Git 2.21.3
[git.git] / http.c
blob2b8136275af6d1dea4d5d09b5861c6b4048989e1
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;
89 static struct {
90 const char *name;
91 long curlauth_param;
92 } proxy_authmethods[] = {
93 { "basic", CURLAUTH_BASIC },
94 { "digest", CURLAUTH_DIGEST },
95 { "negotiate", CURLAUTH_GSSNEGOTIATE },
96 { "ntlm", CURLAUTH_NTLM },
97 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
98 { "anyauth", CURLAUTH_ANY },
99 #endif
101 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
102 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
103 * here, too
106 #ifdef CURLGSSAPI_DELEGATION_FLAG
107 static const char *curl_deleg;
108 static struct {
109 const char *name;
110 long curl_deleg_param;
111 } curl_deleg_levels[] = {
112 { "none", CURLGSSAPI_DELEGATION_NONE },
113 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
114 { "always", CURLGSSAPI_DELEGATION_FLAG },
116 #endif
118 static struct credential proxy_auth = CREDENTIAL_INIT;
119 static const char *curl_proxyuserpwd;
120 static const char *curl_cookie_file;
121 static int curl_save_cookies;
122 struct credential http_auth = CREDENTIAL_INIT;
123 static int http_proactive_auth;
124 static const char *user_agent;
125 static int curl_empty_auth = -1;
127 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
129 #if LIBCURL_VERSION_NUM >= 0x071700
130 /* Use CURLOPT_KEYPASSWD as is */
131 #elif LIBCURL_VERSION_NUM >= 0x070903
132 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
133 #else
134 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
135 #endif
137 static struct credential cert_auth = CREDENTIAL_INIT;
138 static int ssl_cert_password_required;
139 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
140 static unsigned long http_auth_methods = CURLAUTH_ANY;
141 static int http_auth_methods_restricted;
142 /* Modes for which empty_auth cannot actually help us. */
143 static unsigned long empty_auth_useless =
144 CURLAUTH_BASIC
145 #ifdef CURLAUTH_DIGEST_IE
146 | CURLAUTH_DIGEST_IE
147 #endif
148 | CURLAUTH_DIGEST;
149 #endif
151 static struct curl_slist *pragma_header;
152 static struct curl_slist *no_pragma_header;
153 static struct curl_slist *extra_http_headers;
155 static struct active_request_slot *active_queue_head;
157 static char *cached_accept_language;
159 static char *http_ssl_backend;
161 static int http_schannel_check_revoke = 1;
163 * With the backend being set to `schannel`, setting sslCAinfo would override
164 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
165 * by default.
167 static int http_schannel_use_ssl_cainfo;
169 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
171 size_t size = eltsize * nmemb;
172 struct buffer *buffer = buffer_;
174 if (size > buffer->buf.len - buffer->posn)
175 size = buffer->buf.len - buffer->posn;
176 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
177 buffer->posn += size;
179 return size;
182 #ifndef NO_CURL_IOCTL
183 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
185 struct buffer *buffer = clientp;
187 switch (cmd) {
188 case CURLIOCMD_NOP:
189 return CURLIOE_OK;
191 case CURLIOCMD_RESTARTREAD:
192 buffer->posn = 0;
193 return CURLIOE_OK;
195 default:
196 return CURLIOE_UNKNOWNCMD;
199 #endif
201 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
203 size_t size = eltsize * nmemb;
204 struct strbuf *buffer = buffer_;
206 strbuf_add(buffer, ptr, size);
207 return size;
210 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
212 return eltsize * nmemb;
215 static void closedown_active_slot(struct active_request_slot *slot)
217 active_requests--;
218 slot->in_use = 0;
221 static void finish_active_slot(struct active_request_slot *slot)
223 closedown_active_slot(slot);
224 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
226 if (slot->finished != NULL)
227 (*slot->finished) = 1;
229 /* Store slot results so they can be read after the slot is reused */
230 if (slot->results != NULL) {
231 slot->results->curl_result = slot->curl_result;
232 slot->results->http_code = slot->http_code;
233 #if LIBCURL_VERSION_NUM >= 0x070a08
234 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
235 &slot->results->auth_avail);
236 #else
237 slot->results->auth_avail = 0;
238 #endif
240 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
241 &slot->results->http_connectcode);
244 /* Run callback if appropriate */
245 if (slot->callback_func != NULL)
246 slot->callback_func(slot->callback_data);
249 static void xmulti_remove_handle(struct active_request_slot *slot)
251 #ifdef USE_CURL_MULTI
252 curl_multi_remove_handle(curlm, slot->curl);
253 #endif
256 #ifdef USE_CURL_MULTI
257 static void process_curl_messages(void)
259 int num_messages;
260 struct active_request_slot *slot;
261 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
263 while (curl_message != NULL) {
264 if (curl_message->msg == CURLMSG_DONE) {
265 int curl_result = curl_message->data.result;
266 slot = active_queue_head;
267 while (slot != NULL &&
268 slot->curl != curl_message->easy_handle)
269 slot = slot->next;
270 if (slot != NULL) {
271 xmulti_remove_handle(slot);
272 slot->curl_result = curl_result;
273 finish_active_slot(slot);
274 } else {
275 fprintf(stderr, "Received DONE message for unknown request!\n");
277 } else {
278 fprintf(stderr, "Unknown CURL message received: %d\n",
279 (int)curl_message->msg);
281 curl_message = curl_multi_info_read(curlm, &num_messages);
284 #endif
286 static int http_options(const char *var, const char *value, void *cb)
288 if (!strcmp("http.version", var)) {
289 return git_config_string(&curl_http_version, var, value);
291 if (!strcmp("http.sslverify", var)) {
292 curl_ssl_verify = git_config_bool(var, value);
293 return 0;
295 if (!strcmp("http.sslcipherlist", var))
296 return git_config_string(&ssl_cipherlist, var, value);
297 if (!strcmp("http.sslversion", var))
298 return git_config_string(&ssl_version, var, value);
299 if (!strcmp("http.sslcert", var))
300 return git_config_pathname(&ssl_cert, var, value);
301 #if LIBCURL_VERSION_NUM >= 0x070903
302 if (!strcmp("http.sslkey", var))
303 return git_config_pathname(&ssl_key, var, value);
304 #endif
305 #if LIBCURL_VERSION_NUM >= 0x070908
306 if (!strcmp("http.sslcapath", var))
307 return git_config_pathname(&ssl_capath, var, value);
308 #endif
309 if (!strcmp("http.sslcainfo", var))
310 return git_config_pathname(&ssl_cainfo, var, value);
311 if (!strcmp("http.sslcertpasswordprotected", var)) {
312 ssl_cert_password_required = git_config_bool(var, value);
313 return 0;
315 if (!strcmp("http.ssltry", var)) {
316 curl_ssl_try = git_config_bool(var, value);
317 return 0;
319 if (!strcmp("http.sslbackend", var)) {
320 free(http_ssl_backend);
321 http_ssl_backend = xstrdup_or_null(value);
322 return 0;
325 if (!strcmp("http.schannelcheckrevoke", var)) {
326 http_schannel_check_revoke = git_config_bool(var, value);
327 return 0;
330 if (!strcmp("http.schannelusesslcainfo", var)) {
331 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
332 return 0;
335 if (!strcmp("http.minsessions", var)) {
336 min_curl_sessions = git_config_int(var, value);
337 #ifndef USE_CURL_MULTI
338 if (min_curl_sessions > 1)
339 min_curl_sessions = 1;
340 #endif
341 return 0;
343 #ifdef USE_CURL_MULTI
344 if (!strcmp("http.maxrequests", var)) {
345 max_requests = git_config_int(var, value);
346 return 0;
348 #endif
349 if (!strcmp("http.lowspeedlimit", var)) {
350 curl_low_speed_limit = (long)git_config_int(var, value);
351 return 0;
353 if (!strcmp("http.lowspeedtime", var)) {
354 curl_low_speed_time = (long)git_config_int(var, value);
355 return 0;
358 if (!strcmp("http.noepsv", var)) {
359 curl_ftp_no_epsv = git_config_bool(var, value);
360 return 0;
362 if (!strcmp("http.proxy", var))
363 return git_config_string(&curl_http_proxy, var, value);
365 if (!strcmp("http.proxyauthmethod", var))
366 return git_config_string(&http_proxy_authmethod, var, value);
368 if (!strcmp("http.cookiefile", var))
369 return git_config_pathname(&curl_cookie_file, var, value);
370 if (!strcmp("http.savecookies", var)) {
371 curl_save_cookies = git_config_bool(var, value);
372 return 0;
375 if (!strcmp("http.postbuffer", var)) {
376 http_post_buffer = git_config_ssize_t(var, value);
377 if (http_post_buffer < 0)
378 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
379 if (http_post_buffer < LARGE_PACKET_MAX)
380 http_post_buffer = LARGE_PACKET_MAX;
381 return 0;
384 if (!strcmp("http.useragent", var))
385 return git_config_string(&user_agent, var, value);
387 if (!strcmp("http.emptyauth", var)) {
388 if (value && !strcmp("auto", value))
389 curl_empty_auth = -1;
390 else
391 curl_empty_auth = git_config_bool(var, value);
392 return 0;
395 if (!strcmp("http.delegation", var)) {
396 #ifdef CURLGSSAPI_DELEGATION_FLAG
397 return git_config_string(&curl_deleg, var, value);
398 #else
399 warning(_("Delegation control is not supported with cURL < 7.22.0"));
400 return 0;
401 #endif
404 if (!strcmp("http.pinnedpubkey", var)) {
405 #if LIBCURL_VERSION_NUM >= 0x072c00
406 return git_config_pathname(&ssl_pinnedkey, var, value);
407 #else
408 warning(_("Public key pinning not supported with cURL < 7.44.0"));
409 return 0;
410 #endif
413 if (!strcmp("http.extraheader", var)) {
414 if (!value) {
415 return config_error_nonbool(var);
416 } else if (!*value) {
417 curl_slist_free_all(extra_http_headers);
418 extra_http_headers = NULL;
419 } else {
420 extra_http_headers =
421 curl_slist_append(extra_http_headers, value);
423 return 0;
426 if (!strcmp("http.followredirects", var)) {
427 if (value && !strcmp(value, "initial"))
428 http_follow_config = HTTP_FOLLOW_INITIAL;
429 else if (git_config_bool(var, value))
430 http_follow_config = HTTP_FOLLOW_ALWAYS;
431 else
432 http_follow_config = HTTP_FOLLOW_NONE;
433 return 0;
436 /* Fall back on the default ones */
437 return git_default_config(var, value, cb);
440 static int curl_empty_auth_enabled(void)
442 if (curl_empty_auth >= 0)
443 return curl_empty_auth;
445 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
447 * Our libcurl is too old to do AUTH_ANY in the first place;
448 * just default to turning the feature off.
450 #else
452 * In the automatic case, kick in the empty-auth
453 * hack as long as we would potentially try some
454 * method more exotic than "Basic" or "Digest".
456 * But only do this when this is our second or
457 * subsequent request, as by then we know what
458 * methods are available.
460 if (http_auth_methods_restricted &&
461 (http_auth_methods & ~empty_auth_useless))
462 return 1;
463 #endif
464 return 0;
467 static void init_curl_http_auth(CURL *result)
469 if (!http_auth.username || !*http_auth.username) {
470 if (curl_empty_auth_enabled())
471 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
472 return;
475 credential_fill(&http_auth);
477 #if LIBCURL_VERSION_NUM >= 0x071301
478 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
479 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
480 #else
482 static struct strbuf up = STRBUF_INIT;
484 * Note that we assume we only ever have a single set of
485 * credentials in a given program run, so we do not have
486 * to worry about updating this buffer, only setting its
487 * initial value.
489 if (!up.len)
490 strbuf_addf(&up, "%s:%s",
491 http_auth.username, http_auth.password);
492 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
494 #endif
497 /* *var must be free-able */
498 static void var_override(const char **var, char *value)
500 if (value) {
501 free((void *)*var);
502 *var = xstrdup(value);
506 static void set_proxyauth_name_password(CURL *result)
508 #if LIBCURL_VERSION_NUM >= 0x071301
509 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
510 proxy_auth.username);
511 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
512 proxy_auth.password);
513 #else
514 struct strbuf s = STRBUF_INIT;
516 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
517 strbuf_addch(&s, ':');
518 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
519 curl_proxyuserpwd = strbuf_detach(&s, NULL);
520 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
521 #endif
524 static void init_curl_proxy_auth(CURL *result)
526 if (proxy_auth.username) {
527 if (!proxy_auth.password)
528 credential_fill(&proxy_auth);
529 set_proxyauth_name_password(result);
532 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
534 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
535 if (http_proxy_authmethod) {
536 int i;
537 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
538 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
539 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
540 proxy_authmethods[i].curlauth_param);
541 break;
544 if (i == ARRAY_SIZE(proxy_authmethods)) {
545 warning("unsupported proxy authentication method %s: using anyauth",
546 http_proxy_authmethod);
547 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
550 else
551 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
552 #endif
555 static int has_cert_password(void)
557 if (ssl_cert == NULL || ssl_cert_password_required != 1)
558 return 0;
559 if (!cert_auth.password) {
560 cert_auth.protocol = xstrdup("cert");
561 cert_auth.host = xstrdup("");
562 cert_auth.username = xstrdup("");
563 cert_auth.path = xstrdup(ssl_cert);
564 credential_fill(&cert_auth);
566 return 1;
569 #if LIBCURL_VERSION_NUM >= 0x071900
570 static void set_curl_keepalive(CURL *c)
572 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
575 #elif LIBCURL_VERSION_NUM >= 0x071000
576 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
578 int ka = 1;
579 int rc;
580 socklen_t len = (socklen_t)sizeof(ka);
582 if (type != CURLSOCKTYPE_IPCXN)
583 return 0;
585 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
586 if (rc < 0)
587 warning_errno("unable to set SO_KEEPALIVE on socket");
589 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
592 static void set_curl_keepalive(CURL *c)
594 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
597 #else
598 static void set_curl_keepalive(CURL *c)
600 /* not supported on older curl versions */
602 #endif
604 static void redact_sensitive_header(struct strbuf *header)
606 const char *sensitive_header;
608 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
609 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
610 /* The first token is the type, which is OK to log */
611 while (isspace(*sensitive_header))
612 sensitive_header++;
613 while (*sensitive_header && !isspace(*sensitive_header))
614 sensitive_header++;
615 /* Everything else is opaque and possibly sensitive */
616 strbuf_setlen(header, sensitive_header - header->buf);
617 strbuf_addstr(header, " <redacted>");
618 } else if (cookies_to_redact.nr &&
619 skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
620 struct strbuf redacted_header = STRBUF_INIT;
621 char *cookie;
623 while (isspace(*sensitive_header))
624 sensitive_header++;
627 * The contents of header starting from sensitive_header will
628 * subsequently be overridden, so it is fine to mutate this
629 * string (hence the assignment to "char *").
631 cookie = (char *) sensitive_header;
633 while (cookie) {
634 char *equals;
635 char *semicolon = strstr(cookie, "; ");
636 if (semicolon)
637 *semicolon = 0;
638 equals = strchrnul(cookie, '=');
639 if (!equals) {
640 /* invalid cookie, just append and continue */
641 strbuf_addstr(&redacted_header, cookie);
642 continue;
644 *equals = 0; /* temporarily set to NUL for lookup */
645 if (string_list_lookup(&cookies_to_redact, cookie)) {
646 strbuf_addstr(&redacted_header, cookie);
647 strbuf_addstr(&redacted_header, "=<redacted>");
648 } else {
649 *equals = '=';
650 strbuf_addstr(&redacted_header, cookie);
652 if (semicolon) {
654 * There are more cookies. (Or, for some
655 * reason, the input string ends in "; ".)
657 strbuf_addstr(&redacted_header, "; ");
658 cookie = semicolon + strlen("; ");
659 } else {
660 cookie = NULL;
664 strbuf_setlen(header, sensitive_header - header->buf);
665 strbuf_addbuf(header, &redacted_header);
669 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
671 struct strbuf out = STRBUF_INIT;
672 struct strbuf **headers, **header;
674 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
675 text, (long)size, (long)size);
676 trace_strbuf(&trace_curl, &out);
677 strbuf_reset(&out);
678 strbuf_add(&out, ptr, size);
679 headers = strbuf_split_max(&out, '\n', 0);
681 for (header = headers; *header; header++) {
682 if (hide_sensitive_header)
683 redact_sensitive_header(*header);
684 strbuf_insert((*header), 0, text, strlen(text));
685 strbuf_insert((*header), strlen(text), ": ", 2);
686 strbuf_rtrim((*header));
687 strbuf_addch((*header), '\n');
688 trace_strbuf(&trace_curl, (*header));
690 strbuf_list_free(headers);
691 strbuf_release(&out);
694 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
696 size_t i;
697 struct strbuf out = STRBUF_INIT;
698 unsigned int width = 60;
700 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
701 text, (long)size, (long)size);
702 trace_strbuf(&trace_curl, &out);
704 for (i = 0; i < size; i += width) {
705 size_t w;
707 strbuf_reset(&out);
708 strbuf_addf(&out, "%s: ", text);
709 for (w = 0; (w < width) && (i + w < size); w++) {
710 unsigned char ch = ptr[i + w];
712 strbuf_addch(&out,
713 (ch >= 0x20) && (ch < 0x80)
714 ? ch : '.');
716 strbuf_addch(&out, '\n');
717 trace_strbuf(&trace_curl, &out);
719 strbuf_release(&out);
722 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
724 const char *text;
725 enum { NO_FILTER = 0, DO_FILTER = 1 };
727 switch (type) {
728 case CURLINFO_TEXT:
729 trace_printf_key(&trace_curl, "== Info: %s", data);
730 break;
731 case CURLINFO_HEADER_OUT:
732 text = "=> Send header";
733 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
734 break;
735 case CURLINFO_DATA_OUT:
736 if (trace_curl_data) {
737 text = "=> Send data";
738 curl_dump_data(text, (unsigned char *)data, size);
740 break;
741 case CURLINFO_SSL_DATA_OUT:
742 if (trace_curl_data) {
743 text = "=> Send SSL data";
744 curl_dump_data(text, (unsigned char *)data, size);
746 break;
747 case CURLINFO_HEADER_IN:
748 text = "<= Recv header";
749 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
750 break;
751 case CURLINFO_DATA_IN:
752 if (trace_curl_data) {
753 text = "<= Recv data";
754 curl_dump_data(text, (unsigned char *)data, size);
756 break;
757 case CURLINFO_SSL_DATA_IN:
758 if (trace_curl_data) {
759 text = "<= Recv SSL data";
760 curl_dump_data(text, (unsigned char *)data, size);
762 break;
764 default: /* we ignore unknown types by default */
765 return 0;
767 return 0;
770 void setup_curl_trace(CURL *handle)
772 if (!trace_want(&trace_curl))
773 return;
774 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
775 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
776 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
779 #ifdef CURLPROTO_HTTP
780 static long get_curl_allowed_protocols(int from_user)
782 long allowed_protocols = 0;
784 if (is_transport_allowed("http", from_user))
785 allowed_protocols |= CURLPROTO_HTTP;
786 if (is_transport_allowed("https", from_user))
787 allowed_protocols |= CURLPROTO_HTTPS;
788 if (is_transport_allowed("ftp", from_user))
789 allowed_protocols |= CURLPROTO_FTP;
790 if (is_transport_allowed("ftps", from_user))
791 allowed_protocols |= CURLPROTO_FTPS;
793 return allowed_protocols;
795 #endif
797 #if LIBCURL_VERSION_NUM >=0x072f00
798 static int get_curl_http_version_opt(const char *version_string, long *opt)
800 int i;
801 static struct {
802 const char *name;
803 long opt_token;
804 } choice[] = {
805 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
806 { "HTTP/2", CURL_HTTP_VERSION_2 }
809 for (i = 0; i < ARRAY_SIZE(choice); i++) {
810 if (!strcmp(version_string, choice[i].name)) {
811 *opt = choice[i].opt_token;
812 return 0;
816 warning("unknown value given to http.version: '%s'", version_string);
817 return -1; /* not found */
820 #endif
822 static CURL *get_curl_handle(void)
824 CURL *result = curl_easy_init();
826 if (!result)
827 die("curl_easy_init failed");
829 if (!curl_ssl_verify) {
830 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
831 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
832 } else {
833 /* Verify authenticity of the peer's certificate */
834 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
835 /* The name in the cert must match whom we tried to connect */
836 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
839 #if LIBCURL_VERSION_NUM >= 0x072f00 // 7.47.0
840 if (curl_http_version) {
841 long opt;
842 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
843 /* Set request use http version */
844 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
847 #endif
849 #if LIBCURL_VERSION_NUM >= 0x070907
850 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
851 #endif
852 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
853 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
854 #endif
856 #ifdef CURLGSSAPI_DELEGATION_FLAG
857 if (curl_deleg) {
858 int i;
859 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
860 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
861 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
862 curl_deleg_levels[i].curl_deleg_param);
863 break;
866 if (i == ARRAY_SIZE(curl_deleg_levels))
867 warning("Unknown delegation method '%s': using default",
868 curl_deleg);
870 #endif
872 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
873 !http_schannel_check_revoke) {
874 #if LIBCURL_VERSION_NUM >= 0x072c00
875 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
876 #else
877 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
878 #endif
881 if (http_proactive_auth)
882 init_curl_http_auth(result);
884 if (getenv("GIT_SSL_VERSION"))
885 ssl_version = getenv("GIT_SSL_VERSION");
886 if (ssl_version && *ssl_version) {
887 int i;
888 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
889 if (!strcmp(ssl_version, sslversions[i].name)) {
890 curl_easy_setopt(result, CURLOPT_SSLVERSION,
891 sslversions[i].ssl_version);
892 break;
895 if (i == ARRAY_SIZE(sslversions))
896 warning("unsupported ssl version %s: using default",
897 ssl_version);
900 if (getenv("GIT_SSL_CIPHER_LIST"))
901 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
902 if (ssl_cipherlist != NULL && *ssl_cipherlist)
903 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
904 ssl_cipherlist);
906 if (ssl_cert != NULL)
907 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
908 if (has_cert_password())
909 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
910 #if LIBCURL_VERSION_NUM >= 0x070903
911 if (ssl_key != NULL)
912 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
913 #endif
914 #if LIBCURL_VERSION_NUM >= 0x070908
915 if (ssl_capath != NULL)
916 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
917 #endif
918 #if LIBCURL_VERSION_NUM >= 0x072c00
919 if (ssl_pinnedkey != NULL)
920 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
921 #endif
922 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
923 !http_schannel_use_ssl_cainfo) {
924 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
925 #if LIBCURL_VERSION_NUM >= 0x073400
926 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
927 #endif
928 } else if (ssl_cainfo != NULL)
929 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
931 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
932 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
933 curl_low_speed_limit);
934 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
935 curl_low_speed_time);
938 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
939 #if LIBCURL_VERSION_NUM >= 0x071301
940 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
941 #elif LIBCURL_VERSION_NUM >= 0x071101
942 curl_easy_setopt(result, CURLOPT_POST301, 1);
943 #endif
944 #ifdef CURLPROTO_HTTP
945 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
946 get_curl_allowed_protocols(0));
947 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
948 get_curl_allowed_protocols(-1));
949 #else
950 warning(_("Protocol restrictions not supported with cURL < 7.19.4"));
951 #endif
952 if (getenv("GIT_CURL_VERBOSE"))
953 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
954 setup_curl_trace(result);
955 if (getenv("GIT_TRACE_CURL_NO_DATA"))
956 trace_curl_data = 0;
957 if (getenv("GIT_REDACT_COOKIES")) {
958 string_list_split(&cookies_to_redact,
959 getenv("GIT_REDACT_COOKIES"), ',', -1);
960 string_list_sort(&cookies_to_redact);
963 curl_easy_setopt(result, CURLOPT_USERAGENT,
964 user_agent ? user_agent : git_user_agent());
966 if (curl_ftp_no_epsv)
967 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
969 #ifdef CURLOPT_USE_SSL
970 if (curl_ssl_try)
971 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
972 #endif
975 * CURL also examines these variables as a fallback; but we need to query
976 * them here in order to decide whether to prompt for missing password (cf.
977 * init_curl_proxy_auth()).
979 * Unlike many other common environment variables, these are historically
980 * lowercase only. It appears that CURL did not know this and implemented
981 * only uppercase variants, which was later corrected to take both - with
982 * the exception of http_proxy, which is lowercase only also in CURL. As
983 * the lowercase versions are the historical quasi-standard, they take
984 * precedence here, as in CURL.
986 if (!curl_http_proxy) {
987 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
988 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
989 var_override(&curl_http_proxy, getenv("https_proxy"));
990 } else {
991 var_override(&curl_http_proxy, getenv("http_proxy"));
993 if (!curl_http_proxy) {
994 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
995 var_override(&curl_http_proxy, getenv("all_proxy"));
999 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1001 * Handle case with the empty http.proxy value here to keep
1002 * common code clean.
1003 * NB: empty option disables proxying at all.
1005 curl_easy_setopt(result, CURLOPT_PROXY, "");
1006 } else if (curl_http_proxy) {
1007 #if LIBCURL_VERSION_NUM >= 0x071800
1008 if (starts_with(curl_http_proxy, "socks5h"))
1009 curl_easy_setopt(result,
1010 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1011 else if (starts_with(curl_http_proxy, "socks5"))
1012 curl_easy_setopt(result,
1013 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1014 else if (starts_with(curl_http_proxy, "socks4a"))
1015 curl_easy_setopt(result,
1016 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1017 else if (starts_with(curl_http_proxy, "socks"))
1018 curl_easy_setopt(result,
1019 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1020 #endif
1021 #if LIBCURL_VERSION_NUM >= 0x073400
1022 else if (starts_with(curl_http_proxy, "https"))
1023 curl_easy_setopt(result,
1024 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1025 #endif
1026 if (strstr(curl_http_proxy, "://"))
1027 credential_from_url(&proxy_auth, curl_http_proxy);
1028 else {
1029 struct strbuf url = STRBUF_INIT;
1030 strbuf_addf(&url, "http://%s", curl_http_proxy);
1031 credential_from_url(&proxy_auth, url.buf);
1032 strbuf_release(&url);
1035 if (!proxy_auth.host)
1036 die("Invalid proxy URL '%s'", curl_http_proxy);
1038 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1039 #if LIBCURL_VERSION_NUM >= 0x071304
1040 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1041 var_override(&curl_no_proxy, getenv("no_proxy"));
1042 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1043 #endif
1045 init_curl_proxy_auth(result);
1047 set_curl_keepalive(result);
1049 return result;
1052 static void set_from_env(const char **var, const char *envname)
1054 const char *val = getenv(envname);
1055 if (val)
1056 *var = val;
1059 void http_init(struct remote *remote, const char *url, int proactive_auth)
1061 char *low_speed_limit;
1062 char *low_speed_time;
1063 char *normalized_url;
1064 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
1066 config.section = "http";
1067 config.key = NULL;
1068 config.collect_fn = http_options;
1069 config.cascade_fn = git_default_config;
1070 config.cb = NULL;
1072 http_is_verbose = 0;
1073 normalized_url = url_normalize(url, &config.url);
1075 git_config(urlmatch_config_entry, &config);
1076 free(normalized_url);
1078 #if LIBCURL_VERSION_NUM >= 0x073800
1079 if (http_ssl_backend) {
1080 const curl_ssl_backend **backends;
1081 struct strbuf buf = STRBUF_INIT;
1082 int i;
1084 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1085 case CURLSSLSET_UNKNOWN_BACKEND:
1086 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1087 "Supported SSL backends:"),
1088 http_ssl_backend);
1089 for (i = 0; backends[i]; i++)
1090 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1091 die("%s", buf.buf);
1092 case CURLSSLSET_NO_BACKENDS:
1093 die(_("Could not set SSL backend to '%s': "
1094 "cURL was built without SSL backends"),
1095 http_ssl_backend);
1096 case CURLSSLSET_TOO_LATE:
1097 die(_("Could not set SSL backend to '%s': already set"),
1098 http_ssl_backend);
1099 case CURLSSLSET_OK:
1100 break; /* Okay! */
1103 #endif
1105 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1106 die("curl_global_init failed");
1108 http_proactive_auth = proactive_auth;
1110 if (remote && remote->http_proxy)
1111 curl_http_proxy = xstrdup(remote->http_proxy);
1113 if (remote)
1114 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1116 pragma_header = curl_slist_append(http_copy_default_headers(),
1117 "Pragma: no-cache");
1118 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1119 "Pragma:");
1121 #ifdef USE_CURL_MULTI
1123 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1124 if (http_max_requests != NULL)
1125 max_requests = atoi(http_max_requests);
1128 curlm = curl_multi_init();
1129 if (!curlm)
1130 die("curl_multi_init failed");
1131 #endif
1133 if (getenv("GIT_SSL_NO_VERIFY"))
1134 curl_ssl_verify = 0;
1136 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1137 #if LIBCURL_VERSION_NUM >= 0x070903
1138 set_from_env(&ssl_key, "GIT_SSL_KEY");
1139 #endif
1140 #if LIBCURL_VERSION_NUM >= 0x070908
1141 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1142 #endif
1143 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1145 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1147 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1148 if (low_speed_limit != NULL)
1149 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1150 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1151 if (low_speed_time != NULL)
1152 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1154 if (curl_ssl_verify == -1)
1155 curl_ssl_verify = 1;
1157 curl_session_count = 0;
1158 #ifdef USE_CURL_MULTI
1159 if (max_requests < 1)
1160 max_requests = DEFAULT_MAX_REQUESTS;
1161 #endif
1163 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1164 curl_ftp_no_epsv = 1;
1166 if (url) {
1167 credential_from_url(&http_auth, url);
1168 if (!ssl_cert_password_required &&
1169 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1170 starts_with(url, "https://"))
1171 ssl_cert_password_required = 1;
1174 #ifndef NO_CURL_EASY_DUPHANDLE
1175 curl_default = get_curl_handle();
1176 #endif
1179 void http_cleanup(void)
1181 struct active_request_slot *slot = active_queue_head;
1183 while (slot != NULL) {
1184 struct active_request_slot *next = slot->next;
1185 if (slot->curl != NULL) {
1186 xmulti_remove_handle(slot);
1187 curl_easy_cleanup(slot->curl);
1189 free(slot);
1190 slot = next;
1192 active_queue_head = NULL;
1194 #ifndef NO_CURL_EASY_DUPHANDLE
1195 curl_easy_cleanup(curl_default);
1196 #endif
1198 #ifdef USE_CURL_MULTI
1199 curl_multi_cleanup(curlm);
1200 #endif
1201 curl_global_cleanup();
1203 curl_slist_free_all(extra_http_headers);
1204 extra_http_headers = NULL;
1206 curl_slist_free_all(pragma_header);
1207 pragma_header = NULL;
1209 curl_slist_free_all(no_pragma_header);
1210 no_pragma_header = NULL;
1212 if (curl_http_proxy) {
1213 free((void *)curl_http_proxy);
1214 curl_http_proxy = NULL;
1217 if (proxy_auth.password) {
1218 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1219 FREE_AND_NULL(proxy_auth.password);
1222 free((void *)curl_proxyuserpwd);
1223 curl_proxyuserpwd = NULL;
1225 free((void *)http_proxy_authmethod);
1226 http_proxy_authmethod = NULL;
1228 if (cert_auth.password != NULL) {
1229 memset(cert_auth.password, 0, strlen(cert_auth.password));
1230 FREE_AND_NULL(cert_auth.password);
1232 ssl_cert_password_required = 0;
1234 FREE_AND_NULL(cached_accept_language);
1237 struct active_request_slot *get_active_slot(void)
1239 struct active_request_slot *slot = active_queue_head;
1240 struct active_request_slot *newslot;
1242 #ifdef USE_CURL_MULTI
1243 int num_transfers;
1245 /* Wait for a slot to open up if the queue is full */
1246 while (active_requests >= max_requests) {
1247 curl_multi_perform(curlm, &num_transfers);
1248 if (num_transfers < active_requests)
1249 process_curl_messages();
1251 #endif
1253 while (slot != NULL && slot->in_use)
1254 slot = slot->next;
1256 if (slot == NULL) {
1257 newslot = xmalloc(sizeof(*newslot));
1258 newslot->curl = NULL;
1259 newslot->in_use = 0;
1260 newslot->next = NULL;
1262 slot = active_queue_head;
1263 if (slot == NULL) {
1264 active_queue_head = newslot;
1265 } else {
1266 while (slot->next != NULL)
1267 slot = slot->next;
1268 slot->next = newslot;
1270 slot = newslot;
1273 if (slot->curl == NULL) {
1274 #ifdef NO_CURL_EASY_DUPHANDLE
1275 slot->curl = get_curl_handle();
1276 #else
1277 slot->curl = curl_easy_duphandle(curl_default);
1278 #endif
1279 curl_session_count++;
1282 active_requests++;
1283 slot->in_use = 1;
1284 slot->results = NULL;
1285 slot->finished = NULL;
1286 slot->callback_data = NULL;
1287 slot->callback_func = NULL;
1288 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1289 if (curl_save_cookies)
1290 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1291 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1292 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1293 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1294 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1295 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1296 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1297 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1298 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1299 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1300 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1303 * Default following to off unless "ALWAYS" is configured; this gives
1304 * callers a sane starting point, and they can tweak for individual
1305 * HTTP_FOLLOW_* cases themselves.
1307 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1308 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1309 else
1310 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1312 #if LIBCURL_VERSION_NUM >= 0x070a08
1313 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1314 #endif
1315 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1316 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1317 #endif
1318 if (http_auth.password || curl_empty_auth_enabled())
1319 init_curl_http_auth(slot->curl);
1321 return slot;
1324 int start_active_slot(struct active_request_slot *slot)
1326 #ifdef USE_CURL_MULTI
1327 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1328 int num_transfers;
1330 if (curlm_result != CURLM_OK &&
1331 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1332 warning("curl_multi_add_handle failed: %s",
1333 curl_multi_strerror(curlm_result));
1334 active_requests--;
1335 slot->in_use = 0;
1336 return 0;
1340 * We know there must be something to do, since we just added
1341 * something.
1343 curl_multi_perform(curlm, &num_transfers);
1344 #endif
1345 return 1;
1348 #ifdef USE_CURL_MULTI
1349 struct fill_chain {
1350 void *data;
1351 int (*fill)(void *);
1352 struct fill_chain *next;
1355 static struct fill_chain *fill_cfg;
1357 void add_fill_function(void *data, int (*fill)(void *))
1359 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1360 struct fill_chain **linkp = &fill_cfg;
1361 new_fill->data = data;
1362 new_fill->fill = fill;
1363 new_fill->next = NULL;
1364 while (*linkp)
1365 linkp = &(*linkp)->next;
1366 *linkp = new_fill;
1369 void fill_active_slots(void)
1371 struct active_request_slot *slot = active_queue_head;
1373 while (active_requests < max_requests) {
1374 struct fill_chain *fill;
1375 for (fill = fill_cfg; fill; fill = fill->next)
1376 if (fill->fill(fill->data))
1377 break;
1379 if (!fill)
1380 break;
1383 while (slot != NULL) {
1384 if (!slot->in_use && slot->curl != NULL
1385 && curl_session_count > min_curl_sessions) {
1386 curl_easy_cleanup(slot->curl);
1387 slot->curl = NULL;
1388 curl_session_count--;
1390 slot = slot->next;
1394 void step_active_slots(void)
1396 int num_transfers;
1397 CURLMcode curlm_result;
1399 do {
1400 curlm_result = curl_multi_perform(curlm, &num_transfers);
1401 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1402 if (num_transfers < active_requests) {
1403 process_curl_messages();
1404 fill_active_slots();
1407 #endif
1409 void run_active_slot(struct active_request_slot *slot)
1411 #ifdef USE_CURL_MULTI
1412 fd_set readfds;
1413 fd_set writefds;
1414 fd_set excfds;
1415 int max_fd;
1416 struct timeval select_timeout;
1417 int finished = 0;
1419 slot->finished = &finished;
1420 while (!finished) {
1421 step_active_slots();
1423 if (slot->in_use) {
1424 #if LIBCURL_VERSION_NUM >= 0x070f04
1425 long curl_timeout;
1426 curl_multi_timeout(curlm, &curl_timeout);
1427 if (curl_timeout == 0) {
1428 continue;
1429 } else if (curl_timeout == -1) {
1430 select_timeout.tv_sec = 0;
1431 select_timeout.tv_usec = 50000;
1432 } else {
1433 select_timeout.tv_sec = curl_timeout / 1000;
1434 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1436 #else
1437 select_timeout.tv_sec = 0;
1438 select_timeout.tv_usec = 50000;
1439 #endif
1441 max_fd = -1;
1442 FD_ZERO(&readfds);
1443 FD_ZERO(&writefds);
1444 FD_ZERO(&excfds);
1445 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1448 * It can happen that curl_multi_timeout returns a pathologically
1449 * long timeout when curl_multi_fdset returns no file descriptors
1450 * to read. See commit message for more details.
1452 if (max_fd < 0 &&
1453 (select_timeout.tv_sec > 0 ||
1454 select_timeout.tv_usec > 50000)) {
1455 select_timeout.tv_sec = 0;
1456 select_timeout.tv_usec = 50000;
1459 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1462 #else
1463 while (slot->in_use) {
1464 slot->curl_result = curl_easy_perform(slot->curl);
1465 finish_active_slot(slot);
1467 #endif
1470 static void release_active_slot(struct active_request_slot *slot)
1472 closedown_active_slot(slot);
1473 if (slot->curl) {
1474 xmulti_remove_handle(slot);
1475 if (curl_session_count > min_curl_sessions) {
1476 curl_easy_cleanup(slot->curl);
1477 slot->curl = NULL;
1478 curl_session_count--;
1481 #ifdef USE_CURL_MULTI
1482 fill_active_slots();
1483 #endif
1486 void finish_all_active_slots(void)
1488 struct active_request_slot *slot = active_queue_head;
1490 while (slot != NULL)
1491 if (slot->in_use) {
1492 run_active_slot(slot);
1493 slot = active_queue_head;
1494 } else {
1495 slot = slot->next;
1499 /* Helpers for modifying and creating URLs */
1500 static inline int needs_quote(int ch)
1502 if (((ch >= 'A') && (ch <= 'Z'))
1503 || ((ch >= 'a') && (ch <= 'z'))
1504 || ((ch >= '0') && (ch <= '9'))
1505 || (ch == '/')
1506 || (ch == '-')
1507 || (ch == '.'))
1508 return 0;
1509 return 1;
1512 static char *quote_ref_url(const char *base, const char *ref)
1514 struct strbuf buf = STRBUF_INIT;
1515 const char *cp;
1516 int ch;
1518 end_url_with_slash(&buf, base);
1520 for (cp = ref; (ch = *cp) != 0; cp++)
1521 if (needs_quote(ch))
1522 strbuf_addf(&buf, "%%%02x", ch);
1523 else
1524 strbuf_addch(&buf, *cp);
1526 return strbuf_detach(&buf, NULL);
1529 void append_remote_object_url(struct strbuf *buf, const char *url,
1530 const char *hex,
1531 int only_two_digit_prefix)
1533 end_url_with_slash(buf, url);
1535 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1536 if (!only_two_digit_prefix)
1537 strbuf_addstr(buf, hex + 2);
1540 char *get_remote_object_url(const char *url, const char *hex,
1541 int only_two_digit_prefix)
1543 struct strbuf buf = STRBUF_INIT;
1544 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1545 return strbuf_detach(&buf, NULL);
1548 static int handle_curl_result(struct slot_results *results)
1551 * If we see a failing http code with CURLE_OK, we have turned off
1552 * FAILONERROR (to keep the server's custom error response), and should
1553 * translate the code into failure here.
1555 * Likewise, if we see a redirect (30x code), that means we turned off
1556 * redirect-following, and we should treat the result as an error.
1558 if (results->curl_result == CURLE_OK &&
1559 results->http_code >= 300) {
1560 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1562 * Normally curl will already have put the "reason phrase"
1563 * from the server into curl_errorstr; unfortunately without
1564 * FAILONERROR it is lost, so we can give only the numeric
1565 * status code.
1567 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1568 "The requested URL returned error: %ld",
1569 results->http_code);
1572 if (results->curl_result == CURLE_OK) {
1573 credential_approve(&http_auth);
1574 if (proxy_auth.password)
1575 credential_approve(&proxy_auth);
1576 return HTTP_OK;
1577 } else if (missing_target(results))
1578 return HTTP_MISSING_TARGET;
1579 else if (results->http_code == 401) {
1580 if (http_auth.username && http_auth.password) {
1581 credential_reject(&http_auth);
1582 return HTTP_NOAUTH;
1583 } else {
1584 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1585 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1586 if (results->auth_avail) {
1587 http_auth_methods &= results->auth_avail;
1588 http_auth_methods_restricted = 1;
1590 #endif
1591 return HTTP_REAUTH;
1593 } else {
1594 if (results->http_connectcode == 407)
1595 credential_reject(&proxy_auth);
1596 #if LIBCURL_VERSION_NUM >= 0x070c00
1597 if (!curl_errorstr[0])
1598 strlcpy(curl_errorstr,
1599 curl_easy_strerror(results->curl_result),
1600 sizeof(curl_errorstr));
1601 #endif
1602 return HTTP_ERROR;
1606 int run_one_slot(struct active_request_slot *slot,
1607 struct slot_results *results)
1609 slot->results = results;
1610 if (!start_active_slot(slot)) {
1611 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1612 "failed to start HTTP request");
1613 return HTTP_START_FAILED;
1616 run_active_slot(slot);
1617 return handle_curl_result(results);
1620 struct curl_slist *http_copy_default_headers(void)
1622 struct curl_slist *headers = NULL, *h;
1624 for (h = extra_http_headers; h; h = h->next)
1625 headers = curl_slist_append(headers, h->data);
1627 return headers;
1630 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1632 char *ptr;
1633 CURLcode ret;
1635 strbuf_reset(buf);
1636 ret = curl_easy_getinfo(curl, info, &ptr);
1637 if (!ret && ptr)
1638 strbuf_addstr(buf, ptr);
1639 return ret;
1643 * Check for and extract a content-type parameter. "raw"
1644 * should be positioned at the start of the potential
1645 * parameter, with any whitespace already removed.
1647 * "name" is the name of the parameter. The value is appended
1648 * to "out".
1650 static int extract_param(const char *raw, const char *name,
1651 struct strbuf *out)
1653 size_t len = strlen(name);
1655 if (strncasecmp(raw, name, len))
1656 return -1;
1657 raw += len;
1659 if (*raw != '=')
1660 return -1;
1661 raw++;
1663 while (*raw && !isspace(*raw) && *raw != ';')
1664 strbuf_addch(out, *raw++);
1665 return 0;
1669 * Extract a normalized version of the content type, with any
1670 * spaces suppressed, all letters lowercased, and no trailing ";"
1671 * or parameters.
1673 * Note that we will silently remove even invalid whitespace. For
1674 * example, "text / plain" is specifically forbidden by RFC 2616,
1675 * but "text/plain" is the only reasonable output, and this keeps
1676 * our code simple.
1678 * If the "charset" argument is not NULL, store the value of any
1679 * charset parameter there.
1681 * Example:
1682 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1683 * "text / plain" -> "text/plain"
1685 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1686 struct strbuf *charset)
1688 const char *p;
1690 strbuf_reset(type);
1691 strbuf_grow(type, raw->len);
1692 for (p = raw->buf; *p; p++) {
1693 if (isspace(*p))
1694 continue;
1695 if (*p == ';') {
1696 p++;
1697 break;
1699 strbuf_addch(type, tolower(*p));
1702 if (!charset)
1703 return;
1705 strbuf_reset(charset);
1706 while (*p) {
1707 while (isspace(*p) || *p == ';')
1708 p++;
1709 if (!extract_param(p, "charset", charset))
1710 return;
1711 while (*p && !isspace(*p))
1712 p++;
1715 if (!charset->len && starts_with(type->buf, "text/"))
1716 strbuf_addstr(charset, "ISO-8859-1");
1719 static void write_accept_language(struct strbuf *buf)
1722 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1723 * that, q-value will be smaller than 0.001, the minimum q-value the
1724 * HTTP specification allows. See
1725 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1727 const int MAX_DECIMAL_PLACES = 3;
1728 const int MAX_LANGUAGE_TAGS = 1000;
1729 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1730 char **language_tags = NULL;
1731 int num_langs = 0;
1732 const char *s = get_preferred_languages();
1733 int i;
1734 struct strbuf tag = STRBUF_INIT;
1736 /* Don't add Accept-Language header if no language is preferred. */
1737 if (!s)
1738 return;
1741 * Split the colon-separated string of preferred languages into
1742 * language_tags array.
1744 do {
1745 /* collect language tag */
1746 for (; *s && (isalnum(*s) || *s == '_'); s++)
1747 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1749 /* skip .codeset, @modifier and any other unnecessary parts */
1750 while (*s && *s != ':')
1751 s++;
1753 if (tag.len) {
1754 num_langs++;
1755 REALLOC_ARRAY(language_tags, num_langs);
1756 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1757 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1758 break;
1760 } while (*s++);
1762 /* write Accept-Language header into buf */
1763 if (num_langs) {
1764 int last_buf_len = 0;
1765 int max_q;
1766 int decimal_places;
1767 char q_format[32];
1769 /* add '*' */
1770 REALLOC_ARRAY(language_tags, num_langs + 1);
1771 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1773 /* compute decimal_places */
1774 for (max_q = 1, decimal_places = 0;
1775 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1776 decimal_places++, max_q *= 10)
1779 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1781 strbuf_addstr(buf, "Accept-Language: ");
1783 for (i = 0; i < num_langs; i++) {
1784 if (i > 0)
1785 strbuf_addstr(buf, ", ");
1787 strbuf_addstr(buf, language_tags[i]);
1789 if (i > 0)
1790 strbuf_addf(buf, q_format, max_q - i);
1792 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1793 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1794 break;
1797 last_buf_len = buf->len;
1801 /* free language tags -- last one is a static '*' */
1802 for (i = 0; i < num_langs - 1; i++)
1803 free(language_tags[i]);
1804 free(language_tags);
1808 * Get an Accept-Language header which indicates user's preferred languages.
1810 * Examples:
1811 * LANGUAGE= -> ""
1812 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1813 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1814 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1815 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1816 * LANGUAGE= LANG=C -> ""
1818 static const char *get_accept_language(void)
1820 if (!cached_accept_language) {
1821 struct strbuf buf = STRBUF_INIT;
1822 write_accept_language(&buf);
1823 if (buf.len > 0)
1824 cached_accept_language = strbuf_detach(&buf, NULL);
1827 return cached_accept_language;
1830 static void http_opt_request_remainder(CURL *curl, off_t pos)
1832 char buf[128];
1833 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1834 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1837 /* http_request() targets */
1838 #define HTTP_REQUEST_STRBUF 0
1839 #define HTTP_REQUEST_FILE 1
1841 static int http_request(const char *url,
1842 void *result, int target,
1843 const struct http_get_options *options)
1845 struct active_request_slot *slot;
1846 struct slot_results results;
1847 struct curl_slist *headers = http_copy_default_headers();
1848 struct strbuf buf = STRBUF_INIT;
1849 const char *accept_language;
1850 int ret;
1852 slot = get_active_slot();
1853 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1855 if (result == NULL) {
1856 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1857 } else {
1858 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1859 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1861 if (target == HTTP_REQUEST_FILE) {
1862 off_t posn = ftello(result);
1863 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1864 fwrite);
1865 if (posn > 0)
1866 http_opt_request_remainder(slot->curl, posn);
1867 } else
1868 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1869 fwrite_buffer);
1872 accept_language = get_accept_language();
1874 if (accept_language)
1875 headers = curl_slist_append(headers, accept_language);
1877 strbuf_addstr(&buf, "Pragma:");
1878 if (options && options->no_cache)
1879 strbuf_addstr(&buf, " no-cache");
1880 if (options && options->initial_request &&
1881 http_follow_config == HTTP_FOLLOW_INITIAL)
1882 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1884 headers = curl_slist_append(headers, buf.buf);
1886 /* Add additional headers here */
1887 if (options && options->extra_headers) {
1888 const struct string_list_item *item;
1889 for_each_string_list_item(item, options->extra_headers) {
1890 headers = curl_slist_append(headers, item->string);
1894 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1895 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1896 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1897 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1899 ret = run_one_slot(slot, &results);
1901 if (options && options->content_type) {
1902 struct strbuf raw = STRBUF_INIT;
1903 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1904 extract_content_type(&raw, options->content_type,
1905 options->charset);
1906 strbuf_release(&raw);
1909 if (options && options->effective_url)
1910 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1911 options->effective_url);
1913 curl_slist_free_all(headers);
1914 strbuf_release(&buf);
1916 return ret;
1920 * Update the "base" url to a more appropriate value, as deduced by
1921 * redirects seen when requesting a URL starting with "url".
1923 * The "asked" parameter is a URL that we asked curl to access, and must begin
1924 * with "base".
1926 * The "got" parameter is the URL that curl reported to us as where we ended
1927 * up.
1929 * Returns 1 if we updated the base url, 0 otherwise.
1931 * Our basic strategy is to compare "base" and "asked" to find the bits
1932 * specific to our request. We then strip those bits off of "got" to yield the
1933 * new base. So for example, if our base is "http://example.com/foo.git",
1934 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1935 * with "https://other.example.com/foo.git/info/refs". We would want the
1936 * new URL to become "https://other.example.com/foo.git".
1938 * Note that this assumes a sane redirect scheme. It's entirely possible
1939 * in the example above to end up at a URL that does not even end in
1940 * "info/refs". In such a case we die. There's not much we can do, such a
1941 * scheme is unlikely to represent a real git repository, and failing to
1942 * rewrite the base opens options for malicious redirects to do funny things.
1944 static int update_url_from_redirect(struct strbuf *base,
1945 const char *asked,
1946 const struct strbuf *got)
1948 const char *tail;
1949 size_t new_len;
1951 if (!strcmp(asked, got->buf))
1952 return 0;
1954 if (!skip_prefix(asked, base->buf, &tail))
1955 BUG("update_url_from_redirect: %s is not a superset of %s",
1956 asked, base->buf);
1958 new_len = got->len;
1959 if (!strip_suffix_mem(got->buf, &new_len, tail))
1960 die(_("unable to update url base from redirection:\n"
1961 " asked for: %s\n"
1962 " redirect: %s"),
1963 asked, got->buf);
1965 strbuf_reset(base);
1966 strbuf_add(base, got->buf, new_len);
1968 return 1;
1971 static int http_request_reauth(const char *url,
1972 void *result, int target,
1973 struct http_get_options *options)
1975 int ret = http_request(url, result, target, options);
1977 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1978 return ret;
1980 if (options && options->effective_url && options->base_url) {
1981 if (update_url_from_redirect(options->base_url,
1982 url, options->effective_url)) {
1983 credential_from_url(&http_auth, options->base_url->buf);
1984 url = options->effective_url->buf;
1988 if (ret != HTTP_REAUTH)
1989 return ret;
1992 * The previous request may have put cruft into our output stream; we
1993 * should clear it out before making our next request.
1995 switch (target) {
1996 case HTTP_REQUEST_STRBUF:
1997 strbuf_reset(result);
1998 break;
1999 case HTTP_REQUEST_FILE:
2000 if (fflush(result)) {
2001 error_errno("unable to flush a file");
2002 return HTTP_START_FAILED;
2004 rewind(result);
2005 if (ftruncate(fileno(result), 0) < 0) {
2006 error_errno("unable to truncate a file");
2007 return HTTP_START_FAILED;
2009 break;
2010 default:
2011 BUG("Unknown http_request target");
2014 credential_fill(&http_auth);
2016 return http_request(url, result, target, options);
2019 int http_get_strbuf(const char *url,
2020 struct strbuf *result,
2021 struct http_get_options *options)
2023 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2027 * Downloads a URL and stores the result in the given file.
2029 * If a previous interrupted download is detected (i.e. a previous temporary
2030 * file is still around) the download is resumed.
2032 static int http_get_file(const char *url, const char *filename,
2033 struct http_get_options *options)
2035 int ret;
2036 struct strbuf tmpfile = STRBUF_INIT;
2037 FILE *result;
2039 strbuf_addf(&tmpfile, "%s.temp", filename);
2040 result = fopen(tmpfile.buf, "a");
2041 if (!result) {
2042 error("Unable to open local file %s", tmpfile.buf);
2043 ret = HTTP_ERROR;
2044 goto cleanup;
2047 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2048 fclose(result);
2050 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2051 ret = HTTP_ERROR;
2052 cleanup:
2053 strbuf_release(&tmpfile);
2054 return ret;
2057 int http_fetch_ref(const char *base, struct ref *ref)
2059 struct http_get_options options = {0};
2060 char *url;
2061 struct strbuf buffer = STRBUF_INIT;
2062 int ret = -1;
2064 options.no_cache = 1;
2066 url = quote_ref_url(base, ref->name);
2067 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2068 strbuf_rtrim(&buffer);
2069 if (buffer.len == 40)
2070 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2071 else if (starts_with(buffer.buf, "ref: ")) {
2072 ref->symref = xstrdup(buffer.buf + 5);
2073 ret = 0;
2077 strbuf_release(&buffer);
2078 free(url);
2079 return ret;
2082 /* Helpers for fetching packs */
2083 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
2085 char *url, *tmp;
2086 struct strbuf buf = STRBUF_INIT;
2088 if (http_is_verbose)
2089 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
2091 end_url_with_slash(&buf, base_url);
2092 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
2093 url = strbuf_detach(&buf, NULL);
2095 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
2096 tmp = strbuf_detach(&buf, NULL);
2098 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2099 error("Unable to get pack index %s", url);
2100 FREE_AND_NULL(tmp);
2103 free(url);
2104 return tmp;
2107 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2108 unsigned char *sha1, const char *base_url)
2110 struct packed_git *new_pack;
2111 char *tmp_idx = NULL;
2112 int ret;
2114 if (has_pack_index(sha1)) {
2115 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2116 if (!new_pack)
2117 return -1; /* parse_pack_index() already issued error message */
2118 goto add_pack;
2121 tmp_idx = fetch_pack_index(sha1, base_url);
2122 if (!tmp_idx)
2123 return -1;
2125 new_pack = parse_pack_index(sha1, tmp_idx);
2126 if (!new_pack) {
2127 unlink(tmp_idx);
2128 free(tmp_idx);
2130 return -1; /* parse_pack_index() already issued error message */
2133 ret = verify_pack_index(new_pack);
2134 if (!ret) {
2135 close_pack_index(new_pack);
2136 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2138 free(tmp_idx);
2139 if (ret)
2140 return -1;
2142 add_pack:
2143 new_pack->next = *packs_head;
2144 *packs_head = new_pack;
2145 return 0;
2148 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2150 struct http_get_options options = {0};
2151 int ret = 0, i = 0;
2152 char *url, *data;
2153 struct strbuf buf = STRBUF_INIT;
2154 unsigned char hash[GIT_MAX_RAWSZ];
2155 const unsigned hexsz = the_hash_algo->hexsz;
2157 end_url_with_slash(&buf, base_url);
2158 strbuf_addstr(&buf, "objects/info/packs");
2159 url = strbuf_detach(&buf, NULL);
2161 options.no_cache = 1;
2162 ret = http_get_strbuf(url, &buf, &options);
2163 if (ret != HTTP_OK)
2164 goto cleanup;
2166 data = buf.buf;
2167 while (i < buf.len) {
2168 switch (data[i]) {
2169 case 'P':
2170 i++;
2171 if (i + hexsz + 12 <= buf.len &&
2172 starts_with(data + i, " pack-") &&
2173 starts_with(data + i + hexsz + 6, ".pack\n")) {
2174 get_sha1_hex(data + i + 6, hash);
2175 fetch_and_setup_pack_index(packs_head, hash,
2176 base_url);
2177 i += hexsz + 11;
2178 break;
2180 default:
2181 while (i < buf.len && data[i] != '\n')
2182 i++;
2184 i++;
2187 cleanup:
2188 free(url);
2189 return ret;
2192 void release_http_pack_request(struct http_pack_request *preq)
2194 if (preq->packfile != NULL) {
2195 fclose(preq->packfile);
2196 preq->packfile = NULL;
2198 preq->slot = NULL;
2199 strbuf_release(&preq->tmpfile);
2200 free(preq->url);
2201 free(preq);
2204 int finish_http_pack_request(struct http_pack_request *preq)
2206 struct packed_git **lst;
2207 struct packed_git *p = preq->target;
2208 char *tmp_idx;
2209 size_t len;
2210 struct child_process ip = CHILD_PROCESS_INIT;
2212 close_pack_index(p);
2214 fclose(preq->packfile);
2215 preq->packfile = NULL;
2217 lst = preq->lst;
2218 while (*lst != p)
2219 lst = &((*lst)->next);
2220 *lst = (*lst)->next;
2222 if (!strip_suffix(preq->tmpfile.buf, ".pack.temp", &len))
2223 BUG("pack tmpfile does not end in .pack.temp?");
2224 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile.buf);
2226 argv_array_push(&ip.args, "index-pack");
2227 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2228 argv_array_push(&ip.args, preq->tmpfile.buf);
2229 ip.git_cmd = 1;
2230 ip.no_stdin = 1;
2231 ip.no_stdout = 1;
2233 if (run_command(&ip)) {
2234 unlink(preq->tmpfile.buf);
2235 unlink(tmp_idx);
2236 free(tmp_idx);
2237 return -1;
2240 unlink(sha1_pack_index_name(p->sha1));
2242 if (finalize_object_file(preq->tmpfile.buf, sha1_pack_name(p->sha1))
2243 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2244 free(tmp_idx);
2245 return -1;
2248 install_packed_git(the_repository, p);
2249 free(tmp_idx);
2250 return 0;
2253 struct http_pack_request *new_http_pack_request(
2254 struct packed_git *target, const char *base_url)
2256 off_t prev_posn = 0;
2257 struct strbuf buf = STRBUF_INIT;
2258 struct http_pack_request *preq;
2260 preq = xcalloc(1, sizeof(*preq));
2261 strbuf_init(&preq->tmpfile, 0);
2262 preq->target = target;
2264 end_url_with_slash(&buf, base_url);
2265 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2266 sha1_to_hex(target->sha1));
2267 preq->url = strbuf_detach(&buf, NULL);
2269 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(target->sha1));
2270 preq->packfile = fopen(preq->tmpfile.buf, "a");
2271 if (!preq->packfile) {
2272 error("Unable to open local file %s for pack",
2273 preq->tmpfile.buf);
2274 goto abort;
2277 preq->slot = get_active_slot();
2278 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2279 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2280 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2281 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2282 no_pragma_header);
2285 * If there is data present from a previous transfer attempt,
2286 * resume where it left off
2288 prev_posn = ftello(preq->packfile);
2289 if (prev_posn>0) {
2290 if (http_is_verbose)
2291 fprintf(stderr,
2292 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2293 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2294 http_opt_request_remainder(preq->slot->curl, prev_posn);
2297 return preq;
2299 abort:
2300 strbuf_release(&preq->tmpfile);
2301 free(preq->url);
2302 free(preq);
2303 return NULL;
2306 /* Helpers for fetching objects (loose) */
2307 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2308 void *data)
2310 unsigned char expn[4096];
2311 size_t size = eltsize * nmemb;
2312 int posn = 0;
2313 struct http_object_request *freq = data;
2314 struct active_request_slot *slot = freq->slot;
2316 if (slot) {
2317 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2318 &slot->http_code);
2319 if (c != CURLE_OK)
2320 BUG("curl_easy_getinfo for HTTP code failed: %s",
2321 curl_easy_strerror(c));
2322 if (slot->http_code >= 300)
2323 return size;
2326 do {
2327 ssize_t retval = xwrite(freq->localfile,
2328 (char *) ptr + posn, size - posn);
2329 if (retval < 0)
2330 return posn;
2331 posn += retval;
2332 } while (posn < size);
2334 freq->stream.avail_in = size;
2335 freq->stream.next_in = (void *)ptr;
2336 do {
2337 freq->stream.next_out = expn;
2338 freq->stream.avail_out = sizeof(expn);
2339 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2340 git_SHA1_Update(&freq->c, expn,
2341 sizeof(expn) - freq->stream.avail_out);
2342 } while (freq->stream.avail_in && freq->zret == Z_OK);
2343 return size;
2346 struct http_object_request *new_http_object_request(const char *base_url,
2347 const struct object_id *oid)
2349 char *hex = oid_to_hex(oid);
2350 struct strbuf filename = STRBUF_INIT;
2351 struct strbuf prevfile = STRBUF_INIT;
2352 int prevlocal;
2353 char prev_buf[PREV_BUF_SIZE];
2354 ssize_t prev_read = 0;
2355 off_t prev_posn = 0;
2356 struct http_object_request *freq;
2358 freq = xcalloc(1, sizeof(*freq));
2359 strbuf_init(&freq->tmpfile, 0);
2360 oidcpy(&freq->oid, oid);
2361 freq->localfile = -1;
2363 loose_object_path(the_repository, &filename, oid);
2364 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2366 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2367 unlink_or_warn(prevfile.buf);
2368 rename(freq->tmpfile.buf, prevfile.buf);
2369 unlink_or_warn(freq->tmpfile.buf);
2370 strbuf_release(&filename);
2372 if (freq->localfile != -1)
2373 error("fd leakage in start: %d", freq->localfile);
2374 freq->localfile = open(freq->tmpfile.buf,
2375 O_WRONLY | O_CREAT | O_EXCL, 0666);
2377 * This could have failed due to the "lazy directory creation";
2378 * try to mkdir the last path component.
2380 if (freq->localfile < 0 && errno == ENOENT) {
2381 char *dir = strrchr(freq->tmpfile.buf, '/');
2382 if (dir) {
2383 *dir = 0;
2384 mkdir(freq->tmpfile.buf, 0777);
2385 *dir = '/';
2387 freq->localfile = open(freq->tmpfile.buf,
2388 O_WRONLY | O_CREAT | O_EXCL, 0666);
2391 if (freq->localfile < 0) {
2392 error_errno("Couldn't create temporary file %s",
2393 freq->tmpfile.buf);
2394 goto abort;
2397 git_inflate_init(&freq->stream);
2399 git_SHA1_Init(&freq->c);
2401 freq->url = get_remote_object_url(base_url, hex, 0);
2404 * If a previous temp file is present, process what was already
2405 * fetched.
2407 prevlocal = open(prevfile.buf, O_RDONLY);
2408 if (prevlocal != -1) {
2409 do {
2410 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2411 if (prev_read>0) {
2412 if (fwrite_sha1_file(prev_buf,
2414 prev_read,
2415 freq) == prev_read) {
2416 prev_posn += prev_read;
2417 } else {
2418 prev_read = -1;
2421 } while (prev_read > 0);
2422 close(prevlocal);
2424 unlink_or_warn(prevfile.buf);
2425 strbuf_release(&prevfile);
2428 * Reset inflate/SHA1 if there was an error reading the previous temp
2429 * file; also rewind to the beginning of the local file.
2431 if (prev_read == -1) {
2432 memset(&freq->stream, 0, sizeof(freq->stream));
2433 git_inflate_init(&freq->stream);
2434 git_SHA1_Init(&freq->c);
2435 if (prev_posn>0) {
2436 prev_posn = 0;
2437 lseek(freq->localfile, 0, SEEK_SET);
2438 if (ftruncate(freq->localfile, 0) < 0) {
2439 error_errno("Couldn't truncate temporary file %s",
2440 freq->tmpfile.buf);
2441 goto abort;
2446 freq->slot = get_active_slot();
2448 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2449 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2450 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2451 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2452 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2453 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2456 * If we have successfully processed data from a previous fetch
2457 * attempt, only fetch the data we don't already have.
2459 if (prev_posn>0) {
2460 if (http_is_verbose)
2461 fprintf(stderr,
2462 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2463 hex, (uintmax_t)prev_posn);
2464 http_opt_request_remainder(freq->slot->curl, prev_posn);
2467 return freq;
2469 abort:
2470 strbuf_release(&prevfile);
2471 free(freq->url);
2472 free(freq);
2473 return NULL;
2476 void process_http_object_request(struct http_object_request *freq)
2478 if (freq->slot == NULL)
2479 return;
2480 freq->curl_result = freq->slot->curl_result;
2481 freq->http_code = freq->slot->http_code;
2482 freq->slot = NULL;
2485 int finish_http_object_request(struct http_object_request *freq)
2487 struct stat st;
2488 struct strbuf filename = STRBUF_INIT;
2490 close(freq->localfile);
2491 freq->localfile = -1;
2493 process_http_object_request(freq);
2495 if (freq->http_code == 416) {
2496 warning("requested range invalid; we may already have all the data.");
2497 } else if (freq->curl_result != CURLE_OK) {
2498 if (stat(freq->tmpfile.buf, &st) == 0)
2499 if (st.st_size == 0)
2500 unlink_or_warn(freq->tmpfile.buf);
2501 return -1;
2504 git_inflate_end(&freq->stream);
2505 git_SHA1_Final(freq->real_oid.hash, &freq->c);
2506 if (freq->zret != Z_STREAM_END) {
2507 unlink_or_warn(freq->tmpfile.buf);
2508 return -1;
2510 if (!oideq(&freq->oid, &freq->real_oid)) {
2511 unlink_or_warn(freq->tmpfile.buf);
2512 return -1;
2514 loose_object_path(the_repository, &filename, &freq->oid);
2515 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2516 strbuf_release(&filename);
2518 return freq->rename;
2521 void abort_http_object_request(struct http_object_request *freq)
2523 unlink_or_warn(freq->tmpfile.buf);
2525 release_http_object_request(freq);
2528 void release_http_object_request(struct http_object_request *freq)
2530 if (freq->localfile != -1) {
2531 close(freq->localfile);
2532 freq->localfile = -1;
2534 FREE_AND_NULL(freq->url);
2535 if (freq->slot != NULL) {
2536 freq->slot->callback_func = NULL;
2537 freq->slot->callback_data = NULL;
2538 release_active_slot(freq->slot);
2539 freq->slot = NULL;
2541 strbuf_release(&freq->tmpfile);