http: use new headers for each object request
[git/gitster.git] / http.c
blob22639b09742a336ef72e8c9f6405294e95f90bb2
1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
3 #include "hex.h"
4 #include "http.h"
5 #include "config.h"
6 #include "pack.h"
7 #include "run-command.h"
8 #include "url.h"
9 #include "urlmatch.h"
10 #include "credential.h"
11 #include "version.h"
12 #include "pkt-line.h"
13 #include "gettext.h"
14 #include "trace.h"
15 #include "transport.h"
16 #include "packfile.h"
17 #include "string-list.h"
18 #include "object-file.h"
19 #include "object-store-ll.h"
21 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
22 static int trace_curl_data = 1;
23 static int trace_curl_redact = 1;
24 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
25 int active_requests;
26 int http_is_verbose;
27 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
29 static int min_curl_sessions = 1;
30 static int curl_session_count;
31 static int max_requests = -1;
32 static CURLM *curlm;
33 static CURL *curl_default;
35 #define PREV_BUF_SIZE 4096
37 char curl_errorstr[CURL_ERROR_SIZE];
39 static int curl_ssl_verify = -1;
40 static int curl_ssl_try;
41 static const char *curl_http_version = NULL;
42 static const char *ssl_cert;
43 static const char *ssl_cert_type;
44 static const char *ssl_cipherlist;
45 static const char *ssl_version;
46 static struct {
47 const char *name;
48 long ssl_version;
49 } sslversions[] = {
50 { "sslv2", CURL_SSLVERSION_SSLv2 },
51 { "sslv3", CURL_SSLVERSION_SSLv3 },
52 { "tlsv1", CURL_SSLVERSION_TLSv1 },
53 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
54 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
55 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
56 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
57 #endif
58 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
59 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
60 #endif
62 static const char *ssl_key;
63 static const char *ssl_key_type;
64 static const char *ssl_capath;
65 static const char *curl_no_proxy;
66 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
67 static const char *ssl_pinnedkey;
68 #endif
69 static const char *ssl_cainfo;
70 static long curl_low_speed_limit = -1;
71 static long curl_low_speed_time = -1;
72 static int curl_ftp_no_epsv;
73 static const char *curl_http_proxy;
74 static const char *http_proxy_authmethod;
76 static const char *http_proxy_ssl_cert;
77 static const char *http_proxy_ssl_key;
78 static const char *http_proxy_ssl_ca_info;
79 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
80 static int proxy_ssl_cert_password_required;
82 static struct {
83 const char *name;
84 long curlauth_param;
85 } proxy_authmethods[] = {
86 { "basic", CURLAUTH_BASIC },
87 { "digest", CURLAUTH_DIGEST },
88 { "negotiate", CURLAUTH_GSSNEGOTIATE },
89 { "ntlm", CURLAUTH_NTLM },
90 { "anyauth", CURLAUTH_ANY },
92 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
93 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
94 * here, too
97 #ifdef CURLGSSAPI_DELEGATION_FLAG
98 static const char *curl_deleg;
99 static struct {
100 const char *name;
101 long curl_deleg_param;
102 } curl_deleg_levels[] = {
103 { "none", CURLGSSAPI_DELEGATION_NONE },
104 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
105 { "always", CURLGSSAPI_DELEGATION_FLAG },
107 #endif
109 static struct credential proxy_auth = CREDENTIAL_INIT;
110 static const char *curl_proxyuserpwd;
111 static const char *curl_cookie_file;
112 static int curl_save_cookies;
113 struct credential http_auth = CREDENTIAL_INIT;
114 static int http_proactive_auth;
115 static const char *user_agent;
116 static int curl_empty_auth = -1;
118 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
120 static struct credential cert_auth = CREDENTIAL_INIT;
121 static int ssl_cert_password_required;
122 static unsigned long http_auth_methods = CURLAUTH_ANY;
123 static int http_auth_methods_restricted;
124 /* Modes for which empty_auth cannot actually help us. */
125 static unsigned long empty_auth_useless =
126 CURLAUTH_BASIC
127 | CURLAUTH_DIGEST_IE
128 | CURLAUTH_DIGEST;
130 static struct curl_slist *pragma_header;
131 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
133 static struct curl_slist *host_resolutions;
135 static struct active_request_slot *active_queue_head;
137 static char *cached_accept_language;
139 static char *http_ssl_backend;
141 static int http_schannel_check_revoke = 1;
143 * With the backend being set to `schannel`, setting sslCAinfo would override
144 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
145 * by default.
147 static int http_schannel_use_ssl_cainfo;
149 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
151 size_t size = eltsize * nmemb;
152 struct buffer *buffer = buffer_;
154 if (size > buffer->buf.len - buffer->posn)
155 size = buffer->buf.len - buffer->posn;
156 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
157 buffer->posn += size;
159 return size / eltsize;
162 int seek_buffer(void *clientp, curl_off_t offset, int origin)
164 struct buffer *buffer = clientp;
166 if (origin != SEEK_SET)
167 BUG("seek_buffer only handles SEEK_SET");
168 if (offset < 0 || offset >= buffer->buf.len) {
169 error("curl seek would be outside of buffer");
170 return CURL_SEEKFUNC_FAIL;
173 buffer->posn = offset;
174 return CURL_SEEKFUNC_OK;
177 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
179 size_t size = eltsize * nmemb;
180 struct strbuf *buffer = buffer_;
182 strbuf_add(buffer, ptr, size);
183 return nmemb;
187 * A folded header continuation line starts with any number of spaces or
188 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
189 * It is not a continuation line if the line starts with any other character.
191 static inline int is_hdr_continuation(const char *ptr, const size_t size)
193 return size && (*ptr == ' ' || *ptr == '\t');
196 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
198 size_t size = eltsize * nmemb;
199 struct strvec *values = &http_auth.wwwauth_headers;
200 struct strbuf buf = STRBUF_INIT;
201 const char *val;
202 size_t val_len;
205 * Header lines may not come NULL-terminated from libcurl so we must
206 * limit all scans to the maximum length of the header line, or leverage
207 * strbufs for all operations.
209 * In addition, it is possible that header values can be split over
210 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
211 * but older servers may still emit them. A continuation header field
212 * value is identified as starting with a space or horizontal tab.
214 * The formal definition of a header field as given in RFC 7230 is:
216 * header-field = field-name ":" OWS field-value OWS
218 * field-name = token
219 * field-value = *( field-content / obs-fold )
220 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
221 * field-vchar = VCHAR / obs-text
223 * obs-fold = CRLF 1*( SP / HTAB )
224 * ; obsolete line folding
225 * ; see Section 3.2.4
228 /* Start of a new WWW-Authenticate header */
229 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
230 strbuf_add(&buf, val, val_len);
233 * Strip the CRLF that should be present at the end of each
234 * field as well as any trailing or leading whitespace from the
235 * value.
237 strbuf_trim(&buf);
239 strvec_push(values, buf.buf);
240 http_auth.header_is_last_match = 1;
241 goto exit;
245 * This line could be a continuation of the previously matched header
246 * field. If this is the case then we should append this value to the
247 * end of the previously consumed value.
249 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
251 * Trim the CRLF and any leading or trailing from this line.
253 strbuf_add(&buf, ptr, size);
254 strbuf_trim(&buf);
257 * At this point we should always have at least one existing
258 * value, even if it is empty. Do not bother appending the new
259 * value if this continuation header is itself empty.
261 if (!values->nr) {
262 BUG("should have at least one existing header value");
263 } else if (buf.len) {
264 char *prev = xstrdup(values->v[values->nr - 1]);
266 /* Join two non-empty values with a single space. */
267 const char *const sp = *prev ? " " : "";
269 strvec_pop(values);
270 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
271 free(prev);
274 goto exit;
277 /* Not a continuation of a previously matched auth header line. */
278 http_auth.header_is_last_match = 0;
281 * If this is a HTTP status line and not a header field, this signals
282 * a different HTTP response. libcurl writes all the output of all
283 * response headers of all responses, including redirects.
284 * We only care about the last HTTP request response's headers so clear
285 * the existing array.
287 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
288 strvec_clear(values);
290 exit:
291 strbuf_release(&buf);
292 return size;
295 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
296 void *data UNUSED)
298 return nmemb;
301 static struct curl_slist *object_request_headers(void)
303 return curl_slist_append(http_copy_default_headers(), "Pragma:");
306 static void closedown_active_slot(struct active_request_slot *slot)
308 active_requests--;
309 slot->in_use = 0;
312 static void finish_active_slot(struct active_request_slot *slot)
314 closedown_active_slot(slot);
315 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
317 if (slot->finished)
318 (*slot->finished) = 1;
320 /* Store slot results so they can be read after the slot is reused */
321 if (slot->results) {
322 slot->results->curl_result = slot->curl_result;
323 slot->results->http_code = slot->http_code;
324 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
325 &slot->results->auth_avail);
327 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
328 &slot->results->http_connectcode);
331 /* Run callback if appropriate */
332 if (slot->callback_func)
333 slot->callback_func(slot->callback_data);
336 static void xmulti_remove_handle(struct active_request_slot *slot)
338 curl_multi_remove_handle(curlm, slot->curl);
341 static void process_curl_messages(void)
343 int num_messages;
344 struct active_request_slot *slot;
345 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
347 while (curl_message != NULL) {
348 if (curl_message->msg == CURLMSG_DONE) {
349 int curl_result = curl_message->data.result;
350 slot = active_queue_head;
351 while (slot != NULL &&
352 slot->curl != curl_message->easy_handle)
353 slot = slot->next;
354 if (slot) {
355 xmulti_remove_handle(slot);
356 slot->curl_result = curl_result;
357 finish_active_slot(slot);
358 } else {
359 fprintf(stderr, "Received DONE message for unknown request!\n");
361 } else {
362 fprintf(stderr, "Unknown CURL message received: %d\n",
363 (int)curl_message->msg);
365 curl_message = curl_multi_info_read(curlm, &num_messages);
369 static int http_options(const char *var, const char *value,
370 const struct config_context *ctx, void *data)
372 if (!strcmp("http.version", var)) {
373 return git_config_string(&curl_http_version, var, value);
375 if (!strcmp("http.sslverify", var)) {
376 curl_ssl_verify = git_config_bool(var, value);
377 return 0;
379 if (!strcmp("http.sslcipherlist", var))
380 return git_config_string(&ssl_cipherlist, var, value);
381 if (!strcmp("http.sslversion", var))
382 return git_config_string(&ssl_version, var, value);
383 if (!strcmp("http.sslcert", var))
384 return git_config_pathname(&ssl_cert, var, value);
385 if (!strcmp("http.sslcerttype", var))
386 return git_config_string(&ssl_cert_type, var, value);
387 if (!strcmp("http.sslkey", var))
388 return git_config_pathname(&ssl_key, var, value);
389 if (!strcmp("http.sslkeytype", var))
390 return git_config_string(&ssl_key_type, var, value);
391 if (!strcmp("http.sslcapath", var))
392 return git_config_pathname(&ssl_capath, var, value);
393 if (!strcmp("http.sslcainfo", var))
394 return git_config_pathname(&ssl_cainfo, var, value);
395 if (!strcmp("http.sslcertpasswordprotected", var)) {
396 ssl_cert_password_required = git_config_bool(var, value);
397 return 0;
399 if (!strcmp("http.ssltry", var)) {
400 curl_ssl_try = git_config_bool(var, value);
401 return 0;
403 if (!strcmp("http.sslbackend", var)) {
404 free(http_ssl_backend);
405 http_ssl_backend = xstrdup_or_null(value);
406 return 0;
409 if (!strcmp("http.schannelcheckrevoke", var)) {
410 http_schannel_check_revoke = git_config_bool(var, value);
411 return 0;
414 if (!strcmp("http.schannelusesslcainfo", var)) {
415 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
416 return 0;
419 if (!strcmp("http.minsessions", var)) {
420 min_curl_sessions = git_config_int(var, value, ctx->kvi);
421 if (min_curl_sessions > 1)
422 min_curl_sessions = 1;
423 return 0;
425 if (!strcmp("http.maxrequests", var)) {
426 max_requests = git_config_int(var, value, ctx->kvi);
427 return 0;
429 if (!strcmp("http.lowspeedlimit", var)) {
430 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
431 return 0;
433 if (!strcmp("http.lowspeedtime", var)) {
434 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
435 return 0;
438 if (!strcmp("http.noepsv", var)) {
439 curl_ftp_no_epsv = git_config_bool(var, value);
440 return 0;
442 if (!strcmp("http.proxy", var))
443 return git_config_string(&curl_http_proxy, var, value);
445 if (!strcmp("http.proxyauthmethod", var))
446 return git_config_string(&http_proxy_authmethod, var, value);
448 if (!strcmp("http.proxysslcert", var))
449 return git_config_string(&http_proxy_ssl_cert, var, value);
451 if (!strcmp("http.proxysslkey", var))
452 return git_config_string(&http_proxy_ssl_key, var, value);
454 if (!strcmp("http.proxysslcainfo", var))
455 return git_config_string(&http_proxy_ssl_ca_info, var, value);
457 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
458 proxy_ssl_cert_password_required = git_config_bool(var, value);
459 return 0;
462 if (!strcmp("http.cookiefile", var))
463 return git_config_pathname(&curl_cookie_file, var, value);
464 if (!strcmp("http.savecookies", var)) {
465 curl_save_cookies = git_config_bool(var, value);
466 return 0;
469 if (!strcmp("http.postbuffer", var)) {
470 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
471 if (http_post_buffer < 0)
472 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
473 if (http_post_buffer < LARGE_PACKET_MAX)
474 http_post_buffer = LARGE_PACKET_MAX;
475 return 0;
478 if (!strcmp("http.useragent", var))
479 return git_config_string(&user_agent, var, value);
481 if (!strcmp("http.emptyauth", var)) {
482 if (value && !strcmp("auto", value))
483 curl_empty_auth = -1;
484 else
485 curl_empty_auth = git_config_bool(var, value);
486 return 0;
489 if (!strcmp("http.delegation", var)) {
490 #ifdef CURLGSSAPI_DELEGATION_FLAG
491 return git_config_string(&curl_deleg, var, value);
492 #else
493 warning(_("Delegation control is not supported with cURL < 7.22.0"));
494 return 0;
495 #endif
498 if (!strcmp("http.pinnedpubkey", var)) {
499 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
500 return git_config_pathname(&ssl_pinnedkey, var, value);
501 #else
502 warning(_("Public key pinning not supported with cURL < 7.39.0"));
503 return 0;
504 #endif
507 if (!strcmp("http.extraheader", var)) {
508 if (!value) {
509 return config_error_nonbool(var);
510 } else if (!*value) {
511 string_list_clear(&extra_http_headers, 0);
512 } else {
513 string_list_append(&extra_http_headers, value);
515 return 0;
518 if (!strcmp("http.curloptresolve", var)) {
519 if (!value) {
520 return config_error_nonbool(var);
521 } else if (!*value) {
522 curl_slist_free_all(host_resolutions);
523 host_resolutions = NULL;
524 } else {
525 host_resolutions = curl_slist_append(host_resolutions, value);
527 return 0;
530 if (!strcmp("http.followredirects", var)) {
531 if (value && !strcmp(value, "initial"))
532 http_follow_config = HTTP_FOLLOW_INITIAL;
533 else if (git_config_bool(var, value))
534 http_follow_config = HTTP_FOLLOW_ALWAYS;
535 else
536 http_follow_config = HTTP_FOLLOW_NONE;
537 return 0;
540 /* Fall back on the default ones */
541 return git_default_config(var, value, ctx, data);
544 static int curl_empty_auth_enabled(void)
546 if (curl_empty_auth >= 0)
547 return curl_empty_auth;
550 * In the automatic case, kick in the empty-auth
551 * hack as long as we would potentially try some
552 * method more exotic than "Basic" or "Digest".
554 * But only do this when this is our second or
555 * subsequent request, as by then we know what
556 * methods are available.
558 if (http_auth_methods_restricted &&
559 (http_auth_methods & ~empty_auth_useless))
560 return 1;
561 return 0;
564 static void init_curl_http_auth(CURL *result)
566 if (!http_auth.username || !*http_auth.username) {
567 if (curl_empty_auth_enabled())
568 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
569 return;
572 credential_fill(&http_auth);
574 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
575 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
578 /* *var must be free-able */
579 static void var_override(const char **var, char *value)
581 if (value) {
582 free((void *)*var);
583 *var = xstrdup(value);
587 static void set_proxyauth_name_password(CURL *result)
589 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
590 proxy_auth.username);
591 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
592 proxy_auth.password);
595 static void init_curl_proxy_auth(CURL *result)
597 if (proxy_auth.username) {
598 if (!proxy_auth.password)
599 credential_fill(&proxy_auth);
600 set_proxyauth_name_password(result);
603 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
605 if (http_proxy_authmethod) {
606 int i;
607 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
608 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
609 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
610 proxy_authmethods[i].curlauth_param);
611 break;
614 if (i == ARRAY_SIZE(proxy_authmethods)) {
615 warning("unsupported proxy authentication method %s: using anyauth",
616 http_proxy_authmethod);
617 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
620 else
621 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
624 static int has_cert_password(void)
626 if (ssl_cert == NULL || ssl_cert_password_required != 1)
627 return 0;
628 if (!cert_auth.password) {
629 cert_auth.protocol = xstrdup("cert");
630 cert_auth.host = xstrdup("");
631 cert_auth.username = xstrdup("");
632 cert_auth.path = xstrdup(ssl_cert);
633 credential_fill(&cert_auth);
635 return 1;
638 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
639 static int has_proxy_cert_password(void)
641 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
642 return 0;
643 if (!proxy_cert_auth.password) {
644 proxy_cert_auth.protocol = xstrdup("cert");
645 proxy_cert_auth.host = xstrdup("");
646 proxy_cert_auth.username = xstrdup("");
647 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
648 credential_fill(&proxy_cert_auth);
650 return 1;
652 #endif
654 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
655 static void set_curl_keepalive(CURL *c)
657 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
660 #else
661 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
663 int ka = 1;
664 int rc;
665 socklen_t len = (socklen_t)sizeof(ka);
667 if (type != CURLSOCKTYPE_IPCXN)
668 return 0;
670 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
671 if (rc < 0)
672 warning_errno("unable to set SO_KEEPALIVE on socket");
674 return CURL_SOCKOPT_OK;
677 static void set_curl_keepalive(CURL *c)
679 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
681 #endif
683 /* Return 1 if redactions have been made, 0 otherwise. */
684 static int redact_sensitive_header(struct strbuf *header, size_t offset)
686 int ret = 0;
687 const char *sensitive_header;
689 if (trace_curl_redact &&
690 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
691 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
692 /* The first token is the type, which is OK to log */
693 while (isspace(*sensitive_header))
694 sensitive_header++;
695 while (*sensitive_header && !isspace(*sensitive_header))
696 sensitive_header++;
697 /* Everything else is opaque and possibly sensitive */
698 strbuf_setlen(header, sensitive_header - header->buf);
699 strbuf_addstr(header, " <redacted>");
700 ret = 1;
701 } else if (trace_curl_redact &&
702 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
703 struct strbuf redacted_header = STRBUF_INIT;
704 const char *cookie;
706 while (isspace(*sensitive_header))
707 sensitive_header++;
709 cookie = sensitive_header;
711 while (cookie) {
712 char *equals;
713 char *semicolon = strstr(cookie, "; ");
714 if (semicolon)
715 *semicolon = 0;
716 equals = strchrnul(cookie, '=');
717 if (!equals) {
718 /* invalid cookie, just append and continue */
719 strbuf_addstr(&redacted_header, cookie);
720 continue;
722 strbuf_add(&redacted_header, cookie, equals - cookie);
723 strbuf_addstr(&redacted_header, "=<redacted>");
724 if (semicolon) {
726 * There are more cookies. (Or, for some
727 * reason, the input string ends in "; ".)
729 strbuf_addstr(&redacted_header, "; ");
730 cookie = semicolon + strlen("; ");
731 } else {
732 cookie = NULL;
736 strbuf_setlen(header, sensitive_header - header->buf);
737 strbuf_addbuf(header, &redacted_header);
738 ret = 1;
740 return ret;
743 static int match_curl_h2_trace(const char *line, const char **out)
745 const char *p;
748 * curl prior to 8.1.0 gives us:
750 * h2h3 [<header-name>: <header-val>]
752 * Starting in 8.1.0, the first token became just "h2".
754 if (skip_iprefix(line, "h2h3 [", out) ||
755 skip_iprefix(line, "h2 [", out))
756 return 1;
759 * curl 8.3.0 uses:
760 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
761 * where <stream-id> is numeric.
763 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
764 while (isdigit(*p))
765 p++;
766 if (skip_prefix(p, "] [", out))
767 return 1;
770 return 0;
773 /* Redact headers in info */
774 static void redact_sensitive_info_header(struct strbuf *header)
776 const char *sensitive_header;
778 if (trace_curl_redact &&
779 match_curl_h2_trace(header->buf, &sensitive_header)) {
780 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
781 /* redaction ate our closing bracket */
782 strbuf_addch(header, ']');
787 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
789 struct strbuf out = STRBUF_INIT;
790 struct strbuf **headers, **header;
792 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
793 text, (long)size, (long)size);
794 trace_strbuf(&trace_curl, &out);
795 strbuf_reset(&out);
796 strbuf_add(&out, ptr, size);
797 headers = strbuf_split_max(&out, '\n', 0);
799 for (header = headers; *header; header++) {
800 if (hide_sensitive_header)
801 redact_sensitive_header(*header, 0);
802 strbuf_insertstr((*header), 0, text);
803 strbuf_insertstr((*header), strlen(text), ": ");
804 strbuf_rtrim((*header));
805 strbuf_addch((*header), '\n');
806 trace_strbuf(&trace_curl, (*header));
808 strbuf_list_free(headers);
809 strbuf_release(&out);
812 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
814 size_t i;
815 struct strbuf out = STRBUF_INIT;
816 unsigned int width = 60;
818 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
819 text, (long)size, (long)size);
820 trace_strbuf(&trace_curl, &out);
822 for (i = 0; i < size; i += width) {
823 size_t w;
825 strbuf_reset(&out);
826 strbuf_addf(&out, "%s: ", text);
827 for (w = 0; (w < width) && (i + w < size); w++) {
828 unsigned char ch = ptr[i + w];
830 strbuf_addch(&out,
831 (ch >= 0x20) && (ch < 0x80)
832 ? ch : '.');
834 strbuf_addch(&out, '\n');
835 trace_strbuf(&trace_curl, &out);
837 strbuf_release(&out);
840 static void curl_dump_info(char *data, size_t size)
842 struct strbuf buf = STRBUF_INIT;
844 strbuf_add(&buf, data, size);
846 redact_sensitive_info_header(&buf);
847 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
849 strbuf_release(&buf);
852 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
853 char *data, size_t size,
854 void *userp UNUSED)
856 const char *text;
857 enum { NO_FILTER = 0, DO_FILTER = 1 };
859 switch (type) {
860 case CURLINFO_TEXT:
861 curl_dump_info(data, size);
862 break;
863 case CURLINFO_HEADER_OUT:
864 text = "=> Send header";
865 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
866 break;
867 case CURLINFO_DATA_OUT:
868 if (trace_curl_data) {
869 text = "=> Send data";
870 curl_dump_data(text, (unsigned char *)data, size);
872 break;
873 case CURLINFO_SSL_DATA_OUT:
874 if (trace_curl_data) {
875 text = "=> Send SSL data";
876 curl_dump_data(text, (unsigned char *)data, size);
878 break;
879 case CURLINFO_HEADER_IN:
880 text = "<= Recv header";
881 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
882 break;
883 case CURLINFO_DATA_IN:
884 if (trace_curl_data) {
885 text = "<= Recv data";
886 curl_dump_data(text, (unsigned char *)data, size);
888 break;
889 case CURLINFO_SSL_DATA_IN:
890 if (trace_curl_data) {
891 text = "<= Recv SSL data";
892 curl_dump_data(text, (unsigned char *)data, size);
894 break;
896 default: /* we ignore unknown types by default */
897 return 0;
899 return 0;
902 void http_trace_curl_no_data(void)
904 trace_override_envvar(&trace_curl, "1");
905 trace_curl_data = 0;
908 void setup_curl_trace(CURL *handle)
910 if (!trace_want(&trace_curl))
911 return;
912 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
913 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
914 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
917 static void proto_list_append(struct strbuf *list, const char *proto)
919 if (!list)
920 return;
921 if (list->len)
922 strbuf_addch(list, ',');
923 strbuf_addstr(list, proto);
926 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
928 long bits = 0;
930 if (is_transport_allowed("http", from_user)) {
931 bits |= CURLPROTO_HTTP;
932 proto_list_append(list, "http");
934 if (is_transport_allowed("https", from_user)) {
935 bits |= CURLPROTO_HTTPS;
936 proto_list_append(list, "https");
938 if (is_transport_allowed("ftp", from_user)) {
939 bits |= CURLPROTO_FTP;
940 proto_list_append(list, "ftp");
942 if (is_transport_allowed("ftps", from_user)) {
943 bits |= CURLPROTO_FTPS;
944 proto_list_append(list, "ftps");
947 return bits;
950 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
951 static int get_curl_http_version_opt(const char *version_string, long *opt)
953 int i;
954 static struct {
955 const char *name;
956 long opt_token;
957 } choice[] = {
958 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
959 { "HTTP/2", CURL_HTTP_VERSION_2 }
962 for (i = 0; i < ARRAY_SIZE(choice); i++) {
963 if (!strcmp(version_string, choice[i].name)) {
964 *opt = choice[i].opt_token;
965 return 0;
969 warning("unknown value given to http.version: '%s'", version_string);
970 return -1; /* not found */
973 #endif
975 static CURL *get_curl_handle(void)
977 CURL *result = curl_easy_init();
979 if (!result)
980 die("curl_easy_init failed");
982 if (!curl_ssl_verify) {
983 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
984 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
985 } else {
986 /* Verify authenticity of the peer's certificate */
987 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
988 /* The name in the cert must match whom we tried to connect */
989 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
992 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
993 if (curl_http_version) {
994 long opt;
995 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
996 /* Set request use http version */
997 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
1000 #endif
1002 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
1003 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1005 #ifdef CURLGSSAPI_DELEGATION_FLAG
1006 if (curl_deleg) {
1007 int i;
1008 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1009 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1010 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1011 curl_deleg_levels[i].curl_deleg_param);
1012 break;
1015 if (i == ARRAY_SIZE(curl_deleg_levels))
1016 warning("Unknown delegation method '%s': using default",
1017 curl_deleg);
1019 #endif
1021 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1022 !http_schannel_check_revoke) {
1023 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1024 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1025 #else
1026 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1027 #endif
1030 if (http_proactive_auth)
1031 init_curl_http_auth(result);
1033 if (getenv("GIT_SSL_VERSION"))
1034 ssl_version = getenv("GIT_SSL_VERSION");
1035 if (ssl_version && *ssl_version) {
1036 int i;
1037 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1038 if (!strcmp(ssl_version, sslversions[i].name)) {
1039 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1040 sslversions[i].ssl_version);
1041 break;
1044 if (i == ARRAY_SIZE(sslversions))
1045 warning("unsupported ssl version %s: using default",
1046 ssl_version);
1049 if (getenv("GIT_SSL_CIPHER_LIST"))
1050 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1051 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1052 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1053 ssl_cipherlist);
1055 if (ssl_cert)
1056 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1057 if (ssl_cert_type)
1058 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1059 if (has_cert_password())
1060 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1061 if (ssl_key)
1062 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1063 if (ssl_key_type)
1064 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1065 if (ssl_capath)
1066 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1067 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1068 if (ssl_pinnedkey)
1069 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1070 #endif
1071 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1072 !http_schannel_use_ssl_cainfo) {
1073 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1074 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1075 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1076 #endif
1077 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1078 if (ssl_cainfo)
1079 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1080 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1081 if (http_proxy_ssl_ca_info)
1082 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1083 #endif
1086 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1087 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1088 curl_low_speed_limit);
1089 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1090 curl_low_speed_time);
1093 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1094 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1096 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1098 struct strbuf buf = STRBUF_INIT;
1100 get_curl_allowed_protocols(0, &buf);
1101 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1102 strbuf_reset(&buf);
1104 get_curl_allowed_protocols(-1, &buf);
1105 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1106 strbuf_release(&buf);
1108 #else
1109 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1110 get_curl_allowed_protocols(0, NULL));
1111 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1112 get_curl_allowed_protocols(-1, NULL));
1113 #endif
1115 if (getenv("GIT_CURL_VERBOSE"))
1116 http_trace_curl_no_data();
1117 setup_curl_trace(result);
1118 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1119 trace_curl_data = 0;
1120 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1121 trace_curl_redact = 0;
1123 curl_easy_setopt(result, CURLOPT_USERAGENT,
1124 user_agent ? user_agent : git_user_agent());
1126 if (curl_ftp_no_epsv)
1127 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1129 if (curl_ssl_try)
1130 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1133 * CURL also examines these variables as a fallback; but we need to query
1134 * them here in order to decide whether to prompt for missing password (cf.
1135 * init_curl_proxy_auth()).
1137 * Unlike many other common environment variables, these are historically
1138 * lowercase only. It appears that CURL did not know this and implemented
1139 * only uppercase variants, which was later corrected to take both - with
1140 * the exception of http_proxy, which is lowercase only also in CURL. As
1141 * the lowercase versions are the historical quasi-standard, they take
1142 * precedence here, as in CURL.
1144 if (!curl_http_proxy) {
1145 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1146 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1147 var_override(&curl_http_proxy, getenv("https_proxy"));
1148 } else {
1149 var_override(&curl_http_proxy, getenv("http_proxy"));
1151 if (!curl_http_proxy) {
1152 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1153 var_override(&curl_http_proxy, getenv("all_proxy"));
1157 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1159 * Handle case with the empty http.proxy value here to keep
1160 * common code clean.
1161 * NB: empty option disables proxying at all.
1163 curl_easy_setopt(result, CURLOPT_PROXY, "");
1164 } else if (curl_http_proxy) {
1165 if (starts_with(curl_http_proxy, "socks5h"))
1166 curl_easy_setopt(result,
1167 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1168 else if (starts_with(curl_http_proxy, "socks5"))
1169 curl_easy_setopt(result,
1170 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1171 else if (starts_with(curl_http_proxy, "socks4a"))
1172 curl_easy_setopt(result,
1173 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1174 else if (starts_with(curl_http_proxy, "socks"))
1175 curl_easy_setopt(result,
1176 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1177 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1178 else if (starts_with(curl_http_proxy, "https")) {
1179 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1181 if (http_proxy_ssl_cert)
1182 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1184 if (http_proxy_ssl_key)
1185 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1187 if (has_proxy_cert_password())
1188 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1190 #endif
1191 if (strstr(curl_http_proxy, "://"))
1192 credential_from_url(&proxy_auth, curl_http_proxy);
1193 else {
1194 struct strbuf url = STRBUF_INIT;
1195 strbuf_addf(&url, "http://%s", curl_http_proxy);
1196 credential_from_url(&proxy_auth, url.buf);
1197 strbuf_release(&url);
1200 if (!proxy_auth.host)
1201 die("Invalid proxy URL '%s'", curl_http_proxy);
1203 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1204 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1205 var_override(&curl_no_proxy, getenv("no_proxy"));
1206 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1208 init_curl_proxy_auth(result);
1210 set_curl_keepalive(result);
1212 return result;
1215 static void set_from_env(const char **var, const char *envname)
1217 const char *val = getenv(envname);
1218 if (val)
1219 *var = val;
1222 void http_init(struct remote *remote, const char *url, int proactive_auth)
1224 char *low_speed_limit;
1225 char *low_speed_time;
1226 char *normalized_url;
1227 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1229 config.section = "http";
1230 config.key = NULL;
1231 config.collect_fn = http_options;
1232 config.cascade_fn = git_default_config;
1233 config.cb = NULL;
1235 http_is_verbose = 0;
1236 normalized_url = url_normalize(url, &config.url);
1238 git_config(urlmatch_config_entry, &config);
1239 free(normalized_url);
1240 string_list_clear(&config.vars, 1);
1242 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1243 if (http_ssl_backend) {
1244 const curl_ssl_backend **backends;
1245 struct strbuf buf = STRBUF_INIT;
1246 int i;
1248 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1249 case CURLSSLSET_UNKNOWN_BACKEND:
1250 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1251 "Supported SSL backends:"),
1252 http_ssl_backend);
1253 for (i = 0; backends[i]; i++)
1254 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1255 die("%s", buf.buf);
1256 case CURLSSLSET_NO_BACKENDS:
1257 die(_("Could not set SSL backend to '%s': "
1258 "cURL was built without SSL backends"),
1259 http_ssl_backend);
1260 case CURLSSLSET_TOO_LATE:
1261 die(_("Could not set SSL backend to '%s': already set"),
1262 http_ssl_backend);
1263 case CURLSSLSET_OK:
1264 break; /* Okay! */
1267 #endif
1269 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1270 die("curl_global_init failed");
1272 http_proactive_auth = proactive_auth;
1274 if (remote && remote->http_proxy)
1275 curl_http_proxy = xstrdup(remote->http_proxy);
1277 if (remote)
1278 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1280 pragma_header = curl_slist_append(http_copy_default_headers(),
1281 "Pragma: no-cache");
1284 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1285 if (http_max_requests)
1286 max_requests = atoi(http_max_requests);
1289 curlm = curl_multi_init();
1290 if (!curlm)
1291 die("curl_multi_init failed");
1293 if (getenv("GIT_SSL_NO_VERIFY"))
1294 curl_ssl_verify = 0;
1296 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1297 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1298 set_from_env(&ssl_key, "GIT_SSL_KEY");
1299 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1300 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1301 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1303 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1305 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1306 if (low_speed_limit)
1307 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1308 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1309 if (low_speed_time)
1310 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1312 if (curl_ssl_verify == -1)
1313 curl_ssl_verify = 1;
1315 curl_session_count = 0;
1316 if (max_requests < 1)
1317 max_requests = DEFAULT_MAX_REQUESTS;
1319 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1320 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1321 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1323 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1324 proxy_ssl_cert_password_required = 1;
1326 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1327 curl_ftp_no_epsv = 1;
1329 if (url) {
1330 credential_from_url(&http_auth, url);
1331 if (!ssl_cert_password_required &&
1332 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1333 starts_with(url, "https://"))
1334 ssl_cert_password_required = 1;
1337 curl_default = get_curl_handle();
1340 void http_cleanup(void)
1342 struct active_request_slot *slot = active_queue_head;
1344 while (slot != NULL) {
1345 struct active_request_slot *next = slot->next;
1346 if (slot->curl) {
1347 xmulti_remove_handle(slot);
1348 curl_easy_cleanup(slot->curl);
1350 free(slot);
1351 slot = next;
1353 active_queue_head = NULL;
1355 curl_easy_cleanup(curl_default);
1357 curl_multi_cleanup(curlm);
1358 curl_global_cleanup();
1360 string_list_clear(&extra_http_headers, 0);
1362 curl_slist_free_all(pragma_header);
1363 pragma_header = NULL;
1365 curl_slist_free_all(host_resolutions);
1366 host_resolutions = NULL;
1368 if (curl_http_proxy) {
1369 free((void *)curl_http_proxy);
1370 curl_http_proxy = NULL;
1373 if (proxy_auth.password) {
1374 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1375 FREE_AND_NULL(proxy_auth.password);
1378 free((void *)curl_proxyuserpwd);
1379 curl_proxyuserpwd = NULL;
1381 free((void *)http_proxy_authmethod);
1382 http_proxy_authmethod = NULL;
1384 if (cert_auth.password) {
1385 memset(cert_auth.password, 0, strlen(cert_auth.password));
1386 FREE_AND_NULL(cert_auth.password);
1388 ssl_cert_password_required = 0;
1390 if (proxy_cert_auth.password) {
1391 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1392 FREE_AND_NULL(proxy_cert_auth.password);
1394 proxy_ssl_cert_password_required = 0;
1396 FREE_AND_NULL(cached_accept_language);
1399 struct active_request_slot *get_active_slot(void)
1401 struct active_request_slot *slot = active_queue_head;
1402 struct active_request_slot *newslot;
1404 int num_transfers;
1406 /* Wait for a slot to open up if the queue is full */
1407 while (active_requests >= max_requests) {
1408 curl_multi_perform(curlm, &num_transfers);
1409 if (num_transfers < active_requests)
1410 process_curl_messages();
1413 while (slot != NULL && slot->in_use)
1414 slot = slot->next;
1416 if (!slot) {
1417 newslot = xmalloc(sizeof(*newslot));
1418 newslot->curl = NULL;
1419 newslot->in_use = 0;
1420 newslot->next = NULL;
1422 slot = active_queue_head;
1423 if (!slot) {
1424 active_queue_head = newslot;
1425 } else {
1426 while (slot->next != NULL)
1427 slot = slot->next;
1428 slot->next = newslot;
1430 slot = newslot;
1433 if (!slot->curl) {
1434 slot->curl = curl_easy_duphandle(curl_default);
1435 curl_session_count++;
1438 active_requests++;
1439 slot->in_use = 1;
1440 slot->results = NULL;
1441 slot->finished = NULL;
1442 slot->callback_data = NULL;
1443 slot->callback_func = NULL;
1444 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1445 if (curl_save_cookies)
1446 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1447 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1448 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1449 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1450 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1451 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1452 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1453 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1454 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1455 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1456 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1457 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1460 * Default following to off unless "ALWAYS" is configured; this gives
1461 * callers a sane starting point, and they can tweak for individual
1462 * HTTP_FOLLOW_* cases themselves.
1464 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1465 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1466 else
1467 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1469 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1470 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1471 if (http_auth.password || curl_empty_auth_enabled())
1472 init_curl_http_auth(slot->curl);
1474 return slot;
1477 int start_active_slot(struct active_request_slot *slot)
1479 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1480 int num_transfers;
1482 if (curlm_result != CURLM_OK &&
1483 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1484 warning("curl_multi_add_handle failed: %s",
1485 curl_multi_strerror(curlm_result));
1486 active_requests--;
1487 slot->in_use = 0;
1488 return 0;
1492 * We know there must be something to do, since we just added
1493 * something.
1495 curl_multi_perform(curlm, &num_transfers);
1496 return 1;
1499 struct fill_chain {
1500 void *data;
1501 int (*fill)(void *);
1502 struct fill_chain *next;
1505 static struct fill_chain *fill_cfg;
1507 void add_fill_function(void *data, int (*fill)(void *))
1509 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1510 struct fill_chain **linkp = &fill_cfg;
1511 new_fill->data = data;
1512 new_fill->fill = fill;
1513 new_fill->next = NULL;
1514 while (*linkp)
1515 linkp = &(*linkp)->next;
1516 *linkp = new_fill;
1519 void fill_active_slots(void)
1521 struct active_request_slot *slot = active_queue_head;
1523 while (active_requests < max_requests) {
1524 struct fill_chain *fill;
1525 for (fill = fill_cfg; fill; fill = fill->next)
1526 if (fill->fill(fill->data))
1527 break;
1529 if (!fill)
1530 break;
1533 while (slot != NULL) {
1534 if (!slot->in_use && slot->curl != NULL
1535 && curl_session_count > min_curl_sessions) {
1536 curl_easy_cleanup(slot->curl);
1537 slot->curl = NULL;
1538 curl_session_count--;
1540 slot = slot->next;
1544 void step_active_slots(void)
1546 int num_transfers;
1547 CURLMcode curlm_result;
1549 do {
1550 curlm_result = curl_multi_perform(curlm, &num_transfers);
1551 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1552 if (num_transfers < active_requests) {
1553 process_curl_messages();
1554 fill_active_slots();
1558 void run_active_slot(struct active_request_slot *slot)
1560 fd_set readfds;
1561 fd_set writefds;
1562 fd_set excfds;
1563 int max_fd;
1564 struct timeval select_timeout;
1565 int finished = 0;
1567 slot->finished = &finished;
1568 while (!finished) {
1569 step_active_slots();
1571 if (slot->in_use) {
1572 long curl_timeout;
1573 curl_multi_timeout(curlm, &curl_timeout);
1574 if (curl_timeout == 0) {
1575 continue;
1576 } else if (curl_timeout == -1) {
1577 select_timeout.tv_sec = 0;
1578 select_timeout.tv_usec = 50000;
1579 } else {
1580 select_timeout.tv_sec = curl_timeout / 1000;
1581 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1584 max_fd = -1;
1585 FD_ZERO(&readfds);
1586 FD_ZERO(&writefds);
1587 FD_ZERO(&excfds);
1588 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1591 * It can happen that curl_multi_timeout returns a pathologically
1592 * long timeout when curl_multi_fdset returns no file descriptors
1593 * to read. See commit message for more details.
1595 if (max_fd < 0 &&
1596 (select_timeout.tv_sec > 0 ||
1597 select_timeout.tv_usec > 50000)) {
1598 select_timeout.tv_sec = 0;
1599 select_timeout.tv_usec = 50000;
1602 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1607 * The value of slot->finished we set before the loop was used
1608 * to set our "finished" variable when our request completed.
1610 * 1. The slot may not have been reused for another requst
1611 * yet, in which case it still has &finished.
1613 * 2. The slot may already be in-use to serve another request,
1614 * which can further be divided into two cases:
1616 * (a) If call run_active_slot() hasn't been called for that
1617 * other request, slot->finished would have been cleared
1618 * by get_active_slot() and has NULL.
1620 * (b) If the request did call run_active_slot(), then the
1621 * call would have updated slot->finished at the beginning
1622 * of this function, and with the clearing of the member
1623 * below, we would find that slot->finished is now NULL.
1625 * In all cases, slot->finished has no useful information to
1626 * anybody at this point. Some compilers warn us for
1627 * attempting to smuggle a pointer that is about to become
1628 * invalid, i.e. &finished. We clear it here to assure them.
1630 slot->finished = NULL;
1633 static void release_active_slot(struct active_request_slot *slot)
1635 closedown_active_slot(slot);
1636 if (slot->curl) {
1637 xmulti_remove_handle(slot);
1638 if (curl_session_count > min_curl_sessions) {
1639 curl_easy_cleanup(slot->curl);
1640 slot->curl = NULL;
1641 curl_session_count--;
1644 fill_active_slots();
1647 void finish_all_active_slots(void)
1649 struct active_request_slot *slot = active_queue_head;
1651 while (slot != NULL)
1652 if (slot->in_use) {
1653 run_active_slot(slot);
1654 slot = active_queue_head;
1655 } else {
1656 slot = slot->next;
1660 /* Helpers for modifying and creating URLs */
1661 static inline int needs_quote(int ch)
1663 if (((ch >= 'A') && (ch <= 'Z'))
1664 || ((ch >= 'a') && (ch <= 'z'))
1665 || ((ch >= '0') && (ch <= '9'))
1666 || (ch == '/')
1667 || (ch == '-')
1668 || (ch == '.'))
1669 return 0;
1670 return 1;
1673 static char *quote_ref_url(const char *base, const char *ref)
1675 struct strbuf buf = STRBUF_INIT;
1676 const char *cp;
1677 int ch;
1679 end_url_with_slash(&buf, base);
1681 for (cp = ref; (ch = *cp) != 0; cp++)
1682 if (needs_quote(ch))
1683 strbuf_addf(&buf, "%%%02x", ch);
1684 else
1685 strbuf_addch(&buf, *cp);
1687 return strbuf_detach(&buf, NULL);
1690 void append_remote_object_url(struct strbuf *buf, const char *url,
1691 const char *hex,
1692 int only_two_digit_prefix)
1694 end_url_with_slash(buf, url);
1696 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1697 if (!only_two_digit_prefix)
1698 strbuf_addstr(buf, hex + 2);
1701 char *get_remote_object_url(const char *url, const char *hex,
1702 int only_two_digit_prefix)
1704 struct strbuf buf = STRBUF_INIT;
1705 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1706 return strbuf_detach(&buf, NULL);
1709 void normalize_curl_result(CURLcode *result, long http_code,
1710 char *errorstr, size_t errorlen)
1713 * If we see a failing http code with CURLE_OK, we have turned off
1714 * FAILONERROR (to keep the server's custom error response), and should
1715 * translate the code into failure here.
1717 * Likewise, if we see a redirect (30x code), that means we turned off
1718 * redirect-following, and we should treat the result as an error.
1720 if (*result == CURLE_OK && http_code >= 300) {
1721 *result = CURLE_HTTP_RETURNED_ERROR;
1723 * Normally curl will already have put the "reason phrase"
1724 * from the server into curl_errorstr; unfortunately without
1725 * FAILONERROR it is lost, so we can give only the numeric
1726 * status code.
1728 xsnprintf(errorstr, errorlen,
1729 "The requested URL returned error: %ld",
1730 http_code);
1734 static int handle_curl_result(struct slot_results *results)
1736 normalize_curl_result(&results->curl_result, results->http_code,
1737 curl_errorstr, sizeof(curl_errorstr));
1739 if (results->curl_result == CURLE_OK) {
1740 credential_approve(&http_auth);
1741 credential_approve(&proxy_auth);
1742 credential_approve(&cert_auth);
1743 return HTTP_OK;
1744 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1746 * We can't tell from here whether it's a bad path, bad
1747 * certificate, bad password, or something else wrong
1748 * with the certificate. So we reject the credential to
1749 * avoid caching or saving a bad password.
1751 credential_reject(&cert_auth);
1752 return HTTP_NOAUTH;
1753 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1754 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1755 return HTTP_NOMATCHPUBLICKEY;
1756 #endif
1757 } else if (missing_target(results))
1758 return HTTP_MISSING_TARGET;
1759 else if (results->http_code == 401) {
1760 if (http_auth.username && http_auth.password) {
1761 credential_reject(&http_auth);
1762 return HTTP_NOAUTH;
1763 } else {
1764 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1765 if (results->auth_avail) {
1766 http_auth_methods &= results->auth_avail;
1767 http_auth_methods_restricted = 1;
1769 return HTTP_REAUTH;
1771 } else {
1772 if (results->http_connectcode == 407)
1773 credential_reject(&proxy_auth);
1774 if (!curl_errorstr[0])
1775 strlcpy(curl_errorstr,
1776 curl_easy_strerror(results->curl_result),
1777 sizeof(curl_errorstr));
1778 return HTTP_ERROR;
1782 int run_one_slot(struct active_request_slot *slot,
1783 struct slot_results *results)
1785 slot->results = results;
1786 if (!start_active_slot(slot)) {
1787 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1788 "failed to start HTTP request");
1789 return HTTP_START_FAILED;
1792 run_active_slot(slot);
1793 return handle_curl_result(results);
1796 struct curl_slist *http_copy_default_headers(void)
1798 struct curl_slist *headers = NULL;
1799 const struct string_list_item *item;
1801 for_each_string_list_item(item, &extra_http_headers)
1802 headers = curl_slist_append(headers, item->string);
1804 return headers;
1807 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1809 char *ptr;
1810 CURLcode ret;
1812 strbuf_reset(buf);
1813 ret = curl_easy_getinfo(curl, info, &ptr);
1814 if (!ret && ptr)
1815 strbuf_addstr(buf, ptr);
1816 return ret;
1820 * Check for and extract a content-type parameter. "raw"
1821 * should be positioned at the start of the potential
1822 * parameter, with any whitespace already removed.
1824 * "name" is the name of the parameter. The value is appended
1825 * to "out".
1827 static int extract_param(const char *raw, const char *name,
1828 struct strbuf *out)
1830 size_t len = strlen(name);
1832 if (strncasecmp(raw, name, len))
1833 return -1;
1834 raw += len;
1836 if (*raw != '=')
1837 return -1;
1838 raw++;
1840 while (*raw && !isspace(*raw) && *raw != ';')
1841 strbuf_addch(out, *raw++);
1842 return 0;
1846 * Extract a normalized version of the content type, with any
1847 * spaces suppressed, all letters lowercased, and no trailing ";"
1848 * or parameters.
1850 * Note that we will silently remove even invalid whitespace. For
1851 * example, "text / plain" is specifically forbidden by RFC 2616,
1852 * but "text/plain" is the only reasonable output, and this keeps
1853 * our code simple.
1855 * If the "charset" argument is not NULL, store the value of any
1856 * charset parameter there.
1858 * Example:
1859 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1860 * "text / plain" -> "text/plain"
1862 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1863 struct strbuf *charset)
1865 const char *p;
1867 strbuf_reset(type);
1868 strbuf_grow(type, raw->len);
1869 for (p = raw->buf; *p; p++) {
1870 if (isspace(*p))
1871 continue;
1872 if (*p == ';') {
1873 p++;
1874 break;
1876 strbuf_addch(type, tolower(*p));
1879 if (!charset)
1880 return;
1882 strbuf_reset(charset);
1883 while (*p) {
1884 while (isspace(*p) || *p == ';')
1885 p++;
1886 if (!extract_param(p, "charset", charset))
1887 return;
1888 while (*p && !isspace(*p))
1889 p++;
1892 if (!charset->len && starts_with(type->buf, "text/"))
1893 strbuf_addstr(charset, "ISO-8859-1");
1896 static void write_accept_language(struct strbuf *buf)
1899 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1900 * that, q-value will be smaller than 0.001, the minimum q-value the
1901 * HTTP specification allows. See
1902 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
1904 const int MAX_DECIMAL_PLACES = 3;
1905 const int MAX_LANGUAGE_TAGS = 1000;
1906 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1907 char **language_tags = NULL;
1908 int num_langs = 0;
1909 const char *s = get_preferred_languages();
1910 int i;
1911 struct strbuf tag = STRBUF_INIT;
1913 /* Don't add Accept-Language header if no language is preferred. */
1914 if (!s)
1915 return;
1918 * Split the colon-separated string of preferred languages into
1919 * language_tags array.
1921 do {
1922 /* collect language tag */
1923 for (; *s && (isalnum(*s) || *s == '_'); s++)
1924 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1926 /* skip .codeset, @modifier and any other unnecessary parts */
1927 while (*s && *s != ':')
1928 s++;
1930 if (tag.len) {
1931 num_langs++;
1932 REALLOC_ARRAY(language_tags, num_langs);
1933 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1934 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1935 break;
1937 } while (*s++);
1939 /* write Accept-Language header into buf */
1940 if (num_langs) {
1941 int last_buf_len = 0;
1942 int max_q;
1943 int decimal_places;
1944 char q_format[32];
1946 /* add '*' */
1947 REALLOC_ARRAY(language_tags, num_langs + 1);
1948 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1950 /* compute decimal_places */
1951 for (max_q = 1, decimal_places = 0;
1952 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1953 decimal_places++, max_q *= 10)
1956 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1958 strbuf_addstr(buf, "Accept-Language: ");
1960 for (i = 0; i < num_langs; i++) {
1961 if (i > 0)
1962 strbuf_addstr(buf, ", ");
1964 strbuf_addstr(buf, language_tags[i]);
1966 if (i > 0)
1967 strbuf_addf(buf, q_format, max_q - i);
1969 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1970 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1971 break;
1974 last_buf_len = buf->len;
1978 /* free language tags -- last one is a static '*' */
1979 for (i = 0; i < num_langs - 1; i++)
1980 free(language_tags[i]);
1981 free(language_tags);
1985 * Get an Accept-Language header which indicates user's preferred languages.
1987 * Examples:
1988 * LANGUAGE= -> ""
1989 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1990 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1991 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1992 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1993 * LANGUAGE= LANG=C -> ""
1995 const char *http_get_accept_language_header(void)
1997 if (!cached_accept_language) {
1998 struct strbuf buf = STRBUF_INIT;
1999 write_accept_language(&buf);
2000 if (buf.len > 0)
2001 cached_accept_language = strbuf_detach(&buf, NULL);
2004 return cached_accept_language;
2007 static void http_opt_request_remainder(CURL *curl, off_t pos)
2009 char buf[128];
2010 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2011 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2014 /* http_request() targets */
2015 #define HTTP_REQUEST_STRBUF 0
2016 #define HTTP_REQUEST_FILE 1
2018 static int http_request(const char *url,
2019 void *result, int target,
2020 const struct http_get_options *options)
2022 struct active_request_slot *slot;
2023 struct slot_results results;
2024 struct curl_slist *headers = http_copy_default_headers();
2025 struct strbuf buf = STRBUF_INIT;
2026 const char *accept_language;
2027 int ret;
2029 slot = get_active_slot();
2030 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2032 if (!result) {
2033 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2034 } else {
2035 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2036 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2038 if (target == HTTP_REQUEST_FILE) {
2039 off_t posn = ftello(result);
2040 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2041 fwrite);
2042 if (posn > 0)
2043 http_opt_request_remainder(slot->curl, posn);
2044 } else
2045 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2046 fwrite_buffer);
2049 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2051 accept_language = http_get_accept_language_header();
2053 if (accept_language)
2054 headers = curl_slist_append(headers, accept_language);
2056 strbuf_addstr(&buf, "Pragma:");
2057 if (options && options->no_cache)
2058 strbuf_addstr(&buf, " no-cache");
2059 if (options && options->initial_request &&
2060 http_follow_config == HTTP_FOLLOW_INITIAL)
2061 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2063 headers = curl_slist_append(headers, buf.buf);
2065 /* Add additional headers here */
2066 if (options && options->extra_headers) {
2067 const struct string_list_item *item;
2068 for_each_string_list_item(item, options->extra_headers) {
2069 headers = curl_slist_append(headers, item->string);
2073 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2074 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2075 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2076 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2078 ret = run_one_slot(slot, &results);
2080 if (options && options->content_type) {
2081 struct strbuf raw = STRBUF_INIT;
2082 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2083 extract_content_type(&raw, options->content_type,
2084 options->charset);
2085 strbuf_release(&raw);
2088 if (options && options->effective_url)
2089 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2090 options->effective_url);
2092 curl_slist_free_all(headers);
2093 strbuf_release(&buf);
2095 return ret;
2099 * Update the "base" url to a more appropriate value, as deduced by
2100 * redirects seen when requesting a URL starting with "url".
2102 * The "asked" parameter is a URL that we asked curl to access, and must begin
2103 * with "base".
2105 * The "got" parameter is the URL that curl reported to us as where we ended
2106 * up.
2108 * Returns 1 if we updated the base url, 0 otherwise.
2110 * Our basic strategy is to compare "base" and "asked" to find the bits
2111 * specific to our request. We then strip those bits off of "got" to yield the
2112 * new base. So for example, if our base is "http://example.com/foo.git",
2113 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2114 * with "https://other.example.com/foo.git/info/refs". We would want the
2115 * new URL to become "https://other.example.com/foo.git".
2117 * Note that this assumes a sane redirect scheme. It's entirely possible
2118 * in the example above to end up at a URL that does not even end in
2119 * "info/refs". In such a case we die. There's not much we can do, such a
2120 * scheme is unlikely to represent a real git repository, and failing to
2121 * rewrite the base opens options for malicious redirects to do funny things.
2123 static int update_url_from_redirect(struct strbuf *base,
2124 const char *asked,
2125 const struct strbuf *got)
2127 const char *tail;
2128 size_t new_len;
2130 if (!strcmp(asked, got->buf))
2131 return 0;
2133 if (!skip_prefix(asked, base->buf, &tail))
2134 BUG("update_url_from_redirect: %s is not a superset of %s",
2135 asked, base->buf);
2137 new_len = got->len;
2138 if (!strip_suffix_mem(got->buf, &new_len, tail))
2139 die(_("unable to update url base from redirection:\n"
2140 " asked for: %s\n"
2141 " redirect: %s"),
2142 asked, got->buf);
2144 strbuf_reset(base);
2145 strbuf_add(base, got->buf, new_len);
2147 return 1;
2150 static int http_request_reauth(const char *url,
2151 void *result, int target,
2152 struct http_get_options *options)
2154 int ret = http_request(url, result, target, options);
2156 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2157 return ret;
2159 if (options && options->effective_url && options->base_url) {
2160 if (update_url_from_redirect(options->base_url,
2161 url, options->effective_url)) {
2162 credential_from_url(&http_auth, options->base_url->buf);
2163 url = options->effective_url->buf;
2167 if (ret != HTTP_REAUTH)
2168 return ret;
2171 * The previous request may have put cruft into our output stream; we
2172 * should clear it out before making our next request.
2174 switch (target) {
2175 case HTTP_REQUEST_STRBUF:
2176 strbuf_reset(result);
2177 break;
2178 case HTTP_REQUEST_FILE:
2179 if (fflush(result)) {
2180 error_errno("unable to flush a file");
2181 return HTTP_START_FAILED;
2183 rewind(result);
2184 if (ftruncate(fileno(result), 0) < 0) {
2185 error_errno("unable to truncate a file");
2186 return HTTP_START_FAILED;
2188 break;
2189 default:
2190 BUG("Unknown http_request target");
2193 credential_fill(&http_auth);
2195 return http_request(url, result, target, options);
2198 int http_get_strbuf(const char *url,
2199 struct strbuf *result,
2200 struct http_get_options *options)
2202 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2206 * Downloads a URL and stores the result in the given file.
2208 * If a previous interrupted download is detected (i.e. a previous temporary
2209 * file is still around) the download is resumed.
2211 int http_get_file(const char *url, const char *filename,
2212 struct http_get_options *options)
2214 int ret;
2215 struct strbuf tmpfile = STRBUF_INIT;
2216 FILE *result;
2218 strbuf_addf(&tmpfile, "%s.temp", filename);
2219 result = fopen(tmpfile.buf, "a");
2220 if (!result) {
2221 error("Unable to open local file %s", tmpfile.buf);
2222 ret = HTTP_ERROR;
2223 goto cleanup;
2226 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2227 fclose(result);
2229 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2230 ret = HTTP_ERROR;
2231 cleanup:
2232 strbuf_release(&tmpfile);
2233 return ret;
2236 int http_fetch_ref(const char *base, struct ref *ref)
2238 struct http_get_options options = {0};
2239 char *url;
2240 struct strbuf buffer = STRBUF_INIT;
2241 int ret = -1;
2243 options.no_cache = 1;
2245 url = quote_ref_url(base, ref->name);
2246 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2247 strbuf_rtrim(&buffer);
2248 if (buffer.len == the_hash_algo->hexsz)
2249 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2250 else if (starts_with(buffer.buf, "ref: ")) {
2251 ref->symref = xstrdup(buffer.buf + 5);
2252 ret = 0;
2256 strbuf_release(&buffer);
2257 free(url);
2258 return ret;
2261 /* Helpers for fetching packs */
2262 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2264 char *url, *tmp;
2265 struct strbuf buf = STRBUF_INIT;
2267 if (http_is_verbose)
2268 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2270 end_url_with_slash(&buf, base_url);
2271 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2272 url = strbuf_detach(&buf, NULL);
2274 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2275 tmp = strbuf_detach(&buf, NULL);
2277 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2278 error("Unable to get pack index %s", url);
2279 FREE_AND_NULL(tmp);
2282 free(url);
2283 return tmp;
2286 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2287 unsigned char *sha1, const char *base_url)
2289 struct packed_git *new_pack;
2290 char *tmp_idx = NULL;
2291 int ret;
2293 if (has_pack_index(sha1)) {
2294 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2295 if (!new_pack)
2296 return -1; /* parse_pack_index() already issued error message */
2297 goto add_pack;
2300 tmp_idx = fetch_pack_index(sha1, base_url);
2301 if (!tmp_idx)
2302 return -1;
2304 new_pack = parse_pack_index(sha1, tmp_idx);
2305 if (!new_pack) {
2306 unlink(tmp_idx);
2307 free(tmp_idx);
2309 return -1; /* parse_pack_index() already issued error message */
2312 ret = verify_pack_index(new_pack);
2313 if (!ret) {
2314 close_pack_index(new_pack);
2315 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2317 free(tmp_idx);
2318 if (ret)
2319 return -1;
2321 add_pack:
2322 new_pack->next = *packs_head;
2323 *packs_head = new_pack;
2324 return 0;
2327 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2329 struct http_get_options options = {0};
2330 int ret = 0;
2331 char *url;
2332 const char *data;
2333 struct strbuf buf = STRBUF_INIT;
2334 struct object_id oid;
2336 end_url_with_slash(&buf, base_url);
2337 strbuf_addstr(&buf, "objects/info/packs");
2338 url = strbuf_detach(&buf, NULL);
2340 options.no_cache = 1;
2341 ret = http_get_strbuf(url, &buf, &options);
2342 if (ret != HTTP_OK)
2343 goto cleanup;
2345 data = buf.buf;
2346 while (*data) {
2347 if (skip_prefix(data, "P pack-", &data) &&
2348 !parse_oid_hex(data, &oid, &data) &&
2349 skip_prefix(data, ".pack", &data) &&
2350 (*data == '\n' || *data == '\0')) {
2351 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2352 } else {
2353 data = strchrnul(data, '\n');
2355 if (*data)
2356 data++; /* skip past newline */
2359 cleanup:
2360 free(url);
2361 return ret;
2364 void release_http_pack_request(struct http_pack_request *preq)
2366 if (preq->packfile) {
2367 fclose(preq->packfile);
2368 preq->packfile = NULL;
2370 preq->slot = NULL;
2371 strbuf_release(&preq->tmpfile);
2372 curl_slist_free_all(preq->headers);
2373 free(preq->url);
2374 free(preq);
2377 static const char *default_index_pack_args[] =
2378 {"index-pack", "--stdin", NULL};
2380 int finish_http_pack_request(struct http_pack_request *preq)
2382 struct child_process ip = CHILD_PROCESS_INIT;
2383 int tmpfile_fd;
2384 int ret = 0;
2386 fclose(preq->packfile);
2387 preq->packfile = NULL;
2389 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2391 ip.git_cmd = 1;
2392 ip.in = tmpfile_fd;
2393 strvec_pushv(&ip.args, preq->index_pack_args ?
2394 preq->index_pack_args :
2395 default_index_pack_args);
2397 if (preq->preserve_index_pack_stdout)
2398 ip.out = 0;
2399 else
2400 ip.no_stdout = 1;
2402 if (run_command(&ip)) {
2403 ret = -1;
2404 goto cleanup;
2407 cleanup:
2408 close(tmpfile_fd);
2409 unlink(preq->tmpfile.buf);
2410 return ret;
2413 void http_install_packfile(struct packed_git *p,
2414 struct packed_git **list_to_remove_from)
2416 struct packed_git **lst = list_to_remove_from;
2418 while (*lst != p)
2419 lst = &((*lst)->next);
2420 *lst = (*lst)->next;
2422 install_packed_git(the_repository, p);
2425 struct http_pack_request *new_http_pack_request(
2426 const unsigned char *packed_git_hash, const char *base_url) {
2428 struct strbuf buf = STRBUF_INIT;
2430 end_url_with_slash(&buf, base_url);
2431 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2432 hash_to_hex(packed_git_hash));
2433 return new_direct_http_pack_request(packed_git_hash,
2434 strbuf_detach(&buf, NULL));
2437 struct http_pack_request *new_direct_http_pack_request(
2438 const unsigned char *packed_git_hash, char *url)
2440 off_t prev_posn = 0;
2441 struct http_pack_request *preq;
2443 CALLOC_ARRAY(preq, 1);
2444 strbuf_init(&preq->tmpfile, 0);
2446 preq->url = url;
2448 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2449 preq->packfile = fopen(preq->tmpfile.buf, "a");
2450 if (!preq->packfile) {
2451 error("Unable to open local file %s for pack",
2452 preq->tmpfile.buf);
2453 goto abort;
2456 preq->slot = get_active_slot();
2457 preq->headers = object_request_headers();
2458 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2459 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2460 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2461 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER, preq->headers);
2464 * If there is data present from a previous transfer attempt,
2465 * resume where it left off
2467 prev_posn = ftello(preq->packfile);
2468 if (prev_posn>0) {
2469 if (http_is_verbose)
2470 fprintf(stderr,
2471 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2472 hash_to_hex(packed_git_hash),
2473 (uintmax_t)prev_posn);
2474 http_opt_request_remainder(preq->slot->curl, prev_posn);
2477 return preq;
2479 abort:
2480 strbuf_release(&preq->tmpfile);
2481 free(preq->url);
2482 free(preq);
2483 return NULL;
2486 /* Helpers for fetching objects (loose) */
2487 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2488 void *data)
2490 unsigned char expn[4096];
2491 size_t size = eltsize * nmemb;
2492 int posn = 0;
2493 struct http_object_request *freq = data;
2494 struct active_request_slot *slot = freq->slot;
2496 if (slot) {
2497 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2498 &slot->http_code);
2499 if (c != CURLE_OK)
2500 BUG("curl_easy_getinfo for HTTP code failed: %s",
2501 curl_easy_strerror(c));
2502 if (slot->http_code >= 300)
2503 return nmemb;
2506 do {
2507 ssize_t retval = xwrite(freq->localfile,
2508 (char *) ptr + posn, size - posn);
2509 if (retval < 0)
2510 return posn / eltsize;
2511 posn += retval;
2512 } while (posn < size);
2514 freq->stream.avail_in = size;
2515 freq->stream.next_in = (void *)ptr;
2516 do {
2517 freq->stream.next_out = expn;
2518 freq->stream.avail_out = sizeof(expn);
2519 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2520 the_hash_algo->update_fn(&freq->c, expn,
2521 sizeof(expn) - freq->stream.avail_out);
2522 } while (freq->stream.avail_in && freq->zret == Z_OK);
2523 return nmemb;
2526 struct http_object_request *new_http_object_request(const char *base_url,
2527 const struct object_id *oid)
2529 char *hex = oid_to_hex(oid);
2530 struct strbuf filename = STRBUF_INIT;
2531 struct strbuf prevfile = STRBUF_INIT;
2532 int prevlocal;
2533 char prev_buf[PREV_BUF_SIZE];
2534 ssize_t prev_read = 0;
2535 off_t prev_posn = 0;
2536 struct http_object_request *freq;
2538 CALLOC_ARRAY(freq, 1);
2539 strbuf_init(&freq->tmpfile, 0);
2540 oidcpy(&freq->oid, oid);
2541 freq->localfile = -1;
2543 loose_object_path(the_repository, &filename, oid);
2544 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2546 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2547 unlink_or_warn(prevfile.buf);
2548 rename(freq->tmpfile.buf, prevfile.buf);
2549 unlink_or_warn(freq->tmpfile.buf);
2550 strbuf_release(&filename);
2552 if (freq->localfile != -1)
2553 error("fd leakage in start: %d", freq->localfile);
2554 freq->localfile = open(freq->tmpfile.buf,
2555 O_WRONLY | O_CREAT | O_EXCL, 0666);
2557 * This could have failed due to the "lazy directory creation";
2558 * try to mkdir the last path component.
2560 if (freq->localfile < 0 && errno == ENOENT) {
2561 char *dir = strrchr(freq->tmpfile.buf, '/');
2562 if (dir) {
2563 *dir = 0;
2564 mkdir(freq->tmpfile.buf, 0777);
2565 *dir = '/';
2567 freq->localfile = open(freq->tmpfile.buf,
2568 O_WRONLY | O_CREAT | O_EXCL, 0666);
2571 if (freq->localfile < 0) {
2572 error_errno("Couldn't create temporary file %s",
2573 freq->tmpfile.buf);
2574 goto abort;
2577 git_inflate_init(&freq->stream);
2579 the_hash_algo->init_fn(&freq->c);
2581 freq->url = get_remote_object_url(base_url, hex, 0);
2584 * If a previous temp file is present, process what was already
2585 * fetched.
2587 prevlocal = open(prevfile.buf, O_RDONLY);
2588 if (prevlocal != -1) {
2589 do {
2590 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2591 if (prev_read>0) {
2592 if (fwrite_sha1_file(prev_buf,
2594 prev_read,
2595 freq) == prev_read) {
2596 prev_posn += prev_read;
2597 } else {
2598 prev_read = -1;
2601 } while (prev_read > 0);
2602 close(prevlocal);
2604 unlink_or_warn(prevfile.buf);
2605 strbuf_release(&prevfile);
2608 * Reset inflate/SHA1 if there was an error reading the previous temp
2609 * file; also rewind to the beginning of the local file.
2611 if (prev_read == -1) {
2612 memset(&freq->stream, 0, sizeof(freq->stream));
2613 git_inflate_init(&freq->stream);
2614 the_hash_algo->init_fn(&freq->c);
2615 if (prev_posn>0) {
2616 prev_posn = 0;
2617 lseek(freq->localfile, 0, SEEK_SET);
2618 if (ftruncate(freq->localfile, 0) < 0) {
2619 error_errno("Couldn't truncate temporary file %s",
2620 freq->tmpfile.buf);
2621 goto abort;
2626 freq->slot = get_active_slot();
2627 freq->headers = object_request_headers();
2629 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2630 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2631 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2632 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2633 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2634 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, freq->headers);
2637 * If we have successfully processed data from a previous fetch
2638 * attempt, only fetch the data we don't already have.
2640 if (prev_posn>0) {
2641 if (http_is_verbose)
2642 fprintf(stderr,
2643 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2644 hex, (uintmax_t)prev_posn);
2645 http_opt_request_remainder(freq->slot->curl, prev_posn);
2648 return freq;
2650 abort:
2651 strbuf_release(&prevfile);
2652 free(freq->url);
2653 free(freq);
2654 return NULL;
2657 void process_http_object_request(struct http_object_request *freq)
2659 if (!freq->slot)
2660 return;
2661 freq->curl_result = freq->slot->curl_result;
2662 freq->http_code = freq->slot->http_code;
2663 freq->slot = NULL;
2666 int finish_http_object_request(struct http_object_request *freq)
2668 struct stat st;
2669 struct strbuf filename = STRBUF_INIT;
2671 close(freq->localfile);
2672 freq->localfile = -1;
2674 process_http_object_request(freq);
2676 if (freq->http_code == 416) {
2677 warning("requested range invalid; we may already have all the data.");
2678 } else if (freq->curl_result != CURLE_OK) {
2679 if (stat(freq->tmpfile.buf, &st) == 0)
2680 if (st.st_size == 0)
2681 unlink_or_warn(freq->tmpfile.buf);
2682 return -1;
2685 git_inflate_end(&freq->stream);
2686 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2687 if (freq->zret != Z_STREAM_END) {
2688 unlink_or_warn(freq->tmpfile.buf);
2689 return -1;
2691 if (!oideq(&freq->oid, &freq->real_oid)) {
2692 unlink_or_warn(freq->tmpfile.buf);
2693 return -1;
2695 loose_object_path(the_repository, &filename, &freq->oid);
2696 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2697 strbuf_release(&filename);
2699 return freq->rename;
2702 void abort_http_object_request(struct http_object_request *freq)
2704 unlink_or_warn(freq->tmpfile.buf);
2706 release_http_object_request(freq);
2709 void release_http_object_request(struct http_object_request *freq)
2711 if (freq->localfile != -1) {
2712 close(freq->localfile);
2713 freq->localfile = -1;
2715 FREE_AND_NULL(freq->url);
2716 if (freq->slot) {
2717 freq->slot->callback_func = NULL;
2718 freq->slot->callback_data = NULL;
2719 release_active_slot(freq->slot);
2720 freq->slot = NULL;
2722 curl_slist_free_all(freq->headers);
2723 strbuf_release(&freq->tmpfile);