strvec: declare the `strvec_push_nodup()` function globally
[git.git] / http.c
blob13fa94bef39f4a052be1d10e9017ad09246537c5
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "git-curl-compat.h"
5 #include "hex.h"
6 #include "http.h"
7 #include "config.h"
8 #include "pack.h"
9 #include "run-command.h"
10 #include "url.h"
11 #include "urlmatch.h"
12 #include "credential.h"
13 #include "version.h"
14 #include "pkt-line.h"
15 #include "gettext.h"
16 #include "trace.h"
17 #include "transport.h"
18 #include "packfile.h"
19 #include "string-list.h"
20 #include "object-file.h"
21 #include "object-store-ll.h"
23 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
24 static int trace_curl_data = 1;
25 static int trace_curl_redact = 1;
26 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
27 int active_requests;
28 int http_is_verbose;
29 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
31 static int min_curl_sessions = 1;
32 static int curl_session_count;
33 static int max_requests = -1;
34 static CURLM *curlm;
35 static CURL *curl_default;
37 #define PREV_BUF_SIZE 4096
39 char curl_errorstr[CURL_ERROR_SIZE];
41 static int curl_ssl_verify = -1;
42 static int curl_ssl_try;
43 static char *curl_http_version;
44 static char *ssl_cert;
45 static char *ssl_cert_type;
46 static char *ssl_cipherlist;
47 static char *ssl_version;
48 static struct {
49 const char *name;
50 long ssl_version;
51 } sslversions[] = {
52 { "sslv2", CURL_SSLVERSION_SSLv2 },
53 { "sslv3", CURL_SSLVERSION_SSLv3 },
54 { "tlsv1", CURL_SSLVERSION_TLSv1 },
55 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
56 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
57 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
58 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
59 #endif
60 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
61 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
62 #endif
64 static char *ssl_key;
65 static char *ssl_key_type;
66 static char *ssl_capath;
67 static char *curl_no_proxy;
68 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
69 static char *ssl_pinnedkey;
70 #endif
71 static char *ssl_cainfo;
72 static long curl_low_speed_limit = -1;
73 static long curl_low_speed_time = -1;
74 static int curl_ftp_no_epsv;
75 static char *curl_http_proxy;
76 static char *http_proxy_authmethod;
78 static char *http_proxy_ssl_cert;
79 static char *http_proxy_ssl_key;
80 static char *http_proxy_ssl_ca_info;
81 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
82 static int proxy_ssl_cert_password_required;
84 static struct {
85 const char *name;
86 long curlauth_param;
87 } proxy_authmethods[] = {
88 { "basic", CURLAUTH_BASIC },
89 { "digest", CURLAUTH_DIGEST },
90 { "negotiate", CURLAUTH_GSSNEGOTIATE },
91 { "ntlm", CURLAUTH_NTLM },
92 { "anyauth", CURLAUTH_ANY },
94 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
95 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
96 * here, too
99 #ifdef CURLGSSAPI_DELEGATION_FLAG
100 static char *curl_deleg;
101 static struct {
102 const char *name;
103 long curl_deleg_param;
104 } curl_deleg_levels[] = {
105 { "none", CURLGSSAPI_DELEGATION_NONE },
106 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
107 { "always", CURLGSSAPI_DELEGATION_FLAG },
109 #endif
111 static struct credential proxy_auth = CREDENTIAL_INIT;
112 static const char *curl_proxyuserpwd;
113 static char *curl_cookie_file;
114 static int curl_save_cookies;
115 struct credential http_auth = CREDENTIAL_INIT;
116 static int http_proactive_auth;
117 static char *user_agent;
118 static int curl_empty_auth = -1;
120 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
122 static struct credential cert_auth = CREDENTIAL_INIT;
123 static int ssl_cert_password_required;
124 static unsigned long http_auth_methods = CURLAUTH_ANY;
125 static int http_auth_methods_restricted;
126 /* Modes for which empty_auth cannot actually help us. */
127 static unsigned long empty_auth_useless =
128 CURLAUTH_BASIC
129 | CURLAUTH_DIGEST_IE
130 | CURLAUTH_DIGEST;
132 static struct curl_slist *pragma_header;
133 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
135 static struct curl_slist *host_resolutions;
137 static struct active_request_slot *active_queue_head;
139 static char *cached_accept_language;
141 static char *http_ssl_backend;
143 static int http_schannel_check_revoke = 1;
145 * With the backend being set to `schannel`, setting sslCAinfo would override
146 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
147 * by default.
149 static int http_schannel_use_ssl_cainfo;
151 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
153 size_t size = eltsize * nmemb;
154 struct buffer *buffer = buffer_;
156 if (size > buffer->buf.len - buffer->posn)
157 size = buffer->buf.len - buffer->posn;
158 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
159 buffer->posn += size;
161 return size / eltsize;
164 int seek_buffer(void *clientp, curl_off_t offset, int origin)
166 struct buffer *buffer = clientp;
168 if (origin != SEEK_SET)
169 BUG("seek_buffer only handles SEEK_SET");
170 if (offset < 0 || offset >= buffer->buf.len) {
171 error("curl seek would be outside of buffer");
172 return CURL_SEEKFUNC_FAIL;
175 buffer->posn = offset;
176 return CURL_SEEKFUNC_OK;
179 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
181 size_t size = eltsize * nmemb;
182 struct strbuf *buffer = buffer_;
184 strbuf_add(buffer, ptr, size);
185 return nmemb;
189 * A folded header continuation line starts with any number of spaces or
190 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
191 * It is not a continuation line if the line starts with any other character.
193 static inline int is_hdr_continuation(const char *ptr, const size_t size)
195 return size && (*ptr == ' ' || *ptr == '\t');
198 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
200 size_t size = eltsize * nmemb;
201 struct strvec *values = &http_auth.wwwauth_headers;
202 struct strbuf buf = STRBUF_INIT;
203 const char *val;
204 size_t val_len;
207 * Header lines may not come NULL-terminated from libcurl so we must
208 * limit all scans to the maximum length of the header line, or leverage
209 * strbufs for all operations.
211 * In addition, it is possible that header values can be split over
212 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
213 * but older servers may still emit them. A continuation header field
214 * value is identified as starting with a space or horizontal tab.
216 * The formal definition of a header field as given in RFC 7230 is:
218 * header-field = field-name ":" OWS field-value OWS
220 * field-name = token
221 * field-value = *( field-content / obs-fold )
222 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
223 * field-vchar = VCHAR / obs-text
225 * obs-fold = CRLF 1*( SP / HTAB )
226 * ; obsolete line folding
227 * ; see Section 3.2.4
230 /* Start of a new WWW-Authenticate header */
231 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
232 strbuf_add(&buf, val, val_len);
235 * Strip the CRLF that should be present at the end of each
236 * field as well as any trailing or leading whitespace from the
237 * value.
239 strbuf_trim(&buf);
241 strvec_push(values, buf.buf);
242 http_auth.header_is_last_match = 1;
243 goto exit;
247 * This line could be a continuation of the previously matched header
248 * field. If this is the case then we should append this value to the
249 * end of the previously consumed value.
251 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
253 * Trim the CRLF and any leading or trailing from this line.
255 strbuf_add(&buf, ptr, size);
256 strbuf_trim(&buf);
259 * At this point we should always have at least one existing
260 * value, even if it is empty. Do not bother appending the new
261 * value if this continuation header is itself empty.
263 if (!values->nr) {
264 BUG("should have at least one existing header value");
265 } else if (buf.len) {
266 char *prev = xstrdup(values->v[values->nr - 1]);
268 /* Join two non-empty values with a single space. */
269 const char *const sp = *prev ? " " : "";
271 strvec_pop(values);
272 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
273 free(prev);
276 goto exit;
279 /* Not a continuation of a previously matched auth header line. */
280 http_auth.header_is_last_match = 0;
283 * If this is a HTTP status line and not a header field, this signals
284 * a different HTTP response. libcurl writes all the output of all
285 * response headers of all responses, including redirects.
286 * We only care about the last HTTP request response's headers so clear
287 * the existing array.
289 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
290 strvec_clear(values);
292 exit:
293 strbuf_release(&buf);
294 return size;
297 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
298 void *data UNUSED)
300 return nmemb;
303 static struct curl_slist *object_request_headers(void)
305 return curl_slist_append(http_copy_default_headers(), "Pragma:");
308 static void closedown_active_slot(struct active_request_slot *slot)
310 active_requests--;
311 slot->in_use = 0;
314 static void finish_active_slot(struct active_request_slot *slot)
316 closedown_active_slot(slot);
317 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
319 if (slot->finished)
320 (*slot->finished) = 1;
322 /* Store slot results so they can be read after the slot is reused */
323 if (slot->results) {
324 slot->results->curl_result = slot->curl_result;
325 slot->results->http_code = slot->http_code;
326 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
327 &slot->results->auth_avail);
329 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
330 &slot->results->http_connectcode);
333 /* Run callback if appropriate */
334 if (slot->callback_func)
335 slot->callback_func(slot->callback_data);
338 static void xmulti_remove_handle(struct active_request_slot *slot)
340 curl_multi_remove_handle(curlm, slot->curl);
343 static void process_curl_messages(void)
345 int num_messages;
346 struct active_request_slot *slot;
347 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
349 while (curl_message != NULL) {
350 if (curl_message->msg == CURLMSG_DONE) {
351 int curl_result = curl_message->data.result;
352 slot = active_queue_head;
353 while (slot != NULL &&
354 slot->curl != curl_message->easy_handle)
355 slot = slot->next;
356 if (slot) {
357 xmulti_remove_handle(slot);
358 slot->curl_result = curl_result;
359 finish_active_slot(slot);
360 } else {
361 fprintf(stderr, "Received DONE message for unknown request!\n");
363 } else {
364 fprintf(stderr, "Unknown CURL message received: %d\n",
365 (int)curl_message->msg);
367 curl_message = curl_multi_info_read(curlm, &num_messages);
371 static int http_options(const char *var, const char *value,
372 const struct config_context *ctx, void *data)
374 if (!strcmp("http.version", var)) {
375 return git_config_string(&curl_http_version, var, value);
377 if (!strcmp("http.sslverify", var)) {
378 curl_ssl_verify = git_config_bool(var, value);
379 return 0;
381 if (!strcmp("http.sslcipherlist", var))
382 return git_config_string(&ssl_cipherlist, var, value);
383 if (!strcmp("http.sslversion", var))
384 return git_config_string(&ssl_version, var, value);
385 if (!strcmp("http.sslcert", var))
386 return git_config_pathname(&ssl_cert, var, value);
387 if (!strcmp("http.sslcerttype", var))
388 return git_config_string(&ssl_cert_type, var, value);
389 if (!strcmp("http.sslkey", var))
390 return git_config_pathname(&ssl_key, var, value);
391 if (!strcmp("http.sslkeytype", var))
392 return git_config_string(&ssl_key_type, var, value);
393 if (!strcmp("http.sslcapath", var))
394 return git_config_pathname(&ssl_capath, var, value);
395 if (!strcmp("http.sslcainfo", var))
396 return git_config_pathname(&ssl_cainfo, var, value);
397 if (!strcmp("http.sslcertpasswordprotected", var)) {
398 ssl_cert_password_required = git_config_bool(var, value);
399 return 0;
401 if (!strcmp("http.ssltry", var)) {
402 curl_ssl_try = git_config_bool(var, value);
403 return 0;
405 if (!strcmp("http.sslbackend", var)) {
406 free(http_ssl_backend);
407 http_ssl_backend = xstrdup_or_null(value);
408 return 0;
411 if (!strcmp("http.schannelcheckrevoke", var)) {
412 http_schannel_check_revoke = git_config_bool(var, value);
413 return 0;
416 if (!strcmp("http.schannelusesslcainfo", var)) {
417 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
418 return 0;
421 if (!strcmp("http.minsessions", var)) {
422 min_curl_sessions = git_config_int(var, value, ctx->kvi);
423 if (min_curl_sessions > 1)
424 min_curl_sessions = 1;
425 return 0;
427 if (!strcmp("http.maxrequests", var)) {
428 max_requests = git_config_int(var, value, ctx->kvi);
429 return 0;
431 if (!strcmp("http.lowspeedlimit", var)) {
432 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
433 return 0;
435 if (!strcmp("http.lowspeedtime", var)) {
436 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
437 return 0;
440 if (!strcmp("http.noepsv", var)) {
441 curl_ftp_no_epsv = git_config_bool(var, value);
442 return 0;
444 if (!strcmp("http.proxy", var))
445 return git_config_string(&curl_http_proxy, var, value);
447 if (!strcmp("http.proxyauthmethod", var))
448 return git_config_string(&http_proxy_authmethod, var, value);
450 if (!strcmp("http.proxysslcert", var))
451 return git_config_string(&http_proxy_ssl_cert, var, value);
453 if (!strcmp("http.proxysslkey", var))
454 return git_config_string(&http_proxy_ssl_key, var, value);
456 if (!strcmp("http.proxysslcainfo", var))
457 return git_config_string(&http_proxy_ssl_ca_info, var, value);
459 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
460 proxy_ssl_cert_password_required = git_config_bool(var, value);
461 return 0;
464 if (!strcmp("http.cookiefile", var))
465 return git_config_pathname(&curl_cookie_file, var, value);
466 if (!strcmp("http.savecookies", var)) {
467 curl_save_cookies = git_config_bool(var, value);
468 return 0;
471 if (!strcmp("http.postbuffer", var)) {
472 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
473 if (http_post_buffer < 0)
474 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
475 if (http_post_buffer < LARGE_PACKET_MAX)
476 http_post_buffer = LARGE_PACKET_MAX;
477 return 0;
480 if (!strcmp("http.useragent", var))
481 return git_config_string(&user_agent, var, value);
483 if (!strcmp("http.emptyauth", var)) {
484 if (value && !strcmp("auto", value))
485 curl_empty_auth = -1;
486 else
487 curl_empty_auth = git_config_bool(var, value);
488 return 0;
491 if (!strcmp("http.delegation", var)) {
492 #ifdef CURLGSSAPI_DELEGATION_FLAG
493 return git_config_string(&curl_deleg, var, value);
494 #else
495 warning(_("Delegation control is not supported with cURL < 7.22.0"));
496 return 0;
497 #endif
500 if (!strcmp("http.pinnedpubkey", var)) {
501 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
502 return git_config_pathname(&ssl_pinnedkey, var, value);
503 #else
504 warning(_("Public key pinning not supported with cURL < 7.39.0"));
505 return 0;
506 #endif
509 if (!strcmp("http.extraheader", var)) {
510 if (!value) {
511 return config_error_nonbool(var);
512 } else if (!*value) {
513 string_list_clear(&extra_http_headers, 0);
514 } else {
515 string_list_append(&extra_http_headers, value);
517 return 0;
520 if (!strcmp("http.curloptresolve", var)) {
521 if (!value) {
522 return config_error_nonbool(var);
523 } else if (!*value) {
524 curl_slist_free_all(host_resolutions);
525 host_resolutions = NULL;
526 } else {
527 host_resolutions = curl_slist_append(host_resolutions, value);
529 return 0;
532 if (!strcmp("http.followredirects", var)) {
533 if (value && !strcmp(value, "initial"))
534 http_follow_config = HTTP_FOLLOW_INITIAL;
535 else if (git_config_bool(var, value))
536 http_follow_config = HTTP_FOLLOW_ALWAYS;
537 else
538 http_follow_config = HTTP_FOLLOW_NONE;
539 return 0;
542 /* Fall back on the default ones */
543 return git_default_config(var, value, ctx, data);
546 static int curl_empty_auth_enabled(void)
548 if (curl_empty_auth >= 0)
549 return curl_empty_auth;
552 * In the automatic case, kick in the empty-auth
553 * hack as long as we would potentially try some
554 * method more exotic than "Basic" or "Digest".
556 * But only do this when this is our second or
557 * subsequent request, as by then we know what
558 * methods are available.
560 if (http_auth_methods_restricted &&
561 (http_auth_methods & ~empty_auth_useless))
562 return 1;
563 return 0;
566 struct curl_slist *http_append_auth_header(const struct credential *c,
567 struct curl_slist *headers)
569 if (c->authtype && c->credential) {
570 struct strbuf auth = STRBUF_INIT;
571 strbuf_addf(&auth, "Authorization: %s %s",
572 c->authtype, c->credential);
573 headers = curl_slist_append(headers, auth.buf);
574 strbuf_release(&auth);
576 return headers;
579 static void init_curl_http_auth(CURL *result)
581 if ((!http_auth.username || !*http_auth.username) &&
582 (!http_auth.credential || !*http_auth.credential)) {
583 if (curl_empty_auth_enabled())
584 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
585 return;
588 credential_fill(&http_auth, 1);
590 if (http_auth.password) {
591 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
592 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
596 /* *var must be free-able */
597 static void var_override(char **var, char *value)
599 if (value) {
600 free(*var);
601 *var = xstrdup(value);
605 static void set_proxyauth_name_password(CURL *result)
607 if (proxy_auth.password) {
608 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
609 proxy_auth.username);
610 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
611 proxy_auth.password);
612 } else if (proxy_auth.authtype && proxy_auth.credential) {
613 curl_easy_setopt(result, CURLOPT_PROXYHEADER,
614 http_append_auth_header(&proxy_auth, NULL));
618 static void init_curl_proxy_auth(CURL *result)
620 if (proxy_auth.username) {
621 if (!proxy_auth.password && !proxy_auth.credential)
622 credential_fill(&proxy_auth, 1);
623 set_proxyauth_name_password(result);
626 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
628 if (http_proxy_authmethod) {
629 int i;
630 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
631 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
632 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
633 proxy_authmethods[i].curlauth_param);
634 break;
637 if (i == ARRAY_SIZE(proxy_authmethods)) {
638 warning("unsupported proxy authentication method %s: using anyauth",
639 http_proxy_authmethod);
640 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
643 else
644 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
647 static int has_cert_password(void)
649 if (ssl_cert == NULL || ssl_cert_password_required != 1)
650 return 0;
651 if (!cert_auth.password) {
652 cert_auth.protocol = xstrdup("cert");
653 cert_auth.host = xstrdup("");
654 cert_auth.username = xstrdup("");
655 cert_auth.path = xstrdup(ssl_cert);
656 credential_fill(&cert_auth, 0);
658 return 1;
661 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
662 static int has_proxy_cert_password(void)
664 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
665 return 0;
666 if (!proxy_cert_auth.password) {
667 proxy_cert_auth.protocol = xstrdup("cert");
668 proxy_cert_auth.host = xstrdup("");
669 proxy_cert_auth.username = xstrdup("");
670 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
671 credential_fill(&proxy_cert_auth, 0);
673 return 1;
675 #endif
677 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
678 static void set_curl_keepalive(CURL *c)
680 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
683 #else
684 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
686 int ka = 1;
687 int rc;
688 socklen_t len = (socklen_t)sizeof(ka);
690 if (type != CURLSOCKTYPE_IPCXN)
691 return 0;
693 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
694 if (rc < 0)
695 warning_errno("unable to set SO_KEEPALIVE on socket");
697 return CURL_SOCKOPT_OK;
700 static void set_curl_keepalive(CURL *c)
702 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
704 #endif
706 /* Return 1 if redactions have been made, 0 otherwise. */
707 static int redact_sensitive_header(struct strbuf *header, size_t offset)
709 int ret = 0;
710 const char *sensitive_header;
712 if (trace_curl_redact &&
713 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
714 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
715 /* The first token is the type, which is OK to log */
716 while (isspace(*sensitive_header))
717 sensitive_header++;
718 while (*sensitive_header && !isspace(*sensitive_header))
719 sensitive_header++;
720 /* Everything else is opaque and possibly sensitive */
721 strbuf_setlen(header, sensitive_header - header->buf);
722 strbuf_addstr(header, " <redacted>");
723 ret = 1;
724 } else if (trace_curl_redact &&
725 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
726 struct strbuf redacted_header = STRBUF_INIT;
727 const char *cookie;
729 while (isspace(*sensitive_header))
730 sensitive_header++;
732 cookie = sensitive_header;
734 while (cookie) {
735 char *equals;
736 char *semicolon = strstr(cookie, "; ");
737 if (semicolon)
738 *semicolon = 0;
739 equals = strchrnul(cookie, '=');
740 if (!equals) {
741 /* invalid cookie, just append and continue */
742 strbuf_addstr(&redacted_header, cookie);
743 continue;
745 strbuf_add(&redacted_header, cookie, equals - cookie);
746 strbuf_addstr(&redacted_header, "=<redacted>");
747 if (semicolon) {
749 * There are more cookies. (Or, for some
750 * reason, the input string ends in "; ".)
752 strbuf_addstr(&redacted_header, "; ");
753 cookie = semicolon + strlen("; ");
754 } else {
755 cookie = NULL;
759 strbuf_setlen(header, sensitive_header - header->buf);
760 strbuf_addbuf(header, &redacted_header);
761 ret = 1;
763 return ret;
766 static int match_curl_h2_trace(const char *line, const char **out)
768 const char *p;
771 * curl prior to 8.1.0 gives us:
773 * h2h3 [<header-name>: <header-val>]
775 * Starting in 8.1.0, the first token became just "h2".
777 if (skip_iprefix(line, "h2h3 [", out) ||
778 skip_iprefix(line, "h2 [", out))
779 return 1;
782 * curl 8.3.0 uses:
783 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
784 * where <stream-id> is numeric.
786 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
787 while (isdigit(*p))
788 p++;
789 if (skip_prefix(p, "] [", out))
790 return 1;
793 return 0;
796 /* Redact headers in info */
797 static void redact_sensitive_info_header(struct strbuf *header)
799 const char *sensitive_header;
801 if (trace_curl_redact &&
802 match_curl_h2_trace(header->buf, &sensitive_header)) {
803 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
804 /* redaction ate our closing bracket */
805 strbuf_addch(header, ']');
810 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
812 struct strbuf out = STRBUF_INIT;
813 struct strbuf **headers, **header;
815 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
816 text, (long)size, (long)size);
817 trace_strbuf(&trace_curl, &out);
818 strbuf_reset(&out);
819 strbuf_add(&out, ptr, size);
820 headers = strbuf_split_max(&out, '\n', 0);
822 for (header = headers; *header; header++) {
823 if (hide_sensitive_header)
824 redact_sensitive_header(*header, 0);
825 strbuf_insertstr((*header), 0, text);
826 strbuf_insertstr((*header), strlen(text), ": ");
827 strbuf_rtrim((*header));
828 strbuf_addch((*header), '\n');
829 trace_strbuf(&trace_curl, (*header));
831 strbuf_list_free(headers);
832 strbuf_release(&out);
835 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
837 size_t i;
838 struct strbuf out = STRBUF_INIT;
839 unsigned int width = 60;
841 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
842 text, (long)size, (long)size);
843 trace_strbuf(&trace_curl, &out);
845 for (i = 0; i < size; i += width) {
846 size_t w;
848 strbuf_reset(&out);
849 strbuf_addf(&out, "%s: ", text);
850 for (w = 0; (w < width) && (i + w < size); w++) {
851 unsigned char ch = ptr[i + w];
853 strbuf_addch(&out,
854 (ch >= 0x20) && (ch < 0x80)
855 ? ch : '.');
857 strbuf_addch(&out, '\n');
858 trace_strbuf(&trace_curl, &out);
860 strbuf_release(&out);
863 static void curl_dump_info(char *data, size_t size)
865 struct strbuf buf = STRBUF_INIT;
867 strbuf_add(&buf, data, size);
869 redact_sensitive_info_header(&buf);
870 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
872 strbuf_release(&buf);
875 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
876 char *data, size_t size,
877 void *userp UNUSED)
879 const char *text;
880 enum { NO_FILTER = 0, DO_FILTER = 1 };
882 switch (type) {
883 case CURLINFO_TEXT:
884 curl_dump_info(data, size);
885 break;
886 case CURLINFO_HEADER_OUT:
887 text = "=> Send header";
888 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
889 break;
890 case CURLINFO_DATA_OUT:
891 if (trace_curl_data) {
892 text = "=> Send data";
893 curl_dump_data(text, (unsigned char *)data, size);
895 break;
896 case CURLINFO_SSL_DATA_OUT:
897 if (trace_curl_data) {
898 text = "=> Send SSL data";
899 curl_dump_data(text, (unsigned char *)data, size);
901 break;
902 case CURLINFO_HEADER_IN:
903 text = "<= Recv header";
904 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
905 break;
906 case CURLINFO_DATA_IN:
907 if (trace_curl_data) {
908 text = "<= Recv data";
909 curl_dump_data(text, (unsigned char *)data, size);
911 break;
912 case CURLINFO_SSL_DATA_IN:
913 if (trace_curl_data) {
914 text = "<= Recv SSL data";
915 curl_dump_data(text, (unsigned char *)data, size);
917 break;
919 default: /* we ignore unknown types by default */
920 return 0;
922 return 0;
925 void http_trace_curl_no_data(void)
927 trace_override_envvar(&trace_curl, "1");
928 trace_curl_data = 0;
931 void setup_curl_trace(CURL *handle)
933 if (!trace_want(&trace_curl))
934 return;
935 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
936 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
937 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
940 static void proto_list_append(struct strbuf *list, const char *proto)
942 if (!list)
943 return;
944 if (list->len)
945 strbuf_addch(list, ',');
946 strbuf_addstr(list, proto);
949 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
951 long bits = 0;
953 if (is_transport_allowed("http", from_user)) {
954 bits |= CURLPROTO_HTTP;
955 proto_list_append(list, "http");
957 if (is_transport_allowed("https", from_user)) {
958 bits |= CURLPROTO_HTTPS;
959 proto_list_append(list, "https");
961 if (is_transport_allowed("ftp", from_user)) {
962 bits |= CURLPROTO_FTP;
963 proto_list_append(list, "ftp");
965 if (is_transport_allowed("ftps", from_user)) {
966 bits |= CURLPROTO_FTPS;
967 proto_list_append(list, "ftps");
970 return bits;
973 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
974 static int get_curl_http_version_opt(const char *version_string, long *opt)
976 int i;
977 static struct {
978 const char *name;
979 long opt_token;
980 } choice[] = {
981 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
982 { "HTTP/2", CURL_HTTP_VERSION_2 }
985 for (i = 0; i < ARRAY_SIZE(choice); i++) {
986 if (!strcmp(version_string, choice[i].name)) {
987 *opt = choice[i].opt_token;
988 return 0;
992 warning("unknown value given to http.version: '%s'", version_string);
993 return -1; /* not found */
996 #endif
998 static CURL *get_curl_handle(void)
1000 CURL *result = curl_easy_init();
1002 if (!result)
1003 die("curl_easy_init failed");
1005 if (!curl_ssl_verify) {
1006 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
1007 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
1008 } else {
1009 /* Verify authenticity of the peer's certificate */
1010 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
1011 /* The name in the cert must match whom we tried to connect */
1012 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
1015 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1016 if (curl_http_version) {
1017 long opt;
1018 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
1019 /* Set request use http version */
1020 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
1023 #endif
1025 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
1026 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1028 #ifdef CURLGSSAPI_DELEGATION_FLAG
1029 if (curl_deleg) {
1030 int i;
1031 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1032 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1033 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1034 curl_deleg_levels[i].curl_deleg_param);
1035 break;
1038 if (i == ARRAY_SIZE(curl_deleg_levels))
1039 warning("Unknown delegation method '%s': using default",
1040 curl_deleg);
1042 #endif
1044 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1045 !http_schannel_check_revoke) {
1046 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1047 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1048 #else
1049 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1050 #endif
1053 if (http_proactive_auth)
1054 init_curl_http_auth(result);
1056 if (getenv("GIT_SSL_VERSION"))
1057 ssl_version = getenv("GIT_SSL_VERSION");
1058 if (ssl_version && *ssl_version) {
1059 int i;
1060 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1061 if (!strcmp(ssl_version, sslversions[i].name)) {
1062 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1063 sslversions[i].ssl_version);
1064 break;
1067 if (i == ARRAY_SIZE(sslversions))
1068 warning("unsupported ssl version %s: using default",
1069 ssl_version);
1072 if (getenv("GIT_SSL_CIPHER_LIST"))
1073 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1074 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1075 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1076 ssl_cipherlist);
1078 if (ssl_cert)
1079 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1080 if (ssl_cert_type)
1081 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1082 if (has_cert_password())
1083 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1084 if (ssl_key)
1085 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1086 if (ssl_key_type)
1087 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1088 if (ssl_capath)
1089 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1090 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1091 if (ssl_pinnedkey)
1092 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1093 #endif
1094 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1095 !http_schannel_use_ssl_cainfo) {
1096 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1097 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1098 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1099 #endif
1100 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1101 if (ssl_cainfo)
1102 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1103 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1104 if (http_proxy_ssl_ca_info)
1105 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1106 #endif
1109 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1110 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1111 curl_low_speed_limit);
1112 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1113 curl_low_speed_time);
1116 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1117 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1119 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1121 struct strbuf buf = STRBUF_INIT;
1123 get_curl_allowed_protocols(0, &buf);
1124 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1125 strbuf_reset(&buf);
1127 get_curl_allowed_protocols(-1, &buf);
1128 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1129 strbuf_release(&buf);
1131 #else
1132 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1133 get_curl_allowed_protocols(0, NULL));
1134 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1135 get_curl_allowed_protocols(-1, NULL));
1136 #endif
1138 if (getenv("GIT_CURL_VERBOSE"))
1139 http_trace_curl_no_data();
1140 setup_curl_trace(result);
1141 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1142 trace_curl_data = 0;
1143 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1144 trace_curl_redact = 0;
1146 curl_easy_setopt(result, CURLOPT_USERAGENT,
1147 user_agent ? user_agent : git_user_agent());
1149 if (curl_ftp_no_epsv)
1150 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1152 if (curl_ssl_try)
1153 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1156 * CURL also examines these variables as a fallback; but we need to query
1157 * them here in order to decide whether to prompt for missing password (cf.
1158 * init_curl_proxy_auth()).
1160 * Unlike many other common environment variables, these are historically
1161 * lowercase only. It appears that CURL did not know this and implemented
1162 * only uppercase variants, which was later corrected to take both - with
1163 * the exception of http_proxy, which is lowercase only also in CURL. As
1164 * the lowercase versions are the historical quasi-standard, they take
1165 * precedence here, as in CURL.
1167 if (!curl_http_proxy) {
1168 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1169 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1170 var_override(&curl_http_proxy, getenv("https_proxy"));
1171 } else {
1172 var_override(&curl_http_proxy, getenv("http_proxy"));
1174 if (!curl_http_proxy) {
1175 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1176 var_override(&curl_http_proxy, getenv("all_proxy"));
1180 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1182 * Handle case with the empty http.proxy value here to keep
1183 * common code clean.
1184 * NB: empty option disables proxying at all.
1186 curl_easy_setopt(result, CURLOPT_PROXY, "");
1187 } else if (curl_http_proxy) {
1188 if (starts_with(curl_http_proxy, "socks5h"))
1189 curl_easy_setopt(result,
1190 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1191 else if (starts_with(curl_http_proxy, "socks5"))
1192 curl_easy_setopt(result,
1193 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1194 else if (starts_with(curl_http_proxy, "socks4a"))
1195 curl_easy_setopt(result,
1196 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1197 else if (starts_with(curl_http_proxy, "socks"))
1198 curl_easy_setopt(result,
1199 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1200 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1201 else if (starts_with(curl_http_proxy, "https")) {
1202 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1204 if (http_proxy_ssl_cert)
1205 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1207 if (http_proxy_ssl_key)
1208 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1210 if (has_proxy_cert_password())
1211 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1213 #endif
1214 if (strstr(curl_http_proxy, "://"))
1215 credential_from_url(&proxy_auth, curl_http_proxy);
1216 else {
1217 struct strbuf url = STRBUF_INIT;
1218 strbuf_addf(&url, "http://%s", curl_http_proxy);
1219 credential_from_url(&proxy_auth, url.buf);
1220 strbuf_release(&url);
1223 if (!proxy_auth.host)
1224 die("Invalid proxy URL '%s'", curl_http_proxy);
1226 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1227 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1228 var_override(&curl_no_proxy, getenv("no_proxy"));
1229 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1231 init_curl_proxy_auth(result);
1233 set_curl_keepalive(result);
1235 return result;
1238 static void set_from_env(char **var, const char *envname)
1240 const char *val = getenv(envname);
1241 if (val) {
1242 FREE_AND_NULL(*var);
1243 *var = xstrdup(val);
1247 void http_init(struct remote *remote, const char *url, int proactive_auth)
1249 char *low_speed_limit;
1250 char *low_speed_time;
1251 char *normalized_url;
1252 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1254 config.section = "http";
1255 config.key = NULL;
1256 config.collect_fn = http_options;
1257 config.cascade_fn = git_default_config;
1258 config.cb = NULL;
1260 http_is_verbose = 0;
1261 normalized_url = url_normalize(url, &config.url);
1263 git_config(urlmatch_config_entry, &config);
1264 free(normalized_url);
1265 string_list_clear(&config.vars, 1);
1267 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1268 if (http_ssl_backend) {
1269 const curl_ssl_backend **backends;
1270 struct strbuf buf = STRBUF_INIT;
1271 int i;
1273 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1274 case CURLSSLSET_UNKNOWN_BACKEND:
1275 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1276 "Supported SSL backends:"),
1277 http_ssl_backend);
1278 for (i = 0; backends[i]; i++)
1279 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1280 die("%s", buf.buf);
1281 case CURLSSLSET_NO_BACKENDS:
1282 die(_("Could not set SSL backend to '%s': "
1283 "cURL was built without SSL backends"),
1284 http_ssl_backend);
1285 case CURLSSLSET_TOO_LATE:
1286 die(_("Could not set SSL backend to '%s': already set"),
1287 http_ssl_backend);
1288 case CURLSSLSET_OK:
1289 break; /* Okay! */
1292 #endif
1294 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1295 die("curl_global_init failed");
1297 http_proactive_auth = proactive_auth;
1299 if (remote && remote->http_proxy)
1300 curl_http_proxy = xstrdup(remote->http_proxy);
1302 if (remote)
1303 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1305 pragma_header = curl_slist_append(http_copy_default_headers(),
1306 "Pragma: no-cache");
1309 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1310 if (http_max_requests)
1311 max_requests = atoi(http_max_requests);
1314 curlm = curl_multi_init();
1315 if (!curlm)
1316 die("curl_multi_init failed");
1318 if (getenv("GIT_SSL_NO_VERIFY"))
1319 curl_ssl_verify = 0;
1321 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1322 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1323 set_from_env(&ssl_key, "GIT_SSL_KEY");
1324 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1325 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1326 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1328 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1330 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1331 if (low_speed_limit)
1332 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1333 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1334 if (low_speed_time)
1335 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1337 if (curl_ssl_verify == -1)
1338 curl_ssl_verify = 1;
1340 curl_session_count = 0;
1341 if (max_requests < 1)
1342 max_requests = DEFAULT_MAX_REQUESTS;
1344 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1345 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1346 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1348 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1349 proxy_ssl_cert_password_required = 1;
1351 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1352 curl_ftp_no_epsv = 1;
1354 if (url) {
1355 credential_from_url(&http_auth, url);
1356 if (!ssl_cert_password_required &&
1357 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1358 starts_with(url, "https://"))
1359 ssl_cert_password_required = 1;
1362 curl_default = get_curl_handle();
1365 void http_cleanup(void)
1367 struct active_request_slot *slot = active_queue_head;
1369 while (slot != NULL) {
1370 struct active_request_slot *next = slot->next;
1371 if (slot->curl) {
1372 xmulti_remove_handle(slot);
1373 curl_easy_cleanup(slot->curl);
1375 free(slot);
1376 slot = next;
1378 active_queue_head = NULL;
1380 curl_easy_cleanup(curl_default);
1382 curl_multi_cleanup(curlm);
1383 curl_global_cleanup();
1385 string_list_clear(&extra_http_headers, 0);
1387 curl_slist_free_all(pragma_header);
1388 pragma_header = NULL;
1390 curl_slist_free_all(host_resolutions);
1391 host_resolutions = NULL;
1393 if (curl_http_proxy) {
1394 free((void *)curl_http_proxy);
1395 curl_http_proxy = NULL;
1398 if (proxy_auth.password) {
1399 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1400 FREE_AND_NULL(proxy_auth.password);
1403 free((void *)curl_proxyuserpwd);
1404 curl_proxyuserpwd = NULL;
1406 free((void *)http_proxy_authmethod);
1407 http_proxy_authmethod = NULL;
1409 if (cert_auth.password) {
1410 memset(cert_auth.password, 0, strlen(cert_auth.password));
1411 FREE_AND_NULL(cert_auth.password);
1413 ssl_cert_password_required = 0;
1415 if (proxy_cert_auth.password) {
1416 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1417 FREE_AND_NULL(proxy_cert_auth.password);
1419 proxy_ssl_cert_password_required = 0;
1421 FREE_AND_NULL(cached_accept_language);
1424 struct active_request_slot *get_active_slot(void)
1426 struct active_request_slot *slot = active_queue_head;
1427 struct active_request_slot *newslot;
1429 int num_transfers;
1431 /* Wait for a slot to open up if the queue is full */
1432 while (active_requests >= max_requests) {
1433 curl_multi_perform(curlm, &num_transfers);
1434 if (num_transfers < active_requests)
1435 process_curl_messages();
1438 while (slot != NULL && slot->in_use)
1439 slot = slot->next;
1441 if (!slot) {
1442 newslot = xmalloc(sizeof(*newslot));
1443 newslot->curl = NULL;
1444 newslot->in_use = 0;
1445 newslot->next = NULL;
1447 slot = active_queue_head;
1448 if (!slot) {
1449 active_queue_head = newslot;
1450 } else {
1451 while (slot->next != NULL)
1452 slot = slot->next;
1453 slot->next = newslot;
1455 slot = newslot;
1458 if (!slot->curl) {
1459 slot->curl = curl_easy_duphandle(curl_default);
1460 curl_session_count++;
1463 active_requests++;
1464 slot->in_use = 1;
1465 slot->results = NULL;
1466 slot->finished = NULL;
1467 slot->callback_data = NULL;
1468 slot->callback_func = NULL;
1469 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1470 if (curl_save_cookies)
1471 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1472 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1473 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1474 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1475 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1476 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1477 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1478 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1479 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, -1L);
1480 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1481 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1482 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1483 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1486 * Default following to off unless "ALWAYS" is configured; this gives
1487 * callers a sane starting point, and they can tweak for individual
1488 * HTTP_FOLLOW_* cases themselves.
1490 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1491 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1492 else
1493 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1495 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1496 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1497 if (http_auth.password || http_auth.credential || curl_empty_auth_enabled())
1498 init_curl_http_auth(slot->curl);
1500 return slot;
1503 int start_active_slot(struct active_request_slot *slot)
1505 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1506 int num_transfers;
1508 if (curlm_result != CURLM_OK &&
1509 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1510 warning("curl_multi_add_handle failed: %s",
1511 curl_multi_strerror(curlm_result));
1512 active_requests--;
1513 slot->in_use = 0;
1514 return 0;
1518 * We know there must be something to do, since we just added
1519 * something.
1521 curl_multi_perform(curlm, &num_transfers);
1522 return 1;
1525 struct fill_chain {
1526 void *data;
1527 int (*fill)(void *);
1528 struct fill_chain *next;
1531 static struct fill_chain *fill_cfg;
1533 void add_fill_function(void *data, int (*fill)(void *))
1535 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1536 struct fill_chain **linkp = &fill_cfg;
1537 new_fill->data = data;
1538 new_fill->fill = fill;
1539 new_fill->next = NULL;
1540 while (*linkp)
1541 linkp = &(*linkp)->next;
1542 *linkp = new_fill;
1545 void fill_active_slots(void)
1547 struct active_request_slot *slot = active_queue_head;
1549 while (active_requests < max_requests) {
1550 struct fill_chain *fill;
1551 for (fill = fill_cfg; fill; fill = fill->next)
1552 if (fill->fill(fill->data))
1553 break;
1555 if (!fill)
1556 break;
1559 while (slot != NULL) {
1560 if (!slot->in_use && slot->curl != NULL
1561 && curl_session_count > min_curl_sessions) {
1562 curl_easy_cleanup(slot->curl);
1563 slot->curl = NULL;
1564 curl_session_count--;
1566 slot = slot->next;
1570 void step_active_slots(void)
1572 int num_transfers;
1573 CURLMcode curlm_result;
1575 do {
1576 curlm_result = curl_multi_perform(curlm, &num_transfers);
1577 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1578 if (num_transfers < active_requests) {
1579 process_curl_messages();
1580 fill_active_slots();
1584 void run_active_slot(struct active_request_slot *slot)
1586 fd_set readfds;
1587 fd_set writefds;
1588 fd_set excfds;
1589 int max_fd;
1590 struct timeval select_timeout;
1591 int finished = 0;
1593 slot->finished = &finished;
1594 while (!finished) {
1595 step_active_slots();
1597 if (slot->in_use) {
1598 long curl_timeout;
1599 curl_multi_timeout(curlm, &curl_timeout);
1600 if (curl_timeout == 0) {
1601 continue;
1602 } else if (curl_timeout == -1) {
1603 select_timeout.tv_sec = 0;
1604 select_timeout.tv_usec = 50000;
1605 } else {
1606 select_timeout.tv_sec = curl_timeout / 1000;
1607 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1610 max_fd = -1;
1611 FD_ZERO(&readfds);
1612 FD_ZERO(&writefds);
1613 FD_ZERO(&excfds);
1614 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1617 * It can happen that curl_multi_timeout returns a pathologically
1618 * long timeout when curl_multi_fdset returns no file descriptors
1619 * to read. See commit message for more details.
1621 if (max_fd < 0 &&
1622 (select_timeout.tv_sec > 0 ||
1623 select_timeout.tv_usec > 50000)) {
1624 select_timeout.tv_sec = 0;
1625 select_timeout.tv_usec = 50000;
1628 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1633 * The value of slot->finished we set before the loop was used
1634 * to set our "finished" variable when our request completed.
1636 * 1. The slot may not have been reused for another requst
1637 * yet, in which case it still has &finished.
1639 * 2. The slot may already be in-use to serve another request,
1640 * which can further be divided into two cases:
1642 * (a) If call run_active_slot() hasn't been called for that
1643 * other request, slot->finished would have been cleared
1644 * by get_active_slot() and has NULL.
1646 * (b) If the request did call run_active_slot(), then the
1647 * call would have updated slot->finished at the beginning
1648 * of this function, and with the clearing of the member
1649 * below, we would find that slot->finished is now NULL.
1651 * In all cases, slot->finished has no useful information to
1652 * anybody at this point. Some compilers warn us for
1653 * attempting to smuggle a pointer that is about to become
1654 * invalid, i.e. &finished. We clear it here to assure them.
1656 slot->finished = NULL;
1659 static void release_active_slot(struct active_request_slot *slot)
1661 closedown_active_slot(slot);
1662 if (slot->curl) {
1663 xmulti_remove_handle(slot);
1664 if (curl_session_count > min_curl_sessions) {
1665 curl_easy_cleanup(slot->curl);
1666 slot->curl = NULL;
1667 curl_session_count--;
1670 fill_active_slots();
1673 void finish_all_active_slots(void)
1675 struct active_request_slot *slot = active_queue_head;
1677 while (slot != NULL)
1678 if (slot->in_use) {
1679 run_active_slot(slot);
1680 slot = active_queue_head;
1681 } else {
1682 slot = slot->next;
1686 /* Helpers for modifying and creating URLs */
1687 static inline int needs_quote(int ch)
1689 if (((ch >= 'A') && (ch <= 'Z'))
1690 || ((ch >= 'a') && (ch <= 'z'))
1691 || ((ch >= '0') && (ch <= '9'))
1692 || (ch == '/')
1693 || (ch == '-')
1694 || (ch == '.'))
1695 return 0;
1696 return 1;
1699 static char *quote_ref_url(const char *base, const char *ref)
1701 struct strbuf buf = STRBUF_INIT;
1702 const char *cp;
1703 int ch;
1705 end_url_with_slash(&buf, base);
1707 for (cp = ref; (ch = *cp) != 0; cp++)
1708 if (needs_quote(ch))
1709 strbuf_addf(&buf, "%%%02x", ch);
1710 else
1711 strbuf_addch(&buf, *cp);
1713 return strbuf_detach(&buf, NULL);
1716 void append_remote_object_url(struct strbuf *buf, const char *url,
1717 const char *hex,
1718 int only_two_digit_prefix)
1720 end_url_with_slash(buf, url);
1722 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1723 if (!only_two_digit_prefix)
1724 strbuf_addstr(buf, hex + 2);
1727 char *get_remote_object_url(const char *url, const char *hex,
1728 int only_two_digit_prefix)
1730 struct strbuf buf = STRBUF_INIT;
1731 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1732 return strbuf_detach(&buf, NULL);
1735 void normalize_curl_result(CURLcode *result, long http_code,
1736 char *errorstr, size_t errorlen)
1739 * If we see a failing http code with CURLE_OK, we have turned off
1740 * FAILONERROR (to keep the server's custom error response), and should
1741 * translate the code into failure here.
1743 * Likewise, if we see a redirect (30x code), that means we turned off
1744 * redirect-following, and we should treat the result as an error.
1746 if (*result == CURLE_OK && http_code >= 300) {
1747 *result = CURLE_HTTP_RETURNED_ERROR;
1749 * Normally curl will already have put the "reason phrase"
1750 * from the server into curl_errorstr; unfortunately without
1751 * FAILONERROR it is lost, so we can give only the numeric
1752 * status code.
1754 xsnprintf(errorstr, errorlen,
1755 "The requested URL returned error: %ld",
1756 http_code);
1760 static int handle_curl_result(struct slot_results *results)
1762 normalize_curl_result(&results->curl_result, results->http_code,
1763 curl_errorstr, sizeof(curl_errorstr));
1765 if (results->curl_result == CURLE_OK) {
1766 credential_approve(&http_auth);
1767 credential_approve(&proxy_auth);
1768 credential_approve(&cert_auth);
1769 return HTTP_OK;
1770 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1772 * We can't tell from here whether it's a bad path, bad
1773 * certificate, bad password, or something else wrong
1774 * with the certificate. So we reject the credential to
1775 * avoid caching or saving a bad password.
1777 credential_reject(&cert_auth);
1778 return HTTP_NOAUTH;
1779 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1780 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1781 return HTTP_NOMATCHPUBLICKEY;
1782 #endif
1783 } else if (missing_target(results))
1784 return HTTP_MISSING_TARGET;
1785 else if (results->http_code == 401) {
1786 if ((http_auth.username && http_auth.password) ||\
1787 (http_auth.authtype && http_auth.credential)) {
1788 if (http_auth.multistage) {
1789 credential_clear_secrets(&http_auth);
1790 return HTTP_REAUTH;
1792 credential_reject(&http_auth);
1793 return HTTP_NOAUTH;
1794 } else {
1795 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1796 if (results->auth_avail) {
1797 http_auth_methods &= results->auth_avail;
1798 http_auth_methods_restricted = 1;
1800 return HTTP_REAUTH;
1802 } else {
1803 if (results->http_connectcode == 407)
1804 credential_reject(&proxy_auth);
1805 if (!curl_errorstr[0])
1806 strlcpy(curl_errorstr,
1807 curl_easy_strerror(results->curl_result),
1808 sizeof(curl_errorstr));
1809 return HTTP_ERROR;
1813 int run_one_slot(struct active_request_slot *slot,
1814 struct slot_results *results)
1816 slot->results = results;
1817 if (!start_active_slot(slot)) {
1818 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1819 "failed to start HTTP request");
1820 return HTTP_START_FAILED;
1823 run_active_slot(slot);
1824 return handle_curl_result(results);
1827 struct curl_slist *http_copy_default_headers(void)
1829 struct curl_slist *headers = NULL;
1830 const struct string_list_item *item;
1832 for_each_string_list_item(item, &extra_http_headers)
1833 headers = curl_slist_append(headers, item->string);
1835 return headers;
1838 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1840 char *ptr;
1841 CURLcode ret;
1843 strbuf_reset(buf);
1844 ret = curl_easy_getinfo(curl, info, &ptr);
1845 if (!ret && ptr)
1846 strbuf_addstr(buf, ptr);
1847 return ret;
1851 * Check for and extract a content-type parameter. "raw"
1852 * should be positioned at the start of the potential
1853 * parameter, with any whitespace already removed.
1855 * "name" is the name of the parameter. The value is appended
1856 * to "out".
1858 static int extract_param(const char *raw, const char *name,
1859 struct strbuf *out)
1861 size_t len = strlen(name);
1863 if (strncasecmp(raw, name, len))
1864 return -1;
1865 raw += len;
1867 if (*raw != '=')
1868 return -1;
1869 raw++;
1871 while (*raw && !isspace(*raw) && *raw != ';')
1872 strbuf_addch(out, *raw++);
1873 return 0;
1877 * Extract a normalized version of the content type, with any
1878 * spaces suppressed, all letters lowercased, and no trailing ";"
1879 * or parameters.
1881 * Note that we will silently remove even invalid whitespace. For
1882 * example, "text / plain" is specifically forbidden by RFC 2616,
1883 * but "text/plain" is the only reasonable output, and this keeps
1884 * our code simple.
1886 * If the "charset" argument is not NULL, store the value of any
1887 * charset parameter there.
1889 * Example:
1890 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1891 * "text / plain" -> "text/plain"
1893 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1894 struct strbuf *charset)
1896 const char *p;
1898 strbuf_reset(type);
1899 strbuf_grow(type, raw->len);
1900 for (p = raw->buf; *p; p++) {
1901 if (isspace(*p))
1902 continue;
1903 if (*p == ';') {
1904 p++;
1905 break;
1907 strbuf_addch(type, tolower(*p));
1910 if (!charset)
1911 return;
1913 strbuf_reset(charset);
1914 while (*p) {
1915 while (isspace(*p) || *p == ';')
1916 p++;
1917 if (!extract_param(p, "charset", charset))
1918 return;
1919 while (*p && !isspace(*p))
1920 p++;
1923 if (!charset->len && starts_with(type->buf, "text/"))
1924 strbuf_addstr(charset, "ISO-8859-1");
1927 static void write_accept_language(struct strbuf *buf)
1930 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1931 * that, q-value will be smaller than 0.001, the minimum q-value the
1932 * HTTP specification allows. See
1933 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
1935 const int MAX_DECIMAL_PLACES = 3;
1936 const int MAX_LANGUAGE_TAGS = 1000;
1937 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1938 char **language_tags = NULL;
1939 int num_langs = 0;
1940 const char *s = get_preferred_languages();
1941 int i;
1942 struct strbuf tag = STRBUF_INIT;
1944 /* Don't add Accept-Language header if no language is preferred. */
1945 if (!s)
1946 return;
1949 * Split the colon-separated string of preferred languages into
1950 * language_tags array.
1952 do {
1953 /* collect language tag */
1954 for (; *s && (isalnum(*s) || *s == '_'); s++)
1955 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1957 /* skip .codeset, @modifier and any other unnecessary parts */
1958 while (*s && *s != ':')
1959 s++;
1961 if (tag.len) {
1962 num_langs++;
1963 REALLOC_ARRAY(language_tags, num_langs);
1964 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1965 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1966 break;
1968 } while (*s++);
1970 /* write Accept-Language header into buf */
1971 if (num_langs) {
1972 int last_buf_len = 0;
1973 int max_q;
1974 int decimal_places;
1975 char q_format[32];
1977 /* add '*' */
1978 REALLOC_ARRAY(language_tags, num_langs + 1);
1979 language_tags[num_langs++] = xstrdup("*");
1981 /* compute decimal_places */
1982 for (max_q = 1, decimal_places = 0;
1983 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1984 decimal_places++, max_q *= 10)
1987 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1989 strbuf_addstr(buf, "Accept-Language: ");
1991 for (i = 0; i < num_langs; i++) {
1992 if (i > 0)
1993 strbuf_addstr(buf, ", ");
1995 strbuf_addstr(buf, language_tags[i]);
1997 if (i > 0)
1998 strbuf_addf(buf, q_format, max_q - i);
2000 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
2001 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
2002 break;
2005 last_buf_len = buf->len;
2009 for (i = 0; i < num_langs; i++)
2010 free(language_tags[i]);
2011 free(language_tags);
2015 * Get an Accept-Language header which indicates user's preferred languages.
2017 * Examples:
2018 * LANGUAGE= -> ""
2019 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
2020 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
2021 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
2022 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
2023 * LANGUAGE= LANG=C -> ""
2025 const char *http_get_accept_language_header(void)
2027 if (!cached_accept_language) {
2028 struct strbuf buf = STRBUF_INIT;
2029 write_accept_language(&buf);
2030 if (buf.len > 0)
2031 cached_accept_language = strbuf_detach(&buf, NULL);
2034 return cached_accept_language;
2037 static void http_opt_request_remainder(CURL *curl, off_t pos)
2039 char buf[128];
2040 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2041 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2044 /* http_request() targets */
2045 #define HTTP_REQUEST_STRBUF 0
2046 #define HTTP_REQUEST_FILE 1
2048 static int http_request(const char *url,
2049 void *result, int target,
2050 const struct http_get_options *options)
2052 struct active_request_slot *slot;
2053 struct slot_results results;
2054 struct curl_slist *headers = http_copy_default_headers();
2055 struct strbuf buf = STRBUF_INIT;
2056 const char *accept_language;
2057 int ret;
2059 slot = get_active_slot();
2060 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2062 if (!result) {
2063 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2064 } else {
2065 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2066 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2068 if (target == HTTP_REQUEST_FILE) {
2069 off_t posn = ftello(result);
2070 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2071 fwrite);
2072 if (posn > 0)
2073 http_opt_request_remainder(slot->curl, posn);
2074 } else
2075 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2076 fwrite_buffer);
2079 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2081 accept_language = http_get_accept_language_header();
2083 if (accept_language)
2084 headers = curl_slist_append(headers, accept_language);
2086 strbuf_addstr(&buf, "Pragma:");
2087 if (options && options->no_cache)
2088 strbuf_addstr(&buf, " no-cache");
2089 if (options && options->initial_request &&
2090 http_follow_config == HTTP_FOLLOW_INITIAL)
2091 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2093 headers = curl_slist_append(headers, buf.buf);
2095 /* Add additional headers here */
2096 if (options && options->extra_headers) {
2097 const struct string_list_item *item;
2098 if (options && options->extra_headers) {
2099 for_each_string_list_item(item, options->extra_headers) {
2100 headers = curl_slist_append(headers, item->string);
2105 headers = http_append_auth_header(&http_auth, headers);
2107 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2108 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2109 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2110 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2112 ret = run_one_slot(slot, &results);
2114 if (options && options->content_type) {
2115 struct strbuf raw = STRBUF_INIT;
2116 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2117 extract_content_type(&raw, options->content_type,
2118 options->charset);
2119 strbuf_release(&raw);
2122 if (options && options->effective_url)
2123 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2124 options->effective_url);
2126 curl_slist_free_all(headers);
2127 strbuf_release(&buf);
2129 return ret;
2133 * Update the "base" url to a more appropriate value, as deduced by
2134 * redirects seen when requesting a URL starting with "url".
2136 * The "asked" parameter is a URL that we asked curl to access, and must begin
2137 * with "base".
2139 * The "got" parameter is the URL that curl reported to us as where we ended
2140 * up.
2142 * Returns 1 if we updated the base url, 0 otherwise.
2144 * Our basic strategy is to compare "base" and "asked" to find the bits
2145 * specific to our request. We then strip those bits off of "got" to yield the
2146 * new base. So for example, if our base is "http://example.com/foo.git",
2147 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2148 * with "https://other.example.com/foo.git/info/refs". We would want the
2149 * new URL to become "https://other.example.com/foo.git".
2151 * Note that this assumes a sane redirect scheme. It's entirely possible
2152 * in the example above to end up at a URL that does not even end in
2153 * "info/refs". In such a case we die. There's not much we can do, such a
2154 * scheme is unlikely to represent a real git repository, and failing to
2155 * rewrite the base opens options for malicious redirects to do funny things.
2157 static int update_url_from_redirect(struct strbuf *base,
2158 const char *asked,
2159 const struct strbuf *got)
2161 const char *tail;
2162 size_t new_len;
2164 if (!strcmp(asked, got->buf))
2165 return 0;
2167 if (!skip_prefix(asked, base->buf, &tail))
2168 BUG("update_url_from_redirect: %s is not a superset of %s",
2169 asked, base->buf);
2171 new_len = got->len;
2172 if (!strip_suffix_mem(got->buf, &new_len, tail))
2173 die(_("unable to update url base from redirection:\n"
2174 " asked for: %s\n"
2175 " redirect: %s"),
2176 asked, got->buf);
2178 strbuf_reset(base);
2179 strbuf_add(base, got->buf, new_len);
2181 return 1;
2184 static int http_request_reauth(const char *url,
2185 void *result, int target,
2186 struct http_get_options *options)
2188 int i = 3;
2189 int ret = http_request(url, result, target, options);
2191 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2192 return ret;
2194 if (options && options->effective_url && options->base_url) {
2195 if (update_url_from_redirect(options->base_url,
2196 url, options->effective_url)) {
2197 credential_from_url(&http_auth, options->base_url->buf);
2198 url = options->effective_url->buf;
2202 while (ret == HTTP_REAUTH && --i) {
2204 * The previous request may have put cruft into our output stream; we
2205 * should clear it out before making our next request.
2207 switch (target) {
2208 case HTTP_REQUEST_STRBUF:
2209 strbuf_reset(result);
2210 break;
2211 case HTTP_REQUEST_FILE:
2212 if (fflush(result)) {
2213 error_errno("unable to flush a file");
2214 return HTTP_START_FAILED;
2216 rewind(result);
2217 if (ftruncate(fileno(result), 0) < 0) {
2218 error_errno("unable to truncate a file");
2219 return HTTP_START_FAILED;
2221 break;
2222 default:
2223 BUG("Unknown http_request target");
2226 credential_fill(&http_auth, 1);
2228 ret = http_request(url, result, target, options);
2230 return ret;
2233 int http_get_strbuf(const char *url,
2234 struct strbuf *result,
2235 struct http_get_options *options)
2237 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2241 * Downloads a URL and stores the result in the given file.
2243 * If a previous interrupted download is detected (i.e. a previous temporary
2244 * file is still around) the download is resumed.
2246 int http_get_file(const char *url, const char *filename,
2247 struct http_get_options *options)
2249 int ret;
2250 struct strbuf tmpfile = STRBUF_INIT;
2251 FILE *result;
2253 strbuf_addf(&tmpfile, "%s.temp", filename);
2254 result = fopen(tmpfile.buf, "a");
2255 if (!result) {
2256 error("Unable to open local file %s", tmpfile.buf);
2257 ret = HTTP_ERROR;
2258 goto cleanup;
2261 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2262 fclose(result);
2264 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2265 ret = HTTP_ERROR;
2266 cleanup:
2267 strbuf_release(&tmpfile);
2268 return ret;
2271 int http_fetch_ref(const char *base, struct ref *ref)
2273 struct http_get_options options = {0};
2274 char *url;
2275 struct strbuf buffer = STRBUF_INIT;
2276 int ret = -1;
2278 options.no_cache = 1;
2280 url = quote_ref_url(base, ref->name);
2281 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2282 strbuf_rtrim(&buffer);
2283 if (buffer.len == the_hash_algo->hexsz)
2284 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2285 else if (starts_with(buffer.buf, "ref: ")) {
2286 ref->symref = xstrdup(buffer.buf + 5);
2287 ret = 0;
2291 strbuf_release(&buffer);
2292 free(url);
2293 return ret;
2296 /* Helpers for fetching packs */
2297 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2299 char *url, *tmp;
2300 struct strbuf buf = STRBUF_INIT;
2302 if (http_is_verbose)
2303 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2305 end_url_with_slash(&buf, base_url);
2306 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2307 url = strbuf_detach(&buf, NULL);
2309 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2310 tmp = strbuf_detach(&buf, NULL);
2312 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2313 error("Unable to get pack index %s", url);
2314 FREE_AND_NULL(tmp);
2317 free(url);
2318 return tmp;
2321 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2322 unsigned char *sha1, const char *base_url)
2324 struct packed_git *new_pack;
2325 char *tmp_idx = NULL;
2326 int ret;
2328 if (has_pack_index(sha1)) {
2329 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2330 if (!new_pack)
2331 return -1; /* parse_pack_index() already issued error message */
2332 goto add_pack;
2335 tmp_idx = fetch_pack_index(sha1, base_url);
2336 if (!tmp_idx)
2337 return -1;
2339 new_pack = parse_pack_index(sha1, tmp_idx);
2340 if (!new_pack) {
2341 unlink(tmp_idx);
2342 free(tmp_idx);
2344 return -1; /* parse_pack_index() already issued error message */
2347 ret = verify_pack_index(new_pack);
2348 if (!ret) {
2349 close_pack_index(new_pack);
2350 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2352 free(tmp_idx);
2353 if (ret)
2354 return -1;
2356 add_pack:
2357 new_pack->next = *packs_head;
2358 *packs_head = new_pack;
2359 return 0;
2362 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2364 struct http_get_options options = {0};
2365 int ret = 0;
2366 char *url;
2367 const char *data;
2368 struct strbuf buf = STRBUF_INIT;
2369 struct object_id oid;
2371 end_url_with_slash(&buf, base_url);
2372 strbuf_addstr(&buf, "objects/info/packs");
2373 url = strbuf_detach(&buf, NULL);
2375 options.no_cache = 1;
2376 ret = http_get_strbuf(url, &buf, &options);
2377 if (ret != HTTP_OK)
2378 goto cleanup;
2380 data = buf.buf;
2381 while (*data) {
2382 if (skip_prefix(data, "P pack-", &data) &&
2383 !parse_oid_hex(data, &oid, &data) &&
2384 skip_prefix(data, ".pack", &data) &&
2385 (*data == '\n' || *data == '\0')) {
2386 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2387 } else {
2388 data = strchrnul(data, '\n');
2390 if (*data)
2391 data++; /* skip past newline */
2394 cleanup:
2395 free(url);
2396 return ret;
2399 void release_http_pack_request(struct http_pack_request *preq)
2401 if (preq->packfile) {
2402 fclose(preq->packfile);
2403 preq->packfile = NULL;
2405 preq->slot = NULL;
2406 strbuf_release(&preq->tmpfile);
2407 curl_slist_free_all(preq->headers);
2408 free(preq->url);
2409 free(preq);
2412 static const char *default_index_pack_args[] =
2413 {"index-pack", "--stdin", NULL};
2415 int finish_http_pack_request(struct http_pack_request *preq)
2417 struct child_process ip = CHILD_PROCESS_INIT;
2418 int tmpfile_fd;
2419 int ret = 0;
2421 fclose(preq->packfile);
2422 preq->packfile = NULL;
2424 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2426 ip.git_cmd = 1;
2427 ip.in = tmpfile_fd;
2428 strvec_pushv(&ip.args, preq->index_pack_args ?
2429 preq->index_pack_args :
2430 default_index_pack_args);
2432 if (preq->preserve_index_pack_stdout)
2433 ip.out = 0;
2434 else
2435 ip.no_stdout = 1;
2437 if (run_command(&ip)) {
2438 ret = -1;
2439 goto cleanup;
2442 cleanup:
2443 close(tmpfile_fd);
2444 unlink(preq->tmpfile.buf);
2445 return ret;
2448 void http_install_packfile(struct packed_git *p,
2449 struct packed_git **list_to_remove_from)
2451 struct packed_git **lst = list_to_remove_from;
2453 while (*lst != p)
2454 lst = &((*lst)->next);
2455 *lst = (*lst)->next;
2457 install_packed_git(the_repository, p);
2460 struct http_pack_request *new_http_pack_request(
2461 const unsigned char *packed_git_hash, const char *base_url) {
2463 struct strbuf buf = STRBUF_INIT;
2465 end_url_with_slash(&buf, base_url);
2466 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2467 hash_to_hex(packed_git_hash));
2468 return new_direct_http_pack_request(packed_git_hash,
2469 strbuf_detach(&buf, NULL));
2472 struct http_pack_request *new_direct_http_pack_request(
2473 const unsigned char *packed_git_hash, char *url)
2475 off_t prev_posn = 0;
2476 struct http_pack_request *preq;
2478 CALLOC_ARRAY(preq, 1);
2479 strbuf_init(&preq->tmpfile, 0);
2481 preq->url = url;
2483 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2484 preq->packfile = fopen(preq->tmpfile.buf, "a");
2485 if (!preq->packfile) {
2486 error("Unable to open local file %s for pack",
2487 preq->tmpfile.buf);
2488 goto abort;
2491 preq->slot = get_active_slot();
2492 preq->headers = object_request_headers();
2493 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2494 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2495 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2496 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER, preq->headers);
2499 * If there is data present from a previous transfer attempt,
2500 * resume where it left off
2502 prev_posn = ftello(preq->packfile);
2503 if (prev_posn>0) {
2504 if (http_is_verbose)
2505 fprintf(stderr,
2506 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2507 hash_to_hex(packed_git_hash),
2508 (uintmax_t)prev_posn);
2509 http_opt_request_remainder(preq->slot->curl, prev_posn);
2512 return preq;
2514 abort:
2515 strbuf_release(&preq->tmpfile);
2516 free(preq->url);
2517 free(preq);
2518 return NULL;
2521 /* Helpers for fetching objects (loose) */
2522 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2523 void *data)
2525 unsigned char expn[4096];
2526 size_t size = eltsize * nmemb;
2527 int posn = 0;
2528 struct http_object_request *freq = data;
2529 struct active_request_slot *slot = freq->slot;
2531 if (slot) {
2532 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2533 &slot->http_code);
2534 if (c != CURLE_OK)
2535 BUG("curl_easy_getinfo for HTTP code failed: %s",
2536 curl_easy_strerror(c));
2537 if (slot->http_code >= 300)
2538 return nmemb;
2541 do {
2542 ssize_t retval = xwrite(freq->localfile,
2543 (char *) ptr + posn, size - posn);
2544 if (retval < 0)
2545 return posn / eltsize;
2546 posn += retval;
2547 } while (posn < size);
2549 freq->stream.avail_in = size;
2550 freq->stream.next_in = (void *)ptr;
2551 do {
2552 freq->stream.next_out = expn;
2553 freq->stream.avail_out = sizeof(expn);
2554 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2555 the_hash_algo->update_fn(&freq->c, expn,
2556 sizeof(expn) - freq->stream.avail_out);
2557 } while (freq->stream.avail_in && freq->zret == Z_OK);
2558 return nmemb;
2561 struct http_object_request *new_http_object_request(const char *base_url,
2562 const struct object_id *oid)
2564 char *hex = oid_to_hex(oid);
2565 struct strbuf filename = STRBUF_INIT;
2566 struct strbuf prevfile = STRBUF_INIT;
2567 int prevlocal;
2568 char prev_buf[PREV_BUF_SIZE];
2569 ssize_t prev_read = 0;
2570 off_t prev_posn = 0;
2571 struct http_object_request *freq;
2573 CALLOC_ARRAY(freq, 1);
2574 strbuf_init(&freq->tmpfile, 0);
2575 oidcpy(&freq->oid, oid);
2576 freq->localfile = -1;
2578 loose_object_path(the_repository, &filename, oid);
2579 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2581 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2582 unlink_or_warn(prevfile.buf);
2583 rename(freq->tmpfile.buf, prevfile.buf);
2584 unlink_or_warn(freq->tmpfile.buf);
2585 strbuf_release(&filename);
2587 if (freq->localfile != -1)
2588 error("fd leakage in start: %d", freq->localfile);
2589 freq->localfile = open(freq->tmpfile.buf,
2590 O_WRONLY | O_CREAT | O_EXCL, 0666);
2592 * This could have failed due to the "lazy directory creation";
2593 * try to mkdir the last path component.
2595 if (freq->localfile < 0 && errno == ENOENT) {
2596 char *dir = strrchr(freq->tmpfile.buf, '/');
2597 if (dir) {
2598 *dir = 0;
2599 mkdir(freq->tmpfile.buf, 0777);
2600 *dir = '/';
2602 freq->localfile = open(freq->tmpfile.buf,
2603 O_WRONLY | O_CREAT | O_EXCL, 0666);
2606 if (freq->localfile < 0) {
2607 error_errno("Couldn't create temporary file %s",
2608 freq->tmpfile.buf);
2609 goto abort;
2612 git_inflate_init(&freq->stream);
2614 the_hash_algo->init_fn(&freq->c);
2616 freq->url = get_remote_object_url(base_url, hex, 0);
2619 * If a previous temp file is present, process what was already
2620 * fetched.
2622 prevlocal = open(prevfile.buf, O_RDONLY);
2623 if (prevlocal != -1) {
2624 do {
2625 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2626 if (prev_read>0) {
2627 if (fwrite_sha1_file(prev_buf,
2629 prev_read,
2630 freq) == prev_read) {
2631 prev_posn += prev_read;
2632 } else {
2633 prev_read = -1;
2636 } while (prev_read > 0);
2637 close(prevlocal);
2639 unlink_or_warn(prevfile.buf);
2640 strbuf_release(&prevfile);
2643 * Reset inflate/SHA1 if there was an error reading the previous temp
2644 * file; also rewind to the beginning of the local file.
2646 if (prev_read == -1) {
2647 memset(&freq->stream, 0, sizeof(freq->stream));
2648 git_inflate_init(&freq->stream);
2649 the_hash_algo->init_fn(&freq->c);
2650 if (prev_posn>0) {
2651 prev_posn = 0;
2652 lseek(freq->localfile, 0, SEEK_SET);
2653 if (ftruncate(freq->localfile, 0) < 0) {
2654 error_errno("Couldn't truncate temporary file %s",
2655 freq->tmpfile.buf);
2656 goto abort;
2661 freq->slot = get_active_slot();
2662 freq->headers = object_request_headers();
2664 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2665 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2666 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2667 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2668 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2669 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, freq->headers);
2672 * If we have successfully processed data from a previous fetch
2673 * attempt, only fetch the data we don't already have.
2675 if (prev_posn>0) {
2676 if (http_is_verbose)
2677 fprintf(stderr,
2678 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2679 hex, (uintmax_t)prev_posn);
2680 http_opt_request_remainder(freq->slot->curl, prev_posn);
2683 return freq;
2685 abort:
2686 strbuf_release(&prevfile);
2687 free(freq->url);
2688 free(freq);
2689 return NULL;
2692 void process_http_object_request(struct http_object_request *freq)
2694 if (!freq->slot)
2695 return;
2696 freq->curl_result = freq->slot->curl_result;
2697 freq->http_code = freq->slot->http_code;
2698 freq->slot = NULL;
2701 int finish_http_object_request(struct http_object_request *freq)
2703 struct stat st;
2704 struct strbuf filename = STRBUF_INIT;
2706 close(freq->localfile);
2707 freq->localfile = -1;
2709 process_http_object_request(freq);
2711 if (freq->http_code == 416) {
2712 warning("requested range invalid; we may already have all the data.");
2713 } else if (freq->curl_result != CURLE_OK) {
2714 if (stat(freq->tmpfile.buf, &st) == 0)
2715 if (st.st_size == 0)
2716 unlink_or_warn(freq->tmpfile.buf);
2717 return -1;
2720 git_inflate_end(&freq->stream);
2721 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2722 if (freq->zret != Z_STREAM_END) {
2723 unlink_or_warn(freq->tmpfile.buf);
2724 return -1;
2726 if (!oideq(&freq->oid, &freq->real_oid)) {
2727 unlink_or_warn(freq->tmpfile.buf);
2728 return -1;
2730 loose_object_path(the_repository, &filename, &freq->oid);
2731 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2732 strbuf_release(&filename);
2734 return freq->rename;
2737 void abort_http_object_request(struct http_object_request *freq)
2739 unlink_or_warn(freq->tmpfile.buf);
2741 release_http_object_request(freq);
2744 void release_http_object_request(struct http_object_request *freq)
2746 if (freq->localfile != -1) {
2747 close(freq->localfile);
2748 freq->localfile = -1;
2750 FREE_AND_NULL(freq->url);
2751 if (freq->slot) {
2752 freq->slot->callback_func = NULL;
2753 freq->slot->callback_data = NULL;
2754 release_active_slot(freq->slot);
2755 freq->slot = NULL;
2757 curl_slist_free_all(freq->headers);
2758 strbuf_release(&freq->tmpfile);