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 if ((error
= gitno_extract_url_parts(&t
->proxy_connection_data
.host
, &t
->proxy_connection_data
.port
, NULL
,
404 &t
->proxy_connection_data
.user
, &t
->proxy_connection_data
.pass
, proxy_url
, NULL
)) < 0)
407 if (t
->proxy_connection_data
.user
&& t
->proxy_connection_data
.pass
) {
408 if ((error
= git_cred_userpass_plaintext_new(&t
->proxy_cred
, t
->proxy_connection_data
.user
, t
->proxy_connection_data
.pass
)) < 0)
412 if (t
->proxy_connection_data
.use_ssl
)
413 git_buf_PUTS(&processed_url
, SCHEME_HTTPS
);
415 git_buf_PUTS(&processed_url
, SCHEME_HTTP
);
417 git_buf_puts(&processed_url
, t
->proxy_connection_data
.host
);
418 if (t
->proxy_connection_data
.port
)
419 git_buf_printf(&processed_url
, ":%s", t
->proxy_connection_data
.port
);
421 if (git_buf_oom(&processed_url
)) {
427 /* Convert URL to wide characters */
428 if ((error
= git__utf8_to_16_alloc(&proxy_wide
, processed_url
.ptr
)) < 0)
432 proxy_info
.dwAccessType
= WINHTTP_ACCESS_TYPE_NAMED_PROXY
;
433 proxy_info
.lpszProxy
= proxy_wide
;
434 proxy_info
.lpszProxyBypass
= NULL
;
436 if (!WinHttpSetOption(s
->request
,
437 WINHTTP_OPTION_PROXY
,
439 sizeof(WINHTTP_PROXY_INFO
))) {
440 giterr_set(GITERR_OS
, "Failed to set proxy");
441 git__free(proxy_wide
);
445 git__free(proxy_wide
);
448 if (t
->proxy_cred
->credtype
== GIT_CREDTYPE_USERPASS_PLAINTEXT
) {
449 if ((error
= apply_basic_credential_proxy(s
->request
, t
->proxy_cred
)) < 0)
456 /* Disable WinHTTP redirects so we can handle them manually. Why, you ask?
457 * http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b2ff8879-ab9f-4218-8f09-16d25dff87ae
459 if (!WinHttpSetOption(s
->request
,
460 WINHTTP_OPTION_DISABLE_FEATURE
,
462 sizeof(disable_redirects
))) {
463 giterr_set(GITERR_OS
, "Failed to disable redirects");
467 /* Strip unwanted headers (X-P2P-PeerDist, X-P2P-PeerDistEx) that WinHTTP
468 * adds itself. This option may not be supported by the underlying
469 * platform, so we do not error-check it */
470 WinHttpSetOption(s
->request
,
471 WINHTTP_OPTION_PEERDIST_EXTENSION_STATE
,
475 /* Send Pragma: no-cache header */
476 if (!WinHttpAddRequestHeaders(s
->request
, pragma_nocache
, (ULONG
) -1L, WINHTTP_ADDREQ_FLAG_ADD
)) {
477 giterr_set(GITERR_OS
, "Failed to add a header to the request");
481 if (post_verb
== s
->verb
) {
482 /* Send Content-Type and Accept headers -- only necessary on a POST */
484 if (git_buf_printf(&buf
,
485 "Content-Type: application/x-git-%s-request",
489 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
490 giterr_set(GITERR_OS
, "Failed to convert content-type to wide characters");
494 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
495 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
496 giterr_set(GITERR_OS
, "Failed to add a header to the request");
501 if (git_buf_printf(&buf
,
502 "Accept: application/x-git-%s-result",
506 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
507 giterr_set(GITERR_OS
, "Failed to convert accept header to wide characters");
511 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
512 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
513 giterr_set(GITERR_OS
, "Failed to add a header to the request");
518 for (i
= 0; i
< t
->owner
->custom_headers
.count
; i
++) {
519 if (t
->owner
->custom_headers
.strings
[i
]) {
521 git_buf_puts(&buf
, t
->owner
->custom_headers
.strings
[i
]);
522 if (git__utf8_to_16(ct
, MAX_CONTENT_TYPE_LEN
, git_buf_cstr(&buf
)) < 0) {
523 giterr_set(GITERR_OS
, "Failed to convert custom header to wide characters");
527 if (!WinHttpAddRequestHeaders(s
->request
, ct
, (ULONG
)-1L,
528 WINHTTP_ADDREQ_FLAG_ADD
| WINHTTP_ADDREQ_FLAG_REPLACE
)) {
529 giterr_set(GITERR_OS
, "Failed to add a header to the request");
535 /* If requested, disable certificate validation */
536 if (t
->connection_data
.use_ssl
) {
539 if (t
->owner
->parent
.read_flags(&t
->owner
->parent
, &flags
) < 0)
543 /* If we have a credential on the subtransport, apply it to the request */
545 t
->cred
->credtype
== GIT_CREDTYPE_USERPASS_PLAINTEXT
&&
546 t
->auth_mechanism
== GIT_WINHTTP_AUTH_BASIC
&&
547 apply_basic_credential(s
->request
, t
->cred
) < 0)
550 t
->cred
->credtype
== GIT_CREDTYPE_DEFAULT
&&
551 t
->auth_mechanism
== GIT_WINHTTP_AUTH_NEGOTIATE
&&
552 apply_default_credentials(s
->request
) < 0)
555 /* If no other credentials have been applied and the URL has username and
556 * password, use those */
557 if (!t
->cred
&& t
->connection_data
.user
&& t
->connection_data
.pass
) {
559 git_cred_userpass_plaintext_new(&t
->url_cred
, t
->connection_data
.user
, t
->connection_data
.pass
) < 0)
561 if (apply_basic_credential(s
->request
, t
->url_cred
) < 0)
565 /* We've done everything up to calling WinHttpSendRequest. */
571 winhttp_stream_close(s
);
573 git__free(proxy_url
);
578 static int parse_unauthorized_response(
583 DWORD supported
, first
, target
;
588 /* WinHttpQueryHeaders() must be called before WinHttpQueryAuthSchemes().
589 * We can assume this was already done, since we know we are unauthorized.
591 if (!WinHttpQueryAuthSchemes(request
, &supported
, &first
, &target
)) {
592 giterr_set(GITERR_OS
, "Failed to parse supported auth schemes");
596 if (WINHTTP_AUTH_SCHEME_BASIC
& supported
) {
597 *allowed_types
|= GIT_CREDTYPE_USERPASS_PLAINTEXT
;
598 *auth_mechanism
= GIT_WINHTTP_AUTH_BASIC
;
601 if ((WINHTTP_AUTH_SCHEME_NTLM
& supported
) ||
602 (WINHTTP_AUTH_SCHEME_NEGOTIATE
& supported
)) {
603 *allowed_types
|= GIT_CREDTYPE_DEFAULT
;
604 *auth_mechanism
= GIT_WINHTTP_AUTH_NEGOTIATE
;
610 static int write_chunk(HINTERNET request
, const char *buffer
, size_t len
)
613 git_buf buf
= GIT_BUF_INIT
;
616 git_buf_printf(&buf
, "%X\r\n", len
);
618 if (git_buf_oom(&buf
))
621 if (!WinHttpWriteData(request
,
622 git_buf_cstr(&buf
), (DWORD
)git_buf_len(&buf
),
625 giterr_set(GITERR_OS
, "Failed to write chunk header");
632 if (!WinHttpWriteData(request
,
635 giterr_set(GITERR_OS
, "Failed to write chunk");
640 if (!WinHttpWriteData(request
,
643 giterr_set(GITERR_OS
, "Failed to write chunk footer");
650 static int winhttp_close_connection(winhttp_subtransport
*t
)
655 if (!WinHttpCloseHandle(t
->connection
)) {
656 giterr_set(GITERR_OS
, "Unable to close connection");
660 t
->connection
= NULL
;
664 if (!WinHttpCloseHandle(t
->session
)) {
665 giterr_set(GITERR_OS
, "Unable to close session");
675 static int user_agent(git_buf
*ua
)
677 const char *custom
= git_libgit2__user_agent();
680 git_buf_PUTS(ua
, "git/1.0 (");
683 git_buf_puts(ua
, custom
);
685 git_buf_PUTS(ua
, "libgit2 " LIBGIT2_VERSION
);
687 return git_buf_putc(ua
, ')');
690 static int winhttp_connect(
691 winhttp_subtransport
*t
)
696 git_buf ua
= GIT_BUF_INIT
;
698 int default_timeout
= TIMEOUT_INFINITE
;
699 int default_connect_timeout
= DEFAULT_CONNECT_TIMEOUT
;
702 t
->connection
= NULL
;
705 if (git__strtol32(&port
, t
->connection_data
.port
, NULL
, 10) < 0)
709 if (git__utf8_to_16_alloc(&wide_host
, t
->connection_data
.host
) < 0) {
710 giterr_set(GITERR_OS
, "Unable to convert host to wide characters");
714 if ((error
= user_agent(&ua
)) < 0) {
715 git__free(wide_host
);
719 if (git__utf8_to_16_alloc(&wide_ua
, git_buf_cstr(&ua
)) < 0) {
720 giterr_set(GITERR_OS
, "Unable to convert host to wide characters");
721 git__free(wide_host
);
728 /* Establish session */
729 t
->session
= WinHttpOpen(
731 WINHTTP_ACCESS_TYPE_DEFAULT_PROXY
,
732 WINHTTP_NO_PROXY_NAME
,
733 WINHTTP_NO_PROXY_BYPASS
,
737 giterr_set(GITERR_OS
, "Failed to init WinHTTP");
741 if (!WinHttpSetTimeouts(t
->session
, default_timeout
, default_connect_timeout
, default_timeout
, default_timeout
)) {
742 giterr_set(GITERR_OS
, "Failed to set timeouts for WinHTTP");
747 /* Establish connection */
748 t
->connection
= WinHttpConnect(
751 (INTERNET_PORT
) port
,
754 if (!t
->connection
) {
755 giterr_set(GITERR_OS
, "Failed to connect to host");
763 winhttp_close_connection(t
);
765 git__free(wide_host
);
771 static int do_send_request(winhttp_stream
*s
, size_t len
, int ignore_length
)
774 if (!WinHttpSendRequest(s
->request
,
775 WINHTTP_NO_ADDITIONAL_HEADERS
, 0,
776 WINHTTP_NO_REQUEST_DATA
, 0,
777 WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH
, 0)) {
781 if (!WinHttpSendRequest(s
->request
,
782 WINHTTP_NO_ADDITIONAL_HEADERS
, 0,
783 WINHTTP_NO_REQUEST_DATA
, 0,
792 static int send_request(winhttp_stream
*s
, size_t len
, int ignore_length
)
794 int request_failed
= 0, cert_valid
= 1, error
= 0;
797 if ((error
= do_send_request(s
, len
, ignore_length
)) < 0)
800 if (request_failed
) {
801 if (GetLastError() != ERROR_WINHTTP_SECURE_FAILURE
) {
802 giterr_set(GITERR_OS
, "failed to send request");
810 if ((error
= certificate_check(s
, cert_valid
)) < 0) {
812 giterr_set(GITERR_OS
, "user cancelled certificate check");
817 /* if neither the request nor the certificate check returned errors, we're done */
821 ignore_flags
= no_check_cert_flags
;
823 if (!WinHttpSetOption(s
->request
, WINHTTP_OPTION_SECURITY_FLAGS
, &ignore_flags
, sizeof(ignore_flags
))) {
824 giterr_set(GITERR_OS
, "failed to set security options");
828 if ((error
= do_send_request(s
, len
, ignore_length
)) < 0)
829 giterr_set(GITERR_OS
, "failed to send request");
834 static int winhttp_stream_read(
835 git_smart_subtransport_stream
*stream
,
840 winhttp_stream
*s
= (winhttp_stream
*)stream
;
841 winhttp_subtransport
*t
= OWNING_SUBTRANSPORT(s
);
843 char replay_count
= 0;
847 /* Enforce a reasonable cap on the number of replays */
848 if (++replay_count
>= 7) {
849 giterr_set(GITERR_NET
, "Too many redirects or authentication replays");
853 /* Connect if necessary */
854 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
857 if (!s
->received_response
) {
858 DWORD status_code
, status_code_length
, content_type_length
, bytes_written
;
859 char expected_content_type_8
[MAX_CONTENT_TYPE_LEN
];
860 wchar_t expected_content_type
[MAX_CONTENT_TYPE_LEN
], content_type
[MAX_CONTENT_TYPE_LEN
];
862 if (!s
->sent_request
) {
864 if ((error
= send_request(s
, s
->post_body_len
, 0)) < 0)
871 assert(s
->verb
== post_verb
);
873 /* Flush, if necessary */
874 if (s
->chunk_buffer_len
> 0 &&
875 write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
878 s
->chunk_buffer_len
= 0;
880 /* Write the final chunk. */
881 if (!WinHttpWriteData(s
->request
,
884 giterr_set(GITERR_OS
, "Failed to write final chunk");
888 else if (s
->post_body
) {
890 DWORD len
= s
->post_body_len
, bytes_read
;
892 if (INVALID_SET_FILE_POINTER
== SetFilePointer(s
->post_body
,
894 NO_ERROR
!= GetLastError()) {
895 giterr_set(GITERR_OS
, "Failed to reset file pointer");
899 buffer
= git__malloc(CACHED_POST_BODY_BUF_SIZE
);
904 if (!ReadFile(s
->post_body
, buffer
,
905 min(CACHED_POST_BODY_BUF_SIZE
, len
),
906 &bytes_read
, NULL
) ||
909 giterr_set(GITERR_OS
, "Failed to read from temp file");
913 if (!WinHttpWriteData(s
->request
, buffer
,
914 bytes_read
, &bytes_written
)) {
916 giterr_set(GITERR_OS
, "Failed to write data");
921 assert(bytes_read
== bytes_written
);
926 /* Eagerly close the temp file */
927 CloseHandle(s
->post_body
);
931 if (!WinHttpReceiveResponse(s
->request
, 0)) {
932 giterr_set(GITERR_OS
, "Failed to receive response");
936 /* Verify that we got a 200 back */
937 status_code_length
= sizeof(status_code
);
939 if (!WinHttpQueryHeaders(s
->request
,
940 WINHTTP_QUERY_STATUS_CODE
| WINHTTP_QUERY_FLAG_NUMBER
,
941 WINHTTP_HEADER_NAME_BY_INDEX
,
942 &status_code
, &status_code_length
,
943 WINHTTP_NO_HEADER_INDEX
)) {
944 giterr_set(GITERR_OS
, "Failed to retrieve status code");
948 /* The implementation of WinHTTP prior to Windows 7 will not
949 * redirect to an identical URI. Some Git hosters use self-redirects
950 * as part of their DoS mitigation strategy. Check first to see if we
951 * have a redirect status code, and that we haven't already streamed
952 * a post body. (We can't replay a streamed POST.) */
954 (HTTP_STATUS_MOVED
== status_code
||
955 HTTP_STATUS_REDIRECT
== status_code
||
956 (HTTP_STATUS_REDIRECT_METHOD
== status_code
&&
957 get_verb
== s
->verb
) ||
958 HTTP_STATUS_REDIRECT_KEEP_VERB
== status_code
)) {
960 /* Check for Windows 7. This workaround is only necessary on
961 * Windows Vista and earlier. Windows 7 is version 6.1. */
963 DWORD location_length
;
966 /* OK, fetch the Location header from the redirect. */
967 if (WinHttpQueryHeaders(s
->request
,
968 WINHTTP_QUERY_LOCATION
,
969 WINHTTP_HEADER_NAME_BY_INDEX
,
970 WINHTTP_NO_OUTPUT_BUFFER
,
972 WINHTTP_NO_HEADER_INDEX
) ||
973 GetLastError() != ERROR_INSUFFICIENT_BUFFER
) {
974 giterr_set(GITERR_OS
, "Failed to read Location header");
978 location
= git__malloc(location_length
);
979 GITERR_CHECK_ALLOC(location
);
981 if (!WinHttpQueryHeaders(s
->request
,
982 WINHTTP_QUERY_LOCATION
,
983 WINHTTP_HEADER_NAME_BY_INDEX
,
986 WINHTTP_NO_HEADER_INDEX
)) {
987 giterr_set(GITERR_OS
, "Failed to read Location header");
992 /* Convert the Location header to UTF-8 */
993 if (git__utf16_to_8_alloc(&location8
, location
) < 0) {
994 giterr_set(GITERR_OS
, "Failed to convert Location header to UTF-8");
1001 /* Replay the request */
1002 winhttp_stream_close(s
);
1004 if (!git__prefixcmp_icase(location8
, prefix_https
)) {
1005 /* Upgrade to secure connection; disconnect and start over */
1006 if (gitno_connection_data_from_url(&t
->connection_data
, location8
, s
->service_url
) < 0) {
1007 git__free(location8
);
1011 winhttp_close_connection(t
);
1013 if (winhttp_connect(t
) < 0)
1017 git__free(location8
);
1021 /* Handle proxy authentication failures */
1022 if (status_code
== HTTP_STATUS_PROXY_AUTH_REQ
) {
1025 if (parse_unauthorized_response(s
->request
, &allowed_types
, &t
->auth_mechanism
) < 0)
1028 /* TODO: extract the username from the url, no payload? */
1029 if (t
->owner
->proxy
.credentials
) {
1031 cred_error
= t
->owner
->proxy
.credentials(&t
->proxy_cred
, t
->owner
->proxy
.url
, NULL
, allowed_types
, NULL
);
1037 winhttp_stream_close(s
);
1041 /* Handle authentication failures */
1042 if (HTTP_STATUS_DENIED
== status_code
&& get_verb
== s
->verb
) {
1045 if (parse_unauthorized_response(s
->request
, &allowed_types
, &t
->auth_mechanism
) < 0)
1048 if (allowed_types
) {
1051 git_cred_free(t
->cred
);
1053 /* Start with the user-supplied credential callback, if present */
1054 if (t
->owner
->cred_acquire_cb
) {
1055 cred_error
= t
->owner
->cred_acquire_cb(&t
->cred
, t
->owner
->url
,
1056 t
->connection_data
.user
, allowed_types
, t
->owner
->cred_acquire_payload
);
1058 /* Treat GIT_PASSTHROUGH as though git_cred_acquire_cb isn't set */
1059 if (cred_error
== GIT_PASSTHROUGH
)
1061 else if (cred_error
< 0)
1065 /* Invoke the fallback credentials acquisition callback if necessary */
1066 if (cred_error
> 0) {
1067 cred_error
= fallback_cred_acquire_cb(&t
->cred
, t
->owner
->url
,
1068 t
->connection_data
.user
, allowed_types
, NULL
);
1077 winhttp_stream_close(s
);
1079 /* Successfully acquired a credential */
1085 if (HTTP_STATUS_OK
!= status_code
) {
1086 giterr_set(GITERR_NET
, "Request failed with status code: %d", status_code
);
1090 /* Verify that we got the correct content-type back */
1091 if (post_verb
== s
->verb
)
1092 p_snprintf(expected_content_type_8
, MAX_CONTENT_TYPE_LEN
, "application/x-git-%s-result", s
->service
);
1094 p_snprintf(expected_content_type_8
, MAX_CONTENT_TYPE_LEN
, "application/x-git-%s-advertisement", s
->service
);
1096 if (git__utf8_to_16(expected_content_type
, MAX_CONTENT_TYPE_LEN
, expected_content_type_8
) < 0) {
1097 giterr_set(GITERR_OS
, "Failed to convert expected content-type to wide characters");
1101 content_type_length
= sizeof(content_type
);
1103 if (!WinHttpQueryHeaders(s
->request
,
1104 WINHTTP_QUERY_CONTENT_TYPE
,
1105 WINHTTP_HEADER_NAME_BY_INDEX
,
1106 &content_type
, &content_type_length
,
1107 WINHTTP_NO_HEADER_INDEX
)) {
1108 giterr_set(GITERR_OS
, "Failed to retrieve response content-type");
1112 if (wcscmp(expected_content_type
, content_type
)) {
1113 giterr_set(GITERR_NET
, "Received unexpected content-type");
1117 s
->received_response
= 1;
1120 if (!WinHttpReadData(s
->request
,
1125 giterr_set(GITERR_OS
, "Failed to read data");
1129 *bytes_read
= dw_bytes_read
;
1134 static int winhttp_stream_write_single(
1135 git_smart_subtransport_stream
*stream
,
1139 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1140 DWORD bytes_written
;
1143 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1146 /* This implementation of write permits only a single call. */
1147 if (s
->sent_request
) {
1148 giterr_set(GITERR_NET
, "Subtransport configured for only one write");
1152 if ((error
= send_request(s
, len
, 0)) < 0)
1155 s
->sent_request
= 1;
1157 if (!WinHttpWriteData(s
->request
,
1161 giterr_set(GITERR_OS
, "Failed to write data");
1165 assert((DWORD
)len
== bytes_written
);
1170 static int put_uuid_string(LPWSTR buffer
, size_t buffer_len_cch
)
1173 RPC_STATUS status
= UuidCreate(&uuid
);
1176 if (RPC_S_OK
!= status
&&
1177 RPC_S_UUID_LOCAL_ONLY
!= status
&&
1178 RPC_S_UUID_NO_ADDRESS
!= status
) {
1179 giterr_set(GITERR_NET
, "Unable to generate name for temp file");
1183 if (buffer_len_cch
< UUID_LENGTH_CCH
+ 1) {
1184 giterr_set(GITERR_NET
, "Buffer too small for name of temp file");
1188 #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
1189 result
= swprintf_s(buffer
, buffer_len_cch
,
1191 result
= wsprintfW(buffer
,
1193 L
"%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x",
1194 uuid
.Data1
, uuid
.Data2
, uuid
.Data3
,
1195 uuid
.Data4
[0], uuid
.Data4
[1], uuid
.Data4
[2], uuid
.Data4
[3],
1196 uuid
.Data4
[4], uuid
.Data4
[5], uuid
.Data4
[6], uuid
.Data4
[7]);
1198 if (result
< UUID_LENGTH_CCH
) {
1199 giterr_set(GITERR_OS
, "Unable to generate name for temp file");
1206 static int get_temp_file(LPWSTR buffer
, DWORD buffer_len_cch
)
1210 if (!GetTempPathW(buffer_len_cch
, buffer
)) {
1211 giterr_set(GITERR_OS
, "Failed to get temp path");
1215 len
= wcslen(buffer
);
1217 if (buffer
[len
- 1] != '\\' && len
< buffer_len_cch
)
1218 buffer
[len
++] = '\\';
1220 if (put_uuid_string(&buffer
[len
], (size_t)buffer_len_cch
- len
) < 0)
1226 static int winhttp_stream_write_buffered(
1227 git_smart_subtransport_stream
*stream
,
1231 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1232 DWORD bytes_written
;
1234 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1237 /* Buffer the payload, using a temporary file so we delegate
1238 * memory management of the data to the operating system. */
1239 if (!s
->post_body
) {
1240 wchar_t temp_path
[MAX_PATH
+ 1];
1242 if (get_temp_file(temp_path
, MAX_PATH
+ 1) < 0)
1245 s
->post_body
= CreateFileW(temp_path
,
1246 GENERIC_READ
| GENERIC_WRITE
,
1247 FILE_SHARE_DELETE
, NULL
,
1249 FILE_ATTRIBUTE_TEMPORARY
| FILE_FLAG_DELETE_ON_CLOSE
| FILE_FLAG_SEQUENTIAL_SCAN
,
1252 if (INVALID_HANDLE_VALUE
== s
->post_body
) {
1253 s
->post_body
= NULL
;
1254 giterr_set(GITERR_OS
, "Failed to create temporary file");
1259 if (!WriteFile(s
->post_body
, buffer
, (DWORD
)len
, &bytes_written
, NULL
)) {
1260 giterr_set(GITERR_OS
, "Failed to write to temporary file");
1264 assert((DWORD
)len
== bytes_written
);
1266 s
->post_body_len
+= bytes_written
;
1271 static int winhttp_stream_write_chunked(
1272 git_smart_subtransport_stream
*stream
,
1276 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1279 if (!s
->request
&& winhttp_stream_connect(s
) < 0)
1282 if (!s
->sent_request
) {
1283 /* Send Transfer-Encoding: chunked header */
1284 if (!WinHttpAddRequestHeaders(s
->request
,
1285 transfer_encoding
, (ULONG
) -1L,
1286 WINHTTP_ADDREQ_FLAG_ADD
)) {
1287 giterr_set(GITERR_OS
, "Failed to add a header to the request");
1291 if ((error
= send_request(s
, 0, 1)) < 0)
1294 s
->sent_request
= 1;
1297 if (len
> CACHED_POST_BODY_BUF_SIZE
) {
1298 /* Flush, if necessary */
1299 if (s
->chunk_buffer_len
> 0) {
1300 if (write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
1303 s
->chunk_buffer_len
= 0;
1306 /* Write chunk directly */
1307 if (write_chunk(s
->request
, buffer
, len
) < 0)
1311 /* Append as much to the buffer as we can */
1312 int count
= (int)min(CACHED_POST_BODY_BUF_SIZE
- s
->chunk_buffer_len
, len
);
1314 if (!s
->chunk_buffer
)
1315 s
->chunk_buffer
= git__malloc(CACHED_POST_BODY_BUF_SIZE
);
1317 memcpy(s
->chunk_buffer
+ s
->chunk_buffer_len
, buffer
, count
);
1318 s
->chunk_buffer_len
+= count
;
1322 /* Is the buffer full? If so, then flush */
1323 if (CACHED_POST_BODY_BUF_SIZE
== s
->chunk_buffer_len
) {
1324 if (write_chunk(s
->request
, s
->chunk_buffer
, s
->chunk_buffer_len
) < 0)
1327 s
->chunk_buffer_len
= 0;
1329 /* Is there any remaining data from the source? */
1331 memcpy(s
->chunk_buffer
, buffer
, len
);
1332 s
->chunk_buffer_len
= (unsigned int)len
;
1340 static void winhttp_stream_free(git_smart_subtransport_stream
*stream
)
1342 winhttp_stream
*s
= (winhttp_stream
*)stream
;
1344 winhttp_stream_close(s
);
1348 static int winhttp_stream_alloc(winhttp_subtransport
*t
, winhttp_stream
**stream
)
1355 s
= git__calloc(1, sizeof(winhttp_stream
));
1356 GITERR_CHECK_ALLOC(s
);
1358 s
->parent
.subtransport
= &t
->parent
;
1359 s
->parent
.read
= winhttp_stream_read
;
1360 s
->parent
.write
= winhttp_stream_write_single
;
1361 s
->parent
.free
= winhttp_stream_free
;
1368 static int winhttp_uploadpack_ls(
1369 winhttp_subtransport
*t
,
1374 s
->service
= upload_pack_service
;
1375 s
->service_url
= upload_pack_ls_service_url
;
1381 static int winhttp_uploadpack(
1382 winhttp_subtransport
*t
,
1387 s
->service
= upload_pack_service
;
1388 s
->service_url
= upload_pack_service_url
;
1389 s
->verb
= post_verb
;
1394 static int winhttp_receivepack_ls(
1395 winhttp_subtransport
*t
,
1400 s
->service
= receive_pack_service
;
1401 s
->service_url
= receive_pack_ls_service_url
;
1407 static int winhttp_receivepack(
1408 winhttp_subtransport
*t
,
1413 /* WinHTTP only supports Transfer-Encoding: chunked
1414 * on Windows Vista (NT 6.0) and higher. */
1415 s
->chunked
= git_has_win32_version(6, 0, 0);
1418 s
->parent
.write
= winhttp_stream_write_chunked
;
1420 s
->parent
.write
= winhttp_stream_write_buffered
;
1422 s
->service
= receive_pack_service
;
1423 s
->service_url
= receive_pack_service_url
;
1424 s
->verb
= post_verb
;
1429 static int winhttp_action(
1430 git_smart_subtransport_stream
**stream
,
1431 git_smart_subtransport
*subtransport
,
1433 git_smart_service_t action
)
1435 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1440 if ((ret
= gitno_connection_data_from_url(&t
->connection_data
, url
, NULL
)) < 0 ||
1441 (ret
= winhttp_connect(t
)) < 0)
1444 if (winhttp_stream_alloc(t
, &s
) < 0)
1452 case GIT_SERVICE_UPLOADPACK_LS
:
1453 ret
= winhttp_uploadpack_ls(t
, s
);
1456 case GIT_SERVICE_UPLOADPACK
:
1457 ret
= winhttp_uploadpack(t
, s
);
1460 case GIT_SERVICE_RECEIVEPACK_LS
:
1461 ret
= winhttp_receivepack_ls(t
, s
);
1464 case GIT_SERVICE_RECEIVEPACK
:
1465 ret
= winhttp_receivepack(t
, s
);
1473 *stream
= &s
->parent
;
1478 static int winhttp_close(git_smart_subtransport
*subtransport
)
1480 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1482 gitno_connection_data_free_ptrs(&t
->connection_data
);
1483 memset(&t
->connection_data
, 0x0, sizeof(gitno_connection_data
));
1486 t
->cred
->free(t
->cred
);
1491 t
->url_cred
->free(t
->url_cred
);
1495 return winhttp_close_connection(t
);
1498 static void winhttp_free(git_smart_subtransport
*subtransport
)
1500 winhttp_subtransport
*t
= (winhttp_subtransport
*)subtransport
;
1502 winhttp_close(subtransport
);
1507 int git_smart_subtransport_http(git_smart_subtransport
**out
, git_transport
*owner
, void *param
)
1509 winhttp_subtransport
*t
;
1516 t
= git__calloc(1, sizeof(winhttp_subtransport
));
1517 GITERR_CHECK_ALLOC(t
);
1519 t
->owner
= (transport_smart
*)owner
;
1520 t
->parent
.action
= winhttp_action
;
1521 t
->parent
.close
= winhttp_close
;
1522 t
->parent
.free
= winhttp_free
;
1524 *out
= (git_smart_subtransport
*) t
;
1528 #endif /* GIT_WINHTTP */