The second batch
[git/gitster.git] / http.c
blob752c879c1f159495e7a4c3647bd0a078f1aa29f8
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 string_list extra_http_headers = STRING_LIST_INIT_DUP;
133 static struct curl_slist *host_resolutions;
135 static struct active_request_slot *active_queue_head;
137 static char *cached_accept_language;
139 static char *http_ssl_backend;
141 static int http_schannel_check_revoke = 1;
143 * With the backend being set to `schannel`, setting sslCAinfo would override
144 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
145 * by default.
147 static int http_schannel_use_ssl_cainfo;
149 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
151 size_t size = eltsize * nmemb;
152 struct buffer *buffer = buffer_;
154 if (size > buffer->buf.len - buffer->posn)
155 size = buffer->buf.len - buffer->posn;
156 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
157 buffer->posn += size;
159 return size / eltsize;
162 int seek_buffer(void *clientp, curl_off_t offset, int origin)
164 struct buffer *buffer = clientp;
166 if (origin != SEEK_SET)
167 BUG("seek_buffer only handles SEEK_SET");
168 if (offset < 0 || offset >= buffer->buf.len) {
169 error("curl seek would be outside of buffer");
170 return CURL_SEEKFUNC_FAIL;
173 buffer->posn = offset;
174 return CURL_SEEKFUNC_OK;
177 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
179 size_t size = eltsize * nmemb;
180 struct strbuf *buffer = buffer_;
182 strbuf_add(buffer, ptr, size);
183 return nmemb;
187 * A folded header continuation line starts with any number of spaces or
188 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
189 * It is not a continuation line if the line starts with any other character.
191 static inline int is_hdr_continuation(const char *ptr, const size_t size)
193 return size && (*ptr == ' ' || *ptr == '\t');
196 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
198 size_t size = eltsize * nmemb;
199 struct strvec *values = &http_auth.wwwauth_headers;
200 struct strbuf buf = STRBUF_INIT;
201 const char *val;
202 size_t val_len;
205 * Header lines may not come NULL-terminated from libcurl so we must
206 * limit all scans to the maximum length of the header line, or leverage
207 * strbufs for all operations.
209 * In addition, it is possible that header values can be split over
210 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
211 * but older servers may still emit them. A continuation header field
212 * value is identified as starting with a space or horizontal tab.
214 * The formal definition of a header field as given in RFC 7230 is:
216 * header-field = field-name ":" OWS field-value OWS
218 * field-name = token
219 * field-value = *( field-content / obs-fold )
220 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
221 * field-vchar = VCHAR / obs-text
223 * obs-fold = CRLF 1*( SP / HTAB )
224 * ; obsolete line folding
225 * ; see Section 3.2.4
228 /* Start of a new WWW-Authenticate header */
229 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
230 strbuf_add(&buf, val, val_len);
233 * Strip the CRLF that should be present at the end of each
234 * field as well as any trailing or leading whitespace from the
235 * value.
237 strbuf_trim(&buf);
239 strvec_push(values, buf.buf);
240 http_auth.header_is_last_match = 1;
241 goto exit;
245 * This line could be a continuation of the previously matched header
246 * field. If this is the case then we should append this value to the
247 * end of the previously consumed value.
249 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
251 * Trim the CRLF and any leading or trailing from this line.
253 strbuf_add(&buf, ptr, size);
254 strbuf_trim(&buf);
257 * At this point we should always have at least one existing
258 * value, even if it is empty. Do not bother appending the new
259 * value if this continuation header is itself empty.
261 if (!values->nr) {
262 BUG("should have at least one existing header value");
263 } else if (buf.len) {
264 char *prev = xstrdup(values->v[values->nr - 1]);
266 /* Join two non-empty values with a single space. */
267 const char *const sp = *prev ? " " : "";
269 strvec_pop(values);
270 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
271 free(prev);
274 goto exit;
277 /* Not a continuation of a previously matched auth header line. */
278 http_auth.header_is_last_match = 0;
281 * If this is a HTTP status line and not a header field, this signals
282 * a different HTTP response. libcurl writes all the output of all
283 * response headers of all responses, including redirects.
284 * We only care about the last HTTP request response's headers so clear
285 * the existing array.
287 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
288 strvec_clear(values);
290 exit:
291 strbuf_release(&buf);
292 return size;
295 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
296 void *data UNUSED)
298 return nmemb;
301 static struct curl_slist *object_request_headers(void)
303 return curl_slist_append(http_copy_default_headers(), "Pragma:");
306 static void closedown_active_slot(struct active_request_slot *slot)
308 active_requests--;
309 slot->in_use = 0;
312 static void finish_active_slot(struct active_request_slot *slot)
314 closedown_active_slot(slot);
315 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
317 if (slot->finished)
318 (*slot->finished) = 1;
320 /* Store slot results so they can be read after the slot is reused */
321 if (slot->results) {
322 slot->results->curl_result = slot->curl_result;
323 slot->results->http_code = slot->http_code;
324 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
325 &slot->results->auth_avail);
327 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
328 &slot->results->http_connectcode);
331 /* Run callback if appropriate */
332 if (slot->callback_func)
333 slot->callback_func(slot->callback_data);
336 static void xmulti_remove_handle(struct active_request_slot *slot)
338 curl_multi_remove_handle(curlm, slot->curl);
341 static void process_curl_messages(void)
343 int num_messages;
344 struct active_request_slot *slot;
345 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
347 while (curl_message != NULL) {
348 if (curl_message->msg == CURLMSG_DONE) {
349 int curl_result = curl_message->data.result;
350 slot = active_queue_head;
351 while (slot != NULL &&
352 slot->curl != curl_message->easy_handle)
353 slot = slot->next;
354 if (slot) {
355 xmulti_remove_handle(slot);
356 slot->curl_result = curl_result;
357 finish_active_slot(slot);
358 } else {
359 fprintf(stderr, "Received DONE message for unknown request!\n");
361 } else {
362 fprintf(stderr, "Unknown CURL message received: %d\n",
363 (int)curl_message->msg);
365 curl_message = curl_multi_info_read(curlm, &num_messages);
369 static int http_options(const char *var, const char *value,
370 const struct config_context *ctx, void *data)
372 if (!strcmp("http.version", var)) {
373 return git_config_string(&curl_http_version, var, value);
375 if (!strcmp("http.sslverify", var)) {
376 curl_ssl_verify = git_config_bool(var, value);
377 return 0;
379 if (!strcmp("http.sslcipherlist", var))
380 return git_config_string(&ssl_cipherlist, var, value);
381 if (!strcmp("http.sslversion", var))
382 return git_config_string(&ssl_version, var, value);
383 if (!strcmp("http.sslcert", var))
384 return git_config_pathname(&ssl_cert, var, value);
385 if (!strcmp("http.sslcerttype", var))
386 return git_config_string(&ssl_cert_type, var, value);
387 if (!strcmp("http.sslkey", var))
388 return git_config_pathname(&ssl_key, var, value);
389 if (!strcmp("http.sslkeytype", var))
390 return git_config_string(&ssl_key_type, var, value);
391 if (!strcmp("http.sslcapath", var))
392 return git_config_pathname(&ssl_capath, var, value);
393 if (!strcmp("http.sslcainfo", var))
394 return git_config_pathname(&ssl_cainfo, var, value);
395 if (!strcmp("http.sslcertpasswordprotected", var)) {
396 ssl_cert_password_required = git_config_bool(var, value);
397 return 0;
399 if (!strcmp("http.ssltry", var)) {
400 curl_ssl_try = git_config_bool(var, value);
401 return 0;
403 if (!strcmp("http.sslbackend", var)) {
404 free(http_ssl_backend);
405 http_ssl_backend = xstrdup_or_null(value);
406 return 0;
409 if (!strcmp("http.schannelcheckrevoke", var)) {
410 http_schannel_check_revoke = git_config_bool(var, value);
411 return 0;
414 if (!strcmp("http.schannelusesslcainfo", var)) {
415 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
416 return 0;
419 if (!strcmp("http.minsessions", var)) {
420 min_curl_sessions = git_config_int(var, value, ctx->kvi);
421 if (min_curl_sessions > 1)
422 min_curl_sessions = 1;
423 return 0;
425 if (!strcmp("http.maxrequests", var)) {
426 max_requests = git_config_int(var, value, ctx->kvi);
427 return 0;
429 if (!strcmp("http.lowspeedlimit", var)) {
430 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
431 return 0;
433 if (!strcmp("http.lowspeedtime", var)) {
434 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
435 return 0;
438 if (!strcmp("http.noepsv", var)) {
439 curl_ftp_no_epsv = git_config_bool(var, value);
440 return 0;
442 if (!strcmp("http.proxy", var))
443 return git_config_string(&curl_http_proxy, var, value);
445 if (!strcmp("http.proxyauthmethod", var))
446 return git_config_string(&http_proxy_authmethod, var, value);
448 if (!strcmp("http.proxysslcert", var))
449 return git_config_string(&http_proxy_ssl_cert, var, value);
451 if (!strcmp("http.proxysslkey", var))
452 return git_config_string(&http_proxy_ssl_key, var, value);
454 if (!strcmp("http.proxysslcainfo", var))
455 return git_config_string(&http_proxy_ssl_ca_info, var, value);
457 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
458 proxy_ssl_cert_password_required = git_config_bool(var, value);
459 return 0;
462 if (!strcmp("http.cookiefile", var))
463 return git_config_pathname(&curl_cookie_file, var, value);
464 if (!strcmp("http.savecookies", var)) {
465 curl_save_cookies = git_config_bool(var, value);
466 return 0;
469 if (!strcmp("http.postbuffer", var)) {
470 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
471 if (http_post_buffer < 0)
472 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
473 if (http_post_buffer < LARGE_PACKET_MAX)
474 http_post_buffer = LARGE_PACKET_MAX;
475 return 0;
478 if (!strcmp("http.useragent", var))
479 return git_config_string(&user_agent, var, value);
481 if (!strcmp("http.emptyauth", var)) {
482 if (value && !strcmp("auto", value))
483 curl_empty_auth = -1;
484 else
485 curl_empty_auth = git_config_bool(var, value);
486 return 0;
489 if (!strcmp("http.delegation", var)) {
490 #ifdef CURLGSSAPI_DELEGATION_FLAG
491 return git_config_string(&curl_deleg, var, value);
492 #else
493 warning(_("Delegation control is not supported with cURL < 7.22.0"));
494 return 0;
495 #endif
498 if (!strcmp("http.pinnedpubkey", var)) {
499 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
500 return git_config_pathname(&ssl_pinnedkey, var, value);
501 #else
502 warning(_("Public key pinning not supported with cURL < 7.39.0"));
503 return 0;
504 #endif
507 if (!strcmp("http.extraheader", var)) {
508 if (!value) {
509 return config_error_nonbool(var);
510 } else if (!*value) {
511 string_list_clear(&extra_http_headers, 0);
512 } else {
513 string_list_append(&extra_http_headers, value);
515 return 0;
518 if (!strcmp("http.curloptresolve", var)) {
519 if (!value) {
520 return config_error_nonbool(var);
521 } else if (!*value) {
522 curl_slist_free_all(host_resolutions);
523 host_resolutions = NULL;
524 } else {
525 host_resolutions = curl_slist_append(host_resolutions, value);
527 return 0;
530 if (!strcmp("http.followredirects", var)) {
531 if (value && !strcmp(value, "initial"))
532 http_follow_config = HTTP_FOLLOW_INITIAL;
533 else if (git_config_bool(var, value))
534 http_follow_config = HTTP_FOLLOW_ALWAYS;
535 else
536 http_follow_config = HTTP_FOLLOW_NONE;
537 return 0;
540 /* Fall back on the default ones */
541 return git_default_config(var, value, ctx, data);
544 static int curl_empty_auth_enabled(void)
546 if (curl_empty_auth >= 0)
547 return curl_empty_auth;
550 * In the automatic case, kick in the empty-auth
551 * hack as long as we would potentially try some
552 * method more exotic than "Basic" or "Digest".
554 * But only do this when this is our second or
555 * subsequent request, as by then we know what
556 * methods are available.
558 if (http_auth_methods_restricted &&
559 (http_auth_methods & ~empty_auth_useless))
560 return 1;
561 return 0;
564 struct curl_slist *http_append_auth_header(const struct credential *c,
565 struct curl_slist *headers)
567 if (c->authtype && c->credential) {
568 struct strbuf auth = STRBUF_INIT;
569 strbuf_addf(&auth, "Authorization: %s %s",
570 c->authtype, c->credential);
571 headers = curl_slist_append(headers, auth.buf);
572 strbuf_release(&auth);
574 return headers;
577 static void init_curl_http_auth(CURL *result)
579 if ((!http_auth.username || !*http_auth.username) &&
580 (!http_auth.credential || !*http_auth.credential)) {
581 if (curl_empty_auth_enabled())
582 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
583 return;
586 credential_fill(&http_auth, 1);
588 if (http_auth.password) {
589 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
590 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
594 /* *var must be free-able */
595 static void var_override(const char **var, char *value)
597 if (value) {
598 free((void *)*var);
599 *var = xstrdup(value);
603 static void set_proxyauth_name_password(CURL *result)
605 if (proxy_auth.password) {
606 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
607 proxy_auth.username);
608 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
609 proxy_auth.password);
610 } else if (proxy_auth.authtype && proxy_auth.credential) {
611 curl_easy_setopt(result, CURLOPT_PROXYHEADER,
612 http_append_auth_header(&proxy_auth, NULL));
616 static void init_curl_proxy_auth(CURL *result)
618 if (proxy_auth.username) {
619 if (!proxy_auth.password && !proxy_auth.credential)
620 credential_fill(&proxy_auth, 1);
621 set_proxyauth_name_password(result);
624 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
626 if (http_proxy_authmethod) {
627 int i;
628 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
629 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
630 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
631 proxy_authmethods[i].curlauth_param);
632 break;
635 if (i == ARRAY_SIZE(proxy_authmethods)) {
636 warning("unsupported proxy authentication method %s: using anyauth",
637 http_proxy_authmethod);
638 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
641 else
642 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
645 static int has_cert_password(void)
647 if (ssl_cert == NULL || ssl_cert_password_required != 1)
648 return 0;
649 if (!cert_auth.password) {
650 cert_auth.protocol = xstrdup("cert");
651 cert_auth.host = xstrdup("");
652 cert_auth.username = xstrdup("");
653 cert_auth.path = xstrdup(ssl_cert);
654 credential_fill(&cert_auth, 0);
656 return 1;
659 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
660 static int has_proxy_cert_password(void)
662 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
663 return 0;
664 if (!proxy_cert_auth.password) {
665 proxy_cert_auth.protocol = xstrdup("cert");
666 proxy_cert_auth.host = xstrdup("");
667 proxy_cert_auth.username = xstrdup("");
668 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
669 credential_fill(&proxy_cert_auth, 0);
671 return 1;
673 #endif
675 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
676 static void set_curl_keepalive(CURL *c)
678 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
681 #else
682 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
684 int ka = 1;
685 int rc;
686 socklen_t len = (socklen_t)sizeof(ka);
688 if (type != CURLSOCKTYPE_IPCXN)
689 return 0;
691 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
692 if (rc < 0)
693 warning_errno("unable to set SO_KEEPALIVE on socket");
695 return CURL_SOCKOPT_OK;
698 static void set_curl_keepalive(CURL *c)
700 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
702 #endif
704 /* Return 1 if redactions have been made, 0 otherwise. */
705 static int redact_sensitive_header(struct strbuf *header, size_t offset)
707 int ret = 0;
708 const char *sensitive_header;
710 if (trace_curl_redact &&
711 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
712 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
713 /* The first token is the type, which is OK to log */
714 while (isspace(*sensitive_header))
715 sensitive_header++;
716 while (*sensitive_header && !isspace(*sensitive_header))
717 sensitive_header++;
718 /* Everything else is opaque and possibly sensitive */
719 strbuf_setlen(header, sensitive_header - header->buf);
720 strbuf_addstr(header, " <redacted>");
721 ret = 1;
722 } else if (trace_curl_redact &&
723 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
724 struct strbuf redacted_header = STRBUF_INIT;
725 const char *cookie;
727 while (isspace(*sensitive_header))
728 sensitive_header++;
730 cookie = sensitive_header;
732 while (cookie) {
733 char *equals;
734 char *semicolon = strstr(cookie, "; ");
735 if (semicolon)
736 *semicolon = 0;
737 equals = strchrnul(cookie, '=');
738 if (!equals) {
739 /* invalid cookie, just append and continue */
740 strbuf_addstr(&redacted_header, cookie);
741 continue;
743 strbuf_add(&redacted_header, cookie, equals - cookie);
744 strbuf_addstr(&redacted_header, "=<redacted>");
745 if (semicolon) {
747 * There are more cookies. (Or, for some
748 * reason, the input string ends in "; ".)
750 strbuf_addstr(&redacted_header, "; ");
751 cookie = semicolon + strlen("; ");
752 } else {
753 cookie = NULL;
757 strbuf_setlen(header, sensitive_header - header->buf);
758 strbuf_addbuf(header, &redacted_header);
759 ret = 1;
761 return ret;
764 static int match_curl_h2_trace(const char *line, const char **out)
766 const char *p;
769 * curl prior to 8.1.0 gives us:
771 * h2h3 [<header-name>: <header-val>]
773 * Starting in 8.1.0, the first token became just "h2".
775 if (skip_iprefix(line, "h2h3 [", out) ||
776 skip_iprefix(line, "h2 [", out))
777 return 1;
780 * curl 8.3.0 uses:
781 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
782 * where <stream-id> is numeric.
784 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
785 while (isdigit(*p))
786 p++;
787 if (skip_prefix(p, "] [", out))
788 return 1;
791 return 0;
794 /* Redact headers in info */
795 static void redact_sensitive_info_header(struct strbuf *header)
797 const char *sensitive_header;
799 if (trace_curl_redact &&
800 match_curl_h2_trace(header->buf, &sensitive_header)) {
801 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
802 /* redaction ate our closing bracket */
803 strbuf_addch(header, ']');
808 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
810 struct strbuf out = STRBUF_INIT;
811 struct strbuf **headers, **header;
813 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
814 text, (long)size, (long)size);
815 trace_strbuf(&trace_curl, &out);
816 strbuf_reset(&out);
817 strbuf_add(&out, ptr, size);
818 headers = strbuf_split_max(&out, '\n', 0);
820 for (header = headers; *header; header++) {
821 if (hide_sensitive_header)
822 redact_sensitive_header(*header, 0);
823 strbuf_insertstr((*header), 0, text);
824 strbuf_insertstr((*header), strlen(text), ": ");
825 strbuf_rtrim((*header));
826 strbuf_addch((*header), '\n');
827 trace_strbuf(&trace_curl, (*header));
829 strbuf_list_free(headers);
830 strbuf_release(&out);
833 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
835 size_t i;
836 struct strbuf out = STRBUF_INIT;
837 unsigned int width = 60;
839 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
840 text, (long)size, (long)size);
841 trace_strbuf(&trace_curl, &out);
843 for (i = 0; i < size; i += width) {
844 size_t w;
846 strbuf_reset(&out);
847 strbuf_addf(&out, "%s: ", text);
848 for (w = 0; (w < width) && (i + w < size); w++) {
849 unsigned char ch = ptr[i + w];
851 strbuf_addch(&out,
852 (ch >= 0x20) && (ch < 0x80)
853 ? ch : '.');
855 strbuf_addch(&out, '\n');
856 trace_strbuf(&trace_curl, &out);
858 strbuf_release(&out);
861 static void curl_dump_info(char *data, size_t size)
863 struct strbuf buf = STRBUF_INIT;
865 strbuf_add(&buf, data, size);
867 redact_sensitive_info_header(&buf);
868 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
870 strbuf_release(&buf);
873 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
874 char *data, size_t size,
875 void *userp UNUSED)
877 const char *text;
878 enum { NO_FILTER = 0, DO_FILTER = 1 };
880 switch (type) {
881 case CURLINFO_TEXT:
882 curl_dump_info(data, size);
883 break;
884 case CURLINFO_HEADER_OUT:
885 text = "=> Send header";
886 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
887 break;
888 case CURLINFO_DATA_OUT:
889 if (trace_curl_data) {
890 text = "=> Send data";
891 curl_dump_data(text, (unsigned char *)data, size);
893 break;
894 case CURLINFO_SSL_DATA_OUT:
895 if (trace_curl_data) {
896 text = "=> Send SSL data";
897 curl_dump_data(text, (unsigned char *)data, size);
899 break;
900 case CURLINFO_HEADER_IN:
901 text = "<= Recv header";
902 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
903 break;
904 case CURLINFO_DATA_IN:
905 if (trace_curl_data) {
906 text = "<= Recv data";
907 curl_dump_data(text, (unsigned char *)data, size);
909 break;
910 case CURLINFO_SSL_DATA_IN:
911 if (trace_curl_data) {
912 text = "<= Recv SSL data";
913 curl_dump_data(text, (unsigned char *)data, size);
915 break;
917 default: /* we ignore unknown types by default */
918 return 0;
920 return 0;
923 void http_trace_curl_no_data(void)
925 trace_override_envvar(&trace_curl, "1");
926 trace_curl_data = 0;
929 void setup_curl_trace(CURL *handle)
931 if (!trace_want(&trace_curl))
932 return;
933 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
934 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
935 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
938 static void proto_list_append(struct strbuf *list, const char *proto)
940 if (!list)
941 return;
942 if (list->len)
943 strbuf_addch(list, ',');
944 strbuf_addstr(list, proto);
947 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
949 long bits = 0;
951 if (is_transport_allowed("http", from_user)) {
952 bits |= CURLPROTO_HTTP;
953 proto_list_append(list, "http");
955 if (is_transport_allowed("https", from_user)) {
956 bits |= CURLPROTO_HTTPS;
957 proto_list_append(list, "https");
959 if (is_transport_allowed("ftp", from_user)) {
960 bits |= CURLPROTO_FTP;
961 proto_list_append(list, "ftp");
963 if (is_transport_allowed("ftps", from_user)) {
964 bits |= CURLPROTO_FTPS;
965 proto_list_append(list, "ftps");
968 return bits;
971 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
972 static int get_curl_http_version_opt(const char *version_string, long *opt)
974 int i;
975 static struct {
976 const char *name;
977 long opt_token;
978 } choice[] = {
979 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
980 { "HTTP/2", CURL_HTTP_VERSION_2 }
983 for (i = 0; i < ARRAY_SIZE(choice); i++) {
984 if (!strcmp(version_string, choice[i].name)) {
985 *opt = choice[i].opt_token;
986 return 0;
990 warning("unknown value given to http.version: '%s'", version_string);
991 return -1; /* not found */
994 #endif
996 static CURL *get_curl_handle(void)
998 CURL *result = curl_easy_init();
1000 if (!result)
1001 die("curl_easy_init failed");
1003 if (!curl_ssl_verify) {
1004 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
1005 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
1006 } else {
1007 /* Verify authenticity of the peer's certificate */
1008 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
1009 /* The name in the cert must match whom we tried to connect */
1010 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
1013 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1014 if (curl_http_version) {
1015 long opt;
1016 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
1017 /* Set request use http version */
1018 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
1021 #endif
1023 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
1024 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1026 #ifdef CURLGSSAPI_DELEGATION_FLAG
1027 if (curl_deleg) {
1028 int i;
1029 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1030 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1031 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1032 curl_deleg_levels[i].curl_deleg_param);
1033 break;
1036 if (i == ARRAY_SIZE(curl_deleg_levels))
1037 warning("Unknown delegation method '%s': using default",
1038 curl_deleg);
1040 #endif
1042 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1043 !http_schannel_check_revoke) {
1044 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1045 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1046 #else
1047 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1048 #endif
1051 if (http_proactive_auth)
1052 init_curl_http_auth(result);
1054 if (getenv("GIT_SSL_VERSION"))
1055 ssl_version = getenv("GIT_SSL_VERSION");
1056 if (ssl_version && *ssl_version) {
1057 int i;
1058 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1059 if (!strcmp(ssl_version, sslversions[i].name)) {
1060 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1061 sslversions[i].ssl_version);
1062 break;
1065 if (i == ARRAY_SIZE(sslversions))
1066 warning("unsupported ssl version %s: using default",
1067 ssl_version);
1070 if (getenv("GIT_SSL_CIPHER_LIST"))
1071 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1072 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1073 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1074 ssl_cipherlist);
1076 if (ssl_cert)
1077 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1078 if (ssl_cert_type)
1079 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1080 if (has_cert_password())
1081 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1082 if (ssl_key)
1083 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1084 if (ssl_key_type)
1085 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1086 if (ssl_capath)
1087 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1088 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1089 if (ssl_pinnedkey)
1090 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1091 #endif
1092 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1093 !http_schannel_use_ssl_cainfo) {
1094 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1095 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1096 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1097 #endif
1098 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1099 if (ssl_cainfo)
1100 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1101 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1102 if (http_proxy_ssl_ca_info)
1103 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1104 #endif
1107 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1108 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1109 curl_low_speed_limit);
1110 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1111 curl_low_speed_time);
1114 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1115 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1117 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1119 struct strbuf buf = STRBUF_INIT;
1121 get_curl_allowed_protocols(0, &buf);
1122 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1123 strbuf_reset(&buf);
1125 get_curl_allowed_protocols(-1, &buf);
1126 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1127 strbuf_release(&buf);
1129 #else
1130 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1131 get_curl_allowed_protocols(0, NULL));
1132 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1133 get_curl_allowed_protocols(-1, NULL));
1134 #endif
1136 if (getenv("GIT_CURL_VERBOSE"))
1137 http_trace_curl_no_data();
1138 setup_curl_trace(result);
1139 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1140 trace_curl_data = 0;
1141 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1142 trace_curl_redact = 0;
1144 curl_easy_setopt(result, CURLOPT_USERAGENT,
1145 user_agent ? user_agent : git_user_agent());
1147 if (curl_ftp_no_epsv)
1148 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1150 if (curl_ssl_try)
1151 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1154 * CURL also examines these variables as a fallback; but we need to query
1155 * them here in order to decide whether to prompt for missing password (cf.
1156 * init_curl_proxy_auth()).
1158 * Unlike many other common environment variables, these are historically
1159 * lowercase only. It appears that CURL did not know this and implemented
1160 * only uppercase variants, which was later corrected to take both - with
1161 * the exception of http_proxy, which is lowercase only also in CURL. As
1162 * the lowercase versions are the historical quasi-standard, they take
1163 * precedence here, as in CURL.
1165 if (!curl_http_proxy) {
1166 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1167 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1168 var_override(&curl_http_proxy, getenv("https_proxy"));
1169 } else {
1170 var_override(&curl_http_proxy, getenv("http_proxy"));
1172 if (!curl_http_proxy) {
1173 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1174 var_override(&curl_http_proxy, getenv("all_proxy"));
1178 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1180 * Handle case with the empty http.proxy value here to keep
1181 * common code clean.
1182 * NB: empty option disables proxying at all.
1184 curl_easy_setopt(result, CURLOPT_PROXY, "");
1185 } else if (curl_http_proxy) {
1186 if (starts_with(curl_http_proxy, "socks5h"))
1187 curl_easy_setopt(result,
1188 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1189 else if (starts_with(curl_http_proxy, "socks5"))
1190 curl_easy_setopt(result,
1191 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1192 else if (starts_with(curl_http_proxy, "socks4a"))
1193 curl_easy_setopt(result,
1194 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1195 else if (starts_with(curl_http_proxy, "socks"))
1196 curl_easy_setopt(result,
1197 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1198 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1199 else if (starts_with(curl_http_proxy, "https")) {
1200 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1202 if (http_proxy_ssl_cert)
1203 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1205 if (http_proxy_ssl_key)
1206 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1208 if (has_proxy_cert_password())
1209 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1211 #endif
1212 if (strstr(curl_http_proxy, "://"))
1213 credential_from_url(&proxy_auth, curl_http_proxy);
1214 else {
1215 struct strbuf url = STRBUF_INIT;
1216 strbuf_addf(&url, "http://%s", curl_http_proxy);
1217 credential_from_url(&proxy_auth, url.buf);
1218 strbuf_release(&url);
1221 if (!proxy_auth.host)
1222 die("Invalid proxy URL '%s'", curl_http_proxy);
1224 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1225 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1226 var_override(&curl_no_proxy, getenv("no_proxy"));
1227 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1229 init_curl_proxy_auth(result);
1231 set_curl_keepalive(result);
1233 return result;
1236 static void set_from_env(const char **var, const char *envname)
1238 const char *val = getenv(envname);
1239 if (val)
1240 *var = val;
1243 void http_init(struct remote *remote, const char *url, int proactive_auth)
1245 char *low_speed_limit;
1246 char *low_speed_time;
1247 char *normalized_url;
1248 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1250 config.section = "http";
1251 config.key = NULL;
1252 config.collect_fn = http_options;
1253 config.cascade_fn = git_default_config;
1254 config.cb = NULL;
1256 http_is_verbose = 0;
1257 normalized_url = url_normalize(url, &config.url);
1259 git_config(urlmatch_config_entry, &config);
1260 free(normalized_url);
1261 string_list_clear(&config.vars, 1);
1263 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1264 if (http_ssl_backend) {
1265 const curl_ssl_backend **backends;
1266 struct strbuf buf = STRBUF_INIT;
1267 int i;
1269 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1270 case CURLSSLSET_UNKNOWN_BACKEND:
1271 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1272 "Supported SSL backends:"),
1273 http_ssl_backend);
1274 for (i = 0; backends[i]; i++)
1275 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1276 die("%s", buf.buf);
1277 case CURLSSLSET_NO_BACKENDS:
1278 die(_("Could not set SSL backend to '%s': "
1279 "cURL was built without SSL backends"),
1280 http_ssl_backend);
1281 case CURLSSLSET_TOO_LATE:
1282 die(_("Could not set SSL backend to '%s': already set"),
1283 http_ssl_backend);
1284 case CURLSSLSET_OK:
1285 break; /* Okay! */
1288 #endif
1290 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1291 die("curl_global_init failed");
1293 http_proactive_auth = proactive_auth;
1295 if (remote && remote->http_proxy)
1296 curl_http_proxy = xstrdup(remote->http_proxy);
1298 if (remote)
1299 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1301 pragma_header = curl_slist_append(http_copy_default_headers(),
1302 "Pragma: no-cache");
1305 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1306 if (http_max_requests)
1307 max_requests = atoi(http_max_requests);
1310 curlm = curl_multi_init();
1311 if (!curlm)
1312 die("curl_multi_init failed");
1314 if (getenv("GIT_SSL_NO_VERIFY"))
1315 curl_ssl_verify = 0;
1317 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1318 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1319 set_from_env(&ssl_key, "GIT_SSL_KEY");
1320 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1321 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1322 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1324 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1326 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1327 if (low_speed_limit)
1328 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1329 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1330 if (low_speed_time)
1331 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1333 if (curl_ssl_verify == -1)
1334 curl_ssl_verify = 1;
1336 curl_session_count = 0;
1337 if (max_requests < 1)
1338 max_requests = DEFAULT_MAX_REQUESTS;
1340 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1341 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1342 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1344 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1345 proxy_ssl_cert_password_required = 1;
1347 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1348 curl_ftp_no_epsv = 1;
1350 if (url) {
1351 credential_from_url(&http_auth, url);
1352 if (!ssl_cert_password_required &&
1353 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1354 starts_with(url, "https://"))
1355 ssl_cert_password_required = 1;
1358 curl_default = get_curl_handle();
1361 void http_cleanup(void)
1363 struct active_request_slot *slot = active_queue_head;
1365 while (slot != NULL) {
1366 struct active_request_slot *next = slot->next;
1367 if (slot->curl) {
1368 xmulti_remove_handle(slot);
1369 curl_easy_cleanup(slot->curl);
1371 free(slot);
1372 slot = next;
1374 active_queue_head = NULL;
1376 curl_easy_cleanup(curl_default);
1378 curl_multi_cleanup(curlm);
1379 curl_global_cleanup();
1381 string_list_clear(&extra_http_headers, 0);
1383 curl_slist_free_all(pragma_header);
1384 pragma_header = NULL;
1386 curl_slist_free_all(host_resolutions);
1387 host_resolutions = NULL;
1389 if (curl_http_proxy) {
1390 free((void *)curl_http_proxy);
1391 curl_http_proxy = NULL;
1394 if (proxy_auth.password) {
1395 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1396 FREE_AND_NULL(proxy_auth.password);
1399 free((void *)curl_proxyuserpwd);
1400 curl_proxyuserpwd = NULL;
1402 free((void *)http_proxy_authmethod);
1403 http_proxy_authmethod = NULL;
1405 if (cert_auth.password) {
1406 memset(cert_auth.password, 0, strlen(cert_auth.password));
1407 FREE_AND_NULL(cert_auth.password);
1409 ssl_cert_password_required = 0;
1411 if (proxy_cert_auth.password) {
1412 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1413 FREE_AND_NULL(proxy_cert_auth.password);
1415 proxy_ssl_cert_password_required = 0;
1417 FREE_AND_NULL(cached_accept_language);
1420 struct active_request_slot *get_active_slot(void)
1422 struct active_request_slot *slot = active_queue_head;
1423 struct active_request_slot *newslot;
1425 int num_transfers;
1427 /* Wait for a slot to open up if the queue is full */
1428 while (active_requests >= max_requests) {
1429 curl_multi_perform(curlm, &num_transfers);
1430 if (num_transfers < active_requests)
1431 process_curl_messages();
1434 while (slot != NULL && slot->in_use)
1435 slot = slot->next;
1437 if (!slot) {
1438 newslot = xmalloc(sizeof(*newslot));
1439 newslot->curl = NULL;
1440 newslot->in_use = 0;
1441 newslot->next = NULL;
1443 slot = active_queue_head;
1444 if (!slot) {
1445 active_queue_head = newslot;
1446 } else {
1447 while (slot->next != NULL)
1448 slot = slot->next;
1449 slot->next = newslot;
1451 slot = newslot;
1454 if (!slot->curl) {
1455 slot->curl = curl_easy_duphandle(curl_default);
1456 curl_session_count++;
1459 active_requests++;
1460 slot->in_use = 1;
1461 slot->results = NULL;
1462 slot->finished = NULL;
1463 slot->callback_data = NULL;
1464 slot->callback_func = NULL;
1465 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1466 if (curl_save_cookies)
1467 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1468 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1469 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1470 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1471 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1472 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1473 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1474 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1475 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, -1L);
1476 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1477 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1478 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1479 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1482 * Default following to off unless "ALWAYS" is configured; this gives
1483 * callers a sane starting point, and they can tweak for individual
1484 * HTTP_FOLLOW_* cases themselves.
1486 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1487 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1488 else
1489 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1491 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1492 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1493 if (http_auth.password || http_auth.credential || curl_empty_auth_enabled())
1494 init_curl_http_auth(slot->curl);
1496 return slot;
1499 int start_active_slot(struct active_request_slot *slot)
1501 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1502 int num_transfers;
1504 if (curlm_result != CURLM_OK &&
1505 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1506 warning("curl_multi_add_handle failed: %s",
1507 curl_multi_strerror(curlm_result));
1508 active_requests--;
1509 slot->in_use = 0;
1510 return 0;
1514 * We know there must be something to do, since we just added
1515 * something.
1517 curl_multi_perform(curlm, &num_transfers);
1518 return 1;
1521 struct fill_chain {
1522 void *data;
1523 int (*fill)(void *);
1524 struct fill_chain *next;
1527 static struct fill_chain *fill_cfg;
1529 void add_fill_function(void *data, int (*fill)(void *))
1531 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1532 struct fill_chain **linkp = &fill_cfg;
1533 new_fill->data = data;
1534 new_fill->fill = fill;
1535 new_fill->next = NULL;
1536 while (*linkp)
1537 linkp = &(*linkp)->next;
1538 *linkp = new_fill;
1541 void fill_active_slots(void)
1543 struct active_request_slot *slot = active_queue_head;
1545 while (active_requests < max_requests) {
1546 struct fill_chain *fill;
1547 for (fill = fill_cfg; fill; fill = fill->next)
1548 if (fill->fill(fill->data))
1549 break;
1551 if (!fill)
1552 break;
1555 while (slot != NULL) {
1556 if (!slot->in_use && slot->curl != NULL
1557 && curl_session_count > min_curl_sessions) {
1558 curl_easy_cleanup(slot->curl);
1559 slot->curl = NULL;
1560 curl_session_count--;
1562 slot = slot->next;
1566 void step_active_slots(void)
1568 int num_transfers;
1569 CURLMcode curlm_result;
1571 do {
1572 curlm_result = curl_multi_perform(curlm, &num_transfers);
1573 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1574 if (num_transfers < active_requests) {
1575 process_curl_messages();
1576 fill_active_slots();
1580 void run_active_slot(struct active_request_slot *slot)
1582 fd_set readfds;
1583 fd_set writefds;
1584 fd_set excfds;
1585 int max_fd;
1586 struct timeval select_timeout;
1587 int finished = 0;
1589 slot->finished = &finished;
1590 while (!finished) {
1591 step_active_slots();
1593 if (slot->in_use) {
1594 long curl_timeout;
1595 curl_multi_timeout(curlm, &curl_timeout);
1596 if (curl_timeout == 0) {
1597 continue;
1598 } else if (curl_timeout == -1) {
1599 select_timeout.tv_sec = 0;
1600 select_timeout.tv_usec = 50000;
1601 } else {
1602 select_timeout.tv_sec = curl_timeout / 1000;
1603 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1606 max_fd = -1;
1607 FD_ZERO(&readfds);
1608 FD_ZERO(&writefds);
1609 FD_ZERO(&excfds);
1610 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1613 * It can happen that curl_multi_timeout returns a pathologically
1614 * long timeout when curl_multi_fdset returns no file descriptors
1615 * to read. See commit message for more details.
1617 if (max_fd < 0 &&
1618 (select_timeout.tv_sec > 0 ||
1619 select_timeout.tv_usec > 50000)) {
1620 select_timeout.tv_sec = 0;
1621 select_timeout.tv_usec = 50000;
1624 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1629 * The value of slot->finished we set before the loop was used
1630 * to set our "finished" variable when our request completed.
1632 * 1. The slot may not have been reused for another requst
1633 * yet, in which case it still has &finished.
1635 * 2. The slot may already be in-use to serve another request,
1636 * which can further be divided into two cases:
1638 * (a) If call run_active_slot() hasn't been called for that
1639 * other request, slot->finished would have been cleared
1640 * by get_active_slot() and has NULL.
1642 * (b) If the request did call run_active_slot(), then the
1643 * call would have updated slot->finished at the beginning
1644 * of this function, and with the clearing of the member
1645 * below, we would find that slot->finished is now NULL.
1647 * In all cases, slot->finished has no useful information to
1648 * anybody at this point. Some compilers warn us for
1649 * attempting to smuggle a pointer that is about to become
1650 * invalid, i.e. &finished. We clear it here to assure them.
1652 slot->finished = NULL;
1655 static void release_active_slot(struct active_request_slot *slot)
1657 closedown_active_slot(slot);
1658 if (slot->curl) {
1659 xmulti_remove_handle(slot);
1660 if (curl_session_count > min_curl_sessions) {
1661 curl_easy_cleanup(slot->curl);
1662 slot->curl = NULL;
1663 curl_session_count--;
1666 fill_active_slots();
1669 void finish_all_active_slots(void)
1671 struct active_request_slot *slot = active_queue_head;
1673 while (slot != NULL)
1674 if (slot->in_use) {
1675 run_active_slot(slot);
1676 slot = active_queue_head;
1677 } else {
1678 slot = slot->next;
1682 /* Helpers for modifying and creating URLs */
1683 static inline int needs_quote(int ch)
1685 if (((ch >= 'A') && (ch <= 'Z'))
1686 || ((ch >= 'a') && (ch <= 'z'))
1687 || ((ch >= '0') && (ch <= '9'))
1688 || (ch == '/')
1689 || (ch == '-')
1690 || (ch == '.'))
1691 return 0;
1692 return 1;
1695 static char *quote_ref_url(const char *base, const char *ref)
1697 struct strbuf buf = STRBUF_INIT;
1698 const char *cp;
1699 int ch;
1701 end_url_with_slash(&buf, base);
1703 for (cp = ref; (ch = *cp) != 0; cp++)
1704 if (needs_quote(ch))
1705 strbuf_addf(&buf, "%%%02x", ch);
1706 else
1707 strbuf_addch(&buf, *cp);
1709 return strbuf_detach(&buf, NULL);
1712 void append_remote_object_url(struct strbuf *buf, const char *url,
1713 const char *hex,
1714 int only_two_digit_prefix)
1716 end_url_with_slash(buf, url);
1718 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1719 if (!only_two_digit_prefix)
1720 strbuf_addstr(buf, hex + 2);
1723 char *get_remote_object_url(const char *url, const char *hex,
1724 int only_two_digit_prefix)
1726 struct strbuf buf = STRBUF_INIT;
1727 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1728 return strbuf_detach(&buf, NULL);
1731 void normalize_curl_result(CURLcode *result, long http_code,
1732 char *errorstr, size_t errorlen)
1735 * If we see a failing http code with CURLE_OK, we have turned off
1736 * FAILONERROR (to keep the server's custom error response), and should
1737 * translate the code into failure here.
1739 * Likewise, if we see a redirect (30x code), that means we turned off
1740 * redirect-following, and we should treat the result as an error.
1742 if (*result == CURLE_OK && http_code >= 300) {
1743 *result = CURLE_HTTP_RETURNED_ERROR;
1745 * Normally curl will already have put the "reason phrase"
1746 * from the server into curl_errorstr; unfortunately without
1747 * FAILONERROR it is lost, so we can give only the numeric
1748 * status code.
1750 xsnprintf(errorstr, errorlen,
1751 "The requested URL returned error: %ld",
1752 http_code);
1756 static int handle_curl_result(struct slot_results *results)
1758 normalize_curl_result(&results->curl_result, results->http_code,
1759 curl_errorstr, sizeof(curl_errorstr));
1761 if (results->curl_result == CURLE_OK) {
1762 credential_approve(&http_auth);
1763 credential_approve(&proxy_auth);
1764 credential_approve(&cert_auth);
1765 return HTTP_OK;
1766 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1768 * We can't tell from here whether it's a bad path, bad
1769 * certificate, bad password, or something else wrong
1770 * with the certificate. So we reject the credential to
1771 * avoid caching or saving a bad password.
1773 credential_reject(&cert_auth);
1774 return HTTP_NOAUTH;
1775 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1776 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1777 return HTTP_NOMATCHPUBLICKEY;
1778 #endif
1779 } else if (missing_target(results))
1780 return HTTP_MISSING_TARGET;
1781 else if (results->http_code == 401) {
1782 if ((http_auth.username && http_auth.password) ||\
1783 (http_auth.authtype && http_auth.credential)) {
1784 if (http_auth.multistage) {
1785 credential_clear_secrets(&http_auth);
1786 return HTTP_REAUTH;
1788 credential_reject(&http_auth);
1789 return HTTP_NOAUTH;
1790 } else {
1791 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1792 if (results->auth_avail) {
1793 http_auth_methods &= results->auth_avail;
1794 http_auth_methods_restricted = 1;
1796 return HTTP_REAUTH;
1798 } else {
1799 if (results->http_connectcode == 407)
1800 credential_reject(&proxy_auth);
1801 if (!curl_errorstr[0])
1802 strlcpy(curl_errorstr,
1803 curl_easy_strerror(results->curl_result),
1804 sizeof(curl_errorstr));
1805 return HTTP_ERROR;
1809 int run_one_slot(struct active_request_slot *slot,
1810 struct slot_results *results)
1812 slot->results = results;
1813 if (!start_active_slot(slot)) {
1814 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1815 "failed to start HTTP request");
1816 return HTTP_START_FAILED;
1819 run_active_slot(slot);
1820 return handle_curl_result(results);
1823 struct curl_slist *http_copy_default_headers(void)
1825 struct curl_slist *headers = NULL;
1826 const struct string_list_item *item;
1828 for_each_string_list_item(item, &extra_http_headers)
1829 headers = curl_slist_append(headers, item->string);
1831 return headers;
1834 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1836 char *ptr;
1837 CURLcode ret;
1839 strbuf_reset(buf);
1840 ret = curl_easy_getinfo(curl, info, &ptr);
1841 if (!ret && ptr)
1842 strbuf_addstr(buf, ptr);
1843 return ret;
1847 * Check for and extract a content-type parameter. "raw"
1848 * should be positioned at the start of the potential
1849 * parameter, with any whitespace already removed.
1851 * "name" is the name of the parameter. The value is appended
1852 * to "out".
1854 static int extract_param(const char *raw, const char *name,
1855 struct strbuf *out)
1857 size_t len = strlen(name);
1859 if (strncasecmp(raw, name, len))
1860 return -1;
1861 raw += len;
1863 if (*raw != '=')
1864 return -1;
1865 raw++;
1867 while (*raw && !isspace(*raw) && *raw != ';')
1868 strbuf_addch(out, *raw++);
1869 return 0;
1873 * Extract a normalized version of the content type, with any
1874 * spaces suppressed, all letters lowercased, and no trailing ";"
1875 * or parameters.
1877 * Note that we will silently remove even invalid whitespace. For
1878 * example, "text / plain" is specifically forbidden by RFC 2616,
1879 * but "text/plain" is the only reasonable output, and this keeps
1880 * our code simple.
1882 * If the "charset" argument is not NULL, store the value of any
1883 * charset parameter there.
1885 * Example:
1886 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1887 * "text / plain" -> "text/plain"
1889 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1890 struct strbuf *charset)
1892 const char *p;
1894 strbuf_reset(type);
1895 strbuf_grow(type, raw->len);
1896 for (p = raw->buf; *p; p++) {
1897 if (isspace(*p))
1898 continue;
1899 if (*p == ';') {
1900 p++;
1901 break;
1903 strbuf_addch(type, tolower(*p));
1906 if (!charset)
1907 return;
1909 strbuf_reset(charset);
1910 while (*p) {
1911 while (isspace(*p) || *p == ';')
1912 p++;
1913 if (!extract_param(p, "charset", charset))
1914 return;
1915 while (*p && !isspace(*p))
1916 p++;
1919 if (!charset->len && starts_with(type->buf, "text/"))
1920 strbuf_addstr(charset, "ISO-8859-1");
1923 static void write_accept_language(struct strbuf *buf)
1926 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1927 * that, q-value will be smaller than 0.001, the minimum q-value the
1928 * HTTP specification allows. See
1929 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
1931 const int MAX_DECIMAL_PLACES = 3;
1932 const int MAX_LANGUAGE_TAGS = 1000;
1933 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1934 char **language_tags = NULL;
1935 int num_langs = 0;
1936 const char *s = get_preferred_languages();
1937 int i;
1938 struct strbuf tag = STRBUF_INIT;
1940 /* Don't add Accept-Language header if no language is preferred. */
1941 if (!s)
1942 return;
1945 * Split the colon-separated string of preferred languages into
1946 * language_tags array.
1948 do {
1949 /* collect language tag */
1950 for (; *s && (isalnum(*s) || *s == '_'); s++)
1951 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1953 /* skip .codeset, @modifier and any other unnecessary parts */
1954 while (*s && *s != ':')
1955 s++;
1957 if (tag.len) {
1958 num_langs++;
1959 REALLOC_ARRAY(language_tags, num_langs);
1960 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1961 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1962 break;
1964 } while (*s++);
1966 /* write Accept-Language header into buf */
1967 if (num_langs) {
1968 int last_buf_len = 0;
1969 int max_q;
1970 int decimal_places;
1971 char q_format[32];
1973 /* add '*' */
1974 REALLOC_ARRAY(language_tags, num_langs + 1);
1975 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1977 /* compute decimal_places */
1978 for (max_q = 1, decimal_places = 0;
1979 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1980 decimal_places++, max_q *= 10)
1983 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1985 strbuf_addstr(buf, "Accept-Language: ");
1987 for (i = 0; i < num_langs; i++) {
1988 if (i > 0)
1989 strbuf_addstr(buf, ", ");
1991 strbuf_addstr(buf, language_tags[i]);
1993 if (i > 0)
1994 strbuf_addf(buf, q_format, max_q - i);
1996 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1997 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1998 break;
2001 last_buf_len = buf->len;
2005 /* free language tags -- last one is a static '*' */
2006 for (i = 0; i < num_langs - 1; i++)
2007 free(language_tags[i]);
2008 free(language_tags);
2012 * Get an Accept-Language header which indicates user's preferred languages.
2014 * Examples:
2015 * LANGUAGE= -> ""
2016 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
2017 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
2018 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
2019 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
2020 * LANGUAGE= LANG=C -> ""
2022 const char *http_get_accept_language_header(void)
2024 if (!cached_accept_language) {
2025 struct strbuf buf = STRBUF_INIT;
2026 write_accept_language(&buf);
2027 if (buf.len > 0)
2028 cached_accept_language = strbuf_detach(&buf, NULL);
2031 return cached_accept_language;
2034 static void http_opt_request_remainder(CURL *curl, off_t pos)
2036 char buf[128];
2037 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2038 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2041 /* http_request() targets */
2042 #define HTTP_REQUEST_STRBUF 0
2043 #define HTTP_REQUEST_FILE 1
2045 static int http_request(const char *url,
2046 void *result, int target,
2047 const struct http_get_options *options)
2049 struct active_request_slot *slot;
2050 struct slot_results results;
2051 struct curl_slist *headers = http_copy_default_headers();
2052 struct strbuf buf = STRBUF_INIT;
2053 const char *accept_language;
2054 int ret;
2056 slot = get_active_slot();
2057 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2059 if (!result) {
2060 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2061 } else {
2062 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2063 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2065 if (target == HTTP_REQUEST_FILE) {
2066 off_t posn = ftello(result);
2067 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2068 fwrite);
2069 if (posn > 0)
2070 http_opt_request_remainder(slot->curl, posn);
2071 } else
2072 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2073 fwrite_buffer);
2076 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2078 accept_language = http_get_accept_language_header();
2080 if (accept_language)
2081 headers = curl_slist_append(headers, accept_language);
2083 strbuf_addstr(&buf, "Pragma:");
2084 if (options && options->no_cache)
2085 strbuf_addstr(&buf, " no-cache");
2086 if (options && options->initial_request &&
2087 http_follow_config == HTTP_FOLLOW_INITIAL)
2088 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2090 headers = curl_slist_append(headers, buf.buf);
2092 /* Add additional headers here */
2093 if (options && options->extra_headers) {
2094 const struct string_list_item *item;
2095 if (options && options->extra_headers) {
2096 for_each_string_list_item(item, options->extra_headers) {
2097 headers = curl_slist_append(headers, item->string);
2102 headers = http_append_auth_header(&http_auth, headers);
2104 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2105 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2106 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2107 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2109 ret = run_one_slot(slot, &results);
2111 if (options && options->content_type) {
2112 struct strbuf raw = STRBUF_INIT;
2113 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2114 extract_content_type(&raw, options->content_type,
2115 options->charset);
2116 strbuf_release(&raw);
2119 if (options && options->effective_url)
2120 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2121 options->effective_url);
2123 curl_slist_free_all(headers);
2124 strbuf_release(&buf);
2126 return ret;
2130 * Update the "base" url to a more appropriate value, as deduced by
2131 * redirects seen when requesting a URL starting with "url".
2133 * The "asked" parameter is a URL that we asked curl to access, and must begin
2134 * with "base".
2136 * The "got" parameter is the URL that curl reported to us as where we ended
2137 * up.
2139 * Returns 1 if we updated the base url, 0 otherwise.
2141 * Our basic strategy is to compare "base" and "asked" to find the bits
2142 * specific to our request. We then strip those bits off of "got" to yield the
2143 * new base. So for example, if our base is "http://example.com/foo.git",
2144 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2145 * with "https://other.example.com/foo.git/info/refs". We would want the
2146 * new URL to become "https://other.example.com/foo.git".
2148 * Note that this assumes a sane redirect scheme. It's entirely possible
2149 * in the example above to end up at a URL that does not even end in
2150 * "info/refs". In such a case we die. There's not much we can do, such a
2151 * scheme is unlikely to represent a real git repository, and failing to
2152 * rewrite the base opens options for malicious redirects to do funny things.
2154 static int update_url_from_redirect(struct strbuf *base,
2155 const char *asked,
2156 const struct strbuf *got)
2158 const char *tail;
2159 size_t new_len;
2161 if (!strcmp(asked, got->buf))
2162 return 0;
2164 if (!skip_prefix(asked, base->buf, &tail))
2165 BUG("update_url_from_redirect: %s is not a superset of %s",
2166 asked, base->buf);
2168 new_len = got->len;
2169 if (!strip_suffix_mem(got->buf, &new_len, tail))
2170 die(_("unable to update url base from redirection:\n"
2171 " asked for: %s\n"
2172 " redirect: %s"),
2173 asked, got->buf);
2175 strbuf_reset(base);
2176 strbuf_add(base, got->buf, new_len);
2178 return 1;
2181 static int http_request_reauth(const char *url,
2182 void *result, int target,
2183 struct http_get_options *options)
2185 int i = 3;
2186 int ret = http_request(url, result, target, options);
2188 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2189 return ret;
2191 if (options && options->effective_url && options->base_url) {
2192 if (update_url_from_redirect(options->base_url,
2193 url, options->effective_url)) {
2194 credential_from_url(&http_auth, options->base_url->buf);
2195 url = options->effective_url->buf;
2199 while (ret == HTTP_REAUTH && --i) {
2201 * The previous request may have put cruft into our output stream; we
2202 * should clear it out before making our next request.
2204 switch (target) {
2205 case HTTP_REQUEST_STRBUF:
2206 strbuf_reset(result);
2207 break;
2208 case HTTP_REQUEST_FILE:
2209 if (fflush(result)) {
2210 error_errno("unable to flush a file");
2211 return HTTP_START_FAILED;
2213 rewind(result);
2214 if (ftruncate(fileno(result), 0) < 0) {
2215 error_errno("unable to truncate a file");
2216 return HTTP_START_FAILED;
2218 break;
2219 default:
2220 BUG("Unknown http_request target");
2223 credential_fill(&http_auth, 1);
2225 ret = http_request(url, result, target, options);
2227 return ret;
2230 int http_get_strbuf(const char *url,
2231 struct strbuf *result,
2232 struct http_get_options *options)
2234 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2238 * Downloads a URL and stores the result in the given file.
2240 * If a previous interrupted download is detected (i.e. a previous temporary
2241 * file is still around) the download is resumed.
2243 int http_get_file(const char *url, const char *filename,
2244 struct http_get_options *options)
2246 int ret;
2247 struct strbuf tmpfile = STRBUF_INIT;
2248 FILE *result;
2250 strbuf_addf(&tmpfile, "%s.temp", filename);
2251 result = fopen(tmpfile.buf, "a");
2252 if (!result) {
2253 error("Unable to open local file %s", tmpfile.buf);
2254 ret = HTTP_ERROR;
2255 goto cleanup;
2258 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2259 fclose(result);
2261 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2262 ret = HTTP_ERROR;
2263 cleanup:
2264 strbuf_release(&tmpfile);
2265 return ret;
2268 int http_fetch_ref(const char *base, struct ref *ref)
2270 struct http_get_options options = {0};
2271 char *url;
2272 struct strbuf buffer = STRBUF_INIT;
2273 int ret = -1;
2275 options.no_cache = 1;
2277 url = quote_ref_url(base, ref->name);
2278 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2279 strbuf_rtrim(&buffer);
2280 if (buffer.len == the_hash_algo->hexsz)
2281 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2282 else if (starts_with(buffer.buf, "ref: ")) {
2283 ref->symref = xstrdup(buffer.buf + 5);
2284 ret = 0;
2288 strbuf_release(&buffer);
2289 free(url);
2290 return ret;
2293 /* Helpers for fetching packs */
2294 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2296 char *url, *tmp;
2297 struct strbuf buf = STRBUF_INIT;
2299 if (http_is_verbose)
2300 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2302 end_url_with_slash(&buf, base_url);
2303 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2304 url = strbuf_detach(&buf, NULL);
2306 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2307 tmp = strbuf_detach(&buf, NULL);
2309 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2310 error("Unable to get pack index %s", url);
2311 FREE_AND_NULL(tmp);
2314 free(url);
2315 return tmp;
2318 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2319 unsigned char *sha1, const char *base_url)
2321 struct packed_git *new_pack;
2322 char *tmp_idx = NULL;
2323 int ret;
2325 if (has_pack_index(sha1)) {
2326 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2327 if (!new_pack)
2328 return -1; /* parse_pack_index() already issued error message */
2329 goto add_pack;
2332 tmp_idx = fetch_pack_index(sha1, base_url);
2333 if (!tmp_idx)
2334 return -1;
2336 new_pack = parse_pack_index(sha1, tmp_idx);
2337 if (!new_pack) {
2338 unlink(tmp_idx);
2339 free(tmp_idx);
2341 return -1; /* parse_pack_index() already issued error message */
2344 ret = verify_pack_index(new_pack);
2345 if (!ret) {
2346 close_pack_index(new_pack);
2347 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2349 free(tmp_idx);
2350 if (ret)
2351 return -1;
2353 add_pack:
2354 new_pack->next = *packs_head;
2355 *packs_head = new_pack;
2356 return 0;
2359 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2361 struct http_get_options options = {0};
2362 int ret = 0;
2363 char *url;
2364 const char *data;
2365 struct strbuf buf = STRBUF_INIT;
2366 struct object_id oid;
2368 end_url_with_slash(&buf, base_url);
2369 strbuf_addstr(&buf, "objects/info/packs");
2370 url = strbuf_detach(&buf, NULL);
2372 options.no_cache = 1;
2373 ret = http_get_strbuf(url, &buf, &options);
2374 if (ret != HTTP_OK)
2375 goto cleanup;
2377 data = buf.buf;
2378 while (*data) {
2379 if (skip_prefix(data, "P pack-", &data) &&
2380 !parse_oid_hex(data, &oid, &data) &&
2381 skip_prefix(data, ".pack", &data) &&
2382 (*data == '\n' || *data == '\0')) {
2383 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2384 } else {
2385 data = strchrnul(data, '\n');
2387 if (*data)
2388 data++; /* skip past newline */
2391 cleanup:
2392 free(url);
2393 return ret;
2396 void release_http_pack_request(struct http_pack_request *preq)
2398 if (preq->packfile) {
2399 fclose(preq->packfile);
2400 preq->packfile = NULL;
2402 preq->slot = NULL;
2403 strbuf_release(&preq->tmpfile);
2404 curl_slist_free_all(preq->headers);
2405 free(preq->url);
2406 free(preq);
2409 static const char *default_index_pack_args[] =
2410 {"index-pack", "--stdin", NULL};
2412 int finish_http_pack_request(struct http_pack_request *preq)
2414 struct child_process ip = CHILD_PROCESS_INIT;
2415 int tmpfile_fd;
2416 int ret = 0;
2418 fclose(preq->packfile);
2419 preq->packfile = NULL;
2421 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2423 ip.git_cmd = 1;
2424 ip.in = tmpfile_fd;
2425 strvec_pushv(&ip.args, preq->index_pack_args ?
2426 preq->index_pack_args :
2427 default_index_pack_args);
2429 if (preq->preserve_index_pack_stdout)
2430 ip.out = 0;
2431 else
2432 ip.no_stdout = 1;
2434 if (run_command(&ip)) {
2435 ret = -1;
2436 goto cleanup;
2439 cleanup:
2440 close(tmpfile_fd);
2441 unlink(preq->tmpfile.buf);
2442 return ret;
2445 void http_install_packfile(struct packed_git *p,
2446 struct packed_git **list_to_remove_from)
2448 struct packed_git **lst = list_to_remove_from;
2450 while (*lst != p)
2451 lst = &((*lst)->next);
2452 *lst = (*lst)->next;
2454 install_packed_git(the_repository, p);
2457 struct http_pack_request *new_http_pack_request(
2458 const unsigned char *packed_git_hash, const char *base_url) {
2460 struct strbuf buf = STRBUF_INIT;
2462 end_url_with_slash(&buf, base_url);
2463 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2464 hash_to_hex(packed_git_hash));
2465 return new_direct_http_pack_request(packed_git_hash,
2466 strbuf_detach(&buf, NULL));
2469 struct http_pack_request *new_direct_http_pack_request(
2470 const unsigned char *packed_git_hash, char *url)
2472 off_t prev_posn = 0;
2473 struct http_pack_request *preq;
2475 CALLOC_ARRAY(preq, 1);
2476 strbuf_init(&preq->tmpfile, 0);
2478 preq->url = url;
2480 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2481 preq->packfile = fopen(preq->tmpfile.buf, "a");
2482 if (!preq->packfile) {
2483 error("Unable to open local file %s for pack",
2484 preq->tmpfile.buf);
2485 goto abort;
2488 preq->slot = get_active_slot();
2489 preq->headers = object_request_headers();
2490 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2491 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2492 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2493 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER, preq->headers);
2496 * If there is data present from a previous transfer attempt,
2497 * resume where it left off
2499 prev_posn = ftello(preq->packfile);
2500 if (prev_posn>0) {
2501 if (http_is_verbose)
2502 fprintf(stderr,
2503 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2504 hash_to_hex(packed_git_hash),
2505 (uintmax_t)prev_posn);
2506 http_opt_request_remainder(preq->slot->curl, prev_posn);
2509 return preq;
2511 abort:
2512 strbuf_release(&preq->tmpfile);
2513 free(preq->url);
2514 free(preq);
2515 return NULL;
2518 /* Helpers for fetching objects (loose) */
2519 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2520 void *data)
2522 unsigned char expn[4096];
2523 size_t size = eltsize * nmemb;
2524 int posn = 0;
2525 struct http_object_request *freq = data;
2526 struct active_request_slot *slot = freq->slot;
2528 if (slot) {
2529 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2530 &slot->http_code);
2531 if (c != CURLE_OK)
2532 BUG("curl_easy_getinfo for HTTP code failed: %s",
2533 curl_easy_strerror(c));
2534 if (slot->http_code >= 300)
2535 return nmemb;
2538 do {
2539 ssize_t retval = xwrite(freq->localfile,
2540 (char *) ptr + posn, size - posn);
2541 if (retval < 0)
2542 return posn / eltsize;
2543 posn += retval;
2544 } while (posn < size);
2546 freq->stream.avail_in = size;
2547 freq->stream.next_in = (void *)ptr;
2548 do {
2549 freq->stream.next_out = expn;
2550 freq->stream.avail_out = sizeof(expn);
2551 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2552 the_hash_algo->update_fn(&freq->c, expn,
2553 sizeof(expn) - freq->stream.avail_out);
2554 } while (freq->stream.avail_in && freq->zret == Z_OK);
2555 return nmemb;
2558 struct http_object_request *new_http_object_request(const char *base_url,
2559 const struct object_id *oid)
2561 char *hex = oid_to_hex(oid);
2562 struct strbuf filename = STRBUF_INIT;
2563 struct strbuf prevfile = STRBUF_INIT;
2564 int prevlocal;
2565 char prev_buf[PREV_BUF_SIZE];
2566 ssize_t prev_read = 0;
2567 off_t prev_posn = 0;
2568 struct http_object_request *freq;
2570 CALLOC_ARRAY(freq, 1);
2571 strbuf_init(&freq->tmpfile, 0);
2572 oidcpy(&freq->oid, oid);
2573 freq->localfile = -1;
2575 loose_object_path(the_repository, &filename, oid);
2576 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2578 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2579 unlink_or_warn(prevfile.buf);
2580 rename(freq->tmpfile.buf, prevfile.buf);
2581 unlink_or_warn(freq->tmpfile.buf);
2582 strbuf_release(&filename);
2584 if (freq->localfile != -1)
2585 error("fd leakage in start: %d", freq->localfile);
2586 freq->localfile = open(freq->tmpfile.buf,
2587 O_WRONLY | O_CREAT | O_EXCL, 0666);
2589 * This could have failed due to the "lazy directory creation";
2590 * try to mkdir the last path component.
2592 if (freq->localfile < 0 && errno == ENOENT) {
2593 char *dir = strrchr(freq->tmpfile.buf, '/');
2594 if (dir) {
2595 *dir = 0;
2596 mkdir(freq->tmpfile.buf, 0777);
2597 *dir = '/';
2599 freq->localfile = open(freq->tmpfile.buf,
2600 O_WRONLY | O_CREAT | O_EXCL, 0666);
2603 if (freq->localfile < 0) {
2604 error_errno("Couldn't create temporary file %s",
2605 freq->tmpfile.buf);
2606 goto abort;
2609 git_inflate_init(&freq->stream);
2611 the_hash_algo->init_fn(&freq->c);
2613 freq->url = get_remote_object_url(base_url, hex, 0);
2616 * If a previous temp file is present, process what was already
2617 * fetched.
2619 prevlocal = open(prevfile.buf, O_RDONLY);
2620 if (prevlocal != -1) {
2621 do {
2622 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2623 if (prev_read>0) {
2624 if (fwrite_sha1_file(prev_buf,
2626 prev_read,
2627 freq) == prev_read) {
2628 prev_posn += prev_read;
2629 } else {
2630 prev_read = -1;
2633 } while (prev_read > 0);
2634 close(prevlocal);
2636 unlink_or_warn(prevfile.buf);
2637 strbuf_release(&prevfile);
2640 * Reset inflate/SHA1 if there was an error reading the previous temp
2641 * file; also rewind to the beginning of the local file.
2643 if (prev_read == -1) {
2644 memset(&freq->stream, 0, sizeof(freq->stream));
2645 git_inflate_init(&freq->stream);
2646 the_hash_algo->init_fn(&freq->c);
2647 if (prev_posn>0) {
2648 prev_posn = 0;
2649 lseek(freq->localfile, 0, SEEK_SET);
2650 if (ftruncate(freq->localfile, 0) < 0) {
2651 error_errno("Couldn't truncate temporary file %s",
2652 freq->tmpfile.buf);
2653 goto abort;
2658 freq->slot = get_active_slot();
2659 freq->headers = object_request_headers();
2661 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2662 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2663 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2664 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2665 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2666 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, freq->headers);
2669 * If we have successfully processed data from a previous fetch
2670 * attempt, only fetch the data we don't already have.
2672 if (prev_posn>0) {
2673 if (http_is_verbose)
2674 fprintf(stderr,
2675 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2676 hex, (uintmax_t)prev_posn);
2677 http_opt_request_remainder(freq->slot->curl, prev_posn);
2680 return freq;
2682 abort:
2683 strbuf_release(&prevfile);
2684 free(freq->url);
2685 free(freq);
2686 return NULL;
2689 void process_http_object_request(struct http_object_request *freq)
2691 if (!freq->slot)
2692 return;
2693 freq->curl_result = freq->slot->curl_result;
2694 freq->http_code = freq->slot->http_code;
2695 freq->slot = NULL;
2698 int finish_http_object_request(struct http_object_request *freq)
2700 struct stat st;
2701 struct strbuf filename = STRBUF_INIT;
2703 close(freq->localfile);
2704 freq->localfile = -1;
2706 process_http_object_request(freq);
2708 if (freq->http_code == 416) {
2709 warning("requested range invalid; we may already have all the data.");
2710 } else if (freq->curl_result != CURLE_OK) {
2711 if (stat(freq->tmpfile.buf, &st) == 0)
2712 if (st.st_size == 0)
2713 unlink_or_warn(freq->tmpfile.buf);
2714 return -1;
2717 git_inflate_end(&freq->stream);
2718 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2719 if (freq->zret != Z_STREAM_END) {
2720 unlink_or_warn(freq->tmpfile.buf);
2721 return -1;
2723 if (!oideq(&freq->oid, &freq->real_oid)) {
2724 unlink_or_warn(freq->tmpfile.buf);
2725 return -1;
2727 loose_object_path(the_repository, &filename, &freq->oid);
2728 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2729 strbuf_release(&filename);
2731 return freq->rename;
2734 void abort_http_object_request(struct http_object_request *freq)
2736 unlink_or_warn(freq->tmpfile.buf);
2738 release_http_object_request(freq);
2741 void release_http_object_request(struct http_object_request *freq)
2743 if (freq->localfile != -1) {
2744 close(freq->localfile);
2745 freq->localfile = -1;
2747 FREE_AND_NULL(freq->url);
2748 if (freq->slot) {
2749 freq->slot->callback_func = NULL;
2750 freq->slot->callback_data = NULL;
2751 release_active_slot(freq->slot);
2752 freq->slot = NULL;
2754 curl_slist_free_all(freq->headers);
2755 strbuf_release(&freq->tmpfile);