Sync with 'maint'
[git.git] / http.c
blob58242b9d2dd595e9e0a5cb2d9bc6f38927546328
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"
22 #include "tempfile.h"
24 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
25 static int trace_curl_data = 1;
26 static int trace_curl_redact = 1;
27 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
28 int active_requests;
29 int http_is_verbose;
30 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
32 static int min_curl_sessions = 1;
33 static int curl_session_count;
34 static int max_requests = -1;
35 static CURLM *curlm;
36 static CURL *curl_default;
38 #define PREV_BUF_SIZE 4096
40 char curl_errorstr[CURL_ERROR_SIZE];
42 static int curl_ssl_verify = -1;
43 static int curl_ssl_try;
44 static char *curl_http_version;
45 static char *ssl_cert;
46 static char *ssl_cert_type;
47 static char *ssl_cipherlist;
48 static char *ssl_version;
49 static struct {
50 const char *name;
51 long ssl_version;
52 } sslversions[] = {
53 { "sslv2", CURL_SSLVERSION_SSLv2 },
54 { "sslv3", CURL_SSLVERSION_SSLv3 },
55 { "tlsv1", CURL_SSLVERSION_TLSv1 },
56 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
57 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
58 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
59 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
60 #endif
61 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
62 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
63 #endif
65 static char *ssl_key;
66 static char *ssl_key_type;
67 static char *ssl_capath;
68 static char *curl_no_proxy;
69 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
70 static char *ssl_pinnedkey;
71 #endif
72 static char *ssl_cainfo;
73 static long curl_low_speed_limit = -1;
74 static long curl_low_speed_time = -1;
75 static int curl_ftp_no_epsv;
76 static char *curl_http_proxy;
77 static char *http_proxy_authmethod;
79 static char *http_proxy_ssl_cert;
80 static char *http_proxy_ssl_key;
81 static char *http_proxy_ssl_ca_info;
82 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
83 static int proxy_ssl_cert_password_required;
85 static struct {
86 const char *name;
87 long curlauth_param;
88 } proxy_authmethods[] = {
89 { "basic", CURLAUTH_BASIC },
90 { "digest", CURLAUTH_DIGEST },
91 { "negotiate", CURLAUTH_GSSNEGOTIATE },
92 { "ntlm", CURLAUTH_NTLM },
93 { "anyauth", CURLAUTH_ANY },
95 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
96 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
97 * here, too
100 #ifdef CURLGSSAPI_DELEGATION_FLAG
101 static char *curl_deleg;
102 static struct {
103 const char *name;
104 long curl_deleg_param;
105 } curl_deleg_levels[] = {
106 { "none", CURLGSSAPI_DELEGATION_NONE },
107 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
108 { "always", CURLGSSAPI_DELEGATION_FLAG },
110 #endif
112 enum proactive_auth {
113 PROACTIVE_AUTH_NONE = 0,
114 PROACTIVE_AUTH_IF_CREDENTIALS,
115 PROACTIVE_AUTH_AUTO,
116 PROACTIVE_AUTH_BASIC,
119 static struct credential proxy_auth = CREDENTIAL_INIT;
120 static const char *curl_proxyuserpwd;
121 static char *curl_cookie_file;
122 static int curl_save_cookies;
123 struct credential http_auth = CREDENTIAL_INIT;
124 static enum proactive_auth http_proactive_auth;
125 static char *user_agent;
126 static int curl_empty_auth = -1;
128 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
130 static struct credential cert_auth = CREDENTIAL_INIT;
131 static int ssl_cert_password_required;
132 static unsigned long http_auth_methods = CURLAUTH_ANY;
133 static int http_auth_methods_restricted;
134 /* Modes for which empty_auth cannot actually help us. */
135 static unsigned long empty_auth_useless =
136 CURLAUTH_BASIC
137 | CURLAUTH_DIGEST_IE
138 | CURLAUTH_DIGEST;
140 static struct curl_slist *pragma_header;
141 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
143 static struct curl_slist *host_resolutions;
145 static struct active_request_slot *active_queue_head;
147 static char *cached_accept_language;
149 static char *http_ssl_backend;
151 static int http_schannel_check_revoke = 1;
153 * With the backend being set to `schannel`, setting sslCAinfo would override
154 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
155 * by default.
157 static int http_schannel_use_ssl_cainfo;
159 static int always_auth_proactively(void)
161 return http_proactive_auth != PROACTIVE_AUTH_NONE &&
162 http_proactive_auth != PROACTIVE_AUTH_IF_CREDENTIALS;
165 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
167 size_t size = eltsize * nmemb;
168 struct buffer *buffer = buffer_;
170 if (size > buffer->buf.len - buffer->posn)
171 size = buffer->buf.len - buffer->posn;
172 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
173 buffer->posn += size;
175 return size / eltsize;
178 int seek_buffer(void *clientp, curl_off_t offset, int origin)
180 struct buffer *buffer = clientp;
182 if (origin != SEEK_SET)
183 BUG("seek_buffer only handles SEEK_SET");
184 if (offset < 0 || offset >= buffer->buf.len) {
185 error("curl seek would be outside of buffer");
186 return CURL_SEEKFUNC_FAIL;
189 buffer->posn = offset;
190 return CURL_SEEKFUNC_OK;
193 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
195 size_t size = eltsize * nmemb;
196 struct strbuf *buffer = buffer_;
198 strbuf_add(buffer, ptr, size);
199 return nmemb;
203 * A folded header continuation line starts with any number of spaces or
204 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
205 * It is not a continuation line if the line starts with any other character.
207 static inline int is_hdr_continuation(const char *ptr, const size_t size)
209 return size && (*ptr == ' ' || *ptr == '\t');
212 static size_t fwrite_wwwauth(char *ptr, size_t eltsize, size_t nmemb, void *p UNUSED)
214 size_t size = eltsize * nmemb;
215 struct strvec *values = &http_auth.wwwauth_headers;
216 struct strbuf buf = STRBUF_INIT;
217 const char *val;
218 size_t val_len;
221 * Header lines may not come NULL-terminated from libcurl so we must
222 * limit all scans to the maximum length of the header line, or leverage
223 * strbufs for all operations.
225 * In addition, it is possible that header values can be split over
226 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
227 * but older servers may still emit them. A continuation header field
228 * value is identified as starting with a space or horizontal tab.
230 * The formal definition of a header field as given in RFC 7230 is:
232 * header-field = field-name ":" OWS field-value OWS
234 * field-name = token
235 * field-value = *( field-content / obs-fold )
236 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
237 * field-vchar = VCHAR / obs-text
239 * obs-fold = CRLF 1*( SP / HTAB )
240 * ; obsolete line folding
241 * ; see Section 3.2.4
244 /* Start of a new WWW-Authenticate header */
245 if (skip_iprefix_mem(ptr, size, "www-authenticate:", &val, &val_len)) {
246 strbuf_add(&buf, val, val_len);
249 * Strip the CRLF that should be present at the end of each
250 * field as well as any trailing or leading whitespace from the
251 * value.
253 strbuf_trim(&buf);
255 strvec_push(values, buf.buf);
256 http_auth.header_is_last_match = 1;
257 goto exit;
261 * This line could be a continuation of the previously matched header
262 * field. If this is the case then we should append this value to the
263 * end of the previously consumed value.
265 if (http_auth.header_is_last_match && is_hdr_continuation(ptr, size)) {
267 * Trim the CRLF and any leading or trailing from this line.
269 strbuf_add(&buf, ptr, size);
270 strbuf_trim(&buf);
273 * At this point we should always have at least one existing
274 * value, even if it is empty. Do not bother appending the new
275 * value if this continuation header is itself empty.
277 if (!values->nr) {
278 BUG("should have at least one existing header value");
279 } else if (buf.len) {
280 char *prev = xstrdup(values->v[values->nr - 1]);
282 /* Join two non-empty values with a single space. */
283 const char *const sp = *prev ? " " : "";
285 strvec_pop(values);
286 strvec_pushf(values, "%s%s%s", prev, sp, buf.buf);
287 free(prev);
290 goto exit;
293 /* Not a continuation of a previously matched auth header line. */
294 http_auth.header_is_last_match = 0;
297 * If this is a HTTP status line and not a header field, this signals
298 * a different HTTP response. libcurl writes all the output of all
299 * response headers of all responses, including redirects.
300 * We only care about the last HTTP request response's headers so clear
301 * the existing array.
303 if (skip_iprefix_mem(ptr, size, "http/", &val, &val_len))
304 strvec_clear(values);
306 exit:
307 strbuf_release(&buf);
308 return size;
311 size_t fwrite_null(char *ptr UNUSED, size_t eltsize UNUSED, size_t nmemb,
312 void *data UNUSED)
314 return nmemb;
317 static struct curl_slist *object_request_headers(void)
319 return curl_slist_append(http_copy_default_headers(), "Pragma:");
322 static void closedown_active_slot(struct active_request_slot *slot)
324 active_requests--;
325 slot->in_use = 0;
328 static void finish_active_slot(struct active_request_slot *slot)
330 closedown_active_slot(slot);
331 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
333 if (slot->finished)
334 (*slot->finished) = 1;
336 /* Store slot results so they can be read after the slot is reused */
337 if (slot->results) {
338 slot->results->curl_result = slot->curl_result;
339 slot->results->http_code = slot->http_code;
340 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
341 &slot->results->auth_avail);
343 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
344 &slot->results->http_connectcode);
347 /* Run callback if appropriate */
348 if (slot->callback_func)
349 slot->callback_func(slot->callback_data);
352 static void xmulti_remove_handle(struct active_request_slot *slot)
354 curl_multi_remove_handle(curlm, slot->curl);
357 static void process_curl_messages(void)
359 int num_messages;
360 struct active_request_slot *slot;
361 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
363 while (curl_message != NULL) {
364 if (curl_message->msg == CURLMSG_DONE) {
365 int curl_result = curl_message->data.result;
366 slot = active_queue_head;
367 while (slot != NULL &&
368 slot->curl != curl_message->easy_handle)
369 slot = slot->next;
370 if (slot) {
371 xmulti_remove_handle(slot);
372 slot->curl_result = curl_result;
373 finish_active_slot(slot);
374 } else {
375 fprintf(stderr, "Received DONE message for unknown request!\n");
377 } else {
378 fprintf(stderr, "Unknown CURL message received: %d\n",
379 (int)curl_message->msg);
381 curl_message = curl_multi_info_read(curlm, &num_messages);
385 static int http_options(const char *var, const char *value,
386 const struct config_context *ctx, void *data)
388 if (!strcmp("http.version", var)) {
389 return git_config_string(&curl_http_version, var, value);
391 if (!strcmp("http.sslverify", var)) {
392 curl_ssl_verify = git_config_bool(var, value);
393 return 0;
395 if (!strcmp("http.sslcipherlist", var))
396 return git_config_string(&ssl_cipherlist, var, value);
397 if (!strcmp("http.sslversion", var))
398 return git_config_string(&ssl_version, var, value);
399 if (!strcmp("http.sslcert", var))
400 return git_config_pathname(&ssl_cert, var, value);
401 if (!strcmp("http.sslcerttype", var))
402 return git_config_string(&ssl_cert_type, var, value);
403 if (!strcmp("http.sslkey", var))
404 return git_config_pathname(&ssl_key, var, value);
405 if (!strcmp("http.sslkeytype", var))
406 return git_config_string(&ssl_key_type, var, value);
407 if (!strcmp("http.sslcapath", var))
408 return git_config_pathname(&ssl_capath, var, value);
409 if (!strcmp("http.sslcainfo", var))
410 return git_config_pathname(&ssl_cainfo, var, value);
411 if (!strcmp("http.sslcertpasswordprotected", var)) {
412 ssl_cert_password_required = git_config_bool(var, value);
413 return 0;
415 if (!strcmp("http.ssltry", var)) {
416 curl_ssl_try = git_config_bool(var, value);
417 return 0;
419 if (!strcmp("http.sslbackend", var)) {
420 free(http_ssl_backend);
421 http_ssl_backend = xstrdup_or_null(value);
422 return 0;
425 if (!strcmp("http.schannelcheckrevoke", var)) {
426 http_schannel_check_revoke = git_config_bool(var, value);
427 return 0;
430 if (!strcmp("http.schannelusesslcainfo", var)) {
431 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
432 return 0;
435 if (!strcmp("http.minsessions", var)) {
436 min_curl_sessions = git_config_int(var, value, ctx->kvi);
437 if (min_curl_sessions > 1)
438 min_curl_sessions = 1;
439 return 0;
441 if (!strcmp("http.maxrequests", var)) {
442 max_requests = git_config_int(var, value, ctx->kvi);
443 return 0;
445 if (!strcmp("http.lowspeedlimit", var)) {
446 curl_low_speed_limit = (long)git_config_int(var, value, ctx->kvi);
447 return 0;
449 if (!strcmp("http.lowspeedtime", var)) {
450 curl_low_speed_time = (long)git_config_int(var, value, ctx->kvi);
451 return 0;
454 if (!strcmp("http.noepsv", var)) {
455 curl_ftp_no_epsv = git_config_bool(var, value);
456 return 0;
458 if (!strcmp("http.proxy", var))
459 return git_config_string(&curl_http_proxy, var, value);
461 if (!strcmp("http.proxyauthmethod", var))
462 return git_config_string(&http_proxy_authmethod, var, value);
464 if (!strcmp("http.proxysslcert", var))
465 return git_config_string(&http_proxy_ssl_cert, var, value);
467 if (!strcmp("http.proxysslkey", var))
468 return git_config_string(&http_proxy_ssl_key, var, value);
470 if (!strcmp("http.proxysslcainfo", var))
471 return git_config_string(&http_proxy_ssl_ca_info, var, value);
473 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
474 proxy_ssl_cert_password_required = git_config_bool(var, value);
475 return 0;
478 if (!strcmp("http.cookiefile", var))
479 return git_config_pathname(&curl_cookie_file, var, value);
480 if (!strcmp("http.savecookies", var)) {
481 curl_save_cookies = git_config_bool(var, value);
482 return 0;
485 if (!strcmp("http.postbuffer", var)) {
486 http_post_buffer = git_config_ssize_t(var, value, ctx->kvi);
487 if (http_post_buffer < 0)
488 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
489 if (http_post_buffer < LARGE_PACKET_MAX)
490 http_post_buffer = LARGE_PACKET_MAX;
491 return 0;
494 if (!strcmp("http.useragent", var))
495 return git_config_string(&user_agent, var, value);
497 if (!strcmp("http.emptyauth", var)) {
498 if (value && !strcmp("auto", value))
499 curl_empty_auth = -1;
500 else
501 curl_empty_auth = git_config_bool(var, value);
502 return 0;
505 if (!strcmp("http.delegation", var)) {
506 #ifdef CURLGSSAPI_DELEGATION_FLAG
507 return git_config_string(&curl_deleg, var, value);
508 #else
509 warning(_("Delegation control is not supported with cURL < 7.22.0"));
510 return 0;
511 #endif
514 if (!strcmp("http.pinnedpubkey", var)) {
515 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
516 return git_config_pathname(&ssl_pinnedkey, var, value);
517 #else
518 warning(_("Public key pinning not supported with cURL < 7.39.0"));
519 return 0;
520 #endif
523 if (!strcmp("http.extraheader", var)) {
524 if (!value) {
525 return config_error_nonbool(var);
526 } else if (!*value) {
527 string_list_clear(&extra_http_headers, 0);
528 } else {
529 string_list_append(&extra_http_headers, value);
531 return 0;
534 if (!strcmp("http.curloptresolve", var)) {
535 if (!value) {
536 return config_error_nonbool(var);
537 } else if (!*value) {
538 curl_slist_free_all(host_resolutions);
539 host_resolutions = NULL;
540 } else {
541 host_resolutions = curl_slist_append(host_resolutions, value);
543 return 0;
546 if (!strcmp("http.followredirects", var)) {
547 if (value && !strcmp(value, "initial"))
548 http_follow_config = HTTP_FOLLOW_INITIAL;
549 else if (git_config_bool(var, value))
550 http_follow_config = HTTP_FOLLOW_ALWAYS;
551 else
552 http_follow_config = HTTP_FOLLOW_NONE;
553 return 0;
556 if (!strcmp("http.proactiveauth", var)) {
557 if (!value)
558 return config_error_nonbool(var);
559 if (!strcmp(value, "auto"))
560 http_proactive_auth = PROACTIVE_AUTH_AUTO;
561 else if (!strcmp(value, "basic"))
562 http_proactive_auth = PROACTIVE_AUTH_BASIC;
563 else if (!strcmp(value, "none"))
564 http_proactive_auth = PROACTIVE_AUTH_NONE;
565 else
566 warning(_("Unknown value for http.proactiveauth"));
567 return 0;
570 /* Fall back on the default ones */
571 return git_default_config(var, value, ctx, data);
574 static int curl_empty_auth_enabled(void)
576 if (curl_empty_auth >= 0)
577 return curl_empty_auth;
580 * In the automatic case, kick in the empty-auth
581 * hack as long as we would potentially try some
582 * method more exotic than "Basic" or "Digest".
584 * But only do this when this is our second or
585 * subsequent request, as by then we know what
586 * methods are available.
588 if (http_auth_methods_restricted &&
589 (http_auth_methods & ~empty_auth_useless))
590 return 1;
591 return 0;
594 struct curl_slist *http_append_auth_header(const struct credential *c,
595 struct curl_slist *headers)
597 if (c->authtype && c->credential) {
598 struct strbuf auth = STRBUF_INIT;
599 strbuf_addf(&auth, "Authorization: %s %s",
600 c->authtype, c->credential);
601 headers = curl_slist_append(headers, auth.buf);
602 strbuf_release(&auth);
604 return headers;
607 static void init_curl_http_auth(CURL *result)
609 if ((!http_auth.username || !*http_auth.username) &&
610 (!http_auth.credential || !*http_auth.credential)) {
611 int empty_auth = curl_empty_auth_enabled();
612 if ((empty_auth != -1 && !always_auth_proactively()) || empty_auth == 1) {
613 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
614 return;
615 } else if (!always_auth_proactively()) {
616 return;
617 } else if (http_proactive_auth == PROACTIVE_AUTH_BASIC) {
618 strvec_push(&http_auth.wwwauth_headers, "Basic");
622 credential_fill(&http_auth, 1);
624 if (http_auth.password) {
625 if (always_auth_proactively()) {
627 * We got a credential without an authtype and we don't
628 * know what's available. Since our only two options at
629 * the moment are auto (which defaults to basic) and
630 * basic, use basic for now.
632 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
634 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
635 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
639 /* *var must be free-able */
640 static void var_override(char **var, char *value)
642 if (value) {
643 free(*var);
644 *var = xstrdup(value);
648 static void set_proxyauth_name_password(CURL *result)
650 if (proxy_auth.password) {
651 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
652 proxy_auth.username);
653 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
654 proxy_auth.password);
655 } else if (proxy_auth.authtype && proxy_auth.credential) {
656 curl_easy_setopt(result, CURLOPT_PROXYHEADER,
657 http_append_auth_header(&proxy_auth, NULL));
661 static void init_curl_proxy_auth(CURL *result)
663 if (proxy_auth.username) {
664 if (!proxy_auth.password && !proxy_auth.credential)
665 credential_fill(&proxy_auth, 1);
666 set_proxyauth_name_password(result);
669 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
671 if (http_proxy_authmethod) {
672 int i;
673 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
674 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
675 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
676 proxy_authmethods[i].curlauth_param);
677 break;
680 if (i == ARRAY_SIZE(proxy_authmethods)) {
681 warning("unsupported proxy authentication method %s: using anyauth",
682 http_proxy_authmethod);
683 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
686 else
687 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
690 static int has_cert_password(void)
692 if (ssl_cert == NULL || ssl_cert_password_required != 1)
693 return 0;
694 if (!cert_auth.password) {
695 cert_auth.protocol = xstrdup("cert");
696 cert_auth.host = xstrdup("");
697 cert_auth.username = xstrdup("");
698 cert_auth.path = xstrdup(ssl_cert);
699 credential_fill(&cert_auth, 0);
701 return 1;
704 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
705 static int has_proxy_cert_password(void)
707 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
708 return 0;
709 if (!proxy_cert_auth.password) {
710 proxy_cert_auth.protocol = xstrdup("cert");
711 proxy_cert_auth.host = xstrdup("");
712 proxy_cert_auth.username = xstrdup("");
713 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
714 credential_fill(&proxy_cert_auth, 0);
716 return 1;
718 #endif
720 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
721 static void set_curl_keepalive(CURL *c)
723 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
726 #else
727 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
729 int ka = 1;
730 int rc;
731 socklen_t len = (socklen_t)sizeof(ka);
733 if (type != CURLSOCKTYPE_IPCXN)
734 return 0;
736 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
737 if (rc < 0)
738 warning_errno("unable to set SO_KEEPALIVE on socket");
740 return CURL_SOCKOPT_OK;
743 static void set_curl_keepalive(CURL *c)
745 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
747 #endif
749 /* Return 1 if redactions have been made, 0 otherwise. */
750 static int redact_sensitive_header(struct strbuf *header, size_t offset)
752 int ret = 0;
753 const char *sensitive_header;
755 if (trace_curl_redact &&
756 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
757 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
758 /* The first token is the type, which is OK to log */
759 while (isspace(*sensitive_header))
760 sensitive_header++;
761 while (*sensitive_header && !isspace(*sensitive_header))
762 sensitive_header++;
763 /* Everything else is opaque and possibly sensitive */
764 strbuf_setlen(header, sensitive_header - header->buf);
765 strbuf_addstr(header, " <redacted>");
766 ret = 1;
767 } else if (trace_curl_redact &&
768 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
769 struct strbuf redacted_header = STRBUF_INIT;
770 const char *cookie;
772 while (isspace(*sensitive_header))
773 sensitive_header++;
775 cookie = sensitive_header;
777 while (cookie) {
778 char *equals;
779 char *semicolon = strstr(cookie, "; ");
780 if (semicolon)
781 *semicolon = 0;
782 equals = strchrnul(cookie, '=');
783 if (!equals) {
784 /* invalid cookie, just append and continue */
785 strbuf_addstr(&redacted_header, cookie);
786 continue;
788 strbuf_add(&redacted_header, cookie, equals - cookie);
789 strbuf_addstr(&redacted_header, "=<redacted>");
790 if (semicolon) {
792 * There are more cookies. (Or, for some
793 * reason, the input string ends in "; ".)
795 strbuf_addstr(&redacted_header, "; ");
796 cookie = semicolon + strlen("; ");
797 } else {
798 cookie = NULL;
802 strbuf_setlen(header, sensitive_header - header->buf);
803 strbuf_addbuf(header, &redacted_header);
804 strbuf_release(&redacted_header);
805 ret = 1;
807 return ret;
810 static int match_curl_h2_trace(const char *line, const char **out)
812 const char *p;
815 * curl prior to 8.1.0 gives us:
817 * h2h3 [<header-name>: <header-val>]
819 * Starting in 8.1.0, the first token became just "h2".
821 if (skip_iprefix(line, "h2h3 [", out) ||
822 skip_iprefix(line, "h2 [", out))
823 return 1;
826 * curl 8.3.0 uses:
827 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
828 * where <stream-id> is numeric.
830 if (skip_iprefix(line, "[HTTP/2] [", &p)) {
831 while (isdigit(*p))
832 p++;
833 if (skip_prefix(p, "] [", out))
834 return 1;
837 return 0;
840 /* Redact headers in info */
841 static void redact_sensitive_info_header(struct strbuf *header)
843 const char *sensitive_header;
845 if (trace_curl_redact &&
846 match_curl_h2_trace(header->buf, &sensitive_header)) {
847 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
848 /* redaction ate our closing bracket */
849 strbuf_addch(header, ']');
854 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
856 struct strbuf out = STRBUF_INIT;
857 struct strbuf **headers, **header;
859 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
860 text, (long)size, (long)size);
861 trace_strbuf(&trace_curl, &out);
862 strbuf_reset(&out);
863 strbuf_add(&out, ptr, size);
864 headers = strbuf_split_max(&out, '\n', 0);
866 for (header = headers; *header; header++) {
867 if (hide_sensitive_header)
868 redact_sensitive_header(*header, 0);
869 strbuf_insertstr((*header), 0, text);
870 strbuf_insertstr((*header), strlen(text), ": ");
871 strbuf_rtrim((*header));
872 strbuf_addch((*header), '\n');
873 trace_strbuf(&trace_curl, (*header));
875 strbuf_list_free(headers);
876 strbuf_release(&out);
879 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
881 size_t i;
882 struct strbuf out = STRBUF_INIT;
883 unsigned int width = 60;
885 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
886 text, (long)size, (long)size);
887 trace_strbuf(&trace_curl, &out);
889 for (i = 0; i < size; i += width) {
890 size_t w;
892 strbuf_reset(&out);
893 strbuf_addf(&out, "%s: ", text);
894 for (w = 0; (w < width) && (i + w < size); w++) {
895 unsigned char ch = ptr[i + w];
897 strbuf_addch(&out,
898 (ch >= 0x20) && (ch < 0x80)
899 ? ch : '.');
901 strbuf_addch(&out, '\n');
902 trace_strbuf(&trace_curl, &out);
904 strbuf_release(&out);
907 static void curl_dump_info(char *data, size_t size)
909 struct strbuf buf = STRBUF_INIT;
911 strbuf_add(&buf, data, size);
913 redact_sensitive_info_header(&buf);
914 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
916 strbuf_release(&buf);
919 static int curl_trace(CURL *handle UNUSED, curl_infotype type,
920 char *data, size_t size,
921 void *userp UNUSED)
923 const char *text;
924 enum { NO_FILTER = 0, DO_FILTER = 1 };
926 switch (type) {
927 case CURLINFO_TEXT:
928 curl_dump_info(data, size);
929 break;
930 case CURLINFO_HEADER_OUT:
931 text = "=> Send header";
932 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
933 break;
934 case CURLINFO_DATA_OUT:
935 if (trace_curl_data) {
936 text = "=> Send data";
937 curl_dump_data(text, (unsigned char *)data, size);
939 break;
940 case CURLINFO_SSL_DATA_OUT:
941 if (trace_curl_data) {
942 text = "=> Send SSL data";
943 curl_dump_data(text, (unsigned char *)data, size);
945 break;
946 case CURLINFO_HEADER_IN:
947 text = "<= Recv header";
948 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
949 break;
950 case CURLINFO_DATA_IN:
951 if (trace_curl_data) {
952 text = "<= Recv data";
953 curl_dump_data(text, (unsigned char *)data, size);
955 break;
956 case CURLINFO_SSL_DATA_IN:
957 if (trace_curl_data) {
958 text = "<= Recv SSL data";
959 curl_dump_data(text, (unsigned char *)data, size);
961 break;
963 default: /* we ignore unknown types by default */
964 return 0;
966 return 0;
969 void http_trace_curl_no_data(void)
971 trace_override_envvar(&trace_curl, "1");
972 trace_curl_data = 0;
975 void setup_curl_trace(CURL *handle)
977 if (!trace_want(&trace_curl))
978 return;
979 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
980 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
981 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
984 static void proto_list_append(struct strbuf *list, const char *proto)
986 if (!list)
987 return;
988 if (list->len)
989 strbuf_addch(list, ',');
990 strbuf_addstr(list, proto);
993 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
995 long bits = 0;
997 if (is_transport_allowed("http", from_user)) {
998 bits |= CURLPROTO_HTTP;
999 proto_list_append(list, "http");
1001 if (is_transport_allowed("https", from_user)) {
1002 bits |= CURLPROTO_HTTPS;
1003 proto_list_append(list, "https");
1005 if (is_transport_allowed("ftp", from_user)) {
1006 bits |= CURLPROTO_FTP;
1007 proto_list_append(list, "ftp");
1009 if (is_transport_allowed("ftps", from_user)) {
1010 bits |= CURLPROTO_FTPS;
1011 proto_list_append(list, "ftps");
1014 return bits;
1017 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1018 static int get_curl_http_version_opt(const char *version_string, long *opt)
1020 int i;
1021 static struct {
1022 const char *name;
1023 long opt_token;
1024 } choice[] = {
1025 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
1026 { "HTTP/2", CURL_HTTP_VERSION_2 }
1029 for (i = 0; i < ARRAY_SIZE(choice); i++) {
1030 if (!strcmp(version_string, choice[i].name)) {
1031 *opt = choice[i].opt_token;
1032 return 0;
1036 warning("unknown value given to http.version: '%s'", version_string);
1037 return -1; /* not found */
1040 #endif
1042 static CURL *get_curl_handle(void)
1044 CURL *result = curl_easy_init();
1046 if (!result)
1047 die("curl_easy_init failed");
1049 if (!curl_ssl_verify) {
1050 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
1051 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
1052 } else {
1053 /* Verify authenticity of the peer's certificate */
1054 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
1055 /* The name in the cert must match whom we tried to connect */
1056 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
1059 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1060 if (curl_http_version) {
1061 long opt;
1062 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
1063 /* Set request use http version */
1064 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
1067 #endif
1069 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
1070 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
1072 #ifdef CURLGSSAPI_DELEGATION_FLAG
1073 if (curl_deleg) {
1074 int i;
1075 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
1076 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
1077 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
1078 curl_deleg_levels[i].curl_deleg_param);
1079 break;
1082 if (i == ARRAY_SIZE(curl_deleg_levels))
1083 warning("Unknown delegation method '%s': using default",
1084 curl_deleg);
1086 #endif
1088 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1089 !http_schannel_check_revoke) {
1090 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1091 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
1092 #else
1093 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1094 #endif
1097 if (http_proactive_auth != PROACTIVE_AUTH_NONE)
1098 init_curl_http_auth(result);
1100 if (getenv("GIT_SSL_VERSION"))
1101 ssl_version = getenv("GIT_SSL_VERSION");
1102 if (ssl_version && *ssl_version) {
1103 int i;
1104 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
1105 if (!strcmp(ssl_version, sslversions[i].name)) {
1106 curl_easy_setopt(result, CURLOPT_SSLVERSION,
1107 sslversions[i].ssl_version);
1108 break;
1111 if (i == ARRAY_SIZE(sslversions))
1112 warning("unsupported ssl version %s: using default",
1113 ssl_version);
1116 if (getenv("GIT_SSL_CIPHER_LIST"))
1117 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
1118 if (ssl_cipherlist != NULL && *ssl_cipherlist)
1119 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
1120 ssl_cipherlist);
1122 if (ssl_cert)
1123 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
1124 if (ssl_cert_type)
1125 curl_easy_setopt(result, CURLOPT_SSLCERTTYPE, ssl_cert_type);
1126 if (has_cert_password())
1127 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
1128 if (ssl_key)
1129 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
1130 if (ssl_key_type)
1131 curl_easy_setopt(result, CURLOPT_SSLKEYTYPE, ssl_key_type);
1132 if (ssl_capath)
1133 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
1134 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1135 if (ssl_pinnedkey)
1136 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
1137 #endif
1138 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
1139 !http_schannel_use_ssl_cainfo) {
1140 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
1141 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1142 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
1143 #endif
1144 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
1145 if (ssl_cainfo)
1146 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
1147 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1148 if (http_proxy_ssl_ca_info)
1149 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
1150 #endif
1153 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
1154 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
1155 curl_low_speed_limit);
1156 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
1157 curl_low_speed_time);
1160 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
1161 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
1163 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1165 struct strbuf buf = STRBUF_INIT;
1167 get_curl_allowed_protocols(0, &buf);
1168 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
1169 strbuf_reset(&buf);
1171 get_curl_allowed_protocols(-1, &buf);
1172 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
1173 strbuf_release(&buf);
1175 #else
1176 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
1177 get_curl_allowed_protocols(0, NULL));
1178 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
1179 get_curl_allowed_protocols(-1, NULL));
1180 #endif
1182 if (getenv("GIT_CURL_VERBOSE"))
1183 http_trace_curl_no_data();
1184 setup_curl_trace(result);
1185 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1186 trace_curl_data = 0;
1187 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1188 trace_curl_redact = 0;
1190 curl_easy_setopt(result, CURLOPT_USERAGENT,
1191 user_agent ? user_agent : git_user_agent());
1193 if (curl_ftp_no_epsv)
1194 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1196 if (curl_ssl_try)
1197 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1200 * CURL also examines these variables as a fallback; but we need to query
1201 * them here in order to decide whether to prompt for missing password (cf.
1202 * init_curl_proxy_auth()).
1204 * Unlike many other common environment variables, these are historically
1205 * lowercase only. It appears that CURL did not know this and implemented
1206 * only uppercase variants, which was later corrected to take both - with
1207 * the exception of http_proxy, which is lowercase only also in CURL. As
1208 * the lowercase versions are the historical quasi-standard, they take
1209 * precedence here, as in CURL.
1211 if (!curl_http_proxy) {
1212 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1213 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1214 var_override(&curl_http_proxy, getenv("https_proxy"));
1215 } else {
1216 var_override(&curl_http_proxy, getenv("http_proxy"));
1218 if (!curl_http_proxy) {
1219 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1220 var_override(&curl_http_proxy, getenv("all_proxy"));
1224 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1226 * Handle case with the empty http.proxy value here to keep
1227 * common code clean.
1228 * NB: empty option disables proxying at all.
1230 curl_easy_setopt(result, CURLOPT_PROXY, "");
1231 } else if (curl_http_proxy) {
1232 struct strbuf proxy = STRBUF_INIT;
1234 if (starts_with(curl_http_proxy, "socks5h"))
1235 curl_easy_setopt(result,
1236 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1237 else if (starts_with(curl_http_proxy, "socks5"))
1238 curl_easy_setopt(result,
1239 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1240 else if (starts_with(curl_http_proxy, "socks4a"))
1241 curl_easy_setopt(result,
1242 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1243 else if (starts_with(curl_http_proxy, "socks"))
1244 curl_easy_setopt(result,
1245 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1246 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1247 else if (starts_with(curl_http_proxy, "https")) {
1248 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1250 if (http_proxy_ssl_cert)
1251 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1253 if (http_proxy_ssl_key)
1254 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1256 if (has_proxy_cert_password())
1257 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1259 #endif
1260 if (strstr(curl_http_proxy, "://"))
1261 credential_from_url(&proxy_auth, curl_http_proxy);
1262 else {
1263 struct strbuf url = STRBUF_INIT;
1264 strbuf_addf(&url, "http://%s", curl_http_proxy);
1265 credential_from_url(&proxy_auth, url.buf);
1266 strbuf_release(&url);
1269 if (!proxy_auth.host)
1270 die("Invalid proxy URL '%s'", curl_http_proxy);
1272 strbuf_addstr(&proxy, proxy_auth.host);
1273 if (proxy_auth.path) {
1274 curl_version_info_data *ver = curl_version_info(CURLVERSION_NOW);
1276 if (ver->version_num < 0x075400)
1277 die("libcurl 7.84 or later is required to support paths in proxy URLs");
1279 if (!starts_with(proxy_auth.protocol, "socks"))
1280 die("Invalid proxy URL '%s': only SOCKS proxies support paths",
1281 curl_http_proxy);
1283 if (strcasecmp(proxy_auth.host, "localhost"))
1284 die("Invalid proxy URL '%s': host must be localhost if a path is present",
1285 curl_http_proxy);
1287 strbuf_addch(&proxy, '/');
1288 strbuf_add_percentencode(&proxy, proxy_auth.path, 0);
1290 curl_easy_setopt(result, CURLOPT_PROXY, proxy.buf);
1291 strbuf_release(&proxy);
1293 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1294 var_override(&curl_no_proxy, getenv("no_proxy"));
1295 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1297 init_curl_proxy_auth(result);
1299 set_curl_keepalive(result);
1301 return result;
1304 static void set_from_env(char **var, const char *envname)
1306 const char *val = getenv(envname);
1307 if (val) {
1308 FREE_AND_NULL(*var);
1309 *var = xstrdup(val);
1313 void http_init(struct remote *remote, const char *url, int proactive_auth)
1315 char *low_speed_limit;
1316 char *low_speed_time;
1317 char *normalized_url;
1318 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1320 config.section = "http";
1321 config.key = NULL;
1322 config.collect_fn = http_options;
1323 config.cascade_fn = git_default_config;
1324 config.cb = NULL;
1326 http_is_verbose = 0;
1327 normalized_url = url_normalize(url, &config.url);
1329 git_config(urlmatch_config_entry, &config);
1330 free(normalized_url);
1331 string_list_clear(&config.vars, 1);
1333 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1334 if (http_ssl_backend) {
1335 const curl_ssl_backend **backends;
1336 struct strbuf buf = STRBUF_INIT;
1337 int i;
1339 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1340 case CURLSSLSET_UNKNOWN_BACKEND:
1341 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1342 "Supported SSL backends:"),
1343 http_ssl_backend);
1344 for (i = 0; backends[i]; i++)
1345 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1346 die("%s", buf.buf);
1347 case CURLSSLSET_NO_BACKENDS:
1348 die(_("Could not set SSL backend to '%s': "
1349 "cURL was built without SSL backends"),
1350 http_ssl_backend);
1351 case CURLSSLSET_TOO_LATE:
1352 die(_("Could not set SSL backend to '%s': already set"),
1353 http_ssl_backend);
1354 case CURLSSLSET_OK:
1355 break; /* Okay! */
1358 #endif
1360 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1361 die("curl_global_init failed");
1363 if (proactive_auth && http_proactive_auth == PROACTIVE_AUTH_NONE)
1364 http_proactive_auth = PROACTIVE_AUTH_IF_CREDENTIALS;
1366 if (remote && remote->http_proxy)
1367 curl_http_proxy = xstrdup(remote->http_proxy);
1369 if (remote)
1370 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1372 pragma_header = curl_slist_append(http_copy_default_headers(),
1373 "Pragma: no-cache");
1376 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1377 if (http_max_requests)
1378 max_requests = atoi(http_max_requests);
1381 curlm = curl_multi_init();
1382 if (!curlm)
1383 die("curl_multi_init failed");
1385 if (getenv("GIT_SSL_NO_VERIFY"))
1386 curl_ssl_verify = 0;
1388 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1389 set_from_env(&ssl_cert_type, "GIT_SSL_CERT_TYPE");
1390 set_from_env(&ssl_key, "GIT_SSL_KEY");
1391 set_from_env(&ssl_key_type, "GIT_SSL_KEY_TYPE");
1392 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1393 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1395 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1397 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1398 if (low_speed_limit)
1399 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1400 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1401 if (low_speed_time)
1402 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1404 if (curl_ssl_verify == -1)
1405 curl_ssl_verify = 1;
1407 curl_session_count = 0;
1408 if (max_requests < 1)
1409 max_requests = DEFAULT_MAX_REQUESTS;
1411 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1412 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1413 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1415 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1416 proxy_ssl_cert_password_required = 1;
1418 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1419 curl_ftp_no_epsv = 1;
1421 if (url) {
1422 credential_from_url(&http_auth, url);
1423 if (!ssl_cert_password_required &&
1424 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1425 starts_with(url, "https://"))
1426 ssl_cert_password_required = 1;
1429 curl_default = get_curl_handle();
1432 void http_cleanup(void)
1434 struct active_request_slot *slot = active_queue_head;
1436 while (slot != NULL) {
1437 struct active_request_slot *next = slot->next;
1438 if (slot->curl) {
1439 xmulti_remove_handle(slot);
1440 curl_easy_cleanup(slot->curl);
1442 free(slot);
1443 slot = next;
1445 active_queue_head = NULL;
1447 curl_easy_cleanup(curl_default);
1449 curl_multi_cleanup(curlm);
1450 curl_global_cleanup();
1452 string_list_clear(&extra_http_headers, 0);
1454 curl_slist_free_all(pragma_header);
1455 pragma_header = NULL;
1457 curl_slist_free_all(host_resolutions);
1458 host_resolutions = NULL;
1460 if (curl_http_proxy) {
1461 free((void *)curl_http_proxy);
1462 curl_http_proxy = NULL;
1465 if (proxy_auth.password) {
1466 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1467 FREE_AND_NULL(proxy_auth.password);
1470 free((void *)curl_proxyuserpwd);
1471 curl_proxyuserpwd = NULL;
1473 free((void *)http_proxy_authmethod);
1474 http_proxy_authmethod = NULL;
1476 if (cert_auth.password) {
1477 memset(cert_auth.password, 0, strlen(cert_auth.password));
1478 FREE_AND_NULL(cert_auth.password);
1480 ssl_cert_password_required = 0;
1482 if (proxy_cert_auth.password) {
1483 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1484 FREE_AND_NULL(proxy_cert_auth.password);
1486 proxy_ssl_cert_password_required = 0;
1488 FREE_AND_NULL(cached_accept_language);
1491 struct active_request_slot *get_active_slot(void)
1493 struct active_request_slot *slot = active_queue_head;
1494 struct active_request_slot *newslot;
1496 int num_transfers;
1498 /* Wait for a slot to open up if the queue is full */
1499 while (active_requests >= max_requests) {
1500 curl_multi_perform(curlm, &num_transfers);
1501 if (num_transfers < active_requests)
1502 process_curl_messages();
1505 while (slot != NULL && slot->in_use)
1506 slot = slot->next;
1508 if (!slot) {
1509 newslot = xmalloc(sizeof(*newslot));
1510 newslot->curl = NULL;
1511 newslot->in_use = 0;
1512 newslot->next = NULL;
1514 slot = active_queue_head;
1515 if (!slot) {
1516 active_queue_head = newslot;
1517 } else {
1518 while (slot->next != NULL)
1519 slot = slot->next;
1520 slot->next = newslot;
1522 slot = newslot;
1525 if (!slot->curl) {
1526 slot->curl = curl_easy_duphandle(curl_default);
1527 curl_session_count++;
1530 active_requests++;
1531 slot->in_use = 1;
1532 slot->results = NULL;
1533 slot->finished = NULL;
1534 slot->callback_data = NULL;
1535 slot->callback_func = NULL;
1537 if (curl_cookie_file && !strcmp(curl_cookie_file, "-")) {
1538 warning(_("refusing to read cookies from http.cookiefile '-'"));
1539 FREE_AND_NULL(curl_cookie_file);
1541 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1542 if (curl_save_cookies && (!curl_cookie_file || !curl_cookie_file[0])) {
1543 curl_save_cookies = 0;
1544 warning(_("ignoring http.savecookies for empty http.cookiefile"));
1546 if (curl_save_cookies)
1547 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1548 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1549 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1550 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1551 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1552 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1553 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1554 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1555 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, -1L);
1556 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1557 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1558 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1559 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1562 * Default following to off unless "ALWAYS" is configured; this gives
1563 * callers a sane starting point, and they can tweak for individual
1564 * HTTP_FOLLOW_* cases themselves.
1566 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1567 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1568 else
1569 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1571 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1572 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1573 if (http_auth.password || http_auth.credential || curl_empty_auth_enabled())
1574 init_curl_http_auth(slot->curl);
1576 return slot;
1579 int start_active_slot(struct active_request_slot *slot)
1581 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1582 int num_transfers;
1584 if (curlm_result != CURLM_OK &&
1585 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1586 warning("curl_multi_add_handle failed: %s",
1587 curl_multi_strerror(curlm_result));
1588 active_requests--;
1589 slot->in_use = 0;
1590 return 0;
1594 * We know there must be something to do, since we just added
1595 * something.
1597 curl_multi_perform(curlm, &num_transfers);
1598 return 1;
1601 struct fill_chain {
1602 void *data;
1603 int (*fill)(void *);
1604 struct fill_chain *next;
1607 static struct fill_chain *fill_cfg;
1609 void add_fill_function(void *data, int (*fill)(void *))
1611 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1612 struct fill_chain **linkp = &fill_cfg;
1613 new_fill->data = data;
1614 new_fill->fill = fill;
1615 new_fill->next = NULL;
1616 while (*linkp)
1617 linkp = &(*linkp)->next;
1618 *linkp = new_fill;
1621 void fill_active_slots(void)
1623 struct active_request_slot *slot = active_queue_head;
1625 while (active_requests < max_requests) {
1626 struct fill_chain *fill;
1627 for (fill = fill_cfg; fill; fill = fill->next)
1628 if (fill->fill(fill->data))
1629 break;
1631 if (!fill)
1632 break;
1635 while (slot != NULL) {
1636 if (!slot->in_use && slot->curl != NULL
1637 && curl_session_count > min_curl_sessions) {
1638 curl_easy_cleanup(slot->curl);
1639 slot->curl = NULL;
1640 curl_session_count--;
1642 slot = slot->next;
1646 void step_active_slots(void)
1648 int num_transfers;
1649 CURLMcode curlm_result;
1651 do {
1652 curlm_result = curl_multi_perform(curlm, &num_transfers);
1653 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1654 if (num_transfers < active_requests) {
1655 process_curl_messages();
1656 fill_active_slots();
1660 void run_active_slot(struct active_request_slot *slot)
1662 fd_set readfds;
1663 fd_set writefds;
1664 fd_set excfds;
1665 int max_fd;
1666 struct timeval select_timeout;
1667 int finished = 0;
1669 slot->finished = &finished;
1670 while (!finished) {
1671 step_active_slots();
1673 if (slot->in_use) {
1674 long curl_timeout;
1675 curl_multi_timeout(curlm, &curl_timeout);
1676 if (curl_timeout == 0) {
1677 continue;
1678 } else if (curl_timeout == -1) {
1679 select_timeout.tv_sec = 0;
1680 select_timeout.tv_usec = 50000;
1681 } else {
1682 select_timeout.tv_sec = curl_timeout / 1000;
1683 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1686 max_fd = -1;
1687 FD_ZERO(&readfds);
1688 FD_ZERO(&writefds);
1689 FD_ZERO(&excfds);
1690 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1693 * It can happen that curl_multi_timeout returns a pathologically
1694 * long timeout when curl_multi_fdset returns no file descriptors
1695 * to read. See commit message for more details.
1697 if (max_fd < 0 &&
1698 (select_timeout.tv_sec > 0 ||
1699 select_timeout.tv_usec > 50000)) {
1700 select_timeout.tv_sec = 0;
1701 select_timeout.tv_usec = 50000;
1704 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1709 * The value of slot->finished we set before the loop was used
1710 * to set our "finished" variable when our request completed.
1712 * 1. The slot may not have been reused for another request
1713 * yet, in which case it still has &finished.
1715 * 2. The slot may already be in-use to serve another request,
1716 * which can further be divided into two cases:
1718 * (a) If call run_active_slot() hasn't been called for that
1719 * other request, slot->finished would have been cleared
1720 * by get_active_slot() and has NULL.
1722 * (b) If the request did call run_active_slot(), then the
1723 * call would have updated slot->finished at the beginning
1724 * of this function, and with the clearing of the member
1725 * below, we would find that slot->finished is now NULL.
1727 * In all cases, slot->finished has no useful information to
1728 * anybody at this point. Some compilers warn us for
1729 * attempting to smuggle a pointer that is about to become
1730 * invalid, i.e. &finished. We clear it here to assure them.
1732 slot->finished = NULL;
1735 static void release_active_slot(struct active_request_slot *slot)
1737 closedown_active_slot(slot);
1738 if (slot->curl) {
1739 xmulti_remove_handle(slot);
1740 if (curl_session_count > min_curl_sessions) {
1741 curl_easy_cleanup(slot->curl);
1742 slot->curl = NULL;
1743 curl_session_count--;
1746 fill_active_slots();
1749 void finish_all_active_slots(void)
1751 struct active_request_slot *slot = active_queue_head;
1753 while (slot != NULL)
1754 if (slot->in_use) {
1755 run_active_slot(slot);
1756 slot = active_queue_head;
1757 } else {
1758 slot = slot->next;
1762 /* Helpers for modifying and creating URLs */
1763 static inline int needs_quote(int ch)
1765 if (((ch >= 'A') && (ch <= 'Z'))
1766 || ((ch >= 'a') && (ch <= 'z'))
1767 || ((ch >= '0') && (ch <= '9'))
1768 || (ch == '/')
1769 || (ch == '-')
1770 || (ch == '.'))
1771 return 0;
1772 return 1;
1775 static char *quote_ref_url(const char *base, const char *ref)
1777 struct strbuf buf = STRBUF_INIT;
1778 const char *cp;
1779 int ch;
1781 end_url_with_slash(&buf, base);
1783 for (cp = ref; (ch = *cp) != 0; cp++)
1784 if (needs_quote(ch))
1785 strbuf_addf(&buf, "%%%02x", ch);
1786 else
1787 strbuf_addch(&buf, *cp);
1789 return strbuf_detach(&buf, NULL);
1792 void append_remote_object_url(struct strbuf *buf, const char *url,
1793 const char *hex,
1794 int only_two_digit_prefix)
1796 end_url_with_slash(buf, url);
1798 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1799 if (!only_two_digit_prefix)
1800 strbuf_addstr(buf, hex + 2);
1803 char *get_remote_object_url(const char *url, const char *hex,
1804 int only_two_digit_prefix)
1806 struct strbuf buf = STRBUF_INIT;
1807 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1808 return strbuf_detach(&buf, NULL);
1811 void normalize_curl_result(CURLcode *result, long http_code,
1812 char *errorstr, size_t errorlen)
1815 * If we see a failing http code with CURLE_OK, we have turned off
1816 * FAILONERROR (to keep the server's custom error response), and should
1817 * translate the code into failure here.
1819 * Likewise, if we see a redirect (30x code), that means we turned off
1820 * redirect-following, and we should treat the result as an error.
1822 if (*result == CURLE_OK && http_code >= 300) {
1823 *result = CURLE_HTTP_RETURNED_ERROR;
1825 * Normally curl will already have put the "reason phrase"
1826 * from the server into curl_errorstr; unfortunately without
1827 * FAILONERROR it is lost, so we can give only the numeric
1828 * status code.
1830 xsnprintf(errorstr, errorlen,
1831 "The requested URL returned error: %ld",
1832 http_code);
1836 static int handle_curl_result(struct slot_results *results)
1838 normalize_curl_result(&results->curl_result, results->http_code,
1839 curl_errorstr, sizeof(curl_errorstr));
1841 if (results->curl_result == CURLE_OK) {
1842 credential_approve(&http_auth);
1843 credential_approve(&proxy_auth);
1844 credential_approve(&cert_auth);
1845 return HTTP_OK;
1846 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1848 * We can't tell from here whether it's a bad path, bad
1849 * certificate, bad password, or something else wrong
1850 * with the certificate. So we reject the credential to
1851 * avoid caching or saving a bad password.
1853 credential_reject(&cert_auth);
1854 return HTTP_NOAUTH;
1855 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1856 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1857 return HTTP_NOMATCHPUBLICKEY;
1858 #endif
1859 } else if (missing_target(results))
1860 return HTTP_MISSING_TARGET;
1861 else if (results->http_code == 401) {
1862 if ((http_auth.username && http_auth.password) ||\
1863 (http_auth.authtype && http_auth.credential)) {
1864 if (http_auth.multistage) {
1865 credential_clear_secrets(&http_auth);
1866 return HTTP_REAUTH;
1868 credential_reject(&http_auth);
1869 if (always_auth_proactively())
1870 http_proactive_auth = PROACTIVE_AUTH_NONE;
1871 return HTTP_NOAUTH;
1872 } else {
1873 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1874 if (results->auth_avail) {
1875 http_auth_methods &= results->auth_avail;
1876 http_auth_methods_restricted = 1;
1878 return HTTP_REAUTH;
1880 } else {
1881 if (results->http_connectcode == 407)
1882 credential_reject(&proxy_auth);
1883 if (!curl_errorstr[0])
1884 strlcpy(curl_errorstr,
1885 curl_easy_strerror(results->curl_result),
1886 sizeof(curl_errorstr));
1887 return HTTP_ERROR;
1891 int run_one_slot(struct active_request_slot *slot,
1892 struct slot_results *results)
1894 slot->results = results;
1895 if (!start_active_slot(slot)) {
1896 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1897 "failed to start HTTP request");
1898 return HTTP_START_FAILED;
1901 run_active_slot(slot);
1902 return handle_curl_result(results);
1905 struct curl_slist *http_copy_default_headers(void)
1907 struct curl_slist *headers = NULL;
1908 const struct string_list_item *item;
1910 for_each_string_list_item(item, &extra_http_headers)
1911 headers = curl_slist_append(headers, item->string);
1913 return headers;
1916 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1918 char *ptr;
1919 CURLcode ret;
1921 strbuf_reset(buf);
1922 ret = curl_easy_getinfo(curl, info, &ptr);
1923 if (!ret && ptr)
1924 strbuf_addstr(buf, ptr);
1925 return ret;
1929 * Check for and extract a content-type parameter. "raw"
1930 * should be positioned at the start of the potential
1931 * parameter, with any whitespace already removed.
1933 * "name" is the name of the parameter. The value is appended
1934 * to "out".
1936 static int extract_param(const char *raw, const char *name,
1937 struct strbuf *out)
1939 size_t len = strlen(name);
1941 if (strncasecmp(raw, name, len))
1942 return -1;
1943 raw += len;
1945 if (*raw != '=')
1946 return -1;
1947 raw++;
1949 while (*raw && !isspace(*raw) && *raw != ';')
1950 strbuf_addch(out, *raw++);
1951 return 0;
1955 * Extract a normalized version of the content type, with any
1956 * spaces suppressed, all letters lowercased, and no trailing ";"
1957 * or parameters.
1959 * Note that we will silently remove even invalid whitespace. For
1960 * example, "text / plain" is specifically forbidden by RFC 2616,
1961 * but "text/plain" is the only reasonable output, and this keeps
1962 * our code simple.
1964 * If the "charset" argument is not NULL, store the value of any
1965 * charset parameter there.
1967 * Example:
1968 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1969 * "text / plain" -> "text/plain"
1971 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1972 struct strbuf *charset)
1974 const char *p;
1976 strbuf_reset(type);
1977 strbuf_grow(type, raw->len);
1978 for (p = raw->buf; *p; p++) {
1979 if (isspace(*p))
1980 continue;
1981 if (*p == ';') {
1982 p++;
1983 break;
1985 strbuf_addch(type, tolower(*p));
1988 if (!charset)
1989 return;
1991 strbuf_reset(charset);
1992 while (*p) {
1993 while (isspace(*p) || *p == ';')
1994 p++;
1995 if (!extract_param(p, "charset", charset))
1996 return;
1997 while (*p && !isspace(*p))
1998 p++;
2001 if (!charset->len && starts_with(type->buf, "text/"))
2002 strbuf_addstr(charset, "ISO-8859-1");
2005 static void write_accept_language(struct strbuf *buf)
2008 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
2009 * that, q-value will be smaller than 0.001, the minimum q-value the
2010 * HTTP specification allows. See
2011 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
2013 const int MAX_DECIMAL_PLACES = 3;
2014 const int MAX_LANGUAGE_TAGS = 1000;
2015 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
2016 char **language_tags = NULL;
2017 int num_langs = 0;
2018 const char *s = get_preferred_languages();
2019 int i;
2020 struct strbuf tag = STRBUF_INIT;
2022 /* Don't add Accept-Language header if no language is preferred. */
2023 if (!s)
2024 return;
2027 * Split the colon-separated string of preferred languages into
2028 * language_tags array.
2030 do {
2031 /* collect language tag */
2032 for (; *s && (isalnum(*s) || *s == '_'); s++)
2033 strbuf_addch(&tag, *s == '_' ? '-' : *s);
2035 /* skip .codeset, @modifier and any other unnecessary parts */
2036 while (*s && *s != ':')
2037 s++;
2039 if (tag.len) {
2040 num_langs++;
2041 REALLOC_ARRAY(language_tags, num_langs);
2042 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
2043 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
2044 break;
2046 } while (*s++);
2048 /* write Accept-Language header into buf */
2049 if (num_langs) {
2050 int last_buf_len = 0;
2051 int max_q;
2052 int decimal_places;
2053 char q_format[32];
2055 /* add '*' */
2056 REALLOC_ARRAY(language_tags, num_langs + 1);
2057 language_tags[num_langs++] = xstrdup("*");
2059 /* compute decimal_places */
2060 for (max_q = 1, decimal_places = 0;
2061 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
2062 decimal_places++, max_q *= 10)
2065 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
2067 strbuf_addstr(buf, "Accept-Language: ");
2069 for (i = 0; i < num_langs; i++) {
2070 if (i > 0)
2071 strbuf_addstr(buf, ", ");
2073 strbuf_addstr(buf, language_tags[i]);
2075 if (i > 0)
2076 strbuf_addf(buf, q_format, max_q - i);
2078 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
2079 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
2080 break;
2083 last_buf_len = buf->len;
2087 for (i = 0; i < num_langs; i++)
2088 free(language_tags[i]);
2089 free(language_tags);
2093 * Get an Accept-Language header which indicates user's preferred languages.
2095 * Examples:
2096 * LANGUAGE= -> ""
2097 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
2098 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
2099 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
2100 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
2101 * LANGUAGE= LANG=C -> ""
2103 const char *http_get_accept_language_header(void)
2105 if (!cached_accept_language) {
2106 struct strbuf buf = STRBUF_INIT;
2107 write_accept_language(&buf);
2108 if (buf.len > 0)
2109 cached_accept_language = strbuf_detach(&buf, NULL);
2112 return cached_accept_language;
2115 static void http_opt_request_remainder(CURL *curl, off_t pos)
2117 char buf[128];
2118 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
2119 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
2122 /* http_request() targets */
2123 #define HTTP_REQUEST_STRBUF 0
2124 #define HTTP_REQUEST_FILE 1
2126 static int http_request(const char *url,
2127 void *result, int target,
2128 const struct http_get_options *options)
2130 struct active_request_slot *slot;
2131 struct slot_results results;
2132 struct curl_slist *headers = http_copy_default_headers();
2133 struct strbuf buf = STRBUF_INIT;
2134 const char *accept_language;
2135 int ret;
2137 slot = get_active_slot();
2138 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
2140 if (!result) {
2141 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
2142 } else {
2143 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
2144 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
2146 if (target == HTTP_REQUEST_FILE) {
2147 off_t posn = ftello(result);
2148 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2149 fwrite);
2150 if (posn > 0)
2151 http_opt_request_remainder(slot->curl, posn);
2152 } else
2153 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
2154 fwrite_buffer);
2157 curl_easy_setopt(slot->curl, CURLOPT_HEADERFUNCTION, fwrite_wwwauth);
2159 accept_language = http_get_accept_language_header();
2161 if (accept_language)
2162 headers = curl_slist_append(headers, accept_language);
2164 strbuf_addstr(&buf, "Pragma:");
2165 if (options && options->no_cache)
2166 strbuf_addstr(&buf, " no-cache");
2167 if (options && options->initial_request &&
2168 http_follow_config == HTTP_FOLLOW_INITIAL)
2169 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
2171 headers = curl_slist_append(headers, buf.buf);
2173 /* Add additional headers here */
2174 if (options && options->extra_headers) {
2175 const struct string_list_item *item;
2176 if (options && options->extra_headers) {
2177 for_each_string_list_item(item, options->extra_headers) {
2178 headers = curl_slist_append(headers, item->string);
2183 headers = http_append_auth_header(&http_auth, headers);
2185 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
2186 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
2187 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
2188 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
2190 ret = run_one_slot(slot, &results);
2192 if (options && options->content_type) {
2193 struct strbuf raw = STRBUF_INIT;
2194 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
2195 extract_content_type(&raw, options->content_type,
2196 options->charset);
2197 strbuf_release(&raw);
2200 if (options && options->effective_url)
2201 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
2202 options->effective_url);
2204 curl_slist_free_all(headers);
2205 strbuf_release(&buf);
2207 return ret;
2211 * Update the "base" url to a more appropriate value, as deduced by
2212 * redirects seen when requesting a URL starting with "url".
2214 * The "asked" parameter is a URL that we asked curl to access, and must begin
2215 * with "base".
2217 * The "got" parameter is the URL that curl reported to us as where we ended
2218 * up.
2220 * Returns 1 if we updated the base url, 0 otherwise.
2222 * Our basic strategy is to compare "base" and "asked" to find the bits
2223 * specific to our request. We then strip those bits off of "got" to yield the
2224 * new base. So for example, if our base is "http://example.com/foo.git",
2225 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2226 * with "https://other.example.com/foo.git/info/refs". We would want the
2227 * new URL to become "https://other.example.com/foo.git".
2229 * Note that this assumes a sane redirect scheme. It's entirely possible
2230 * in the example above to end up at a URL that does not even end in
2231 * "info/refs". In such a case we die. There's not much we can do, such a
2232 * scheme is unlikely to represent a real git repository, and failing to
2233 * rewrite the base opens options for malicious redirects to do funny things.
2235 static int update_url_from_redirect(struct strbuf *base,
2236 const char *asked,
2237 const struct strbuf *got)
2239 const char *tail;
2240 size_t new_len;
2242 if (!strcmp(asked, got->buf))
2243 return 0;
2245 if (!skip_prefix(asked, base->buf, &tail))
2246 BUG("update_url_from_redirect: %s is not a superset of %s",
2247 asked, base->buf);
2249 new_len = got->len;
2250 if (!strip_suffix_mem(got->buf, &new_len, tail))
2251 die(_("unable to update url base from redirection:\n"
2252 " asked for: %s\n"
2253 " redirect: %s"),
2254 asked, got->buf);
2256 strbuf_reset(base);
2257 strbuf_add(base, got->buf, new_len);
2259 return 1;
2262 static int http_request_reauth(const char *url,
2263 void *result, int target,
2264 struct http_get_options *options)
2266 int i = 3;
2267 int ret;
2269 if (always_auth_proactively())
2270 credential_fill(&http_auth, 1);
2272 ret = http_request(url, result, target, options);
2274 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2275 return ret;
2277 if (options && options->effective_url && options->base_url) {
2278 if (update_url_from_redirect(options->base_url,
2279 url, options->effective_url)) {
2280 credential_from_url(&http_auth, options->base_url->buf);
2281 url = options->effective_url->buf;
2285 while (ret == HTTP_REAUTH && --i) {
2287 * The previous request may have put cruft into our output stream; we
2288 * should clear it out before making our next request.
2290 switch (target) {
2291 case HTTP_REQUEST_STRBUF:
2292 strbuf_reset(result);
2293 break;
2294 case HTTP_REQUEST_FILE: {
2295 FILE *f = result;
2296 if (fflush(f)) {
2297 error_errno("unable to flush a file");
2298 return HTTP_START_FAILED;
2300 rewind(f);
2301 if (ftruncate(fileno(f), 0) < 0) {
2302 error_errno("unable to truncate a file");
2303 return HTTP_START_FAILED;
2305 break;
2307 default:
2308 BUG("Unknown http_request target");
2311 credential_fill(&http_auth, 1);
2313 ret = http_request(url, result, target, options);
2315 return ret;
2318 int http_get_strbuf(const char *url,
2319 struct strbuf *result,
2320 struct http_get_options *options)
2322 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2326 * Downloads a URL and stores the result in the given file.
2328 * If a previous interrupted download is detected (i.e. a previous temporary
2329 * file is still around) the download is resumed.
2331 int http_get_file(const char *url, const char *filename,
2332 struct http_get_options *options)
2334 int ret;
2335 struct strbuf tmpfile = STRBUF_INIT;
2336 FILE *result;
2338 strbuf_addf(&tmpfile, "%s.temp", filename);
2339 result = fopen(tmpfile.buf, "a");
2340 if (!result) {
2341 error("Unable to open local file %s", tmpfile.buf);
2342 ret = HTTP_ERROR;
2343 goto cleanup;
2346 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2347 fclose(result);
2349 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2350 ret = HTTP_ERROR;
2351 cleanup:
2352 strbuf_release(&tmpfile);
2353 return ret;
2356 int http_fetch_ref(const char *base, struct ref *ref)
2358 struct http_get_options options = {0};
2359 char *url;
2360 struct strbuf buffer = STRBUF_INIT;
2361 int ret = -1;
2363 options.no_cache = 1;
2365 url = quote_ref_url(base, ref->name);
2366 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2367 strbuf_rtrim(&buffer);
2368 if (buffer.len == the_hash_algo->hexsz)
2369 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2370 else if (starts_with(buffer.buf, "ref: ")) {
2371 ref->symref = xstrdup(buffer.buf + 5);
2372 ret = 0;
2376 strbuf_release(&buffer);
2377 free(url);
2378 return ret;
2381 /* Helpers for fetching packs */
2382 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2384 char *url, *tmp;
2385 struct strbuf buf = STRBUF_INIT;
2387 if (http_is_verbose)
2388 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2390 end_url_with_slash(&buf, base_url);
2391 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2392 url = strbuf_detach(&buf, NULL);
2395 * Don't put this into packs/, since it's just temporary and we don't
2396 * want to confuse it with our local .idx files. We'll generate our
2397 * own index if we choose to download the matching packfile.
2399 * It's tempting to use xmks_tempfile() here, but it's important that
2400 * the file not exist, otherwise http_get_file() complains. So we
2401 * create a filename that should be unique, and then just register it
2402 * as a tempfile so that it will get cleaned up on exit.
2404 * In theory we could hold on to the tempfile and delete these as soon
2405 * as we download the matching pack, but it would take a bit of
2406 * refactoring. Leaving them until the process ends is probably OK.
2408 tmp = xstrfmt("%s/tmp_pack_%s.idx",
2409 repo_get_object_directory(the_repository),
2410 hash_to_hex(hash));
2411 register_tempfile(tmp);
2413 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2414 error("Unable to get pack index %s", url);
2415 FREE_AND_NULL(tmp);
2418 free(url);
2419 return tmp;
2422 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2423 unsigned char *sha1, const char *base_url)
2425 struct packed_git *new_pack, *p;
2426 char *tmp_idx = NULL;
2427 int ret;
2430 * If we already have the pack locally, no need to fetch its index or
2431 * even add it to list; we already have all of its objects.
2433 for (p = get_all_packs(the_repository); p; p = p->next) {
2434 if (hasheq(p->hash, sha1, the_repository->hash_algo))
2435 return 0;
2438 tmp_idx = fetch_pack_index(sha1, base_url);
2439 if (!tmp_idx)
2440 return -1;
2442 new_pack = parse_pack_index(sha1, tmp_idx);
2443 if (!new_pack) {
2444 unlink(tmp_idx);
2445 free(tmp_idx);
2447 return -1; /* parse_pack_index() already issued error message */
2450 ret = verify_pack_index(new_pack);
2451 if (!ret)
2452 close_pack_index(new_pack);
2453 free(tmp_idx);
2454 if (ret)
2455 return -1;
2457 new_pack->next = *packs_head;
2458 *packs_head = new_pack;
2459 return 0;
2462 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2464 struct http_get_options options = {0};
2465 int ret = 0;
2466 char *url;
2467 const char *data;
2468 struct strbuf buf = STRBUF_INIT;
2469 struct object_id oid;
2471 end_url_with_slash(&buf, base_url);
2472 strbuf_addstr(&buf, "objects/info/packs");
2473 url = strbuf_detach(&buf, NULL);
2475 options.no_cache = 1;
2476 ret = http_get_strbuf(url, &buf, &options);
2477 if (ret != HTTP_OK)
2478 goto cleanup;
2480 data = buf.buf;
2481 while (*data) {
2482 if (skip_prefix(data, "P pack-", &data) &&
2483 !parse_oid_hex(data, &oid, &data) &&
2484 skip_prefix(data, ".pack", &data) &&
2485 (*data == '\n' || *data == '\0')) {
2486 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2487 } else {
2488 data = strchrnul(data, '\n');
2490 if (*data)
2491 data++; /* skip past newline */
2494 cleanup:
2495 free(url);
2496 strbuf_release(&buf);
2497 return ret;
2500 void release_http_pack_request(struct http_pack_request *preq)
2502 if (preq->packfile) {
2503 fclose(preq->packfile);
2504 preq->packfile = NULL;
2506 preq->slot = NULL;
2507 strbuf_release(&preq->tmpfile);
2508 curl_slist_free_all(preq->headers);
2509 free(preq->url);
2510 free(preq);
2513 static const char *default_index_pack_args[] =
2514 {"index-pack", "--stdin", NULL};
2516 int finish_http_pack_request(struct http_pack_request *preq)
2518 struct child_process ip = CHILD_PROCESS_INIT;
2519 int tmpfile_fd;
2520 int ret = 0;
2522 fclose(preq->packfile);
2523 preq->packfile = NULL;
2525 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2527 ip.git_cmd = 1;
2528 ip.in = tmpfile_fd;
2529 strvec_pushv(&ip.args, preq->index_pack_args ?
2530 preq->index_pack_args :
2531 default_index_pack_args);
2533 if (preq->preserve_index_pack_stdout)
2534 ip.out = 0;
2535 else
2536 ip.no_stdout = 1;
2538 if (run_command(&ip)) {
2539 ret = -1;
2540 goto cleanup;
2543 cleanup:
2544 close(tmpfile_fd);
2545 unlink(preq->tmpfile.buf);
2546 return ret;
2549 void http_install_packfile(struct packed_git *p,
2550 struct packed_git **list_to_remove_from)
2552 struct packed_git **lst = list_to_remove_from;
2554 while (*lst != p)
2555 lst = &((*lst)->next);
2556 *lst = (*lst)->next;
2558 install_packed_git(the_repository, p);
2561 struct http_pack_request *new_http_pack_request(
2562 const unsigned char *packed_git_hash, const char *base_url) {
2564 struct strbuf buf = STRBUF_INIT;
2566 end_url_with_slash(&buf, base_url);
2567 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2568 hash_to_hex(packed_git_hash));
2569 return new_direct_http_pack_request(packed_git_hash,
2570 strbuf_detach(&buf, NULL));
2573 struct http_pack_request *new_direct_http_pack_request(
2574 const unsigned char *packed_git_hash, char *url)
2576 off_t prev_posn = 0;
2577 struct http_pack_request *preq;
2579 CALLOC_ARRAY(preq, 1);
2580 strbuf_init(&preq->tmpfile, 0);
2582 preq->url = url;
2584 odb_pack_name(&preq->tmpfile, packed_git_hash, "pack");
2585 strbuf_addstr(&preq->tmpfile, ".temp");
2586 preq->packfile = fopen(preq->tmpfile.buf, "a");
2587 if (!preq->packfile) {
2588 error("Unable to open local file %s for pack",
2589 preq->tmpfile.buf);
2590 goto abort;
2593 preq->slot = get_active_slot();
2594 preq->headers = object_request_headers();
2595 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2596 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2597 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2598 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER, preq->headers);
2601 * If there is data present from a previous transfer attempt,
2602 * resume where it left off
2604 prev_posn = ftello(preq->packfile);
2605 if (prev_posn>0) {
2606 if (http_is_verbose)
2607 fprintf(stderr,
2608 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2609 hash_to_hex(packed_git_hash),
2610 (uintmax_t)prev_posn);
2611 http_opt_request_remainder(preq->slot->curl, prev_posn);
2614 return preq;
2616 abort:
2617 strbuf_release(&preq->tmpfile);
2618 free(preq->url);
2619 free(preq);
2620 return NULL;
2623 /* Helpers for fetching objects (loose) */
2624 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2625 void *data)
2627 unsigned char expn[4096];
2628 size_t size = eltsize * nmemb;
2629 int posn = 0;
2630 struct http_object_request *freq = data;
2631 struct active_request_slot *slot = freq->slot;
2633 if (slot) {
2634 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2635 &slot->http_code);
2636 if (c != CURLE_OK)
2637 BUG("curl_easy_getinfo for HTTP code failed: %s",
2638 curl_easy_strerror(c));
2639 if (slot->http_code >= 300)
2640 return nmemb;
2643 do {
2644 ssize_t retval = xwrite(freq->localfile,
2645 (char *) ptr + posn, size - posn);
2646 if (retval < 0)
2647 return posn / eltsize;
2648 posn += retval;
2649 } while (posn < size);
2651 freq->stream.avail_in = size;
2652 freq->stream.next_in = (void *)ptr;
2653 do {
2654 freq->stream.next_out = expn;
2655 freq->stream.avail_out = sizeof(expn);
2656 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2657 the_hash_algo->update_fn(&freq->c, expn,
2658 sizeof(expn) - freq->stream.avail_out);
2659 } while (freq->stream.avail_in && freq->zret == Z_OK);
2660 return nmemb;
2663 struct http_object_request *new_http_object_request(const char *base_url,
2664 const struct object_id *oid)
2666 char *hex = oid_to_hex(oid);
2667 struct strbuf filename = STRBUF_INIT;
2668 struct strbuf prevfile = STRBUF_INIT;
2669 int prevlocal;
2670 char prev_buf[PREV_BUF_SIZE];
2671 ssize_t prev_read = 0;
2672 off_t prev_posn = 0;
2673 struct http_object_request *freq;
2675 CALLOC_ARRAY(freq, 1);
2676 strbuf_init(&freq->tmpfile, 0);
2677 oidcpy(&freq->oid, oid);
2678 freq->localfile = -1;
2680 loose_object_path(the_repository, &filename, oid);
2681 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2683 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2684 unlink_or_warn(prevfile.buf);
2685 rename(freq->tmpfile.buf, prevfile.buf);
2686 unlink_or_warn(freq->tmpfile.buf);
2687 strbuf_release(&filename);
2689 if (freq->localfile != -1)
2690 error("fd leakage in start: %d", freq->localfile);
2691 freq->localfile = open(freq->tmpfile.buf,
2692 O_WRONLY | O_CREAT | O_EXCL, 0666);
2694 * This could have failed due to the "lazy directory creation";
2695 * try to mkdir the last path component.
2697 if (freq->localfile < 0 && errno == ENOENT) {
2698 char *dir = strrchr(freq->tmpfile.buf, '/');
2699 if (dir) {
2700 *dir = 0;
2701 mkdir(freq->tmpfile.buf, 0777);
2702 *dir = '/';
2704 freq->localfile = open(freq->tmpfile.buf,
2705 O_WRONLY | O_CREAT | O_EXCL, 0666);
2708 if (freq->localfile < 0) {
2709 error_errno("Couldn't create temporary file %s",
2710 freq->tmpfile.buf);
2711 goto abort;
2714 git_inflate_init(&freq->stream);
2716 the_hash_algo->init_fn(&freq->c);
2718 freq->url = get_remote_object_url(base_url, hex, 0);
2721 * If a previous temp file is present, process what was already
2722 * fetched.
2724 prevlocal = open(prevfile.buf, O_RDONLY);
2725 if (prevlocal != -1) {
2726 do {
2727 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2728 if (prev_read>0) {
2729 if (fwrite_sha1_file(prev_buf,
2731 prev_read,
2732 freq) == prev_read) {
2733 prev_posn += prev_read;
2734 } else {
2735 prev_read = -1;
2738 } while (prev_read > 0);
2739 close(prevlocal);
2741 unlink_or_warn(prevfile.buf);
2742 strbuf_release(&prevfile);
2745 * Reset inflate/SHA1 if there was an error reading the previous temp
2746 * file; also rewind to the beginning of the local file.
2748 if (prev_read == -1) {
2749 git_inflate_end(&freq->stream);
2750 memset(&freq->stream, 0, sizeof(freq->stream));
2751 git_inflate_init(&freq->stream);
2752 the_hash_algo->init_fn(&freq->c);
2753 if (prev_posn>0) {
2754 prev_posn = 0;
2755 lseek(freq->localfile, 0, SEEK_SET);
2756 if (ftruncate(freq->localfile, 0) < 0) {
2757 error_errno("Couldn't truncate temporary file %s",
2758 freq->tmpfile.buf);
2759 goto abort;
2764 freq->slot = get_active_slot();
2765 freq->headers = object_request_headers();
2767 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2768 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2769 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2770 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2771 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2772 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, freq->headers);
2775 * If we have successfully processed data from a previous fetch
2776 * attempt, only fetch the data we don't already have.
2778 if (prev_posn>0) {
2779 if (http_is_verbose)
2780 fprintf(stderr,
2781 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2782 hex, (uintmax_t)prev_posn);
2783 http_opt_request_remainder(freq->slot->curl, prev_posn);
2786 return freq;
2788 abort:
2789 strbuf_release(&prevfile);
2790 free(freq->url);
2791 free(freq);
2792 return NULL;
2795 void process_http_object_request(struct http_object_request *freq)
2797 if (!freq->slot)
2798 return;
2799 freq->curl_result = freq->slot->curl_result;
2800 freq->http_code = freq->slot->http_code;
2801 freq->slot = NULL;
2804 int finish_http_object_request(struct http_object_request *freq)
2806 struct stat st;
2807 struct strbuf filename = STRBUF_INIT;
2809 close(freq->localfile);
2810 freq->localfile = -1;
2812 process_http_object_request(freq);
2814 if (freq->http_code == 416) {
2815 warning("requested range invalid; we may already have all the data.");
2816 } else if (freq->curl_result != CURLE_OK) {
2817 if (stat(freq->tmpfile.buf, &st) == 0)
2818 if (st.st_size == 0)
2819 unlink_or_warn(freq->tmpfile.buf);
2820 return -1;
2823 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2824 if (freq->zret != Z_STREAM_END) {
2825 unlink_or_warn(freq->tmpfile.buf);
2826 return -1;
2828 if (!oideq(&freq->oid, &freq->real_oid)) {
2829 unlink_or_warn(freq->tmpfile.buf);
2830 return -1;
2832 loose_object_path(the_repository, &filename, &freq->oid);
2833 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2834 strbuf_release(&filename);
2836 return freq->rename;
2839 void abort_http_object_request(struct http_object_request **freq_p)
2841 struct http_object_request *freq = *freq_p;
2842 unlink_or_warn(freq->tmpfile.buf);
2844 release_http_object_request(freq_p);
2847 void release_http_object_request(struct http_object_request **freq_p)
2849 struct http_object_request *freq = *freq_p;
2850 if (freq->localfile != -1) {
2851 close(freq->localfile);
2852 freq->localfile = -1;
2854 FREE_AND_NULL(freq->url);
2855 if (freq->slot) {
2856 freq->slot->callback_func = NULL;
2857 freq->slot->callback_data = NULL;
2858 release_active_slot(freq->slot);
2859 freq->slot = NULL;
2861 curl_slist_free_all(freq->headers);
2862 strbuf_release(&freq->tmpfile);
2863 git_inflate_end(&freq->stream);
2865 free(freq);
2866 *freq_p = NULL;