winhttp.c 30.1 KB
Newer Older
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#ifdef GIT_WINHTTP

#include "git2.h"
#include "git2/transport.h"
#include "buffer.h"
#include "posix.h"
#include "netops.h"
#include "smart.h"
16 17
#include "remote.h"
#include "repository.h"
18 19 20 21

#include <winhttp.h>
#pragma comment(lib, "winhttp")

Russell Belfer committed
22 23
#include <strsafe.h>

24 25 26 27
/* For IInternetSecurityManager zone check */
#include <objbase.h>
#include <urlmon.h>

28 29 30
/* For UuidCreate */
#pragma comment(lib, "rpcrt4")

31 32 33 34
#define WIDEN2(s) L ## s
#define WIDEN(s) WIDEN2(s)

#define MAX_CONTENT_TYPE_LEN	100
35
#define WINHTTP_OPTION_PEERDIST_EXTENSION_STATE	109
36 37 38
#define CACHED_POST_BODY_BUF_SIZE	4096
#define UUID_LENGTH_CCH	32

39 40 41 42 43
static const char *prefix_http = "http://";
static const char *prefix_https = "https://";
static const char *upload_pack_service = "upload-pack";
static const char *upload_pack_ls_service_url = "/info/refs?service=git-upload-pack";
static const char *upload_pack_service_url = "/git-upload-pack";
44 45 46
static const char *receive_pack_service = "receive-pack";
static const char *receive_pack_ls_service_url = "/info/refs?service=git-receive-pack";
static const char *receive_pack_service_url = "/git-receive-pack";
47 48
static const wchar_t *get_verb = L"GET";
static const wchar_t *post_verb = L"POST";
49
static const wchar_t *pragma_nocache = L"Pragma: no-cache";
50
static const wchar_t *transfer_encoding = L"Transfer-Encoding: chunked";
51 52 53 54 55 56
static const int no_check_cert_flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID |
	SECURITY_FLAG_IGNORE_CERT_DATE_INVALID |
	SECURITY_FLAG_IGNORE_UNKNOWN_CA;

#define OWNING_SUBTRANSPORT(s) ((winhttp_subtransport *)(s)->parent.subtransport)

57 58
typedef enum {
	GIT_WINHTTP_AUTH_BASIC = 1,
59
	GIT_WINHTTP_AUTH_NEGOTIATE = 2,
60 61
} winhttp_authmechanism_t;

62 63 64 65 66 67
typedef struct {
	git_smart_subtransport_stream parent;
	const char *service;
	const char *service_url;
	const wchar_t *verb;
	HINTERNET request;
68
	wchar_t *request_uri;
69 70 71 72
	char *chunk_buffer;
	unsigned chunk_buffer_len;
	HANDLE post_body;
	DWORD post_body_len;
73
	unsigned sent_request : 1,
74 75
		received_response : 1,
		chunked : 1;
76 77 78 79
} winhttp_stream;

typedef struct {
	git_smart_subtransport parent;
80
	transport_smart *owner;
81
	gitno_connection_data connection_data;
82
	git_cred *cred;
83
	git_cred *url_cred;
84
	int auth_mechanism;
85 86 87 88
	HINTERNET session;
	HINTERNET connection;
} winhttp_subtransport;

