1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "git-curl-compat.h"
9 #include "run-command.h"
12 #include "credential.h"
17 #include "transport.h"
19 #include "string-list.h"
20 #include "object-file.h"
21 #include "object-store-ll.h"
23 static struct trace_key trace_curl
= TRACE_KEY_INIT(CURL
);
24 static int trace_curl_data
= 1;
25 static int trace_curl_redact
= 1;
26 long int git_curl_ipresolve
= CURL_IPRESOLVE_WHATEVER
;
29 ssize_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
31 static int min_curl_sessions
= 1;
32 static int curl_session_count
;
33 static int max_requests
= -1;
35 static CURL
*curl_default
;
37 #define PREV_BUF_SIZE 4096
39 char curl_errorstr
[CURL_ERROR_SIZE
];
41 static int curl_ssl_verify
= -1;
42 static int curl_ssl_try
;
43 static char *curl_http_version
;
44 static char *ssl_cert
;
45 static char *ssl_cert_type
;
46 static char *ssl_cipherlist
;
47 static char *ssl_version
;
52 { "sslv2", CURL_SSLVERSION_SSLv2
},
53 { "sslv3", CURL_SSLVERSION_SSLv3
},
54 { "tlsv1", CURL_SSLVERSION_TLSv1
},
55 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
56 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
57 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
58 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
60 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
61 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3
},
65 static char *ssl_key_type
;
66 static char *ssl_capath
;
67 static char *curl_no_proxy
;
68 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
69 static char *ssl_pinnedkey
;
71 static char *ssl_cainfo
;
72 static long curl_low_speed_limit
= -1;
73 static long curl_low_speed_time
= -1;
74 static int curl_ftp_no_epsv
;
75 static char *curl_http_proxy
;
76 static char *http_proxy_authmethod
;
78 static char *http_proxy_ssl_cert
;
79 static char *http_proxy_ssl_key
;
80 static char *http_proxy_ssl_ca_info
;
81 static struct credential proxy_cert_auth
= CREDENTIAL_INIT
;
82 static int proxy_ssl_cert_password_required
;
87 } proxy_authmethods
[] = {
88 { "basic", CURLAUTH_BASIC
},
89 { "digest", CURLAUTH_DIGEST
},
90 { "negotiate", CURLAUTH_GSSNEGOTIATE
},
91 { "ntlm", CURLAUTH_NTLM
},
92 { "anyauth", CURLAUTH_ANY
},
94 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
95 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
99 #ifdef CURLGSSAPI_DELEGATION_FLAG
100 static char *curl_deleg
;
103 long curl_deleg_param
;
104 } curl_deleg_levels
[] = {
105 { "none", CURLGSSAPI_DELEGATION_NONE
},
106 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG
},
107 { "always", CURLGSSAPI_DELEGATION_FLAG
},
111 enum proactive_auth
{
112 PROACTIVE_AUTH_NONE
= 0,
113 PROACTIVE_AUTH_IF_CREDENTIALS
,
115 PROACTIVE_AUTH_BASIC
,
118 static struct credential proxy_auth
= CREDENTIAL_INIT
;
119 static const char *curl_proxyuserpwd
;
120 static char *curl_cookie_file
;
121 static int curl_save_cookies
;
122 struct credential http_auth
= CREDENTIAL_INIT
;
123 static enum proactive_auth http_proactive_auth
;
124 static char *user_agent
;
125 static int curl_empty_auth
= -1;
127 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
129 static struct credential cert_auth
= CREDENTIAL_INIT
;
130 static int ssl_cert_password_required
;
131 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
132 static int http_auth_methods_restricted
;
133 /* Modes for which empty_auth cannot actually help us. */
134 static unsigned long empty_auth_useless
=
139 static struct curl_slist
*pragma_header
;
140 static struct string_list extra_http_headers
= STRING_LIST_INIT_DUP
;
142 static struct curl_slist
*host_resolutions
;
144 static struct active_request_slot
*active_queue_head
;
146 static char *cached_accept_language
;
148 static char *http_ssl_backend
;
150 static int http_schannel_check_revoke
= 1;
152 * With the backend being set to `schannel`, setting sslCAinfo would override
153 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
156 static int http_schannel_use_ssl_cainfo
;
158 static int always_auth_proactively(void)
160 return http_proactive_auth
!= PROACTIVE_AUTH_NONE
&&
161 http_proactive_auth
!= PROACTIVE_AUTH_IF_CREDENTIALS
;
164 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
166 size_t size
= eltsize
* nmemb
;
167 struct buffer
*buffer
= buffer_
;
169 if (size
> buffer
->buf
.len
- buffer
->posn
)
170 size
= buffer
->buf
.len
- buffer
->posn
;
171 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
172 buffer
->posn
+= size
;
174 return size
/ eltsize
;
177 int seek_buffer(void *clientp
, curl_off_t offset
, int origin
)
179 struct buffer
*buffer
= clientp
;
181 if (origin
!= SEEK_SET
)
182 BUG("seek_buffer only handles SEEK_SET");
183 if (offset
< 0 || offset
>= buffer
->buf
.len
) {
184 error("curl seek would be outside of buffer");
185 return CURL_SEEKFUNC_FAIL
;
188 buffer
->posn
= offset
;
189 return CURL_SEEKFUNC_OK
;
192 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
194 size_t size
= eltsize
* nmemb
;
195 struct strbuf
*buffer
= buffer_
;
197 strbuf_add(buffer
, ptr
, size
);
202 * A folded header continuation line starts with any number of spaces or
203 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
204 * It is not a continuation line if the line starts with any other character.
206 static inline int is_hdr_continuation(const char *ptr
, const size_t size
)
208 return size
&& (*ptr
== ' ' || *ptr
== '\t');
211 static size_t fwrite_wwwauth(char *ptr
, size_t eltsize
, size_t nmemb
, void *p UNUSED
)
213 size_t size
= eltsize
* nmemb
;
214 struct strvec
*values
= &http_auth
.wwwauth_headers
;
215 struct strbuf buf
= STRBUF_INIT
;
220 * Header lines may not come NULL-terminated from libcurl so we must
221 * limit all scans to the maximum length of the header line, or leverage
222 * strbufs for all operations.
224 * In addition, it is possible that header values can be split over
225 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
226 * but older servers may still emit them. A continuation header field
227 * value is identified as starting with a space or horizontal tab.
229 * The formal definition of a header field as given in RFC 7230 is:
231 * header-field = field-name ":" OWS field-value OWS
234 * field-value = *( field-content / obs-fold )
235 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
236 * field-vchar = VCHAR / obs-text
238 * obs-fold = CRLF 1*( SP / HTAB )
239 * ; obsolete line folding
240 * ; see Section 3.2.4
243 /* Start of a new WWW-Authenticate header */
244 if (skip_iprefix_mem(ptr
, size
, "www-authenticate:", &val
, &val_len
)) {
245 strbuf_add(&buf
, val
, val_len
);
248 * Strip the CRLF that should be present at the end of each
249 * field as well as any trailing or leading whitespace from the
254 strvec_push(values
, buf
.buf
);
255 http_auth
.header_is_last_match
= 1;
260 * This line could be a continuation of the previously matched header
261 * field. If this is the case then we should append this value to the
262 * end of the previously consumed value.
264 if (http_auth
.header_is_last_match
&& is_hdr_continuation(ptr
, size
)) {
266 * Trim the CRLF and any leading or trailing from this line.
268 strbuf_add(&buf
, ptr
, size
);
272 * At this point we should always have at least one existing
273 * value, even if it is empty. Do not bother appending the new
274 * value if this continuation header is itself empty.
277 BUG("should have at least one existing header value");
278 } else if (buf
.len
) {
279 char *prev
= xstrdup(values
->v
[values
->nr
- 1]);
281 /* Join two non-empty values with a single space. */
282 const char *const sp
= *prev
? " " : "";
285 strvec_pushf(values
, "%s%s%s", prev
, sp
, buf
.buf
);
292 /* Not a continuation of a previously matched auth header line. */
293 http_auth
.header_is_last_match
= 0;
296 * If this is a HTTP status line and not a header field, this signals
297 * a different HTTP response. libcurl writes all the output of all
298 * response headers of all responses, including redirects.
299 * We only care about the last HTTP request response's headers so clear
300 * the existing array.
302 if (skip_iprefix_mem(ptr
, size
, "http/", &val
, &val_len
))
303 strvec_clear(values
);
306 strbuf_release(&buf
);
310 size_t fwrite_null(char *ptr UNUSED
, size_t eltsize UNUSED
, size_t nmemb
,
316 static struct curl_slist
*object_request_headers(void)
318 return curl_slist_append(http_copy_default_headers(), "Pragma:");
321 static void closedown_active_slot(struct active_request_slot
*slot
)
327 static void finish_active_slot(struct active_request_slot
*slot
)
329 closedown_active_slot(slot
);
330 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
333 (*slot
->finished
) = 1;
335 /* Store slot results so they can be read after the slot is reused */
337 slot
->results
->curl_result
= slot
->curl_result
;
338 slot
->results
->http_code
= slot
->http_code
;
339 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
340 &slot
->results
->auth_avail
);
342 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
343 &slot
->results
->http_connectcode
);
346 /* Run callback if appropriate */
347 if (slot
->callback_func
)
348 slot
->callback_func(slot
->callback_data
);
351 static void xmulti_remove_handle(struct active_request_slot
*slot
)
353 curl_multi_remove_handle(curlm
, slot
->curl
);
356 static void process_curl_messages(void)
359 struct active_request_slot
*slot
;
360 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
362 while (curl_message
!= NULL
) {
363 if (curl_message
->msg
== CURLMSG_DONE
) {
364 int curl_result
= curl_message
->data
.result
;
365 slot
= active_queue_head
;
366 while (slot
!= NULL
&&
367 slot
->curl
!= curl_message
->easy_handle
)
370 xmulti_remove_handle(slot
);
371 slot
->curl_result
= curl_result
;
372 finish_active_slot(slot
);
374 fprintf(stderr
, "Received DONE message for unknown request!\n");
377 fprintf(stderr
, "Unknown CURL message received: %d\n",
378 (int)curl_message
->msg
);
380 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
384 static int http_options(const char *var
, const char *value
,
385 const struct config_context
*ctx
, void *data
)
387 if (!strcmp("http.version", var
)) {
388 return git_config_string(&curl_http_version
, var
, value
);
390 if (!strcmp("http.sslverify", var
)) {
391 curl_ssl_verify
= git_config_bool(var
, value
);
394 if (!strcmp("http.sslcipherlist", var
))
395 return git_config_string(&ssl_cipherlist
, var
, value
);
396 if (!strcmp("http.sslversion", var
))
397 return git_config_string(&ssl_version
, var
, value
);
398 if (!strcmp("http.sslcert", var
))
399 return git_config_pathname(&ssl_cert
, var
, value
);
400 if (!strcmp("http.sslcerttype", var
))
401 return git_config_string(&ssl_cert_type
, var
, value
);
402 if (!strcmp("http.sslkey", var
))
403 return git_config_pathname(&ssl_key
, var
, value
);
404 if (!strcmp("http.sslkeytype", var
))
405 return git_config_string(&ssl_key_type
, var
, value
);
406 if (!strcmp("http.sslcapath", var
))
407 return git_config_pathname(&ssl_capath
, var
, value
);
408 if (!strcmp("http.sslcainfo", var
))
409 return git_config_pathname(&ssl_cainfo
, var
, value
);
410 if (!strcmp("http.sslcertpasswordprotected", var
)) {
411 ssl_cert_password_required
= git_config_bool(var
, value
);
414 if (!strcmp("http.ssltry", var
)) {
415 curl_ssl_try
= git_config_bool(var
, value
);
418 if (!strcmp("http.sslbackend", var
)) {
419 free(http_ssl_backend
);
420 http_ssl_backend
= xstrdup_or_null(value
);
424 if (!strcmp("http.schannelcheckrevoke", var
)) {
425 http_schannel_check_revoke
= git_config_bool(var
, value
);
429 if (!strcmp("http.schannelusesslcainfo", var
)) {
430 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
434 if (!strcmp("http.minsessions", var
)) {
435 min_curl_sessions
= git_config_int(var
, value
, ctx
->kvi
);
436 if (min_curl_sessions
> 1)
437 min_curl_sessions
= 1;
440 if (!strcmp("http.maxrequests", var
)) {
441 max_requests
= git_config_int(var
, value
, ctx
->kvi
);
444 if (!strcmp("http.lowspeedlimit", var
)) {
445 curl_low_speed_limit
= (long)git_config_int(var
, value
, ctx
->kvi
);
448 if (!strcmp("http.lowspeedtime", var
)) {
449 curl_low_speed_time
= (long)git_config_int(var
, value
, ctx
->kvi
);
453 if (!strcmp("http.noepsv", var
)) {
454 curl_ftp_no_epsv
= git_config_bool(var
, value
);
457 if (!strcmp("http.proxy", var
))
458 return git_config_string(&curl_http_proxy
, var
, value
);
460 if (!strcmp("http.proxyauthmethod", var
))
461 return git_config_string(&http_proxy_authmethod
, var
, value
);
463 if (!strcmp("http.proxysslcert", var
))
464 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
466 if (!strcmp("http.proxysslkey", var
))
467 return git_config_string(&http_proxy_ssl_key
, var
, value
);
469 if (!strcmp("http.proxysslcainfo", var
))
470 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
472 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
473 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
477 if (!strcmp("http.cookiefile", var
))
478 return git_config_pathname(&curl_cookie_file
, var
, value
);
479 if (!strcmp("http.savecookies", var
)) {
480 curl_save_cookies
= git_config_bool(var
, value
);
484 if (!strcmp("http.postbuffer", var
)) {
485 http_post_buffer
= git_config_ssize_t(var
, value
, ctx
->kvi
);
486 if (http_post_buffer
< 0)
487 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
488 if (http_post_buffer
< LARGE_PACKET_MAX
)
489 http_post_buffer
= LARGE_PACKET_MAX
;
493 if (!strcmp("http.useragent", var
))
494 return git_config_string(&user_agent
, var
, value
);
496 if (!strcmp("http.emptyauth", var
)) {
497 if (value
&& !strcmp("auto", value
))
498 curl_empty_auth
= -1;
500 curl_empty_auth
= git_config_bool(var
, value
);
504 if (!strcmp("http.delegation", var
)) {
505 #ifdef CURLGSSAPI_DELEGATION_FLAG
506 return git_config_string(&curl_deleg
, var
, value
);
508 warning(_("Delegation control is not supported with cURL < 7.22.0"));
513 if (!strcmp("http.pinnedpubkey", var
)) {
514 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
515 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
517 warning(_("Public key pinning not supported with cURL < 7.39.0"));
522 if (!strcmp("http.extraheader", var
)) {
524 return config_error_nonbool(var
);
525 } else if (!*value
) {
526 string_list_clear(&extra_http_headers
, 0);
528 string_list_append(&extra_http_headers
, value
);
533 if (!strcmp("http.curloptresolve", var
)) {
535 return config_error_nonbool(var
);
536 } else if (!*value
) {
537 curl_slist_free_all(host_resolutions
);
538 host_resolutions
= NULL
;
540 host_resolutions
= curl_slist_append(host_resolutions
, value
);
545 if (!strcmp("http.followredirects", var
)) {
546 if (value
&& !strcmp(value
, "initial"))
547 http_follow_config
= HTTP_FOLLOW_INITIAL
;
548 else if (git_config_bool(var
, value
))
549 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
551 http_follow_config
= HTTP_FOLLOW_NONE
;
555 if (!strcmp("http.proactiveauth", var
)) {
557 return config_error_nonbool(var
);
558 if (!strcmp(value
, "auto"))
559 http_proactive_auth
= PROACTIVE_AUTH_AUTO
;
560 else if (!strcmp(value
, "basic"))
561 http_proactive_auth
= PROACTIVE_AUTH_BASIC
;
562 else if (!strcmp(value
, "none"))
563 http_proactive_auth
= PROACTIVE_AUTH_NONE
;
565 warning(_("Unknown value for http.proactiveauth"));
569 /* Fall back on the default ones */
570 return git_default_config(var
, value
, ctx
, data
);
573 static int curl_empty_auth_enabled(void)
575 if (curl_empty_auth
>= 0)
576 return curl_empty_auth
;
579 * In the automatic case, kick in the empty-auth
580 * hack as long as we would potentially try some
581 * method more exotic than "Basic" or "Digest".
583 * But only do this when this is our second or
584 * subsequent request, as by then we know what
585 * methods are available.
587 if (http_auth_methods_restricted
&&
588 (http_auth_methods
& ~empty_auth_useless
))
593 struct curl_slist
*http_append_auth_header(const struct credential
*c
,
594 struct curl_slist
*headers
)
596 if (c
->authtype
&& c
->credential
) {
597 struct strbuf auth
= STRBUF_INIT
;
598 strbuf_addf(&auth
, "Authorization: %s %s",
599 c
->authtype
, c
->credential
);
600 headers
= curl_slist_append(headers
, auth
.buf
);
601 strbuf_release(&auth
);
606 static void init_curl_http_auth(CURL
*result
)
608 if ((!http_auth
.username
|| !*http_auth
.username
) &&
609 (!http_auth
.credential
|| !*http_auth
.credential
)) {
610 int empty_auth
= curl_empty_auth_enabled();
611 if ((empty_auth
!= -1 && !always_auth_proactively()) || empty_auth
== 1) {
612 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
614 } else if (!always_auth_proactively()) {
616 } else if (http_proactive_auth
== PROACTIVE_AUTH_BASIC
) {
617 strvec_push(&http_auth
.wwwauth_headers
, "Basic");
621 credential_fill(&http_auth
, 1);
623 if (http_auth
.password
) {
624 if (always_auth_proactively()) {
626 * We got a credential without an authtype and we don't
627 * know what's available. Since our only two options at
628 * the moment are auto (which defaults to basic) and
629 * basic, use basic for now.
631 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_BASIC
);
633 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
634 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
638 /* *var must be free-able */
639 static void var_override(char **var
, char *value
)
643 *var
= xstrdup(value
);
647 static void set_proxyauth_name_password(CURL
*result
)
649 if (proxy_auth
.password
) {
650 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
651 proxy_auth
.username
);
652 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
653 proxy_auth
.password
);
654 } else if (proxy_auth
.authtype
&& proxy_auth
.credential
) {
655 curl_easy_setopt(result
, CURLOPT_PROXYHEADER
,
656 http_append_auth_header(&proxy_auth
, NULL
));
660 static void init_curl_proxy_auth(CURL
*result
)
662 if (proxy_auth
.username
) {
663 if (!proxy_auth
.password
&& !proxy_auth
.credential
)
664 credential_fill(&proxy_auth
, 1);
665 set_proxyauth_name_password(result
);
668 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
670 if (http_proxy_authmethod
) {
672 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
673 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
674 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
675 proxy_authmethods
[i
].curlauth_param
);
679 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
680 warning("unsupported proxy authentication method %s: using anyauth",
681 http_proxy_authmethod
);
682 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
686 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
689 static int has_cert_password(void)
691 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
693 if (!cert_auth
.password
) {
694 cert_auth
.protocol
= xstrdup("cert");
695 cert_auth
.host
= xstrdup("");
696 cert_auth
.username
= xstrdup("");
697 cert_auth
.path
= xstrdup(ssl_cert
);
698 credential_fill(&cert_auth
, 0);
703 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
704 static int has_proxy_cert_password(void)
706 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
708 if (!proxy_cert_auth
.password
) {
709 proxy_cert_auth
.protocol
= xstrdup("cert");
710 proxy_cert_auth
.host
= xstrdup("");
711 proxy_cert_auth
.username
= xstrdup("");
712 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
713 credential_fill(&proxy_cert_auth
, 0);
719 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
720 static void set_curl_keepalive(CURL
*c
)
722 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
726 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
730 socklen_t len
= (socklen_t
)sizeof(ka
);
732 if (type
!= CURLSOCKTYPE_IPCXN
)
735 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
737 warning_errno("unable to set SO_KEEPALIVE on socket");
739 return CURL_SOCKOPT_OK
;
742 static void set_curl_keepalive(CURL
*c
)
744 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
748 /* Return 1 if redactions have been made, 0 otherwise. */
749 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
752 const char *sensitive_header
;
754 if (trace_curl_redact
&&
755 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
756 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
757 /* The first token is the type, which is OK to log */
758 while (isspace(*sensitive_header
))
760 while (*sensitive_header
&& !isspace(*sensitive_header
))
762 /* Everything else is opaque and possibly sensitive */
763 strbuf_setlen(header
, sensitive_header
- header
->buf
);
764 strbuf_addstr(header
, " <redacted>");
766 } else if (trace_curl_redact
&&
767 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
768 struct strbuf redacted_header
= STRBUF_INIT
;
771 while (isspace(*sensitive_header
))
774 cookie
= sensitive_header
;
778 char *semicolon
= strstr(cookie
, "; ");
781 equals
= strchrnul(cookie
, '=');
783 /* invalid cookie, just append and continue */
784 strbuf_addstr(&redacted_header
, cookie
);
787 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
788 strbuf_addstr(&redacted_header
, "=<redacted>");
791 * There are more cookies. (Or, for some
792 * reason, the input string ends in "; ".)
794 strbuf_addstr(&redacted_header
, "; ");
795 cookie
= semicolon
+ strlen("; ");
801 strbuf_setlen(header
, sensitive_header
- header
->buf
);
802 strbuf_addbuf(header
, &redacted_header
);
808 static int match_curl_h2_trace(const char *line
, const char **out
)
813 * curl prior to 8.1.0 gives us:
815 * h2h3 [<header-name>: <header-val>]
817 * Starting in 8.1.0, the first token became just "h2".
819 if (skip_iprefix(line
, "h2h3 [", out
) ||
820 skip_iprefix(line
, "h2 [", out
))
825 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
826 * where <stream-id> is numeric.
828 if (skip_iprefix(line
, "[HTTP/2] [", &p
)) {
831 if (skip_prefix(p
, "] [", out
))
838 /* Redact headers in info */
839 static void redact_sensitive_info_header(struct strbuf
*header
)
841 const char *sensitive_header
;
843 if (trace_curl_redact
&&
844 match_curl_h2_trace(header
->buf
, &sensitive_header
)) {
845 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
846 /* redaction ate our closing bracket */
847 strbuf_addch(header
, ']');
852 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
854 struct strbuf out
= STRBUF_INIT
;
855 struct strbuf
**headers
, **header
;
857 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
858 text
, (long)size
, (long)size
);
859 trace_strbuf(&trace_curl
, &out
);
861 strbuf_add(&out
, ptr
, size
);
862 headers
= strbuf_split_max(&out
, '\n', 0);
864 for (header
= headers
; *header
; header
++) {
865 if (hide_sensitive_header
)
866 redact_sensitive_header(*header
, 0);
867 strbuf_insertstr((*header
), 0, text
);
868 strbuf_insertstr((*header
), strlen(text
), ": ");
869 strbuf_rtrim((*header
));
870 strbuf_addch((*header
), '\n');
871 trace_strbuf(&trace_curl
, (*header
));
873 strbuf_list_free(headers
);
874 strbuf_release(&out
);
877 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
880 struct strbuf out
= STRBUF_INIT
;
881 unsigned int width
= 60;
883 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
884 text
, (long)size
, (long)size
);
885 trace_strbuf(&trace_curl
, &out
);
887 for (i
= 0; i
< size
; i
+= width
) {
891 strbuf_addf(&out
, "%s: ", text
);
892 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
893 unsigned char ch
= ptr
[i
+ w
];
896 (ch
>= 0x20) && (ch
< 0x80)
899 strbuf_addch(&out
, '\n');
900 trace_strbuf(&trace_curl
, &out
);
902 strbuf_release(&out
);
905 static void curl_dump_info(char *data
, size_t size
)
907 struct strbuf buf
= STRBUF_INIT
;
909 strbuf_add(&buf
, data
, size
);
911 redact_sensitive_info_header(&buf
);
912 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
914 strbuf_release(&buf
);
917 static int curl_trace(CURL
*handle UNUSED
, curl_infotype type
,
918 char *data
, size_t size
,
922 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
926 curl_dump_info(data
, size
);
928 case CURLINFO_HEADER_OUT
:
929 text
= "=> Send header";
930 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
932 case CURLINFO_DATA_OUT
:
933 if (trace_curl_data
) {
934 text
= "=> Send data";
935 curl_dump_data(text
, (unsigned char *)data
, size
);
938 case CURLINFO_SSL_DATA_OUT
:
939 if (trace_curl_data
) {
940 text
= "=> Send SSL data";
941 curl_dump_data(text
, (unsigned char *)data
, size
);
944 case CURLINFO_HEADER_IN
:
945 text
= "<= Recv header";
946 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
948 case CURLINFO_DATA_IN
:
949 if (trace_curl_data
) {
950 text
= "<= Recv data";
951 curl_dump_data(text
, (unsigned char *)data
, size
);
954 case CURLINFO_SSL_DATA_IN
:
955 if (trace_curl_data
) {
956 text
= "<= Recv SSL data";
957 curl_dump_data(text
, (unsigned char *)data
, size
);
961 default: /* we ignore unknown types by default */
967 void http_trace_curl_no_data(void)
969 trace_override_envvar(&trace_curl
, "1");
973 void setup_curl_trace(CURL
*handle
)
975 if (!trace_want(&trace_curl
))
977 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
978 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
979 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
982 static void proto_list_append(struct strbuf
*list
, const char *proto
)
987 strbuf_addch(list
, ',');
988 strbuf_addstr(list
, proto
);
991 static long get_curl_allowed_protocols(int from_user
, struct strbuf
*list
)
995 if (is_transport_allowed("http", from_user
)) {
996 bits
|= CURLPROTO_HTTP
;
997 proto_list_append(list
, "http");
999 if (is_transport_allowed("https", from_user
)) {
1000 bits
|= CURLPROTO_HTTPS
;
1001 proto_list_append(list
, "https");
1003 if (is_transport_allowed("ftp", from_user
)) {
1004 bits
|= CURLPROTO_FTP
;
1005 proto_list_append(list
, "ftp");
1007 if (is_transport_allowed("ftps", from_user
)) {
1008 bits
|= CURLPROTO_FTPS
;
1009 proto_list_append(list
, "ftps");
1015 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1016 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
1023 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
1024 { "HTTP/2", CURL_HTTP_VERSION_2
}
1027 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
1028 if (!strcmp(version_string
, choice
[i
].name
)) {
1029 *opt
= choice
[i
].opt_token
;
1034 warning("unknown value given to http.version: '%s'", version_string
);
1035 return -1; /* not found */
1040 static CURL
*get_curl_handle(void)
1042 CURL
*result
= curl_easy_init();
1045 die("curl_easy_init failed");
1047 if (!curl_ssl_verify
) {
1048 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
1049 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
1051 /* Verify authenticity of the peer's certificate */
1052 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
1053 /* The name in the cert must match whom we tried to connect */
1054 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
1057 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1058 if (curl_http_version
) {
1060 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
1061 /* Set request use http version */
1062 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
1067 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
1068 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
1070 #ifdef CURLGSSAPI_DELEGATION_FLAG
1073 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
1074 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
1075 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
1076 curl_deleg_levels
[i
].curl_deleg_param
);
1080 if (i
== ARRAY_SIZE(curl_deleg_levels
))
1081 warning("Unknown delegation method '%s': using default",
1086 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1087 !http_schannel_check_revoke
) {
1088 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1089 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
1091 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1095 if (http_proactive_auth
!= PROACTIVE_AUTH_NONE
)
1096 init_curl_http_auth(result
);
1098 if (getenv("GIT_SSL_VERSION"))
1099 ssl_version
= getenv("GIT_SSL_VERSION");
1100 if (ssl_version
&& *ssl_version
) {
1102 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
1103 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
1104 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
1105 sslversions
[i
].ssl_version
);
1109 if (i
== ARRAY_SIZE(sslversions
))
1110 warning("unsupported ssl version %s: using default",
1114 if (getenv("GIT_SSL_CIPHER_LIST"))
1115 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
1116 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
1117 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
1121 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
1123 curl_easy_setopt(result
, CURLOPT_SSLCERTTYPE
, ssl_cert_type
);
1124 if (has_cert_password())
1125 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
1127 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
1129 curl_easy_setopt(result
, CURLOPT_SSLKEYTYPE
, ssl_key_type
);
1131 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
1132 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1134 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
1136 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1137 !http_schannel_use_ssl_cainfo
) {
1138 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
1139 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1140 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
1142 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
1144 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
1145 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1146 if (http_proxy_ssl_ca_info
)
1147 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
1151 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
1152 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
1153 curl_low_speed_limit
);
1154 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
1155 curl_low_speed_time
);
1158 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
1159 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
1161 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1163 struct strbuf buf
= STRBUF_INIT
;
1165 get_curl_allowed_protocols(0, &buf
);
1166 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS_STR
, buf
.buf
);
1169 get_curl_allowed_protocols(-1, &buf
);
1170 curl_easy_setopt(result
, CURLOPT_PROTOCOLS_STR
, buf
.buf
);
1171 strbuf_release(&buf
);
1174 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
1175 get_curl_allowed_protocols(0, NULL
));
1176 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
1177 get_curl_allowed_protocols(-1, NULL
));
1180 if (getenv("GIT_CURL_VERBOSE"))
1181 http_trace_curl_no_data();
1182 setup_curl_trace(result
);
1183 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1184 trace_curl_data
= 0;
1185 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1186 trace_curl_redact
= 0;
1188 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
1189 user_agent
? user_agent
: git_user_agent());
1191 if (curl_ftp_no_epsv
)
1192 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
1195 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
1198 * CURL also examines these variables as a fallback; but we need to query
1199 * them here in order to decide whether to prompt for missing password (cf.
1200 * init_curl_proxy_auth()).
1202 * Unlike many other common environment variables, these are historically
1203 * lowercase only. It appears that CURL did not know this and implemented
1204 * only uppercase variants, which was later corrected to take both - with
1205 * the exception of http_proxy, which is lowercase only also in CURL. As
1206 * the lowercase versions are the historical quasi-standard, they take
1207 * precedence here, as in CURL.
1209 if (!curl_http_proxy
) {
1210 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
1211 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
1212 var_override(&curl_http_proxy
, getenv("https_proxy"));
1214 var_override(&curl_http_proxy
, getenv("http_proxy"));
1216 if (!curl_http_proxy
) {
1217 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
1218 var_override(&curl_http_proxy
, getenv("all_proxy"));
1222 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1224 * Handle case with the empty http.proxy value here to keep
1225 * common code clean.
1226 * NB: empty option disables proxying at all.
1228 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1229 } else if (curl_http_proxy
) {
1230 if (starts_with(curl_http_proxy
, "socks5h"))
1231 curl_easy_setopt(result
,
1232 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1233 else if (starts_with(curl_http_proxy
, "socks5"))
1234 curl_easy_setopt(result
,
1235 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1236 else if (starts_with(curl_http_proxy
, "socks4a"))
1237 curl_easy_setopt(result
,
1238 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1239 else if (starts_with(curl_http_proxy
, "socks"))
1240 curl_easy_setopt(result
,
1241 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1242 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1243 else if (starts_with(curl_http_proxy
, "https")) {
1244 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1246 if (http_proxy_ssl_cert
)
1247 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1249 if (http_proxy_ssl_key
)
1250 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1252 if (has_proxy_cert_password())
1253 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1256 if (strstr(curl_http_proxy
, "://"))
1257 credential_from_url(&proxy_auth
, curl_http_proxy
);
1259 struct strbuf url
= STRBUF_INIT
;
1260 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1261 credential_from_url(&proxy_auth
, url
.buf
);
1262 strbuf_release(&url
);
1265 if (!proxy_auth
.host
)
1266 die("Invalid proxy URL '%s'", curl_http_proxy
);
1268 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1269 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1270 var_override(&curl_no_proxy
, getenv("no_proxy"));
1271 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1273 init_curl_proxy_auth(result
);
1275 set_curl_keepalive(result
);
1280 static void set_from_env(char **var
, const char *envname
)
1282 const char *val
= getenv(envname
);
1284 FREE_AND_NULL(*var
);
1285 *var
= xstrdup(val
);
1289 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1291 char *low_speed_limit
;
1292 char *low_speed_time
;
1293 char *normalized_url
;
1294 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1296 config
.section
= "http";
1298 config
.collect_fn
= http_options
;
1299 config
.cascade_fn
= git_default_config
;
1302 http_is_verbose
= 0;
1303 normalized_url
= url_normalize(url
, &config
.url
);
1305 git_config(urlmatch_config_entry
, &config
);
1306 free(normalized_url
);
1307 string_list_clear(&config
.vars
, 1);
1309 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1310 if (http_ssl_backend
) {
1311 const curl_ssl_backend
**backends
;
1312 struct strbuf buf
= STRBUF_INIT
;
1315 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1316 case CURLSSLSET_UNKNOWN_BACKEND
:
1317 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1318 "Supported SSL backends:"),
1320 for (i
= 0; backends
[i
]; i
++)
1321 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1323 case CURLSSLSET_NO_BACKENDS
:
1324 die(_("Could not set SSL backend to '%s': "
1325 "cURL was built without SSL backends"),
1327 case CURLSSLSET_TOO_LATE
:
1328 die(_("Could not set SSL backend to '%s': already set"),
1336 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1337 die("curl_global_init failed");
1339 if (proactive_auth
&& http_proactive_auth
== PROACTIVE_AUTH_NONE
)
1340 http_proactive_auth
= PROACTIVE_AUTH_IF_CREDENTIALS
;
1342 if (remote
&& remote
->http_proxy
)
1343 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1346 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1348 pragma_header
= curl_slist_append(http_copy_default_headers(),
1349 "Pragma: no-cache");
1352 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1353 if (http_max_requests
)
1354 max_requests
= atoi(http_max_requests
);
1357 curlm
= curl_multi_init();
1359 die("curl_multi_init failed");
1361 if (getenv("GIT_SSL_NO_VERIFY"))
1362 curl_ssl_verify
= 0;
1364 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1365 set_from_env(&ssl_cert_type
, "GIT_SSL_CERT_TYPE");
1366 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1367 set_from_env(&ssl_key_type
, "GIT_SSL_KEY_TYPE");
1368 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1369 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1371 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1373 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1374 if (low_speed_limit
)
1375 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1376 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1378 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1380 if (curl_ssl_verify
== -1)
1381 curl_ssl_verify
= 1;
1383 curl_session_count
= 0;
1384 if (max_requests
< 1)
1385 max_requests
= DEFAULT_MAX_REQUESTS
;
1387 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1388 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1389 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1391 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1392 proxy_ssl_cert_password_required
= 1;
1394 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1395 curl_ftp_no_epsv
= 1;
1398 credential_from_url(&http_auth
, url
);
1399 if (!ssl_cert_password_required
&&
1400 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1401 starts_with(url
, "https://"))
1402 ssl_cert_password_required
= 1;
1405 curl_default
= get_curl_handle();
1408 void http_cleanup(void)
1410 struct active_request_slot
*slot
= active_queue_head
;
1412 while (slot
!= NULL
) {
1413 struct active_request_slot
*next
= slot
->next
;
1415 xmulti_remove_handle(slot
);
1416 curl_easy_cleanup(slot
->curl
);
1421 active_queue_head
= NULL
;
1423 curl_easy_cleanup(curl_default
);
1425 curl_multi_cleanup(curlm
);
1426 curl_global_cleanup();
1428 string_list_clear(&extra_http_headers
, 0);
1430 curl_slist_free_all(pragma_header
);
1431 pragma_header
= NULL
;
1433 curl_slist_free_all(host_resolutions
);
1434 host_resolutions
= NULL
;
1436 if (curl_http_proxy
) {
1437 free((void *)curl_http_proxy
);
1438 curl_http_proxy
= NULL
;
1441 if (proxy_auth
.password
) {
1442 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1443 FREE_AND_NULL(proxy_auth
.password
);
1446 free((void *)curl_proxyuserpwd
);
1447 curl_proxyuserpwd
= NULL
;
1449 free((void *)http_proxy_authmethod
);
1450 http_proxy_authmethod
= NULL
;
1452 if (cert_auth
.password
) {
1453 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1454 FREE_AND_NULL(cert_auth
.password
);
1456 ssl_cert_password_required
= 0;
1458 if (proxy_cert_auth
.password
) {
1459 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1460 FREE_AND_NULL(proxy_cert_auth
.password
);
1462 proxy_ssl_cert_password_required
= 0;
1464 FREE_AND_NULL(cached_accept_language
);
1467 struct active_request_slot
*get_active_slot(void)
1469 struct active_request_slot
*slot
= active_queue_head
;
1470 struct active_request_slot
*newslot
;
1474 /* Wait for a slot to open up if the queue is full */
1475 while (active_requests
>= max_requests
) {
1476 curl_multi_perform(curlm
, &num_transfers
);
1477 if (num_transfers
< active_requests
)
1478 process_curl_messages();
1481 while (slot
!= NULL
&& slot
->in_use
)
1485 newslot
= xmalloc(sizeof(*newslot
));
1486 newslot
->curl
= NULL
;
1487 newslot
->in_use
= 0;
1488 newslot
->next
= NULL
;
1490 slot
= active_queue_head
;
1492 active_queue_head
= newslot
;
1494 while (slot
->next
!= NULL
)
1496 slot
->next
= newslot
;
1502 slot
->curl
= curl_easy_duphandle(curl_default
);
1503 curl_session_count
++;
1508 slot
->results
= NULL
;
1509 slot
->finished
= NULL
;
1510 slot
->callback_data
= NULL
;
1511 slot
->callback_func
= NULL
;
1513 if (curl_cookie_file
&& !strcmp(curl_cookie_file
, "-")) {
1514 warning(_("refusing to read cookies from http.cookiefile '-'"));
1515 FREE_AND_NULL(curl_cookie_file
);
1517 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1518 if (curl_save_cookies
&& (!curl_cookie_file
|| !curl_cookie_file
[0])) {
1519 curl_save_cookies
= 0;
1520 warning(_("ignoring http.savecookies for empty http.cookiefile"));
1522 if (curl_save_cookies
)
1523 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1524 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1525 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1526 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1527 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1528 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1529 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1530 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1531 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDSIZE
, -1L);
1532 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1533 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1534 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1535 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1538 * Default following to off unless "ALWAYS" is configured; this gives
1539 * callers a sane starting point, and they can tweak for individual
1540 * HTTP_FOLLOW_* cases themselves.
1542 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1543 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1545 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1547 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1548 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1549 if (http_auth
.password
|| http_auth
.credential
|| curl_empty_auth_enabled())
1550 init_curl_http_auth(slot
->curl
);
1555 int start_active_slot(struct active_request_slot
*slot
)
1557 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1560 if (curlm_result
!= CURLM_OK
&&
1561 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1562 warning("curl_multi_add_handle failed: %s",
1563 curl_multi_strerror(curlm_result
));
1570 * We know there must be something to do, since we just added
1573 curl_multi_perform(curlm
, &num_transfers
);
1579 int (*fill
)(void *);
1580 struct fill_chain
*next
;
1583 static struct fill_chain
*fill_cfg
;
1585 void add_fill_function(void *data
, int (*fill
)(void *))
1587 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1588 struct fill_chain
**linkp
= &fill_cfg
;
1589 new_fill
->data
= data
;
1590 new_fill
->fill
= fill
;
1591 new_fill
->next
= NULL
;
1593 linkp
= &(*linkp
)->next
;
1597 void fill_active_slots(void)
1599 struct active_request_slot
*slot
= active_queue_head
;
1601 while (active_requests
< max_requests
) {
1602 struct fill_chain
*fill
;
1603 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1604 if (fill
->fill(fill
->data
))
1611 while (slot
!= NULL
) {
1612 if (!slot
->in_use
&& slot
->curl
!= NULL
1613 && curl_session_count
> min_curl_sessions
) {
1614 curl_easy_cleanup(slot
->curl
);
1616 curl_session_count
--;
1622 void step_active_slots(void)
1625 CURLMcode curlm_result
;
1628 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1629 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1630 if (num_transfers
< active_requests
) {
1631 process_curl_messages();
1632 fill_active_slots();
1636 void run_active_slot(struct active_request_slot
*slot
)
1642 struct timeval select_timeout
;
1645 slot
->finished
= &finished
;
1647 step_active_slots();
1651 curl_multi_timeout(curlm
, &curl_timeout
);
1652 if (curl_timeout
== 0) {
1654 } else if (curl_timeout
== -1) {
1655 select_timeout
.tv_sec
= 0;
1656 select_timeout
.tv_usec
= 50000;
1658 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1659 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1666 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1669 * It can happen that curl_multi_timeout returns a pathologically
1670 * long timeout when curl_multi_fdset returns no file descriptors
1671 * to read. See commit message for more details.
1674 (select_timeout
.tv_sec
> 0 ||
1675 select_timeout
.tv_usec
> 50000)) {
1676 select_timeout
.tv_sec
= 0;
1677 select_timeout
.tv_usec
= 50000;
1680 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1685 * The value of slot->finished we set before the loop was used
1686 * to set our "finished" variable when our request completed.
1688 * 1. The slot may not have been reused for another requst
1689 * yet, in which case it still has &finished.
1691 * 2. The slot may already be in-use to serve another request,
1692 * which can further be divided into two cases:
1694 * (a) If call run_active_slot() hasn't been called for that
1695 * other request, slot->finished would have been cleared
1696 * by get_active_slot() and has NULL.
1698 * (b) If the request did call run_active_slot(), then the
1699 * call would have updated slot->finished at the beginning
1700 * of this function, and with the clearing of the member
1701 * below, we would find that slot->finished is now NULL.
1703 * In all cases, slot->finished has no useful information to
1704 * anybody at this point. Some compilers warn us for
1705 * attempting to smuggle a pointer that is about to become
1706 * invalid, i.e. &finished. We clear it here to assure them.
1708 slot
->finished
= NULL
;
1711 static void release_active_slot(struct active_request_slot
*slot
)
1713 closedown_active_slot(slot
);
1715 xmulti_remove_handle(slot
);
1716 if (curl_session_count
> min_curl_sessions
) {
1717 curl_easy_cleanup(slot
->curl
);
1719 curl_session_count
--;
1722 fill_active_slots();
1725 void finish_all_active_slots(void)
1727 struct active_request_slot
*slot
= active_queue_head
;
1729 while (slot
!= NULL
)
1731 run_active_slot(slot
);
1732 slot
= active_queue_head
;
1738 /* Helpers for modifying and creating URLs */
1739 static inline int needs_quote(int ch
)
1741 if (((ch
>= 'A') && (ch
<= 'Z'))
1742 || ((ch
>= 'a') && (ch
<= 'z'))
1743 || ((ch
>= '0') && (ch
<= '9'))
1751 static char *quote_ref_url(const char *base
, const char *ref
)
1753 struct strbuf buf
= STRBUF_INIT
;
1757 end_url_with_slash(&buf
, base
);
1759 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1760 if (needs_quote(ch
))
1761 strbuf_addf(&buf
, "%%%02x", ch
);
1763 strbuf_addch(&buf
, *cp
);
1765 return strbuf_detach(&buf
, NULL
);
1768 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1770 int only_two_digit_prefix
)
1772 end_url_with_slash(buf
, url
);
1774 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1775 if (!only_two_digit_prefix
)
1776 strbuf_addstr(buf
, hex
+ 2);
1779 char *get_remote_object_url(const char *url
, const char *hex
,
1780 int only_two_digit_prefix
)
1782 struct strbuf buf
= STRBUF_INIT
;
1783 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1784 return strbuf_detach(&buf
, NULL
);
1787 void normalize_curl_result(CURLcode
*result
, long http_code
,
1788 char *errorstr
, size_t errorlen
)
1791 * If we see a failing http code with CURLE_OK, we have turned off
1792 * FAILONERROR (to keep the server's custom error response), and should
1793 * translate the code into failure here.
1795 * Likewise, if we see a redirect (30x code), that means we turned off
1796 * redirect-following, and we should treat the result as an error.
1798 if (*result
== CURLE_OK
&& http_code
>= 300) {
1799 *result
= CURLE_HTTP_RETURNED_ERROR
;
1801 * Normally curl will already have put the "reason phrase"
1802 * from the server into curl_errorstr; unfortunately without
1803 * FAILONERROR it is lost, so we can give only the numeric
1806 xsnprintf(errorstr
, errorlen
,
1807 "The requested URL returned error: %ld",
1812 static int handle_curl_result(struct slot_results
*results
)
1814 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1815 curl_errorstr
, sizeof(curl_errorstr
));
1817 if (results
->curl_result
== CURLE_OK
) {
1818 credential_approve(&http_auth
);
1819 credential_approve(&proxy_auth
);
1820 credential_approve(&cert_auth
);
1822 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1824 * We can't tell from here whether it's a bad path, bad
1825 * certificate, bad password, or something else wrong
1826 * with the certificate. So we reject the credential to
1827 * avoid caching or saving a bad password.
1829 credential_reject(&cert_auth
);
1831 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1832 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1833 return HTTP_NOMATCHPUBLICKEY
;
1835 } else if (missing_target(results
))
1836 return HTTP_MISSING_TARGET
;
1837 else if (results
->http_code
== 401) {
1838 if ((http_auth
.username
&& http_auth
.password
) ||\
1839 (http_auth
.authtype
&& http_auth
.credential
)) {
1840 if (http_auth
.multistage
) {
1841 credential_clear_secrets(&http_auth
);
1844 credential_reject(&http_auth
);
1845 if (always_auth_proactively())
1846 http_proactive_auth
= PROACTIVE_AUTH_NONE
;
1849 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1850 if (results
->auth_avail
) {
1851 http_auth_methods
&= results
->auth_avail
;
1852 http_auth_methods_restricted
= 1;
1857 if (results
->http_connectcode
== 407)
1858 credential_reject(&proxy_auth
);
1859 if (!curl_errorstr
[0])
1860 strlcpy(curl_errorstr
,
1861 curl_easy_strerror(results
->curl_result
),
1862 sizeof(curl_errorstr
));
1867 int run_one_slot(struct active_request_slot
*slot
,
1868 struct slot_results
*results
)
1870 slot
->results
= results
;
1871 if (!start_active_slot(slot
)) {
1872 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1873 "failed to start HTTP request");
1874 return HTTP_START_FAILED
;
1877 run_active_slot(slot
);
1878 return handle_curl_result(results
);
1881 struct curl_slist
*http_copy_default_headers(void)
1883 struct curl_slist
*headers
= NULL
;
1884 const struct string_list_item
*item
;
1886 for_each_string_list_item(item
, &extra_http_headers
)
1887 headers
= curl_slist_append(headers
, item
->string
);
1892 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1898 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1900 strbuf_addstr(buf
, ptr
);
1905 * Check for and extract a content-type parameter. "raw"
1906 * should be positioned at the start of the potential
1907 * parameter, with any whitespace already removed.
1909 * "name" is the name of the parameter. The value is appended
1912 static int extract_param(const char *raw
, const char *name
,
1915 size_t len
= strlen(name
);
1917 if (strncasecmp(raw
, name
, len
))
1925 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1926 strbuf_addch(out
, *raw
++);
1931 * Extract a normalized version of the content type, with any
1932 * spaces suppressed, all letters lowercased, and no trailing ";"
1935 * Note that we will silently remove even invalid whitespace. For
1936 * example, "text / plain" is specifically forbidden by RFC 2616,
1937 * but "text/plain" is the only reasonable output, and this keeps
1940 * If the "charset" argument is not NULL, store the value of any
1941 * charset parameter there.
1944 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1945 * "text / plain" -> "text/plain"
1947 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1948 struct strbuf
*charset
)
1953 strbuf_grow(type
, raw
->len
);
1954 for (p
= raw
->buf
; *p
; p
++) {
1961 strbuf_addch(type
, tolower(*p
));
1967 strbuf_reset(charset
);
1969 while (isspace(*p
) || *p
== ';')
1971 if (!extract_param(p
, "charset", charset
))
1973 while (*p
&& !isspace(*p
))
1977 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1978 strbuf_addstr(charset
, "ISO-8859-1");
1981 static void write_accept_language(struct strbuf
*buf
)
1984 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1985 * that, q-value will be smaller than 0.001, the minimum q-value the
1986 * HTTP specification allows. See
1987 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
1989 const int MAX_DECIMAL_PLACES
= 3;
1990 const int MAX_LANGUAGE_TAGS
= 1000;
1991 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1992 char **language_tags
= NULL
;
1994 const char *s
= get_preferred_languages();
1996 struct strbuf tag
= STRBUF_INIT
;
1998 /* Don't add Accept-Language header if no language is preferred. */
2003 * Split the colon-separated string of preferred languages into
2004 * language_tags array.
2007 /* collect language tag */
2008 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
2009 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
2011 /* skip .codeset, @modifier and any other unnecessary parts */
2012 while (*s
&& *s
!= ':')
2017 REALLOC_ARRAY(language_tags
, num_langs
);
2018 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
2019 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
2024 /* write Accept-Language header into buf */
2026 int last_buf_len
= 0;
2032 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
2033 language_tags
[num_langs
++] = xstrdup("*");
2035 /* compute decimal_places */
2036 for (max_q
= 1, decimal_places
= 0;
2037 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
2038 decimal_places
++, max_q
*= 10)
2041 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
2043 strbuf_addstr(buf
, "Accept-Language: ");
2045 for (i
= 0; i
< num_langs
; i
++) {
2047 strbuf_addstr(buf
, ", ");
2049 strbuf_addstr(buf
, language_tags
[i
]);
2052 strbuf_addf(buf
, q_format
, max_q
- i
);
2054 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
2055 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
2059 last_buf_len
= buf
->len
;
2063 for (i
= 0; i
< num_langs
; i
++)
2064 free(language_tags
[i
]);
2065 free(language_tags
);
2069 * Get an Accept-Language header which indicates user's preferred languages.
2073 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
2074 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
2075 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
2076 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
2077 * LANGUAGE= LANG=C -> ""
2079 const char *http_get_accept_language_header(void)
2081 if (!cached_accept_language
) {
2082 struct strbuf buf
= STRBUF_INIT
;
2083 write_accept_language(&buf
);
2085 cached_accept_language
= strbuf_detach(&buf
, NULL
);
2088 return cached_accept_language
;
2091 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
2094 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
2095 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
2098 /* http_request() targets */
2099 #define HTTP_REQUEST_STRBUF 0
2100 #define HTTP_REQUEST_FILE 1
2102 static int http_request(const char *url
,
2103 void *result
, int target
,
2104 const struct http_get_options
*options
)
2106 struct active_request_slot
*slot
;
2107 struct slot_results results
;
2108 struct curl_slist
*headers
= http_copy_default_headers();
2109 struct strbuf buf
= STRBUF_INIT
;
2110 const char *accept_language
;
2113 slot
= get_active_slot();
2114 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
2117 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
2119 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
2120 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
2122 if (target
== HTTP_REQUEST_FILE
) {
2123 off_t posn
= ftello(result
);
2124 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2127 http_opt_request_remainder(slot
->curl
, posn
);
2129 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2133 curl_easy_setopt(slot
->curl
, CURLOPT_HEADERFUNCTION
, fwrite_wwwauth
);
2135 accept_language
= http_get_accept_language_header();
2137 if (accept_language
)
2138 headers
= curl_slist_append(headers
, accept_language
);
2140 strbuf_addstr(&buf
, "Pragma:");
2141 if (options
&& options
->no_cache
)
2142 strbuf_addstr(&buf
, " no-cache");
2143 if (options
&& options
->initial_request
&&
2144 http_follow_config
== HTTP_FOLLOW_INITIAL
)
2145 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
2147 headers
= curl_slist_append(headers
, buf
.buf
);
2149 /* Add additional headers here */
2150 if (options
&& options
->extra_headers
) {
2151 const struct string_list_item
*item
;
2152 if (options
&& options
->extra_headers
) {
2153 for_each_string_list_item(item
, options
->extra_headers
) {
2154 headers
= curl_slist_append(headers
, item
->string
);
2159 headers
= http_append_auth_header(&http_auth
, headers
);
2161 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
2162 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
2163 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
2164 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
2166 ret
= run_one_slot(slot
, &results
);
2168 if (options
&& options
->content_type
) {
2169 struct strbuf raw
= STRBUF_INIT
;
2170 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
2171 extract_content_type(&raw
, options
->content_type
,
2173 strbuf_release(&raw
);
2176 if (options
&& options
->effective_url
)
2177 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
2178 options
->effective_url
);
2180 curl_slist_free_all(headers
);
2181 strbuf_release(&buf
);
2187 * Update the "base" url to a more appropriate value, as deduced by
2188 * redirects seen when requesting a URL starting with "url".
2190 * The "asked" parameter is a URL that we asked curl to access, and must begin
2193 * The "got" parameter is the URL that curl reported to us as where we ended
2196 * Returns 1 if we updated the base url, 0 otherwise.
2198 * Our basic strategy is to compare "base" and "asked" to find the bits
2199 * specific to our request. We then strip those bits off of "got" to yield the
2200 * new base. So for example, if our base is "http://example.com/foo.git",
2201 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2202 * with "https://other.example.com/foo.git/info/refs". We would want the
2203 * new URL to become "https://other.example.com/foo.git".
2205 * Note that this assumes a sane redirect scheme. It's entirely possible
2206 * in the example above to end up at a URL that does not even end in
2207 * "info/refs". In such a case we die. There's not much we can do, such a
2208 * scheme is unlikely to represent a real git repository, and failing to
2209 * rewrite the base opens options for malicious redirects to do funny things.
2211 static int update_url_from_redirect(struct strbuf
*base
,
2213 const struct strbuf
*got
)
2218 if (!strcmp(asked
, got
->buf
))
2221 if (!skip_prefix(asked
, base
->buf
, &tail
))
2222 BUG("update_url_from_redirect: %s is not a superset of %s",
2226 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
2227 die(_("unable to update url base from redirection:\n"
2233 strbuf_add(base
, got
->buf
, new_len
);
2238 static int http_request_reauth(const char *url
,
2239 void *result
, int target
,
2240 struct http_get_options
*options
)
2245 if (always_auth_proactively())
2246 credential_fill(&http_auth
, 1);
2248 ret
= http_request(url
, result
, target
, options
);
2250 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2253 if (options
&& options
->effective_url
&& options
->base_url
) {
2254 if (update_url_from_redirect(options
->base_url
,
2255 url
, options
->effective_url
)) {
2256 credential_from_url(&http_auth
, options
->base_url
->buf
);
2257 url
= options
->effective_url
->buf
;
2261 while (ret
== HTTP_REAUTH
&& --i
) {
2263 * The previous request may have put cruft into our output stream; we
2264 * should clear it out before making our next request.
2267 case HTTP_REQUEST_STRBUF
:
2268 strbuf_reset(result
);
2270 case HTTP_REQUEST_FILE
:
2271 if (fflush(result
)) {
2272 error_errno("unable to flush a file");
2273 return HTTP_START_FAILED
;
2276 if (ftruncate(fileno(result
), 0) < 0) {
2277 error_errno("unable to truncate a file");
2278 return HTTP_START_FAILED
;
2282 BUG("Unknown http_request target");
2285 credential_fill(&http_auth
, 1);
2287 ret
= http_request(url
, result
, target
, options
);
2292 int http_get_strbuf(const char *url
,
2293 struct strbuf
*result
,
2294 struct http_get_options
*options
)
2296 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2300 * Downloads a URL and stores the result in the given file.
2302 * If a previous interrupted download is detected (i.e. a previous temporary
2303 * file is still around) the download is resumed.
2305 int http_get_file(const char *url
, const char *filename
,
2306 struct http_get_options
*options
)
2309 struct strbuf tmpfile
= STRBUF_INIT
;
2312 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2313 result
= fopen(tmpfile
.buf
, "a");
2315 error("Unable to open local file %s", tmpfile
.buf
);
2320 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2323 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2326 strbuf_release(&tmpfile
);
2330 int http_fetch_ref(const char *base
, struct ref
*ref
)
2332 struct http_get_options options
= {0};
2334 struct strbuf buffer
= STRBUF_INIT
;
2337 options
.no_cache
= 1;
2339 url
= quote_ref_url(base
, ref
->name
);
2340 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2341 strbuf_rtrim(&buffer
);
2342 if (buffer
.len
== the_hash_algo
->hexsz
)
2343 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2344 else if (starts_with(buffer
.buf
, "ref: ")) {
2345 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2350 strbuf_release(&buffer
);
2355 /* Helpers for fetching packs */
2356 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2359 struct strbuf buf
= STRBUF_INIT
;
2361 if (http_is_verbose
)
2362 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2364 end_url_with_slash(&buf
, base_url
);
2365 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2366 url
= strbuf_detach(&buf
, NULL
);
2368 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2369 tmp
= strbuf_detach(&buf
, NULL
);
2371 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2372 error("Unable to get pack index %s", url
);
2380 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2381 unsigned char *sha1
, const char *base_url
)
2383 struct packed_git
*new_pack
;
2384 char *tmp_idx
= NULL
;
2387 if (has_pack_index(sha1
)) {
2388 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2390 return -1; /* parse_pack_index() already issued error message */
2394 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2398 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2403 return -1; /* parse_pack_index() already issued error message */
2406 ret
= verify_pack_index(new_pack
);
2408 close_pack_index(new_pack
);
2409 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2416 new_pack
->next
= *packs_head
;
2417 *packs_head
= new_pack
;
2421 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2423 struct http_get_options options
= {0};
2427 struct strbuf buf
= STRBUF_INIT
;
2428 struct object_id oid
;
2430 end_url_with_slash(&buf
, base_url
);
2431 strbuf_addstr(&buf
, "objects/info/packs");
2432 url
= strbuf_detach(&buf
, NULL
);
2434 options
.no_cache
= 1;
2435 ret
= http_get_strbuf(url
, &buf
, &options
);
2441 if (skip_prefix(data
, "P pack-", &data
) &&
2442 !parse_oid_hex(data
, &oid
, &data
) &&
2443 skip_prefix(data
, ".pack", &data
) &&
2444 (*data
== '\n' || *data
== '\0')) {
2445 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2447 data
= strchrnul(data
, '\n');
2450 data
++; /* skip past newline */
2458 void release_http_pack_request(struct http_pack_request
*preq
)
2460 if (preq
->packfile
) {
2461 fclose(preq
->packfile
);
2462 preq
->packfile
= NULL
;
2465 strbuf_release(&preq
->tmpfile
);
2466 curl_slist_free_all(preq
->headers
);
2471 static const char *default_index_pack_args
[] =
2472 {"index-pack", "--stdin", NULL
};
2474 int finish_http_pack_request(struct http_pack_request
*preq
)
2476 struct child_process ip
= CHILD_PROCESS_INIT
;
2480 fclose(preq
->packfile
);
2481 preq
->packfile
= NULL
;
2483 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2487 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2488 preq
->index_pack_args
:
2489 default_index_pack_args
);
2491 if (preq
->preserve_index_pack_stdout
)
2496 if (run_command(&ip
)) {
2503 unlink(preq
->tmpfile
.buf
);
2507 void http_install_packfile(struct packed_git
*p
,
2508 struct packed_git
**list_to_remove_from
)
2510 struct packed_git
**lst
= list_to_remove_from
;
2513 lst
= &((*lst
)->next
);
2514 *lst
= (*lst
)->next
;
2516 install_packed_git(the_repository
, p
);
2519 struct http_pack_request
*new_http_pack_request(
2520 const unsigned char *packed_git_hash
, const char *base_url
) {
2522 struct strbuf buf
= STRBUF_INIT
;
2524 end_url_with_slash(&buf
, base_url
);
2525 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2526 hash_to_hex(packed_git_hash
));
2527 return new_direct_http_pack_request(packed_git_hash
,
2528 strbuf_detach(&buf
, NULL
));
2531 struct http_pack_request
*new_direct_http_pack_request(
2532 const unsigned char *packed_git_hash
, char *url
)
2534 off_t prev_posn
= 0;
2535 struct http_pack_request
*preq
;
2537 CALLOC_ARRAY(preq
, 1);
2538 strbuf_init(&preq
->tmpfile
, 0);
2542 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2543 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2544 if (!preq
->packfile
) {
2545 error("Unable to open local file %s for pack",
2550 preq
->slot
= get_active_slot();
2551 preq
->headers
= object_request_headers();
2552 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2553 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2554 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2555 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
, preq
->headers
);
2558 * If there is data present from a previous transfer attempt,
2559 * resume where it left off
2561 prev_posn
= ftello(preq
->packfile
);
2563 if (http_is_verbose
)
2565 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2566 hash_to_hex(packed_git_hash
),
2567 (uintmax_t)prev_posn
);
2568 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2574 strbuf_release(&preq
->tmpfile
);
2580 /* Helpers for fetching objects (loose) */
2581 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2584 unsigned char expn
[4096];
2585 size_t size
= eltsize
* nmemb
;
2587 struct http_object_request
*freq
= data
;
2588 struct active_request_slot
*slot
= freq
->slot
;
2591 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2594 BUG("curl_easy_getinfo for HTTP code failed: %s",
2595 curl_easy_strerror(c
));
2596 if (slot
->http_code
>= 300)
2601 ssize_t retval
= xwrite(freq
->localfile
,
2602 (char *) ptr
+ posn
, size
- posn
);
2604 return posn
/ eltsize
;
2606 } while (posn
< size
);
2608 freq
->stream
.avail_in
= size
;
2609 freq
->stream
.next_in
= (void *)ptr
;
2611 freq
->stream
.next_out
= expn
;
2612 freq
->stream
.avail_out
= sizeof(expn
);
2613 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2614 the_hash_algo
->update_fn(&freq
->c
, expn
,
2615 sizeof(expn
) - freq
->stream
.avail_out
);
2616 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2620 struct http_object_request
*new_http_object_request(const char *base_url
,
2621 const struct object_id
*oid
)
2623 char *hex
= oid_to_hex(oid
);
2624 struct strbuf filename
= STRBUF_INIT
;
2625 struct strbuf prevfile
= STRBUF_INIT
;
2627 char prev_buf
[PREV_BUF_SIZE
];
2628 ssize_t prev_read
= 0;
2629 off_t prev_posn
= 0;
2630 struct http_object_request
*freq
;
2632 CALLOC_ARRAY(freq
, 1);
2633 strbuf_init(&freq
->tmpfile
, 0);
2634 oidcpy(&freq
->oid
, oid
);
2635 freq
->localfile
= -1;
2637 loose_object_path(the_repository
, &filename
, oid
);
2638 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2640 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2641 unlink_or_warn(prevfile
.buf
);
2642 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2643 unlink_or_warn(freq
->tmpfile
.buf
);
2644 strbuf_release(&filename
);
2646 if (freq
->localfile
!= -1)
2647 error("fd leakage in start: %d", freq
->localfile
);
2648 freq
->localfile
= open(freq
->tmpfile
.buf
,
2649 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2651 * This could have failed due to the "lazy directory creation";
2652 * try to mkdir the last path component.
2654 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2655 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2658 mkdir(freq
->tmpfile
.buf
, 0777);
2661 freq
->localfile
= open(freq
->tmpfile
.buf
,
2662 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2665 if (freq
->localfile
< 0) {
2666 error_errno("Couldn't create temporary file %s",
2671 git_inflate_init(&freq
->stream
);
2673 the_hash_algo
->init_fn(&freq
->c
);
2675 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2678 * If a previous temp file is present, process what was already
2681 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2682 if (prevlocal
!= -1) {
2684 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2686 if (fwrite_sha1_file(prev_buf
,
2689 freq
) == prev_read
) {
2690 prev_posn
+= prev_read
;
2695 } while (prev_read
> 0);
2698 unlink_or_warn(prevfile
.buf
);
2699 strbuf_release(&prevfile
);
2702 * Reset inflate/SHA1 if there was an error reading the previous temp
2703 * file; also rewind to the beginning of the local file.
2705 if (prev_read
== -1) {
2706 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2707 git_inflate_init(&freq
->stream
);
2708 the_hash_algo
->init_fn(&freq
->c
);
2711 lseek(freq
->localfile
, 0, SEEK_SET
);
2712 if (ftruncate(freq
->localfile
, 0) < 0) {
2713 error_errno("Couldn't truncate temporary file %s",
2720 freq
->slot
= get_active_slot();
2721 freq
->headers
= object_request_headers();
2723 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2724 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2725 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2726 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2727 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2728 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, freq
->headers
);
2731 * If we have successfully processed data from a previous fetch
2732 * attempt, only fetch the data we don't already have.
2735 if (http_is_verbose
)
2737 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2738 hex
, (uintmax_t)prev_posn
);
2739 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2745 strbuf_release(&prevfile
);
2751 void process_http_object_request(struct http_object_request
*freq
)
2755 freq
->curl_result
= freq
->slot
->curl_result
;
2756 freq
->http_code
= freq
->slot
->http_code
;
2760 int finish_http_object_request(struct http_object_request
*freq
)
2763 struct strbuf filename
= STRBUF_INIT
;
2765 close(freq
->localfile
);
2766 freq
->localfile
= -1;
2768 process_http_object_request(freq
);
2770 if (freq
->http_code
== 416) {
2771 warning("requested range invalid; we may already have all the data.");
2772 } else if (freq
->curl_result
!= CURLE_OK
) {
2773 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2774 if (st
.st_size
== 0)
2775 unlink_or_warn(freq
->tmpfile
.buf
);
2779 git_inflate_end(&freq
->stream
);
2780 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2781 if (freq
->zret
!= Z_STREAM_END
) {
2782 unlink_or_warn(freq
->tmpfile
.buf
);
2785 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2786 unlink_or_warn(freq
->tmpfile
.buf
);
2789 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2790 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2791 strbuf_release(&filename
);
2793 return freq
->rename
;
2796 void abort_http_object_request(struct http_object_request
*freq
)
2798 unlink_or_warn(freq
->tmpfile
.buf
);
2800 release_http_object_request(freq
);
2803 void release_http_object_request(struct http_object_request
*freq
)
2805 if (freq
->localfile
!= -1) {
2806 close(freq
->localfile
);
2807 freq
->localfile
= -1;
2809 FREE_AND_NULL(freq
->url
);
2811 freq
->slot
->callback_func
= NULL
;
2812 freq
->slot
->callback_data
= NULL
;
2813 release_active_slot(freq
->slot
);
2816 curl_slist_free_all(freq
->headers
);
2817 strbuf_release(&freq
->tmpfile
);