2 * Copyright (C) the libgit2 contributors. All rights reserved.
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
11 #include "git2/transport.h"
17 #include "repository.h"
23 /* For IInternetSecurityManager zone check */
27 #define WIDEN2(s) L ## s
28 #define WIDEN(s) WIDEN2(s)
30 #define MAX_CONTENT_TYPE_LEN 100
31 #define WINHTTP_OPTION_PEERDIST_EXTENSION_STATE 109
32 #define CACHED_POST_BODY_BUF_SIZE 4096
33 #define UUID_LENGTH_CCH 32
34 #define TIMEOUT_INFINITE -1
35 #define DEFAULT_CONNECT_TIMEOUT 60000
36 #ifndef WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH
37 #define WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH 0
40 static const char *prefix_https
= "https://";
41 static const char *upload_pack_service
= "upload-pack";
42 static const char *upload_pack_ls_service_url
= "/info/refs?service=git-upload-pack";
43 static const char *upload_pack_service_url
= "/git-upload-pack";
44 static const char *receive_pack_service
= "receive-pack";
45 static const char *receive_pack_ls_service_url
= "/info/refs?service=git-receive-pack";
46 static const char *receive_pack_service_url
= "/git-receive-pack";
47 static const wchar_t *get_verb
= L
"GET";
48 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 static const int no_check_cert_flags
= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
|
52 SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
|
53 SECURITY_FLAG_IGNORE_UNKNOWN_CA
;
55 #if defined(__MINGW32__)
56 const CLSID CLSID_InternetSecurityManager
= { 0x7B8A2D94, 0x0AC9, 0x11D1,
57 { 0x89, 0x6C, 0x00, 0xC0, 0x4F, 0xB6, 0xBF, 0xC4 } };
58 const IID IID_IInternetSecurityManager
= { 0x79EAC9EE, 0xBAF9, 0x11CE,
59 { 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B } };
62 #define OWNING_SUBTRANSPORT(s) ((winhttp_subtransport *)(s)->parent.subtransport)
65 GIT_WINHTTP_AUTH_BASIC
= 1,
66 GIT_WINHTTP_AUTH_NEGOTIATE
= 2,
67 } winhttp_authmechanism_t
;
70 git_smart_subtransport_stream parent
;
72 const char *service_url
;
77 unsigned chunk_buffer_len
;
80 unsigned sent_request
: 1,
81 received_response
: 1,
86 git_smart_subtransport parent
;
87 transport_smart
*owner
;
88 gitno_connection_data connection_data
;
94 } winhttp_subtransport
;
96 static int apply_basic_credential(HINTERNET request
, git_cred
*cred
)
98 git_cred_userpass_plaintext
*c
= (git_cred_userpass_plaintext
*)cred
;
99 git_buf buf
= GIT_BUF_INIT
, raw
= GIT_BUF_INIT
;
100 wchar_t *wide
= NULL
;
101 int error
= -1, wide_len
;
103 git_buf_printf(&raw
, "%s:%s", c
->username
, c
->password
);
105 if (git_buf_oom(&raw
) ||
106 git_buf_puts(&buf
, "Authorization: Basic ") < 0 ||
107 git_buf_encode_base64(&buf
, git_buf_cstr(&raw
), raw
.size
) < 0)
110 if ((wide_len
= git__utf8_to_16_alloc(&wide
, git_buf_cstr(&buf
))) < 0) {
111 giterr_set(GITERR_OS
, "Failed to convert string to wide form");
115 if (!WinHttpAddRequestHeaders(request
, wide
, (ULONG
) -1L, WINHTTP_ADDREQ_FLAG_ADD
)) {
116 giterr_set(GITERR_OS
, "Failed to add a header to the request");
123 /* We were dealing with plaintext passwords, so clean up after ourselves a bit. */
125 memset(wide
, 0x0, wide_len
* sizeof(wchar_t));
128 memset(buf
.ptr
, 0x0, buf
.size
);
131 memset(raw
.ptr
, 0x0, raw
.size
);
139 static int apply_default_credentials(HINTERNET request
)
141 /* Either the caller explicitly requested that default credentials be passed,
142 * or our fallback credential callback was invoked and checked that the target
143 * URI was in the appropriate Internet Explorer security zone. By setting this
144 * flag, we guarantee that the credentials are delivered by WinHTTP. The default
145 * is "medium" which applies to the intranet and sounds like it would correspond
146 * to Internet Explorer security zones, but in fact does not. */
147 DWORD data
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
149 if (!WinHttpSetOption(request
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &data
, sizeof(DWORD
)))
155 static int fallback_cred_acquire_cb(
158 const char *username_from_url
,
159 unsigned int allowed_types
,
164 GIT_UNUSED(username_from_url
);
167 /* If the target URI supports integrated Windows authentication
168 * as an authentication mechanism */
169 if (GIT_CREDTYPE_DEFAULT
& allowed_types
) {
172 /* Convert URL to wide characters */
173 if (git__utf8_to_16_alloc(&wide_url
, url
) < 0) {
174 giterr_set(GITERR_OS
, "Failed to convert string to wide form");
178 if (SUCCEEDED(CoInitializeEx(NULL
, COINIT_MULTITHREADED
))) {
179 IInternetSecurityManager
* pISM
;
181 /* And if the target URI is in the My Computer, Intranet, or Trusted zones */
182 if (SUCCEEDED(CoCreateInstance(&CLSID_InternetSecurityManager
, NULL
,
183 CLSCTX_ALL
, &IID_IInternetSecurityManager
, (void **)&pISM
))) {
186 if (SUCCEEDED(pISM
->lpVtbl
->MapUrlToZone(pISM
, wide_url
, &dwZone
, 0)) &&
187 (URLZONE_LOCAL_MACHINE
== dwZone
||
188 URLZONE_INTRANET
== dwZone
||
189 URLZONE_TRUSTED
== dwZone
)) {
190 git_cred
*existing
= *cred
;
193 existing
->free(existing
);
195 /* Then use default Windows credentials to authenticate this request */
196 error
= git_cred_default_new(cred
);
199 pISM
->lpVtbl
->Release(pISM
);
211 static int certificate_check(winhttp_stream
*s
, int valid
)
214 winhttp_subtransport
*t
= OWNING_SUBTRANSPORT(s
);
215 PCERT_CONTEXT cert_ctx
;
216 DWORD cert_ctx_size
= sizeof(cert_ctx
);
219 /* If there is no override, we should fail if WinHTTP doesn't think it's fine */
220 if (t
->owner
->certificate_check_cb
== NULL
&& !valid
)
221 return GIT_ECERTIFICATE
;
223 if (t
->owner
->certificate_check_cb
== NULL
|| !t
->connection_data
.use_ssl
)
226 if (!WinHttpQueryOption(s
->request
, WINHTTP_OPTION_SERVER_CERT_CONTEXT
, &cert_ctx
, &cert_ctx_size
)) {
227 giterr_set(GITERR_OS
, "failed to get server certificate");
232 cert
.parent
.cert_type
= GIT_CERT_X509
;
233 cert
.data
= cert_ctx
->pbCertEncoded
;
234 cert
.len
= cert_ctx
->cbCertEncoded
;
235 error
= t
->owner
->certificate_check_cb((git_cert
*) &cert
, valid
, t
->connection_data
.host
, t
->owner
->cred_acquire_payload
);
236 CertFreeCertificateContext(cert_ctx
);
238 if (error
< 0 && !giterr_last())
239 giterr_set(GITERR_NET
, "user cancelled certificate check");
244 static void winhttp_stream_close(winhttp_stream
*s
)
246 if (s
->chunk_buffer
) {
247 git__free(s
->chunk_buffer
);
248 s
->chunk_buffer
= NULL
;
252 CloseHandle(s
->post_body
);
256 if (s
->request_uri
) {
257 git__free(s
->request_uri
);
258 s
->request_uri
= NULL
;
262 WinHttpCloseHandle(s
->request
);
269 static int winhttp_stream_connect(winhttp_stream
*s
)
271 winhttp_subtransport
*t
= OWNING_SUBTRANSPORT(s
);
272 git_buf buf
= GIT_BUF_INIT
;
273 char *proxy_url
= NULL
;
274 wchar_t ct
[MAX_CONTENT_TYPE_LEN
];
275 LPCWSTR types
[] = { L
"*/*", NULL
};
276 BOOL peerdist
= FALSE
;
278 unsigned long disable_redirects
= WINHTTP_DISABLE_REDIRECTS
;
279 int default_timeout
= TIMEOUT_INFINITE
;
280 int default_connect_timeout
= DEFAULT_CONNECT_TIMEOUT
;
284 git_buf_printf(&buf
, "%s%s", t
->connection_data
.path
, s
->service_url
);
286 if (git_buf_oom(&buf
))
289 /* Convert URL to wide characters */
290 if (git__utf8_to_16_alloc(&s
->request_uri
, git_buf_cstr(&buf
)) < 0) {
291 giterr_set(GITERR_OS
, "Failed to convert string to wide form");
295 /* Establish request */
296 s
->request
= WinHttpOpenRequest(
303 t
->connection_data
.use_ssl
? WINHTTP_FLAG_SECURE
: 0);
306 giterr_set(GITERR_OS
, "Failed to open request");
310 if (!WinHttpSetTimeouts(s
->request
, default_timeout
, default_connect_timeout
, default_timeout
, default_timeout
)) {
311 giterr_set(GITERR_OS
, "Failed to set timeouts for WinHTTP");
315 /* Set proxy if necessary */
316 if (git_remote__get_http_proxy(t
->owner
->owner
, !!t
->connection_data
.use_ssl
, &proxy_url
) < 0)
320 WINHTTP_PROXY_INFO proxy_info
;
323 /* Convert URL to wide characters */
324 int proxy_wide_len
= git__utf8_to_16_alloc(&proxy_wide
, proxy_url
);
326 if (proxy_wide_len
< 0) {
327 giterr_set(GITERR_OS
, "Failed to convert string to wide form");
331 /* Strip any trailing forward slash on the proxy URL;
332 * WinHTTP doesn't like it if one is present */
333 if (proxy_wide_len
> 1 && L
'/' == proxy_wide
[proxy_wide_len
- 2])
334 proxy_wide
[proxy_wide_len
- 2] = L
'\0';
336 proxy_info
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
337 proxy_info
.lpszProxy
= proxy_wide
;
338 proxy_info
.lpszProxyBypass
= NULL
;
340 if (!WinHttpSetOption(s
->request
,
341 WINHTTP_OPTION_PROXY
,
343 sizeof(WINHTTP_PROXY_INFO
))) {
344 giterr_set(GITERR_OS
, "Failed to set proxy");
345 git__free(proxy_wide
);
349 git__free(proxy_wide
);
352 /* Disable WinHTTP redirects so we can handle them manually. Why, you ask?
353 * http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae
355 if (!WinHttpSetOption(s
->request
,
356 WINHTTP_OPTION_DISABLE_FEATURE
,
358 sizeof(disable_redirects
))) {
359 giterr_set(GITERR_OS
, "Failed to disable redirects");
363 /* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP
364 * adds itself. This option may not be supported by the underlying
365 * platform, so we do not error-check it */
366 WinHttpSetOption(s
->request
,
367 WINHTTP_OPTION_PEERDIST_EXTENSION_STATE
,
371 /* Send Pragma: no-cache header */
372 if (!WinHttpAddRequestHeaders(s
->request
, pragma_nocache
, (ULONG
) -1L, WINHTTP_ADDREQ_FLAG_ADD
)) {
373 giterr_set(GITERR_OS
, "Failed to add a header to the request");
377 if (post_verb
== s
->verb
) {
378 /* Send Content-Type and Accept headers -- only necessary on a POST */
380 if (git_buf_printf(&buf
,
381 "Content-Type: application/x-git-%s-request",
385 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
386 giterr_set(GITERR_OS
, "Failed to convert content-type to wide characters");
390 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
391 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
392 giterr_set(GITERR_OS
, "Failed to add a header to the request");
397 if (git_buf_printf(&buf
,
398 "Accept: application/x-git-%s-result",
402 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
403 giterr_set(GITERR_OS
, "Failed to convert accept header to wide characters");
407 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
408 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
409 giterr_set(GITERR_OS
, "Failed to add a header to the request");
414 for (i
= 0; i
< t
->owner
->custom_headers
.count
; i
++) {
415 if (t
->owner
->custom_headers
.strings
[i
]) {
417 git_buf_puts(&buf
, t
->owner
->custom_headers
.strings
[i
]);
418 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
419 giterr_set(GITERR_OS
, "Failed to convert custom header to wide characters");
423 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
424 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
425 giterr_set(GITERR_OS
, "Failed to add a header to the request");
431 /* If requested, disable certificate validation */
432 if (t
->connection_data
.use_ssl
) {
435 if (t
->owner
->parent
.read_flags(&t
->owner
->parent
, &flags
) < 0)
439 /* If we have a credential on the subtransport, apply it to the request */
441 t
->cred
->credtype
== GIT_CREDTYPE_USERPASS_PLAINTEXT
&&
442 t
->auth_mechanism
== GIT_WINHTTP_AUTH_BASIC
&&
443 apply_basic_credential(s
->request
, t
->cred
) < 0)
446 t
->cred
->credtype
== GIT_CREDTYPE_DEFAULT
&&
447 t
->auth_mechanism
== GIT_WINHTTP_AUTH_NEGOTIATE
&&
448 apply_default_credentials(s
->request
) < 0)
451 /* If no other credentials have been applied and the URL has username and
452 * password, use those */
453 if (!t
->cred
&& t
->connection_data
.user
&& t
->connection_data
.pass
) {
455 git_cred_userpass_plaintext_new(&t
->url_cred
, t
->connection_data
.user
, t
->connection_data
.pass
) < 0)
457 if (apply_basic_credential(s
->request
, t
->url_cred
) < 0)
461 /* We've done everything up to calling WinHttpSendRequest. */
467 winhttp_stream_close(s
);
469 git__free(proxy_url
);
474 static int parse_unauthorized_response(
479 DWORD supported
, first
, target
;
484 /* WinHttpQueryHeaders() must be called before WinHttpQueryAuthSchemes().
485 * We can assume this was already done, since we know we are unauthorized.
487 if (!WinHttpQueryAuthSchemes(request
, &supported
, &first
, &target
)) {
488 giterr_set(GITERR_OS
, "Failed to parse supported auth schemes");
492 if (WINHTTP_AUTH_SCHEME_BASIC
& supported
) {
493 *allowed_types
|= GIT_CREDTYPE_USERPASS_PLAINTEXT
;
494 *auth_mechanism
= GIT_WINHTTP_AUTH_BASIC
;
497 if ((WINHTTP_AUTH_SCHEME_NTLM
& supported
) ||
498 (WINHTTP_AUTH_SCHEME_NEGOTIATE
& supported
)) {
499 *allowed_types
|= GIT_CREDTYPE_DEFAULT
;
500 *auth_mechanism
= GIT_WINHTTP_AUTH_NEGOTIATE
;
506 static int write_chunk(HINTERNET request
, const char *buffer
, size_t len
)
509 git_buf buf
= GIT_BUF_INIT
;
512 git_buf_printf(&buf
, "%X\r\n", len
);
514 if (git_buf_oom(&buf
))
517 if (!WinHttpWriteData(request
,
518 git_buf_cstr(&buf
), (DWORD
)git_buf_len(&buf
),
521 giterr_set(GITERR_OS
, "Failed to write chunk header");
528 if (!WinHttpWriteData(request
,
531 giterr_set(GITERR_OS
, "Failed to write chunk");
536 if (!WinHttpWriteData(request
,
539 giterr_set(GITERR_OS
, "Failed to write chunk footer");
546 static int winhttp_close_connection(winhttp_subtransport
*t
)
551 if (!WinHttpCloseHandle(t
->connection
)) {
552 giterr_set(GITERR_OS
, "Unable to close connection");
556 t
->connection
= NULL
;
560 if (!WinHttpCloseHandle(t
->session
)) {
561 giterr_set(GITERR_OS
, "Unable to close session");
571 static int user_agent(git_buf
*ua
)
573 const char *custom
= git_libgit2__user_agent();
576 git_buf_PUTS(ua
, "git/1.0 (");
579 git_buf_puts(ua
, custom
);
581 git_buf_PUTS(ua
, "libgit2 " LIBGIT2_VERSION
);
583 return git_buf_putc(ua
, ')');
586 static int winhttp_connect(
587 winhttp_subtransport
*t
)
592 git_buf ua
= GIT_BUF_INIT
;
594 int default_timeout
= TIMEOUT_INFINITE
;
595 int default_connect_timeout
= DEFAULT_CONNECT_TIMEOUT
;
598 t
->connection
= NULL
;
601 if (git__strtol32(&port
, t
->connection_data
.port
, NULL
, 10) < 0)
605 if (git__utf8_to_16_alloc(&wide_host
, t
->connection_data
.host
) < 0) {
606 giterr_set(GITERR_OS
, "Unable to convert host to wide characters");
610 if ((error
= user_agent(&ua
)) < 0) {
611 git__free(wide_host
);
615 if (git__utf8_to_16_alloc(&wide_ua
, git_buf_cstr(&ua
)) < 0) {
616 giterr_set(GITERR_OS
, "Unable to convert host to wide characters");
617 git__free(wide_host
);
624 /* Establish session */
625 t
->session
= WinHttpOpen(
627 WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
,
628 WINHTTP_NO_PROXY_NAME
,
629 WINHTTP_NO_PROXY_BYPASS
,
633 giterr_set(GITERR_OS
, "Failed to init WinHTTP");
637 if (!WinHttpSetTimeouts(t
->session
, default_timeout
, default_connect_timeout
, default_timeout
, default_timeout
)) {
638 giterr_set(GITERR_OS
, "Failed to set timeouts for WinHTTP");
643 /* Establish connection */
644 t
->connection
= WinHttpConnect(
647 (INTERNET_PORT
) port
,
650 if (!t
->connection
) {
651 giterr_set(GITERR_OS
, "Failed to connect to host");
659 winhttp_close_connection(t
);
661 git__free(wide_host
);
667 static int do_send_request(winhttp_stream
*s
, size_t len
, int ignore_length
)
670 if (!WinHttpSendRequest(s
->request
,
671 WINHTTP_NO_ADDITIONAL_HEADERS
, 0,
672 WINHTTP_NO_REQUEST_DATA
, 0,
673 WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH
, 0)) {
677 if (!WinHttpSendRequest(s
->request
,
678 WINHTTP_NO_ADDITIONAL_HEADERS
, 0,
679 WINHTTP_NO_REQUEST_DATA
, 0,
688 static int send_request(winhttp_stream
*s
, size_t len
, int ignore_length
)
690 int request_failed
= 0, cert_valid
= 1, error
= 0;
693 if ((error
= do_send_request(s
, len
, ignore_length
)) < 0)
696 if (request_failed
) {
697 if (GetLastError() != ERROR_WINHTTP_SECURE_FAILURE
) {
698 giterr_set(GITERR_OS
, "failed to send request");
706 if ((error
= certificate_check(s
, cert_valid
)) < 0) {
708 giterr_set(GITERR_OS
, "user cancelled certificate check");
713 /* if neither the request nor the certificate check returned errors, we're done */
717 ignore_flags
= no_check_cert_flags
;
719 if (!WinHttpSetOption(s
->request
, WINHTTP_OPTION_SECURITY_FLAGS
, &ignore_flags
, sizeof(ignore_flags
))) {
720 giterr_set(GITERR_OS
, "failed to set security options");
724 if ((error
= do_send_request(s
, len
, ignore_length
)) < 0)
725 giterr_set(GITERR_OS
, "failed to send request");
730 static int winhttp_stream_read(
731 git_smart_subtransport_stream
*stream
,
736 winhttp_stream
*s
= (winhttp_stream
*)stream
;
737 winhttp_subtransport
*t
= OWNING_SUBTRANSPORT(s
);
739 char replay_count
= 0;
743 /* Enforce a reasonable cap on the number of replays */
744 if (++replay_count
>= 7) {
745 giterr_set(GITERR_NET
, "Too many redirects or authentication replays");
749 /* Connect if necessary */
750 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
753 if (!s
->received_response
) {
754 DWORD status_code
, status_code_length
, content_type_length
, bytes_written
;
755 char expected_content_type_8
[MAX_CONTENT_TYPE_LEN
];
756 wchar_t expected_content_type
[MAX_CONTENT_TYPE_LEN
], content_type
[MAX_CONTENT_TYPE_LEN
];
758 if (!s
->sent_request
) {
760 if ((error
= send_request(s
, s
->post_body_len
, 0)) < 0)
767 assert(s
->verb
== post_verb
);
769 /* Flush, if necessary */
770 if (s
->chunk_buffer_len
> 0 &&
771 write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
774 s
->chunk_buffer_len
= 0;
776 /* Write the final chunk. */
777 if (!WinHttpWriteData(s
->request
,
780 giterr_set(GITERR_OS
, "Failed to write final chunk");
784 else if (s
->post_body
) {
786 DWORD len
= s
->post_body_len
, bytes_read
;
788 if (INVALID_SET_FILE_POINTER
== SetFilePointer(s
->post_body
,
790 NO_ERROR
!= GetLastError()) {
791 giterr_set(GITERR_OS
, "Failed to reset file pointer");
795 buffer
= git__malloc(CACHED_POST_BODY_BUF_SIZE
);
800 if (!ReadFile(s
->post_body
, buffer
,
801 min(CACHED_POST_BODY_BUF_SIZE
, len
),
802 &bytes_read
, NULL
) ||
805 giterr_set(GITERR_OS
, "Failed to read from temp file");
809 if (!WinHttpWriteData(s
->request
, buffer
,
810 bytes_read
, &bytes_written
)) {
812 giterr_set(GITERR_OS
, "Failed to write data");
817 assert(bytes_read
== bytes_written
);
822 /* Eagerly close the temp file */
823 CloseHandle(s
->post_body
);
827 if (!WinHttpReceiveResponse(s
->request
, 0)) {
828 giterr_set(GITERR_OS
, "Failed to receive response");
832 /* Verify that we got a 200 back */
833 status_code_length
= sizeof(status_code
);
835 if (!WinHttpQueryHeaders(s
->request
,
836 WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
,
837 WINHTTP_HEADER_NAME_BY_INDEX
,
838 &status_code
, &status_code_length
,
839 WINHTTP_NO_HEADER_INDEX
)) {
840 giterr_set(GITERR_OS
, "Failed to retrieve status code");
844 /* The implementation of WinHTTP prior to Windows 7 will not
845 * redirect to an identical URI. Some Git hosters use self-redirects
846 * as part of their DoS mitigation strategy. Check first to see if we
847 * have a redirect status code, and that we haven't already streamed
848 * a post body. (We can't replay a streamed POST.) */
850 (HTTP_STATUS_MOVED
== status_code
||
851 HTTP_STATUS_REDIRECT
== status_code
||
852 (HTTP_STATUS_REDIRECT_METHOD
== status_code
&&
853 get_verb
== s
->verb
) ||
854 HTTP_STATUS_REDIRECT_KEEP_VERB
== status_code
)) {
856 /* Check for Windows 7. This workaround is only necessary on
857 * Windows Vista and earlier. Windows 7 is version 6.1. */
859 DWORD location_length
;
862 /* OK, fetch the Location header from the redirect. */
863 if (WinHttpQueryHeaders(s
->request
,
864 WINHTTP_QUERY_LOCATION
,
865 WINHTTP_HEADER_NAME_BY_INDEX
,
866 WINHTTP_NO_OUTPUT_BUFFER
,
868 WINHTTP_NO_HEADER_INDEX
) ||
869 GetLastError() != ERROR_INSUFFICIENT_BUFFER
) {
870 giterr_set(GITERR_OS
, "Failed to read Location header");
874 location
= git__malloc(location_length
);
875 GITERR_CHECK_ALLOC(location
);
877 if (!WinHttpQueryHeaders(s
->request
,
878 WINHTTP_QUERY_LOCATION
,
879 WINHTTP_HEADER_NAME_BY_INDEX
,
882 WINHTTP_NO_HEADER_INDEX
)) {
883 giterr_set(GITERR_OS
, "Failed to read Location header");
888 /* Convert the Location header to UTF-8 */
889 if (git__utf16_to_8_alloc(&location8
, location
) < 0) {
890 giterr_set(GITERR_OS
, "Failed to convert Location header to UTF-8");
897 /* Replay the request */
898 winhttp_stream_close(s
);
900 if (!git__prefixcmp_icase(location8
, prefix_https
)) {
901 /* Upgrade to secure connection; disconnect and start over */
902 if (gitno_connection_data_from_url(&t
->connection_data
, location8
, s
->service_url
) < 0) {
903 git__free(location8
);
907 winhttp_close_connection(t
);
909 if (winhttp_connect(t
) < 0)
913 git__free(location8
);
917 /* Handle authentication failures */
918 if (HTTP_STATUS_DENIED
== status_code
&& get_verb
== s
->verb
) {
921 if (parse_unauthorized_response(s
->request
, &allowed_types
, &t
->auth_mechanism
) < 0)
925 (!t
->cred
|| 0 == (t
->cred
->credtype
& allowed_types
))) {
928 /* Start with the user-supplied credential callback, if present */
929 if (t
->owner
->cred_acquire_cb
) {
930 cred_error
= t
->owner
->cred_acquire_cb(&t
->cred
, t
->owner
->url
,
931 t
->connection_data
.user
, allowed_types
, t
->owner
->cred_acquire_payload
);
937 /* Invoke the fallback credentials acquisition callback if necessary */
938 if (cred_error
> 0) {
939 cred_error
= fallback_cred_acquire_cb(&t
->cred
, t
->owner
->url
,
940 t
->connection_data
.user
, allowed_types
, NULL
);
949 winhttp_stream_close(s
);
951 /* Successfully acquired a credential */
957 if (HTTP_STATUS_OK
!= status_code
) {
958 giterr_set(GITERR_NET
, "Request failed with status code: %d", status_code
);
962 /* Verify that we got the correct content-type back */
963 if (post_verb
== s
->verb
)
964 p_snprintf(expected_content_type_8
, MAX_CONTENT_TYPE_LEN
, "application/x-git-%s-result", s
->service
);
966 p_snprintf(expected_content_type_8
, MAX_CONTENT_TYPE_LEN
, "application/x-git-%s-advertisement", s
->service
);
968 if (git__utf8_to_16(expected_content_type
, MAX_CONTENT_TYPE_LEN
, expected_content_type_8
) < 0) {
969 giterr_set(GITERR_OS
, "Failed to convert expected content-type to wide characters");
973 content_type_length
= sizeof(content_type
);
975 if (!WinHttpQueryHeaders(s
->request
,
976 WINHTTP_QUERY_CONTENT_TYPE
,
977 WINHTTP_HEADER_NAME_BY_INDEX
,
978 &content_type
, &content_type_length
,
979 WINHTTP_NO_HEADER_INDEX
)) {
980 giterr_set(GITERR_OS
, "Failed to retrieve response content-type");
984 if (wcscmp(expected_content_type
, content_type
)) {
985 giterr_set(GITERR_NET
, "Received unexpected content-type");
989 s
->received_response
= 1;
992 if (!WinHttpReadData(s
->request
,
997 giterr_set(GITERR_OS
, "Failed to read data");
1001 *bytes_read
= dw_bytes_read
;
1006 static int winhttp_stream_write_single(
1007 git_smart_subtransport_stream
*stream
,
1011 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1012 DWORD bytes_written
;
1015 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1018 /* This implementation of write permits only a single call. */
1019 if (s
->sent_request
) {
1020 giterr_set(GITERR_NET
, "Subtransport configured for only one write");
1024 if ((error
= send_request(s
, len
, 0)) < 0)
1027 s
->sent_request
= 1;
1029 if (!WinHttpWriteData(s
->request
,
1033 giterr_set(GITERR_OS
, "Failed to write data");
1037 assert((DWORD
)len
== bytes_written
);
1042 static int put_uuid_string(LPWSTR buffer
, size_t buffer_len_cch
)
1045 RPC_STATUS status
= UuidCreate(&uuid
);
1048 if (RPC_S_OK
!= status
&&
1049 RPC_S_UUID_LOCAL_ONLY
!= status
&&
1050 RPC_S_UUID_NO_ADDRESS
!= status
) {
1051 giterr_set(GITERR_NET
, "Unable to generate name for temp file");
1055 if (buffer_len_cch
< UUID_LENGTH_CCH
+ 1) {
1056 giterr_set(GITERR_NET
, "Buffer too small for name of temp file");
1060 #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
1061 result
= swprintf_s(buffer
, buffer_len_cch
,
1063 result
= wsprintfW(buffer
,
1065 L
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x",
1066 uuid
.Data1
, uuid
.Data2
, uuid
.Data3
,
1067 uuid
.Data4
[0], uuid
.Data4
[1], uuid
.Data4
[2], uuid
.Data4
[3],
1068 uuid
.Data4
[4], uuid
.Data4
[5], uuid
.Data4
[6], uuid
.Data4
[7]);
1070 if (result
< UUID_LENGTH_CCH
) {
1071 giterr_set(GITERR_OS
, "Unable to generate name for temp file");
1078 static int get_temp_file(LPWSTR buffer
, DWORD buffer_len_cch
)
1082 if (!GetTempPathW(buffer_len_cch
, buffer
)) {
1083 giterr_set(GITERR_OS
, "Failed to get temp path");
1087 len
= wcslen(buffer
);
1089 if (buffer
[len
- 1] != '\\' && len
< buffer_len_cch
)
1090 buffer
[len
++] = '\\';
1092 if (put_uuid_string(&buffer
[len
], (size_t)buffer_len_cch
- len
) < 0)
1098 static int winhttp_stream_write_buffered(
1099 git_smart_subtransport_stream
*stream
,
1103 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1104 DWORD bytes_written
;
1106 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1109 /* Buffer the payload, using a temporary file so we delegate
1110 * memory management of the data to the operating system. */
1111 if (!s
->post_body
) {
1112 wchar_t temp_path
[MAX_PATH
+ 1];
1114 if (get_temp_file(temp_path
, MAX_PATH
+ 1) < 0)
1117 s
->post_body
= CreateFileW(temp_path
,
1118 GENERIC_READ
| GENERIC_WRITE
,
1119 FILE_SHARE_DELETE
, NULL
,
1121 FILE_ATTRIBUTE_TEMPORARY
| FILE_FLAG_DELETE_ON_CLOSE
| FILE_FLAG_SEQUENTIAL_SCAN
,
1124 if (INVALID_HANDLE_VALUE
== s
->post_body
) {
1125 s
->post_body
= NULL
;
1126 giterr_set(GITERR_OS
, "Failed to create temporary file");
1131 if (!WriteFile(s
->post_body
, buffer
, (DWORD
)len
, &bytes_written
, NULL
)) {
1132 giterr_set(GITERR_OS
, "Failed to write to temporary file");
1136 assert((DWORD
)len
== bytes_written
);
1138 s
->post_body_len
+= bytes_written
;
1143 static int winhttp_stream_write_chunked(
1144 git_smart_subtransport_stream
*stream
,
1148 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1151 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1154 if (!s
->sent_request
) {
1155 /* Send Transfer-Encoding: chunked header */
1156 if (!WinHttpAddRequestHeaders(s
->request
,
1157 transfer_encoding
, (ULONG
) -1L,
1158 WINHTTP_ADDREQ_FLAG_ADD
)) {
1159 giterr_set(GITERR_OS
, "Failed to add a header to the request");
1163 if ((error
= send_request(s
, 0, 1)) < 0)
1166 s
->sent_request
= 1;
1169 if (len
> CACHED_POST_BODY_BUF_SIZE
) {
1170 /* Flush, if necessary */
1171 if (s
->chunk_buffer_len
> 0) {
1172 if (write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
1175 s
->chunk_buffer_len
= 0;
1178 /* Write chunk directly */
1179 if (write_chunk(s
->request
, buffer
, len
) < 0)
1183 /* Append as much to the buffer as we can */
1184 int count
= (int)min(CACHED_POST_BODY_BUF_SIZE
- s
->chunk_buffer_len
, len
);
1186 if (!s
->chunk_buffer
)
1187 s
->chunk_buffer
= git__malloc(CACHED_POST_BODY_BUF_SIZE
);
1189 memcpy(s
->chunk_buffer
+ s
->chunk_buffer_len
, buffer
, count
);
1190 s
->chunk_buffer_len
+= count
;
1194 /* Is the buffer full? If so, then flush */
1195 if (CACHED_POST_BODY_BUF_SIZE
== s
->chunk_buffer_len
) {
1196 if (write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
1199 s
->chunk_buffer_len
= 0;
1201 /* Is there any remaining data from the source? */
1203 memcpy(s
->chunk_buffer
, buffer
, len
);
1204 s
->chunk_buffer_len
= (unsigned int)len
;
1212 static void winhttp_stream_free(git_smart_subtransport_stream
*stream
)
1214 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1216 winhttp_stream_close(s
);
1220 static int winhttp_stream_alloc(winhttp_subtransport
*t
, winhttp_stream
**stream
)
1227 s
= git__calloc(1, sizeof(winhttp_stream
));
1228 GITERR_CHECK_ALLOC(s
);
1230 s
->parent
.subtransport
= &t
->parent
;
1231 s
->parent
.read
= winhttp_stream_read
;
1232 s
->parent
.write
= winhttp_stream_write_single
;
1233 s
->parent
.free
= winhttp_stream_free
;
1240 static int winhttp_uploadpack_ls(
1241 winhttp_subtransport
*t
,
1246 s
->service
= upload_pack_service
;
1247 s
->service_url
= upload_pack_ls_service_url
;
1253 static int winhttp_uploadpack(
1254 winhttp_subtransport
*t
,
1259 s
->service
= upload_pack_service
;
1260 s
->service_url
= upload_pack_service_url
;
1261 s
->verb
= post_verb
;
1266 static int winhttp_receivepack_ls(
1267 winhttp_subtransport
*t
,
1272 s
->service
= receive_pack_service
;
1273 s
->service_url
= receive_pack_ls_service_url
;
1279 static int winhttp_receivepack(
1280 winhttp_subtransport
*t
,
1285 /* WinHTTP only supports Transfer-Encoding: chunked
1286 * on Windows Vista (NT 6.0) and higher. */
1287 s
->chunked
= git_has_win32_version(6, 0, 0);
1290 s
->parent
.write
= winhttp_stream_write_chunked
;
1292 s
->parent
.write
= winhttp_stream_write_buffered
;
1294 s
->service
= receive_pack_service
;
1295 s
->service_url
= receive_pack_service_url
;
1296 s
->verb
= post_verb
;
1301 static int winhttp_action(
1302 git_smart_subtransport_stream
**stream
,
1303 git_smart_subtransport
*subtransport
,
1305 git_smart_service_t action
)
1307 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1312 if ((ret
= gitno_connection_data_from_url(&t
->connection_data
, url
, NULL
)) < 0 ||
1313 (ret
= winhttp_connect(t
)) < 0)
1316 if (winhttp_stream_alloc(t
, &s
) < 0)
1324 case GIT_SERVICE_UPLOADPACK_LS
:
1325 ret
= winhttp_uploadpack_ls(t
, s
);
1328 case GIT_SERVICE_UPLOADPACK
:
1329 ret
= winhttp_uploadpack(t
, s
);
1332 case GIT_SERVICE_RECEIVEPACK_LS
:
1333 ret
= winhttp_receivepack_ls(t
, s
);
1336 case GIT_SERVICE_RECEIVEPACK
:
1337 ret
= winhttp_receivepack(t
, s
);
1345 *stream
= &s
->parent
;
1350 static int winhttp_close(git_smart_subtransport
*subtransport
)
1352 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1354 gitno_connection_data_free_ptrs(&t
->connection_data
);
1355 memset(&t
->connection_data
, 0x0, sizeof(gitno_connection_data
));
1358 t
->cred
->free(t
->cred
);
1363 t
->url_cred
->free(t
->url_cred
);
1367 return winhttp_close_connection(t
);
1370 static void winhttp_free(git_smart_subtransport
*subtransport
)
1372 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1374 winhttp_close(subtransport
);
1379 int git_smart_subtransport_http(git_smart_subtransport
**out
, git_transport
*owner
, void *param
)
1381 winhttp_subtransport
*t
;
1388 t
= git__calloc(1, sizeof(winhttp_subtransport
));
1389 GITERR_CHECK_ALLOC(t
);
1391 t
->owner
= (transport_smart
*)owner
;
1392 t
->parent
.action
= winhttp_action
;
1393 t
->parent
.close
= winhttp_close
;
1394 t
->parent
.free
= winhttp_free
;
1396 *out
= (git_smart_subtransport
*) t
;
1400 #endif /* GIT_WINHTTP */