89 90 91 92 93
static int apply_basic_credential(HINTERNET request, git_cred *cred)
{
	git_cred_userpass_plaintext *c = (git_cred_userpass_plaintext *)cred;
	git_buf buf = GIT_BUF_INIT, raw = GIT_BUF_INIT;
	wchar_t *wide = NULL;
94
	int error = -1, wide_len;
95 96 97 98 99 100 101 102

	git_buf_printf(&raw, "%s:%s", c->username, c->password);

	if (git_buf_oom(&raw) ||
		git_buf_puts(&buf, "Authorization: Basic ") < 0 ||
		git_buf_put_base64(&buf, git_buf_cstr(&raw), raw.size) < 0)
		goto on_error;

103
	if ((wide_len = git__utf8_to_16_alloc(&wide, git_buf_cstr(&buf))) < 0) {
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
		giterr_set(GITERR_OS, "Failed to convert string to wide form");
		goto on_error;
	}

	if (!WinHttpAddRequestHeaders(request, wide, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) {
		giterr_set(GITERR_OS, "Failed to add a header to the request");
		goto on_error;
	}

	error = 0;

on_error:
	/* We were dealing with plaintext passwords, so clean up after ourselves a bit. */
	if (wide)
		memset(wide, 0x0, wide_len * sizeof(wchar_t));

	if (buf.size)
		memset(buf.ptr, 0x0, buf.size);

	if (raw.size)
		memset(raw.ptr, 0x0, raw.size);

	git__free(wide);
	git_buf_free(&buf);
	git_buf_free(&raw);
	return error;
}

132 133
static int apply_default_credentials(HINTERNET request)
{
134 135 136 137 138 139
	/* Either the caller explicitly requested that default credentials be passed,
	 * or our fallback credential callback was invoked and checked that the target
	 * URI was in the appropriate Internet Explorer security zone. By setting this
	 * flag, we guarantee that the credentials are delivered by WinHTTP. The default
	 * is "medium" which applies to the intranet and sounds like it would correspond
	 * to Internet Explorer security zones, but in fact does not. */
140 141 142 143 144 145 146 147
	DWORD data = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;

	if (!WinHttpSetOption(request, WINHTTP_OPTION_AUTOLOGON_POLICY, &data, sizeof(DWORD)))
		return -1;

	return 0;
}

148 149 150 151 152 153 154 155 156 157 158 159
static int fallback_cred_acquire_cb(
	git_cred **cred,
	const char *url,
	const char *username_from_url,
	unsigned int allowed_types,
	void *payload)
{
	int error = 1;

	/* If the target URI supports integrated Windows authentication
	 * as an authentication mechanism */
	if (GIT_CREDTYPE_DEFAULT & allowed_types) {
160
		wchar_t *wide_url;
161 162

		/* Convert URL to wide characters */
163
		if (git__utf8_to_16_alloc(&wide_url, url) < 0) {
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
			giterr_set(GITERR_OS, "Failed to convert string to wide form");
			return -1;
		}

		if (SUCCEEDED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) {
			IInternetSecurityManager* pISM;

			/* And if the target URI is in the My Computer, Intranet, or Trusted zones */
			if (SUCCEEDED(CoCreateInstance(&CLSID_InternetSecurityManager, NULL,
				CLSCTX_ALL, &IID_IInternetSecurityManager, (void **)&pISM))) {
				DWORD dwZone;

				if (SUCCEEDED(pISM->lpVtbl->MapUrlToZone(pISM, wide_url, &dwZone, 0)) &&
					(URLZONE_LOCAL_MACHINE == dwZone ||
					URLZONE_INTRANET == dwZone ||
					URLZONE_TRUSTED == dwZone)) {
					git_cred *existing = *cred;

					if (existing)
						existing->free(existing);

					/* Then use default Windows credentials to authenticate this request */
					error = git_cred_default_new(cred);
				}

				pISM->lpVtbl->Release(pISM);
			}

			CoUninitialize();
		}

		git__free(wide_url);
	}

	return error;
}

201 202 203 204
static int winhttp_stream_connect(winhttp_stream *s)
{
	winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
	git_buf buf = GIT_BUF_INIT;
205
	char *proxy_url = NULL;
206
	wchar_t ct[MAX_CONTENT_TYPE_LEN];
207
	wchar_t *types[] = { L"*/*", NULL };
208
	BOOL peerdist = FALSE;
209
	int error = -1;
210
	unsigned long disable_redirects = WINHTTP_DISABLE_REDIRECTS;
211 212

	/* Prepare URL */
213
	git_buf_printf(&buf, "%s%s", t->connection_data.path, s->service_url);
214 215 216 217

	if (git_buf_oom(&buf))
		return -1;

218
	/* Convert URL to wide characters */
219
	if (git__utf8_to_16_alloc(&s->request_uri, git_buf_cstr(&buf)) < 0) {
220 221 222
		giterr_set(GITERR_OS, "Failed to convert string to wide form");
		goto on_error;
	}
223 224 225 226 227

	/* Establish request */
	s->request = WinHttpOpenRequest(
			t->connection,
			s->verb,
228
			s->request_uri,
229 230 231
			NULL,
			WINHTTP_NO_REFERER,
			types,
232
			t->connection_data.use_ssl ? WINHTTP_FLAG_SECURE : 0);
233 234 235 236 237 238

	if (!s->request) {
		giterr_set(GITERR_OS, "Failed to open request");
		goto on_error;
	}

239
	/* Set proxy if necessary */
240
	if (git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url) < 0)
241 242 243 244
		goto on_error;

	if (proxy_url) {
		WINHTTP_PROXY_INFO proxy_info;
245 246 247
		wchar_t *proxy_wide;

		/* Convert URL to wide characters */
248
		int proxy_wide_len = git__utf8_to_16_alloc(&proxy_wide, proxy_url);
249

250
		if (proxy_wide_len < 0) {
251 252 253
			giterr_set(GITERR_OS, "Failed to convert string to wide form");
			goto on_error;
		}
254 255 256

		/* Strip any trailing forward slash on the proxy URL;
		 * WinHTTP doesn't like it if one is present */
257 258
		if (proxy_wide_len > 1 && L'/' == proxy_wide[proxy_wide_len - 2])
			proxy_wide[proxy_wide_len - 2] = L'\0';
259 260

		proxy_info.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
261
		proxy_info.lpszProxy = proxy_wide;
262 263 264 265 266 267 268
		proxy_info.lpszProxyBypass = NULL;

		if (!WinHttpSetOption(s->request,
			WINHTTP_OPTION_PROXY,
			&proxy_info,
			sizeof(WINHTTP_PROXY_INFO))) {
			giterr_set(GITERR_OS, "Failed to set proxy");
269
			git__free(proxy_wide);
270 271
			goto on_error;
		}
272 273

		git__free(proxy_wide);
274 275
	}

276 277 278
	/* Disable WinHTTP redirects so we can handle them manually. Why, you ask?
	 * http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae
	 */
279 280 281 282 283 284 285 286
	if (!WinHttpSetOption(s->request,
		WINHTTP_OPTION_DISABLE_FEATURE,
		&disable_redirects,
		sizeof(disable_redirects))) {
			giterr_set(GITERR_OS, "Failed to disable redirects");
			goto on_error;
	}

287 288 289 290 291 292 293 294 295 296 297 298 299 300
	/* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP
	 * adds itself. This option may not be supported by the underlying
	 * platform, so we do not error-check it */
	WinHttpSetOption(s->request,
		WINHTTP_OPTION_PEERDIST_EXTENSION_STATE,
		&peerdist,
		sizeof(peerdist));

	/* Send Pragma: no-cache header */
	if (!WinHttpAddRequestHeaders(s->request, pragma_nocache, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) {
		giterr_set(GITERR_OS, "Failed to add a header to the request");
		goto on_error;
	}

301
	if (post_verb == s->verb) {
Ben Straub committed
302
		/* Send Content-Type and Accept headers -- only necessary on a POST */
303
		git_buf_clear(&buf);
Ben Straub committed
304
		if (git_buf_printf(&buf,
305 306
			"Content-Type: application/x-git-%s-request",
			s->service) < 0)
307 308
			goto on_error;

309 310 311 312
		if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
			giterr_set(GITERR_OS, "Failed to convert content-type to wide characters");
			goto on_error;
		}
313

314 315 316 317 318 319 320 321 322 323 324 325
		if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
			WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
			giterr_set(GITERR_OS, "Failed to add a header to the request");
			goto on_error;
		}

		git_buf_clear(&buf);
		if (git_buf_printf(&buf,
			"Accept: application/x-git-%s-result",
			s->service) < 0)
			goto on_error;

326 327 328 329
		if (git__utf8_to_16(ct, MAX_CONTENT_TYPE_LEN, git_buf_cstr(&buf)) < 0) {
			giterr_set(GITERR_OS, "Failed to convert accept header to wide characters");
			goto on_error;
		}
330 331

		if (!WinHttpAddRequestHeaders(s->request, ct, (ULONG)-1L,
Ben Straub committed
332
			WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE)) {
333 334 335
			giterr_set(GITERR_OS, "Failed to add a header to the request");
			goto on_error;
		}
336 337 338
	}

	/* If requested, disable certificate validation */
