]> git.proxmox.com Git - libgit2.git/blob - src/transports/winhttp.c
proxy: don't specify the protocol in the type
[libgit2.git] / src / transports / winhttp.c
1 /*
2 * Copyright (C) the libgit2 contributors. All rights reserved.
3 *
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.
6 */
7
8 #ifdef GIT_WINHTTP
9
10 #include "git2.h"
11 #include "git2/transport.h"
12 #include "buffer.h"
13 #include "posix.h"
14 #include "netops.h"
15 #include "smart.h"
16 #include "remote.h"
17 #include "repository.h"
18 #include "global.h"
19
20 #include <wincrypt.h>
21 #include <winhttp.h>
22
23 /* For IInternetSecurityManager zone check */
24 #include <objbase.h>
25 #include <urlmon.h>
26
27 #define WIDEN2(s) L ## s
28 #define WIDEN(s) WIDEN2(s)
29
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
38 #endif
39
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;
54
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 } };
62
63 # define CLSID_InternetSecurityManager CLSID_InternetSecurityManager_mingw
64 # define IID_IInternetSecurityManager IID_IInternetSecurityManager_mingw
65 #endif
66
67 #define OWNING_SUBTRANSPORT(s) ((winhttp_subtransport *)(s)->parent.subtransport)
68
69 typedef enum {
70 GIT_WINHTTP_AUTH_BASIC = 1,
71 GIT_WINHTTP_AUTH_NEGOTIATE = 2,
72 } winhttp_authmechanism_t;
73
74 typedef struct {
75 git_smart_subtransport_stream parent;
76 const char *service;
77 const char *service_url;
78 const wchar_t *verb;
79 HINTERNET request;
80 wchar_t *request_uri;
81 char *chunk_buffer;
82 unsigned chunk_buffer_len;
83 HANDLE post_body;
84 DWORD post_body_len;
85 unsigned sent_request : 1,
86 received_response : 1,
87 chunked : 1;
88 } winhttp_stream;
89
90 typedef struct {
91 git_smart_subtransport parent;
92 transport_smart *owner;
93 gitno_connection_data connection_data;
94 gitno_connection_data proxy_connection_data;
95 git_cred *cred;
96 git_cred *url_cred;
97 git_cred *proxy_cred;
98 int auth_mechanism;
99 HINTERNET session;
100 HINTERNET connection;
101 } winhttp_subtransport;
102
103 static int apply_basic_credential_proxy(HINTERNET request, git_cred *cred)
104 {
105 git_cred_userpass_plaintext *c = (git_cred_userpass_plaintext *)cred;
106 wchar_t *user, *pass;
107 int error;
108
109 if ((error = git__utf8_to_16_alloc(&user, c->username)) < 0)
110 return error;
111
112 if ((error = git__utf8_to_16_alloc(&pass, c->password)) < 0)
113 return error;
114
115 if (!WinHttpSetCredentials(request, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC,
116 user, pass, NULL)) {
117 giterr_set(GITERR_OS, "failed to set proxy auth");
118 error = -1;
119 }
120
121 git__free(user);
122 git__free(pass);
123
124 return error;
125 }
126
127 static int apply_basic_credential(HINTERNET request, git_cred *cred)
128 {
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;
133
134 git_buf_printf(&raw, "%s:%s", c->username, c->password);
135
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)
139 goto on_error;
140
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");
143 goto on_error;
144 }
145
146 if (!WinHttpAddRequestHeaders(request, wide, (ULONG) -1L, WINHTTP_ADDREQ_FLAG_ADD)) {
147 giterr_set(GITERR_OS, "Failed to add a header to the request");
148 goto on_error;
149 }
150
151 error = 0;
152
153 on_error:
154 /* We were dealing with plaintext passwords, so clean up after ourselves a bit. */
155 if (wide)
156 memset(wide, 0x0, wide_len * sizeof(wchar_t));
157
158 if (buf.size)
159 memset(buf.ptr, 0x0, buf.size);
160
161 if (raw.size)
162 memset(raw.ptr, 0x0, raw.size);
163
164 git__free(wide);
165 git_buf_free(&buf);
166 git_buf_free(&raw);
167 return error;
168 }
169
170 static int apply_default_credentials(HINTERNET request)
171 {
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;
179
180 if (!WinHttpSetOption(request, WINHTTP_OPTION_AUTOLOGON_POLICY, &data, sizeof(DWORD)))
181 return -1;
182
183 return 0;
184 }
185
186 static int fallback_cred_acquire_cb(
187 git_cred **cred,
188 const char *url,
189 const char *username_from_url,
190 unsigned int allowed_types,
191 void *payload)
192 {
193 int error = 1;
194
195 GIT_UNUSED(username_from_url);
196 GIT_UNUSED(payload);
197
198 /* If the target URI supports integrated Windows authentication
199 * as an authentication mechanism */
200 if (GIT_CREDTYPE_DEFAULT & allowed_types) {
201 wchar_t *wide_url;
202
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");
206 return -1;
207 }
208
209 if (SUCCEEDED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) {
210 IInternetSecurityManager* pISM;
211
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))) {
215 DWORD dwZone;
216
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;
222
223 if (existing)
224 existing->free(existing);
225
226 /* Then use default Windows credentials to authenticate this request */
227 error = git_cred_default_new(cred);
228 }
229
230 pISM->lpVtbl->Release(pISM);
231 }
232
233 CoUninitialize();
234 }
235
236 git__free(wide_url);
237 }
238
239 return error;
240 }
241
242 static int certificate_check(winhttp_stream *s, int valid)
243 {
244 int error;
245 winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
246 PCERT_CONTEXT cert_ctx;
247 DWORD cert_ctx_size = sizeof(cert_ctx);
248 git_cert_x509 cert;
249
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;
253
254 if (t->owner->certificate_check_cb == NULL || !t->connection_data.use_ssl)
255 return 0;
256
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");
259 return -1;
260 }
261
262 giterr_clear();
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);
268
269 if (error < 0 && !giterr_last())
270 giterr_set(GITERR_NET, "user cancelled certificate check");
271
272 return error;
273 }
274
275 static void winhttp_stream_close(winhttp_stream *s)
276 {
277 if (s->chunk_buffer) {
278 git__free(s->chunk_buffer);
279 s->chunk_buffer = NULL;
280 }
281
282 if (s->post_body) {
283 CloseHandle(s->post_body);
284 s->post_body = NULL;
285 }
286
287 if (s->request_uri) {
288 git__free(s->request_uri);
289 s->request_uri = NULL;
290 }
291
292 if (s->request) {
293 WinHttpCloseHandle(s->request);
294 s->request = NULL;
295 }
296
297 s->sent_request = 0;
298 }
299
300 /**
301 * Extract the url and password from a URL. The outputs are pointers
302 * into the input.
303 */
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)
307 {
308 URL_COMPONENTS components = { 0 };
309
310 components.dwStructSize = sizeof(components);
311 /* These tell WinHttpCrackUrl that we're interested in the fields */
312 components.dwUserNameLength = 1;
313 components.dwPasswordLength = 1;
314
315 if (!WinHttpCrackUrl(url, url_len, 0, &components)) {
316 giterr_set(GITERR_OS, "failed to extract user/pass from url");
317 return -1;
318 }
319
320 *user = components.lpszUserName;
321 *user_len = components.dwUserNameLength;
322 *pass = components.lpszPassword;
323 *pass_len = components.dwPasswordLength;
324
325 return 0;
326 }
327
328 #define SCHEME_HTTP "http://"
329 #define SCHEME_HTTPS "https://"
330
331 static int winhttp_stream_connect(winhttp_stream *s)
332 {
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;
339 int error = -1;
340 unsigned long disable_redirects = WINHTTP_DISABLE_REDIRECTS;
341 int default_timeout = TIMEOUT_INFINITE;
342 int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
343 size_t i;
344 const git_proxy_options *proxy_opts;
345
346 /* Prepare URL */
347 git_buf_printf(&buf, "%s%s", t->connection_data.path, s->service_url);
348
349 if (git_buf_oom(&buf))
350 return -1;
351
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");
355 goto on_error;
356 }
357
358 /* Establish request */
359 s->request = WinHttpOpenRequest(
360 t->connection,
361 s->verb,
362 s->request_uri,
363 NULL,
364 WINHTTP_NO_REFERER,
365 types,
366 t->connection_data.use_ssl ? WINHTTP_FLAG_SECURE : 0);
367
368 if (!s->request) {
369 giterr_set(GITERR_OS, "Failed to open request");
370 goto on_error;
371 }
372
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");
375 goto on_error;
376 }
377
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)
382 goto on_error;
383 }
384 else if (proxy_opts->type == GIT_PROXY_SPECIFIED) {
385 proxy_url = git__strdup(proxy_opts->url);
386 GITERR_CHECK_ALLOC(proxy_url);
387 }
388
389 if (proxy_url) {
390 git_buf processed_url = GIT_BUF_INIT;
391 WINHTTP_PROXY_INFO proxy_info;
392 wchar_t *proxy_wide;
393
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;
398 } else {
399 giterr_set(GITERR_NET, "invalid URL: '%s'", proxy_url);
400 return -1;
401 }
402
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)
405 goto on_error;
406
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)
409 goto on_error;
410 }
411
412 if (t->proxy_connection_data.use_ssl)
413 git_buf_PUTS(&processed_url, SCHEME_HTTPS);
414 else
415 git_buf_PUTS(&processed_url, SCHEME_HTTP);
416
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);
420
421 if (git_buf_oom(&processed_url)) {
422 giterr_set_oom();
423 error = -1;
424 goto on_error;
425 }
426
427 /* Convert URL to wide characters */
428 if ((error = git__utf8_to_16_alloc(&proxy_wide, processed_url.ptr)) < 0)
429 goto on_error;
430
431
432 proxy_info.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
433 proxy_info.lpszProxy = proxy_wide;
434 proxy_info.lpszProxyBypass = NULL;
435
436 if (!WinHttpSetOption(s->request,
437 WINHTTP_OPTION_PROXY,
438 &proxy_info,
439 sizeof(WINHTTP_PROXY_INFO))) {
440 giterr_set(GITERR_OS, "Failed to set proxy");
441 git__free(proxy_wide);
442 goto on_error;
443 }
444
445 git__free(proxy_wide);
446
447 if (t->proxy_cred) {
448 if (t->proxy_cred->credtype == GIT_CREDTYPE_USERPASS_PLAINTEXT) {
449 if ((error = apply_basic_credential_proxy(s->request, t->proxy_cred)) < 0)
450 goto on_error;
451 }
452 }
453
454 }
455
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
458 */
459 if (!WinHttpSetOption(s->request,
460 WINHTTP_OPTION_DISABLE_FEATURE,
461 &disable_redirects,
462 sizeof(disable_redirects))) {
463 giterr_set(GITERR_OS, "Failed to disable redirects");
464 goto on_error;
465 }
466
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,
472 &peerdist,
473 sizeof(peerdist));
474
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");
478 goto on_error;
479 }
480
481 if (post_verb == s->verb) {
482 /* Send Content-Type and Accept headers -- only necessary on a POST */
483 git_buf_clear(&buf);
484 if (git_buf_printf(&buf,
485 "Content-Type: application/x-git-%s-request",
486 s->service) < 0)
487 goto on_error;
488
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");
491 goto on_error;
492 }
493
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");
497 goto on_error;
498 }
499
500 git_buf_clear(&buf);
501 if (git_buf_printf(&buf,
502 "Accept: application/x-git-%s-result",
503 s->service) < 0)
504 goto on_error;
505
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");
508 goto on_error;
509 }
510
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");
514 goto on_error;
515 }
516 }
517
518 for (i = 0; i < t->owner->custom_headers.count; i++) {
519 if (t->owner->custom_headers.strings[i]) {
520 git_buf_clear(&buf);
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");
524 goto on_error;
525 }
526
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");
530 goto on_error;
531 }
532 }
533 }
534
535 /* If requested, disable certificate validation */
536 if (t->connection_data.use_ssl) {
537 int flags;
538
539 if (t->owner->parent.read_flags(&t->owner->parent, &flags) < 0)
540 goto on_error;
541 }
542
543 /* If we have a credential on the subtransport, apply it to the request */
544 if (t->cred &&
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)
548 goto on_error;
549 else if (t->cred &&
550 t->cred->credtype == GIT_CREDTYPE_DEFAULT &&
551 t->auth_mechanism == GIT_WINHTTP_AUTH_NEGOTIATE &&
552 apply_default_credentials(s->request) < 0)
553 goto on_error;
554
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) {
558 if (!t->url_cred &&
559 git_cred_userpass_plaintext_new(&t->url_cred, t->connection_data.user, t->connection_data.pass) < 0)
560 goto on_error;
561 if (apply_basic_credential(s->request, t->url_cred) < 0)
562 goto on_error;
563 }
564
565 /* We've done everything up to calling WinHttpSendRequest. */
566
567 error = 0;
568
569 on_error:
570 if (error < 0)
571 winhttp_stream_close(s);
572
573 git__free(proxy_url);
574 git_buf_free(&buf);
575 return error;
576 }
577
578 static int parse_unauthorized_response(
579 HINTERNET request,
580 int *allowed_types,
581 int *auth_mechanism)
582 {
583 DWORD supported, first, target;
584
585 *allowed_types = 0;
586 *auth_mechanism = 0;
587
588 /* WinHttpQueryHeaders() must be called before WinHttpQueryAuthSchemes().
589 * We can assume this was already done, since we know we are unauthorized.
590 */
591 if (!WinHttpQueryAuthSchemes(request, &supported, &first, &target)) {
592 giterr_set(GITERR_OS, "Failed to parse supported auth schemes");
593 return -1;
594 }
595
596 if (WINHTTP_AUTH_SCHEME_BASIC & supported) {
597 *allowed_types |= GIT_CREDTYPE_USERPASS_PLAINTEXT;
598 *auth_mechanism = GIT_WINHTTP_AUTH_BASIC;
599 }
600
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;
605 }
606
607 return 0;
608 }
609
610 static int write_chunk(HINTERNET request, const char *buffer, size_t len)
611 {
612 DWORD bytes_written;
613 git_buf buf = GIT_BUF_INIT;
614
615 /* Chunk header */
616 git_buf_printf(&buf, "%X\r\n", len);
617
618 if (git_buf_oom(&buf))
619 return -1;
620
621 if (!WinHttpWriteData(request,
622 git_buf_cstr(&buf), (DWORD)git_buf_len(&buf),
623 &bytes_written)) {
624 git_buf_free(&buf);
625 giterr_set(GITERR_OS, "Failed to write chunk header");
626 return -1;
627 }
628
629 git_buf_free(&buf);
630
631 /* Chunk body */
632 if (!WinHttpWriteData(request,
633 buffer, (DWORD)len,
634 &bytes_written)) {
635 giterr_set(GITERR_OS, "Failed to write chunk");
636 return -1;
637 }
638
639 /* Chunk footer */
640 if (!WinHttpWriteData(request,
641 "\r\n", 2,
642 &bytes_written)) {
643 giterr_set(GITERR_OS, "Failed to write chunk footer");
644 return -1;
645 }
646
647 return 0;
648 }
649
650 static int winhttp_close_connection(winhttp_subtransport *t)
651 {
652 int ret = 0;
653
654 if (t->connection) {
655 if (!WinHttpCloseHandle(t->connection)) {
656 giterr_set(GITERR_OS, "Unable to close connection");
657 ret = -1;
658 }
659
660 t->connection = NULL;
661 }
662
663 if (t->session) {
664 if (!WinHttpCloseHandle(t->session)) {
665 giterr_set(GITERR_OS, "Unable to close session");
666 ret = -1;
667 }
668
669 t->session = NULL;
670 }
671
672 return ret;
673 }
674
675 static int user_agent(git_buf *ua)
676 {
677 const char *custom = git_libgit2__user_agent();
678
679 git_buf_clear(ua);
680 git_buf_PUTS(ua, "git/1.0 (");
681
682 if (custom)
683 git_buf_puts(ua, custom);
684 else
685 git_buf_PUTS(ua, "libgit2 " LIBGIT2_VERSION);
686
687 return git_buf_putc(ua, ')');
688 }
689
690 static int winhttp_connect(
691 winhttp_subtransport *t)
692 {
693 wchar_t *wide_host;
694 int32_t port;
695 wchar_t *wide_ua;
696 git_buf ua = GIT_BUF_INIT;
697 int error = -1;
698 int default_timeout = TIMEOUT_INFINITE;
699 int default_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
700
701 t->session = NULL;
702 t->connection = NULL;
703
704 /* Prepare port */
705 if (git__strtol32(&port, t->connection_data.port, NULL, 10) < 0)
706 return -1;
707
708 /* Prepare host */
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");
711 return -1;
712 }
713
714 if ((error = user_agent(&ua)) < 0) {
715 git__free(wide_host);
716 return error;
717 }
718
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);
722 git_buf_free(&ua);
723 return -1;
724 }
725
726 git_buf_free(&ua);
727
728 /* Establish session */
729 t->session = WinHttpOpen(
730 wide_ua,
731 WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
732 WINHTTP_NO_PROXY_NAME,
733 WINHTTP_NO_PROXY_BYPASS,
734 0);
735
736 if (!t->session) {
737 giterr_set(GITERR_OS, "Failed to init WinHTTP");
738 goto on_error;
739 }
740
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");
743 goto on_error;
744 }
745
746
747 /* Establish connection */
748 t->connection = WinHttpConnect(
749 t->session,
750 wide_host,
751 (INTERNET_PORT) port,
752 0);
753
754 if (!t->connection) {
755 giterr_set(GITERR_OS, "Failed to connect to host");
756 goto on_error;
757 }
758
759 error = 0;
760
761 on_error:
762 if (error < 0)
763 winhttp_close_connection(t);
764
765 git__free(wide_host);
766 git__free(wide_ua);
767
768 return error;
769 }
770
771 static int do_send_request(winhttp_stream *s, size_t len, int ignore_length)
772 {
773 if (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)) {
778 return -1;
779 }
780 } else {
781 if (!WinHttpSendRequest(s->request,
782 WINHTTP_NO_ADDITIONAL_HEADERS, 0,
783 WINHTTP_NO_REQUEST_DATA, 0,
784 len, 0)) {
785 return -1;
786 }
787 }
788
789 return 0;
790 }
791
792 static int send_request(winhttp_stream *s, size_t len, int ignore_length)
793 {
794 int request_failed = 0, cert_valid = 1, error = 0;
795 DWORD ignore_flags;
796
797 if ((error = do_send_request(s, len, ignore_length)) < 0)
798 request_failed = 1;
799
800 if (request_failed) {
801 if (GetLastError() != ERROR_WINHTTP_SECURE_FAILURE) {
802 giterr_set(GITERR_OS, "failed to send request");
803 return -1;
804 } else {
805 cert_valid = 0;
806 }
807 }
808
809 giterr_clear();
810 if ((error = certificate_check(s, cert_valid)) < 0) {
811 if (!giterr_last())
812 giterr_set(GITERR_OS, "user cancelled certificate check");
813
814 return error;
815 }
816
817 /* if neither the request nor the certificate check returned errors, we're done */
818 if (!request_failed)
819 return 0;
820
821 ignore_flags = no_check_cert_flags;
822
823 if (!WinHttpSetOption(s->request, WINHTTP_OPTION_SECURITY_FLAGS, &ignore_flags, sizeof(ignore_flags))) {
824 giterr_set(GITERR_OS, "failed to set security options");
825 return -1;
826 }
827
828 if ((error = do_send_request(s, len, ignore_length)) < 0)
829 giterr_set(GITERR_OS, "failed to send request");
830
831 return error;
832 }
833
834 static int winhttp_stream_read(
835 git_smart_subtransport_stream *stream,
836 char *buffer,
837 size_t buf_size,
838 size_t *bytes_read)
839 {
840 winhttp_stream *s = (winhttp_stream *)stream;
841 winhttp_subtransport *t = OWNING_SUBTRANSPORT(s);
842 DWORD dw_bytes_read;
843 char replay_count = 0;
844 int error;
845
846 replay:
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");
850 return -1;
851 }
852
853 /* Connect if necessary */
854 if (!s->request && winhttp_stream_connect(s) < 0)
855 return -1;
856
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];
861
862 if (!s->sent_request) {
863
864 if ((error = send_request(s, s->post_body_len, 0)) < 0)
865 return error;
866
867 s->sent_request = 1;
868 }
869
870 if (s->chunked) {
871 assert(s->verb == post_verb);
872
873 /* Flush, if necessary */
874 if (s->chunk_buffer_len > 0 &&
875 write_chunk(s->request, s->chunk_buffer, s->chunk_buffer_len) < 0)
876 return -1;
877
878 s->chunk_buffer_len = 0;
879
880 /* Write the final chunk. */
881 if (!WinHttpWriteData(s->request,
882 "0\r\n\r\n", 5,
883 &bytes_written)) {
884 giterr_set(GITERR_OS, "Failed to write final chunk");
885 return -1;
886 }
887 }
888 else if (s->post_body) {
889 char *buffer;
890 DWORD len = s->post_body_len, bytes_read;
891
892 if (INVALID_SET_FILE_POINTER == SetFilePointer(s->post_body,
893 0, 0, FILE_BEGIN) &&
894 NO_ERROR != GetLastError()) {
895 giterr_set(GITERR_OS, "Failed to reset file pointer");
896 return -1;
897 }
898
899 buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE);
900
901 while (len > 0) {
902 DWORD bytes_written;
903
904 if (!ReadFile(s->post_body, buffer,
905 min(CACHED_POST_BODY_BUF_SIZE, len),
906 &bytes_read, NULL) ||
907 !bytes_read) {
908 git__free(buffer);
909 giterr_set(GITERR_OS, "Failed to read from temp file");
910 return -1;
911 }
912
913 if (!WinHttpWriteData(s->request, buffer,
914 bytes_read, &bytes_written)) {
915 git__free(buffer);
916 giterr_set(GITERR_OS, "Failed to write data");
917 return -1;
918 }
919
920 len -= bytes_read;
921 assert(bytes_read == bytes_written);
922 }
923
924 git__free(buffer);
925
926 /* Eagerly close the temp file */
927 CloseHandle(s->post_body);
928 s->post_body = NULL;
929 }
930
931 if (!WinHttpReceiveResponse(s->request, 0)) {
932 giterr_set(GITERR_OS, "Failed to receive response");
933 return -1;
934 }
935
936 /* Verify that we got a 200 back */
937 status_code_length = sizeof(status_code);
938
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");
945 return -1;
946 }
947
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.) */
953 if (!s->chunked &&
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)) {
959
960 /* Check for Windows 7. This workaround is only necessary on
961 * Windows Vista and earlier. Windows 7 is version 6.1. */
962 wchar_t *location;
963 DWORD location_length;
964 char *location8;
965
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,
971 &location_length,
972 WINHTTP_NO_HEADER_INDEX) ||
973 GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
974 giterr_set(GITERR_OS, "Failed to read Location header");
975 return -1;
976 }
977
978 location = git__malloc(location_length);
979 GITERR_CHECK_ALLOC(location);
980
981 if (!WinHttpQueryHeaders(s->request,
982 WINHTTP_QUERY_LOCATION,
983 WINHTTP_HEADER_NAME_BY_INDEX,
984 location,
985 &location_length,
986 WINHTTP_NO_HEADER_INDEX)) {
987 giterr_set(GITERR_OS, "Failed to read Location header");
988 git__free(location);
989 return -1;
990 }
991
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");
995 git__free(location);
996 return -1;
997 }
998
999 git__free(location);
1000
1001 /* Replay the request */
1002 winhttp_stream_close(s);
1003
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);
1008 return -1;
1009 }
1010
1011 winhttp_close_connection(t);
1012
1013 if (winhttp_connect(t) < 0)
1014 return -1;
1015 }
1016
1017 git__free(location8);
1018 goto replay;
1019 }
1020
1021 /* Handle proxy authentication failures */
1022 if (status_code == HTTP_STATUS_PROXY_AUTH_REQ) {
1023 int allowed_types;
1024
1025 if (parse_unauthorized_response(s->request, &allowed_types, &t->auth_mechanism) < 0)
1026 return -1;
1027
1028 /* TODO: extract the username from the url, no payload? */
1029 if (t->owner->proxy.credentials) {
1030 int cred_error = 1;
1031 cred_error = t->owner->proxy.credentials(&t->proxy_cred, t->owner->proxy.url, NULL, allowed_types, NULL);
1032
1033 if (cred_error < 0)
1034 return cred_error;
1035 }
1036
1037 winhttp_stream_close(s);
1038 goto replay;
1039 }
1040
1041 /* Handle authentication failures */
1042 if (HTTP_STATUS_DENIED == status_code && get_verb == s->verb) {
1043 int allowed_types;
1044
1045 if (parse_unauthorized_response(s->request, &allowed_types, &t->auth_mechanism) < 0)
1046 return -1;
1047
1048 if (allowed_types) {
1049 int cred_error = 1;
1050
1051 git_cred_free(t->cred);
1052 t->cred = NULL;
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);
1057
1058 /* Treat GIT_PASSTHROUGH as though git_cred_acquire_cb isn't set */
1059 if (cred_error == GIT_PASSTHROUGH)
1060 cred_error = 1;
1061 else if (cred_error < 0)
1062 return cred_error;
1063 }
1064
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);
1069
1070 if (cred_error < 0)
1071 return cred_error;
1072 }
1073
1074 if (!cred_error) {
1075 assert(t->cred);
1076
1077 winhttp_stream_close(s);
1078
1079 /* Successfully acquired a credential */
1080 goto replay;
1081 }
1082 }
1083 }
1084
1085 if (HTTP_STATUS_OK != status_code) {
1086 giterr_set(GITERR_NET, "Request failed with status code: %d", status_code);
1087 return -1;
1088 }
1089
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);
1093 else
1094 p_snprintf(expected_content_type_8, MAX_CONTENT_TYPE_LEN, "application/x-git-%s-advertisement", s->service);
1095
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");
1098 return -1;
1099 }
1100
1101 content_type_length = sizeof(content_type);
1102
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");
1109 return -1;
1110 }
1111
1112 if (wcscmp(expected_content_type, content_type)) {
1113 giterr_set(GITERR_NET, "Received unexpected content-type");
1114 return -1;
1115 }
1116
1117 s->received_response = 1;
1118 }
1119
1120 if (!WinHttpReadData(s->request,
1121 (LPVOID)buffer,
1122 (DWORD)buf_size,
1123 &dw_bytes_read))
1124 {
1125 giterr_set(GITERR_OS, "Failed to read data");
1126 return -1;
1127 }
1128
1129 *bytes_read = dw_bytes_read;
1130
1131 return 0;
1132 }
1133
1134 static int winhttp_stream_write_single(
1135 git_smart_subtransport_stream *stream,
1136 const char *buffer,
1137 size_t len)
1138 {
1139 winhttp_stream *s = (winhttp_stream *)stream;
1140 DWORD bytes_written;
1141 int error;
1142
1143 if (!s->request && winhttp_stream_connect(s) < 0)
1144 return -1;
1145
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");
1149 return -1;
1150 }
1151
1152 if ((error = send_request(s, len, 0)) < 0)
1153 return error;
1154
1155 s->sent_request = 1;
1156
1157 if (!WinHttpWriteData(s->request,
1158 (LPCVOID)buffer,
1159 (DWORD)len,
1160 &bytes_written)) {
1161 giterr_set(GITERR_OS, "Failed to write data");
1162 return -1;
1163 }
1164
1165 assert((DWORD)len == bytes_written);
1166
1167 return 0;
1168 }
1169
1170 static int put_uuid_string(LPWSTR buffer, size_t buffer_len_cch)
1171 {
1172 UUID uuid;
1173 RPC_STATUS status = UuidCreate(&uuid);
1174 int result;
1175
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");
1180 return -1;
1181 }
1182
1183 if (buffer_len_cch < UUID_LENGTH_CCH + 1) {
1184 giterr_set(GITERR_NET, "Buffer too small for name of temp file");
1185 return -1;
1186 }
1187
1188 #if !defined(__MINGW32__) || defined(MINGW_HAS_SECURE_API)
1189 result = swprintf_s(buffer, buffer_len_cch,
1190 #else
1191 result = wsprintfW(buffer,
1192 #endif
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]);
1197
1198 if (result < UUID_LENGTH_CCH) {
1199 giterr_set(GITERR_OS, "Unable to generate name for temp file");
1200 return -1;
1201 }
1202
1203 return 0;
1204 }
1205
1206 static int get_temp_file(LPWSTR buffer, DWORD buffer_len_cch)
1207 {
1208 size_t len;
1209
1210 if (!GetTempPathW(buffer_len_cch, buffer)) {
1211 giterr_set(GITERR_OS, "Failed to get temp path");
1212 return -1;
1213 }
1214
1215 len = wcslen(buffer);
1216
1217 if (buffer[len - 1] != '\\' && len < buffer_len_cch)
1218 buffer[len++] = '\\';
1219
1220 if (put_uuid_string(&buffer[len], (size_t)buffer_len_cch - len) < 0)
1221 return -1;
1222
1223 return 0;
1224 }
1225
1226 static int winhttp_stream_write_buffered(
1227 git_smart_subtransport_stream *stream,
1228 const char *buffer,
1229 size_t len)
1230 {
1231 winhttp_stream *s = (winhttp_stream *)stream;
1232 DWORD bytes_written;
1233
1234 if (!s->request && winhttp_stream_connect(s) < 0)
1235 return -1;
1236
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];
1241
1242 if (get_temp_file(temp_path, MAX_PATH + 1) < 0)
1243 return -1;
1244
1245 s->post_body = CreateFileW(temp_path,
1246 GENERIC_READ | GENERIC_WRITE,
1247 FILE_SHARE_DELETE, NULL,
1248 CREATE_NEW,
1249 FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | FILE_FLAG_SEQUENTIAL_SCAN,
1250 NULL);
1251
1252 if (INVALID_HANDLE_VALUE == s->post_body) {
1253 s->post_body = NULL;
1254 giterr_set(GITERR_OS, "Failed to create temporary file");
1255 return -1;
1256 }
1257 }
1258
1259 if (!WriteFile(s->post_body, buffer, (DWORD)len, &bytes_written, NULL)) {
1260 giterr_set(GITERR_OS, "Failed to write to temporary file");
1261 return -1;
1262 }
1263
1264 assert((DWORD)len == bytes_written);
1265
1266 s->post_body_len += bytes_written;
1267
1268 return 0;
1269 }
1270
1271 static int winhttp_stream_write_chunked(
1272 git_smart_subtransport_stream *stream,
1273 const char *buffer,
1274 size_t len)
1275 {
1276 winhttp_stream *s = (winhttp_stream *)stream;
1277 int error;
1278
1279 if (!s->request && winhttp_stream_connect(s) < 0)
1280 return -1;
1281
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");
1288 return -1;
1289 }
1290
1291 if ((error = send_request(s, 0, 1)) < 0)
1292 return error;
1293
1294 s->sent_request = 1;
1295 }
1296
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)
1301 return -1;
1302
1303 s->chunk_buffer_len = 0;
1304 }
1305
1306 /* Write chunk directly */
1307 if (write_chunk(s->request, buffer, len) < 0)
1308 return -1;
1309 }
1310 else {
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);
1313
1314 if (!s->chunk_buffer)
1315 s->chunk_buffer = git__malloc(CACHED_POST_BODY_BUF_SIZE);
1316
1317 memcpy(s->chunk_buffer + s->chunk_buffer_len, buffer, count);
1318 s->chunk_buffer_len += count;
1319 buffer += count;
1320 len -= count;
1321
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)
1325 return -1;
1326
1327 s->chunk_buffer_len = 0;
1328
1329 /* Is there any remaining data from the source? */
1330 if (len > 0) {
1331 memcpy(s->chunk_buffer, buffer, len);
1332 s->chunk_buffer_len = (unsigned int)len;
1333 }
1334 }
1335 }
1336
1337 return 0;
1338 }
1339
1340 static void winhttp_stream_free(git_smart_subtransport_stream *stream)
1341 {
1342 winhttp_stream *s = (winhttp_stream *)stream;
1343
1344 winhttp_stream_close(s);
1345 git__free(s);
1346 }
1347
1348 static int winhttp_stream_alloc(winhttp_subtransport *t, winhttp_stream **stream)
1349 {
1350 winhttp_stream *s;
1351
1352 if (!stream)
1353 return -1;
1354
1355 s = git__calloc(1, sizeof(winhttp_stream));
1356 GITERR_CHECK_ALLOC(s);
1357
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;
1362
1363 *stream = s;
1364
1365 return 0;
1366 }
1367
1368 static int winhttp_uploadpack_ls(
1369 winhttp_subtransport *t,
1370 winhttp_stream *s)
1371 {
1372 GIT_UNUSED(t);
1373
1374 s->service = upload_pack_service;
1375 s->service_url = upload_pack_ls_service_url;
1376 s->verb = get_verb;
1377
1378 return 0;
1379 }
1380
1381 static int winhttp_uploadpack(
1382 winhttp_subtransport *t,
1383 winhttp_stream *s)
1384 {
1385 GIT_UNUSED(t);
1386
1387 s->service = upload_pack_service;
1388 s->service_url = upload_pack_service_url;
1389 s->verb = post_verb;
1390
1391 return 0;
1392 }
1393
1394 static int winhttp_receivepack_ls(
1395 winhttp_subtransport *t,
1396 winhttp_stream *s)
1397 {
1398 GIT_UNUSED(t);
1399
1400 s->service = receive_pack_service;
1401 s->service_url = receive_pack_ls_service_url;
1402 s->verb = get_verb;
1403
1404 return 0;
1405 }
1406
1407 static int winhttp_receivepack(
1408 winhttp_subtransport *t,
1409 winhttp_stream *s)
1410 {
1411 GIT_UNUSED(t);
1412
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);
1416
1417 if (s->chunked)
1418 s->parent.write = winhttp_stream_write_chunked;
1419 else
1420 s->parent.write = winhttp_stream_write_buffered;
1421
1422 s->service = receive_pack_service;
1423 s->service_url = receive_pack_service_url;
1424 s->verb = post_verb;
1425
1426 return 0;
1427 }
1428
1429 static int winhttp_action(
1430 git_smart_subtransport_stream **stream,
1431 git_smart_subtransport *subtransport,
1432 const char *url,
1433 git_smart_service_t action)
1434 {
1435 winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
1436 winhttp_stream *s;
1437 int ret = -1;
1438
1439 if (!t->connection)
1440 if ((ret = gitno_connection_data_from_url(&t->connection_data, url, NULL)) < 0 ||
1441 (ret = winhttp_connect(t)) < 0)
1442 return ret;
1443
1444 if (winhttp_stream_alloc(t, &s) < 0)
1445 return -1;
1446
1447 if (!stream)
1448 return -1;
1449
1450 switch (action)
1451 {
1452 case GIT_SERVICE_UPLOADPACK_LS:
1453 ret = winhttp_uploadpack_ls(t, s);
1454 break;
1455
1456 case GIT_SERVICE_UPLOADPACK:
1457 ret = winhttp_uploadpack(t, s);
1458 break;
1459
1460 case GIT_SERVICE_RECEIVEPACK_LS:
1461 ret = winhttp_receivepack_ls(t, s);
1462 break;
1463
1464 case GIT_SERVICE_RECEIVEPACK:
1465 ret = winhttp_receivepack(t, s);
1466 break;
1467
1468 default:
1469 assert(0);
1470 }
1471
1472 if (!ret)
1473 *stream = &s->parent;
1474
1475 return ret;
1476 }
1477
1478 static int winhttp_close(git_smart_subtransport *subtransport)
1479 {
1480 winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
1481
1482 gitno_connection_data_free_ptrs(&t->connection_data);
1483 memset(&t->connection_data, 0x0, sizeof(gitno_connection_data));
1484
1485 if (t->cred) {
1486 t->cred->free(t->cred);
1487 t->cred = NULL;
1488 }
1489
1490 if (t->url_cred) {
1491 t->url_cred->free(t->url_cred);
1492 t->url_cred = NULL;
1493 }
1494
1495 return winhttp_close_connection(t);
1496 }
1497
1498 static void winhttp_free(git_smart_subtransport *subtransport)
1499 {
1500 winhttp_subtransport *t = (winhttp_subtransport *)subtransport;
1501
1502 winhttp_close(subtransport);
1503
1504 git__free(t);
1505 }
1506
1507 int git_smart_subtransport_http(git_smart_subtransport **out, git_transport *owner, void *param)
1508 {
1509 winhttp_subtransport *t;
1510
1511 GIT_UNUSED(param);
1512
1513 if (!out)
1514 return -1;
1515
1516 t = git__calloc(1, sizeof(winhttp_subtransport));
1517 GITERR_CHECK_ALLOC(t);
1518
1519 t->owner = (transport_smart *)owner;
1520 t->parent.action = winhttp_action;
1521 t->parent.close = winhttp_close;
1522 t->parent.free = winhttp_free;
1523
1524 *out = (git_smart_subtransport *) t;
1525 return 0;
1526 }
1527
1528 #endif /* GIT_WINHTTP */