1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
7 #include "run-command.h"
10 #include "credential.h"
15 #include "transport.h"
17 #include "string-list.h"
18 #include "object-file.h"
19 #include "object-store-ll.h"
21 static struct trace_key trace_curl
= TRACE_KEY_INIT(CURL
);
22 static int trace_curl_data
= 1;
23 static int trace_curl_redact
= 1;
24 long int git_curl_ipresolve
= CURL_IPRESOLVE_WHATEVER
;
27 ssize_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
29 static int min_curl_sessions
= 1;
30 static int curl_session_count
;
31 static int max_requests
= -1;
33 static CURL
*curl_default
;
35 #define PREV_BUF_SIZE 4096
37 char curl_errorstr
[CURL_ERROR_SIZE
];
39 static int curl_ssl_verify
= -1;
40 static int curl_ssl_try
;
41 static char *curl_http_version
;
42 static char *ssl_cert
;
43 static char *ssl_cert_type
;
44 static char *ssl_cipherlist
;
45 static char *ssl_version
;
50 { "sslv2", CURL_SSLVERSION_SSLv2
},
51 { "sslv3", CURL_SSLVERSION_SSLv3
},
52 { "tlsv1", CURL_SSLVERSION_TLSv1
},
53 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
54 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
55 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
56 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
58 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
59 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3
},
63 static char *ssl_key_type
;
64 static char *ssl_capath
;
65 static char *curl_no_proxy
;
66 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
67 static char *ssl_pinnedkey
;
69 static char *ssl_cainfo
;
70 static long curl_low_speed_limit
= -1;
71 static long curl_low_speed_time
= -1;
72 static int curl_ftp_no_epsv
;
73 static char *curl_http_proxy
;
74 static char *http_proxy_authmethod
;
76 static char *http_proxy_ssl_cert
;
77 static char *http_proxy_ssl_key
;
78 static char *http_proxy_ssl_ca_info
;
79 static struct credential proxy_cert_auth
= CREDENTIAL_INIT
;
80 static int proxy_ssl_cert_password_required
;
85 } proxy_authmethods
[] = {
86 { "basic", CURLAUTH_BASIC
},
87 { "digest", CURLAUTH_DIGEST
},
88 { "negotiate", CURLAUTH_GSSNEGOTIATE
},
89 { "ntlm", CURLAUTH_NTLM
},
90 { "anyauth", CURLAUTH_ANY
},
92 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
93 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
97 #ifdef CURLGSSAPI_DELEGATION_FLAG
98 static char *curl_deleg
;
101 long curl_deleg_param
;
102 } curl_deleg_levels
[] = {
103 { "none", CURLGSSAPI_DELEGATION_NONE
},
104 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG
},
105 { "always", CURLGSSAPI_DELEGATION_FLAG
},
109 static struct credential proxy_auth
= CREDENTIAL_INIT
;
110 static const char *curl_proxyuserpwd
;
111 static char *curl_cookie_file
;
112 static int curl_save_cookies
;
113 struct credential http_auth
= CREDENTIAL_INIT
;
114 static int http_proactive_auth
;
115 static char *user_agent
;
116 static int curl_empty_auth
= -1;
118 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
120 static struct credential cert_auth
= CREDENTIAL_INIT
;
121 static int ssl_cert_password_required
;
122 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
123 static int http_auth_methods_restricted
;
124 /* Modes for which empty_auth cannot actually help us. */
125 static unsigned long empty_auth_useless
=
130 static struct curl_slist
*pragma_header
;
131 static struct string_list extra_http_headers
= STRING_LIST_INIT_DUP
;
133 static struct curl_slist
*host_resolutions
;
135 static struct active_request_slot
*active_queue_head
;
137 static char *cached_accept_language
;
139 static char *http_ssl_backend
;
141 static int http_schannel_check_revoke
= 1;
143 * With the backend being set to `schannel`, setting sslCAinfo would override
144 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
147 static int http_schannel_use_ssl_cainfo
;
149 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
151 size_t size
= eltsize
* nmemb
;
152 struct buffer
*buffer
= buffer_
;
154 if (size
> buffer
->buf
.len
- buffer
->posn
)
155 size
= buffer
->buf
.len
- buffer
->posn
;
156 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
157 buffer
->posn
+= size
;
159 return size
/ eltsize
;
162 int seek_buffer(void *clientp
, curl_off_t offset
, int origin
)
164 struct buffer
*buffer
= clientp
;
166 if (origin
!= SEEK_SET
)
167 BUG("seek_buffer only handles SEEK_SET");
168 if (offset
< 0 || offset
>= buffer
->buf
.len
) {
169 error("curl seek would be outside of buffer");
170 return CURL_SEEKFUNC_FAIL
;
173 buffer
->posn
= offset
;
174 return CURL_SEEKFUNC_OK
;
177 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
179 size_t size
= eltsize
* nmemb
;
180 struct strbuf
*buffer
= buffer_
;
182 strbuf_add(buffer
, ptr
, size
);
187 * A folded header continuation line starts with any number of spaces or
188 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
189 * It is not a continuation line if the line starts with any other character.
191 static inline int is_hdr_continuation(const char *ptr
, const size_t size
)
193 return size
&& (*ptr
== ' ' || *ptr
== '\t');
196 static size_t fwrite_wwwauth(char *ptr
, size_t eltsize
, size_t nmemb
, void *p UNUSED
)
198 size_t size
= eltsize
* nmemb
;
199 struct strvec
*values
= &http_auth
.wwwauth_headers
;
200 struct strbuf buf
= STRBUF_INIT
;
205 * Header lines may not come NULL-terminated from libcurl so we must
206 * limit all scans to the maximum length of the header line, or leverage
207 * strbufs for all operations.
209 * In addition, it is possible that header values can be split over
210 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
211 * but older servers may still emit them. A continuation header field
212 * value is identified as starting with a space or horizontal tab.
214 * The formal definition of a header field as given in RFC 7230 is:
216 * header-field = field-name ":" OWS field-value OWS
219 * field-value = *( field-content / obs-fold )
220 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
221 * field-vchar = VCHAR / obs-text
223 * obs-fold = CRLF 1*( SP / HTAB )
224 * ; obsolete line folding
225 * ; see Section 3.2.4
228 /* Start of a new WWW-Authenticate header */
229 if (skip_iprefix_mem(ptr
, size
, "www-authenticate:", &val
, &val_len
)) {
230 strbuf_add(&buf
, val
, val_len
);
233 * Strip the CRLF that should be present at the end of each
234 * field as well as any trailing or leading whitespace from the
239 strvec_push(values
, buf
.buf
);
240 http_auth
.header_is_last_match
= 1;
245 * This line could be a continuation of the previously matched header
246 * field. If this is the case then we should append this value to the
247 * end of the previously consumed value.
249 if (http_auth
.header_is_last_match
&& is_hdr_continuation(ptr
, size
)) {
251 * Trim the CRLF and any leading or trailing from this line.
253 strbuf_add(&buf
, ptr
, size
);
257 * At this point we should always have at least one existing
258 * value, even if it is empty. Do not bother appending the new
259 * value if this continuation header is itself empty.
262 BUG("should have at least one existing header value");
263 } else if (buf
.len
) {
264 char *prev
= xstrdup(values
->v
[values
->nr
- 1]);
266 /* Join two non-empty values with a single space. */
267 const char *const sp
= *prev
? " " : "";
270 strvec_pushf(values
, "%s%s%s", prev
, sp
, buf
.buf
);
277 /* Not a continuation of a previously matched auth header line. */
278 http_auth
.header_is_last_match
= 0;
281 * If this is a HTTP status line and not a header field, this signals
282 * a different HTTP response. libcurl writes all the output of all
283 * response headers of all responses, including redirects.
284 * We only care about the last HTTP request response's headers so clear
285 * the existing array.
287 if (skip_iprefix_mem(ptr
, size
, "http/", &val
, &val_len
))
288 strvec_clear(values
);
291 strbuf_release(&buf
);
295 size_t fwrite_null(char *ptr UNUSED
, size_t eltsize UNUSED
, size_t nmemb
,
301 static struct curl_slist
*object_request_headers(void)
303 return curl_slist_append(http_copy_default_headers(), "Pragma:");
306 static void closedown_active_slot(struct active_request_slot
*slot
)
312 static void finish_active_slot(struct active_request_slot
*slot
)
314 closedown_active_slot(slot
);
315 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
318 (*slot
->finished
) = 1;
320 /* Store slot results so they can be read after the slot is reused */
322 slot
->results
->curl_result
= slot
->curl_result
;
323 slot
->results
->http_code
= slot
->http_code
;
324 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
325 &slot
->results
->auth_avail
);
327 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
328 &slot
->results
->http_connectcode
);
331 /* Run callback if appropriate */
332 if (slot
->callback_func
)
333 slot
->callback_func(slot
->callback_data
);
336 static void xmulti_remove_handle(struct active_request_slot
*slot
)
338 curl_multi_remove_handle(curlm
, slot
->curl
);
341 static void process_curl_messages(void)
344 struct active_request_slot
*slot
;
345 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
347 while (curl_message
!= NULL
) {
348 if (curl_message
->msg
== CURLMSG_DONE
) {
349 int curl_result
= curl_message
->data
.result
;
350 slot
= active_queue_head
;
351 while (slot
!= NULL
&&
352 slot
->curl
!= curl_message
->easy_handle
)
355 xmulti_remove_handle(slot
);
356 slot
->curl_result
= curl_result
;
357 finish_active_slot(slot
);
359 fprintf(stderr
, "Received DONE message for unknown request!\n");
362 fprintf(stderr
, "Unknown CURL message received: %d\n",
363 (int)curl_message
->msg
);
365 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
369 static int http_options(const char *var
, const char *value
,
370 const struct config_context
*ctx
, void *data
)
372 if (!strcmp("http.version", var
)) {
373 return git_config_string(&curl_http_version
, var
, value
);
375 if (!strcmp("http.sslverify", var
)) {
376 curl_ssl_verify
= git_config_bool(var
, value
);
379 if (!strcmp("http.sslcipherlist", var
))
380 return git_config_string(&ssl_cipherlist
, var
, value
);
381 if (!strcmp("http.sslversion", var
))
382 return git_config_string(&ssl_version
, var
, value
);
383 if (!strcmp("http.sslcert", var
))
384 return git_config_pathname(&ssl_cert
, var
, value
);
385 if (!strcmp("http.sslcerttype", var
))
386 return git_config_string(&ssl_cert_type
, var
, value
);
387 if (!strcmp("http.sslkey", var
))
388 return git_config_pathname(&ssl_key
, var
, value
);
389 if (!strcmp("http.sslkeytype", var
))
390 return git_config_string(&ssl_key_type
, var
, value
);
391 if (!strcmp("http.sslcapath", var
))
392 return git_config_pathname(&ssl_capath
, var
, value
);
393 if (!strcmp("http.sslcainfo", var
))
394 return git_config_pathname(&ssl_cainfo
, var
, value
);
395 if (!strcmp("http.sslcertpasswordprotected", var
)) {
396 ssl_cert_password_required
= git_config_bool(var
, value
);
399 if (!strcmp("http.ssltry", var
)) {
400 curl_ssl_try
= git_config_bool(var
, value
);
403 if (!strcmp("http.sslbackend", var
)) {
404 free(http_ssl_backend
);
405 http_ssl_backend
= xstrdup_or_null(value
);
409 if (!strcmp("http.schannelcheckrevoke", var
)) {
410 http_schannel_check_revoke
= git_config_bool(var
, value
);
414 if (!strcmp("http.schannelusesslcainfo", var
)) {
415 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
419 if (!strcmp("http.minsessions", var
)) {
420 min_curl_sessions
= git_config_int(var
, value
, ctx
->kvi
);
421 if (min_curl_sessions
> 1)
422 min_curl_sessions
= 1;
425 if (!strcmp("http.maxrequests", var
)) {
426 max_requests
= git_config_int(var
, value
, ctx
->kvi
);
429 if (!strcmp("http.lowspeedlimit", var
)) {
430 curl_low_speed_limit
= (long)git_config_int(var
, value
, ctx
->kvi
);
433 if (!strcmp("http.lowspeedtime", var
)) {
434 curl_low_speed_time
= (long)git_config_int(var
, value
, ctx
->kvi
);
438 if (!strcmp("http.noepsv", var
)) {
439 curl_ftp_no_epsv
= git_config_bool(var
, value
);
442 if (!strcmp("http.proxy", var
))
443 return git_config_string(&curl_http_proxy
, var
, value
);
445 if (!strcmp("http.proxyauthmethod", var
))
446 return git_config_string(&http_proxy_authmethod
, var
, value
);
448 if (!strcmp("http.proxysslcert", var
))
449 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
451 if (!strcmp("http.proxysslkey", var
))
452 return git_config_string(&http_proxy_ssl_key
, var
, value
);
454 if (!strcmp("http.proxysslcainfo", var
))
455 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
457 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
458 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
462 if (!strcmp("http.cookiefile", var
))
463 return git_config_pathname(&curl_cookie_file
, var
, value
);
464 if (!strcmp("http.savecookies", var
)) {
465 curl_save_cookies
= git_config_bool(var
, value
);
469 if (!strcmp("http.postbuffer", var
)) {
470 http_post_buffer
= git_config_ssize_t(var
, value
, ctx
->kvi
);
471 if (http_post_buffer
< 0)
472 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
473 if (http_post_buffer
< LARGE_PACKET_MAX
)
474 http_post_buffer
= LARGE_PACKET_MAX
;
478 if (!strcmp("http.useragent", var
))
479 return git_config_string(&user_agent
, var
, value
);
481 if (!strcmp("http.emptyauth", var
)) {
482 if (value
&& !strcmp("auto", value
))
483 curl_empty_auth
= -1;
485 curl_empty_auth
= git_config_bool(var
, value
);
489 if (!strcmp("http.delegation", var
)) {
490 #ifdef CURLGSSAPI_DELEGATION_FLAG
491 return git_config_string(&curl_deleg
, var
, value
);
493 warning(_("Delegation control is not supported with cURL < 7.22.0"));
498 if (!strcmp("http.pinnedpubkey", var
)) {
499 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
500 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
502 warning(_("Public key pinning not supported with cURL < 7.39.0"));
507 if (!strcmp("http.extraheader", var
)) {
509 return config_error_nonbool(var
);
510 } else if (!*value
) {
511 string_list_clear(&extra_http_headers
, 0);
513 string_list_append(&extra_http_headers
, value
);
518 if (!strcmp("http.curloptresolve", var
)) {
520 return config_error_nonbool(var
);
521 } else if (!*value
) {
522 curl_slist_free_all(host_resolutions
);
523 host_resolutions
= NULL
;
525 host_resolutions
= curl_slist_append(host_resolutions
, value
);
530 if (!strcmp("http.followredirects", var
)) {
531 if (value
&& !strcmp(value
, "initial"))
532 http_follow_config
= HTTP_FOLLOW_INITIAL
;
533 else if (git_config_bool(var
, value
))
534 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
536 http_follow_config
= HTTP_FOLLOW_NONE
;
540 /* Fall back on the default ones */
541 return git_default_config(var
, value
, ctx
, data
);
544 static int curl_empty_auth_enabled(void)
546 if (curl_empty_auth
>= 0)
547 return curl_empty_auth
;
550 * In the automatic case, kick in the empty-auth
551 * hack as long as we would potentially try some
552 * method more exotic than "Basic" or "Digest".
554 * But only do this when this is our second or
555 * subsequent request, as by then we know what
556 * methods are available.
558 if (http_auth_methods_restricted
&&
559 (http_auth_methods
& ~empty_auth_useless
))
564 struct curl_slist
*http_append_auth_header(const struct credential
*c
,
565 struct curl_slist
*headers
)
567 if (c
->authtype
&& c
->credential
) {
568 struct strbuf auth
= STRBUF_INIT
;
569 strbuf_addf(&auth
, "Authorization: %s %s",
570 c
->authtype
, c
->credential
);
571 headers
= curl_slist_append(headers
, auth
.buf
);
572 strbuf_release(&auth
);
577 static void init_curl_http_auth(CURL
*result
)
579 if ((!http_auth
.username
|| !*http_auth
.username
) &&
580 (!http_auth
.credential
|| !*http_auth
.credential
)) {
581 if (curl_empty_auth_enabled())
582 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
586 credential_fill(&http_auth
, 1);
588 if (http_auth
.password
) {
589 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
590 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
594 /* *var must be free-able */
595 static void var_override(char **var
, char *value
)
599 *var
= xstrdup(value
);
603 static void set_proxyauth_name_password(CURL
*result
)
605 if (proxy_auth
.password
) {
606 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
607 proxy_auth
.username
);
608 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
609 proxy_auth
.password
);
610 } else if (proxy_auth
.authtype
&& proxy_auth
.credential
) {
611 curl_easy_setopt(result
, CURLOPT_PROXYHEADER
,
612 http_append_auth_header(&proxy_auth
, NULL
));
616 static void init_curl_proxy_auth(CURL
*result
)
618 if (proxy_auth
.username
) {
619 if (!proxy_auth
.password
&& !proxy_auth
.credential
)
620 credential_fill(&proxy_auth
, 1);
621 set_proxyauth_name_password(result
);
624 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
626 if (http_proxy_authmethod
) {
628 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
629 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
630 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
631 proxy_authmethods
[i
].curlauth_param
);
635 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
636 warning("unsupported proxy authentication method %s: using anyauth",
637 http_proxy_authmethod
);
638 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
642 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
645 static int has_cert_password(void)
647 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
649 if (!cert_auth
.password
) {
650 cert_auth
.protocol
= xstrdup("cert");
651 cert_auth
.host
= xstrdup("");
652 cert_auth
.username
= xstrdup("");
653 cert_auth
.path
= xstrdup(ssl_cert
);
654 credential_fill(&cert_auth
, 0);
659 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
660 static int has_proxy_cert_password(void)
662 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
664 if (!proxy_cert_auth
.password
) {
665 proxy_cert_auth
.protocol
= xstrdup("cert");
666 proxy_cert_auth
.host
= xstrdup("");
667 proxy_cert_auth
.username
= xstrdup("");
668 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
669 credential_fill(&proxy_cert_auth
, 0);
675 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
676 static void set_curl_keepalive(CURL
*c
)
678 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
682 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
686 socklen_t len
= (socklen_t
)sizeof(ka
);
688 if (type
!= CURLSOCKTYPE_IPCXN
)
691 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
693 warning_errno("unable to set SO_KEEPALIVE on socket");
695 return CURL_SOCKOPT_OK
;
698 static void set_curl_keepalive(CURL
*c
)
700 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
704 /* Return 1 if redactions have been made, 0 otherwise. */
705 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
708 const char *sensitive_header
;
710 if (trace_curl_redact
&&
711 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
712 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
713 /* The first token is the type, which is OK to log */
714 while (isspace(*sensitive_header
))
716 while (*sensitive_header
&& !isspace(*sensitive_header
))
718 /* Everything else is opaque and possibly sensitive */
719 strbuf_setlen(header
, sensitive_header
- header
->buf
);
720 strbuf_addstr(header
, " <redacted>");
722 } else if (trace_curl_redact
&&
723 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
724 struct strbuf redacted_header
= STRBUF_INIT
;
727 while (isspace(*sensitive_header
))
730 cookie
= sensitive_header
;
734 char *semicolon
= strstr(cookie
, "; ");
737 equals
= strchrnul(cookie
, '=');
739 /* invalid cookie, just append and continue */
740 strbuf_addstr(&redacted_header
, cookie
);
743 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
744 strbuf_addstr(&redacted_header
, "=<redacted>");
747 * There are more cookies. (Or, for some
748 * reason, the input string ends in "; ".)
750 strbuf_addstr(&redacted_header
, "; ");
751 cookie
= semicolon
+ strlen("; ");
757 strbuf_setlen(header
, sensitive_header
- header
->buf
);
758 strbuf_addbuf(header
, &redacted_header
);
764 static int match_curl_h2_trace(const char *line
, const char **out
)
769 * curl prior to 8.1.0 gives us:
771 * h2h3 [<header-name>: <header-val>]
773 * Starting in 8.1.0, the first token became just "h2".
775 if (skip_iprefix(line
, "h2h3 [", out
) ||
776 skip_iprefix(line
, "h2 [", out
))
781 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
782 * where <stream-id> is numeric.
784 if (skip_iprefix(line
, "[HTTP/2] [", &p
)) {
787 if (skip_prefix(p
, "] [", out
))
794 /* Redact headers in info */
795 static void redact_sensitive_info_header(struct strbuf
*header
)
797 const char *sensitive_header
;
799 if (trace_curl_redact
&&
800 match_curl_h2_trace(header
->buf
, &sensitive_header
)) {
801 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
802 /* redaction ate our closing bracket */
803 strbuf_addch(header
, ']');
808 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
810 struct strbuf out
= STRBUF_INIT
;
811 struct strbuf
**headers
, **header
;
813 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
814 text
, (long)size
, (long)size
);
815 trace_strbuf(&trace_curl
, &out
);
817 strbuf_add(&out
, ptr
, size
);
818 headers
= strbuf_split_max(&out
, '\n', 0);
820 for (header
= headers
; *header
; header
++) {
821 if (hide_sensitive_header
)
822 redact_sensitive_header(*header
, 0);
823 strbuf_insertstr((*header
), 0, text
);
824 strbuf_insertstr((*header
), strlen(text
), ": ");
825 strbuf_rtrim((*header
));
826 strbuf_addch((*header
), '\n');
827 trace_strbuf(&trace_curl
, (*header
));
829 strbuf_list_free(headers
);
830 strbuf_release(&out
);
833 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
836 struct strbuf out
= STRBUF_INIT
;
837 unsigned int width
= 60;
839 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
840 text
, (long)size
, (long)size
);
841 trace_strbuf(&trace_curl
, &out
);
843 for (i
= 0; i
< size
; i
+= width
) {
847 strbuf_addf(&out
, "%s: ", text
);
848 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
849 unsigned char ch
= ptr
[i
+ w
];
852 (ch
>= 0x20) && (ch
< 0x80)
855 strbuf_addch(&out
, '\n');
856 trace_strbuf(&trace_curl
, &out
);
858 strbuf_release(&out
);
861 static void curl_dump_info(char *data
, size_t size
)
863 struct strbuf buf
= STRBUF_INIT
;
865 strbuf_add(&buf
, data
, size
);
867 redact_sensitive_info_header(&buf
);
868 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
870 strbuf_release(&buf
);
873 static int curl_trace(CURL
*handle UNUSED
, curl_infotype type
,
874 char *data
, size_t size
,
878 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
882 curl_dump_info(data
, size
);
884 case CURLINFO_HEADER_OUT
:
885 text
= "=> Send header";
886 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
888 case CURLINFO_DATA_OUT
:
889 if (trace_curl_data
) {
890 text
= "=> Send data";
891 curl_dump_data(text
, (unsigned char *)data
, size
);
894 case CURLINFO_SSL_DATA_OUT
:
895 if (trace_curl_data
) {
896 text
= "=> Send SSL data";
897 curl_dump_data(text
, (unsigned char *)data
, size
);
900 case CURLINFO_HEADER_IN
:
901 text
= "<= Recv header";
902 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
904 case CURLINFO_DATA_IN
:
905 if (trace_curl_data
) {
906 text
= "<= Recv data";
907 curl_dump_data(text
, (unsigned char *)data
, size
);
910 case CURLINFO_SSL_DATA_IN
:
911 if (trace_curl_data
) {
912 text
= "<= Recv SSL data";
913 curl_dump_data(text
, (unsigned char *)data
, size
);
917 default: /* we ignore unknown types by default */
923 void http_trace_curl_no_data(void)
925 trace_override_envvar(&trace_curl
, "1");
929 void setup_curl_trace(CURL
*handle
)
931 if (!trace_want(&trace_curl
))
933 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
934 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
935 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
938 static void proto_list_append(struct strbuf
*list
, const char *proto
)
943 strbuf_addch(list
, ',');
944 strbuf_addstr(list
, proto
);
947 static long get_curl_allowed_protocols(int from_user
, struct strbuf
*list
)
951 if (is_transport_allowed("http", from_user
)) {
952 bits
|= CURLPROTO_HTTP
;
953 proto_list_append(list
, "http");
955 if (is_transport_allowed("https", from_user
)) {
956 bits
|= CURLPROTO_HTTPS
;
957 proto_list_append(list
, "https");
959 if (is_transport_allowed("ftp", from_user
)) {
960 bits
|= CURLPROTO_FTP
;
961 proto_list_append(list
, "ftp");
963 if (is_transport_allowed("ftps", from_user
)) {
964 bits
|= CURLPROTO_FTPS
;
965 proto_list_append(list
, "ftps");
971 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
972 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
979 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
980 { "HTTP/2", CURL_HTTP_VERSION_2
}
983 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
984 if (!strcmp(version_string
, choice
[i
].name
)) {
985 *opt
= choice
[i
].opt_token
;
990 warning("unknown value given to http.version: '%s'", version_string
);
991 return -1; /* not found */
996 static CURL
*get_curl_handle(void)
998 CURL
*result
= curl_easy_init();
1001 die("curl_easy_init failed");
1003 if (!curl_ssl_verify
) {
1004 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
1005 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
1007 /* Verify authenticity of the peer's certificate */
1008 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
1009 /* The name in the cert must match whom we tried to connect */
1010 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
1013 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
1014 if (curl_http_version
) {
1016 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
1017 /* Set request use http version */
1018 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
1023 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
1024 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
1026 #ifdef CURLGSSAPI_DELEGATION_FLAG
1029 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
1030 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
1031 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
1032 curl_deleg_levels
[i
].curl_deleg_param
);
1036 if (i
== ARRAY_SIZE(curl_deleg_levels
))
1037 warning("Unknown delegation method '%s': using default",
1042 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1043 !http_schannel_check_revoke
) {
1044 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1045 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
1047 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1051 if (http_proactive_auth
)
1052 init_curl_http_auth(result
);
1054 if (getenv("GIT_SSL_VERSION"))
1055 ssl_version
= getenv("GIT_SSL_VERSION");
1056 if (ssl_version
&& *ssl_version
) {
1058 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
1059 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
1060 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
1061 sslversions
[i
].ssl_version
);
1065 if (i
== ARRAY_SIZE(sslversions
))
1066 warning("unsupported ssl version %s: using default",
1070 if (getenv("GIT_SSL_CIPHER_LIST"))
1071 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
1072 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
1073 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
1077 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
1079 curl_easy_setopt(result
, CURLOPT_SSLCERTTYPE
, ssl_cert_type
);
1080 if (has_cert_password())
1081 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
1083 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
1085 curl_easy_setopt(result
, CURLOPT_SSLKEYTYPE
, ssl_key_type
);
1087 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
1088 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1090 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
1092 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1093 !http_schannel_use_ssl_cainfo
) {
1094 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
1095 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1096 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
1098 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
1100 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
1101 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1102 if (http_proxy_ssl_ca_info
)
1103 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
1107 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
1108 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
1109 curl_low_speed_limit
);
1110 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
1111 curl_low_speed_time
);
1114 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
1115 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
1117 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1119 struct strbuf buf
= STRBUF_INIT
;
1121 get_curl_allowed_protocols(0, &buf
);
1122 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS_STR
, buf
.buf
);
1125 get_curl_allowed_protocols(-1, &buf
);
1126 curl_easy_setopt(result
, CURLOPT_PROTOCOLS_STR
, buf
.buf
);
1127 strbuf_release(&buf
);
1130 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
1131 get_curl_allowed_protocols(0, NULL
));
1132 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
1133 get_curl_allowed_protocols(-1, NULL
));
1136 if (getenv("GIT_CURL_VERBOSE"))
1137 http_trace_curl_no_data();
1138 setup_curl_trace(result
);
1139 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1140 trace_curl_data
= 0;
1141 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1142 trace_curl_redact
= 0;
1144 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
1145 user_agent
? user_agent
: git_user_agent());
1147 if (curl_ftp_no_epsv
)
1148 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
1151 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
1154 * CURL also examines these variables as a fallback; but we need to query
1155 * them here in order to decide whether to prompt for missing password (cf.
1156 * init_curl_proxy_auth()).
1158 * Unlike many other common environment variables, these are historically
1159 * lowercase only. It appears that CURL did not know this and implemented
1160 * only uppercase variants, which was later corrected to take both - with
1161 * the exception of http_proxy, which is lowercase only also in CURL. As
1162 * the lowercase versions are the historical quasi-standard, they take
1163 * precedence here, as in CURL.
1165 if (!curl_http_proxy
) {
1166 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
1167 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
1168 var_override(&curl_http_proxy
, getenv("https_proxy"));
1170 var_override(&curl_http_proxy
, getenv("http_proxy"));
1172 if (!curl_http_proxy
) {
1173 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
1174 var_override(&curl_http_proxy
, getenv("all_proxy"));
1178 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1180 * Handle case with the empty http.proxy value here to keep
1181 * common code clean.
1182 * NB: empty option disables proxying at all.
1184 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1185 } else if (curl_http_proxy
) {
1186 if (starts_with(curl_http_proxy
, "socks5h"))
1187 curl_easy_setopt(result
,
1188 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1189 else if (starts_with(curl_http_proxy
, "socks5"))
1190 curl_easy_setopt(result
,
1191 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1192 else if (starts_with(curl_http_proxy
, "socks4a"))
1193 curl_easy_setopt(result
,
1194 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1195 else if (starts_with(curl_http_proxy
, "socks"))
1196 curl_easy_setopt(result
,
1197 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1198 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1199 else if (starts_with(curl_http_proxy
, "https")) {
1200 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1202 if (http_proxy_ssl_cert
)
1203 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1205 if (http_proxy_ssl_key
)
1206 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1208 if (has_proxy_cert_password())
1209 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1212 if (strstr(curl_http_proxy
, "://"))
1213 credential_from_url(&proxy_auth
, curl_http_proxy
);
1215 struct strbuf url
= STRBUF_INIT
;
1216 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1217 credential_from_url(&proxy_auth
, url
.buf
);
1218 strbuf_release(&url
);
1221 if (!proxy_auth
.host
)
1222 die("Invalid proxy URL '%s'", curl_http_proxy
);
1224 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1225 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1226 var_override(&curl_no_proxy
, getenv("no_proxy"));
1227 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1229 init_curl_proxy_auth(result
);
1231 set_curl_keepalive(result
);
1236 static void set_from_env(char **var
, const char *envname
)
1238 const char *val
= getenv(envname
);
1240 FREE_AND_NULL(*var
);
1241 *var
= xstrdup(val
);
1245 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1247 char *low_speed_limit
;
1248 char *low_speed_time
;
1249 char *normalized_url
;
1250 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1252 config
.section
= "http";
1254 config
.collect_fn
= http_options
;
1255 config
.cascade_fn
= git_default_config
;
1258 http_is_verbose
= 0;
1259 normalized_url
= url_normalize(url
, &config
.url
);
1261 git_config(urlmatch_config_entry
, &config
);
1262 free(normalized_url
);
1263 string_list_clear(&config
.vars
, 1);
1265 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1266 if (http_ssl_backend
) {
1267 const curl_ssl_backend
**backends
;
1268 struct strbuf buf
= STRBUF_INIT
;
1271 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1272 case CURLSSLSET_UNKNOWN_BACKEND
:
1273 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1274 "Supported SSL backends:"),
1276 for (i
= 0; backends
[i
]; i
++)
1277 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1279 case CURLSSLSET_NO_BACKENDS
:
1280 die(_("Could not set SSL backend to '%s': "
1281 "cURL was built without SSL backends"),
1283 case CURLSSLSET_TOO_LATE
:
1284 die(_("Could not set SSL backend to '%s': already set"),
1292 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1293 die("curl_global_init failed");
1295 http_proactive_auth
= proactive_auth
;
1297 if (remote
&& remote
->http_proxy
)
1298 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1301 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1303 pragma_header
= curl_slist_append(http_copy_default_headers(),
1304 "Pragma: no-cache");
1307 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1308 if (http_max_requests
)
1309 max_requests
= atoi(http_max_requests
);
1312 curlm
= curl_multi_init();
1314 die("curl_multi_init failed");
1316 if (getenv("GIT_SSL_NO_VERIFY"))
1317 curl_ssl_verify
= 0;
1319 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1320 set_from_env(&ssl_cert_type
, "GIT_SSL_CERT_TYPE");
1321 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1322 set_from_env(&ssl_key_type
, "GIT_SSL_KEY_TYPE");
1323 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1324 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1326 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1328 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1329 if (low_speed_limit
)
1330 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1331 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1333 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1335 if (curl_ssl_verify
== -1)
1336 curl_ssl_verify
= 1;
1338 curl_session_count
= 0;
1339 if (max_requests
< 1)
1340 max_requests
= DEFAULT_MAX_REQUESTS
;
1342 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1343 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1344 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1346 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1347 proxy_ssl_cert_password_required
= 1;
1349 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1350 curl_ftp_no_epsv
= 1;
1353 credential_from_url(&http_auth
, url
);
1354 if (!ssl_cert_password_required
&&
1355 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1356 starts_with(url
, "https://"))
1357 ssl_cert_password_required
= 1;
1360 curl_default
= get_curl_handle();
1363 void http_cleanup(void)
1365 struct active_request_slot
*slot
= active_queue_head
;
1367 while (slot
!= NULL
) {
1368 struct active_request_slot
*next
= slot
->next
;
1370 xmulti_remove_handle(slot
);
1371 curl_easy_cleanup(slot
->curl
);
1376 active_queue_head
= NULL
;
1378 curl_easy_cleanup(curl_default
);
1380 curl_multi_cleanup(curlm
);
1381 curl_global_cleanup();
1383 string_list_clear(&extra_http_headers
, 0);
1385 curl_slist_free_all(pragma_header
);
1386 pragma_header
= NULL
;
1388 curl_slist_free_all(host_resolutions
);
1389 host_resolutions
= NULL
;
1391 if (curl_http_proxy
) {
1392 free((void *)curl_http_proxy
);
1393 curl_http_proxy
= NULL
;
1396 if (proxy_auth
.password
) {
1397 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1398 FREE_AND_NULL(proxy_auth
.password
);
1401 free((void *)curl_proxyuserpwd
);
1402 curl_proxyuserpwd
= NULL
;
1404 free((void *)http_proxy_authmethod
);
1405 http_proxy_authmethod
= NULL
;
1407 if (cert_auth
.password
) {
1408 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1409 FREE_AND_NULL(cert_auth
.password
);
1411 ssl_cert_password_required
= 0;
1413 if (proxy_cert_auth
.password
) {
1414 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1415 FREE_AND_NULL(proxy_cert_auth
.password
);
1417 proxy_ssl_cert_password_required
= 0;
1419 FREE_AND_NULL(cached_accept_language
);
1422 struct active_request_slot
*get_active_slot(void)
1424 struct active_request_slot
*slot
= active_queue_head
;
1425 struct active_request_slot
*newslot
;
1429 /* Wait for a slot to open up if the queue is full */
1430 while (active_requests
>= max_requests
) {
1431 curl_multi_perform(curlm
, &num_transfers
);
1432 if (num_transfers
< active_requests
)
1433 process_curl_messages();
1436 while (slot
!= NULL
&& slot
->in_use
)
1440 newslot
= xmalloc(sizeof(*newslot
));
1441 newslot
->curl
= NULL
;
1442 newslot
->in_use
= 0;
1443 newslot
->next
= NULL
;
1445 slot
= active_queue_head
;
1447 active_queue_head
= newslot
;
1449 while (slot
->next
!= NULL
)
1451 slot
->next
= newslot
;
1457 slot
->curl
= curl_easy_duphandle(curl_default
);
1458 curl_session_count
++;
1463 slot
->results
= NULL
;
1464 slot
->finished
= NULL
;
1465 slot
->callback_data
= NULL
;
1466 slot
->callback_func
= NULL
;
1467 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1468 if (curl_save_cookies
)
1469 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1470 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1471 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1472 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1473 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1474 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1475 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1476 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1477 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDSIZE
, -1L);
1478 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1479 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1480 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1481 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1484 * Default following to off unless "ALWAYS" is configured; this gives
1485 * callers a sane starting point, and they can tweak for individual
1486 * HTTP_FOLLOW_* cases themselves.
1488 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1489 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1491 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1493 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1494 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1495 if (http_auth
.password
|| http_auth
.credential
|| curl_empty_auth_enabled())
1496 init_curl_http_auth(slot
->curl
);
1501 int start_active_slot(struct active_request_slot
*slot
)
1503 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1506 if (curlm_result
!= CURLM_OK
&&
1507 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1508 warning("curl_multi_add_handle failed: %s",
1509 curl_multi_strerror(curlm_result
));
1516 * We know there must be something to do, since we just added
1519 curl_multi_perform(curlm
, &num_transfers
);
1525 int (*fill
)(void *);
1526 struct fill_chain
*next
;
1529 static struct fill_chain
*fill_cfg
;
1531 void add_fill_function(void *data
, int (*fill
)(void *))
1533 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1534 struct fill_chain
**linkp
= &fill_cfg
;
1535 new_fill
->data
= data
;
1536 new_fill
->fill
= fill
;
1537 new_fill
->next
= NULL
;
1539 linkp
= &(*linkp
)->next
;
1543 void fill_active_slots(void)
1545 struct active_request_slot
*slot
= active_queue_head
;
1547 while (active_requests
< max_requests
) {
1548 struct fill_chain
*fill
;
1549 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1550 if (fill
->fill(fill
->data
))
1557 while (slot
!= NULL
) {
1558 if (!slot
->in_use
&& slot
->curl
!= NULL
1559 && curl_session_count
> min_curl_sessions
) {
1560 curl_easy_cleanup(slot
->curl
);
1562 curl_session_count
--;
1568 void step_active_slots(void)
1571 CURLMcode curlm_result
;
1574 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1575 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1576 if (num_transfers
< active_requests
) {
1577 process_curl_messages();
1578 fill_active_slots();
1582 void run_active_slot(struct active_request_slot
*slot
)
1588 struct timeval select_timeout
;
1591 slot
->finished
= &finished
;
1593 step_active_slots();
1597 curl_multi_timeout(curlm
, &curl_timeout
);
1598 if (curl_timeout
== 0) {
1600 } else if (curl_timeout
== -1) {
1601 select_timeout
.tv_sec
= 0;
1602 select_timeout
.tv_usec
= 50000;
1604 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1605 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1612 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1615 * It can happen that curl_multi_timeout returns a pathologically
1616 * long timeout when curl_multi_fdset returns no file descriptors
1617 * to read. See commit message for more details.
1620 (select_timeout
.tv_sec
> 0 ||
1621 select_timeout
.tv_usec
> 50000)) {
1622 select_timeout
.tv_sec
= 0;
1623 select_timeout
.tv_usec
= 50000;
1626 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1631 * The value of slot->finished we set before the loop was used
1632 * to set our "finished" variable when our request completed.
1634 * 1. The slot may not have been reused for another requst
1635 * yet, in which case it still has &finished.
1637 * 2. The slot may already be in-use to serve another request,
1638 * which can further be divided into two cases:
1640 * (a) If call run_active_slot() hasn't been called for that
1641 * other request, slot->finished would have been cleared
1642 * by get_active_slot() and has NULL.
1644 * (b) If the request did call run_active_slot(), then the
1645 * call would have updated slot->finished at the beginning
1646 * of this function, and with the clearing of the member
1647 * below, we would find that slot->finished is now NULL.
1649 * In all cases, slot->finished has no useful information to
1650 * anybody at this point. Some compilers warn us for
1651 * attempting to smuggle a pointer that is about to become
1652 * invalid, i.e. &finished. We clear it here to assure them.
1654 slot
->finished
= NULL
;
1657 static void release_active_slot(struct active_request_slot
*slot
)
1659 closedown_active_slot(slot
);
1661 xmulti_remove_handle(slot
);
1662 if (curl_session_count
> min_curl_sessions
) {
1663 curl_easy_cleanup(slot
->curl
);
1665 curl_session_count
--;
1668 fill_active_slots();
1671 void finish_all_active_slots(void)
1673 struct active_request_slot
*slot
= active_queue_head
;
1675 while (slot
!= NULL
)
1677 run_active_slot(slot
);
1678 slot
= active_queue_head
;
1684 /* Helpers for modifying and creating URLs */
1685 static inline int needs_quote(int ch
)
1687 if (((ch
>= 'A') && (ch
<= 'Z'))
1688 || ((ch
>= 'a') && (ch
<= 'z'))
1689 || ((ch
>= '0') && (ch
<= '9'))
1697 static char *quote_ref_url(const char *base
, const char *ref
)
1699 struct strbuf buf
= STRBUF_INIT
;
1703 end_url_with_slash(&buf
, base
);
1705 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1706 if (needs_quote(ch
))
1707 strbuf_addf(&buf
, "%%%02x", ch
);
1709 strbuf_addch(&buf
, *cp
);
1711 return strbuf_detach(&buf
, NULL
);
1714 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1716 int only_two_digit_prefix
)
1718 end_url_with_slash(buf
, url
);
1720 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1721 if (!only_two_digit_prefix
)
1722 strbuf_addstr(buf
, hex
+ 2);
1725 char *get_remote_object_url(const char *url
, const char *hex
,
1726 int only_two_digit_prefix
)
1728 struct strbuf buf
= STRBUF_INIT
;
1729 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1730 return strbuf_detach(&buf
, NULL
);
1733 void normalize_curl_result(CURLcode
*result
, long http_code
,
1734 char *errorstr
, size_t errorlen
)
1737 * If we see a failing http code with CURLE_OK, we have turned off
1738 * FAILONERROR (to keep the server's custom error response), and should
1739 * translate the code into failure here.
1741 * Likewise, if we see a redirect (30x code), that means we turned off
1742 * redirect-following, and we should treat the result as an error.
1744 if (*result
== CURLE_OK
&& http_code
>= 300) {
1745 *result
= CURLE_HTTP_RETURNED_ERROR
;
1747 * Normally curl will already have put the "reason phrase"
1748 * from the server into curl_errorstr; unfortunately without
1749 * FAILONERROR it is lost, so we can give only the numeric
1752 xsnprintf(errorstr
, errorlen
,
1753 "The requested URL returned error: %ld",
1758 static int handle_curl_result(struct slot_results
*results
)
1760 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1761 curl_errorstr
, sizeof(curl_errorstr
));
1763 if (results
->curl_result
== CURLE_OK
) {
1764 credential_approve(&http_auth
);
1765 credential_approve(&proxy_auth
);
1766 credential_approve(&cert_auth
);
1768 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1770 * We can't tell from here whether it's a bad path, bad
1771 * certificate, bad password, or something else wrong
1772 * with the certificate. So we reject the credential to
1773 * avoid caching or saving a bad password.
1775 credential_reject(&cert_auth
);
1777 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1778 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1779 return HTTP_NOMATCHPUBLICKEY
;
1781 } else if (missing_target(results
))
1782 return HTTP_MISSING_TARGET
;
1783 else if (results
->http_code
== 401) {
1784 if ((http_auth
.username
&& http_auth
.password
) ||\
1785 (http_auth
.authtype
&& http_auth
.credential
)) {
1786 if (http_auth
.multistage
) {
1787 credential_clear_secrets(&http_auth
);
1790 credential_reject(&http_auth
);
1793 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1794 if (results
->auth_avail
) {
1795 http_auth_methods
&= results
->auth_avail
;
1796 http_auth_methods_restricted
= 1;
1801 if (results
->http_connectcode
== 407)
1802 credential_reject(&proxy_auth
);
1803 if (!curl_errorstr
[0])
1804 strlcpy(curl_errorstr
,
1805 curl_easy_strerror(results
->curl_result
),
1806 sizeof(curl_errorstr
));
1811 int run_one_slot(struct active_request_slot
*slot
,
1812 struct slot_results
*results
)
1814 slot
->results
= results
;
1815 if (!start_active_slot(slot
)) {
1816 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1817 "failed to start HTTP request");
1818 return HTTP_START_FAILED
;
1821 run_active_slot(slot
);
1822 return handle_curl_result(results
);
1825 struct curl_slist
*http_copy_default_headers(void)
1827 struct curl_slist
*headers
= NULL
;
1828 const struct string_list_item
*item
;
1830 for_each_string_list_item(item
, &extra_http_headers
)
1831 headers
= curl_slist_append(headers
, item
->string
);
1836 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1842 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1844 strbuf_addstr(buf
, ptr
);
1849 * Check for and extract a content-type parameter. "raw"
1850 * should be positioned at the start of the potential
1851 * parameter, with any whitespace already removed.
1853 * "name" is the name of the parameter. The value is appended
1856 static int extract_param(const char *raw
, const char *name
,
1859 size_t len
= strlen(name
);
1861 if (strncasecmp(raw
, name
, len
))
1869 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1870 strbuf_addch(out
, *raw
++);
1875 * Extract a normalized version of the content type, with any
1876 * spaces suppressed, all letters lowercased, and no trailing ";"
1879 * Note that we will silently remove even invalid whitespace. For
1880 * example, "text / plain" is specifically forbidden by RFC 2616,
1881 * but "text/plain" is the only reasonable output, and this keeps
1884 * If the "charset" argument is not NULL, store the value of any
1885 * charset parameter there.
1888 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1889 * "text / plain" -> "text/plain"
1891 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1892 struct strbuf
*charset
)
1897 strbuf_grow(type
, raw
->len
);
1898 for (p
= raw
->buf
; *p
; p
++) {
1905 strbuf_addch(type
, tolower(*p
));
1911 strbuf_reset(charset
);
1913 while (isspace(*p
) || *p
== ';')
1915 if (!extract_param(p
, "charset", charset
))
1917 while (*p
&& !isspace(*p
))
1921 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1922 strbuf_addstr(charset
, "ISO-8859-1");
1925 static void write_accept_language(struct strbuf
*buf
)
1928 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1929 * that, q-value will be smaller than 0.001, the minimum q-value the
1930 * HTTP specification allows. See
1931 * https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.1 for q-value.
1933 const int MAX_DECIMAL_PLACES
= 3;
1934 const int MAX_LANGUAGE_TAGS
= 1000;
1935 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1936 char **language_tags
= NULL
;
1938 const char *s
= get_preferred_languages();
1940 struct strbuf tag
= STRBUF_INIT
;
1942 /* Don't add Accept-Language header if no language is preferred. */
1947 * Split the colon-separated string of preferred languages into
1948 * language_tags array.
1951 /* collect language tag */
1952 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1953 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1955 /* skip .codeset, @modifier and any other unnecessary parts */
1956 while (*s
&& *s
!= ':')
1961 REALLOC_ARRAY(language_tags
, num_langs
);
1962 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1963 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1968 /* write Accept-Language header into buf */
1970 int last_buf_len
= 0;
1976 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1977 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1979 /* compute decimal_places */
1980 for (max_q
= 1, decimal_places
= 0;
1981 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1982 decimal_places
++, max_q
*= 10)
1985 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1987 strbuf_addstr(buf
, "Accept-Language: ");
1989 for (i
= 0; i
< num_langs
; i
++) {
1991 strbuf_addstr(buf
, ", ");
1993 strbuf_addstr(buf
, language_tags
[i
]);
1996 strbuf_addf(buf
, q_format
, max_q
- i
);
1998 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1999 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
2003 last_buf_len
= buf
->len
;
2007 /* free language tags -- last one is a static '*' */
2008 for (i
= 0; i
< num_langs
- 1; i
++)
2009 free(language_tags
[i
]);
2010 free(language_tags
);
2014 * Get an Accept-Language header which indicates user's preferred languages.
2018 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
2019 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
2020 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
2021 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
2022 * LANGUAGE= LANG=C -> ""
2024 const char *http_get_accept_language_header(void)
2026 if (!cached_accept_language
) {
2027 struct strbuf buf
= STRBUF_INIT
;
2028 write_accept_language(&buf
);
2030 cached_accept_language
= strbuf_detach(&buf
, NULL
);
2033 return cached_accept_language
;
2036 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
2039 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
2040 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
2043 /* http_request() targets */
2044 #define HTTP_REQUEST_STRBUF 0
2045 #define HTTP_REQUEST_FILE 1
2047 static int http_request(const char *url
,
2048 void *result
, int target
,
2049 const struct http_get_options
*options
)
2051 struct active_request_slot
*slot
;
2052 struct slot_results results
;
2053 struct curl_slist
*headers
= http_copy_default_headers();
2054 struct strbuf buf
= STRBUF_INIT
;
2055 const char *accept_language
;
2058 slot
= get_active_slot();
2059 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
2062 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
2064 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
2065 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
2067 if (target
== HTTP_REQUEST_FILE
) {
2068 off_t posn
= ftello(result
);
2069 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2072 http_opt_request_remainder(slot
->curl
, posn
);
2074 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2078 curl_easy_setopt(slot
->curl
, CURLOPT_HEADERFUNCTION
, fwrite_wwwauth
);
2080 accept_language
= http_get_accept_language_header();
2082 if (accept_language
)
2083 headers
= curl_slist_append(headers
, accept_language
);
2085 strbuf_addstr(&buf
, "Pragma:");
2086 if (options
&& options
->no_cache
)
2087 strbuf_addstr(&buf
, " no-cache");
2088 if (options
&& options
->initial_request
&&
2089 http_follow_config
== HTTP_FOLLOW_INITIAL
)
2090 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
2092 headers
= curl_slist_append(headers
, buf
.buf
);
2094 /* Add additional headers here */
2095 if (options
&& options
->extra_headers
) {
2096 const struct string_list_item
*item
;
2097 if (options
&& options
->extra_headers
) {
2098 for_each_string_list_item(item
, options
->extra_headers
) {
2099 headers
= curl_slist_append(headers
, item
->string
);
2104 headers
= http_append_auth_header(&http_auth
, headers
);
2106 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
2107 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
2108 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
2109 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
2111 ret
= run_one_slot(slot
, &results
);
2113 if (options
&& options
->content_type
) {
2114 struct strbuf raw
= STRBUF_INIT
;
2115 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
2116 extract_content_type(&raw
, options
->content_type
,
2118 strbuf_release(&raw
);
2121 if (options
&& options
->effective_url
)
2122 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
2123 options
->effective_url
);
2125 curl_slist_free_all(headers
);
2126 strbuf_release(&buf
);
2132 * Update the "base" url to a more appropriate value, as deduced by
2133 * redirects seen when requesting a URL starting with "url".
2135 * The "asked" parameter is a URL that we asked curl to access, and must begin
2138 * The "got" parameter is the URL that curl reported to us as where we ended
2141 * Returns 1 if we updated the base url, 0 otherwise.
2143 * Our basic strategy is to compare "base" and "asked" to find the bits
2144 * specific to our request. We then strip those bits off of "got" to yield the
2145 * new base. So for example, if our base is "http://example.com/foo.git",
2146 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2147 * with "https://other.example.com/foo.git/info/refs". We would want the
2148 * new URL to become "https://other.example.com/foo.git".
2150 * Note that this assumes a sane redirect scheme. It's entirely possible
2151 * in the example above to end up at a URL that does not even end in
2152 * "info/refs". In such a case we die. There's not much we can do, such a
2153 * scheme is unlikely to represent a real git repository, and failing to
2154 * rewrite the base opens options for malicious redirects to do funny things.
2156 static int update_url_from_redirect(struct strbuf
*base
,
2158 const struct strbuf
*got
)
2163 if (!strcmp(asked
, got
->buf
))
2166 if (!skip_prefix(asked
, base
->buf
, &tail
))
2167 BUG("update_url_from_redirect: %s is not a superset of %s",
2171 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
2172 die(_("unable to update url base from redirection:\n"
2178 strbuf_add(base
, got
->buf
, new_len
);
2183 static int http_request_reauth(const char *url
,
2184 void *result
, int target
,
2185 struct http_get_options
*options
)
2188 int ret
= http_request(url
, result
, target
, options
);
2190 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2193 if (options
&& options
->effective_url
&& options
->base_url
) {
2194 if (update_url_from_redirect(options
->base_url
,
2195 url
, options
->effective_url
)) {
2196 credential_from_url(&http_auth
, options
->base_url
->buf
);
2197 url
= options
->effective_url
->buf
;
2201 while (ret
== HTTP_REAUTH
&& --i
) {
2203 * The previous request may have put cruft into our output stream; we
2204 * should clear it out before making our next request.
2207 case HTTP_REQUEST_STRBUF
:
2208 strbuf_reset(result
);
2210 case HTTP_REQUEST_FILE
:
2211 if (fflush(result
)) {
2212 error_errno("unable to flush a file");
2213 return HTTP_START_FAILED
;
2216 if (ftruncate(fileno(result
), 0) < 0) {
2217 error_errno("unable to truncate a file");
2218 return HTTP_START_FAILED
;
2222 BUG("Unknown http_request target");
2225 credential_fill(&http_auth
, 1);
2227 ret
= http_request(url
, result
, target
, options
);
2232 int http_get_strbuf(const char *url
,
2233 struct strbuf
*result
,
2234 struct http_get_options
*options
)
2236 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2240 * Downloads a URL and stores the result in the given file.
2242 * If a previous interrupted download is detected (i.e. a previous temporary
2243 * file is still around) the download is resumed.
2245 int http_get_file(const char *url
, const char *filename
,
2246 struct http_get_options
*options
)
2249 struct strbuf tmpfile
= STRBUF_INIT
;
2252 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2253 result
= fopen(tmpfile
.buf
, "a");
2255 error("Unable to open local file %s", tmpfile
.buf
);
2260 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2263 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2266 strbuf_release(&tmpfile
);
2270 int http_fetch_ref(const char *base
, struct ref
*ref
)
2272 struct http_get_options options
= {0};
2274 struct strbuf buffer
= STRBUF_INIT
;
2277 options
.no_cache
= 1;
2279 url
= quote_ref_url(base
, ref
->name
);
2280 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2281 strbuf_rtrim(&buffer
);
2282 if (buffer
.len
== the_hash_algo
->hexsz
)
2283 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2284 else if (starts_with(buffer
.buf
, "ref: ")) {
2285 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2290 strbuf_release(&buffer
);
2295 /* Helpers for fetching packs */
2296 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2299 struct strbuf buf
= STRBUF_INIT
;
2301 if (http_is_verbose
)
2302 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2304 end_url_with_slash(&buf
, base_url
);
2305 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2306 url
= strbuf_detach(&buf
, NULL
);
2308 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2309 tmp
= strbuf_detach(&buf
, NULL
);
2311 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2312 error("Unable to get pack index %s", url
);
2320 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2321 unsigned char *sha1
, const char *base_url
)
2323 struct packed_git
*new_pack
;
2324 char *tmp_idx
= NULL
;
2327 if (has_pack_index(sha1
)) {
2328 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2330 return -1; /* parse_pack_index() already issued error message */
2334 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2338 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2343 return -1; /* parse_pack_index() already issued error message */
2346 ret
= verify_pack_index(new_pack
);
2348 close_pack_index(new_pack
);
2349 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2356 new_pack
->next
= *packs_head
;
2357 *packs_head
= new_pack
;
2361 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2363 struct http_get_options options
= {0};
2367 struct strbuf buf
= STRBUF_INIT
;
2368 struct object_id oid
;
2370 end_url_with_slash(&buf
, base_url
);
2371 strbuf_addstr(&buf
, "objects/info/packs");
2372 url
= strbuf_detach(&buf
, NULL
);
2374 options
.no_cache
= 1;
2375 ret
= http_get_strbuf(url
, &buf
, &options
);
2381 if (skip_prefix(data
, "P pack-", &data
) &&
2382 !parse_oid_hex(data
, &oid
, &data
) &&
2383 skip_prefix(data
, ".pack", &data
) &&
2384 (*data
== '\n' || *data
== '\0')) {
2385 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2387 data
= strchrnul(data
, '\n');
2390 data
++; /* skip past newline */
2398 void release_http_pack_request(struct http_pack_request
*preq
)
2400 if (preq
->packfile
) {
2401 fclose(preq
->packfile
);
2402 preq
->packfile
= NULL
;
2405 strbuf_release(&preq
->tmpfile
);
2406 curl_slist_free_all(preq
->headers
);
2411 static const char *default_index_pack_args
[] =
2412 {"index-pack", "--stdin", NULL
};
2414 int finish_http_pack_request(struct http_pack_request
*preq
)
2416 struct child_process ip
= CHILD_PROCESS_INIT
;
2420 fclose(preq
->packfile
);
2421 preq
->packfile
= NULL
;
2423 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2427 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2428 preq
->index_pack_args
:
2429 default_index_pack_args
);
2431 if (preq
->preserve_index_pack_stdout
)
2436 if (run_command(&ip
)) {
2443 unlink(preq
->tmpfile
.buf
);
2447 void http_install_packfile(struct packed_git
*p
,
2448 struct packed_git
**list_to_remove_from
)
2450 struct packed_git
**lst
= list_to_remove_from
;
2453 lst
= &((*lst
)->next
);
2454 *lst
= (*lst
)->next
;
2456 install_packed_git(the_repository
, p
);
2459 struct http_pack_request
*new_http_pack_request(
2460 const unsigned char *packed_git_hash
, const char *base_url
) {
2462 struct strbuf buf
= STRBUF_INIT
;
2464 end_url_with_slash(&buf
, base_url
);
2465 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2466 hash_to_hex(packed_git_hash
));
2467 return new_direct_http_pack_request(packed_git_hash
,
2468 strbuf_detach(&buf
, NULL
));
2471 struct http_pack_request
*new_direct_http_pack_request(
2472 const unsigned char *packed_git_hash
, char *url
)
2474 off_t prev_posn
= 0;
2475 struct http_pack_request
*preq
;
2477 CALLOC_ARRAY(preq
, 1);
2478 strbuf_init(&preq
->tmpfile
, 0);
2482 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2483 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2484 if (!preq
->packfile
) {
2485 error("Unable to open local file %s for pack",
2490 preq
->slot
= get_active_slot();
2491 preq
->headers
= object_request_headers();
2492 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2493 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2494 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2495 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
, preq
->headers
);
2498 * If there is data present from a previous transfer attempt,
2499 * resume where it left off
2501 prev_posn
= ftello(preq
->packfile
);
2503 if (http_is_verbose
)
2505 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2506 hash_to_hex(packed_git_hash
),
2507 (uintmax_t)prev_posn
);
2508 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2514 strbuf_release(&preq
->tmpfile
);
2520 /* Helpers for fetching objects (loose) */
2521 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2524 unsigned char expn
[4096];
2525 size_t size
= eltsize
* nmemb
;
2527 struct http_object_request
*freq
= data
;
2528 struct active_request_slot
*slot
= freq
->slot
;
2531 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2534 BUG("curl_easy_getinfo for HTTP code failed: %s",
2535 curl_easy_strerror(c
));
2536 if (slot
->http_code
>= 300)
2541 ssize_t retval
= xwrite(freq
->localfile
,
2542 (char *) ptr
+ posn
, size
- posn
);
2544 return posn
/ eltsize
;
2546 } while (posn
< size
);
2548 freq
->stream
.avail_in
= size
;
2549 freq
->stream
.next_in
= (void *)ptr
;
2551 freq
->stream
.next_out
= expn
;
2552 freq
->stream
.avail_out
= sizeof(expn
);
2553 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2554 the_hash_algo
->update_fn(&freq
->c
, expn
,
2555 sizeof(expn
) - freq
->stream
.avail_out
);
2556 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2560 struct http_object_request
*new_http_object_request(const char *base_url
,
2561 const struct object_id
*oid
)
2563 char *hex
= oid_to_hex(oid
);
2564 struct strbuf filename
= STRBUF_INIT
;
2565 struct strbuf prevfile
= STRBUF_INIT
;
2567 char prev_buf
[PREV_BUF_SIZE
];
2568 ssize_t prev_read
= 0;
2569 off_t prev_posn
= 0;
2570 struct http_object_request
*freq
;
2572 CALLOC_ARRAY(freq
, 1);
2573 strbuf_init(&freq
->tmpfile
, 0);
2574 oidcpy(&freq
->oid
, oid
);
2575 freq
->localfile
= -1;
2577 loose_object_path(the_repository
, &filename
, oid
);
2578 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2580 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2581 unlink_or_warn(prevfile
.buf
);
2582 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2583 unlink_or_warn(freq
->tmpfile
.buf
);
2584 strbuf_release(&filename
);
2586 if (freq
->localfile
!= -1)
2587 error("fd leakage in start: %d", freq
->localfile
);
2588 freq
->localfile
= open(freq
->tmpfile
.buf
,
2589 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2591 * This could have failed due to the "lazy directory creation";
2592 * try to mkdir the last path component.
2594 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2595 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2598 mkdir(freq
->tmpfile
.buf
, 0777);
2601 freq
->localfile
= open(freq
->tmpfile
.buf
,
2602 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2605 if (freq
->localfile
< 0) {
2606 error_errno("Couldn't create temporary file %s",
2611 git_inflate_init(&freq
->stream
);
2613 the_hash_algo
->init_fn(&freq
->c
);
2615 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2618 * If a previous temp file is present, process what was already
2621 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2622 if (prevlocal
!= -1) {
2624 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2626 if (fwrite_sha1_file(prev_buf
,
2629 freq
) == prev_read
) {
2630 prev_posn
+= prev_read
;
2635 } while (prev_read
> 0);
2638 unlink_or_warn(prevfile
.buf
);
2639 strbuf_release(&prevfile
);
2642 * Reset inflate/SHA1 if there was an error reading the previous temp
2643 * file; also rewind to the beginning of the local file.
2645 if (prev_read
== -1) {
2646 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2647 git_inflate_init(&freq
->stream
);
2648 the_hash_algo
->init_fn(&freq
->c
);
2651 lseek(freq
->localfile
, 0, SEEK_SET
);
2652 if (ftruncate(freq
->localfile
, 0) < 0) {
2653 error_errno("Couldn't truncate temporary file %s",
2660 freq
->slot
= get_active_slot();
2661 freq
->headers
= object_request_headers();
2663 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2664 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2665 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2666 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2667 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2668 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, freq
->headers
);
2671 * If we have successfully processed data from a previous fetch
2672 * attempt, only fetch the data we don't already have.
2675 if (http_is_verbose
)
2677 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2678 hex
, (uintmax_t)prev_posn
);
2679 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2685 strbuf_release(&prevfile
);
2691 void process_http_object_request(struct http_object_request
*freq
)
2695 freq
->curl_result
= freq
->slot
->curl_result
;
2696 freq
->http_code
= freq
->slot
->http_code
;
2700 int finish_http_object_request(struct http_object_request
*freq
)
2703 struct strbuf filename
= STRBUF_INIT
;
2705 close(freq
->localfile
);
2706 freq
->localfile
= -1;
2708 process_http_object_request(freq
);
2710 if (freq
->http_code
== 416) {
2711 warning("requested range invalid; we may already have all the data.");
2712 } else if (freq
->curl_result
!= CURLE_OK
) {
2713 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2714 if (st
.st_size
== 0)
2715 unlink_or_warn(freq
->tmpfile
.buf
);
2719 git_inflate_end(&freq
->stream
);
2720 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2721 if (freq
->zret
!= Z_STREAM_END
) {
2722 unlink_or_warn(freq
->tmpfile
.buf
);
2725 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2726 unlink_or_warn(freq
->tmpfile
.buf
);
2729 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2730 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2731 strbuf_release(&filename
);
2733 return freq
->rename
;
2736 void abort_http_object_request(struct http_object_request
*freq
)
2738 unlink_or_warn(freq
->tmpfile
.buf
);
2740 release_http_object_request(freq
);
2743 void release_http_object_request(struct http_object_request
*freq
)
2745 if (freq
->localfile
!= -1) {
2746 close(freq
->localfile
);
2747 freq
->localfile
= -1;
2749 FREE_AND_NULL(freq
->url
);
2751 freq
->slot
->callback_func
= NULL
;
2752 freq
->slot
->callback_data
= NULL
;
2753 release_active_slot(freq
->slot
);
2756 curl_slist_free_all(freq
->headers
);
2757 strbuf_release(&freq
->tmpfile
);