339
	if (t->connection_data.use_ssl) {
340 341 342 343 344 345 346
		int flags;

		if (t->owner->parent.read_flags(&t->owner->parent, &flags) < 0)
			goto on_error;

		if ((GIT_TRANSPORTFLAGS_NO_CHECK_CERT & flags) &&
			!WinHttpSetOption(s->request, WINHTTP_OPTION_SECURITY_FLAGS,
347 348 349 350 351 352
			(LPVOID)&no_check_cert_flags, sizeof(no_check_cert_flags))) {
			giterr_set(GITERR_OS, "Failed to set options to ignore cert errors");
			goto on_error;
		}
	}

353 354 355 356 357 358
	/* If we have a credential on the subtransport, apply it to the request */
	if (t->cred &&
		t->cred->credtype == GIT_CREDTYPE_USERPASS_PLAINTEXT &&
		t->auth_mechanism == GIT_WINHTTP_AUTH_BASIC &&
		apply_basic_credential(s->request, t->cred) < 0)
		goto on_error;
359 360 361 362 363
	else if (t->cred &&
		t->cred->credtype == GIT_CREDTYPE_DEFAULT &&
		t->auth_mechanism == GIT_WINHTTP_AUTH_NEGOTIATE &&
		apply_default_credentials(s->request) < 0)
		goto on_error;
364

365 366
	/* If no other credentials have been applied and the URL has username and
	 * password, use those */
367
	if (!t->cred && t->connection_data.user && t->connection_data.pass) {
368
		if (!t->url_cred &&
369
			git_cred_userpass_plaintext_new(&t->url_cred, t->connection_data.user, t->connection_data.pass) < 0)
370 371 372 373 374
			goto on_error;
		if (apply_basic_credential(s->request, t->url_cred) < 0)
			goto on_error;
	}

375 376
	/* We've done everything up to calling WinHttpSendRequest. */

377
	error = 0;
378 379

on_error:
380
	git__free(proxy_url);
381
	git_buf_free(&buf);
382
	return error;
383 384
}

385 386 387 388 389
static int parse_unauthorized_response(
	HINTERNET request,
	int *allowed_types,
	int *auth_mechanism)
{
390
	DWORD supported, first, target;
391 392

	*allowed_types = 0;
393
	*auth_mechanism = 0;
394

395 396 397 398 399 400 401
	/* WinHttpQueryHeaders() must be called before WinHttpQueryAuthSchemes(). 
	 * We can assume this was already done, since we know we are unauthorized. 
	 */
	if (!WinHttpQueryAuthSchemes(request, &supported, &first, &target)) {
		giterr_set(GITERR_OS, "Failed to parse supported auth schemes"); 
		return -1;
	}
402

403 404 405 406
	if (WINHTTP_AUTH_SCHEME_BASIC & supported) {
		*allowed_types |= GIT_CREDTYPE_USERPASS_PLAINTEXT;
		*auth_mechanism = GIT_WINHTTP_AUTH_BASIC;
	}
407

408 409 410 411 412 413
	if ((WINHTTP_AUTH_SCHEME_NTLM & supported) ||
		(WINHTTP_AUTH_SCHEME_NEGOTIATE & supported)) {
		*allowed_types |= GIT_CREDTYPE_DEFAULT;
		*auth_mechanism = GIT_WINHTTP_AUTH_NEGOTIATE;
	}

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	return 0;
}

