Merge branch 'jk/unused-post-2.40'
[git.git] / http.c
blobdbe4d29ef7abb87bf4a9cba21558745975ac795f
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_cipherlist;
44 static const char *ssl_version;
45 static struct {
46 const char *name;
47 long ssl_version;
48 } sslversions[] = {
49 { "sslv2", CURL_SSLVERSION_SSLv2 },
50 { "sslv3", CURL_SSLVERSION_SSLv3 },
51 { "tlsv1", CURL_SSLVERSION_TLSv1 },
52 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
53 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
54 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
55 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
56 #endif
57 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
58 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
59 #endif
61 static const char *ssl_key;
62 static const char *ssl_capath;
63 static const char *curl_no_proxy;
64 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
65 static const char *ssl_pinnedkey;
66 #endif
67 static const char *ssl_cainfo;
68 static long curl_low_speed_limit = -1;
69 static long curl_low_speed_time = -1;
70 static int curl_ftp_no_epsv;
71 static const char *curl_http_proxy;
72 static const char *http_proxy_authmethod;
74 static const char *http_proxy_ssl_cert;
75 static const char *http_proxy_ssl_key;
76 static const char *http_proxy_ssl_ca_info;
77 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
78 static int proxy_ssl_cert_password_required;
80 static struct {
81 const char *name;
82 long curlauth_param;
83 } proxy_authmethods[] = {
84 { "basic", CURLAUTH_BASIC },
85 { "digest", CURLAUTH_DIGEST },
86 { "negotiate", CURLAUTH_GSSNEGOTIATE },
87 { "ntlm", CURLAUTH_NTLM },
88 { "anyauth", CURLAUTH_ANY },
90 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
91 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
92 * here, too
95 #ifdef CURLGSSAPI_DELEGATION_FLAG
96 static const char *curl_deleg;
97 static struct {
98 const char *name;
99 long curl_deleg_param;
100 } curl_deleg_levels[] = {
101 { "none", CURLGSSAPI_DELEGATION_NONE },
102 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
103 { "always", CURLGSSAPI_DELEGATION_FLAG },
105 #endif
107 static struct credential proxy_auth = CREDENTIAL_INIT;
108 static const char *curl_proxyuserpwd;
109 static const char *curl_cookie_file;
110 static int curl_save_cookies;
111 struct credential http_auth = CREDENTIAL_INIT;
112 static int http_proactive_auth;
113 static const char *user_agent;
114 static int curl_empty_auth = -1;
116 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
118 static struct credential cert_auth = CREDENTIAL_INIT;
119 static int ssl_cert_password_required;
120 static unsigned long http_auth_methods = CURLAUTH_ANY;
121 static int http_auth_methods_restricted;
122 /* Modes for which empty_auth cannot actually help us. */
123 static unsigned long empty_auth_useless =
124 CURLAUTH_BASIC
125 | CURLAUTH_DIGEST_IE
126 | CURLAUTH_DIGEST;
128 static struct curl_slist *pragma_header;
129 static struct curl_slist *no_pragma_header;
130 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
132 static struct curl_slist *host_resolutions;
134 static struct active_request_slot *active_queue_head;
136 static char *cached_accept_language;
138 static char *http_ssl_backend;
140 static int http_schannel_check_revoke = 1;
142 * With the backend being set to `schannel`, setting sslCAinfo would override
143 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
144 * by default.
146 static int http_schannel_use_ssl_cainfo;
148 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
150 size_t size = eltsize * nmemb;
151 struct buffer *buffer = buffer_;
153 if (size > buffer->buf.len - buffer->posn)
154 size = buffer->buf.len - buffer->posn;
155 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
156 buffer->posn += size;
158 return size / eltsize;
161 int seek_buffer(void *clientp, curl_off_t offset, int origin)
163 struct buffer *buffer = clientp;
165 if (origin != SEEK_SET)
166 BUG("seek_buffer only handles SEEK_SET");
167 if (offset < 0 || offset >= buffer->buf.len) {
168 error("curl seek would be outside of buffer");
169 return CURL_SEEKFUNC_FAIL;
172 buffer->posn = offset;
173 return CURL_SEEKFUNC_OK;
176 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
178 size_t size = eltsize * nmemb;
179 struct strbuf *buffer = buffer_;
181 strbuf_add(buffer, ptr, size);
182 return nmemb;
186 * A folded header continuation line starts with any number of spaces or
187 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
188 * It is not a continuation line if the line starts with any other character.
190 static inline int is_hdr_continuation(const char *ptr, const size_t size)
192 return size && (*ptr == ' ' || *ptr == '\t');
195 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p)
197 size_t size = eltsize * nmemb;
198 struct strvec *values = &http_auth.wwwauth_headers;
199 struct strbuf buf = STRBUF_INIT;
200 const char *val;
201 size_t val_len;
204 * Header lines may not come NULL-terminated from libcurl so we must
205 * limit all scans to the maximum length of the header line, or leverage
206 * strbufs for all operations.
208 * In addition, it is possible that header values can be split over
209 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
210 * but older servers may still emit them. A continuation header field
211 * value is identified as starting with a space or horizontal tab.
213 * The formal definition of a header field as given in RFC 7230 is:
215 * header-field = field-name ":" OWS field-value OWS
217 * field-name = token
218 * field-value = *( field-content / obs-fold )
219 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
220 * field-vchar = VCHAR / obs-text
222 * obs-fold = CRLF 1*( SP / HTAB )
223 * ; obsolete line folding
224 * ; see Section 3.2.4
227 /* Start of a new WWW-Authenticate header */
228 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
229 strbuf_add(&buf, val, val_len);
232 * Strip the CRLF that should be present at the end of each
233 * field as well as any trailing or leading whitespace from the
234 * value.
236 strbuf_trim(&buf);
238 strvec_push(values, buf.buf);
239 http_auth.header_is_last_match = 1;
240 goto exit;
244 * This line could be a continuation of the previously matched header
245 * field. If this is the case then we should append this value to the
246 * end of the previously consumed value.
248 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
250 * Trim the CRLF and any leading or trailing from this line.
252 strbuf_add(&buf, ptr, size);
253 strbuf_trim(&buf);
256 * At this point we should always have at least one existing
257 * value, even if it is empty. Do not bother appending the new
258 * value if this continuation header is itself empty.
260 if (!values->nr) {
261 BUG("should have at least one existing header value");
262 } else if (buf.len) {
263 char *prev = xstrdup(values->v[values->nr - 1]);
265 /* Join two non-empty values with a single space. */
266 const char *const sp = *prev ? " " : "";
268 strvec_pop(values);
269 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
270 free(prev);
273 goto exit;
276 /* Not a continuation of a previously matched auth header line. */
277 http_auth.header_is_last_match = 0;
280 * If this is a HTTP status line and not a header field, this signals
281 * a different HTTP response. libcurl writes all the output of all
282 * response headers of all responses, including redirects.
283 * We only care about the last HTTP request response's headers so clear
284 * the existing array.
286 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
287 strvec_clear(values);
289 exit:
290 strbuf_release(&buf);
291 return size;
294 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
296 return nmemb;
299 static void closedown_active_slot(struct active_request_slot *slot)
301 active_requests--;
302 slot->in_use = 0;
305 static void finish_active_slot(struct active_request_slot *slot)
307 closedown_active_slot(slot);
308 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
310 if (slot->finished)
311 (*slot->finished) = 1;
313 /* Store slot results so they can be read after the slot is reused */
314 if (slot->results) {
315 slot->results->curl_result = slot->curl_result;
316 slot->results->http_code = slot->http_code;
317 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
318 &slot->results->auth_avail);
320 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
321 &slot->results->http_connectcode);
324 /* Run callback if appropriate */
325 if (slot->callback_func)
326 slot->callback_func(slot->callback_data);
329 static void xmulti_remove_handle(struct active_request_slot *slot)
331 curl_multi_remove_handle(curlm, slot->curl);
334 static void process_curl_messages(void)
336 int num_messages;
337 struct active_request_slot *slot;
338 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
340 while (curl_message != NULL) {
341 if (curl_message->msg == CURLMSG_DONE) {
342 int curl_result = curl_message->data.result;
343 slot = active_queue_head;
344 while (slot != NULL &&
345 slot->curl != curl_message->easy_handle)
346 slot = slot->next;
347 if (slot) {
348 xmulti_remove_handle(slot);
349 slot->curl_result = curl_result;
350 finish_active_slot(slot);
351 } else {
352 fprintf(stderr, "Received DONE message for unknown request!\n");
354 } else {
355 fprintf(stderr, "Unknown CURL message received: %d\n",
356 (int)curl_message->msg);
358 curl_message = curl_multi_info_read(curlm, &num_messages);
362 static int http_options(const char *var, const char *value, void *cb)
364 if (!strcmp("http.version", var)) {
365 return git_config_string(&curl_http_version, var, value);
367 if (!strcmp("http.sslverify", var)) {
368 curl_ssl_verify = git_config_bool(var, value);
369 return 0;
371 if (!strcmp("http.sslcipherlist", var))
372 return git_config_string(&ssl_cipherlist, var, value);
373 if (!strcmp("http.sslversion", var))
374 return git_config_string(&ssl_version, var, value);
375 if (!strcmp("http.sslcert", var))
376 return git_config_pathname(&ssl_cert, var, value);
377 if (!strcmp("http.sslkey", var))
378 return git_config_pathname(&ssl_key, var, value);
379 if (!strcmp("http.sslcapath", var))
380 return git_config_pathname(&ssl_capath, var, value);
381 if (!strcmp("http.sslcainfo", var))
382 return git_config_pathname(&ssl_cainfo, var, value);
383 if (!strcmp("http.sslcertpasswordprotected", var)) {
384 ssl_cert_password_required = git_config_bool(var, value);
385 return 0;
387 if (!strcmp("http.ssltry", var)) {
388 curl_ssl_try = git_config_bool(var, value);
389 return 0;
391 if (!strcmp("http.sslbackend", var)) {
392 free(http_ssl_backend);
393 http_ssl_backend = xstrdup_or_null(value);
394 return 0;
397 if (!strcmp("http.schannelcheckrevoke", var)) {
398 http_schannel_check_revoke = git_config_bool(var, value);
399 return 0;
402 if (!strcmp("http.schannelusesslcainfo", var)) {
403 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
404 return 0;
407 if (!strcmp("http.minsessions", var)) {
408 min_curl_sessions = git_config_int(var, value);
409 if (min_curl_sessions > 1)
410 min_curl_sessions = 1;
411 return 0;
413 if (!strcmp("http.maxrequests", var)) {
414 max_requests = git_config_int(var, value);
415 return 0;
417 if (!strcmp("http.lowspeedlimit", var)) {
418 curl_low_speed_limit = (long)git_config_int(var, value);
419 return 0;
421 if (!strcmp("http.lowspeedtime", var)) {
422 curl_low_speed_time = (long)git_config_int(var, value);
423 return 0;
426 if (!strcmp("http.noepsv", var)) {
427 curl_ftp_no_epsv = git_config_bool(var, value);
428 return 0;
430 if (!strcmp("http.proxy", var))
431 return git_config_string(&curl_http_proxy, var, value);
433 if (!strcmp("http.proxyauthmethod", var))
434 return git_config_string(&http_proxy_authmethod, var, value);
436 if (!strcmp("http.proxysslcert", var))
437 return git_config_string(&http_proxy_ssl_cert, var, value);
439 if (!strcmp("http.proxysslkey", var))
440 return git_config_string(&http_proxy_ssl_key, var, value);
442 if (!strcmp("http.proxysslcainfo", var))
443 return git_config_string(&http_proxy_ssl_ca_info, var, value);
445 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
446 proxy_ssl_cert_password_required = git_config_bool(var, value);
447 return 0;
450 if (!strcmp("http.cookiefile", var))
451 return git_config_pathname(&curl_cookie_file, var, value);
452 if (!strcmp("http.savecookies", var)) {
453 curl_save_cookies = git_config_bool(var, value);
454 return 0;
457 if (!strcmp("http.postbuffer", var)) {
458 http_post_buffer = git_config_ssize_t(var, value);
459 if (http_post_buffer < 0)
460 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
461 if (http_post_buffer < LARGE_PACKET_MAX)
462 http_post_buffer = LARGE_PACKET_MAX;
463 return 0;
466 if (!strcmp("http.useragent", var))
467 return git_config_string(&user_agent, var, value);
469 if (!strcmp("http.emptyauth", var)) {
470 if (value && !strcmp("auto", value))
471 curl_empty_auth = -1;
472 else
473 curl_empty_auth = git_config_bool(var, value);
474 return 0;
477 if (!strcmp("http.delegation", var)) {
478 #ifdef CURLGSSAPI_DELEGATION_FLAG
479 return git_config_string(&curl_deleg, var, value);
480 #else
481 warning(_("Delegation control is not supported with cURL < 7.22.0"));
482 return 0;
483 #endif
486 if (!strcmp("http.pinnedpubkey", var)) {
487 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
488 return git_config_pathname(&ssl_pinnedkey, var, value);
489 #else
490 warning(_("Public key pinning not supported with cURL < 7.39.0"));
491 return 0;
492 #endif
495 if (!strcmp("http.extraheader", var)) {
496 if (!value) {
497 return config_error_nonbool(var);
498 } else if (!*value) {
499 string_list_clear(&extra_http_headers, 0);
500 } else {
501 string_list_append(&extra_http_headers, value);
503 return 0;
506 if (!strcmp("http.curloptresolve", var)) {
507 if (!value) {
508 return config_error_nonbool(var);
509 } else if (!*value) {
510 curl_slist_free_all(host_resolutions);
511 host_resolutions = NULL;
512 } else {
513 host_resolutions = curl_slist_append(host_resolutions, value);
515 return 0;
518 if (!strcmp("http.followredirects", var)) {
519 if (value && !strcmp(value, "initial"))
520 http_follow_config = HTTP_FOLLOW_INITIAL;
521 else if (git_config_bool(var, value))
522 http_follow_config = HTTP_FOLLOW_ALWAYS;
523 else
524 http_follow_config = HTTP_FOLLOW_NONE;
525 return 0;
528 /* Fall back on the default ones */
529 return git_default_config(var, value, cb);
532 static int curl_empty_auth_enabled(void)
534 if (curl_empty_auth >= 0)
535 return curl_empty_auth;
538 * In the automatic case, kick in the empty-auth
539 * hack as long as we would potentially try some
540 * method more exotic than "Basic" or "Digest".
542 * But only do this when this is our second or
543 * subsequent request, as by then we know what
544 * methods are available.
546 if (http_auth_methods_restricted &&
547 (http_auth_methods & ~empty_auth_useless))
548 return 1;
549 return 0;
552 static void init_curl_http_auth(CURL *result)
554 if (!http_auth.username || !*http_auth.username) {
555 if (curl_empty_auth_enabled())
556 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
557 return;
560 credential_fill(&http_auth);
562 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
563 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
566 /* *var must be free-able */
567 static void var_override(const char **var, char *value)
569 if (value) {
570 free((void *)*var);
571 *var = xstrdup(value);
575 static void set_proxyauth_name_password(CURL *result)
577 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
578 proxy_auth.username);
579 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
580 proxy_auth.password);
583 static void init_curl_proxy_auth(CURL *result)
585 if (proxy_auth.username) {
586 if (!proxy_auth.password)
587 credential_fill(&proxy_auth);
588 set_proxyauth_name_password(result);
591 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
593 if (http_proxy_authmethod) {
594 int i;
595 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
596 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
597 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
598 proxy_authmethods[i].curlauth_param);
599 break;
602 if (i == ARRAY_SIZE(proxy_authmethods)) {
603 warning("unsupported proxy authentication method %s: using anyauth",
604 http_proxy_authmethod);
605 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
608 else
609 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
612 static int has_cert_password(void)
614 if (ssl_cert == NULL || ssl_cert_password_required != 1)
615 return 0;
616 if (!cert_auth.password) {
617 cert_auth.protocol = xstrdup("cert");
618 cert_auth.host = xstrdup("");
619 cert_auth.username = xstrdup("");
620 cert_auth.path = xstrdup(ssl_cert);
621 credential_fill(&cert_auth);
623 return 1;
626 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
627 static int has_proxy_cert_password(void)
629 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
630 return 0;
631 if (!proxy_cert_auth.password) {
632 proxy_cert_auth.protocol = xstrdup("cert");
633 proxy_cert_auth.host = xstrdup("");
634 proxy_cert_auth.username = xstrdup("");
635 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
636 credential_fill(&proxy_cert_auth);
638 return 1;
640 #endif
642 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
643 static void set_curl_keepalive(CURL *c)
645 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
648 #else
649 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
651 int ka = 1;
652 int rc;
653 socklen_t len = (socklen_t)sizeof(ka);
655 if (type != CURLSOCKTYPE_IPCXN)
656 return 0;
658 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
659 if (rc < 0)
660 warning_errno("unable to set SO_KEEPALIVE on socket");
662 return CURL_SOCKOPT_OK;
665 static void set_curl_keepalive(CURL *c)
667 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
669 #endif
671 /* Return 1 if redactions have been made, 0 otherwise. */
672 static int redact_sensitive_header(struct strbuf *header, size_t offset)
674 int ret = 0;
675 const char *sensitive_header;
677 if (trace_curl_redact &&
678 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
679 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
680 /* The first token is the type, which is OK to log */
681 while (isspace(*sensitive_header))
682 sensitive_header++;
683 while (*sensitive_header && !isspace(*sensitive_header))
684 sensitive_header++;
685 /* Everything else is opaque and possibly sensitive */
686 strbuf_setlen(header, sensitive_header - header->buf);
687 strbuf_addstr(header, " <redacted>");
688 ret = 1;
689 } else if (trace_curl_redact &&
690 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
691 struct strbuf redacted_header = STRBUF_INIT;
692 const char *cookie;
694 while (isspace(*sensitive_header))
695 sensitive_header++;
697 cookie = sensitive_header;
699 while (cookie) {
700 char *equals;
701 char *semicolon = strstr(cookie, "; ");
702 if (semicolon)
703 *semicolon = 0;
704 equals = strchrnul(cookie, '=');
705 if (!equals) {
706 /* invalid cookie, just append and continue */
707 strbuf_addstr(&redacted_header, cookie);
708 continue;
710 strbuf_add(&redacted_header, cookie, equals - cookie);
711 strbuf_addstr(&redacted_header, "=<redacted>");
712 if (semicolon) {
714 * There are more cookies. (Or, for some
715 * reason, the input string ends in "; ".)
717 strbuf_addstr(&redacted_header, "; ");
718 cookie = semicolon + strlen("; ");
719 } else {
720 cookie = NULL;
724 strbuf_setlen(header, sensitive_header - header->buf);
725 strbuf_addbuf(header, &redacted_header);
726 ret = 1;
728 return ret;
731 /* Redact headers in info */
732 static void redact_sensitive_info_header(struct strbuf *header)
734 const char *sensitive_header;
737 * curl's h2h3 prints headers in info, e.g.:
738 * h2h3 [<header-name>: <header-val>]
740 if (trace_curl_redact &&
741 skip_iprefix(header->buf, "h2h3 [", &sensitive_header)) {
742 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
743 /* redaction ate our closing bracket */
744 strbuf_addch(header, ']');
749 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
751 struct strbuf out = STRBUF_INIT;
752 struct strbuf **headers, **header;
754 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
755 text, (long)size, (long)size);
756 trace_strbuf(&trace_curl, &out);
757 strbuf_reset(&out);
758 strbuf_add(&out, ptr, size);
759 headers = strbuf_split_max(&out, '\n', 0);
761 for (header = headers; *header; header++) {
762 if (hide_sensitive_header)
763 redact_sensitive_header(*header, 0);
764 strbuf_insertstr((*header), 0, text);
765 strbuf_insertstr((*header), strlen(text), ": ");
766 strbuf_rtrim((*header));
767 strbuf_addch((*header), '\n');
768 trace_strbuf(&trace_curl, (*header));
770 strbuf_list_free(headers);
771 strbuf_release(&out);
774 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
776 size_t i;
777 struct strbuf out = STRBUF_INIT;
778 unsigned int width = 60;
780 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
781 text, (long)size, (long)size);
782 trace_strbuf(&trace_curl, &out);
784 for (i = 0; i < size; i += width) {
785 size_t w;
787 strbuf_reset(&out);
788 strbuf_addf(&out, "%s: ", text);
789 for (w = 0; (w < width) && (i + w < size); w++) {
790 unsigned char ch = ptr[i + w];
792 strbuf_addch(&out,
793 (ch >= 0x20) && (ch < 0x80)
794 ? ch : '.');
796 strbuf_addch(&out, '\n');
797 trace_strbuf(&trace_curl, &out);
799 strbuf_release(&out);
802 static void curl_dump_info(char *data, size_t size)
804 struct strbuf buf = STRBUF_INIT;
806 strbuf_add(&buf, data, size);
808 redact_sensitive_info_header(&buf);
809 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
811 strbuf_release(&buf);
814 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
816 const char *text;
817 enum { NO_FILTER = 0, DO_FILTER = 1 };
819 switch (type) {
820 case CURLINFO_TEXT:
821 curl_dump_info(data, size);
822 break;
823 case CURLINFO_HEADER_OUT:
824 text = "=> Send header";
825 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
826 break;
827 case CURLINFO_DATA_OUT:
828 if (trace_curl_data) {
829 text = "=> Send data";
830 curl_dump_data(text, (unsigned char *)data, size);
832 break;
833 case CURLINFO_SSL_DATA_OUT:
834 if (trace_curl_data) {
835 text = "=> Send SSL data";
836 curl_dump_data(text, (unsigned char *)data, size);
838 break;
839 case CURLINFO_HEADER_IN:
840 text = "<= Recv header";
841 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
842 break;
843 case CURLINFO_DATA_IN:
844 if (trace_curl_data) {
845 text = "<= Recv data";
846 curl_dump_data(text, (unsigned char *)data, size);
848 break;
849 case CURLINFO_SSL_DATA_IN:
850 if (trace_curl_data) {
851 text = "<= Recv SSL data";
852 curl_dump_data(text, (unsigned char *)data, size);
854 break;
856 default: /* we ignore unknown types by default */
857 return 0;
859 return 0;
862 void http_trace_curl_no_data(void)
864 trace_override_envvar(&trace_curl, "1");
865 trace_curl_data = 0;
868 void setup_curl_trace(CURL *handle)
870 if (!trace_want(&trace_curl))
871 return;
872 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
873 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
874 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
877 static void proto_list_append(struct strbuf *list, const char *proto)
879 if (!list)
880 return;
881 if (list->len)
882 strbuf_addch(list, ',');
883 strbuf_addstr(list, proto);
886 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
888 long bits = 0;
890 if (is_transport_allowed("http", from_user)) {
891 bits |= CURLPROTO_HTTP;
892 proto_list_append(list, "http");
894 if (is_transport_allowed("https", from_user)) {
895 bits |= CURLPROTO_HTTPS;
896 proto_list_append(list, "https");
898 if (is_transport_allowed("ftp", from_user)) {
899 bits |= CURLPROTO_FTP;
900 proto_list_append(list, "ftp");
902 if (is_transport_allowed("ftps", from_user)) {
903 bits |= CURLPROTO_FTPS;
904 proto_list_append(list, "ftps");
907 return bits;
910 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
911 static int get_curl_http_version_opt(const char *version_string, long *opt)
913 int i;
914 static struct {
915 const char *name;
916 long opt_token;
917 } choice[] = {
918 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
919 { "HTTP/2", CURL_HTTP_VERSION_2 }
922 for (i = 0; i < ARRAY_SIZE(choice); i++) {
923 if (!strcmp(version_string, choice[i].name)) {
924 *opt = choice[i].opt_token;
925 return 0;
929 warning("unknown value given to http.version: '%s'", version_string);
930 return -1; /* not found */
933 #endif
935 static CURL *get_curl_handle(void)
937 CURL *result = curl_easy_init();
939 if (!result)
940 die("curl_easy_init failed");
942 if (!curl_ssl_verify) {
943 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
944 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
945 } else {
946 /* Verify authenticity of the peer's certificate */
947 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
948 /* The name in the cert must match whom we tried to connect */
949 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
952 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
953 if (curl_http_version) {
954 long opt;
955 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
956 /* Set request use http version */
957 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
960 #endif
962 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
963 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
965 #ifdef CURLGSSAPI_DELEGATION_FLAG
966 if (curl_deleg) {
967 int i;
968 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
969 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
970 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
971 curl_deleg_levels[i].curl_deleg_param);
972 break;
975 if (i == ARRAY_SIZE(curl_deleg_levels))
976 warning("Unknown delegation method '%s': using default",
977 curl_deleg);
979 #endif
981 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
982 !http_schannel_check_revoke) {
983 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
984 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
985 #else
986 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
987 #endif
990 if (http_proactive_auth)
991 init_curl_http_auth(result);
993 if (getenv("GIT_SSL_VERSION"))
994 ssl_version = getenv("GIT_SSL_VERSION");
995 if (ssl_version && *ssl_version) {
996 int i;
997 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
998 if (!strcmp(ssl_version, sslversions[i].name)) {
999 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1000 sslversions[i].ssl_version);
1001 break;
1004 if (i == ARRAY_SIZE(sslversions))
1005 warning("unsupported ssl version %s: using default",
1006 ssl_version);
1009 if (getenv("GIT_SSL_CIPHER_LIST"))
1010 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1011 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1012 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1013 ssl_cipherlist);
1015 if (ssl_cert)
1016 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1017 if (has_cert_password())
1018 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1019 if (ssl_key)
1020 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1021 if (ssl_capath)
1022 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1023 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1024 if (ssl_pinnedkey)
1025 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1026 #endif
1027 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1028 !http_schannel_use_ssl_cainfo) {
1029 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1030 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1031 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1032 #endif
1033 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1034 if (ssl_cainfo)
1035 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1036 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1037 if (http_proxy_ssl_ca_info)
1038 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1039 #endif
1042 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1043 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1044 curl_low_speed_limit);
1045 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1046 curl_low_speed_time);
1049 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1050 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1052 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1054 struct strbuf buf = STRBUF_INIT;
1056 get_curl_allowed_protocols(0, &buf);
1057 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1058 strbuf_reset(&buf);
1060 get_curl_allowed_protocols(-1, &buf);
1061 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1062 strbuf_release(&buf);
1064 #else
1065 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1066 get_curl_allowed_protocols(0, NULL));
1067 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1068 get_curl_allowed_protocols(-1, NULL));
1069 #endif
1071 if (getenv("GIT_CURL_VERBOSE"))
1072 http_trace_curl_no_data();
1073 setup_curl_trace(result);
1074 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1075 trace_curl_data = 0;
1076 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1077 trace_curl_redact = 0;
1079 curl_easy_setopt(result, CURLOPT_USERAGENT,
1080 user_agent ? user_agent : git_user_agent());
1082 if (curl_ftp_no_epsv)
1083 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1085 if (curl_ssl_try)
1086 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1089 * CURL also examines these variables as a fallback; but we need to query
1090 * them here in order to decide whether to prompt for missing password (cf.
1091 * init_curl_proxy_auth()).
1093 * Unlike many other common environment variables, these are historically
1094 * lowercase only. It appears that CURL did not know this and implemented
1095 * only uppercase variants, which was later corrected to take both - with
1096 * the exception of http_proxy, which is lowercase only also in CURL. As
1097 * the lowercase versions are the historical quasi-standard, they take
1098 * precedence here, as in CURL.
1100 if (!curl_http_proxy) {
1101 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1102 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1103 var_override(&curl_http_proxy, getenv("https_proxy"));
1104 } else {
1105 var_override(&curl_http_proxy, getenv("http_proxy"));
1107 if (!curl_http_proxy) {
1108 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1109 var_override(&curl_http_proxy, getenv("all_proxy"));
1113 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1115 * Handle case with the empty http.proxy value here to keep
1116 * common code clean.
1117 * NB: empty option disables proxying at all.
1119 curl_easy_setopt(result, CURLOPT_PROXY, "");
1120 } else if (curl_http_proxy) {
1121 if (starts_with(curl_http_proxy, "socks5h"))
1122 curl_easy_setopt(result,
1123 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1124 else if (starts_with(curl_http_proxy, "socks5"))
1125 curl_easy_setopt(result,
1126 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1127 else if (starts_with(curl_http_proxy, "socks4a"))
1128 curl_easy_setopt(result,
1129 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1130 else if (starts_with(curl_http_proxy, "socks"))
1131 curl_easy_setopt(result,
1132 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1133 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1134 else if (starts_with(curl_http_proxy, "https")) {
1135 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1137 if (http_proxy_ssl_cert)
1138 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1140 if (http_proxy_ssl_key)
1141 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1143 if (has_proxy_cert_password())
1144 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1146 #endif
1147 if (strstr(curl_http_proxy, "://"))
1148 credential_from_url(&proxy_auth, curl_http_proxy);
1149 else {
1150 struct strbuf url = STRBUF_INIT;
1151 strbuf_addf(&url, "http://%s", curl_http_proxy);
1152 credential_from_url(&proxy_auth, url.buf);
1153 strbuf_release(&url);
1156 if (!proxy_auth.host)
1157 die("Invalid proxy URL '%s'", curl_http_proxy);
1159 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1160 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1161 var_override(&curl_no_proxy, getenv("no_proxy"));
1162 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1164 init_curl_proxy_auth(result);
1166 set_curl_keepalive(result);
1168 return result;
1171 static void set_from_env(const char **var, const char *envname)
1173 const char *val = getenv(envname);
1174 if (val)
1175 *var = val;
1178 void http_init(struct remote *remote, const char *url, int proactive_auth)
1180 char *low_speed_limit;
1181 char *low_speed_time;
1182 char *normalized_url;
1183 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1185 config.section = "http";
1186 config.key = NULL;
1187 config.collect_fn = http_options;
1188 config.cascade_fn = git_default_config;
1189 config.cb = NULL;
1191 http_is_verbose = 0;
1192 normalized_url = url_normalize(url, &config.url);
1194 git_config(urlmatch_config_entry, &config);
1195 free(normalized_url);
1196 string_list_clear(&config.vars, 1);
1198 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1199 if (http_ssl_backend) {
1200 const curl_ssl_backend **backends;
1201 struct strbuf buf = STRBUF_INIT;
1202 int i;
1204 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1205 case CURLSSLSET_UNKNOWN_BACKEND:
1206 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1207 "Supported SSL backends:"),
1208 http_ssl_backend);
1209 for (i = 0; backends[i]; i++)
1210 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1211 die("%s", buf.buf);
1212 case CURLSSLSET_NO_BACKENDS:
1213 die(_("Could not set SSL backend to '%s': "
1214 "cURL was built without SSL backends"),
1215 http_ssl_backend);
1216 case CURLSSLSET_TOO_LATE:
1217 die(_("Could not set SSL backend to '%s': already set"),
1218 http_ssl_backend);
1219 case CURLSSLSET_OK:
1220 break; /* Okay! */
1223 #endif
1225 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1226 die("curl_global_init failed");
1228 http_proactive_auth = proactive_auth;
1230 if (remote && remote->http_proxy)
1231 curl_http_proxy = xstrdup(remote->http_proxy);
1233 if (remote)
1234 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1236 pragma_header = curl_slist_append(http_copy_default_headers(),
1237 "Pragma: no-cache");
1238 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1239 "Pragma:");
1242 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1243 if (http_max_requests)
1244 max_requests = atoi(http_max_requests);
1247 curlm = curl_multi_init();
1248 if (!curlm)
1249 die("curl_multi_init failed");
1251 if (getenv("GIT_SSL_NO_VERIFY"))
1252 curl_ssl_verify = 0;
1254 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1255 set_from_env(&ssl_key, "GIT_SSL_KEY");
1256 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1257 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1259 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1261 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1262 if (low_speed_limit)
1263 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1264 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1265 if (low_speed_time)
1266 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1268 if (curl_ssl_verify == -1)
1269 curl_ssl_verify = 1;
1271 curl_session_count = 0;
1272 if (max_requests < 1)
1273 max_requests = DEFAULT_MAX_REQUESTS;
1275 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1276 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1277 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1279 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1280 proxy_ssl_cert_password_required = 1;
1282 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1283 curl_ftp_no_epsv = 1;
1285 if (url) {
1286 credential_from_url(&http_auth, url);
1287 if (!ssl_cert_password_required &&
1288 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1289 starts_with(url, "https://"))
1290 ssl_cert_password_required = 1;
1293 curl_default = get_curl_handle();
1296 void http_cleanup(void)
1298 struct active_request_slot *slot = active_queue_head;
1300 while (slot != NULL) {
1301 struct active_request_slot *next = slot->next;
1302 if (slot->curl) {
1303 xmulti_remove_handle(slot);
1304 curl_easy_cleanup(slot->curl);
1306 free(slot);
1307 slot = next;
1309 active_queue_head = NULL;
1311 curl_easy_cleanup(curl_default);
1313 curl_multi_cleanup(curlm);
1314 curl_global_cleanup();
1316 string_list_clear(&extra_http_headers, 0);
1318 curl_slist_free_all(pragma_header);
1319 pragma_header = NULL;
1321 curl_slist_free_all(no_pragma_header);
1322 no_pragma_header = NULL;
1324 curl_slist_free_all(host_resolutions);
1325 host_resolutions = NULL;
1327 if (curl_http_proxy) {
1328 free((void *)curl_http_proxy);
1329 curl_http_proxy = NULL;
1332 if (proxy_auth.password) {
1333 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1334 FREE_AND_NULL(proxy_auth.password);
1337 free((void *)curl_proxyuserpwd);
1338 curl_proxyuserpwd = NULL;
1340 free((void *)http_proxy_authmethod);
1341 http_proxy_authmethod = NULL;
1343 if (cert_auth.password) {
1344 memset(cert_auth.password, 0, strlen(cert_auth.password));
1345 FREE_AND_NULL(cert_auth.password);
1347 ssl_cert_password_required = 0;
1349 if (proxy_cert_auth.password) {
1350 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1351 FREE_AND_NULL(proxy_cert_auth.password);
1353 proxy_ssl_cert_password_required = 0;
1355 FREE_AND_NULL(cached_accept_language);
1358 struct active_request_slot *get_active_slot(void)
1360 struct active_request_slot *slot = active_queue_head;
1361 struct active_request_slot *newslot;
1363 int num_transfers;
1365 /* Wait for a slot to open up if the queue is full */
1366 while (active_requests >= max_requests) {
1367 curl_multi_perform(curlm, &num_transfers);
1368 if (num_transfers < active_requests)
1369 process_curl_messages();
1372 while (slot != NULL && slot->in_use)
1373 slot = slot->next;
1375 if (!slot) {
1376 newslot = xmalloc(sizeof(*newslot));
1377 newslot->curl = NULL;
1378 newslot->in_use = 0;
1379 newslot->next = NULL;
1381 slot = active_queue_head;
1382 if (!slot) {
1383 active_queue_head = newslot;
1384 } else {
1385 while (slot->next != NULL)
1386 slot = slot->next;
1387 slot->next = newslot;
1389 slot = newslot;
1392 if (!slot->curl) {
1393 slot->curl = curl_easy_duphandle(curl_default);
1394 curl_session_count++;
1397 active_requests++;
1398 slot->in_use = 1;
1399 slot->results = NULL;
1400 slot->finished = NULL;
1401 slot->callback_data = NULL;
1402 slot->callback_func = NULL;
1403 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1404 if (curl_save_cookies)
1405 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1406 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1407 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1408 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1409 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1410 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1411 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1412 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1413 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1414 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1415 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1416 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1419 * Default following to off unless "ALWAYS" is configured; this gives
1420 * callers a sane starting point, and they can tweak for individual
1421 * HTTP_FOLLOW_* cases themselves.
1423 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1424 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1425 else
1426 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1428 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1429 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1430 if (http_auth.password || curl_empty_auth_enabled())
1431 init_curl_http_auth(slot->curl);
1433 return slot;
1436 int start_active_slot(struct active_request_slot *slot)
1438 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1439 int num_transfers;
1441 if (curlm_result != CURLM_OK &&
1442 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1443 warning("curl_multi_add_handle failed: %s",
1444 curl_multi_strerror(curlm_result));
1445 active_requests--;
1446 slot->in_use = 0;
1447 return 0;
1451 * We know there must be something to do, since we just added
1452 * something.
1454 curl_multi_perform(curlm, &num_transfers);
1455 return 1;
1458 struct fill_chain {
1459 void *data;
1460 int (*fill)(void *);
1461 struct fill_chain *next;
1464 static struct fill_chain *fill_cfg;
1466 void add_fill_function(void *data, int (*fill)(void *))
1468 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1469 struct fill_chain **linkp = &fill_cfg;
1470 new_fill->data = data;
1471 new_fill->fill = fill;
1472 new_fill->next = NULL;
1473 while (*linkp)
1474 linkp = &(*linkp)->next;
1475 *linkp = new_fill;
1478 void fill_active_slots(void)
1480 struct active_request_slot *slot = active_queue_head;
1482 while (active_requests < max_requests) {
1483 struct fill_chain *fill;
1484 for (fill = fill_cfg; fill; fill = fill->next)
1485 if (fill->fill(fill->data))
1486 break;
1488 if (!fill)
1489 break;
1492 while (slot != NULL) {
1493 if (!slot->in_use && slot->curl != NULL
1494 && curl_session_count > min_curl_sessions) {
1495 curl_easy_cleanup(slot->curl);
1496 slot->curl = NULL;
1497 curl_session_count--;
1499 slot = slot->next;
1503 void step_active_slots(void)
1505 int num_transfers;
1506 CURLMcode curlm_result;
1508 do {
1509 curlm_result = curl_multi_perform(curlm, &num_transfers);
1510 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1511 if (num_transfers < active_requests) {
1512 process_curl_messages();
1513 fill_active_slots();
1517 void run_active_slot(struct active_request_slot *slot)
1519 fd_set readfds;
1520 fd_set writefds;
1521 fd_set excfds;
1522 int max_fd;
1523 struct timeval select_timeout;
1524 int finished = 0;
1526 slot->finished = &finished;
1527 while (!finished) {
1528 step_active_slots();
1530 if (slot->in_use) {
1531 long curl_timeout;
1532 curl_multi_timeout(curlm, &curl_timeout);
1533 if (curl_timeout == 0) {
1534 continue;
1535 } else if (curl_timeout == -1) {
1536 select_timeout.tv_sec = 0;
1537 select_timeout.tv_usec = 50000;
1538 } else {
1539 select_timeout.tv_sec = curl_timeout / 1000;
1540 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1543 max_fd = -1;
1544 FD_ZERO(&readfds);
1545 FD_ZERO(&writefds);
1546 FD_ZERO(&excfds);
1547 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1550 * It can happen that curl_multi_timeout returns a pathologically
1551 * long timeout when curl_multi_fdset returns no file descriptors
1552 * to read. See commit message for more details.
1554 if (max_fd < 0 &&
1555 (select_timeout.tv_sec > 0 ||
1556 select_timeout.tv_usec > 50000)) {
1557 select_timeout.tv_sec = 0;
1558 select_timeout.tv_usec = 50000;
1561 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1566 * The value of slot->finished we set before the loop was used
1567 * to set our "finished" variable when our request completed.
1569 * 1. The slot may not have been reused for another requst
1570 * yet, in which case it still has &finished.
1572 * 2. The slot may already be in-use to serve another request,
1573 * which can further be divided into two cases:
1575 * (a) If call run_active_slot() hasn't been called for that
1576 * other request, slot->finished would have been cleared
1577 * by get_active_slot() and has NULL.
1579 * (b) If the request did call run_active_slot(), then the
1580 * call would have updated slot->finished at the beginning
1581 * of this function, and with the clearing of the member
1582 * below, we would find that slot->finished is now NULL.
1584 * In all cases, slot->finished has no useful information to
1585 * anybody at this point. Some compilers warn us for
1586 * attempting to smuggle a pointer that is about to become
1587 * invalid, i.e. &finished. We clear it here to assure them.
1589 slot->finished = NULL;
1592 static void release_active_slot(struct active_request_slot *slot)
1594 closedown_active_slot(slot);
1595 if (slot->curl) {
1596 xmulti_remove_handle(slot);
1597 if (curl_session_count > min_curl_sessions) {
1598 curl_easy_cleanup(slot->curl);
1599 slot->curl = NULL;
1600 curl_session_count--;
1603 fill_active_slots();
1606 void finish_all_active_slots(void)
1608 struct active_request_slot *slot = active_queue_head;
1610 while (slot != NULL)
1611 if (slot->in_use) {
1612 run_active_slot(slot);
1613 slot = active_queue_head;
1614 } else {
1615 slot = slot->next;
1619 /* Helpers for modifying and creating URLs */
1620 static inline int needs_quote(int ch)
1622 if (((ch >= 'A') && (ch <= 'Z'))
1623 || ((ch >= 'a') && (ch <= 'z'))
1624 || ((ch >= '0') && (ch <= '9'))
1625 || (ch == '/')
1626 || (ch == '-')
1627 || (ch == '.'))
1628 return 0;
1629 return 1;
1632 static char *quote_ref_url(const char *base, const char *ref)
1634 struct strbuf buf = STRBUF_INIT;
1635 const char *cp;
1636 int ch;
1638 end_url_with_slash(&buf, base);
1640 for (cp = ref; (ch = *cp) != 0; cp++)
1641 if (needs_quote(ch))
1642 strbuf_addf(&buf, "%%%02x", ch);
1643 else
1644 strbuf_addch(&buf, *cp);
1646 return strbuf_detach(&buf, NULL);
1649 void append_remote_object_url(struct strbuf *buf, const char *url,
1650 const char *hex,
1651 int only_two_digit_prefix)
1653 end_url_with_slash(buf, url);
1655 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1656 if (!only_two_digit_prefix)
1657 strbuf_addstr(buf, hex + 2);
1660 char *get_remote_object_url(const char *url, const char *hex,
1661 int only_two_digit_prefix)
1663 struct strbuf buf = STRBUF_INIT;
1664 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1665 return strbuf_detach(&buf, NULL);
1668 void normalize_curl_result(CURLcode *result, long http_code,
1669 char *errorstr, size_t errorlen)
1672 * If we see a failing http code with CURLE_OK, we have turned off
1673 * FAILONERROR (to keep the server's custom error response), and should
1674 * translate the code into failure here.
1676 * Likewise, if we see a redirect (30x code), that means we turned off
1677 * redirect-following, and we should treat the result as an error.
1679 if (*result == CURLE_OK && http_code >= 300) {
1680 *result = CURLE_HTTP_RETURNED_ERROR;
1682 * Normally curl will already have put the "reason phrase"
1683 * from the server into curl_errorstr; unfortunately without
1684 * FAILONERROR it is lost, so we can give only the numeric
1685 * status code.
1687 xsnprintf(errorstr, errorlen,
1688 "The requested URL returned error: %ld",
1689 http_code);
1693 static int handle_curl_result(struct slot_results *results)
1695 normalize_curl_result(&results->curl_result, results->http_code,
1696 curl_errorstr, sizeof(curl_errorstr));
1698 if (results->curl_result == CURLE_OK) {
1699 credential_approve(&http_auth);
1700 credential_approve(&proxy_auth);
1701 credential_approve(&cert_auth);
1702 return HTTP_OK;
1703 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1705 * We can't tell from here whether it's a bad path, bad
1706 * certificate, bad password, or something else wrong
1707 * with the certificate. So we reject the credential to
1708 * avoid caching or saving a bad password.
1710 credential_reject(&cert_auth);
1711 return HTTP_NOAUTH;
1712 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1713 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1714 return HTTP_NOMATCHPUBLICKEY;
1715 #endif
1716 } else if (missing_target(results))
1717 return HTTP_MISSING_TARGET;
1718 else if (results->http_code == 401) {
1719 if (http_auth.username && http_auth.password) {
1720 credential_reject(&http_auth);
1721 return HTTP_NOAUTH;
1722 } else {
1723 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1724 if (results->auth_avail) {
1725 http_auth_methods &= results->auth_avail;
1726 http_auth_methods_restricted = 1;
1728 return HTTP_REAUTH;
1730 } else {
1731 if (results->http_connectcode == 407)
1732 credential_reject(&proxy_auth);
1733 if (!curl_errorstr[0])
1734 strlcpy(curl_errorstr,
1735 curl_easy_strerror(results->curl_result),
1736 sizeof(curl_errorstr));
1737 return HTTP_ERROR;
1741 int run_one_slot(struct active_request_slot *slot,
1742 struct slot_results *results)
1744 slot->results = results;
1745 if (!start_active_slot(slot)) {
1746 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1747 "failed to start HTTP request");
1748 return HTTP_START_FAILED;
1751 run_active_slot(slot);
1752 return handle_curl_result(results);
1755 struct curl_slist *http_copy_default_headers(void)
1757 struct curl_slist *headers = NULL;
1758 const struct string_list_item *item;
1760 for_each_string_list_item(item, &extra_http_headers)
1761 headers = curl_slist_append(headers, item->string);
1763 return headers;
1766 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1768 char *ptr;
1769 CURLcode ret;
1771 strbuf_reset(buf);
1772 ret = curl_easy_getinfo(curl, info, &ptr);
1773 if (!ret && ptr)
1774 strbuf_addstr(buf, ptr);
1775 return ret;
1779 * Check for and extract a content-type parameter. "raw"
1780 * should be positioned at the start of the potential
1781 * parameter, with any whitespace already removed.
1783 * "name" is the name of the parameter. The value is appended
1784 * to "out".
1786 static int extract_param(const char *raw, const char *name,
1787 struct strbuf *out)
1789 size_t len = strlen(name);
1791 if (strncasecmp(raw, name, len))
1792 return -1;
1793 raw += len;
1795 if (*raw != '=')
1796 return -1;
1797 raw++;
1799 while (*raw && !isspace(*raw) && *raw != ';')
1800 strbuf_addch(out, *raw++);
1801 return 0;
1805 * Extract a normalized version of the content type, with any
1806 * spaces suppressed, all letters lowercased, and no trailing ";"
1807 * or parameters.
1809 * Note that we will silently remove even invalid whitespace. For
1810 * example, "text / plain" is specifically forbidden by RFC 2616,
1811 * but "text/plain" is the only reasonable output, and this keeps
1812 * our code simple.
1814 * If the "charset" argument is not NULL, store the value of any
1815 * charset parameter there.
1817 * Example:
1818 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1819 * "text / plain" -> "text/plain"
1821 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1822 struct strbuf *charset)
1824 const char *p;
1826 strbuf_reset(type);
1827 strbuf_grow(type, raw->len);
1828 for (p = raw->buf; *p; p++) {
1829 if (isspace(*p))
1830 continue;
1831 if (*p == ';') {
1832 p++;
1833 break;
1835 strbuf_addch(type, tolower(*p));
1838 if (!charset)
1839 return;
1841 strbuf_reset(charset);
1842 while (*p) {
1843 while (isspace(*p) || *p == ';')
1844 p++;
1845 if (!extract_param(p, "charset", charset))
1846 return;
1847 while (*p && !isspace(*p))
1848 p++;
1851 if (!charset->len && starts_with(type->buf, "text/"))
1852 strbuf_addstr(charset, "ISO-8859-1");
1855 static void write_accept_language(struct strbuf *buf)
1858 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1859 * that, q-value will be smaller than 0.001, the minimum q-value the
1860 * HTTP specification allows. See
1861 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1863 const int MAX_DECIMAL_PLACES = 3;
1864 const int MAX_LANGUAGE_TAGS = 1000;
1865 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1866 char **language_tags = NULL;
1867 int num_langs = 0;
1868 const char *s = get_preferred_languages();
1869 int i;
1870 struct strbuf tag = STRBUF_INIT;
1872 /* Don't add Accept-Language header if no language is preferred. */
1873 if (!s)
1874 return;
1877 * Split the colon-separated string of preferred languages into
1878 * language_tags array.
1880 do {
1881 /* collect language tag */
1882 for (; *s && (isalnum(*s) || *s == '_'); s++)
1883 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1885 /* skip .codeset, @modifier and any other unnecessary parts */
1886 while (*s && *s != ':')
1887 s++;
1889 if (tag.len) {
1890 num_langs++;
1891 REALLOC_ARRAY(language_tags, num_langs);
1892 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1893 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1894 break;
1896 } while (*s++);
1898 /* write Accept-Language header into buf */
1899 if (num_langs) {
1900 int last_buf_len = 0;
1901 int max_q;
1902 int decimal_places;
1903 char q_format[32];
1905 /* add '*' */
1906 REALLOC_ARRAY(language_tags, num_langs + 1);
1907 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1909 /* compute decimal_places */
1910 for (max_q = 1, decimal_places = 0;
1911 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1912 decimal_places++, max_q *= 10)
1915 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1917 strbuf_addstr(buf, "Accept-Language: ");
1919 for (i = 0; i < num_langs; i++) {
1920 if (i > 0)
1921 strbuf_addstr(buf, ", ");
1923 strbuf_addstr(buf, language_tags[i]);
1925 if (i > 0)
1926 strbuf_addf(buf, q_format, max_q - i);
1928 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1929 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1930 break;
1933 last_buf_len = buf->len;
1937 /* free language tags -- last one is a static '*' */
1938 for (i = 0; i < num_langs - 1; i++)
1939 free(language_tags[i]);
1940 free(language_tags);
1944 * Get an Accept-Language header which indicates user's preferred languages.
1946 * Examples:
1947 * LANGUAGE= -> ""
1948 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1949 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1950 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1951 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1952 * LANGUAGE= LANG=C -> ""
1954 const char *http_get_accept_language_header(void)
1956 if (!cached_accept_language) {
1957 struct strbuf buf = STRBUF_INIT;
1958 write_accept_language(&buf);
1959 if (buf.len > 0)
1960 cached_accept_language = strbuf_detach(&buf, NULL);
1963 return cached_accept_language;
1966 static void http_opt_request_remainder(CURL *curl, off_t pos)
1968 char buf[128];
1969 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1970 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1973 /* http_request() targets */
1974 #define HTTP_REQUEST_STRBUF 0
1975 #define HTTP_REQUEST_FILE 1
1977 static int http_request(const char *url,
1978 void *result, int target,
1979 const struct http_get_options *options)
1981 struct active_request_slot *slot;
1982 struct slot_results results;
1983 struct curl_slist *headers = http_copy_default_headers();
1984 struct strbuf buf = STRBUF_INIT;
1985 const char *accept_language;
1986 int ret;
1988 slot = get_active_slot();
1989 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1991 if (!result) {
1992 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1993 } else {
1994 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1995 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
1997 if (target == HTTP_REQUEST_FILE) {
1998 off_t posn = ftello(result);
1999 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2000 fwrite);
2001 if (posn > 0)
2002 http_opt_request_remainder(slot->curl, posn);
2003 } else
2004 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2005 fwrite_buffer);
2008 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2010 accept_language = http_get_accept_language_header();
2012 if (accept_language)
2013 headers = curl_slist_append(headers, accept_language);
2015 strbuf_addstr(&buf, "Pragma:");
2016 if (options && options->no_cache)
2017 strbuf_addstr(&buf, " no-cache");
2018 if (options && options->initial_request &&
2019 http_follow_config == HTTP_FOLLOW_INITIAL)
2020 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2022 headers = curl_slist_append(headers, buf.buf);
2024 /* Add additional headers here */
2025 if (options && options->extra_headers) {
2026 const struct string_list_item *item;
2027 for_each_string_list_item(item, options->extra_headers) {
2028 headers = curl_slist_append(headers, item->string);
2032 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2033 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2034 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2035 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2037 ret = run_one_slot(slot, &results);
2039 if (options && options->content_type) {
2040 struct strbuf raw = STRBUF_INIT;
2041 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2042 extract_content_type(&raw, options->content_type,
2043 options->charset);
2044 strbuf_release(&raw);
2047 if (options && options->effective_url)
2048 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2049 options->effective_url);
2051 curl_slist_free_all(headers);
2052 strbuf_release(&buf);
2054 return ret;
2058 * Update the "base" url to a more appropriate value, as deduced by
2059 * redirects seen when requesting a URL starting with "url".
2061 * The "asked" parameter is a URL that we asked curl to access, and must begin
2062 * with "base".
2064 * The "got" parameter is the URL that curl reported to us as where we ended
2065 * up.
2067 * Returns 1 if we updated the base url, 0 otherwise.
2069 * Our basic strategy is to compare "base" and "asked" to find the bits
2070 * specific to our request. We then strip those bits off of "got" to yield the
2071 * new base. So for example, if our base is "http://example.com/foo.git",
2072 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2073 * with "https://other.example.com/foo.git/info/refs". We would want the
2074 * new URL to become "https://other.example.com/foo.git".
2076 * Note that this assumes a sane redirect scheme. It's entirely possible
2077 * in the example above to end up at a URL that does not even end in
2078 * "info/refs". In such a case we die. There's not much we can do, such a
2079 * scheme is unlikely to represent a real git repository, and failing to
2080 * rewrite the base opens options for malicious redirects to do funny things.
2082 static int update_url_from_redirect(struct strbuf *base,
2083 const char *asked,
2084 const struct strbuf *got)
2086 const char *tail;
2087 size_t new_len;
2089 if (!strcmp(asked, got->buf))
2090 return 0;
2092 if (!skip_prefix(asked, base->buf, &tail))
2093 BUG("update_url_from_redirect: %s is not a superset of %s",
2094 asked, base->buf);
2096 new_len = got->len;
2097 if (!strip_suffix_mem(got->buf, &new_len, tail))
2098 die(_("unable to update url base from redirection:\n"
2099 " asked for: %s\n"
2100 " redirect: %s"),
2101 asked, got->buf);
2103 strbuf_reset(base);
2104 strbuf_add(base, got->buf, new_len);
2106 return 1;
2109 static int http_request_reauth(const char *url,
2110 void *result, int target,
2111 struct http_get_options *options)
2113 int ret = http_request(url, result, target, options);
2115 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2116 return ret;
2118 if (options && options->effective_url && options->base_url) {
2119 if (update_url_from_redirect(options->base_url,
2120 url, options->effective_url)) {
2121 credential_from_url(&http_auth, options->base_url->buf);
2122 url = options->effective_url->buf;
2126 if (ret != HTTP_REAUTH)
2127 return ret;
2130 * The previous request may have put cruft into our output stream; we
2131 * should clear it out before making our next request.
2133 switch (target) {
2134 case HTTP_REQUEST_STRBUF:
2135 strbuf_reset(result);
2136 break;
2137 case HTTP_REQUEST_FILE:
2138 if (fflush(result)) {
2139 error_errno("unable to flush a file");
2140 return HTTP_START_FAILED;
2142 rewind(result);
2143 if (ftruncate(fileno(result), 0) < 0) {
2144 error_errno("unable to truncate a file");
2145 return HTTP_START_FAILED;
2147 break;
2148 default:
2149 BUG("Unknown http_request target");
2152 credential_fill(&http_auth);
2154 return http_request(url, result, target, options);
2157 int http_get_strbuf(const char *url,
2158 struct strbuf *result,
2159 struct http_get_options *options)
2161 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2165 * Downloads a URL and stores the result in the given file.
2167 * If a previous interrupted download is detected (i.e. a previous temporary
2168 * file is still around) the download is resumed.
2170 int http_get_file(const char *url, const char *filename,
2171 struct http_get_options *options)
2173 int ret;
2174 struct strbuf tmpfile = STRBUF_INIT;
2175 FILE *result;
2177 strbuf_addf(&tmpfile, "%s.temp", filename);
2178 result = fopen(tmpfile.buf, "a");
2179 if (!result) {
2180 error("Unable to open local file %s", tmpfile.buf);
2181 ret = HTTP_ERROR;
2182 goto cleanup;
2185 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2186 fclose(result);
2188 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2189 ret = HTTP_ERROR;
2190 cleanup:
2191 strbuf_release(&tmpfile);
2192 return ret;
2195 int http_fetch_ref(const char *base, struct ref *ref)
2197 struct http_get_options options = {0};
2198 char *url;
2199 struct strbuf buffer = STRBUF_INIT;
2200 int ret = -1;
2202 options.no_cache = 1;
2204 url = quote_ref_url(base, ref->name);
2205 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2206 strbuf_rtrim(&buffer);
2207 if (buffer.len == the_hash_algo->hexsz)
2208 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2209 else if (starts_with(buffer.buf, "ref: ")) {
2210 ref->symref = xstrdup(buffer.buf + 5);
2211 ret = 0;
2215 strbuf_release(&buffer);
2216 free(url);
2217 return ret;
2220 /* Helpers for fetching packs */
2221 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2223 char *url, *tmp;
2224 struct strbuf buf = STRBUF_INIT;
2226 if (http_is_verbose)
2227 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2229 end_url_with_slash(&buf, base_url);
2230 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2231 url = strbuf_detach(&buf, NULL);
2233 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2234 tmp = strbuf_detach(&buf, NULL);
2236 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2237 error("Unable to get pack index %s", url);
2238 FREE_AND_NULL(tmp);
2241 free(url);
2242 return tmp;
2245 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2246 unsigned char *sha1, const char *base_url)
2248 struct packed_git *new_pack;
2249 char *tmp_idx = NULL;
2250 int ret;
2252 if (has_pack_index(sha1)) {
2253 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2254 if (!new_pack)
2255 return -1; /* parse_pack_index() already issued error message */
2256 goto add_pack;
2259 tmp_idx = fetch_pack_index(sha1, base_url);
2260 if (!tmp_idx)
2261 return -1;
2263 new_pack = parse_pack_index(sha1, tmp_idx);
2264 if (!new_pack) {
2265 unlink(tmp_idx);
2266 free(tmp_idx);
2268 return -1; /* parse_pack_index() already issued error message */
2271 ret = verify_pack_index(new_pack);
2272 if (!ret) {
2273 close_pack_index(new_pack);
2274 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2276 free(tmp_idx);
2277 if (ret)
2278 return -1;
2280 add_pack:
2281 new_pack->next = *packs_head;
2282 *packs_head = new_pack;
2283 return 0;
2286 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2288 struct http_get_options options = {0};
2289 int ret = 0;
2290 char *url;
2291 const char *data;
2292 struct strbuf buf = STRBUF_INIT;
2293 struct object_id oid;
2295 end_url_with_slash(&buf, base_url);
2296 strbuf_addstr(&buf, "objects/info/packs");
2297 url = strbuf_detach(&buf, NULL);
2299 options.no_cache = 1;
2300 ret = http_get_strbuf(url, &buf, &options);
2301 if (ret != HTTP_OK)
2302 goto cleanup;
2304 data = buf.buf;
2305 while (*data) {
2306 if (skip_prefix(data, "P pack-", &data) &&
2307 !parse_oid_hex(data, &oid, &data) &&
2308 skip_prefix(data, ".pack", &data) &&
2309 (*data == '\n' || *data == '\0')) {
2310 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2311 } else {
2312 data = strchrnul(data, '\n');
2314 if (*data)
2315 data++; /* skip past newline */
2318 cleanup:
2319 free(url);
2320 return ret;
2323 void release_http_pack_request(struct http_pack_request *preq)
2325 if (preq->packfile) {
2326 fclose(preq->packfile);
2327 preq->packfile = NULL;
2329 preq->slot = NULL;
2330 strbuf_release(&preq->tmpfile);
2331 free(preq->url);
2332 free(preq);
2335 static const char *default_index_pack_args[] =
2336 {"index-pack", "--stdin", NULL};
2338 int finish_http_pack_request(struct http_pack_request *preq)
2340 struct child_process ip = CHILD_PROCESS_INIT;
2341 int tmpfile_fd;
2342 int ret = 0;
2344 fclose(preq->packfile);
2345 preq->packfile = NULL;
2347 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2349 ip.git_cmd = 1;
2350 ip.in = tmpfile_fd;
2351 strvec_pushv(&ip.args, preq->index_pack_args ?
2352 preq->index_pack_args :
2353 default_index_pack_args);
2355 if (preq->preserve_index_pack_stdout)
2356 ip.out = 0;
2357 else
2358 ip.no_stdout = 1;
2360 if (run_command(&ip)) {
2361 ret = -1;
2362 goto cleanup;
2365 cleanup:
2366 close(tmpfile_fd);
2367 unlink(preq->tmpfile.buf);
2368 return ret;
2371 void http_install_packfile(struct packed_git *p,
2372 struct packed_git **list_to_remove_from)
2374 struct packed_git **lst = list_to_remove_from;
2376 while (*lst != p)
2377 lst = &((*lst)->next);
2378 *lst = (*lst)->next;
2380 install_packed_git(the_repository, p);
2383 struct http_pack_request *new_http_pack_request(
2384 const unsigned char *packed_git_hash, const char *base_url) {
2386 struct strbuf buf = STRBUF_INIT;
2388 end_url_with_slash(&buf, base_url);
2389 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2390 hash_to_hex(packed_git_hash));
2391 return new_direct_http_pack_request(packed_git_hash,
2392 strbuf_detach(&buf, NULL));
2395 struct http_pack_request *new_direct_http_pack_request(
2396 const unsigned char *packed_git_hash, char *url)
2398 off_t prev_posn = 0;
2399 struct http_pack_request *preq;
2401 CALLOC_ARRAY(preq, 1);
2402 strbuf_init(&preq->tmpfile, 0);
2404 preq->url = url;
2406 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2407 preq->packfile = fopen(preq->tmpfile.buf, "a");
2408 if (!preq->packfile) {
2409 error("Unable to open local file %s for pack",
2410 preq->tmpfile.buf);
2411 goto abort;
2414 preq->slot = get_active_slot();
2415 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2416 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2417 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2418 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2419 no_pragma_header);
2422 * If there is data present from a previous transfer attempt,
2423 * resume where it left off
2425 prev_posn = ftello(preq->packfile);
2426 if (prev_posn>0) {
2427 if (http_is_verbose)
2428 fprintf(stderr,
2429 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2430 hash_to_hex(packed_git_hash),
2431 (uintmax_t)prev_posn);
2432 http_opt_request_remainder(preq->slot->curl, prev_posn);
2435 return preq;
2437 abort:
2438 strbuf_release(&preq->tmpfile);
2439 free(preq->url);
2440 free(preq);
2441 return NULL;
2444 /* Helpers for fetching objects (loose) */
2445 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2446 void *data)
2448 unsigned char expn[4096];
2449 size_t size = eltsize * nmemb;
2450 int posn = 0;
2451 struct http_object_request *freq = data;
2452 struct active_request_slot *slot = freq->slot;
2454 if (slot) {
2455 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2456 &slot->http_code);
2457 if (c != CURLE_OK)
2458 BUG("curl_easy_getinfo for HTTP code failed: %s",
2459 curl_easy_strerror(c));
2460 if (slot->http_code >= 300)
2461 return nmemb;
2464 do {
2465 ssize_t retval = xwrite(freq->localfile,
2466 (char *) ptr + posn, size - posn);
2467 if (retval < 0)
2468 return posn / eltsize;
2469 posn += retval;
2470 } while (posn < size);
2472 freq->stream.avail_in = size;
2473 freq->stream.next_in = (void *)ptr;
2474 do {
2475 freq->stream.next_out = expn;
2476 freq->stream.avail_out = sizeof(expn);
2477 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2478 the_hash_algo->update_fn(&freq->c, expn,
2479 sizeof(expn) - freq->stream.avail_out);
2480 } while (freq->stream.avail_in && freq->zret == Z_OK);
2481 return nmemb;
2484 struct http_object_request *new_http_object_request(const char *base_url,
2485 const struct object_id *oid)
2487 char *hex = oid_to_hex(oid);
2488 struct strbuf filename = STRBUF_INIT;
2489 struct strbuf prevfile = STRBUF_INIT;
2490 int prevlocal;
2491 char prev_buf[PREV_BUF_SIZE];
2492 ssize_t prev_read = 0;
2493 off_t prev_posn = 0;
2494 struct http_object_request *freq;
2496 CALLOC_ARRAY(freq, 1);
2497 strbuf_init(&freq->tmpfile, 0);
2498 oidcpy(&freq->oid, oid);
2499 freq->localfile = -1;
2501 loose_object_path(the_repository, &filename, oid);
2502 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2504 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2505 unlink_or_warn(prevfile.buf);
2506 rename(freq->tmpfile.buf, prevfile.buf);
2507 unlink_or_warn(freq->tmpfile.buf);
2508 strbuf_release(&filename);
2510 if (freq->localfile != -1)
2511 error("fd leakage in start: %d", freq->localfile);
2512 freq->localfile = open(freq->tmpfile.buf,
2513 O_WRONLY | O_CREAT | O_EXCL, 0666);
2515 * This could have failed due to the "lazy directory creation";
2516 * try to mkdir the last path component.
2518 if (freq->localfile < 0 && errno == ENOENT) {
2519 char *dir = strrchr(freq->tmpfile.buf, '/');
2520 if (dir) {
2521 *dir = 0;
2522 mkdir(freq->tmpfile.buf, 0777);
2523 *dir = '/';
2525 freq->localfile = open(freq->tmpfile.buf,
2526 O_WRONLY | O_CREAT | O_EXCL, 0666);
2529 if (freq->localfile < 0) {
2530 error_errno("Couldn't create temporary file %s",
2531 freq->tmpfile.buf);
2532 goto abort;
2535 git_inflate_init(&freq->stream);
2537 the_hash_algo->init_fn(&freq->c);
2539 freq->url = get_remote_object_url(base_url, hex, 0);
2542 * If a previous temp file is present, process what was already
2543 * fetched.
2545 prevlocal = open(prevfile.buf, O_RDONLY);
2546 if (prevlocal != -1) {
2547 do {
2548 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2549 if (prev_read>0) {
2550 if (fwrite_sha1_file(prev_buf,
2552 prev_read,
2553 freq) == prev_read) {
2554 prev_posn += prev_read;
2555 } else {
2556 prev_read = -1;
2559 } while (prev_read > 0);
2560 close(prevlocal);
2562 unlink_or_warn(prevfile.buf);
2563 strbuf_release(&prevfile);
2566 * Reset inflate/SHA1 if there was an error reading the previous temp
2567 * file; also rewind to the beginning of the local file.
2569 if (prev_read == -1) {
2570 memset(&freq->stream, 0, sizeof(freq->stream));
2571 git_inflate_init(&freq->stream);
2572 the_hash_algo->init_fn(&freq->c);
2573 if (prev_posn>0) {
2574 prev_posn = 0;
2575 lseek(freq->localfile, 0, SEEK_SET);
2576 if (ftruncate(freq->localfile, 0) < 0) {
2577 error_errno("Couldn't truncate temporary file %s",
2578 freq->tmpfile.buf);
2579 goto abort;
2584 freq->slot = get_active_slot();
2586 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2587 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2588 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2589 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2590 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2591 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2594 * If we have successfully processed data from a previous fetch
2595 * attempt, only fetch the data we don't already have.
2597 if (prev_posn>0) {
2598 if (http_is_verbose)
2599 fprintf(stderr,
2600 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2601 hex, (uintmax_t)prev_posn);
2602 http_opt_request_remainder(freq->slot->curl, prev_posn);
2605 return freq;
2607 abort:
2608 strbuf_release(&prevfile);
2609 free(freq->url);
2610 free(freq);
2611 return NULL;
2614 void process_http_object_request(struct http_object_request *freq)
2616 if (!freq->slot)
2617 return;
2618 freq->curl_result = freq->slot->curl_result;
2619 freq->http_code = freq->slot->http_code;
2620 freq->slot = NULL;
2623 int finish_http_object_request(struct http_object_request *freq)
2625 struct stat st;
2626 struct strbuf filename = STRBUF_INIT;
2628 close(freq->localfile);
2629 freq->localfile = -1;
2631 process_http_object_request(freq);
2633 if (freq->http_code == 416) {
2634 warning("requested range invalid; we may already have all the data.");
2635 } else if (freq->curl_result != CURLE_OK) {
2636 if (stat(freq->tmpfile.buf, &st) == 0)
2637 if (st.st_size == 0)
2638 unlink_or_warn(freq->tmpfile.buf);
2639 return -1;
2642 git_inflate_end(&freq->stream);
2643 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2644 if (freq->zret != Z_STREAM_END) {
2645 unlink_or_warn(freq->tmpfile.buf);
2646 return -1;
2648 if (!oideq(&freq->oid, &freq->real_oid)) {
2649 unlink_or_warn(freq->tmpfile.buf);
2650 return -1;
2652 loose_object_path(the_repository, &filename, &freq->oid);
2653 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2654 strbuf_release(&filename);
2656 return freq->rename;
2659 void abort_http_object_request(struct http_object_request *freq)
2661 unlink_or_warn(freq->tmpfile.buf);
2663 release_http_object_request(freq);
2666 void release_http_object_request(struct http_object_request *freq)
2668 if (freq->localfile != -1) {
2669 close(freq->localfile);
2670 freq->localfile = -1;
2672 FREE_AND_NULL(freq->url);
2673 if (freq->slot) {
2674 freq->slot->callback_func = NULL;
2675 freq->slot->callback_data = NULL;
2676 release_active_slot(freq->slot);
2677 freq->slot = NULL;
2679 strbuf_release(&freq->tmpfile);