Merge branch 'az/grep-group-error-message-update'
[alt-git.git] / http.c
blobe73b136e5897bd8fce2f874b20f316141ba59c31
1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
3 #include "hex.h"
4 #include "http.h"
5 #include "config.h"
6 #include "pack.h"
7 #include "run-command.h"
8 #include "url.h"
9 #include "urlmatch.h"
10 #include "credential.h"
11 #include "version.h"
12 #include "pkt-line.h"
13 #include "gettext.h"
14 #include "trace.h"
15 #include "transport.h"
16 #include "packfile.h"
17 #include "string-list.h"
18 #include "object-file.h"
19 #include "object-store-ll.h"
21 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
22 static int trace_curl_data = 1;
23 static int trace_curl_redact = 1;
24 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
25 int active_requests;
26 int http_is_verbose;
27 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
29 static int min_curl_sessions = 1;
30 static int curl_session_count;
31 static int max_requests = -1;
32 static CURLM *curlm;
33 static CURL *curl_default;
35 #define PREV_BUF_SIZE 4096
37 char curl_errorstr[CURL_ERROR_SIZE];
39 static int curl_ssl_verify = -1;
40 static int curl_ssl_try;
41 static const char *curl_http_version = NULL;
42 static const char *ssl_cert;
43 static const char *ssl_cert_type;
44 static const char *ssl_cipherlist;
45 static const char *ssl_version;
46 static struct {
47 const char *name;
48 long ssl_version;
49 } sslversions[] = {
50 { "sslv2", CURL_SSLVERSION_SSLv2 },
51 { "sslv3", CURL_SSLVERSION_SSLv3 },
52 { "tlsv1", CURL_SSLVERSION_TLSv1 },
53 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
54 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
55 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
56 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
57 #endif
58 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
59 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
60 #endif
62 static const char *ssl_key;
63 static const char *ssl_key_type;
64 static const char *ssl_capath;
65 static const char *curl_no_proxy;
66 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
67 static const char *ssl_pinnedkey;
68 #endif
69 static const char *ssl_cainfo;
70 static long curl_low_speed_limit = -1;
71 static long curl_low_speed_time = -1;
72 static int curl_ftp_no_epsv;
73 static const char *curl_http_proxy;
74 static const char *http_proxy_authmethod;
76 static const char *http_proxy_ssl_cert;
77 static const char *http_proxy_ssl_key;
78 static const char *http_proxy_ssl_ca_info;
79 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
80 static int proxy_ssl_cert_password_required;
82 static struct {
83 const char *name;
84 long curlauth_param;
85 } proxy_authmethods[] = {
86 { "basic", CURLAUTH_BASIC },
87 { "digest", CURLAUTH_DIGEST },
88 { "negotiate", CURLAUTH_GSSNEGOTIATE },
89 { "ntlm", CURLAUTH_NTLM },
90 { "anyauth", CURLAUTH_ANY },
92 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
93 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
94 * here, too
97 #ifdef CURLGSSAPI_DELEGATION_FLAG
98 static const char *curl_deleg;
99 static struct {
100 const char *name;
101 long curl_deleg_param;
102 } curl_deleg_levels[] = {
103 { "none", CURLGSSAPI_DELEGATION_NONE },
104 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
105 { "always", CURLGSSAPI_DELEGATION_FLAG },
107 #endif
109 static struct credential proxy_auth = CREDENTIAL_INIT;
110 static const char *curl_proxyuserpwd;
111 static const char *curl_cookie_file;
112 static int curl_save_cookies;
113 struct credential http_auth = CREDENTIAL_INIT;
114 static int http_proactive_auth;
115 static const char *user_agent;
116 static int curl_empty_auth = -1;
118 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
120 static struct credential cert_auth = CREDENTIAL_INIT;
121 static int ssl_cert_password_required;
122 static unsigned long http_auth_methods = CURLAUTH_ANY;
123 static int http_auth_methods_restricted;
124 /* Modes for which empty_auth cannot actually help us. */
125 static unsigned long empty_auth_useless =
126 CURLAUTH_BASIC
127 | CURLAUTH_DIGEST_IE
128 | CURLAUTH_DIGEST;
130 static struct curl_slist *pragma_header;
131 static struct curl_slist *no_pragma_header;
132 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
134 static struct curl_slist *host_resolutions;
136 static struct active_request_slot *active_queue_head;
138 static char *cached_accept_language;
140 static char *http_ssl_backend;
142 static int http_schannel_check_revoke = 1;
144 * With the backend being set to `schannel`, setting sslCAinfo would override
145 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
146 * by default.
148 static int http_schannel_use_ssl_cainfo;
150 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
152 size_t size = eltsize * nmemb;
153 struct buffer *buffer = buffer_;
155 if (size > buffer->buf.len - buffer->posn)
156 size = buffer->buf.len - buffer->posn;
157 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
158 buffer->posn += size;
160 return size / eltsize;
163 int seek_buffer(void *clientp, curl_off_t offset, int origin)
165 struct buffer *buffer = clientp;
167 if (origin != SEEK_SET)
168 BUG("seek_buffer only handles SEEK_SET");
169 if (offset < 0 || offset >= buffer->buf.len) {
170 error("curl seek would be outside of buffer");
171 return CURL_SEEKFUNC_FAIL;
174 buffer->posn = offset;
175 return CURL_SEEKFUNC_OK;
178 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
180 size_t size = eltsize * nmemb;
181 struct strbuf *buffer = buffer_;
183 strbuf_add(buffer, ptr, size);
184 return nmemb;
188 * A folded header continuation line starts with any number of spaces or
189 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
190 * It is not a continuation line if the line starts with any other character.
192 static inline int is_hdr_continuation(const char *ptr, const size_t size)
194 return size && (*ptr == ' ' || *ptr == '\t');
197 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
199 size_t size = eltsize * nmemb;
200 struct strvec *values = &http_auth.wwwauth_headers;
201 struct strbuf buf = STRBUF_INIT;
202 const char *val;
203 size_t val_len;
206 * Header lines may not come NULL-terminated from libcurl so we must
207 * limit all scans to the maximum length of the header line, or leverage
208 * strbufs for all operations.
210 * In addition, it is possible that header values can be split over
211 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
212 * but older servers may still emit them. A continuation header field
213 * value is identified as starting with a space or horizontal tab.
215 * The formal definition of a header field as given in RFC 7230 is:
217 * header-field = field-name ":" OWS field-value OWS
219 * field-name = token
220 * field-value = *( field-content / obs-fold )
221 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
222 * field-vchar = VCHAR / obs-text
224 * obs-fold = CRLF 1*( SP / HTAB )
225 * ; obsolete line folding
226 * ; see Section 3.2.4
229 /* Start of a new WWW-Authenticate header */
230 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
231 strbuf_add(&buf, val, val_len);
234 * Strip the CRLF that should be present at the end of each
235 * field as well as any trailing or leading whitespace from the
236 * value.
238 strbuf_trim(&buf);
240 strvec_push(values, buf.buf);
241 http_auth.header_is_last_match = 1;
242 goto exit;
246 * This line could be a continuation of the previously matched header
247 * field. If this is the case then we should append this value to the
248 * end of the previously consumed value.
250 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
252 * Trim the CRLF and any leading or trailing from this line.
254 strbuf_add(&buf, ptr, size);
255 strbuf_trim(&buf);
258 * At this point we should always have at least one existing
259 * value, even if it is empty. Do not bother appending the new
260 * value if this continuation header is itself empty.
262 if (!values->nr) {
263 BUG("should have at least one existing header value");
264 } else if (buf.len) {
265 char *prev = xstrdup(values->v[values->nr - 1]);
267 /* Join two non-empty values with a single space. */
268 const char *const sp = *prev ? " " : "";
270 strvec_pop(values);
271 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
272 free(prev);
275 goto exit;
278 /* Not a continuation of a previously matched auth header line. */
279 http_auth.header_is_last_match = 0;
282 * If this is a HTTP status line and not a header field, this signals
283 * a different HTTP response. libcurl writes all the output of all
284 * response headers of all responses, including redirects.
285 * We only care about the last HTTP request response's headers so clear
286 * the existing array.
288 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
289 strvec_clear(values);
291 exit:
292 strbuf_release(&buf);
293 return size;
296 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
297 void *data UNUSED)
299 return nmemb;
302 static void closedown_active_slot(struct active_request_slot *slot)
304 active_requests--;
305 slot->in_use = 0;
308 static void finish_active_slot(struct active_request_slot *slot)
310 closedown_active_slot(slot);
311 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
313 if (slot->finished)
314 (*slot->finished) = 1;
316 /* Store slot results so they can be read after the slot is reused */
317 if (slot->results) {
318 slot->results->curl_result = slot->curl_result;
319 slot->results->http_code = slot->http_code;
320 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
321 &slot->results->auth_avail);
323 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
324 &slot->results->http_connectcode);
327 /* Run callback if appropriate */
328 if (slot->callback_func)
329 slot->callback_func(slot->callback_data);
332 static void xmulti_remove_handle(struct active_request_slot *slot)
334 curl_multi_remove_handle(curlm, slot->curl);
337 static void process_curl_messages(void)
339 int num_messages;
340 struct active_request_slot *slot;
341 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
343 while (curl_message != NULL) {
344 if (curl_message->msg == CURLMSG_DONE) {
345 int curl_result = curl_message->data.result;
346 slot = active_queue_head;
347 while (slot != NULL &&
348 slot->curl != curl_message->easy_handle)
349 slot = slot->next;
350 if (slot) {
351 xmulti_remove_handle(slot);
352 slot->curl_result = curl_result;
353 finish_active_slot(slot);
354 } else {
355 fprintf(stderr, "Received DONE message for unknown request!\n");
357 } else {
358 fprintf(stderr, "Unknown CURL message received: %d\n",
359 (int)curl_message->msg);
361 curl_message = curl_multi_info_read(curlm, &num_messages);
365 static int http_options(const char *var, const char *value,
366 const struct config_context *ctx, void *data)
368 if (!strcmp("http.version", var)) {
369 return git_config_string(&curl_http_version, var, value);
371 if (!strcmp("http.sslverify", var)) {
372 curl_ssl_verify = git_config_bool(var, value);
373 return 0;
375 if (!strcmp("http.sslcipherlist", var))
376 return git_config_string(&ssl_cipherlist, var, value);
377 if (!strcmp("http.sslversion", var))
378 return git_config_string(&ssl_version, var, value);
379 if (!strcmp("http.sslcert", var))
380 return git_config_pathname(&ssl_cert, var, value);
381 if (!strcmp("http.sslcerttype", var))
382 return git_config_string(&ssl_cert_type, var, value);
383 if (!strcmp("http.sslkey", var))
384 return git_config_pathname(&ssl_key, var, value);
385 if (!strcmp("http.sslkeytype", var))
386 return git_config_string(&ssl_key_type, var, value);
387 if (!strcmp("http.sslcapath", var))
388 return git_config_pathname(&ssl_capath, var, value);
389 if (!strcmp("http.sslcainfo", var))
390 return git_config_pathname(&ssl_cainfo, var, value);
391 if (!strcmp("http.sslcertpasswordprotected", var)) {
392 ssl_cert_password_required = git_config_bool(var, value);
393 return 0;
395 if (!strcmp("http.ssltry", var)) {
396 curl_ssl_try = git_config_bool(var, value);
397 return 0;
399 if (!strcmp("http.sslbackend", var)) {
400 free(http_ssl_backend);
401 http_ssl_backend = xstrdup_or_null(value);
402 return 0;
405 if (!strcmp("http.schannelcheckrevoke", var)) {
406 http_schannel_check_revoke = git_config_bool(var, value);
407 return 0;
410 if (!strcmp("http.schannelusesslcainfo", var)) {
411 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
412 return 0;
415 if (!strcmp("http.minsessions", var)) {
416 min_curl_sessions = git_config_int(var, value, ctx->kvi);
417 if (min_curl_sessions > 1)
418 min_curl_sessions = 1;
419 return 0;
421 if (!strcmp("http.maxrequests", var)) {
422 max_requests = git_config_int(var, value, ctx->kvi);
423 return 0;
425 if (!strcmp("http.lowspeedlimit", var)) {
426 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
427 return 0;
429 if (!strcmp("http.lowspeedtime", var)) {
430 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
431 return 0;
434 if (!strcmp("http.noepsv", var)) {
435 curl_ftp_no_epsv = git_config_bool(var, value);
436 return 0;
438 if (!strcmp("http.proxy", var))
439 return git_config_string(&curl_http_proxy, var, value);
441 if (!strcmp("http.proxyauthmethod", var))
442 return git_config_string(&http_proxy_authmethod, var, value);
444 if (!strcmp("http.proxysslcert", var))
445 return git_config_string(&http_proxy_ssl_cert, var, value);
447 if (!strcmp("http.proxysslkey", var))
448 return git_config_string(&http_proxy_ssl_key, var, value);
450 if (!strcmp("http.proxysslcainfo", var))
451 return git_config_string(&http_proxy_ssl_ca_info, var, value);
453 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
454 proxy_ssl_cert_password_required = git_config_bool(var, value);
455 return 0;
458 if (!strcmp("http.cookiefile", var))
459 return git_config_pathname(&curl_cookie_file, var, value);
460 if (!strcmp("http.savecookies", var)) {
461 curl_save_cookies = git_config_bool(var, value);
462 return 0;
465 if (!strcmp("http.postbuffer", var)) {
466 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
467 if (http_post_buffer < 0)
468 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
469 if (http_post_buffer < LARGE_PACKET_MAX)
470 http_post_buffer = LARGE_PACKET_MAX;
471 return 0;
474 if (!strcmp("http.useragent", var))
475 return git_config_string(&user_agent, var, value);
477 if (!strcmp("http.emptyauth", var)) {
478 if (value && !strcmp("auto", value))
479 curl_empty_auth = -1;
480 else
481 curl_empty_auth = git_config_bool(var, value);
482 return 0;
485 if (!strcmp("http.delegation", var)) {
486 #ifdef CURLGSSAPI_DELEGATION_FLAG
487 return git_config_string(&curl_deleg, var, value);
488 #else
489 warning(_("Delegation control is not supported with cURL < 7.22.0"));
490 return 0;
491 #endif
494 if (!strcmp("http.pinnedpubkey", var)) {
495 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
496 return git_config_pathname(&ssl_pinnedkey, var, value);
497 #else
498 warning(_("Public key pinning not supported with cURL < 7.39.0"));
499 return 0;
500 #endif
503 if (!strcmp("http.extraheader", var)) {
504 if (!value) {
505 return config_error_nonbool(var);
506 } else if (!*value) {
507 string_list_clear(&extra_http_headers, 0);
508 } else {
509 string_list_append(&extra_http_headers, value);
511 return 0;
514 if (!strcmp("http.curloptresolve", var)) {
515 if (!value) {
516 return config_error_nonbool(var);
517 } else if (!*value) {
518 curl_slist_free_all(host_resolutions);
519 host_resolutions = NULL;
520 } else {
521 host_resolutions = curl_slist_append(host_resolutions, value);
523 return 0;
526 if (!strcmp("http.followredirects", var)) {
527 if (value && !strcmp(value, "initial"))
528 http_follow_config = HTTP_FOLLOW_INITIAL;
529 else if (git_config_bool(var, value))
530 http_follow_config = HTTP_FOLLOW_ALWAYS;
531 else
532 http_follow_config = HTTP_FOLLOW_NONE;
533 return 0;
536 /* Fall back on the default ones */
537 return git_default_config(var, value, ctx, data);
540 static int curl_empty_auth_enabled(void)
542 if (curl_empty_auth >= 0)
543 return curl_empty_auth;
546 * In the automatic case, kick in the empty-auth
547 * hack as long as we would potentially try some
548 * method more exotic than "Basic" or "Digest".
550 * But only do this when this is our second or
551 * subsequent request, as by then we know what
552 * methods are available.
554 if (http_auth_methods_restricted &&
555 (http_auth_methods & ~empty_auth_useless))
556 return 1;
557 return 0;
560 static void init_curl_http_auth(CURL *result)
562 if (!http_auth.username || !*http_auth.username) {
563 if (curl_empty_auth_enabled())
564 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
565 return;
568 credential_fill(&http_auth);
570 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
571 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
574 /* *var must be free-able */
575 static void var_override(const char **var, char *value)
577 if (value) {
578 free((void *)*var);
579 *var = xstrdup(value);
583 static void set_proxyauth_name_password(CURL *result)
585 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
586 proxy_auth.username);
587 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
588 proxy_auth.password);
591 static void init_curl_proxy_auth(CURL *result)
593 if (proxy_auth.username) {
594 if (!proxy_auth.password)
595 credential_fill(&proxy_auth);
596 set_proxyauth_name_password(result);
599 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
601 if (http_proxy_authmethod) {
602 int i;
603 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
604 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
605 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
606 proxy_authmethods[i].curlauth_param);
607 break;
610 if (i == ARRAY_SIZE(proxy_authmethods)) {
611 warning("unsupported proxy authentication method %s: using anyauth",
612 http_proxy_authmethod);
613 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
616 else
617 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
620 static int has_cert_password(void)
622 if (ssl_cert == NULL || ssl_cert_password_required != 1)
623 return 0;
624 if (!cert_auth.password) {
625 cert_auth.protocol = xstrdup("cert");
626 cert_auth.host = xstrdup("");
627 cert_auth.username = xstrdup("");
628 cert_auth.path = xstrdup(ssl_cert);
629 credential_fill(&cert_auth);
631 return 1;
634 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
635 static int has_proxy_cert_password(void)
637 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
638 return 0;
639 if (!proxy_cert_auth.password) {
640 proxy_cert_auth.protocol = xstrdup("cert");
641 proxy_cert_auth.host = xstrdup("");
642 proxy_cert_auth.username = xstrdup("");
643 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
644 credential_fill(&proxy_cert_auth);
646 return 1;
648 #endif
650 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
651 static void set_curl_keepalive(CURL *c)
653 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
656 #else
657 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
659 int ka = 1;
660 int rc;
661 socklen_t len = (socklen_t)sizeof(ka);
663 if (type != CURLSOCKTYPE_IPCXN)
664 return 0;
666 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
667 if (rc < 0)
668 warning_errno("unable to set SO_KEEPALIVE on socket");
670 return CURL_SOCKOPT_OK;
673 static void set_curl_keepalive(CURL *c)
675 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
677 #endif
679 /* Return 1 if redactions have been made, 0 otherwise. */
680 static int redact_sensitive_header(struct strbuf *header, size_t offset)
682 int ret = 0;
683 const char *sensitive_header;
685 if (trace_curl_redact &&
686 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
687 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
688 /* The first token is the type, which is OK to log */
689 while (isspace(*sensitive_header))
690 sensitive_header++;
691 while (*sensitive_header && !isspace(*sensitive_header))
692 sensitive_header++;
693 /* Everything else is opaque and possibly sensitive */
694 strbuf_setlen(header, sensitive_header - header->buf);
695 strbuf_addstr(header, " <redacted>");
696 ret = 1;
697 } else if (trace_curl_redact &&
698 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
699 struct strbuf redacted_header = STRBUF_INIT;
700 const char *cookie;
702 while (isspace(*sensitive_header))
703 sensitive_header++;
705 cookie = sensitive_header;
707 while (cookie) {
708 char *equals;
709 char *semicolon = strstr(cookie, "; ");
710 if (semicolon)
711 *semicolon = 0;
712 equals = strchrnul(cookie, '=');
713 if (!equals) {
714 /* invalid cookie, just append and continue */
715 strbuf_addstr(&redacted_header, cookie);
716 continue;
718 strbuf_add(&redacted_header, cookie, equals - cookie);
719 strbuf_addstr(&redacted_header, "=<redacted>");
720 if (semicolon) {
722 * There are more cookies. (Or, for some
723 * reason, the input string ends in "; ".)
725 strbuf_addstr(&redacted_header, "; ");
726 cookie = semicolon + strlen("; ");
727 } else {
728 cookie = NULL;
732 strbuf_setlen(header, sensitive_header - header->buf);
733 strbuf_addbuf(header, &redacted_header);
734 ret = 1;
736 return ret;
739 static int match_curl_h2_trace(const char *line, const char **out)
741 const char *p;
744 * curl prior to 8.1.0 gives us:
746 * h2h3 [<header-name>: <header-val>]
748 * Starting in 8.1.0, the first token became just "h2".
750 if (skip_iprefix(line, "h2h3 [", out) ||
751 skip_iprefix(line, "h2 [", out))
752 return 1;
755 * curl 8.3.0 uses:
756 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
757 * where <stream-id> is numeric.
759 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
760 while (isdigit(*p))
761 p++;
762 if (skip_prefix(p, "] [", out))
763 return 1;
766 return 0;
769 /* Redact headers in info */
770 static void redact_sensitive_info_header(struct strbuf *header)
772 const char *sensitive_header;
774 if (trace_curl_redact &&
775 match_curl_h2_trace(header->buf, &sensitive_header)) {
776 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
777 /* redaction ate our closing bracket */
778 strbuf_addch(header, ']');
783 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
785 struct strbuf out = STRBUF_INIT;
786 struct strbuf **headers, **header;
788 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
789 text, (long)size, (long)size);
790 trace_strbuf(&trace_curl, &out);
791 strbuf_reset(&out);
792 strbuf_add(&out, ptr, size);
793 headers = strbuf_split_max(&out, '\n', 0);
795 for (header = headers; *header; header++) {
796 if (hide_sensitive_header)
797 redact_sensitive_header(*header, 0);
798 strbuf_insertstr((*header), 0, text);
799 strbuf_insertstr((*header), strlen(text), ": ");
800 strbuf_rtrim((*header));
801 strbuf_addch((*header), '\n');
802 trace_strbuf(&trace_curl, (*header));
804 strbuf_list_free(headers);
805 strbuf_release(&out);
808 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
810 size_t i;
811 struct strbuf out = STRBUF_INIT;
812 unsigned int width = 60;
814 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
815 text, (long)size, (long)size);
816 trace_strbuf(&trace_curl, &out);
818 for (i = 0; i < size; i += width) {
819 size_t w;
821 strbuf_reset(&out);
822 strbuf_addf(&out, "%s: ", text);
823 for (w = 0; (w < width) && (i + w < size); w++) {
824 unsigned char ch = ptr[i + w];
826 strbuf_addch(&out,
827 (ch >= 0x20) && (ch < 0x80)
828 ? ch : '.');
830 strbuf_addch(&out, '\n');
831 trace_strbuf(&trace_curl, &out);
833 strbuf_release(&out);
836 static void curl_dump_info(char *data, size_t size)
838 struct strbuf buf = STRBUF_INIT;
840 strbuf_add(&buf, data, size);
842 redact_sensitive_info_header(&buf);
843 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
845 strbuf_release(&buf);
848 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
849 char *data, size_t size,
850 void *userp UNUSED)
852 const char *text;
853 enum { NO_FILTER = 0, DO_FILTER = 1 };
855 switch (type) {
856 case CURLINFO_TEXT:
857 curl_dump_info(data, size);
858 break;
859 case CURLINFO_HEADER_OUT:
860 text = "=> Send header";
861 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
862 break;
863 case CURLINFO_DATA_OUT:
864 if (trace_curl_data) {
865 text = "=> Send data";
866 curl_dump_data(text, (unsigned char *)data, size);
868 break;
869 case CURLINFO_SSL_DATA_OUT:
870 if (trace_curl_data) {
871 text = "=> Send SSL data";
872 curl_dump_data(text, (unsigned char *)data, size);
874 break;
875 case CURLINFO_HEADER_IN:
876 text = "<= Recv header";
877 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
878 break;
879 case CURLINFO_DATA_IN:
880 if (trace_curl_data) {
881 text = "<= Recv data";
882 curl_dump_data(text, (unsigned char *)data, size);
884 break;
885 case CURLINFO_SSL_DATA_IN:
886 if (trace_curl_data) {
887 text = "<= Recv SSL data";
888 curl_dump_data(text, (unsigned char *)data, size);
890 break;
892 default: /* we ignore unknown types by default */
893 return 0;
895 return 0;
898 void http_trace_curl_no_data(void)
900 trace_override_envvar(&trace_curl, "1");
901 trace_curl_data = 0;
904 void setup_curl_trace(CURL *handle)
906 if (!trace_want(&trace_curl))
907 return;
908 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
909 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
910 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
913 static void proto_list_append(struct strbuf *list, const char *proto)
915 if (!list)
916 return;
917 if (list->len)
918 strbuf_addch(list, ',');
919 strbuf_addstr(list, proto);
922 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
924 long bits = 0;
926 if (is_transport_allowed("http", from_user)) {
927 bits |= CURLPROTO_HTTP;
928 proto_list_append(list, "http");
930 if (is_transport_allowed("https", from_user)) {
931 bits |= CURLPROTO_HTTPS;
932 proto_list_append(list, "https");
934 if (is_transport_allowed("ftp", from_user)) {
935 bits |= CURLPROTO_FTP;
936 proto_list_append(list, "ftp");
938 if (is_transport_allowed("ftps", from_user)) {
939 bits |= CURLPROTO_FTPS;
940 proto_list_append(list, "ftps");
943 return bits;
946 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
947 static int get_curl_http_version_opt(const char *version_string, long *opt)
949 int i;
950 static struct {
951 const char *name;
952 long opt_token;
953 } choice[] = {
954 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
955 { "HTTP/2", CURL_HTTP_VERSION_2 }
958 for (i = 0; i < ARRAY_SIZE(choice); i++) {
959 if (!strcmp(version_string, choice[i].name)) {
960 *opt = choice[i].opt_token;
961 return 0;
965 warning("unknown value given to http.version: '%s'", version_string);
966 return -1; /* not found */
969 #endif
971 static CURL *get_curl_handle(void)
973 CURL *result = curl_easy_init();
975 if (!result)
976 die("curl_easy_init failed");
978 if (!curl_ssl_verify) {
979 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
980 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
981 } else {
982 /* Verify authenticity of the peer's certificate */
983 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
984 /* The name in the cert must match whom we tried to connect */
985 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
988 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
989 if (curl_http_version) {
990 long opt;
991 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
992 /* Set request use http version */
993 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
996 #endif
998 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
999 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1001 #ifdef CURLGSSAPI_DELEGATION_FLAG
1002 if (curl_deleg) {
1003 int i;
1004 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1005 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1006 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1007 curl_deleg_levels[i].curl_deleg_param);
1008 break;
1011 if (i == ARRAY_SIZE(curl_deleg_levels))
1012 warning("Unknown delegation method '%s': using default",
1013 curl_deleg);
1015 #endif
1017 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1018 !http_schannel_check_revoke) {
1019 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1020 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1021 #else
1022 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1023 #endif
1026 if (http_proactive_auth)
1027 init_curl_http_auth(result);
1029 if (getenv("GIT_SSL_VERSION"))
1030 ssl_version = getenv("GIT_SSL_VERSION");
1031 if (ssl_version && *ssl_version) {
1032 int i;
1033 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1034 if (!strcmp(ssl_version, sslversions[i].name)) {
1035 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1036 sslversions[i].ssl_version);
1037 break;
1040 if (i == ARRAY_SIZE(sslversions))
1041 warning("unsupported ssl version %s: using default",
1042 ssl_version);
1045 if (getenv("GIT_SSL_CIPHER_LIST"))
1046 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1047 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1048 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1049 ssl_cipherlist);
1051 if (ssl_cert)
1052 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1053 if (ssl_cert_type)
1054 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1055 if (has_cert_password())
1056 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1057 if (ssl_key)
1058 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1059 if (ssl_key_type)
1060 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1061 if (ssl_capath)
1062 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1063 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1064 if (ssl_pinnedkey)
1065 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1066 #endif
1067 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1068 !http_schannel_use_ssl_cainfo) {
1069 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1070 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1071 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1072 #endif
1073 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1074 if (ssl_cainfo)
1075 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1076 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1077 if (http_proxy_ssl_ca_info)
1078 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1079 #endif
1082 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1083 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1084 curl_low_speed_limit);
1085 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1086 curl_low_speed_time);
1089 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1090 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1092 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1094 struct strbuf buf = STRBUF_INIT;
1096 get_curl_allowed_protocols(0, &buf);
1097 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1098 strbuf_reset(&buf);
1100 get_curl_allowed_protocols(-1, &buf);
1101 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1102 strbuf_release(&buf);
1104 #else
1105 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1106 get_curl_allowed_protocols(0, NULL));
1107 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1108 get_curl_allowed_protocols(-1, NULL));
1109 #endif
1111 if (getenv("GIT_CURL_VERBOSE"))
1112 http_trace_curl_no_data();
1113 setup_curl_trace(result);
1114 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1115 trace_curl_data = 0;
1116 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1117 trace_curl_redact = 0;
1119 curl_easy_setopt(result, CURLOPT_USERAGENT,
1120 user_agent ? user_agent : git_user_agent());
1122 if (curl_ftp_no_epsv)
1123 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1125 if (curl_ssl_try)
1126 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1129 * CURL also examines these variables as a fallback; but we need to query
1130 * them here in order to decide whether to prompt for missing password (cf.
1131 * init_curl_proxy_auth()).
1133 * Unlike many other common environment variables, these are historically
1134 * lowercase only. It appears that CURL did not know this and implemented
1135 * only uppercase variants, which was later corrected to take both - with
1136 * the exception of http_proxy, which is lowercase only also in CURL. As
1137 * the lowercase versions are the historical quasi-standard, they take
1138 * precedence here, as in CURL.
1140 if (!curl_http_proxy) {
1141 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1142 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1143 var_override(&curl_http_proxy, getenv("https_proxy"));
1144 } else {
1145 var_override(&curl_http_proxy, getenv("http_proxy"));
1147 if (!curl_http_proxy) {
1148 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1149 var_override(&curl_http_proxy, getenv("all_proxy"));
1153 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1155 * Handle case with the empty http.proxy value here to keep
1156 * common code clean.
1157 * NB: empty option disables proxying at all.
1159 curl_easy_setopt(result, CURLOPT_PROXY, "");
1160 } else if (curl_http_proxy) {
1161 if (starts_with(curl_http_proxy, "socks5h"))
1162 curl_easy_setopt(result,
1163 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1164 else if (starts_with(curl_http_proxy, "socks5"))
1165 curl_easy_setopt(result,
1166 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1167 else if (starts_with(curl_http_proxy, "socks4a"))
1168 curl_easy_setopt(result,
1169 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1170 else if (starts_with(curl_http_proxy, "socks"))
1171 curl_easy_setopt(result,
1172 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1173 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1174 else if (starts_with(curl_http_proxy, "https")) {
1175 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1177 if (http_proxy_ssl_cert)
1178 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1180 if (http_proxy_ssl_key)
1181 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1183 if (has_proxy_cert_password())
1184 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1186 #endif
1187 if (strstr(curl_http_proxy, "://"))
1188 credential_from_url(&proxy_auth, curl_http_proxy);
1189 else {
1190 struct strbuf url = STRBUF_INIT;
1191 strbuf_addf(&url, "http://%s", curl_http_proxy);
1192 credential_from_url(&proxy_auth, url.buf);
1193 strbuf_release(&url);
1196 if (!proxy_auth.host)
1197 die("Invalid proxy URL '%s'", curl_http_proxy);
1199 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1200 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1201 var_override(&curl_no_proxy, getenv("no_proxy"));
1202 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1204 init_curl_proxy_auth(result);
1206 set_curl_keepalive(result);
1208 return result;
1211 static void set_from_env(const char **var, const char *envname)
1213 const char *val = getenv(envname);
1214 if (val)
1215 *var = val;
1218 void http_init(struct remote *remote, const char *url, int proactive_auth)
1220 char *low_speed_limit;
1221 char *low_speed_time;
1222 char *normalized_url;
1223 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1225 config.section = "http";
1226 config.key = NULL;
1227 config.collect_fn = http_options;
1228 config.cascade_fn = git_default_config;
1229 config.cb = NULL;
1231 http_is_verbose = 0;
1232 normalized_url = url_normalize(url, &config.url);
1234 git_config(urlmatch_config_entry, &config);
1235 free(normalized_url);
1236 string_list_clear(&config.vars, 1);
1238 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1239 if (http_ssl_backend) {
1240 const curl_ssl_backend **backends;
1241 struct strbuf buf = STRBUF_INIT;
1242 int i;
1244 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1245 case CURLSSLSET_UNKNOWN_BACKEND:
1246 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1247 "Supported SSL backends:"),
1248 http_ssl_backend);
1249 for (i = 0; backends[i]; i++)
1250 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1251 die("%s", buf.buf);
1252 case CURLSSLSET_NO_BACKENDS:
1253 die(_("Could not set SSL backend to '%s': "
1254 "cURL was built without SSL backends"),
1255 http_ssl_backend);
1256 case CURLSSLSET_TOO_LATE:
1257 die(_("Could not set SSL backend to '%s': already set"),
1258 http_ssl_backend);
1259 case CURLSSLSET_OK:
1260 break; /* Okay! */
1263 #endif
1265 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1266 die("curl_global_init failed");
1268 http_proactive_auth = proactive_auth;
1270 if (remote && remote->http_proxy)
1271 curl_http_proxy = xstrdup(remote->http_proxy);
1273 if (remote)
1274 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1276 pragma_header = curl_slist_append(http_copy_default_headers(),
1277 "Pragma: no-cache");
1278 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1279 "Pragma:");
1282 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1283 if (http_max_requests)
1284 max_requests = atoi(http_max_requests);
1287 curlm = curl_multi_init();
1288 if (!curlm)
1289 die("curl_multi_init failed");
1291 if (getenv("GIT_SSL_NO_VERIFY"))
1292 curl_ssl_verify = 0;
1294 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1295 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1296 set_from_env(&ssl_key, "GIT_SSL_KEY");
1297 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1298 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1299 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1301 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1303 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1304 if (low_speed_limit)
1305 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1306 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1307 if (low_speed_time)
1308 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1310 if (curl_ssl_verify == -1)
1311 curl_ssl_verify = 1;
1313 curl_session_count = 0;
1314 if (max_requests < 1)
1315 max_requests = DEFAULT_MAX_REQUESTS;
1317 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1318 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1319 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1321 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1322 proxy_ssl_cert_password_required = 1;
1324 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1325 curl_ftp_no_epsv = 1;
1327 if (url) {
1328 credential_from_url(&http_auth, url);
1329 if (!ssl_cert_password_required &&
1330 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1331 starts_with(url, "https://"))
1332 ssl_cert_password_required = 1;
1335 curl_default = get_curl_handle();
1338 void http_cleanup(void)
1340 struct active_request_slot *slot = active_queue_head;
1342 while (slot != NULL) {
1343 struct active_request_slot *next = slot->next;
1344 if (slot->curl) {
1345 xmulti_remove_handle(slot);
1346 curl_easy_cleanup(slot->curl);
1348 free(slot);
1349 slot = next;
1351 active_queue_head = NULL;
1353 curl_easy_cleanup(curl_default);
1355 curl_multi_cleanup(curlm);
1356 curl_global_cleanup();
1358 string_list_clear(&extra_http_headers, 0);
1360 curl_slist_free_all(pragma_header);
1361 pragma_header = NULL;
1363 curl_slist_free_all(no_pragma_header);
1364 no_pragma_header = NULL;
1366 curl_slist_free_all(host_resolutions);
1367 host_resolutions = NULL;
1369 if (curl_http_proxy) {
1370 free((void *)curl_http_proxy);
1371 curl_http_proxy = NULL;
1374 if (proxy_auth.password) {
1375 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1376 FREE_AND_NULL(proxy_auth.password);
1379 free((void *)curl_proxyuserpwd);
1380 curl_proxyuserpwd = NULL;
1382 free((void *)http_proxy_authmethod);
1383 http_proxy_authmethod = NULL;
1385 if (cert_auth.password) {
1386 memset(cert_auth.password, 0, strlen(cert_auth.password));
1387 FREE_AND_NULL(cert_auth.password);
1389 ssl_cert_password_required = 0;
1391 if (proxy_cert_auth.password) {
1392 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1393 FREE_AND_NULL(proxy_cert_auth.password);
1395 proxy_ssl_cert_password_required = 0;
1397 FREE_AND_NULL(cached_accept_language);
1400 struct active_request_slot *get_active_slot(void)
1402 struct active_request_slot *slot = active_queue_head;
1403 struct active_request_slot *newslot;
1405 int num_transfers;
1407 /* Wait for a slot to open up if the queue is full */
1408 while (active_requests >= max_requests) {
1409 curl_multi_perform(curlm, &num_transfers);
1410 if (num_transfers < active_requests)
1411 process_curl_messages();
1414 while (slot != NULL && slot->in_use)
1415 slot = slot->next;
1417 if (!slot) {
1418 newslot = xmalloc(sizeof(*newslot));
1419 newslot->curl = NULL;
1420 newslot->in_use = 0;
1421 newslot->next = NULL;
1423 slot = active_queue_head;
1424 if (!slot) {
1425 active_queue_head = newslot;
1426 } else {
1427 while (slot->next != NULL)
1428 slot = slot->next;
1429 slot->next = newslot;
1431 slot = newslot;
1434 if (!slot->curl) {
1435 slot->curl = curl_easy_duphandle(curl_default);
1436 curl_session_count++;
1439 active_requests++;
1440 slot->in_use = 1;
1441 slot->results = NULL;
1442 slot->finished = NULL;
1443 slot->callback_data = NULL;
1444 slot->callback_func = NULL;
1445 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1446 if (curl_save_cookies)
1447 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1448 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1449 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1450 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1451 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1452 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1453 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1454 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1455 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1456 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1457 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1458 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1461 * Default following to off unless "ALWAYS" is configured; this gives
1462 * callers a sane starting point, and they can tweak for individual
1463 * HTTP_FOLLOW_* cases themselves.
1465 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1466 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1467 else
1468 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1470 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1471 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1472 if (http_auth.password || curl_empty_auth_enabled())
1473 init_curl_http_auth(slot->curl);
1475 return slot;
1478 int start_active_slot(struct active_request_slot *slot)
1480 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1481 int num_transfers;
1483 if (curlm_result != CURLM_OK &&
1484 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1485 warning("curl_multi_add_handle failed: %s",
1486 curl_multi_strerror(curlm_result));
1487 active_requests--;
1488 slot->in_use = 0;
1489 return 0;
1493 * We know there must be something to do, since we just added
1494 * something.
1496 curl_multi_perform(curlm, &num_transfers);
1497 return 1;
1500 struct fill_chain {
1501 void *data;
1502 int (*fill)(void *);
1503 struct fill_chain *next;
1506 static struct fill_chain *fill_cfg;
1508 void add_fill_function(void *data, int (*fill)(void *))
1510 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1511 struct fill_chain **linkp = &fill_cfg;
1512 new_fill->data = data;
1513 new_fill->fill = fill;
1514 new_fill->next = NULL;
1515 while (*linkp)
1516 linkp = &(*linkp)->next;
1517 *linkp = new_fill;
1520 void fill_active_slots(void)
1522 struct active_request_slot *slot = active_queue_head;
1524 while (active_requests < max_requests) {
1525 struct fill_chain *fill;
1526 for (fill = fill_cfg; fill; fill = fill->next)
1527 if (fill->fill(fill->data))
1528 break;
1530 if (!fill)
1531 break;
1534 while (slot != NULL) {
1535 if (!slot->in_use && slot->curl != NULL
1536 && curl_session_count > min_curl_sessions) {
1537 curl_easy_cleanup(slot->curl);
1538 slot->curl = NULL;
1539 curl_session_count--;
1541 slot = slot->next;
1545 void step_active_slots(void)
1547 int num_transfers;
1548 CURLMcode curlm_result;
1550 do {
1551 curlm_result = curl_multi_perform(curlm, &num_transfers);
1552 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1553 if (num_transfers < active_requests) {
1554 process_curl_messages();
1555 fill_active_slots();
1559 void run_active_slot(struct active_request_slot *slot)
1561 fd_set readfds;
1562 fd_set writefds;
1563 fd_set excfds;
1564 int max_fd;
1565 struct timeval select_timeout;
1566 int finished = 0;
1568 slot->finished = &finished;
1569 while (!finished) {
1570 step_active_slots();
1572 if (slot->in_use) {
1573 long curl_timeout;
1574 curl_multi_timeout(curlm, &curl_timeout);
1575 if (curl_timeout == 0) {
1576 continue;
1577 } else if (curl_timeout == -1) {
1578 select_timeout.tv_sec = 0;
1579 select_timeout.tv_usec = 50000;
1580 } else {
1581 select_timeout.tv_sec = curl_timeout / 1000;
1582 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1585 max_fd = -1;
1586 FD_ZERO(&readfds);
1587 FD_ZERO(&writefds);
1588 FD_ZERO(&excfds);
1589 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1592 * It can happen that curl_multi_timeout returns a pathologically
1593 * long timeout when curl_multi_fdset returns no file descriptors
1594 * to read. See commit message for more details.
1596 if (max_fd < 0 &&
1597 (select_timeout.tv_sec > 0 ||
1598 select_timeout.tv_usec > 50000)) {
1599 select_timeout.tv_sec = 0;
1600 select_timeout.tv_usec = 50000;
1603 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1608 * The value of slot->finished we set before the loop was used
1609 * to set our "finished" variable when our request completed.
1611 * 1. The slot may not have been reused for another requst
1612 * yet, in which case it still has &finished.
1614 * 2. The slot may already be in-use to serve another request,
1615 * which can further be divided into two cases:
1617 * (a) If call run_active_slot() hasn't been called for that
1618 * other request, slot->finished would have been cleared
1619 * by get_active_slot() and has NULL.
1621 * (b) If the request did call run_active_slot(), then the
1622 * call would have updated slot->finished at the beginning
1623 * of this function, and with the clearing of the member
1624 * below, we would find that slot->finished is now NULL.
1626 * In all cases, slot->finished has no useful information to
1627 * anybody at this point. Some compilers warn us for
1628 * attempting to smuggle a pointer that is about to become
1629 * invalid, i.e. &finished. We clear it here to assure them.
1631 slot->finished = NULL;
1634 static void release_active_slot(struct active_request_slot *slot)
1636 closedown_active_slot(slot);
1637 if (slot->curl) {
1638 xmulti_remove_handle(slot);
1639 if (curl_session_count > min_curl_sessions) {
1640 curl_easy_cleanup(slot->curl);
1641 slot->curl = NULL;
1642 curl_session_count--;
1645 fill_active_slots();
1648 void finish_all_active_slots(void)
1650 struct active_request_slot *slot = active_queue_head;
1652 while (slot != NULL)
1653 if (slot->in_use) {
1654 run_active_slot(slot);
1655 slot = active_queue_head;
1656 } else {
1657 slot = slot->next;
1661 /* Helpers for modifying and creating URLs */
1662 static inline int needs_quote(int ch)
1664 if (((ch >= 'A') && (ch <= 'Z'))
1665 || ((ch >= 'a') && (ch <= 'z'))
1666 || ((ch >= '0') && (ch <= '9'))
1667 || (ch == '/')
1668 || (ch == '-')
1669 || (ch == '.'))
1670 return 0;
1671 return 1;
1674 static char *quote_ref_url(const char *base, const char *ref)
1676 struct strbuf buf = STRBUF_INIT;
1677 const char *cp;
1678 int ch;
1680 end_url_with_slash(&buf, base);
1682 for (cp = ref; (ch = *cp) != 0; cp++)
1683 if (needs_quote(ch))
1684 strbuf_addf(&buf, "%%%02x", ch);
1685 else
1686 strbuf_addch(&buf, *cp);
1688 return strbuf_detach(&buf, NULL);
1691 void append_remote_object_url(struct strbuf *buf, const char *url,
1692 const char *hex,
1693 int only_two_digit_prefix)
1695 end_url_with_slash(buf, url);
1697 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1698 if (!only_two_digit_prefix)
1699 strbuf_addstr(buf, hex + 2);
1702 char *get_remote_object_url(const char *url, const char *hex,
1703 int only_two_digit_prefix)
1705 struct strbuf buf = STRBUF_INIT;
1706 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1707 return strbuf_detach(&buf, NULL);
1710 void normalize_curl_result(CURLcode *result, long http_code,
1711 char *errorstr, size_t errorlen)
1714 * If we see a failing http code with CURLE_OK, we have turned off
1715 * FAILONERROR (to keep the server's custom error response), and should
1716 * translate the code into failure here.
1718 * Likewise, if we see a redirect (30x code), that means we turned off
1719 * redirect-following, and we should treat the result as an error.
1721 if (*result == CURLE_OK && http_code >= 300) {
1722 *result = CURLE_HTTP_RETURNED_ERROR;
1724 * Normally curl will already have put the "reason phrase"
1725 * from the server into curl_errorstr; unfortunately without
1726 * FAILONERROR it is lost, so we can give only the numeric
1727 * status code.
1729 xsnprintf(errorstr, errorlen,
1730 "The requested URL returned error: %ld",
1731 http_code);
1735 static int handle_curl_result(struct slot_results *results)
1737 normalize_curl_result(&results->curl_result, results->http_code,
1738 curl_errorstr, sizeof(curl_errorstr));
1740 if (results->curl_result == CURLE_OK) {
1741 credential_approve(&http_auth);
1742 credential_approve(&proxy_auth);
1743 credential_approve(&cert_auth);
1744 return HTTP_OK;
1745 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1747 * We can't tell from here whether it's a bad path, bad
1748 * certificate, bad password, or something else wrong
1749 * with the certificate. So we reject the credential to
1750 * avoid caching or saving a bad password.
1752 credential_reject(&cert_auth);
1753 return HTTP_NOAUTH;
1754 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1755 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1756 return HTTP_NOMATCHPUBLICKEY;
1757 #endif
1758 } else if (missing_target(results))
1759 return HTTP_MISSING_TARGET;
1760 else if (results->http_code == 401) {
1761 if (http_auth.username && http_auth.password) {
1762 credential_reject(&http_auth);
1763 return HTTP_NOAUTH;
1764 } else {
1765 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1766 if (results->auth_avail) {
1767 http_auth_methods &= results->auth_avail;
1768 http_auth_methods_restricted = 1;
1770 return HTTP_REAUTH;
1772 } else {
1773 if (results->http_connectcode == 407)
1774 credential_reject(&proxy_auth);
1775 if (!curl_errorstr[0])
1776 strlcpy(curl_errorstr,
1777 curl_easy_strerror(results->curl_result),
1778 sizeof(curl_errorstr));
1779 return HTTP_ERROR;
1783 int run_one_slot(struct active_request_slot *slot,
1784 struct slot_results *results)
1786 slot->results = results;
1787 if (!start_active_slot(slot)) {
1788 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1789 "failed to start HTTP request");
1790 return HTTP_START_FAILED;
1793 run_active_slot(slot);
1794 return handle_curl_result(results);
1797 struct curl_slist *http_copy_default_headers(void)
1799 struct curl_slist *headers = NULL;
1800 const struct string_list_item *item;
1802 for_each_string_list_item(item, &extra_http_headers)
1803 headers = curl_slist_append(headers, item->string);
1805 return headers;
1808 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1810 char *ptr;
1811 CURLcode ret;
1813 strbuf_reset(buf);
1814 ret = curl_easy_getinfo(curl, info, &ptr);
1815 if (!ret && ptr)
1816 strbuf_addstr(buf, ptr);
1817 return ret;
1821 * Check for and extract a content-type parameter. "raw"
1822 * should be positioned at the start of the potential
1823 * parameter, with any whitespace already removed.
1825 * "name" is the name of the parameter. The value is appended
1826 * to "out".
1828 static int extract_param(const char *raw, const char *name,
1829 struct strbuf *out)
1831 size_t len = strlen(name);
1833 if (strncasecmp(raw, name, len))
1834 return -1;
1835 raw += len;
1837 if (*raw != '=')
1838 return -1;
1839 raw++;
1841 while (*raw && !isspace(*raw) && *raw != ';')
1842 strbuf_addch(out, *raw++);
1843 return 0;
1847 * Extract a normalized version of the content type, with any
1848 * spaces suppressed, all letters lowercased, and no trailing ";"
1849 * or parameters.
1851 * Note that we will silently remove even invalid whitespace. For
1852 * example, "text / plain" is specifically forbidden by RFC 2616,
1853 * but "text/plain" is the only reasonable output, and this keeps
1854 * our code simple.
1856 * If the "charset" argument is not NULL, store the value of any
1857 * charset parameter there.
1859 * Example:
1860 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1861 * "text / plain" -> "text/plain"
1863 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1864 struct strbuf *charset)
1866 const char *p;
1868 strbuf_reset(type);
1869 strbuf_grow(type, raw->len);
1870 for (p = raw->buf; *p; p++) {
1871 if (isspace(*p))
1872 continue;
1873 if (*p == ';') {
1874 p++;
1875 break;
1877 strbuf_addch(type, tolower(*p));
1880 if (!charset)
1881 return;
1883 strbuf_reset(charset);
1884 while (*p) {
1885 while (isspace(*p) || *p == ';')
1886 p++;
1887 if (!extract_param(p, "charset", charset))
1888 return;
1889 while (*p && !isspace(*p))
1890 p++;
1893 if (!charset->len && starts_with(type->buf, "text/"))
1894 strbuf_addstr(charset, "ISO-8859-1");
1897 static void write_accept_language(struct strbuf *buf)
1900 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1901 * that, q-value will be smaller than 0.001, the minimum q-value the
1902 * HTTP specification allows. See
1903 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
1905 const int MAX_DECIMAL_PLACES = 3;
1906 const int MAX_LANGUAGE_TAGS = 1000;
1907 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1908 char **language_tags = NULL;
1909 int num_langs = 0;
1910 const char *s = get_preferred_languages();
1911 int i;
1912 struct strbuf tag = STRBUF_INIT;
1914 /* Don't add Accept-Language header if no language is preferred. */
1915 if (!s)
1916 return;
1919 * Split the colon-separated string of preferred languages into
1920 * language_tags array.
1922 do {
1923 /* collect language tag */
1924 for (; *s && (isalnum(*s) || *s == '_'); s++)
1925 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1927 /* skip .codeset, @modifier and any other unnecessary parts */
1928 while (*s && *s != ':')
1929 s++;
1931 if (tag.len) {
1932 num_langs++;
1933 REALLOC_ARRAY(language_tags, num_langs);
1934 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1935 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1936 break;
1938 } while (*s++);
1940 /* write Accept-Language header into buf */
1941 if (num_langs) {
1942 int last_buf_len = 0;
1943 int max_q;
1944 int decimal_places;
1945 char q_format[32];
1947 /* add '*' */
1948 REALLOC_ARRAY(language_tags, num_langs + 1);
1949 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1951 /* compute decimal_places */
1952 for (max_q = 1, decimal_places = 0;
1953 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1954 decimal_places++, max_q *= 10)
1957 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1959 strbuf_addstr(buf, "Accept-Language: ");
1961 for (i = 0; i < num_langs; i++) {
1962 if (i > 0)
1963 strbuf_addstr(buf, ", ");
1965 strbuf_addstr(buf, language_tags[i]);
1967 if (i > 0)
1968 strbuf_addf(buf, q_format, max_q - i);
1970 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1971 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1972 break;
1975 last_buf_len = buf->len;
1979 /* free language tags -- last one is a static '*' */
1980 for (i = 0; i < num_langs - 1; i++)
1981 free(language_tags[i]);
1982 free(language_tags);
1986 * Get an Accept-Language header which indicates user's preferred languages.
1988 * Examples:
1989 * LANGUAGE= -> ""
1990 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1991 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1992 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1993 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1994 * LANGUAGE= LANG=C -> ""
1996 const char *http_get_accept_language_header(void)
1998 if (!cached_accept_language) {
1999 struct strbuf buf = STRBUF_INIT;
2000 write_accept_language(&buf);
2001 if (buf.len > 0)
2002 cached_accept_language = strbuf_detach(&buf, NULL);
2005 return cached_accept_language;
2008 static void http_opt_request_remainder(CURL *curl, off_t pos)
2010 char buf[128];
2011 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2012 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2015 /* http_request() targets */
2016 #define HTTP_REQUEST_STRBUF 0
2017 #define HTTP_REQUEST_FILE 1
2019 static int http_request(const char *url,
2020 void *result, int target,
2021 const struct http_get_options *options)
2023 struct active_request_slot *slot;
2024 struct slot_results results;
2025 struct curl_slist *headers = http_copy_default_headers();
2026 struct strbuf buf = STRBUF_INIT;
2027 const char *accept_language;
2028 int ret;
2030 slot = get_active_slot();
2031 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2033 if (!result) {
2034 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2035 } else {
2036 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2037 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2039 if (target == HTTP_REQUEST_FILE) {
2040 off_t posn = ftello(result);
2041 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2042 fwrite);
2043 if (posn > 0)
2044 http_opt_request_remainder(slot->curl, posn);
2045 } else
2046 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2047 fwrite_buffer);
2050 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2052 accept_language = http_get_accept_language_header();
2054 if (accept_language)
2055 headers = curl_slist_append(headers, accept_language);
2057 strbuf_addstr(&buf, "Pragma:");
2058 if (options && options->no_cache)
2059 strbuf_addstr(&buf, " no-cache");
2060 if (options && options->initial_request &&
2061 http_follow_config == HTTP_FOLLOW_INITIAL)
2062 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2064 headers = curl_slist_append(headers, buf.buf);
2066 /* Add additional headers here */
2067 if (options && options->extra_headers) {
2068 const struct string_list_item *item;
2069 for_each_string_list_item(item, options->extra_headers) {
2070 headers = curl_slist_append(headers, item->string);
2074 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2075 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2076 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2077 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2079 ret = run_one_slot(slot, &results);
2081 if (options && options->content_type) {
2082 struct strbuf raw = STRBUF_INIT;
2083 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2084 extract_content_type(&raw, options->content_type,
2085 options->charset);
2086 strbuf_release(&raw);
2089 if (options && options->effective_url)
2090 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2091 options->effective_url);
2093 curl_slist_free_all(headers);
2094 strbuf_release(&buf);
2096 return ret;
2100 * Update the "base" url to a more appropriate value, as deduced by
2101 * redirects seen when requesting a URL starting with "url".
2103 * The "asked" parameter is a URL that we asked curl to access, and must begin
2104 * with "base".
2106 * The "got" parameter is the URL that curl reported to us as where we ended
2107 * up.
2109 * Returns 1 if we updated the base url, 0 otherwise.
2111 * Our basic strategy is to compare "base" and "asked" to find the bits
2112 * specific to our request. We then strip those bits off of "got" to yield the
2113 * new base. So for example, if our base is "http://example.com/foo.git",
2114 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2115 * with "https://other.example.com/foo.git/info/refs". We would want the
2116 * new URL to become "https://other.example.com/foo.git".
2118 * Note that this assumes a sane redirect scheme. It's entirely possible
2119 * in the example above to end up at a URL that does not even end in
2120 * "info/refs". In such a case we die. There's not much we can do, such a
2121 * scheme is unlikely to represent a real git repository, and failing to
2122 * rewrite the base opens options for malicious redirects to do funny things.
2124 static int update_url_from_redirect(struct strbuf *base,
2125 const char *asked,
2126 const struct strbuf *got)
2128 const char *tail;
2129 size_t new_len;
2131 if (!strcmp(asked, got->buf))
2132 return 0;
2134 if (!skip_prefix(asked, base->buf, &tail))
2135 BUG("update_url_from_redirect: %s is not a superset of %s",
2136 asked, base->buf);
2138 new_len = got->len;
2139 if (!strip_suffix_mem(got->buf, &new_len, tail))
2140 die(_("unable to update url base from redirection:\n"
2141 " asked for: %s\n"
2142 " redirect: %s"),
2143 asked, got->buf);
2145 strbuf_reset(base);
2146 strbuf_add(base, got->buf, new_len);
2148 return 1;
2151 static int http_request_reauth(const char *url,
2152 void *result, int target,
2153 struct http_get_options *options)
2155 int ret = http_request(url, result, target, options);
2157 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2158 return ret;
2160 if (options && options->effective_url && options->base_url) {
2161 if (update_url_from_redirect(options->base_url,
2162 url, options->effective_url)) {
2163 credential_from_url(&http_auth, options->base_url->buf);
2164 url = options->effective_url->buf;
2168 if (ret != HTTP_REAUTH)
2169 return ret;
2172 * The previous request may have put cruft into our output stream; we
2173 * should clear it out before making our next request.
2175 switch (target) {
2176 case HTTP_REQUEST_STRBUF:
2177 strbuf_reset(result);
2178 break;
2179 case HTTP_REQUEST_FILE:
2180 if (fflush(result)) {
2181 error_errno("unable to flush a file");
2182 return HTTP_START_FAILED;
2184 rewind(result);
2185 if (ftruncate(fileno(result), 0) < 0) {
2186 error_errno("unable to truncate a file");
2187 return HTTP_START_FAILED;
2189 break;
2190 default:
2191 BUG("Unknown http_request target");
2194 credential_fill(&http_auth);
2196 return http_request(url, result, target, options);
2199 int http_get_strbuf(const char *url,
2200 struct strbuf *result,
2201 struct http_get_options *options)
2203 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2207 * Downloads a URL and stores the result in the given file.
2209 * If a previous interrupted download is detected (i.e. a previous temporary
2210 * file is still around) the download is resumed.
2212 int http_get_file(const char *url, const char *filename,
2213 struct http_get_options *options)
2215 int ret;
2216 struct strbuf tmpfile = STRBUF_INIT;
2217 FILE *result;
2219 strbuf_addf(&tmpfile, "%s.temp", filename);
2220 result = fopen(tmpfile.buf, "a");
2221 if (!result) {
2222 error("Unable to open local file %s", tmpfile.buf);
2223 ret = HTTP_ERROR;
2224 goto cleanup;
2227 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2228 fclose(result);
2230 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2231 ret = HTTP_ERROR;
2232 cleanup:
2233 strbuf_release(&tmpfile);
2234 return ret;
2237 int http_fetch_ref(const char *base, struct ref *ref)
2239 struct http_get_options options = {0};
2240 char *url;
2241 struct strbuf buffer = STRBUF_INIT;
2242 int ret = -1;
2244 options.no_cache = 1;
2246 url = quote_ref_url(base, ref->name);
2247 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2248 strbuf_rtrim(&buffer);
2249 if (buffer.len == the_hash_algo->hexsz)
2250 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2251 else if (starts_with(buffer.buf, "ref: ")) {
2252 ref->symref = xstrdup(buffer.buf + 5);
2253 ret = 0;
2257 strbuf_release(&buffer);
2258 free(url);
2259 return ret;
2262 /* Helpers for fetching packs */
2263 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2265 char *url, *tmp;
2266 struct strbuf buf = STRBUF_INIT;
2268 if (http_is_verbose)
2269 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2271 end_url_with_slash(&buf, base_url);
2272 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2273 url = strbuf_detach(&buf, NULL);
2275 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2276 tmp = strbuf_detach(&buf, NULL);
2278 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2279 error("Unable to get pack index %s", url);
2280 FREE_AND_NULL(tmp);
2283 free(url);
2284 return tmp;
2287 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2288 unsigned char *sha1, const char *base_url)
2290 struct packed_git *new_pack;
2291 char *tmp_idx = NULL;
2292 int ret;
2294 if (has_pack_index(sha1)) {
2295 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2296 if (!new_pack)
2297 return -1; /* parse_pack_index() already issued error message */
2298 goto add_pack;
2301 tmp_idx = fetch_pack_index(sha1, base_url);
2302 if (!tmp_idx)
2303 return -1;
2305 new_pack = parse_pack_index(sha1, tmp_idx);
2306 if (!new_pack) {
2307 unlink(tmp_idx);
2308 free(tmp_idx);
2310 return -1; /* parse_pack_index() already issued error message */
2313 ret = verify_pack_index(new_pack);
2314 if (!ret) {
2315 close_pack_index(new_pack);
2316 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2318 free(tmp_idx);
2319 if (ret)
2320 return -1;
2322 add_pack:
2323 new_pack->next = *packs_head;
2324 *packs_head = new_pack;
2325 return 0;
2328 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2330 struct http_get_options options = {0};
2331 int ret = 0;
2332 char *url;
2333 const char *data;
2334 struct strbuf buf = STRBUF_INIT;
2335 struct object_id oid;
2337 end_url_with_slash(&buf, base_url);
2338 strbuf_addstr(&buf, "objects/info/packs");
2339 url = strbuf_detach(&buf, NULL);
2341 options.no_cache = 1;
2342 ret = http_get_strbuf(url, &buf, &options);
2343 if (ret != HTTP_OK)
2344 goto cleanup;
2346 data = buf.buf;
2347 while (*data) {
2348 if (skip_prefix(data, "P pack-", &data) &&
2349 !parse_oid_hex(data, &oid, &data) &&
2350 skip_prefix(data, ".pack", &data) &&
2351 (*data == '\n' || *data == '\0')) {
2352 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2353 } else {
2354 data = strchrnul(data, '\n');
2356 if (*data)
2357 data++; /* skip past newline */
2360 cleanup:
2361 free(url);
2362 return ret;
2365 void release_http_pack_request(struct http_pack_request *preq)
2367 if (preq->packfile) {
2368 fclose(preq->packfile);
2369 preq->packfile = NULL;
2371 preq->slot = NULL;
2372 strbuf_release(&preq->tmpfile);
2373 free(preq->url);
2374 free(preq);
2377 static const char *default_index_pack_args[] =
2378 {"index-pack", "--stdin", NULL};
2380 int finish_http_pack_request(struct http_pack_request *preq)
2382 struct child_process ip = CHILD_PROCESS_INIT;
2383 int tmpfile_fd;
2384 int ret = 0;
2386 fclose(preq->packfile);
2387 preq->packfile = NULL;
2389 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2391 ip.git_cmd = 1;
2392 ip.in = tmpfile_fd;
2393 strvec_pushv(&ip.args, preq->index_pack_args ?
2394 preq->index_pack_args :
2395 default_index_pack_args);
2397 if (preq->preserve_index_pack_stdout)
2398 ip.out = 0;
2399 else
2400 ip.no_stdout = 1;
2402 if (run_command(&ip)) {
2403 ret = -1;
2404 goto cleanup;
2407 cleanup:
2408 close(tmpfile_fd);
2409 unlink(preq->tmpfile.buf);
2410 return ret;
2413 void http_install_packfile(struct packed_git *p,
2414 struct packed_git **list_to_remove_from)
2416 struct packed_git **lst = list_to_remove_from;
2418 while (*lst != p)
2419 lst = &((*lst)->next);
2420 *lst = (*lst)->next;
2422 install_packed_git(the_repository, p);
2425 struct http_pack_request *new_http_pack_request(
2426 const unsigned char *packed_git_hash, const char *base_url) {
2428 struct strbuf buf = STRBUF_INIT;
2430 end_url_with_slash(&buf, base_url);
2431 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2432 hash_to_hex(packed_git_hash));
2433 return new_direct_http_pack_request(packed_git_hash,
2434 strbuf_detach(&buf, NULL));
2437 struct http_pack_request *new_direct_http_pack_request(
2438 const unsigned char *packed_git_hash, char *url)
2440 off_t prev_posn = 0;
2441 struct http_pack_request *preq;
2443 CALLOC_ARRAY(preq, 1);
2444 strbuf_init(&preq->tmpfile, 0);
2446 preq->url = url;
2448 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2449 preq->packfile = fopen(preq->tmpfile.buf, "a");
2450 if (!preq->packfile) {
2451 error("Unable to open local file %s for pack",
2452 preq->tmpfile.buf);
2453 goto abort;
2456 preq->slot = get_active_slot();
2457 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2458 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2459 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2460 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2461 no_pragma_header);
2464 * If there is data present from a previous transfer attempt,
2465 * resume where it left off
2467 prev_posn = ftello(preq->packfile);
2468 if (prev_posn>0) {
2469 if (http_is_verbose)
2470 fprintf(stderr,
2471 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2472 hash_to_hex(packed_git_hash),
2473 (uintmax_t)prev_posn);
2474 http_opt_request_remainder(preq->slot->curl, prev_posn);
2477 return preq;
2479 abort:
2480 strbuf_release(&preq->tmpfile);
2481 free(preq->url);
2482 free(preq);
2483 return NULL;
2486 /* Helpers for fetching objects (loose) */
2487 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2488 void *data)
2490 unsigned char expn[4096];
2491 size_t size = eltsize * nmemb;
2492 int posn = 0;
2493 struct http_object_request *freq = data;
2494 struct active_request_slot *slot = freq->slot;
2496 if (slot) {
2497 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2498 &slot->http_code);
2499 if (c != CURLE_OK)
2500 BUG("curl_easy_getinfo for HTTP code failed: %s",
2501 curl_easy_strerror(c));
2502 if (slot->http_code >= 300)
2503 return nmemb;
2506 do {
2507 ssize_t retval = xwrite(freq->localfile,
2508 (char *) ptr + posn, size - posn);
2509 if (retval < 0)
2510 return posn / eltsize;
2511 posn += retval;
2512 } while (posn < size);
2514 freq->stream.avail_in = size;
2515 freq->stream.next_in = (void *)ptr;
2516 do {
2517 freq->stream.next_out = expn;
2518 freq->stream.avail_out = sizeof(expn);
2519 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2520 the_hash_algo->update_fn(&freq->c, expn,
2521 sizeof(expn) - freq->stream.avail_out);
2522 } while (freq->stream.avail_in && freq->zret == Z_OK);
2523 return nmemb;
2526 struct http_object_request *new_http_object_request(const char *base_url,
2527 const struct object_id *oid)
2529 char *hex = oid_to_hex(oid);
2530 struct strbuf filename = STRBUF_INIT;
2531 struct strbuf prevfile = STRBUF_INIT;
2532 int prevlocal;
2533 char prev_buf[PREV_BUF_SIZE];
2534 ssize_t prev_read = 0;
2535 off_t prev_posn = 0;
2536 struct http_object_request *freq;
2538 CALLOC_ARRAY(freq, 1);
2539 strbuf_init(&freq->tmpfile, 0);
2540 oidcpy(&freq->oid, oid);
2541 freq->localfile = -1;
2543 loose_object_path(the_repository, &filename, oid);
2544 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2546 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2547 unlink_or_warn(prevfile.buf);
2548 rename(freq->tmpfile.buf, prevfile.buf);
2549 unlink_or_warn(freq->tmpfile.buf);
2550 strbuf_release(&filename);
2552 if (freq->localfile != -1)
2553 error("fd leakage in start: %d", freq->localfile);
2554 freq->localfile = open(freq->tmpfile.buf,
2555 O_WRONLY | O_CREAT | O_EXCL, 0666);
2557 * This could have failed due to the "lazy directory creation";
2558 * try to mkdir the last path component.
2560 if (freq->localfile < 0 && errno == ENOENT) {
2561 char *dir = strrchr(freq->tmpfile.buf, '/');
2562 if (dir) {
2563 *dir = 0;
2564 mkdir(freq->tmpfile.buf, 0777);
2565 *dir = '/';
2567 freq->localfile = open(freq->tmpfile.buf,
2568 O_WRONLY | O_CREAT | O_EXCL, 0666);
2571 if (freq->localfile < 0) {
2572 error_errno("Couldn't create temporary file %s",
2573 freq->tmpfile.buf);
2574 goto abort;
2577 git_inflate_init(&freq->stream);
2579 the_hash_algo->init_fn(&freq->c);
2581 freq->url = get_remote_object_url(base_url, hex, 0);
2584 * If a previous temp file is present, process what was already
2585 * fetched.
2587 prevlocal = open(prevfile.buf, O_RDONLY);
2588 if (prevlocal != -1) {
2589 do {
2590 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2591 if (prev_read>0) {
2592 if (fwrite_sha1_file(prev_buf,
2594 prev_read,
2595 freq) == prev_read) {
2596 prev_posn += prev_read;
2597 } else {
2598 prev_read = -1;
2601 } while (prev_read > 0);
2602 close(prevlocal);
2604 unlink_or_warn(prevfile.buf);
2605 strbuf_release(&prevfile);
2608 * Reset inflate/SHA1 if there was an error reading the previous temp
2609 * file; also rewind to the beginning of the local file.
2611 if (prev_read == -1) {
2612 memset(&freq->stream, 0, sizeof(freq->stream));
2613 git_inflate_init(&freq->stream);
2614 the_hash_algo->init_fn(&freq->c);
2615 if (prev_posn>0) {
2616 prev_posn = 0;
2617 lseek(freq->localfile, 0, SEEK_SET);
2618 if (ftruncate(freq->localfile, 0) < 0) {
2619 error_errno("Couldn't truncate temporary file %s",
2620 freq->tmpfile.buf);
2621 goto abort;
2626 freq->slot = get_active_slot();
2628 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2629 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2630 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2631 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2632 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2633 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2636 * If we have successfully processed data from a previous fetch
2637 * attempt, only fetch the data we don't already have.
2639 if (prev_posn>0) {
2640 if (http_is_verbose)
2641 fprintf(stderr,
2642 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2643 hex, (uintmax_t)prev_posn);
2644 http_opt_request_remainder(freq->slot->curl, prev_posn);
2647 return freq;
2649 abort:
2650 strbuf_release(&prevfile);
2651 free(freq->url);
2652 free(freq);
2653 return NULL;
2656 void process_http_object_request(struct http_object_request *freq)
2658 if (!freq->slot)
2659 return;
2660 freq->curl_result = freq->slot->curl_result;
2661 freq->http_code = freq->slot->http_code;
2662 freq->slot = NULL;
2665 int finish_http_object_request(struct http_object_request *freq)
2667 struct stat st;
2668 struct strbuf filename = STRBUF_INIT;
2670 close(freq->localfile);
2671 freq->localfile = -1;
2673 process_http_object_request(freq);
2675 if (freq->http_code == 416) {
2676 warning("requested range invalid; we may already have all the data.");
2677 } else if (freq->curl_result != CURLE_OK) {
2678 if (stat(freq->tmpfile.buf, &st) == 0)
2679 if (st.st_size == 0)
2680 unlink_or_warn(freq->tmpfile.buf);
2681 return -1;
2684 git_inflate_end(&freq->stream);
2685 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2686 if (freq->zret != Z_STREAM_END) {
2687 unlink_or_warn(freq->tmpfile.buf);
2688 return -1;
2690 if (!oideq(&freq->oid, &freq->real_oid)) {
2691 unlink_or_warn(freq->tmpfile.buf);
2692 return -1;
2694 loose_object_path(the_repository, &filename, &freq->oid);
2695 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2696 strbuf_release(&filename);
2698 return freq->rename;
2701 void abort_http_object_request(struct http_object_request *freq)
2703 unlink_or_warn(freq->tmpfile.buf);
2705 release_http_object_request(freq);
2708 void release_http_object_request(struct http_object_request *freq)
2710 if (freq->localfile != -1) {
2711 close(freq->localfile);
2712 freq->localfile = -1;
2714 FREE_AND_NULL(freq->url);
2715 if (freq->slot) {
2716 freq->slot->callback_func = NULL;
2717 freq->slot->callback_data = NULL;
2718 release_active_slot(freq->slot);
2719 freq->slot = NULL;
2721 strbuf_release(&freq->tmpfile);