static int write_chunk(HINTERNET request, const char *buffer, size_t len)
{
	DWORD bytes_written;
	git_buf buf = GIT_BUF_INIT;

	/* Chunk header */
	git_buf_printf(&buf, "%X\r\n", len);

	if (git_buf_oom(&buf))
		return -1;

	if (!WinHttpWriteData(request,
429
		git_buf_cstr(&buf),	(DWORD)git_buf_len(&buf),
430 431 432 433
		&bytes_written)) {
		git_buf_free(&buf);
		giterr_set(GITERR_OS, "Failed to write chunk header");
		return -1;
434 435
	}

436 437 438 439
	git_buf_free(&buf);

	/* Chunk body */
	if (!WinHttpWriteData(request,
440
		buffer, (DWORD)len,
441 442 443 444 445 446 447 448 449 450 451 452 453 454
		&bytes_written)) {
		giterr_set(GITERR_OS, "Failed to write chunk");
		return -1;
	}

	/* Chunk footer */
	if (!WinHttpWriteData(request,
		"\r\n", 2,
		&bytes_written)) {
		giterr_set(GITERR_OS, "Failed to write chunk footer");
		return -1;
	}

	return 0;
455 456
}

457 458 459 460 461
static int winhttp_connect(
	winhttp_subtransport *t,
	const char *url)
{
	wchar_t *ua = L"git/1.0 (libgit2 " WIDEN(LIBGIT2_VERSION) L")";
462
	wchar_t *wide_host;
463 464
	int32_t port;
	const char *default_port = "80";
465
	int error = -1;
466 467

	/* Prepare port */
468
	if (git__strtol32(&port, t->connection_data.port, NULL, 10) < 0)
469 470 471
		return -1;

	/* Prepare host */
472 473 474 475
	if (git__utf8_to_16_alloc(&wide_host, t->connection_data.host) < 0) {
		giterr_set(GITERR_OS, "Unable to convert host to wide characters");
		return -1;
	}
476 477 478 479 480 481 482 483 484 485 486

	/* Establish session */
	t->session = WinHttpOpen(
		ua,
		WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
		WINHTTP_NO_PROXY_NAME,
		WINHTTP_NO_PROXY_BYPASS,
		0);

	if (!t->session) {
		giterr_set(GITERR_OS, "Failed to init WinHTTP");
487
		goto on_error;
488 489 490 491 492
	}

	/* Establish connection */
	t->connection = WinHttpConnect(
		t->session,
493
		wide_host,
494 495 496 497 498
		(INTERNET_PORT) port,
		0);

	if (!t->connection) {
		giterr_set(GITERR_OS, "Failed to connect to host");
499
		goto on_error;
500 501
	}

502 503 504 505 506 507
	error = 0;

on_error:
	git__free(wide_host);

	return error;
508 509
}

