t5324: harmonize sha1/sha256 graph chain corruption
[git.git] / http.c
blob8f71bf00d8998af44e177a86d73dbc86872c9726
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 "sideband.h"
8 #include "run-command.h"
9 #include "url.h"
10 #include "urlmatch.h"
11 #include "credential.h"
12 #include "version.h"
13 #include "pkt-line.h"
14 #include "gettext.h"
15 #include "trace.h"
16 #include "transport.h"
17 #include "packfile.h"
18 #include "protocol.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 const char *curl_http_version = NULL;
44 static const char *ssl_cert;
45 static const char *ssl_cert_type;
46 static const char *ssl_cipherlist;
47 static const 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 const char *ssl_key;
65 static const char *ssl_key_type;
66 static const char *ssl_capath;
67 static const char *curl_no_proxy;
68 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
69 static const char *ssl_pinnedkey;
70 #endif
71 static const 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 const char *curl_http_proxy;
76 static const char *http_proxy_authmethod;
78 static const char *http_proxy_ssl_cert;
79 static const char *http_proxy_ssl_key;
80 static const 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 const 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 const 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 const 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 curl_slist *no_pragma_header;
134 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
136 static struct curl_slist *host_resolutions;
138 static struct active_request_slot *active_queue_head;
140 static char *cached_accept_language;
142 static char *http_ssl_backend;
144 static int http_schannel_check_revoke = 1;
146 * With the backend being set to `schannel`, setting sslCAinfo would override
147 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
148 * by default.
150 static int http_schannel_use_ssl_cainfo;
152 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
154 size_t size = eltsize * nmemb;
155 struct buffer *buffer = buffer_;
157 if (size > buffer->buf.len - buffer->posn)
158 size = buffer->buf.len - buffer->posn;
159 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
160 buffer->posn += size;
162 return size / eltsize;
165 int seek_buffer(void *clientp, curl_off_t offset, int origin)
167 struct buffer *buffer = clientp;
169 if (origin != SEEK_SET)
170 BUG("seek_buffer only handles SEEK_SET");
171 if (offset < 0 || offset >= buffer->buf.len) {
172 error("curl seek would be outside of buffer");
173 return CURL_SEEKFUNC_FAIL;
176 buffer->posn = offset;
177 return CURL_SEEKFUNC_OK;
180 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
182 size_t size = eltsize * nmemb;
183 struct strbuf *buffer = buffer_;
185 strbuf_add(buffer, ptr, size);
186 return nmemb;
190 * A folded header continuation line starts with any number of spaces or
191 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
192 * It is not a continuation line if the line starts with any other character.
194 static inline int is_hdr_continuation(const char *ptr, const size_t size)
196 return size && (*ptr == ' ' || *ptr == '\t');
199 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
201 size_t size = eltsize * nmemb;
202 struct strvec *values = &http_auth.wwwauth_headers;
203 struct strbuf buf = STRBUF_INIT;
204 const char *val;
205 size_t val_len;
208 * Header lines may not come NULL-terminated from libcurl so we must
209 * limit all scans to the maximum length of the header line, or leverage
210 * strbufs for all operations.
212 * In addition, it is possible that header values can be split over
213 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
214 * but older servers may still emit them. A continuation header field
215 * value is identified as starting with a space or horizontal tab.
217 * The formal definition of a header field as given in RFC 7230 is:
219 * header-field = field-name ":" OWS field-value OWS
221 * field-name = token
222 * field-value = *( field-content / obs-fold )
223 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
224 * field-vchar = VCHAR / obs-text
226 * obs-fold = CRLF 1*( SP / HTAB )
227 * ; obsolete line folding
228 * ; see Section 3.2.4
231 /* Start of a new WWW-Authenticate header */
232 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
233 strbuf_add(&buf, val, val_len);
236 * Strip the CRLF that should be present at the end of each
237 * field as well as any trailing or leading whitespace from the
238 * value.
240 strbuf_trim(&buf);
242 strvec_push(values, buf.buf);
243 http_auth.header_is_last_match = 1;
244 goto exit;
248 * This line could be a continuation of the previously matched header
249 * field. If this is the case then we should append this value to the
250 * end of the previously consumed value.
252 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
254 * Trim the CRLF and any leading or trailing from this line.
256 strbuf_add(&buf, ptr, size);
257 strbuf_trim(&buf);
260 * At this point we should always have at least one existing
261 * value, even if it is empty. Do not bother appending the new
262 * value if this continuation header is itself empty.
264 if (!values->nr) {
265 BUG("should have at least one existing header value");
266 } else if (buf.len) {
267 char *prev = xstrdup(values->v[values->nr - 1]);
269 /* Join two non-empty values with a single space. */
270 const char *const sp = *prev ? " " : "";
272 strvec_pop(values);
273 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
274 free(prev);
277 goto exit;
280 /* Not a continuation of a previously matched auth header line. */
281 http_auth.header_is_last_match = 0;
284 * If this is a HTTP status line and not a header field, this signals
285 * a different HTTP response. libcurl writes all the output of all
286 * response headers of all responses, including redirects.
287 * We only care about the last HTTP request response's headers so clear
288 * the existing array.
290 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
291 strvec_clear(values);
293 exit:
294 strbuf_release(&buf);
295 return size;
298 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
299 void *data UNUSED)
301 return nmemb;
304 static void closedown_active_slot(struct active_request_slot *slot)
306 active_requests--;
307 slot->in_use = 0;
310 static void finish_active_slot(struct active_request_slot *slot)
312 closedown_active_slot(slot);
313 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
315 if (slot->finished)
316 (*slot->finished) = 1;
318 /* Store slot results so they can be read after the slot is reused */
319 if (slot->results) {
320 slot->results->curl_result = slot->curl_result;
321 slot->results->http_code = slot->http_code;
322 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
323 &slot->results->auth_avail);
325 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
326 &slot->results->http_connectcode);
329 /* Run callback if appropriate */
330 if (slot->callback_func)
331 slot->callback_func(slot->callback_data);
334 static void xmulti_remove_handle(struct active_request_slot *slot)
336 curl_multi_remove_handle(curlm, slot->curl);
339 static void process_curl_messages(void)
341 int num_messages;
342 struct active_request_slot *slot;
343 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
345 while (curl_message != NULL) {
346 if (curl_message->msg == CURLMSG_DONE) {
347 int curl_result = curl_message->data.result;
348 slot = active_queue_head;
349 while (slot != NULL &&
350 slot->curl != curl_message->easy_handle)
351 slot = slot->next;
352 if (slot) {
353 xmulti_remove_handle(slot);
354 slot->curl_result = curl_result;
355 finish_active_slot(slot);
356 } else {
357 fprintf(stderr, "Received DONE message for unknown request!\n");
359 } else {
360 fprintf(stderr, "Unknown CURL message received: %d\n",
361 (int)curl_message->msg);
363 curl_message = curl_multi_info_read(curlm, &num_messages);
367 static int http_options(const char *var, const char *value,
368 const struct config_context *ctx, void *data)
370 if (!strcmp("http.version", var)) {
371 return git_config_string(&curl_http_version, var, value);
373 if (!strcmp("http.sslverify", var)) {
374 curl_ssl_verify = git_config_bool(var, value);
375 return 0;
377 if (!strcmp("http.sslcipherlist", var))
378 return git_config_string(&ssl_cipherlist, var, value);
379 if (!strcmp("http.sslversion", var))
380 return git_config_string(&ssl_version, var, value);
381 if (!strcmp("http.sslcert", var))
382 return git_config_pathname(&ssl_cert, var, value);
383 if (!strcmp("http.sslcerttype", var))
384 return git_config_string(&ssl_cert_type, var, value);
385 if (!strcmp("http.sslkey", var))
386 return git_config_pathname(&ssl_key, var, value);
387 if (!strcmp("http.sslkeytype", var))
388 return git_config_string(&ssl_key_type, var, value);
389 if (!strcmp("http.sslcapath", var))
390 return git_config_pathname(&ssl_capath, var, value);
391 if (!strcmp("http.sslcainfo", var))
392 return git_config_pathname(&ssl_cainfo, var, value);
393 if (!strcmp("http.sslcertpasswordprotected", var)) {
394 ssl_cert_password_required = git_config_bool(var, value);
395 return 0;
397 if (!strcmp("http.ssltry", var)) {
398 curl_ssl_try = git_config_bool(var, value);
399 return 0;
401 if (!strcmp("http.sslbackend", var)) {
402 free(http_ssl_backend);
403 http_ssl_backend = xstrdup_or_null(value);
404 return 0;
407 if (!strcmp("http.schannelcheckrevoke", var)) {
408 http_schannel_check_revoke = git_config_bool(var, value);
409 return 0;
412 if (!strcmp("http.schannelusesslcainfo", var)) {
413 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
414 return 0;
417 if (!strcmp("http.minsessions", var)) {
418 min_curl_sessions = git_config_int(var, value, ctx->kvi);
419 if (min_curl_sessions > 1)
420 min_curl_sessions = 1;
421 return 0;
423 if (!strcmp("http.maxrequests", var)) {
424 max_requests = git_config_int(var, value, ctx->kvi);
425 return 0;
427 if (!strcmp("http.lowspeedlimit", var)) {
428 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
429 return 0;
431 if (!strcmp("http.lowspeedtime", var)) {
432 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
433 return 0;
436 if (!strcmp("http.noepsv", var)) {
437 curl_ftp_no_epsv = git_config_bool(var, value);
438 return 0;
440 if (!strcmp("http.proxy", var))
441 return git_config_string(&curl_http_proxy, var, value);
443 if (!strcmp("http.proxyauthmethod", var))
444 return git_config_string(&http_proxy_authmethod, var, value);
446 if (!strcmp("http.proxysslcert", var))
447 return git_config_string(&http_proxy_ssl_cert, var, value);
449 if (!strcmp("http.proxysslkey", var))
450 return git_config_string(&http_proxy_ssl_key, var, value);
452 if (!strcmp("http.proxysslcainfo", var))
453 return git_config_string(&http_proxy_ssl_ca_info, var, value);
455 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
456 proxy_ssl_cert_password_required = git_config_bool(var, value);
457 return 0;
460 if (!strcmp("http.cookiefile", var))
461 return git_config_pathname(&curl_cookie_file, var, value);
462 if (!strcmp("http.savecookies", var)) {
463 curl_save_cookies = git_config_bool(var, value);
464 return 0;
467 if (!strcmp("http.postbuffer", var)) {
468 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
469 if (http_post_buffer < 0)
470 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
471 if (http_post_buffer < LARGE_PACKET_MAX)
472 http_post_buffer = LARGE_PACKET_MAX;
473 return 0;
476 if (!strcmp("http.useragent", var))
477 return git_config_string(&user_agent, var, value);
479 if (!strcmp("http.emptyauth", var)) {
480 if (value && !strcmp("auto", value))
481 curl_empty_auth = -1;
482 else
483 curl_empty_auth = git_config_bool(var, value);
484 return 0;
487 if (!strcmp("http.delegation", var)) {
488 #ifdef CURLGSSAPI_DELEGATION_FLAG
489 return git_config_string(&curl_deleg, var, value);
490 #else
491 warning(_("Delegation control is not supported with cURL < 7.22.0"));
492 return 0;
493 #endif
496 if (!strcmp("http.pinnedpubkey", var)) {
497 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
498 return git_config_pathname(&ssl_pinnedkey, var, value);
499 #else
500 warning(_("Public key pinning not supported with cURL < 7.39.0"));
501 return 0;
502 #endif
505 if (!strcmp("http.extraheader", var)) {
506 if (!value) {
507 return config_error_nonbool(var);
508 } else if (!*value) {
509 string_list_clear(&extra_http_headers, 0);
510 } else {
511 string_list_append(&extra_http_headers, value);
513 return 0;
516 if (!strcmp("http.curloptresolve", var)) {
517 if (!value) {
518 return config_error_nonbool(var);
519 } else if (!*value) {
520 curl_slist_free_all(host_resolutions);
521 host_resolutions = NULL;
522 } else {
523 host_resolutions = curl_slist_append(host_resolutions, value);
525 return 0;
528 if (!strcmp("http.followredirects", var)) {
529 if (value && !strcmp(value, "initial"))
530 http_follow_config = HTTP_FOLLOW_INITIAL;
531 else if (git_config_bool(var, value))
532 http_follow_config = HTTP_FOLLOW_ALWAYS;
533 else
534 http_follow_config = HTTP_FOLLOW_NONE;
535 return 0;
538 /* Fall back on the default ones */
539 return git_default_config(var, value, ctx, data);
542 static int curl_empty_auth_enabled(void)
544 if (curl_empty_auth >= 0)
545 return curl_empty_auth;
548 * In the automatic case, kick in the empty-auth
549 * hack as long as we would potentially try some
550 * method more exotic than "Basic" or "Digest".
552 * But only do this when this is our second or
553 * subsequent request, as by then we know what
554 * methods are available.
556 if (http_auth_methods_restricted &&
557 (http_auth_methods & ~empty_auth_useless))
558 return 1;
559 return 0;
562 static void init_curl_http_auth(CURL *result)
564 if (!http_auth.username || !*http_auth.username) {
565 if (curl_empty_auth_enabled())
566 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
567 return;
570 credential_fill(&http_auth);
572 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
573 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
576 /* *var must be free-able */
577 static void var_override(const char **var, char *value)
579 if (value) {
580 free((void *)*var);
581 *var = xstrdup(value);
585 static void set_proxyauth_name_password(CURL *result)
587 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
588 proxy_auth.username);
589 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
590 proxy_auth.password);
593 static void init_curl_proxy_auth(CURL *result)
595 if (proxy_auth.username) {
596 if (!proxy_auth.password)
597 credential_fill(&proxy_auth);
598 set_proxyauth_name_password(result);
601 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
603 if (http_proxy_authmethod) {
604 int i;
605 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
606 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
607 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
608 proxy_authmethods[i].curlauth_param);
609 break;
612 if (i == ARRAY_SIZE(proxy_authmethods)) {
613 warning("unsupported proxy authentication method %s: using anyauth",
614 http_proxy_authmethod);
615 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
618 else
619 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
622 static int has_cert_password(void)
624 if (ssl_cert == NULL || ssl_cert_password_required != 1)
625 return 0;
626 if (!cert_auth.password) {
627 cert_auth.protocol = xstrdup("cert");
628 cert_auth.host = xstrdup("");
629 cert_auth.username = xstrdup("");
630 cert_auth.path = xstrdup(ssl_cert);
631 credential_fill(&cert_auth);
633 return 1;
636 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
637 static int has_proxy_cert_password(void)
639 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
640 return 0;
641 if (!proxy_cert_auth.password) {
642 proxy_cert_auth.protocol = xstrdup("cert");
643 proxy_cert_auth.host = xstrdup("");
644 proxy_cert_auth.username = xstrdup("");
645 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
646 credential_fill(&proxy_cert_auth);
648 return 1;
650 #endif
652 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
653 static void set_curl_keepalive(CURL *c)
655 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
658 #else
659 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
661 int ka = 1;
662 int rc;
663 socklen_t len = (socklen_t)sizeof(ka);
665 if (type != CURLSOCKTYPE_IPCXN)
666 return 0;
668 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
669 if (rc < 0)
670 warning_errno("unable to set SO_KEEPALIVE on socket");
672 return CURL_SOCKOPT_OK;
675 static void set_curl_keepalive(CURL *c)
677 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
679 #endif
681 /* Return 1 if redactions have been made, 0 otherwise. */
682 static int redact_sensitive_header(struct strbuf *header, size_t offset)
684 int ret = 0;
685 const char *sensitive_header;
687 if (trace_curl_redact &&
688 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
689 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
690 /* The first token is the type, which is OK to log */
691 while (isspace(*sensitive_header))
692 sensitive_header++;
693 while (*sensitive_header && !isspace(*sensitive_header))
694 sensitive_header++;
695 /* Everything else is opaque and possibly sensitive */
696 strbuf_setlen(header, sensitive_header - header->buf);
697 strbuf_addstr(header, " <redacted>");
698 ret = 1;
699 } else if (trace_curl_redact &&
700 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
701 struct strbuf redacted_header = STRBUF_INIT;
702 const char *cookie;
704 while (isspace(*sensitive_header))
705 sensitive_header++;
707 cookie = sensitive_header;
709 while (cookie) {
710 char *equals;
711 char *semicolon = strstr(cookie, "; ");
712 if (semicolon)
713 *semicolon = 0;
714 equals = strchrnul(cookie, '=');
715 if (!equals) {
716 /* invalid cookie, just append and continue */
717 strbuf_addstr(&redacted_header, cookie);
718 continue;
720 strbuf_add(&redacted_header, cookie, equals - cookie);
721 strbuf_addstr(&redacted_header, "=<redacted>");
722 if (semicolon) {
724 * There are more cookies. (Or, for some
725 * reason, the input string ends in "; ".)
727 strbuf_addstr(&redacted_header, "; ");
728 cookie = semicolon + strlen("; ");
729 } else {
730 cookie = NULL;
734 strbuf_setlen(header, sensitive_header - header->buf);
735 strbuf_addbuf(header, &redacted_header);
736 ret = 1;
738 return ret;
741 static int match_curl_h2_trace(const char *line, const char **out)
743 const char *p;
746 * curl prior to 8.1.0 gives us:
748 * h2h3 [<header-name>: <header-val>]
750 * Starting in 8.1.0, the first token became just "h2".
752 if (skip_iprefix(line, "h2h3 [", out) ||
753 skip_iprefix(line, "h2 [", out))
754 return 1;
757 * curl 8.3.0 uses:
758 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
759 * where <stream-id> is numeric.
761 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
762 while (isdigit(*p))
763 p++;
764 if (skip_prefix(p, "] [", out))
765 return 1;
768 return 0;
771 /* Redact headers in info */
772 static void redact_sensitive_info_header(struct strbuf *header)
774 const char *sensitive_header;
776 if (trace_curl_redact &&
777 match_curl_h2_trace(header->buf, &sensitive_header)) {
778 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
779 /* redaction ate our closing bracket */
780 strbuf_addch(header, ']');
785 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
787 struct strbuf out = STRBUF_INIT;
788 struct strbuf **headers, **header;
790 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
791 text, (long)size, (long)size);
792 trace_strbuf(&trace_curl, &out);
793 strbuf_reset(&out);
794 strbuf_add(&out, ptr, size);
795 headers = strbuf_split_max(&out, '\n', 0);
797 for (header = headers; *header; header++) {
798 if (hide_sensitive_header)
799 redact_sensitive_header(*header, 0);
800 strbuf_insertstr((*header), 0, text);
801 strbuf_insertstr((*header), strlen(text), ": ");
802 strbuf_rtrim((*header));
803 strbuf_addch((*header), '\n');
804 trace_strbuf(&trace_curl, (*header));
806 strbuf_list_free(headers);
807 strbuf_release(&out);
810 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
812 size_t i;
813 struct strbuf out = STRBUF_INIT;
814 unsigned int width = 60;
816 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
817 text, (long)size, (long)size);
818 trace_strbuf(&trace_curl, &out);
820 for (i = 0; i < size; i += width) {
821 size_t w;
823 strbuf_reset(&out);
824 strbuf_addf(&out, "%s: ", text);
825 for (w = 0; (w < width) && (i + w < size); w++) {
826 unsigned char ch = ptr[i + w];
828 strbuf_addch(&out,
829 (ch >= 0x20) && (ch < 0x80)
830 ? ch : '.');
832 strbuf_addch(&out, '\n');
833 trace_strbuf(&trace_curl, &out);
835 strbuf_release(&out);
838 static void curl_dump_info(char *data, size_t size)
840 struct strbuf buf = STRBUF_INIT;
842 strbuf_add(&buf, data, size);
844 redact_sensitive_info_header(&buf);
845 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
847 strbuf_release(&buf);
850 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
851 char *data, size_t size,
852 void *userp UNUSED)
854 const char *text;
855 enum { NO_FILTER = 0, DO_FILTER = 1 };
857 switch (type) {
858 case CURLINFO_TEXT:
859 curl_dump_info(data, size);
860 break;
861 case CURLINFO_HEADER_OUT:
862 text = "=> Send header";
863 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
864 break;
865 case CURLINFO_DATA_OUT:
866 if (trace_curl_data) {
867 text = "=> Send data";
868 curl_dump_data(text, (unsigned char *)data, size);
870 break;
871 case CURLINFO_SSL_DATA_OUT:
872 if (trace_curl_data) {
873 text = "=> Send SSL data";
874 curl_dump_data(text, (unsigned char *)data, size);
876 break;
877 case CURLINFO_HEADER_IN:
878 text = "<= Recv header";
879 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
880 break;
881 case CURLINFO_DATA_IN:
882 if (trace_curl_data) {
883 text = "<= Recv data";
884 curl_dump_data(text, (unsigned char *)data, size);
886 break;
887 case CURLINFO_SSL_DATA_IN:
888 if (trace_curl_data) {
889 text = "<= Recv SSL data";
890 curl_dump_data(text, (unsigned char *)data, size);
892 break;
894 default: /* we ignore unknown types by default */
895 return 0;
897 return 0;
900 void http_trace_curl_no_data(void)
902 trace_override_envvar(&trace_curl, "1");
903 trace_curl_data = 0;
906 void setup_curl_trace(CURL *handle)
908 if (!trace_want(&trace_curl))
909 return;
910 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
911 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
912 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
915 static void proto_list_append(struct strbuf *list, const char *proto)
917 if (!list)
918 return;
919 if (list->len)
920 strbuf_addch(list, ',');
921 strbuf_addstr(list, proto);
924 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
926 long bits = 0;
928 if (is_transport_allowed("http", from_user)) {
929 bits |= CURLPROTO_HTTP;
930 proto_list_append(list, "http");
932 if (is_transport_allowed("https", from_user)) {
933 bits |= CURLPROTO_HTTPS;
934 proto_list_append(list, "https");
936 if (is_transport_allowed("ftp", from_user)) {
937 bits |= CURLPROTO_FTP;
938 proto_list_append(list, "ftp");
940 if (is_transport_allowed("ftps", from_user)) {
941 bits |= CURLPROTO_FTPS;
942 proto_list_append(list, "ftps");
945 return bits;
948 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
949 static int get_curl_http_version_opt(const char *version_string, long *opt)
951 int i;
952 static struct {
953 const char *name;
954 long opt_token;
955 } choice[] = {
956 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
957 { "HTTP/2", CURL_HTTP_VERSION_2 }
960 for (i = 0; i < ARRAY_SIZE(choice); i++) {
961 if (!strcmp(version_string, choice[i].name)) {
962 *opt = choice[i].opt_token;
963 return 0;
967 warning("unknown value given to http.version: '%s'", version_string);
968 return -1; /* not found */
971 #endif
973 static CURL *get_curl_handle(void)
975 CURL *result = curl_easy_init();
977 if (!result)
978 die("curl_easy_init failed");
980 if (!curl_ssl_verify) {
981 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
982 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
983 } else {
984 /* Verify authenticity of the peer's certificate */
985 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
986 /* The name in the cert must match whom we tried to connect */
987 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
990 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
991 if (curl_http_version) {
992 long opt;
993 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
994 /* Set request use http version */
995 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
998 #endif
1000 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
1001 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1003 #ifdef CURLGSSAPI_DELEGATION_FLAG
1004 if (curl_deleg) {
1005 int i;
1006 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1007 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1008 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1009 curl_deleg_levels[i].curl_deleg_param);
1010 break;
1013 if (i == ARRAY_SIZE(curl_deleg_levels))
1014 warning("Unknown delegation method '%s': using default",
1015 curl_deleg);
1017 #endif
1019 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1020 !http_schannel_check_revoke) {
1021 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1022 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1023 #else
1024 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1025 #endif
1028 if (http_proactive_auth)
1029 init_curl_http_auth(result);
1031 if (getenv("GIT_SSL_VERSION"))
1032 ssl_version = getenv("GIT_SSL_VERSION");
1033 if (ssl_version && *ssl_version) {
1034 int i;
1035 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1036 if (!strcmp(ssl_version, sslversions[i].name)) {
1037 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1038 sslversions[i].ssl_version);
1039 break;
1042 if (i == ARRAY_SIZE(sslversions))
1043 warning("unsupported ssl version %s: using default",
1044 ssl_version);
1047 if (getenv("GIT_SSL_CIPHER_LIST"))
1048 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1049 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1050 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1051 ssl_cipherlist);
1053 if (ssl_cert)
1054 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1055 if (ssl_cert_type)
1056 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1057 if (has_cert_password())
1058 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1059 if (ssl_key)
1060 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1061 if (ssl_key_type)
1062 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1063 if (ssl_capath)
1064 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1065 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1066 if (ssl_pinnedkey)
1067 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1068 #endif
1069 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1070 !http_schannel_use_ssl_cainfo) {
1071 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1072 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1073 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1074 #endif
1075 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1076 if (ssl_cainfo)
1077 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1078 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1079 if (http_proxy_ssl_ca_info)
1080 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1081 #endif
1084 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1085 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1086 curl_low_speed_limit);
1087 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1088 curl_low_speed_time);
1091 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1092 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1094 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1096 struct strbuf buf = STRBUF_INIT;
1098 get_curl_allowed_protocols(0, &buf);
1099 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1100 strbuf_reset(&buf);
1102 get_curl_allowed_protocols(-1, &buf);
1103 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1104 strbuf_release(&buf);
1106 #else
1107 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1108 get_curl_allowed_protocols(0, NULL));
1109 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1110 get_curl_allowed_protocols(-1, NULL));
1111 #endif
1113 if (getenv("GIT_CURL_VERBOSE"))
1114 http_trace_curl_no_data();
1115 setup_curl_trace(result);
1116 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1117 trace_curl_data = 0;
1118 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1119 trace_curl_redact = 0;
1121 curl_easy_setopt(result, CURLOPT_USERAGENT,
1122 user_agent ? user_agent : git_user_agent());
1124 if (curl_ftp_no_epsv)
1125 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1127 if (curl_ssl_try)
1128 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1131 * CURL also examines these variables as a fallback; but we need to query
1132 * them here in order to decide whether to prompt for missing password (cf.
1133 * init_curl_proxy_auth()).
1135 * Unlike many other common environment variables, these are historically
1136 * lowercase only. It appears that CURL did not know this and implemented
1137 * only uppercase variants, which was later corrected to take both - with
1138 * the exception of http_proxy, which is lowercase only also in CURL. As
1139 * the lowercase versions are the historical quasi-standard, they take
1140 * precedence here, as in CURL.
1142 if (!curl_http_proxy) {
1143 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1144 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1145 var_override(&curl_http_proxy, getenv("https_proxy"));
1146 } else {
1147 var_override(&curl_http_proxy, getenv("http_proxy"));
1149 if (!curl_http_proxy) {
1150 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1151 var_override(&curl_http_proxy, getenv("all_proxy"));
1155 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1157 * Handle case with the empty http.proxy value here to keep
1158 * common code clean.
1159 * NB: empty option disables proxying at all.
1161 curl_easy_setopt(result, CURLOPT_PROXY, "");
1162 } else if (curl_http_proxy) {
1163 if (starts_with(curl_http_proxy, "socks5h"))
1164 curl_easy_setopt(result,
1165 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1166 else if (starts_with(curl_http_proxy, "socks5"))
1167 curl_easy_setopt(result,
1168 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1169 else if (starts_with(curl_http_proxy, "socks4a"))
1170 curl_easy_setopt(result,
1171 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1172 else if (starts_with(curl_http_proxy, "socks"))
1173 curl_easy_setopt(result,
1174 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1175 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1176 else if (starts_with(curl_http_proxy, "https")) {
1177 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1179 if (http_proxy_ssl_cert)
1180 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1182 if (http_proxy_ssl_key)
1183 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1185 if (has_proxy_cert_password())
1186 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1188 #endif
1189 if (strstr(curl_http_proxy, "://"))
1190 credential_from_url(&proxy_auth, curl_http_proxy);
1191 else {
1192 struct strbuf url = STRBUF_INIT;
1193 strbuf_addf(&url, "http://%s", curl_http_proxy);
1194 credential_from_url(&proxy_auth, url.buf);
1195 strbuf_release(&url);
1198 if (!proxy_auth.host)
1199 die("Invalid proxy URL '%s'", curl_http_proxy);
1201 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1202 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1203 var_override(&curl_no_proxy, getenv("no_proxy"));
1204 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1206 init_curl_proxy_auth(result);
1208 set_curl_keepalive(result);
1210 return result;
1213 static void set_from_env(const char **var, const char *envname)
1215 const char *val = getenv(envname);
1216 if (val)
1217 *var = val;
1220 void http_init(struct remote *remote, const char *url, int proactive_auth)
1222 char *low_speed_limit;
1223 char *low_speed_time;
1224 char *normalized_url;
1225 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1227 config.section = "http";
1228 config.key = NULL;
1229 config.collect_fn = http_options;
1230 config.cascade_fn = git_default_config;
1231 config.cb = NULL;
1233 http_is_verbose = 0;
1234 normalized_url = url_normalize(url, &config.url);
1236 git_config(urlmatch_config_entry, &config);
1237 free(normalized_url);
1238 string_list_clear(&config.vars, 1);
1240 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1241 if (http_ssl_backend) {
1242 const curl_ssl_backend **backends;
1243 struct strbuf buf = STRBUF_INIT;
1244 int i;
1246 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1247 case CURLSSLSET_UNKNOWN_BACKEND:
1248 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1249 "Supported SSL backends:"),
1250 http_ssl_backend);
1251 for (i = 0; backends[i]; i++)
1252 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1253 die("%s", buf.buf);
1254 case CURLSSLSET_NO_BACKENDS:
1255 die(_("Could not set SSL backend to '%s': "
1256 "cURL was built without SSL backends"),
1257 http_ssl_backend);
1258 case CURLSSLSET_TOO_LATE:
1259 die(_("Could not set SSL backend to '%s': already set"),
1260 http_ssl_backend);
1261 case CURLSSLSET_OK:
1262 break; /* Okay! */
1265 #endif
1267 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1268 die("curl_global_init failed");
1270 http_proactive_auth = proactive_auth;
1272 if (remote && remote->http_proxy)
1273 curl_http_proxy = xstrdup(remote->http_proxy);
1275 if (remote)
1276 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1278 pragma_header = curl_slist_append(http_copy_default_headers(),
1279 "Pragma: no-cache");
1280 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1281 "Pragma:");
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(no_pragma_header);
1366 no_pragma_header = NULL;
1368 curl_slist_free_all(host_resolutions);
1369 host_resolutions = NULL;
1371 if (curl_http_proxy) {
1372 free((void *)curl_http_proxy);
1373 curl_http_proxy = NULL;
1376 if (proxy_auth.password) {
1377 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1378 FREE_AND_NULL(proxy_auth.password);
1381 free((void *)curl_proxyuserpwd);
1382 curl_proxyuserpwd = NULL;
1384 free((void *)http_proxy_authmethod);
1385 http_proxy_authmethod = NULL;
1387 if (cert_auth.password) {
1388 memset(cert_auth.password, 0, strlen(cert_auth.password));
1389 FREE_AND_NULL(cert_auth.password);
1391 ssl_cert_password_required = 0;
1393 if (proxy_cert_auth.password) {
1394 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1395 FREE_AND_NULL(proxy_cert_auth.password);
1397 proxy_ssl_cert_password_required = 0;
1399 FREE_AND_NULL(cached_accept_language);
1402 struct active_request_slot *get_active_slot(void)
1404 struct active_request_slot *slot = active_queue_head;
1405 struct active_request_slot *newslot;
1407 int num_transfers;
1409 /* Wait for a slot to open up if the queue is full */
1410 while (active_requests >= max_requests) {
1411 curl_multi_perform(curlm, &num_transfers);
1412 if (num_transfers < active_requests)
1413 process_curl_messages();
1416 while (slot != NULL && slot->in_use)
1417 slot = slot->next;
1419 if (!slot) {
1420 newslot = xmalloc(sizeof(*newslot));
1421 newslot->curl = NULL;
1422 newslot->in_use = 0;
1423 newslot->next = NULL;
1425 slot = active_queue_head;
1426 if (!slot) {
1427 active_queue_head = newslot;
1428 } else {
1429 while (slot->next != NULL)
1430 slot = slot->next;
1431 slot->next = newslot;
1433 slot = newslot;
1436 if (!slot->curl) {
1437 slot->curl = curl_easy_duphandle(curl_default);
1438 curl_session_count++;
1441 active_requests++;
1442 slot->in_use = 1;
1443 slot->results = NULL;
1444 slot->finished = NULL;
1445 slot->callback_data = NULL;
1446 slot->callback_func = NULL;
1447 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1448 if (curl_save_cookies)
1449 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1450 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1451 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1452 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1453 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1454 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1455 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1456 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1457 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1458 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1459 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1460 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1463 * Default following to off unless "ALWAYS" is configured; this gives
1464 * callers a sane starting point, and they can tweak for individual
1465 * HTTP_FOLLOW_* cases themselves.
1467 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1468 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1469 else
1470 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1472 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1473 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1474 if (http_auth.password || curl_empty_auth_enabled())
1475 init_curl_http_auth(slot->curl);
1477 return slot;
1480 int start_active_slot(struct active_request_slot *slot)
1482 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1483 int num_transfers;
1485 if (curlm_result != CURLM_OK &&
1486 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1487 warning("curl_multi_add_handle failed: %s",
1488 curl_multi_strerror(curlm_result));
1489 active_requests--;
1490 slot->in_use = 0;
1491 return 0;
1495 * We know there must be something to do, since we just added
1496 * something.
1498 curl_multi_perform(curlm, &num_transfers);
1499 return 1;
1502 struct fill_chain {
1503 void *data;
1504 int (*fill)(void *);
1505 struct fill_chain *next;
1508 static struct fill_chain *fill_cfg;
1510 void add_fill_function(void *data, int (*fill)(void *))
1512 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1513 struct fill_chain **linkp = &fill_cfg;
1514 new_fill->data = data;
1515 new_fill->fill = fill;
1516 new_fill->next = NULL;
1517 while (*linkp)
1518 linkp = &(*linkp)->next;
1519 *linkp = new_fill;
1522 void fill_active_slots(void)
1524 struct active_request_slot *slot = active_queue_head;
1526 while (active_requests < max_requests) {
1527 struct fill_chain *fill;
1528 for (fill = fill_cfg; fill; fill = fill->next)
1529 if (fill->fill(fill->data))
1530 break;
1532 if (!fill)
1533 break;
1536 while (slot != NULL) {
1537 if (!slot->in_use && slot->curl != NULL
1538 && curl_session_count > min_curl_sessions) {
1539 curl_easy_cleanup(slot->curl);
1540 slot->curl = NULL;
1541 curl_session_count--;
1543 slot = slot->next;
1547 void step_active_slots(void)
1549 int num_transfers;
1550 CURLMcode curlm_result;
1552 do {
1553 curlm_result = curl_multi_perform(curlm, &num_transfers);
1554 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1555 if (num_transfers < active_requests) {
1556 process_curl_messages();
1557 fill_active_slots();
1561 void run_active_slot(struct active_request_slot *slot)
1563 fd_set readfds;
1564 fd_set writefds;
1565 fd_set excfds;
1566 int max_fd;
1567 struct timeval select_timeout;
1568 int finished = 0;
1570 slot->finished = &finished;
1571 while (!finished) {
1572 step_active_slots();
1574 if (slot->in_use) {
1575 long curl_timeout;
1576 curl_multi_timeout(curlm, &curl_timeout);
1577 if (curl_timeout == 0) {
1578 continue;
1579 } else if (curl_timeout == -1) {
1580 select_timeout.tv_sec = 0;
1581 select_timeout.tv_usec = 50000;
1582 } else {
1583 select_timeout.tv_sec = curl_timeout / 1000;
1584 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1587 max_fd = -1;
1588 FD_ZERO(&readfds);
1589 FD_ZERO(&writefds);
1590 FD_ZERO(&excfds);
1591 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1594 * It can happen that curl_multi_timeout returns a pathologically
1595 * long timeout when curl_multi_fdset returns no file descriptors
1596 * to read. See commit message for more details.
1598 if (max_fd < 0 &&
1599 (select_timeout.tv_sec > 0 ||
1600 select_timeout.tv_usec > 50000)) {
1601 select_timeout.tv_sec = 0;
1602 select_timeout.tv_usec = 50000;
1605 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1610 * The value of slot->finished we set before the loop was used
1611 * to set our "finished" variable when our request completed.
1613 * 1. The slot may not have been reused for another requst
1614 * yet, in which case it still has &finished.
1616 * 2. The slot may already be in-use to serve another request,
1617 * which can further be divided into two cases:
1619 * (a) If call run_active_slot() hasn't been called for that
1620 * other request, slot->finished would have been cleared
1621 * by get_active_slot() and has NULL.
1623 * (b) If the request did call run_active_slot(), then the
1624 * call would have updated slot->finished at the beginning
1625 * of this function, and with the clearing of the member
1626 * below, we would find that slot->finished is now NULL.
1628 * In all cases, slot->finished has no useful information to
1629 * anybody at this point. Some compilers warn us for
1630 * attempting to smuggle a pointer that is about to become
1631 * invalid, i.e. &finished. We clear it here to assure them.
1633 slot->finished = NULL;
1636 static void release_active_slot(struct active_request_slot *slot)
1638 closedown_active_slot(slot);
1639 if (slot->curl) {
1640 xmulti_remove_handle(slot);
1641 if (curl_session_count > min_curl_sessions) {
1642 curl_easy_cleanup(slot->curl);
1643 slot->curl = NULL;
1644 curl_session_count--;
1647 fill_active_slots();
1650 void finish_all_active_slots(void)
1652 struct active_request_slot *slot = active_queue_head;
1654 while (slot != NULL)
1655 if (slot->in_use) {
1656 run_active_slot(slot);
1657 slot = active_queue_head;
1658 } else {
1659 slot = slot->next;
1663 /* Helpers for modifying and creating URLs */
1664 static inline int needs_quote(int ch)
1666 if (((ch >= 'A') && (ch <= 'Z'))
1667 || ((ch >= 'a') && (ch <= 'z'))
1668 || ((ch >= '0') && (ch <= '9'))
1669 || (ch == '/')
1670 || (ch == '-')
1671 || (ch == '.'))
1672 return 0;
1673 return 1;
1676 static char *quote_ref_url(const char *base, const char *ref)
1678 struct strbuf buf = STRBUF_INIT;
1679 const char *cp;
1680 int ch;
1682 end_url_with_slash(&buf, base);
1684 for (cp = ref; (ch = *cp) != 0; cp++)
1685 if (needs_quote(ch))
1686 strbuf_addf(&buf, "%%%02x", ch);
1687 else
1688 strbuf_addch(&buf, *cp);
1690 return strbuf_detach(&buf, NULL);
1693 void append_remote_object_url(struct strbuf *buf, const char *url,
1694 const char *hex,
1695 int only_two_digit_prefix)
1697 end_url_with_slash(buf, url);
1699 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1700 if (!only_two_digit_prefix)
1701 strbuf_addstr(buf, hex + 2);
1704 char *get_remote_object_url(const char *url, const char *hex,
1705 int only_two_digit_prefix)
1707 struct strbuf buf = STRBUF_INIT;
1708 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1709 return strbuf_detach(&buf, NULL);
1712 void normalize_curl_result(CURLcode *result, long http_code,
1713 char *errorstr, size_t errorlen)
1716 * If we see a failing http code with CURLE_OK, we have turned off
1717 * FAILONERROR (to keep the server's custom error response), and should
1718 * translate the code into failure here.
1720 * Likewise, if we see a redirect (30x code), that means we turned off
1721 * redirect-following, and we should treat the result as an error.
1723 if (*result == CURLE_OK && http_code >= 300) {
1724 *result = CURLE_HTTP_RETURNED_ERROR;
1726 * Normally curl will already have put the "reason phrase"
1727 * from the server into curl_errorstr; unfortunately without
1728 * FAILONERROR it is lost, so we can give only the numeric
1729 * status code.
1731 xsnprintf(errorstr, errorlen,
1732 "The requested URL returned error: %ld",
1733 http_code);
1737 static int handle_curl_result(struct slot_results *results)
1739 normalize_curl_result(&results->curl_result, results->http_code,
1740 curl_errorstr, sizeof(curl_errorstr));
1742 if (results->curl_result == CURLE_OK) {
1743 credential_approve(&http_auth);
1744 credential_approve(&proxy_auth);
1745 credential_approve(&cert_auth);
1746 return HTTP_OK;
1747 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1749 * We can't tell from here whether it's a bad path, bad
1750 * certificate, bad password, or something else wrong
1751 * with the certificate. So we reject the credential to
1752 * avoid caching or saving a bad password.
1754 credential_reject(&cert_auth);
1755 return HTTP_NOAUTH;
1756 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1757 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1758 return HTTP_NOMATCHPUBLICKEY;
1759 #endif
1760 } else if (missing_target(results))
1761 return HTTP_MISSING_TARGET;
1762 else if (results->http_code == 401) {
1763 if (http_auth.username && http_auth.password) {
1764 credential_reject(&http_auth);
1765 return HTTP_NOAUTH;
1766 } else {
1767 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1768 if (results->auth_avail) {
1769 http_auth_methods &= results->auth_avail;
1770 http_auth_methods_restricted = 1;
1772 return HTTP_REAUTH;
1774 } else {
1775 if (results->http_connectcode == 407)
1776 credential_reject(&proxy_auth);
1777 if (!curl_errorstr[0])
1778 strlcpy(curl_errorstr,
1779 curl_easy_strerror(results->curl_result),
1780 sizeof(curl_errorstr));
1781 return HTTP_ERROR;
1785 int run_one_slot(struct active_request_slot *slot,
1786 struct slot_results *results)
1788 slot->results = results;
1789 if (!start_active_slot(slot)) {
1790 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1791 "failed to start HTTP request");
1792 return HTTP_START_FAILED;
1795 run_active_slot(slot);
1796 return handle_curl_result(results);
1799 struct curl_slist *http_copy_default_headers(void)
1801 struct curl_slist *headers = NULL;
1802 const struct string_list_item *item;
1804 for_each_string_list_item(item, &extra_http_headers)
1805 headers = curl_slist_append(headers, item->string);
1807 return headers;
1810 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1812 char *ptr;
1813 CURLcode ret;
1815 strbuf_reset(buf);
1816 ret = curl_easy_getinfo(curl, info, &ptr);
1817 if (!ret && ptr)
1818 strbuf_addstr(buf, ptr);
1819 return ret;
1823 * Check for and extract a content-type parameter. "raw"
1824 * should be positioned at the start of the potential
1825 * parameter, with any whitespace already removed.
1827 * "name" is the name of the parameter. The value is appended
1828 * to "out".
1830 static int extract_param(const char *raw, const char *name,
1831 struct strbuf *out)
1833 size_t len = strlen(name);
1835 if (strncasecmp(raw, name, len))
1836 return -1;
1837 raw += len;
1839 if (*raw != '=')
1840 return -1;
1841 raw++;
1843 while (*raw && !isspace(*raw) && *raw != ';')
1844 strbuf_addch(out, *raw++);
1845 return 0;
1849 * Extract a normalized version of the content type, with any
1850 * spaces suppressed, all letters lowercased, and no trailing ";"
1851 * or parameters.
1853 * Note that we will silently remove even invalid whitespace. For
1854 * example, "text / plain" is specifically forbidden by RFC 2616,
1855 * but "text/plain" is the only reasonable output, and this keeps
1856 * our code simple.
1858 * If the "charset" argument is not NULL, store the value of any
1859 * charset parameter there.
1861 * Example:
1862 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1863 * "text / plain" -> "text/plain"
1865 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1866 struct strbuf *charset)
1868 const char *p;
1870 strbuf_reset(type);
1871 strbuf_grow(type, raw->len);
1872 for (p = raw->buf; *p; p++) {
1873 if (isspace(*p))
1874 continue;
1875 if (*p == ';') {
1876 p++;
1877 break;
1879 strbuf_addch(type, tolower(*p));
1882 if (!charset)
1883 return;
1885 strbuf_reset(charset);
1886 while (*p) {
1887 while (isspace(*p) || *p == ';')
1888 p++;
1889 if (!extract_param(p, "charset", charset))
1890 return;
1891 while (*p && !isspace(*p))
1892 p++;
1895 if (!charset->len && starts_with(type->buf, "text/"))
1896 strbuf_addstr(charset, "ISO-8859-1");
1899 static void write_accept_language(struct strbuf *buf)
1902 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1903 * that, q-value will be smaller than 0.001, the minimum q-value the
1904 * HTTP specification allows. See
1905 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1907 const int MAX_DECIMAL_PLACES = 3;
1908 const int MAX_LANGUAGE_TAGS = 1000;
1909 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1910 char **language_tags = NULL;
1911 int num_langs = 0;
1912 const char *s = get_preferred_languages();
1913 int i;
1914 struct strbuf tag = STRBUF_INIT;
1916 /* Don't add Accept-Language header if no language is preferred. */
1917 if (!s)
1918 return;
1921 * Split the colon-separated string of preferred languages into
1922 * language_tags array.
1924 do {
1925 /* collect language tag */
1926 for (; *s && (isalnum(*s) || *s == '_'); s++)
1927 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1929 /* skip .codeset, @modifier and any other unnecessary parts */
1930 while (*s && *s != ':')
1931 s++;
1933 if (tag.len) {
1934 num_langs++;
1935 REALLOC_ARRAY(language_tags, num_langs);
1936 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1937 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1938 break;
1940 } while (*s++);
1942 /* write Accept-Language header into buf */
1943 if (num_langs) {
1944 int last_buf_len = 0;
1945 int max_q;
1946 int decimal_places;
1947 char q_format[32];
1949 /* add '*' */
1950 REALLOC_ARRAY(language_tags, num_langs + 1);
1951 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1953 /* compute decimal_places */
1954 for (max_q = 1, decimal_places = 0;
1955 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1956 decimal_places++, max_q *= 10)
1959 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1961 strbuf_addstr(buf, "Accept-Language: ");
1963 for (i = 0; i < num_langs; i++) {
1964 if (i > 0)
1965 strbuf_addstr(buf, ", ");
1967 strbuf_addstr(buf, language_tags[i]);
1969 if (i > 0)
1970 strbuf_addf(buf, q_format, max_q - i);
1972 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1973 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1974 break;
1977 last_buf_len = buf->len;
1981 /* free language tags -- last one is a static '*' */
1982 for (i = 0; i < num_langs - 1; i++)
1983 free(language_tags[i]);
1984 free(language_tags);
1988 * Get an Accept-Language header which indicates user's preferred languages.
1990 * Examples:
1991 * LANGUAGE= -> ""
1992 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1993 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1994 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1995 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1996 * LANGUAGE= LANG=C -> ""
1998 const char *http_get_accept_language_header(void)
2000 if (!cached_accept_language) {
2001 struct strbuf buf = STRBUF_INIT;
2002 write_accept_language(&buf);
2003 if (buf.len > 0)
2004 cached_accept_language = strbuf_detach(&buf, NULL);
2007 return cached_accept_language;
2010 static void http_opt_request_remainder(CURL *curl, off_t pos)
2012 char buf[128];
2013 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2014 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2017 /* http_request() targets */
2018 #define HTTP_REQUEST_STRBUF 0
2019 #define HTTP_REQUEST_FILE 1
2021 static int http_request(const char *url,
2022 void *result, int target,
2023 const struct http_get_options *options)
2025 struct active_request_slot *slot;
2026 struct slot_results results;
2027 struct curl_slist *headers = http_copy_default_headers();
2028 struct strbuf buf = STRBUF_INIT;
2029 const char *accept_language;
2030 int ret;
2032 slot = get_active_slot();
2033 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2035 if (!result) {
2036 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2037 } else {
2038 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2039 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2041 if (target == HTTP_REQUEST_FILE) {
2042 off_t posn = ftello(result);
2043 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2044 fwrite);
2045 if (posn > 0)
2046 http_opt_request_remainder(slot->curl, posn);
2047 } else
2048 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2049 fwrite_buffer);
2052 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2054 accept_language = http_get_accept_language_header();
2056 if (accept_language)
2057 headers = curl_slist_append(headers, accept_language);
2059 strbuf_addstr(&buf, "Pragma:");
2060 if (options && options->no_cache)
2061 strbuf_addstr(&buf, " no-cache");
2062 if (options && options->initial_request &&
2063 http_follow_config == HTTP_FOLLOW_INITIAL)
2064 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2066 headers = curl_slist_append(headers, buf.buf);
2068 /* Add additional headers here */
2069 if (options && options->extra_headers) {
2070 const struct string_list_item *item;
2071 for_each_string_list_item(item, options->extra_headers) {
2072 headers = curl_slist_append(headers, item->string);
2076 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2077 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2078 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2079 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2081 ret = run_one_slot(slot, &results);
2083 if (options && options->content_type) {
2084 struct strbuf raw = STRBUF_INIT;
2085 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2086 extract_content_type(&raw, options->content_type,
2087 options->charset);
2088 strbuf_release(&raw);
2091 if (options && options->effective_url)
2092 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2093 options->effective_url);
2095 curl_slist_free_all(headers);
2096 strbuf_release(&buf);
2098 return ret;
2102 * Update the "base" url to a more appropriate value, as deduced by
2103 * redirects seen when requesting a URL starting with "url".
2105 * The "asked" parameter is a URL that we asked curl to access, and must begin
2106 * with "base".
2108 * The "got" parameter is the URL that curl reported to us as where we ended
2109 * up.
2111 * Returns 1 if we updated the base url, 0 otherwise.
2113 * Our basic strategy is to compare "base" and "asked" to find the bits
2114 * specific to our request. We then strip those bits off of "got" to yield the
2115 * new base. So for example, if our base is "http://example.com/foo.git",
2116 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2117 * with "https://other.example.com/foo.git/info/refs". We would want the
2118 * new URL to become "https://other.example.com/foo.git".
2120 * Note that this assumes a sane redirect scheme. It's entirely possible
2121 * in the example above to end up at a URL that does not even end in
2122 * "info/refs". In such a case we die. There's not much we can do, such a
2123 * scheme is unlikely to represent a real git repository, and failing to
2124 * rewrite the base opens options for malicious redirects to do funny things.
2126 static int update_url_from_redirect(struct strbuf *base,
2127 const char *asked,
2128 const struct strbuf *got)
2130 const char *tail;
2131 size_t new_len;
2133 if (!strcmp(asked, got->buf))
2134 return 0;
2136 if (!skip_prefix(asked, base->buf, &tail))
2137 BUG("update_url_from_redirect: %s is not a superset of %s",
2138 asked, base->buf);
2140 new_len = got->len;
2141 if (!strip_suffix_mem(got->buf, &new_len, tail))
2142 die(_("unable to update url base from redirection:\n"
2143 " asked for: %s\n"
2144 " redirect: %s"),
2145 asked, got->buf);
2147 strbuf_reset(base);
2148 strbuf_add(base, got->buf, new_len);
2150 return 1;
2153 static int http_request_reauth(const char *url,
2154 void *result, int target,
2155 struct http_get_options *options)
2157 int ret = http_request(url, result, target, options);
2159 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2160 return ret;
2162 if (options && options->effective_url && options->base_url) {
2163 if (update_url_from_redirect(options->base_url,
2164 url, options->effective_url)) {
2165 credential_from_url(&http_auth, options->base_url->buf);
2166 url = options->effective_url->buf;
2170 if (ret != HTTP_REAUTH)
2171 return ret;
2174 * The previous request may have put cruft into our output stream; we
2175 * should clear it out before making our next request.
2177 switch (target) {
2178 case HTTP_REQUEST_STRBUF:
2179 strbuf_reset(result);
2180 break;
2181 case HTTP_REQUEST_FILE:
2182 if (fflush(result)) {
2183 error_errno("unable to flush a file");
2184 return HTTP_START_FAILED;
2186 rewind(result);
2187 if (ftruncate(fileno(result), 0) < 0) {
2188 error_errno("unable to truncate a file");
2189 return HTTP_START_FAILED;
2191 break;
2192 default:
2193 BUG("Unknown http_request target");
2196 credential_fill(&http_auth);
2198 return http_request(url, result, target, options);
2201 int http_get_strbuf(const char *url,
2202 struct strbuf *result,
2203 struct http_get_options *options)
2205 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2209 * Downloads a URL and stores the result in the given file.
2211 * If a previous interrupted download is detected (i.e. a previous temporary
2212 * file is still around) the download is resumed.
2214 int http_get_file(const char *url, const char *filename,
2215 struct http_get_options *options)
2217 int ret;
2218 struct strbuf tmpfile = STRBUF_INIT;
2219 FILE *result;
2221 strbuf_addf(&tmpfile, "%s.temp", filename);
2222 result = fopen(tmpfile.buf, "a");
2223 if (!result) {
2224 error("Unable to open local file %s", tmpfile.buf);
2225 ret = HTTP_ERROR;
2226 goto cleanup;
2229 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2230 fclose(result);
2232 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2233 ret = HTTP_ERROR;
2234 cleanup:
2235 strbuf_release(&tmpfile);
2236 return ret;
2239 int http_fetch_ref(const char *base, struct ref *ref)
2241 struct http_get_options options = {0};
2242 char *url;
2243 struct strbuf buffer = STRBUF_INIT;
2244 int ret = -1;
2246 options.no_cache = 1;
2248 url = quote_ref_url(base, ref->name);
2249 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2250 strbuf_rtrim(&buffer);
2251 if (buffer.len == the_hash_algo->hexsz)
2252 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2253 else if (starts_with(buffer.buf, "ref: ")) {
2254 ref->symref = xstrdup(buffer.buf + 5);
2255 ret = 0;
2259 strbuf_release(&buffer);
2260 free(url);
2261 return ret;
2264 /* Helpers for fetching packs */
2265 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2267 char *url, *tmp;
2268 struct strbuf buf = STRBUF_INIT;
2270 if (http_is_verbose)
2271 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2273 end_url_with_slash(&buf, base_url);
2274 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2275 url = strbuf_detach(&buf, NULL);
2277 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2278 tmp = strbuf_detach(&buf, NULL);
2280 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2281 error("Unable to get pack index %s", url);
2282 FREE_AND_NULL(tmp);
2285 free(url);
2286 return tmp;
2289 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2290 unsigned char *sha1, const char *base_url)
2292 struct packed_git *new_pack;
2293 char *tmp_idx = NULL;
2294 int ret;
2296 if (has_pack_index(sha1)) {
2297 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2298 if (!new_pack)
2299 return -1; /* parse_pack_index() already issued error message */
2300 goto add_pack;
2303 tmp_idx = fetch_pack_index(sha1, base_url);
2304 if (!tmp_idx)
2305 return -1;
2307 new_pack = parse_pack_index(sha1, tmp_idx);
2308 if (!new_pack) {
2309 unlink(tmp_idx);
2310 free(tmp_idx);
2312 return -1; /* parse_pack_index() already issued error message */
2315 ret = verify_pack_index(new_pack);
2316 if (!ret) {
2317 close_pack_index(new_pack);
2318 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2320 free(tmp_idx);
2321 if (ret)
2322 return -1;
2324 add_pack:
2325 new_pack->next = *packs_head;
2326 *packs_head = new_pack;
2327 return 0;
2330 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2332 struct http_get_options options = {0};
2333 int ret = 0;
2334 char *url;
2335 const char *data;
2336 struct strbuf buf = STRBUF_INIT;
2337 struct object_id oid;
2339 end_url_with_slash(&buf, base_url);
2340 strbuf_addstr(&buf, "objects/info/packs");
2341 url = strbuf_detach(&buf, NULL);
2343 options.no_cache = 1;
2344 ret = http_get_strbuf(url, &buf, &options);
2345 if (ret != HTTP_OK)
2346 goto cleanup;
2348 data = buf.buf;
2349 while (*data) {
2350 if (skip_prefix(data, "P pack-", &data) &&
2351 !parse_oid_hex(data, &oid, &data) &&
2352 skip_prefix(data, ".pack", &data) &&
2353 (*data == '\n' || *data == '\0')) {
2354 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2355 } else {
2356 data = strchrnul(data, '\n');
2358 if (*data)
2359 data++; /* skip past newline */
2362 cleanup:
2363 free(url);
2364 return ret;
2367 void release_http_pack_request(struct http_pack_request *preq)
2369 if (preq->packfile) {
2370 fclose(preq->packfile);
2371 preq->packfile = NULL;
2373 preq->slot = NULL;
2374 strbuf_release(&preq->tmpfile);
2375 free(preq->url);
2376 free(preq);
2379 static const char *default_index_pack_args[] =
2380 {"index-pack", "--stdin", NULL};
2382 int finish_http_pack_request(struct http_pack_request *preq)
2384 struct child_process ip = CHILD_PROCESS_INIT;
2385 int tmpfile_fd;
2386 int ret = 0;
2388 fclose(preq->packfile);
2389 preq->packfile = NULL;
2391 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2393 ip.git_cmd = 1;
2394 ip.in = tmpfile_fd;
2395 strvec_pushv(&ip.args, preq->index_pack_args ?
2396 preq->index_pack_args :
2397 default_index_pack_args);
2399 if (preq->preserve_index_pack_stdout)
2400 ip.out = 0;
2401 else
2402 ip.no_stdout = 1;
2404 if (run_command(&ip)) {
2405 ret = -1;
2406 goto cleanup;
2409 cleanup:
2410 close(tmpfile_fd);
2411 unlink(preq->tmpfile.buf);
2412 return ret;
2415 void http_install_packfile(struct packed_git *p,
2416 struct packed_git **list_to_remove_from)
2418 struct packed_git **lst = list_to_remove_from;
2420 while (*lst != p)
2421 lst = &((*lst)->next);
2422 *lst = (*lst)->next;
2424 install_packed_git(the_repository, p);
2427 struct http_pack_request *new_http_pack_request(
2428 const unsigned char *packed_git_hash, const char *base_url) {
2430 struct strbuf buf = STRBUF_INIT;
2432 end_url_with_slash(&buf, base_url);
2433 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2434 hash_to_hex(packed_git_hash));
2435 return new_direct_http_pack_request(packed_git_hash,
2436 strbuf_detach(&buf, NULL));
2439 struct http_pack_request *new_direct_http_pack_request(
2440 const unsigned char *packed_git_hash, char *url)
2442 off_t prev_posn = 0;
2443 struct http_pack_request *preq;
2445 CALLOC_ARRAY(preq, 1);
2446 strbuf_init(&preq->tmpfile, 0);
2448 preq->url = url;
2450 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2451 preq->packfile = fopen(preq->tmpfile.buf, "a");
2452 if (!preq->packfile) {
2453 error("Unable to open local file %s for pack",
2454 preq->tmpfile.buf);
2455 goto abort;
2458 preq->slot = get_active_slot();
2459 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2460 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2461 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2462 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2463 no_pragma_header);
2466 * If there is data present from a previous transfer attempt,
2467 * resume where it left off
2469 prev_posn = ftello(preq->packfile);
2470 if (prev_posn>0) {
2471 if (http_is_verbose)
2472 fprintf(stderr,
2473 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2474 hash_to_hex(packed_git_hash),
2475 (uintmax_t)prev_posn);
2476 http_opt_request_remainder(preq->slot->curl, prev_posn);
2479 return preq;
2481 abort:
2482 strbuf_release(&preq->tmpfile);
2483 free(preq->url);
2484 free(preq);
2485 return NULL;
2488 /* Helpers for fetching objects (loose) */
2489 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2490 void *data)
2492 unsigned char expn[4096];
2493 size_t size = eltsize * nmemb;
2494 int posn = 0;
2495 struct http_object_request *freq = data;
2496 struct active_request_slot *slot = freq->slot;
2498 if (slot) {
2499 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2500 &slot->http_code);
2501 if (c != CURLE_OK)
2502 BUG("curl_easy_getinfo for HTTP code failed: %s",
2503 curl_easy_strerror(c));
2504 if (slot->http_code >= 300)
2505 return nmemb;
2508 do {
2509 ssize_t retval = xwrite(freq->localfile,
2510 (char *) ptr + posn, size - posn);
2511 if (retval < 0)
2512 return posn / eltsize;
2513 posn += retval;
2514 } while (posn < size);
2516 freq->stream.avail_in = size;
2517 freq->stream.next_in = (void *)ptr;
2518 do {
2519 freq->stream.next_out = expn;
2520 freq->stream.avail_out = sizeof(expn);
2521 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2522 the_hash_algo->update_fn(&freq->c, expn,
2523 sizeof(expn) - freq->stream.avail_out);
2524 } while (freq->stream.avail_in && freq->zret == Z_OK);
2525 return nmemb;
2528 struct http_object_request *new_http_object_request(const char *base_url,
2529 const struct object_id *oid)
2531 char *hex = oid_to_hex(oid);
2532 struct strbuf filename = STRBUF_INIT;
2533 struct strbuf prevfile = STRBUF_INIT;
2534 int prevlocal;
2535 char prev_buf[PREV_BUF_SIZE];
2536 ssize_t prev_read = 0;
2537 off_t prev_posn = 0;
2538 struct http_object_request *freq;
2540 CALLOC_ARRAY(freq, 1);
2541 strbuf_init(&freq->tmpfile, 0);
2542 oidcpy(&freq->oid, oid);
2543 freq->localfile = -1;
2545 loose_object_path(the_repository, &filename, oid);
2546 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2548 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2549 unlink_or_warn(prevfile.buf);
2550 rename(freq->tmpfile.buf, prevfile.buf);
2551 unlink_or_warn(freq->tmpfile.buf);
2552 strbuf_release(&filename);
2554 if (freq->localfile != -1)
2555 error("fd leakage in start: %d", freq->localfile);
2556 freq->localfile = open(freq->tmpfile.buf,
2557 O_WRONLY | O_CREAT | O_EXCL, 0666);
2559 * This could have failed due to the "lazy directory creation";
2560 * try to mkdir the last path component.
2562 if (freq->localfile < 0 && errno == ENOENT) {
2563 char *dir = strrchr(freq->tmpfile.buf, '/');
2564 if (dir) {
2565 *dir = 0;
2566 mkdir(freq->tmpfile.buf, 0777);
2567 *dir = '/';
2569 freq->localfile = open(freq->tmpfile.buf,
2570 O_WRONLY | O_CREAT | O_EXCL, 0666);
2573 if (freq->localfile < 0) {
2574 error_errno("Couldn't create temporary file %s",
2575 freq->tmpfile.buf);
2576 goto abort;
2579 git_inflate_init(&freq->stream);
2581 the_hash_algo->init_fn(&freq->c);
2583 freq->url = get_remote_object_url(base_url, hex, 0);
2586 * If a previous temp file is present, process what was already
2587 * fetched.
2589 prevlocal = open(prevfile.buf, O_RDONLY);
2590 if (prevlocal != -1) {
2591 do {
2592 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2593 if (prev_read>0) {
2594 if (fwrite_sha1_file(prev_buf,
2596 prev_read,
2597 freq) == prev_read) {
2598 prev_posn += prev_read;
2599 } else {
2600 prev_read = -1;
2603 } while (prev_read > 0);
2604 close(prevlocal);
2606 unlink_or_warn(prevfile.buf);
2607 strbuf_release(&prevfile);
2610 * Reset inflate/SHA1 if there was an error reading the previous temp
2611 * file; also rewind to the beginning of the local file.
2613 if (prev_read == -1) {
2614 memset(&freq->stream, 0, sizeof(freq->stream));
2615 git_inflate_init(&freq->stream);
2616 the_hash_algo->init_fn(&freq->c);
2617 if (prev_posn>0) {
2618 prev_posn = 0;
2619 lseek(freq->localfile, 0, SEEK_SET);
2620 if (ftruncate(freq->localfile, 0) < 0) {
2621 error_errno("Couldn't truncate temporary file %s",
2622 freq->tmpfile.buf);
2623 goto abort;
2628 freq->slot = get_active_slot();
2630 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2631 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2632 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2633 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2634 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2635 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2638 * If we have successfully processed data from a previous fetch
2639 * attempt, only fetch the data we don't already have.
2641 if (prev_posn>0) {
2642 if (http_is_verbose)
2643 fprintf(stderr,
2644 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2645 hex, (uintmax_t)prev_posn);
2646 http_opt_request_remainder(freq->slot->curl, prev_posn);
2649 return freq;
2651 abort:
2652 strbuf_release(&prevfile);
2653 free(freq->url);
2654 free(freq);
2655 return NULL;
2658 void process_http_object_request(struct http_object_request *freq)
2660 if (!freq->slot)
2661 return;
2662 freq->curl_result = freq->slot->curl_result;
2663 freq->http_code = freq->slot->http_code;
2664 freq->slot = NULL;
2667 int finish_http_object_request(struct http_object_request *freq)
2669 struct stat st;
2670 struct strbuf filename = STRBUF_INIT;
2672 close(freq->localfile);
2673 freq->localfile = -1;
2675 process_http_object_request(freq);
2677 if (freq->http_code == 416) {
2678 warning("requested range invalid; we may already have all the data.");
2679 } else if (freq->curl_result != CURLE_OK) {
2680 if (stat(freq->tmpfile.buf, &st) == 0)
2681 if (st.st_size == 0)
2682 unlink_or_warn(freq->tmpfile.buf);
2683 return -1;
2686 git_inflate_end(&freq->stream);
2687 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2688 if (freq->zret != Z_STREAM_END) {
2689 unlink_or_warn(freq->tmpfile.buf);
2690 return -1;
2692 if (!oideq(&freq->oid, &freq->real_oid)) {
2693 unlink_or_warn(freq->tmpfile.buf);
2694 return -1;
2696 loose_object_path(the_repository, &filename, &freq->oid);
2697 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2698 strbuf_release(&filename);
2700 return freq->rename;
2703 void abort_http_object_request(struct http_object_request *freq)
2705 unlink_or_warn(freq->tmpfile.buf);
2707 release_http_object_request(freq);
2710 void release_http_object_request(struct http_object_request *freq)
2712 if (freq->localfile != -1) {
2713 close(freq->localfile);
2714 freq->localfile = -1;
2716 FREE_AND_NULL(freq->url);
2717 if (freq->slot) {
2718 freq->slot->callback_func = NULL;
2719 freq->slot->callback_data = NULL;
2720 release_active_slot(freq->slot);
2721 freq->slot = NULL;
2723 strbuf_release(&freq->tmpfile);