The fifth batch
[alt-git.git] / http.c
blob8a5ba3f47769424e8315658b1f14903cc4957ecf
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 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
162 struct buffer *buffer = clientp;
164 switch (cmd) {
165 case CURLIOCMD_NOP:
166 return CURLIOE_OK;
168 case CURLIOCMD_RESTARTREAD:
169 buffer->posn = 0;
170 return CURLIOE_OK;
172 default:
173 return CURLIOE_UNKNOWNCMD;
177 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
179 size_t size = eltsize * nmemb;
180 struct strbuf *buffer = buffer_;
182 strbuf_add(buffer, ptr, size);
183 return nmemb;
186 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
188 return nmemb;
191 static void closedown_active_slot(struct active_request_slot *slot)
193 active_requests--;
194 slot->in_use = 0;
197 static void finish_active_slot(struct active_request_slot *slot)
199 closedown_active_slot(slot);
200 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
202 if (slot->finished)
203 (*slot->finished) = 1;
205 /* Store slot results so they can be read after the slot is reused */
206 if (slot->results) {
207 slot->results->curl_result = slot->curl_result;
208 slot->results->http_code = slot->http_code;
209 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
210 &slot->results->auth_avail);
212 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
213 &slot->results->http_connectcode);
216 /* Run callback if appropriate */
217 if (slot->callback_func)
218 slot->callback_func(slot->callback_data);
221 static void xmulti_remove_handle(struct active_request_slot *slot)
223 curl_multi_remove_handle(curlm, slot->curl);
226 static void process_curl_messages(void)
228 int num_messages;
229 struct active_request_slot *slot;
230 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
232 while (curl_message != NULL) {
233 if (curl_message->msg == CURLMSG_DONE) {
234 int curl_result = curl_message->data.result;
235 slot = active_queue_head;
236 while (slot != NULL &&
237 slot->curl != curl_message->easy_handle)
238 slot = slot->next;
239 if (slot) {
240 xmulti_remove_handle(slot);
241 slot->curl_result = curl_result;
242 finish_active_slot(slot);
243 } else {
244 fprintf(stderr, "Received DONE message for unknown request!\n");
246 } else {
247 fprintf(stderr, "Unknown CURL message received: %d\n",
248 (int)curl_message->msg);
250 curl_message = curl_multi_info_read(curlm, &num_messages);
254 static int http_options(const char *var, const char *value, void *cb)
256 if (!strcmp("http.version", var)) {
257 return git_config_string(&curl_http_version, var, value);
259 if (!strcmp("http.sslverify", var)) {
260 curl_ssl_verify = git_config_bool(var, value);
261 return 0;
263 if (!strcmp("http.sslcipherlist", var))
264 return git_config_string(&ssl_cipherlist, var, value);
265 if (!strcmp("http.sslversion", var))
266 return git_config_string(&ssl_version, var, value);
267 if (!strcmp("http.sslcert", var))
268 return git_config_pathname(&ssl_cert, var, value);
269 if (!strcmp("http.sslkey", var))
270 return git_config_pathname(&ssl_key, var, value);
271 if (!strcmp("http.sslcapath", var))
272 return git_config_pathname(&ssl_capath, var, value);
273 if (!strcmp("http.sslcainfo", var))
274 return git_config_pathname(&ssl_cainfo, var, value);
275 if (!strcmp("http.sslcertpasswordprotected", var)) {
276 ssl_cert_password_required = git_config_bool(var, value);
277 return 0;
279 if (!strcmp("http.ssltry", var)) {
280 curl_ssl_try = git_config_bool(var, value);
281 return 0;
283 if (!strcmp("http.sslbackend", var)) {
284 free(http_ssl_backend);
285 http_ssl_backend = xstrdup_or_null(value);
286 return 0;
289 if (!strcmp("http.schannelcheckrevoke", var)) {
290 http_schannel_check_revoke = git_config_bool(var, value);
291 return 0;
294 if (!strcmp("http.schannelusesslcainfo", var)) {
295 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
296 return 0;
299 if (!strcmp("http.minsessions", var)) {
300 min_curl_sessions = git_config_int(var, value);
301 if (min_curl_sessions > 1)
302 min_curl_sessions = 1;
303 return 0;
305 if (!strcmp("http.maxrequests", var)) {
306 max_requests = git_config_int(var, value);
307 return 0;
309 if (!strcmp("http.lowspeedlimit", var)) {
310 curl_low_speed_limit = (long)git_config_int(var, value);
311 return 0;
313 if (!strcmp("http.lowspeedtime", var)) {
314 curl_low_speed_time = (long)git_config_int(var, value);
315 return 0;
318 if (!strcmp("http.noepsv", var)) {
319 curl_ftp_no_epsv = git_config_bool(var, value);
320 return 0;
322 if (!strcmp("http.proxy", var))
323 return git_config_string(&curl_http_proxy, var, value);
325 if (!strcmp("http.proxyauthmethod", var))
326 return git_config_string(&http_proxy_authmethod, var, value);
328 if (!strcmp("http.proxysslcert", var))
329 return git_config_string(&http_proxy_ssl_cert, var, value);
331 if (!strcmp("http.proxysslkey", var))
332 return git_config_string(&http_proxy_ssl_key, var, value);
334 if (!strcmp("http.proxysslcainfo", var))
335 return git_config_string(&http_proxy_ssl_ca_info, var, value);
337 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
338 proxy_ssl_cert_password_required = git_config_bool(var, value);
339 return 0;
342 if (!strcmp("http.cookiefile", var))
343 return git_config_pathname(&curl_cookie_file, var, value);
344 if (!strcmp("http.savecookies", var)) {
345 curl_save_cookies = git_config_bool(var, value);
346 return 0;
349 if (!strcmp("http.postbuffer", var)) {
350 http_post_buffer = git_config_ssize_t(var, value);
351 if (http_post_buffer < 0)
352 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
353 if (http_post_buffer < LARGE_PACKET_MAX)
354 http_post_buffer = LARGE_PACKET_MAX;
355 return 0;
358 if (!strcmp("http.useragent", var))
359 return git_config_string(&user_agent, var, value);
361 if (!strcmp("http.emptyauth", var)) {
362 if (value && !strcmp("auto", value))
363 curl_empty_auth = -1;
364 else
365 curl_empty_auth = git_config_bool(var, value);
366 return 0;
369 if (!strcmp("http.delegation", var)) {
370 #ifdef CURLGSSAPI_DELEGATION_FLAG
371 return git_config_string(&curl_deleg, var, value);
372 #else
373 warning(_("Delegation control is not supported with cURL < 7.22.0"));
374 return 0;
375 #endif
378 if (!strcmp("http.pinnedpubkey", var)) {
379 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
380 return git_config_pathname(&ssl_pinnedkey, var, value);
381 #else
382 warning(_("Public key pinning not supported with cURL < 7.39.0"));
383 return 0;
384 #endif
387 if (!strcmp("http.extraheader", var)) {
388 if (!value) {
389 return config_error_nonbool(var);
390 } else if (!*value) {
391 string_list_clear(&extra_http_headers, 0);
392 } else {
393 string_list_append(&extra_http_headers, value);
395 return 0;
398 if (!strcmp("http.curloptresolve", var)) {
399 if (!value) {
400 return config_error_nonbool(var);
401 } else if (!*value) {
402 curl_slist_free_all(host_resolutions);
403 host_resolutions = NULL;
404 } else {
405 host_resolutions = curl_slist_append(host_resolutions, value);
407 return 0;
410 if (!strcmp("http.followredirects", var)) {
411 if (value && !strcmp(value, "initial"))
412 http_follow_config = HTTP_FOLLOW_INITIAL;
413 else if (git_config_bool(var, value))
414 http_follow_config = HTTP_FOLLOW_ALWAYS;
415 else
416 http_follow_config = HTTP_FOLLOW_NONE;
417 return 0;
420 /* Fall back on the default ones */
421 return git_default_config(var, value, cb);
424 static int curl_empty_auth_enabled(void)
426 if (curl_empty_auth >= 0)
427 return curl_empty_auth;
430 * In the automatic case, kick in the empty-auth
431 * hack as long as we would potentially try some
432 * method more exotic than "Basic" or "Digest".
434 * But only do this when this is our second or
435 * subsequent request, as by then we know what
436 * methods are available.
438 if (http_auth_methods_restricted &&
439 (http_auth_methods & ~empty_auth_useless))
440 return 1;
441 return 0;
444 static void init_curl_http_auth(CURL *result)
446 if (!http_auth.username || !*http_auth.username) {
447 if (curl_empty_auth_enabled())
448 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
449 return;
452 credential_fill(&http_auth);
454 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
455 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
458 /* *var must be free-able */
459 static void var_override(const char **var, char *value)
461 if (value) {
462 free((void *)*var);
463 *var = xstrdup(value);
467 static void set_proxyauth_name_password(CURL *result)
469 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
470 proxy_auth.username);
471 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
472 proxy_auth.password);
475 static void init_curl_proxy_auth(CURL *result)
477 if (proxy_auth.username) {
478 if (!proxy_auth.password)
479 credential_fill(&proxy_auth);
480 set_proxyauth_name_password(result);
483 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
485 if (http_proxy_authmethod) {
486 int i;
487 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
488 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
489 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
490 proxy_authmethods[i].curlauth_param);
491 break;
494 if (i == ARRAY_SIZE(proxy_authmethods)) {
495 warning("unsupported proxy authentication method %s: using anyauth",
496 http_proxy_authmethod);
497 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
500 else
501 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
504 static int has_cert_password(void)
506 if (ssl_cert == NULL || ssl_cert_password_required != 1)
507 return 0;
508 if (!cert_auth.password) {
509 cert_auth.protocol = xstrdup("cert");
510 cert_auth.host = xstrdup("");
511 cert_auth.username = xstrdup("");
512 cert_auth.path = xstrdup(ssl_cert);
513 credential_fill(&cert_auth);
515 return 1;
518 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
519 static int has_proxy_cert_password(void)
521 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
522 return 0;
523 if (!proxy_cert_auth.password) {
524 proxy_cert_auth.protocol = xstrdup("cert");
525 proxy_cert_auth.host = xstrdup("");
526 proxy_cert_auth.username = xstrdup("");
527 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
528 credential_fill(&proxy_cert_auth);
530 return 1;
532 #endif
534 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
535 static void set_curl_keepalive(CURL *c)
537 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
540 #else
541 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
543 int ka = 1;
544 int rc;
545 socklen_t len = (socklen_t)sizeof(ka);
547 if (type != CURLSOCKTYPE_IPCXN)
548 return 0;
550 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
551 if (rc < 0)
552 warning_errno("unable to set SO_KEEPALIVE on socket");
554 return CURL_SOCKOPT_OK;
557 static void set_curl_keepalive(CURL *c)
559 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
561 #endif
563 /* Return 1 if redactions have been made, 0 otherwise. */
564 static int redact_sensitive_header(struct strbuf *header, size_t offset)
566 int ret = 0;
567 const char *sensitive_header;
569 if (trace_curl_redact &&
570 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
571 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
572 /* The first token is the type, which is OK to log */
573 while (isspace(*sensitive_header))
574 sensitive_header++;
575 while (*sensitive_header && !isspace(*sensitive_header))
576 sensitive_header++;
577 /* Everything else is opaque and possibly sensitive */
578 strbuf_setlen(header, sensitive_header - header->buf);
579 strbuf_addstr(header, " <redacted>");
580 ret = 1;
581 } else if (trace_curl_redact &&
582 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
583 struct strbuf redacted_header = STRBUF_INIT;
584 const char *cookie;
586 while (isspace(*sensitive_header))
587 sensitive_header++;
589 cookie = sensitive_header;
591 while (cookie) {
592 char *equals;
593 char *semicolon = strstr(cookie, "; ");
594 if (semicolon)
595 *semicolon = 0;
596 equals = strchrnul(cookie, '=');
597 if (!equals) {
598 /* invalid cookie, just append and continue */
599 strbuf_addstr(&redacted_header, cookie);
600 continue;
602 strbuf_add(&redacted_header, cookie, equals - cookie);
603 strbuf_addstr(&redacted_header, "=<redacted>");
604 if (semicolon) {
606 * There are more cookies. (Or, for some
607 * reason, the input string ends in "; ".)
609 strbuf_addstr(&redacted_header, "; ");
610 cookie = semicolon + strlen("; ");
611 } else {
612 cookie = NULL;
616 strbuf_setlen(header, sensitive_header - header->buf);
617 strbuf_addbuf(header, &redacted_header);
618 ret = 1;
620 return ret;
623 /* Redact headers in info */
624 static void redact_sensitive_info_header(struct strbuf *header)
626 const char *sensitive_header;
629 * curl's h2h3 prints headers in info, e.g.:
630 * h2h3 [<header-name>: <header-val>]
632 if (trace_curl_redact &&
633 skip_iprefix(header->buf, "h2h3 [", &sensitive_header)) {
634 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
635 /* redaction ate our closing bracket */
636 strbuf_addch(header, ']');
641 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
643 struct strbuf out = STRBUF_INIT;
644 struct strbuf **headers, **header;
646 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
647 text, (long)size, (long)size);
648 trace_strbuf(&trace_curl, &out);
649 strbuf_reset(&out);
650 strbuf_add(&out, ptr, size);
651 headers = strbuf_split_max(&out, '\n', 0);
653 for (header = headers; *header; header++) {
654 if (hide_sensitive_header)
655 redact_sensitive_header(*header, 0);
656 strbuf_insertstr((*header), 0, text);
657 strbuf_insertstr((*header), strlen(text), ": ");
658 strbuf_rtrim((*header));
659 strbuf_addch((*header), '\n');
660 trace_strbuf(&trace_curl, (*header));
662 strbuf_list_free(headers);
663 strbuf_release(&out);
666 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
668 size_t i;
669 struct strbuf out = STRBUF_INIT;
670 unsigned int width = 60;
672 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
673 text, (long)size, (long)size);
674 trace_strbuf(&trace_curl, &out);
676 for (i = 0; i < size; i += width) {
677 size_t w;
679 strbuf_reset(&out);
680 strbuf_addf(&out, "%s: ", text);
681 for (w = 0; (w < width) && (i + w < size); w++) {
682 unsigned char ch = ptr[i + w];
684 strbuf_addch(&out,
685 (ch >= 0x20) && (ch < 0x80)
686 ? ch : '.');
688 strbuf_addch(&out, '\n');
689 trace_strbuf(&trace_curl, &out);
691 strbuf_release(&out);
694 static void curl_dump_info(char *data, size_t size)
696 struct strbuf buf = STRBUF_INIT;
698 strbuf_add(&buf, data, size);
700 redact_sensitive_info_header(&buf);
701 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
703 strbuf_release(&buf);
706 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
708 const char *text;
709 enum { NO_FILTER = 0, DO_FILTER = 1 };
711 switch (type) {
712 case CURLINFO_TEXT:
713 curl_dump_info(data, size);
714 break;
715 case CURLINFO_HEADER_OUT:
716 text = "=> Send header";
717 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
718 break;
719 case CURLINFO_DATA_OUT:
720 if (trace_curl_data) {
721 text = "=> Send data";
722 curl_dump_data(text, (unsigned char *)data, size);
724 break;
725 case CURLINFO_SSL_DATA_OUT:
726 if (trace_curl_data) {
727 text = "=> Send SSL data";
728 curl_dump_data(text, (unsigned char *)data, size);
730 break;
731 case CURLINFO_HEADER_IN:
732 text = "<= Recv header";
733 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
734 break;
735 case CURLINFO_DATA_IN:
736 if (trace_curl_data) {
737 text = "<= Recv data";
738 curl_dump_data(text, (unsigned char *)data, size);
740 break;
741 case CURLINFO_SSL_DATA_IN:
742 if (trace_curl_data) {
743 text = "<= Recv SSL data";
744 curl_dump_data(text, (unsigned char *)data, size);
746 break;
748 default: /* we ignore unknown types by default */
749 return 0;
751 return 0;
754 void http_trace_curl_no_data(void)
756 trace_override_envvar(&trace_curl, "1");
757 trace_curl_data = 0;
760 void setup_curl_trace(CURL *handle)
762 if (!trace_want(&trace_curl))
763 return;
764 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
765 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
766 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
769 static long get_curl_allowed_protocols(int from_user)
771 long allowed_protocols = 0;
773 if (is_transport_allowed("http", from_user))
774 allowed_protocols |= CURLPROTO_HTTP;
775 if (is_transport_allowed("https", from_user))
776 allowed_protocols |= CURLPROTO_HTTPS;
777 if (is_transport_allowed("ftp", from_user))
778 allowed_protocols |= CURLPROTO_FTP;
779 if (is_transport_allowed("ftps", from_user))
780 allowed_protocols |= CURLPROTO_FTPS;
782 return allowed_protocols;
785 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
786 static int get_curl_http_version_opt(const char *version_string, long *opt)
788 int i;
789 static struct {
790 const char *name;
791 long opt_token;
792 } choice[] = {
793 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
794 { "HTTP/2", CURL_HTTP_VERSION_2 }
797 for (i = 0; i < ARRAY_SIZE(choice); i++) {
798 if (!strcmp(version_string, choice[i].name)) {
799 *opt = choice[i].opt_token;
800 return 0;
804 warning("unknown value given to http.version: '%s'", version_string);
805 return -1; /* not found */
808 #endif
810 static CURL *get_curl_handle(void)
812 CURL *result = curl_easy_init();
814 if (!result)
815 die("curl_easy_init failed");
817 if (!curl_ssl_verify) {
818 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
819 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
820 } else {
821 /* Verify authenticity of the peer's certificate */
822 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
823 /* The name in the cert must match whom we tried to connect */
824 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
827 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
828 if (curl_http_version) {
829 long opt;
830 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
831 /* Set request use http version */
832 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
835 #endif
837 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
838 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
840 #ifdef CURLGSSAPI_DELEGATION_FLAG
841 if (curl_deleg) {
842 int i;
843 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
844 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
845 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
846 curl_deleg_levels[i].curl_deleg_param);
847 break;
850 if (i == ARRAY_SIZE(curl_deleg_levels))
851 warning("Unknown delegation method '%s': using default",
852 curl_deleg);
854 #endif
856 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
857 !http_schannel_check_revoke) {
858 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
859 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
860 #else
861 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
862 #endif
865 if (http_proactive_auth)
866 init_curl_http_auth(result);
868 if (getenv("GIT_SSL_VERSION"))
869 ssl_version = getenv("GIT_SSL_VERSION");
870 if (ssl_version && *ssl_version) {
871 int i;
872 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
873 if (!strcmp(ssl_version, sslversions[i].name)) {
874 curl_easy_setopt(result, CURLOPT_SSLVERSION,
875 sslversions[i].ssl_version);
876 break;
879 if (i == ARRAY_SIZE(sslversions))
880 warning("unsupported ssl version %s: using default",
881 ssl_version);
884 if (getenv("GIT_SSL_CIPHER_LIST"))
885 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
886 if (ssl_cipherlist != NULL && *ssl_cipherlist)
887 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
888 ssl_cipherlist);
890 if (ssl_cert)
891 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
892 if (has_cert_password())
893 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
894 if (ssl_key)
895 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
896 if (ssl_capath)
897 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
898 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
899 if (ssl_pinnedkey)
900 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
901 #endif
902 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
903 !http_schannel_use_ssl_cainfo) {
904 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
905 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
906 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
907 #endif
908 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
909 if (ssl_cainfo)
910 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
911 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
912 if (http_proxy_ssl_ca_info)
913 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
914 #endif
917 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
918 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
919 curl_low_speed_limit);
920 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
921 curl_low_speed_time);
924 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
925 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
926 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
927 get_curl_allowed_protocols(0));
928 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
929 get_curl_allowed_protocols(-1));
930 if (getenv("GIT_CURL_VERBOSE"))
931 http_trace_curl_no_data();
932 setup_curl_trace(result);
933 if (getenv("GIT_TRACE_CURL_NO_DATA"))
934 trace_curl_data = 0;
935 if (!git_env_bool("GIT_TRACE_REDACT", 1))
936 trace_curl_redact = 0;
938 curl_easy_setopt(result, CURLOPT_USERAGENT,
939 user_agent ? user_agent : git_user_agent());
941 if (curl_ftp_no_epsv)
942 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
944 if (curl_ssl_try)
945 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
948 * CURL also examines these variables as a fallback; but we need to query
949 * them here in order to decide whether to prompt for missing password (cf.
950 * init_curl_proxy_auth()).
952 * Unlike many other common environment variables, these are historically
953 * lowercase only. It appears that CURL did not know this and implemented
954 * only uppercase variants, which was later corrected to take both - with
955 * the exception of http_proxy, which is lowercase only also in CURL. As
956 * the lowercase versions are the historical quasi-standard, they take
957 * precedence here, as in CURL.
959 if (!curl_http_proxy) {
960 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
961 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
962 var_override(&curl_http_proxy, getenv("https_proxy"));
963 } else {
964 var_override(&curl_http_proxy, getenv("http_proxy"));
966 if (!curl_http_proxy) {
967 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
968 var_override(&curl_http_proxy, getenv("all_proxy"));
972 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
974 * Handle case with the empty http.proxy value here to keep
975 * common code clean.
976 * NB: empty option disables proxying at all.
978 curl_easy_setopt(result, CURLOPT_PROXY, "");
979 } else if (curl_http_proxy) {
980 if (starts_with(curl_http_proxy, "socks5h"))
981 curl_easy_setopt(result,
982 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
983 else if (starts_with(curl_http_proxy, "socks5"))
984 curl_easy_setopt(result,
985 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
986 else if (starts_with(curl_http_proxy, "socks4a"))
987 curl_easy_setopt(result,
988 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
989 else if (starts_with(curl_http_proxy, "socks"))
990 curl_easy_setopt(result,
991 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
992 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
993 else if (starts_with(curl_http_proxy, "https")) {
994 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
996 if (http_proxy_ssl_cert)
997 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
999 if (http_proxy_ssl_key)
1000 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1002 if (has_proxy_cert_password())
1003 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1005 #endif
1006 if (strstr(curl_http_proxy, "://"))
1007 credential_from_url(&proxy_auth, curl_http_proxy);
1008 else {
1009 struct strbuf url = STRBUF_INIT;
1010 strbuf_addf(&url, "http://%s", curl_http_proxy);
1011 credential_from_url(&proxy_auth, url.buf);
1012 strbuf_release(&url);
1015 if (!proxy_auth.host)
1016 die("Invalid proxy URL '%s'", curl_http_proxy);
1018 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1019 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1020 var_override(&curl_no_proxy, getenv("no_proxy"));
1021 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1023 init_curl_proxy_auth(result);
1025 set_curl_keepalive(result);
1027 return result;
1030 static void set_from_env(const char **var, const char *envname)
1032 const char *val = getenv(envname);
1033 if (val)
1034 *var = val;
1037 void http_init(struct remote *remote, const char *url, int proactive_auth)
1039 char *low_speed_limit;
1040 char *low_speed_time;
1041 char *normalized_url;
1042 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1044 config.section = "http";
1045 config.key = NULL;
1046 config.collect_fn = http_options;
1047 config.cascade_fn = git_default_config;
1048 config.cb = NULL;
1050 http_is_verbose = 0;
1051 normalized_url = url_normalize(url, &config.url);
1053 git_config(urlmatch_config_entry, &config);
1054 free(normalized_url);
1055 string_list_clear(&config.vars, 1);
1057 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1058 if (http_ssl_backend) {
1059 const curl_ssl_backend **backends;
1060 struct strbuf buf = STRBUF_INIT;
1061 int i;
1063 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1064 case CURLSSLSET_UNKNOWN_BACKEND:
1065 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1066 "Supported SSL backends:"),
1067 http_ssl_backend);
1068 for (i = 0; backends[i]; i++)
1069 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1070 die("%s", buf.buf);
1071 case CURLSSLSET_NO_BACKENDS:
1072 die(_("Could not set SSL backend to '%s': "
1073 "cURL was built without SSL backends"),
1074 http_ssl_backend);
1075 case CURLSSLSET_TOO_LATE:
1076 die(_("Could not set SSL backend to '%s': already set"),
1077 http_ssl_backend);
1078 case CURLSSLSET_OK:
1079 break; /* Okay! */
1082 #endif
1084 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1085 die("curl_global_init failed");
1087 http_proactive_auth = proactive_auth;
1089 if (remote && remote->http_proxy)
1090 curl_http_proxy = xstrdup(remote->http_proxy);
1092 if (remote)
1093 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1095 pragma_header = curl_slist_append(http_copy_default_headers(),
1096 "Pragma: no-cache");
1097 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1098 "Pragma:");
1101 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1102 if (http_max_requests)
1103 max_requests = atoi(http_max_requests);
1106 curlm = curl_multi_init();
1107 if (!curlm)
1108 die("curl_multi_init failed");
1110 if (getenv("GIT_SSL_NO_VERIFY"))
1111 curl_ssl_verify = 0;
1113 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1114 set_from_env(&ssl_key, "GIT_SSL_KEY");
1115 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1116 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1118 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1120 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1121 if (low_speed_limit)
1122 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1123 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1124 if (low_speed_time)
1125 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1127 if (curl_ssl_verify == -1)
1128 curl_ssl_verify = 1;
1130 curl_session_count = 0;
1131 if (max_requests < 1)
1132 max_requests = DEFAULT_MAX_REQUESTS;
1134 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1135 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1136 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1138 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1139 proxy_ssl_cert_password_required = 1;
1141 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1142 curl_ftp_no_epsv = 1;
1144 if (url) {
1145 credential_from_url(&http_auth, url);
1146 if (!ssl_cert_password_required &&
1147 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1148 starts_with(url, "https://"))
1149 ssl_cert_password_required = 1;
1152 curl_default = get_curl_handle();
1155 void http_cleanup(void)
1157 struct active_request_slot *slot = active_queue_head;
1159 while (slot != NULL) {
1160 struct active_request_slot *next = slot->next;
1161 if (slot->curl) {
1162 xmulti_remove_handle(slot);
1163 curl_easy_cleanup(slot->curl);
1165 free(slot);
1166 slot = next;
1168 active_queue_head = NULL;
1170 curl_easy_cleanup(curl_default);
1172 curl_multi_cleanup(curlm);
1173 curl_global_cleanup();
1175 string_list_clear(&extra_http_headers, 0);
1177 curl_slist_free_all(pragma_header);
1178 pragma_header = NULL;
1180 curl_slist_free_all(no_pragma_header);
1181 no_pragma_header = NULL;
1183 curl_slist_free_all(host_resolutions);
1184 host_resolutions = NULL;
1186 if (curl_http_proxy) {
1187 free((void *)curl_http_proxy);
1188 curl_http_proxy = NULL;
1191 if (proxy_auth.password) {
1192 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1193 FREE_AND_NULL(proxy_auth.password);
1196 free((void *)curl_proxyuserpwd);
1197 curl_proxyuserpwd = NULL;
1199 free((void *)http_proxy_authmethod);
1200 http_proxy_authmethod = NULL;
1202 if (cert_auth.password) {
1203 memset(cert_auth.password, 0, strlen(cert_auth.password));
1204 FREE_AND_NULL(cert_auth.password);
1206 ssl_cert_password_required = 0;
1208 if (proxy_cert_auth.password) {
1209 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1210 FREE_AND_NULL(proxy_cert_auth.password);
1212 proxy_ssl_cert_password_required = 0;
1214 FREE_AND_NULL(cached_accept_language);
1217 struct active_request_slot *get_active_slot(void)
1219 struct active_request_slot *slot = active_queue_head;
1220 struct active_request_slot *newslot;
1222 int num_transfers;
1224 /* Wait for a slot to open up if the queue is full */
1225 while (active_requests >= max_requests) {
1226 curl_multi_perform(curlm, &num_transfers);
1227 if (num_transfers < active_requests)
1228 process_curl_messages();
1231 while (slot != NULL && slot->in_use)
1232 slot = slot->next;
1234 if (!slot) {
1235 newslot = xmalloc(sizeof(*newslot));
1236 newslot->curl = NULL;
1237 newslot->in_use = 0;
1238 newslot->next = NULL;
1240 slot = active_queue_head;
1241 if (!slot) {
1242 active_queue_head = newslot;
1243 } else {
1244 while (slot->next != NULL)
1245 slot = slot->next;
1246 slot->next = newslot;
1248 slot = newslot;
1251 if (!slot->curl) {
1252 slot->curl = curl_easy_duphandle(curl_default);
1253 curl_session_count++;
1256 active_requests++;
1257 slot->in_use = 1;
1258 slot->results = NULL;
1259 slot->finished = NULL;
1260 slot->callback_data = NULL;
1261 slot->callback_func = NULL;
1262 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1263 if (curl_save_cookies)
1264 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1265 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1266 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1267 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1268 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1269 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1270 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1271 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1272 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1273 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1274 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1275 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1278 * Default following to off unless "ALWAYS" is configured; this gives
1279 * callers a sane starting point, and they can tweak for individual
1280 * HTTP_FOLLOW_* cases themselves.
1282 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1283 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1284 else
1285 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1287 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1288 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1289 if (http_auth.password || curl_empty_auth_enabled())
1290 init_curl_http_auth(slot->curl);
1292 return slot;
1295 int start_active_slot(struct active_request_slot *slot)
1297 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1298 int num_transfers;
1300 if (curlm_result != CURLM_OK &&
1301 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1302 warning("curl_multi_add_handle failed: %s",
1303 curl_multi_strerror(curlm_result));
1304 active_requests--;
1305 slot->in_use = 0;
1306 return 0;
1310 * We know there must be something to do, since we just added
1311 * something.
1313 curl_multi_perform(curlm, &num_transfers);
1314 return 1;
1317 struct fill_chain {
1318 void *data;
1319 int (*fill)(void *);
1320 struct fill_chain *next;
1323 static struct fill_chain *fill_cfg;
1325 void add_fill_function(void *data, int (*fill)(void *))
1327 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1328 struct fill_chain **linkp = &fill_cfg;
1329 new_fill->data = data;
1330 new_fill->fill = fill;
1331 new_fill->next = NULL;
1332 while (*linkp)
1333 linkp = &(*linkp)->next;
1334 *linkp = new_fill;
1337 void fill_active_slots(void)
1339 struct active_request_slot *slot = active_queue_head;
1341 while (active_requests < max_requests) {
1342 struct fill_chain *fill;
1343 for (fill = fill_cfg; fill; fill = fill->next)
1344 if (fill->fill(fill->data))
1345 break;
1347 if (!fill)
1348 break;
1351 while (slot != NULL) {
1352 if (!slot->in_use && slot->curl != NULL
1353 && curl_session_count > min_curl_sessions) {
1354 curl_easy_cleanup(slot->curl);
1355 slot->curl = NULL;
1356 curl_session_count--;
1358 slot = slot->next;
1362 void step_active_slots(void)
1364 int num_transfers;
1365 CURLMcode curlm_result;
1367 do {
1368 curlm_result = curl_multi_perform(curlm, &num_transfers);
1369 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1370 if (num_transfers < active_requests) {
1371 process_curl_messages();
1372 fill_active_slots();
1376 void run_active_slot(struct active_request_slot *slot)
1378 fd_set readfds;
1379 fd_set writefds;
1380 fd_set excfds;
1381 int max_fd;
1382 struct timeval select_timeout;
1383 int finished = 0;
1385 slot->finished = &finished;
1386 while (!finished) {
1387 step_active_slots();
1389 if (slot->in_use) {
1390 long curl_timeout;
1391 curl_multi_timeout(curlm, &curl_timeout);
1392 if (curl_timeout == 0) {
1393 continue;
1394 } else if (curl_timeout == -1) {
1395 select_timeout.tv_sec = 0;
1396 select_timeout.tv_usec = 50000;
1397 } else {
1398 select_timeout.tv_sec = curl_timeout / 1000;
1399 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1402 max_fd = -1;
1403 FD_ZERO(&readfds);
1404 FD_ZERO(&writefds);
1405 FD_ZERO(&excfds);
1406 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1409 * It can happen that curl_multi_timeout returns a pathologically
1410 * long timeout when curl_multi_fdset returns no file descriptors
1411 * to read. See commit message for more details.
1413 if (max_fd < 0 &&
1414 (select_timeout.tv_sec > 0 ||
1415 select_timeout.tv_usec > 50000)) {
1416 select_timeout.tv_sec = 0;
1417 select_timeout.tv_usec = 50000;
1420 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1425 * The value of slot->finished we set before the loop was used
1426 * to set our "finished" variable when our request completed.
1428 * 1. The slot may not have been reused for another requst
1429 * yet, in which case it still has &finished.
1431 * 2. The slot may already be in-use to serve another request,
1432 * which can further be divided into two cases:
1434 * (a) If call run_active_slot() hasn't been called for that
1435 * other request, slot->finished would have been cleared
1436 * by get_active_slot() and has NULL.
1438 * (b) If the request did call run_active_slot(), then the
1439 * call would have updated slot->finished at the beginning
1440 * of this function, and with the clearing of the member
1441 * below, we would find that slot->finished is now NULL.
1443 * In all cases, slot->finished has no useful information to
1444 * anybody at this point. Some compilers warn us for
1445 * attempting to smuggle a pointer that is about to become
1446 * invalid, i.e. &finished. We clear it here to assure them.
1448 slot->finished = NULL;
1451 static void release_active_slot(struct active_request_slot *slot)
1453 closedown_active_slot(slot);
1454 if (slot->curl) {
1455 xmulti_remove_handle(slot);
1456 if (curl_session_count > min_curl_sessions) {
1457 curl_easy_cleanup(slot->curl);
1458 slot->curl = NULL;
1459 curl_session_count--;
1462 fill_active_slots();
1465 void finish_all_active_slots(void)
1467 struct active_request_slot *slot = active_queue_head;
1469 while (slot != NULL)
1470 if (slot->in_use) {
1471 run_active_slot(slot);
1472 slot = active_queue_head;
1473 } else {
1474 slot = slot->next;
1478 /* Helpers for modifying and creating URLs */
1479 static inline int needs_quote(int ch)
1481 if (((ch >= 'A') && (ch <= 'Z'))
1482 || ((ch >= 'a') && (ch <= 'z'))
1483 || ((ch >= '0') && (ch <= '9'))
1484 || (ch == '/')
1485 || (ch == '-')
1486 || (ch == '.'))
1487 return 0;
1488 return 1;
1491 static char *quote_ref_url(const char *base, const char *ref)
1493 struct strbuf buf = STRBUF_INIT;
1494 const char *cp;
1495 int ch;
1497 end_url_with_slash(&buf, base);
1499 for (cp = ref; (ch = *cp) != 0; cp++)
1500 if (needs_quote(ch))
1501 strbuf_addf(&buf, "%%%02x", ch);
1502 else
1503 strbuf_addch(&buf, *cp);
1505 return strbuf_detach(&buf, NULL);
1508 void append_remote_object_url(struct strbuf *buf, const char *url,
1509 const char *hex,
1510 int only_two_digit_prefix)
1512 end_url_with_slash(buf, url);
1514 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1515 if (!only_two_digit_prefix)
1516 strbuf_addstr(buf, hex + 2);
1519 char *get_remote_object_url(const char *url, const char *hex,
1520 int only_two_digit_prefix)
1522 struct strbuf buf = STRBUF_INIT;
1523 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1524 return strbuf_detach(&buf, NULL);
1527 void normalize_curl_result(CURLcode *result, long http_code,
1528 char *errorstr, size_t errorlen)
1531 * If we see a failing http code with CURLE_OK, we have turned off
1532 * FAILONERROR (to keep the server's custom error response), and should
1533 * translate the code into failure here.
1535 * Likewise, if we see a redirect (30x code), that means we turned off
1536 * redirect-following, and we should treat the result as an error.
1538 if (*result == CURLE_OK && http_code >= 300) {
1539 *result = CURLE_HTTP_RETURNED_ERROR;
1541 * Normally curl will already have put the "reason phrase"
1542 * from the server into curl_errorstr; unfortunately without
1543 * FAILONERROR it is lost, so we can give only the numeric
1544 * status code.
1546 xsnprintf(errorstr, errorlen,
1547 "The requested URL returned error: %ld",
1548 http_code);
1552 static int handle_curl_result(struct slot_results *results)
1554 normalize_curl_result(&results->curl_result, results->http_code,
1555 curl_errorstr, sizeof(curl_errorstr));
1557 if (results->curl_result == CURLE_OK) {
1558 credential_approve(&http_auth);
1559 credential_approve(&proxy_auth);
1560 credential_approve(&cert_auth);
1561 return HTTP_OK;
1562 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1564 * We can't tell from here whether it's a bad path, bad
1565 * certificate, bad password, or something else wrong
1566 * with the certificate. So we reject the credential to
1567 * avoid caching or saving a bad password.
1569 credential_reject(&cert_auth);
1570 return HTTP_NOAUTH;
1571 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1572 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1573 return HTTP_NOMATCHPUBLICKEY;
1574 #endif
1575 } else if (missing_target(results))
1576 return HTTP_MISSING_TARGET;
1577 else if (results->http_code == 401) {
1578 if (http_auth.username && http_auth.password) {
1579 credential_reject(&http_auth);
1580 return HTTP_NOAUTH;
1581 } else {
1582 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1583 if (results->auth_avail) {
1584 http_auth_methods &= results->auth_avail;
1585 http_auth_methods_restricted = 1;
1587 return HTTP_REAUTH;
1589 } else {
1590 if (results->http_connectcode == 407)
1591 credential_reject(&proxy_auth);
1592 if (!curl_errorstr[0])
1593 strlcpy(curl_errorstr,
1594 curl_easy_strerror(results->curl_result),
1595 sizeof(curl_errorstr));
1596 return HTTP_ERROR;
1600 int run_one_slot(struct active_request_slot *slot,
1601 struct slot_results *results)
1603 slot->results = results;
1604 if (!start_active_slot(slot)) {
1605 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1606 "failed to start HTTP request");
1607 return HTTP_START_FAILED;
1610 run_active_slot(slot);
1611 return handle_curl_result(results);
1614 struct curl_slist *http_copy_default_headers(void)
1616 struct curl_slist *headers = NULL;
1617 const struct string_list_item *item;
1619 for_each_string_list_item(item, &extra_http_headers)
1620 headers = curl_slist_append(headers, item->string);
1622 return headers;
1625 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1627 char *ptr;
1628 CURLcode ret;
1630 strbuf_reset(buf);
1631 ret = curl_easy_getinfo(curl, info, &ptr);
1632 if (!ret && ptr)
1633 strbuf_addstr(buf, ptr);
1634 return ret;
1638 * Check for and extract a content-type parameter. "raw"
1639 * should be positioned at the start of the potential
1640 * parameter, with any whitespace already removed.
1642 * "name" is the name of the parameter. The value is appended
1643 * to "out".
1645 static int extract_param(const char *raw, const char *name,
1646 struct strbuf *out)
1648 size_t len = strlen(name);
1650 if (strncasecmp(raw, name, len))
1651 return -1;
1652 raw += len;
1654 if (*raw != '=')
1655 return -1;
1656 raw++;
1658 while (*raw && !isspace(*raw) && *raw != ';')
1659 strbuf_addch(out, *raw++);
1660 return 0;
1664 * Extract a normalized version of the content type, with any
1665 * spaces suppressed, all letters lowercased, and no trailing ";"
1666 * or parameters.
1668 * Note that we will silently remove even invalid whitespace. For
1669 * example, "text / plain" is specifically forbidden by RFC 2616,
1670 * but "text/plain" is the only reasonable output, and this keeps
1671 * our code simple.
1673 * If the "charset" argument is not NULL, store the value of any
1674 * charset parameter there.
1676 * Example:
1677 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1678 * "text / plain" -> "text/plain"
1680 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1681 struct strbuf *charset)
1683 const char *p;
1685 strbuf_reset(type);
1686 strbuf_grow(type, raw->len);
1687 for (p = raw->buf; *p; p++) {
1688 if (isspace(*p))
1689 continue;
1690 if (*p == ';') {
1691 p++;
1692 break;
1694 strbuf_addch(type, tolower(*p));
1697 if (!charset)
1698 return;
1700 strbuf_reset(charset);
1701 while (*p) {
1702 while (isspace(*p) || *p == ';')
1703 p++;
1704 if (!extract_param(p, "charset", charset))
1705 return;
1706 while (*p && !isspace(*p))
1707 p++;
1710 if (!charset->len && starts_with(type->buf, "text/"))
1711 strbuf_addstr(charset, "ISO-8859-1");
1714 static void write_accept_language(struct strbuf *buf)
1717 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1718 * that, q-value will be smaller than 0.001, the minimum q-value the
1719 * HTTP specification allows. See
1720 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1722 const int MAX_DECIMAL_PLACES = 3;
1723 const int MAX_LANGUAGE_TAGS = 1000;
1724 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1725 char **language_tags = NULL;
1726 int num_langs = 0;
1727 const char *s = get_preferred_languages();
1728 int i;
1729 struct strbuf tag = STRBUF_INIT;
1731 /* Don't add Accept-Language header if no language is preferred. */
1732 if (!s)
1733 return;
1736 * Split the colon-separated string of preferred languages into
1737 * language_tags array.
1739 do {
1740 /* collect language tag */
1741 for (; *s && (isalnum(*s) || *s == '_'); s++)
1742 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1744 /* skip .codeset, @modifier and any other unnecessary parts */
1745 while (*s && *s != ':')
1746 s++;
1748 if (tag.len) {
1749 num_langs++;
1750 REALLOC_ARRAY(language_tags, num_langs);
1751 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1752 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1753 break;
1755 } while (*s++);
1757 /* write Accept-Language header into buf */
1758 if (num_langs) {
1759 int last_buf_len = 0;
1760 int max_q;
1761 int decimal_places;
1762 char q_format[32];
1764 /* add '*' */
1765 REALLOC_ARRAY(language_tags, num_langs + 1);
1766 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1768 /* compute decimal_places */
1769 for (max_q = 1, decimal_places = 0;
1770 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1771 decimal_places++, max_q *= 10)
1774 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1776 strbuf_addstr(buf, "Accept-Language: ");
1778 for (i = 0; i < num_langs; i++) {
1779 if (i > 0)
1780 strbuf_addstr(buf, ", ");
1782 strbuf_addstr(buf, language_tags[i]);
1784 if (i > 0)
1785 strbuf_addf(buf, q_format, max_q - i);
1787 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1788 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1789 break;
1792 last_buf_len = buf->len;
1796 /* free language tags -- last one is a static '*' */
1797 for (i = 0; i < num_langs - 1; i++)
1798 free(language_tags[i]);
1799 free(language_tags);
1803 * Get an Accept-Language header which indicates user's preferred languages.
1805 * Examples:
1806 * LANGUAGE= -> ""
1807 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1808 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1809 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1810 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1811 * LANGUAGE= LANG=C -> ""
1813 const char *http_get_accept_language_header(void)
1815 if (!cached_accept_language) {
1816 struct strbuf buf = STRBUF_INIT;
1817 write_accept_language(&buf);
1818 if (buf.len > 0)
1819 cached_accept_language = strbuf_detach(&buf, NULL);
1822 return cached_accept_language;
1825 static void http_opt_request_remainder(CURL *curl, off_t pos)
1827 char buf[128];
1828 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1829 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1832 /* http_request() targets */
1833 #define HTTP_REQUEST_STRBUF 0
1834 #define HTTP_REQUEST_FILE 1
1836 static int http_request(const char *url,
1837 void *result, int target,
1838 const struct http_get_options *options)
1840 struct active_request_slot *slot;
1841 struct slot_results results;
1842 struct curl_slist *headers = http_copy_default_headers();
1843 struct strbuf buf = STRBUF_INIT;
1844 const char *accept_language;
1845 int ret;
1847 slot = get_active_slot();
1848 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1850 if (!result) {
1851 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1852 } else {
1853 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1854 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
1856 if (target == HTTP_REQUEST_FILE) {
1857 off_t posn = ftello(result);
1858 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1859 fwrite);
1860 if (posn > 0)
1861 http_opt_request_remainder(slot->curl, posn);
1862 } else
1863 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1864 fwrite_buffer);
1867 accept_language = http_get_accept_language_header();
1869 if (accept_language)
1870 headers = curl_slist_append(headers, accept_language);
1872 strbuf_addstr(&buf, "Pragma:");
1873 if (options && options->no_cache)
1874 strbuf_addstr(&buf, " no-cache");
1875 if (options && options->initial_request &&
1876 http_follow_config == HTTP_FOLLOW_INITIAL)
1877 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1879 headers = curl_slist_append(headers, buf.buf);
1881 /* Add additional headers here */
1882 if (options && options->extra_headers) {
1883 const struct string_list_item *item;
1884 for_each_string_list_item(item, options->extra_headers) {
1885 headers = curl_slist_append(headers, item->string);
1889 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1890 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1891 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1892 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1894 ret = run_one_slot(slot, &results);
1896 if (options && options->content_type) {
1897 struct strbuf raw = STRBUF_INIT;
1898 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1899 extract_content_type(&raw, options->content_type,
1900 options->charset);
1901 strbuf_release(&raw);
1904 if (options && options->effective_url)
1905 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1906 options->effective_url);
1908 curl_slist_free_all(headers);
1909 strbuf_release(&buf);
1911 return ret;
1915 * Update the "base" url to a more appropriate value, as deduced by
1916 * redirects seen when requesting a URL starting with "url".
1918 * The "asked" parameter is a URL that we asked curl to access, and must begin
1919 * with "base".
1921 * The "got" parameter is the URL that curl reported to us as where we ended
1922 * up.
1924 * Returns 1 if we updated the base url, 0 otherwise.
1926 * Our basic strategy is to compare "base" and "asked" to find the bits
1927 * specific to our request. We then strip those bits off of "got" to yield the
1928 * new base. So for example, if our base is "http://example.com/foo.git",
1929 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1930 * with "https://other.example.com/foo.git/info/refs". We would want the
1931 * new URL to become "https://other.example.com/foo.git".
1933 * Note that this assumes a sane redirect scheme. It's entirely possible
1934 * in the example above to end up at a URL that does not even end in
1935 * "info/refs". In such a case we die. There's not much we can do, such a
1936 * scheme is unlikely to represent a real git repository, and failing to
1937 * rewrite the base opens options for malicious redirects to do funny things.
1939 static int update_url_from_redirect(struct strbuf *base,
1940 const char *asked,
1941 const struct strbuf *got)
1943 const char *tail;
1944 size_t new_len;
1946 if (!strcmp(asked, got->buf))
1947 return 0;
1949 if (!skip_prefix(asked, base->buf, &tail))
1950 BUG("update_url_from_redirect: %s is not a superset of %s",
1951 asked, base->buf);
1953 new_len = got->len;
1954 if (!strip_suffix_mem(got->buf, &new_len, tail))
1955 die(_("unable to update url base from redirection:\n"
1956 " asked for: %s\n"
1957 " redirect: %s"),
1958 asked, got->buf);
1960 strbuf_reset(base);
1961 strbuf_add(base, got->buf, new_len);
1963 return 1;
1966 static int http_request_reauth(const char *url,
1967 void *result, int target,
1968 struct http_get_options *options)
1970 int ret = http_request(url, result, target, options);
1972 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1973 return ret;
1975 if (options && options->effective_url && options->base_url) {
1976 if (update_url_from_redirect(options->base_url,
1977 url, options->effective_url)) {
1978 credential_from_url(&http_auth, options->base_url->buf);
1979 url = options->effective_url->buf;
1983 if (ret != HTTP_REAUTH)
1984 return ret;
1987 * The previous request may have put cruft into our output stream; we
1988 * should clear it out before making our next request.
1990 switch (target) {
1991 case HTTP_REQUEST_STRBUF:
1992 strbuf_reset(result);
1993 break;
1994 case HTTP_REQUEST_FILE:
1995 if (fflush(result)) {
1996 error_errno("unable to flush a file");
1997 return HTTP_START_FAILED;
1999 rewind(result);
2000 if (ftruncate(fileno(result), 0) < 0) {
2001 error_errno("unable to truncate a file");
2002 return HTTP_START_FAILED;
2004 break;
2005 default:
2006 BUG("Unknown http_request target");
2009 credential_fill(&http_auth);
2011 return http_request(url, result, target, options);
2014 int http_get_strbuf(const char *url,
2015 struct strbuf *result,
2016 struct http_get_options *options)
2018 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2022 * Downloads a URL and stores the result in the given file.
2024 * If a previous interrupted download is detected (i.e. a previous temporary
2025 * file is still around) the download is resumed.
2027 int http_get_file(const char *url, const char *filename,
2028 struct http_get_options *options)
2030 int ret;
2031 struct strbuf tmpfile = STRBUF_INIT;
2032 FILE *result;
2034 strbuf_addf(&tmpfile, "%s.temp", filename);
2035 result = fopen(tmpfile.buf, "a");
2036 if (!result) {
2037 error("Unable to open local file %s", tmpfile.buf);
2038 ret = HTTP_ERROR;
2039 goto cleanup;
2042 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2043 fclose(result);
2045 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2046 ret = HTTP_ERROR;
2047 cleanup:
2048 strbuf_release(&tmpfile);
2049 return ret;
2052 int http_fetch_ref(const char *base, struct ref *ref)
2054 struct http_get_options options = {0};
2055 char *url;
2056 struct strbuf buffer = STRBUF_INIT;
2057 int ret = -1;
2059 options.no_cache = 1;
2061 url = quote_ref_url(base, ref->name);
2062 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2063 strbuf_rtrim(&buffer);
2064 if (buffer.len == the_hash_algo->hexsz)
2065 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2066 else if (starts_with(buffer.buf, "ref: ")) {
2067 ref->symref = xstrdup(buffer.buf + 5);
2068 ret = 0;
2072 strbuf_release(&buffer);
2073 free(url);
2074 return ret;
2077 /* Helpers for fetching packs */
2078 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2080 char *url, *tmp;
2081 struct strbuf buf = STRBUF_INIT;
2083 if (http_is_verbose)
2084 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2086 end_url_with_slash(&buf, base_url);
2087 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2088 url = strbuf_detach(&buf, NULL);
2090 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2091 tmp = strbuf_detach(&buf, NULL);
2093 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2094 error("Unable to get pack index %s", url);
2095 FREE_AND_NULL(tmp);
2098 free(url);
2099 return tmp;
2102 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2103 unsigned char *sha1, const char *base_url)
2105 struct packed_git *new_pack;
2106 char *tmp_idx = NULL;
2107 int ret;
2109 if (has_pack_index(sha1)) {
2110 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2111 if (!new_pack)
2112 return -1; /* parse_pack_index() already issued error message */
2113 goto add_pack;
2116 tmp_idx = fetch_pack_index(sha1, base_url);
2117 if (!tmp_idx)
2118 return -1;
2120 new_pack = parse_pack_index(sha1, tmp_idx);
2121 if (!new_pack) {
2122 unlink(tmp_idx);
2123 free(tmp_idx);
2125 return -1; /* parse_pack_index() already issued error message */
2128 ret = verify_pack_index(new_pack);
2129 if (!ret) {
2130 close_pack_index(new_pack);
2131 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2133 free(tmp_idx);
2134 if (ret)
2135 return -1;
2137 add_pack:
2138 new_pack->next = *packs_head;
2139 *packs_head = new_pack;
2140 return 0;
2143 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2145 struct http_get_options options = {0};
2146 int ret = 0;
2147 char *url;
2148 const char *data;
2149 struct strbuf buf = STRBUF_INIT;
2150 struct object_id oid;
2152 end_url_with_slash(&buf, base_url);
2153 strbuf_addstr(&buf, "objects/info/packs");
2154 url = strbuf_detach(&buf, NULL);
2156 options.no_cache = 1;
2157 ret = http_get_strbuf(url, &buf, &options);
2158 if (ret != HTTP_OK)
2159 goto cleanup;
2161 data = buf.buf;
2162 while (*data) {
2163 if (skip_prefix(data, "P pack-", &data) &&
2164 !parse_oid_hex(data, &oid, &data) &&
2165 skip_prefix(data, ".pack", &data) &&
2166 (*data == '\n' || *data == '\0')) {
2167 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2168 } else {
2169 data = strchrnul(data, '\n');
2171 if (*data)
2172 data++; /* skip past newline */
2175 cleanup:
2176 free(url);
2177 return ret;
2180 void release_http_pack_request(struct http_pack_request *preq)
2182 if (preq->packfile) {
2183 fclose(preq->packfile);
2184 preq->packfile = NULL;
2186 preq->slot = NULL;
2187 strbuf_release(&preq->tmpfile);
2188 free(preq->url);
2189 free(preq);
2192 static const char *default_index_pack_args[] =
2193 {"index-pack", "--stdin", NULL};
2195 int finish_http_pack_request(struct http_pack_request *preq)
2197 struct child_process ip = CHILD_PROCESS_INIT;
2198 int tmpfile_fd;
2199 int ret = 0;
2201 fclose(preq->packfile);
2202 preq->packfile = NULL;
2204 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2206 ip.git_cmd = 1;
2207 ip.in = tmpfile_fd;
2208 strvec_pushv(&ip.args, preq->index_pack_args ?
2209 preq->index_pack_args :
2210 default_index_pack_args);
2212 if (preq->preserve_index_pack_stdout)
2213 ip.out = 0;
2214 else
2215 ip.no_stdout = 1;
2217 if (run_command(&ip)) {
2218 ret = -1;
2219 goto cleanup;
2222 cleanup:
2223 close(tmpfile_fd);
2224 unlink(preq->tmpfile.buf);
2225 return ret;
2228 void http_install_packfile(struct packed_git *p,
2229 struct packed_git **list_to_remove_from)
2231 struct packed_git **lst = list_to_remove_from;
2233 while (*lst != p)
2234 lst = &((*lst)->next);
2235 *lst = (*lst)->next;
2237 install_packed_git(the_repository, p);
2240 struct http_pack_request *new_http_pack_request(
2241 const unsigned char *packed_git_hash, const char *base_url) {
2243 struct strbuf buf = STRBUF_INIT;
2245 end_url_with_slash(&buf, base_url);
2246 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2247 hash_to_hex(packed_git_hash));
2248 return new_direct_http_pack_request(packed_git_hash,
2249 strbuf_detach(&buf, NULL));
2252 struct http_pack_request *new_direct_http_pack_request(
2253 const unsigned char *packed_git_hash, char *url)
2255 off_t prev_posn = 0;
2256 struct http_pack_request *preq;
2258 CALLOC_ARRAY(preq, 1);
2259 strbuf_init(&preq->tmpfile, 0);
2261 preq->url = url;
2263 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2264 preq->packfile = fopen(preq->tmpfile.buf, "a");
2265 if (!preq->packfile) {
2266 error("Unable to open local file %s for pack",
2267 preq->tmpfile.buf);
2268 goto abort;
2271 preq->slot = get_active_slot();
2272 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2273 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2274 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2275 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2276 no_pragma_header);
2279 * If there is data present from a previous transfer attempt,
2280 * resume where it left off
2282 prev_posn = ftello(preq->packfile);
2283 if (prev_posn>0) {
2284 if (http_is_verbose)
2285 fprintf(stderr,
2286 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2287 hash_to_hex(packed_git_hash),
2288 (uintmax_t)prev_posn);
2289 http_opt_request_remainder(preq->slot->curl, prev_posn);
2292 return preq;
2294 abort:
2295 strbuf_release(&preq->tmpfile);
2296 free(preq->url);
2297 free(preq);
2298 return NULL;
2301 /* Helpers for fetching objects (loose) */
2302 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2303 void *data)
2305 unsigned char expn[4096];
2306 size_t size = eltsize * nmemb;
2307 int posn = 0;
2308 struct http_object_request *freq = data;
2309 struct active_request_slot *slot = freq->slot;
2311 if (slot) {
2312 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2313 &slot->http_code);
2314 if (c != CURLE_OK)
2315 BUG("curl_easy_getinfo for HTTP code failed: %s",
2316 curl_easy_strerror(c));
2317 if (slot->http_code >= 300)
2318 return nmemb;
2321 do {
2322 ssize_t retval = xwrite(freq->localfile,
2323 (char *) ptr + posn, size - posn);
2324 if (retval < 0)
2325 return posn / eltsize;
2326 posn += retval;
2327 } while (posn < size);
2329 freq->stream.avail_in = size;
2330 freq->stream.next_in = (void *)ptr;
2331 do {
2332 freq->stream.next_out = expn;
2333 freq->stream.avail_out = sizeof(expn);
2334 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2335 the_hash_algo->update_fn(&freq->c, expn,
2336 sizeof(expn) - freq->stream.avail_out);
2337 } while (freq->stream.avail_in && freq->zret == Z_OK);
2338 return nmemb;
2341 struct http_object_request *new_http_object_request(const char *base_url,
2342 const struct object_id *oid)
2344 char *hex = oid_to_hex(oid);
2345 struct strbuf filename = STRBUF_INIT;
2346 struct strbuf prevfile = STRBUF_INIT;
2347 int prevlocal;
2348 char prev_buf[PREV_BUF_SIZE];
2349 ssize_t prev_read = 0;
2350 off_t prev_posn = 0;
2351 struct http_object_request *freq;
2353 CALLOC_ARRAY(freq, 1);
2354 strbuf_init(&freq->tmpfile, 0);
2355 oidcpy(&freq->oid, oid);
2356 freq->localfile = -1;
2358 loose_object_path(the_repository, &filename, oid);
2359 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2361 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2362 unlink_or_warn(prevfile.buf);
2363 rename(freq->tmpfile.buf, prevfile.buf);
2364 unlink_or_warn(freq->tmpfile.buf);
2365 strbuf_release(&filename);
2367 if (freq->localfile != -1)
2368 error("fd leakage in start: %d", freq->localfile);
2369 freq->localfile = open(freq->tmpfile.buf,
2370 O_WRONLY | O_CREAT | O_EXCL, 0666);
2372 * This could have failed due to the "lazy directory creation";
2373 * try to mkdir the last path component.
2375 if (freq->localfile < 0 && errno == ENOENT) {
2376 char *dir = strrchr(freq->tmpfile.buf, '/');
2377 if (dir) {
2378 *dir = 0;
2379 mkdir(freq->tmpfile.buf, 0777);
2380 *dir = '/';
2382 freq->localfile = open(freq->tmpfile.buf,
2383 O_WRONLY | O_CREAT | O_EXCL, 0666);
2386 if (freq->localfile < 0) {
2387 error_errno("Couldn't create temporary file %s",
2388 freq->tmpfile.buf);
2389 goto abort;
2392 git_inflate_init(&freq->stream);
2394 the_hash_algo->init_fn(&freq->c);
2396 freq->url = get_remote_object_url(base_url, hex, 0);
2399 * If a previous temp file is present, process what was already
2400 * fetched.
2402 prevlocal = open(prevfile.buf, O_RDONLY);
2403 if (prevlocal != -1) {
2404 do {
2405 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2406 if (prev_read>0) {
2407 if (fwrite_sha1_file(prev_buf,
2409 prev_read,
2410 freq) == prev_read) {
2411 prev_posn += prev_read;
2412 } else {
2413 prev_read = -1;
2416 } while (prev_read > 0);
2417 close(prevlocal);
2419 unlink_or_warn(prevfile.buf);
2420 strbuf_release(&prevfile);
2423 * Reset inflate/SHA1 if there was an error reading the previous temp
2424 * file; also rewind to the beginning of the local file.
2426 if (prev_read == -1) {
2427 memset(&freq->stream, 0, sizeof(freq->stream));
2428 git_inflate_init(&freq->stream);
2429 the_hash_algo->init_fn(&freq->c);
2430 if (prev_posn>0) {
2431 prev_posn = 0;
2432 lseek(freq->localfile, 0, SEEK_SET);
2433 if (ftruncate(freq->localfile, 0) < 0) {
2434 error_errno("Couldn't truncate temporary file %s",
2435 freq->tmpfile.buf);
2436 goto abort;
2441 freq->slot = get_active_slot();
2443 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2444 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2445 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2446 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2447 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2448 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2451 * If we have successfully processed data from a previous fetch
2452 * attempt, only fetch the data we don't already have.
2454 if (prev_posn>0) {
2455 if (http_is_verbose)
2456 fprintf(stderr,
2457 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2458 hex, (uintmax_t)prev_posn);
2459 http_opt_request_remainder(freq->slot->curl, prev_posn);
2462 return freq;
2464 abort:
2465 strbuf_release(&prevfile);
2466 free(freq->url);
2467 free(freq);
2468 return NULL;
2471 void process_http_object_request(struct http_object_request *freq)
2473 if (!freq->slot)
2474 return;
2475 freq->curl_result = freq->slot->curl_result;
2476 freq->http_code = freq->slot->http_code;
2477 freq->slot = NULL;
2480 int finish_http_object_request(struct http_object_request *freq)
2482 struct stat st;
2483 struct strbuf filename = STRBUF_INIT;
2485 close(freq->localfile);
2486 freq->localfile = -1;
2488 process_http_object_request(freq);
2490 if (freq->http_code == 416) {
2491 warning("requested range invalid; we may already have all the data.");
2492 } else if (freq->curl_result != CURLE_OK) {
2493 if (stat(freq->tmpfile.buf, &st) == 0)
2494 if (st.st_size == 0)
2495 unlink_or_warn(freq->tmpfile.buf);
2496 return -1;
2499 git_inflate_end(&freq->stream);
2500 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2501 if (freq->zret != Z_STREAM_END) {
2502 unlink_or_warn(freq->tmpfile.buf);
2503 return -1;
2505 if (!oideq(&freq->oid, &freq->real_oid)) {
2506 unlink_or_warn(freq->tmpfile.buf);
2507 return -1;
2509 loose_object_path(the_repository, &filename, &freq->oid);
2510 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2511 strbuf_release(&filename);
2513 return freq->rename;
2516 void abort_http_object_request(struct http_object_request *freq)
2518 unlink_or_warn(freq->tmpfile.buf);
2520 release_http_object_request(freq);
2523 void release_http_object_request(struct http_object_request *freq)
2525 if (freq->localfile != -1) {
2526 close(freq->localfile);
2527 freq->localfile = -1;
2529 FREE_AND_NULL(freq->url);
2530 if (freq->slot) {
2531 freq->slot->callback_func = NULL;
2532 freq->slot->callback_data = NULL;
2533 release_active_slot(freq->slot);
2534 freq->slot = NULL;
2536 strbuf_release(&freq->tmpfile);