510 511 512 513 514 515 516 517
static int winhttp_stream_read(
	git_smart_subtransport_stream *stream,
	char *buffer,
	size_t buf_size,
	size_t *bytes_read)
{
	winhttp_stream *s = (winhttp_stream *)stream;
	winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
518
	DWORD dw_bytes_read;
519
	char replay_count = 0;
520

521
replay:
522 523 524 525 526 527
	/* Enforce a reasonable cap on the number of replays */
	if (++replay_count >= 7) {
		giterr_set(GITERR_NET, "Too many redirects or authentication replays");
		return -1;
	}

528 529 530 531 532
	/* Connect if necessary */
	if (!s->request && winhttp_stream_connect(s) < 0)
		return -1;

	if (!s->received_response) {
533
		DWORD status_code, status_code_length, content_type_length, bytes_written;
534 535 536
		char expected_content_type_8[MAX_CONTENT_TYPE_LEN];
		wchar_t expected_content_type[MAX_CONTENT_TYPE_LEN], content_type[MAX_CONTENT_TYPE_LEN];

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
		if (!s->sent_request) {
			if (!WinHttpSendRequest(s->request,
				WINHTTP_NO_ADDITIONAL_HEADERS, 0,
				WINHTTP_NO_REQUEST_DATA, 0,
				s->post_body_len, 0)) {
				giterr_set(GITERR_OS, "Failed to send request");
				return -1;
			}

			s->sent_request = 1;
		}

		if (s->chunked) {
			assert(s->verb == post_verb);

			/* Flush, if necessary */
			if (s->chunk_buffer_len > 0 &&
				write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0)
				return -1;

			s->chunk_buffer_len = 0;

			/* Write the final chunk. */
			if (!WinHttpWriteData(s->request,
				"0\r\n\r\n", 5,
				&bytes_written)) {
				giterr_set(GITERR_OS, "Failed to write final chunk");
				return -1;
			}
		}
		else if (s->post_body) {
			char *buffer;
			DWORD len = s->post_body_len, bytes_read;

			if (INVALID_SET_FILE_POINTER == SetFilePointer(s->post_body,
					0, 0, FILE_BEGIN) &&
				NO_ERROR != GetLastError()) {
				giterr_set(GITERR_OS, "Failed to reset file pointer");
				return -1;
			}

578
			buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE);
579 580 581 582 583

			while (len > 0) {
				DWORD bytes_written;

				if (!ReadFile(s->post_body, buffer,
584
					min(CACHED_POST_BODY_BUF_SIZE, len),
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
					&bytes_read, NULL) ||
					!bytes_read) {
					git__free(buffer);
					giterr_set(GITERR_OS, "Failed to read from temp file");
					return -1;
				}

				if (!WinHttpWriteData(s->request, buffer,
					bytes_read, &bytes_written)) {
					git__free(buffer);
					giterr_set(GITERR_OS, "Failed to write data");
					return -1;
				}

				len -= bytes_read;
				assert(bytes_read == bytes_written);
			}

			git__free(buffer);

			/* Eagerly close the temp file */
			CloseHandle(s->post_body);
			s->post_body = NULL;
		}

610 611 612 613 614 615 616 617 618 619 620 621 622
		if (!WinHttpReceiveResponse(s->request, 0)) {
			giterr_set(GITERR_OS, "Failed to receive response");
			return -1;
		}

		/* Verify that we got a 200 back */
		status_code_length = sizeof(status_code);

		if (!WinHttpQueryHeaders(s->request,
			WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
			WINHTTP_HEADER_NAME_BY_INDEX,
			&status_code, &status_code_length,
			WINHTTP_NO_HEADER_INDEX)) {
623
				giterr_set(GITERR_OS, "Failed to retrieve status code");
624 625 626
				return -1;
		}

627 628 629 630 631 632 633 634 635 636 637 638 639 640
		/* The implementation of WinHTTP prior to Windows 7 will not
		 * redirect to an identical URI. Some Git hosters use self-redirects
		 * as part of their DoS mitigation strategy. Check first to see if we
		 * have a redirect status code, and that we haven't already streamed
		 * a post body. (We can't replay a streamed POST.) */
		if (!s->chunked &&
			(HTTP_STATUS_MOVED == status_code ||
			 HTTP_STATUS_REDIRECT == status_code ||
			 (HTTP_STATUS_REDIRECT_METHOD == status_code &&
			  get_verb == s->verb) ||
			 HTTP_STATUS_REDIRECT_KEEP_VERB == status_code)) {

			/* Check for Windows 7. This workaround is only necessary on
			 * Windows Vista and earlier. Windows 7 is version 6.1. */
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
			wchar_t *location;
			DWORD location_length;
			char *location8;

			/* OK, fetch the Location header from the redirect. */
			if (WinHttpQueryHeaders(s->request,
				WINHTTP_QUERY_LOCATION,
				WINHTTP_HEADER_NAME_BY_INDEX,
				WINHTTP_NO_OUTPUT_BUFFER,
				&location_length,
				WINHTTP_NO_HEADER_INDEX) ||
				GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
				giterr_set(GITERR_OS, "Failed to read Location header");
				return -1;
			}
656

657 658 659 660 661 662 663 664 665 666
			location = git__malloc(location_length);
			GITERR_CHECK_ALLOC(location);

			if (!WinHttpQueryHeaders(s->request,
				WINHTTP_QUERY_LOCATION,
				WINHTTP_HEADER_NAME_BY_INDEX,
				location,
				&location_length,
				WINHTTP_NO_HEADER_INDEX)) {
				giterr_set(GITERR_OS, "Failed to read Location header");
667
				git__free(location);
668 669
				return -1;
			}
670 671 672 673 674 675 676 677

			/* Convert the Location header to UTF-8 */
			if (git__utf16_to_8_alloc(&location8, location) < 0) {
				giterr_set(GITERR_OS, "Failed to convert Location header to UTF-8");
				git__free(location);
				return -1;
			}

678 679 680 681 682 683 684 685 686
			git__free(location);

			/* Replay the request */
			WinHttpCloseHandle(s->request);
			s->request = NULL;
			s->sent_request = 0;

			if (!git__prefixcmp_icase(location8, prefix_https)) {
				/* Upgrade to secure connection; disconnect and start over */
687 688
				if (gitno_connection_data_from_url(&t->connection_data, location8, s->service_url) < 0) {
					git__free(location8);
689
					return -1;
690 691
				}

692
				winhttp_connect(t, location8);
693
			}
694 695 696

			git__free(location8);
			goto replay;
697 698
		}

699
		/* Handle authentication failures */
700
		if (HTTP_STATUS_DENIED == status_code && get_verb == s->verb) {
701 702 703 704 705 706 707
			int allowed_types;

			if (parse_unauthorized_response(s->request, &allowed_types, &t->auth_mechanism) < 0)
				return -1;

			if (allowed_types &&
				(!t->cred || 0 == (t->cred->credtype & allowed_types))) {
708
				int cred_error = 1;
709

710 711 712 713
				/* Start with the user-supplied credential callback, if present */
				if (t->owner->cred_acquire_cb) {
					cred_error = t->owner->cred_acquire_cb(&t->cred, t->owner->url,
						t->connection_data.user, allowed_types,	t->owner->cred_acquire_payload);
714

715 716 717
					if (cred_error < 0)
						return cred_error;
				}
718

719 720 721 722
				/* Invoke the fallback credentials acquisition callback if necessary */
				if (cred_error > 0) {
					cred_error = fallback_cred_acquire_cb(&t->cred, t->owner->url,
						t->connection_data.user, allowed_types, NULL);
723

724 725 726 727 728 729 730 731 732 733 734 735 736 737
					if (cred_error < 0)
						return cred_error;
				}

				if (!cred_error) {
					assert(t->cred);

					WinHttpCloseHandle(s->request);
					s->request = NULL;
					s->sent_request = 0;

					/* Successfully acquired a credential */
					goto replay;
				}
738 739 740
			}
		}

741 742 743 744 745 746 747 748 749 750 751
		if (HTTP_STATUS_OK != status_code) {
			giterr_set(GITERR_NET, "Request failed with status code: %d", status_code);
			return -1;
		}

		/* Verify that we got the correct content-type back */
		if (post_verb == s->verb)
			snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-result", s->service);
		else
			snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-advertisement", s->service);

752 753 754 755 756
		if (git__utf8_to_16(expected_content_type, MAX_CONTENT_TYPE_LEN, expected_content_type_8) < 0) {
			giterr_set(GITERR_OS, "Failed to convert expected content-type to wide characters");
			return -1;
		}

757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
		content_type_length = sizeof(content_type);

		if (!WinHttpQueryHeaders(s->request,
			WINHTTP_QUERY_CONTENT_TYPE,
			WINHTTP_HEADER_NAME_BY_INDEX,
			&content_type, &content_type_length,
			WINHTTP_NO_HEADER_INDEX)) {
				giterr_set(GITERR_OS, "Failed to retrieve response content-type");
				return -1;
		}

		if (wcscmp(expected_content_type, content_type)) {
			giterr_set(GITERR_NET, "Received unexpected content-type");
			return -1;
		}

		s->received_response = 1;
	}

	if (!WinHttpReadData(s->request,
		(LPVOID)buffer,
778
		(DWORD)buf_size,
779
		&dw_bytes_read))
