1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
8 #include "run-command.h"
11 #include "credential.h"
16 #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 const char *curl_http_version
= NULL
;
44 static const char *ssl_cert
;
45 static const char *ssl_cert_type
;
46 static const char *ssl_cipherlist
;
47 static const 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
},
64 static const char *ssl_key
;
65 static const char *ssl_key_type
;
66 static const char *ssl_capath
;
67 static const char *curl_no_proxy
;
68 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
69 static const char *ssl_pinnedkey
;
71 static const 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 const char *curl_http_proxy
;
76 static const char *http_proxy_authmethod
;
78 static const char *http_proxy_ssl_cert
;
79 static const char *http_proxy_ssl_key
;
80 static const 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 const 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 static struct credential proxy_auth
= CREDENTIAL_INIT
;
112 static const char *curl_proxyuserpwd
;
113 static const char *curl_cookie_file
;
114 static int curl_save_cookies
;
115 struct credential http_auth
= CREDENTIAL_INIT
;
116 static int http_proactive_auth
;
117 static const char *user_agent
;
118 static int curl_empty_auth
= -1;
120 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
122 static struct credential cert_auth
= CREDENTIAL_INIT
;
123 static int ssl_cert_password_required
;
124 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
125 static int http_auth_methods_restricted
;
126 /* Modes for which empty_auth cannot actually help us. */
127 static unsigned long empty_auth_useless
=
132 static struct curl_slist
*pragma_header
;
133 static struct curl_slist
*no_pragma_header
;
134 static struct string_list extra_http_headers
= STRING_LIST_INIT_DUP
;
136 static struct curl_slist
*host_resolutions
;
138 static struct active_request_slot
*active_queue_head
;
140 static char *cached_accept_language
;
142 static char *http_ssl_backend
;
144 static int http_schannel_check_revoke
= 1;
146 * With the backend being set to `schannel`, setting sslCAinfo would override
147 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
150 static int http_schannel_use_ssl_cainfo
;
152 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
154 size_t size
= eltsize
* nmemb
;
155 struct buffer
*buffer
= buffer_
;
157 if (size
> buffer
->buf
.len
- buffer
->posn
)
158 size
= buffer
->buf
.len
- buffer
->posn
;
159 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
160 buffer
->posn
+= size
;
162 return size
/ eltsize
;
165 int seek_buffer(void *clientp
, curl_off_t offset
, int origin
)
167 struct buffer
*buffer
= clientp
;
169 if (origin
!= SEEK_SET
)
170 BUG("seek_buffer only handles SEEK_SET");
171 if (offset
< 0 || offset
>= buffer
->buf
.len
) {
172 error("curl seek would be outside of buffer");
173 return CURL_SEEKFUNC_FAIL
;
176 buffer
->posn
= offset
;
177 return CURL_SEEKFUNC_OK
;
180 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
182 size_t size
= eltsize
* nmemb
;
183 struct strbuf
*buffer
= buffer_
;
185 strbuf_add(buffer
, ptr
, size
);
190 * A folded header continuation line starts with any number of spaces or
191 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
192 * It is not a continuation line if the line starts with any other character.
194 static inline int is_hdr_continuation(const char *ptr
, const size_t size
)
196 return size
&& (*ptr
== ' ' || *ptr
== '\t');
199 static size_t fwrite_wwwauth(char *ptr
, size_t eltsize
, size_t nmemb
, void *p UNUSED
)
201 size_t size
= eltsize
* nmemb
;
202 struct strvec
*values
= &http_auth
.wwwauth_headers
;
203 struct strbuf buf
= STRBUF_INIT
;
208 * Header lines may not come NULL-terminated from libcurl so we must
209 * limit all scans to the maximum length of the header line, or leverage
210 * strbufs for all operations.
212 * In addition, it is possible that header values can be split over
213 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
214 * but older servers may still emit them. A continuation header field
215 * value is identified as starting with a space or horizontal tab.
217 * The formal definition of a header field as given in RFC 7230 is:
219 * header-field = field-name ":" OWS field-value OWS
222 * field-value = *( field-content / obs-fold )
223 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
224 * field-vchar = VCHAR / obs-text
226 * obs-fold = CRLF 1*( SP / HTAB )
227 * ; obsolete line folding
228 * ; see Section 3.2.4
231 /* Start of a new WWW-Authenticate header */
232 if (skip_iprefix_mem(ptr
, size
, "www-authenticate:", &val
, &val_len
)) {
233 strbuf_add(&buf
, val
, val_len
);
236 * Strip the CRLF that should be present at the end of each
237 * field as well as any trailing or leading whitespace from the
242 strvec_push(values
, buf
.buf
);
243 http_auth
.header_is_last_match
= 1;
248 * This line could be a continuation of the previously matched header
249 * field. If this is the case then we should append this value to the
250 * end of the previously consumed value.
252 if (http_auth
.header_is_last_match
&& is_hdr_continuation(ptr
, size
)) {
254 * Trim the CRLF and any leading or trailing from this line.
256 strbuf_add(&buf
, ptr
, size
);
260 * At this point we should always have at least one existing
261 * value, even if it is empty. Do not bother appending the new
262 * value if this continuation header is itself empty.
265 BUG("should have at least one existing header value");
266 } else if (buf
.len
) {
267 char *prev
= xstrdup(values
->v
[values
->nr
- 1]);
269 /* Join two non-empty values with a single space. */
270 const char *const sp
= *prev
? " " : "";
273 strvec_pushf(values
, "%s%s%s", prev
, sp
, buf
.buf
);
280 /* Not a continuation of a previously matched auth header line. */
281 http_auth
.header_is_last_match
= 0;
284 * If this is a HTTP status line and not a header field, this signals
285 * a different HTTP response. libcurl writes all the output of all
286 * response headers of all responses, including redirects.
287 * We only care about the last HTTP request response's headers so clear
288 * the existing array.
290 if (skip_iprefix_mem(ptr
, size
, "http/", &val
, &val_len
))
291 strvec_clear(values
);
294 strbuf_release(&buf
);
298 size_t fwrite_null(char *ptr UNUSED
, size_t eltsize UNUSED
, size_t nmemb
,
304 static void closedown_active_slot(struct active_request_slot
*slot
)
310 static void finish_active_slot(struct active_request_slot
*slot
)
312 closedown_active_slot(slot
);
313 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
316 (*slot
->finished
) = 1;
318 /* Store slot results so they can be read after the slot is reused */
320 slot
->results
->curl_result
= slot
->curl_result
;
321 slot
->results
->http_code
= slot
->http_code
;
322 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
323 &slot
->results
->auth_avail
);
325 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
326 &slot
->results
->http_connectcode
);
329 /* Run callback if appropriate */
330 if (slot
->callback_func
)
331 slot
->callback_func(slot
->callback_data
);
334 static void xmulti_remove_handle(struct active_request_slot
*slot
)
336 curl_multi_remove_handle(curlm
, slot
->curl
);
339 static void process_curl_messages(void)
342 struct active_request_slot
*slot
;
343 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
345 while (curl_message
!= NULL
) {
346 if (curl_message
->msg
== CURLMSG_DONE
) {
347 int curl_result
= curl_message
->data
.result
;
348 slot
= active_queue_head
;
349 while (slot
!= NULL
&&
350 slot
->curl
!= curl_message
->easy_handle
)
353 xmulti_remove_handle(slot
);
354 slot
->curl_result
= curl_result
;
355 finish_active_slot(slot
);
357 fprintf(stderr
, "Received DONE message for unknown request!\n");
360 fprintf(stderr
, "Unknown CURL message received: %d\n",
361 (int)curl_message
->msg
);
363 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
367 static int http_options(const char *var
, const char *value
,
368 const struct config_context
*ctx
, void *data
)
370 if (!strcmp("http.version", var
)) {
371 return git_config_string(&curl_http_version
, var
, value
);
373 if (!strcmp("http.sslverify", var
)) {
374 curl_ssl_verify
= git_config_bool(var
, value
);
377 if (!strcmp("http.sslcipherlist", var
))
378 return git_config_string(&ssl_cipherlist
, var
, value
);
379 if (!strcmp("http.sslversion", var
))
380 return git_config_string(&ssl_version
, var
, value
);
381 if (!strcmp("http.sslcert", var
))
382 return git_config_pathname(&ssl_cert
, var
, value
);
383 if (!strcmp("http.sslcerttype", var
))
384 return git_config_string(&ssl_cert_type
, var
, value
);
385 if (!strcmp("http.sslkey", var
))
386 return git_config_pathname(&ssl_key
, var
, value
);
387 if (!strcmp("http.sslkeytype", var
))
388 return git_config_string(&ssl_key_type
, var
, value
);
389 if (!strcmp("http.sslcapath", var
))
390 return git_config_pathname(&ssl_capath
, var
, value
);
391 if (!strcmp("http.sslcainfo", var
))
392 return git_config_pathname(&ssl_cainfo
, var
, value
);
393 if (!strcmp("http.sslcertpasswordprotected", var
)) {
394 ssl_cert_password_required
= git_config_bool(var
, value
);
397 if (!strcmp("http.ssltry", var
)) {
398 curl_ssl_try
= git_config_bool(var
, value
);
401 if (!strcmp("http.sslbackend", var
)) {
402 free(http_ssl_backend
);
403 http_ssl_backend
= xstrdup_or_null(value
);
407 if (!strcmp("http.schannelcheckrevoke", var
)) {
408 http_schannel_check_revoke
= git_config_bool(var
, value
);
412 if (!strcmp("http.schannelusesslcainfo", var
)) {
413 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
417 if (!strcmp("http.minsessions", var
)) {
418 min_curl_sessions
= git_config_int(var
, value
, ctx
->kvi
);
419 if (min_curl_sessions
> 1)
420 min_curl_sessions
= 1;
423 if (!strcmp("http.maxrequests", var
)) {
424 max_requests
= git_config_int(var
, value
, ctx
->kvi
);
427 if (!strcmp("http.lowspeedlimit", var
)) {
428 curl_low_speed_limit
= (long)git_config_int(var
, value
, ctx
->kvi
);
431 if (!strcmp("http.lowspeedtime", var
)) {
432 curl_low_speed_time
= (long)git_config_int(var
, value
, ctx
->kvi
);
436 if (!strcmp("http.noepsv", var
)) {
437 curl_ftp_no_epsv
= git_config_bool(var
, value
);
440 if (!strcmp("http.proxy", var
))
441 return git_config_string(&curl_http_proxy
, var
, value
);
443 if (!strcmp("http.proxyauthmethod", var
))
444 return git_config_string(&http_proxy_authmethod
, var
, value
);
446 if (!strcmp("http.proxysslcert", var
))
447 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
449 if (!strcmp("http.proxysslkey", var
))
450 return git_config_string(&http_proxy_ssl_key
, var
, value
);
452 if (!strcmp("http.proxysslcainfo", var
))
453 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
455 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
456 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
460 if (!strcmp("http.cookiefile", var
))
461 return git_config_pathname(&curl_cookie_file
, var
, value
);
462 if (!strcmp("http.savecookies", var
)) {
463 curl_save_cookies
= git_config_bool(var
, value
);
467 if (!strcmp("http.postbuffer", var
)) {
468 http_post_buffer
= git_config_ssize_t(var
, value
, ctx
->kvi
);
469 if (http_post_buffer
< 0)
470 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
471 if (http_post_buffer
< LARGE_PACKET_MAX
)
472 http_post_buffer
= LARGE_PACKET_MAX
;
476 if (!strcmp("http.useragent", var
))
477 return git_config_string(&user_agent
, var
, value
);
479 if (!strcmp("http.emptyauth", var
)) {
480 if (value
&& !strcmp("auto", value
))
481 curl_empty_auth
= -1;
483 curl_empty_auth
= git_config_bool(var
, value
);
487 if (!strcmp("http.delegation", var
)) {
488 #ifdef CURLGSSAPI_DELEGATION_FLAG
489 return git_config_string(&curl_deleg
, var
, value
);
491 warning(_("Delegation control is not supported with cURL < 7.22.0"));
496 if (!strcmp("http.pinnedpubkey", var
)) {
497 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
498 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
500 warning(_("Public key pinning not supported with cURL < 7.39.0"));
505 if (!strcmp("http.extraheader", var
)) {
507 return config_error_nonbool(var
);
508 } else if (!*value
) {
509 string_list_clear(&extra_http_headers
, 0);
511 string_list_append(&extra_http_headers
, value
);
516 if (!strcmp("http.curloptresolve", var
)) {
518 return config_error_nonbool(var
);
519 } else if (!*value
) {
520 curl_slist_free_all(host_resolutions
);
521 host_resolutions
= NULL
;
523 host_resolutions
= curl_slist_append(host_resolutions
, value
);
528 if (!strcmp("http.followredirects", var
)) {
529 if (value
&& !strcmp(value
, "initial"))
530 http_follow_config
= HTTP_FOLLOW_INITIAL
;
531 else if (git_config_bool(var
, value
))
532 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
534 http_follow_config
= HTTP_FOLLOW_NONE
;
538 /* Fall back on the default ones */
539 return git_default_config(var
, value
, ctx
, data
);
542 static int curl_empty_auth_enabled(void)
544 if (curl_empty_auth
>= 0)
545 return curl_empty_auth
;
548 * In the automatic case, kick in the empty-auth
549 * hack as long as we would potentially try some
550 * method more exotic than "Basic" or "Digest".
552 * But only do this when this is our second or
553 * subsequent request, as by then we know what
554 * methods are available.
556 if (http_auth_methods_restricted
&&
557 (http_auth_methods
& ~empty_auth_useless
))
562 static void init_curl_http_auth(CURL
*result
)
564 if (!http_auth
.username
|| !*http_auth
.username
) {
565 if (curl_empty_auth_enabled())
566 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
570 credential_fill(&http_auth
);
572 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
573 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
576 /* *var must be free-able */
577 static void var_override(const char **var
, char *value
)
581 *var
= xstrdup(value
);
585 static void set_proxyauth_name_password(CURL
*result
)
587 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
588 proxy_auth
.username
);
589 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
590 proxy_auth
.password
);
593 static void init_curl_proxy_auth(CURL
*result
)
595 if (proxy_auth
.username
) {
596 if (!proxy_auth
.password
)
597 credential_fill(&proxy_auth
);
598 set_proxyauth_name_password(result
);
601 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
603 if (http_proxy_authmethod
) {
605 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
606 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
607 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
608 proxy_authmethods
[i
].curlauth_param
);
612 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
613 warning("unsupported proxy authentication method %s: using anyauth",
614 http_proxy_authmethod
);
615 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
619 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
622 static int has_cert_password(void)
624 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
626 if (!cert_auth
.password
) {
627 cert_auth
.protocol
= xstrdup("cert");
628 cert_auth
.host
= xstrdup("");
629 cert_auth
.username
= xstrdup("");
630 cert_auth
.path
= xstrdup(ssl_cert
);
631 credential_fill(&cert_auth
);
636 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
637 static int has_proxy_cert_password(void)
639 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
641 if (!proxy_cert_auth
.password
) {
642 proxy_cert_auth
.protocol
= xstrdup("cert");
643 proxy_cert_auth
.host
= xstrdup("");
644 proxy_cert_auth
.username
= xstrdup("");
645 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
646 credential_fill(&proxy_cert_auth
);
652 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
653 static void set_curl_keepalive(CURL
*c
)
655 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
659 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
663 socklen_t len
= (socklen_t
)sizeof(ka
);
665 if (type
!= CURLSOCKTYPE_IPCXN
)
668 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
670 warning_errno("unable to set SO_KEEPALIVE on socket");
672 return CURL_SOCKOPT_OK
;
675 static void set_curl_keepalive(CURL
*c
)
677 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
681 /* Return 1 if redactions have been made, 0 otherwise. */
682 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
685 const char *sensitive_header
;
687 if (trace_curl_redact
&&
688 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
689 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
690 /* The first token is the type, which is OK to log */
691 while (isspace(*sensitive_header
))
693 while (*sensitive_header
&& !isspace(*sensitive_header
))
695 /* Everything else is opaque and possibly sensitive */
696 strbuf_setlen(header
, sensitive_header
- header
->buf
);
697 strbuf_addstr(header
, " <redacted>");
699 } else if (trace_curl_redact
&&
700 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
701 struct strbuf redacted_header
= STRBUF_INIT
;
704 while (isspace(*sensitive_header
))
707 cookie
= sensitive_header
;
711 char *semicolon
= strstr(cookie
, "; ");
714 equals
= strchrnul(cookie
, '=');
716 /* invalid cookie, just append and continue */
717 strbuf_addstr(&redacted_header
, cookie
);
720 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
721 strbuf_addstr(&redacted_header
, "=<redacted>");
724 * There are more cookies. (Or, for some
725 * reason, the input string ends in "; ".)
727 strbuf_addstr(&redacted_header
, "; ");
728 cookie
= semicolon
+ strlen("; ");
734 strbuf_setlen(header
, sensitive_header
- header
->buf
);
735 strbuf_addbuf(header
, &redacted_header
);
741 static int match_curl_h2_trace(const char *line
, const char **out
)
746 * curl prior to 8.1.0 gives us:
748 * h2h3 [<header-name>: <header-val>]
750 * Starting in 8.1.0, the first token became just "h2".
752 if (skip_iprefix(line
, "h2h3 [", out
) ||
753 skip_iprefix(line
, "h2 [", out
))
758 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
759 * where <stream-id> is numeric.
761 if (skip_iprefix(line
, "[HTTP/2] [", &p
)) {
764 if (skip_prefix(p
, "] [", out
))
771 /* Redact headers in info */
772 static void redact_sensitive_info_header(struct strbuf
*header
)
774 const char *sensitive_header
;
776 if (trace_curl_redact
&&
777 match_curl_h2_trace(header
->buf
, &sensitive_header
)) {
778 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
779 /* redaction ate our closing bracket */
780 strbuf_addch(header
, ']');
785 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
787 struct strbuf out
= STRBUF_INIT
;
788 struct strbuf
**headers
, **header
;
790 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
791 text
, (long)size
, (long)size
);
792 trace_strbuf(&trace_curl
, &out
);
794 strbuf_add(&out
, ptr
, size
);
795 headers
= strbuf_split_max(&out
, '\n', 0);
797 for (header
= headers
; *header
; header
++) {
798 if (hide_sensitive_header
)
799 redact_sensitive_header(*header
, 0);
800 strbuf_insertstr((*header
), 0, text
);
801 strbuf_insertstr((*header
), strlen(text
), ": ");
802 strbuf_rtrim((*header
));
803 strbuf_addch((*header
), '\n');
804 trace_strbuf(&trace_curl
, (*header
));
806 strbuf_list_free(headers
);
807 strbuf_release(&out
);
810 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
813 struct strbuf out
= STRBUF_INIT
;
814 unsigned int width
= 60;
816 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
817 text
, (long)size
, (long)size
);
818 trace_strbuf(&trace_curl
, &out
);
820 for (i
= 0; i
< size
; i
+= width
) {
824 strbuf_addf(&out
, "%s: ", text
);
825 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
826 unsigned char ch
= ptr
[i
+ w
];
829 (ch
>= 0x20) && (ch
< 0x80)
832 strbuf_addch(&out
, '\n');
833 trace_strbuf(&trace_curl
, &out
);
835 strbuf_release(&out
);
838 static void curl_dump_info(char *data
, size_t size
)
840 struct strbuf buf
= STRBUF_INIT
;
842 strbuf_add(&buf
, data
, size
);
844 redact_sensitive_info_header(&buf
);
845 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
847 strbuf_release(&buf
);
850 static int curl_trace(CURL
*handle UNUSED
, curl_infotype type
,
851 char *data
, size_t size
,
855 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
859 curl_dump_info(data
, size
);
861 case CURLINFO_HEADER_OUT
:
862 text
= "=> Send header";
863 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
865 case CURLINFO_DATA_OUT
:
866 if (trace_curl_data
) {
867 text
= "=> Send data";
868 curl_dump_data(text
, (unsigned char *)data
, size
);
871 case CURLINFO_SSL_DATA_OUT
:
872 if (trace_curl_data
) {
873 text
= "=> Send SSL data";
874 curl_dump_data(text
, (unsigned char *)data
, size
);
877 case CURLINFO_HEADER_IN
:
878 text
= "<= Recv header";
879 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
881 case CURLINFO_DATA_IN
:
882 if (trace_curl_data
) {
883 text
= "<= Recv data";
884 curl_dump_data(text
, (unsigned char *)data
, size
);
887 case CURLINFO_SSL_DATA_IN
:
888 if (trace_curl_data
) {
889 text
= "<= Recv SSL data";
890 curl_dump_data(text
, (unsigned char *)data
, size
);
894 default: /* we ignore unknown types by default */
900 void http_trace_curl_no_data(void)
902 trace_override_envvar(&trace_curl
, "1");
906 void setup_curl_trace(CURL
*handle
)
908 if (!trace_want(&trace_curl
))
910 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
911 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
912 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
915 static void proto_list_append(struct strbuf
*list
, const char *proto
)
920 strbuf_addch(list
, ',');
921 strbuf_addstr(list
, proto
);
924 static long get_curl_allowed_protocols(int from_user
, struct strbuf
*list
)
928 if (is_transport_allowed("http", from_user
)) {
929 bits
|= CURLPROTO_HTTP
;
930 proto_list_append(list
, "http");
932 if (is_transport_allowed("https", from_user
)) {
933 bits
|= CURLPROTO_HTTPS
;
934 proto_list_append(list
, "https");
936 if (is_transport_allowed("ftp", from_user
)) {
937 bits
|= CURLPROTO_FTP
;
938 proto_list_append(list
, "ftp");
940 if (is_transport_allowed("ftps", from_user
)) {
941 bits
|= CURLPROTO_FTPS
;
942 proto_list_append(list
, "ftps");
948 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
949 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
956 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
957 { "HTTP/2", CURL_HTTP_VERSION_2
}
960 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
961 if (!strcmp(version_string
, choice
[i
].name
)) {
962 *opt
= choice
[i
].opt_token
;
967 warning("unknown value given to http.version: '%s'", version_string
);
968 return -1; /* not found */
973 static CURL
*get_curl_handle(void)
975 CURL
*result
= curl_easy_init();
978 die("curl_easy_init failed");
980 if (!curl_ssl_verify
) {
981 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
982 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
984 /* Verify authenticity of the peer's certificate */
985 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
986 /* The name in the cert must match whom we tried to connect */
987 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
990 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
991 if (curl_http_version
) {
993 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
994 /* Set request use http version */
995 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
1000 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
1001 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
1003 #ifdef CURLGSSAPI_DELEGATION_FLAG
1006 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
1007 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
1008 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
1009 curl_deleg_levels
[i
].curl_deleg_param
);
1013 if (i
== ARRAY_SIZE(curl_deleg_levels
))
1014 warning("Unknown delegation method '%s': using default",
1019 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1020 !http_schannel_check_revoke
) {
1021 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
1022 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
1024 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
1028 if (http_proactive_auth
)
1029 init_curl_http_auth(result
);
1031 if (getenv("GIT_SSL_VERSION"))
1032 ssl_version
= getenv("GIT_SSL_VERSION");
1033 if (ssl_version
&& *ssl_version
) {
1035 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
1036 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
1037 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
1038 sslversions
[i
].ssl_version
);
1042 if (i
== ARRAY_SIZE(sslversions
))
1043 warning("unsupported ssl version %s: using default",
1047 if (getenv("GIT_SSL_CIPHER_LIST"))
1048 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
1049 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
1050 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
1054 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
1056 curl_easy_setopt(result
, CURLOPT_SSLCERTTYPE
, ssl_cert_type
);
1057 if (has_cert_password())
1058 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
1060 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
1062 curl_easy_setopt(result
, CURLOPT_SSLKEYTYPE
, ssl_key_type
);
1064 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
1065 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1067 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
1069 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1070 !http_schannel_use_ssl_cainfo
) {
1071 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
1072 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1073 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
1075 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
1077 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
1078 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1079 if (http_proxy_ssl_ca_info
)
1080 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
1084 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
1085 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
1086 curl_low_speed_limit
);
1087 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
1088 curl_low_speed_time
);
1091 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
1092 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
1094 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1096 struct strbuf buf
= STRBUF_INIT
;
1098 get_curl_allowed_protocols(0, &buf
);
1099 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS_STR
, buf
.buf
);
1102 get_curl_allowed_protocols(-1, &buf
);
1103 curl_easy_setopt(result
, CURLOPT_PROTOCOLS_STR
, buf
.buf
);
1104 strbuf_release(&buf
);
1107 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
1108 get_curl_allowed_protocols(0, NULL
));
1109 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
1110 get_curl_allowed_protocols(-1, NULL
));
1113 if (getenv("GIT_CURL_VERBOSE"))
1114 http_trace_curl_no_data();
1115 setup_curl_trace(result
);
1116 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1117 trace_curl_data
= 0;
1118 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1119 trace_curl_redact
= 0;
1121 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
1122 user_agent
? user_agent
: git_user_agent());
1124 if (curl_ftp_no_epsv
)
1125 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
1128 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
1131 * CURL also examines these variables as a fallback; but we need to query
1132 * them here in order to decide whether to prompt for missing password (cf.
1133 * init_curl_proxy_auth()).
1135 * Unlike many other common environment variables, these are historically
1136 * lowercase only. It appears that CURL did not know this and implemented
1137 * only uppercase variants, which was later corrected to take both - with
1138 * the exception of http_proxy, which is lowercase only also in CURL. As
1139 * the lowercase versions are the historical quasi-standard, they take
1140 * precedence here, as in CURL.
1142 if (!curl_http_proxy
) {
1143 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
1144 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
1145 var_override(&curl_http_proxy
, getenv("https_proxy"));
1147 var_override(&curl_http_proxy
, getenv("http_proxy"));
1149 if (!curl_http_proxy
) {
1150 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
1151 var_override(&curl_http_proxy
, getenv("all_proxy"));
1155 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1157 * Handle case with the empty http.proxy value here to keep
1158 * common code clean.
1159 * NB: empty option disables proxying at all.
1161 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1162 } else if (curl_http_proxy
) {
1163 if (starts_with(curl_http_proxy
, "socks5h"))
1164 curl_easy_setopt(result
,
1165 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1166 else if (starts_with(curl_http_proxy
, "socks5"))
1167 curl_easy_setopt(result
,
1168 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1169 else if (starts_with(curl_http_proxy
, "socks4a"))
1170 curl_easy_setopt(result
,
1171 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1172 else if (starts_with(curl_http_proxy
, "socks"))
1173 curl_easy_setopt(result
,
1174 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1175 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1176 else if (starts_with(curl_http_proxy
, "https")) {
1177 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1179 if (http_proxy_ssl_cert
)
1180 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1182 if (http_proxy_ssl_key
)
1183 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1185 if (has_proxy_cert_password())
1186 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1189 if (strstr(curl_http_proxy
, "://"))
1190 credential_from_url(&proxy_auth
, curl_http_proxy
);
1192 struct strbuf url
= STRBUF_INIT
;
1193 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1194 credential_from_url(&proxy_auth
, url
.buf
);
1195 strbuf_release(&url
);
1198 if (!proxy_auth
.host
)
1199 die("Invalid proxy URL '%s'", curl_http_proxy
);
1201 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1202 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1203 var_override(&curl_no_proxy
, getenv("no_proxy"));
1204 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1206 init_curl_proxy_auth(result
);
1208 set_curl_keepalive(result
);
1213 static void set_from_env(const char **var
, const char *envname
)
1215 const char *val
= getenv(envname
);
1220 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1222 char *low_speed_limit
;
1223 char *low_speed_time
;
1224 char *normalized_url
;
1225 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1227 config
.section
= "http";
1229 config
.collect_fn
= http_options
;
1230 config
.cascade_fn
= git_default_config
;
1233 http_is_verbose
= 0;
1234 normalized_url
= url_normalize(url
, &config
.url
);
1236 git_config(urlmatch_config_entry
, &config
);
1237 free(normalized_url
);
1238 string_list_clear(&config
.vars
, 1);
1240 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1241 if (http_ssl_backend
) {
1242 const curl_ssl_backend
**backends
;
1243 struct strbuf buf
= STRBUF_INIT
;
1246 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1247 case CURLSSLSET_UNKNOWN_BACKEND
:
1248 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1249 "Supported SSL backends:"),
1251 for (i
= 0; backends
[i
]; i
++)
1252 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1254 case CURLSSLSET_NO_BACKENDS
:
1255 die(_("Could not set SSL backend to '%s': "
1256 "cURL was built without SSL backends"),
1258 case CURLSSLSET_TOO_LATE
:
1259 die(_("Could not set SSL backend to '%s': already set"),
1267 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1268 die("curl_global_init failed");
1270 http_proactive_auth
= proactive_auth
;
1272 if (remote
&& remote
->http_proxy
)
1273 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1276 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1278 pragma_header
= curl_slist_append(http_copy_default_headers(),
1279 "Pragma: no-cache");
1280 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
1284 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1285 if (http_max_requests
)
1286 max_requests
= atoi(http_max_requests
);
1289 curlm
= curl_multi_init();
1291 die("curl_multi_init failed");
1293 if (getenv("GIT_SSL_NO_VERIFY"))
1294 curl_ssl_verify
= 0;
1296 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1297 set_from_env(&ssl_cert_type
, "GIT_SSL_CERT_TYPE");
1298 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1299 set_from_env(&ssl_key_type
, "GIT_SSL_KEY_TYPE");
1300 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1301 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1303 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1305 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1306 if (low_speed_limit
)
1307 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1308 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1310 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1312 if (curl_ssl_verify
== -1)
1313 curl_ssl_verify
= 1;
1315 curl_session_count
= 0;
1316 if (max_requests
< 1)
1317 max_requests
= DEFAULT_MAX_REQUESTS
;
1319 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1320 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1321 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1323 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1324 proxy_ssl_cert_password_required
= 1;
1326 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1327 curl_ftp_no_epsv
= 1;
1330 credential_from_url(&http_auth
, url
);
1331 if (!ssl_cert_password_required
&&
1332 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1333 starts_with(url
, "https://"))
1334 ssl_cert_password_required
= 1;
1337 curl_default
= get_curl_handle();
1340 void http_cleanup(void)
1342 struct active_request_slot
*slot
= active_queue_head
;
1344 while (slot
!= NULL
) {
1345 struct active_request_slot
*next
= slot
->next
;
1347 xmulti_remove_handle(slot
);
1348 curl_easy_cleanup(slot
->curl
);
1353 active_queue_head
= NULL
;
1355 curl_easy_cleanup(curl_default
);
1357 curl_multi_cleanup(curlm
);
1358 curl_global_cleanup();
1360 string_list_clear(&extra_http_headers
, 0);
1362 curl_slist_free_all(pragma_header
);
1363 pragma_header
= NULL
;
1365 curl_slist_free_all(no_pragma_header
);
1366 no_pragma_header
= NULL
;
1368 curl_slist_free_all(host_resolutions
);
1369 host_resolutions
= NULL
;
1371 if (curl_http_proxy
) {
1372 free((void *)curl_http_proxy
);
1373 curl_http_proxy
= NULL
;
1376 if (proxy_auth
.password
) {
1377 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1378 FREE_AND_NULL(proxy_auth
.password
);
1381 free((void *)curl_proxyuserpwd
);
1382 curl_proxyuserpwd
= NULL
;
1384 free((void *)http_proxy_authmethod
);
1385 http_proxy_authmethod
= NULL
;
1387 if (cert_auth
.password
) {
1388 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1389 FREE_AND_NULL(cert_auth
.password
);
1391 ssl_cert_password_required
= 0;
1393 if (proxy_cert_auth
.password
) {
1394 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1395 FREE_AND_NULL(proxy_cert_auth
.password
);
1397 proxy_ssl_cert_password_required
= 0;
1399 FREE_AND_NULL(cached_accept_language
);
1402 struct active_request_slot
*get_active_slot(void)
1404 struct active_request_slot
*slot
= active_queue_head
;
1405 struct active_request_slot
*newslot
;
1409 /* Wait for a slot to open up if the queue is full */
1410 while (active_requests
>= max_requests
) {
1411 curl_multi_perform(curlm
, &num_transfers
);
1412 if (num_transfers
< active_requests
)
1413 process_curl_messages();
1416 while (slot
!= NULL
&& slot
->in_use
)
1420 newslot
= xmalloc(sizeof(*newslot
));
1421 newslot
->curl
= NULL
;
1422 newslot
->in_use
= 0;
1423 newslot
->next
= NULL
;
1425 slot
= active_queue_head
;
1427 active_queue_head
= newslot
;
1429 while (slot
->next
!= NULL
)
1431 slot
->next
= newslot
;
1437 slot
->curl
= curl_easy_duphandle(curl_default
);
1438 curl_session_count
++;
1443 slot
->results
= NULL
;
1444 slot
->finished
= NULL
;
1445 slot
->callback_data
= NULL
;
1446 slot
->callback_func
= NULL
;
1447 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1448 if (curl_save_cookies
)
1449 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1450 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1451 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1452 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1453 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1454 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1455 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1456 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1457 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1458 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1459 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1460 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1463 * Default following to off unless "ALWAYS" is configured; this gives
1464 * callers a sane starting point, and they can tweak for individual
1465 * HTTP_FOLLOW_* cases themselves.
1467 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1468 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1470 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1472 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1473 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1474 if (http_auth
.password
|| curl_empty_auth_enabled())
1475 init_curl_http_auth(slot
->curl
);
1480 int start_active_slot(struct active_request_slot
*slot
)
1482 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1485 if (curlm_result
!= CURLM_OK
&&
1486 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1487 warning("curl_multi_add_handle failed: %s",
1488 curl_multi_strerror(curlm_result
));
1495 * We know there must be something to do, since we just added
1498 curl_multi_perform(curlm
, &num_transfers
);
1504 int (*fill
)(void *);
1505 struct fill_chain
*next
;
1508 static struct fill_chain
*fill_cfg
;
1510 void add_fill_function(void *data
, int (*fill
)(void *))
1512 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1513 struct fill_chain
**linkp
= &fill_cfg
;
1514 new_fill
->data
= data
;
1515 new_fill
->fill
= fill
;
1516 new_fill
->next
= NULL
;
1518 linkp
= &(*linkp
)->next
;
1522 void fill_active_slots(void)
1524 struct active_request_slot
*slot
= active_queue_head
;
1526 while (active_requests
< max_requests
) {
1527 struct fill_chain
*fill
;
1528 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1529 if (fill
->fill(fill
->data
))
1536 while (slot
!= NULL
) {
1537 if (!slot
->in_use
&& slot
->curl
!= NULL
1538 && curl_session_count
> min_curl_sessions
) {
1539 curl_easy_cleanup(slot
->curl
);
1541 curl_session_count
--;
1547 void step_active_slots(void)
1550 CURLMcode curlm_result
;
1553 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1554 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1555 if (num_transfers
< active_requests
) {
1556 process_curl_messages();
1557 fill_active_slots();
1561 void run_active_slot(struct active_request_slot
*slot
)
1567 struct timeval select_timeout
;
1570 slot
->finished
= &finished
;
1572 step_active_slots();
1576 curl_multi_timeout(curlm
, &curl_timeout
);
1577 if (curl_timeout
== 0) {
1579 } else if (curl_timeout
== -1) {
1580 select_timeout
.tv_sec
= 0;
1581 select_timeout
.tv_usec
= 50000;
1583 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1584 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1591 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1594 * It can happen that curl_multi_timeout returns a pathologically
1595 * long timeout when curl_multi_fdset returns no file descriptors
1596 * to read. See commit message for more details.
1599 (select_timeout
.tv_sec
> 0 ||
1600 select_timeout
.tv_usec
> 50000)) {
1601 select_timeout
.tv_sec
= 0;
1602 select_timeout
.tv_usec
= 50000;
1605 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1610 * The value of slot->finished we set before the loop was used
1611 * to set our "finished" variable when our request completed.
1613 * 1. The slot may not have been reused for another requst
1614 * yet, in which case it still has &finished.
1616 * 2. The slot may already be in-use to serve another request,
1617 * which can further be divided into two cases:
1619 * (a) If call run_active_slot() hasn't been called for that
1620 * other request, slot->finished would have been cleared
1621 * by get_active_slot() and has NULL.
1623 * (b) If the request did call run_active_slot(), then the
1624 * call would have updated slot->finished at the beginning
1625 * of this function, and with the clearing of the member
1626 * below, we would find that slot->finished is now NULL.
1628 * In all cases, slot->finished has no useful information to
1629 * anybody at this point. Some compilers warn us for
1630 * attempting to smuggle a pointer that is about to become
1631 * invalid, i.e. &finished. We clear it here to assure them.
1633 slot
->finished
= NULL
;
1636 static void release_active_slot(struct active_request_slot
*slot
)
1638 closedown_active_slot(slot
);
1640 xmulti_remove_handle(slot
);
1641 if (curl_session_count
> min_curl_sessions
) {
1642 curl_easy_cleanup(slot
->curl
);
1644 curl_session_count
--;
1647 fill_active_slots();
1650 void finish_all_active_slots(void)
1652 struct active_request_slot
*slot
= active_queue_head
;
1654 while (slot
!= NULL
)
1656 run_active_slot(slot
);
1657 slot
= active_queue_head
;
1663 /* Helpers for modifying and creating URLs */
1664 static inline int needs_quote(int ch
)
1666 if (((ch
>= 'A') && (ch
<= 'Z'))
1667 || ((ch
>= 'a') && (ch
<= 'z'))
1668 || ((ch
>= '0') && (ch
<= '9'))
1676 static char *quote_ref_url(const char *base
, const char *ref
)
1678 struct strbuf buf
= STRBUF_INIT
;
1682 end_url_with_slash(&buf
, base
);
1684 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1685 if (needs_quote(ch
))
1686 strbuf_addf(&buf
, "%%%02x", ch
);
1688 strbuf_addch(&buf
, *cp
);
1690 return strbuf_detach(&buf
, NULL
);
1693 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1695 int only_two_digit_prefix
)
1697 end_url_with_slash(buf
, url
);
1699 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1700 if (!only_two_digit_prefix
)
1701 strbuf_addstr(buf
, hex
+ 2);
1704 char *get_remote_object_url(const char *url
, const char *hex
,
1705 int only_two_digit_prefix
)
1707 struct strbuf buf
= STRBUF_INIT
;
1708 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1709 return strbuf_detach(&buf
, NULL
);
1712 void normalize_curl_result(CURLcode
*result
, long http_code
,
1713 char *errorstr
, size_t errorlen
)
1716 * If we see a failing http code with CURLE_OK, we have turned off
1717 * FAILONERROR (to keep the server's custom error response), and should
1718 * translate the code into failure here.
1720 * Likewise, if we see a redirect (30x code), that means we turned off
1721 * redirect-following, and we should treat the result as an error.
1723 if (*result
== CURLE_OK
&& http_code
>= 300) {
1724 *result
= CURLE_HTTP_RETURNED_ERROR
;
1726 * Normally curl will already have put the "reason phrase"
1727 * from the server into curl_errorstr; unfortunately without
1728 * FAILONERROR it is lost, so we can give only the numeric
1731 xsnprintf(errorstr
, errorlen
,
1732 "The requested URL returned error: %ld",
1737 static int handle_curl_result(struct slot_results
*results
)
1739 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1740 curl_errorstr
, sizeof(curl_errorstr
));
1742 if (results
->curl_result
== CURLE_OK
) {
1743 credential_approve(&http_auth
);
1744 credential_approve(&proxy_auth
);
1745 credential_approve(&cert_auth
);
1747 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1749 * We can't tell from here whether it's a bad path, bad
1750 * certificate, bad password, or something else wrong
1751 * with the certificate. So we reject the credential to
1752 * avoid caching or saving a bad password.
1754 credential_reject(&cert_auth
);
1756 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1757 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1758 return HTTP_NOMATCHPUBLICKEY
;
1760 } else if (missing_target(results
))
1761 return HTTP_MISSING_TARGET
;
1762 else if (results
->http_code
== 401) {
1763 if (http_auth
.username
&& http_auth
.password
) {
1764 credential_reject(&http_auth
);
1767 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1768 if (results
->auth_avail
) {
1769 http_auth_methods
&= results
->auth_avail
;
1770 http_auth_methods_restricted
= 1;
1775 if (results
->http_connectcode
== 407)
1776 credential_reject(&proxy_auth
);
1777 if (!curl_errorstr
[0])
1778 strlcpy(curl_errorstr
,
1779 curl_easy_strerror(results
->curl_result
),
1780 sizeof(curl_errorstr
));
1785 int run_one_slot(struct active_request_slot
*slot
,
1786 struct slot_results
*results
)
1788 slot
->results
= results
;
1789 if (!start_active_slot(slot
)) {
1790 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1791 "failed to start HTTP request");
1792 return HTTP_START_FAILED
;
1795 run_active_slot(slot
);
1796 return handle_curl_result(results
);
1799 struct curl_slist
*http_copy_default_headers(void)
1801 struct curl_slist
*headers
= NULL
;
1802 const struct string_list_item
*item
;
1804 for_each_string_list_item(item
, &extra_http_headers
)
1805 headers
= curl_slist_append(headers
, item
->string
);
1810 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1816 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1818 strbuf_addstr(buf
, ptr
);
1823 * Check for and extract a content-type parameter. "raw"
1824 * should be positioned at the start of the potential
1825 * parameter, with any whitespace already removed.
1827 * "name" is the name of the parameter. The value is appended
1830 static int extract_param(const char *raw
, const char *name
,
1833 size_t len
= strlen(name
);
1835 if (strncasecmp(raw
, name
, len
))
1843 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1844 strbuf_addch(out
, *raw
++);
1849 * Extract a normalized version of the content type, with any
1850 * spaces suppressed, all letters lowercased, and no trailing ";"
1853 * Note that we will silently remove even invalid whitespace. For
1854 * example, "text / plain" is specifically forbidden by RFC 2616,
1855 * but "text/plain" is the only reasonable output, and this keeps
1858 * If the "charset" argument is not NULL, store the value of any
1859 * charset parameter there.
1862 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1863 * "text / plain" -> "text/plain"
1865 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1866 struct strbuf
*charset
)
1871 strbuf_grow(type
, raw
->len
);
1872 for (p
= raw
->buf
; *p
; p
++) {
1879 strbuf_addch(type
, tolower(*p
));
1885 strbuf_reset(charset
);
1887 while (isspace(*p
) || *p
== ';')
1889 if (!extract_param(p
, "charset", charset
))
1891 while (*p
&& !isspace(*p
))
1895 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1896 strbuf_addstr(charset
, "ISO-8859-1");
1899 static void write_accept_language(struct strbuf
*buf
)
1902 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1903 * that, q-value will be smaller than 0.001, the minimum q-value the
1904 * HTTP specification allows. See
1905 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1907 const int MAX_DECIMAL_PLACES
= 3;
1908 const int MAX_LANGUAGE_TAGS
= 1000;
1909 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1910 char **language_tags
= NULL
;
1912 const char *s
= get_preferred_languages();
1914 struct strbuf tag
= STRBUF_INIT
;
1916 /* Don't add Accept-Language header if no language is preferred. */
1921 * Split the colon-separated string of preferred languages into
1922 * language_tags array.
1925 /* collect language tag */
1926 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1927 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1929 /* skip .codeset, @modifier and any other unnecessary parts */
1930 while (*s
&& *s
!= ':')
1935 REALLOC_ARRAY(language_tags
, num_langs
);
1936 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1937 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1942 /* write Accept-Language header into buf */
1944 int last_buf_len
= 0;
1950 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1951 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1953 /* compute decimal_places */
1954 for (max_q
= 1, decimal_places
= 0;
1955 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1956 decimal_places
++, max_q
*= 10)
1959 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1961 strbuf_addstr(buf
, "Accept-Language: ");
1963 for (i
= 0; i
< num_langs
; i
++) {
1965 strbuf_addstr(buf
, ", ");
1967 strbuf_addstr(buf
, language_tags
[i
]);
1970 strbuf_addf(buf
, q_format
, max_q
- i
);
1972 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1973 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1977 last_buf_len
= buf
->len
;
1981 /* free language tags -- last one is a static '*' */
1982 for (i
= 0; i
< num_langs
- 1; i
++)
1983 free(language_tags
[i
]);
1984 free(language_tags
);
1988 * Get an Accept-Language header which indicates user's preferred languages.
1992 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1993 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1994 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1995 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1996 * LANGUAGE= LANG=C -> ""
1998 const char *http_get_accept_language_header(void)
2000 if (!cached_accept_language
) {
2001 struct strbuf buf
= STRBUF_INIT
;
2002 write_accept_language(&buf
);
2004 cached_accept_language
= strbuf_detach(&buf
, NULL
);
2007 return cached_accept_language
;
2010 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
2013 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
2014 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
2017 /* http_request() targets */
2018 #define HTTP_REQUEST_STRBUF 0
2019 #define HTTP_REQUEST_FILE 1
2021 static int http_request(const char *url
,
2022 void *result
, int target
,
2023 const struct http_get_options
*options
)
2025 struct active_request_slot
*slot
;
2026 struct slot_results results
;
2027 struct curl_slist
*headers
= http_copy_default_headers();
2028 struct strbuf buf
= STRBUF_INIT
;
2029 const char *accept_language
;
2032 slot
= get_active_slot();
2033 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
2036 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
2038 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
2039 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
2041 if (target
== HTTP_REQUEST_FILE
) {
2042 off_t posn
= ftello(result
);
2043 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2046 http_opt_request_remainder(slot
->curl
, posn
);
2048 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2052 curl_easy_setopt(slot
->curl
, CURLOPT_HEADERFUNCTION
, fwrite_wwwauth
);
2054 accept_language
= http_get_accept_language_header();
2056 if (accept_language
)
2057 headers
= curl_slist_append(headers
, accept_language
);
2059 strbuf_addstr(&buf
, "Pragma:");
2060 if (options
&& options
->no_cache
)
2061 strbuf_addstr(&buf
, " no-cache");
2062 if (options
&& options
->initial_request
&&
2063 http_follow_config
== HTTP_FOLLOW_INITIAL
)
2064 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
2066 headers
= curl_slist_append(headers
, buf
.buf
);
2068 /* Add additional headers here */
2069 if (options
&& options
->extra_headers
) {
2070 const struct string_list_item
*item
;
2071 for_each_string_list_item(item
, options
->extra_headers
) {
2072 headers
= curl_slist_append(headers
, item
->string
);
2076 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
2077 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
2078 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
2079 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
2081 ret
= run_one_slot(slot
, &results
);
2083 if (options
&& options
->content_type
) {
2084 struct strbuf raw
= STRBUF_INIT
;
2085 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
2086 extract_content_type(&raw
, options
->content_type
,
2088 strbuf_release(&raw
);
2091 if (options
&& options
->effective_url
)
2092 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
2093 options
->effective_url
);
2095 curl_slist_free_all(headers
);
2096 strbuf_release(&buf
);
2102 * Update the "base" url to a more appropriate value, as deduced by
2103 * redirects seen when requesting a URL starting with "url".
2105 * The "asked" parameter is a URL that we asked curl to access, and must begin
2108 * The "got" parameter is the URL that curl reported to us as where we ended
2111 * Returns 1 if we updated the base url, 0 otherwise.
2113 * Our basic strategy is to compare "base" and "asked" to find the bits
2114 * specific to our request. We then strip those bits off of "got" to yield the
2115 * new base. So for example, if our base is "http://example.com/foo.git",
2116 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2117 * with "https://other.example.com/foo.git/info/refs". We would want the
2118 * new URL to become "https://other.example.com/foo.git".
2120 * Note that this assumes a sane redirect scheme. It's entirely possible
2121 * in the example above to end up at a URL that does not even end in
2122 * "info/refs". In such a case we die. There's not much we can do, such a
2123 * scheme is unlikely to represent a real git repository, and failing to
2124 * rewrite the base opens options for malicious redirects to do funny things.
2126 static int update_url_from_redirect(struct strbuf
*base
,
2128 const struct strbuf
*got
)
2133 if (!strcmp(asked
, got
->buf
))
2136 if (!skip_prefix(asked
, base
->buf
, &tail
))
2137 BUG("update_url_from_redirect: %s is not a superset of %s",
2141 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
2142 die(_("unable to update url base from redirection:\n"
2148 strbuf_add(base
, got
->buf
, new_len
);
2153 static int http_request_reauth(const char *url
,
2154 void *result
, int target
,
2155 struct http_get_options
*options
)
2157 int ret
= http_request(url
, result
, target
, options
);
2159 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2162 if (options
&& options
->effective_url
&& options
->base_url
) {
2163 if (update_url_from_redirect(options
->base_url
,
2164 url
, options
->effective_url
)) {
2165 credential_from_url(&http_auth
, options
->base_url
->buf
);
2166 url
= options
->effective_url
->buf
;
2170 if (ret
!= HTTP_REAUTH
)
2174 * The previous request may have put cruft into our output stream; we
2175 * should clear it out before making our next request.
2178 case HTTP_REQUEST_STRBUF
:
2179 strbuf_reset(result
);
2181 case HTTP_REQUEST_FILE
:
2182 if (fflush(result
)) {
2183 error_errno("unable to flush a file");
2184 return HTTP_START_FAILED
;
2187 if (ftruncate(fileno(result
), 0) < 0) {
2188 error_errno("unable to truncate a file");
2189 return HTTP_START_FAILED
;
2193 BUG("Unknown http_request target");
2196 credential_fill(&http_auth
);
2198 return http_request(url
, result
, target
, options
);
2201 int http_get_strbuf(const char *url
,
2202 struct strbuf
*result
,
2203 struct http_get_options
*options
)
2205 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2209 * Downloads a URL and stores the result in the given file.
2211 * If a previous interrupted download is detected (i.e. a previous temporary
2212 * file is still around) the download is resumed.
2214 int http_get_file(const char *url
, const char *filename
,
2215 struct http_get_options
*options
)
2218 struct strbuf tmpfile
= STRBUF_INIT
;
2221 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2222 result
= fopen(tmpfile
.buf
, "a");
2224 error("Unable to open local file %s", tmpfile
.buf
);
2229 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2232 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2235 strbuf_release(&tmpfile
);
2239 int http_fetch_ref(const char *base
, struct ref
*ref
)
2241 struct http_get_options options
= {0};
2243 struct strbuf buffer
= STRBUF_INIT
;
2246 options
.no_cache
= 1;
2248 url
= quote_ref_url(base
, ref
->name
);
2249 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2250 strbuf_rtrim(&buffer
);
2251 if (buffer
.len
== the_hash_algo
->hexsz
)
2252 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2253 else if (starts_with(buffer
.buf
, "ref: ")) {
2254 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2259 strbuf_release(&buffer
);
2264 /* Helpers for fetching packs */
2265 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2268 struct strbuf buf
= STRBUF_INIT
;
2270 if (http_is_verbose
)
2271 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2273 end_url_with_slash(&buf
, base_url
);
2274 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2275 url
= strbuf_detach(&buf
, NULL
);
2277 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2278 tmp
= strbuf_detach(&buf
, NULL
);
2280 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2281 error("Unable to get pack index %s", url
);
2289 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2290 unsigned char *sha1
, const char *base_url
)
2292 struct packed_git
*new_pack
;
2293 char *tmp_idx
= NULL
;
2296 if (has_pack_index(sha1
)) {
2297 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2299 return -1; /* parse_pack_index() already issued error message */
2303 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2307 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2312 return -1; /* parse_pack_index() already issued error message */
2315 ret
= verify_pack_index(new_pack
);
2317 close_pack_index(new_pack
);
2318 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2325 new_pack
->next
= *packs_head
;
2326 *packs_head
= new_pack
;
2330 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2332 struct http_get_options options
= {0};
2336 struct strbuf buf
= STRBUF_INIT
;
2337 struct object_id oid
;
2339 end_url_with_slash(&buf
, base_url
);
2340 strbuf_addstr(&buf
, "objects/info/packs");
2341 url
= strbuf_detach(&buf
, NULL
);
2343 options
.no_cache
= 1;
2344 ret
= http_get_strbuf(url
, &buf
, &options
);
2350 if (skip_prefix(data
, "P pack-", &data
) &&
2351 !parse_oid_hex(data
, &oid
, &data
) &&
2352 skip_prefix(data
, ".pack", &data
) &&
2353 (*data
== '\n' || *data
== '\0')) {
2354 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2356 data
= strchrnul(data
, '\n');
2359 data
++; /* skip past newline */
2367 void release_http_pack_request(struct http_pack_request
*preq
)
2369 if (preq
->packfile
) {
2370 fclose(preq
->packfile
);
2371 preq
->packfile
= NULL
;
2374 strbuf_release(&preq
->tmpfile
);
2379 static const char *default_index_pack_args
[] =
2380 {"index-pack", "--stdin", NULL
};
2382 int finish_http_pack_request(struct http_pack_request
*preq
)
2384 struct child_process ip
= CHILD_PROCESS_INIT
;
2388 fclose(preq
->packfile
);
2389 preq
->packfile
= NULL
;
2391 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2395 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2396 preq
->index_pack_args
:
2397 default_index_pack_args
);
2399 if (preq
->preserve_index_pack_stdout
)
2404 if (run_command(&ip
)) {
2411 unlink(preq
->tmpfile
.buf
);
2415 void http_install_packfile(struct packed_git
*p
,
2416 struct packed_git
**list_to_remove_from
)
2418 struct packed_git
**lst
= list_to_remove_from
;
2421 lst
= &((*lst
)->next
);
2422 *lst
= (*lst
)->next
;
2424 install_packed_git(the_repository
, p
);
2427 struct http_pack_request
*new_http_pack_request(
2428 const unsigned char *packed_git_hash
, const char *base_url
) {
2430 struct strbuf buf
= STRBUF_INIT
;
2432 end_url_with_slash(&buf
, base_url
);
2433 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2434 hash_to_hex(packed_git_hash
));
2435 return new_direct_http_pack_request(packed_git_hash
,
2436 strbuf_detach(&buf
, NULL
));
2439 struct http_pack_request
*new_direct_http_pack_request(
2440 const unsigned char *packed_git_hash
, char *url
)
2442 off_t prev_posn
= 0;
2443 struct http_pack_request
*preq
;
2445 CALLOC_ARRAY(preq
, 1);
2446 strbuf_init(&preq
->tmpfile
, 0);
2450 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2451 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2452 if (!preq
->packfile
) {
2453 error("Unable to open local file %s for pack",
2458 preq
->slot
= get_active_slot();
2459 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2460 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2461 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2462 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
2466 * If there is data present from a previous transfer attempt,
2467 * resume where it left off
2469 prev_posn
= ftello(preq
->packfile
);
2471 if (http_is_verbose
)
2473 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2474 hash_to_hex(packed_git_hash
),
2475 (uintmax_t)prev_posn
);
2476 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2482 strbuf_release(&preq
->tmpfile
);
2488 /* Helpers for fetching objects (loose) */
2489 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2492 unsigned char expn
[4096];
2493 size_t size
= eltsize
* nmemb
;
2495 struct http_object_request
*freq
= data
;
2496 struct active_request_slot
*slot
= freq
->slot
;
2499 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2502 BUG("curl_easy_getinfo for HTTP code failed: %s",
2503 curl_easy_strerror(c
));
2504 if (slot
->http_code
>= 300)
2509 ssize_t retval
= xwrite(freq
->localfile
,
2510 (char *) ptr
+ posn
, size
- posn
);
2512 return posn
/ eltsize
;
2514 } while (posn
< size
);
2516 freq
->stream
.avail_in
= size
;
2517 freq
->stream
.next_in
= (void *)ptr
;
2519 freq
->stream
.next_out
= expn
;
2520 freq
->stream
.avail_out
= sizeof(expn
);
2521 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2522 the_hash_algo
->update_fn(&freq
->c
, expn
,
2523 sizeof(expn
) - freq
->stream
.avail_out
);
2524 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2528 struct http_object_request
*new_http_object_request(const char *base_url
,
2529 const struct object_id
*oid
)
2531 char *hex
= oid_to_hex(oid
);
2532 struct strbuf filename
= STRBUF_INIT
;
2533 struct strbuf prevfile
= STRBUF_INIT
;
2535 char prev_buf
[PREV_BUF_SIZE
];
2536 ssize_t prev_read
= 0;
2537 off_t prev_posn
= 0;
2538 struct http_object_request
*freq
;
2540 CALLOC_ARRAY(freq
, 1);
2541 strbuf_init(&freq
->tmpfile
, 0);
2542 oidcpy(&freq
->oid
, oid
);
2543 freq
->localfile
= -1;
2545 loose_object_path(the_repository
, &filename
, oid
);
2546 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2548 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2549 unlink_or_warn(prevfile
.buf
);
2550 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2551 unlink_or_warn(freq
->tmpfile
.buf
);
2552 strbuf_release(&filename
);
2554 if (freq
->localfile
!= -1)
2555 error("fd leakage in start: %d", freq
->localfile
);
2556 freq
->localfile
= open(freq
->tmpfile
.buf
,
2557 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2559 * This could have failed due to the "lazy directory creation";
2560 * try to mkdir the last path component.
2562 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2563 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2566 mkdir(freq
->tmpfile
.buf
, 0777);
2569 freq
->localfile
= open(freq
->tmpfile
.buf
,
2570 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2573 if (freq
->localfile
< 0) {
2574 error_errno("Couldn't create temporary file %s",
2579 git_inflate_init(&freq
->stream
);
2581 the_hash_algo
->init_fn(&freq
->c
);
2583 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2586 * If a previous temp file is present, process what was already
2589 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2590 if (prevlocal
!= -1) {
2592 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2594 if (fwrite_sha1_file(prev_buf
,
2597 freq
) == prev_read
) {
2598 prev_posn
+= prev_read
;
2603 } while (prev_read
> 0);
2606 unlink_or_warn(prevfile
.buf
);
2607 strbuf_release(&prevfile
);
2610 * Reset inflate/SHA1 if there was an error reading the previous temp
2611 * file; also rewind to the beginning of the local file.
2613 if (prev_read
== -1) {
2614 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2615 git_inflate_init(&freq
->stream
);
2616 the_hash_algo
->init_fn(&freq
->c
);
2619 lseek(freq
->localfile
, 0, SEEK_SET
);
2620 if (ftruncate(freq
->localfile
, 0) < 0) {
2621 error_errno("Couldn't truncate temporary file %s",
2628 freq
->slot
= get_active_slot();
2630 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2631 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2632 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2633 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2634 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2635 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2638 * If we have successfully processed data from a previous fetch
2639 * attempt, only fetch the data we don't already have.
2642 if (http_is_verbose
)
2644 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2645 hex
, (uintmax_t)prev_posn
);
2646 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2652 strbuf_release(&prevfile
);
2658 void process_http_object_request(struct http_object_request
*freq
)
2662 freq
->curl_result
= freq
->slot
->curl_result
;
2663 freq
->http_code
= freq
->slot
->http_code
;
2667 int finish_http_object_request(struct http_object_request
*freq
)
2670 struct strbuf filename
= STRBUF_INIT
;
2672 close(freq
->localfile
);
2673 freq
->localfile
= -1;
2675 process_http_object_request(freq
);
2677 if (freq
->http_code
== 416) {
2678 warning("requested range invalid; we may already have all the data.");
2679 } else if (freq
->curl_result
!= CURLE_OK
) {
2680 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2681 if (st
.st_size
== 0)
2682 unlink_or_warn(freq
->tmpfile
.buf
);
2686 git_inflate_end(&freq
->stream
);
2687 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2688 if (freq
->zret
!= Z_STREAM_END
) {
2689 unlink_or_warn(freq
->tmpfile
.buf
);
2692 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2693 unlink_or_warn(freq
->tmpfile
.buf
);
2696 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2697 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2698 strbuf_release(&filename
);
2700 return freq
->rename
;
2703 void abort_http_object_request(struct http_object_request
*freq
)
2705 unlink_or_warn(freq
->tmpfile
.buf
);
2707 release_http_object_request(freq
);
2710 void release_http_object_request(struct http_object_request
*freq
)
2712 if (freq
->localfile
!= -1) {
2713 close(freq
->localfile
);
2714 freq
->localfile
= -1;
2716 FREE_AND_NULL(freq
->url
);
2718 freq
->slot
->callback_func
= NULL
;
2719 freq
->slot
->callback_data
= NULL
;
2720 release_active_slot(freq
->slot
);
2723 strbuf_release(&freq
->tmpfile
);