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 static const CLSID CLSID_InternetSecurityManager_mingw
=
57 { 0x7B8A2D94, 0x0AC9, 0x11D1,
58 { 0x89, 0x6C, 0x00, 0xC0, 0x4F, 0xB6, 0xBF, 0xC4 } };
59 static const IID IID_IInternetSecurityManager_mingw
=
60 { 0x79EAC9EE, 0xBAF9, 0x11CE,
61 { 0x8C, 0x82, 0x00, 0xAA, 0x00, 0x4B, 0xA9, 0x0B } };
63 # define CLSID_InternetSecurityManager CLSID_InternetSecurityManager_mingw
64 # define IID_IInternetSecurityManager IID_IInternetSecurityManager_mingw
67 #define OWNING_SUBTRANSPORT(s) ((winhttp_subtransport *)(s)->parent.subtransport)
70 GIT_WINHTTP_AUTH_BASIC
= 1,
71 GIT_WINHTTP_AUTH_NEGOTIATE
= 2,
72 } winhttp_authmechanism_t
;
75 git_smart_subtransport_stream parent
;
77 const char *service_url
;
82 unsigned chunk_buffer_len
;
85 unsigned sent_request
: 1,
86 received_response
: 1,
91 git_smart_subtransport parent
;
92 transport_smart
*owner
;
93 gitno_connection_data connection_data
;
94 gitno_connection_data proxy_connection_data
;
100 HINTERNET connection
;
101 } winhttp_subtransport
;
103 static int apply_basic_credential_proxy(HINTERNET request
, git_cred
*cred
)
105 git_cred_userpass_plaintext
*c
= (git_cred_userpass_plaintext
*)cred
;
106 wchar_t *user
, *pass
;
109 if ((error
= git__utf8_to_16_alloc(&user
, c
->username
)) < 0)
112 if ((error
= git__utf8_to_16_alloc(&pass
, c
->password
)) < 0)
115 if (!WinHttpSetCredentials(request
, WINHTTP_AUTH_TARGET_PROXY
, WINHTTP_AUTH_SCHEME_BASIC
,
117 giterr_set(GITERR_OS
, "failed to set proxy auth");
127 static int apply_basic_credential(HINTERNET request
, git_cred
*cred
)
129 git_cred_userpass_plaintext
*c
= (git_cred_userpass_plaintext
*)cred
;
130 git_buf buf
= GIT_BUF_INIT
, raw
= GIT_BUF_INIT
;
131 wchar_t *wide
= NULL
;
132 int error
= -1, wide_len
;
134 git_buf_printf(&raw
, "%s:%s", c
->username
, c
->password
);
136 if (git_buf_oom(&raw
) ||
137 git_buf_puts(&buf
, "Authorization: Basic ") < 0 ||
138 git_buf_encode_base64(&buf
, git_buf_cstr(&raw
), raw
.size
) < 0)
141 if ((wide_len
= git__utf8_to_16_alloc(&wide
, git_buf_cstr(&buf
))) < 0) {
142 giterr_set(GITERR_OS
, "Failed to convert string to wide form");
146 if (!WinHttpAddRequestHeaders(request
, wide
, (ULONG
) -1L, WINHTTP_ADDREQ_FLAG_ADD
)) {
147 giterr_set(GITERR_OS
, "Failed to add a header to the request");
154 /* We were dealing with plaintext passwords, so clean up after ourselves a bit. */
156 memset(wide
, 0x0, wide_len
* sizeof(wchar_t));
159 memset(buf
.ptr
, 0x0, buf
.size
);
162 memset(raw
.ptr
, 0x0, raw
.size
);
170 static int apply_default_credentials(HINTERNET request
)
172 /* Either the caller explicitly requested that default credentials be passed,
173 * or our fallback credential callback was invoked and checked that the target
174 * URI was in the appropriate Internet Explorer security zone. By setting this
175 * flag, we guarantee that the credentials are delivered by WinHTTP. The default
176 * is "medium" which applies to the intranet and sounds like it would correspond
177 * to Internet Explorer security zones, but in fact does not. */
178 DWORD data
= WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW
;
180 if (!WinHttpSetOption(request
, WINHTTP_OPTION_AUTOLOGON_POLICY
, &data
, sizeof(DWORD
)))
186 static int fallback_cred_acquire_cb(
189 const char *username_from_url
,
190 unsigned int allowed_types
,
195 GIT_UNUSED(username_from_url
);
198 /* If the target URI supports integrated Windows authentication
199 * as an authentication mechanism */
200 if (GIT_CREDTYPE_DEFAULT
& allowed_types
) {
203 /* Convert URL to wide characters */
204 if (git__utf8_to_16_alloc(&wide_url
, url
) < 0) {
205 giterr_set(GITERR_OS
, "Failed to convert string to wide form");
209 if (SUCCEEDED(CoInitializeEx(NULL
, COINIT_MULTITHREADED
))) {
210 IInternetSecurityManager
* pISM
;
212 /* And if the target URI is in the My Computer, Intranet, or Trusted zones */
213 if (SUCCEEDED(CoCreateInstance(&CLSID_InternetSecurityManager
, NULL
,
214 CLSCTX_ALL
, &IID_IInternetSecurityManager
, (void **)&pISM
))) {
217 if (SUCCEEDED(pISM
->lpVtbl
->MapUrlToZone(pISM
, wide_url
, &dwZone
, 0)) &&
218 (URLZONE_LOCAL_MACHINE
== dwZone
||
219 URLZONE_INTRANET
== dwZone
||
220 URLZONE_TRUSTED
== dwZone
)) {
221 git_cred
*existing
= *cred
;
224 existing
->free(existing
);
226 /* Then use default Windows credentials to authenticate this request */
227 error
= git_cred_default_new(cred
);
230 pISM
->lpVtbl
->Release(pISM
);
242 static int certificate_check(winhttp_stream
*s
, int valid
)
245 winhttp_subtransport
*t
= OWNING_SUBTRANSPORT(s
);
246 PCERT_CONTEXT cert_ctx
;
247 DWORD cert_ctx_size
= sizeof(cert_ctx
);
250 /* If there is no override, we should fail if WinHTTP doesn't think it's fine */
251 if (t
->owner
->certificate_check_cb
== NULL
&& !valid
)
252 return GIT_ECERTIFICATE
;
254 if (t
->owner
->certificate_check_cb
== NULL
|| !t
->connection_data
.use_ssl
)
257 if (!WinHttpQueryOption(s
->request
, WINHTTP_OPTION_SERVER_CERT_CONTEXT
, &cert_ctx
, &cert_ctx_size
)) {
258 giterr_set(GITERR_OS
, "failed to get server certificate");
263 cert
.parent
.cert_type
= GIT_CERT_X509
;
264 cert
.data
= cert_ctx
->pbCertEncoded
;
265 cert
.len
= cert_ctx
->cbCertEncoded
;
266 error
= t
->owner
->certificate_check_cb((git_cert
*) &cert
, valid
, t
->connection_data
.host
, t
->owner
->cred_acquire_payload
);
267 CertFreeCertificateContext(cert_ctx
);
269 if (error
< 0 && !giterr_last())
270 giterr_set(GITERR_NET
, "user cancelled certificate check");
275 static void winhttp_stream_close(winhttp_stream
*s
)
277 if (s
->chunk_buffer
) {
278 git__free(s
->chunk_buffer
);
279 s
->chunk_buffer
= NULL
;
283 CloseHandle(s
->post_body
);
287 if (s
->request_uri
) {
288 git__free(s
->request_uri
);
289 s
->request_uri
= NULL
;
293 WinHttpCloseHandle(s
->request
);
301 * Extract the url and password from a URL. The outputs are pointers
304 static int userpass_from_url(wchar_t **user
, int *user_len
,
305 wchar_t **pass
, int *pass_len
,
306 const wchar_t *url
, int url_len
)
308 URL_COMPONENTS components
= { 0 };
310 components
.dwStructSize
= sizeof(components
);
311 /* These tell WinHttpCrackUrl that we're interested in the fields */
312 components
.dwUserNameLength
= 1;
313 components
.dwPasswordLength
= 1;
315 if (!WinHttpCrackUrl(url
, url_len
, 0, &components
)) {
316 giterr_set(GITERR_OS
, "failed to extract user/pass from url");
320 *user
= components
.lpszUserName
;
321 *user_len
= components
.dwUserNameLength
;
322 *pass
= components
.lpszPassword
;
323 *pass_len
= components
.dwPasswordLength
;
328 #define SCHEME_HTTP "http://"
329 #define SCHEME_HTTPS "https://"
331 static int winhttp_stream_connect(winhttp_stream
*s
)
333 winhttp_subtransport
*t
= OWNING_SUBTRANSPORT(s
);
334 git_buf buf
= GIT_BUF_INIT
;
335 char *proxy_url
= NULL
;
336 wchar_t ct
[MAX_CONTENT_TYPE_LEN
];
337 LPCWSTR types
[] = { L
"*/*", NULL
};
338 BOOL peerdist
= FALSE
;
340 unsigned long disable_redirects
= WINHTTP_DISABLE_REDIRECTS
;
341 int default_timeout
= TIMEOUT_INFINITE
;
342 int default_connect_timeout
= DEFAULT_CONNECT_TIMEOUT
;
344 const git_proxy_options
*proxy_opts
;
347 git_buf_printf(&buf
, "%s%s", t
->connection_data
.path
, s
->service_url
);
349 if (git_buf_oom(&buf
))
352 /* Convert URL to wide characters */
353 if (git__utf8_to_16_alloc(&s
->request_uri
, git_buf_cstr(&buf
)) < 0) {
354 giterr_set(GITERR_OS
, "Failed to convert string to wide form");
358 /* Establish request */
359 s
->request
= WinHttpOpenRequest(
366 t
->connection_data
.use_ssl
? WINHTTP_FLAG_SECURE
: 0);
369 giterr_set(GITERR_OS
, "Failed to open request");
373 if (!WinHttpSetTimeouts(s
->request
, default_timeout
, default_connect_timeout
, default_timeout
, default_timeout
)) {
374 giterr_set(GITERR_OS
, "Failed to set timeouts for WinHTTP");
378 proxy_opts
= &t
->owner
->proxy
;
379 if (proxy_opts
->type
== GIT_PROXY_AUTO
) {
380 /* Set proxy if necessary */
381 if (git_remote__get_http_proxy(t
->owner
->owner
, !!t
->connection_data
.use_ssl
, &proxy_url
) < 0)
384 else if (proxy_opts
->type
== GIT_PROXY_SPECIFIED
) {
385 proxy_url
= git__strdup(proxy_opts
->url
);
386 GITERR_CHECK_ALLOC(proxy_url
);
390 git_buf processed_url
= GIT_BUF_INIT
;
391 WINHTTP_PROXY_INFO proxy_info
;
394 if (!git__prefixcmp(proxy_url
, SCHEME_HTTP
)) {
395 t
->proxy_connection_data
.use_ssl
= false;
396 } else if (!git__prefixcmp(proxy_url
, SCHEME_HTTPS
)) {
397 t
->proxy_connection_data
.use_ssl
= true;
399 giterr_set(GITERR_NET
, "invalid URL: '%s'", proxy_url
);
403 gitno_connection_data_free_ptrs(&t
->proxy_connection_data
);
405 if ((error
= gitno_extract_url_parts(&t
->proxy_connection_data
.host
, &t
->proxy_connection_data
.port
, NULL
,
406 &t
->proxy_connection_data
.user
, &t
->proxy_connection_data
.pass
, proxy_url
, NULL
)) < 0)
409 if (t
->proxy_connection_data
.user
&& t
->proxy_connection_data
.pass
) {
411 t
->proxy_cred
->free(t
->proxy_cred
);
414 if ((error
= git_cred_userpass_plaintext_new(&t
->proxy_cred
, t
->proxy_connection_data
.user
, t
->proxy_connection_data
.pass
)) < 0)
418 if (t
->proxy_connection_data
.use_ssl
)
419 git_buf_PUTS(&processed_url
, SCHEME_HTTPS
);
421 git_buf_PUTS(&processed_url
, SCHEME_HTTP
);
423 git_buf_puts(&processed_url
, t
->proxy_connection_data
.host
);
424 if (t
->proxy_connection_data
.port
)
425 git_buf_printf(&processed_url
, ":%s", t
->proxy_connection_data
.port
);
427 if (git_buf_oom(&processed_url
)) {
433 /* Convert URL to wide characters */
434 error
= git__utf8_to_16_alloc(&proxy_wide
, processed_url
.ptr
);
435 git_buf_free(&processed_url
);
439 proxy_info
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
440 proxy_info
.lpszProxy
= proxy_wide
;
441 proxy_info
.lpszProxyBypass
= NULL
;
443 if (!WinHttpSetOption(s
->request
,
444 WINHTTP_OPTION_PROXY
,
446 sizeof(WINHTTP_PROXY_INFO
))) {
447 giterr_set(GITERR_OS
, "Failed to set proxy");
448 git__free(proxy_wide
);
452 git__free(proxy_wide
);
455 if (t
->proxy_cred
->credtype
== GIT_CREDTYPE_USERPASS_PLAINTEXT
) {
456 if ((error
= apply_basic_credential_proxy(s
->request
, t
->proxy_cred
)) < 0)
463 /* Disable WinHTTP redirects so we can handle them manually. Why, you ask?
464 * http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae
466 if (!WinHttpSetOption(s
->request
,
467 WINHTTP_OPTION_DISABLE_FEATURE
,
469 sizeof(disable_redirects
))) {
470 giterr_set(GITERR_OS
, "Failed to disable redirects");
474 /* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP
475 * adds itself. This option may not be supported by the underlying
476 * platform, so we do not error-check it */
477 WinHttpSetOption(s
->request
,
478 WINHTTP_OPTION_PEERDIST_EXTENSION_STATE
,
482 /* Send Pragma: no-cache header */
483 if (!WinHttpAddRequestHeaders(s
->request
, pragma_nocache
, (ULONG
) -1L, WINHTTP_ADDREQ_FLAG_ADD
)) {
484 giterr_set(GITERR_OS
, "Failed to add a header to the request");
488 if (post_verb
== s
->verb
) {
489 /* Send Content-Type and Accept headers -- only necessary on a POST */
491 if (git_buf_printf(&buf
,
492 "Content-Type: application/x-git-%s-request",
496 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
497 giterr_set(GITERR_OS
, "Failed to convert content-type to wide characters");
501 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
502 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
503 giterr_set(GITERR_OS
, "Failed to add a header to the request");
508 if (git_buf_printf(&buf
,
509 "Accept: application/x-git-%s-result",
513 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
514 giterr_set(GITERR_OS
, "Failed to convert accept header to wide characters");
518 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
519 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
520 giterr_set(GITERR_OS
, "Failed to add a header to the request");
525 for (i
= 0; i
< t
->owner
->custom_headers
.count
; i
++) {
526 if (t
->owner
->custom_headers
.strings
[i
]) {
528 git_buf_puts(&buf
, t
->owner
->custom_headers
.strings
[i
]);
529 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
530 giterr_set(GITERR_OS
, "Failed to convert custom header to wide characters");
534 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
535 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
536 giterr_set(GITERR_OS
, "Failed to add a header to the request");
542 /* If requested, disable certificate validation */
543 if (t
->connection_data
.use_ssl
) {
546 if (t
->owner
->parent
.read_flags(&t
->owner
->parent
, &flags
) < 0)
550 /* If we have a credential on the subtransport, apply it to the request */
552 t
->cred
->credtype
== GIT_CREDTYPE_USERPASS_PLAINTEXT
&&
553 t
->auth_mechanism
== GIT_WINHTTP_AUTH_BASIC
&&
554 apply_basic_credential(s
->request
, t
->cred
) < 0)
557 t
->cred
->credtype
== GIT_CREDTYPE_DEFAULT
&&
558 t
->auth_mechanism
== GIT_WINHTTP_AUTH_NEGOTIATE
&&
559 apply_default_credentials(s
->request
) < 0)
562 /* If no other credentials have been applied and the URL has username and
563 * password, use those */
564 if (!t
->cred
&& t
->connection_data
.user
&& t
->connection_data
.pass
) {
566 git_cred_userpass_plaintext_new(&t
->url_cred
, t
->connection_data
.user
, t
->connection_data
.pass
) < 0)
568 if (apply_basic_credential(s
->request
, t
->url_cred
) < 0)
572 /* We've done everything up to calling WinHttpSendRequest. */
578 winhttp_stream_close(s
);
580 git__free(proxy_url
);
585 static int parse_unauthorized_response(
590 DWORD supported
, first
, target
;
595 /* WinHttpQueryHeaders() must be called before WinHttpQueryAuthSchemes().
596 * We can assume this was already done, since we know we are unauthorized.
598 if (!WinHttpQueryAuthSchemes(request
, &supported
, &first
, &target
)) {
599 giterr_set(GITERR_OS
, "Failed to parse supported auth schemes");
603 if (WINHTTP_AUTH_SCHEME_BASIC
& supported
) {
604 *allowed_types
|= GIT_CREDTYPE_USERPASS_PLAINTEXT
;
605 *auth_mechanism
= GIT_WINHTTP_AUTH_BASIC
;
608 if ((WINHTTP_AUTH_SCHEME_NTLM
& supported
) ||
609 (WINHTTP_AUTH_SCHEME_NEGOTIATE
& supported
)) {
610 *allowed_types
|= GIT_CREDTYPE_DEFAULT
;
611 *auth_mechanism
= GIT_WINHTTP_AUTH_NEGOTIATE
;
617 static int write_chunk(HINTERNET request
, const char *buffer
, size_t len
)
620 git_buf buf
= GIT_BUF_INIT
;
623 git_buf_printf(&buf
, "%X\r\n", len
);
625 if (git_buf_oom(&buf
))
628 if (!WinHttpWriteData(request
,
629 git_buf_cstr(&buf
), (DWORD
)git_buf_len(&buf
),
632 giterr_set(GITERR_OS
, "Failed to write chunk header");
639 if (!WinHttpWriteData(request
,
642 giterr_set(GITERR_OS
, "Failed to write chunk");
647 if (!WinHttpWriteData(request
,
650 giterr_set(GITERR_OS
, "Failed to write chunk footer");
657 static int winhttp_close_connection(winhttp_subtransport
*t
)
662 if (!WinHttpCloseHandle(t
->connection
)) {
663 giterr_set(GITERR_OS
, "Unable to close connection");
667 t
->connection
= NULL
;
671 if (!WinHttpCloseHandle(t
->session
)) {
672 giterr_set(GITERR_OS
, "Unable to close session");
682 static int user_agent(git_buf
*ua
)
684 const char *custom
= git_libgit2__user_agent();
687 git_buf_PUTS(ua
, "git/1.0 (");
690 git_buf_puts(ua
, custom
);
692 git_buf_PUTS(ua
, "libgit2 " LIBGIT2_VERSION
);
694 return git_buf_putc(ua
, ')');
697 static int winhttp_connect(
698 winhttp_subtransport
*t
)
703 git_buf ua
= GIT_BUF_INIT
;
705 int default_timeout
= TIMEOUT_INFINITE
;
706 int default_connect_timeout
= DEFAULT_CONNECT_TIMEOUT
;
709 t
->connection
= NULL
;
712 if (git__strtol32(&port
, t
->connection_data
.port
, NULL
, 10) < 0)
716 if (git__utf8_to_16_alloc(&wide_host
, t
->connection_data
.host
) < 0) {
717 giterr_set(GITERR_OS
, "Unable to convert host to wide characters");
721 if ((error
= user_agent(&ua
)) < 0) {
722 git__free(wide_host
);
726 if (git__utf8_to_16_alloc(&wide_ua
, git_buf_cstr(&ua
)) < 0) {
727 giterr_set(GITERR_OS
, "Unable to convert host to wide characters");
728 git__free(wide_host
);
735 /* Establish session */
736 t
->session
= WinHttpOpen(
738 WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
,
739 WINHTTP_NO_PROXY_NAME
,
740 WINHTTP_NO_PROXY_BYPASS
,
744 giterr_set(GITERR_OS
, "Failed to init WinHTTP");
748 if (!WinHttpSetTimeouts(t
->session
, default_timeout
, default_connect_timeout
, default_timeout
, default_timeout
)) {
749 giterr_set(GITERR_OS
, "Failed to set timeouts for WinHTTP");
754 /* Establish connection */
755 t
->connection
= WinHttpConnect(
758 (INTERNET_PORT
) port
,
761 if (!t
->connection
) {
762 giterr_set(GITERR_OS
, "Failed to connect to host");
770 winhttp_close_connection(t
);
772 git__free(wide_host
);
778 static int do_send_request(winhttp_stream
*s
, size_t len
, int ignore_length
)
781 if (!WinHttpSendRequest(s
->request
,
782 WINHTTP_NO_ADDITIONAL_HEADERS
, 0,
783 WINHTTP_NO_REQUEST_DATA
, 0,
784 WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH
, 0)) {
788 if (!WinHttpSendRequest(s
->request
,
789 WINHTTP_NO_ADDITIONAL_HEADERS
, 0,
790 WINHTTP_NO_REQUEST_DATA
, 0,
799 static int send_request(winhttp_stream
*s
, size_t len
, int ignore_length
)
801 int request_failed
= 0, cert_valid
= 1, error
= 0;
804 if ((error
= do_send_request(s
, len
, ignore_length
)) < 0)
807 if (request_failed
) {
808 if (GetLastError() != ERROR_WINHTTP_SECURE_FAILURE
) {
809 giterr_set(GITERR_OS
, "failed to send request");
817 if ((error
= certificate_check(s
, cert_valid
)) < 0) {
819 giterr_set(GITERR_OS
, "user cancelled certificate check");
824 /* if neither the request nor the certificate check returned errors, we're done */
828 ignore_flags
= no_check_cert_flags
;
830 if (!WinHttpSetOption(s
->request
, WINHTTP_OPTION_SECURITY_FLAGS
, &ignore_flags
, sizeof(ignore_flags
))) {
831 giterr_set(GITERR_OS
, "failed to set security options");
835 if ((error
= do_send_request(s
, len
, ignore_length
)) < 0)
836 giterr_set(GITERR_OS
, "failed to send request");
841 static int winhttp_stream_read(
842 git_smart_subtransport_stream
*stream
,
847 winhttp_stream
*s
= (winhttp_stream
*)stream
;
848 winhttp_subtransport
*t
= OWNING_SUBTRANSPORT(s
);
850 char replay_count
= 0;
854 /* Enforce a reasonable cap on the number of replays */
855 if (++replay_count
>= 7) {
856 giterr_set(GITERR_NET
, "Too many redirects or authentication replays");
860 /* Connect if necessary */
861 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
864 if (!s
->received_response
) {
865 DWORD status_code
, status_code_length
, content_type_length
, bytes_written
;
866 char expected_content_type_8
[MAX_CONTENT_TYPE_LEN
];
867 wchar_t expected_content_type
[MAX_CONTENT_TYPE_LEN
], content_type
[MAX_CONTENT_TYPE_LEN
];
869 if (!s
->sent_request
) {
871 if ((error
= send_request(s
, s
->post_body_len
, 0)) < 0)
878 assert(s
->verb
== post_verb
);
880 /* Flush, if necessary */
881 if (s
->chunk_buffer_len
> 0 &&
882 write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
885 s
->chunk_buffer_len
= 0;
887 /* Write the final chunk. */
888 if (!WinHttpWriteData(s
->request
,
891 giterr_set(GITERR_OS
, "Failed to write final chunk");
895 else if (s
->post_body
) {
897 DWORD len
= s
->post_body_len
, bytes_read
;
899 if (INVALID_SET_FILE_POINTER
== SetFilePointer(s
->post_body
,
901 NO_ERROR
!= GetLastError()) {
902 giterr_set(GITERR_OS
, "Failed to reset file pointer");
906 buffer
= git__malloc(CACHED_POST_BODY_BUF_SIZE
);
911 if (!ReadFile(s
->post_body
, buffer
,
912 min(CACHED_POST_BODY_BUF_SIZE
, len
),
913 &bytes_read
, NULL
) ||
916 giterr_set(GITERR_OS
, "Failed to read from temp file");
920 if (!WinHttpWriteData(s
->request
, buffer
,
921 bytes_read
, &bytes_written
)) {
923 giterr_set(GITERR_OS
, "Failed to write data");
928 assert(bytes_read
== bytes_written
);
933 /* Eagerly close the temp file */
934 CloseHandle(s
->post_body
);
938 if (!WinHttpReceiveResponse(s
->request
, 0)) {
939 giterr_set(GITERR_OS
, "Failed to receive response");
943 /* Verify that we got a 200 back */
944 status_code_length
= sizeof(status_code
);
946 if (!WinHttpQueryHeaders(s
->request
,
947 WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
,
948 WINHTTP_HEADER_NAME_BY_INDEX
,
949 &status_code
, &status_code_length
,
950 WINHTTP_NO_HEADER_INDEX
)) {
951 giterr_set(GITERR_OS
, "Failed to retrieve status code");
955 /* The implementation of WinHTTP prior to Windows 7 will not
956 * redirect to an identical URI. Some Git hosters use self-redirects
957 * as part of their DoS mitigation strategy. Check first to see if we
958 * have a redirect status code, and that we haven't already streamed
959 * a post body. (We can't replay a streamed POST.) */
961 (HTTP_STATUS_MOVED
== status_code
||
962 HTTP_STATUS_REDIRECT
== status_code
||
963 (HTTP_STATUS_REDIRECT_METHOD
== status_code
&&
964 get_verb
== s
->verb
) ||
965 HTTP_STATUS_REDIRECT_KEEP_VERB
== status_code
)) {
967 /* Check for Windows 7. This workaround is only necessary on
968 * Windows Vista and earlier. Windows 7 is version 6.1. */
970 DWORD location_length
;
973 /* OK, fetch the Location header from the redirect. */
974 if (WinHttpQueryHeaders(s
->request
,
975 WINHTTP_QUERY_LOCATION
,
976 WINHTTP_HEADER_NAME_BY_INDEX
,
977 WINHTTP_NO_OUTPUT_BUFFER
,
979 WINHTTP_NO_HEADER_INDEX
) ||
980 GetLastError() != ERROR_INSUFFICIENT_BUFFER
) {
981 giterr_set(GITERR_OS
, "Failed to read Location header");
985 location
= git__malloc(location_length
);
986 GITERR_CHECK_ALLOC(location
);
988 if (!WinHttpQueryHeaders(s
->request
,
989 WINHTTP_QUERY_LOCATION
,
990 WINHTTP_HEADER_NAME_BY_INDEX
,
993 WINHTTP_NO_HEADER_INDEX
)) {
994 giterr_set(GITERR_OS
, "Failed to read Location header");
999 /* Convert the Location header to UTF-8 */
1000 if (git__utf16_to_8_alloc(&location8
, location
) < 0) {
1001 giterr_set(GITERR_OS
, "Failed to convert Location header to UTF-8");
1002 git__free(location
);
1006 git__free(location
);
1008 /* Replay the request */
1009 winhttp_stream_close(s
);
1011 if (!git__prefixcmp_icase(location8
, prefix_https
)) {
1012 /* Upgrade to secure connection; disconnect and start over */
1013 if (gitno_connection_data_from_url(&t
->connection_data
, location8
, s
->service_url
) < 0) {
1014 git__free(location8
);
1018 winhttp_close_connection(t
);
1020 if (winhttp_connect(t
) < 0)
1024 git__free(location8
);
1028 /* Handle proxy authentication failures */
1029 if (status_code
== HTTP_STATUS_PROXY_AUTH_REQ
) {
1032 if (parse_unauthorized_response(s
->request
, &allowed_types
, &t
->auth_mechanism
) < 0)
1035 /* TODO: extract the username from the url, no payload? */
1036 if (t
->owner
->proxy
.credentials
) {
1038 cred_error
= t
->owner
->proxy
.credentials(&t
->proxy_cred
, t
->owner
->proxy
.url
, NULL
, allowed_types
, NULL
);
1044 winhttp_stream_close(s
);
1048 /* Handle authentication failures */
1049 if (HTTP_STATUS_DENIED
== status_code
&& get_verb
== s
->verb
) {
1052 if (parse_unauthorized_response(s
->request
, &allowed_types
, &t
->auth_mechanism
) < 0)
1055 if (allowed_types
) {
1058 git_cred_free(t
->cred
);
1060 /* Start with the user-supplied credential callback, if present */
1061 if (t
->owner
->cred_acquire_cb
) {
1062 cred_error
= t
->owner
->cred_acquire_cb(&t
->cred
, t
->owner
->url
,
1063 t
->connection_data
.user
, allowed_types
, t
->owner
->cred_acquire_payload
);
1065 /* Treat GIT_PASSTHROUGH as though git_cred_acquire_cb isn't set */
1066 if (cred_error
== GIT_PASSTHROUGH
)
1068 else if (cred_error
< 0)
1072 /* Invoke the fallback credentials acquisition callback if necessary */
1073 if (cred_error
> 0) {
1074 cred_error
= fallback_cred_acquire_cb(&t
->cred
, t
->owner
->url
,
1075 t
->connection_data
.user
, allowed_types
, NULL
);
1084 winhttp_stream_close(s
);
1086 /* Successfully acquired a credential */
1092 if (HTTP_STATUS_OK
!= status_code
) {
1093 giterr_set(GITERR_NET
, "Request failed with status code: %d", status_code
);
1097 /* Verify that we got the correct content-type back */
1098 if (post_verb
== s
->verb
)
1099 p_snprintf(expected_content_type_8
, MAX_CONTENT_TYPE_LEN
, "application/x-git-%s-result", s
->service
);
1101 p_snprintf(expected_content_type_8
, MAX_CONTENT_TYPE_LEN
, "application/x-git-%s-advertisement", s
->service
);
1103 if (git__utf8_to_16(expected_content_type
, MAX_CONTENT_TYPE_LEN
, expected_content_type_8
) < 0) {
1104 giterr_set(GITERR_OS
, "Failed to convert expected content-type to wide characters");
1108 content_type_length
= sizeof(content_type
);
1110 if (!WinHttpQueryHeaders(s
->request
,
1111 WINHTTP_QUERY_CONTENT_TYPE
,
1112 WINHTTP_HEADER_NAME_BY_INDEX
,
1113 &content_type
, &content_type_length
,
1114 WINHTTP_NO_HEADER_INDEX
)) {
1115 giterr_set(GITERR_OS
, "Failed to retrieve response content-type");
1119 if (wcscmp(expected_content_type
, content_type
)) {
1120 giterr_set(GITERR_NET
, "Received unexpected content-type");
1124 s
->received_response
= 1;
1127 if (!WinHttpReadData(s
->request
,
1132 giterr_set(GITERR_OS
, "Failed to read data");
1136 *bytes_read
= dw_bytes_read
;
1141 static int winhttp_stream_write_single(
1142 git_smart_subtransport_stream
*stream
,
1146 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1147 DWORD bytes_written
;
1150 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1153 /* This implementation of write permits only a single call. */
1154 if (s
->sent_request
) {
1155 giterr_set(GITERR_NET
, "Subtransport configured for only one write");
1159 if ((error
= send_request(s
, len
, 0)) < 0)
1162 s
->sent_request
= 1;
1164 if (!WinHttpWriteData(s
->request
,
1168 giterr_set(GITERR_OS
, "Failed to write data");
1172 assert((DWORD
)len
== bytes_written
);
1177 static int put_uuid_string(LPWSTR buffer
, size_t buffer_len_cch
)
1180 RPC_STATUS status
= UuidCreate(&uuid
);
1183 if (RPC_S_OK
!= status
&&
1184 RPC_S_UUID_LOCAL_ONLY
!= status
&&
1185 RPC_S_UUID_NO_ADDRESS
!= status
) {
1186 giterr_set(GITERR_NET
, "Unable to generate name for temp file");
1190 if (buffer_len_cch
< UUID_LENGTH_CCH
+ 1) {
1191 giterr_set(GITERR_NET
, "Buffer too small for name of temp file");
1195 #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
1196 result
= swprintf_s(buffer
, buffer_len_cch
,
1198 result
= wsprintfW(buffer
,
1200 L
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x",
1201 uuid
.Data1
, uuid
.Data2
, uuid
.Data3
,
1202 uuid
.Data4
[0], uuid
.Data4
[1], uuid
.Data4
[2], uuid
.Data4
[3],
1203 uuid
.Data4
[4], uuid
.Data4
[5], uuid
.Data4
[6], uuid
.Data4
[7]);
1205 if (result
< UUID_LENGTH_CCH
) {
1206 giterr_set(GITERR_OS
, "Unable to generate name for temp file");
1213 static int get_temp_file(LPWSTR buffer
, DWORD buffer_len_cch
)
1217 if (!GetTempPathW(buffer_len_cch
, buffer
)) {
1218 giterr_set(GITERR_OS
, "Failed to get temp path");
1222 len
= wcslen(buffer
);
1224 if (buffer
[len
- 1] != '\\' && len
< buffer_len_cch
)
1225 buffer
[len
++] = '\\';
1227 if (put_uuid_string(&buffer
[len
], (size_t)buffer_len_cch
- len
) < 0)
1233 static int winhttp_stream_write_buffered(
1234 git_smart_subtransport_stream
*stream
,
1238 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1239 DWORD bytes_written
;
1241 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1244 /* Buffer the payload, using a temporary file so we delegate
1245 * memory management of the data to the operating system. */
1246 if (!s
->post_body
) {
1247 wchar_t temp_path
[MAX_PATH
+ 1];
1249 if (get_temp_file(temp_path
, MAX_PATH
+ 1) < 0)
1252 s
->post_body
= CreateFileW(temp_path
,
1253 GENERIC_READ
| GENERIC_WRITE
,
1254 FILE_SHARE_DELETE
, NULL
,
1256 FILE_ATTRIBUTE_TEMPORARY
| FILE_FLAG_DELETE_ON_CLOSE
| FILE_FLAG_SEQUENTIAL_SCAN
,
1259 if (INVALID_HANDLE_VALUE
== s
->post_body
) {
1260 s
->post_body
= NULL
;
1261 giterr_set(GITERR_OS
, "Failed to create temporary file");
1266 if (!WriteFile(s
->post_body
, buffer
, (DWORD
)len
, &bytes_written
, NULL
)) {
1267 giterr_set(GITERR_OS
, "Failed to write to temporary file");
1271 assert((DWORD
)len
== bytes_written
);
1273 s
->post_body_len
+= bytes_written
;
1278 static int winhttp_stream_write_chunked(
1279 git_smart_subtransport_stream
*stream
,
1283 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1286 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1289 if (!s
->sent_request
) {
1290 /* Send Transfer-Encoding: chunked header */
1291 if (!WinHttpAddRequestHeaders(s
->request
,
1292 transfer_encoding
, (ULONG
) -1L,
1293 WINHTTP_ADDREQ_FLAG_ADD
)) {
1294 giterr_set(GITERR_OS
, "Failed to add a header to the request");
1298 if ((error
= send_request(s
, 0, 1)) < 0)
1301 s
->sent_request
= 1;
1304 if (len
> CACHED_POST_BODY_BUF_SIZE
) {
1305 /* Flush, if necessary */
1306 if (s
->chunk_buffer_len
> 0) {
1307 if (write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
1310 s
->chunk_buffer_len
= 0;
1313 /* Write chunk directly */
1314 if (write_chunk(s
->request
, buffer
, len
) < 0)
1318 /* Append as much to the buffer as we can */
1319 int count
= (int)min(CACHED_POST_BODY_BUF_SIZE
- s
->chunk_buffer_len
, len
);
1321 if (!s
->chunk_buffer
)
1322 s
->chunk_buffer
= git__malloc(CACHED_POST_BODY_BUF_SIZE
);
1324 memcpy(s
->chunk_buffer
+ s
->chunk_buffer_len
, buffer
, count
);
1325 s
->chunk_buffer_len
+= count
;
1329 /* Is the buffer full? If so, then flush */
1330 if (CACHED_POST_BODY_BUF_SIZE
== s
->chunk_buffer_len
) {
1331 if (write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
1334 s
->chunk_buffer_len
= 0;
1336 /* Is there any remaining data from the source? */
1338 memcpy(s
->chunk_buffer
, buffer
, len
);
1339 s
->chunk_buffer_len
= (unsigned int)len
;
1347 static void winhttp_stream_free(git_smart_subtransport_stream
*stream
)
1349 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1351 winhttp_stream_close(s
);
1355 static int winhttp_stream_alloc(winhttp_subtransport
*t
, winhttp_stream
**stream
)
1362 s
= git__calloc(1, sizeof(winhttp_stream
));
1363 GITERR_CHECK_ALLOC(s
);
1365 s
->parent
.subtransport
= &t
->parent
;
1366 s
->parent
.read
= winhttp_stream_read
;
1367 s
->parent
.write
= winhttp_stream_write_single
;
1368 s
->parent
.free
= winhttp_stream_free
;
1375 static int winhttp_uploadpack_ls(
1376 winhttp_subtransport
*t
,
1381 s
->service
= upload_pack_service
;
1382 s
->service_url
= upload_pack_ls_service_url
;
1388 static int winhttp_uploadpack(
1389 winhttp_subtransport
*t
,
1394 s
->service
= upload_pack_service
;
1395 s
->service_url
= upload_pack_service_url
;
1396 s
->verb
= post_verb
;
1401 static int winhttp_receivepack_ls(
1402 winhttp_subtransport
*t
,
1407 s
->service
= receive_pack_service
;
1408 s
->service_url
= receive_pack_ls_service_url
;
1414 static int winhttp_receivepack(
1415 winhttp_subtransport
*t
,
1420 /* WinHTTP only supports Transfer-Encoding: chunked
1421 * on Windows Vista (NT 6.0) and higher. */
1422 s
->chunked
= git_has_win32_version(6, 0, 0);
1425 s
->parent
.write
= winhttp_stream_write_chunked
;
1427 s
->parent
.write
= winhttp_stream_write_buffered
;
1429 s
->service
= receive_pack_service
;
1430 s
->service_url
= receive_pack_service_url
;
1431 s
->verb
= post_verb
;
1436 static int winhttp_action(
1437 git_smart_subtransport_stream
**stream
,
1438 git_smart_subtransport
*subtransport
,
1440 git_smart_service_t action
)
1442 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1447 if ((ret
= gitno_connection_data_from_url(&t
->connection_data
, url
, NULL
)) < 0 ||
1448 (ret
= winhttp_connect(t
)) < 0)
1451 if (winhttp_stream_alloc(t
, &s
) < 0)
1459 case GIT_SERVICE_UPLOADPACK_LS
:
1460 ret
= winhttp_uploadpack_ls(t
, s
);
1463 case GIT_SERVICE_UPLOADPACK
:
1464 ret
= winhttp_uploadpack(t
, s
);
1467 case GIT_SERVICE_RECEIVEPACK_LS
:
1468 ret
= winhttp_receivepack_ls(t
, s
);
1471 case GIT_SERVICE_RECEIVEPACK
:
1472 ret
= winhttp_receivepack(t
, s
);
1480 *stream
= &s
->parent
;
1485 static int winhttp_close(git_smart_subtransport
*subtransport
)
1487 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1489 gitno_connection_data_free_ptrs(&t
->connection_data
);
1490 memset(&t
->connection_data
, 0x0, sizeof(gitno_connection_data
));
1491 gitno_connection_data_free_ptrs(&t
->proxy_connection_data
);
1492 memset(&t
->proxy_connection_data
, 0x0, sizeof(gitno_connection_data
));
1495 t
->cred
->free(t
->cred
);
1499 if (t
->proxy_cred
) {
1500 t
->proxy_cred
->free(t
->proxy_cred
);
1501 t
->proxy_cred
= NULL
;
1505 t
->url_cred
->free(t
->url_cred
);
1509 return winhttp_close_connection(t
);
1512 static void winhttp_free(git_smart_subtransport
*subtransport
)
1514 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1516 winhttp_close(subtransport
);
1521 int git_smart_subtransport_http(git_smart_subtransport
**out
, git_transport
*owner
, void *param
)
1523 winhttp_subtransport
*t
;
1530 t
= git__calloc(1, sizeof(winhttp_subtransport
));
1531 GITERR_CHECK_ALLOC(t
);
1533 t
->owner
= (transport_smart
*)owner
;
1534 t
->parent
.action
= winhttp_action
;
1535 t
->parent
.close
= winhttp_close
;
1536 t
->parent
.free
= winhttp_free
;
1538 *out
= (git_smart_subtransport
*) t
;
1542 #endif /* GIT_WINHTTP */