780 781 782 783 784
	{
		giterr_set(GITERR_OS, "Failed to read data");
		return -1;
	}

785 786
	*bytes_read = dw_bytes_read;

787 788 789
	return 0;
}

790
static int winhttp_stream_write_single(
791 792 793 794 795 796 797 798 799 800 801
	git_smart_subtransport_stream *stream,
	const char *buffer,
	size_t len)
{
	winhttp_stream *s = (winhttp_stream *)stream;
	winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
	DWORD bytes_written;

	if (!s->request && winhttp_stream_connect(s) < 0)
		return -1;

802 803 804 805 806 807 808
	/* This implementation of write permits only a single call. */
	if (s->sent_request) {
		giterr_set(GITERR_NET, "Subtransport configured for only one write");
		return -1;
	}

	if (!WinHttpSendRequest(s->request,
809 810 811 812 813 814 815 816 817 818 819 820 821
			WINHTTP_NO_ADDITIONAL_HEADERS, 0,
			WINHTTP_NO_REQUEST_DATA, 0,
			(DWORD)len, 0)) {
		giterr_set(GITERR_OS, "Failed to send request");
		return -1;
	}

	s->sent_request = 1;

	if (!WinHttpWriteData(s->request,
			(LPCVOID)buffer,
			(DWORD)len,
			&bytes_written)) {
822 823 824 825 826 827 828 829 830
		giterr_set(GITERR_OS, "Failed to write data");
		return -1;
	}

	assert((DWORD)len == bytes_written);

	return 0;
}

831
static int put_uuid_string(LPWSTR buffer, size_t buffer_len_cch)
832 833 834
{
	UUID uuid;
	RPC_STATUS status = UuidCreate(&uuid);
835
	HRESULT result;
836 837 838 839 840 841 842 843

	if (RPC_S_OK != status &&
		RPC_S_UUID_LOCAL_ONLY != status &&
		RPC_S_UUID_NO_ADDRESS != status) {
		giterr_set(GITERR_NET, "Unable to generate name for temp file");
		return -1;
	}

844 845
	if (buffer_len_cch < UUID_LENGTH_CCH + 1) {
		giterr_set(GITERR_NET, "Buffer too small for name of temp file");
846 847 848
		return -1;
	}

849 850 851
	result = StringCbPrintfW(
		buffer, buffer_len_cch,
		L"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x",
852 853 854 855
		uuid.Data1, uuid.Data2, uuid.Data3,
		uuid.Data4[0], uuid.Data4[1], uuid.Data4[2], uuid.Data4[3],
		uuid.Data4[4], uuid.Data4[5], uuid.Data4[6], uuid.Data4[7]);

856
	if (FAILED(result)) {
857 858 859 860 861 862 863 864 865
		giterr_set(GITERR_OS, "Unable to generate name for temp file");
		return -1;
	}

	return 0;
}

