The fourth batch
[alt-git.git] / http.c
blobf08b2ae47465332714494cd5ea054880d42702c1
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
4 #include "git-compat-util.h"
5 #include "git-curl-compat.h"
6 #include "hex.h"
7 #include "http.h"
8 #include "config.h"
9 #include "pack.h"
10 #include "run-command.h"
11 #include "url.h"
12 #include "urlmatch.h"
13 #include "credential.h"
14 #include "version.h"
15 #include "pkt-line.h"
16 #include "gettext.h"
17 #include "trace.h"
18 #include "transport.h"
19 #include "packfile.h"
20 #include "string-list.h"
21 #include "object-file.h"
22 #include "object-store-ll.h"
23 #include "tempfile.h"
25 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
26 static int trace_curl_data = 1;
27 static int trace_curl_redact = 1;
28 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
29 int active_requests;
30 int http_is_verbose;
31 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
33 static int min_curl_sessions = 1;
34 static int curl_session_count;
35 static int max_requests = -1;
36 static CURLM *curlm;
37 static CURL *curl_default;
39 #define PREV_BUF_SIZE 4096
41 char curl_errorstr[CURL_ERROR_SIZE];
43 static int curl_ssl_verify = -1;
44 static int curl_ssl_try;
45 static char *curl_http_version;
46 static char *ssl_cert;
47 static char *ssl_cert_type;
48 static char *ssl_cipherlist;
49 static char *ssl_version;
50 static struct {
51 const char *name;
52 long ssl_version;
53 } sslversions[] = {
54 { "sslv2", CURL_SSLVERSION_SSLv2 },
55 { "sslv3", CURL_SSLVERSION_SSLv3 },
56 { "tlsv1", CURL_SSLVERSION_TLSv1 },
57 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
58 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
59 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
60 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
62 static char *ssl_key;
63 static char *ssl_key_type;
64 static char *ssl_capath;
65 static char *curl_no_proxy;
66 static char *ssl_pinnedkey;
67 static char *ssl_cainfo;
68 static long curl_low_speed_limit = -1;
69 static long curl_low_speed_time = -1;
70 static int curl_ftp_no_epsv;
71 static char *curl_http_proxy;
72 static char *http_proxy_authmethod;
74 static char *http_proxy_ssl_cert;
75 static char *http_proxy_ssl_key;
76 static char *http_proxy_ssl_ca_info;
77 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
78 static int proxy_ssl_cert_password_required;
80 static struct {
81 const char *name;
82 long curlauth_param;
83 } proxy_authmethods[] = {
84 { "basic", CURLAUTH_BASIC },
85 { "digest", CURLAUTH_DIGEST },
86 { "negotiate", CURLAUTH_GSSNEGOTIATE },
87 { "ntlm", CURLAUTH_NTLM },
88 { "anyauth", CURLAUTH_ANY },
90 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
91 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
92 * here, too
95 #ifdef CURLGSSAPI_DELEGATION_FLAG
96 static char *curl_deleg;
97 static struct {
98 const char *name;
99 long curl_deleg_param;
100 } curl_deleg_levels[] = {
101 { "none", CURLGSSAPI_DELEGATION_NONE },
102 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
103 { "always", CURLGSSAPI_DELEGATION_FLAG },
105 #endif
107 enum proactive_auth {
108 PROACTIVE_AUTH_NONE = 0,
109 PROACTIVE_AUTH_IF_CREDENTIALS,
110 PROACTIVE_AUTH_AUTO,
111 PROACTIVE_AUTH_BASIC,
114 static struct credential proxy_auth = CREDENTIAL_INIT;
115 static const char *curl_proxyuserpwd;
116 static char *curl_cookie_file;
117 static int curl_save_cookies;
118 struct credential http_auth = CREDENTIAL_INIT;
119 static enum proactive_auth http_proactive_auth;
120 static char *user_agent;
121 static int curl_empty_auth = -1;
123 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
125 static struct credential cert_auth = CREDENTIAL_INIT;
126 static int ssl_cert_password_required;
127 static unsigned long http_auth_methods = CURLAUTH_ANY;
128 static int http_auth_methods_restricted;
129 /* Modes for which empty_auth cannot actually help us. */
130 static unsigned long empty_auth_useless =
131 CURLAUTH_BASIC
132 | CURLAUTH_DIGEST_IE
133 | CURLAUTH_DIGEST;
135 static struct curl_slist *pragma_header;
136 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
138 static struct curl_slist *host_resolutions;
140 static struct active_request_slot *active_queue_head;
142 static char *cached_accept_language;
144 static char *http_ssl_backend;
146 static int http_schannel_check_revoke = 1;
148 * With the backend being set to `schannel`, setting sslCAinfo would override
149 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
150 * by default.
152 static int http_schannel_use_ssl_cainfo;
154 static int always_auth_proactively(void)
156 return http_proactive_auth != PROACTIVE_AUTH_NONE &&
157 http_proactive_auth != PROACTIVE_AUTH_IF_CREDENTIALS;
160 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
162 size_t size = eltsize * nmemb;
163 struct buffer *buffer = buffer_;
165 if (size > buffer->buf.len - buffer->posn)
166 size = buffer->buf.len - buffer->posn;
167 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
168 buffer->posn += size;
170 return size / eltsize;
173 int seek_buffer(void *clientp, curl_off_t offset, int origin)
175 struct buffer *buffer = clientp;
177 if (origin != SEEK_SET)
178 BUG("seek_buffer only handles SEEK_SET");
179 if (offset < 0 || offset >= buffer->buf.len) {
180 error("curl seek would be outside of buffer");
181 return CURL_SEEKFUNC_FAIL;
184 buffer->posn = offset;
185 return CURL_SEEKFUNC_OK;
188 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
190 size_t size = eltsize * nmemb;
191 struct strbuf *buffer = buffer_;
193 strbuf_add(buffer, ptr, size);
194 return nmemb;
198 * A folded header continuation line starts with any number of spaces or
199 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
200 * It is not a continuation line if the line starts with any other character.
202 static inline int is_hdr_continuation(const char *ptr, const size_t size)
204 return size && (*ptr == ' ' || *ptr == '\t');
207 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
209 size_t size = eltsize * nmemb;
210 struct strvec *values = &http_auth.wwwauth_headers;
211 struct strbuf buf = STRBUF_INIT;
212 const char *val;
213 size_t val_len;
216 * Header lines may not come NULL-terminated from libcurl so we must
217 * limit all scans to the maximum length of the header line, or leverage
218 * strbufs for all operations.
220 * In addition, it is possible that header values can be split over
221 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
222 * but older servers may still emit them. A continuation header field
223 * value is identified as starting with a space or horizontal tab.
225 * The formal definition of a header field as given in RFC 7230 is:
227 * header-field = field-name ":" OWS field-value OWS
229 * field-name = token
230 * field-value = *( field-content / obs-fold )
231 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
232 * field-vchar = VCHAR / obs-text
234 * obs-fold = CRLF 1*( SP / HTAB )
235 * ; obsolete line folding
236 * ; see Section 3.2.4
239 /* Start of a new WWW-Authenticate header */
240 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
241 strbuf_add(&buf, val, val_len);
244 * Strip the CRLF that should be present at the end of each
245 * field as well as any trailing or leading whitespace from the
246 * value.
248 strbuf_trim(&buf);
250 strvec_push(values, buf.buf);
251 http_auth.header_is_last_match = 1;
252 goto exit;
256 * This line could be a continuation of the previously matched header
257 * field. If this is the case then we should append this value to the
258 * end of the previously consumed value.
260 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
262 * Trim the CRLF and any leading or trailing from this line.
264 strbuf_add(&buf, ptr, size);
265 strbuf_trim(&buf);
268 * At this point we should always have at least one existing
269 * value, even if it is empty. Do not bother appending the new
270 * value if this continuation header is itself empty.
272 if (!values->nr) {
273 BUG("should have at least one existing header value");
274 } else if (buf.len) {
275 char *prev = xstrdup(values->v[values->nr - 1]);
277 /* Join two non-empty values with a single space. */
278 const char *const sp = *prev ? " " : "";
280 strvec_pop(values);
281 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
282 free(prev);
285 goto exit;
288 /* Not a continuation of a previously matched auth header line. */
289 http_auth.header_is_last_match = 0;
292 * If this is a HTTP status line and not a header field, this signals
293 * a different HTTP response. libcurl writes all the output of all
294 * response headers of all responses, including redirects.
295 * We only care about the last HTTP request response's headers so clear
296 * the existing array.
298 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
299 strvec_clear(values);
301 exit:
302 strbuf_release(&buf);
303 return size;
306 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
307 void *data UNUSED)
309 return nmemb;
312 static struct curl_slist *object_request_headers(void)
314 return curl_slist_append(http_copy_default_headers(), "Pragma:");
317 static void closedown_active_slot(struct active_request_slot *slot)
319 active_requests--;
320 slot->in_use = 0;
323 static void finish_active_slot(struct active_request_slot *slot)
325 closedown_active_slot(slot);
326 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
328 if (slot->finished)
329 (*slot->finished) = 1;
331 /* Store slot results so they can be read after the slot is reused */
332 if (slot->results) {
333 slot->results->curl_result = slot->curl_result;
334 slot->results->http_code = slot->http_code;
335 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
336 &slot->results->auth_avail);
338 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
339 &slot->results->http_connectcode);
342 /* Run callback if appropriate */
343 if (slot->callback_func)
344 slot->callback_func(slot->callback_data);
347 static void xmulti_remove_handle(struct active_request_slot *slot)
349 curl_multi_remove_handle(curlm, slot->curl);
352 static void process_curl_messages(void)
354 int num_messages;
355 struct active_request_slot *slot;
356 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
358 while (curl_message != NULL) {
359 if (curl_message->msg == CURLMSG_DONE) {
360 int curl_result = curl_message->data.result;
361 slot = active_queue_head;
362 while (slot != NULL &&
363 slot->curl != curl_message->easy_handle)
364 slot = slot->next;
365 if (slot) {
366 xmulti_remove_handle(slot);
367 slot->curl_result = curl_result;
368 finish_active_slot(slot);
369 } else {
370 fprintf(stderr, "Received DONE message for unknown request!\n");
372 } else {
373 fprintf(stderr, "Unknown CURL message received: %d\n",
374 (int)curl_message->msg);
376 curl_message = curl_multi_info_read(curlm, &num_messages);
380 static int http_options(const char *var, const char *value,
381 const struct config_context *ctx, void *data)
383 if (!strcmp("http.version", var)) {
384 return git_config_string(&curl_http_version, var, value);
386 if (!strcmp("http.sslverify", var)) {
387 curl_ssl_verify = git_config_bool(var, value);
388 return 0;
390 if (!strcmp("http.sslcipherlist", var))
391 return git_config_string(&ssl_cipherlist, var, value);
392 if (!strcmp("http.sslversion", var))
393 return git_config_string(&ssl_version, var, value);
394 if (!strcmp("http.sslcert", var))
395 return git_config_pathname(&ssl_cert, var, value);
396 if (!strcmp("http.sslcerttype", var))
397 return git_config_string(&ssl_cert_type, var, value);
398 if (!strcmp("http.sslkey", var))
399 return git_config_pathname(&ssl_key, var, value);
400 if (!strcmp("http.sslkeytype", var))
401 return git_config_string(&ssl_key_type, var, value);
402 if (!strcmp("http.sslcapath", var))
403 return git_config_pathname(&ssl_capath, var, value);
404 if (!strcmp("http.sslcainfo", var))
405 return git_config_pathname(&ssl_cainfo, var, value);
406 if (!strcmp("http.sslcertpasswordprotected", var)) {
407 ssl_cert_password_required = git_config_bool(var, value);
408 return 0;
410 if (!strcmp("http.ssltry", var)) {
411 curl_ssl_try = git_config_bool(var, value);
412 return 0;
414 if (!strcmp("http.sslbackend", var)) {
415 free(http_ssl_backend);
416 http_ssl_backend = xstrdup_or_null(value);
417 return 0;
420 if (!strcmp("http.schannelcheckrevoke", var)) {
421 http_schannel_check_revoke = git_config_bool(var, value);
422 return 0;
425 if (!strcmp("http.schannelusesslcainfo", var)) {
426 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
427 return 0;
430 if (!strcmp("http.minsessions", var)) {
431 min_curl_sessions = git_config_int(var, value, ctx->kvi);
432 if (min_curl_sessions > 1)
433 min_curl_sessions = 1;
434 return 0;
436 if (!strcmp("http.maxrequests", var)) {
437 max_requests = git_config_int(var, value, ctx->kvi);
438 return 0;
440 if (!strcmp("http.lowspeedlimit", var)) {
441 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
442 return 0;
444 if (!strcmp("http.lowspeedtime", var)) {
445 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
446 return 0;
449 if (!strcmp("http.noepsv", var)) {
450 curl_ftp_no_epsv = git_config_bool(var, value);
451 return 0;
453 if (!strcmp("http.proxy", var))
454 return git_config_string(&curl_http_proxy, var, value);
456 if (!strcmp("http.proxyauthmethod", var))
457 return git_config_string(&http_proxy_authmethod, var, value);
459 if (!strcmp("http.proxysslcert", var))
460 return git_config_string(&http_proxy_ssl_cert, var, value);
462 if (!strcmp("http.proxysslkey", var))
463 return git_config_string(&http_proxy_ssl_key, var, value);
465 if (!strcmp("http.proxysslcainfo", var))
466 return git_config_string(&http_proxy_ssl_ca_info, var, value);
468 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
469 proxy_ssl_cert_password_required = git_config_bool(var, value);
470 return 0;
473 if (!strcmp("http.cookiefile", var))
474 return git_config_pathname(&curl_cookie_file, var, value);
475 if (!strcmp("http.savecookies", var)) {
476 curl_save_cookies = git_config_bool(var, value);
477 return 0;
480 if (!strcmp("http.postbuffer", var)) {
481 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
482 if (http_post_buffer < 0)
483 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
484 if (http_post_buffer < LARGE_PACKET_MAX)
485 http_post_buffer = LARGE_PACKET_MAX;
486 return 0;
489 if (!strcmp("http.useragent", var))
490 return git_config_string(&user_agent, var, value);
492 if (!strcmp("http.emptyauth", var)) {
493 if (value && !strcmp("auto", value))
494 curl_empty_auth = -1;
495 else
496 curl_empty_auth = git_config_bool(var, value);
497 return 0;
500 if (!strcmp("http.delegation", var)) {
501 #ifdef CURLGSSAPI_DELEGATION_FLAG
502 return git_config_string(&curl_deleg, var, value);
503 #else
504 warning(_("Delegation control is not supported with cURL < 7.22.0"));
505 return 0;
506 #endif
509 if (!strcmp("http.pinnedpubkey", var)) {
510 return git_config_pathname(&ssl_pinnedkey, var, value);
513 if (!strcmp("http.extraheader", var)) {
514 if (!value) {
515 return config_error_nonbool(var);
516 } else if (!*value) {
517 string_list_clear(&extra_http_headers, 0);
518 } else {
519 string_list_append(&extra_http_headers, value);
521 return 0;
524 if (!strcmp("http.curloptresolve", var)) {
525 if (!value) {
526 return config_error_nonbool(var);
527 } else if (!*value) {
528 curl_slist_free_all(host_resolutions);
529 host_resolutions = NULL;
530 } else {
531 host_resolutions = curl_slist_append(host_resolutions, value);
533 return 0;
536 if (!strcmp("http.followredirects", var)) {
537 if (value && !strcmp(value, "initial"))
538 http_follow_config = HTTP_FOLLOW_INITIAL;
539 else if (git_config_bool(var, value))
540 http_follow_config = HTTP_FOLLOW_ALWAYS;
541 else
542 http_follow_config = HTTP_FOLLOW_NONE;
543 return 0;
546 if (!strcmp("http.proactiveauth", var)) {
547 if (!value)
548 return config_error_nonbool(var);
549 if (!strcmp(value, "auto"))
550 http_proactive_auth = PROACTIVE_AUTH_AUTO;
551 else if (!strcmp(value, "basic"))
552 http_proactive_auth = PROACTIVE_AUTH_BASIC;
553 else if (!strcmp(value, "none"))
554 http_proactive_auth = PROACTIVE_AUTH_NONE;
555 else
556 warning(_("Unknown value for http.proactiveauth"));
557 return 0;
560 /* Fall back on the default ones */
561 return git_default_config(var, value, ctx, data);
564 static int curl_empty_auth_enabled(void)
566 if (curl_empty_auth >= 0)
567 return curl_empty_auth;
570 * In the automatic case, kick in the empty-auth
571 * hack as long as we would potentially try some
572 * method more exotic than "Basic" or "Digest".
574 * But only do this when this is our second or
575 * subsequent request, as by then we know what
576 * methods are available.
578 if (http_auth_methods_restricted &&
579 (http_auth_methods & ~empty_auth_useless))
580 return 1;
581 return 0;
584 struct curl_slist *http_append_auth_header(const struct credential *c,
585 struct curl_slist *headers)
587 if (c->authtype && c->credential) {
588 struct strbuf auth = STRBUF_INIT;
589 strbuf_addf(&auth, "Authorization: %s %s",
590 c->authtype, c->credential);
591 headers = curl_slist_append(headers, auth.buf);
592 strbuf_release(&auth);
594 return headers;
597 static void init_curl_http_auth(CURL *result)
599 if ((!http_auth.username || !*http_auth.username) &&
600 (!http_auth.credential || !*http_auth.credential)) {
601 int empty_auth = curl_empty_auth_enabled();
602 if ((empty_auth != -1 && !always_auth_proactively()) || empty_auth == 1) {
603 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
604 return;
605 } else if (!always_auth_proactively()) {
606 return;
607 } else if (http_proactive_auth == PROACTIVE_AUTH_BASIC) {
608 strvec_push(&http_auth.wwwauth_headers, "Basic");
612 credential_fill(the_repository, &http_auth, 1);
614 if (http_auth.password) {
615 if (always_auth_proactively()) {
617 * We got a credential without an authtype and we don't
618 * know what's available. Since our only two options at
619 * the moment are auto (which defaults to basic) and
620 * basic, use basic for now.
622 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
624 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
625 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
629 /* *var must be free-able */
630 static void var_override(char **var, char *value)
632 if (value) {
633 free(*var);
634 *var = xstrdup(value);
638 static void set_proxyauth_name_password(CURL *result)
640 if (proxy_auth.password) {
641 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
642 proxy_auth.username);
643 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
644 proxy_auth.password);
645 } else if (proxy_auth.authtype && proxy_auth.credential) {
646 curl_easy_setopt(result, CURLOPT_PROXYHEADER,
647 http_append_auth_header(&proxy_auth, NULL));
651 static void init_curl_proxy_auth(CURL *result)
653 if (proxy_auth.username) {
654 if (!proxy_auth.password && !proxy_auth.credential)
655 credential_fill(the_repository, &proxy_auth, 1);
656 set_proxyauth_name_password(result);
659 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
661 if (http_proxy_authmethod) {
662 int i;
663 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
664 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
665 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
666 proxy_authmethods[i].curlauth_param);
667 break;
670 if (i == ARRAY_SIZE(proxy_authmethods)) {
671 warning("unsupported proxy authentication method %s: using anyauth",
672 http_proxy_authmethod);
673 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
676 else
677 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
680 static int has_cert_password(void)
682 if (ssl_cert == NULL || ssl_cert_password_required != 1)
683 return 0;
684 if (!cert_auth.password) {
685 cert_auth.protocol = xstrdup("cert");
686 cert_auth.host = xstrdup("");
687 cert_auth.username = xstrdup("");
688 cert_auth.path = xstrdup(ssl_cert);
689 credential_fill(the_repository, &cert_auth, 0);
691 return 1;
694 static int has_proxy_cert_password(void)
696 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
697 return 0;
698 if (!proxy_cert_auth.password) {
699 proxy_cert_auth.protocol = xstrdup("cert");
700 proxy_cert_auth.host = xstrdup("");
701 proxy_cert_auth.username = xstrdup("");
702 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
703 credential_fill(the_repository, &proxy_cert_auth, 0);
705 return 1;
708 static void set_curl_keepalive(CURL *c)
710 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
713 /* Return 1 if redactions have been made, 0 otherwise. */
714 static int redact_sensitive_header(struct strbuf *header, size_t offset)
716 int ret = 0;
717 const char *sensitive_header;
719 if (trace_curl_redact &&
720 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
721 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
722 /* The first token is the type, which is OK to log */
723 while (isspace(*sensitive_header))
724 sensitive_header++;
725 while (*sensitive_header && !isspace(*sensitive_header))
726 sensitive_header++;
727 /* Everything else is opaque and possibly sensitive */
728 strbuf_setlen(header, sensitive_header - header->buf);
729 strbuf_addstr(header, " <redacted>");
730 ret = 1;
731 } else if (trace_curl_redact &&
732 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
733 struct strbuf redacted_header = STRBUF_INIT;
734 const char *cookie;
736 while (isspace(*sensitive_header))
737 sensitive_header++;
739 cookie = sensitive_header;
741 while (cookie) {
742 char *equals;
743 char *semicolon = strstr(cookie, "; ");
744 if (semicolon)
745 *semicolon = 0;
746 equals = strchrnul(cookie, '=');
747 if (!equals) {
748 /* invalid cookie, just append and continue */
749 strbuf_addstr(&redacted_header, cookie);
750 continue;
752 strbuf_add(&redacted_header, cookie, equals - cookie);
753 strbuf_addstr(&redacted_header, "=<redacted>");
754 if (semicolon) {
756 * There are more cookies. (Or, for some
757 * reason, the input string ends in "; ".)
759 strbuf_addstr(&redacted_header, "; ");
760 cookie = semicolon + strlen("; ");
761 } else {
762 cookie = NULL;
766 strbuf_setlen(header, sensitive_header - header->buf);
767 strbuf_addbuf(header, &redacted_header);
768 strbuf_release(&redacted_header);
769 ret = 1;
771 return ret;
774 static int match_curl_h2_trace(const char *line, const char **out)
776 const char *p;
779 * curl prior to 8.1.0 gives us:
781 * h2h3 [<header-name>: <header-val>]
783 * Starting in 8.1.0, the first token became just "h2".
785 if (skip_iprefix(line, "h2h3 [", out) ||
786 skip_iprefix(line, "h2 [", out))
787 return 1;
790 * curl 8.3.0 uses:
791 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
792 * where <stream-id> is numeric.
794 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
795 while (isdigit(*p))
796 p++;
797 if (skip_prefix(p, "] [", out))
798 return 1;
801 return 0;
804 /* Redact headers in info */
805 static void redact_sensitive_info_header(struct strbuf *header)
807 const char *sensitive_header;
809 if (trace_curl_redact &&
810 match_curl_h2_trace(header->buf, &sensitive_header)) {
811 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
812 /* redaction ate our closing bracket */
813 strbuf_addch(header, ']');
818 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
820 struct strbuf out = STRBUF_INIT;
821 struct strbuf **headers, **header;
823 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
824 text, (long)size, (long)size);
825 trace_strbuf(&trace_curl, &out);
826 strbuf_reset(&out);
827 strbuf_add(&out, ptr, size);
828 headers = strbuf_split_max(&out, '\n', 0);
830 for (header = headers; *header; header++) {
831 if (hide_sensitive_header)
832 redact_sensitive_header(*header, 0);
833 strbuf_insertstr((*header), 0, text);
834 strbuf_insertstr((*header), strlen(text), ": ");
835 strbuf_rtrim((*header));
836 strbuf_addch((*header), '\n');
837 trace_strbuf(&trace_curl, (*header));
839 strbuf_list_free(headers);
840 strbuf_release(&out);
843 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
845 size_t i;
846 struct strbuf out = STRBUF_INIT;
847 unsigned int width = 60;
849 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
850 text, (long)size, (long)size);
851 trace_strbuf(&trace_curl, &out);
853 for (i = 0; i < size; i += width) {
854 size_t w;
856 strbuf_reset(&out);
857 strbuf_addf(&out, "%s: ", text);
858 for (w = 0; (w < width) && (i + w < size); w++) {
859 unsigned char ch = ptr[i + w];
861 strbuf_addch(&out,
862 (ch >= 0x20) && (ch < 0x80)
863 ? ch : '.');
865 strbuf_addch(&out, '\n');
866 trace_strbuf(&trace_curl, &out);
868 strbuf_release(&out);
871 static void curl_dump_info(char *data, size_t size)
873 struct strbuf buf = STRBUF_INIT;
875 strbuf_add(&buf, data, size);
877 redact_sensitive_info_header(&buf);
878 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
880 strbuf_release(&buf);
883 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
884 char *data, size_t size,
885 void *userp UNUSED)
887 const char *text;
888 enum { NO_FILTER = 0, DO_FILTER = 1 };
890 switch (type) {
891 case CURLINFO_TEXT:
892 curl_dump_info(data, size);
893 break;
894 case CURLINFO_HEADER_OUT:
895 text = "=> Send header";
896 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
897 break;
898 case CURLINFO_DATA_OUT:
899 if (trace_curl_data) {
900 text = "=> Send data";
901 curl_dump_data(text, (unsigned char *)data, size);
903 break;
904 case CURLINFO_SSL_DATA_OUT:
905 if (trace_curl_data) {
906 text = "=> Send SSL data";
907 curl_dump_data(text, (unsigned char *)data, size);
909 break;
910 case CURLINFO_HEADER_IN:
911 text = "<= Recv header";
912 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
913 break;
914 case CURLINFO_DATA_IN:
915 if (trace_curl_data) {
916 text = "<= Recv data";
917 curl_dump_data(text, (unsigned char *)data, size);
919 break;
920 case CURLINFO_SSL_DATA_IN:
921 if (trace_curl_data) {
922 text = "<= Recv SSL data";
923 curl_dump_data(text, (unsigned char *)data, size);
925 break;
927 default: /* we ignore unknown types by default */
928 return 0;
930 return 0;
933 void http_trace_curl_no_data(void)
935 trace_override_envvar(&trace_curl, "1");
936 trace_curl_data = 0;
939 void setup_curl_trace(CURL *handle)
941 if (!trace_want(&trace_curl))
942 return;
943 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
944 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
945 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
948 static void proto_list_append(struct strbuf *list, const char *proto)
950 if (!list)
951 return;
952 if (list->len)
953 strbuf_addch(list, ',');
954 strbuf_addstr(list, proto);
957 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
959 long bits = 0;
961 if (is_transport_allowed("http", from_user)) {
962 bits |= CURLPROTO_HTTP;
963 proto_list_append(list, "http");
965 if (is_transport_allowed("https", from_user)) {
966 bits |= CURLPROTO_HTTPS;
967 proto_list_append(list, "https");
969 if (is_transport_allowed("ftp", from_user)) {
970 bits |= CURLPROTO_FTP;
971 proto_list_append(list, "ftp");
973 if (is_transport_allowed("ftps", from_user)) {
974 bits |= CURLPROTO_FTPS;
975 proto_list_append(list, "ftps");
978 return bits;
981 static int get_curl_http_version_opt(const char *version_string, long *opt)
983 int i;
984 static struct {
985 const char *name;
986 long opt_token;
987 } choice[] = {
988 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
989 { "HTTP/2", CURL_HTTP_VERSION_2 }
992 for (i = 0; i < ARRAY_SIZE(choice); i++) {
993 if (!strcmp(version_string, choice[i].name)) {
994 *opt = choice[i].opt_token;
995 return 0;
999 warning("unknown value given to http.version: '%s'", version_string);
1000 return -1; /* not found */
1003 static CURL *get_curl_handle(void)
1005 CURL *result = curl_easy_init();
1007 if (!result)
1008 die("curl_easy_init failed");
1010 if (!curl_ssl_verify) {
1011 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
1012 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
1013 } else {
1014 /* Verify authenticity of the peer's certificate */
1015 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
1016 /* The name in the cert must match whom we tried to connect */
1017 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
1020 if (curl_http_version) {
1021 long opt;
1022 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
1023 /* Set request use http version */
1024 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
1028 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
1029 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1031 #ifdef CURLGSSAPI_DELEGATION_FLAG
1032 if (curl_deleg) {
1033 int i;
1034 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1035 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1036 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1037 curl_deleg_levels[i].curl_deleg_param);
1038 break;
1041 if (i == ARRAY_SIZE(curl_deleg_levels))
1042 warning("Unknown delegation method '%s': using default",
1043 curl_deleg);
1045 #endif
1047 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1048 !http_schannel_check_revoke) {
1049 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1052 if (http_proactive_auth != PROACTIVE_AUTH_NONE)
1053 init_curl_http_auth(result);
1055 if (getenv("GIT_SSL_VERSION"))
1056 ssl_version = getenv("GIT_SSL_VERSION");
1057 if (ssl_version && *ssl_version) {
1058 int i;
1059 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1060 if (!strcmp(ssl_version, sslversions[i].name)) {
1061 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1062 sslversions[i].ssl_version);
1063 break;
1066 if (i == ARRAY_SIZE(sslversions))
1067 warning("unsupported ssl version %s: using default",
1068 ssl_version);
1071 if (getenv("GIT_SSL_CIPHER_LIST"))
1072 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1073 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1074 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1075 ssl_cipherlist);
1077 if (ssl_cert)
1078 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1079 if (ssl_cert_type)
1080 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1081 if (has_cert_password())
1082 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1083 if (ssl_key)
1084 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1085 if (ssl_key_type)
1086 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1087 if (ssl_capath)
1088 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1089 if (ssl_pinnedkey)
1090 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1091 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1092 !http_schannel_use_ssl_cainfo) {
1093 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1094 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1095 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1096 if (ssl_cainfo)
1097 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1098 if (http_proxy_ssl_ca_info)
1099 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1102 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1103 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1104 curl_low_speed_limit);
1105 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1106 curl_low_speed_time);
1109 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1110 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1112 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1114 struct strbuf buf = STRBUF_INIT;
1116 get_curl_allowed_protocols(0, &buf);
1117 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1118 strbuf_reset(&buf);
1120 get_curl_allowed_protocols(-1, &buf);
1121 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1122 strbuf_release(&buf);
1124 #else
1125 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1126 get_curl_allowed_protocols(0, NULL));
1127 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1128 get_curl_allowed_protocols(-1, NULL));
1129 #endif
1131 if (getenv("GIT_CURL_VERBOSE"))
1132 http_trace_curl_no_data();
1133 setup_curl_trace(result);
1134 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1135 trace_curl_data = 0;
1136 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1137 trace_curl_redact = 0;
1139 curl_easy_setopt(result, CURLOPT_USERAGENT,
1140 user_agent ? user_agent : git_user_agent());
1142 if (curl_ftp_no_epsv)
1143 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1145 if (curl_ssl_try)
1146 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1149 * CURL also examines these variables as a fallback; but we need to query
1150 * them here in order to decide whether to prompt for missing password (cf.
1151 * init_curl_proxy_auth()).
1153 * Unlike many other common environment variables, these are historically
1154 * lowercase only. It appears that CURL did not know this and implemented
1155 * only uppercase variants, which was later corrected to take both - with
1156 * the exception of http_proxy, which is lowercase only also in CURL. As
1157 * the lowercase versions are the historical quasi-standard, they take
1158 * precedence here, as in CURL.
1160 if (!curl_http_proxy) {
1161 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1162 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1163 var_override(&curl_http_proxy, getenv("https_proxy"));
1164 } else {
1165 var_override(&curl_http_proxy, getenv("http_proxy"));
1167 if (!curl_http_proxy) {
1168 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1169 var_override(&curl_http_proxy, getenv("all_proxy"));
1173 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1175 * Handle case with the empty http.proxy value here to keep
1176 * common code clean.
1177 * NB: empty option disables proxying at all.
1179 curl_easy_setopt(result, CURLOPT_PROXY, "");
1180 } else if (curl_http_proxy) {
1181 struct strbuf proxy = STRBUF_INIT;
1183 if (starts_with(curl_http_proxy, "socks5h"))
1184 curl_easy_setopt(result,
1185 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1186 else if (starts_with(curl_http_proxy, "socks5"))
1187 curl_easy_setopt(result,
1188 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1189 else if (starts_with(curl_http_proxy, "socks4a"))
1190 curl_easy_setopt(result,
1191 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1192 else if (starts_with(curl_http_proxy, "socks"))
1193 curl_easy_setopt(result,
1194 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1195 else if (starts_with(curl_http_proxy, "https")) {
1196 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1198 if (http_proxy_ssl_cert)
1199 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1201 if (http_proxy_ssl_key)
1202 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1204 if (has_proxy_cert_password())
1205 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1207 if (strstr(curl_http_proxy, "://"))
1208 credential_from_url(&proxy_auth, curl_http_proxy);
1209 else {
1210 struct strbuf url = STRBUF_INIT;
1211 strbuf_addf(&url, "http://%s", curl_http_proxy);
1212 credential_from_url(&proxy_auth, url.buf);
1213 strbuf_release(&url);
1216 if (!proxy_auth.host)
1217 die("Invalid proxy URL '%s'", curl_http_proxy);
1219 strbuf_addstr(&proxy, proxy_auth.host);
1220 if (proxy_auth.path) {
1221 curl_version_info_data *ver = curl_version_info(CURLVERSION_NOW);
1223 if (ver->version_num < 0x075400)
1224 die("libcurl 7.84 or later is required to support paths in proxy URLs");
1226 if (!starts_with(proxy_auth.protocol, "socks"))
1227 die("Invalid proxy URL '%s': only SOCKS proxies support paths",
1228 curl_http_proxy);
1230 if (strcasecmp(proxy_auth.host, "localhost"))
1231 die("Invalid proxy URL '%s': host must be localhost if a path is present",
1232 curl_http_proxy);
1234 strbuf_addch(&proxy, '/');
1235 strbuf_add_percentencode(&proxy, proxy_auth.path, 0);
1237 curl_easy_setopt(result, CURLOPT_PROXY, proxy.buf);
1238 strbuf_release(&proxy);
1240 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1241 var_override(&curl_no_proxy, getenv("no_proxy"));
1242 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1244 init_curl_proxy_auth(result);
1246 set_curl_keepalive(result);
1248 return result;
1251 static void set_from_env(char **var, const char *envname)
1253 const char *val = getenv(envname);
1254 if (val) {
1255 FREE_AND_NULL(*var);
1256 *var = xstrdup(val);
1260 void http_init(struct remote *remote, const char *url, int proactive_auth)
1262 char *low_speed_limit;
1263 char *low_speed_time;
1264 char *normalized_url;
1265 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1267 config.section = "http";
1268 config.key = NULL;
1269 config.collect_fn = http_options;
1270 config.cascade_fn = git_default_config;
1271 config.cb = NULL;
1273 http_is_verbose = 0;
1274 normalized_url = url_normalize(url, &config.url);
1276 git_config(urlmatch_config_entry, &config);
1277 free(normalized_url);
1278 string_list_clear(&config.vars, 1);
1280 if (http_ssl_backend) {
1281 const curl_ssl_backend **backends;
1282 struct strbuf buf = STRBUF_INIT;
1283 int i;
1285 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1286 case CURLSSLSET_UNKNOWN_BACKEND:
1287 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1288 "Supported SSL backends:"),
1289 http_ssl_backend);
1290 for (i = 0; backends[i]; i++)
1291 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1292 die("%s", buf.buf);
1293 case CURLSSLSET_NO_BACKENDS:
1294 die(_("Could not set SSL backend to '%s': "
1295 "cURL was built without SSL backends"),
1296 http_ssl_backend);
1297 case CURLSSLSET_TOO_LATE:
1298 die(_("Could not set SSL backend to '%s': already set"),
1299 http_ssl_backend);
1300 case CURLSSLSET_OK:
1301 break; /* Okay! */
1305 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1306 die("curl_global_init failed");
1308 if (proactive_auth && http_proactive_auth == PROACTIVE_AUTH_NONE)
1309 http_proactive_auth = PROACTIVE_AUTH_IF_CREDENTIALS;
1311 if (remote && remote->http_proxy)
1312 curl_http_proxy = xstrdup(remote->http_proxy);
1314 if (remote)
1315 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1317 pragma_header = curl_slist_append(http_copy_default_headers(),
1318 "Pragma: no-cache");
1321 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1322 if (http_max_requests)
1323 max_requests = atoi(http_max_requests);
1326 curlm = curl_multi_init();
1327 if (!curlm)
1328 die("curl_multi_init failed");
1330 if (getenv("GIT_SSL_NO_VERIFY"))
1331 curl_ssl_verify = 0;
1333 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1334 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1335 set_from_env(&ssl_key, "GIT_SSL_KEY");
1336 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1337 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1338 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1340 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1342 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1343 if (low_speed_limit)
1344 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1345 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1346 if (low_speed_time)
1347 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1349 if (curl_ssl_verify == -1)
1350 curl_ssl_verify = 1;
1352 curl_session_count = 0;
1353 if (max_requests < 1)
1354 max_requests = DEFAULT_MAX_REQUESTS;
1356 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1357 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1358 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1360 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1361 proxy_ssl_cert_password_required = 1;
1363 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1364 curl_ftp_no_epsv = 1;
1366 if (url) {
1367 credential_from_url(&http_auth, url);
1368 if (!ssl_cert_password_required &&
1369 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1370 starts_with(url, "https://"))
1371 ssl_cert_password_required = 1;
1374 curl_default = get_curl_handle();
1377 void http_cleanup(void)
1379 struct active_request_slot *slot = active_queue_head;
1381 while (slot != NULL) {
1382 struct active_request_slot *next = slot->next;
1383 if (slot->curl) {
1384 xmulti_remove_handle(slot);
1385 curl_easy_cleanup(slot->curl);
1387 free(slot);
1388 slot = next;
1390 active_queue_head = NULL;
1392 curl_easy_cleanup(curl_default);
1394 curl_multi_cleanup(curlm);
1395 curl_global_cleanup();
1397 string_list_clear(&extra_http_headers, 0);
1399 curl_slist_free_all(pragma_header);
1400 pragma_header = NULL;
1402 curl_slist_free_all(host_resolutions);
1403 host_resolutions = NULL;
1405 if (curl_http_proxy) {
1406 free((void *)curl_http_proxy);
1407 curl_http_proxy = NULL;
1410 if (proxy_auth.password) {
1411 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1412 FREE_AND_NULL(proxy_auth.password);
1415 free((void *)curl_proxyuserpwd);
1416 curl_proxyuserpwd = NULL;
1418 free((void *)http_proxy_authmethod);
1419 http_proxy_authmethod = NULL;
1421 if (cert_auth.password) {
1422 memset(cert_auth.password, 0, strlen(cert_auth.password));
1423 FREE_AND_NULL(cert_auth.password);
1425 ssl_cert_password_required = 0;
1427 if (proxy_cert_auth.password) {
1428 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1429 FREE_AND_NULL(proxy_cert_auth.password);
1431 proxy_ssl_cert_password_required = 0;
1433 FREE_AND_NULL(cached_accept_language);
1436 struct active_request_slot *get_active_slot(void)
1438 struct active_request_slot *slot = active_queue_head;
1439 struct active_request_slot *newslot;
1441 int num_transfers;
1443 /* Wait for a slot to open up if the queue is full */
1444 while (active_requests >= max_requests) {
1445 curl_multi_perform(curlm, &num_transfers);
1446 if (num_transfers < active_requests)
1447 process_curl_messages();
1450 while (slot != NULL && slot->in_use)
1451 slot = slot->next;
1453 if (!slot) {
1454 newslot = xmalloc(sizeof(*newslot));
1455 newslot->curl = NULL;
1456 newslot->in_use = 0;
1457 newslot->next = NULL;
1459 slot = active_queue_head;
1460 if (!slot) {
1461 active_queue_head = newslot;
1462 } else {
1463 while (slot->next != NULL)
1464 slot = slot->next;
1465 slot->next = newslot;
1467 slot = newslot;
1470 if (!slot->curl) {
1471 slot->curl = curl_easy_duphandle(curl_default);
1472 curl_session_count++;
1475 active_requests++;
1476 slot->in_use = 1;
1477 slot->results = NULL;
1478 slot->finished = NULL;
1479 slot->callback_data = NULL;
1480 slot->callback_func = NULL;
1482 if (curl_cookie_file && !strcmp(curl_cookie_file, "-")) {
1483 warning(_("refusing to read cookies from http.cookiefile '-'"));
1484 FREE_AND_NULL(curl_cookie_file);
1486 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1487 if (curl_save_cookies && (!curl_cookie_file || !curl_cookie_file[0])) {
1488 curl_save_cookies = 0;
1489 warning(_("ignoring http.savecookies for empty http.cookiefile"));
1491 if (curl_save_cookies)
1492 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1493 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1494 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1495 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1496 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1497 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1498 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1499 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1500 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, -1L);
1501 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1502 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1503 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1504 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1507 * Default following to off unless "ALWAYS" is configured; this gives
1508 * callers a sane starting point, and they can tweak for individual
1509 * HTTP_FOLLOW_* cases themselves.
1511 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1512 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1513 else
1514 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1516 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1517 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1518 if (http_auth.password || http_auth.credential || curl_empty_auth_enabled())
1519 init_curl_http_auth(slot->curl);
1521 return slot;
1524 int start_active_slot(struct active_request_slot *slot)
1526 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1527 int num_transfers;
1529 if (curlm_result != CURLM_OK &&
1530 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1531 warning("curl_multi_add_handle failed: %s",
1532 curl_multi_strerror(curlm_result));
1533 active_requests--;
1534 slot->in_use = 0;
1535 return 0;
1539 * We know there must be something to do, since we just added
1540 * something.
1542 curl_multi_perform(curlm, &num_transfers);
1543 return 1;
1546 struct fill_chain {
1547 void *data;
1548 int (*fill)(void *);
1549 struct fill_chain *next;
1552 static struct fill_chain *fill_cfg;
1554 void add_fill_function(void *data, int (*fill)(void *))
1556 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1557 struct fill_chain **linkp = &fill_cfg;
1558 new_fill->data = data;
1559 new_fill->fill = fill;
1560 new_fill->next = NULL;
1561 while (*linkp)
1562 linkp = &(*linkp)->next;
1563 *linkp = new_fill;
1566 void fill_active_slots(void)
1568 struct active_request_slot *slot = active_queue_head;
1570 while (active_requests < max_requests) {
1571 struct fill_chain *fill;
1572 for (fill = fill_cfg; fill; fill = fill->next)
1573 if (fill->fill(fill->data))
1574 break;
1576 if (!fill)
1577 break;
1580 while (slot != NULL) {
1581 if (!slot->in_use && slot->curl != NULL
1582 && curl_session_count > min_curl_sessions) {
1583 curl_easy_cleanup(slot->curl);
1584 slot->curl = NULL;
1585 curl_session_count--;
1587 slot = slot->next;
1591 void step_active_slots(void)
1593 int num_transfers;
1594 CURLMcode curlm_result;
1596 do {
1597 curlm_result = curl_multi_perform(curlm, &num_transfers);
1598 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1599 if (num_transfers < active_requests) {
1600 process_curl_messages();
1601 fill_active_slots();
1605 void run_active_slot(struct active_request_slot *slot)
1607 fd_set readfds;
1608 fd_set writefds;
1609 fd_set excfds;
1610 int max_fd;
1611 struct timeval select_timeout;
1612 int finished = 0;
1614 slot->finished = &finished;
1615 while (!finished) {
1616 step_active_slots();
1618 if (slot->in_use) {
1619 long curl_timeout;
1620 curl_multi_timeout(curlm, &curl_timeout);
1621 if (curl_timeout == 0) {
1622 continue;
1623 } else if (curl_timeout == -1) {
1624 select_timeout.tv_sec = 0;
1625 select_timeout.tv_usec = 50000;
1626 } else {
1627 select_timeout.tv_sec = curl_timeout / 1000;
1628 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1631 max_fd = -1;
1632 FD_ZERO(&readfds);
1633 FD_ZERO(&writefds);
1634 FD_ZERO(&excfds);
1635 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1638 * It can happen that curl_multi_timeout returns a pathologically
1639 * long timeout when curl_multi_fdset returns no file descriptors
1640 * to read. See commit message for more details.
1642 if (max_fd < 0 &&
1643 (select_timeout.tv_sec > 0 ||
1644 select_timeout.tv_usec > 50000)) {
1645 select_timeout.tv_sec = 0;
1646 select_timeout.tv_usec = 50000;
1649 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1654 * The value of slot->finished we set before the loop was used
1655 * to set our "finished" variable when our request completed.
1657 * 1. The slot may not have been reused for another request
1658 * yet, in which case it still has &finished.
1660 * 2. The slot may already be in-use to serve another request,
1661 * which can further be divided into two cases:
1663 * (a) If call run_active_slot() hasn't been called for that
1664 * other request, slot->finished would have been cleared
1665 * by get_active_slot() and has NULL.
1667 * (b) If the request did call run_active_slot(), then the
1668 * call would have updated slot->finished at the beginning
1669 * of this function, and with the clearing of the member
1670 * below, we would find that slot->finished is now NULL.
1672 * In all cases, slot->finished has no useful information to
1673 * anybody at this point. Some compilers warn us for
1674 * attempting to smuggle a pointer that is about to become
1675 * invalid, i.e. &finished. We clear it here to assure them.
1677 slot->finished = NULL;
1680 static void release_active_slot(struct active_request_slot *slot)
1682 closedown_active_slot(slot);
1683 if (slot->curl) {
1684 xmulti_remove_handle(slot);
1685 if (curl_session_count > min_curl_sessions) {
1686 curl_easy_cleanup(slot->curl);
1687 slot->curl = NULL;
1688 curl_session_count--;
1691 fill_active_slots();
1694 void finish_all_active_slots(void)
1696 struct active_request_slot *slot = active_queue_head;
1698 while (slot != NULL)
1699 if (slot->in_use) {
1700 run_active_slot(slot);
1701 slot = active_queue_head;
1702 } else {
1703 slot = slot->next;
1707 /* Helpers for modifying and creating URLs */
1708 static inline int needs_quote(int ch)
1710 if (((ch >= 'A') && (ch <= 'Z'))
1711 || ((ch >= 'a') && (ch <= 'z'))
1712 || ((ch >= '0') && (ch <= '9'))
1713 || (ch == '/')
1714 || (ch == '-')
1715 || (ch == '.'))
1716 return 0;
1717 return 1;
1720 static char *quote_ref_url(const char *base, const char *ref)
1722 struct strbuf buf = STRBUF_INIT;
1723 const char *cp;
1724 int ch;
1726 end_url_with_slash(&buf, base);
1728 for (cp = ref; (ch = *cp) != 0; cp++)
1729 if (needs_quote(ch))
1730 strbuf_addf(&buf, "%%%02x", ch);
1731 else
1732 strbuf_addch(&buf, *cp);
1734 return strbuf_detach(&buf, NULL);
1737 void append_remote_object_url(struct strbuf *buf, const char *url,
1738 const char *hex,
1739 int only_two_digit_prefix)
1741 end_url_with_slash(buf, url);
1743 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1744 if (!only_two_digit_prefix)
1745 strbuf_addstr(buf, hex + 2);
1748 char *get_remote_object_url(const char *url, const char *hex,
1749 int only_two_digit_prefix)
1751 struct strbuf buf = STRBUF_INIT;
1752 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1753 return strbuf_detach(&buf, NULL);
1756 void normalize_curl_result(CURLcode *result, long http_code,
1757 char *errorstr, size_t errorlen)
1760 * If we see a failing http code with CURLE_OK, we have turned off
1761 * FAILONERROR (to keep the server's custom error response), and should
1762 * translate the code into failure here.
1764 * Likewise, if we see a redirect (30x code), that means we turned off
1765 * redirect-following, and we should treat the result as an error.
1767 if (*result == CURLE_OK && http_code >= 300) {
1768 *result = CURLE_HTTP_RETURNED_ERROR;
1770 * Normally curl will already have put the "reason phrase"
1771 * from the server into curl_errorstr; unfortunately without
1772 * FAILONERROR it is lost, so we can give only the numeric
1773 * status code.
1775 xsnprintf(errorstr, errorlen,
1776 "The requested URL returned error: %ld",
1777 http_code);
1781 static int handle_curl_result(struct slot_results *results)
1783 normalize_curl_result(&results->curl_result, results->http_code,
1784 curl_errorstr, sizeof(curl_errorstr));
1786 if (results->curl_result == CURLE_OK) {
1787 credential_approve(the_repository, &http_auth);
1788 credential_approve(the_repository, &proxy_auth);
1789 credential_approve(the_repository, &cert_auth);
1790 return HTTP_OK;
1791 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1793 * We can't tell from here whether it's a bad path, bad
1794 * certificate, bad password, or something else wrong
1795 * with the certificate. So we reject the credential to
1796 * avoid caching or saving a bad password.
1798 credential_reject(the_repository, &cert_auth);
1799 return HTTP_NOAUTH;
1800 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1801 return HTTP_NOMATCHPUBLICKEY;
1802 } else if (missing_target(results))
1803 return HTTP_MISSING_TARGET;
1804 else if (results->http_code == 401) {
1805 if ((http_auth.username && http_auth.password) ||\
1806 (http_auth.authtype && http_auth.credential)) {
1807 if (http_auth.multistage) {
1808 credential_clear_secrets(&http_auth);
1809 return HTTP_REAUTH;
1811 credential_reject(the_repository, &http_auth);
1812 if (always_auth_proactively())
1813 http_proactive_auth = PROACTIVE_AUTH_NONE;
1814 return HTTP_NOAUTH;
1815 } else {
1816 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1817 if (results->auth_avail) {
1818 http_auth_methods &= results->auth_avail;
1819 http_auth_methods_restricted = 1;
1821 return HTTP_REAUTH;
1823 } else {
1824 if (results->http_connectcode == 407)
1825 credential_reject(the_repository, &proxy_auth);
1826 if (!curl_errorstr[0])
1827 strlcpy(curl_errorstr,
1828 curl_easy_strerror(results->curl_result),
1829 sizeof(curl_errorstr));
1830 return HTTP_ERROR;
1834 int run_one_slot(struct active_request_slot *slot,
1835 struct slot_results *results)
1837 slot->results = results;
1838 if (!start_active_slot(slot)) {
1839 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1840 "failed to start HTTP request");
1841 return HTTP_START_FAILED;
1844 run_active_slot(slot);
1845 return handle_curl_result(results);
1848 struct curl_slist *http_copy_default_headers(void)
1850 struct curl_slist *headers = NULL;
1851 const struct string_list_item *item;
1853 for_each_string_list_item(item, &extra_http_headers)
1854 headers = curl_slist_append(headers, item->string);
1856 return headers;
1859 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1861 char *ptr;
1862 CURLcode ret;
1864 strbuf_reset(buf);
1865 ret = curl_easy_getinfo(curl, info, &ptr);
1866 if (!ret && ptr)
1867 strbuf_addstr(buf, ptr);
1868 return ret;
1872 * Check for and extract a content-type parameter. "raw"
1873 * should be positioned at the start of the potential
1874 * parameter, with any whitespace already removed.
1876 * "name" is the name of the parameter. The value is appended
1877 * to "out".
1879 static int extract_param(const char *raw, const char *name,
1880 struct strbuf *out)
1882 size_t len = strlen(name);
1884 if (strncasecmp(raw, name, len))
1885 return -1;
1886 raw += len;
1888 if (*raw != '=')
1889 return -1;
1890 raw++;
1892 while (*raw && !isspace(*raw) && *raw != ';')
1893 strbuf_addch(out, *raw++);
1894 return 0;
1898 * Extract a normalized version of the content type, with any
1899 * spaces suppressed, all letters lowercased, and no trailing ";"
1900 * or parameters.
1902 * Note that we will silently remove even invalid whitespace. For
1903 * example, "text / plain" is specifically forbidden by RFC 2616,
1904 * but "text/plain" is the only reasonable output, and this keeps
1905 * our code simple.
1907 * If the "charset" argument is not NULL, store the value of any
1908 * charset parameter there.
1910 * Example:
1911 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1912 * "text / plain" -> "text/plain"
1914 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1915 struct strbuf *charset)
1917 const char *p;
1919 strbuf_reset(type);
1920 strbuf_grow(type, raw->len);
1921 for (p = raw->buf; *p; p++) {
1922 if (isspace(*p))
1923 continue;
1924 if (*p == ';') {
1925 p++;
1926 break;
1928 strbuf_addch(type, tolower(*p));
1931 if (!charset)
1932 return;
1934 strbuf_reset(charset);
1935 while (*p) {
1936 while (isspace(*p) || *p == ';')
1937 p++;
1938 if (!extract_param(p, "charset", charset))
1939 return;
1940 while (*p && !isspace(*p))
1941 p++;
1944 if (!charset->len && starts_with(type->buf, "text/"))
1945 strbuf_addstr(charset, "ISO-8859-1");
1948 static void write_accept_language(struct strbuf *buf)
1951 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1952 * that, q-value will be smaller than 0.001, the minimum q-value the
1953 * HTTP specification allows. See
1954 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
1956 const int MAX_DECIMAL_PLACES = 3;
1957 const int MAX_LANGUAGE_TAGS = 1000;
1958 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1959 char **language_tags = NULL;
1960 int num_langs = 0;
1961 const char *s = get_preferred_languages();
1962 int i;
1963 struct strbuf tag = STRBUF_INIT;
1965 /* Don't add Accept-Language header if no language is preferred. */
1966 if (!s)
1967 return;
1970 * Split the colon-separated string of preferred languages into
1971 * language_tags array.
1973 do {
1974 /* collect language tag */
1975 for (; *s && (isalnum(*s) || *s == '_'); s++)
1976 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1978 /* skip .codeset, @modifier and any other unnecessary parts */
1979 while (*s && *s != ':')
1980 s++;
1982 if (tag.len) {
1983 num_langs++;
1984 REALLOC_ARRAY(language_tags, num_langs);
1985 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1986 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1987 break;
1989 } while (*s++);
1991 /* write Accept-Language header into buf */
1992 if (num_langs) {
1993 int last_buf_len = 0;
1994 int max_q;
1995 int decimal_places;
1996 char q_format[32];
1998 /* add '*' */
1999 REALLOC_ARRAY(language_tags, num_langs + 1);
2000 language_tags[num_langs++] = xstrdup("*");
2002 /* compute decimal_places */
2003 for (max_q = 1, decimal_places = 0;
2004 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
2005 decimal_places++, max_q *= 10)
2008 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
2010 strbuf_addstr(buf, "Accept-Language: ");
2012 for (i = 0; i < num_langs; i++) {
2013 if (i > 0)
2014 strbuf_addstr(buf, ", ");
2016 strbuf_addstr(buf, language_tags[i]);
2018 if (i > 0)
2019 strbuf_addf(buf, q_format, max_q - i);
2021 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
2022 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
2023 break;
2026 last_buf_len = buf->len;
2030 for (i = 0; i < num_langs; i++)
2031 free(language_tags[i]);
2032 free(language_tags);
2036 * Get an Accept-Language header which indicates user's preferred languages.
2038 * Examples:
2039 * LANGUAGE= -> ""
2040 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
2041 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
2042 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
2043 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
2044 * LANGUAGE= LANG=C -> ""
2046 const char *http_get_accept_language_header(void)
2048 if (!cached_accept_language) {
2049 struct strbuf buf = STRBUF_INIT;
2050 write_accept_language(&buf);
2051 if (buf.len > 0)
2052 cached_accept_language = strbuf_detach(&buf, NULL);
2055 return cached_accept_language;
2058 static void http_opt_request_remainder(CURL *curl, off_t pos)
2060 char buf[128];
2061 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2062 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2065 /* http_request() targets */
2066 #define HTTP_REQUEST_STRBUF 0
2067 #define HTTP_REQUEST_FILE 1
2069 static int http_request(const char *url,
2070 void *result, int target,
2071 const struct http_get_options *options)
2073 struct active_request_slot *slot;
2074 struct slot_results results;
2075 struct curl_slist *headers = http_copy_default_headers();
2076 struct strbuf buf = STRBUF_INIT;
2077 const char *accept_language;
2078 int ret;
2080 slot = get_active_slot();
2081 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2083 if (!result) {
2084 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2085 } else {
2086 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2087 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2089 if (target == HTTP_REQUEST_FILE) {
2090 off_t posn = ftello(result);
2091 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2092 fwrite);
2093 if (posn > 0)
2094 http_opt_request_remainder(slot->curl, posn);
2095 } else
2096 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2097 fwrite_buffer);
2100 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2102 accept_language = http_get_accept_language_header();
2104 if (accept_language)
2105 headers = curl_slist_append(headers, accept_language);
2107 strbuf_addstr(&buf, "Pragma:");
2108 if (options && options->no_cache)
2109 strbuf_addstr(&buf, " no-cache");
2110 if (options && options->initial_request &&
2111 http_follow_config == HTTP_FOLLOW_INITIAL)
2112 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2114 headers = curl_slist_append(headers, buf.buf);
2116 /* Add additional headers here */
2117 if (options && options->extra_headers) {
2118 const struct string_list_item *item;
2119 if (options && options->extra_headers) {
2120 for_each_string_list_item(item, options->extra_headers) {
2121 headers = curl_slist_append(headers, item->string);
2126 headers = http_append_auth_header(&http_auth, headers);
2128 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2129 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2130 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2131 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2133 ret = run_one_slot(slot, &results);
2135 if (options && options->content_type) {
2136 struct strbuf raw = STRBUF_INIT;
2137 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2138 extract_content_type(&raw, options->content_type,
2139 options->charset);
2140 strbuf_release(&raw);
2143 if (options && options->effective_url)
2144 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2145 options->effective_url);
2147 curl_slist_free_all(headers);
2148 strbuf_release(&buf);
2150 return ret;
2154 * Update the "base" url to a more appropriate value, as deduced by
2155 * redirects seen when requesting a URL starting with "url".
2157 * The "asked" parameter is a URL that we asked curl to access, and must begin
2158 * with "base".
2160 * The "got" parameter is the URL that curl reported to us as where we ended
2161 * up.
2163 * Returns 1 if we updated the base url, 0 otherwise.
2165 * Our basic strategy is to compare "base" and "asked" to find the bits
2166 * specific to our request. We then strip those bits off of "got" to yield the
2167 * new base. So for example, if our base is "http://example.com/foo.git",
2168 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2169 * with "https://other.example.com/foo.git/info/refs". We would want the
2170 * new URL to become "https://other.example.com/foo.git".
2172 * Note that this assumes a sane redirect scheme. It's entirely possible
2173 * in the example above to end up at a URL that does not even end in
2174 * "info/refs". In such a case we die. There's not much we can do, such a
2175 * scheme is unlikely to represent a real git repository, and failing to
2176 * rewrite the base opens options for malicious redirects to do funny things.
2178 static int update_url_from_redirect(struct strbuf *base,
2179 const char *asked,
2180 const struct strbuf *got)
2182 const char *tail;
2183 size_t new_len;
2185 if (!strcmp(asked, got->buf))
2186 return 0;
2188 if (!skip_prefix(asked, base->buf, &tail))
2189 BUG("update_url_from_redirect: %s is not a superset of %s",
2190 asked, base->buf);
2192 new_len = got->len;
2193 if (!strip_suffix_mem(got->buf, &new_len, tail))
2194 die(_("unable to update url base from redirection:\n"
2195 " asked for: %s\n"
2196 " redirect: %s"),
2197 asked, got->buf);
2199 strbuf_reset(base);
2200 strbuf_add(base, got->buf, new_len);
2202 return 1;
2205 static int http_request_reauth(const char *url,
2206 void *result, int target,
2207 struct http_get_options *options)
2209 int i = 3;
2210 int ret;
2212 if (always_auth_proactively())
2213 credential_fill(the_repository, &http_auth, 1);
2215 ret = http_request(url, result, target, options);
2217 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2218 return ret;
2220 if (options && options->effective_url && options->base_url) {
2221 if (update_url_from_redirect(options->base_url,
2222 url, options->effective_url)) {
2223 credential_from_url(&http_auth, options->base_url->buf);
2224 url = options->effective_url->buf;
2228 while (ret == HTTP_REAUTH && --i) {
2230 * The previous request may have put cruft into our output stream; we
2231 * should clear it out before making our next request.
2233 switch (target) {
2234 case HTTP_REQUEST_STRBUF:
2235 strbuf_reset(result);
2236 break;
2237 case HTTP_REQUEST_FILE: {
2238 FILE *f = result;
2239 if (fflush(f)) {
2240 error_errno("unable to flush a file");
2241 return HTTP_START_FAILED;
2243 rewind(f);
2244 if (ftruncate(fileno(f), 0) < 0) {
2245 error_errno("unable to truncate a file");
2246 return HTTP_START_FAILED;
2248 break;
2250 default:
2251 BUG("Unknown http_request target");
2254 credential_fill(the_repository, &http_auth, 1);
2256 ret = http_request(url, result, target, options);
2258 return ret;
2261 int http_get_strbuf(const char *url,
2262 struct strbuf *result,
2263 struct http_get_options *options)
2265 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2269 * Downloads a URL and stores the result in the given file.
2271 * If a previous interrupted download is detected (i.e. a previous temporary
2272 * file is still around) the download is resumed.
2274 int http_get_file(const char *url, const char *filename,
2275 struct http_get_options *options)
2277 int ret;
2278 struct strbuf tmpfile = STRBUF_INIT;
2279 FILE *result;
2281 strbuf_addf(&tmpfile, "%s.temp", filename);
2282 result = fopen(tmpfile.buf, "a");
2283 if (!result) {
2284 error("Unable to open local file %s", tmpfile.buf);
2285 ret = HTTP_ERROR;
2286 goto cleanup;
2289 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2290 fclose(result);
2292 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2293 ret = HTTP_ERROR;
2294 cleanup:
2295 strbuf_release(&tmpfile);
2296 return ret;
2299 int http_fetch_ref(const char *base, struct ref *ref)
2301 struct http_get_options options = {0};
2302 char *url;
2303 struct strbuf buffer = STRBUF_INIT;
2304 int ret = -1;
2306 options.no_cache = 1;
2308 url = quote_ref_url(base, ref->name);
2309 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2310 strbuf_rtrim(&buffer);
2311 if (buffer.len == the_hash_algo->hexsz)
2312 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2313 else if (starts_with(buffer.buf, "ref: ")) {
2314 ref->symref = xstrdup(buffer.buf + 5);
2315 ret = 0;
2319 strbuf_release(&buffer);
2320 free(url);
2321 return ret;
2324 /* Helpers for fetching packs */
2325 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2327 char *url, *tmp;
2328 struct strbuf buf = STRBUF_INIT;
2330 if (http_is_verbose)
2331 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2333 end_url_with_slash(&buf, base_url);
2334 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2335 url = strbuf_detach(&buf, NULL);
2338 * Don't put this into packs/, since it's just temporary and we don't
2339 * want to confuse it with our local .idx files. We'll generate our
2340 * own index if we choose to download the matching packfile.
2342 * It's tempting to use xmks_tempfile() here, but it's important that
2343 * the file not exist, otherwise http_get_file() complains. So we
2344 * create a filename that should be unique, and then just register it
2345 * as a tempfile so that it will get cleaned up on exit.
2347 * In theory we could hold on to the tempfile and delete these as soon
2348 * as we download the matching pack, but it would take a bit of
2349 * refactoring. Leaving them until the process ends is probably OK.
2351 tmp = xstrfmt("%s/tmp_pack_%s.idx",
2352 repo_get_object_directory(the_repository),
2353 hash_to_hex(hash));
2354 register_tempfile(tmp);
2356 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2357 error("Unable to get pack index %s", url);
2358 FREE_AND_NULL(tmp);
2361 free(url);
2362 return tmp;
2365 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2366 unsigned char *sha1, const char *base_url)
2368 struct packed_git *new_pack, *p;
2369 char *tmp_idx = NULL;
2370 int ret;
2373 * If we already have the pack locally, no need to fetch its index or
2374 * even add it to list; we already have all of its objects.
2376 for (p = get_all_packs(the_repository); p; p = p->next) {
2377 if (hasheq(p->hash, sha1, the_repository->hash_algo))
2378 return 0;
2381 tmp_idx = fetch_pack_index(sha1, base_url);
2382 if (!tmp_idx)
2383 return -1;
2385 new_pack = parse_pack_index(the_repository, sha1, tmp_idx);
2386 if (!new_pack) {
2387 unlink(tmp_idx);
2388 free(tmp_idx);
2390 return -1; /* parse_pack_index() already issued error message */
2393 ret = verify_pack_index(new_pack);
2394 if (!ret)
2395 close_pack_index(new_pack);
2396 free(tmp_idx);
2397 if (ret)
2398 return -1;
2400 new_pack->next = *packs_head;
2401 *packs_head = new_pack;
2402 return 0;
2405 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2407 struct http_get_options options = {0};
2408 int ret = 0;
2409 char *url;
2410 const char *data;
2411 struct strbuf buf = STRBUF_INIT;
2412 struct object_id oid;
2414 end_url_with_slash(&buf, base_url);
2415 strbuf_addstr(&buf, "objects/info/packs");
2416 url = strbuf_detach(&buf, NULL);
2418 options.no_cache = 1;
2419 ret = http_get_strbuf(url, &buf, &options);
2420 if (ret != HTTP_OK)
2421 goto cleanup;
2423 data = buf.buf;
2424 while (*data) {
2425 if (skip_prefix(data, "P pack-", &data) &&
2426 !parse_oid_hex(data, &oid, &data) &&
2427 skip_prefix(data, ".pack", &data) &&
2428 (*data == '\n' || *data == '\0')) {
2429 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2430 } else {
2431 data = strchrnul(data, '\n');
2433 if (*data)
2434 data++; /* skip past newline */
2437 cleanup:
2438 free(url);
2439 strbuf_release(&buf);
2440 return ret;
2443 void release_http_pack_request(struct http_pack_request *preq)
2445 if (preq->packfile) {
2446 fclose(preq->packfile);
2447 preq->packfile = NULL;
2449 preq->slot = NULL;
2450 strbuf_release(&preq->tmpfile);
2451 curl_slist_free_all(preq->headers);
2452 free(preq->url);
2453 free(preq);
2456 static const char *default_index_pack_args[] =
2457 {"index-pack", "--stdin", NULL};
2459 int finish_http_pack_request(struct http_pack_request *preq)
2461 struct child_process ip = CHILD_PROCESS_INIT;
2462 int tmpfile_fd;
2463 int ret = 0;
2465 fclose(preq->packfile);
2466 preq->packfile = NULL;
2468 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2470 ip.git_cmd = 1;
2471 ip.in = tmpfile_fd;
2472 strvec_pushv(&ip.args, preq->index_pack_args ?
2473 preq->index_pack_args :
2474 default_index_pack_args);
2476 if (preq->preserve_index_pack_stdout)
2477 ip.out = 0;
2478 else
2479 ip.no_stdout = 1;
2481 if (run_command(&ip)) {
2482 ret = -1;
2483 goto cleanup;
2486 cleanup:
2487 close(tmpfile_fd);
2488 unlink(preq->tmpfile.buf);
2489 return ret;
2492 void http_install_packfile(struct packed_git *p,
2493 struct packed_git **list_to_remove_from)
2495 struct packed_git **lst = list_to_remove_from;
2497 while (*lst != p)
2498 lst = &((*lst)->next);
2499 *lst = (*lst)->next;
2501 install_packed_git(the_repository, p);
2504 struct http_pack_request *new_http_pack_request(
2505 const unsigned char *packed_git_hash, const char *base_url) {
2507 struct strbuf buf = STRBUF_INIT;
2509 end_url_with_slash(&buf, base_url);
2510 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2511 hash_to_hex(packed_git_hash));
2512 return new_direct_http_pack_request(packed_git_hash,
2513 strbuf_detach(&buf, NULL));
2516 struct http_pack_request *new_direct_http_pack_request(
2517 const unsigned char *packed_git_hash, char *url)
2519 off_t prev_posn = 0;
2520 struct http_pack_request *preq;
2522 CALLOC_ARRAY(preq, 1);
2523 strbuf_init(&preq->tmpfile, 0);
2525 preq->url = url;
2527 odb_pack_name(the_repository, &preq->tmpfile, packed_git_hash, "pack");
2528 strbuf_addstr(&preq->tmpfile, ".temp");
2529 preq->packfile = fopen(preq->tmpfile.buf, "a");
2530 if (!preq->packfile) {
2531 error("Unable to open local file %s for pack",
2532 preq->tmpfile.buf);
2533 goto abort;
2536 preq->slot = get_active_slot();
2537 preq->headers = object_request_headers();
2538 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2539 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2540 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2541 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER, preq->headers);
2544 * If there is data present from a previous transfer attempt,
2545 * resume where it left off
2547 prev_posn = ftello(preq->packfile);
2548 if (prev_posn>0) {
2549 if (http_is_verbose)
2550 fprintf(stderr,
2551 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2552 hash_to_hex(packed_git_hash),
2553 (uintmax_t)prev_posn);
2554 http_opt_request_remainder(preq->slot->curl, prev_posn);
2557 return preq;
2559 abort:
2560 strbuf_release(&preq->tmpfile);
2561 free(preq->url);
2562 free(preq);
2563 return NULL;
2566 /* Helpers for fetching objects (loose) */
2567 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2568 void *data)
2570 unsigned char expn[4096];
2571 size_t size = eltsize * nmemb;
2572 int posn = 0;
2573 struct http_object_request *freq = data;
2574 struct active_request_slot *slot = freq->slot;
2576 if (slot) {
2577 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2578 &slot->http_code);
2579 if (c != CURLE_OK)
2580 BUG("curl_easy_getinfo for HTTP code failed: %s",
2581 curl_easy_strerror(c));
2582 if (slot->http_code >= 300)
2583 return nmemb;
2586 do {
2587 ssize_t retval = xwrite(freq->localfile,
2588 (char *) ptr + posn, size - posn);
2589 if (retval < 0)
2590 return posn / eltsize;
2591 posn += retval;
2592 } while (posn < size);
2594 freq->stream.avail_in = size;
2595 freq->stream.next_in = (void *)ptr;
2596 do {
2597 freq->stream.next_out = expn;
2598 freq->stream.avail_out = sizeof(expn);
2599 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2600 the_hash_algo->update_fn(&freq->c, expn,
2601 sizeof(expn) - freq->stream.avail_out);
2602 } while (freq->stream.avail_in && freq->zret == Z_OK);
2603 return nmemb;
2606 struct http_object_request *new_http_object_request(const char *base_url,
2607 const struct object_id *oid)
2609 char *hex = oid_to_hex(oid);
2610 struct strbuf filename = STRBUF_INIT;
2611 struct strbuf prevfile = STRBUF_INIT;
2612 int prevlocal;
2613 char prev_buf[PREV_BUF_SIZE];
2614 ssize_t prev_read = 0;
2615 off_t prev_posn = 0;
2616 struct http_object_request *freq;
2618 CALLOC_ARRAY(freq, 1);
2619 strbuf_init(&freq->tmpfile, 0);
2620 oidcpy(&freq->oid, oid);
2621 freq->localfile = -1;
2623 loose_object_path(the_repository, &filename, oid);
2624 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2626 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2627 unlink_or_warn(prevfile.buf);
2628 rename(freq->tmpfile.buf, prevfile.buf);
2629 unlink_or_warn(freq->tmpfile.buf);
2630 strbuf_release(&filename);
2632 if (freq->localfile != -1)
2633 error("fd leakage in start: %d", freq->localfile);
2634 freq->localfile = open(freq->tmpfile.buf,
2635 O_WRONLY | O_CREAT | O_EXCL, 0666);
2637 * This could have failed due to the "lazy directory creation";
2638 * try to mkdir the last path component.
2640 if (freq->localfile < 0 && errno == ENOENT) {
2641 char *dir = strrchr(freq->tmpfile.buf, '/');
2642 if (dir) {
2643 *dir = 0;
2644 mkdir(freq->tmpfile.buf, 0777);
2645 *dir = '/';
2647 freq->localfile = open(freq->tmpfile.buf,
2648 O_WRONLY | O_CREAT | O_EXCL, 0666);
2651 if (freq->localfile < 0) {
2652 error_errno("Couldn't create temporary file %s",
2653 freq->tmpfile.buf);
2654 goto abort;
2657 git_inflate_init(&freq->stream);
2659 the_hash_algo->init_fn(&freq->c);
2661 freq->url = get_remote_object_url(base_url, hex, 0);
2664 * If a previous temp file is present, process what was already
2665 * fetched.
2667 prevlocal = open(prevfile.buf, O_RDONLY);
2668 if (prevlocal != -1) {
2669 do {
2670 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2671 if (prev_read>0) {
2672 if (fwrite_sha1_file(prev_buf,
2674 prev_read,
2675 freq) == prev_read) {
2676 prev_posn += prev_read;
2677 } else {
2678 prev_read = -1;
2681 } while (prev_read > 0);
2682 close(prevlocal);
2684 unlink_or_warn(prevfile.buf);
2685 strbuf_release(&prevfile);
2688 * Reset inflate/SHA1 if there was an error reading the previous temp
2689 * file; also rewind to the beginning of the local file.
2691 if (prev_read == -1) {
2692 git_inflate_end(&freq->stream);
2693 memset(&freq->stream, 0, sizeof(freq->stream));
2694 git_inflate_init(&freq->stream);
2695 the_hash_algo->init_fn(&freq->c);
2696 if (prev_posn>0) {
2697 prev_posn = 0;
2698 lseek(freq->localfile, 0, SEEK_SET);
2699 if (ftruncate(freq->localfile, 0) < 0) {
2700 error_errno("Couldn't truncate temporary file %s",
2701 freq->tmpfile.buf);
2702 goto abort;
2707 freq->slot = get_active_slot();
2708 freq->headers = object_request_headers();
2710 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2711 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2712 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2713 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2714 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2715 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, freq->headers);
2718 * If we have successfully processed data from a previous fetch
2719 * attempt, only fetch the data we don't already have.
2721 if (prev_posn>0) {
2722 if (http_is_verbose)
2723 fprintf(stderr,
2724 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2725 hex, (uintmax_t)prev_posn);
2726 http_opt_request_remainder(freq->slot->curl, prev_posn);
2729 return freq;
2731 abort:
2732 strbuf_release(&prevfile);
2733 free(freq->url);
2734 free(freq);
2735 return NULL;
2738 void process_http_object_request(struct http_object_request *freq)
2740 if (!freq->slot)
2741 return;
2742 freq->curl_result = freq->slot->curl_result;
2743 freq->http_code = freq->slot->http_code;
2744 freq->slot = NULL;
2747 int finish_http_object_request(struct http_object_request *freq)
2749 struct stat st;
2750 struct strbuf filename = STRBUF_INIT;
2752 close(freq->localfile);
2753 freq->localfile = -1;
2755 process_http_object_request(freq);
2757 if (freq->http_code == 416) {
2758 warning("requested range invalid; we may already have all the data.");
2759 } else if (freq->curl_result != CURLE_OK) {
2760 if (stat(freq->tmpfile.buf, &st) == 0)
2761 if (st.st_size == 0)
2762 unlink_or_warn(freq->tmpfile.buf);
2763 return -1;
2766 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2767 if (freq->zret != Z_STREAM_END) {
2768 unlink_or_warn(freq->tmpfile.buf);
2769 return -1;
2771 if (!oideq(&freq->oid, &freq->real_oid)) {
2772 unlink_or_warn(freq->tmpfile.buf);
2773 return -1;
2775 loose_object_path(the_repository, &filename, &freq->oid);
2776 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2777 strbuf_release(&filename);
2779 return freq->rename;
2782 void abort_http_object_request(struct http_object_request **freq_p)
2784 struct http_object_request *freq = *freq_p;
2785 unlink_or_warn(freq->tmpfile.buf);
2787 release_http_object_request(freq_p);
2790 void release_http_object_request(struct http_object_request **freq_p)
2792 struct http_object_request *freq = *freq_p;
2793 if (freq->localfile != -1) {
2794 close(freq->localfile);
2795 freq->localfile = -1;
2797 FREE_AND_NULL(freq->url);
2798 if (freq->slot) {
2799 freq->slot->callback_func = NULL;
2800 freq->slot->callback_data = NULL;
2801 release_active_slot(freq->slot);
2802 freq->slot = NULL;
2804 curl_slist_free_all(freq->headers);
2805 strbuf_release(&freq->tmpfile);
2806 git_inflate_end(&freq->stream);
2808 free(freq);
2809 *freq_p = NULL;