rebase: add coverage of other incompatible options
[alt-git.git] / http.c
blobc4b6ddef287b90f6492706cdaa483c1832d8b06c
1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
3 #include "http.h"
4 #include "config.h"
5 #include "pack.h"
6 #include "sideband.h"
7 #include "run-command.h"
8 #include "url.h"
9 #include "urlmatch.h"
10 #include "credential.h"
11 #include "version.h"
12 #include "pkt-line.h"
13 #include "gettext.h"
14 #include "transport.h"
15 #include "packfile.h"
16 #include "protocol.h"
17 #include "string-list.h"
18 #include "object-store.h"
20 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
21 static int trace_curl_data = 1;
22 static int trace_curl_redact = 1;
23 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
24 int active_requests;
25 int http_is_verbose;
26 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
28 static int min_curl_sessions = 1;
29 static int curl_session_count;
30 static int max_requests = -1;
31 static CURLM *curlm;
32 static CURL *curl_default;
34 #define PREV_BUF_SIZE 4096
36 char curl_errorstr[CURL_ERROR_SIZE];
38 static int curl_ssl_verify = -1;
39 static int curl_ssl_try;
40 static const char *curl_http_version = NULL;
41 static const char *ssl_cert;
42 static const char *ssl_cipherlist;
43 static const char *ssl_version;
44 static struct {
45 const char *name;
46 long ssl_version;
47 } sslversions[] = {
48 { "sslv2", CURL_SSLVERSION_SSLv2 },
49 { "sslv3", CURL_SSLVERSION_SSLv3 },
50 { "tlsv1", CURL_SSLVERSION_TLSv1 },
51 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
52 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
53 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
54 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
55 #endif
56 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
57 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
58 #endif
60 static const char *ssl_key;
61 static const char *ssl_capath;
62 static const char *curl_no_proxy;
63 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
64 static const char *ssl_pinnedkey;
65 #endif
66 static const char *ssl_cainfo;
67 static long curl_low_speed_limit = -1;
68 static long curl_low_speed_time = -1;
69 static int curl_ftp_no_epsv;
70 static const char *curl_http_proxy;
71 static const char *http_proxy_authmethod;
73 static const char *http_proxy_ssl_cert;
74 static const char *http_proxy_ssl_key;
75 static const char *http_proxy_ssl_ca_info;
76 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
77 static int proxy_ssl_cert_password_required;
79 static struct {
80 const char *name;
81 long curlauth_param;
82 } proxy_authmethods[] = {
83 { "basic", CURLAUTH_BASIC },
84 { "digest", CURLAUTH_DIGEST },
85 { "negotiate", CURLAUTH_GSSNEGOTIATE },
86 { "ntlm", CURLAUTH_NTLM },
87 { "anyauth", CURLAUTH_ANY },
89 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
90 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
91 * here, too
94 #ifdef CURLGSSAPI_DELEGATION_FLAG
95 static const char *curl_deleg;
96 static struct {
97 const char *name;
98 long curl_deleg_param;
99 } curl_deleg_levels[] = {
100 { "none", CURLGSSAPI_DELEGATION_NONE },
101 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
102 { "always", CURLGSSAPI_DELEGATION_FLAG },
104 #endif
106 static struct credential proxy_auth = CREDENTIAL_INIT;
107 static const char *curl_proxyuserpwd;
108 static const char *curl_cookie_file;
109 static int curl_save_cookies;
110 struct credential http_auth = CREDENTIAL_INIT;
111 static int http_proactive_auth;
112 static const char *user_agent;
113 static int curl_empty_auth = -1;
115 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
117 static struct credential cert_auth = CREDENTIAL_INIT;
118 static int ssl_cert_password_required;
119 static unsigned long http_auth_methods = CURLAUTH_ANY;
120 static int http_auth_methods_restricted;
121 /* Modes for which empty_auth cannot actually help us. */
122 static unsigned long empty_auth_useless =
123 CURLAUTH_BASIC
124 | CURLAUTH_DIGEST_IE
125 | CURLAUTH_DIGEST;
127 static struct curl_slist *pragma_header;
128 static struct curl_slist *no_pragma_header;
129 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
131 static struct curl_slist *host_resolutions;
133 static struct active_request_slot *active_queue_head;
135 static char *cached_accept_language;
137 static char *http_ssl_backend;
139 static int http_schannel_check_revoke = 1;
141 * With the backend being set to `schannel`, setting sslCAinfo would override
142 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
143 * by default.
145 static int http_schannel_use_ssl_cainfo;
147 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
149 size_t size = eltsize * nmemb;
150 struct buffer *buffer = buffer_;
152 if (size > buffer->buf.len - buffer->posn)
153 size = buffer->buf.len - buffer->posn;
154 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
155 buffer->posn += size;
157 return size / eltsize;
160 int seek_buffer(void *clientp, curl_off_t offset, int origin)
162 struct buffer *buffer = clientp;
164 if (origin != SEEK_SET)
165 BUG("seek_buffer only handles SEEK_SET");
166 if (offset < 0 || offset >= buffer->buf.len) {
167 error("curl seek would be outside of buffer");
168 return CURL_SEEKFUNC_FAIL;
171 buffer->posn = offset;
172 return CURL_SEEKFUNC_OK;
175 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
177 size_t size = eltsize * nmemb;
178 struct strbuf *buffer = buffer_;
180 strbuf_add(buffer, ptr, size);
181 return nmemb;
184 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
186 return nmemb;
189 static void closedown_active_slot(struct active_request_slot *slot)
191 active_requests--;
192 slot->in_use = 0;
195 static void finish_active_slot(struct active_request_slot *slot)
197 closedown_active_slot(slot);
198 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
200 if (slot->finished)
201 (*slot->finished) = 1;
203 /* Store slot results so they can be read after the slot is reused */
204 if (slot->results) {
205 slot->results->curl_result = slot->curl_result;
206 slot->results->http_code = slot->http_code;
207 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
208 &slot->results->auth_avail);
210 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
211 &slot->results->http_connectcode);
214 /* Run callback if appropriate */
215 if (slot->callback_func)
216 slot->callback_func(slot->callback_data);
219 static void xmulti_remove_handle(struct active_request_slot *slot)
221 curl_multi_remove_handle(curlm, slot->curl);
224 static void process_curl_messages(void)
226 int num_messages;
227 struct active_request_slot *slot;
228 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
230 while (curl_message != NULL) {
231 if (curl_message->msg == CURLMSG_DONE) {
232 int curl_result = curl_message->data.result;
233 slot = active_queue_head;
234 while (slot != NULL &&
235 slot->curl != curl_message->easy_handle)
236 slot = slot->next;
237 if (slot) {
238 xmulti_remove_handle(slot);
239 slot->curl_result = curl_result;
240 finish_active_slot(slot);
241 } else {
242 fprintf(stderr, "Received DONE message for unknown request!\n");
244 } else {
245 fprintf(stderr, "Unknown CURL message received: %d\n",
246 (int)curl_message->msg);
248 curl_message = curl_multi_info_read(curlm, &num_messages);
252 static int http_options(const char *var, const char *value, void *cb)
254 if (!strcmp("http.version", var)) {
255 return git_config_string(&curl_http_version, var, value);
257 if (!strcmp("http.sslverify", var)) {
258 curl_ssl_verify = git_config_bool(var, value);
259 return 0;
261 if (!strcmp("http.sslcipherlist", var))
262 return git_config_string(&ssl_cipherlist, var, value);
263 if (!strcmp("http.sslversion", var))
264 return git_config_string(&ssl_version, var, value);
265 if (!strcmp("http.sslcert", var))
266 return git_config_pathname(&ssl_cert, var, value);
267 if (!strcmp("http.sslkey", var))
268 return git_config_pathname(&ssl_key, var, value);
269 if (!strcmp("http.sslcapath", var))
270 return git_config_pathname(&ssl_capath, var, value);
271 if (!strcmp("http.sslcainfo", var))
272 return git_config_pathname(&ssl_cainfo, var, value);
273 if (!strcmp("http.sslcertpasswordprotected", var)) {
274 ssl_cert_password_required = git_config_bool(var, value);
275 return 0;
277 if (!strcmp("http.ssltry", var)) {
278 curl_ssl_try = git_config_bool(var, value);
279 return 0;
281 if (!strcmp("http.sslbackend", var)) {
282 free(http_ssl_backend);
283 http_ssl_backend = xstrdup_or_null(value);
284 return 0;
287 if (!strcmp("http.schannelcheckrevoke", var)) {
288 http_schannel_check_revoke = git_config_bool(var, value);
289 return 0;
292 if (!strcmp("http.schannelusesslcainfo", var)) {
293 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
294 return 0;
297 if (!strcmp("http.minsessions", var)) {
298 min_curl_sessions = git_config_int(var, value);
299 if (min_curl_sessions > 1)
300 min_curl_sessions = 1;
301 return 0;
303 if (!strcmp("http.maxrequests", var)) {
304 max_requests = git_config_int(var, value);
305 return 0;
307 if (!strcmp("http.lowspeedlimit", var)) {
308 curl_low_speed_limit = (long)git_config_int(var, value);
309 return 0;
311 if (!strcmp("http.lowspeedtime", var)) {
312 curl_low_speed_time = (long)git_config_int(var, value);
313 return 0;
316 if (!strcmp("http.noepsv", var)) {
317 curl_ftp_no_epsv = git_config_bool(var, value);
318 return 0;
320 if (!strcmp("http.proxy", var))
321 return git_config_string(&curl_http_proxy, var, value);
323 if (!strcmp("http.proxyauthmethod", var))
324 return git_config_string(&http_proxy_authmethod, var, value);
326 if (!strcmp("http.proxysslcert", var))
327 return git_config_string(&http_proxy_ssl_cert, var, value);
329 if (!strcmp("http.proxysslkey", var))
330 return git_config_string(&http_proxy_ssl_key, var, value);
332 if (!strcmp("http.proxysslcainfo", var))
333 return git_config_string(&http_proxy_ssl_ca_info, var, value);
335 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
336 proxy_ssl_cert_password_required = git_config_bool(var, value);
337 return 0;
340 if (!strcmp("http.cookiefile", var))
341 return git_config_pathname(&curl_cookie_file, var, value);
342 if (!strcmp("http.savecookies", var)) {
343 curl_save_cookies = git_config_bool(var, value);
344 return 0;
347 if (!strcmp("http.postbuffer", var)) {
348 http_post_buffer = git_config_ssize_t(var, value);
349 if (http_post_buffer < 0)
350 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
351 if (http_post_buffer < LARGE_PACKET_MAX)
352 http_post_buffer = LARGE_PACKET_MAX;
353 return 0;
356 if (!strcmp("http.useragent", var))
357 return git_config_string(&user_agent, var, value);
359 if (!strcmp("http.emptyauth", var)) {
360 if (value && !strcmp("auto", value))
361 curl_empty_auth = -1;
362 else
363 curl_empty_auth = git_config_bool(var, value);
364 return 0;
367 if (!strcmp("http.delegation", var)) {
368 #ifdef CURLGSSAPI_DELEGATION_FLAG
369 return git_config_string(&curl_deleg, var, value);
370 #else
371 warning(_("Delegation control is not supported with cURL < 7.22.0"));
372 return 0;
373 #endif
376 if (!strcmp("http.pinnedpubkey", var)) {
377 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
378 return git_config_pathname(&ssl_pinnedkey, var, value);
379 #else
380 warning(_("Public key pinning not supported with cURL < 7.39.0"));
381 return 0;
382 #endif
385 if (!strcmp("http.extraheader", var)) {
386 if (!value) {
387 return config_error_nonbool(var);
388 } else if (!*value) {
389 string_list_clear(&extra_http_headers, 0);
390 } else {
391 string_list_append(&extra_http_headers, value);
393 return 0;
396 if (!strcmp("http.curloptresolve", var)) {
397 if (!value) {
398 return config_error_nonbool(var);
399 } else if (!*value) {
400 curl_slist_free_all(host_resolutions);
401 host_resolutions = NULL;
402 } else {
403 host_resolutions = curl_slist_append(host_resolutions, value);
405 return 0;
408 if (!strcmp("http.followredirects", var)) {
409 if (value && !strcmp(value, "initial"))
410 http_follow_config = HTTP_FOLLOW_INITIAL;
411 else if (git_config_bool(var, value))
412 http_follow_config = HTTP_FOLLOW_ALWAYS;
413 else
414 http_follow_config = HTTP_FOLLOW_NONE;
415 return 0;
418 /* Fall back on the default ones */
419 return git_default_config(var, value, cb);
422 static int curl_empty_auth_enabled(void)
424 if (curl_empty_auth >= 0)
425 return curl_empty_auth;
428 * In the automatic case, kick in the empty-auth
429 * hack as long as we would potentially try some
430 * method more exotic than "Basic" or "Digest".
432 * But only do this when this is our second or
433 * subsequent request, as by then we know what
434 * methods are available.
436 if (http_auth_methods_restricted &&
437 (http_auth_methods & ~empty_auth_useless))
438 return 1;
439 return 0;
442 static void init_curl_http_auth(CURL *result)
444 if (!http_auth.username || !*http_auth.username) {
445 if (curl_empty_auth_enabled())
446 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
447 return;
450 credential_fill(&http_auth);
452 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
453 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
456 /* *var must be free-able */
457 static void var_override(const char **var, char *value)
459 if (value) {
460 free((void *)*var);
461 *var = xstrdup(value);
465 static void set_proxyauth_name_password(CURL *result)
467 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
468 proxy_auth.username);
469 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
470 proxy_auth.password);
473 static void init_curl_proxy_auth(CURL *result)
475 if (proxy_auth.username) {
476 if (!proxy_auth.password)
477 credential_fill(&proxy_auth);
478 set_proxyauth_name_password(result);
481 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
483 if (http_proxy_authmethod) {
484 int i;
485 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
486 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
487 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
488 proxy_authmethods[i].curlauth_param);
489 break;
492 if (i == ARRAY_SIZE(proxy_authmethods)) {
493 warning("unsupported proxy authentication method %s: using anyauth",
494 http_proxy_authmethod);
495 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
498 else
499 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
502 static int has_cert_password(void)
504 if (ssl_cert == NULL || ssl_cert_password_required != 1)
505 return 0;
506 if (!cert_auth.password) {
507 cert_auth.protocol = xstrdup("cert");
508 cert_auth.host = xstrdup("");
509 cert_auth.username = xstrdup("");
510 cert_auth.path = xstrdup(ssl_cert);
511 credential_fill(&cert_auth);
513 return 1;
516 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
517 static int has_proxy_cert_password(void)
519 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
520 return 0;
521 if (!proxy_cert_auth.password) {
522 proxy_cert_auth.protocol = xstrdup("cert");
523 proxy_cert_auth.host = xstrdup("");
524 proxy_cert_auth.username = xstrdup("");
525 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
526 credential_fill(&proxy_cert_auth);
528 return 1;
530 #endif
532 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
533 static void set_curl_keepalive(CURL *c)
535 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
538 #else
539 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
541 int ka = 1;
542 int rc;
543 socklen_t len = (socklen_t)sizeof(ka);
545 if (type != CURLSOCKTYPE_IPCXN)
546 return 0;
548 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
549 if (rc < 0)
550 warning_errno("unable to set SO_KEEPALIVE on socket");
552 return CURL_SOCKOPT_OK;
555 static void set_curl_keepalive(CURL *c)
557 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
559 #endif
561 /* Return 1 if redactions have been made, 0 otherwise. */
562 static int redact_sensitive_header(struct strbuf *header, size_t offset)
564 int ret = 0;
565 const char *sensitive_header;
567 if (trace_curl_redact &&
568 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
569 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
570 /* The first token is the type, which is OK to log */
571 while (isspace(*sensitive_header))
572 sensitive_header++;
573 while (*sensitive_header && !isspace(*sensitive_header))
574 sensitive_header++;
575 /* Everything else is opaque and possibly sensitive */
576 strbuf_setlen(header, sensitive_header - header->buf);
577 strbuf_addstr(header, " <redacted>");
578 ret = 1;
579 } else if (trace_curl_redact &&
580 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
581 struct strbuf redacted_header = STRBUF_INIT;
582 const char *cookie;
584 while (isspace(*sensitive_header))
585 sensitive_header++;
587 cookie = sensitive_header;
589 while (cookie) {
590 char *equals;
591 char *semicolon = strstr(cookie, "; ");
592 if (semicolon)
593 *semicolon = 0;
594 equals = strchrnul(cookie, '=');
595 if (!equals) {
596 /* invalid cookie, just append and continue */
597 strbuf_addstr(&redacted_header, cookie);
598 continue;
600 strbuf_add(&redacted_header, cookie, equals - cookie);
601 strbuf_addstr(&redacted_header, "=<redacted>");
602 if (semicolon) {
604 * There are more cookies. (Or, for some
605 * reason, the input string ends in "; ".)
607 strbuf_addstr(&redacted_header, "; ");
608 cookie = semicolon + strlen("; ");
609 } else {
610 cookie = NULL;
614 strbuf_setlen(header, sensitive_header - header->buf);
615 strbuf_addbuf(header, &redacted_header);
616 ret = 1;
618 return ret;
621 /* Redact headers in info */
622 static void redact_sensitive_info_header(struct strbuf *header)
624 const char *sensitive_header;
627 * curl's h2h3 prints headers in info, e.g.:
628 * h2h3 [<header-name>: <header-val>]
630 if (trace_curl_redact &&
631 skip_iprefix(header->buf, "h2h3 [", &sensitive_header)) {
632 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
633 /* redaction ate our closing bracket */
634 strbuf_addch(header, ']');
639 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
641 struct strbuf out = STRBUF_INIT;
642 struct strbuf **headers, **header;
644 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
645 text, (long)size, (long)size);
646 trace_strbuf(&trace_curl, &out);
647 strbuf_reset(&out);
648 strbuf_add(&out, ptr, size);
649 headers = strbuf_split_max(&out, '\n', 0);
651 for (header = headers; *header; header++) {
652 if (hide_sensitive_header)
653 redact_sensitive_header(*header, 0);
654 strbuf_insertstr((*header), 0, text);
655 strbuf_insertstr((*header), strlen(text), ": ");
656 strbuf_rtrim((*header));
657 strbuf_addch((*header), '\n');
658 trace_strbuf(&trace_curl, (*header));
660 strbuf_list_free(headers);
661 strbuf_release(&out);
664 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
666 size_t i;
667 struct strbuf out = STRBUF_INIT;
668 unsigned int width = 60;
670 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
671 text, (long)size, (long)size);
672 trace_strbuf(&trace_curl, &out);
674 for (i = 0; i < size; i += width) {
675 size_t w;
677 strbuf_reset(&out);
678 strbuf_addf(&out, "%s: ", text);
679 for (w = 0; (w < width) && (i + w < size); w++) {
680 unsigned char ch = ptr[i + w];
682 strbuf_addch(&out,
683 (ch >= 0x20) && (ch < 0x80)
684 ? ch : '.');
686 strbuf_addch(&out, '\n');
687 trace_strbuf(&trace_curl, &out);
689 strbuf_release(&out);
692 static void curl_dump_info(char *data, size_t size)
694 struct strbuf buf = STRBUF_INIT;
696 strbuf_add(&buf, data, size);
698 redact_sensitive_info_header(&buf);
699 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
701 strbuf_release(&buf);
704 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
706 const char *text;
707 enum { NO_FILTER = 0, DO_FILTER = 1 };
709 switch (type) {
710 case CURLINFO_TEXT:
711 curl_dump_info(data, size);
712 break;
713 case CURLINFO_HEADER_OUT:
714 text = "=> Send header";
715 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
716 break;
717 case CURLINFO_DATA_OUT:
718 if (trace_curl_data) {
719 text = "=> Send data";
720 curl_dump_data(text, (unsigned char *)data, size);
722 break;
723 case CURLINFO_SSL_DATA_OUT:
724 if (trace_curl_data) {
725 text = "=> Send SSL data";
726 curl_dump_data(text, (unsigned char *)data, size);
728 break;
729 case CURLINFO_HEADER_IN:
730 text = "<= Recv header";
731 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
732 break;
733 case CURLINFO_DATA_IN:
734 if (trace_curl_data) {
735 text = "<= Recv data";
736 curl_dump_data(text, (unsigned char *)data, size);
738 break;
739 case CURLINFO_SSL_DATA_IN:
740 if (trace_curl_data) {
741 text = "<= Recv SSL data";
742 curl_dump_data(text, (unsigned char *)data, size);
744 break;
746 default: /* we ignore unknown types by default */
747 return 0;
749 return 0;
752 void http_trace_curl_no_data(void)
754 trace_override_envvar(&trace_curl, "1");
755 trace_curl_data = 0;
758 void setup_curl_trace(CURL *handle)
760 if (!trace_want(&trace_curl))
761 return;
762 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
763 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
764 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
767 static void proto_list_append(struct strbuf *list, const char *proto)
769 if (!list)
770 return;
771 if (list->len)
772 strbuf_addch(list, ',');
773 strbuf_addstr(list, proto);
776 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
778 long bits = 0;
780 if (is_transport_allowed("http", from_user)) {
781 bits |= CURLPROTO_HTTP;
782 proto_list_append(list, "http");
784 if (is_transport_allowed("https", from_user)) {
785 bits |= CURLPROTO_HTTPS;
786 proto_list_append(list, "https");
788 if (is_transport_allowed("ftp", from_user)) {
789 bits |= CURLPROTO_FTP;
790 proto_list_append(list, "ftp");
792 if (is_transport_allowed("ftps", from_user)) {
793 bits |= CURLPROTO_FTPS;
794 proto_list_append(list, "ftps");
797 return bits;
800 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
801 static int get_curl_http_version_opt(const char *version_string, long *opt)
803 int i;
804 static struct {
805 const char *name;
806 long opt_token;
807 } choice[] = {
808 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
809 { "HTTP/2", CURL_HTTP_VERSION_2 }
812 for (i = 0; i < ARRAY_SIZE(choice); i++) {
813 if (!strcmp(version_string, choice[i].name)) {
814 *opt = choice[i].opt_token;
815 return 0;
819 warning("unknown value given to http.version: '%s'", version_string);
820 return -1; /* not found */
823 #endif
825 static CURL *get_curl_handle(void)
827 CURL *result = curl_easy_init();
829 if (!result)
830 die("curl_easy_init failed");
832 if (!curl_ssl_verify) {
833 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
834 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
835 } else {
836 /* Verify authenticity of the peer's certificate */
837 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
838 /* The name in the cert must match whom we tried to connect */
839 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
842 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
843 if (curl_http_version) {
844 long opt;
845 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
846 /* Set request use http version */
847 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
850 #endif
852 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
853 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
855 #ifdef CURLGSSAPI_DELEGATION_FLAG
856 if (curl_deleg) {
857 int i;
858 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
859 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
860 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
861 curl_deleg_levels[i].curl_deleg_param);
862 break;
865 if (i == ARRAY_SIZE(curl_deleg_levels))
866 warning("Unknown delegation method '%s': using default",
867 curl_deleg);
869 #endif
871 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
872 !http_schannel_check_revoke) {
873 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
874 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
875 #else
876 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
877 #endif
880 if (http_proactive_auth)
881 init_curl_http_auth(result);
883 if (getenv("GIT_SSL_VERSION"))
884 ssl_version = getenv("GIT_SSL_VERSION");
885 if (ssl_version && *ssl_version) {
886 int i;
887 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
888 if (!strcmp(ssl_version, sslversions[i].name)) {
889 curl_easy_setopt(result, CURLOPT_SSLVERSION,
890 sslversions[i].ssl_version);
891 break;
894 if (i == ARRAY_SIZE(sslversions))
895 warning("unsupported ssl version %s: using default",
896 ssl_version);
899 if (getenv("GIT_SSL_CIPHER_LIST"))
900 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
901 if (ssl_cipherlist != NULL && *ssl_cipherlist)
902 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
903 ssl_cipherlist);
905 if (ssl_cert)
906 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
907 if (has_cert_password())
908 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
909 if (ssl_key)
910 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
911 if (ssl_capath)
912 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
913 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
914 if (ssl_pinnedkey)
915 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
916 #endif
917 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
918 !http_schannel_use_ssl_cainfo) {
919 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
920 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
921 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
922 #endif
923 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
924 if (ssl_cainfo)
925 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
926 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
927 if (http_proxy_ssl_ca_info)
928 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
929 #endif
932 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
933 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
934 curl_low_speed_limit);
935 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
936 curl_low_speed_time);
939 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
940 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
942 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
944 struct strbuf buf = STRBUF_INIT;
946 get_curl_allowed_protocols(0, &buf);
947 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
948 strbuf_reset(&buf);
950 get_curl_allowed_protocols(-1, &buf);
951 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
952 strbuf_release(&buf);
954 #else
955 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
956 get_curl_allowed_protocols(0, NULL));
957 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
958 get_curl_allowed_protocols(-1, NULL));
959 #endif
961 if (getenv("GIT_CURL_VERBOSE"))
962 http_trace_curl_no_data();
963 setup_curl_trace(result);
964 if (getenv("GIT_TRACE_CURL_NO_DATA"))
965 trace_curl_data = 0;
966 if (!git_env_bool("GIT_TRACE_REDACT", 1))
967 trace_curl_redact = 0;
969 curl_easy_setopt(result, CURLOPT_USERAGENT,
970 user_agent ? user_agent : git_user_agent());
972 if (curl_ftp_no_epsv)
973 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
975 if (curl_ssl_try)
976 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
979 * CURL also examines these variables as a fallback; but we need to query
980 * them here in order to decide whether to prompt for missing password (cf.
981 * init_curl_proxy_auth()).
983 * Unlike many other common environment variables, these are historically
984 * lowercase only. It appears that CURL did not know this and implemented
985 * only uppercase variants, which was later corrected to take both - with
986 * the exception of http_proxy, which is lowercase only also in CURL. As
987 * the lowercase versions are the historical quasi-standard, they take
988 * precedence here, as in CURL.
990 if (!curl_http_proxy) {
991 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
992 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
993 var_override(&curl_http_proxy, getenv("https_proxy"));
994 } else {
995 var_override(&curl_http_proxy, getenv("http_proxy"));
997 if (!curl_http_proxy) {
998 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
999 var_override(&curl_http_proxy, getenv("all_proxy"));
1003 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1005 * Handle case with the empty http.proxy value here to keep
1006 * common code clean.
1007 * NB: empty option disables proxying at all.
1009 curl_easy_setopt(result, CURLOPT_PROXY, "");
1010 } else if (curl_http_proxy) {
1011 if (starts_with(curl_http_proxy, "socks5h"))
1012 curl_easy_setopt(result,
1013 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1014 else if (starts_with(curl_http_proxy, "socks5"))
1015 curl_easy_setopt(result,
1016 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1017 else if (starts_with(curl_http_proxy, "socks4a"))
1018 curl_easy_setopt(result,
1019 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1020 else if (starts_with(curl_http_proxy, "socks"))
1021 curl_easy_setopt(result,
1022 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1023 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1024 else if (starts_with(curl_http_proxy, "https")) {
1025 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1027 if (http_proxy_ssl_cert)
1028 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1030 if (http_proxy_ssl_key)
1031 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1033 if (has_proxy_cert_password())
1034 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1036 #endif
1037 if (strstr(curl_http_proxy, "://"))
1038 credential_from_url(&proxy_auth, curl_http_proxy);
1039 else {
1040 struct strbuf url = STRBUF_INIT;
1041 strbuf_addf(&url, "http://%s", curl_http_proxy);
1042 credential_from_url(&proxy_auth, url.buf);
1043 strbuf_release(&url);
1046 if (!proxy_auth.host)
1047 die("Invalid proxy URL '%s'", curl_http_proxy);
1049 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1050 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1051 var_override(&curl_no_proxy, getenv("no_proxy"));
1052 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1054 init_curl_proxy_auth(result);
1056 set_curl_keepalive(result);
1058 return result;
1061 static void set_from_env(const char **var, const char *envname)
1063 const char *val = getenv(envname);
1064 if (val)
1065 *var = val;
1068 void http_init(struct remote *remote, const char *url, int proactive_auth)
1070 char *low_speed_limit;
1071 char *low_speed_time;
1072 char *normalized_url;
1073 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1075 config.section = "http";
1076 config.key = NULL;
1077 config.collect_fn = http_options;
1078 config.cascade_fn = git_default_config;
1079 config.cb = NULL;
1081 http_is_verbose = 0;
1082 normalized_url = url_normalize(url, &config.url);
1084 git_config(urlmatch_config_entry, &config);
1085 free(normalized_url);
1086 string_list_clear(&config.vars, 1);
1088 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1089 if (http_ssl_backend) {
1090 const curl_ssl_backend **backends;
1091 struct strbuf buf = STRBUF_INIT;
1092 int i;
1094 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1095 case CURLSSLSET_UNKNOWN_BACKEND:
1096 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1097 "Supported SSL backends:"),
1098 http_ssl_backend);
1099 for (i = 0; backends[i]; i++)
1100 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1101 die("%s", buf.buf);
1102 case CURLSSLSET_NO_BACKENDS:
1103 die(_("Could not set SSL backend to '%s': "
1104 "cURL was built without SSL backends"),
1105 http_ssl_backend);
1106 case CURLSSLSET_TOO_LATE:
1107 die(_("Could not set SSL backend to '%s': already set"),
1108 http_ssl_backend);
1109 case CURLSSLSET_OK:
1110 break; /* Okay! */
1113 #endif
1115 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1116 die("curl_global_init failed");
1118 http_proactive_auth = proactive_auth;
1120 if (remote && remote->http_proxy)
1121 curl_http_proxy = xstrdup(remote->http_proxy);
1123 if (remote)
1124 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1126 pragma_header = curl_slist_append(http_copy_default_headers(),
1127 "Pragma: no-cache");
1128 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1129 "Pragma:");
1132 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1133 if (http_max_requests)
1134 max_requests = atoi(http_max_requests);
1137 curlm = curl_multi_init();
1138 if (!curlm)
1139 die("curl_multi_init failed");
1141 if (getenv("GIT_SSL_NO_VERIFY"))
1142 curl_ssl_verify = 0;
1144 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1145 set_from_env(&ssl_key, "GIT_SSL_KEY");
1146 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1147 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1149 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1151 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1152 if (low_speed_limit)
1153 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1154 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1155 if (low_speed_time)
1156 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1158 if (curl_ssl_verify == -1)
1159 curl_ssl_verify = 1;
1161 curl_session_count = 0;
1162 if (max_requests < 1)
1163 max_requests = DEFAULT_MAX_REQUESTS;
1165 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1166 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1167 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1169 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1170 proxy_ssl_cert_password_required = 1;
1172 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1173 curl_ftp_no_epsv = 1;
1175 if (url) {
1176 credential_from_url(&http_auth, url);
1177 if (!ssl_cert_password_required &&
1178 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1179 starts_with(url, "https://"))
1180 ssl_cert_password_required = 1;
1183 curl_default = get_curl_handle();
1186 void http_cleanup(void)
1188 struct active_request_slot *slot = active_queue_head;
1190 while (slot != NULL) {
1191 struct active_request_slot *next = slot->next;
1192 if (slot->curl) {
1193 xmulti_remove_handle(slot);
1194 curl_easy_cleanup(slot->curl);
1196 free(slot);
1197 slot = next;
1199 active_queue_head = NULL;
1201 curl_easy_cleanup(curl_default);
1203 curl_multi_cleanup(curlm);
1204 curl_global_cleanup();
1206 string_list_clear(&extra_http_headers, 0);
1208 curl_slist_free_all(pragma_header);
1209 pragma_header = NULL;
1211 curl_slist_free_all(no_pragma_header);
1212 no_pragma_header = NULL;
1214 curl_slist_free_all(host_resolutions);
1215 host_resolutions = NULL;
1217 if (curl_http_proxy) {
1218 free((void *)curl_http_proxy);
1219 curl_http_proxy = NULL;
1222 if (proxy_auth.password) {
1223 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1224 FREE_AND_NULL(proxy_auth.password);
1227 free((void *)curl_proxyuserpwd);
1228 curl_proxyuserpwd = NULL;
1230 free((void *)http_proxy_authmethod);
1231 http_proxy_authmethod = NULL;
1233 if (cert_auth.password) {
1234 memset(cert_auth.password, 0, strlen(cert_auth.password));
1235 FREE_AND_NULL(cert_auth.password);
1237 ssl_cert_password_required = 0;
1239 if (proxy_cert_auth.password) {
1240 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1241 FREE_AND_NULL(proxy_cert_auth.password);
1243 proxy_ssl_cert_password_required = 0;
1245 FREE_AND_NULL(cached_accept_language);
1248 struct active_request_slot *get_active_slot(void)
1250 struct active_request_slot *slot = active_queue_head;
1251 struct active_request_slot *newslot;
1253 int num_transfers;
1255 /* Wait for a slot to open up if the queue is full */
1256 while (active_requests >= max_requests) {
1257 curl_multi_perform(curlm, &num_transfers);
1258 if (num_transfers < active_requests)
1259 process_curl_messages();
1262 while (slot != NULL && slot->in_use)
1263 slot = slot->next;
1265 if (!slot) {
1266 newslot = xmalloc(sizeof(*newslot));
1267 newslot->curl = NULL;
1268 newslot->in_use = 0;
1269 newslot->next = NULL;
1271 slot = active_queue_head;
1272 if (!slot) {
1273 active_queue_head = newslot;
1274 } else {
1275 while (slot->next != NULL)
1276 slot = slot->next;
1277 slot->next = newslot;
1279 slot = newslot;
1282 if (!slot->curl) {
1283 slot->curl = curl_easy_duphandle(curl_default);
1284 curl_session_count++;
1287 active_requests++;
1288 slot->in_use = 1;
1289 slot->results = NULL;
1290 slot->finished = NULL;
1291 slot->callback_data = NULL;
1292 slot->callback_func = NULL;
1293 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1294 if (curl_save_cookies)
1295 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1296 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1297 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1298 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1299 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1300 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1301 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1302 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1303 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1304 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1305 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1306 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1309 * Default following to off unless "ALWAYS" is configured; this gives
1310 * callers a sane starting point, and they can tweak for individual
1311 * HTTP_FOLLOW_* cases themselves.
1313 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1314 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1315 else
1316 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1318 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1319 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1320 if (http_auth.password || curl_empty_auth_enabled())
1321 init_curl_http_auth(slot->curl);
1323 return slot;
1326 int start_active_slot(struct active_request_slot *slot)
1328 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1329 int num_transfers;
1331 if (curlm_result != CURLM_OK &&
1332 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1333 warning("curl_multi_add_handle failed: %s",
1334 curl_multi_strerror(curlm_result));
1335 active_requests--;
1336 slot->in_use = 0;
1337 return 0;
1341 * We know there must be something to do, since we just added
1342 * something.
1344 curl_multi_perform(curlm, &num_transfers);
1345 return 1;
1348 struct fill_chain {
1349 void *data;
1350 int (*fill)(void *);
1351 struct fill_chain *next;
1354 static struct fill_chain *fill_cfg;
1356 void add_fill_function(void *data, int (*fill)(void *))
1358 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1359 struct fill_chain **linkp = &fill_cfg;
1360 new_fill->data = data;
1361 new_fill->fill = fill;
1362 new_fill->next = NULL;
1363 while (*linkp)
1364 linkp = &(*linkp)->next;
1365 *linkp = new_fill;
1368 void fill_active_slots(void)
1370 struct active_request_slot *slot = active_queue_head;
1372 while (active_requests < max_requests) {
1373 struct fill_chain *fill;
1374 for (fill = fill_cfg; fill; fill = fill->next)
1375 if (fill->fill(fill->data))
1376 break;
1378 if (!fill)
1379 break;
1382 while (slot != NULL) {
1383 if (!slot->in_use && slot->curl != NULL
1384 && curl_session_count > min_curl_sessions) {
1385 curl_easy_cleanup(slot->curl);
1386 slot->curl = NULL;
1387 curl_session_count--;
1389 slot = slot->next;
1393 void step_active_slots(void)
1395 int num_transfers;
1396 CURLMcode curlm_result;
1398 do {
1399 curlm_result = curl_multi_perform(curlm, &num_transfers);
1400 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1401 if (num_transfers < active_requests) {
1402 process_curl_messages();
1403 fill_active_slots();
1407 void run_active_slot(struct active_request_slot *slot)
1409 fd_set readfds;
1410 fd_set writefds;
1411 fd_set excfds;
1412 int max_fd;
1413 struct timeval select_timeout;
1414 int finished = 0;
1416 slot->finished = &finished;
1417 while (!finished) {
1418 step_active_slots();
1420 if (slot->in_use) {
1421 long curl_timeout;
1422 curl_multi_timeout(curlm, &curl_timeout);
1423 if (curl_timeout == 0) {
1424 continue;
1425 } else if (curl_timeout == -1) {
1426 select_timeout.tv_sec = 0;
1427 select_timeout.tv_usec = 50000;
1428 } else {
1429 select_timeout.tv_sec = curl_timeout / 1000;
1430 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1433 max_fd = -1;
1434 FD_ZERO(&readfds);
1435 FD_ZERO(&writefds);
1436 FD_ZERO(&excfds);
1437 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1440 * It can happen that curl_multi_timeout returns a pathologically
1441 * long timeout when curl_multi_fdset returns no file descriptors
1442 * to read. See commit message for more details.
1444 if (max_fd < 0 &&
1445 (select_timeout.tv_sec > 0 ||
1446 select_timeout.tv_usec > 50000)) {
1447 select_timeout.tv_sec = 0;
1448 select_timeout.tv_usec = 50000;
1451 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1456 * The value of slot->finished we set before the loop was used
1457 * to set our "finished" variable when our request completed.
1459 * 1. The slot may not have been reused for another requst
1460 * yet, in which case it still has &finished.
1462 * 2. The slot may already be in-use to serve another request,
1463 * which can further be divided into two cases:
1465 * (a) If call run_active_slot() hasn't been called for that
1466 * other request, slot->finished would have been cleared
1467 * by get_active_slot() and has NULL.
1469 * (b) If the request did call run_active_slot(), then the
1470 * call would have updated slot->finished at the beginning
1471 * of this function, and with the clearing of the member
1472 * below, we would find that slot->finished is now NULL.
1474 * In all cases, slot->finished has no useful information to
1475 * anybody at this point. Some compilers warn us for
1476 * attempting to smuggle a pointer that is about to become
1477 * invalid, i.e. &finished. We clear it here to assure them.
1479 slot->finished = NULL;
1482 static void release_active_slot(struct active_request_slot *slot)
1484 closedown_active_slot(slot);
1485 if (slot->curl) {
1486 xmulti_remove_handle(slot);
1487 if (curl_session_count > min_curl_sessions) {
1488 curl_easy_cleanup(slot->curl);
1489 slot->curl = NULL;
1490 curl_session_count--;
1493 fill_active_slots();
1496 void finish_all_active_slots(void)
1498 struct active_request_slot *slot = active_queue_head;
1500 while (slot != NULL)
1501 if (slot->in_use) {
1502 run_active_slot(slot);
1503 slot = active_queue_head;
1504 } else {
1505 slot = slot->next;
1509 /* Helpers for modifying and creating URLs */
1510 static inline int needs_quote(int ch)
1512 if (((ch >= 'A') && (ch <= 'Z'))
1513 || ((ch >= 'a') && (ch <= 'z'))
1514 || ((ch >= '0') && (ch <= '9'))
1515 || (ch == '/')
1516 || (ch == '-')
1517 || (ch == '.'))
1518 return 0;
1519 return 1;
1522 static char *quote_ref_url(const char *base, const char *ref)
1524 struct strbuf buf = STRBUF_INIT;
1525 const char *cp;
1526 int ch;
1528 end_url_with_slash(&buf, base);
1530 for (cp = ref; (ch = *cp) != 0; cp++)
1531 if (needs_quote(ch))
1532 strbuf_addf(&buf, "%%%02x", ch);
1533 else
1534 strbuf_addch(&buf, *cp);
1536 return strbuf_detach(&buf, NULL);
1539 void append_remote_object_url(struct strbuf *buf, const char *url,
1540 const char *hex,
1541 int only_two_digit_prefix)
1543 end_url_with_slash(buf, url);
1545 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1546 if (!only_two_digit_prefix)
1547 strbuf_addstr(buf, hex + 2);
1550 char *get_remote_object_url(const char *url, const char *hex,
1551 int only_two_digit_prefix)
1553 struct strbuf buf = STRBUF_INIT;
1554 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1555 return strbuf_detach(&buf, NULL);
1558 void normalize_curl_result(CURLcode *result, long http_code,
1559 char *errorstr, size_t errorlen)
1562 * If we see a failing http code with CURLE_OK, we have turned off
1563 * FAILONERROR (to keep the server's custom error response), and should
1564 * translate the code into failure here.
1566 * Likewise, if we see a redirect (30x code), that means we turned off
1567 * redirect-following, and we should treat the result as an error.
1569 if (*result == CURLE_OK && http_code >= 300) {
1570 *result = CURLE_HTTP_RETURNED_ERROR;
1572 * Normally curl will already have put the "reason phrase"
1573 * from the server into curl_errorstr; unfortunately without
1574 * FAILONERROR it is lost, so we can give only the numeric
1575 * status code.
1577 xsnprintf(errorstr, errorlen,
1578 "The requested URL returned error: %ld",
1579 http_code);
1583 static int handle_curl_result(struct slot_results *results)
1585 normalize_curl_result(&results->curl_result, results->http_code,
1586 curl_errorstr, sizeof(curl_errorstr));
1588 if (results->curl_result == CURLE_OK) {
1589 credential_approve(&http_auth);
1590 credential_approve(&proxy_auth);
1591 credential_approve(&cert_auth);
1592 return HTTP_OK;
1593 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1595 * We can't tell from here whether it's a bad path, bad
1596 * certificate, bad password, or something else wrong
1597 * with the certificate. So we reject the credential to
1598 * avoid caching or saving a bad password.
1600 credential_reject(&cert_auth);
1601 return HTTP_NOAUTH;
1602 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1603 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1604 return HTTP_NOMATCHPUBLICKEY;
1605 #endif
1606 } else if (missing_target(results))
1607 return HTTP_MISSING_TARGET;
1608 else if (results->http_code == 401) {
1609 if (http_auth.username && http_auth.password) {
1610 credential_reject(&http_auth);
1611 return HTTP_NOAUTH;
1612 } else {
1613 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1614 if (results->auth_avail) {
1615 http_auth_methods &= results->auth_avail;
1616 http_auth_methods_restricted = 1;
1618 return HTTP_REAUTH;
1620 } else {
1621 if (results->http_connectcode == 407)
1622 credential_reject(&proxy_auth);
1623 if (!curl_errorstr[0])
1624 strlcpy(curl_errorstr,
1625 curl_easy_strerror(results->curl_result),
1626 sizeof(curl_errorstr));
1627 return HTTP_ERROR;
1631 int run_one_slot(struct active_request_slot *slot,
1632 struct slot_results *results)
1634 slot->results = results;
1635 if (!start_active_slot(slot)) {
1636 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1637 "failed to start HTTP request");
1638 return HTTP_START_FAILED;
1641 run_active_slot(slot);
1642 return handle_curl_result(results);
1645 struct curl_slist *http_copy_default_headers(void)
1647 struct curl_slist *headers = NULL;
1648 const struct string_list_item *item;
1650 for_each_string_list_item(item, &extra_http_headers)
1651 headers = curl_slist_append(headers, item->string);
1653 return headers;
1656 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1658 char *ptr;
1659 CURLcode ret;
1661 strbuf_reset(buf);
1662 ret = curl_easy_getinfo(curl, info, &ptr);
1663 if (!ret && ptr)
1664 strbuf_addstr(buf, ptr);
1665 return ret;
1669 * Check for and extract a content-type parameter. "raw"
1670 * should be positioned at the start of the potential
1671 * parameter, with any whitespace already removed.
1673 * "name" is the name of the parameter. The value is appended
1674 * to "out".
1676 static int extract_param(const char *raw, const char *name,
1677 struct strbuf *out)
1679 size_t len = strlen(name);
1681 if (strncasecmp(raw, name, len))
1682 return -1;
1683 raw += len;
1685 if (*raw != '=')
1686 return -1;
1687 raw++;
1689 while (*raw && !isspace(*raw) && *raw != ';')
1690 strbuf_addch(out, *raw++);
1691 return 0;
1695 * Extract a normalized version of the content type, with any
1696 * spaces suppressed, all letters lowercased, and no trailing ";"
1697 * or parameters.
1699 * Note that we will silently remove even invalid whitespace. For
1700 * example, "text / plain" is specifically forbidden by RFC 2616,
1701 * but "text/plain" is the only reasonable output, and this keeps
1702 * our code simple.
1704 * If the "charset" argument is not NULL, store the value of any
1705 * charset parameter there.
1707 * Example:
1708 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1709 * "text / plain" -> "text/plain"
1711 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1712 struct strbuf *charset)
1714 const char *p;
1716 strbuf_reset(type);
1717 strbuf_grow(type, raw->len);
1718 for (p = raw->buf; *p; p++) {
1719 if (isspace(*p))
1720 continue;
1721 if (*p == ';') {
1722 p++;
1723 break;
1725 strbuf_addch(type, tolower(*p));
1728 if (!charset)
1729 return;
1731 strbuf_reset(charset);
1732 while (*p) {
1733 while (isspace(*p) || *p == ';')
1734 p++;
1735 if (!extract_param(p, "charset", charset))
1736 return;
1737 while (*p && !isspace(*p))
1738 p++;
1741 if (!charset->len && starts_with(type->buf, "text/"))
1742 strbuf_addstr(charset, "ISO-8859-1");
1745 static void write_accept_language(struct strbuf *buf)
1748 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1749 * that, q-value will be smaller than 0.001, the minimum q-value the
1750 * HTTP specification allows. See
1751 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1753 const int MAX_DECIMAL_PLACES = 3;
1754 const int MAX_LANGUAGE_TAGS = 1000;
1755 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1756 char **language_tags = NULL;
1757 int num_langs = 0;
1758 const char *s = get_preferred_languages();
1759 int i;
1760 struct strbuf tag = STRBUF_INIT;
1762 /* Don't add Accept-Language header if no language is preferred. */
1763 if (!s)
1764 return;
1767 * Split the colon-separated string of preferred languages into
1768 * language_tags array.
1770 do {
1771 /* collect language tag */
1772 for (; *s && (isalnum(*s) || *s == '_'); s++)
1773 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1775 /* skip .codeset, @modifier and any other unnecessary parts */
1776 while (*s && *s != ':')
1777 s++;
1779 if (tag.len) {
1780 num_langs++;
1781 REALLOC_ARRAY(language_tags, num_langs);
1782 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1783 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1784 break;
1786 } while (*s++);
1788 /* write Accept-Language header into buf */
1789 if (num_langs) {
1790 int last_buf_len = 0;
1791 int max_q;
1792 int decimal_places;
1793 char q_format[32];
1795 /* add '*' */
1796 REALLOC_ARRAY(language_tags, num_langs + 1);
1797 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1799 /* compute decimal_places */
1800 for (max_q = 1, decimal_places = 0;
1801 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1802 decimal_places++, max_q *= 10)
1805 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1807 strbuf_addstr(buf, "Accept-Language: ");
1809 for (i = 0; i < num_langs; i++) {
1810 if (i > 0)
1811 strbuf_addstr(buf, ", ");
1813 strbuf_addstr(buf, language_tags[i]);
1815 if (i > 0)
1816 strbuf_addf(buf, q_format, max_q - i);
1818 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1819 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1820 break;
1823 last_buf_len = buf->len;
1827 /* free language tags -- last one is a static '*' */
1828 for (i = 0; i < num_langs - 1; i++)
1829 free(language_tags[i]);
1830 free(language_tags);
1834 * Get an Accept-Language header which indicates user's preferred languages.
1836 * Examples:
1837 * LANGUAGE= -> ""
1838 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1839 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1840 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1841 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1842 * LANGUAGE= LANG=C -> ""
1844 const char *http_get_accept_language_header(void)
1846 if (!cached_accept_language) {
1847 struct strbuf buf = STRBUF_INIT;
1848 write_accept_language(&buf);
1849 if (buf.len > 0)
1850 cached_accept_language = strbuf_detach(&buf, NULL);
1853 return cached_accept_language;
1856 static void http_opt_request_remainder(CURL *curl, off_t pos)
1858 char buf[128];
1859 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1860 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1863 /* http_request() targets */
1864 #define HTTP_REQUEST_STRBUF 0
1865 #define HTTP_REQUEST_FILE 1
1867 static int http_request(const char *url,
1868 void *result, int target,
1869 const struct http_get_options *options)
1871 struct active_request_slot *slot;
1872 struct slot_results results;
1873 struct curl_slist *headers = http_copy_default_headers();
1874 struct strbuf buf = STRBUF_INIT;
1875 const char *accept_language;
1876 int ret;
1878 slot = get_active_slot();
1879 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1881 if (!result) {
1882 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1883 } else {
1884 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1885 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
1887 if (target == HTTP_REQUEST_FILE) {
1888 off_t posn = ftello(result);
1889 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1890 fwrite);
1891 if (posn > 0)
1892 http_opt_request_remainder(slot->curl, posn);
1893 } else
1894 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1895 fwrite_buffer);
1898 accept_language = http_get_accept_language_header();
1900 if (accept_language)
1901 headers = curl_slist_append(headers, accept_language);
1903 strbuf_addstr(&buf, "Pragma:");
1904 if (options && options->no_cache)
1905 strbuf_addstr(&buf, " no-cache");
1906 if (options && options->initial_request &&
1907 http_follow_config == HTTP_FOLLOW_INITIAL)
1908 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1910 headers = curl_slist_append(headers, buf.buf);
1912 /* Add additional headers here */
1913 if (options && options->extra_headers) {
1914 const struct string_list_item *item;
1915 for_each_string_list_item(item, options->extra_headers) {
1916 headers = curl_slist_append(headers, item->string);
1920 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1921 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1922 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1923 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1925 ret = run_one_slot(slot, &results);
1927 if (options && options->content_type) {
1928 struct strbuf raw = STRBUF_INIT;
1929 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1930 extract_content_type(&raw, options->content_type,
1931 options->charset);
1932 strbuf_release(&raw);
1935 if (options && options->effective_url)
1936 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1937 options->effective_url);
1939 curl_slist_free_all(headers);
1940 strbuf_release(&buf);
1942 return ret;
1946 * Update the "base" url to a more appropriate value, as deduced by
1947 * redirects seen when requesting a URL starting with "url".
1949 * The "asked" parameter is a URL that we asked curl to access, and must begin
1950 * with "base".
1952 * The "got" parameter is the URL that curl reported to us as where we ended
1953 * up.
1955 * Returns 1 if we updated the base url, 0 otherwise.
1957 * Our basic strategy is to compare "base" and "asked" to find the bits
1958 * specific to our request. We then strip those bits off of "got" to yield the
1959 * new base. So for example, if our base is "http://example.com/foo.git",
1960 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1961 * with "https://other.example.com/foo.git/info/refs". We would want the
1962 * new URL to become "https://other.example.com/foo.git".
1964 * Note that this assumes a sane redirect scheme. It's entirely possible
1965 * in the example above to end up at a URL that does not even end in
1966 * "info/refs". In such a case we die. There's not much we can do, such a
1967 * scheme is unlikely to represent a real git repository, and failing to
1968 * rewrite the base opens options for malicious redirects to do funny things.
1970 static int update_url_from_redirect(struct strbuf *base,
1971 const char *asked,
1972 const struct strbuf *got)
1974 const char *tail;
1975 size_t new_len;
1977 if (!strcmp(asked, got->buf))
1978 return 0;
1980 if (!skip_prefix(asked, base->buf, &tail))
1981 BUG("update_url_from_redirect: %s is not a superset of %s",
1982 asked, base->buf);
1984 new_len = got->len;
1985 if (!strip_suffix_mem(got->buf, &new_len, tail))
1986 die(_("unable to update url base from redirection:\n"
1987 " asked for: %s\n"
1988 " redirect: %s"),
1989 asked, got->buf);
1991 strbuf_reset(base);
1992 strbuf_add(base, got->buf, new_len);
1994 return 1;
1997 static int http_request_reauth(const char *url,
1998 void *result, int target,
1999 struct http_get_options *options)
2001 int ret = http_request(url, result, target, options);
2003 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2004 return ret;
2006 if (options && options->effective_url && options->base_url) {
2007 if (update_url_from_redirect(options->base_url,
2008 url, options->effective_url)) {
2009 credential_from_url(&http_auth, options->base_url->buf);
2010 url = options->effective_url->buf;
2014 if (ret != HTTP_REAUTH)
2015 return ret;
2018 * The previous request may have put cruft into our output stream; we
2019 * should clear it out before making our next request.
2021 switch (target) {
2022 case HTTP_REQUEST_STRBUF:
2023 strbuf_reset(result);
2024 break;
2025 case HTTP_REQUEST_FILE:
2026 if (fflush(result)) {
2027 error_errno("unable to flush a file");
2028 return HTTP_START_FAILED;
2030 rewind(result);
2031 if (ftruncate(fileno(result), 0) < 0) {
2032 error_errno("unable to truncate a file");
2033 return HTTP_START_FAILED;
2035 break;
2036 default:
2037 BUG("Unknown http_request target");
2040 credential_fill(&http_auth);
2042 return http_request(url, result, target, options);
2045 int http_get_strbuf(const char *url,
2046 struct strbuf *result,
2047 struct http_get_options *options)
2049 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2053 * Downloads a URL and stores the result in the given file.
2055 * If a previous interrupted download is detected (i.e. a previous temporary
2056 * file is still around) the download is resumed.
2058 int http_get_file(const char *url, const char *filename,
2059 struct http_get_options *options)
2061 int ret;
2062 struct strbuf tmpfile = STRBUF_INIT;
2063 FILE *result;
2065 strbuf_addf(&tmpfile, "%s.temp", filename);
2066 result = fopen(tmpfile.buf, "a");
2067 if (!result) {
2068 error("Unable to open local file %s", tmpfile.buf);
2069 ret = HTTP_ERROR;
2070 goto cleanup;
2073 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2074 fclose(result);
2076 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2077 ret = HTTP_ERROR;
2078 cleanup:
2079 strbuf_release(&tmpfile);
2080 return ret;
2083 int http_fetch_ref(const char *base, struct ref *ref)
2085 struct http_get_options options = {0};
2086 char *url;
2087 struct strbuf buffer = STRBUF_INIT;
2088 int ret = -1;
2090 options.no_cache = 1;
2092 url = quote_ref_url(base, ref->name);
2093 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2094 strbuf_rtrim(&buffer);
2095 if (buffer.len == the_hash_algo->hexsz)
2096 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2097 else if (starts_with(buffer.buf, "ref: ")) {
2098 ref->symref = xstrdup(buffer.buf + 5);
2099 ret = 0;
2103 strbuf_release(&buffer);
2104 free(url);
2105 return ret;
2108 /* Helpers for fetching packs */
2109 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2111 char *url, *tmp;
2112 struct strbuf buf = STRBUF_INIT;
2114 if (http_is_verbose)
2115 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2117 end_url_with_slash(&buf, base_url);
2118 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2119 url = strbuf_detach(&buf, NULL);
2121 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2122 tmp = strbuf_detach(&buf, NULL);
2124 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2125 error("Unable to get pack index %s", url);
2126 FREE_AND_NULL(tmp);
2129 free(url);
2130 return tmp;
2133 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2134 unsigned char *sha1, const char *base_url)
2136 struct packed_git *new_pack;
2137 char *tmp_idx = NULL;
2138 int ret;
2140 if (has_pack_index(sha1)) {
2141 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2142 if (!new_pack)
2143 return -1; /* parse_pack_index() already issued error message */
2144 goto add_pack;
2147 tmp_idx = fetch_pack_index(sha1, base_url);
2148 if (!tmp_idx)
2149 return -1;
2151 new_pack = parse_pack_index(sha1, tmp_idx);
2152 if (!new_pack) {
2153 unlink(tmp_idx);
2154 free(tmp_idx);
2156 return -1; /* parse_pack_index() already issued error message */
2159 ret = verify_pack_index(new_pack);
2160 if (!ret) {
2161 close_pack_index(new_pack);
2162 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2164 free(tmp_idx);
2165 if (ret)
2166 return -1;
2168 add_pack:
2169 new_pack->next = *packs_head;
2170 *packs_head = new_pack;
2171 return 0;
2174 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2176 struct http_get_options options = {0};
2177 int ret = 0;
2178 char *url;
2179 const char *data;
2180 struct strbuf buf = STRBUF_INIT;
2181 struct object_id oid;
2183 end_url_with_slash(&buf, base_url);
2184 strbuf_addstr(&buf, "objects/info/packs");
2185 url = strbuf_detach(&buf, NULL);
2187 options.no_cache = 1;
2188 ret = http_get_strbuf(url, &buf, &options);
2189 if (ret != HTTP_OK)
2190 goto cleanup;
2192 data = buf.buf;
2193 while (*data) {
2194 if (skip_prefix(data, "P pack-", &data) &&
2195 !parse_oid_hex(data, &oid, &data) &&
2196 skip_prefix(data, ".pack", &data) &&
2197 (*data == '\n' || *data == '\0')) {
2198 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2199 } else {
2200 data = strchrnul(data, '\n');
2202 if (*data)
2203 data++; /* skip past newline */
2206 cleanup:
2207 free(url);
2208 return ret;
2211 void release_http_pack_request(struct http_pack_request *preq)
2213 if (preq->packfile) {
2214 fclose(preq->packfile);
2215 preq->packfile = NULL;
2217 preq->slot = NULL;
2218 strbuf_release(&preq->tmpfile);
2219 free(preq->url);
2220 free(preq);
2223 static const char *default_index_pack_args[] =
2224 {"index-pack", "--stdin", NULL};
2226 int finish_http_pack_request(struct http_pack_request *preq)
2228 struct child_process ip = CHILD_PROCESS_INIT;
2229 int tmpfile_fd;
2230 int ret = 0;
2232 fclose(preq->packfile);
2233 preq->packfile = NULL;
2235 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2237 ip.git_cmd = 1;
2238 ip.in = tmpfile_fd;
2239 strvec_pushv(&ip.args, preq->index_pack_args ?
2240 preq->index_pack_args :
2241 default_index_pack_args);
2243 if (preq->preserve_index_pack_stdout)
2244 ip.out = 0;
2245 else
2246 ip.no_stdout = 1;
2248 if (run_command(&ip)) {
2249 ret = -1;
2250 goto cleanup;
2253 cleanup:
2254 close(tmpfile_fd);
2255 unlink(preq->tmpfile.buf);
2256 return ret;
2259 void http_install_packfile(struct packed_git *p,
2260 struct packed_git **list_to_remove_from)
2262 struct packed_git **lst = list_to_remove_from;
2264 while (*lst != p)
2265 lst = &((*lst)->next);
2266 *lst = (*lst)->next;
2268 install_packed_git(the_repository, p);
2271 struct http_pack_request *new_http_pack_request(
2272 const unsigned char *packed_git_hash, const char *base_url) {
2274 struct strbuf buf = STRBUF_INIT;
2276 end_url_with_slash(&buf, base_url);
2277 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2278 hash_to_hex(packed_git_hash));
2279 return new_direct_http_pack_request(packed_git_hash,
2280 strbuf_detach(&buf, NULL));
2283 struct http_pack_request *new_direct_http_pack_request(
2284 const unsigned char *packed_git_hash, char *url)
2286 off_t prev_posn = 0;
2287 struct http_pack_request *preq;
2289 CALLOC_ARRAY(preq, 1);
2290 strbuf_init(&preq->tmpfile, 0);
2292 preq->url = url;
2294 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2295 preq->packfile = fopen(preq->tmpfile.buf, "a");
2296 if (!preq->packfile) {
2297 error("Unable to open local file %s for pack",
2298 preq->tmpfile.buf);
2299 goto abort;
2302 preq->slot = get_active_slot();
2303 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2304 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2305 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2306 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2307 no_pragma_header);
2310 * If there is data present from a previous transfer attempt,
2311 * resume where it left off
2313 prev_posn = ftello(preq->packfile);
2314 if (prev_posn>0) {
2315 if (http_is_verbose)
2316 fprintf(stderr,
2317 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2318 hash_to_hex(packed_git_hash),
2319 (uintmax_t)prev_posn);
2320 http_opt_request_remainder(preq->slot->curl, prev_posn);
2323 return preq;
2325 abort:
2326 strbuf_release(&preq->tmpfile);
2327 free(preq->url);
2328 free(preq);
2329 return NULL;
2332 /* Helpers for fetching objects (loose) */
2333 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2334 void *data)
2336 unsigned char expn[4096];
2337 size_t size = eltsize * nmemb;
2338 int posn = 0;
2339 struct http_object_request *freq = data;
2340 struct active_request_slot *slot = freq->slot;
2342 if (slot) {
2343 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2344 &slot->http_code);
2345 if (c != CURLE_OK)
2346 BUG("curl_easy_getinfo for HTTP code failed: %s",
2347 curl_easy_strerror(c));
2348 if (slot->http_code >= 300)
2349 return nmemb;
2352 do {
2353 ssize_t retval = xwrite(freq->localfile,
2354 (char *) ptr + posn, size - posn);
2355 if (retval < 0)
2356 return posn / eltsize;
2357 posn += retval;
2358 } while (posn < size);
2360 freq->stream.avail_in = size;
2361 freq->stream.next_in = (void *)ptr;
2362 do {
2363 freq->stream.next_out = expn;
2364 freq->stream.avail_out = sizeof(expn);
2365 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2366 the_hash_algo->update_fn(&freq->c, expn,
2367 sizeof(expn) - freq->stream.avail_out);
2368 } while (freq->stream.avail_in && freq->zret == Z_OK);
2369 return nmemb;
2372 struct http_object_request *new_http_object_request(const char *base_url,
2373 const struct object_id *oid)
2375 char *hex = oid_to_hex(oid);
2376 struct strbuf filename = STRBUF_INIT;
2377 struct strbuf prevfile = STRBUF_INIT;
2378 int prevlocal;
2379 char prev_buf[PREV_BUF_SIZE];
2380 ssize_t prev_read = 0;
2381 off_t prev_posn = 0;
2382 struct http_object_request *freq;
2384 CALLOC_ARRAY(freq, 1);
2385 strbuf_init(&freq->tmpfile, 0);
2386 oidcpy(&freq->oid, oid);
2387 freq->localfile = -1;
2389 loose_object_path(the_repository, &filename, oid);
2390 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2392 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2393 unlink_or_warn(prevfile.buf);
2394 rename(freq->tmpfile.buf, prevfile.buf);
2395 unlink_or_warn(freq->tmpfile.buf);
2396 strbuf_release(&filename);
2398 if (freq->localfile != -1)
2399 error("fd leakage in start: %d", freq->localfile);
2400 freq->localfile = open(freq->tmpfile.buf,
2401 O_WRONLY | O_CREAT | O_EXCL, 0666);
2403 * This could have failed due to the "lazy directory creation";
2404 * try to mkdir the last path component.
2406 if (freq->localfile < 0 && errno == ENOENT) {
2407 char *dir = strrchr(freq->tmpfile.buf, '/');
2408 if (dir) {
2409 *dir = 0;
2410 mkdir(freq->tmpfile.buf, 0777);
2411 *dir = '/';
2413 freq->localfile = open(freq->tmpfile.buf,
2414 O_WRONLY | O_CREAT | O_EXCL, 0666);
2417 if (freq->localfile < 0) {
2418 error_errno("Couldn't create temporary file %s",
2419 freq->tmpfile.buf);
2420 goto abort;
2423 git_inflate_init(&freq->stream);
2425 the_hash_algo->init_fn(&freq->c);
2427 freq->url = get_remote_object_url(base_url, hex, 0);
2430 * If a previous temp file is present, process what was already
2431 * fetched.
2433 prevlocal = open(prevfile.buf, O_RDONLY);
2434 if (prevlocal != -1) {
2435 do {
2436 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2437 if (prev_read>0) {
2438 if (fwrite_sha1_file(prev_buf,
2440 prev_read,
2441 freq) == prev_read) {
2442 prev_posn += prev_read;
2443 } else {
2444 prev_read = -1;
2447 } while (prev_read > 0);
2448 close(prevlocal);
2450 unlink_or_warn(prevfile.buf);
2451 strbuf_release(&prevfile);
2454 * Reset inflate/SHA1 if there was an error reading the previous temp
2455 * file; also rewind to the beginning of the local file.
2457 if (prev_read == -1) {
2458 memset(&freq->stream, 0, sizeof(freq->stream));
2459 git_inflate_init(&freq->stream);
2460 the_hash_algo->init_fn(&freq->c);
2461 if (prev_posn>0) {
2462 prev_posn = 0;
2463 lseek(freq->localfile, 0, SEEK_SET);
2464 if (ftruncate(freq->localfile, 0) < 0) {
2465 error_errno("Couldn't truncate temporary file %s",
2466 freq->tmpfile.buf);
2467 goto abort;
2472 freq->slot = get_active_slot();
2474 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2475 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2476 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2477 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2478 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2479 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2482 * If we have successfully processed data from a previous fetch
2483 * attempt, only fetch the data we don't already have.
2485 if (prev_posn>0) {
2486 if (http_is_verbose)
2487 fprintf(stderr,
2488 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2489 hex, (uintmax_t)prev_posn);
2490 http_opt_request_remainder(freq->slot->curl, prev_posn);
2493 return freq;
2495 abort:
2496 strbuf_release(&prevfile);
2497 free(freq->url);
2498 free(freq);
2499 return NULL;
2502 void process_http_object_request(struct http_object_request *freq)
2504 if (!freq->slot)
2505 return;
2506 freq->curl_result = freq->slot->curl_result;
2507 freq->http_code = freq->slot->http_code;
2508 freq->slot = NULL;
2511 int finish_http_object_request(struct http_object_request *freq)
2513 struct stat st;
2514 struct strbuf filename = STRBUF_INIT;
2516 close(freq->localfile);
2517 freq->localfile = -1;
2519 process_http_object_request(freq);
2521 if (freq->http_code == 416) {
2522 warning("requested range invalid; we may already have all the data.");
2523 } else if (freq->curl_result != CURLE_OK) {
2524 if (stat(freq->tmpfile.buf, &st) == 0)
2525 if (st.st_size == 0)
2526 unlink_or_warn(freq->tmpfile.buf);
2527 return -1;
2530 git_inflate_end(&freq->stream);
2531 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2532 if (freq->zret != Z_STREAM_END) {
2533 unlink_or_warn(freq->tmpfile.buf);
2534 return -1;
2536 if (!oideq(&freq->oid, &freq->real_oid)) {
2537 unlink_or_warn(freq->tmpfile.buf);
2538 return -1;
2540 loose_object_path(the_repository, &filename, &freq->oid);
2541 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2542 strbuf_release(&filename);
2544 return freq->rename;
2547 void abort_http_object_request(struct http_object_request *freq)
2549 unlink_or_warn(freq->tmpfile.buf);
2551 release_http_object_request(freq);
2554 void release_http_object_request(struct http_object_request *freq)
2556 if (freq->localfile != -1) {
2557 close(freq->localfile);
2558 freq->localfile = -1;
2560 FREE_AND_NULL(freq->url);
2561 if (freq->slot) {
2562 freq->slot->callback_func = NULL;
2563 freq->slot->callback_data = NULL;
2564 release_active_slot(freq->slot);
2565 freq->slot = NULL;
2567 strbuf_release(&freq->tmpfile);