Merge branch 'jk/test-lsan-improvements'
[git/gitster.git] / http.c
blobd59e59f66b12b62e187f4a9bbacfca2d31d658f9
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "git-curl-compat.h"
5 #include "hex.h"
6 #include "http.h"
7 #include "config.h"
8 #include "pack.h"
9 #include "run-command.h"
10 #include "url.h"
11 #include "urlmatch.h"
12 #include "credential.h"
13 #include "version.h"
14 #include "pkt-line.h"
15 #include "gettext.h"
16 #include "trace.h"
17 #include "transport.h"
18 #include "packfile.h"
19 #include "string-list.h"
20 #include "object-file.h"
21 #include "object-store-ll.h"
23 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
24 static int trace_curl_data = 1;
25 static int trace_curl_redact = 1;
26 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
27 int active_requests;
28 int http_is_verbose;
29 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
31 static int min_curl_sessions = 1;
32 static int curl_session_count;
33 static int max_requests = -1;
34 static CURLM *curlm;
35 static CURL *curl_default;
37 #define PREV_BUF_SIZE 4096
39 char curl_errorstr[CURL_ERROR_SIZE];
41 static int curl_ssl_verify = -1;
42 static int curl_ssl_try;
43 static char *curl_http_version;
44 static char *ssl_cert;
45 static char *ssl_cert_type;
46 static char *ssl_cipherlist;
47 static char *ssl_version;
48 static struct {
49 const char *name;
50 long ssl_version;
51 } sslversions[] = {
52 { "sslv2", CURL_SSLVERSION_SSLv2 },
53 { "sslv3", CURL_SSLVERSION_SSLv3 },
54 { "tlsv1", CURL_SSLVERSION_TLSv1 },
55 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
56 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
57 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
58 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
59 #endif
60 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
61 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
62 #endif
64 static char *ssl_key;
65 static char *ssl_key_type;
66 static char *ssl_capath;
67 static char *curl_no_proxy;
68 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
69 static char *ssl_pinnedkey;
70 #endif
71 static char *ssl_cainfo;
72 static long curl_low_speed_limit = -1;
73 static long curl_low_speed_time = -1;
74 static int curl_ftp_no_epsv;
75 static char *curl_http_proxy;
76 static char *http_proxy_authmethod;
78 static char *http_proxy_ssl_cert;
79 static char *http_proxy_ssl_key;
80 static char *http_proxy_ssl_ca_info;
81 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
82 static int proxy_ssl_cert_password_required;
84 static struct {
85 const char *name;
86 long curlauth_param;
87 } proxy_authmethods[] = {
88 { "basic", CURLAUTH_BASIC },
89 { "digest", CURLAUTH_DIGEST },
90 { "negotiate", CURLAUTH_GSSNEGOTIATE },
91 { "ntlm", CURLAUTH_NTLM },
92 { "anyauth", CURLAUTH_ANY },
94 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
95 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
96 * here, too
99 #ifdef CURLGSSAPI_DELEGATION_FLAG
100 static char *curl_deleg;
101 static struct {
102 const char *name;
103 long curl_deleg_param;
104 } curl_deleg_levels[] = {
105 { "none", CURLGSSAPI_DELEGATION_NONE },
106 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
107 { "always", CURLGSSAPI_DELEGATION_FLAG },
109 #endif
111 enum proactive_auth {
112 PROACTIVE_AUTH_NONE = 0,
113 PROACTIVE_AUTH_IF_CREDENTIALS,
114 PROACTIVE_AUTH_AUTO,
115 PROACTIVE_AUTH_BASIC,
118 static struct credential proxy_auth = CREDENTIAL_INIT;
119 static const char *curl_proxyuserpwd;
120 static char *curl_cookie_file;
121 static int curl_save_cookies;
122 struct credential http_auth = CREDENTIAL_INIT;
123 static enum proactive_auth http_proactive_auth;
124 static char *user_agent;
125 static int curl_empty_auth = -1;
127 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
129 static struct credential cert_auth = CREDENTIAL_INIT;
130 static int ssl_cert_password_required;
131 static unsigned long http_auth_methods = CURLAUTH_ANY;
132 static int http_auth_methods_restricted;
133 /* Modes for which empty_auth cannot actually help us. */
134 static unsigned long empty_auth_useless =
135 CURLAUTH_BASIC
136 | CURLAUTH_DIGEST_IE
137 | CURLAUTH_DIGEST;
139 static struct curl_slist *pragma_header;
140 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
142 static struct curl_slist *host_resolutions;
144 static struct active_request_slot *active_queue_head;
146 static char *cached_accept_language;
148 static char *http_ssl_backend;
150 static int http_schannel_check_revoke = 1;
152 * With the backend being set to `schannel`, setting sslCAinfo would override
153 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
154 * by default.
156 static int http_schannel_use_ssl_cainfo;
158 static int always_auth_proactively(void)
160 return http_proactive_auth != PROACTIVE_AUTH_NONE &&
161 http_proactive_auth != PROACTIVE_AUTH_IF_CREDENTIALS;
164 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
166 size_t size = eltsize * nmemb;
167 struct buffer *buffer = buffer_;
169 if (size > buffer->buf.len - buffer->posn)
170 size = buffer->buf.len - buffer->posn;
171 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
172 buffer->posn += size;
174 return size / eltsize;
177 int seek_buffer(void *clientp, curl_off_t offset, int origin)
179 struct buffer *buffer = clientp;
181 if (origin != SEEK_SET)
182 BUG("seek_buffer only handles SEEK_SET");
183 if (offset < 0 || offset >= buffer->buf.len) {
184 error("curl seek would be outside of buffer");
185 return CURL_SEEKFUNC_FAIL;
188 buffer->posn = offset;
189 return CURL_SEEKFUNC_OK;
192 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
194 size_t size = eltsize * nmemb;
195 struct strbuf *buffer = buffer_;
197 strbuf_add(buffer, ptr, size);
198 return nmemb;
202 * A folded header continuation line starts with any number of spaces or
203 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
204 * It is not a continuation line if the line starts with any other character.
206 static inline int is_hdr_continuation(const char *ptr, const size_t size)
208 return size && (*ptr == ' ' || *ptr == '\t');
211 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
213 size_t size = eltsize * nmemb;
214 struct strvec *values = &http_auth.wwwauth_headers;
215 struct strbuf buf = STRBUF_INIT;
216 const char *val;
217 size_t val_len;
220 * Header lines may not come NULL-terminated from libcurl so we must
221 * limit all scans to the maximum length of the header line, or leverage
222 * strbufs for all operations.
224 * In addition, it is possible that header values can be split over
225 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
226 * but older servers may still emit them. A continuation header field
227 * value is identified as starting with a space or horizontal tab.
229 * The formal definition of a header field as given in RFC 7230 is:
231 * header-field = field-name ":" OWS field-value OWS
233 * field-name = token
234 * field-value = *( field-content / obs-fold )
235 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
236 * field-vchar = VCHAR / obs-text
238 * obs-fold = CRLF 1*( SP / HTAB )
239 * ; obsolete line folding
240 * ; see Section 3.2.4
243 /* Start of a new WWW-Authenticate header */
244 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
245 strbuf_add(&buf, val, val_len);
248 * Strip the CRLF that should be present at the end of each
249 * field as well as any trailing or leading whitespace from the
250 * value.
252 strbuf_trim(&buf);
254 strvec_push(values, buf.buf);
255 http_auth.header_is_last_match = 1;
256 goto exit;
260 * This line could be a continuation of the previously matched header
261 * field. If this is the case then we should append this value to the
262 * end of the previously consumed value.
264 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
266 * Trim the CRLF and any leading or trailing from this line.
268 strbuf_add(&buf, ptr, size);
269 strbuf_trim(&buf);
272 * At this point we should always have at least one existing
273 * value, even if it is empty. Do not bother appending the new
274 * value if this continuation header is itself empty.
276 if (!values->nr) {
277 BUG("should have at least one existing header value");
278 } else if (buf.len) {
279 char *prev = xstrdup(values->v[values->nr - 1]);
281 /* Join two non-empty values with a single space. */
282 const char *const sp = *prev ? " " : "";
284 strvec_pop(values);
285 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
286 free(prev);
289 goto exit;
292 /* Not a continuation of a previously matched auth header line. */
293 http_auth.header_is_last_match = 0;
296 * If this is a HTTP status line and not a header field, this signals
297 * a different HTTP response. libcurl writes all the output of all
298 * response headers of all responses, including redirects.
299 * We only care about the last HTTP request response's headers so clear
300 * the existing array.
302 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
303 strvec_clear(values);
305 exit:
306 strbuf_release(&buf);
307 return size;
310 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
311 void *data UNUSED)
313 return nmemb;
316 static struct curl_slist *object_request_headers(void)
318 return curl_slist_append(http_copy_default_headers(), "Pragma:");
321 static void closedown_active_slot(struct active_request_slot *slot)
323 active_requests--;
324 slot->in_use = 0;
327 static void finish_active_slot(struct active_request_slot *slot)
329 closedown_active_slot(slot);
330 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
332 if (slot->finished)
333 (*slot->finished) = 1;
335 /* Store slot results so they can be read after the slot is reused */
336 if (slot->results) {
337 slot->results->curl_result = slot->curl_result;
338 slot->results->http_code = slot->http_code;
339 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
340 &slot->results->auth_avail);
342 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
343 &slot->results->http_connectcode);
346 /* Run callback if appropriate */
347 if (slot->callback_func)
348 slot->callback_func(slot->callback_data);
351 static void xmulti_remove_handle(struct active_request_slot *slot)
353 curl_multi_remove_handle(curlm, slot->curl);
356 static void process_curl_messages(void)
358 int num_messages;
359 struct active_request_slot *slot;
360 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
362 while (curl_message != NULL) {
363 if (curl_message->msg == CURLMSG_DONE) {
364 int curl_result = curl_message->data.result;
365 slot = active_queue_head;
366 while (slot != NULL &&
367 slot->curl != curl_message->easy_handle)
368 slot = slot->next;
369 if (slot) {
370 xmulti_remove_handle(slot);
371 slot->curl_result = curl_result;
372 finish_active_slot(slot);
373 } else {
374 fprintf(stderr, "Received DONE message for unknown request!\n");
376 } else {
377 fprintf(stderr, "Unknown CURL message received: %d\n",
378 (int)curl_message->msg);
380 curl_message = curl_multi_info_read(curlm, &num_messages);
384 static int http_options(const char *var, const char *value,
385 const struct config_context *ctx, void *data)
387 if (!strcmp("http.version", var)) {
388 return git_config_string(&curl_http_version, var, value);
390 if (!strcmp("http.sslverify", var)) {
391 curl_ssl_verify = git_config_bool(var, value);
392 return 0;
394 if (!strcmp("http.sslcipherlist", var))
395 return git_config_string(&ssl_cipherlist, var, value);
396 if (!strcmp("http.sslversion", var))
397 return git_config_string(&ssl_version, var, value);
398 if (!strcmp("http.sslcert", var))
399 return git_config_pathname(&ssl_cert, var, value);
400 if (!strcmp("http.sslcerttype", var))
401 return git_config_string(&ssl_cert_type, var, value);
402 if (!strcmp("http.sslkey", var))
403 return git_config_pathname(&ssl_key, var, value);
404 if (!strcmp("http.sslkeytype", var))
405 return git_config_string(&ssl_key_type, var, value);
406 if (!strcmp("http.sslcapath", var))
407 return git_config_pathname(&ssl_capath, var, value);
408 if (!strcmp("http.sslcainfo", var))
409 return git_config_pathname(&ssl_cainfo, var, value);
410 if (!strcmp("http.sslcertpasswordprotected", var)) {
411 ssl_cert_password_required = git_config_bool(var, value);
412 return 0;
414 if (!strcmp("http.ssltry", var)) {
415 curl_ssl_try = git_config_bool(var, value);
416 return 0;
418 if (!strcmp("http.sslbackend", var)) {
419 free(http_ssl_backend);
420 http_ssl_backend = xstrdup_or_null(value);
421 return 0;
424 if (!strcmp("http.schannelcheckrevoke", var)) {
425 http_schannel_check_revoke = git_config_bool(var, value);
426 return 0;
429 if (!strcmp("http.schannelusesslcainfo", var)) {
430 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
431 return 0;
434 if (!strcmp("http.minsessions", var)) {
435 min_curl_sessions = git_config_int(var, value, ctx->kvi);
436 if (min_curl_sessions > 1)
437 min_curl_sessions = 1;
438 return 0;
440 if (!strcmp("http.maxrequests", var)) {
441 max_requests = git_config_int(var, value, ctx->kvi);
442 return 0;
444 if (!strcmp("http.lowspeedlimit", var)) {
445 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
446 return 0;
448 if (!strcmp("http.lowspeedtime", var)) {
449 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
450 return 0;
453 if (!strcmp("http.noepsv", var)) {
454 curl_ftp_no_epsv = git_config_bool(var, value);
455 return 0;
457 if (!strcmp("http.proxy", var))
458 return git_config_string(&curl_http_proxy, var, value);
460 if (!strcmp("http.proxyauthmethod", var))
461 return git_config_string(&http_proxy_authmethod, var, value);
463 if (!strcmp("http.proxysslcert", var))
464 return git_config_string(&http_proxy_ssl_cert, var, value);
466 if (!strcmp("http.proxysslkey", var))
467 return git_config_string(&http_proxy_ssl_key, var, value);
469 if (!strcmp("http.proxysslcainfo", var))
470 return git_config_string(&http_proxy_ssl_ca_info, var, value);
472 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
473 proxy_ssl_cert_password_required = git_config_bool(var, value);
474 return 0;
477 if (!strcmp("http.cookiefile", var))
478 return git_config_pathname(&curl_cookie_file, var, value);
479 if (!strcmp("http.savecookies", var)) {
480 curl_save_cookies = git_config_bool(var, value);
481 return 0;
484 if (!strcmp("http.postbuffer", var)) {
485 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
486 if (http_post_buffer < 0)
487 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
488 if (http_post_buffer < LARGE_PACKET_MAX)
489 http_post_buffer = LARGE_PACKET_MAX;
490 return 0;
493 if (!strcmp("http.useragent", var))
494 return git_config_string(&user_agent, var, value);
496 if (!strcmp("http.emptyauth", var)) {
497 if (value && !strcmp("auto", value))
498 curl_empty_auth = -1;
499 else
500 curl_empty_auth = git_config_bool(var, value);
501 return 0;
504 if (!strcmp("http.delegation", var)) {
505 #ifdef CURLGSSAPI_DELEGATION_FLAG
506 return git_config_string(&curl_deleg, var, value);
507 #else
508 warning(_("Delegation control is not supported with cURL < 7.22.0"));
509 return 0;
510 #endif
513 if (!strcmp("http.pinnedpubkey", var)) {
514 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
515 return git_config_pathname(&ssl_pinnedkey, var, value);
516 #else
517 warning(_("Public key pinning not supported with cURL < 7.39.0"));
518 return 0;
519 #endif
522 if (!strcmp("http.extraheader", var)) {
523 if (!value) {
524 return config_error_nonbool(var);
525 } else if (!*value) {
526 string_list_clear(&extra_http_headers, 0);
527 } else {
528 string_list_append(&extra_http_headers, value);
530 return 0;
533 if (!strcmp("http.curloptresolve", var)) {
534 if (!value) {
535 return config_error_nonbool(var);
536 } else if (!*value) {
537 curl_slist_free_all(host_resolutions);
538 host_resolutions = NULL;
539 } else {
540 host_resolutions = curl_slist_append(host_resolutions, value);
542 return 0;
545 if (!strcmp("http.followredirects", var)) {
546 if (value && !strcmp(value, "initial"))
547 http_follow_config = HTTP_FOLLOW_INITIAL;
548 else if (git_config_bool(var, value))
549 http_follow_config = HTTP_FOLLOW_ALWAYS;
550 else
551 http_follow_config = HTTP_FOLLOW_NONE;
552 return 0;
555 if (!strcmp("http.proactiveauth", var)) {
556 if (!value)
557 return config_error_nonbool(var);
558 if (!strcmp(value, "auto"))
559 http_proactive_auth = PROACTIVE_AUTH_AUTO;
560 else if (!strcmp(value, "basic"))
561 http_proactive_auth = PROACTIVE_AUTH_BASIC;
562 else if (!strcmp(value, "none"))
563 http_proactive_auth = PROACTIVE_AUTH_NONE;
564 else
565 warning(_("Unknown value for http.proactiveauth"));
566 return 0;
569 /* Fall back on the default ones */
570 return git_default_config(var, value, ctx, data);
573 static int curl_empty_auth_enabled(void)
575 if (curl_empty_auth >= 0)
576 return curl_empty_auth;
579 * In the automatic case, kick in the empty-auth
580 * hack as long as we would potentially try some
581 * method more exotic than "Basic" or "Digest".
583 * But only do this when this is our second or
584 * subsequent request, as by then we know what
585 * methods are available.
587 if (http_auth_methods_restricted &&
588 (http_auth_methods & ~empty_auth_useless))
589 return 1;
590 return 0;
593 struct curl_slist *http_append_auth_header(const struct credential *c,
594 struct curl_slist *headers)
596 if (c->authtype && c->credential) {
597 struct strbuf auth = STRBUF_INIT;
598 strbuf_addf(&auth, "Authorization: %s %s",
599 c->authtype, c->credential);
600 headers = curl_slist_append(headers, auth.buf);
601 strbuf_release(&auth);
603 return headers;
606 static void init_curl_http_auth(CURL *result)
608 if ((!http_auth.username || !*http_auth.username) &&
609 (!http_auth.credential || !*http_auth.credential)) {
610 int empty_auth = curl_empty_auth_enabled();
611 if ((empty_auth != -1 && !always_auth_proactively()) || empty_auth == 1) {
612 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
613 return;
614 } else if (!always_auth_proactively()) {
615 return;
616 } else if (http_proactive_auth == PROACTIVE_AUTH_BASIC) {
617 strvec_push(&http_auth.wwwauth_headers, "Basic");
621 credential_fill(&http_auth, 1);
623 if (http_auth.password) {
624 if (always_auth_proactively()) {
626 * We got a credential without an authtype and we don't
627 * know what's available. Since our only two options at
628 * the moment are auto (which defaults to basic) and
629 * basic, use basic for now.
631 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
633 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
634 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
638 /* *var must be free-able */
639 static void var_override(char **var, char *value)
641 if (value) {
642 free(*var);
643 *var = xstrdup(value);
647 static void set_proxyauth_name_password(CURL *result)
649 if (proxy_auth.password) {
650 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
651 proxy_auth.username);
652 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
653 proxy_auth.password);
654 } else if (proxy_auth.authtype && proxy_auth.credential) {
655 curl_easy_setopt(result, CURLOPT_PROXYHEADER,
656 http_append_auth_header(&proxy_auth, NULL));
660 static void init_curl_proxy_auth(CURL *result)
662 if (proxy_auth.username) {
663 if (!proxy_auth.password && !proxy_auth.credential)
664 credential_fill(&proxy_auth, 1);
665 set_proxyauth_name_password(result);
668 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
670 if (http_proxy_authmethod) {
671 int i;
672 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
673 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
674 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
675 proxy_authmethods[i].curlauth_param);
676 break;
679 if (i == ARRAY_SIZE(proxy_authmethods)) {
680 warning("unsupported proxy authentication method %s: using anyauth",
681 http_proxy_authmethod);
682 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
685 else
686 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
689 static int has_cert_password(void)
691 if (ssl_cert == NULL || ssl_cert_password_required != 1)
692 return 0;
693 if (!cert_auth.password) {
694 cert_auth.protocol = xstrdup("cert");
695 cert_auth.host = xstrdup("");
696 cert_auth.username = xstrdup("");
697 cert_auth.path = xstrdup(ssl_cert);
698 credential_fill(&cert_auth, 0);
700 return 1;
703 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
704 static int has_proxy_cert_password(void)
706 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
707 return 0;
708 if (!proxy_cert_auth.password) {
709 proxy_cert_auth.protocol = xstrdup("cert");
710 proxy_cert_auth.host = xstrdup("");
711 proxy_cert_auth.username = xstrdup("");
712 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
713 credential_fill(&proxy_cert_auth, 0);
715 return 1;
717 #endif
719 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
720 static void set_curl_keepalive(CURL *c)
722 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
725 #else
726 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
728 int ka = 1;
729 int rc;
730 socklen_t len = (socklen_t)sizeof(ka);
732 if (type != CURLSOCKTYPE_IPCXN)
733 return 0;
735 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
736 if (rc < 0)
737 warning_errno("unable to set SO_KEEPALIVE on socket");
739 return CURL_SOCKOPT_OK;
742 static void set_curl_keepalive(CURL *c)
744 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
746 #endif
748 /* Return 1 if redactions have been made, 0 otherwise. */
749 static int redact_sensitive_header(struct strbuf *header, size_t offset)
751 int ret = 0;
752 const char *sensitive_header;
754 if (trace_curl_redact &&
755 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
756 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
757 /* The first token is the type, which is OK to log */
758 while (isspace(*sensitive_header))
759 sensitive_header++;
760 while (*sensitive_header && !isspace(*sensitive_header))
761 sensitive_header++;
762 /* Everything else is opaque and possibly sensitive */
763 strbuf_setlen(header, sensitive_header - header->buf);
764 strbuf_addstr(header, " <redacted>");
765 ret = 1;
766 } else if (trace_curl_redact &&
767 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
768 struct strbuf redacted_header = STRBUF_INIT;
769 const char *cookie;
771 while (isspace(*sensitive_header))
772 sensitive_header++;
774 cookie = sensitive_header;
776 while (cookie) {
777 char *equals;
778 char *semicolon = strstr(cookie, "; ");
779 if (semicolon)
780 *semicolon = 0;
781 equals = strchrnul(cookie, '=');
782 if (!equals) {
783 /* invalid cookie, just append and continue */
784 strbuf_addstr(&redacted_header, cookie);
785 continue;
787 strbuf_add(&redacted_header, cookie, equals - cookie);
788 strbuf_addstr(&redacted_header, "=<redacted>");
789 if (semicolon) {
791 * There are more cookies. (Or, for some
792 * reason, the input string ends in "; ".)
794 strbuf_addstr(&redacted_header, "; ");
795 cookie = semicolon + strlen("; ");
796 } else {
797 cookie = NULL;
801 strbuf_setlen(header, sensitive_header - header->buf);
802 strbuf_addbuf(header, &redacted_header);
803 strbuf_release(&redacted_header);
804 ret = 1;
806 return ret;
809 static int match_curl_h2_trace(const char *line, const char **out)
811 const char *p;
814 * curl prior to 8.1.0 gives us:
816 * h2h3 [<header-name>: <header-val>]
818 * Starting in 8.1.0, the first token became just "h2".
820 if (skip_iprefix(line, "h2h3 [", out) ||
821 skip_iprefix(line, "h2 [", out))
822 return 1;
825 * curl 8.3.0 uses:
826 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
827 * where <stream-id> is numeric.
829 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
830 while (isdigit(*p))
831 p++;
832 if (skip_prefix(p, "] [", out))
833 return 1;
836 return 0;
839 /* Redact headers in info */
840 static void redact_sensitive_info_header(struct strbuf *header)
842 const char *sensitive_header;
844 if (trace_curl_redact &&
845 match_curl_h2_trace(header->buf, &sensitive_header)) {
846 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
847 /* redaction ate our closing bracket */
848 strbuf_addch(header, ']');
853 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
855 struct strbuf out = STRBUF_INIT;
856 struct strbuf **headers, **header;
858 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
859 text, (long)size, (long)size);
860 trace_strbuf(&trace_curl, &out);
861 strbuf_reset(&out);
862 strbuf_add(&out, ptr, size);
863 headers = strbuf_split_max(&out, '\n', 0);
865 for (header = headers; *header; header++) {
866 if (hide_sensitive_header)
867 redact_sensitive_header(*header, 0);
868 strbuf_insertstr((*header), 0, text);
869 strbuf_insertstr((*header), strlen(text), ": ");
870 strbuf_rtrim((*header));
871 strbuf_addch((*header), '\n');
872 trace_strbuf(&trace_curl, (*header));
874 strbuf_list_free(headers);
875 strbuf_release(&out);
878 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
880 size_t i;
881 struct strbuf out = STRBUF_INIT;
882 unsigned int width = 60;
884 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
885 text, (long)size, (long)size);
886 trace_strbuf(&trace_curl, &out);
888 for (i = 0; i < size; i += width) {
889 size_t w;
891 strbuf_reset(&out);
892 strbuf_addf(&out, "%s: ", text);
893 for (w = 0; (w < width) && (i + w < size); w++) {
894 unsigned char ch = ptr[i + w];
896 strbuf_addch(&out,
897 (ch >= 0x20) && (ch < 0x80)
898 ? ch : '.');
900 strbuf_addch(&out, '\n');
901 trace_strbuf(&trace_curl, &out);
903 strbuf_release(&out);
906 static void curl_dump_info(char *data, size_t size)
908 struct strbuf buf = STRBUF_INIT;
910 strbuf_add(&buf, data, size);
912 redact_sensitive_info_header(&buf);
913 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
915 strbuf_release(&buf);
918 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
919 char *data, size_t size,
920 void *userp UNUSED)
922 const char *text;
923 enum { NO_FILTER = 0, DO_FILTER = 1 };
925 switch (type) {
926 case CURLINFO_TEXT:
927 curl_dump_info(data, size);
928 break;
929 case CURLINFO_HEADER_OUT:
930 text = "=> Send header";
931 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
932 break;
933 case CURLINFO_DATA_OUT:
934 if (trace_curl_data) {
935 text = "=> Send data";
936 curl_dump_data(text, (unsigned char *)data, size);
938 break;
939 case CURLINFO_SSL_DATA_OUT:
940 if (trace_curl_data) {
941 text = "=> Send SSL data";
942 curl_dump_data(text, (unsigned char *)data, size);
944 break;
945 case CURLINFO_HEADER_IN:
946 text = "<= Recv header";
947 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
948 break;
949 case CURLINFO_DATA_IN:
950 if (trace_curl_data) {
951 text = "<= Recv data";
952 curl_dump_data(text, (unsigned char *)data, size);
954 break;
955 case CURLINFO_SSL_DATA_IN:
956 if (trace_curl_data) {
957 text = "<= Recv SSL data";
958 curl_dump_data(text, (unsigned char *)data, size);
960 break;
962 default: /* we ignore unknown types by default */
963 return 0;
965 return 0;
968 void http_trace_curl_no_data(void)
970 trace_override_envvar(&trace_curl, "1");
971 trace_curl_data = 0;
974 void setup_curl_trace(CURL *handle)
976 if (!trace_want(&trace_curl))
977 return;
978 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
979 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
980 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
983 static void proto_list_append(struct strbuf *list, const char *proto)
985 if (!list)
986 return;
987 if (list->len)
988 strbuf_addch(list, ',');
989 strbuf_addstr(list, proto);
992 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
994 long bits = 0;
996 if (is_transport_allowed("http", from_user)) {
997 bits |= CURLPROTO_HTTP;
998 proto_list_append(list, "http");
1000 if (is_transport_allowed("https", from_user)) {
1001 bits |= CURLPROTO_HTTPS;
1002 proto_list_append(list, "https");
1004 if (is_transport_allowed("ftp", from_user)) {
1005 bits |= CURLPROTO_FTP;
1006 proto_list_append(list, "ftp");
1008 if (is_transport_allowed("ftps", from_user)) {
1009 bits |= CURLPROTO_FTPS;
1010 proto_list_append(list, "ftps");
1013 return bits;
1016 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1017 static int get_curl_http_version_opt(const char *version_string, long *opt)
1019 int i;
1020 static struct {
1021 const char *name;
1022 long opt_token;
1023 } choice[] = {
1024 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
1025 { "HTTP/2", CURL_HTTP_VERSION_2 }
1028 for (i = 0; i < ARRAY_SIZE(choice); i++) {
1029 if (!strcmp(version_string, choice[i].name)) {
1030 *opt = choice[i].opt_token;
1031 return 0;
1035 warning("unknown value given to http.version: '%s'", version_string);
1036 return -1; /* not found */
1039 #endif
1041 static CURL *get_curl_handle(void)
1043 CURL *result = curl_easy_init();
1045 if (!result)
1046 die("curl_easy_init failed");
1048 if (!curl_ssl_verify) {
1049 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
1050 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
1051 } else {
1052 /* Verify authenticity of the peer's certificate */
1053 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
1054 /* The name in the cert must match whom we tried to connect */
1055 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
1058 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1059 if (curl_http_version) {
1060 long opt;
1061 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
1062 /* Set request use http version */
1063 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
1066 #endif
1068 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
1069 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1071 #ifdef CURLGSSAPI_DELEGATION_FLAG
1072 if (curl_deleg) {
1073 int i;
1074 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1075 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1076 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1077 curl_deleg_levels[i].curl_deleg_param);
1078 break;
1081 if (i == ARRAY_SIZE(curl_deleg_levels))
1082 warning("Unknown delegation method '%s': using default",
1083 curl_deleg);
1085 #endif
1087 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1088 !http_schannel_check_revoke) {
1089 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1090 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1091 #else
1092 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1093 #endif
1096 if (http_proactive_auth != PROACTIVE_AUTH_NONE)
1097 init_curl_http_auth(result);
1099 if (getenv("GIT_SSL_VERSION"))
1100 ssl_version = getenv("GIT_SSL_VERSION");
1101 if (ssl_version && *ssl_version) {
1102 int i;
1103 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1104 if (!strcmp(ssl_version, sslversions[i].name)) {
1105 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1106 sslversions[i].ssl_version);
1107 break;
1110 if (i == ARRAY_SIZE(sslversions))
1111 warning("unsupported ssl version %s: using default",
1112 ssl_version);
1115 if (getenv("GIT_SSL_CIPHER_LIST"))
1116 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1117 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1118 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1119 ssl_cipherlist);
1121 if (ssl_cert)
1122 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1123 if (ssl_cert_type)
1124 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1125 if (has_cert_password())
1126 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1127 if (ssl_key)
1128 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1129 if (ssl_key_type)
1130 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1131 if (ssl_capath)
1132 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1133 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1134 if (ssl_pinnedkey)
1135 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1136 #endif
1137 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1138 !http_schannel_use_ssl_cainfo) {
1139 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1140 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1141 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1142 #endif
1143 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1144 if (ssl_cainfo)
1145 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1146 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1147 if (http_proxy_ssl_ca_info)
1148 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1149 #endif
1152 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1153 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1154 curl_low_speed_limit);
1155 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1156 curl_low_speed_time);
1159 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1160 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1162 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1164 struct strbuf buf = STRBUF_INIT;
1166 get_curl_allowed_protocols(0, &buf);
1167 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1168 strbuf_reset(&buf);
1170 get_curl_allowed_protocols(-1, &buf);
1171 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1172 strbuf_release(&buf);
1174 #else
1175 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1176 get_curl_allowed_protocols(0, NULL));
1177 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1178 get_curl_allowed_protocols(-1, NULL));
1179 #endif
1181 if (getenv("GIT_CURL_VERBOSE"))
1182 http_trace_curl_no_data();
1183 setup_curl_trace(result);
1184 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1185 trace_curl_data = 0;
1186 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1187 trace_curl_redact = 0;
1189 curl_easy_setopt(result, CURLOPT_USERAGENT,
1190 user_agent ? user_agent : git_user_agent());
1192 if (curl_ftp_no_epsv)
1193 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1195 if (curl_ssl_try)
1196 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1199 * CURL also examines these variables as a fallback; but we need to query
1200 * them here in order to decide whether to prompt for missing password (cf.
1201 * init_curl_proxy_auth()).
1203 * Unlike many other common environment variables, these are historically
1204 * lowercase only. It appears that CURL did not know this and implemented
1205 * only uppercase variants, which was later corrected to take both - with
1206 * the exception of http_proxy, which is lowercase only also in CURL. As
1207 * the lowercase versions are the historical quasi-standard, they take
1208 * precedence here, as in CURL.
1210 if (!curl_http_proxy) {
1211 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1212 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1213 var_override(&curl_http_proxy, getenv("https_proxy"));
1214 } else {
1215 var_override(&curl_http_proxy, getenv("http_proxy"));
1217 if (!curl_http_proxy) {
1218 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1219 var_override(&curl_http_proxy, getenv("all_proxy"));
1223 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1225 * Handle case with the empty http.proxy value here to keep
1226 * common code clean.
1227 * NB: empty option disables proxying at all.
1229 curl_easy_setopt(result, CURLOPT_PROXY, "");
1230 } else if (curl_http_proxy) {
1231 struct strbuf proxy = STRBUF_INIT;
1233 if (starts_with(curl_http_proxy, "socks5h"))
1234 curl_easy_setopt(result,
1235 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1236 else if (starts_with(curl_http_proxy, "socks5"))
1237 curl_easy_setopt(result,
1238 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1239 else if (starts_with(curl_http_proxy, "socks4a"))
1240 curl_easy_setopt(result,
1241 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1242 else if (starts_with(curl_http_proxy, "socks"))
1243 curl_easy_setopt(result,
1244 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1245 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1246 else if (starts_with(curl_http_proxy, "https")) {
1247 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1249 if (http_proxy_ssl_cert)
1250 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1252 if (http_proxy_ssl_key)
1253 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1255 if (has_proxy_cert_password())
1256 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1258 #endif
1259 if (strstr(curl_http_proxy, "://"))
1260 credential_from_url(&proxy_auth, curl_http_proxy);
1261 else {
1262 struct strbuf url = STRBUF_INIT;
1263 strbuf_addf(&url, "http://%s", curl_http_proxy);
1264 credential_from_url(&proxy_auth, url.buf);
1265 strbuf_release(&url);
1268 if (!proxy_auth.host)
1269 die("Invalid proxy URL '%s'", curl_http_proxy);
1271 strbuf_addstr(&proxy, proxy_auth.host);
1272 if (proxy_auth.path) {
1273 curl_version_info_data *ver = curl_version_info(CURLVERSION_NOW);
1275 if (ver->version_num < 0x075400)
1276 die("libcurl 7.84 or later is required to support paths in proxy URLs");
1278 if (!starts_with(proxy_auth.protocol, "socks"))
1279 die("Invalid proxy URL '%s': only SOCKS proxies support paths",
1280 curl_http_proxy);
1282 if (strcasecmp(proxy_auth.host, "localhost"))
1283 die("Invalid proxy URL '%s': host must be localhost if a path is present",
1284 curl_http_proxy);
1286 strbuf_addch(&proxy, '/');
1287 strbuf_add_percentencode(&proxy, proxy_auth.path, 0);
1289 curl_easy_setopt(result, CURLOPT_PROXY, proxy.buf);
1290 strbuf_release(&proxy);
1292 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1293 var_override(&curl_no_proxy, getenv("no_proxy"));
1294 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1296 init_curl_proxy_auth(result);
1298 set_curl_keepalive(result);
1300 return result;
1303 static void set_from_env(char **var, const char *envname)
1305 const char *val = getenv(envname);
1306 if (val) {
1307 FREE_AND_NULL(*var);
1308 *var = xstrdup(val);
1312 void http_init(struct remote *remote, const char *url, int proactive_auth)
1314 char *low_speed_limit;
1315 char *low_speed_time;
1316 char *normalized_url;
1317 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1319 config.section = "http";
1320 config.key = NULL;
1321 config.collect_fn = http_options;
1322 config.cascade_fn = git_default_config;
1323 config.cb = NULL;
1325 http_is_verbose = 0;
1326 normalized_url = url_normalize(url, &config.url);
1328 git_config(urlmatch_config_entry, &config);
1329 free(normalized_url);
1330 string_list_clear(&config.vars, 1);
1332 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1333 if (http_ssl_backend) {
1334 const curl_ssl_backend **backends;
1335 struct strbuf buf = STRBUF_INIT;
1336 int i;
1338 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1339 case CURLSSLSET_UNKNOWN_BACKEND:
1340 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1341 "Supported SSL backends:"),
1342 http_ssl_backend);
1343 for (i = 0; backends[i]; i++)
1344 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1345 die("%s", buf.buf);
1346 case CURLSSLSET_NO_BACKENDS:
1347 die(_("Could not set SSL backend to '%s': "
1348 "cURL was built without SSL backends"),
1349 http_ssl_backend);
1350 case CURLSSLSET_TOO_LATE:
1351 die(_("Could not set SSL backend to '%s': already set"),
1352 http_ssl_backend);
1353 case CURLSSLSET_OK:
1354 break; /* Okay! */
1357 #endif
1359 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1360 die("curl_global_init failed");
1362 if (proactive_auth && http_proactive_auth == PROACTIVE_AUTH_NONE)
1363 http_proactive_auth = PROACTIVE_AUTH_IF_CREDENTIALS;
1365 if (remote && remote->http_proxy)
1366 curl_http_proxy = xstrdup(remote->http_proxy);
1368 if (remote)
1369 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1371 pragma_header = curl_slist_append(http_copy_default_headers(),
1372 "Pragma: no-cache");
1375 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1376 if (http_max_requests)
1377 max_requests = atoi(http_max_requests);
1380 curlm = curl_multi_init();
1381 if (!curlm)
1382 die("curl_multi_init failed");
1384 if (getenv("GIT_SSL_NO_VERIFY"))
1385 curl_ssl_verify = 0;
1387 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1388 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1389 set_from_env(&ssl_key, "GIT_SSL_KEY");
1390 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1391 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1392 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1394 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1396 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1397 if (low_speed_limit)
1398 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1399 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1400 if (low_speed_time)
1401 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1403 if (curl_ssl_verify == -1)
1404 curl_ssl_verify = 1;
1406 curl_session_count = 0;
1407 if (max_requests < 1)
1408 max_requests = DEFAULT_MAX_REQUESTS;
1410 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1411 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1412 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1414 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1415 proxy_ssl_cert_password_required = 1;
1417 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1418 curl_ftp_no_epsv = 1;
1420 if (url) {
1421 credential_from_url(&http_auth, url);
1422 if (!ssl_cert_password_required &&
1423 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1424 starts_with(url, "https://"))
1425 ssl_cert_password_required = 1;
1428 curl_default = get_curl_handle();
1431 void http_cleanup(void)
1433 struct active_request_slot *slot = active_queue_head;
1435 while (slot != NULL) {
1436 struct active_request_slot *next = slot->next;
1437 if (slot->curl) {
1438 xmulti_remove_handle(slot);
1439 curl_easy_cleanup(slot->curl);
1441 free(slot);
1442 slot = next;
1444 active_queue_head = NULL;
1446 curl_easy_cleanup(curl_default);
1448 curl_multi_cleanup(curlm);
1449 curl_global_cleanup();
1451 string_list_clear(&extra_http_headers, 0);
1453 curl_slist_free_all(pragma_header);
1454 pragma_header = NULL;
1456 curl_slist_free_all(host_resolutions);
1457 host_resolutions = NULL;
1459 if (curl_http_proxy) {
1460 free((void *)curl_http_proxy);
1461 curl_http_proxy = NULL;
1464 if (proxy_auth.password) {
1465 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1466 FREE_AND_NULL(proxy_auth.password);
1469 free((void *)curl_proxyuserpwd);
1470 curl_proxyuserpwd = NULL;
1472 free((void *)http_proxy_authmethod);
1473 http_proxy_authmethod = NULL;
1475 if (cert_auth.password) {
1476 memset(cert_auth.password, 0, strlen(cert_auth.password));
1477 FREE_AND_NULL(cert_auth.password);
1479 ssl_cert_password_required = 0;
1481 if (proxy_cert_auth.password) {
1482 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1483 FREE_AND_NULL(proxy_cert_auth.password);
1485 proxy_ssl_cert_password_required = 0;
1487 FREE_AND_NULL(cached_accept_language);
1490 struct active_request_slot *get_active_slot(void)
1492 struct active_request_slot *slot = active_queue_head;
1493 struct active_request_slot *newslot;
1495 int num_transfers;
1497 /* Wait for a slot to open up if the queue is full */
1498 while (active_requests >= max_requests) {
1499 curl_multi_perform(curlm, &num_transfers);
1500 if (num_transfers < active_requests)
1501 process_curl_messages();
1504 while (slot != NULL && slot->in_use)
1505 slot = slot->next;
1507 if (!slot) {
1508 newslot = xmalloc(sizeof(*newslot));
1509 newslot->curl = NULL;
1510 newslot->in_use = 0;
1511 newslot->next = NULL;
1513 slot = active_queue_head;
1514 if (!slot) {
1515 active_queue_head = newslot;
1516 } else {
1517 while (slot->next != NULL)
1518 slot = slot->next;
1519 slot->next = newslot;
1521 slot = newslot;
1524 if (!slot->curl) {
1525 slot->curl = curl_easy_duphandle(curl_default);
1526 curl_session_count++;
1529 active_requests++;
1530 slot->in_use = 1;
1531 slot->results = NULL;
1532 slot->finished = NULL;
1533 slot->callback_data = NULL;
1534 slot->callback_func = NULL;
1536 if (curl_cookie_file && !strcmp(curl_cookie_file, "-")) {
1537 warning(_("refusing to read cookies from http.cookiefile '-'"));
1538 FREE_AND_NULL(curl_cookie_file);
1540 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1541 if (curl_save_cookies && (!curl_cookie_file || !curl_cookie_file[0])) {
1542 curl_save_cookies = 0;
1543 warning(_("ignoring http.savecookies for empty http.cookiefile"));
1545 if (curl_save_cookies)
1546 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1547 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1548 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1549 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1550 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1551 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1552 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1553 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1554 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, -1L);
1555 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1556 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1557 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1558 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1561 * Default following to off unless "ALWAYS" is configured; this gives
1562 * callers a sane starting point, and they can tweak for individual
1563 * HTTP_FOLLOW_* cases themselves.
1565 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1566 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1567 else
1568 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1570 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1571 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1572 if (http_auth.password || http_auth.credential || curl_empty_auth_enabled())
1573 init_curl_http_auth(slot->curl);
1575 return slot;
1578 int start_active_slot(struct active_request_slot *slot)
1580 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1581 int num_transfers;
1583 if (curlm_result != CURLM_OK &&
1584 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1585 warning("curl_multi_add_handle failed: %s",
1586 curl_multi_strerror(curlm_result));
1587 active_requests--;
1588 slot->in_use = 0;
1589 return 0;
1593 * We know there must be something to do, since we just added
1594 * something.
1596 curl_multi_perform(curlm, &num_transfers);
1597 return 1;
1600 struct fill_chain {
1601 void *data;
1602 int (*fill)(void *);
1603 struct fill_chain *next;
1606 static struct fill_chain *fill_cfg;
1608 void add_fill_function(void *data, int (*fill)(void *))
1610 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1611 struct fill_chain **linkp = &fill_cfg;
1612 new_fill->data = data;
1613 new_fill->fill = fill;
1614 new_fill->next = NULL;
1615 while (*linkp)
1616 linkp = &(*linkp)->next;
1617 *linkp = new_fill;
1620 void fill_active_slots(void)
1622 struct active_request_slot *slot = active_queue_head;
1624 while (active_requests < max_requests) {
1625 struct fill_chain *fill;
1626 for (fill = fill_cfg; fill; fill = fill->next)
1627 if (fill->fill(fill->data))
1628 break;
1630 if (!fill)
1631 break;
1634 while (slot != NULL) {
1635 if (!slot->in_use && slot->curl != NULL
1636 && curl_session_count > min_curl_sessions) {
1637 curl_easy_cleanup(slot->curl);
1638 slot->curl = NULL;
1639 curl_session_count--;
1641 slot = slot->next;
1645 void step_active_slots(void)
1647 int num_transfers;
1648 CURLMcode curlm_result;
1650 do {
1651 curlm_result = curl_multi_perform(curlm, &num_transfers);
1652 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1653 if (num_transfers < active_requests) {
1654 process_curl_messages();
1655 fill_active_slots();
1659 void run_active_slot(struct active_request_slot *slot)
1661 fd_set readfds;
1662 fd_set writefds;
1663 fd_set excfds;
1664 int max_fd;
1665 struct timeval select_timeout;
1666 int finished = 0;
1668 slot->finished = &finished;
1669 while (!finished) {
1670 step_active_slots();
1672 if (slot->in_use) {
1673 long curl_timeout;
1674 curl_multi_timeout(curlm, &curl_timeout);
1675 if (curl_timeout == 0) {
1676 continue;
1677 } else if (curl_timeout == -1) {
1678 select_timeout.tv_sec = 0;
1679 select_timeout.tv_usec = 50000;
1680 } else {
1681 select_timeout.tv_sec = curl_timeout / 1000;
1682 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1685 max_fd = -1;
1686 FD_ZERO(&readfds);
1687 FD_ZERO(&writefds);
1688 FD_ZERO(&excfds);
1689 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1692 * It can happen that curl_multi_timeout returns a pathologically
1693 * long timeout when curl_multi_fdset returns no file descriptors
1694 * to read. See commit message for more details.
1696 if (max_fd < 0 &&
1697 (select_timeout.tv_sec > 0 ||
1698 select_timeout.tv_usec > 50000)) {
1699 select_timeout.tv_sec = 0;
1700 select_timeout.tv_usec = 50000;
1703 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1708 * The value of slot->finished we set before the loop was used
1709 * to set our "finished" variable when our request completed.
1711 * 1. The slot may not have been reused for another request
1712 * yet, in which case it still has &finished.
1714 * 2. The slot may already be in-use to serve another request,
1715 * which can further be divided into two cases:
1717 * (a) If call run_active_slot() hasn't been called for that
1718 * other request, slot->finished would have been cleared
1719 * by get_active_slot() and has NULL.
1721 * (b) If the request did call run_active_slot(), then the
1722 * call would have updated slot->finished at the beginning
1723 * of this function, and with the clearing of the member
1724 * below, we would find that slot->finished is now NULL.
1726 * In all cases, slot->finished has no useful information to
1727 * anybody at this point. Some compilers warn us for
1728 * attempting to smuggle a pointer that is about to become
1729 * invalid, i.e. &finished. We clear it here to assure them.
1731 slot->finished = NULL;
1734 static void release_active_slot(struct active_request_slot *slot)
1736 closedown_active_slot(slot);
1737 if (slot->curl) {
1738 xmulti_remove_handle(slot);
1739 if (curl_session_count > min_curl_sessions) {
1740 curl_easy_cleanup(slot->curl);
1741 slot->curl = NULL;
1742 curl_session_count--;
1745 fill_active_slots();
1748 void finish_all_active_slots(void)
1750 struct active_request_slot *slot = active_queue_head;
1752 while (slot != NULL)
1753 if (slot->in_use) {
1754 run_active_slot(slot);
1755 slot = active_queue_head;
1756 } else {
1757 slot = slot->next;
1761 /* Helpers for modifying and creating URLs */
1762 static inline int needs_quote(int ch)
1764 if (((ch >= 'A') && (ch <= 'Z'))
1765 || ((ch >= 'a') && (ch <= 'z'))
1766 || ((ch >= '0') && (ch <= '9'))
1767 || (ch == '/')
1768 || (ch == '-')
1769 || (ch == '.'))
1770 return 0;
1771 return 1;
1774 static char *quote_ref_url(const char *base, const char *ref)
1776 struct strbuf buf = STRBUF_INIT;
1777 const char *cp;
1778 int ch;
1780 end_url_with_slash(&buf, base);
1782 for (cp = ref; (ch = *cp) != 0; cp++)
1783 if (needs_quote(ch))
1784 strbuf_addf(&buf, "%%%02x", ch);
1785 else
1786 strbuf_addch(&buf, *cp);
1788 return strbuf_detach(&buf, NULL);
1791 void append_remote_object_url(struct strbuf *buf, const char *url,
1792 const char *hex,
1793 int only_two_digit_prefix)
1795 end_url_with_slash(buf, url);
1797 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1798 if (!only_two_digit_prefix)
1799 strbuf_addstr(buf, hex + 2);
1802 char *get_remote_object_url(const char *url, const char *hex,
1803 int only_two_digit_prefix)
1805 struct strbuf buf = STRBUF_INIT;
1806 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1807 return strbuf_detach(&buf, NULL);
1810 void normalize_curl_result(CURLcode *result, long http_code,
1811 char *errorstr, size_t errorlen)
1814 * If we see a failing http code with CURLE_OK, we have turned off
1815 * FAILONERROR (to keep the server's custom error response), and should
1816 * translate the code into failure here.
1818 * Likewise, if we see a redirect (30x code), that means we turned off
1819 * redirect-following, and we should treat the result as an error.
1821 if (*result == CURLE_OK && http_code >= 300) {
1822 *result = CURLE_HTTP_RETURNED_ERROR;
1824 * Normally curl will already have put the "reason phrase"
1825 * from the server into curl_errorstr; unfortunately without
1826 * FAILONERROR it is lost, so we can give only the numeric
1827 * status code.
1829 xsnprintf(errorstr, errorlen,
1830 "The requested URL returned error: %ld",
1831 http_code);
1835 static int handle_curl_result(struct slot_results *results)
1837 normalize_curl_result(&results->curl_result, results->http_code,
1838 curl_errorstr, sizeof(curl_errorstr));
1840 if (results->curl_result == CURLE_OK) {
1841 credential_approve(&http_auth);
1842 credential_approve(&proxy_auth);
1843 credential_approve(&cert_auth);
1844 return HTTP_OK;
1845 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1847 * We can't tell from here whether it's a bad path, bad
1848 * certificate, bad password, or something else wrong
1849 * with the certificate. So we reject the credential to
1850 * avoid caching or saving a bad password.
1852 credential_reject(&cert_auth);
1853 return HTTP_NOAUTH;
1854 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1855 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1856 return HTTP_NOMATCHPUBLICKEY;
1857 #endif
1858 } else if (missing_target(results))
1859 return HTTP_MISSING_TARGET;
1860 else if (results->http_code == 401) {
1861 if ((http_auth.username && http_auth.password) ||\
1862 (http_auth.authtype && http_auth.credential)) {
1863 if (http_auth.multistage) {
1864 credential_clear_secrets(&http_auth);
1865 return HTTP_REAUTH;
1867 credential_reject(&http_auth);
1868 if (always_auth_proactively())
1869 http_proactive_auth = PROACTIVE_AUTH_NONE;
1870 return HTTP_NOAUTH;
1871 } else {
1872 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1873 if (results->auth_avail) {
1874 http_auth_methods &= results->auth_avail;
1875 http_auth_methods_restricted = 1;
1877 return HTTP_REAUTH;
1879 } else {
1880 if (results->http_connectcode == 407)
1881 credential_reject(&proxy_auth);
1882 if (!curl_errorstr[0])
1883 strlcpy(curl_errorstr,
1884 curl_easy_strerror(results->curl_result),
1885 sizeof(curl_errorstr));
1886 return HTTP_ERROR;
1890 int run_one_slot(struct active_request_slot *slot,
1891 struct slot_results *results)
1893 slot->results = results;
1894 if (!start_active_slot(slot)) {
1895 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1896 "failed to start HTTP request");
1897 return HTTP_START_FAILED;
1900 run_active_slot(slot);
1901 return handle_curl_result(results);
1904 struct curl_slist *http_copy_default_headers(void)
1906 struct curl_slist *headers = NULL;
1907 const struct string_list_item *item;
1909 for_each_string_list_item(item, &extra_http_headers)
1910 headers = curl_slist_append(headers, item->string);
1912 return headers;
1915 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1917 char *ptr;
1918 CURLcode ret;
1920 strbuf_reset(buf);
1921 ret = curl_easy_getinfo(curl, info, &ptr);
1922 if (!ret && ptr)
1923 strbuf_addstr(buf, ptr);
1924 return ret;
1928 * Check for and extract a content-type parameter. "raw"
1929 * should be positioned at the start of the potential
1930 * parameter, with any whitespace already removed.
1932 * "name" is the name of the parameter. The value is appended
1933 * to "out".
1935 static int extract_param(const char *raw, const char *name,
1936 struct strbuf *out)
1938 size_t len = strlen(name);
1940 if (strncasecmp(raw, name, len))
1941 return -1;
1942 raw += len;
1944 if (*raw != '=')
1945 return -1;
1946 raw++;
1948 while (*raw && !isspace(*raw) && *raw != ';')
1949 strbuf_addch(out, *raw++);
1950 return 0;
1954 * Extract a normalized version of the content type, with any
1955 * spaces suppressed, all letters lowercased, and no trailing ";"
1956 * or parameters.
1958 * Note that we will silently remove even invalid whitespace. For
1959 * example, "text / plain" is specifically forbidden by RFC 2616,
1960 * but "text/plain" is the only reasonable output, and this keeps
1961 * our code simple.
1963 * If the "charset" argument is not NULL, store the value of any
1964 * charset parameter there.
1966 * Example:
1967 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1968 * "text / plain" -> "text/plain"
1970 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1971 struct strbuf *charset)
1973 const char *p;
1975 strbuf_reset(type);
1976 strbuf_grow(type, raw->len);
1977 for (p = raw->buf; *p; p++) {
1978 if (isspace(*p))
1979 continue;
1980 if (*p == ';') {
1981 p++;
1982 break;
1984 strbuf_addch(type, tolower(*p));
1987 if (!charset)
1988 return;
1990 strbuf_reset(charset);
1991 while (*p) {
1992 while (isspace(*p) || *p == ';')
1993 p++;
1994 if (!extract_param(p, "charset", charset))
1995 return;
1996 while (*p && !isspace(*p))
1997 p++;
2000 if (!charset->len && starts_with(type->buf, "text/"))
2001 strbuf_addstr(charset, "ISO-8859-1");
2004 static void write_accept_language(struct strbuf *buf)
2007 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
2008 * that, q-value will be smaller than 0.001, the minimum q-value the
2009 * HTTP specification allows. See
2010 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
2012 const int MAX_DECIMAL_PLACES = 3;
2013 const int MAX_LANGUAGE_TAGS = 1000;
2014 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
2015 char **language_tags = NULL;
2016 int num_langs = 0;
2017 const char *s = get_preferred_languages();
2018 int i;
2019 struct strbuf tag = STRBUF_INIT;
2021 /* Don't add Accept-Language header if no language is preferred. */
2022 if (!s)
2023 return;
2026 * Split the colon-separated string of preferred languages into
2027 * language_tags array.
2029 do {
2030 /* collect language tag */
2031 for (; *s && (isalnum(*s) || *s == '_'); s++)
2032 strbuf_addch(&tag, *s == '_' ? '-' : *s);
2034 /* skip .codeset, @modifier and any other unnecessary parts */
2035 while (*s && *s != ':')
2036 s++;
2038 if (tag.len) {
2039 num_langs++;
2040 REALLOC_ARRAY(language_tags, num_langs);
2041 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
2042 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
2043 break;
2045 } while (*s++);
2047 /* write Accept-Language header into buf */
2048 if (num_langs) {
2049 int last_buf_len = 0;
2050 int max_q;
2051 int decimal_places;
2052 char q_format[32];
2054 /* add '*' */
2055 REALLOC_ARRAY(language_tags, num_langs + 1);
2056 language_tags[num_langs++] = xstrdup("*");
2058 /* compute decimal_places */
2059 for (max_q = 1, decimal_places = 0;
2060 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
2061 decimal_places++, max_q *= 10)
2064 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
2066 strbuf_addstr(buf, "Accept-Language: ");
2068 for (i = 0; i < num_langs; i++) {
2069 if (i > 0)
2070 strbuf_addstr(buf, ", ");
2072 strbuf_addstr(buf, language_tags[i]);
2074 if (i > 0)
2075 strbuf_addf(buf, q_format, max_q - i);
2077 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
2078 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
2079 break;
2082 last_buf_len = buf->len;
2086 for (i = 0; i < num_langs; i++)
2087 free(language_tags[i]);
2088 free(language_tags);
2092 * Get an Accept-Language header which indicates user's preferred languages.
2094 * Examples:
2095 * LANGUAGE= -> ""
2096 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
2097 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
2098 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
2099 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
2100 * LANGUAGE= LANG=C -> ""
2102 const char *http_get_accept_language_header(void)
2104 if (!cached_accept_language) {
2105 struct strbuf buf = STRBUF_INIT;
2106 write_accept_language(&buf);
2107 if (buf.len > 0)
2108 cached_accept_language = strbuf_detach(&buf, NULL);
2111 return cached_accept_language;
2114 static void http_opt_request_remainder(CURL *curl, off_t pos)
2116 char buf[128];
2117 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2118 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2121 /* http_request() targets */
2122 #define HTTP_REQUEST_STRBUF 0
2123 #define HTTP_REQUEST_FILE 1
2125 static int http_request(const char *url,
2126 void *result, int target,
2127 const struct http_get_options *options)
2129 struct active_request_slot *slot;
2130 struct slot_results results;
2131 struct curl_slist *headers = http_copy_default_headers();
2132 struct strbuf buf = STRBUF_INIT;
2133 const char *accept_language;
2134 int ret;
2136 slot = get_active_slot();
2137 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2139 if (!result) {
2140 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2141 } else {
2142 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2143 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2145 if (target == HTTP_REQUEST_FILE) {
2146 off_t posn = ftello(result);
2147 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2148 fwrite);
2149 if (posn > 0)
2150 http_opt_request_remainder(slot->curl, posn);
2151 } else
2152 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2153 fwrite_buffer);
2156 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2158 accept_language = http_get_accept_language_header();
2160 if (accept_language)
2161 headers = curl_slist_append(headers, accept_language);
2163 strbuf_addstr(&buf, "Pragma:");
2164 if (options && options->no_cache)
2165 strbuf_addstr(&buf, " no-cache");
2166 if (options && options->initial_request &&
2167 http_follow_config == HTTP_FOLLOW_INITIAL)
2168 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2170 headers = curl_slist_append(headers, buf.buf);
2172 /* Add additional headers here */
2173 if (options && options->extra_headers) {
2174 const struct string_list_item *item;
2175 if (options && options->extra_headers) {
2176 for_each_string_list_item(item, options->extra_headers) {
2177 headers = curl_slist_append(headers, item->string);
2182 headers = http_append_auth_header(&http_auth, headers);
2184 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2185 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2186 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2187 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2189 ret = run_one_slot(slot, &results);
2191 if (options && options->content_type) {
2192 struct strbuf raw = STRBUF_INIT;
2193 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2194 extract_content_type(&raw, options->content_type,
2195 options->charset);
2196 strbuf_release(&raw);
2199 if (options && options->effective_url)
2200 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2201 options->effective_url);
2203 curl_slist_free_all(headers);
2204 strbuf_release(&buf);
2206 return ret;
2210 * Update the "base" url to a more appropriate value, as deduced by
2211 * redirects seen when requesting a URL starting with "url".
2213 * The "asked" parameter is a URL that we asked curl to access, and must begin
2214 * with "base".
2216 * The "got" parameter is the URL that curl reported to us as where we ended
2217 * up.
2219 * Returns 1 if we updated the base url, 0 otherwise.
2221 * Our basic strategy is to compare "base" and "asked" to find the bits
2222 * specific to our request. We then strip those bits off of "got" to yield the
2223 * new base. So for example, if our base is "http://example.com/foo.git",
2224 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2225 * with "https://other.example.com/foo.git/info/refs". We would want the
2226 * new URL to become "https://other.example.com/foo.git".
2228 * Note that this assumes a sane redirect scheme. It's entirely possible
2229 * in the example above to end up at a URL that does not even end in
2230 * "info/refs". In such a case we die. There's not much we can do, such a
2231 * scheme is unlikely to represent a real git repository, and failing to
2232 * rewrite the base opens options for malicious redirects to do funny things.
2234 static int update_url_from_redirect(struct strbuf *base,
2235 const char *asked,
2236 const struct strbuf *got)
2238 const char *tail;
2239 size_t new_len;
2241 if (!strcmp(asked, got->buf))
2242 return 0;
2244 if (!skip_prefix(asked, base->buf, &tail))
2245 BUG("update_url_from_redirect: %s is not a superset of %s",
2246 asked, base->buf);
2248 new_len = got->len;
2249 if (!strip_suffix_mem(got->buf, &new_len, tail))
2250 die(_("unable to update url base from redirection:\n"
2251 " asked for: %s\n"
2252 " redirect: %s"),
2253 asked, got->buf);
2255 strbuf_reset(base);
2256 strbuf_add(base, got->buf, new_len);
2258 return 1;
2261 static int http_request_reauth(const char *url,
2262 void *result, int target,
2263 struct http_get_options *options)
2265 int i = 3;
2266 int ret;
2268 if (always_auth_proactively())
2269 credential_fill(&http_auth, 1);
2271 ret = http_request(url, result, target, options);
2273 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2274 return ret;
2276 if (options && options->effective_url && options->base_url) {
2277 if (update_url_from_redirect(options->base_url,
2278 url, options->effective_url)) {
2279 credential_from_url(&http_auth, options->base_url->buf);
2280 url = options->effective_url->buf;
2284 while (ret == HTTP_REAUTH && --i) {
2286 * The previous request may have put cruft into our output stream; we
2287 * should clear it out before making our next request.
2289 switch (target) {
2290 case HTTP_REQUEST_STRBUF:
2291 strbuf_reset(result);
2292 break;
2293 case HTTP_REQUEST_FILE:
2294 if (fflush(result)) {
2295 error_errno("unable to flush a file");
2296 return HTTP_START_FAILED;
2298 rewind(result);
2299 if (ftruncate(fileno(result), 0) < 0) {
2300 error_errno("unable to truncate a file");
2301 return HTTP_START_FAILED;
2303 break;
2304 default:
2305 BUG("Unknown http_request target");
2308 credential_fill(&http_auth, 1);
2310 ret = http_request(url, result, target, options);
2312 return ret;
2315 int http_get_strbuf(const char *url,
2316 struct strbuf *result,
2317 struct http_get_options *options)
2319 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2323 * Downloads a URL and stores the result in the given file.
2325 * If a previous interrupted download is detected (i.e. a previous temporary
2326 * file is still around) the download is resumed.
2328 int http_get_file(const char *url, const char *filename,
2329 struct http_get_options *options)
2331 int ret;
2332 struct strbuf tmpfile = STRBUF_INIT;
2333 FILE *result;
2335 strbuf_addf(&tmpfile, "%s.temp", filename);
2336 result = fopen(tmpfile.buf, "a");
2337 if (!result) {
2338 error("Unable to open local file %s", tmpfile.buf);
2339 ret = HTTP_ERROR;
2340 goto cleanup;
2343 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2344 fclose(result);
2346 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2347 ret = HTTP_ERROR;
2348 cleanup:
2349 strbuf_release(&tmpfile);
2350 return ret;
2353 int http_fetch_ref(const char *base, struct ref *ref)
2355 struct http_get_options options = {0};
2356 char *url;
2357 struct strbuf buffer = STRBUF_INIT;
2358 int ret = -1;
2360 options.no_cache = 1;
2362 url = quote_ref_url(base, ref->name);
2363 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2364 strbuf_rtrim(&buffer);
2365 if (buffer.len == the_hash_algo->hexsz)
2366 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2367 else if (starts_with(buffer.buf, "ref: ")) {
2368 ref->symref = xstrdup(buffer.buf + 5);
2369 ret = 0;
2373 strbuf_release(&buffer);
2374 free(url);
2375 return ret;
2378 /* Helpers for fetching packs */
2379 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2381 char *url, *tmp;
2382 struct strbuf buf = STRBUF_INIT;
2384 if (http_is_verbose)
2385 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2387 end_url_with_slash(&buf, base_url);
2388 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2389 url = strbuf_detach(&buf, NULL);
2391 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2392 tmp = strbuf_detach(&buf, NULL);
2394 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2395 error("Unable to get pack index %s", url);
2396 FREE_AND_NULL(tmp);
2399 free(url);
2400 return tmp;
2403 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2404 unsigned char *sha1, const char *base_url)
2406 struct packed_git *new_pack;
2407 char *tmp_idx = NULL;
2408 int ret;
2410 if (has_pack_index(sha1)) {
2411 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2412 if (!new_pack)
2413 return -1; /* parse_pack_index() already issued error message */
2414 goto add_pack;
2417 tmp_idx = fetch_pack_index(sha1, base_url);
2418 if (!tmp_idx)
2419 return -1;
2421 new_pack = parse_pack_index(sha1, tmp_idx);
2422 if (!new_pack) {
2423 unlink(tmp_idx);
2424 free(tmp_idx);
2426 return -1; /* parse_pack_index() already issued error message */
2429 ret = verify_pack_index(new_pack);
2430 if (!ret) {
2431 close_pack_index(new_pack);
2432 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2434 free(tmp_idx);
2435 if (ret)
2436 return -1;
2438 add_pack:
2439 new_pack->next = *packs_head;
2440 *packs_head = new_pack;
2441 return 0;
2444 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2446 struct http_get_options options = {0};
2447 int ret = 0;
2448 char *url;
2449 const char *data;
2450 struct strbuf buf = STRBUF_INIT;
2451 struct object_id oid;
2453 end_url_with_slash(&buf, base_url);
2454 strbuf_addstr(&buf, "objects/info/packs");
2455 url = strbuf_detach(&buf, NULL);
2457 options.no_cache = 1;
2458 ret = http_get_strbuf(url, &buf, &options);
2459 if (ret != HTTP_OK)
2460 goto cleanup;
2462 data = buf.buf;
2463 while (*data) {
2464 if (skip_prefix(data, "P pack-", &data) &&
2465 !parse_oid_hex(data, &oid, &data) &&
2466 skip_prefix(data, ".pack", &data) &&
2467 (*data == '\n' || *data == '\0')) {
2468 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2469 } else {
2470 data = strchrnul(data, '\n');
2472 if (*data)
2473 data++; /* skip past newline */
2476 cleanup:
2477 free(url);
2478 strbuf_release(&buf);
2479 return ret;
2482 void release_http_pack_request(struct http_pack_request *preq)
2484 if (preq->packfile) {
2485 fclose(preq->packfile);
2486 preq->packfile = NULL;
2488 preq->slot = NULL;
2489 strbuf_release(&preq->tmpfile);
2490 curl_slist_free_all(preq->headers);
2491 free(preq->url);
2492 free(preq);
2495 static const char *default_index_pack_args[] =
2496 {"index-pack", "--stdin", NULL};
2498 int finish_http_pack_request(struct http_pack_request *preq)
2500 struct child_process ip = CHILD_PROCESS_INIT;
2501 int tmpfile_fd;
2502 int ret = 0;
2504 fclose(preq->packfile);
2505 preq->packfile = NULL;
2507 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2509 ip.git_cmd = 1;
2510 ip.in = tmpfile_fd;
2511 strvec_pushv(&ip.args, preq->index_pack_args ?
2512 preq->index_pack_args :
2513 default_index_pack_args);
2515 if (preq->preserve_index_pack_stdout)
2516 ip.out = 0;
2517 else
2518 ip.no_stdout = 1;
2520 if (run_command(&ip)) {
2521 ret = -1;
2522 goto cleanup;
2525 cleanup:
2526 close(tmpfile_fd);
2527 unlink(preq->tmpfile.buf);
2528 return ret;
2531 void http_install_packfile(struct packed_git *p,
2532 struct packed_git **list_to_remove_from)
2534 struct packed_git **lst = list_to_remove_from;
2536 while (*lst != p)
2537 lst = &((*lst)->next);
2538 *lst = (*lst)->next;
2540 install_packed_git(the_repository, p);
2543 struct http_pack_request *new_http_pack_request(
2544 const unsigned char *packed_git_hash, const char *base_url) {
2546 struct strbuf buf = STRBUF_INIT;
2548 end_url_with_slash(&buf, base_url);
2549 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2550 hash_to_hex(packed_git_hash));
2551 return new_direct_http_pack_request(packed_git_hash,
2552 strbuf_detach(&buf, NULL));
2555 struct http_pack_request *new_direct_http_pack_request(
2556 const unsigned char *packed_git_hash, char *url)
2558 off_t prev_posn = 0;
2559 struct http_pack_request *preq;
2561 CALLOC_ARRAY(preq, 1);
2562 strbuf_init(&preq->tmpfile, 0);
2564 preq->url = url;
2566 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2567 preq->packfile = fopen(preq->tmpfile.buf, "a");
2568 if (!preq->packfile) {
2569 error("Unable to open local file %s for pack",
2570 preq->tmpfile.buf);
2571 goto abort;
2574 preq->slot = get_active_slot();
2575 preq->headers = object_request_headers();
2576 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2577 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2578 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2579 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER, preq->headers);
2582 * If there is data present from a previous transfer attempt,
2583 * resume where it left off
2585 prev_posn = ftello(preq->packfile);
2586 if (prev_posn>0) {
2587 if (http_is_verbose)
2588 fprintf(stderr,
2589 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2590 hash_to_hex(packed_git_hash),
2591 (uintmax_t)prev_posn);
2592 http_opt_request_remainder(preq->slot->curl, prev_posn);
2595 return preq;
2597 abort:
2598 strbuf_release(&preq->tmpfile);
2599 free(preq->url);
2600 free(preq);
2601 return NULL;
2604 /* Helpers for fetching objects (loose) */
2605 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2606 void *data)
2608 unsigned char expn[4096];
2609 size_t size = eltsize * nmemb;
2610 int posn = 0;
2611 struct http_object_request *freq = data;
2612 struct active_request_slot *slot = freq->slot;
2614 if (slot) {
2615 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2616 &slot->http_code);
2617 if (c != CURLE_OK)
2618 BUG("curl_easy_getinfo for HTTP code failed: %s",
2619 curl_easy_strerror(c));
2620 if (slot->http_code >= 300)
2621 return nmemb;
2624 do {
2625 ssize_t retval = xwrite(freq->localfile,
2626 (char *) ptr + posn, size - posn);
2627 if (retval < 0)
2628 return posn / eltsize;
2629 posn += retval;
2630 } while (posn < size);
2632 freq->stream.avail_in = size;
2633 freq->stream.next_in = (void *)ptr;
2634 do {
2635 freq->stream.next_out = expn;
2636 freq->stream.avail_out = sizeof(expn);
2637 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2638 the_hash_algo->update_fn(&freq->c, expn,
2639 sizeof(expn) - freq->stream.avail_out);
2640 } while (freq->stream.avail_in && freq->zret == Z_OK);
2641 return nmemb;
2644 struct http_object_request *new_http_object_request(const char *base_url,
2645 const struct object_id *oid)
2647 char *hex = oid_to_hex(oid);
2648 struct strbuf filename = STRBUF_INIT;
2649 struct strbuf prevfile = STRBUF_INIT;
2650 int prevlocal;
2651 char prev_buf[PREV_BUF_SIZE];
2652 ssize_t prev_read = 0;
2653 off_t prev_posn = 0;
2654 struct http_object_request *freq;
2656 CALLOC_ARRAY(freq, 1);
2657 strbuf_init(&freq->tmpfile, 0);
2658 oidcpy(&freq->oid, oid);
2659 freq->localfile = -1;
2661 loose_object_path(the_repository, &filename, oid);
2662 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2664 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2665 unlink_or_warn(prevfile.buf);
2666 rename(freq->tmpfile.buf, prevfile.buf);
2667 unlink_or_warn(freq->tmpfile.buf);
2668 strbuf_release(&filename);
2670 if (freq->localfile != -1)
2671 error("fd leakage in start: %d", freq->localfile);
2672 freq->localfile = open(freq->tmpfile.buf,
2673 O_WRONLY | O_CREAT | O_EXCL, 0666);
2675 * This could have failed due to the "lazy directory creation";
2676 * try to mkdir the last path component.
2678 if (freq->localfile < 0 && errno == ENOENT) {
2679 char *dir = strrchr(freq->tmpfile.buf, '/');
2680 if (dir) {
2681 *dir = 0;
2682 mkdir(freq->tmpfile.buf, 0777);
2683 *dir = '/';
2685 freq->localfile = open(freq->tmpfile.buf,
2686 O_WRONLY | O_CREAT | O_EXCL, 0666);
2689 if (freq->localfile < 0) {
2690 error_errno("Couldn't create temporary file %s",
2691 freq->tmpfile.buf);
2692 goto abort;
2695 git_inflate_init(&freq->stream);
2697 the_hash_algo->init_fn(&freq->c);
2699 freq->url = get_remote_object_url(base_url, hex, 0);
2702 * If a previous temp file is present, process what was already
2703 * fetched.
2705 prevlocal = open(prevfile.buf, O_RDONLY);
2706 if (prevlocal != -1) {
2707 do {
2708 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2709 if (prev_read>0) {
2710 if (fwrite_sha1_file(prev_buf,
2712 prev_read,
2713 freq) == prev_read) {
2714 prev_posn += prev_read;
2715 } else {
2716 prev_read = -1;
2719 } while (prev_read > 0);
2720 close(prevlocal);
2722 unlink_or_warn(prevfile.buf);
2723 strbuf_release(&prevfile);
2726 * Reset inflate/SHA1 if there was an error reading the previous temp
2727 * file; also rewind to the beginning of the local file.
2729 if (prev_read == -1) {
2730 git_inflate_end(&freq->stream);
2731 memset(&freq->stream, 0, sizeof(freq->stream));
2732 git_inflate_init(&freq->stream);
2733 the_hash_algo->init_fn(&freq->c);
2734 if (prev_posn>0) {
2735 prev_posn = 0;
2736 lseek(freq->localfile, 0, SEEK_SET);
2737 if (ftruncate(freq->localfile, 0) < 0) {
2738 error_errno("Couldn't truncate temporary file %s",
2739 freq->tmpfile.buf);
2740 goto abort;
2745 freq->slot = get_active_slot();
2746 freq->headers = object_request_headers();
2748 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2749 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2750 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2751 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2752 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2753 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, freq->headers);
2756 * If we have successfully processed data from a previous fetch
2757 * attempt, only fetch the data we don't already have.
2759 if (prev_posn>0) {
2760 if (http_is_verbose)
2761 fprintf(stderr,
2762 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2763 hex, (uintmax_t)prev_posn);
2764 http_opt_request_remainder(freq->slot->curl, prev_posn);
2767 return freq;
2769 abort:
2770 strbuf_release(&prevfile);
2771 free(freq->url);
2772 free(freq);
2773 return NULL;
2776 void process_http_object_request(struct http_object_request *freq)
2778 if (!freq->slot)
2779 return;
2780 freq->curl_result = freq->slot->curl_result;
2781 freq->http_code = freq->slot->http_code;
2782 freq->slot = NULL;
2785 int finish_http_object_request(struct http_object_request *freq)
2787 struct stat st;
2788 struct strbuf filename = STRBUF_INIT;
2790 close(freq->localfile);
2791 freq->localfile = -1;
2793 process_http_object_request(freq);
2795 if (freq->http_code == 416) {
2796 warning("requested range invalid; we may already have all the data.");
2797 } else if (freq->curl_result != CURLE_OK) {
2798 if (stat(freq->tmpfile.buf, &st) == 0)
2799 if (st.st_size == 0)
2800 unlink_or_warn(freq->tmpfile.buf);
2801 return -1;
2804 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2805 if (freq->zret != Z_STREAM_END) {
2806 unlink_or_warn(freq->tmpfile.buf);
2807 return -1;
2809 if (!oideq(&freq->oid, &freq->real_oid)) {
2810 unlink_or_warn(freq->tmpfile.buf);
2811 return -1;
2813 loose_object_path(the_repository, &filename, &freq->oid);
2814 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2815 strbuf_release(&filename);
2817 return freq->rename;
2820 void abort_http_object_request(struct http_object_request **freq_p)
2822 struct http_object_request *freq = *freq_p;
2823 unlink_or_warn(freq->tmpfile.buf);
2825 release_http_object_request(freq_p);
2828 void release_http_object_request(struct http_object_request **freq_p)
2830 struct http_object_request *freq = *freq_p;
2831 if (freq->localfile != -1) {
2832 close(freq->localfile);
2833 freq->localfile = -1;
2835 FREE_AND_NULL(freq->url);
2836 if (freq->slot) {
2837 freq->slot->callback_func = NULL;
2838 freq->slot->callback_data = NULL;
2839 release_active_slot(freq->slot);
2840 freq->slot = NULL;
2842 curl_slist_free_all(freq->headers);
2843 strbuf_release(&freq->tmpfile);
2844 git_inflate_end(&freq->stream);
2846 free(freq);
2847 *freq_p = NULL;