treewide: be explicit about dependence on advice.h
[alt-git.git] / http.c
blob0212c0ad3b2b778eb28ed42c966d82d8e2a6a669
1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
3 #include "hex.h"
4 #include "http.h"
5 #include "config.h"
6 #include "pack.h"
7 #include "sideband.h"
8 #include "run-command.h"
9 #include "url.h"
10 #include "urlmatch.h"
11 #include "credential.h"
12 #include "version.h"
13 #include "pkt-line.h"
14 #include "gettext.h"
15 #include "trace.h"
16 #include "transport.h"
17 #include "packfile.h"
18 #include "protocol.h"
19 #include "string-list.h"
20 #include "object-store.h"
22 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
23 static int trace_curl_data = 1;
24 static int trace_curl_redact = 1;
25 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
26 int active_requests;
27 int http_is_verbose;
28 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
30 static int min_curl_sessions = 1;
31 static int curl_session_count;
32 static int max_requests = -1;
33 static CURLM *curlm;
34 static CURL *curl_default;
36 #define PREV_BUF_SIZE 4096
38 char curl_errorstr[CURL_ERROR_SIZE];
40 static int curl_ssl_verify = -1;
41 static int curl_ssl_try;
42 static const char *curl_http_version = NULL;
43 static const char *ssl_cert;
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_capath;
64 static const char *curl_no_proxy;
65 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
66 static const char *ssl_pinnedkey;
67 #endif
68 static const char *ssl_cainfo;
69 static long curl_low_speed_limit = -1;
70 static long curl_low_speed_time = -1;
71 static int curl_ftp_no_epsv;
72 static const char *curl_http_proxy;
73 static const char *http_proxy_authmethod;
75 static const char *http_proxy_ssl_cert;
76 static const char *http_proxy_ssl_key;
77 static const char *http_proxy_ssl_ca_info;
78 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
79 static int proxy_ssl_cert_password_required;
81 static struct {
82 const char *name;
83 long curlauth_param;
84 } proxy_authmethods[] = {
85 { "basic", CURLAUTH_BASIC },
86 { "digest", CURLAUTH_DIGEST },
87 { "negotiate", CURLAUTH_GSSNEGOTIATE },
88 { "ntlm", CURLAUTH_NTLM },
89 { "anyauth", CURLAUTH_ANY },
91 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
92 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
93 * here, too
96 #ifdef CURLGSSAPI_DELEGATION_FLAG
97 static const char *curl_deleg;
98 static struct {
99 const char *name;
100 long curl_deleg_param;
101 } curl_deleg_levels[] = {
102 { "none", CURLGSSAPI_DELEGATION_NONE },
103 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
104 { "always", CURLGSSAPI_DELEGATION_FLAG },
106 #endif
108 static struct credential proxy_auth = CREDENTIAL_INIT;
109 static const char *curl_proxyuserpwd;
110 static const char *curl_cookie_file;
111 static int curl_save_cookies;
112 struct credential http_auth = CREDENTIAL_INIT;
113 static int http_proactive_auth;
114 static const char *user_agent;
115 static int curl_empty_auth = -1;
117 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
119 static struct credential cert_auth = CREDENTIAL_INIT;
120 static int ssl_cert_password_required;
121 static unsigned long http_auth_methods = CURLAUTH_ANY;
122 static int http_auth_methods_restricted;
123 /* Modes for which empty_auth cannot actually help us. */
124 static unsigned long empty_auth_useless =
125 CURLAUTH_BASIC
126 | CURLAUTH_DIGEST_IE
127 | CURLAUTH_DIGEST;
129 static struct curl_slist *pragma_header;
130 static struct curl_slist *no_pragma_header;
131 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
133 static struct curl_slist *host_resolutions;
135 static struct active_request_slot *active_queue_head;
137 static char *cached_accept_language;
139 static char *http_ssl_backend;
141 static int http_schannel_check_revoke = 1;
143 * With the backend being set to `schannel`, setting sslCAinfo would override
144 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
145 * by default.
147 static int http_schannel_use_ssl_cainfo;
149 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
151 size_t size = eltsize * nmemb;
152 struct buffer *buffer = buffer_;
154 if (size > buffer->buf.len - buffer->posn)
155 size = buffer->buf.len - buffer->posn;
156 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
157 buffer->posn += size;
159 return size / eltsize;
162 int seek_buffer(void *clientp, curl_off_t offset, int origin)
164 struct buffer *buffer = clientp;
166 if (origin != SEEK_SET)
167 BUG("seek_buffer only handles SEEK_SET");
168 if (offset < 0 || offset >= buffer->buf.len) {
169 error("curl seek would be outside of buffer");
170 return CURL_SEEKFUNC_FAIL;
173 buffer->posn = offset;
174 return CURL_SEEKFUNC_OK;
177 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
179 size_t size = eltsize * nmemb;
180 struct strbuf *buffer = buffer_;
182 strbuf_add(buffer, ptr, size);
183 return nmemb;
187 * A folded header continuation line starts with any number of spaces or
188 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
189 * It is not a continuation line if the line starts with any other character.
191 static inline int is_hdr_continuation(const char *ptr, const size_t size)
193 return size && (*ptr == ' ' || *ptr == '\t');
196 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p)
198 size_t size = eltsize * nmemb;
199 struct strvec *values = &http_auth.wwwauth_headers;
200 struct strbuf buf = STRBUF_INIT;
201 const char *val;
202 size_t val_len;
205 * Header lines may not come NULL-terminated from libcurl so we must
206 * limit all scans to the maximum length of the header line, or leverage
207 * strbufs for all operations.
209 * In addition, it is possible that header values can be split over
210 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
211 * but older servers may still emit them. A continuation header field
212 * value is identified as starting with a space or horizontal tab.
214 * The formal definition of a header field as given in RFC 7230 is:
216 * header-field = field-name ":" OWS field-value OWS
218 * field-name = token
219 * field-value = *( field-content / obs-fold )
220 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
221 * field-vchar = VCHAR / obs-text
223 * obs-fold = CRLF 1*( SP / HTAB )
224 * ; obsolete line folding
225 * ; see Section 3.2.4
228 /* Start of a new WWW-Authenticate header */
229 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
230 strbuf_add(&buf, val, val_len);
233 * Strip the CRLF that should be present at the end of each
234 * field as well as any trailing or leading whitespace from the
235 * value.
237 strbuf_trim(&buf);
239 strvec_push(values, buf.buf);
240 http_auth.header_is_last_match = 1;
241 goto exit;
245 * This line could be a continuation of the previously matched header
246 * field. If this is the case then we should append this value to the
247 * end of the previously consumed value.
249 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
251 * Trim the CRLF and any leading or trailing from this line.
253 strbuf_add(&buf, ptr, size);
254 strbuf_trim(&buf);
257 * At this point we should always have at least one existing
258 * value, even if it is empty. Do not bother appending the new
259 * value if this continuation header is itself empty.
261 if (!values->nr) {
262 BUG("should have at least one existing header value");
263 } else if (buf.len) {
264 char *prev = xstrdup(values->v[values->nr - 1]);
266 /* Join two non-empty values with a single space. */
267 const char *const sp = *prev ? " " : "";
269 strvec_pop(values);
270 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
271 free(prev);
274 goto exit;
277 /* Not a continuation of a previously matched auth header line. */
278 http_auth.header_is_last_match = 0;
281 * If this is a HTTP status line and not a header field, this signals
282 * a different HTTP response. libcurl writes all the output of all
283 * response headers of all responses, including redirects.
284 * We only care about the last HTTP request response's headers so clear
285 * the existing array.
287 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
288 strvec_clear(values);
290 exit:
291 strbuf_release(&buf);
292 return size;
295 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
297 return nmemb;
300 static void closedown_active_slot(struct active_request_slot *slot)
302 active_requests--;
303 slot->in_use = 0;
306 static void finish_active_slot(struct active_request_slot *slot)
308 closedown_active_slot(slot);
309 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
311 if (slot->finished)
312 (*slot->finished) = 1;
314 /* Store slot results so they can be read after the slot is reused */
315 if (slot->results) {
316 slot->results->curl_result = slot->curl_result;
317 slot->results->http_code = slot->http_code;
318 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
319 &slot->results->auth_avail);
321 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
322 &slot->results->http_connectcode);
325 /* Run callback if appropriate */
326 if (slot->callback_func)
327 slot->callback_func(slot->callback_data);
330 static void xmulti_remove_handle(struct active_request_slot *slot)
332 curl_multi_remove_handle(curlm, slot->curl);
335 static void process_curl_messages(void)
337 int num_messages;
338 struct active_request_slot *slot;
339 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
341 while (curl_message != NULL) {
342 if (curl_message->msg == CURLMSG_DONE) {
343 int curl_result = curl_message->data.result;
344 slot = active_queue_head;
345 while (slot != NULL &&
346 slot->curl != curl_message->easy_handle)
347 slot = slot->next;
348 if (slot) {
349 xmulti_remove_handle(slot);
350 slot->curl_result = curl_result;
351 finish_active_slot(slot);
352 } else {
353 fprintf(stderr, "Received DONE message for unknown request!\n");
355 } else {
356 fprintf(stderr, "Unknown CURL message received: %d\n",
357 (int)curl_message->msg);
359 curl_message = curl_multi_info_read(curlm, &num_messages);
363 static int http_options(const char *var, const char *value, void *cb)
365 if (!strcmp("http.version", var)) {
366 return git_config_string(&curl_http_version, var, value);
368 if (!strcmp("http.sslverify", var)) {
369 curl_ssl_verify = git_config_bool(var, value);
370 return 0;
372 if (!strcmp("http.sslcipherlist", var))
373 return git_config_string(&ssl_cipherlist, var, value);
374 if (!strcmp("http.sslversion", var))
375 return git_config_string(&ssl_version, var, value);
376 if (!strcmp("http.sslcert", var))
377 return git_config_pathname(&ssl_cert, var, value);
378 if (!strcmp("http.sslkey", var))
379 return git_config_pathname(&ssl_key, var, value);
380 if (!strcmp("http.sslcapath", var))
381 return git_config_pathname(&ssl_capath, var, value);
382 if (!strcmp("http.sslcainfo", var))
383 return git_config_pathname(&ssl_cainfo, var, value);
384 if (!strcmp("http.sslcertpasswordprotected", var)) {
385 ssl_cert_password_required = git_config_bool(var, value);
386 return 0;
388 if (!strcmp("http.ssltry", var)) {
389 curl_ssl_try = git_config_bool(var, value);
390 return 0;
392 if (!strcmp("http.sslbackend", var)) {
393 free(http_ssl_backend);
394 http_ssl_backend = xstrdup_or_null(value);
395 return 0;
398 if (!strcmp("http.schannelcheckrevoke", var)) {
399 http_schannel_check_revoke = git_config_bool(var, value);
400 return 0;
403 if (!strcmp("http.schannelusesslcainfo", var)) {
404 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
405 return 0;
408 if (!strcmp("http.minsessions", var)) {
409 min_curl_sessions = git_config_int(var, value);
410 if (min_curl_sessions > 1)
411 min_curl_sessions = 1;
412 return 0;
414 if (!strcmp("http.maxrequests", var)) {
415 max_requests = git_config_int(var, value);
416 return 0;
418 if (!strcmp("http.lowspeedlimit", var)) {
419 curl_low_speed_limit = (long)git_config_int(var, value);
420 return 0;
422 if (!strcmp("http.lowspeedtime", var)) {
423 curl_low_speed_time = (long)git_config_int(var, value);
424 return 0;
427 if (!strcmp("http.noepsv", var)) {
428 curl_ftp_no_epsv = git_config_bool(var, value);
429 return 0;
431 if (!strcmp("http.proxy", var))
432 return git_config_string(&curl_http_proxy, var, value);
434 if (!strcmp("http.proxyauthmethod", var))
435 return git_config_string(&http_proxy_authmethod, var, value);
437 if (!strcmp("http.proxysslcert", var))
438 return git_config_string(&http_proxy_ssl_cert, var, value);
440 if (!strcmp("http.proxysslkey", var))
441 return git_config_string(&http_proxy_ssl_key, var, value);
443 if (!strcmp("http.proxysslcainfo", var))
444 return git_config_string(&http_proxy_ssl_ca_info, var, value);
446 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
447 proxy_ssl_cert_password_required = git_config_bool(var, value);
448 return 0;
451 if (!strcmp("http.cookiefile", var))
452 return git_config_pathname(&curl_cookie_file, var, value);
453 if (!strcmp("http.savecookies", var)) {
454 curl_save_cookies = git_config_bool(var, value);
455 return 0;
458 if (!strcmp("http.postbuffer", var)) {
459 http_post_buffer = git_config_ssize_t(var, value);
460 if (http_post_buffer < 0)
461 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
462 if (http_post_buffer < LARGE_PACKET_MAX)
463 http_post_buffer = LARGE_PACKET_MAX;
464 return 0;
467 if (!strcmp("http.useragent", var))
468 return git_config_string(&user_agent, var, value);
470 if (!strcmp("http.emptyauth", var)) {
471 if (value && !strcmp("auto", value))
472 curl_empty_auth = -1;
473 else
474 curl_empty_auth = git_config_bool(var, value);
475 return 0;
478 if (!strcmp("http.delegation", var)) {
479 #ifdef CURLGSSAPI_DELEGATION_FLAG
480 return git_config_string(&curl_deleg, var, value);
481 #else
482 warning(_("Delegation control is not supported with cURL < 7.22.0"));
483 return 0;
484 #endif
487 if (!strcmp("http.pinnedpubkey", var)) {
488 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
489 return git_config_pathname(&ssl_pinnedkey, var, value);
490 #else
491 warning(_("Public key pinning not supported with cURL < 7.39.0"));
492 return 0;
493 #endif
496 if (!strcmp("http.extraheader", var)) {
497 if (!value) {
498 return config_error_nonbool(var);
499 } else if (!*value) {
500 string_list_clear(&extra_http_headers, 0);
501 } else {
502 string_list_append(&extra_http_headers, value);
504 return 0;
507 if (!strcmp("http.curloptresolve", var)) {
508 if (!value) {
509 return config_error_nonbool(var);
510 } else if (!*value) {
511 curl_slist_free_all(host_resolutions);
512 host_resolutions = NULL;
513 } else {
514 host_resolutions = curl_slist_append(host_resolutions, value);
516 return 0;
519 if (!strcmp("http.followredirects", var)) {
520 if (value && !strcmp(value, "initial"))
521 http_follow_config = HTTP_FOLLOW_INITIAL;
522 else if (git_config_bool(var, value))
523 http_follow_config = HTTP_FOLLOW_ALWAYS;
524 else
525 http_follow_config = HTTP_FOLLOW_NONE;
526 return 0;
529 /* Fall back on the default ones */
530 return git_default_config(var, value, cb);
533 static int curl_empty_auth_enabled(void)
535 if (curl_empty_auth >= 0)
536 return curl_empty_auth;
539 * In the automatic case, kick in the empty-auth
540 * hack as long as we would potentially try some
541 * method more exotic than "Basic" or "Digest".
543 * But only do this when this is our second or
544 * subsequent request, as by then we know what
545 * methods are available.
547 if (http_auth_methods_restricted &&
548 (http_auth_methods & ~empty_auth_useless))
549 return 1;
550 return 0;
553 static void init_curl_http_auth(CURL *result)
555 if (!http_auth.username || !*http_auth.username) {
556 if (curl_empty_auth_enabled())
557 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
558 return;
561 credential_fill(&http_auth);
563 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
564 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
567 /* *var must be free-able */
568 static void var_override(const char **var, char *value)
570 if (value) {
571 free((void *)*var);
572 *var = xstrdup(value);
576 static void set_proxyauth_name_password(CURL *result)
578 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
579 proxy_auth.username);
580 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
581 proxy_auth.password);
584 static void init_curl_proxy_auth(CURL *result)
586 if (proxy_auth.username) {
587 if (!proxy_auth.password)
588 credential_fill(&proxy_auth);
589 set_proxyauth_name_password(result);
592 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
594 if (http_proxy_authmethod) {
595 int i;
596 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
597 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
598 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
599 proxy_authmethods[i].curlauth_param);
600 break;
603 if (i == ARRAY_SIZE(proxy_authmethods)) {
604 warning("unsupported proxy authentication method %s: using anyauth",
605 http_proxy_authmethod);
606 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
609 else
610 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
613 static int has_cert_password(void)
615 if (ssl_cert == NULL || ssl_cert_password_required != 1)
616 return 0;
617 if (!cert_auth.password) {
618 cert_auth.protocol = xstrdup("cert");
619 cert_auth.host = xstrdup("");
620 cert_auth.username = xstrdup("");
621 cert_auth.path = xstrdup(ssl_cert);
622 credential_fill(&cert_auth);
624 return 1;
627 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
628 static int has_proxy_cert_password(void)
630 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
631 return 0;
632 if (!proxy_cert_auth.password) {
633 proxy_cert_auth.protocol = xstrdup("cert");
634 proxy_cert_auth.host = xstrdup("");
635 proxy_cert_auth.username = xstrdup("");
636 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
637 credential_fill(&proxy_cert_auth);
639 return 1;
641 #endif
643 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
644 static void set_curl_keepalive(CURL *c)
646 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
649 #else
650 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
652 int ka = 1;
653 int rc;
654 socklen_t len = (socklen_t)sizeof(ka);
656 if (type != CURLSOCKTYPE_IPCXN)
657 return 0;
659 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
660 if (rc < 0)
661 warning_errno("unable to set SO_KEEPALIVE on socket");
663 return CURL_SOCKOPT_OK;
666 static void set_curl_keepalive(CURL *c)
668 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
670 #endif
672 /* Return 1 if redactions have been made, 0 otherwise. */
673 static int redact_sensitive_header(struct strbuf *header, size_t offset)
675 int ret = 0;
676 const char *sensitive_header;
678 if (trace_curl_redact &&
679 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
680 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
681 /* The first token is the type, which is OK to log */
682 while (isspace(*sensitive_header))
683 sensitive_header++;
684 while (*sensitive_header && !isspace(*sensitive_header))
685 sensitive_header++;
686 /* Everything else is opaque and possibly sensitive */
687 strbuf_setlen(header, sensitive_header - header->buf);
688 strbuf_addstr(header, " <redacted>");
689 ret = 1;
690 } else if (trace_curl_redact &&
691 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
692 struct strbuf redacted_header = STRBUF_INIT;
693 const char *cookie;
695 while (isspace(*sensitive_header))
696 sensitive_header++;
698 cookie = sensitive_header;
700 while (cookie) {
701 char *equals;
702 char *semicolon = strstr(cookie, "; ");
703 if (semicolon)
704 *semicolon = 0;
705 equals = strchrnul(cookie, '=');
706 if (!equals) {
707 /* invalid cookie, just append and continue */
708 strbuf_addstr(&redacted_header, cookie);
709 continue;
711 strbuf_add(&redacted_header, cookie, equals - cookie);
712 strbuf_addstr(&redacted_header, "=<redacted>");
713 if (semicolon) {
715 * There are more cookies. (Or, for some
716 * reason, the input string ends in "; ".)
718 strbuf_addstr(&redacted_header, "; ");
719 cookie = semicolon + strlen("; ");
720 } else {
721 cookie = NULL;
725 strbuf_setlen(header, sensitive_header - header->buf);
726 strbuf_addbuf(header, &redacted_header);
727 ret = 1;
729 return ret;
732 /* Redact headers in info */
733 static void redact_sensitive_info_header(struct strbuf *header)
735 const char *sensitive_header;
738 * curl's h2h3 prints headers in info, e.g.:
739 * h2h3 [<header-name>: <header-val>]
741 if (trace_curl_redact &&
742 skip_iprefix(header->buf, "h2h3 [", &sensitive_header)) {
743 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
744 /* redaction ate our closing bracket */
745 strbuf_addch(header, ']');
750 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
752 struct strbuf out = STRBUF_INIT;
753 struct strbuf **headers, **header;
755 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
756 text, (long)size, (long)size);
757 trace_strbuf(&trace_curl, &out);
758 strbuf_reset(&out);
759 strbuf_add(&out, ptr, size);
760 headers = strbuf_split_max(&out, '\n', 0);
762 for (header = headers; *header; header++) {
763 if (hide_sensitive_header)
764 redact_sensitive_header(*header, 0);
765 strbuf_insertstr((*header), 0, text);
766 strbuf_insertstr((*header), strlen(text), ": ");
767 strbuf_rtrim((*header));
768 strbuf_addch((*header), '\n');
769 trace_strbuf(&trace_curl, (*header));
771 strbuf_list_free(headers);
772 strbuf_release(&out);
775 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
777 size_t i;
778 struct strbuf out = STRBUF_INIT;
779 unsigned int width = 60;
781 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
782 text, (long)size, (long)size);
783 trace_strbuf(&trace_curl, &out);
785 for (i = 0; i < size; i += width) {
786 size_t w;
788 strbuf_reset(&out);
789 strbuf_addf(&out, "%s: ", text);
790 for (w = 0; (w < width) && (i + w < size); w++) {
791 unsigned char ch = ptr[i + w];
793 strbuf_addch(&out,
794 (ch >= 0x20) && (ch < 0x80)
795 ? ch : '.');
797 strbuf_addch(&out, '\n');
798 trace_strbuf(&trace_curl, &out);
800 strbuf_release(&out);
803 static void curl_dump_info(char *data, size_t size)
805 struct strbuf buf = STRBUF_INIT;
807 strbuf_add(&buf, data, size);
809 redact_sensitive_info_header(&buf);
810 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
812 strbuf_release(&buf);
815 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
817 const char *text;
818 enum { NO_FILTER = 0, DO_FILTER = 1 };
820 switch (type) {
821 case CURLINFO_TEXT:
822 curl_dump_info(data, size);
823 break;
824 case CURLINFO_HEADER_OUT:
825 text = "=> Send header";
826 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
827 break;
828 case CURLINFO_DATA_OUT:
829 if (trace_curl_data) {
830 text = "=> Send data";
831 curl_dump_data(text, (unsigned char *)data, size);
833 break;
834 case CURLINFO_SSL_DATA_OUT:
835 if (trace_curl_data) {
836 text = "=> Send SSL data";
837 curl_dump_data(text, (unsigned char *)data, size);
839 break;
840 case CURLINFO_HEADER_IN:
841 text = "<= Recv header";
842 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
843 break;
844 case CURLINFO_DATA_IN:
845 if (trace_curl_data) {
846 text = "<= Recv data";
847 curl_dump_data(text, (unsigned char *)data, size);
849 break;
850 case CURLINFO_SSL_DATA_IN:
851 if (trace_curl_data) {
852 text = "<= Recv SSL data";
853 curl_dump_data(text, (unsigned char *)data, size);
855 break;
857 default: /* we ignore unknown types by default */
858 return 0;
860 return 0;
863 void http_trace_curl_no_data(void)
865 trace_override_envvar(&trace_curl, "1");
866 trace_curl_data = 0;
869 void setup_curl_trace(CURL *handle)
871 if (!trace_want(&trace_curl))
872 return;
873 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
874 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
875 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
878 static void proto_list_append(struct strbuf *list, const char *proto)
880 if (!list)
881 return;
882 if (list->len)
883 strbuf_addch(list, ',');
884 strbuf_addstr(list, proto);
887 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
889 long bits = 0;
891 if (is_transport_allowed("http", from_user)) {
892 bits |= CURLPROTO_HTTP;
893 proto_list_append(list, "http");
895 if (is_transport_allowed("https", from_user)) {
896 bits |= CURLPROTO_HTTPS;
897 proto_list_append(list, "https");
899 if (is_transport_allowed("ftp", from_user)) {
900 bits |= CURLPROTO_FTP;
901 proto_list_append(list, "ftp");
903 if (is_transport_allowed("ftps", from_user)) {
904 bits |= CURLPROTO_FTPS;
905 proto_list_append(list, "ftps");
908 return bits;
911 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
912 static int get_curl_http_version_opt(const char *version_string, long *opt)
914 int i;
915 static struct {
916 const char *name;
917 long opt_token;
918 } choice[] = {
919 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
920 { "HTTP/2", CURL_HTTP_VERSION_2 }
923 for (i = 0; i < ARRAY_SIZE(choice); i++) {
924 if (!strcmp(version_string, choice[i].name)) {
925 *opt = choice[i].opt_token;
926 return 0;
930 warning("unknown value given to http.version: '%s'", version_string);
931 return -1; /* not found */
934 #endif
936 static CURL *get_curl_handle(void)
938 CURL *result = curl_easy_init();
940 if (!result)
941 die("curl_easy_init failed");
943 if (!curl_ssl_verify) {
944 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
945 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
946 } else {
947 /* Verify authenticity of the peer's certificate */
948 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
949 /* The name in the cert must match whom we tried to connect */
950 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
953 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
954 if (curl_http_version) {
955 long opt;
956 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
957 /* Set request use http version */
958 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
961 #endif
963 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
964 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
966 #ifdef CURLGSSAPI_DELEGATION_FLAG
967 if (curl_deleg) {
968 int i;
969 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
970 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
971 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
972 curl_deleg_levels[i].curl_deleg_param);
973 break;
976 if (i == ARRAY_SIZE(curl_deleg_levels))
977 warning("Unknown delegation method '%s': using default",
978 curl_deleg);
980 #endif
982 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
983 !http_schannel_check_revoke) {
984 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
985 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
986 #else
987 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
988 #endif
991 if (http_proactive_auth)
992 init_curl_http_auth(result);
994 if (getenv("GIT_SSL_VERSION"))
995 ssl_version = getenv("GIT_SSL_VERSION");
996 if (ssl_version && *ssl_version) {
997 int i;
998 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
999 if (!strcmp(ssl_version, sslversions[i].name)) {
1000 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1001 sslversions[i].ssl_version);
1002 break;
1005 if (i == ARRAY_SIZE(sslversions))
1006 warning("unsupported ssl version %s: using default",
1007 ssl_version);
1010 if (getenv("GIT_SSL_CIPHER_LIST"))
1011 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1012 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1013 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1014 ssl_cipherlist);
1016 if (ssl_cert)
1017 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1018 if (has_cert_password())
1019 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1020 if (ssl_key)
1021 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1022 if (ssl_capath)
1023 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1024 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1025 if (ssl_pinnedkey)
1026 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1027 #endif
1028 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1029 !http_schannel_use_ssl_cainfo) {
1030 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1031 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1032 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1033 #endif
1034 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1035 if (ssl_cainfo)
1036 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1037 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1038 if (http_proxy_ssl_ca_info)
1039 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1040 #endif
1043 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1044 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1045 curl_low_speed_limit);
1046 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1047 curl_low_speed_time);
1050 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1051 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1053 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1055 struct strbuf buf = STRBUF_INIT;
1057 get_curl_allowed_protocols(0, &buf);
1058 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1059 strbuf_reset(&buf);
1061 get_curl_allowed_protocols(-1, &buf);
1062 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1063 strbuf_release(&buf);
1065 #else
1066 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1067 get_curl_allowed_protocols(0, NULL));
1068 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1069 get_curl_allowed_protocols(-1, NULL));
1070 #endif
1072 if (getenv("GIT_CURL_VERBOSE"))
1073 http_trace_curl_no_data();
1074 setup_curl_trace(result);
1075 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1076 trace_curl_data = 0;
1077 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1078 trace_curl_redact = 0;
1080 curl_easy_setopt(result, CURLOPT_USERAGENT,
1081 user_agent ? user_agent : git_user_agent());
1083 if (curl_ftp_no_epsv)
1084 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1086 if (curl_ssl_try)
1087 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1090 * CURL also examines these variables as a fallback; but we need to query
1091 * them here in order to decide whether to prompt for missing password (cf.
1092 * init_curl_proxy_auth()).
1094 * Unlike many other common environment variables, these are historically
1095 * lowercase only. It appears that CURL did not know this and implemented
1096 * only uppercase variants, which was later corrected to take both - with
1097 * the exception of http_proxy, which is lowercase only also in CURL. As
1098 * the lowercase versions are the historical quasi-standard, they take
1099 * precedence here, as in CURL.
1101 if (!curl_http_proxy) {
1102 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1103 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1104 var_override(&curl_http_proxy, getenv("https_proxy"));
1105 } else {
1106 var_override(&curl_http_proxy, getenv("http_proxy"));
1108 if (!curl_http_proxy) {
1109 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1110 var_override(&curl_http_proxy, getenv("all_proxy"));
1114 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1116 * Handle case with the empty http.proxy value here to keep
1117 * common code clean.
1118 * NB: empty option disables proxying at all.
1120 curl_easy_setopt(result, CURLOPT_PROXY, "");
1121 } else if (curl_http_proxy) {
1122 if (starts_with(curl_http_proxy, "socks5h"))
1123 curl_easy_setopt(result,
1124 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1125 else if (starts_with(curl_http_proxy, "socks5"))
1126 curl_easy_setopt(result,
1127 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1128 else if (starts_with(curl_http_proxy, "socks4a"))
1129 curl_easy_setopt(result,
1130 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1131 else if (starts_with(curl_http_proxy, "socks"))
1132 curl_easy_setopt(result,
1133 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1134 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1135 else if (starts_with(curl_http_proxy, "https")) {
1136 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1138 if (http_proxy_ssl_cert)
1139 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1141 if (http_proxy_ssl_key)
1142 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1144 if (has_proxy_cert_password())
1145 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1147 #endif
1148 if (strstr(curl_http_proxy, "://"))
1149 credential_from_url(&proxy_auth, curl_http_proxy);
1150 else {
1151 struct strbuf url = STRBUF_INIT;
1152 strbuf_addf(&url, "http://%s", curl_http_proxy);
1153 credential_from_url(&proxy_auth, url.buf);
1154 strbuf_release(&url);
1157 if (!proxy_auth.host)
1158 die("Invalid proxy URL '%s'", curl_http_proxy);
1160 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1161 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1162 var_override(&curl_no_proxy, getenv("no_proxy"));
1163 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1165 init_curl_proxy_auth(result);
1167 set_curl_keepalive(result);
1169 return result;
1172 static void set_from_env(const char **var, const char *envname)
1174 const char *val = getenv(envname);
1175 if (val)
1176 *var = val;
1179 void http_init(struct remote *remote, const char *url, int proactive_auth)
1181 char *low_speed_limit;
1182 char *low_speed_time;
1183 char *normalized_url;
1184 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1186 config.section = "http";
1187 config.key = NULL;
1188 config.collect_fn = http_options;
1189 config.cascade_fn = git_default_config;
1190 config.cb = NULL;
1192 http_is_verbose = 0;
1193 normalized_url = url_normalize(url, &config.url);
1195 git_config(urlmatch_config_entry, &config);
1196 free(normalized_url);
1197 string_list_clear(&config.vars, 1);
1199 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1200 if (http_ssl_backend) {
1201 const curl_ssl_backend **backends;
1202 struct strbuf buf = STRBUF_INIT;
1203 int i;
1205 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1206 case CURLSSLSET_UNKNOWN_BACKEND:
1207 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1208 "Supported SSL backends:"),
1209 http_ssl_backend);
1210 for (i = 0; backends[i]; i++)
1211 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1212 die("%s", buf.buf);
1213 case CURLSSLSET_NO_BACKENDS:
1214 die(_("Could not set SSL backend to '%s': "
1215 "cURL was built without SSL backends"),
1216 http_ssl_backend);
1217 case CURLSSLSET_TOO_LATE:
1218 die(_("Could not set SSL backend to '%s': already set"),
1219 http_ssl_backend);
1220 case CURLSSLSET_OK:
1221 break; /* Okay! */
1224 #endif
1226 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1227 die("curl_global_init failed");
1229 http_proactive_auth = proactive_auth;
1231 if (remote && remote->http_proxy)
1232 curl_http_proxy = xstrdup(remote->http_proxy);
1234 if (remote)
1235 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1237 pragma_header = curl_slist_append(http_copy_default_headers(),
1238 "Pragma: no-cache");
1239 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1240 "Pragma:");
1243 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1244 if (http_max_requests)
1245 max_requests = atoi(http_max_requests);
1248 curlm = curl_multi_init();
1249 if (!curlm)
1250 die("curl_multi_init failed");
1252 if (getenv("GIT_SSL_NO_VERIFY"))
1253 curl_ssl_verify = 0;
1255 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1256 set_from_env(&ssl_key, "GIT_SSL_KEY");
1257 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1258 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1260 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1262 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1263 if (low_speed_limit)
1264 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1265 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1266 if (low_speed_time)
1267 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1269 if (curl_ssl_verify == -1)
1270 curl_ssl_verify = 1;
1272 curl_session_count = 0;
1273 if (max_requests < 1)
1274 max_requests = DEFAULT_MAX_REQUESTS;
1276 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1277 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1278 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1280 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1281 proxy_ssl_cert_password_required = 1;
1283 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1284 curl_ftp_no_epsv = 1;
1286 if (url) {
1287 credential_from_url(&http_auth, url);
1288 if (!ssl_cert_password_required &&
1289 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1290 starts_with(url, "https://"))
1291 ssl_cert_password_required = 1;
1294 curl_default = get_curl_handle();
1297 void http_cleanup(void)
1299 struct active_request_slot *slot = active_queue_head;
1301 while (slot != NULL) {
1302 struct active_request_slot *next = slot->next;
1303 if (slot->curl) {
1304 xmulti_remove_handle(slot);
1305 curl_easy_cleanup(slot->curl);
1307 free(slot);
1308 slot = next;
1310 active_queue_head = NULL;
1312 curl_easy_cleanup(curl_default);
1314 curl_multi_cleanup(curlm);
1315 curl_global_cleanup();
1317 string_list_clear(&extra_http_headers, 0);
1319 curl_slist_free_all(pragma_header);
1320 pragma_header = NULL;
1322 curl_slist_free_all(no_pragma_header);
1323 no_pragma_header = NULL;
1325 curl_slist_free_all(host_resolutions);
1326 host_resolutions = NULL;
1328 if (curl_http_proxy) {
1329 free((void *)curl_http_proxy);
1330 curl_http_proxy = NULL;
1333 if (proxy_auth.password) {
1334 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1335 FREE_AND_NULL(proxy_auth.password);
1338 free((void *)curl_proxyuserpwd);
1339 curl_proxyuserpwd = NULL;
1341 free((void *)http_proxy_authmethod);
1342 http_proxy_authmethod = NULL;
1344 if (cert_auth.password) {
1345 memset(cert_auth.password, 0, strlen(cert_auth.password));
1346 FREE_AND_NULL(cert_auth.password);
1348 ssl_cert_password_required = 0;
1350 if (proxy_cert_auth.password) {
1351 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1352 FREE_AND_NULL(proxy_cert_auth.password);
1354 proxy_ssl_cert_password_required = 0;
1356 FREE_AND_NULL(cached_accept_language);
1359 struct active_request_slot *get_active_slot(void)
1361 struct active_request_slot *slot = active_queue_head;
1362 struct active_request_slot *newslot;
1364 int num_transfers;
1366 /* Wait for a slot to open up if the queue is full */
1367 while (active_requests >= max_requests) {
1368 curl_multi_perform(curlm, &num_transfers);
1369 if (num_transfers < active_requests)
1370 process_curl_messages();
1373 while (slot != NULL && slot->in_use)
1374 slot = slot->next;
1376 if (!slot) {
1377 newslot = xmalloc(sizeof(*newslot));
1378 newslot->curl = NULL;
1379 newslot->in_use = 0;
1380 newslot->next = NULL;
1382 slot = active_queue_head;
1383 if (!slot) {
1384 active_queue_head = newslot;
1385 } else {
1386 while (slot->next != NULL)
1387 slot = slot->next;
1388 slot->next = newslot;
1390 slot = newslot;
1393 if (!slot->curl) {
1394 slot->curl = curl_easy_duphandle(curl_default);
1395 curl_session_count++;
1398 active_requests++;
1399 slot->in_use = 1;
1400 slot->results = NULL;
1401 slot->finished = NULL;
1402 slot->callback_data = NULL;
1403 slot->callback_func = NULL;
1404 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1405 if (curl_save_cookies)
1406 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1407 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1408 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1409 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1410 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1411 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1412 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1413 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1414 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1415 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1416 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1417 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1420 * Default following to off unless "ALWAYS" is configured; this gives
1421 * callers a sane starting point, and they can tweak for individual
1422 * HTTP_FOLLOW_* cases themselves.
1424 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1425 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1426 else
1427 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1429 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1430 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1431 if (http_auth.password || curl_empty_auth_enabled())
1432 init_curl_http_auth(slot->curl);
1434 return slot;
1437 int start_active_slot(struct active_request_slot *slot)
1439 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1440 int num_transfers;
1442 if (curlm_result != CURLM_OK &&
1443 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1444 warning("curl_multi_add_handle failed: %s",
1445 curl_multi_strerror(curlm_result));
1446 active_requests--;
1447 slot->in_use = 0;
1448 return 0;
1452 * We know there must be something to do, since we just added
1453 * something.
1455 curl_multi_perform(curlm, &num_transfers);
1456 return 1;
1459 struct fill_chain {
1460 void *data;
1461 int (*fill)(void *);
1462 struct fill_chain *next;
1465 static struct fill_chain *fill_cfg;
1467 void add_fill_function(void *data, int (*fill)(void *))
1469 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1470 struct fill_chain **linkp = &fill_cfg;
1471 new_fill->data = data;
1472 new_fill->fill = fill;
1473 new_fill->next = NULL;
1474 while (*linkp)
1475 linkp = &(*linkp)->next;
1476 *linkp = new_fill;
1479 void fill_active_slots(void)
1481 struct active_request_slot *slot = active_queue_head;
1483 while (active_requests < max_requests) {
1484 struct fill_chain *fill;
1485 for (fill = fill_cfg; fill; fill = fill->next)
1486 if (fill->fill(fill->data))
1487 break;
1489 if (!fill)
1490 break;
1493 while (slot != NULL) {
1494 if (!slot->in_use && slot->curl != NULL
1495 && curl_session_count > min_curl_sessions) {
1496 curl_easy_cleanup(slot->curl);
1497 slot->curl = NULL;
1498 curl_session_count--;
1500 slot = slot->next;
1504 void step_active_slots(void)
1506 int num_transfers;
1507 CURLMcode curlm_result;
1509 do {
1510 curlm_result = curl_multi_perform(curlm, &num_transfers);
1511 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1512 if (num_transfers < active_requests) {
1513 process_curl_messages();
1514 fill_active_slots();
1518 void run_active_slot(struct active_request_slot *slot)
1520 fd_set readfds;
1521 fd_set writefds;
1522 fd_set excfds;
1523 int max_fd;
1524 struct timeval select_timeout;
1525 int finished = 0;
1527 slot->finished = &finished;
1528 while (!finished) {
1529 step_active_slots();
1531 if (slot->in_use) {
1532 long curl_timeout;
1533 curl_multi_timeout(curlm, &curl_timeout);
1534 if (curl_timeout == 0) {
1535 continue;
1536 } else if (curl_timeout == -1) {
1537 select_timeout.tv_sec = 0;
1538 select_timeout.tv_usec = 50000;
1539 } else {
1540 select_timeout.tv_sec = curl_timeout / 1000;
1541 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1544 max_fd = -1;
1545 FD_ZERO(&readfds);
1546 FD_ZERO(&writefds);
1547 FD_ZERO(&excfds);
1548 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1551 * It can happen that curl_multi_timeout returns a pathologically
1552 * long timeout when curl_multi_fdset returns no file descriptors
1553 * to read. See commit message for more details.
1555 if (max_fd < 0 &&
1556 (select_timeout.tv_sec > 0 ||
1557 select_timeout.tv_usec > 50000)) {
1558 select_timeout.tv_sec = 0;
1559 select_timeout.tv_usec = 50000;
1562 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1567 * The value of slot->finished we set before the loop was used
1568 * to set our "finished" variable when our request completed.
1570 * 1. The slot may not have been reused for another requst
1571 * yet, in which case it still has &finished.
1573 * 2. The slot may already be in-use to serve another request,
1574 * which can further be divided into two cases:
1576 * (a) If call run_active_slot() hasn't been called for that
1577 * other request, slot->finished would have been cleared
1578 * by get_active_slot() and has NULL.
1580 * (b) If the request did call run_active_slot(), then the
1581 * call would have updated slot->finished at the beginning
1582 * of this function, and with the clearing of the member
1583 * below, we would find that slot->finished is now NULL.
1585 * In all cases, slot->finished has no useful information to
1586 * anybody at this point. Some compilers warn us for
1587 * attempting to smuggle a pointer that is about to become
1588 * invalid, i.e. &finished. We clear it here to assure them.
1590 slot->finished = NULL;
1593 static void release_active_slot(struct active_request_slot *slot)
1595 closedown_active_slot(slot);
1596 if (slot->curl) {
1597 xmulti_remove_handle(slot);
1598 if (curl_session_count > min_curl_sessions) {
1599 curl_easy_cleanup(slot->curl);
1600 slot->curl = NULL;
1601 curl_session_count--;
1604 fill_active_slots();
1607 void finish_all_active_slots(void)
1609 struct active_request_slot *slot = active_queue_head;
1611 while (slot != NULL)
1612 if (slot->in_use) {
1613 run_active_slot(slot);
1614 slot = active_queue_head;
1615 } else {
1616 slot = slot->next;
1620 /* Helpers for modifying and creating URLs */
1621 static inline int needs_quote(int ch)
1623 if (((ch >= 'A') && (ch <= 'Z'))
1624 || ((ch >= 'a') && (ch <= 'z'))
1625 || ((ch >= '0') && (ch <= '9'))
1626 || (ch == '/')
1627 || (ch == '-')
1628 || (ch == '.'))
1629 return 0;
1630 return 1;
1633 static char *quote_ref_url(const char *base, const char *ref)
1635 struct strbuf buf = STRBUF_INIT;
1636 const char *cp;
1637 int ch;
1639 end_url_with_slash(&buf, base);
1641 for (cp = ref; (ch = *cp) != 0; cp++)
1642 if (needs_quote(ch))
1643 strbuf_addf(&buf, "%%%02x", ch);
1644 else
1645 strbuf_addch(&buf, *cp);
1647 return strbuf_detach(&buf, NULL);
1650 void append_remote_object_url(struct strbuf *buf, const char *url,
1651 const char *hex,
1652 int only_two_digit_prefix)
1654 end_url_with_slash(buf, url);
1656 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1657 if (!only_two_digit_prefix)
1658 strbuf_addstr(buf, hex + 2);
1661 char *get_remote_object_url(const char *url, const char *hex,
1662 int only_two_digit_prefix)
1664 struct strbuf buf = STRBUF_INIT;
1665 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1666 return strbuf_detach(&buf, NULL);
1669 void normalize_curl_result(CURLcode *result, long http_code,
1670 char *errorstr, size_t errorlen)
1673 * If we see a failing http code with CURLE_OK, we have turned off
1674 * FAILONERROR (to keep the server's custom error response), and should
1675 * translate the code into failure here.
1677 * Likewise, if we see a redirect (30x code), that means we turned off
1678 * redirect-following, and we should treat the result as an error.
1680 if (*result == CURLE_OK && http_code >= 300) {
1681 *result = CURLE_HTTP_RETURNED_ERROR;
1683 * Normally curl will already have put the "reason phrase"
1684 * from the server into curl_errorstr; unfortunately without
1685 * FAILONERROR it is lost, so we can give only the numeric
1686 * status code.
1688 xsnprintf(errorstr, errorlen,
1689 "The requested URL returned error: %ld",
1690 http_code);
1694 static int handle_curl_result(struct slot_results *results)
1696 normalize_curl_result(&results->curl_result, results->http_code,
1697 curl_errorstr, sizeof(curl_errorstr));
1699 if (results->curl_result == CURLE_OK) {
1700 credential_approve(&http_auth);
1701 credential_approve(&proxy_auth);
1702 credential_approve(&cert_auth);
1703 return HTTP_OK;
1704 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1706 * We can't tell from here whether it's a bad path, bad
1707 * certificate, bad password, or something else wrong
1708 * with the certificate. So we reject the credential to
1709 * avoid caching or saving a bad password.
1711 credential_reject(&cert_auth);
1712 return HTTP_NOAUTH;
1713 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1714 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1715 return HTTP_NOMATCHPUBLICKEY;
1716 #endif
1717 } else if (missing_target(results))
1718 return HTTP_MISSING_TARGET;
1719 else if (results->http_code == 401) {
1720 if (http_auth.username && http_auth.password) {
1721 credential_reject(&http_auth);
1722 return HTTP_NOAUTH;
1723 } else {
1724 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1725 if (results->auth_avail) {
1726 http_auth_methods &= results->auth_avail;
1727 http_auth_methods_restricted = 1;
1729 return HTTP_REAUTH;
1731 } else {
1732 if (results->http_connectcode == 407)
1733 credential_reject(&proxy_auth);
1734 if (!curl_errorstr[0])
1735 strlcpy(curl_errorstr,
1736 curl_easy_strerror(results->curl_result),
1737 sizeof(curl_errorstr));
1738 return HTTP_ERROR;
1742 int run_one_slot(struct active_request_slot *slot,
1743 struct slot_results *results)
1745 slot->results = results;
1746 if (!start_active_slot(slot)) {
1747 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1748 "failed to start HTTP request");
1749 return HTTP_START_FAILED;
1752 run_active_slot(slot);
1753 return handle_curl_result(results);
1756 struct curl_slist *http_copy_default_headers(void)
1758 struct curl_slist *headers = NULL;
1759 const struct string_list_item *item;
1761 for_each_string_list_item(item, &extra_http_headers)
1762 headers = curl_slist_append(headers, item->string);
1764 return headers;
1767 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1769 char *ptr;
1770 CURLcode ret;
1772 strbuf_reset(buf);
1773 ret = curl_easy_getinfo(curl, info, &ptr);
1774 if (!ret && ptr)
1775 strbuf_addstr(buf, ptr);
1776 return ret;
1780 * Check for and extract a content-type parameter. "raw"
1781 * should be positioned at the start of the potential
1782 * parameter, with any whitespace already removed.
1784 * "name" is the name of the parameter. The value is appended
1785 * to "out".
1787 static int extract_param(const char *raw, const char *name,
1788 struct strbuf *out)
1790 size_t len = strlen(name);
1792 if (strncasecmp(raw, name, len))
1793 return -1;
1794 raw += len;
1796 if (*raw != '=')
1797 return -1;
1798 raw++;
1800 while (*raw && !isspace(*raw) && *raw != ';')
1801 strbuf_addch(out, *raw++);
1802 return 0;
1806 * Extract a normalized version of the content type, with any
1807 * spaces suppressed, all letters lowercased, and no trailing ";"
1808 * or parameters.
1810 * Note that we will silently remove even invalid whitespace. For
1811 * example, "text / plain" is specifically forbidden by RFC 2616,
1812 * but "text/plain" is the only reasonable output, and this keeps
1813 * our code simple.
1815 * If the "charset" argument is not NULL, store the value of any
1816 * charset parameter there.
1818 * Example:
1819 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1820 * "text / plain" -> "text/plain"
1822 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1823 struct strbuf *charset)
1825 const char *p;
1827 strbuf_reset(type);
1828 strbuf_grow(type, raw->len);
1829 for (p = raw->buf; *p; p++) {
1830 if (isspace(*p))
1831 continue;
1832 if (*p == ';') {
1833 p++;
1834 break;
1836 strbuf_addch(type, tolower(*p));
1839 if (!charset)
1840 return;
1842 strbuf_reset(charset);
1843 while (*p) {
1844 while (isspace(*p) || *p == ';')
1845 p++;
1846 if (!extract_param(p, "charset", charset))
1847 return;
1848 while (*p && !isspace(*p))
1849 p++;
1852 if (!charset->len && starts_with(type->buf, "text/"))
1853 strbuf_addstr(charset, "ISO-8859-1");
1856 static void write_accept_language(struct strbuf *buf)
1859 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1860 * that, q-value will be smaller than 0.001, the minimum q-value the
1861 * HTTP specification allows. See
1862 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1864 const int MAX_DECIMAL_PLACES = 3;
1865 const int MAX_LANGUAGE_TAGS = 1000;
1866 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1867 char **language_tags = NULL;
1868 int num_langs = 0;
1869 const char *s = get_preferred_languages();
1870 int i;
1871 struct strbuf tag = STRBUF_INIT;
1873 /* Don't add Accept-Language header if no language is preferred. */
1874 if (!s)
1875 return;
1878 * Split the colon-separated string of preferred languages into
1879 * language_tags array.
1881 do {
1882 /* collect language tag */
1883 for (; *s && (isalnum(*s) || *s == '_'); s++)
1884 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1886 /* skip .codeset, @modifier and any other unnecessary parts */
1887 while (*s && *s != ':')
1888 s++;
1890 if (tag.len) {
1891 num_langs++;
1892 REALLOC_ARRAY(language_tags, num_langs);
1893 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1894 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1895 break;
1897 } while (*s++);
1899 /* write Accept-Language header into buf */
1900 if (num_langs) {
1901 int last_buf_len = 0;
1902 int max_q;
1903 int decimal_places;
1904 char q_format[32];
1906 /* add '*' */
1907 REALLOC_ARRAY(language_tags, num_langs + 1);
1908 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1910 /* compute decimal_places */
1911 for (max_q = 1, decimal_places = 0;
1912 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1913 decimal_places++, max_q *= 10)
1916 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1918 strbuf_addstr(buf, "Accept-Language: ");
1920 for (i = 0; i < num_langs; i++) {
1921 if (i > 0)
1922 strbuf_addstr(buf, ", ");
1924 strbuf_addstr(buf, language_tags[i]);
1926 if (i > 0)
1927 strbuf_addf(buf, q_format, max_q - i);
1929 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1930 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1931 break;
1934 last_buf_len = buf->len;
1938 /* free language tags -- last one is a static '*' */
1939 for (i = 0; i < num_langs - 1; i++)
1940 free(language_tags[i]);
1941 free(language_tags);
1945 * Get an Accept-Language header which indicates user's preferred languages.
1947 * Examples:
1948 * LANGUAGE= -> ""
1949 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1950 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1951 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1952 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1953 * LANGUAGE= LANG=C -> ""
1955 const char *http_get_accept_language_header(void)
1957 if (!cached_accept_language) {
1958 struct strbuf buf = STRBUF_INIT;
1959 write_accept_language(&buf);
1960 if (buf.len > 0)
1961 cached_accept_language = strbuf_detach(&buf, NULL);
1964 return cached_accept_language;
1967 static void http_opt_request_remainder(CURL *curl, off_t pos)
1969 char buf[128];
1970 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1971 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1974 /* http_request() targets */
1975 #define HTTP_REQUEST_STRBUF 0
1976 #define HTTP_REQUEST_FILE 1
1978 static int http_request(const char *url,
1979 void *result, int target,
1980 const struct http_get_options *options)
1982 struct active_request_slot *slot;
1983 struct slot_results results;
1984 struct curl_slist *headers = http_copy_default_headers();
1985 struct strbuf buf = STRBUF_INIT;
1986 const char *accept_language;
1987 int ret;
1989 slot = get_active_slot();
1990 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1992 if (!result) {
1993 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1994 } else {
1995 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1996 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
1998 if (target == HTTP_REQUEST_FILE) {
1999 off_t posn = ftello(result);
2000 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2001 fwrite);
2002 if (posn > 0)
2003 http_opt_request_remainder(slot->curl, posn);
2004 } else
2005 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2006 fwrite_buffer);
2009 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2011 accept_language = http_get_accept_language_header();
2013 if (accept_language)
2014 headers = curl_slist_append(headers, accept_language);
2016 strbuf_addstr(&buf, "Pragma:");
2017 if (options && options->no_cache)
2018 strbuf_addstr(&buf, " no-cache");
2019 if (options && options->initial_request &&
2020 http_follow_config == HTTP_FOLLOW_INITIAL)
2021 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2023 headers = curl_slist_append(headers, buf.buf);
2025 /* Add additional headers here */
2026 if (options && options->extra_headers) {
2027 const struct string_list_item *item;
2028 for_each_string_list_item(item, options->extra_headers) {
2029 headers = curl_slist_append(headers, item->string);
2033 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2034 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2035 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2036 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2038 ret = run_one_slot(slot, &results);
2040 if (options && options->content_type) {
2041 struct strbuf raw = STRBUF_INIT;
2042 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2043 extract_content_type(&raw, options->content_type,
2044 options->charset);
2045 strbuf_release(&raw);
2048 if (options && options->effective_url)
2049 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2050 options->effective_url);
2052 curl_slist_free_all(headers);
2053 strbuf_release(&buf);
2055 return ret;
2059 * Update the "base" url to a more appropriate value, as deduced by
2060 * redirects seen when requesting a URL starting with "url".
2062 * The "asked" parameter is a URL that we asked curl to access, and must begin
2063 * with "base".
2065 * The "got" parameter is the URL that curl reported to us as where we ended
2066 * up.
2068 * Returns 1 if we updated the base url, 0 otherwise.
2070 * Our basic strategy is to compare "base" and "asked" to find the bits
2071 * specific to our request. We then strip those bits off of "got" to yield the
2072 * new base. So for example, if our base is "http://example.com/foo.git",
2073 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2074 * with "https://other.example.com/foo.git/info/refs". We would want the
2075 * new URL to become "https://other.example.com/foo.git".
2077 * Note that this assumes a sane redirect scheme. It's entirely possible
2078 * in the example above to end up at a URL that does not even end in
2079 * "info/refs". In such a case we die. There's not much we can do, such a
2080 * scheme is unlikely to represent a real git repository, and failing to
2081 * rewrite the base opens options for malicious redirects to do funny things.
2083 static int update_url_from_redirect(struct strbuf *base,
2084 const char *asked,
2085 const struct strbuf *got)
2087 const char *tail;
2088 size_t new_len;
2090 if (!strcmp(asked, got->buf))
2091 return 0;
2093 if (!skip_prefix(asked, base->buf, &tail))
2094 BUG("update_url_from_redirect: %s is not a superset of %s",
2095 asked, base->buf);
2097 new_len = got->len;
2098 if (!strip_suffix_mem(got->buf, &new_len, tail))
2099 die(_("unable to update url base from redirection:\n"
2100 " asked for: %s\n"
2101 " redirect: %s"),
2102 asked, got->buf);
2104 strbuf_reset(base);
2105 strbuf_add(base, got->buf, new_len);
2107 return 1;
2110 static int http_request_reauth(const char *url,
2111 void *result, int target,
2112 struct http_get_options *options)
2114 int ret = http_request(url, result, target, options);
2116 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2117 return ret;
2119 if (options && options->effective_url && options->base_url) {
2120 if (update_url_from_redirect(options->base_url,
2121 url, options->effective_url)) {
2122 credential_from_url(&http_auth, options->base_url->buf);
2123 url = options->effective_url->buf;
2127 if (ret != HTTP_REAUTH)
2128 return ret;
2131 * The previous request may have put cruft into our output stream; we
2132 * should clear it out before making our next request.
2134 switch (target) {
2135 case HTTP_REQUEST_STRBUF:
2136 strbuf_reset(result);
2137 break;
2138 case HTTP_REQUEST_FILE:
2139 if (fflush(result)) {
2140 error_errno("unable to flush a file");
2141 return HTTP_START_FAILED;
2143 rewind(result);
2144 if (ftruncate(fileno(result), 0) < 0) {
2145 error_errno("unable to truncate a file");
2146 return HTTP_START_FAILED;
2148 break;
2149 default:
2150 BUG("Unknown http_request target");
2153 credential_fill(&http_auth);
2155 return http_request(url, result, target, options);
2158 int http_get_strbuf(const char *url,
2159 struct strbuf *result,
2160 struct http_get_options *options)
2162 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2166 * Downloads a URL and stores the result in the given file.
2168 * If a previous interrupted download is detected (i.e. a previous temporary
2169 * file is still around) the download is resumed.
2171 int http_get_file(const char *url, const char *filename,
2172 struct http_get_options *options)
2174 int ret;
2175 struct strbuf tmpfile = STRBUF_INIT;
2176 FILE *result;
2178 strbuf_addf(&tmpfile, "%s.temp", filename);
2179 result = fopen(tmpfile.buf, "a");
2180 if (!result) {
2181 error("Unable to open local file %s", tmpfile.buf);
2182 ret = HTTP_ERROR;
2183 goto cleanup;
2186 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2187 fclose(result);
2189 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2190 ret = HTTP_ERROR;
2191 cleanup:
2192 strbuf_release(&tmpfile);
2193 return ret;
2196 int http_fetch_ref(const char *base, struct ref *ref)
2198 struct http_get_options options = {0};
2199 char *url;
2200 struct strbuf buffer = STRBUF_INIT;
2201 int ret = -1;
2203 options.no_cache = 1;
2205 url = quote_ref_url(base, ref->name);
2206 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2207 strbuf_rtrim(&buffer);
2208 if (buffer.len == the_hash_algo->hexsz)
2209 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2210 else if (starts_with(buffer.buf, "ref: ")) {
2211 ref->symref = xstrdup(buffer.buf + 5);
2212 ret = 0;
2216 strbuf_release(&buffer);
2217 free(url);
2218 return ret;
2221 /* Helpers for fetching packs */
2222 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2224 char *url, *tmp;
2225 struct strbuf buf = STRBUF_INIT;
2227 if (http_is_verbose)
2228 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2230 end_url_with_slash(&buf, base_url);
2231 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2232 url = strbuf_detach(&buf, NULL);
2234 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2235 tmp = strbuf_detach(&buf, NULL);
2237 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2238 error("Unable to get pack index %s", url);
2239 FREE_AND_NULL(tmp);
2242 free(url);
2243 return tmp;
2246 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2247 unsigned char *sha1, const char *base_url)
2249 struct packed_git *new_pack;
2250 char *tmp_idx = NULL;
2251 int ret;
2253 if (has_pack_index(sha1)) {
2254 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2255 if (!new_pack)
2256 return -1; /* parse_pack_index() already issued error message */
2257 goto add_pack;
2260 tmp_idx = fetch_pack_index(sha1, base_url);
2261 if (!tmp_idx)
2262 return -1;
2264 new_pack = parse_pack_index(sha1, tmp_idx);
2265 if (!new_pack) {
2266 unlink(tmp_idx);
2267 free(tmp_idx);
2269 return -1; /* parse_pack_index() already issued error message */
2272 ret = verify_pack_index(new_pack);
2273 if (!ret) {
2274 close_pack_index(new_pack);
2275 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2277 free(tmp_idx);
2278 if (ret)
2279 return -1;
2281 add_pack:
2282 new_pack->next = *packs_head;
2283 *packs_head = new_pack;
2284 return 0;
2287 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2289 struct http_get_options options = {0};
2290 int ret = 0;
2291 char *url;
2292 const char *data;
2293 struct strbuf buf = STRBUF_INIT;
2294 struct object_id oid;
2296 end_url_with_slash(&buf, base_url);
2297 strbuf_addstr(&buf, "objects/info/packs");
2298 url = strbuf_detach(&buf, NULL);
2300 options.no_cache = 1;
2301 ret = http_get_strbuf(url, &buf, &options);
2302 if (ret != HTTP_OK)
2303 goto cleanup;
2305 data = buf.buf;
2306 while (*data) {
2307 if (skip_prefix(data, "P pack-", &data) &&
2308 !parse_oid_hex(data, &oid, &data) &&
2309 skip_prefix(data, ".pack", &data) &&
2310 (*data == '\n' || *data == '\0')) {
2311 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2312 } else {
2313 data = strchrnul(data, '\n');
2315 if (*data)
2316 data++; /* skip past newline */
2319 cleanup:
2320 free(url);
2321 return ret;
2324 void release_http_pack_request(struct http_pack_request *preq)
2326 if (preq->packfile) {
2327 fclose(preq->packfile);
2328 preq->packfile = NULL;
2330 preq->slot = NULL;
2331 strbuf_release(&preq->tmpfile);
2332 free(preq->url);
2333 free(preq);
2336 static const char *default_index_pack_args[] =
2337 {"index-pack", "--stdin", NULL};
2339 int finish_http_pack_request(struct http_pack_request *preq)
2341 struct child_process ip = CHILD_PROCESS_INIT;
2342 int tmpfile_fd;
2343 int ret = 0;
2345 fclose(preq->packfile);
2346 preq->packfile = NULL;
2348 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2350 ip.git_cmd = 1;
2351 ip.in = tmpfile_fd;
2352 strvec_pushv(&ip.args, preq->index_pack_args ?
2353 preq->index_pack_args :
2354 default_index_pack_args);
2356 if (preq->preserve_index_pack_stdout)
2357 ip.out = 0;
2358 else
2359 ip.no_stdout = 1;
2361 if (run_command(&ip)) {
2362 ret = -1;
2363 goto cleanup;
2366 cleanup:
2367 close(tmpfile_fd);
2368 unlink(preq->tmpfile.buf);
2369 return ret;
2372 void http_install_packfile(struct packed_git *p,
2373 struct packed_git **list_to_remove_from)
2375 struct packed_git **lst = list_to_remove_from;
2377 while (*lst != p)
2378 lst = &((*lst)->next);
2379 *lst = (*lst)->next;
2381 install_packed_git(the_repository, p);
2384 struct http_pack_request *new_http_pack_request(
2385 const unsigned char *packed_git_hash, const char *base_url) {
2387 struct strbuf buf = STRBUF_INIT;
2389 end_url_with_slash(&buf, base_url);
2390 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2391 hash_to_hex(packed_git_hash));
2392 return new_direct_http_pack_request(packed_git_hash,
2393 strbuf_detach(&buf, NULL));
2396 struct http_pack_request *new_direct_http_pack_request(
2397 const unsigned char *packed_git_hash, char *url)
2399 off_t prev_posn = 0;
2400 struct http_pack_request *preq;
2402 CALLOC_ARRAY(preq, 1);
2403 strbuf_init(&preq->tmpfile, 0);
2405 preq->url = url;
2407 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2408 preq->packfile = fopen(preq->tmpfile.buf, "a");
2409 if (!preq->packfile) {
2410 error("Unable to open local file %s for pack",
2411 preq->tmpfile.buf);
2412 goto abort;
2415 preq->slot = get_active_slot();
2416 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2417 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2418 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2419 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2420 no_pragma_header);
2423 * If there is data present from a previous transfer attempt,
2424 * resume where it left off
2426 prev_posn = ftello(preq->packfile);
2427 if (prev_posn>0) {
2428 if (http_is_verbose)
2429 fprintf(stderr,
2430 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2431 hash_to_hex(packed_git_hash),
2432 (uintmax_t)prev_posn);
2433 http_opt_request_remainder(preq->slot->curl, prev_posn);
2436 return preq;
2438 abort:
2439 strbuf_release(&preq->tmpfile);
2440 free(preq->url);
2441 free(preq);
2442 return NULL;
2445 /* Helpers for fetching objects (loose) */
2446 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2447 void *data)
2449 unsigned char expn[4096];
2450 size_t size = eltsize * nmemb;
2451 int posn = 0;
2452 struct http_object_request *freq = data;
2453 struct active_request_slot *slot = freq->slot;
2455 if (slot) {
2456 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2457 &slot->http_code);
2458 if (c != CURLE_OK)
2459 BUG("curl_easy_getinfo for HTTP code failed: %s",
2460 curl_easy_strerror(c));
2461 if (slot->http_code >= 300)
2462 return nmemb;
2465 do {
2466 ssize_t retval = xwrite(freq->localfile,
2467 (char *) ptr + posn, size - posn);
2468 if (retval < 0)
2469 return posn / eltsize;
2470 posn += retval;
2471 } while (posn < size);
2473 freq->stream.avail_in = size;
2474 freq->stream.next_in = (void *)ptr;
2475 do {
2476 freq->stream.next_out = expn;
2477 freq->stream.avail_out = sizeof(expn);
2478 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2479 the_hash_algo->update_fn(&freq->c, expn,
2480 sizeof(expn) - freq->stream.avail_out);
2481 } while (freq->stream.avail_in && freq->zret == Z_OK);
2482 return nmemb;
2485 struct http_object_request *new_http_object_request(const char *base_url,
2486 const struct object_id *oid)
2488 char *hex = oid_to_hex(oid);
2489 struct strbuf filename = STRBUF_INIT;
2490 struct strbuf prevfile = STRBUF_INIT;
2491 int prevlocal;
2492 char prev_buf[PREV_BUF_SIZE];
2493 ssize_t prev_read = 0;
2494 off_t prev_posn = 0;
2495 struct http_object_request *freq;
2497 CALLOC_ARRAY(freq, 1);
2498 strbuf_init(&freq->tmpfile, 0);
2499 oidcpy(&freq->oid, oid);
2500 freq->localfile = -1;
2502 loose_object_path(the_repository, &filename, oid);
2503 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2505 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2506 unlink_or_warn(prevfile.buf);
2507 rename(freq->tmpfile.buf, prevfile.buf);
2508 unlink_or_warn(freq->tmpfile.buf);
2509 strbuf_release(&filename);
2511 if (freq->localfile != -1)
2512 error("fd leakage in start: %d", freq->localfile);
2513 freq->localfile = open(freq->tmpfile.buf,
2514 O_WRONLY | O_CREAT | O_EXCL, 0666);
2516 * This could have failed due to the "lazy directory creation";
2517 * try to mkdir the last path component.
2519 if (freq->localfile < 0 && errno == ENOENT) {
2520 char *dir = strrchr(freq->tmpfile.buf, '/');
2521 if (dir) {
2522 *dir = 0;
2523 mkdir(freq->tmpfile.buf, 0777);
2524 *dir = '/';
2526 freq->localfile = open(freq->tmpfile.buf,
2527 O_WRONLY | O_CREAT | O_EXCL, 0666);
2530 if (freq->localfile < 0) {
2531 error_errno("Couldn't create temporary file %s",
2532 freq->tmpfile.buf);
2533 goto abort;
2536 git_inflate_init(&freq->stream);
2538 the_hash_algo->init_fn(&freq->c);
2540 freq->url = get_remote_object_url(base_url, hex, 0);
2543 * If a previous temp file is present, process what was already
2544 * fetched.
2546 prevlocal = open(prevfile.buf, O_RDONLY);
2547 if (prevlocal != -1) {
2548 do {
2549 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2550 if (prev_read>0) {
2551 if (fwrite_sha1_file(prev_buf,
2553 prev_read,
2554 freq) == prev_read) {
2555 prev_posn += prev_read;
2556 } else {
2557 prev_read = -1;
2560 } while (prev_read > 0);
2561 close(prevlocal);
2563 unlink_or_warn(prevfile.buf);
2564 strbuf_release(&prevfile);
2567 * Reset inflate/SHA1 if there was an error reading the previous temp
2568 * file; also rewind to the beginning of the local file.
2570 if (prev_read == -1) {
2571 memset(&freq->stream, 0, sizeof(freq->stream));
2572 git_inflate_init(&freq->stream);
2573 the_hash_algo->init_fn(&freq->c);
2574 if (prev_posn>0) {
2575 prev_posn = 0;
2576 lseek(freq->localfile, 0, SEEK_SET);
2577 if (ftruncate(freq->localfile, 0) < 0) {
2578 error_errno("Couldn't truncate temporary file %s",
2579 freq->tmpfile.buf);
2580 goto abort;
2585 freq->slot = get_active_slot();
2587 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2588 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2589 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2590 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2591 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2592 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2595 * If we have successfully processed data from a previous fetch
2596 * attempt, only fetch the data we don't already have.
2598 if (prev_posn>0) {
2599 if (http_is_verbose)
2600 fprintf(stderr,
2601 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2602 hex, (uintmax_t)prev_posn);
2603 http_opt_request_remainder(freq->slot->curl, prev_posn);
2606 return freq;
2608 abort:
2609 strbuf_release(&prevfile);
2610 free(freq->url);
2611 free(freq);
2612 return NULL;
2615 void process_http_object_request(struct http_object_request *freq)
2617 if (!freq->slot)
2618 return;
2619 freq->curl_result = freq->slot->curl_result;
2620 freq->http_code = freq->slot->http_code;
2621 freq->slot = NULL;
2624 int finish_http_object_request(struct http_object_request *freq)
2626 struct stat st;
2627 struct strbuf filename = STRBUF_INIT;
2629 close(freq->localfile);
2630 freq->localfile = -1;
2632 process_http_object_request(freq);
2634 if (freq->http_code == 416) {
2635 warning("requested range invalid; we may already have all the data.");
2636 } else if (freq->curl_result != CURLE_OK) {
2637 if (stat(freq->tmpfile.buf, &st) == 0)
2638 if (st.st_size == 0)
2639 unlink_or_warn(freq->tmpfile.buf);
2640 return -1;
2643 git_inflate_end(&freq->stream);
2644 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2645 if (freq->zret != Z_STREAM_END) {
2646 unlink_or_warn(freq->tmpfile.buf);
2647 return -1;
2649 if (!oideq(&freq->oid, &freq->real_oid)) {
2650 unlink_or_warn(freq->tmpfile.buf);
2651 return -1;
2653 loose_object_path(the_repository, &filename, &freq->oid);
2654 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2655 strbuf_release(&filename);
2657 return freq->rename;
2660 void abort_http_object_request(struct http_object_request *freq)
2662 unlink_or_warn(freq->tmpfile.buf);
2664 release_http_object_request(freq);
2667 void release_http_object_request(struct http_object_request *freq)
2669 if (freq->localfile != -1) {
2670 close(freq->localfile);
2671 freq->localfile = -1;
2673 FREE_AND_NULL(freq->url);
2674 if (freq->slot) {
2675 freq->slot->callback_func = NULL;
2676 freq->slot->callback_data = NULL;
2677 release_active_slot(freq->slot);
2678 freq->slot = NULL;
2680 strbuf_release(&freq->tmpfile);