static int get_temp_file(LPWSTR buffer, DWORD buffer_len_cch)
{
866
	size_t len;
867 868 869 870 871 872 873 874

	if (!GetTempPathW(buffer_len_cch, buffer)) {
		giterr_set(GITERR_OS, "Failed to get temp path");
		return -1;
	}

	len = wcslen(buffer);

875
	if (buffer[len - 1] != '\\' && len < buffer_len_cch)
876 877
		buffer[len++] = '\\';

878
	if (put_uuid_string(&buffer[len], (size_t)buffer_len_cch - len) < 0)
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
		return -1;

	return 0;
}

static int winhttp_stream_write_buffered(
	git_smart_subtransport_stream *stream,
	const char *buffer,
	size_t len)
{
	winhttp_stream *s = (winhttp_stream *)stream;
	winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
	DWORD bytes_written;

	if (!s->request && winhttp_stream_connect(s) < 0)
		return -1;

	/* Buffer the payload, using a temporary file so we delegate
	 * memory management of the data to the operating system. */
	if (!s->post_body) {
		wchar_t temp_path[MAX_PATH + 1];

		if (get_temp_file(temp_path, MAX_PATH + 1) < 0)
			return -1;

		s->post_body = CreateFileW(temp_path,
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_DELETE, NULL,
			CREATE_NEW,
			FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN,
			NULL);

		if (INVALID_HANDLE_VALUE == s->post_body) {
			s->post_body = NULL;
			giterr_set(GITERR_OS, "Failed to create temporary file");
			return -1;
		}
	}

918
	if (!WriteFile(s->post_body, buffer, (DWORD)len, &bytes_written, NULL)) {
919
		giterr_set(GITERR_OS, "Failed to write to temporary file");
920 921 922 923 924
		return -1;
	}

	assert((DWORD)len == bytes_written);

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
	s->post_body_len += bytes_written;

	return 0;
}

static int winhttp_stream_write_chunked(
	git_smart_subtransport_stream *stream,
	const char *buffer,
	size_t len)
{
	winhttp_stream *s = (winhttp_stream *)stream;
	winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);

	if (!s->request && winhttp_stream_connect(s) < 0)
		return -1;

	if (!s->sent_request) {
		/* Send Transfer-Encoding: chunked header */
		if (!WinHttpAddRequestHeaders(s->request,
			transfer_encoding, (ULONG) -1L,
			WINHTTP_ADDREQ_FLAG_ADD)) {
			giterr_set(GITERR_OS, "Failed to add a header to the request");
			return -1;
		}

		if (!WinHttpSendRequest(s->request,
			WINHTTP_NO_ADDITIONAL_HEADERS, 0,
			WINHTTP_NO_REQUEST_DATA, 0,
			WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) {
			giterr_set(GITERR_OS, "Failed to send request");
			return -1;
		}

		s->sent_request = 1;
	}

	if (len > CACHED_POST_BODY_BUF_SIZE) {
		/* Flush, if necessary */
		if (s->chunk_buffer_len > 0) {
			if (write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0)
				return -1;

			s->chunk_buffer_len = 0;
		}

		/* Write chunk directly */
		if (write_chunk(s->request, buffer, len) < 0)
			return -1;
	}
	else {
		/* Append as much to the buffer as we can */
976
		int count = min(CACHED_POST_BODY_BUF_SIZE - s->chunk_buffer_len, (int)len);
977 978

		if (!s->chunk_buffer)
979
			s->chunk_buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE);
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995

		memcpy(s->chunk_buffer + s->chunk_buffer_len, buffer, count);
		s->chunk_buffer_len += count;
		buffer += count;
		len -= count;

		/* Is the buffer full? If so, then flush */
		if (CACHED_POST_BODY_BUF_SIZE == s->chunk_buffer_len) {
			if (write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0)
				return -1;

			s->chunk_buffer_len = 0;

			/* Is there any remaining data from the source? */
			if (len > 0) {
				memcpy(s->chunk_buffer, buffer, len);
996
				s->chunk_buffer_len = (unsigned int)len;
997 998 999 1000
			}
		}
	}

1001 1002 1003 1004 1005 1006 1007
	return 0;
}

static void winhttp_stream_free(git_smart_subtransport_stream *stream)
{
	winhttp_stream *s = (winhttp_stream *)stream;

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
	if (s->chunk_buffer) {
		git__free(s->chunk_buffer);
		s->chunk_buffer = NULL;
	}

	if (s->post_body) {
		CloseHandle(s->post_body);
		s->post_body = NULL;
	}

1018 1019 1020 1021 1022
	if (s->request_uri) {
		git__free(s->request_uri);
		s->request_uri = NULL;
	}

1023 1024 1025 1026 1027 1028 1029 1030
	if (s->request) {
		WinHttpCloseHandle(s->request);
		s->request = NULL;
	}

	git__free(s);
}

1031
static int winhttp_stream_alloc(winhttp_subtransport *t, winhttp_stream **stream)
1032 1033 1034 1035 1036 1037
{
	winhttp_stream *s;

	if (!stream)
		return -1;

1038
	s = git__calloc(sizeof(winhttp_stream), 1);
1039 1040 1041 1042
	GITERR_CHECK_ALLOC(s);

	s->parent.subtransport = &t->parent;
	s->parent.read = winhttp_stream_read;
1043
	s->parent.write = winhttp_stream_write_single;
1044 1045
	s->parent.free = winhttp_stream_free;

1046 1047
	*stream = s;

1048 1049 1050 1051 1052
	return 0;
}

