1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
8 #include "run-command.h"
11 #include "credential.h"
15 #include "transport.h"
18 #include "string-list.h"
19 #include "object-store.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 const char *curl_http_version
= NULL
;
42 static const char *ssl_cert
;
43 static const char *ssl_cert_type
;
44 static const char *ssl_cipherlist
;
45 static const char *ssl_version
;
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
},
62 static const char *ssl_key
;
63 static const char *ssl_key_type
;
64 static const char *ssl_capath
;
65 static const char *curl_no_proxy
;
66 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
67 static const char *ssl_pinnedkey
;
69 static const char *ssl_cainfo
;
70 static long curl_low_speed_limit
= -1;
71 static long curl_low_speed_time
= -1;
72 static int curl_ftp_no_epsv
;
73 static const char *curl_http_proxy
;
74 static const char *http_proxy_authmethod
;
76 static const char *http_proxy_ssl_cert
;
77 static const char *http_proxy_ssl_key
;
78 static const char *http_proxy_ssl_ca_info
;
79 static struct credential proxy_cert_auth
= CREDENTIAL_INIT
;
80 static int proxy_ssl_cert_password_required
;
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 const 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 const char *curl_cookie_file
;
112 static int curl_save_cookies
;
113 struct credential http_auth
= CREDENTIAL_INIT
;
114 static int http_proactive_auth
;
115 static const char *user_agent
;
116 static int curl_empty_auth
= -1;
118 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
120 static struct credential cert_auth
= CREDENTIAL_INIT
;
121 static int ssl_cert_password_required
;
122 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
123 static int http_auth_methods_restricted
;
124 /* Modes for which empty_auth cannot actually help us. */
125 static unsigned long empty_auth_useless
=
130 static struct curl_slist
*pragma_header
;
131 static struct curl_slist
*no_pragma_header
;
132 static struct string_list extra_http_headers
= STRING_LIST_INIT_DUP
;
134 static struct curl_slist
*host_resolutions
;
136 static struct active_request_slot
*active_queue_head
;
138 static char *cached_accept_language
;
140 static char *http_ssl_backend
;
142 static int http_schannel_check_revoke
= 1;
144 * With the backend being set to `schannel`, setting sslCAinfo would override
145 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
148 static int http_schannel_use_ssl_cainfo
;
150 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
152 size_t size
= eltsize
* nmemb
;
153 struct buffer
*buffer
= buffer_
;
155 if (size
> buffer
->buf
.len
- buffer
->posn
)
156 size
= buffer
->buf
.len
- buffer
->posn
;
157 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
158 buffer
->posn
+= size
;
160 return size
/ eltsize
;
163 int seek_buffer(void *clientp
, curl_off_t offset
, int origin
)
165 struct buffer
*buffer
= clientp
;
167 if (origin
!= SEEK_SET
)
168 BUG("seek_buffer only handles SEEK_SET");
169 if (offset
< 0 || offset
>= buffer
->buf
.len
) {
170 error("curl seek would be outside of buffer");
171 return CURL_SEEKFUNC_FAIL
;
174 buffer
->posn
= offset
;
175 return CURL_SEEKFUNC_OK
;
178 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
180 size_t size
= eltsize
* nmemb
;
181 struct strbuf
*buffer
= buffer_
;
183 strbuf_add(buffer
, ptr
, size
);
188 * A folded header continuation line starts with any number of spaces or
189 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
190 * It is not a continuation line if the line starts with any other character.
192 static inline int is_hdr_continuation(const char *ptr
, const size_t size
)
194 return size
&& (*ptr
== ' ' || *ptr
== '\t');
197 static size_t fwrite_wwwauth(char *ptr
, size_t eltsize
, size_t nmemb
, void *p
)
199 size_t size
= eltsize
* nmemb
;
200 struct strvec
*values
= &http_auth
.wwwauth_headers
;
201 struct strbuf buf
= STRBUF_INIT
;
206 * Header lines may not come NULL-terminated from libcurl so we must
207 * limit all scans to the maximum length of the header line, or leverage
208 * strbufs for all operations.
210 * In addition, it is possible that header values can be split over
211 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
212 * but older servers may still emit them. A continuation header field
213 * value is identified as starting with a space or horizontal tab.
215 * The formal definition of a header field as given in RFC 7230 is:
217 * header-field = field-name ":" OWS field-value OWS
220 * field-value = *( field-content / obs-fold )
221 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
222 * field-vchar = VCHAR / obs-text
224 * obs-fold = CRLF 1*( SP / HTAB )
225 * ; obsolete line folding
226 * ; see Section 3.2.4
229 /* Start of a new WWW-Authenticate header */
230 if (skip_iprefix_mem(ptr
, size
, "www-authenticate:", &val
, &val_len
)) {
231 strbuf_add(&buf
, val
, val_len
);
234 * Strip the CRLF that should be present at the end of each
235 * field as well as any trailing or leading whitespace from the
240 strvec_push(values
, buf
.buf
);
241 http_auth
.header_is_last_match
= 1;
246 * This line could be a continuation of the previously matched header
247 * field. If this is the case then we should append this value to the
248 * end of the previously consumed value.
250 if (http_auth
.header_is_last_match
&& is_hdr_continuation(ptr
, size
)) {
252 * Trim the CRLF and any leading or trailing from this line.
254 strbuf_add(&buf
, ptr
, size
);
258 * At this point we should always have at least one existing
259 * value, even if it is empty. Do not bother appending the new
260 * value if this continuation header is itself empty.
263 BUG("should have at least one existing header value");
264 } else if (buf
.len
) {
265 char *prev
= xstrdup(values
->v
[values
->nr
- 1]);
267 /* Join two non-empty values with a single space. */
268 const char *const sp
= *prev
? " " : "";
271 strvec_pushf(values
, "%s%s%s", prev
, sp
, buf
.buf
);
278 /* Not a continuation of a previously matched auth header line. */
279 http_auth
.header_is_last_match
= 0;
282 * If this is a HTTP status line and not a header field, this signals
283 * a different HTTP response. libcurl writes all the output of all
284 * response headers of all responses, including redirects.
285 * We only care about the last HTTP request response's headers so clear
286 * the existing array.
288 if (skip_iprefix_mem(ptr
, size
, "http/", &val
, &val_len
))
289 strvec_clear(values
);
292 strbuf_release(&buf
);
296 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
301 static void closedown_active_slot(struct active_request_slot
*slot
)
307 static void finish_active_slot(struct active_request_slot
*slot
)
309 closedown_active_slot(slot
);
310 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
313 (*slot
->finished
) = 1;
315 /* Store slot results so they can be read after the slot is reused */
317 slot
->results
->curl_result
= slot
->curl_result
;
318 slot
->results
->http_code
= slot
->http_code
;
319 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
320 &slot
->results
->auth_avail
);
322 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
323 &slot
->results
->http_connectcode
);
326 /* Run callback if appropriate */
327 if (slot
->callback_func
)
328 slot
->callback_func(slot
->callback_data
);
331 static void xmulti_remove_handle(struct active_request_slot
*slot
)
333 curl_multi_remove_handle(curlm
, slot
->curl
);
336 static void process_curl_messages(void)
339 struct active_request_slot
*slot
;
340 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
342 while (curl_message
!= NULL
) {
343 if (curl_message
->msg
== CURLMSG_DONE
) {
344 int curl_result
= curl_message
->data
.result
;
345 slot
= active_queue_head
;
346 while (slot
!= NULL
&&
347 slot
->curl
!= curl_message
->easy_handle
)
350 xmulti_remove_handle(slot
);
351 slot
->curl_result
= curl_result
;
352 finish_active_slot(slot
);
354 fprintf(stderr
, "Received DONE message for unknown request!\n");
357 fprintf(stderr
, "Unknown CURL message received: %d\n",
358 (int)curl_message
->msg
);
360 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
364 static int http_options(const char *var
, const char *value
, void *cb
)
366 if (!strcmp("http.version", var
)) {
367 return git_config_string(&curl_http_version
, var
, value
);
369 if (!strcmp("http.sslverify", var
)) {
370 curl_ssl_verify
= git_config_bool(var
, value
);
373 if (!strcmp("http.sslcipherlist", var
))
374 return git_config_string(&ssl_cipherlist
, var
, value
);
375 if (!strcmp("http.sslversion", var
))
376 return git_config_string(&ssl_version
, var
, value
);
377 if (!strcmp("http.sslcert", var
))
378 return git_config_pathname(&ssl_cert
, var
, value
);
379 if (!strcmp("http.sslcerttype", var
))
380 return git_config_string(&ssl_cert_type
, var
, value
);
381 if (!strcmp("http.sslkey", var
))
382 return git_config_pathname(&ssl_key
, var
, value
);
383 if (!strcmp("http.sslkeytype", var
))
384 return git_config_string(&ssl_key_type
, var
, value
);
385 if (!strcmp("http.sslcapath", var
))
386 return git_config_pathname(&ssl_capath
, var
, value
);
387 if (!strcmp("http.sslcainfo", var
))
388 return git_config_pathname(&ssl_cainfo
, var
, value
);
389 if (!strcmp("http.sslcertpasswordprotected", var
)) {
390 ssl_cert_password_required
= git_config_bool(var
, value
);
393 if (!strcmp("http.ssltry", var
)) {
394 curl_ssl_try
= git_config_bool(var
, value
);
397 if (!strcmp("http.sslbackend", var
)) {
398 free(http_ssl_backend
);
399 http_ssl_backend
= xstrdup_or_null(value
);
403 if (!strcmp("http.schannelcheckrevoke", var
)) {
404 http_schannel_check_revoke
= git_config_bool(var
, value
);
408 if (!strcmp("http.schannelusesslcainfo", var
)) {
409 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
413 if (!strcmp("http.minsessions", var
)) {
414 min_curl_sessions
= git_config_int(var
, value
);
415 if (min_curl_sessions
> 1)
416 min_curl_sessions
= 1;
419 if (!strcmp("http.maxrequests", var
)) {
420 max_requests
= git_config_int(var
, value
);
423 if (!strcmp("http.lowspeedlimit", var
)) {
424 curl_low_speed_limit
= (long)git_config_int(var
, value
);
427 if (!strcmp("http.lowspeedtime", var
)) {
428 curl_low_speed_time
= (long)git_config_int(var
, value
);
432 if (!strcmp("http.noepsv", var
)) {
433 curl_ftp_no_epsv
= git_config_bool(var
, value
);
436 if (!strcmp("http.proxy", var
))
437 return git_config_string(&curl_http_proxy
, var
, value
);
439 if (!strcmp("http.proxyauthmethod", var
))
440 return git_config_string(&http_proxy_authmethod
, var
, value
);
442 if (!strcmp("http.proxysslcert", var
))
443 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
445 if (!strcmp("http.proxysslkey", var
))
446 return git_config_string(&http_proxy_ssl_key
, var
, value
);
448 if (!strcmp("http.proxysslcainfo", var
))
449 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
451 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
452 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
456 if (!strcmp("http.cookiefile", var
))
457 return git_config_pathname(&curl_cookie_file
, var
, value
);
458 if (!strcmp("http.savecookies", var
)) {
459 curl_save_cookies
= git_config_bool(var
, value
);
463 if (!strcmp("http.postbuffer", var
)) {
464 http_post_buffer
= git_config_ssize_t(var
, value
);
465 if (http_post_buffer
< 0)
466 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
467 if (http_post_buffer
< LARGE_PACKET_MAX
)
468 http_post_buffer
= LARGE_PACKET_MAX
;
472 if (!strcmp("http.useragent", var
))
473 return git_config_string(&user_agent
, var
, value
);
475 if (!strcmp("http.emptyauth", var
)) {
476 if (value
&& !strcmp("auto", value
))
477 curl_empty_auth
= -1;
479 curl_empty_auth
= git_config_bool(var
, value
);
483 if (!strcmp("http.delegation", var
)) {
484 #ifdef CURLGSSAPI_DELEGATION_FLAG
485 return git_config_string(&curl_deleg
, var
, value
);
487 warning(_("Delegation control is not supported with cURL < 7.22.0"));
492 if (!strcmp("http.pinnedpubkey", var
)) {
493 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
494 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
496 warning(_("Public key pinning not supported with cURL < 7.39.0"));
501 if (!strcmp("http.extraheader", var
)) {
503 return config_error_nonbool(var
);
504 } else if (!*value
) {
505 string_list_clear(&extra_http_headers
, 0);
507 string_list_append(&extra_http_headers
, value
);
512 if (!strcmp("http.curloptresolve", var
)) {
514 return config_error_nonbool(var
);
515 } else if (!*value
) {
516 curl_slist_free_all(host_resolutions
);
517 host_resolutions
= NULL
;
519 host_resolutions
= curl_slist_append(host_resolutions
, value
);
524 if (!strcmp("http.followredirects", var
)) {
525 if (value
&& !strcmp(value
, "initial"))
526 http_follow_config
= HTTP_FOLLOW_INITIAL
;
527 else if (git_config_bool(var
, value
))
528 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
530 http_follow_config
= HTTP_FOLLOW_NONE
;
534 /* Fall back on the default ones */
535 return git_default_config(var
, value
, cb
);
538 static int curl_empty_auth_enabled(void)
540 if (curl_empty_auth
>= 0)
541 return curl_empty_auth
;
544 * In the automatic case, kick in the empty-auth
545 * hack as long as we would potentially try some
546 * method more exotic than "Basic" or "Digest".
548 * But only do this when this is our second or
549 * subsequent request, as by then we know what
550 * methods are available.
552 if (http_auth_methods_restricted
&&
553 (http_auth_methods
& ~empty_auth_useless
))
558 static void init_curl_http_auth(CURL
*result
)
560 if (!http_auth
.username
|| !*http_auth
.username
) {
561 if (curl_empty_auth_enabled())
562 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
566 credential_fill(&http_auth
);
568 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
569 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
572 /* *var must be free-able */
573 static void var_override(const char **var
, char *value
)
577 *var
= xstrdup(value
);
581 static void set_proxyauth_name_password(CURL
*result
)
583 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
584 proxy_auth
.username
);
585 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
586 proxy_auth
.password
);
589 static void init_curl_proxy_auth(CURL
*result
)
591 if (proxy_auth
.username
) {
592 if (!proxy_auth
.password
)
593 credential_fill(&proxy_auth
);
594 set_proxyauth_name_password(result
);
597 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
599 if (http_proxy_authmethod
) {
601 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
602 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
603 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
604 proxy_authmethods
[i
].curlauth_param
);
608 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
609 warning("unsupported proxy authentication method %s: using anyauth",
610 http_proxy_authmethod
);
611 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
615 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
618 static int has_cert_password(void)
620 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
622 if (!cert_auth
.password
) {
623 cert_auth
.protocol
= xstrdup("cert");
624 cert_auth
.host
= xstrdup("");
625 cert_auth
.username
= xstrdup("");
626 cert_auth
.path
= xstrdup(ssl_cert
);
627 credential_fill(&cert_auth
);
632 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
633 static int has_proxy_cert_password(void)
635 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
637 if (!proxy_cert_auth
.password
) {
638 proxy_cert_auth
.protocol
= xstrdup("cert");
639 proxy_cert_auth
.host
= xstrdup("");
640 proxy_cert_auth
.username
= xstrdup("");
641 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
642 credential_fill(&proxy_cert_auth
);
648 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
649 static void set_curl_keepalive(CURL
*c
)
651 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
655 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
659 socklen_t len
= (socklen_t
)sizeof(ka
);
661 if (type
!= CURLSOCKTYPE_IPCXN
)
664 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
666 warning_errno("unable to set SO_KEEPALIVE on socket");
668 return CURL_SOCKOPT_OK
;
671 static void set_curl_keepalive(CURL
*c
)
673 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
677 /* Return 1 if redactions have been made, 0 otherwise. */
678 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
681 const char *sensitive_header
;
683 if (trace_curl_redact
&&
684 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
685 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
686 /* The first token is the type, which is OK to log */
687 while (isspace(*sensitive_header
))
689 while (*sensitive_header
&& !isspace(*sensitive_header
))
691 /* Everything else is opaque and possibly sensitive */
692 strbuf_setlen(header
, sensitive_header
- header
->buf
);
693 strbuf_addstr(header
, " <redacted>");
695 } else if (trace_curl_redact
&&
696 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
697 struct strbuf redacted_header
= STRBUF_INIT
;
700 while (isspace(*sensitive_header
))
703 cookie
= sensitive_header
;
707 char *semicolon
= strstr(cookie
, "; ");
710 equals
= strchrnul(cookie
, '=');
712 /* invalid cookie, just append and continue */
713 strbuf_addstr(&redacted_header
, cookie
);
716 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
717 strbuf_addstr(&redacted_header
, "=<redacted>");
720 * There are more cookies. (Or, for some
721 * reason, the input string ends in "; ".)
723 strbuf_addstr(&redacted_header
, "; ");
724 cookie
= semicolon
+ strlen("; ");
730 strbuf_setlen(header
, sensitive_header
- header
->buf
);
731 strbuf_addbuf(header
, &redacted_header
);
737 /* Redact headers in info */
738 static void redact_sensitive_info_header(struct strbuf
*header
)
740 const char *sensitive_header
;
743 * curl's h2h3 prints headers in info, e.g.:
744 * h2h3 [<header-name>: <header-val>]
746 if (trace_curl_redact
&&
747 skip_iprefix(header
->buf
, "h2h3 [", &sensitive_header
)) {
748 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
749 /* redaction ate our closing bracket */
750 strbuf_addch(header
, ']');
755 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
757 struct strbuf out
= STRBUF_INIT
;
758 struct strbuf
**headers
, **header
;
760 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
761 text
, (long)size
, (long)size
);
762 trace_strbuf(&trace_curl
, &out
);
764 strbuf_add(&out
, ptr
, size
);
765 headers
= strbuf_split_max(&out
, '\n', 0);
767 for (header
= headers
; *header
; header
++) {
768 if (hide_sensitive_header
)
769 redact_sensitive_header(*header
, 0);
770 strbuf_insertstr((*header
), 0, text
);
771 strbuf_insertstr((*header
), strlen(text
), ": ");
772 strbuf_rtrim((*header
));
773 strbuf_addch((*header
), '\n');
774 trace_strbuf(&trace_curl
, (*header
));
776 strbuf_list_free(headers
);
777 strbuf_release(&out
);
780 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
783 struct strbuf out
= STRBUF_INIT
;
784 unsigned int width
= 60;
786 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
787 text
, (long)size
, (long)size
);
788 trace_strbuf(&trace_curl
, &out
);
790 for (i
= 0; i
< size
; i
+= width
) {
794 strbuf_addf(&out
, "%s: ", text
);
795 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
796 unsigned char ch
= ptr
[i
+ w
];
799 (ch
>= 0x20) && (ch
< 0x80)
802 strbuf_addch(&out
, '\n');
803 trace_strbuf(&trace_curl
, &out
);
805 strbuf_release(&out
);
808 static void curl_dump_info(char *data
, size_t size
)
810 struct strbuf buf
= STRBUF_INIT
;
812 strbuf_add(&buf
, data
, size
);
814 redact_sensitive_info_header(&buf
);
815 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
817 strbuf_release(&buf
);
820 static int curl_trace(CURL
*handle
, curl_infotype type
, char *data
, size_t size
, void *userp
)
823 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
827 curl_dump_info(data
, size
);
829 case CURLINFO_HEADER_OUT
:
830 text
= "=> Send header";
831 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
833 case CURLINFO_DATA_OUT
:
834 if (trace_curl_data
) {
835 text
= "=> Send data";
836 curl_dump_data(text
, (unsigned char *)data
, size
);
839 case CURLINFO_SSL_DATA_OUT
:
840 if (trace_curl_data
) {
841 text
= "=> Send SSL data";
842 curl_dump_data(text
, (unsigned char *)data
, size
);
845 case CURLINFO_HEADER_IN
:
846 text
= "<= Recv header";
847 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
849 case CURLINFO_DATA_IN
:
850 if (trace_curl_data
) {
851 text
= "<= Recv data";
852 curl_dump_data(text
, (unsigned char *)data
, size
);
855 case CURLINFO_SSL_DATA_IN
:
856 if (trace_curl_data
) {
857 text
= "<= Recv SSL data";
858 curl_dump_data(text
, (unsigned char *)data
, size
);
862 default: /* we ignore unknown types by default */
868 void http_trace_curl_no_data(void)
870 trace_override_envvar(&trace_curl
, "1");
874 void setup_curl_trace(CURL
*handle
)
876 if (!trace_want(&trace_curl
))
878 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
879 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
880 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
883 static void proto_list_append(struct strbuf
*list
, const char *proto
)
888 strbuf_addch(list
, ',');
889 strbuf_addstr(list
, proto
);
892 static long get_curl_allowed_protocols(int from_user
, struct strbuf
*list
)
896 if (is_transport_allowed("http", from_user
)) {
897 bits
|= CURLPROTO_HTTP
;
898 proto_list_append(list
, "http");
900 if (is_transport_allowed("https", from_user
)) {
901 bits
|= CURLPROTO_HTTPS
;
902 proto_list_append(list
, "https");
904 if (is_transport_allowed("ftp", from_user
)) {
905 bits
|= CURLPROTO_FTP
;
906 proto_list_append(list
, "ftp");
908 if (is_transport_allowed("ftps", from_user
)) {
909 bits
|= CURLPROTO_FTPS
;
910 proto_list_append(list
, "ftps");
916 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
917 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
924 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
925 { "HTTP/2", CURL_HTTP_VERSION_2
}
928 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
929 if (!strcmp(version_string
, choice
[i
].name
)) {
930 *opt
= choice
[i
].opt_token
;
935 warning("unknown value given to http.version: '%s'", version_string
);
936 return -1; /* not found */
941 static CURL
*get_curl_handle(void)
943 CURL
*result
= curl_easy_init();
946 die("curl_easy_init failed");
948 if (!curl_ssl_verify
) {
949 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
950 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
952 /* Verify authenticity of the peer's certificate */
953 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
954 /* The name in the cert must match whom we tried to connect */
955 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
958 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
959 if (curl_http_version
) {
961 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
962 /* Set request use http version */
963 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
968 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
969 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
971 #ifdef CURLGSSAPI_DELEGATION_FLAG
974 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
975 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
976 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
977 curl_deleg_levels
[i
].curl_deleg_param
);
981 if (i
== ARRAY_SIZE(curl_deleg_levels
))
982 warning("Unknown delegation method '%s': using default",
987 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
988 !http_schannel_check_revoke
) {
989 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
990 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
992 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
996 if (http_proactive_auth
)
997 init_curl_http_auth(result
);
999 if (getenv("GIT_SSL_VERSION"))
1000 ssl_version
= getenv("GIT_SSL_VERSION");
1001 if (ssl_version
&& *ssl_version
) {
1003 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
1004 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
1005 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
1006 sslversions
[i
].ssl_version
);
1010 if (i
== ARRAY_SIZE(sslversions
))
1011 warning("unsupported ssl version %s: using default",
1015 if (getenv("GIT_SSL_CIPHER_LIST"))
1016 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
1017 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
1018 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
1022 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
1024 curl_easy_setopt(result
, CURLOPT_SSLCERTTYPE
, ssl_cert_type
);
1025 if (has_cert_password())
1026 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
1028 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
1030 curl_easy_setopt(result
, CURLOPT_SSLKEYTYPE
, ssl_key_type
);
1032 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
1033 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1035 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
1037 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1038 !http_schannel_use_ssl_cainfo
) {
1039 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
1040 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1041 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
1043 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
1045 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
1046 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1047 if (http_proxy_ssl_ca_info
)
1048 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
1052 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
1053 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
1054 curl_low_speed_limit
);
1055 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
1056 curl_low_speed_time
);
1059 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
1060 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
1062 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1064 struct strbuf buf
= STRBUF_INIT
;
1066 get_curl_allowed_protocols(0, &buf
);
1067 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS_STR
, buf
.buf
);
1070 get_curl_allowed_protocols(-1, &buf
);
1071 curl_easy_setopt(result
, CURLOPT_PROTOCOLS_STR
, buf
.buf
);
1072 strbuf_release(&buf
);
1075 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
1076 get_curl_allowed_protocols(0, NULL
));
1077 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
1078 get_curl_allowed_protocols(-1, NULL
));
1081 if (getenv("GIT_CURL_VERBOSE"))
1082 http_trace_curl_no_data();
1083 setup_curl_trace(result
);
1084 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1085 trace_curl_data
= 0;
1086 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1087 trace_curl_redact
= 0;
1089 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
1090 user_agent
? user_agent
: git_user_agent());
1092 if (curl_ftp_no_epsv
)
1093 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
1096 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
1099 * CURL also examines these variables as a fallback; but we need to query
1100 * them here in order to decide whether to prompt for missing password (cf.
1101 * init_curl_proxy_auth()).
1103 * Unlike many other common environment variables, these are historically
1104 * lowercase only. It appears that CURL did not know this and implemented
1105 * only uppercase variants, which was later corrected to take both - with
1106 * the exception of http_proxy, which is lowercase only also in CURL. As
1107 * the lowercase versions are the historical quasi-standard, they take
1108 * precedence here, as in CURL.
1110 if (!curl_http_proxy
) {
1111 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
1112 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
1113 var_override(&curl_http_proxy
, getenv("https_proxy"));
1115 var_override(&curl_http_proxy
, getenv("http_proxy"));
1117 if (!curl_http_proxy
) {
1118 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
1119 var_override(&curl_http_proxy
, getenv("all_proxy"));
1123 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1125 * Handle case with the empty http.proxy value here to keep
1126 * common code clean.
1127 * NB: empty option disables proxying at all.
1129 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1130 } else if (curl_http_proxy
) {
1131 if (starts_with(curl_http_proxy
, "socks5h"))
1132 curl_easy_setopt(result
,
1133 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1134 else if (starts_with(curl_http_proxy
, "socks5"))
1135 curl_easy_setopt(result
,
1136 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1137 else if (starts_with(curl_http_proxy
, "socks4a"))
1138 curl_easy_setopt(result
,
1139 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1140 else if (starts_with(curl_http_proxy
, "socks"))
1141 curl_easy_setopt(result
,
1142 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1143 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1144 else if (starts_with(curl_http_proxy
, "https")) {
1145 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1147 if (http_proxy_ssl_cert
)
1148 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1150 if (http_proxy_ssl_key
)
1151 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1153 if (has_proxy_cert_password())
1154 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1157 if (strstr(curl_http_proxy
, "://"))
1158 credential_from_url(&proxy_auth
, curl_http_proxy
);
1160 struct strbuf url
= STRBUF_INIT
;
1161 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1162 credential_from_url(&proxy_auth
, url
.buf
);
1163 strbuf_release(&url
);
1166 if (!proxy_auth
.host
)
1167 die("Invalid proxy URL '%s'", curl_http_proxy
);
1169 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1170 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1171 var_override(&curl_no_proxy
, getenv("no_proxy"));
1172 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1174 init_curl_proxy_auth(result
);
1176 set_curl_keepalive(result
);
1181 static void set_from_env(const char **var
, const char *envname
)
1183 const char *val
= getenv(envname
);
1188 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1190 char *low_speed_limit
;
1191 char *low_speed_time
;
1192 char *normalized_url
;
1193 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1195 config
.section
= "http";
1197 config
.collect_fn
= http_options
;
1198 config
.cascade_fn
= git_default_config
;
1201 http_is_verbose
= 0;
1202 normalized_url
= url_normalize(url
, &config
.url
);
1204 git_config(urlmatch_config_entry
, &config
);
1205 free(normalized_url
);
1206 string_list_clear(&config
.vars
, 1);
1208 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1209 if (http_ssl_backend
) {
1210 const curl_ssl_backend
**backends
;
1211 struct strbuf buf
= STRBUF_INIT
;
1214 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1215 case CURLSSLSET_UNKNOWN_BACKEND
:
1216 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1217 "Supported SSL backends:"),
1219 for (i
= 0; backends
[i
]; i
++)
1220 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1222 case CURLSSLSET_NO_BACKENDS
:
1223 die(_("Could not set SSL backend to '%s': "
1224 "cURL was built without SSL backends"),
1226 case CURLSSLSET_TOO_LATE
:
1227 die(_("Could not set SSL backend to '%s': already set"),
1235 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1236 die("curl_global_init failed");
1238 http_proactive_auth
= proactive_auth
;
1240 if (remote
&& remote
->http_proxy
)
1241 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1244 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1246 pragma_header
= curl_slist_append(http_copy_default_headers(),
1247 "Pragma: no-cache");
1248 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
1252 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1253 if (http_max_requests
)
1254 max_requests
= atoi(http_max_requests
);
1257 curlm
= curl_multi_init();
1259 die("curl_multi_init failed");
1261 if (getenv("GIT_SSL_NO_VERIFY"))
1262 curl_ssl_verify
= 0;
1264 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1265 set_from_env(&ssl_cert_type
, "GIT_SSL_CERT_TYPE");
1266 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1267 set_from_env(&ssl_key_type
, "GIT_SSL_KEY_TYPE");
1268 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1269 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1271 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1273 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1274 if (low_speed_limit
)
1275 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1276 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1278 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1280 if (curl_ssl_verify
== -1)
1281 curl_ssl_verify
= 1;
1283 curl_session_count
= 0;
1284 if (max_requests
< 1)
1285 max_requests
= DEFAULT_MAX_REQUESTS
;
1287 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1288 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1289 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1291 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1292 proxy_ssl_cert_password_required
= 1;
1294 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1295 curl_ftp_no_epsv
= 1;
1298 credential_from_url(&http_auth
, url
);
1299 if (!ssl_cert_password_required
&&
1300 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1301 starts_with(url
, "https://"))
1302 ssl_cert_password_required
= 1;
1305 curl_default
= get_curl_handle();
1308 void http_cleanup(void)
1310 struct active_request_slot
*slot
= active_queue_head
;
1312 while (slot
!= NULL
) {
1313 struct active_request_slot
*next
= slot
->next
;
1315 xmulti_remove_handle(slot
);
1316 curl_easy_cleanup(slot
->curl
);
1321 active_queue_head
= NULL
;
1323 curl_easy_cleanup(curl_default
);
1325 curl_multi_cleanup(curlm
);
1326 curl_global_cleanup();
1328 string_list_clear(&extra_http_headers
, 0);
1330 curl_slist_free_all(pragma_header
);
1331 pragma_header
= NULL
;
1333 curl_slist_free_all(no_pragma_header
);
1334 no_pragma_header
= NULL
;
1336 curl_slist_free_all(host_resolutions
);
1337 host_resolutions
= NULL
;
1339 if (curl_http_proxy
) {
1340 free((void *)curl_http_proxy
);
1341 curl_http_proxy
= NULL
;
1344 if (proxy_auth
.password
) {
1345 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1346 FREE_AND_NULL(proxy_auth
.password
);
1349 free((void *)curl_proxyuserpwd
);
1350 curl_proxyuserpwd
= NULL
;
1352 free((void *)http_proxy_authmethod
);
1353 http_proxy_authmethod
= NULL
;
1355 if (cert_auth
.password
) {
1356 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1357 FREE_AND_NULL(cert_auth
.password
);
1359 ssl_cert_password_required
= 0;
1361 if (proxy_cert_auth
.password
) {
1362 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1363 FREE_AND_NULL(proxy_cert_auth
.password
);
1365 proxy_ssl_cert_password_required
= 0;
1367 FREE_AND_NULL(cached_accept_language
);
1370 struct active_request_slot
*get_active_slot(void)
1372 struct active_request_slot
*slot
= active_queue_head
;
1373 struct active_request_slot
*newslot
;
1377 /* Wait for a slot to open up if the queue is full */
1378 while (active_requests
>= max_requests
) {
1379 curl_multi_perform(curlm
, &num_transfers
);
1380 if (num_transfers
< active_requests
)
1381 process_curl_messages();
1384 while (slot
!= NULL
&& slot
->in_use
)
1388 newslot
= xmalloc(sizeof(*newslot
));
1389 newslot
->curl
= NULL
;
1390 newslot
->in_use
= 0;
1391 newslot
->next
= NULL
;
1393 slot
= active_queue_head
;
1395 active_queue_head
= newslot
;
1397 while (slot
->next
!= NULL
)
1399 slot
->next
= newslot
;
1405 slot
->curl
= curl_easy_duphandle(curl_default
);
1406 curl_session_count
++;
1411 slot
->results
= NULL
;
1412 slot
->finished
= NULL
;
1413 slot
->callback_data
= NULL
;
1414 slot
->callback_func
= NULL
;
1415 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1416 if (curl_save_cookies
)
1417 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1418 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1419 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1420 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1421 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1422 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1423 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1424 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1425 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1426 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1427 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1428 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1431 * Default following to off unless "ALWAYS" is configured; this gives
1432 * callers a sane starting point, and they can tweak for individual
1433 * HTTP_FOLLOW_* cases themselves.
1435 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1436 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1438 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1440 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1441 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1442 if (http_auth
.password
|| curl_empty_auth_enabled())
1443 init_curl_http_auth(slot
->curl
);
1448 int start_active_slot(struct active_request_slot
*slot
)
1450 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1453 if (curlm_result
!= CURLM_OK
&&
1454 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1455 warning("curl_multi_add_handle failed: %s",
1456 curl_multi_strerror(curlm_result
));
1463 * We know there must be something to do, since we just added
1466 curl_multi_perform(curlm
, &num_transfers
);
1472 int (*fill
)(void *);
1473 struct fill_chain
*next
;
1476 static struct fill_chain
*fill_cfg
;
1478 void add_fill_function(void *data
, int (*fill
)(void *))
1480 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1481 struct fill_chain
**linkp
= &fill_cfg
;
1482 new_fill
->data
= data
;
1483 new_fill
->fill
= fill
;
1484 new_fill
->next
= NULL
;
1486 linkp
= &(*linkp
)->next
;
1490 void fill_active_slots(void)
1492 struct active_request_slot
*slot
= active_queue_head
;
1494 while (active_requests
< max_requests
) {
1495 struct fill_chain
*fill
;
1496 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1497 if (fill
->fill(fill
->data
))
1504 while (slot
!= NULL
) {
1505 if (!slot
->in_use
&& slot
->curl
!= NULL
1506 && curl_session_count
> min_curl_sessions
) {
1507 curl_easy_cleanup(slot
->curl
);
1509 curl_session_count
--;
1515 void step_active_slots(void)
1518 CURLMcode curlm_result
;
1521 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1522 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1523 if (num_transfers
< active_requests
) {
1524 process_curl_messages();
1525 fill_active_slots();
1529 void run_active_slot(struct active_request_slot
*slot
)
1535 struct timeval select_timeout
;
1538 slot
->finished
= &finished
;
1540 step_active_slots();
1544 curl_multi_timeout(curlm
, &curl_timeout
);
1545 if (curl_timeout
== 0) {
1547 } else if (curl_timeout
== -1) {
1548 select_timeout
.tv_sec
= 0;
1549 select_timeout
.tv_usec
= 50000;
1551 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1552 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1559 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1562 * It can happen that curl_multi_timeout returns a pathologically
1563 * long timeout when curl_multi_fdset returns no file descriptors
1564 * to read. See commit message for more details.
1567 (select_timeout
.tv_sec
> 0 ||
1568 select_timeout
.tv_usec
> 50000)) {
1569 select_timeout
.tv_sec
= 0;
1570 select_timeout
.tv_usec
= 50000;
1573 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1578 * The value of slot->finished we set before the loop was used
1579 * to set our "finished" variable when our request completed.
1581 * 1. The slot may not have been reused for another requst
1582 * yet, in which case it still has &finished.
1584 * 2. The slot may already be in-use to serve another request,
1585 * which can further be divided into two cases:
1587 * (a) If call run_active_slot() hasn't been called for that
1588 * other request, slot->finished would have been cleared
1589 * by get_active_slot() and has NULL.
1591 * (b) If the request did call run_active_slot(), then the
1592 * call would have updated slot->finished at the beginning
1593 * of this function, and with the clearing of the member
1594 * below, we would find that slot->finished is now NULL.
1596 * In all cases, slot->finished has no useful information to
1597 * anybody at this point. Some compilers warn us for
1598 * attempting to smuggle a pointer that is about to become
1599 * invalid, i.e. &finished. We clear it here to assure them.
1601 slot
->finished
= NULL
;
1604 static void release_active_slot(struct active_request_slot
*slot
)
1606 closedown_active_slot(slot
);
1608 xmulti_remove_handle(slot
);
1609 if (curl_session_count
> min_curl_sessions
) {
1610 curl_easy_cleanup(slot
->curl
);
1612 curl_session_count
--;
1615 fill_active_slots();
1618 void finish_all_active_slots(void)
1620 struct active_request_slot
*slot
= active_queue_head
;
1622 while (slot
!= NULL
)
1624 run_active_slot(slot
);
1625 slot
= active_queue_head
;
1631 /* Helpers for modifying and creating URLs */
1632 static inline int needs_quote(int ch
)
1634 if (((ch
>= 'A') && (ch
<= 'Z'))
1635 || ((ch
>= 'a') && (ch
<= 'z'))
1636 || ((ch
>= '0') && (ch
<= '9'))
1644 static char *quote_ref_url(const char *base
, const char *ref
)
1646 struct strbuf buf
= STRBUF_INIT
;
1650 end_url_with_slash(&buf
, base
);
1652 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1653 if (needs_quote(ch
))
1654 strbuf_addf(&buf
, "%%%02x", ch
);
1656 strbuf_addch(&buf
, *cp
);
1658 return strbuf_detach(&buf
, NULL
);
1661 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1663 int only_two_digit_prefix
)
1665 end_url_with_slash(buf
, url
);
1667 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1668 if (!only_two_digit_prefix
)
1669 strbuf_addstr(buf
, hex
+ 2);
1672 char *get_remote_object_url(const char *url
, const char *hex
,
1673 int only_two_digit_prefix
)
1675 struct strbuf buf
= STRBUF_INIT
;
1676 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1677 return strbuf_detach(&buf
, NULL
);
1680 void normalize_curl_result(CURLcode
*result
, long http_code
,
1681 char *errorstr
, size_t errorlen
)
1684 * If we see a failing http code with CURLE_OK, we have turned off
1685 * FAILONERROR (to keep the server's custom error response), and should
1686 * translate the code into failure here.
1688 * Likewise, if we see a redirect (30x code), that means we turned off
1689 * redirect-following, and we should treat the result as an error.
1691 if (*result
== CURLE_OK
&& http_code
>= 300) {
1692 *result
= CURLE_HTTP_RETURNED_ERROR
;
1694 * Normally curl will already have put the "reason phrase"
1695 * from the server into curl_errorstr; unfortunately without
1696 * FAILONERROR it is lost, so we can give only the numeric
1699 xsnprintf(errorstr
, errorlen
,
1700 "The requested URL returned error: %ld",
1705 static int handle_curl_result(struct slot_results
*results
)
1707 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1708 curl_errorstr
, sizeof(curl_errorstr
));
1710 if (results
->curl_result
== CURLE_OK
) {
1711 credential_approve(&http_auth
);
1712 credential_approve(&proxy_auth
);
1713 credential_approve(&cert_auth
);
1715 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1717 * We can't tell from here whether it's a bad path, bad
1718 * certificate, bad password, or something else wrong
1719 * with the certificate. So we reject the credential to
1720 * avoid caching or saving a bad password.
1722 credential_reject(&cert_auth
);
1724 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1725 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1726 return HTTP_NOMATCHPUBLICKEY
;
1728 } else if (missing_target(results
))
1729 return HTTP_MISSING_TARGET
;
1730 else if (results
->http_code
== 401) {
1731 if (http_auth
.username
&& http_auth
.password
) {
1732 credential_reject(&http_auth
);
1735 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1736 if (results
->auth_avail
) {
1737 http_auth_methods
&= results
->auth_avail
;
1738 http_auth_methods_restricted
= 1;
1743 if (results
->http_connectcode
== 407)
1744 credential_reject(&proxy_auth
);
1745 if (!curl_errorstr
[0])
1746 strlcpy(curl_errorstr
,
1747 curl_easy_strerror(results
->curl_result
),
1748 sizeof(curl_errorstr
));
1753 int run_one_slot(struct active_request_slot
*slot
,
1754 struct slot_results
*results
)
1756 slot
->results
= results
;
1757 if (!start_active_slot(slot
)) {
1758 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1759 "failed to start HTTP request");
1760 return HTTP_START_FAILED
;
1763 run_active_slot(slot
);
1764 return handle_curl_result(results
);
1767 struct curl_slist
*http_copy_default_headers(void)
1769 struct curl_slist
*headers
= NULL
;
1770 const struct string_list_item
*item
;
1772 for_each_string_list_item(item
, &extra_http_headers
)
1773 headers
= curl_slist_append(headers
, item
->string
);
1778 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1784 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1786 strbuf_addstr(buf
, ptr
);
1791 * Check for and extract a content-type parameter. "raw"
1792 * should be positioned at the start of the potential
1793 * parameter, with any whitespace already removed.
1795 * "name" is the name of the parameter. The value is appended
1798 static int extract_param(const char *raw
, const char *name
,
1801 size_t len
= strlen(name
);
1803 if (strncasecmp(raw
, name
, len
))
1811 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1812 strbuf_addch(out
, *raw
++);
1817 * Extract a normalized version of the content type, with any
1818 * spaces suppressed, all letters lowercased, and no trailing ";"
1821 * Note that we will silently remove even invalid whitespace. For
1822 * example, "text / plain" is specifically forbidden by RFC 2616,
1823 * but "text/plain" is the only reasonable output, and this keeps
1826 * If the "charset" argument is not NULL, store the value of any
1827 * charset parameter there.
1830 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1831 * "text / plain" -> "text/plain"
1833 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1834 struct strbuf
*charset
)
1839 strbuf_grow(type
, raw
->len
);
1840 for (p
= raw
->buf
; *p
; p
++) {
1847 strbuf_addch(type
, tolower(*p
));
1853 strbuf_reset(charset
);
1855 while (isspace(*p
) || *p
== ';')
1857 if (!extract_param(p
, "charset", charset
))
1859 while (*p
&& !isspace(*p
))
1863 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1864 strbuf_addstr(charset
, "ISO-8859-1");
1867 static void write_accept_language(struct strbuf
*buf
)
1870 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1871 * that, q-value will be smaller than 0.001, the minimum q-value the
1872 * HTTP specification allows. See
1873 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1875 const int MAX_DECIMAL_PLACES
= 3;
1876 const int MAX_LANGUAGE_TAGS
= 1000;
1877 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1878 char **language_tags
= NULL
;
1880 const char *s
= get_preferred_languages();
1882 struct strbuf tag
= STRBUF_INIT
;
1884 /* Don't add Accept-Language header if no language is preferred. */
1889 * Split the colon-separated string of preferred languages into
1890 * language_tags array.
1893 /* collect language tag */
1894 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1895 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1897 /* skip .codeset, @modifier and any other unnecessary parts */
1898 while (*s
&& *s
!= ':')
1903 REALLOC_ARRAY(language_tags
, num_langs
);
1904 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1905 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1910 /* write Accept-Language header into buf */
1912 int last_buf_len
= 0;
1918 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1919 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1921 /* compute decimal_places */
1922 for (max_q
= 1, decimal_places
= 0;
1923 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1924 decimal_places
++, max_q
*= 10)
1927 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1929 strbuf_addstr(buf
, "Accept-Language: ");
1931 for (i
= 0; i
< num_langs
; i
++) {
1933 strbuf_addstr(buf
, ", ");
1935 strbuf_addstr(buf
, language_tags
[i
]);
1938 strbuf_addf(buf
, q_format
, max_q
- i
);
1940 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1941 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1945 last_buf_len
= buf
->len
;
1949 /* free language tags -- last one is a static '*' */
1950 for (i
= 0; i
< num_langs
- 1; i
++)
1951 free(language_tags
[i
]);
1952 free(language_tags
);
1956 * Get an Accept-Language header which indicates user's preferred languages.
1960 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1961 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1962 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1963 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1964 * LANGUAGE= LANG=C -> ""
1966 const char *http_get_accept_language_header(void)
1968 if (!cached_accept_language
) {
1969 struct strbuf buf
= STRBUF_INIT
;
1970 write_accept_language(&buf
);
1972 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1975 return cached_accept_language
;
1978 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1981 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1982 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1985 /* http_request() targets */
1986 #define HTTP_REQUEST_STRBUF 0
1987 #define HTTP_REQUEST_FILE 1
1989 static int http_request(const char *url
,
1990 void *result
, int target
,
1991 const struct http_get_options
*options
)
1993 struct active_request_slot
*slot
;
1994 struct slot_results results
;
1995 struct curl_slist
*headers
= http_copy_default_headers();
1996 struct strbuf buf
= STRBUF_INIT
;
1997 const char *accept_language
;
2000 slot
= get_active_slot();
2001 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
2004 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
2006 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
2007 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
2009 if (target
== HTTP_REQUEST_FILE
) {
2010 off_t posn
= ftello(result
);
2011 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2014 http_opt_request_remainder(slot
->curl
, posn
);
2016 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2020 curl_easy_setopt(slot
->curl
, CURLOPT_HEADERFUNCTION
, fwrite_wwwauth
);
2022 accept_language
= http_get_accept_language_header();
2024 if (accept_language
)
2025 headers
= curl_slist_append(headers
, accept_language
);
2027 strbuf_addstr(&buf
, "Pragma:");
2028 if (options
&& options
->no_cache
)
2029 strbuf_addstr(&buf
, " no-cache");
2030 if (options
&& options
->initial_request
&&
2031 http_follow_config
== HTTP_FOLLOW_INITIAL
)
2032 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
2034 headers
= curl_slist_append(headers
, buf
.buf
);
2036 /* Add additional headers here */
2037 if (options
&& options
->extra_headers
) {
2038 const struct string_list_item
*item
;
2039 for_each_string_list_item(item
, options
->extra_headers
) {
2040 headers
= curl_slist_append(headers
, item
->string
);
2044 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
2045 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
2046 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
2047 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
2049 ret
= run_one_slot(slot
, &results
);
2051 if (options
&& options
->content_type
) {
2052 struct strbuf raw
= STRBUF_INIT
;
2053 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
2054 extract_content_type(&raw
, options
->content_type
,
2056 strbuf_release(&raw
);
2059 if (options
&& options
->effective_url
)
2060 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
2061 options
->effective_url
);
2063 curl_slist_free_all(headers
);
2064 strbuf_release(&buf
);
2070 * Update the "base" url to a more appropriate value, as deduced by
2071 * redirects seen when requesting a URL starting with "url".
2073 * The "asked" parameter is a URL that we asked curl to access, and must begin
2076 * The "got" parameter is the URL that curl reported to us as where we ended
2079 * Returns 1 if we updated the base url, 0 otherwise.
2081 * Our basic strategy is to compare "base" and "asked" to find the bits
2082 * specific to our request. We then strip those bits off of "got" to yield the
2083 * new base. So for example, if our base is "http://example.com/foo.git",
2084 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2085 * with "https://other.example.com/foo.git/info/refs". We would want the
2086 * new URL to become "https://other.example.com/foo.git".
2088 * Note that this assumes a sane redirect scheme. It's entirely possible
2089 * in the example above to end up at a URL that does not even end in
2090 * "info/refs". In such a case we die. There's not much we can do, such a
2091 * scheme is unlikely to represent a real git repository, and failing to
2092 * rewrite the base opens options for malicious redirects to do funny things.
2094 static int update_url_from_redirect(struct strbuf
*base
,
2096 const struct strbuf
*got
)
2101 if (!strcmp(asked
, got
->buf
))
2104 if (!skip_prefix(asked
, base
->buf
, &tail
))
2105 BUG("update_url_from_redirect: %s is not a superset of %s",
2109 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
2110 die(_("unable to update url base from redirection:\n"
2116 strbuf_add(base
, got
->buf
, new_len
);
2121 static int http_request_reauth(const char *url
,
2122 void *result
, int target
,
2123 struct http_get_options
*options
)
2125 int ret
= http_request(url
, result
, target
, options
);
2127 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2130 if (options
&& options
->effective_url
&& options
->base_url
) {
2131 if (update_url_from_redirect(options
->base_url
,
2132 url
, options
->effective_url
)) {
2133 credential_from_url(&http_auth
, options
->base_url
->buf
);
2134 url
= options
->effective_url
->buf
;
2138 if (ret
!= HTTP_REAUTH
)
2142 * The previous request may have put cruft into our output stream; we
2143 * should clear it out before making our next request.
2146 case HTTP_REQUEST_STRBUF
:
2147 strbuf_reset(result
);
2149 case HTTP_REQUEST_FILE
:
2150 if (fflush(result
)) {
2151 error_errno("unable to flush a file");
2152 return HTTP_START_FAILED
;
2155 if (ftruncate(fileno(result
), 0) < 0) {
2156 error_errno("unable to truncate a file");
2157 return HTTP_START_FAILED
;
2161 BUG("Unknown http_request target");
2164 credential_fill(&http_auth
);
2166 return http_request(url
, result
, target
, options
);
2169 int http_get_strbuf(const char *url
,
2170 struct strbuf
*result
,
2171 struct http_get_options
*options
)
2173 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2177 * Downloads a URL and stores the result in the given file.
2179 * If a previous interrupted download is detected (i.e. a previous temporary
2180 * file is still around) the download is resumed.
2182 int http_get_file(const char *url
, const char *filename
,
2183 struct http_get_options
*options
)
2186 struct strbuf tmpfile
= STRBUF_INIT
;
2189 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2190 result
= fopen(tmpfile
.buf
, "a");
2192 error("Unable to open local file %s", tmpfile
.buf
);
2197 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2200 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2203 strbuf_release(&tmpfile
);
2207 int http_fetch_ref(const char *base
, struct ref
*ref
)
2209 struct http_get_options options
= {0};
2211 struct strbuf buffer
= STRBUF_INIT
;
2214 options
.no_cache
= 1;
2216 url
= quote_ref_url(base
, ref
->name
);
2217 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2218 strbuf_rtrim(&buffer
);
2219 if (buffer
.len
== the_hash_algo
->hexsz
)
2220 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2221 else if (starts_with(buffer
.buf
, "ref: ")) {
2222 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2227 strbuf_release(&buffer
);
2232 /* Helpers for fetching packs */
2233 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2236 struct strbuf buf
= STRBUF_INIT
;
2238 if (http_is_verbose
)
2239 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2241 end_url_with_slash(&buf
, base_url
);
2242 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2243 url
= strbuf_detach(&buf
, NULL
);
2245 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2246 tmp
= strbuf_detach(&buf
, NULL
);
2248 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2249 error("Unable to get pack index %s", url
);
2257 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2258 unsigned char *sha1
, const char *base_url
)
2260 struct packed_git
*new_pack
;
2261 char *tmp_idx
= NULL
;
2264 if (has_pack_index(sha1
)) {
2265 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2267 return -1; /* parse_pack_index() already issued error message */
2271 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2275 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2280 return -1; /* parse_pack_index() already issued error message */
2283 ret
= verify_pack_index(new_pack
);
2285 close_pack_index(new_pack
);
2286 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2293 new_pack
->next
= *packs_head
;
2294 *packs_head
= new_pack
;
2298 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2300 struct http_get_options options
= {0};
2304 struct strbuf buf
= STRBUF_INIT
;
2305 struct object_id oid
;
2307 end_url_with_slash(&buf
, base_url
);
2308 strbuf_addstr(&buf
, "objects/info/packs");
2309 url
= strbuf_detach(&buf
, NULL
);
2311 options
.no_cache
= 1;
2312 ret
= http_get_strbuf(url
, &buf
, &options
);
2318 if (skip_prefix(data
, "P pack-", &data
) &&
2319 !parse_oid_hex(data
, &oid
, &data
) &&
2320 skip_prefix(data
, ".pack", &data
) &&
2321 (*data
== '\n' || *data
== '\0')) {
2322 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2324 data
= strchrnul(data
, '\n');
2327 data
++; /* skip past newline */
2335 void release_http_pack_request(struct http_pack_request
*preq
)
2337 if (preq
->packfile
) {
2338 fclose(preq
->packfile
);
2339 preq
->packfile
= NULL
;
2342 strbuf_release(&preq
->tmpfile
);
2347 static const char *default_index_pack_args
[] =
2348 {"index-pack", "--stdin", NULL
};
2350 int finish_http_pack_request(struct http_pack_request
*preq
)
2352 struct child_process ip
= CHILD_PROCESS_INIT
;
2356 fclose(preq
->packfile
);
2357 preq
->packfile
= NULL
;
2359 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2363 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2364 preq
->index_pack_args
:
2365 default_index_pack_args
);
2367 if (preq
->preserve_index_pack_stdout
)
2372 if (run_command(&ip
)) {
2379 unlink(preq
->tmpfile
.buf
);
2383 void http_install_packfile(struct packed_git
*p
,
2384 struct packed_git
**list_to_remove_from
)
2386 struct packed_git
**lst
= list_to_remove_from
;
2389 lst
= &((*lst
)->next
);
2390 *lst
= (*lst
)->next
;
2392 install_packed_git(the_repository
, p
);
2395 struct http_pack_request
*new_http_pack_request(
2396 const unsigned char *packed_git_hash
, const char *base_url
) {
2398 struct strbuf buf
= STRBUF_INIT
;
2400 end_url_with_slash(&buf
, base_url
);
2401 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2402 hash_to_hex(packed_git_hash
));
2403 return new_direct_http_pack_request(packed_git_hash
,
2404 strbuf_detach(&buf
, NULL
));
2407 struct http_pack_request
*new_direct_http_pack_request(
2408 const unsigned char *packed_git_hash
, char *url
)
2410 off_t prev_posn
= 0;
2411 struct http_pack_request
*preq
;
2413 CALLOC_ARRAY(preq
, 1);
2414 strbuf_init(&preq
->tmpfile
, 0);
2418 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2419 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2420 if (!preq
->packfile
) {
2421 error("Unable to open local file %s for pack",
2426 preq
->slot
= get_active_slot();
2427 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2428 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2429 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2430 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
2434 * If there is data present from a previous transfer attempt,
2435 * resume where it left off
2437 prev_posn
= ftello(preq
->packfile
);
2439 if (http_is_verbose
)
2441 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2442 hash_to_hex(packed_git_hash
),
2443 (uintmax_t)prev_posn
);
2444 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2450 strbuf_release(&preq
->tmpfile
);
2456 /* Helpers for fetching objects (loose) */
2457 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2460 unsigned char expn
[4096];
2461 size_t size
= eltsize
* nmemb
;
2463 struct http_object_request
*freq
= data
;
2464 struct active_request_slot
*slot
= freq
->slot
;
2467 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2470 BUG("curl_easy_getinfo for HTTP code failed: %s",
2471 curl_easy_strerror(c
));
2472 if (slot
->http_code
>= 300)
2477 ssize_t retval
= xwrite(freq
->localfile
,
2478 (char *) ptr
+ posn
, size
- posn
);
2480 return posn
/ eltsize
;
2482 } while (posn
< size
);
2484 freq
->stream
.avail_in
= size
;
2485 freq
->stream
.next_in
= (void *)ptr
;
2487 freq
->stream
.next_out
= expn
;
2488 freq
->stream
.avail_out
= sizeof(expn
);
2489 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2490 the_hash_algo
->update_fn(&freq
->c
, expn
,
2491 sizeof(expn
) - freq
->stream
.avail_out
);
2492 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2496 struct http_object_request
*new_http_object_request(const char *base_url
,
2497 const struct object_id
*oid
)
2499 char *hex
= oid_to_hex(oid
);
2500 struct strbuf filename
= STRBUF_INIT
;
2501 struct strbuf prevfile
= STRBUF_INIT
;
2503 char prev_buf
[PREV_BUF_SIZE
];
2504 ssize_t prev_read
= 0;
2505 off_t prev_posn
= 0;
2506 struct http_object_request
*freq
;
2508 CALLOC_ARRAY(freq
, 1);
2509 strbuf_init(&freq
->tmpfile
, 0);
2510 oidcpy(&freq
->oid
, oid
);
2511 freq
->localfile
= -1;
2513 loose_object_path(the_repository
, &filename
, oid
);
2514 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2516 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2517 unlink_or_warn(prevfile
.buf
);
2518 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2519 unlink_or_warn(freq
->tmpfile
.buf
);
2520 strbuf_release(&filename
);
2522 if (freq
->localfile
!= -1)
2523 error("fd leakage in start: %d", freq
->localfile
);
2524 freq
->localfile
= open(freq
->tmpfile
.buf
,
2525 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2527 * This could have failed due to the "lazy directory creation";
2528 * try to mkdir the last path component.
2530 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2531 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2534 mkdir(freq
->tmpfile
.buf
, 0777);
2537 freq
->localfile
= open(freq
->tmpfile
.buf
,
2538 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2541 if (freq
->localfile
< 0) {
2542 error_errno("Couldn't create temporary file %s",
2547 git_inflate_init(&freq
->stream
);
2549 the_hash_algo
->init_fn(&freq
->c
);
2551 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2554 * If a previous temp file is present, process what was already
2557 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2558 if (prevlocal
!= -1) {
2560 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2562 if (fwrite_sha1_file(prev_buf
,
2565 freq
) == prev_read
) {
2566 prev_posn
+= prev_read
;
2571 } while (prev_read
> 0);
2574 unlink_or_warn(prevfile
.buf
);
2575 strbuf_release(&prevfile
);
2578 * Reset inflate/SHA1 if there was an error reading the previous temp
2579 * file; also rewind to the beginning of the local file.
2581 if (prev_read
== -1) {
2582 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2583 git_inflate_init(&freq
->stream
);
2584 the_hash_algo
->init_fn(&freq
->c
);
2587 lseek(freq
->localfile
, 0, SEEK_SET
);
2588 if (ftruncate(freq
->localfile
, 0) < 0) {
2589 error_errno("Couldn't truncate temporary file %s",
2596 freq
->slot
= get_active_slot();
2598 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2599 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2600 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2601 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2602 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2603 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2606 * If we have successfully processed data from a previous fetch
2607 * attempt, only fetch the data we don't already have.
2610 if (http_is_verbose
)
2612 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2613 hex
, (uintmax_t)prev_posn
);
2614 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2620 strbuf_release(&prevfile
);
2626 void process_http_object_request(struct http_object_request
*freq
)
2630 freq
->curl_result
= freq
->slot
->curl_result
;
2631 freq
->http_code
= freq
->slot
->http_code
;
2635 int finish_http_object_request(struct http_object_request
*freq
)
2638 struct strbuf filename
= STRBUF_INIT
;
2640 close(freq
->localfile
);
2641 freq
->localfile
= -1;
2643 process_http_object_request(freq
);
2645 if (freq
->http_code
== 416) {
2646 warning("requested range invalid; we may already have all the data.");
2647 } else if (freq
->curl_result
!= CURLE_OK
) {
2648 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2649 if (st
.st_size
== 0)
2650 unlink_or_warn(freq
->tmpfile
.buf
);
2654 git_inflate_end(&freq
->stream
);
2655 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2656 if (freq
->zret
!= Z_STREAM_END
) {
2657 unlink_or_warn(freq
->tmpfile
.buf
);
2660 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2661 unlink_or_warn(freq
->tmpfile
.buf
);
2664 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2665 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2666 strbuf_release(&filename
);
2668 return freq
->rename
;
2671 void abort_http_object_request(struct http_object_request
*freq
)
2673 unlink_or_warn(freq
->tmpfile
.buf
);
2675 release_http_object_request(freq
);
2678 void release_http_object_request(struct http_object_request
*freq
)
2680 if (freq
->localfile
!= -1) {
2681 close(freq
->localfile
);
2682 freq
->localfile
= -1;
2684 FREE_AND_NULL(freq
->url
);
2686 freq
->slot
->callback_func
= NULL
;
2687 freq
->slot
->callback_data
= NULL
;
2688 release_active_slot(freq
->slot
);
2691 strbuf_release(&freq
->tmpfile
);