The third batch
[git/raj.git] / http.c
blob4882c9f5b268970c571628f5a284e46943b86535
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "config.h"
4 #include "pack.h"
5 #include "sideband.h"
6 #include "run-command.h"
7 #include "url.h"
8 #include "urlmatch.h"
9 #include "credential.h"
10 #include "version.h"
11 #include "pkt-line.h"
12 #include "gettext.h"
13 #include "transport.h"
14 #include "packfile.h"
15 #include "protocol.h"
16 #include "string-list.h"
17 #include "object-store.h"
19 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
20 static int trace_curl_data = 1;
21 static struct string_list cookies_to_redact = STRING_LIST_INIT_DUP;
22 #if LIBCURL_VERSION_NUM >= 0x070a08
23 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
24 #else
25 long int git_curl_ipresolve;
26 #endif
27 int active_requests;
28 int http_is_verbose;
29 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
31 #if LIBCURL_VERSION_NUM >= 0x070a06
32 #define LIBCURL_CAN_HANDLE_AUTH_ANY
33 #endif
35 static int min_curl_sessions = 1;
36 static int curl_session_count;
37 #ifdef USE_CURL_MULTI
38 static int max_requests = -1;
39 static CURLM *curlm;
40 #endif
41 #ifndef NO_CURL_EASY_DUPHANDLE
42 static CURL *curl_default;
43 #endif
45 #define PREV_BUF_SIZE 4096
47 char curl_errorstr[CURL_ERROR_SIZE];
49 static int curl_ssl_verify = -1;
50 static int curl_ssl_try;
51 static const char *curl_http_version = NULL;
52 static const char *ssl_cert;
53 static const char *ssl_cipherlist;
54 static const char *ssl_version;
55 static struct {
56 const char *name;
57 long ssl_version;
58 } sslversions[] = {
59 { "sslv2", CURL_SSLVERSION_SSLv2 },
60 { "sslv3", CURL_SSLVERSION_SSLv3 },
61 { "tlsv1", CURL_SSLVERSION_TLSv1 },
62 #if LIBCURL_VERSION_NUM >= 0x072200
63 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
64 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
65 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
66 #endif
67 #if LIBCURL_VERSION_NUM >= 0x073400
68 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
69 #endif
71 #if LIBCURL_VERSION_NUM >= 0x070903
72 static const char *ssl_key;
73 #endif
74 #if LIBCURL_VERSION_NUM >= 0x070908
75 static const char *ssl_capath;
76 #endif
77 #if LIBCURL_VERSION_NUM >= 0x071304
78 static const char *curl_no_proxy;
79 #endif
80 #if LIBCURL_VERSION_NUM >= 0x072c00
81 static const char *ssl_pinnedkey;
82 #endif
83 static const char *ssl_cainfo;
84 static long curl_low_speed_limit = -1;
85 static long curl_low_speed_time = -1;
86 static int curl_ftp_no_epsv;
87 static const char *curl_http_proxy;
88 static const char *http_proxy_authmethod;
90 static const char *http_proxy_ssl_cert;
91 static const char *http_proxy_ssl_key;
92 static const char *http_proxy_ssl_ca_info;
93 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
94 static int proxy_ssl_cert_password_required;
96 static struct {
97 const char *name;
98 long curlauth_param;
99 } proxy_authmethods[] = {
100 { "basic", CURLAUTH_BASIC },
101 { "digest", CURLAUTH_DIGEST },
102 { "negotiate", CURLAUTH_GSSNEGOTIATE },
103 { "ntlm", CURLAUTH_NTLM },
104 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
105 { "anyauth", CURLAUTH_ANY },
106 #endif
108 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
109 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
110 * here, too
113 #ifdef CURLGSSAPI_DELEGATION_FLAG
114 static const char *curl_deleg;
115 static struct {
116 const char *name;
117 long curl_deleg_param;
118 } curl_deleg_levels[] = {
119 { "none", CURLGSSAPI_DELEGATION_NONE },
120 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
121 { "always", CURLGSSAPI_DELEGATION_FLAG },
123 #endif
125 static struct credential proxy_auth = CREDENTIAL_INIT;
126 static const char *curl_proxyuserpwd;
127 static const char *curl_cookie_file;
128 static int curl_save_cookies;
129 struct credential http_auth = CREDENTIAL_INIT;
130 static int http_proactive_auth;
131 static const char *user_agent;
132 static int curl_empty_auth = -1;
134 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
136 #if LIBCURL_VERSION_NUM >= 0x071700
137 /* Use CURLOPT_KEYPASSWD as is */
138 #elif LIBCURL_VERSION_NUM >= 0x070903
139 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
140 #else
141 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
142 #endif
144 static struct credential cert_auth = CREDENTIAL_INIT;
145 static int ssl_cert_password_required;
146 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
147 static unsigned long http_auth_methods = CURLAUTH_ANY;
148 static int http_auth_methods_restricted;
149 /* Modes for which empty_auth cannot actually help us. */
150 static unsigned long empty_auth_useless =
151 CURLAUTH_BASIC
152 #ifdef CURLAUTH_DIGEST_IE
153 | CURLAUTH_DIGEST_IE
154 #endif
155 | CURLAUTH_DIGEST;
156 #endif
158 static struct curl_slist *pragma_header;
159 static struct curl_slist *no_pragma_header;
160 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
162 static struct active_request_slot *active_queue_head;
164 static char *cached_accept_language;
166 static char *http_ssl_backend;
168 static int http_schannel_check_revoke = 1;
170 * With the backend being set to `schannel`, setting sslCAinfo would override
171 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
172 * by default.
174 static int http_schannel_use_ssl_cainfo;
176 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
178 size_t size = eltsize * nmemb;
179 struct buffer *buffer = buffer_;
181 if (size > buffer->buf.len - buffer->posn)
182 size = buffer->buf.len - buffer->posn;
183 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
184 buffer->posn += size;
186 return size / eltsize;
189 #ifndef NO_CURL_IOCTL
190 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
192 struct buffer *buffer = clientp;
194 switch (cmd) {
195 case CURLIOCMD_NOP:
196 return CURLIOE_OK;
198 case CURLIOCMD_RESTARTREAD:
199 buffer->posn = 0;
200 return CURLIOE_OK;
202 default:
203 return CURLIOE_UNKNOWNCMD;
206 #endif
208 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
210 size_t size = eltsize * nmemb;
211 struct strbuf *buffer = buffer_;
213 strbuf_add(buffer, ptr, size);
214 return nmemb;
217 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
219 return nmemb;
222 static void closedown_active_slot(struct active_request_slot *slot)
224 active_requests--;
225 slot->in_use = 0;
228 static void finish_active_slot(struct active_request_slot *slot)
230 closedown_active_slot(slot);
231 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
233 if (slot->finished != NULL)
234 (*slot->finished) = 1;
236 /* Store slot results so they can be read after the slot is reused */
237 if (slot->results != NULL) {
238 slot->results->curl_result = slot->curl_result;
239 slot->results->http_code = slot->http_code;
240 #if LIBCURL_VERSION_NUM >= 0x070a08
241 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
242 &slot->results->auth_avail);
243 #else
244 slot->results->auth_avail = 0;
245 #endif
247 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
248 &slot->results->http_connectcode);
251 /* Run callback if appropriate */
252 if (slot->callback_func != NULL)
253 slot->callback_func(slot->callback_data);
256 static void xmulti_remove_handle(struct active_request_slot *slot)
258 #ifdef USE_CURL_MULTI
259 curl_multi_remove_handle(curlm, slot->curl);
260 #endif
263 #ifdef USE_CURL_MULTI
264 static void process_curl_messages(void)
266 int num_messages;
267 struct active_request_slot *slot;
268 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
270 while (curl_message != NULL) {
271 if (curl_message->msg == CURLMSG_DONE) {
272 int curl_result = curl_message->data.result;
273 slot = active_queue_head;
274 while (slot != NULL &&
275 slot->curl != curl_message->easy_handle)
276 slot = slot->next;
277 if (slot != NULL) {
278 xmulti_remove_handle(slot);
279 slot->curl_result = curl_result;
280 finish_active_slot(slot);
281 } else {
282 fprintf(stderr, "Received DONE message for unknown request!\n");
284 } else {
285 fprintf(stderr, "Unknown CURL message received: %d\n",
286 (int)curl_message->msg);
288 curl_message = curl_multi_info_read(curlm, &num_messages);
291 #endif
293 static int http_options(const char *var, const char *value, void *cb)
295 if (!strcmp("http.version", var)) {
296 return git_config_string(&curl_http_version, var, value);
298 if (!strcmp("http.sslverify", var)) {
299 curl_ssl_verify = git_config_bool(var, value);
300 return 0;
302 if (!strcmp("http.sslcipherlist", var))
303 return git_config_string(&ssl_cipherlist, var, value);
304 if (!strcmp("http.sslversion", var))
305 return git_config_string(&ssl_version, var, value);
306 if (!strcmp("http.sslcert", var))
307 return git_config_pathname(&ssl_cert, var, value);
308 #if LIBCURL_VERSION_NUM >= 0x070903
309 if (!strcmp("http.sslkey", var))
310 return git_config_pathname(&ssl_key, var, value);
311 #endif
312 #if LIBCURL_VERSION_NUM >= 0x070908
313 if (!strcmp("http.sslcapath", var))
314 return git_config_pathname(&ssl_capath, var, value);
315 #endif
316 if (!strcmp("http.sslcainfo", var))
317 return git_config_pathname(&ssl_cainfo, var, value);
318 if (!strcmp("http.sslcertpasswordprotected", var)) {
319 ssl_cert_password_required = git_config_bool(var, value);
320 return 0;
322 if (!strcmp("http.ssltry", var)) {
323 curl_ssl_try = git_config_bool(var, value);
324 return 0;
326 if (!strcmp("http.sslbackend", var)) {
327 free(http_ssl_backend);
328 http_ssl_backend = xstrdup_or_null(value);
329 return 0;
332 if (!strcmp("http.schannelcheckrevoke", var)) {
333 http_schannel_check_revoke = git_config_bool(var, value);
334 return 0;
337 if (!strcmp("http.schannelusesslcainfo", var)) {
338 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
339 return 0;
342 if (!strcmp("http.minsessions", var)) {
343 min_curl_sessions = git_config_int(var, value);
344 #ifndef USE_CURL_MULTI
345 if (min_curl_sessions > 1)
346 min_curl_sessions = 1;
347 #endif
348 return 0;
350 #ifdef USE_CURL_MULTI
351 if (!strcmp("http.maxrequests", var)) {
352 max_requests = git_config_int(var, value);
353 return 0;
355 #endif
356 if (!strcmp("http.lowspeedlimit", var)) {
357 curl_low_speed_limit = (long)git_config_int(var, value);
358 return 0;
360 if (!strcmp("http.lowspeedtime", var)) {
361 curl_low_speed_time = (long)git_config_int(var, value);
362 return 0;
365 if (!strcmp("http.noepsv", var)) {
366 curl_ftp_no_epsv = git_config_bool(var, value);
367 return 0;
369 if (!strcmp("http.proxy", var))
370 return git_config_string(&curl_http_proxy, var, value);
372 if (!strcmp("http.proxyauthmethod", var))
373 return git_config_string(&http_proxy_authmethod, var, value);
375 if (!strcmp("http.proxysslcert", var))
376 return git_config_string(&http_proxy_ssl_cert, var, value);
378 if (!strcmp("http.proxysslkey", var))
379 return git_config_string(&http_proxy_ssl_key, var, value);
381 if (!strcmp("http.proxysslcainfo", var))
382 return git_config_string(&http_proxy_ssl_ca_info, var, value);
384 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
385 proxy_ssl_cert_password_required = git_config_bool(var, value);
386 return 0;
389 if (!strcmp("http.cookiefile", var))
390 return git_config_pathname(&curl_cookie_file, var, value);
391 if (!strcmp("http.savecookies", var)) {
392 curl_save_cookies = git_config_bool(var, value);
393 return 0;
396 if (!strcmp("http.postbuffer", var)) {
397 http_post_buffer = git_config_ssize_t(var, value);
398 if (http_post_buffer < 0)
399 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
400 if (http_post_buffer < LARGE_PACKET_MAX)
401 http_post_buffer = LARGE_PACKET_MAX;
402 return 0;
405 if (!strcmp("http.useragent", var))
406 return git_config_string(&user_agent, var, value);
408 if (!strcmp("http.emptyauth", var)) {
409 if (value && !strcmp("auto", value))
410 curl_empty_auth = -1;
411 else
412 curl_empty_auth = git_config_bool(var, value);
413 return 0;
416 if (!strcmp("http.delegation", var)) {
417 #ifdef CURLGSSAPI_DELEGATION_FLAG
418 return git_config_string(&curl_deleg, var, value);
419 #else
420 warning(_("Delegation control is not supported with cURL < 7.22.0"));
421 return 0;
422 #endif
425 if (!strcmp("http.pinnedpubkey", var)) {
426 #if LIBCURL_VERSION_NUM >= 0x072c00
427 return git_config_pathname(&ssl_pinnedkey, var, value);
428 #else
429 warning(_("Public key pinning not supported with cURL < 7.44.0"));
430 return 0;
431 #endif
434 if (!strcmp("http.extraheader", var)) {
435 if (!value) {
436 return config_error_nonbool(var);
437 } else if (!*value) {
438 string_list_clear(&extra_http_headers, 0);
439 } else {
440 string_list_append(&extra_http_headers, value);
442 return 0;
445 if (!strcmp("http.followredirects", var)) {
446 if (value && !strcmp(value, "initial"))
447 http_follow_config = HTTP_FOLLOW_INITIAL;
448 else if (git_config_bool(var, value))
449 http_follow_config = HTTP_FOLLOW_ALWAYS;
450 else
451 http_follow_config = HTTP_FOLLOW_NONE;
452 return 0;
455 /* Fall back on the default ones */
456 return git_default_config(var, value, cb);
459 static int curl_empty_auth_enabled(void)
461 if (curl_empty_auth >= 0)
462 return curl_empty_auth;
464 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
466 * Our libcurl is too old to do AUTH_ANY in the first place;
467 * just default to turning the feature off.
469 #else
471 * In the automatic case, kick in the empty-auth
472 * hack as long as we would potentially try some
473 * method more exotic than "Basic" or "Digest".
475 * But only do this when this is our second or
476 * subsequent request, as by then we know what
477 * methods are available.
479 if (http_auth_methods_restricted &&
480 (http_auth_methods & ~empty_auth_useless))
481 return 1;
482 #endif
483 return 0;
486 static void init_curl_http_auth(CURL *result)
488 if (!http_auth.username || !*http_auth.username) {
489 if (curl_empty_auth_enabled())
490 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
491 return;
494 credential_fill(&http_auth);
496 #if LIBCURL_VERSION_NUM >= 0x071301
497 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
498 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
499 #else
501 static struct strbuf up = STRBUF_INIT;
503 * Note that we assume we only ever have a single set of
504 * credentials in a given program run, so we do not have
505 * to worry about updating this buffer, only setting its
506 * initial value.
508 if (!up.len)
509 strbuf_addf(&up, "%s:%s",
510 http_auth.username, http_auth.password);
511 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
513 #endif
516 /* *var must be free-able */
517 static void var_override(const char **var, char *value)
519 if (value) {
520 free((void *)*var);
521 *var = xstrdup(value);
525 static void set_proxyauth_name_password(CURL *result)
527 #if LIBCURL_VERSION_NUM >= 0x071301
528 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
529 proxy_auth.username);
530 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
531 proxy_auth.password);
532 #else
533 struct strbuf s = STRBUF_INIT;
535 strbuf_addstr_urlencode(&s, proxy_auth.username,
536 is_rfc3986_unreserved);
537 strbuf_addch(&s, ':');
538 strbuf_addstr_urlencode(&s, proxy_auth.password,
539 is_rfc3986_unreserved);
540 curl_proxyuserpwd = strbuf_detach(&s, NULL);
541 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
542 #endif
545 static void init_curl_proxy_auth(CURL *result)
547 if (proxy_auth.username) {
548 if (!proxy_auth.password)
549 credential_fill(&proxy_auth);
550 set_proxyauth_name_password(result);
553 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
555 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
556 if (http_proxy_authmethod) {
557 int i;
558 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
559 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
560 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
561 proxy_authmethods[i].curlauth_param);
562 break;
565 if (i == ARRAY_SIZE(proxy_authmethods)) {
566 warning("unsupported proxy authentication method %s: using anyauth",
567 http_proxy_authmethod);
568 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
571 else
572 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
573 #endif
576 static int has_cert_password(void)
578 if (ssl_cert == NULL || ssl_cert_password_required != 1)
579 return 0;
580 if (!cert_auth.password) {
581 cert_auth.protocol = xstrdup("cert");
582 cert_auth.host = xstrdup("");
583 cert_auth.username = xstrdup("");
584 cert_auth.path = xstrdup(ssl_cert);
585 credential_fill(&cert_auth);
587 return 1;
590 #if LIBCURL_VERSION_NUM >= 0x073400
591 static int has_proxy_cert_password(void)
593 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
594 return 0;
595 if (!proxy_cert_auth.password) {
596 proxy_cert_auth.protocol = xstrdup("cert");
597 proxy_cert_auth.host = xstrdup("");
598 proxy_cert_auth.username = xstrdup("");
599 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
600 credential_fill(&proxy_cert_auth);
602 return 1;
604 #endif
606 #if LIBCURL_VERSION_NUM >= 0x071900
607 static void set_curl_keepalive(CURL *c)
609 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
612 #elif LIBCURL_VERSION_NUM >= 0x071000
613 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
615 int ka = 1;
616 int rc;
617 socklen_t len = (socklen_t)sizeof(ka);
619 if (type != CURLSOCKTYPE_IPCXN)
620 return 0;
622 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
623 if (rc < 0)
624 warning_errno("unable to set SO_KEEPALIVE on socket");
626 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
629 static void set_curl_keepalive(CURL *c)
631 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
634 #else
635 static void set_curl_keepalive(CURL *c)
637 /* not supported on older curl versions */
639 #endif
641 static void redact_sensitive_header(struct strbuf *header)
643 const char *sensitive_header;
645 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
646 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
647 /* The first token is the type, which is OK to log */
648 while (isspace(*sensitive_header))
649 sensitive_header++;
650 while (*sensitive_header && !isspace(*sensitive_header))
651 sensitive_header++;
652 /* Everything else is opaque and possibly sensitive */
653 strbuf_setlen(header, sensitive_header - header->buf);
654 strbuf_addstr(header, " <redacted>");
655 } else if (cookies_to_redact.nr &&
656 skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
657 struct strbuf redacted_header = STRBUF_INIT;
658 char *cookie;
660 while (isspace(*sensitive_header))
661 sensitive_header++;
664 * The contents of header starting from sensitive_header will
665 * subsequently be overridden, so it is fine to mutate this
666 * string (hence the assignment to "char *").
668 cookie = (char *) sensitive_header;
670 while (cookie) {
671 char *equals;
672 char *semicolon = strstr(cookie, "; ");
673 if (semicolon)
674 *semicolon = 0;
675 equals = strchrnul(cookie, '=');
676 if (!equals) {
677 /* invalid cookie, just append and continue */
678 strbuf_addstr(&redacted_header, cookie);
679 continue;
681 *equals = 0; /* temporarily set to NUL for lookup */
682 if (string_list_lookup(&cookies_to_redact, cookie)) {
683 strbuf_addstr(&redacted_header, cookie);
684 strbuf_addstr(&redacted_header, "=<redacted>");
685 } else {
686 *equals = '=';
687 strbuf_addstr(&redacted_header, cookie);
689 if (semicolon) {
691 * There are more cookies. (Or, for some
692 * reason, the input string ends in "; ".)
694 strbuf_addstr(&redacted_header, "; ");
695 cookie = semicolon + strlen("; ");
696 } else {
697 cookie = NULL;
701 strbuf_setlen(header, sensitive_header - header->buf);
702 strbuf_addbuf(header, &redacted_header);
706 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
708 struct strbuf out = STRBUF_INIT;
709 struct strbuf **headers, **header;
711 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
712 text, (long)size, (long)size);
713 trace_strbuf(&trace_curl, &out);
714 strbuf_reset(&out);
715 strbuf_add(&out, ptr, size);
716 headers = strbuf_split_max(&out, '\n', 0);
718 for (header = headers; *header; header++) {
719 if (hide_sensitive_header)
720 redact_sensitive_header(*header);
721 strbuf_insertstr((*header), 0, text);
722 strbuf_insertstr((*header), strlen(text), ": ");
723 strbuf_rtrim((*header));
724 strbuf_addch((*header), '\n');
725 trace_strbuf(&trace_curl, (*header));
727 strbuf_list_free(headers);
728 strbuf_release(&out);
731 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
733 size_t i;
734 struct strbuf out = STRBUF_INIT;
735 unsigned int width = 60;
737 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
738 text, (long)size, (long)size);
739 trace_strbuf(&trace_curl, &out);
741 for (i = 0; i < size; i += width) {
742 size_t w;
744 strbuf_reset(&out);
745 strbuf_addf(&out, "%s: ", text);
746 for (w = 0; (w < width) && (i + w < size); w++) {
747 unsigned char ch = ptr[i + w];
749 strbuf_addch(&out,
750 (ch >= 0x20) && (ch < 0x80)
751 ? ch : '.');
753 strbuf_addch(&out, '\n');
754 trace_strbuf(&trace_curl, &out);
756 strbuf_release(&out);
759 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
761 const char *text;
762 enum { NO_FILTER = 0, DO_FILTER = 1 };
764 switch (type) {
765 case CURLINFO_TEXT:
766 trace_printf_key(&trace_curl, "== Info: %s", data);
767 break;
768 case CURLINFO_HEADER_OUT:
769 text = "=> Send header";
770 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
771 break;
772 case CURLINFO_DATA_OUT:
773 if (trace_curl_data) {
774 text = "=> Send data";
775 curl_dump_data(text, (unsigned char *)data, size);
777 break;
778 case CURLINFO_SSL_DATA_OUT:
779 if (trace_curl_data) {
780 text = "=> Send SSL data";
781 curl_dump_data(text, (unsigned char *)data, size);
783 break;
784 case CURLINFO_HEADER_IN:
785 text = "<= Recv header";
786 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
787 break;
788 case CURLINFO_DATA_IN:
789 if (trace_curl_data) {
790 text = "<= Recv data";
791 curl_dump_data(text, (unsigned char *)data, size);
793 break;
794 case CURLINFO_SSL_DATA_IN:
795 if (trace_curl_data) {
796 text = "<= Recv SSL data";
797 curl_dump_data(text, (unsigned char *)data, size);
799 break;
801 default: /* we ignore unknown types by default */
802 return 0;
804 return 0;
807 void http_trace_curl_no_data(void)
809 trace_override_envvar(&trace_curl, "1");
810 trace_curl_data = 0;
813 void setup_curl_trace(CURL *handle)
815 if (!trace_want(&trace_curl))
816 return;
817 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
818 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
819 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
822 #ifdef CURLPROTO_HTTP
823 static long get_curl_allowed_protocols(int from_user)
825 long allowed_protocols = 0;
827 if (is_transport_allowed("http", from_user))
828 allowed_protocols |= CURLPROTO_HTTP;
829 if (is_transport_allowed("https", from_user))
830 allowed_protocols |= CURLPROTO_HTTPS;
831 if (is_transport_allowed("ftp", from_user))
832 allowed_protocols |= CURLPROTO_FTP;
833 if (is_transport_allowed("ftps", from_user))
834 allowed_protocols |= CURLPROTO_FTPS;
836 return allowed_protocols;
838 #endif
840 #if LIBCURL_VERSION_NUM >=0x072f00
841 static int get_curl_http_version_opt(const char *version_string, long *opt)
843 int i;
844 static struct {
845 const char *name;
846 long opt_token;
847 } choice[] = {
848 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
849 { "HTTP/2", CURL_HTTP_VERSION_2 }
852 for (i = 0; i < ARRAY_SIZE(choice); i++) {
853 if (!strcmp(version_string, choice[i].name)) {
854 *opt = choice[i].opt_token;
855 return 0;
859 warning("unknown value given to http.version: '%s'", version_string);
860 return -1; /* not found */
863 #endif
865 static CURL *get_curl_handle(void)
867 CURL *result = curl_easy_init();
869 if (!result)
870 die("curl_easy_init failed");
872 if (!curl_ssl_verify) {
873 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
874 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
875 } else {
876 /* Verify authenticity of the peer's certificate */
877 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
878 /* The name in the cert must match whom we tried to connect */
879 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
882 #if LIBCURL_VERSION_NUM >= 0x072f00 // 7.47.0
883 if (curl_http_version) {
884 long opt;
885 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
886 /* Set request use http version */
887 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
890 #endif
892 #if LIBCURL_VERSION_NUM >= 0x070907
893 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
894 #endif
895 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
896 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
897 #endif
899 #ifdef CURLGSSAPI_DELEGATION_FLAG
900 if (curl_deleg) {
901 int i;
902 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
903 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
904 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
905 curl_deleg_levels[i].curl_deleg_param);
906 break;
909 if (i == ARRAY_SIZE(curl_deleg_levels))
910 warning("Unknown delegation method '%s': using default",
911 curl_deleg);
913 #endif
915 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
916 !http_schannel_check_revoke) {
917 #if LIBCURL_VERSION_NUM >= 0x072c00
918 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
919 #else
920 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
921 #endif
924 if (http_proactive_auth)
925 init_curl_http_auth(result);
927 if (getenv("GIT_SSL_VERSION"))
928 ssl_version = getenv("GIT_SSL_VERSION");
929 if (ssl_version && *ssl_version) {
930 int i;
931 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
932 if (!strcmp(ssl_version, sslversions[i].name)) {
933 curl_easy_setopt(result, CURLOPT_SSLVERSION,
934 sslversions[i].ssl_version);
935 break;
938 if (i == ARRAY_SIZE(sslversions))
939 warning("unsupported ssl version %s: using default",
940 ssl_version);
943 if (getenv("GIT_SSL_CIPHER_LIST"))
944 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
945 if (ssl_cipherlist != NULL && *ssl_cipherlist)
946 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
947 ssl_cipherlist);
949 if (ssl_cert != NULL)
950 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
951 if (has_cert_password())
952 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
953 #if LIBCURL_VERSION_NUM >= 0x070903
954 if (ssl_key != NULL)
955 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
956 #endif
957 #if LIBCURL_VERSION_NUM >= 0x070908
958 if (ssl_capath != NULL)
959 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
960 #endif
961 #if LIBCURL_VERSION_NUM >= 0x072c00
962 if (ssl_pinnedkey != NULL)
963 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
964 #endif
965 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
966 !http_schannel_use_ssl_cainfo) {
967 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
968 #if LIBCURL_VERSION_NUM >= 0x073400
969 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
970 #endif
971 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
972 if (ssl_cainfo != NULL)
973 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
974 #if LIBCURL_VERSION_NUM >= 0x073400
975 if (http_proxy_ssl_ca_info != NULL)
976 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
977 #endif
980 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
981 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
982 curl_low_speed_limit);
983 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
984 curl_low_speed_time);
987 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
988 #if LIBCURL_VERSION_NUM >= 0x071301
989 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
990 #elif LIBCURL_VERSION_NUM >= 0x071101
991 curl_easy_setopt(result, CURLOPT_POST301, 1);
992 #endif
993 #ifdef CURLPROTO_HTTP
994 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
995 get_curl_allowed_protocols(0));
996 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
997 get_curl_allowed_protocols(-1));
998 #else
999 warning(_("Protocol restrictions not supported with cURL < 7.19.4"));
1000 #endif
1001 if (getenv("GIT_CURL_VERBOSE"))
1002 http_trace_curl_no_data();
1003 setup_curl_trace(result);
1004 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1005 trace_curl_data = 0;
1006 if (getenv("GIT_REDACT_COOKIES")) {
1007 string_list_split(&cookies_to_redact,
1008 getenv("GIT_REDACT_COOKIES"), ',', -1);
1009 string_list_sort(&cookies_to_redact);
1012 curl_easy_setopt(result, CURLOPT_USERAGENT,
1013 user_agent ? user_agent : git_user_agent());
1015 if (curl_ftp_no_epsv)
1016 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1018 #ifdef CURLOPT_USE_SSL
1019 if (curl_ssl_try)
1020 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1021 #endif
1024 * CURL also examines these variables as a fallback; but we need to query
1025 * them here in order to decide whether to prompt for missing password (cf.
1026 * init_curl_proxy_auth()).
1028 * Unlike many other common environment variables, these are historically
1029 * lowercase only. It appears that CURL did not know this and implemented
1030 * only uppercase variants, which was later corrected to take both - with
1031 * the exception of http_proxy, which is lowercase only also in CURL. As
1032 * the lowercase versions are the historical quasi-standard, they take
1033 * precedence here, as in CURL.
1035 if (!curl_http_proxy) {
1036 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1037 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1038 var_override(&curl_http_proxy, getenv("https_proxy"));
1039 } else {
1040 var_override(&curl_http_proxy, getenv("http_proxy"));
1042 if (!curl_http_proxy) {
1043 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1044 var_override(&curl_http_proxy, getenv("all_proxy"));
1048 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1050 * Handle case with the empty http.proxy value here to keep
1051 * common code clean.
1052 * NB: empty option disables proxying at all.
1054 curl_easy_setopt(result, CURLOPT_PROXY, "");
1055 } else if (curl_http_proxy) {
1056 #if LIBCURL_VERSION_NUM >= 0x071800
1057 if (starts_with(curl_http_proxy, "socks5h"))
1058 curl_easy_setopt(result,
1059 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1060 else if (starts_with(curl_http_proxy, "socks5"))
1061 curl_easy_setopt(result,
1062 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1063 else if (starts_with(curl_http_proxy, "socks4a"))
1064 curl_easy_setopt(result,
1065 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1066 else if (starts_with(curl_http_proxy, "socks"))
1067 curl_easy_setopt(result,
1068 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1069 #endif
1070 #if LIBCURL_VERSION_NUM >= 0x073400
1071 else if (starts_with(curl_http_proxy, "https")) {
1072 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1074 if (http_proxy_ssl_cert)
1075 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1077 if (http_proxy_ssl_key)
1078 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1080 if (has_proxy_cert_password())
1081 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1083 #endif
1084 if (strstr(curl_http_proxy, "://"))
1085 credential_from_url(&proxy_auth, curl_http_proxy);
1086 else {
1087 struct strbuf url = STRBUF_INIT;
1088 strbuf_addf(&url, "http://%s", curl_http_proxy);
1089 credential_from_url(&proxy_auth, url.buf);
1090 strbuf_release(&url);
1093 if (!proxy_auth.host)
1094 die("Invalid proxy URL '%s'", curl_http_proxy);
1096 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1097 #if LIBCURL_VERSION_NUM >= 0x071304
1098 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1099 var_override(&curl_no_proxy, getenv("no_proxy"));
1100 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1101 #endif
1103 init_curl_proxy_auth(result);
1105 set_curl_keepalive(result);
1107 return result;
1110 static void set_from_env(const char **var, const char *envname)
1112 const char *val = getenv(envname);
1113 if (val)
1114 *var = val;
1117 void http_init(struct remote *remote, const char *url, int proactive_auth)
1119 char *low_speed_limit;
1120 char *low_speed_time;
1121 char *normalized_url;
1122 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
1124 config.section = "http";
1125 config.key = NULL;
1126 config.collect_fn = http_options;
1127 config.cascade_fn = git_default_config;
1128 config.cb = NULL;
1130 http_is_verbose = 0;
1131 normalized_url = url_normalize(url, &config.url);
1133 git_config(urlmatch_config_entry, &config);
1134 free(normalized_url);
1135 string_list_clear(&config.vars, 1);
1137 #if LIBCURL_VERSION_NUM >= 0x073800
1138 if (http_ssl_backend) {
1139 const curl_ssl_backend **backends;
1140 struct strbuf buf = STRBUF_INIT;
1141 int i;
1143 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1144 case CURLSSLSET_UNKNOWN_BACKEND:
1145 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1146 "Supported SSL backends:"),
1147 http_ssl_backend);
1148 for (i = 0; backends[i]; i++)
1149 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1150 die("%s", buf.buf);
1151 case CURLSSLSET_NO_BACKENDS:
1152 die(_("Could not set SSL backend to '%s': "
1153 "cURL was built without SSL backends"),
1154 http_ssl_backend);
1155 case CURLSSLSET_TOO_LATE:
1156 die(_("Could not set SSL backend to '%s': already set"),
1157 http_ssl_backend);
1158 case CURLSSLSET_OK:
1159 break; /* Okay! */
1162 #endif
1164 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1165 die("curl_global_init failed");
1167 http_proactive_auth = proactive_auth;
1169 if (remote && remote->http_proxy)
1170 curl_http_proxy = xstrdup(remote->http_proxy);
1172 if (remote)
1173 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1175 pragma_header = curl_slist_append(http_copy_default_headers(),
1176 "Pragma: no-cache");
1177 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1178 "Pragma:");
1180 #ifdef USE_CURL_MULTI
1182 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1183 if (http_max_requests != NULL)
1184 max_requests = atoi(http_max_requests);
1187 curlm = curl_multi_init();
1188 if (!curlm)
1189 die("curl_multi_init failed");
1190 #endif
1192 if (getenv("GIT_SSL_NO_VERIFY"))
1193 curl_ssl_verify = 0;
1195 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1196 #if LIBCURL_VERSION_NUM >= 0x070903
1197 set_from_env(&ssl_key, "GIT_SSL_KEY");
1198 #endif
1199 #if LIBCURL_VERSION_NUM >= 0x070908
1200 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1201 #endif
1202 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1204 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1206 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1207 if (low_speed_limit != NULL)
1208 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1209 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1210 if (low_speed_time != NULL)
1211 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1213 if (curl_ssl_verify == -1)
1214 curl_ssl_verify = 1;
1216 curl_session_count = 0;
1217 #ifdef USE_CURL_MULTI
1218 if (max_requests < 1)
1219 max_requests = DEFAULT_MAX_REQUESTS;
1220 #endif
1222 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1223 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1224 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1226 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1227 proxy_ssl_cert_password_required = 1;
1229 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1230 curl_ftp_no_epsv = 1;
1232 if (url) {
1233 credential_from_url(&http_auth, url);
1234 if (!ssl_cert_password_required &&
1235 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1236 starts_with(url, "https://"))
1237 ssl_cert_password_required = 1;
1240 #ifndef NO_CURL_EASY_DUPHANDLE
1241 curl_default = get_curl_handle();
1242 #endif
1245 void http_cleanup(void)
1247 struct active_request_slot *slot = active_queue_head;
1249 while (slot != NULL) {
1250 struct active_request_slot *next = slot->next;
1251 if (slot->curl != NULL) {
1252 xmulti_remove_handle(slot);
1253 curl_easy_cleanup(slot->curl);
1255 free(slot);
1256 slot = next;
1258 active_queue_head = NULL;
1260 #ifndef NO_CURL_EASY_DUPHANDLE
1261 curl_easy_cleanup(curl_default);
1262 #endif
1264 #ifdef USE_CURL_MULTI
1265 curl_multi_cleanup(curlm);
1266 #endif
1267 curl_global_cleanup();
1269 string_list_clear(&extra_http_headers, 0);
1271 curl_slist_free_all(pragma_header);
1272 pragma_header = NULL;
1274 curl_slist_free_all(no_pragma_header);
1275 no_pragma_header = NULL;
1277 if (curl_http_proxy) {
1278 free((void *)curl_http_proxy);
1279 curl_http_proxy = NULL;
1282 if (proxy_auth.password) {
1283 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1284 FREE_AND_NULL(proxy_auth.password);
1287 free((void *)curl_proxyuserpwd);
1288 curl_proxyuserpwd = NULL;
1290 free((void *)http_proxy_authmethod);
1291 http_proxy_authmethod = NULL;
1293 if (cert_auth.password != NULL) {
1294 memset(cert_auth.password, 0, strlen(cert_auth.password));
1295 FREE_AND_NULL(cert_auth.password);
1297 ssl_cert_password_required = 0;
1299 if (proxy_cert_auth.password != NULL) {
1300 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1301 FREE_AND_NULL(proxy_cert_auth.password);
1303 proxy_ssl_cert_password_required = 0;
1305 FREE_AND_NULL(cached_accept_language);
1308 struct active_request_slot *get_active_slot(void)
1310 struct active_request_slot *slot = active_queue_head;
1311 struct active_request_slot *newslot;
1313 #ifdef USE_CURL_MULTI
1314 int num_transfers;
1316 /* Wait for a slot to open up if the queue is full */
1317 while (active_requests >= max_requests) {
1318 curl_multi_perform(curlm, &num_transfers);
1319 if (num_transfers < active_requests)
1320 process_curl_messages();
1322 #endif
1324 while (slot != NULL && slot->in_use)
1325 slot = slot->next;
1327 if (slot == NULL) {
1328 newslot = xmalloc(sizeof(*newslot));
1329 newslot->curl = NULL;
1330 newslot->in_use = 0;
1331 newslot->next = NULL;
1333 slot = active_queue_head;
1334 if (slot == NULL) {
1335 active_queue_head = newslot;
1336 } else {
1337 while (slot->next != NULL)
1338 slot = slot->next;
1339 slot->next = newslot;
1341 slot = newslot;
1344 if (slot->curl == NULL) {
1345 #ifdef NO_CURL_EASY_DUPHANDLE
1346 slot->curl = get_curl_handle();
1347 #else
1348 slot->curl = curl_easy_duphandle(curl_default);
1349 #endif
1350 curl_session_count++;
1353 active_requests++;
1354 slot->in_use = 1;
1355 slot->results = NULL;
1356 slot->finished = NULL;
1357 slot->callback_data = NULL;
1358 slot->callback_func = NULL;
1359 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1360 if (curl_save_cookies)
1361 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1362 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1363 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1364 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1365 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1366 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1367 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1368 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1369 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1370 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1371 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1374 * Default following to off unless "ALWAYS" is configured; this gives
1375 * callers a sane starting point, and they can tweak for individual
1376 * HTTP_FOLLOW_* cases themselves.
1378 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1379 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1380 else
1381 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1383 #if LIBCURL_VERSION_NUM >= 0x070a08
1384 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1385 #endif
1386 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1387 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1388 #endif
1389 if (http_auth.password || curl_empty_auth_enabled())
1390 init_curl_http_auth(slot->curl);
1392 return slot;
1395 int start_active_slot(struct active_request_slot *slot)
1397 #ifdef USE_CURL_MULTI
1398 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1399 int num_transfers;
1401 if (curlm_result != CURLM_OK &&
1402 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1403 warning("curl_multi_add_handle failed: %s",
1404 curl_multi_strerror(curlm_result));
1405 active_requests--;
1406 slot->in_use = 0;
1407 return 0;
1411 * We know there must be something to do, since we just added
1412 * something.
1414 curl_multi_perform(curlm, &num_transfers);
1415 #endif
1416 return 1;
1419 #ifdef USE_CURL_MULTI
1420 struct fill_chain {
1421 void *data;
1422 int (*fill)(void *);
1423 struct fill_chain *next;
1426 static struct fill_chain *fill_cfg;
1428 void add_fill_function(void *data, int (*fill)(void *))
1430 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1431 struct fill_chain **linkp = &fill_cfg;
1432 new_fill->data = data;
1433 new_fill->fill = fill;
1434 new_fill->next = NULL;
1435 while (*linkp)
1436 linkp = &(*linkp)->next;
1437 *linkp = new_fill;
1440 void fill_active_slots(void)
1442 struct active_request_slot *slot = active_queue_head;
1444 while (active_requests < max_requests) {
1445 struct fill_chain *fill;
1446 for (fill = fill_cfg; fill; fill = fill->next)
1447 if (fill->fill(fill->data))
1448 break;
1450 if (!fill)
1451 break;
1454 while (slot != NULL) {
1455 if (!slot->in_use && slot->curl != NULL
1456 && curl_session_count > min_curl_sessions) {
1457 curl_easy_cleanup(slot->curl);
1458 slot->curl = NULL;
1459 curl_session_count--;
1461 slot = slot->next;
1465 void step_active_slots(void)
1467 int num_transfers;
1468 CURLMcode curlm_result;
1470 do {
1471 curlm_result = curl_multi_perform(curlm, &num_transfers);
1472 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1473 if (num_transfers < active_requests) {
1474 process_curl_messages();
1475 fill_active_slots();
1478 #endif
1480 void run_active_slot(struct active_request_slot *slot)
1482 #ifdef USE_CURL_MULTI
1483 fd_set readfds;
1484 fd_set writefds;
1485 fd_set excfds;
1486 int max_fd;
1487 struct timeval select_timeout;
1488 int finished = 0;
1490 slot->finished = &finished;
1491 while (!finished) {
1492 step_active_slots();
1494 if (slot->in_use) {
1495 #if LIBCURL_VERSION_NUM >= 0x070f04
1496 long curl_timeout;
1497 curl_multi_timeout(curlm, &curl_timeout);
1498 if (curl_timeout == 0) {
1499 continue;
1500 } else if (curl_timeout == -1) {
1501 select_timeout.tv_sec = 0;
1502 select_timeout.tv_usec = 50000;
1503 } else {
1504 select_timeout.tv_sec = curl_timeout / 1000;
1505 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1507 #else
1508 select_timeout.tv_sec = 0;
1509 select_timeout.tv_usec = 50000;
1510 #endif
1512 max_fd = -1;
1513 FD_ZERO(&readfds);
1514 FD_ZERO(&writefds);
1515 FD_ZERO(&excfds);
1516 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1519 * It can happen that curl_multi_timeout returns a pathologically
1520 * long timeout when curl_multi_fdset returns no file descriptors
1521 * to read. See commit message for more details.
1523 if (max_fd < 0 &&
1524 (select_timeout.tv_sec > 0 ||
1525 select_timeout.tv_usec > 50000)) {
1526 select_timeout.tv_sec = 0;
1527 select_timeout.tv_usec = 50000;
1530 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1533 #else
1534 while (slot->in_use) {
1535 slot->curl_result = curl_easy_perform(slot->curl);
1536 finish_active_slot(slot);
1538 #endif
1541 static void release_active_slot(struct active_request_slot *slot)
1543 closedown_active_slot(slot);
1544 if (slot->curl) {
1545 xmulti_remove_handle(slot);
1546 if (curl_session_count > min_curl_sessions) {
1547 curl_easy_cleanup(slot->curl);
1548 slot->curl = NULL;
1549 curl_session_count--;
1552 #ifdef USE_CURL_MULTI
1553 fill_active_slots();
1554 #endif
1557 void finish_all_active_slots(void)
1559 struct active_request_slot *slot = active_queue_head;
1561 while (slot != NULL)
1562 if (slot->in_use) {
1563 run_active_slot(slot);
1564 slot = active_queue_head;
1565 } else {
1566 slot = slot->next;
1570 /* Helpers for modifying and creating URLs */
1571 static inline int needs_quote(int ch)
1573 if (((ch >= 'A') && (ch <= 'Z'))
1574 || ((ch >= 'a') && (ch <= 'z'))
1575 || ((ch >= '0') && (ch <= '9'))
1576 || (ch == '/')
1577 || (ch == '-')
1578 || (ch == '.'))
1579 return 0;
1580 return 1;
1583 static char *quote_ref_url(const char *base, const char *ref)
1585 struct strbuf buf = STRBUF_INIT;
1586 const char *cp;
1587 int ch;
1589 end_url_with_slash(&buf, base);
1591 for (cp = ref; (ch = *cp) != 0; cp++)
1592 if (needs_quote(ch))
1593 strbuf_addf(&buf, "%%%02x", ch);
1594 else
1595 strbuf_addch(&buf, *cp);
1597 return strbuf_detach(&buf, NULL);
1600 void append_remote_object_url(struct strbuf *buf, const char *url,
1601 const char *hex,
1602 int only_two_digit_prefix)
1604 end_url_with_slash(buf, url);
1606 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1607 if (!only_two_digit_prefix)
1608 strbuf_addstr(buf, hex + 2);
1611 char *get_remote_object_url(const char *url, const char *hex,
1612 int only_two_digit_prefix)
1614 struct strbuf buf = STRBUF_INIT;
1615 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1616 return strbuf_detach(&buf, NULL);
1619 void normalize_curl_result(CURLcode *result, long http_code,
1620 char *errorstr, size_t errorlen)
1623 * If we see a failing http code with CURLE_OK, we have turned off
1624 * FAILONERROR (to keep the server's custom error response), and should
1625 * translate the code into failure here.
1627 * Likewise, if we see a redirect (30x code), that means we turned off
1628 * redirect-following, and we should treat the result as an error.
1630 if (*result == CURLE_OK && http_code >= 300) {
1631 *result = CURLE_HTTP_RETURNED_ERROR;
1633 * Normally curl will already have put the "reason phrase"
1634 * from the server into curl_errorstr; unfortunately without
1635 * FAILONERROR it is lost, so we can give only the numeric
1636 * status code.
1638 xsnprintf(errorstr, errorlen,
1639 "The requested URL returned error: %ld",
1640 http_code);
1644 static int handle_curl_result(struct slot_results *results)
1646 normalize_curl_result(&results->curl_result, results->http_code,
1647 curl_errorstr, sizeof(curl_errorstr));
1649 if (results->curl_result == CURLE_OK) {
1650 credential_approve(&http_auth);
1651 if (proxy_auth.password)
1652 credential_approve(&proxy_auth);
1653 return HTTP_OK;
1654 } else if (missing_target(results))
1655 return HTTP_MISSING_TARGET;
1656 else if (results->http_code == 401) {
1657 if (http_auth.username && http_auth.password) {
1658 credential_reject(&http_auth);
1659 return HTTP_NOAUTH;
1660 } else {
1661 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1662 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1663 if (results->auth_avail) {
1664 http_auth_methods &= results->auth_avail;
1665 http_auth_methods_restricted = 1;
1667 #endif
1668 return HTTP_REAUTH;
1670 } else {
1671 if (results->http_connectcode == 407)
1672 credential_reject(&proxy_auth);
1673 #if LIBCURL_VERSION_NUM >= 0x070c00
1674 if (!curl_errorstr[0])
1675 strlcpy(curl_errorstr,
1676 curl_easy_strerror(results->curl_result),
1677 sizeof(curl_errorstr));
1678 #endif
1679 return HTTP_ERROR;
1683 int run_one_slot(struct active_request_slot *slot,
1684 struct slot_results *results)
1686 slot->results = results;
1687 if (!start_active_slot(slot)) {
1688 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1689 "failed to start HTTP request");
1690 return HTTP_START_FAILED;
1693 run_active_slot(slot);
1694 return handle_curl_result(results);
1697 struct curl_slist *http_copy_default_headers(void)
1699 struct curl_slist *headers = NULL;
1700 const struct string_list_item *item;
1702 for_each_string_list_item(item, &extra_http_headers)
1703 headers = curl_slist_append(headers, item->string);
1705 return headers;
1708 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1710 char *ptr;
1711 CURLcode ret;
1713 strbuf_reset(buf);
1714 ret = curl_easy_getinfo(curl, info, &ptr);
1715 if (!ret && ptr)
1716 strbuf_addstr(buf, ptr);
1717 return ret;
1721 * Check for and extract a content-type parameter. "raw"
1722 * should be positioned at the start of the potential
1723 * parameter, with any whitespace already removed.
1725 * "name" is the name of the parameter. The value is appended
1726 * to "out".
1728 static int extract_param(const char *raw, const char *name,
1729 struct strbuf *out)
1731 size_t len = strlen(name);
1733 if (strncasecmp(raw, name, len))
1734 return -1;
1735 raw += len;
1737 if (*raw != '=')
1738 return -1;
1739 raw++;
1741 while (*raw && !isspace(*raw) && *raw != ';')
1742 strbuf_addch(out, *raw++);
1743 return 0;
1747 * Extract a normalized version of the content type, with any
1748 * spaces suppressed, all letters lowercased, and no trailing ";"
1749 * or parameters.
1751 * Note that we will silently remove even invalid whitespace. For
1752 * example, "text / plain" is specifically forbidden by RFC 2616,
1753 * but "text/plain" is the only reasonable output, and this keeps
1754 * our code simple.
1756 * If the "charset" argument is not NULL, store the value of any
1757 * charset parameter there.
1759 * Example:
1760 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1761 * "text / plain" -> "text/plain"
1763 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1764 struct strbuf *charset)
1766 const char *p;
1768 strbuf_reset(type);
1769 strbuf_grow(type, raw->len);
1770 for (p = raw->buf; *p; p++) {
1771 if (isspace(*p))
1772 continue;
1773 if (*p == ';') {
1774 p++;
1775 break;
1777 strbuf_addch(type, tolower(*p));
1780 if (!charset)
1781 return;
1783 strbuf_reset(charset);
1784 while (*p) {
1785 while (isspace(*p) || *p == ';')
1786 p++;
1787 if (!extract_param(p, "charset", charset))
1788 return;
1789 while (*p && !isspace(*p))
1790 p++;
1793 if (!charset->len && starts_with(type->buf, "text/"))
1794 strbuf_addstr(charset, "ISO-8859-1");
1797 static void write_accept_language(struct strbuf *buf)
1800 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1801 * that, q-value will be smaller than 0.001, the minimum q-value the
1802 * HTTP specification allows. See
1803 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1805 const int MAX_DECIMAL_PLACES = 3;
1806 const int MAX_LANGUAGE_TAGS = 1000;
1807 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1808 char **language_tags = NULL;
1809 int num_langs = 0;
1810 const char *s = get_preferred_languages();
1811 int i;
1812 struct strbuf tag = STRBUF_INIT;
1814 /* Don't add Accept-Language header if no language is preferred. */
1815 if (!s)
1816 return;
1819 * Split the colon-separated string of preferred languages into
1820 * language_tags array.
1822 do {
1823 /* collect language tag */
1824 for (; *s && (isalnum(*s) || *s == '_'); s++)
1825 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1827 /* skip .codeset, @modifier and any other unnecessary parts */
1828 while (*s && *s != ':')
1829 s++;
1831 if (tag.len) {
1832 num_langs++;
1833 REALLOC_ARRAY(language_tags, num_langs);
1834 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1835 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1836 break;
1838 } while (*s++);
1840 /* write Accept-Language header into buf */
1841 if (num_langs) {
1842 int last_buf_len = 0;
1843 int max_q;
1844 int decimal_places;
1845 char q_format[32];
1847 /* add '*' */
1848 REALLOC_ARRAY(language_tags, num_langs + 1);
1849 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1851 /* compute decimal_places */
1852 for (max_q = 1, decimal_places = 0;
1853 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1854 decimal_places++, max_q *= 10)
1857 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1859 strbuf_addstr(buf, "Accept-Language: ");
1861 for (i = 0; i < num_langs; i++) {
1862 if (i > 0)
1863 strbuf_addstr(buf, ", ");
1865 strbuf_addstr(buf, language_tags[i]);
1867 if (i > 0)
1868 strbuf_addf(buf, q_format, max_q - i);
1870 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1871 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1872 break;
1875 last_buf_len = buf->len;
1879 /* free language tags -- last one is a static '*' */
1880 for (i = 0; i < num_langs - 1; i++)
1881 free(language_tags[i]);
1882 free(language_tags);
1886 * Get an Accept-Language header which indicates user's preferred languages.
1888 * Examples:
1889 * LANGUAGE= -> ""
1890 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1891 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1892 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1893 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1894 * LANGUAGE= LANG=C -> ""
1896 static const char *get_accept_language(void)
1898 if (!cached_accept_language) {
1899 struct strbuf buf = STRBUF_INIT;
1900 write_accept_language(&buf);
1901 if (buf.len > 0)
1902 cached_accept_language = strbuf_detach(&buf, NULL);
1905 return cached_accept_language;
1908 static void http_opt_request_remainder(CURL *curl, off_t pos)
1910 char buf[128];
1911 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1912 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1915 /* http_request() targets */
1916 #define HTTP_REQUEST_STRBUF 0
1917 #define HTTP_REQUEST_FILE 1
1919 static int http_request(const char *url,
1920 void *result, int target,
1921 const struct http_get_options *options)
1923 struct active_request_slot *slot;
1924 struct slot_results results;
1925 struct curl_slist *headers = http_copy_default_headers();
1926 struct strbuf buf = STRBUF_INIT;
1927 const char *accept_language;
1928 int ret;
1930 slot = get_active_slot();
1931 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1933 if (result == NULL) {
1934 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1935 } else {
1936 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1937 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1939 if (target == HTTP_REQUEST_FILE) {
1940 off_t posn = ftello(result);
1941 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1942 fwrite);
1943 if (posn > 0)
1944 http_opt_request_remainder(slot->curl, posn);
1945 } else
1946 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1947 fwrite_buffer);
1950 accept_language = get_accept_language();
1952 if (accept_language)
1953 headers = curl_slist_append(headers, accept_language);
1955 strbuf_addstr(&buf, "Pragma:");
1956 if (options && options->no_cache)
1957 strbuf_addstr(&buf, " no-cache");
1958 if (options && options->initial_request &&
1959 http_follow_config == HTTP_FOLLOW_INITIAL)
1960 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1962 headers = curl_slist_append(headers, buf.buf);
1964 /* Add additional headers here */
1965 if (options && options->extra_headers) {
1966 const struct string_list_item *item;
1967 for_each_string_list_item(item, options->extra_headers) {
1968 headers = curl_slist_append(headers, item->string);
1972 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1973 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1974 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1975 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1977 ret = run_one_slot(slot, &results);
1979 if (options && options->content_type) {
1980 struct strbuf raw = STRBUF_INIT;
1981 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1982 extract_content_type(&raw, options->content_type,
1983 options->charset);
1984 strbuf_release(&raw);
1987 if (options && options->effective_url)
1988 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1989 options->effective_url);
1991 curl_slist_free_all(headers);
1992 strbuf_release(&buf);
1994 return ret;
1998 * Update the "base" url to a more appropriate value, as deduced by
1999 * redirects seen when requesting a URL starting with "url".
2001 * The "asked" parameter is a URL that we asked curl to access, and must begin
2002 * with "base".
2004 * The "got" parameter is the URL that curl reported to us as where we ended
2005 * up.
2007 * Returns 1 if we updated the base url, 0 otherwise.
2009 * Our basic strategy is to compare "base" and "asked" to find the bits
2010 * specific to our request. We then strip those bits off of "got" to yield the
2011 * new base. So for example, if our base is "http://example.com/foo.git",
2012 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2013 * with "https://other.example.com/foo.git/info/refs". We would want the
2014 * new URL to become "https://other.example.com/foo.git".
2016 * Note that this assumes a sane redirect scheme. It's entirely possible
2017 * in the example above to end up at a URL that does not even end in
2018 * "info/refs". In such a case we die. There's not much we can do, such a
2019 * scheme is unlikely to represent a real git repository, and failing to
2020 * rewrite the base opens options for malicious redirects to do funny things.
2022 static int update_url_from_redirect(struct strbuf *base,
2023 const char *asked,
2024 const struct strbuf *got)
2026 const char *tail;
2027 size_t new_len;
2029 if (!strcmp(asked, got->buf))
2030 return 0;
2032 if (!skip_prefix(asked, base->buf, &tail))
2033 BUG("update_url_from_redirect: %s is not a superset of %s",
2034 asked, base->buf);
2036 new_len = got->len;
2037 if (!strip_suffix_mem(got->buf, &new_len, tail))
2038 die(_("unable to update url base from redirection:\n"
2039 " asked for: %s\n"
2040 " redirect: %s"),
2041 asked, got->buf);
2043 strbuf_reset(base);
2044 strbuf_add(base, got->buf, new_len);
2046 return 1;
2049 static int http_request_reauth(const char *url,
2050 void *result, int target,
2051 struct http_get_options *options)
2053 int ret = http_request(url, result, target, options);
2055 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2056 return ret;
2058 if (options && options->effective_url && options->base_url) {
2059 if (update_url_from_redirect(options->base_url,
2060 url, options->effective_url)) {
2061 credential_from_url(&http_auth, options->base_url->buf);
2062 url = options->effective_url->buf;
2066 if (ret != HTTP_REAUTH)
2067 return ret;
2070 * The previous request may have put cruft into our output stream; we
2071 * should clear it out before making our next request.
2073 switch (target) {
2074 case HTTP_REQUEST_STRBUF:
2075 strbuf_reset(result);
2076 break;
2077 case HTTP_REQUEST_FILE:
2078 if (fflush(result)) {
2079 error_errno("unable to flush a file");
2080 return HTTP_START_FAILED;
2082 rewind(result);
2083 if (ftruncate(fileno(result), 0) < 0) {
2084 error_errno("unable to truncate a file");
2085 return HTTP_START_FAILED;
2087 break;
2088 default:
2089 BUG("Unknown http_request target");
2092 credential_fill(&http_auth);
2094 return http_request(url, result, target, options);
2097 int http_get_strbuf(const char *url,
2098 struct strbuf *result,
2099 struct http_get_options *options)
2101 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2105 * Downloads a URL and stores the result in the given file.
2107 * If a previous interrupted download is detected (i.e. a previous temporary
2108 * file is still around) the download is resumed.
2110 static int http_get_file(const char *url, const char *filename,
2111 struct http_get_options *options)
2113 int ret;
2114 struct strbuf tmpfile = STRBUF_INIT;
2115 FILE *result;
2117 strbuf_addf(&tmpfile, "%s.temp", filename);
2118 result = fopen(tmpfile.buf, "a");
2119 if (!result) {
2120 error("Unable to open local file %s", tmpfile.buf);
2121 ret = HTTP_ERROR;
2122 goto cleanup;
2125 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2126 fclose(result);
2128 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2129 ret = HTTP_ERROR;
2130 cleanup:
2131 strbuf_release(&tmpfile);
2132 return ret;
2135 int http_fetch_ref(const char *base, struct ref *ref)
2137 struct http_get_options options = {0};
2138 char *url;
2139 struct strbuf buffer = STRBUF_INIT;
2140 int ret = -1;
2142 options.no_cache = 1;
2144 url = quote_ref_url(base, ref->name);
2145 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2146 strbuf_rtrim(&buffer);
2147 if (buffer.len == the_hash_algo->hexsz)
2148 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2149 else if (starts_with(buffer.buf, "ref: ")) {
2150 ref->symref = xstrdup(buffer.buf + 5);
2151 ret = 0;
2155 strbuf_release(&buffer);
2156 free(url);
2157 return ret;
2160 /* Helpers for fetching packs */
2161 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2163 char *url, *tmp;
2164 struct strbuf buf = STRBUF_INIT;
2166 if (http_is_verbose)
2167 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2169 end_url_with_slash(&buf, base_url);
2170 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2171 url = strbuf_detach(&buf, NULL);
2173 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2174 tmp = strbuf_detach(&buf, NULL);
2176 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2177 error("Unable to get pack index %s", url);
2178 FREE_AND_NULL(tmp);
2181 free(url);
2182 return tmp;
2185 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2186 unsigned char *sha1, const char *base_url)
2188 struct packed_git *new_pack;
2189 char *tmp_idx = NULL;
2190 int ret;
2192 if (has_pack_index(sha1)) {
2193 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2194 if (!new_pack)
2195 return -1; /* parse_pack_index() already issued error message */
2196 goto add_pack;
2199 tmp_idx = fetch_pack_index(sha1, base_url);
2200 if (!tmp_idx)
2201 return -1;
2203 new_pack = parse_pack_index(sha1, tmp_idx);
2204 if (!new_pack) {
2205 unlink(tmp_idx);
2206 free(tmp_idx);
2208 return -1; /* parse_pack_index() already issued error message */
2211 ret = verify_pack_index(new_pack);
2212 if (!ret) {
2213 close_pack_index(new_pack);
2214 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2216 free(tmp_idx);
2217 if (ret)
2218 return -1;
2220 add_pack:
2221 new_pack->next = *packs_head;
2222 *packs_head = new_pack;
2223 return 0;
2226 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2228 struct http_get_options options = {0};
2229 int ret = 0;
2230 char *url;
2231 const char *data;
2232 struct strbuf buf = STRBUF_INIT;
2233 struct object_id oid;
2235 end_url_with_slash(&buf, base_url);
2236 strbuf_addstr(&buf, "objects/info/packs");
2237 url = strbuf_detach(&buf, NULL);
2239 options.no_cache = 1;
2240 ret = http_get_strbuf(url, &buf, &options);
2241 if (ret != HTTP_OK)
2242 goto cleanup;
2244 data = buf.buf;
2245 while (*data) {
2246 if (skip_prefix(data, "P pack-", &data) &&
2247 !parse_oid_hex(data, &oid, &data) &&
2248 skip_prefix(data, ".pack", &data) &&
2249 (*data == '\n' || *data == '\0')) {
2250 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2251 } else {
2252 data = strchrnul(data, '\n');
2254 if (*data)
2255 data++; /* skip past newline */
2258 cleanup:
2259 free(url);
2260 return ret;
2263 void release_http_pack_request(struct http_pack_request *preq)
2265 if (preq->packfile != NULL) {
2266 fclose(preq->packfile);
2267 preq->packfile = NULL;
2269 preq->slot = NULL;
2270 strbuf_release(&preq->tmpfile);
2271 free(preq->url);
2272 free(preq);
2275 int finish_http_pack_request(struct http_pack_request *preq)
2277 struct packed_git **lst;
2278 struct packed_git *p = preq->target;
2279 char *tmp_idx;
2280 size_t len;
2281 struct child_process ip = CHILD_PROCESS_INIT;
2283 close_pack_index(p);
2285 fclose(preq->packfile);
2286 preq->packfile = NULL;
2288 lst = preq->lst;
2289 while (*lst != p)
2290 lst = &((*lst)->next);
2291 *lst = (*lst)->next;
2293 if (!strip_suffix(preq->tmpfile.buf, ".pack.temp", &len))
2294 BUG("pack tmpfile does not end in .pack.temp?");
2295 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile.buf);
2297 argv_array_push(&ip.args, "index-pack");
2298 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2299 argv_array_push(&ip.args, preq->tmpfile.buf);
2300 ip.git_cmd = 1;
2301 ip.no_stdin = 1;
2302 ip.no_stdout = 1;
2304 if (run_command(&ip)) {
2305 unlink(preq->tmpfile.buf);
2306 unlink(tmp_idx);
2307 free(tmp_idx);
2308 return -1;
2311 unlink(sha1_pack_index_name(p->hash));
2313 if (finalize_object_file(preq->tmpfile.buf, sha1_pack_name(p->hash))
2314 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->hash))) {
2315 free(tmp_idx);
2316 return -1;
2319 install_packed_git(the_repository, p);
2320 free(tmp_idx);
2321 return 0;
2324 struct http_pack_request *new_http_pack_request(
2325 struct packed_git *target, const char *base_url)
2327 off_t prev_posn = 0;
2328 struct strbuf buf = STRBUF_INIT;
2329 struct http_pack_request *preq;
2331 preq = xcalloc(1, sizeof(*preq));
2332 strbuf_init(&preq->tmpfile, 0);
2333 preq->target = target;
2335 end_url_with_slash(&buf, base_url);
2336 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2337 hash_to_hex(target->hash));
2338 preq->url = strbuf_detach(&buf, NULL);
2340 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(target->hash));
2341 preq->packfile = fopen(preq->tmpfile.buf, "a");
2342 if (!preq->packfile) {
2343 error("Unable to open local file %s for pack",
2344 preq->tmpfile.buf);
2345 goto abort;
2348 preq->slot = get_active_slot();
2349 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2350 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2351 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2352 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2353 no_pragma_header);
2356 * If there is data present from a previous transfer attempt,
2357 * resume where it left off
2359 prev_posn = ftello(preq->packfile);
2360 if (prev_posn>0) {
2361 if (http_is_verbose)
2362 fprintf(stderr,
2363 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2364 hash_to_hex(target->hash),
2365 (uintmax_t)prev_posn);
2366 http_opt_request_remainder(preq->slot->curl, prev_posn);
2369 return preq;
2371 abort:
2372 strbuf_release(&preq->tmpfile);
2373 free(preq->url);
2374 free(preq);
2375 return NULL;
2378 /* Helpers for fetching objects (loose) */
2379 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2380 void *data)
2382 unsigned char expn[4096];
2383 size_t size = eltsize * nmemb;
2384 int posn = 0;
2385 struct http_object_request *freq = data;
2386 struct active_request_slot *slot = freq->slot;
2388 if (slot) {
2389 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2390 &slot->http_code);
2391 if (c != CURLE_OK)
2392 BUG("curl_easy_getinfo for HTTP code failed: %s",
2393 curl_easy_strerror(c));
2394 if (slot->http_code >= 300)
2395 return nmemb;
2398 do {
2399 ssize_t retval = xwrite(freq->localfile,
2400 (char *) ptr + posn, size - posn);
2401 if (retval < 0)
2402 return posn / eltsize;
2403 posn += retval;
2404 } while (posn < size);
2406 freq->stream.avail_in = size;
2407 freq->stream.next_in = (void *)ptr;
2408 do {
2409 freq->stream.next_out = expn;
2410 freq->stream.avail_out = sizeof(expn);
2411 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2412 the_hash_algo->update_fn(&freq->c, expn,
2413 sizeof(expn) - freq->stream.avail_out);
2414 } while (freq->stream.avail_in && freq->zret == Z_OK);
2415 return nmemb;
2418 struct http_object_request *new_http_object_request(const char *base_url,
2419 const struct object_id *oid)
2421 char *hex = oid_to_hex(oid);
2422 struct strbuf filename = STRBUF_INIT;
2423 struct strbuf prevfile = STRBUF_INIT;
2424 int prevlocal;
2425 char prev_buf[PREV_BUF_SIZE];
2426 ssize_t prev_read = 0;
2427 off_t prev_posn = 0;
2428 struct http_object_request *freq;
2430 freq = xcalloc(1, sizeof(*freq));
2431 strbuf_init(&freq->tmpfile, 0);
2432 oidcpy(&freq->oid, oid);
2433 freq->localfile = -1;
2435 loose_object_path(the_repository, &filename, oid);
2436 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2438 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2439 unlink_or_warn(prevfile.buf);
2440 rename(freq->tmpfile.buf, prevfile.buf);
2441 unlink_or_warn(freq->tmpfile.buf);
2442 strbuf_release(&filename);
2444 if (freq->localfile != -1)
2445 error("fd leakage in start: %d", freq->localfile);
2446 freq->localfile = open(freq->tmpfile.buf,
2447 O_WRONLY | O_CREAT | O_EXCL, 0666);
2449 * This could have failed due to the "lazy directory creation";
2450 * try to mkdir the last path component.
2452 if (freq->localfile < 0 && errno == ENOENT) {
2453 char *dir = strrchr(freq->tmpfile.buf, '/');
2454 if (dir) {
2455 *dir = 0;
2456 mkdir(freq->tmpfile.buf, 0777);
2457 *dir = '/';
2459 freq->localfile = open(freq->tmpfile.buf,
2460 O_WRONLY | O_CREAT | O_EXCL, 0666);
2463 if (freq->localfile < 0) {
2464 error_errno("Couldn't create temporary file %s",
2465 freq->tmpfile.buf);
2466 goto abort;
2469 git_inflate_init(&freq->stream);
2471 the_hash_algo->init_fn(&freq->c);
2473 freq->url = get_remote_object_url(base_url, hex, 0);
2476 * If a previous temp file is present, process what was already
2477 * fetched.
2479 prevlocal = open(prevfile.buf, O_RDONLY);
2480 if (prevlocal != -1) {
2481 do {
2482 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2483 if (prev_read>0) {
2484 if (fwrite_sha1_file(prev_buf,
2486 prev_read,
2487 freq) == prev_read) {
2488 prev_posn += prev_read;
2489 } else {
2490 prev_read = -1;
2493 } while (prev_read > 0);
2494 close(prevlocal);
2496 unlink_or_warn(prevfile.buf);
2497 strbuf_release(&prevfile);
2500 * Reset inflate/SHA1 if there was an error reading the previous temp
2501 * file; also rewind to the beginning of the local file.
2503 if (prev_read == -1) {
2504 memset(&freq->stream, 0, sizeof(freq->stream));
2505 git_inflate_init(&freq->stream);
2506 the_hash_algo->init_fn(&freq->c);
2507 if (prev_posn>0) {
2508 prev_posn = 0;
2509 lseek(freq->localfile, 0, SEEK_SET);
2510 if (ftruncate(freq->localfile, 0) < 0) {
2511 error_errno("Couldn't truncate temporary file %s",
2512 freq->tmpfile.buf);
2513 goto abort;
2518 freq->slot = get_active_slot();
2520 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2521 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2522 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2523 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2524 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2525 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2528 * If we have successfully processed data from a previous fetch
2529 * attempt, only fetch the data we don't already have.
2531 if (prev_posn>0) {
2532 if (http_is_verbose)
2533 fprintf(stderr,
2534 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2535 hex, (uintmax_t)prev_posn);
2536 http_opt_request_remainder(freq->slot->curl, prev_posn);
2539 return freq;
2541 abort:
2542 strbuf_release(&prevfile);
2543 free(freq->url);
2544 free(freq);
2545 return NULL;
2548 void process_http_object_request(struct http_object_request *freq)
2550 if (freq->slot == NULL)
2551 return;
2552 freq->curl_result = freq->slot->curl_result;
2553 freq->http_code = freq->slot->http_code;
2554 freq->slot = NULL;
2557 int finish_http_object_request(struct http_object_request *freq)
2559 struct stat st;
2560 struct strbuf filename = STRBUF_INIT;
2562 close(freq->localfile);
2563 freq->localfile = -1;
2565 process_http_object_request(freq);
2567 if (freq->http_code == 416) {
2568 warning("requested range invalid; we may already have all the data.");
2569 } else if (freq->curl_result != CURLE_OK) {
2570 if (stat(freq->tmpfile.buf, &st) == 0)
2571 if (st.st_size == 0)
2572 unlink_or_warn(freq->tmpfile.buf);
2573 return -1;
2576 git_inflate_end(&freq->stream);
2577 the_hash_algo->final_fn(freq->real_oid.hash, &freq->c);
2578 if (freq->zret != Z_STREAM_END) {
2579 unlink_or_warn(freq->tmpfile.buf);
2580 return -1;
2582 if (!oideq(&freq->oid, &freq->real_oid)) {
2583 unlink_or_warn(freq->tmpfile.buf);
2584 return -1;
2586 loose_object_path(the_repository, &filename, &freq->oid);
2587 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2588 strbuf_release(&filename);
2590 return freq->rename;
2593 void abort_http_object_request(struct http_object_request *freq)
2595 unlink_or_warn(freq->tmpfile.buf);
2597 release_http_object_request(freq);
2600 void release_http_object_request(struct http_object_request *freq)
2602 if (freq->localfile != -1) {
2603 close(freq->localfile);
2604 freq->localfile = -1;
2606 FREE_AND_NULL(freq->url);
2607 if (freq->slot != NULL) {
2608 freq->slot->callback_func = NULL;
2609 freq->slot->callback_data = NULL;
2610 release_active_slot(freq->slot);
2611 freq->slot = NULL;
2613 strbuf_release(&freq->tmpfile);