static int winhttp_uploadpack_ls(
	winhttp_subtransport *t,
1053
	winhttp_stream *s)
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
{
	s->service = upload_pack_service;
	s->service_url = upload_pack_ls_service_url;
	s->verb = get_verb;

	return 0;
}

static int winhttp_uploadpack(
	winhttp_subtransport *t,
1064
	winhttp_stream *s)
1065
{
1066 1067 1068
	s->service = upload_pack_service;
	s->service_url = upload_pack_service_url;
	s->verb = post_verb;
1069

1070 1071
	return 0;
}
1072

1073 1074 1075 1076 1077 1078 1079
static int winhttp_receivepack_ls(
	winhttp_subtransport *t,
	winhttp_stream *s)
{
	s->service = receive_pack_service;
	s->service_url = receive_pack_ls_service_url;
	s->verb = get_verb;
1080

1081 1082
	return 0;
}
1083

1084 1085 1086 1087 1088 1089
static int winhttp_receivepack(
	winhttp_subtransport *t,
	winhttp_stream *s)
{
	/* WinHTTP only supports Transfer-Encoding: chunked
	 * on Windows Vista (NT 6.0) and higher. */
1090
	s->chunked = git_has_win32_version(6, 0, 0);
1091 1092 1093 1094 1095 1096 1097 1098

	if (s->chunked)
		s->parent.write = winhttp_stream_write_chunked;
	else
		s->parent.write = winhttp_stream_write_buffered;

	s->service = receive_pack_service;
	s->service_url = receive_pack_service_url;
1099 1100 1101 1102 1103 1104 1105
	s->verb = post_verb;

	return 0;
}

static int winhttp_action(
	git_smart_subtransport_stream **stream,
1106
	git_smart_subtransport *subtransport,
1107 1108 1109
	const char *url,
	git_smart_service_t action)
{
1110 1111 1112 1113
	winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
	winhttp_stream *s;
	int ret = -1;

1114 1115 1116
	if (!t->connection)
		if (gitno_connection_data_from_url(&t->connection_data, url, NULL) < 0 ||
			 winhttp_connect(t, url) < 0)
1117
			return -1;
1118 1119 1120

	if (winhttp_stream_alloc(t, &s) < 0)
		return -1;
1121 1122 1123 1124 1125 1126 1127

	if (!stream)
		return -1;

	switch (action)
	{
		case GIT_SERVICE_UPLOADPACK_LS:
1128 1129
			ret = winhttp_uploadpack_ls(t, s);
			break;
1130 1131

		case GIT_SERVICE_UPLOADPACK:
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
			ret = winhttp_uploadpack(t, s);
			break;

		case GIT_SERVICE_RECEIVEPACK_LS:
			ret = winhttp_receivepack_ls(t, s);
			break;

		case GIT_SERVICE_RECEIVEPACK:
			ret = winhttp_receivepack(t, s);
			break;

		default:
			assert(0);
1145 1146
	}

1147 1148 1149 1150
	if (!ret)
		*stream = &s->parent;

	return ret;
1151 1152
}

1153
static int winhttp_close(git_smart_subtransport *subtransport)
1154
{
1155 1156 1157
	winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
	int ret = 0;

1158
	gitno_connection_data_free_ptrs(&t->connection_data);
1159

1160 1161 1162 1163 1164
	if (t->cred) {
		t->cred->free(t->cred);
		t->cred = NULL;
	}

1165 1166 1167 1168 1169
	if (t->url_cred) {
		t->url_cred->free(t->url_cred);
		t->url_cred = NULL;
	}

1170
	if (t->connection) {
1171 1172 1173 1174 1175
		if (!WinHttpCloseHandle(t->connection)) {
			giterr_set(GITERR_OS, "Unable to close connection");
			ret = -1;
		}

1176 1177 1178 1179
		t->connection = NULL;
	}

	if (t->session) {
1180 1181 1182 1183 1184
		if (!WinHttpCloseHandle(t->session)) {
			giterr_set(GITERR_OS, "Unable to close session");
			ret = -1;
		}

1185 1186 1187
		t->session = NULL;
	}

1188 1189 1190 1191 1192 1193 1194 1195 1196
	return ret;
}

static void winhttp_free(git_smart_subtransport *subtransport)
{
	winhttp_subtransport *t = (winhttp_subtransport *)subtransport;

	winhttp_close(subtransport);

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
	git__free(t);
}

int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner)
{
	winhttp_subtransport *t;

	if (!out)
		return -1;

1207
	t = git__calloc(sizeof(winhttp_subtransport), 1);
1208 1209
	GITERR_CHECK_ALLOC(t);

1210
	t->owner = (transport_smart *)owner;
1211
	t->parent.action = winhttp_action;
1212
	t->parent.close = winhttp_close;
1213 1214 1215 1216 1217 1218 1219
	t->parent.free = winhttp_free;

	*out = (git_smart_subtransport *) t;
	return 0;
}

#endif /* GIT_WINHTTP */