diff-files: integrate with sparse index
[git.git] / http.c
blobd5d82c5230f84194442634a84a894d5af74036cc
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 "transport.h"
16 #include "packfile.h"
17 #include "protocol.h"
18 #include "string-list.h"
19 #include "object-store.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 curl_slist *no_pragma_header;
132 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
134 static struct curl_slist *host_resolutions;
136 static struct active_request_slot *active_queue_head;
138 static char *cached_accept_language;
140 static char *http_ssl_backend;
142 static int http_schannel_check_revoke = 1;
144 * With the backend being set to `schannel`, setting sslCAinfo would override
145 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
146 * by default.
148 static int http_schannel_use_ssl_cainfo;
150 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
152 size_t size = eltsize * nmemb;
153 struct buffer *buffer = buffer_;
155 if (size > buffer->buf.len - buffer->posn)
156 size = buffer->buf.len - buffer->posn;
157 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
158 buffer->posn += size;
160 return size / eltsize;
163 int seek_buffer(void *clientp, curl_off_t offset, int origin)
165 struct buffer *buffer = clientp;
167 if (origin != SEEK_SET)
168 BUG("seek_buffer only handles SEEK_SET");
169 if (offset < 0 || offset >= buffer->buf.len) {
170 error("curl seek would be outside of buffer");
171 return CURL_SEEKFUNC_FAIL;
174 buffer->posn = offset;
175 return CURL_SEEKFUNC_OK;
178 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
180 size_t size = eltsize * nmemb;
181 struct strbuf *buffer = buffer_;
183 strbuf_add(buffer, ptr, size);
184 return nmemb;
188 * A folded header continuation line starts with any number of spaces or
189 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
190 * It is not a continuation line if the line starts with any other character.
192 static inline int is_hdr_continuation(const char *ptr, const size_t size)
194 return size && (*ptr == ' ' || *ptr == '\t');
197 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p)
199 size_t size = eltsize * nmemb;
200 struct strvec *values = &http_auth.wwwauth_headers;
201 struct strbuf buf = STRBUF_INIT;
202 const char *val;
203 size_t val_len;
206 * Header lines may not come NULL-terminated from libcurl so we must
207 * limit all scans to the maximum length of the header line, or leverage
208 * strbufs for all operations.
210 * In addition, it is possible that header values can be split over
211 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
212 * but older servers may still emit them. A continuation header field
213 * value is identified as starting with a space or horizontal tab.
215 * The formal definition of a header field as given in RFC 7230 is:
217 * header-field = field-name ":" OWS field-value OWS
219 * field-name = token
220 * field-value = *( field-content / obs-fold )
221 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
222 * field-vchar = VCHAR / obs-text
224 * obs-fold = CRLF 1*( SP / HTAB )
225 * ; obsolete line folding
226 * ; see Section 3.2.4
229 /* Start of a new WWW-Authenticate header */
230 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
231 strbuf_add(&buf, val, val_len);
234 * Strip the CRLF that should be present at the end of each
235 * field as well as any trailing or leading whitespace from the
236 * value.
238 strbuf_trim(&buf);
240 strvec_push(values, buf.buf);
241 http_auth.header_is_last_match = 1;
242 goto exit;
246 * This line could be a continuation of the previously matched header
247 * field. If this is the case then we should append this value to the
248 * end of the previously consumed value.
250 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
252 * Trim the CRLF and any leading or trailing from this line.
254 strbuf_add(&buf, ptr, size);
255 strbuf_trim(&buf);
258 * At this point we should always have at least one existing
259 * value, even if it is empty. Do not bother appending the new
260 * value if this continuation header is itself empty.
262 if (!values->nr) {
263 BUG("should have at least one existing header value");
264 } else if (buf.len) {
265 char *prev = xstrdup(values->v[values->nr - 1]);
267 /* Join two non-empty values with a single space. */
268 const char *const sp = *prev ? " " : "";
270 strvec_pop(values);
271 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
272 free(prev);
275 goto exit;
278 /* Not a continuation of a previously matched auth header line. */
279 http_auth.header_is_last_match = 0;
282 * If this is a HTTP status line and not a header field, this signals
283 * a different HTTP response. libcurl writes all the output of all
284 * response headers of all responses, including redirects.
285 * We only care about the last HTTP request response's headers so clear
286 * the existing array.
288 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
289 strvec_clear(values);
291 exit:
292 strbuf_release(&buf);
293 return size;
296 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
298 return nmemb;
301 static void closedown_active_slot(struct active_request_slot *slot)
303 active_requests--;
304 slot->in_use = 0;
307 static void finish_active_slot(struct active_request_slot *slot)
309 closedown_active_slot(slot);
310 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
312 if (slot->finished)
313 (*slot->finished) = 1;
315 /* Store slot results so they can be read after the slot is reused */
316 if (slot->results) {
317 slot->results->curl_result = slot->curl_result;
318 slot->results->http_code = slot->http_code;
319 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
320 &slot->results->auth_avail);
322 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
323 &slot->results->http_connectcode);
326 /* Run callback if appropriate */
327 if (slot->callback_func)
328 slot->callback_func(slot->callback_data);
331 static void xmulti_remove_handle(struct active_request_slot *slot)
333 curl_multi_remove_handle(curlm, slot->curl);
336 static void process_curl_messages(void)
338 int num_messages;
339 struct active_request_slot *slot;
340 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
342 while (curl_message != NULL) {
343 if (curl_message->msg == CURLMSG_DONE) {
344 int curl_result = curl_message->data.result;
345 slot = active_queue_head;
346 while (slot != NULL &&
347 slot->curl != curl_message->easy_handle)
348 slot = slot->next;
349 if (slot) {
350 xmulti_remove_handle(slot);
351 slot->curl_result = curl_result;
352 finish_active_slot(slot);
353 } else {
354 fprintf(stderr, "Received DONE message for unknown request!\n");
356 } else {
357 fprintf(stderr, "Unknown CURL message received: %d\n",
358 (int)curl_message->msg);
360 curl_message = curl_multi_info_read(curlm, &num_messages);
364 static int http_options(const char *var, const char *value, void *cb)
366 if (!strcmp("http.version", var)) {
367 return git_config_string(&curl_http_version, var, value);
369 if (!strcmp("http.sslverify", var)) {
370 curl_ssl_verify = git_config_bool(var, value);
371 return 0;
373 if (!strcmp("http.sslcipherlist", var))
374 return git_config_string(&ssl_cipherlist, var, value);
375 if (!strcmp("http.sslversion", var))
376 return git_config_string(&ssl_version, var, value);
377 if (!strcmp("http.sslcert", var))
378 return git_config_pathname(&ssl_cert, var, value);
379 if (!strcmp("http.sslcerttype", var))
380 return git_config_string(&ssl_cert_type, var, value);
381 if (!strcmp("http.sslkey", var))
382 return git_config_pathname(&ssl_key, var, value);
383 if (!strcmp("http.sslkeytype", var))
384 return git_config_string(&ssl_key_type, var, value);
385 if (!strcmp("http.sslcapath", var))
386 return git_config_pathname(&ssl_capath, var, value);
387 if (!strcmp("http.sslcainfo", var))
388 return git_config_pathname(&ssl_cainfo, var, value);
389 if (!strcmp("http.sslcertpasswordprotected", var)) {
390 ssl_cert_password_required = git_config_bool(var, value);
391 return 0;
393 if (!strcmp("http.ssltry", var)) {
394 curl_ssl_try = git_config_bool(var, value);
395 return 0;
397 if (!strcmp("http.sslbackend", var)) {
398 free(http_ssl_backend);
399 http_ssl_backend = xstrdup_or_null(value);
400 return 0;
403 if (!strcmp("http.schannelcheckrevoke", var)) {
404 http_schannel_check_revoke = git_config_bool(var, value);
405 return 0;
408 if (!strcmp("http.schannelusesslcainfo", var)) {
409 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
410 return 0;
413 if (!strcmp("http.minsessions", var)) {
414 min_curl_sessions = git_config_int(var, value);
415 if (min_curl_sessions > 1)
416 min_curl_sessions = 1;
417 return 0;
419 if (!strcmp("http.maxrequests", var)) {
420 max_requests = git_config_int(var, value);
421 return 0;
423 if (!strcmp("http.lowspeedlimit", var)) {
424 curl_low_speed_limit = (long)git_config_int(var, value);
425 return 0;
427 if (!strcmp("http.lowspeedtime", var)) {
428 curl_low_speed_time = (long)git_config_int(var, value);
429 return 0;
432 if (!strcmp("http.noepsv", var)) {
433 curl_ftp_no_epsv = git_config_bool(var, value);
434 return 0;
436 if (!strcmp("http.proxy", var))
437 return git_config_string(&curl_http_proxy, var, value);
439 if (!strcmp("http.proxyauthmethod", var))
440 return git_config_string(&http_proxy_authmethod, var, value);
442 if (!strcmp("http.proxysslcert", var))
443 return git_config_string(&http_proxy_ssl_cert, var, value);
445 if (!strcmp("http.proxysslkey", var))
446 return git_config_string(&http_proxy_ssl_key, var, value);
448 if (!strcmp("http.proxysslcainfo", var))
449 return git_config_string(&http_proxy_ssl_ca_info, var, value);
451 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
452 proxy_ssl_cert_password_required = git_config_bool(var, value);
453 return 0;
456 if (!strcmp("http.cookiefile", var))
457 return git_config_pathname(&curl_cookie_file, var, value);
458 if (!strcmp("http.savecookies", var)) {
459 curl_save_cookies = git_config_bool(var, value);
460 return 0;
463 if (!strcmp("http.postbuffer", var)) {
464 http_post_buffer = git_config_ssize_t(var, value);
465 if (http_post_buffer < 0)
466 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
467 if (http_post_buffer < LARGE_PACKET_MAX)
468 http_post_buffer = LARGE_PACKET_MAX;
469 return 0;
472 if (!strcmp("http.useragent", var))
473 return git_config_string(&user_agent, var, value);
475 if (!strcmp("http.emptyauth", var)) {
476 if (value && !strcmp("auto", value))
477 curl_empty_auth = -1;
478 else
479 curl_empty_auth = git_config_bool(var, value);
480 return 0;
483 if (!strcmp("http.delegation", var)) {
484 #ifdef CURLGSSAPI_DELEGATION_FLAG
485 return git_config_string(&curl_deleg, var, value);
486 #else
487 warning(_("Delegation control is not supported with cURL < 7.22.0"));
488 return 0;
489 #endif
492 if (!strcmp("http.pinnedpubkey", var)) {
493 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
494 return git_config_pathname(&ssl_pinnedkey, var, value);
495 #else
496 warning(_("Public key pinning not supported with cURL < 7.39.0"));
497 return 0;
498 #endif
501 if (!strcmp("http.extraheader", var)) {
502 if (!value) {
503 return config_error_nonbool(var);
504 } else if (!*value) {
505 string_list_clear(&extra_http_headers, 0);
506 } else {
507 string_list_append(&extra_http_headers, value);
509 return 0;
512 if (!strcmp("http.curloptresolve", var)) {
513 if (!value) {
514 return config_error_nonbool(var);
515 } else if (!*value) {
516 curl_slist_free_all(host_resolutions);
517 host_resolutions = NULL;
518 } else {
519 host_resolutions = curl_slist_append(host_resolutions, value);
521 return 0;
524 if (!strcmp("http.followredirects", var)) {
525 if (value && !strcmp(value, "initial"))
526 http_follow_config = HTTP_FOLLOW_INITIAL;
527 else if (git_config_bool(var, value))
528 http_follow_config = HTTP_FOLLOW_ALWAYS;
529 else
530 http_follow_config = HTTP_FOLLOW_NONE;
531 return 0;
534 /* Fall back on the default ones */
535 return git_default_config(var, value, cb);
538 static int curl_empty_auth_enabled(void)
540 if (curl_empty_auth >= 0)
541 return curl_empty_auth;
544 * In the automatic case, kick in the empty-auth
545 * hack as long as we would potentially try some
546 * method more exotic than "Basic" or "Digest".
548 * But only do this when this is our second or
549 * subsequent request, as by then we know what
550 * methods are available.
552 if (http_auth_methods_restricted &&
553 (http_auth_methods & ~empty_auth_useless))
554 return 1;
555 return 0;
558 static void init_curl_http_auth(CURL *result)
560 if (!http_auth.username || !*http_auth.username) {
561 if (curl_empty_auth_enabled())
562 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
563 return;
566 credential_fill(&http_auth);
568 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
569 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
572 /* *var must be free-able */
573 static void var_override(const char **var, char *value)
575 if (value) {
576 free((void *)*var);
577 *var = xstrdup(value);
581 static void set_proxyauth_name_password(CURL *result)
583 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
584 proxy_auth.username);
585 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
586 proxy_auth.password);
589 static void init_curl_proxy_auth(CURL *result)
591 if (proxy_auth.username) {
592 if (!proxy_auth.password)
593 credential_fill(&proxy_auth);
594 set_proxyauth_name_password(result);
597 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
599 if (http_proxy_authmethod) {
600 int i;
601 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
602 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
603 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
604 proxy_authmethods[i].curlauth_param);
605 break;
608 if (i == ARRAY_SIZE(proxy_authmethods)) {
609 warning("unsupported proxy authentication method %s: using anyauth",
610 http_proxy_authmethod);
611 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
614 else
615 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
618 static int has_cert_password(void)
620 if (ssl_cert == NULL || ssl_cert_password_required != 1)
621 return 0;
622 if (!cert_auth.password) {
623 cert_auth.protocol = xstrdup("cert");
624 cert_auth.host = xstrdup("");
625 cert_auth.username = xstrdup("");
626 cert_auth.path = xstrdup(ssl_cert);
627 credential_fill(&cert_auth);
629 return 1;
632 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
633 static int has_proxy_cert_password(void)
635 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
636 return 0;
637 if (!proxy_cert_auth.password) {
638 proxy_cert_auth.protocol = xstrdup("cert");
639 proxy_cert_auth.host = xstrdup("");
640 proxy_cert_auth.username = xstrdup("");
641 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
642 credential_fill(&proxy_cert_auth);
644 return 1;
646 #endif
648 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
649 static void set_curl_keepalive(CURL *c)
651 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
654 #else
655 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
657 int ka = 1;
658 int rc;
659 socklen_t len = (socklen_t)sizeof(ka);
661 if (type != CURLSOCKTYPE_IPCXN)
662 return 0;
664 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
665 if (rc < 0)
666 warning_errno("unable to set SO_KEEPALIVE on socket");
668 return CURL_SOCKOPT_OK;
671 static void set_curl_keepalive(CURL *c)
673 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
675 #endif
677 /* Return 1 if redactions have been made, 0 otherwise. */
678 static int redact_sensitive_header(struct strbuf *header, size_t offset)
680 int ret = 0;
681 const char *sensitive_header;
683 if (trace_curl_redact &&
684 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
685 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
686 /* The first token is the type, which is OK to log */
687 while (isspace(*sensitive_header))
688 sensitive_header++;
689 while (*sensitive_header && !isspace(*sensitive_header))
690 sensitive_header++;
691 /* Everything else is opaque and possibly sensitive */
692 strbuf_setlen(header, sensitive_header - header->buf);
693 strbuf_addstr(header, " <redacted>");
694 ret = 1;
695 } else if (trace_curl_redact &&
696 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
697 struct strbuf redacted_header = STRBUF_INIT;
698 const char *cookie;
700 while (isspace(*sensitive_header))
701 sensitive_header++;
703 cookie = sensitive_header;
705 while (cookie) {
706 char *equals;
707 char *semicolon = strstr(cookie, "; ");
708 if (semicolon)
709 *semicolon = 0;
710 equals = strchrnul(cookie, '=');
711 if (!equals) {
712 /* invalid cookie, just append and continue */
713 strbuf_addstr(&redacted_header, cookie);
714 continue;
716 strbuf_add(&redacted_header, cookie, equals - cookie);
717 strbuf_addstr(&redacted_header, "=<redacted>");
718 if (semicolon) {
720 * There are more cookies. (Or, for some
721 * reason, the input string ends in "; ".)
723 strbuf_addstr(&redacted_header, "; ");
724 cookie = semicolon + strlen("; ");
725 } else {
726 cookie = NULL;
730 strbuf_setlen(header, sensitive_header - header->buf);
731 strbuf_addbuf(header, &redacted_header);
732 ret = 1;
734 return ret;
737 /* Redact headers in info */
738 static void redact_sensitive_info_header(struct strbuf *header)
740 const char *sensitive_header;
743 * curl's h2h3 prints headers in info, e.g.:
744 * h2h3 [<header-name>: <header-val>]
746 if (trace_curl_redact &&
747 skip_iprefix(header->buf, "h2h3 [", &sensitive_header)) {
748 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
749 /* redaction ate our closing bracket */
750 strbuf_addch(header, ']');
755 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
757 struct strbuf out = STRBUF_INIT;
758 struct strbuf **headers, **header;
760 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
761 text, (long)size, (long)size);
762 trace_strbuf(&trace_curl, &out);
763 strbuf_reset(&out);
764 strbuf_add(&out, ptr, size);
765 headers = strbuf_split_max(&out, '\n', 0);
767 for (header = headers; *header; header++) {
768 if (hide_sensitive_header)
769 redact_sensitive_header(*header, 0);
770 strbuf_insertstr((*header), 0, text);
771 strbuf_insertstr((*header), strlen(text), ": ");
772 strbuf_rtrim((*header));
773 strbuf_addch((*header), '\n');
774 trace_strbuf(&trace_curl, (*header));
776 strbuf_list_free(headers);
777 strbuf_release(&out);
780 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
782 size_t i;
783 struct strbuf out = STRBUF_INIT;
784 unsigned int width = 60;
786 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
787 text, (long)size, (long)size);
788 trace_strbuf(&trace_curl, &out);
790 for (i = 0; i < size; i += width) {
791 size_t w;
793 strbuf_reset(&out);
794 strbuf_addf(&out, "%s: ", text);
795 for (w = 0; (w < width) && (i + w < size); w++) {
796 unsigned char ch = ptr[i + w];
798 strbuf_addch(&out,
799 (ch >= 0x20) && (ch < 0x80)
800 ? ch : '.');
802 strbuf_addch(&out, '\n');
803 trace_strbuf(&trace_curl, &out);
805 strbuf_release(&out);
808 static void curl_dump_info(char *data, size_t size)
810 struct strbuf buf = STRBUF_INIT;
812 strbuf_add(&buf, data, size);
814 redact_sensitive_info_header(&buf);
815 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
817 strbuf_release(&buf);
820 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
822 const char *text;
823 enum { NO_FILTER = 0, DO_FILTER = 1 };
825 switch (type) {
826 case CURLINFO_TEXT:
827 curl_dump_info(data, size);
828 break;
829 case CURLINFO_HEADER_OUT:
830 text = "=> Send header";
831 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
832 break;
833 case CURLINFO_DATA_OUT:
834 if (trace_curl_data) {
835 text = "=> Send data";
836 curl_dump_data(text, (unsigned char *)data, size);
838 break;
839 case CURLINFO_SSL_DATA_OUT:
840 if (trace_curl_data) {
841 text = "=> Send SSL data";
842 curl_dump_data(text, (unsigned char *)data, size);
844 break;
845 case CURLINFO_HEADER_IN:
846 text = "<= Recv header";
847 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
848 break;
849 case CURLINFO_DATA_IN:
850 if (trace_curl_data) {
851 text = "<= Recv data";
852 curl_dump_data(text, (unsigned char *)data, size);
854 break;
855 case CURLINFO_SSL_DATA_IN:
856 if (trace_curl_data) {
857 text = "<= Recv SSL data";
858 curl_dump_data(text, (unsigned char *)data, size);
860 break;
862 default: /* we ignore unknown types by default */
863 return 0;
865 return 0;
868 void http_trace_curl_no_data(void)
870 trace_override_envvar(&trace_curl, "1");
871 trace_curl_data = 0;
874 void setup_curl_trace(CURL *handle)
876 if (!trace_want(&trace_curl))
877 return;
878 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
879 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
880 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
883 static void proto_list_append(struct strbuf *list, const char *proto)
885 if (!list)
886 return;
887 if (list->len)
888 strbuf_addch(list, ',');
889 strbuf_addstr(list, proto);
892 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
894 long bits = 0;
896 if (is_transport_allowed("http", from_user)) {
897 bits |= CURLPROTO_HTTP;
898 proto_list_append(list, "http");
900 if (is_transport_allowed("https", from_user)) {
901 bits |= CURLPROTO_HTTPS;
902 proto_list_append(list, "https");
904 if (is_transport_allowed("ftp", from_user)) {
905 bits |= CURLPROTO_FTP;
906 proto_list_append(list, "ftp");
908 if (is_transport_allowed("ftps", from_user)) {
909 bits |= CURLPROTO_FTPS;
910 proto_list_append(list, "ftps");
913 return bits;
916 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
917 static int get_curl_http_version_opt(const char *version_string, long *opt)
919 int i;
920 static struct {
921 const char *name;
922 long opt_token;
923 } choice[] = {
924 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
925 { "HTTP/2", CURL_HTTP_VERSION_2 }
928 for (i = 0; i < ARRAY_SIZE(choice); i++) {
929 if (!strcmp(version_string, choice[i].name)) {
930 *opt = choice[i].opt_token;
931 return 0;
935 warning("unknown value given to http.version: '%s'", version_string);
936 return -1; /* not found */
939 #endif
941 static CURL *get_curl_handle(void)
943 CURL *result = curl_easy_init();
945 if (!result)
946 die("curl_easy_init failed");
948 if (!curl_ssl_verify) {
949 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
950 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
951 } else {
952 /* Verify authenticity of the peer's certificate */
953 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
954 /* The name in the cert must match whom we tried to connect */
955 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
958 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
959 if (curl_http_version) {
960 long opt;
961 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
962 /* Set request use http version */
963 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
966 #endif
968 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
969 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
971 #ifdef CURLGSSAPI_DELEGATION_FLAG
972 if (curl_deleg) {
973 int i;
974 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
975 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
976 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
977 curl_deleg_levels[i].curl_deleg_param);
978 break;
981 if (i == ARRAY_SIZE(curl_deleg_levels))
982 warning("Unknown delegation method '%s': using default",
983 curl_deleg);
985 #endif
987 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
988 !http_schannel_check_revoke) {
989 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
990 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
991 #else
992 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
993 #endif
996 if (http_proactive_auth)
997 init_curl_http_auth(result);
999 if (getenv("GIT_SSL_VERSION"))
1000 ssl_version = getenv("GIT_SSL_VERSION");
1001 if (ssl_version && *ssl_version) {
1002 int i;
1003 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1004 if (!strcmp(ssl_version, sslversions[i].name)) {
1005 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1006 sslversions[i].ssl_version);
1007 break;
1010 if (i == ARRAY_SIZE(sslversions))
1011 warning("unsupported ssl version %s: using default",
1012 ssl_version);
1015 if (getenv("GIT_SSL_CIPHER_LIST"))
1016 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1017 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1018 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1019 ssl_cipherlist);
1021 if (ssl_cert)
1022 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1023 if (ssl_cert_type)
1024 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1025 if (has_cert_password())
1026 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1027 if (ssl_key)
1028 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1029 if (ssl_key_type)
1030 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1031 if (ssl_capath)
1032 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1033 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1034 if (ssl_pinnedkey)
1035 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1036 #endif
1037 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1038 !http_schannel_use_ssl_cainfo) {
1039 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1040 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1041 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1042 #endif
1043 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1044 if (ssl_cainfo)
1045 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1046 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1047 if (http_proxy_ssl_ca_info)
1048 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1049 #endif
1052 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1053 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1054 curl_low_speed_limit);
1055 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1056 curl_low_speed_time);
1059 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1060 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1062 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1064 struct strbuf buf = STRBUF_INIT;
1066 get_curl_allowed_protocols(0, &buf);
1067 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1068 strbuf_reset(&buf);
1070 get_curl_allowed_protocols(-1, &buf);
1071 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1072 strbuf_release(&buf);
1074 #else
1075 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1076 get_curl_allowed_protocols(0, NULL));
1077 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1078 get_curl_allowed_protocols(-1, NULL));
1079 #endif
1081 if (getenv("GIT_CURL_VERBOSE"))
1082 http_trace_curl_no_data();
1083 setup_curl_trace(result);
1084 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1085 trace_curl_data = 0;
1086 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1087 trace_curl_redact = 0;
1089 curl_easy_setopt(result, CURLOPT_USERAGENT,
1090 user_agent ? user_agent : git_user_agent());
1092 if (curl_ftp_no_epsv)
1093 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1095 if (curl_ssl_try)
1096 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1099 * CURL also examines these variables as a fallback; but we need to query
1100 * them here in order to decide whether to prompt for missing password (cf.
1101 * init_curl_proxy_auth()).
1103 * Unlike many other common environment variables, these are historically
1104 * lowercase only. It appears that CURL did not know this and implemented
1105 * only uppercase variants, which was later corrected to take both - with
1106 * the exception of http_proxy, which is lowercase only also in CURL. As
1107 * the lowercase versions are the historical quasi-standard, they take
1108 * precedence here, as in CURL.
1110 if (!curl_http_proxy) {
1111 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1112 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1113 var_override(&curl_http_proxy, getenv("https_proxy"));
1114 } else {
1115 var_override(&curl_http_proxy, getenv("http_proxy"));
1117 if (!curl_http_proxy) {
1118 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1119 var_override(&curl_http_proxy, getenv("all_proxy"));
1123 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1125 * Handle case with the empty http.proxy value here to keep
1126 * common code clean.
1127 * NB: empty option disables proxying at all.
1129 curl_easy_setopt(result, CURLOPT_PROXY, "");
1130 } else if (curl_http_proxy) {
1131 if (starts_with(curl_http_proxy, "socks5h"))
1132 curl_easy_setopt(result,
1133 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1134 else if (starts_with(curl_http_proxy, "socks5"))
1135 curl_easy_setopt(result,
1136 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1137 else if (starts_with(curl_http_proxy, "socks4a"))
1138 curl_easy_setopt(result,
1139 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1140 else if (starts_with(curl_http_proxy, "socks"))
1141 curl_easy_setopt(result,
1142 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1143 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1144 else if (starts_with(curl_http_proxy, "https")) {
1145 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1147 if (http_proxy_ssl_cert)
1148 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1150 if (http_proxy_ssl_key)
1151 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1153 if (has_proxy_cert_password())
1154 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1156 #endif
1157 if (strstr(curl_http_proxy, "://"))
1158 credential_from_url(&proxy_auth, curl_http_proxy);
1159 else {
1160 struct strbuf url = STRBUF_INIT;
1161 strbuf_addf(&url, "http://%s", curl_http_proxy);
1162 credential_from_url(&proxy_auth, url.buf);
1163 strbuf_release(&url);
1166 if (!proxy_auth.host)
1167 die("Invalid proxy URL '%s'", curl_http_proxy);
1169 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1170 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1171 var_override(&curl_no_proxy, getenv("no_proxy"));
1172 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1174 init_curl_proxy_auth(result);
1176 set_curl_keepalive(result);
1178 return result;
1181 static void set_from_env(const char **var, const char *envname)
1183 const char *val = getenv(envname);
1184 if (val)
1185 *var = val;
1188 void http_init(struct remote *remote, const char *url, int proactive_auth)
1190 char *low_speed_limit;
1191 char *low_speed_time;
1192 char *normalized_url;
1193 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1195 config.section = "http";
1196 config.key = NULL;
1197 config.collect_fn = http_options;
1198 config.cascade_fn = git_default_config;
1199 config.cb = NULL;
1201 http_is_verbose = 0;
1202 normalized_url = url_normalize(url, &config.url);
1204 git_config(urlmatch_config_entry, &config);
1205 free(normalized_url);
1206 string_list_clear(&config.vars, 1);
1208 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1209 if (http_ssl_backend) {
1210 const curl_ssl_backend **backends;
1211 struct strbuf buf = STRBUF_INIT;
1212 int i;
1214 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1215 case CURLSSLSET_UNKNOWN_BACKEND:
1216 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1217 "Supported SSL backends:"),
1218 http_ssl_backend);
1219 for (i = 0; backends[i]; i++)
1220 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1221 die("%s", buf.buf);
1222 case CURLSSLSET_NO_BACKENDS:
1223 die(_("Could not set SSL backend to '%s': "
1224 "cURL was built without SSL backends"),
1225 http_ssl_backend);
1226 case CURLSSLSET_TOO_LATE:
1227 die(_("Could not set SSL backend to '%s': already set"),
1228 http_ssl_backend);
1229 case CURLSSLSET_OK:
1230 break; /* Okay! */
1233 #endif
1235 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1236 die("curl_global_init failed");
1238 http_proactive_auth = proactive_auth;
1240 if (remote && remote->http_proxy)
1241 curl_http_proxy = xstrdup(remote->http_proxy);
1243 if (remote)
1244 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1246 pragma_header = curl_slist_append(http_copy_default_headers(),
1247 "Pragma: no-cache");
1248 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1249 "Pragma:");
1252 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1253 if (http_max_requests)
1254 max_requests = atoi(http_max_requests);
1257 curlm = curl_multi_init();
1258 if (!curlm)
1259 die("curl_multi_init failed");
1261 if (getenv("GIT_SSL_NO_VERIFY"))
1262 curl_ssl_verify = 0;
1264 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1265 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1266 set_from_env(&ssl_key, "GIT_SSL_KEY");
1267 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1268 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1269 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1271 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1273 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1274 if (low_speed_limit)
1275 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1276 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1277 if (low_speed_time)
1278 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1280 if (curl_ssl_verify == -1)
1281 curl_ssl_verify = 1;
1283 curl_session_count = 0;
1284 if (max_requests < 1)
1285 max_requests = DEFAULT_MAX_REQUESTS;
1287 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1288 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1289 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1291 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1292 proxy_ssl_cert_password_required = 1;
1294 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1295 curl_ftp_no_epsv = 1;
1297 if (url) {
1298 credential_from_url(&http_auth, url);
1299 if (!ssl_cert_password_required &&
1300 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1301 starts_with(url, "https://"))
1302 ssl_cert_password_required = 1;
1305 curl_default = get_curl_handle();
1308 void http_cleanup(void)
1310 struct active_request_slot *slot = active_queue_head;
1312 while (slot != NULL) {
1313 struct active_request_slot *next = slot->next;
1314 if (slot->curl) {
1315 xmulti_remove_handle(slot);
1316 curl_easy_cleanup(slot->curl);
1318 free(slot);
1319 slot = next;
1321 active_queue_head = NULL;
1323 curl_easy_cleanup(curl_default);
1325 curl_multi_cleanup(curlm);
1326 curl_global_cleanup();
1328 string_list_clear(&extra_http_headers, 0);
1330 curl_slist_free_all(pragma_header);
1331 pragma_header = NULL;
1333 curl_slist_free_all(no_pragma_header);
1334 no_pragma_header = NULL;
1336 curl_slist_free_all(host_resolutions);
1337 host_resolutions = NULL;
1339 if (curl_http_proxy) {
1340 free((void *)curl_http_proxy);
1341 curl_http_proxy = NULL;
1344 if (proxy_auth.password) {
1345 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1346 FREE_AND_NULL(proxy_auth.password);
1349 free((void *)curl_proxyuserpwd);
1350 curl_proxyuserpwd = NULL;
1352 free((void *)http_proxy_authmethod);
1353 http_proxy_authmethod = NULL;
1355 if (cert_auth.password) {
1356 memset(cert_auth.password, 0, strlen(cert_auth.password));
1357 FREE_AND_NULL(cert_auth.password);
1359 ssl_cert_password_required = 0;
1361 if (proxy_cert_auth.password) {
1362 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1363 FREE_AND_NULL(proxy_cert_auth.password);
1365 proxy_ssl_cert_password_required = 0;
1367 FREE_AND_NULL(cached_accept_language);
1370 struct active_request_slot *get_active_slot(void)
1372 struct active_request_slot *slot = active_queue_head;
1373 struct active_request_slot *newslot;
1375 int num_transfers;
1377 /* Wait for a slot to open up if the queue is full */
1378 while (active_requests >= max_requests) {
1379 curl_multi_perform(curlm, &num_transfers);
1380 if (num_transfers < active_requests)
1381 process_curl_messages();
1384 while (slot != NULL && slot->in_use)
1385 slot = slot->next;
1387 if (!slot) {
1388 newslot = xmalloc(sizeof(*newslot));
1389 newslot->curl = NULL;
1390 newslot->in_use = 0;
1391 newslot->next = NULL;
1393 slot = active_queue_head;
1394 if (!slot) {
1395 active_queue_head = newslot;
1396 } else {
1397 while (slot->next != NULL)
1398 slot = slot->next;
1399 slot->next = newslot;
1401 slot = newslot;
1404 if (!slot->curl) {
1405 slot->curl = curl_easy_duphandle(curl_default);
1406 curl_session_count++;
1409 active_requests++;
1410 slot->in_use = 1;
1411 slot->results = NULL;
1412 slot->finished = NULL;
1413 slot->callback_data = NULL;
1414 slot->callback_func = NULL;
1415 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1416 if (curl_save_cookies)
1417 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1418 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1419 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1420 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1421 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1422 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1423 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1424 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1425 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1426 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1427 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1428 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1431 * Default following to off unless "ALWAYS" is configured; this gives
1432 * callers a sane starting point, and they can tweak for individual
1433 * HTTP_FOLLOW_* cases themselves.
1435 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1436 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1437 else
1438 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1440 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1441 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1442 if (http_auth.password || curl_empty_auth_enabled())
1443 init_curl_http_auth(slot->curl);
1445 return slot;
1448 int start_active_slot(struct active_request_slot *slot)
1450 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1451 int num_transfers;
1453 if (curlm_result != CURLM_OK &&
1454 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1455 warning("curl_multi_add_handle failed: %s",
1456 curl_multi_strerror(curlm_result));
1457 active_requests--;
1458 slot->in_use = 0;
1459 return 0;
1463 * We know there must be something to do, since we just added
1464 * something.
1466 curl_multi_perform(curlm, &num_transfers);
1467 return 1;
1470 struct fill_chain {
1471 void *data;
1472 int (*fill)(void *);
1473 struct fill_chain *next;
1476 static struct fill_chain *fill_cfg;
1478 void add_fill_function(void *data, int (*fill)(void *))
1480 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1481 struct fill_chain **linkp = &fill_cfg;
1482 new_fill->data = data;
1483 new_fill->fill = fill;
1484 new_fill->next = NULL;
1485 while (*linkp)
1486 linkp = &(*linkp)->next;
1487 *linkp = new_fill;
1490 void fill_active_slots(void)
1492 struct active_request_slot *slot = active_queue_head;
1494 while (active_requests < max_requests) {
1495 struct fill_chain *fill;
1496 for (fill = fill_cfg; fill; fill = fill->next)
1497 if (fill->fill(fill->data))
1498 break;
1500 if (!fill)
1501 break;
1504 while (slot != NULL) {
1505 if (!slot->in_use && slot->curl != NULL
1506 && curl_session_count > min_curl_sessions) {
1507 curl_easy_cleanup(slot->curl);
1508 slot->curl = NULL;
1509 curl_session_count--;
1511 slot = slot->next;
1515 void step_active_slots(void)
1517 int num_transfers;
1518 CURLMcode curlm_result;
1520 do {
1521 curlm_result = curl_multi_perform(curlm, &num_transfers);
1522 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1523 if (num_transfers < active_requests) {
1524 process_curl_messages();
1525 fill_active_slots();
1529 void run_active_slot(struct active_request_slot *slot)
1531 fd_set readfds;
1532 fd_set writefds;
1533 fd_set excfds;
1534 int max_fd;
1535 struct timeval select_timeout;
1536 int finished = 0;
1538 slot->finished = &finished;
1539 while (!finished) {
1540 step_active_slots();
1542 if (slot->in_use) {
1543 long curl_timeout;
1544 curl_multi_timeout(curlm, &curl_timeout);
1545 if (curl_timeout == 0) {
1546 continue;
1547 } else if (curl_timeout == -1) {
1548 select_timeout.tv_sec = 0;
1549 select_timeout.tv_usec = 50000;
1550 } else {
1551 select_timeout.tv_sec = curl_timeout / 1000;
1552 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1555 max_fd = -1;
1556 FD_ZERO(&readfds);
1557 FD_ZERO(&writefds);
1558 FD_ZERO(&excfds);
1559 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1562 * It can happen that curl_multi_timeout returns a pathologically
1563 * long timeout when curl_multi_fdset returns no file descriptors
1564 * to read. See commit message for more details.
1566 if (max_fd < 0 &&
1567 (select_timeout.tv_sec > 0 ||
1568 select_timeout.tv_usec > 50000)) {
1569 select_timeout.tv_sec = 0;
1570 select_timeout.tv_usec = 50000;
1573 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1578 * The value of slot->finished we set before the loop was used
1579 * to set our "finished" variable when our request completed.
1581 * 1. The slot may not have been reused for another requst
1582 * yet, in which case it still has &finished.
1584 * 2. The slot may already be in-use to serve another request,
1585 * which can further be divided into two cases:
1587 * (a) If call run_active_slot() hasn't been called for that
1588 * other request, slot->finished would have been cleared
1589 * by get_active_slot() and has NULL.
1591 * (b) If the request did call run_active_slot(), then the
1592 * call would have updated slot->finished at the beginning
1593 * of this function, and with the clearing of the member
1594 * below, we would find that slot->finished is now NULL.
1596 * In all cases, slot->finished has no useful information to
1597 * anybody at this point. Some compilers warn us for
1598 * attempting to smuggle a pointer that is about to become
1599 * invalid, i.e. &finished. We clear it here to assure them.
1601 slot->finished = NULL;
1604 static void release_active_slot(struct active_request_slot *slot)
1606 closedown_active_slot(slot);
1607 if (slot->curl) {
1608 xmulti_remove_handle(slot);
1609 if (curl_session_count > min_curl_sessions) {
1610 curl_easy_cleanup(slot->curl);
1611 slot->curl = NULL;
1612 curl_session_count--;
1615 fill_active_slots();
1618 void finish_all_active_slots(void)
1620 struct active_request_slot *slot = active_queue_head;
1622 while (slot != NULL)
1623 if (slot->in_use) {
1624 run_active_slot(slot);
1625 slot = active_queue_head;
1626 } else {
1627 slot = slot->next;
1631 /* Helpers for modifying and creating URLs */
1632 static inline int needs_quote(int ch)
1634 if (((ch >= 'A') && (ch <= 'Z'))
1635 || ((ch >= 'a') && (ch <= 'z'))
1636 || ((ch >= '0') && (ch <= '9'))
1637 || (ch == '/')
1638 || (ch == '-')
1639 || (ch == '.'))
1640 return 0;
1641 return 1;
1644 static char *quote_ref_url(const char *base, const char *ref)
1646 struct strbuf buf = STRBUF_INIT;
1647 const char *cp;
1648 int ch;
1650 end_url_with_slash(&buf, base);
1652 for (cp = ref; (ch = *cp) != 0; cp++)
1653 if (needs_quote(ch))
1654 strbuf_addf(&buf, "%%%02x", ch);
1655 else
1656 strbuf_addch(&buf, *cp);
1658 return strbuf_detach(&buf, NULL);
1661 void append_remote_object_url(struct strbuf *buf, const char *url,
1662 const char *hex,
1663 int only_two_digit_prefix)
1665 end_url_with_slash(buf, url);
1667 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1668 if (!only_two_digit_prefix)
1669 strbuf_addstr(buf, hex + 2);
1672 char *get_remote_object_url(const char *url, const char *hex,
1673 int only_two_digit_prefix)
1675 struct strbuf buf = STRBUF_INIT;
1676 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1677 return strbuf_detach(&buf, NULL);
1680 void normalize_curl_result(CURLcode *result, long http_code,
1681 char *errorstr, size_t errorlen)
1684 * If we see a failing http code with CURLE_OK, we have turned off
1685 * FAILONERROR (to keep the server's custom error response), and should
1686 * translate the code into failure here.
1688 * Likewise, if we see a redirect (30x code), that means we turned off
1689 * redirect-following, and we should treat the result as an error.
1691 if (*result == CURLE_OK && http_code >= 300) {
1692 *result = CURLE_HTTP_RETURNED_ERROR;
1694 * Normally curl will already have put the "reason phrase"
1695 * from the server into curl_errorstr; unfortunately without
1696 * FAILONERROR it is lost, so we can give only the numeric
1697 * status code.
1699 xsnprintf(errorstr, errorlen,
1700 "The requested URL returned error: %ld",
1701 http_code);
1705 static int handle_curl_result(struct slot_results *results)
1707 normalize_curl_result(&results->curl_result, results->http_code,
1708 curl_errorstr, sizeof(curl_errorstr));
1710 if (results->curl_result == CURLE_OK) {
1711 credential_approve(&http_auth);
1712 credential_approve(&proxy_auth);
1713 credential_approve(&cert_auth);
1714 return HTTP_OK;
1715 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1717 * We can't tell from here whether it's a bad path, bad
1718 * certificate, bad password, or something else wrong
1719 * with the certificate. So we reject the credential to
1720 * avoid caching or saving a bad password.
1722 credential_reject(&cert_auth);
1723 return HTTP_NOAUTH;
1724 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1725 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1726 return HTTP_NOMATCHPUBLICKEY;
1727 #endif
1728 } else if (missing_target(results))
1729 return HTTP_MISSING_TARGET;
1730 else if (results->http_code == 401) {
1731 if (http_auth.username && http_auth.password) {
1732 credential_reject(&http_auth);
1733 return HTTP_NOAUTH;
1734 } else {
1735 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1736 if (results->auth_avail) {
1737 http_auth_methods &= results->auth_avail;
1738 http_auth_methods_restricted = 1;
1740 return HTTP_REAUTH;
1742 } else {
1743 if (results->http_connectcode == 407)
1744 credential_reject(&proxy_auth);
1745 if (!curl_errorstr[0])
1746 strlcpy(curl_errorstr,
1747 curl_easy_strerror(results->curl_result),
1748 sizeof(curl_errorstr));
1749 return HTTP_ERROR;
1753 int run_one_slot(struct active_request_slot *slot,
1754 struct slot_results *results)
1756 slot->results = results;
1757 if (!start_active_slot(slot)) {
1758 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1759 "failed to start HTTP request");
1760 return HTTP_START_FAILED;
1763 run_active_slot(slot);
1764 return handle_curl_result(results);
1767 struct curl_slist *http_copy_default_headers(void)
1769 struct curl_slist *headers = NULL;
1770 const struct string_list_item *item;
1772 for_each_string_list_item(item, &extra_http_headers)
1773 headers = curl_slist_append(headers, item->string);
1775 return headers;
1778 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1780 char *ptr;
1781 CURLcode ret;
1783 strbuf_reset(buf);
1784 ret = curl_easy_getinfo(curl, info, &ptr);
1785 if (!ret && ptr)
1786 strbuf_addstr(buf, ptr);
1787 return ret;
1791 * Check for and extract a content-type parameter. "raw"
1792 * should be positioned at the start of the potential
1793 * parameter, with any whitespace already removed.
1795 * "name" is the name of the parameter. The value is appended
1796 * to "out".
1798 static int extract_param(const char *raw, const char *name,
1799 struct strbuf *out)
1801 size_t len = strlen(name);
1803 if (strncasecmp(raw, name, len))
1804 return -1;
1805 raw += len;
1807 if (*raw != '=')
1808 return -1;
1809 raw++;
1811 while (*raw && !isspace(*raw) && *raw != ';')
1812 strbuf_addch(out, *raw++);
1813 return 0;
1817 * Extract a normalized version of the content type, with any
1818 * spaces suppressed, all letters lowercased, and no trailing ";"
1819 * or parameters.
1821 * Note that we will silently remove even invalid whitespace. For
1822 * example, "text / plain" is specifically forbidden by RFC 2616,
1823 * but "text/plain" is the only reasonable output, and this keeps
1824 * our code simple.
1826 * If the "charset" argument is not NULL, store the value of any
1827 * charset parameter there.
1829 * Example:
1830 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1831 * "text / plain" -> "text/plain"
1833 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1834 struct strbuf *charset)
1836 const char *p;
1838 strbuf_reset(type);
1839 strbuf_grow(type, raw->len);
1840 for (p = raw->buf; *p; p++) {
1841 if (isspace(*p))
1842 continue;
1843 if (*p == ';') {
1844 p++;
1845 break;
1847 strbuf_addch(type, tolower(*p));
1850 if (!charset)
1851 return;
1853 strbuf_reset(charset);
1854 while (*p) {
1855 while (isspace(*p) || *p == ';')
1856 p++;
1857 if (!extract_param(p, "charset", charset))
1858 return;
1859 while (*p && !isspace(*p))
1860 p++;
1863 if (!charset->len && starts_with(type->buf, "text/"))
1864 strbuf_addstr(charset, "ISO-8859-1");
1867 static void write_accept_language(struct strbuf *buf)
1870 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1871 * that, q-value will be smaller than 0.001, the minimum q-value the
1872 * HTTP specification allows. See
1873 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1875 const int MAX_DECIMAL_PLACES = 3;
1876 const int MAX_LANGUAGE_TAGS = 1000;
1877 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1878 char **language_tags = NULL;
1879 int num_langs = 0;
1880 const char *s = get_preferred_languages();
1881 int i;
1882 struct strbuf tag = STRBUF_INIT;
1884 /* Don't add Accept-Language header if no language is preferred. */
1885 if (!s)
1886 return;
1889 * Split the colon-separated string of preferred languages into
1890 * language_tags array.
1892 do {
1893 /* collect language tag */
1894 for (; *s && (isalnum(*s) || *s == '_'); s++)
1895 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1897 /* skip .codeset, @modifier and any other unnecessary parts */
1898 while (*s && *s != ':')
1899 s++;
1901 if (tag.len) {
1902 num_langs++;
1903 REALLOC_ARRAY(language_tags, num_langs);
1904 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1905 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1906 break;
1908 } while (*s++);
1910 /* write Accept-Language header into buf */
1911 if (num_langs) {
1912 int last_buf_len = 0;
1913 int max_q;
1914 int decimal_places;
1915 char q_format[32];
1917 /* add '*' */
1918 REALLOC_ARRAY(language_tags, num_langs + 1);
1919 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1921 /* compute decimal_places */
1922 for (max_q = 1, decimal_places = 0;
1923 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1924 decimal_places++, max_q *= 10)
1927 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1929 strbuf_addstr(buf, "Accept-Language: ");
1931 for (i = 0; i < num_langs; i++) {
1932 if (i > 0)
1933 strbuf_addstr(buf, ", ");
1935 strbuf_addstr(buf, language_tags[i]);
1937 if (i > 0)
1938 strbuf_addf(buf, q_format, max_q - i);
1940 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1941 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1942 break;
1945 last_buf_len = buf->len;
1949 /* free language tags -- last one is a static '*' */
1950 for (i = 0; i < num_langs - 1; i++)
1951 free(language_tags[i]);
1952 free(language_tags);
1956 * Get an Accept-Language header which indicates user's preferred languages.
1958 * Examples:
1959 * LANGUAGE= -> ""
1960 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1961 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1962 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1963 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1964 * LANGUAGE= LANG=C -> ""
1966 const char *http_get_accept_language_header(void)
1968 if (!cached_accept_language) {
1969 struct strbuf buf = STRBUF_INIT;
1970 write_accept_language(&buf);
1971 if (buf.len > 0)
1972 cached_accept_language = strbuf_detach(&buf, NULL);
1975 return cached_accept_language;
1978 static void http_opt_request_remainder(CURL *curl, off_t pos)
1980 char buf[128];
1981 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1982 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1985 /* http_request() targets */
1986 #define HTTP_REQUEST_STRBUF 0
1987 #define HTTP_REQUEST_FILE 1
1989 static int http_request(const char *url,
1990 void *result, int target,
1991 const struct http_get_options *options)
1993 struct active_request_slot *slot;
1994 struct slot_results results;
1995 struct curl_slist *headers = http_copy_default_headers();
1996 struct strbuf buf = STRBUF_INIT;
1997 const char *accept_language;
1998 int ret;
2000 slot = get_active_slot();
2001 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2003 if (!result) {
2004 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2005 } else {
2006 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2007 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2009 if (target == HTTP_REQUEST_FILE) {
2010 off_t posn = ftello(result);
2011 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2012 fwrite);
2013 if (posn > 0)
2014 http_opt_request_remainder(slot->curl, posn);
2015 } else
2016 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2017 fwrite_buffer);
2020 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2022 accept_language = http_get_accept_language_header();
2024 if (accept_language)
2025 headers = curl_slist_append(headers, accept_language);
2027 strbuf_addstr(&buf, "Pragma:");
2028 if (options && options->no_cache)
2029 strbuf_addstr(&buf, " no-cache");
2030 if (options && options->initial_request &&
2031 http_follow_config == HTTP_FOLLOW_INITIAL)
2032 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2034 headers = curl_slist_append(headers, buf.buf);
2036 /* Add additional headers here */
2037 if (options && options->extra_headers) {
2038 const struct string_list_item *item;
2039 for_each_string_list_item(item, options->extra_headers) {
2040 headers = curl_slist_append(headers, item->string);
2044 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2045 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2046 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2047 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2049 ret = run_one_slot(slot, &results);
2051 if (options && options->content_type) {
2052 struct strbuf raw = STRBUF_INIT;
2053 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2054 extract_content_type(&raw, options->content_type,
2055 options->charset);
2056 strbuf_release(&raw);
2059 if (options && options->effective_url)
2060 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2061 options->effective_url);
2063 curl_slist_free_all(headers);
2064 strbuf_release(&buf);
2066 return ret;
2070 * Update the "base" url to a more appropriate value, as deduced by
2071 * redirects seen when requesting a URL starting with "url".
2073 * The "asked" parameter is a URL that we asked curl to access, and must begin
2074 * with "base".
2076 * The "got" parameter is the URL that curl reported to us as where we ended
2077 * up.
2079 * Returns 1 if we updated the base url, 0 otherwise.
2081 * Our basic strategy is to compare "base" and "asked" to find the bits
2082 * specific to our request. We then strip those bits off of "got" to yield the
2083 * new base. So for example, if our base is "http://example.com/foo.git",
2084 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2085 * with "https://other.example.com/foo.git/info/refs". We would want the
2086 * new URL to become "https://other.example.com/foo.git".
2088 * Note that this assumes a sane redirect scheme. It's entirely possible
2089 * in the example above to end up at a URL that does not even end in
2090 * "info/refs". In such a case we die. There's not much we can do, such a
2091 * scheme is unlikely to represent a real git repository, and failing to
2092 * rewrite the base opens options for malicious redirects to do funny things.
2094 static int update_url_from_redirect(struct strbuf *base,
2095 const char *asked,
2096 const struct strbuf *got)
2098 const char *tail;
2099 size_t new_len;
2101 if (!strcmp(asked, got->buf))
2102 return 0;
2104 if (!skip_prefix(asked, base->buf, &tail))
2105 BUG("update_url_from_redirect: %s is not a superset of %s",
2106 asked, base->buf);
2108 new_len = got->len;
2109 if (!strip_suffix_mem(got->buf, &new_len, tail))
2110 die(_("unable to update url base from redirection:\n"
2111 " asked for: %s\n"
2112 " redirect: %s"),
2113 asked, got->buf);
2115 strbuf_reset(base);
2116 strbuf_add(base, got->buf, new_len);
2118 return 1;
2121 static int http_request_reauth(const char *url,
2122 void *result, int target,
2123 struct http_get_options *options)
2125 int ret = http_request(url, result, target, options);
2127 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2128 return ret;
2130 if (options && options->effective_url && options->base_url) {
2131 if (update_url_from_redirect(options->base_url,
2132 url, options->effective_url)) {
2133 credential_from_url(&http_auth, options->base_url->buf);
2134 url = options->effective_url->buf;
2138 if (ret != HTTP_REAUTH)
2139 return ret;
2142 * The previous request may have put cruft into our output stream; we
2143 * should clear it out before making our next request.
2145 switch (target) {
2146 case HTTP_REQUEST_STRBUF:
2147 strbuf_reset(result);
2148 break;
2149 case HTTP_REQUEST_FILE:
2150 if (fflush(result)) {
2151 error_errno("unable to flush a file");
2152 return HTTP_START_FAILED;
2154 rewind(result);
2155 if (ftruncate(fileno(result), 0) < 0) {
2156 error_errno("unable to truncate a file");
2157 return HTTP_START_FAILED;
2159 break;
2160 default:
2161 BUG("Unknown http_request target");
2164 credential_fill(&http_auth);
2166 return http_request(url, result, target, options);
2169 int http_get_strbuf(const char *url,
2170 struct strbuf *result,
2171 struct http_get_options *options)
2173 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2177 * Downloads a URL and stores the result in the given file.
2179 * If a previous interrupted download is detected (i.e. a previous temporary
2180 * file is still around) the download is resumed.
2182 int http_get_file(const char *url, const char *filename,
2183 struct http_get_options *options)
2185 int ret;
2186 struct strbuf tmpfile = STRBUF_INIT;
2187 FILE *result;
2189 strbuf_addf(&tmpfile, "%s.temp", filename);
2190 result = fopen(tmpfile.buf, "a");
2191 if (!result) {
2192 error("Unable to open local file %s", tmpfile.buf);
2193 ret = HTTP_ERROR;
2194 goto cleanup;
2197 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2198 fclose(result);
2200 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2201 ret = HTTP_ERROR;
2202 cleanup:
2203 strbuf_release(&tmpfile);
2204 return ret;
2207 int http_fetch_ref(const char *base, struct ref *ref)
2209 struct http_get_options options = {0};
2210 char *url;
2211 struct strbuf buffer = STRBUF_INIT;
2212 int ret = -1;
2214 options.no_cache = 1;
2216 url = quote_ref_url(base, ref->name);
2217 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2218 strbuf_rtrim(&buffer);
2219 if (buffer.len == the_hash_algo->hexsz)
2220 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2221 else if (starts_with(buffer.buf, "ref: ")) {
2222 ref->symref = xstrdup(buffer.buf + 5);
2223 ret = 0;
2227 strbuf_release(&buffer);
2228 free(url);
2229 return ret;
2232 /* Helpers for fetching packs */
2233 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2235 char *url, *tmp;
2236 struct strbuf buf = STRBUF_INIT;
2238 if (http_is_verbose)
2239 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2241 end_url_with_slash(&buf, base_url);
2242 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2243 url = strbuf_detach(&buf, NULL);
2245 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2246 tmp = strbuf_detach(&buf, NULL);
2248 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2249 error("Unable to get pack index %s", url);
2250 FREE_AND_NULL(tmp);
2253 free(url);
2254 return tmp;
2257 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2258 unsigned char *sha1, const char *base_url)
2260 struct packed_git *new_pack;
2261 char *tmp_idx = NULL;
2262 int ret;
2264 if (has_pack_index(sha1)) {
2265 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2266 if (!new_pack)
2267 return -1; /* parse_pack_index() already issued error message */
2268 goto add_pack;
2271 tmp_idx = fetch_pack_index(sha1, base_url);
2272 if (!tmp_idx)
2273 return -1;
2275 new_pack = parse_pack_index(sha1, tmp_idx);
2276 if (!new_pack) {
2277 unlink(tmp_idx);
2278 free(tmp_idx);
2280 return -1; /* parse_pack_index() already issued error message */
2283 ret = verify_pack_index(new_pack);
2284 if (!ret) {
2285 close_pack_index(new_pack);
2286 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2288 free(tmp_idx);
2289 if (ret)
2290 return -1;
2292 add_pack:
2293 new_pack->next = *packs_head;
2294 *packs_head = new_pack;
2295 return 0;
2298 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2300 struct http_get_options options = {0};
2301 int ret = 0;
2302 char *url;
2303 const char *data;
2304 struct strbuf buf = STRBUF_INIT;
2305 struct object_id oid;
2307 end_url_with_slash(&buf, base_url);
2308 strbuf_addstr(&buf, "objects/info/packs");
2309 url = strbuf_detach(&buf, NULL);
2311 options.no_cache = 1;
2312 ret = http_get_strbuf(url, &buf, &options);
2313 if (ret != HTTP_OK)
2314 goto cleanup;
2316 data = buf.buf;
2317 while (*data) {
2318 if (skip_prefix(data, "P pack-", &data) &&
2319 !parse_oid_hex(data, &oid, &data) &&
2320 skip_prefix(data, ".pack", &data) &&
2321 (*data == '\n' || *data == '\0')) {
2322 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2323 } else {
2324 data = strchrnul(data, '\n');
2326 if (*data)
2327 data++; /* skip past newline */
2330 cleanup:
2331 free(url);
2332 return ret;
2335 void release_http_pack_request(struct http_pack_request *preq)
2337 if (preq->packfile) {
2338 fclose(preq->packfile);
2339 preq->packfile = NULL;
2341 preq->slot = NULL;
2342 strbuf_release(&preq->tmpfile);
2343 free(preq->url);
2344 free(preq);
2347 static const char *default_index_pack_args[] =
2348 {"index-pack", "--stdin", NULL};
2350 int finish_http_pack_request(struct http_pack_request *preq)
2352 struct child_process ip = CHILD_PROCESS_INIT;
2353 int tmpfile_fd;
2354 int ret = 0;
2356 fclose(preq->packfile);
2357 preq->packfile = NULL;
2359 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2361 ip.git_cmd = 1;
2362 ip.in = tmpfile_fd;
2363 strvec_pushv(&ip.args, preq->index_pack_args ?
2364 preq->index_pack_args :
2365 default_index_pack_args);
2367 if (preq->preserve_index_pack_stdout)
2368 ip.out = 0;
2369 else
2370 ip.no_stdout = 1;
2372 if (run_command(&ip)) {
2373 ret = -1;
2374 goto cleanup;
2377 cleanup:
2378 close(tmpfile_fd);
2379 unlink(preq->tmpfile.buf);
2380 return ret;
2383 void http_install_packfile(struct packed_git *p,
2384 struct packed_git **list_to_remove_from)
2386 struct packed_git **lst = list_to_remove_from;
2388 while (*lst != p)
2389 lst = &((*lst)->next);
2390 *lst = (*lst)->next;
2392 install_packed_git(the_repository, p);
2395 struct http_pack_request *new_http_pack_request(
2396 const unsigned char *packed_git_hash, const char *base_url) {
2398 struct strbuf buf = STRBUF_INIT;
2400 end_url_with_slash(&buf, base_url);
2401 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2402 hash_to_hex(packed_git_hash));
2403 return new_direct_http_pack_request(packed_git_hash,
2404 strbuf_detach(&buf, NULL));
2407 struct http_pack_request *new_direct_http_pack_request(
2408 const unsigned char *packed_git_hash, char *url)
2410 off_t prev_posn = 0;
2411 struct http_pack_request *preq;
2413 CALLOC_ARRAY(preq, 1);
2414 strbuf_init(&preq->tmpfile, 0);
2416 preq->url = url;
2418 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2419 preq->packfile = fopen(preq->tmpfile.buf, "a");
2420 if (!preq->packfile) {
2421 error("Unable to open local file %s for pack",
2422 preq->tmpfile.buf);
2423 goto abort;
2426 preq->slot = get_active_slot();
2427 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2428 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2429 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2430 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2431 no_pragma_header);
2434 * If there is data present from a previous transfer attempt,
2435 * resume where it left off
2437 prev_posn = ftello(preq->packfile);
2438 if (prev_posn>0) {
2439 if (http_is_verbose)
2440 fprintf(stderr,
2441 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2442 hash_to_hex(packed_git_hash),
2443 (uintmax_t)prev_posn);
2444 http_opt_request_remainder(preq->slot->curl, prev_posn);
2447 return preq;
2449 abort:
2450 strbuf_release(&preq->tmpfile);
2451 free(preq->url);
2452 free(preq);
2453 return NULL;
2456 /* Helpers for fetching objects (loose) */
2457 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2458 void *data)
2460 unsigned char expn[4096];
2461 size_t size = eltsize * nmemb;
2462 int posn = 0;
2463 struct http_object_request *freq = data;
2464 struct active_request_slot *slot = freq->slot;
2466 if (slot) {
2467 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2468 &slot->http_code);
2469 if (c != CURLE_OK)
2470 BUG("curl_easy_getinfo for HTTP code failed: %s",
2471 curl_easy_strerror(c));
2472 if (slot->http_code >= 300)
2473 return nmemb;
2476 do {
2477 ssize_t retval = xwrite(freq->localfile,
2478 (char *) ptr + posn, size - posn);
2479 if (retval < 0)
2480 return posn / eltsize;
2481 posn += retval;
2482 } while (posn < size);
2484 freq->stream.avail_in = size;
2485 freq->stream.next_in = (void *)ptr;
2486 do {
2487 freq->stream.next_out = expn;
2488 freq->stream.avail_out = sizeof(expn);
2489 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2490 the_hash_algo->update_fn(&freq->c, expn,
2491 sizeof(expn) - freq->stream.avail_out);
2492 } while (freq->stream.avail_in && freq->zret == Z_OK);
2493 return nmemb;
2496 struct http_object_request *new_http_object_request(const char *base_url,
2497 const struct object_id *oid)
2499 char *hex = oid_to_hex(oid);
2500 struct strbuf filename = STRBUF_INIT;
2501 struct strbuf prevfile = STRBUF_INIT;
2502 int prevlocal;
2503 char prev_buf[PREV_BUF_SIZE];
2504 ssize_t prev_read = 0;
2505 off_t prev_posn = 0;
2506 struct http_object_request *freq;
2508 CALLOC_ARRAY(freq, 1);
2509 strbuf_init(&freq->tmpfile, 0);
2510 oidcpy(&freq->oid, oid);
2511 freq->localfile = -1;
2513 loose_object_path(the_repository, &filename, oid);
2514 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2516 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2517 unlink_or_warn(prevfile.buf);
2518 rename(freq->tmpfile.buf, prevfile.buf);
2519 unlink_or_warn(freq->tmpfile.buf);
2520 strbuf_release(&filename);
2522 if (freq->localfile != -1)
2523 error("fd leakage in start: %d", freq->localfile);
2524 freq->localfile = open(freq->tmpfile.buf,
2525 O_WRONLY | O_CREAT | O_EXCL, 0666);
2527 * This could have failed due to the "lazy directory creation";
2528 * try to mkdir the last path component.
2530 if (freq->localfile < 0 && errno == ENOENT) {
2531 char *dir = strrchr(freq->tmpfile.buf, '/');
2532 if (dir) {
2533 *dir = 0;
2534 mkdir(freq->tmpfile.buf, 0777);
2535 *dir = '/';
2537 freq->localfile = open(freq->tmpfile.buf,
2538 O_WRONLY | O_CREAT | O_EXCL, 0666);
2541 if (freq->localfile < 0) {
2542 error_errno("Couldn't create temporary file %s",
2543 freq->tmpfile.buf);
2544 goto abort;
2547 git_inflate_init(&freq->stream);
2549 the_hash_algo->init_fn(&freq->c);
2551 freq->url = get_remote_object_url(base_url, hex, 0);
2554 * If a previous temp file is present, process what was already
2555 * fetched.
2557 prevlocal = open(prevfile.buf, O_RDONLY);
2558 if (prevlocal != -1) {
2559 do {
2560 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2561 if (prev_read>0) {
2562 if (fwrite_sha1_file(prev_buf,
2564 prev_read,
2565 freq) == prev_read) {
2566 prev_posn += prev_read;
2567 } else {
2568 prev_read = -1;
2571 } while (prev_read > 0);
2572 close(prevlocal);
2574 unlink_or_warn(prevfile.buf);
2575 strbuf_release(&prevfile);
2578 * Reset inflate/SHA1 if there was an error reading the previous temp
2579 * file; also rewind to the beginning of the local file.
2581 if (prev_read == -1) {
2582 memset(&freq->stream, 0, sizeof(freq->stream));
2583 git_inflate_init(&freq->stream);
2584 the_hash_algo->init_fn(&freq->c);
2585 if (prev_posn>0) {
2586 prev_posn = 0;
2587 lseek(freq->localfile, 0, SEEK_SET);
2588 if (ftruncate(freq->localfile, 0) < 0) {
2589 error_errno("Couldn't truncate temporary file %s",
2590 freq->tmpfile.buf);
2591 goto abort;
2596 freq->slot = get_active_slot();
2598 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2599 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2600 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2601 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2602 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2603 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2606 * If we have successfully processed data from a previous fetch
2607 * attempt, only fetch the data we don't already have.
2609 if (prev_posn>0) {
2610 if (http_is_verbose)
2611 fprintf(stderr,
2612 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2613 hex, (uintmax_t)prev_posn);
2614 http_opt_request_remainder(freq->slot->curl, prev_posn);
2617 return freq;
2619 abort:
2620 strbuf_release(&prevfile);
2621 free(freq->url);
2622 free(freq);
2623 return NULL;
2626 void process_http_object_request(struct http_object_request *freq)
2628 if (!freq->slot)
2629 return;
2630 freq->curl_result = freq->slot->curl_result;
2631 freq->http_code = freq->slot->http_code;
2632 freq->slot = NULL;
2635 int finish_http_object_request(struct http_object_request *freq)
2637 struct stat st;
2638 struct strbuf filename = STRBUF_INIT;
2640 close(freq->localfile);
2641 freq->localfile = -1;
2643 process_http_object_request(freq);
2645 if (freq->http_code == 416) {
2646 warning("requested range invalid; we may already have all the data.");
2647 } else if (freq->curl_result != CURLE_OK) {
2648 if (stat(freq->tmpfile.buf, &st) == 0)
2649 if (st.st_size == 0)
2650 unlink_or_warn(freq->tmpfile.buf);
2651 return -1;
2654 git_inflate_end(&freq->stream);
2655 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2656 if (freq->zret != Z_STREAM_END) {
2657 unlink_or_warn(freq->tmpfile.buf);
2658 return -1;
2660 if (!oideq(&freq->oid, &freq->real_oid)) {
2661 unlink_or_warn(freq->tmpfile.buf);
2662 return -1;
2664 loose_object_path(the_repository, &filename, &freq->oid);
2665 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2666 strbuf_release(&filename);
2668 return freq->rename;
2671 void abort_http_object_request(struct http_object_request *freq)
2673 unlink_or_warn(freq->tmpfile.buf);
2675 release_http_object_request(freq);
2678 void release_http_object_request(struct http_object_request *freq)
2680 if (freq->localfile != -1) {
2681 close(freq->localfile);
2682 freq->localfile = -1;
2684 FREE_AND_NULL(freq->url);
2685 if (freq->slot) {
2686 freq->slot->callback_func = NULL;
2687 freq->slot->callback_data = NULL;
2688 release_active_slot(freq->slot);
2689 freq->slot = NULL;
2691 strbuf_release(&freq->tmpfile);