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_cipherlist
;
44 static const char *ssl_version
;
49 { "sslv2", CURL_SSLVERSION_SSLv2
},
50 { "sslv3", CURL_SSLVERSION_SSLv3
},
51 { "tlsv1", CURL_SSLVERSION_TLSv1
},
52 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
53 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
54 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
55 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
57 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
58 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3
},
61 static const char *ssl_key
;
62 static const char *ssl_capath
;
63 static const char *curl_no_proxy
;
64 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
65 static const char *ssl_pinnedkey
;
67 static const char *ssl_cainfo
;
68 static long curl_low_speed_limit
= -1;
69 static long curl_low_speed_time
= -1;
70 static int curl_ftp_no_epsv
;
71 static const char *curl_http_proxy
;
72 static const char *http_proxy_authmethod
;
74 static const char *http_proxy_ssl_cert
;
75 static const char *http_proxy_ssl_key
;
76 static const char *http_proxy_ssl_ca_info
;
77 static struct credential proxy_cert_auth
= CREDENTIAL_INIT
;
78 static int proxy_ssl_cert_password_required
;
83 } proxy_authmethods
[] = {
84 { "basic", CURLAUTH_BASIC
},
85 { "digest", CURLAUTH_DIGEST
},
86 { "negotiate", CURLAUTH_GSSNEGOTIATE
},
87 { "ntlm", CURLAUTH_NTLM
},
88 { "anyauth", CURLAUTH_ANY
},
90 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
91 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
95 #ifdef CURLGSSAPI_DELEGATION_FLAG
96 static const char *curl_deleg
;
99 long curl_deleg_param
;
100 } curl_deleg_levels
[] = {
101 { "none", CURLGSSAPI_DELEGATION_NONE
},
102 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG
},
103 { "always", CURLGSSAPI_DELEGATION_FLAG
},
107 static struct credential proxy_auth
= CREDENTIAL_INIT
;
108 static const char *curl_proxyuserpwd
;
109 static const char *curl_cookie_file
;
110 static int curl_save_cookies
;
111 struct credential http_auth
= CREDENTIAL_INIT
;
112 static int http_proactive_auth
;
113 static const char *user_agent
;
114 static int curl_empty_auth
= -1;
116 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
118 static struct credential cert_auth
= CREDENTIAL_INIT
;
119 static int ssl_cert_password_required
;
120 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
121 static int http_auth_methods_restricted
;
122 /* Modes for which empty_auth cannot actually help us. */
123 static unsigned long empty_auth_useless
=
128 static struct curl_slist
*pragma_header
;
129 static struct curl_slist
*no_pragma_header
;
130 static struct string_list extra_http_headers
= STRING_LIST_INIT_DUP
;
132 static struct curl_slist
*host_resolutions
;
134 static struct active_request_slot
*active_queue_head
;
136 static char *cached_accept_language
;
138 static char *http_ssl_backend
;
140 static int http_schannel_check_revoke
= 1;
142 * With the backend being set to `schannel`, setting sslCAinfo would override
143 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
146 static int http_schannel_use_ssl_cainfo
;
148 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
150 size_t size
= eltsize
* nmemb
;
151 struct buffer
*buffer
= buffer_
;
153 if (size
> buffer
->buf
.len
- buffer
->posn
)
154 size
= buffer
->buf
.len
- buffer
->posn
;
155 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
156 buffer
->posn
+= size
;
158 return size
/ eltsize
;
161 int seek_buffer(void *clientp
, curl_off_t offset
, int origin
)
163 struct buffer
*buffer
= clientp
;
165 if (origin
!= SEEK_SET
)
166 BUG("seek_buffer only handles SEEK_SET");
167 if (offset
< 0 || offset
>= buffer
->buf
.len
) {
168 error("curl seek would be outside of buffer");
169 return CURL_SEEKFUNC_FAIL
;
172 buffer
->posn
= offset
;
173 return CURL_SEEKFUNC_OK
;
176 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
178 size_t size
= eltsize
* nmemb
;
179 struct strbuf
*buffer
= buffer_
;
181 strbuf_add(buffer
, ptr
, size
);
186 * A folded header continuation line starts with any number of spaces or
187 * horizontal tab characters (SP or HTAB) as per RFC 7230 section 3.2.
188 * It is not a continuation line if the line starts with any other character.
190 static inline int is_hdr_continuation(const char *ptr
, const size_t size
)
192 return size
&& (*ptr
== ' ' || *ptr
== '\t');
195 static size_t fwrite_wwwauth(char *ptr
, size_t eltsize
, size_t nmemb
, void *p
)
197 size_t size
= eltsize
* nmemb
;
198 struct strvec
*values
= &http_auth
.wwwauth_headers
;
199 struct strbuf buf
= STRBUF_INIT
;
204 * Header lines may not come NULL-terminated from libcurl so we must
205 * limit all scans to the maximum length of the header line, or leverage
206 * strbufs for all operations.
208 * In addition, it is possible that header values can be split over
209 * multiple lines as per RFC 7230. 'Line folding' has been deprecated
210 * but older servers may still emit them. A continuation header field
211 * value is identified as starting with a space or horizontal tab.
213 * The formal definition of a header field as given in RFC 7230 is:
215 * header-field = field-name ":" OWS field-value OWS
218 * field-value = *( field-content / obs-fold )
219 * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
220 * field-vchar = VCHAR / obs-text
222 * obs-fold = CRLF 1*( SP / HTAB )
223 * ; obsolete line folding
224 * ; see Section 3.2.4
227 /* Start of a new WWW-Authenticate header */
228 if (skip_iprefix_mem(ptr
, size
, "www-authenticate:", &val
, &val_len
)) {
229 strbuf_add(&buf
, val
, val_len
);
232 * Strip the CRLF that should be present at the end of each
233 * field as well as any trailing or leading whitespace from the
238 strvec_push(values
, buf
.buf
);
239 http_auth
.header_is_last_match
= 1;
244 * This line could be a continuation of the previously matched header
245 * field. If this is the case then we should append this value to the
246 * end of the previously consumed value.
248 if (http_auth
.header_is_last_match
&& is_hdr_continuation(ptr
, size
)) {
250 * Trim the CRLF and any leading or trailing from this line.
252 strbuf_add(&buf
, ptr
, size
);
256 * At this point we should always have at least one existing
257 * value, even if it is empty. Do not bother appending the new
258 * value if this continuation header is itself empty.
261 BUG("should have at least one existing header value");
262 } else if (buf
.len
) {
263 char *prev
= xstrdup(values
->v
[values
->nr
- 1]);
265 /* Join two non-empty values with a single space. */
266 const char *const sp
= *prev
? " " : "";
269 strvec_pushf(values
, "%s%s%s", prev
, sp
, buf
.buf
);
276 /* Not a continuation of a previously matched auth header line. */
277 http_auth
.header_is_last_match
= 0;
280 * If this is a HTTP status line and not a header field, this signals
281 * a different HTTP response. libcurl writes all the output of all
282 * response headers of all responses, including redirects.
283 * We only care about the last HTTP request response's headers so clear
284 * the existing array.
286 if (skip_iprefix_mem(ptr
, size
, "http/", &val
, &val_len
))
287 strvec_clear(values
);
290 strbuf_release(&buf
);
294 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
299 static void closedown_active_slot(struct active_request_slot
*slot
)
305 static void finish_active_slot(struct active_request_slot
*slot
)
307 closedown_active_slot(slot
);
308 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
311 (*slot
->finished
) = 1;
313 /* Store slot results so they can be read after the slot is reused */
315 slot
->results
->curl_result
= slot
->curl_result
;
316 slot
->results
->http_code
= slot
->http_code
;
317 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
318 &slot
->results
->auth_avail
);
320 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
321 &slot
->results
->http_connectcode
);
324 /* Run callback if appropriate */
325 if (slot
->callback_func
)
326 slot
->callback_func(slot
->callback_data
);
329 static void xmulti_remove_handle(struct active_request_slot
*slot
)
331 curl_multi_remove_handle(curlm
, slot
->curl
);
334 static void process_curl_messages(void)
337 struct active_request_slot
*slot
;
338 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
340 while (curl_message
!= NULL
) {
341 if (curl_message
->msg
== CURLMSG_DONE
) {
342 int curl_result
= curl_message
->data
.result
;
343 slot
= active_queue_head
;
344 while (slot
!= NULL
&&
345 slot
->curl
!= curl_message
->easy_handle
)
348 xmulti_remove_handle(slot
);
349 slot
->curl_result
= curl_result
;
350 finish_active_slot(slot
);
352 fprintf(stderr
, "Received DONE message for unknown request!\n");
355 fprintf(stderr
, "Unknown CURL message received: %d\n",
356 (int)curl_message
->msg
);
358 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
362 static int http_options(const char *var
, const char *value
, void *cb
)
364 if (!strcmp("http.version", var
)) {
365 return git_config_string(&curl_http_version
, var
, value
);
367 if (!strcmp("http.sslverify", var
)) {
368 curl_ssl_verify
= git_config_bool(var
, value
);
371 if (!strcmp("http.sslcipherlist", var
))
372 return git_config_string(&ssl_cipherlist
, var
, value
);
373 if (!strcmp("http.sslversion", var
))
374 return git_config_string(&ssl_version
, var
, value
);
375 if (!strcmp("http.sslcert", var
))
376 return git_config_pathname(&ssl_cert
, var
, value
);
377 if (!strcmp("http.sslkey", var
))
378 return git_config_pathname(&ssl_key
, var
, value
);
379 if (!strcmp("http.sslcapath", var
))
380 return git_config_pathname(&ssl_capath
, var
, value
);
381 if (!strcmp("http.sslcainfo", var
))
382 return git_config_pathname(&ssl_cainfo
, var
, value
);
383 if (!strcmp("http.sslcertpasswordprotected", var
)) {
384 ssl_cert_password_required
= git_config_bool(var
, value
);
387 if (!strcmp("http.ssltry", var
)) {
388 curl_ssl_try
= git_config_bool(var
, value
);
391 if (!strcmp("http.sslbackend", var
)) {
392 free(http_ssl_backend
);
393 http_ssl_backend
= xstrdup_or_null(value
);
397 if (!strcmp("http.schannelcheckrevoke", var
)) {
398 http_schannel_check_revoke
= git_config_bool(var
, value
);
402 if (!strcmp("http.schannelusesslcainfo", var
)) {
403 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
407 if (!strcmp("http.minsessions", var
)) {
408 min_curl_sessions
= git_config_int(var
, value
);
409 if (min_curl_sessions
> 1)
410 min_curl_sessions
= 1;
413 if (!strcmp("http.maxrequests", var
)) {
414 max_requests
= git_config_int(var
, value
);
417 if (!strcmp("http.lowspeedlimit", var
)) {
418 curl_low_speed_limit
= (long)git_config_int(var
, value
);
421 if (!strcmp("http.lowspeedtime", var
)) {
422 curl_low_speed_time
= (long)git_config_int(var
, value
);
426 if (!strcmp("http.noepsv", var
)) {
427 curl_ftp_no_epsv
= git_config_bool(var
, value
);
430 if (!strcmp("http.proxy", var
))
431 return git_config_string(&curl_http_proxy
, var
, value
);
433 if (!strcmp("http.proxyauthmethod", var
))
434 return git_config_string(&http_proxy_authmethod
, var
, value
);
436 if (!strcmp("http.proxysslcert", var
))
437 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
439 if (!strcmp("http.proxysslkey", var
))
440 return git_config_string(&http_proxy_ssl_key
, var
, value
);
442 if (!strcmp("http.proxysslcainfo", var
))
443 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
445 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
446 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
450 if (!strcmp("http.cookiefile", var
))
451 return git_config_pathname(&curl_cookie_file
, var
, value
);
452 if (!strcmp("http.savecookies", var
)) {
453 curl_save_cookies
= git_config_bool(var
, value
);
457 if (!strcmp("http.postbuffer", var
)) {
458 http_post_buffer
= git_config_ssize_t(var
, value
);
459 if (http_post_buffer
< 0)
460 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
461 if (http_post_buffer
< LARGE_PACKET_MAX
)
462 http_post_buffer
= LARGE_PACKET_MAX
;
466 if (!strcmp("http.useragent", var
))
467 return git_config_string(&user_agent
, var
, value
);
469 if (!strcmp("http.emptyauth", var
)) {
470 if (value
&& !strcmp("auto", value
))
471 curl_empty_auth
= -1;
473 curl_empty_auth
= git_config_bool(var
, value
);
477 if (!strcmp("http.delegation", var
)) {
478 #ifdef CURLGSSAPI_DELEGATION_FLAG
479 return git_config_string(&curl_deleg
, var
, value
);
481 warning(_("Delegation control is not supported with cURL < 7.22.0"));
486 if (!strcmp("http.pinnedpubkey", var
)) {
487 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
488 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
490 warning(_("Public key pinning not supported with cURL < 7.39.0"));
495 if (!strcmp("http.extraheader", var
)) {
497 return config_error_nonbool(var
);
498 } else if (!*value
) {
499 string_list_clear(&extra_http_headers
, 0);
501 string_list_append(&extra_http_headers
, value
);
506 if (!strcmp("http.curloptresolve", var
)) {
508 return config_error_nonbool(var
);
509 } else if (!*value
) {
510 curl_slist_free_all(host_resolutions
);
511 host_resolutions
= NULL
;
513 host_resolutions
= curl_slist_append(host_resolutions
, value
);
518 if (!strcmp("http.followredirects", var
)) {
519 if (value
&& !strcmp(value
, "initial"))
520 http_follow_config
= HTTP_FOLLOW_INITIAL
;
521 else if (git_config_bool(var
, value
))
522 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
524 http_follow_config
= HTTP_FOLLOW_NONE
;
528 /* Fall back on the default ones */
529 return git_default_config(var
, value
, cb
);
532 static int curl_empty_auth_enabled(void)
534 if (curl_empty_auth
>= 0)
535 return curl_empty_auth
;
538 * In the automatic case, kick in the empty-auth
539 * hack as long as we would potentially try some
540 * method more exotic than "Basic" or "Digest".
542 * But only do this when this is our second or
543 * subsequent request, as by then we know what
544 * methods are available.
546 if (http_auth_methods_restricted
&&
547 (http_auth_methods
& ~empty_auth_useless
))
552 static void init_curl_http_auth(CURL
*result
)
554 if (!http_auth
.username
|| !*http_auth
.username
) {
555 if (curl_empty_auth_enabled())
556 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
560 credential_fill(&http_auth
);
562 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
563 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
566 /* *var must be free-able */
567 static void var_override(const char **var
, char *value
)
571 *var
= xstrdup(value
);
575 static void set_proxyauth_name_password(CURL
*result
)
577 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
578 proxy_auth
.username
);
579 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
580 proxy_auth
.password
);
583 static void init_curl_proxy_auth(CURL
*result
)
585 if (proxy_auth
.username
) {
586 if (!proxy_auth
.password
)
587 credential_fill(&proxy_auth
);
588 set_proxyauth_name_password(result
);
591 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
593 if (http_proxy_authmethod
) {
595 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
596 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
597 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
598 proxy_authmethods
[i
].curlauth_param
);
602 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
603 warning("unsupported proxy authentication method %s: using anyauth",
604 http_proxy_authmethod
);
605 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
609 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
612 static int has_cert_password(void)
614 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
616 if (!cert_auth
.password
) {
617 cert_auth
.protocol
= xstrdup("cert");
618 cert_auth
.host
= xstrdup("");
619 cert_auth
.username
= xstrdup("");
620 cert_auth
.path
= xstrdup(ssl_cert
);
621 credential_fill(&cert_auth
);
626 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
627 static int has_proxy_cert_password(void)
629 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
631 if (!proxy_cert_auth
.password
) {
632 proxy_cert_auth
.protocol
= xstrdup("cert");
633 proxy_cert_auth
.host
= xstrdup("");
634 proxy_cert_auth
.username
= xstrdup("");
635 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
636 credential_fill(&proxy_cert_auth
);
642 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
643 static void set_curl_keepalive(CURL
*c
)
645 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
649 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
653 socklen_t len
= (socklen_t
)sizeof(ka
);
655 if (type
!= CURLSOCKTYPE_IPCXN
)
658 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
660 warning_errno("unable to set SO_KEEPALIVE on socket");
662 return CURL_SOCKOPT_OK
;
665 static void set_curl_keepalive(CURL
*c
)
667 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
671 /* Return 1 if redactions have been made, 0 otherwise. */
672 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
675 const char *sensitive_header
;
677 if (trace_curl_redact
&&
678 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
679 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
680 /* The first token is the type, which is OK to log */
681 while (isspace(*sensitive_header
))
683 while (*sensitive_header
&& !isspace(*sensitive_header
))
685 /* Everything else is opaque and possibly sensitive */
686 strbuf_setlen(header
, sensitive_header
- header
->buf
);
687 strbuf_addstr(header
, " <redacted>");
689 } else if (trace_curl_redact
&&
690 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
691 struct strbuf redacted_header
= STRBUF_INIT
;
694 while (isspace(*sensitive_header
))
697 cookie
= sensitive_header
;
701 char *semicolon
= strstr(cookie
, "; ");
704 equals
= strchrnul(cookie
, '=');
706 /* invalid cookie, just append and continue */
707 strbuf_addstr(&redacted_header
, cookie
);
710 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
711 strbuf_addstr(&redacted_header
, "=<redacted>");
714 * There are more cookies. (Or, for some
715 * reason, the input string ends in "; ".)
717 strbuf_addstr(&redacted_header
, "; ");
718 cookie
= semicolon
+ strlen("; ");
724 strbuf_setlen(header
, sensitive_header
- header
->buf
);
725 strbuf_addbuf(header
, &redacted_header
);
731 /* Redact headers in info */
732 static void redact_sensitive_info_header(struct strbuf
*header
)
734 const char *sensitive_header
;
737 * curl's h2h3 prints headers in info, e.g.:
738 * h2h3 [<header-name>: <header-val>]
740 if (trace_curl_redact
&&
741 skip_iprefix(header
->buf
, "h2h3 [", &sensitive_header
)) {
742 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
743 /* redaction ate our closing bracket */
744 strbuf_addch(header
, ']');
749 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
751 struct strbuf out
= STRBUF_INIT
;
752 struct strbuf
**headers
, **header
;
754 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
755 text
, (long)size
, (long)size
);
756 trace_strbuf(&trace_curl
, &out
);
758 strbuf_add(&out
, ptr
, size
);
759 headers
= strbuf_split_max(&out
, '\n', 0);
761 for (header
= headers
; *header
; header
++) {
762 if (hide_sensitive_header
)
763 redact_sensitive_header(*header
, 0);
764 strbuf_insertstr((*header
), 0, text
);
765 strbuf_insertstr((*header
), strlen(text
), ": ");
766 strbuf_rtrim((*header
));
767 strbuf_addch((*header
), '\n');
768 trace_strbuf(&trace_curl
, (*header
));
770 strbuf_list_free(headers
);
771 strbuf_release(&out
);
774 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
777 struct strbuf out
= STRBUF_INIT
;
778 unsigned int width
= 60;
780 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
781 text
, (long)size
, (long)size
);
782 trace_strbuf(&trace_curl
, &out
);
784 for (i
= 0; i
< size
; i
+= width
) {
788 strbuf_addf(&out
, "%s: ", text
);
789 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
790 unsigned char ch
= ptr
[i
+ w
];
793 (ch
>= 0x20) && (ch
< 0x80)
796 strbuf_addch(&out
, '\n');
797 trace_strbuf(&trace_curl
, &out
);
799 strbuf_release(&out
);
802 static void curl_dump_info(char *data
, size_t size
)
804 struct strbuf buf
= STRBUF_INIT
;
806 strbuf_add(&buf
, data
, size
);
808 redact_sensitive_info_header(&buf
);
809 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
811 strbuf_release(&buf
);
814 static int curl_trace(CURL
*handle
, curl_infotype type
, char *data
, size_t size
, void *userp
)
817 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
821 curl_dump_info(data
, size
);
823 case CURLINFO_HEADER_OUT
:
824 text
= "=> Send header";
825 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
827 case CURLINFO_DATA_OUT
:
828 if (trace_curl_data
) {
829 text
= "=> Send data";
830 curl_dump_data(text
, (unsigned char *)data
, size
);
833 case CURLINFO_SSL_DATA_OUT
:
834 if (trace_curl_data
) {
835 text
= "=> Send SSL data";
836 curl_dump_data(text
, (unsigned char *)data
, size
);
839 case CURLINFO_HEADER_IN
:
840 text
= "<= Recv header";
841 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
843 case CURLINFO_DATA_IN
:
844 if (trace_curl_data
) {
845 text
= "<= Recv data";
846 curl_dump_data(text
, (unsigned char *)data
, size
);
849 case CURLINFO_SSL_DATA_IN
:
850 if (trace_curl_data
) {
851 text
= "<= Recv SSL data";
852 curl_dump_data(text
, (unsigned char *)data
, size
);
856 default: /* we ignore unknown types by default */
862 void http_trace_curl_no_data(void)
864 trace_override_envvar(&trace_curl
, "1");
868 void setup_curl_trace(CURL
*handle
)
870 if (!trace_want(&trace_curl
))
872 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
873 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
874 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
877 static void proto_list_append(struct strbuf
*list
, const char *proto
)
882 strbuf_addch(list
, ',');
883 strbuf_addstr(list
, proto
);
886 static long get_curl_allowed_protocols(int from_user
, struct strbuf
*list
)
890 if (is_transport_allowed("http", from_user
)) {
891 bits
|= CURLPROTO_HTTP
;
892 proto_list_append(list
, "http");
894 if (is_transport_allowed("https", from_user
)) {
895 bits
|= CURLPROTO_HTTPS
;
896 proto_list_append(list
, "https");
898 if (is_transport_allowed("ftp", from_user
)) {
899 bits
|= CURLPROTO_FTP
;
900 proto_list_append(list
, "ftp");
902 if (is_transport_allowed("ftps", from_user
)) {
903 bits
|= CURLPROTO_FTPS
;
904 proto_list_append(list
, "ftps");
910 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
911 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
918 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
919 { "HTTP/2", CURL_HTTP_VERSION_2
}
922 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
923 if (!strcmp(version_string
, choice
[i
].name
)) {
924 *opt
= choice
[i
].opt_token
;
929 warning("unknown value given to http.version: '%s'", version_string
);
930 return -1; /* not found */
935 static CURL
*get_curl_handle(void)
937 CURL
*result
= curl_easy_init();
940 die("curl_easy_init failed");
942 if (!curl_ssl_verify
) {
943 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
944 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
946 /* Verify authenticity of the peer's certificate */
947 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
948 /* The name in the cert must match whom we tried to connect */
949 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
952 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
953 if (curl_http_version
) {
955 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
956 /* Set request use http version */
957 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
962 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
963 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
965 #ifdef CURLGSSAPI_DELEGATION_FLAG
968 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
969 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
970 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
971 curl_deleg_levels
[i
].curl_deleg_param
);
975 if (i
== ARRAY_SIZE(curl_deleg_levels
))
976 warning("Unknown delegation method '%s': using default",
981 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
982 !http_schannel_check_revoke
) {
983 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
984 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
986 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
990 if (http_proactive_auth
)
991 init_curl_http_auth(result
);
993 if (getenv("GIT_SSL_VERSION"))
994 ssl_version
= getenv("GIT_SSL_VERSION");
995 if (ssl_version
&& *ssl_version
) {
997 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
998 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
999 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
1000 sslversions
[i
].ssl_version
);
1004 if (i
== ARRAY_SIZE(sslversions
))
1005 warning("unsupported ssl version %s: using default",
1009 if (getenv("GIT_SSL_CIPHER_LIST"))
1010 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
1011 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
1012 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
1016 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
1017 if (has_cert_password())
1018 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
1020 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
1022 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
1023 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1025 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
1027 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1028 !http_schannel_use_ssl_cainfo
) {
1029 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
1030 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1031 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
1033 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
1035 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
1036 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1037 if (http_proxy_ssl_ca_info
)
1038 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
1042 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
1043 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
1044 curl_low_speed_limit
);
1045 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
1046 curl_low_speed_time
);
1049 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
1050 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
1052 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1054 struct strbuf buf
= STRBUF_INIT
;
1056 get_curl_allowed_protocols(0, &buf
);
1057 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS_STR
, buf
.buf
);
1060 get_curl_allowed_protocols(-1, &buf
);
1061 curl_easy_setopt(result
, CURLOPT_PROTOCOLS_STR
, buf
.buf
);
1062 strbuf_release(&buf
);
1065 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
1066 get_curl_allowed_protocols(0, NULL
));
1067 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
1068 get_curl_allowed_protocols(-1, NULL
));
1071 if (getenv("GIT_CURL_VERBOSE"))
1072 http_trace_curl_no_data();
1073 setup_curl_trace(result
);
1074 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1075 trace_curl_data
= 0;
1076 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1077 trace_curl_redact
= 0;
1079 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
1080 user_agent
? user_agent
: git_user_agent());
1082 if (curl_ftp_no_epsv
)
1083 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
1086 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
1089 * CURL also examines these variables as a fallback; but we need to query
1090 * them here in order to decide whether to prompt for missing password (cf.
1091 * init_curl_proxy_auth()).
1093 * Unlike many other common environment variables, these are historically
1094 * lowercase only. It appears that CURL did not know this and implemented
1095 * only uppercase variants, which was later corrected to take both - with
1096 * the exception of http_proxy, which is lowercase only also in CURL. As
1097 * the lowercase versions are the historical quasi-standard, they take
1098 * precedence here, as in CURL.
1100 if (!curl_http_proxy
) {
1101 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
1102 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
1103 var_override(&curl_http_proxy
, getenv("https_proxy"));
1105 var_override(&curl_http_proxy
, getenv("http_proxy"));
1107 if (!curl_http_proxy
) {
1108 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
1109 var_override(&curl_http_proxy
, getenv("all_proxy"));
1113 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1115 * Handle case with the empty http.proxy value here to keep
1116 * common code clean.
1117 * NB: empty option disables proxying at all.
1119 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1120 } else if (curl_http_proxy
) {
1121 if (starts_with(curl_http_proxy
, "socks5h"))
1122 curl_easy_setopt(result
,
1123 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1124 else if (starts_with(curl_http_proxy
, "socks5"))
1125 curl_easy_setopt(result
,
1126 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1127 else if (starts_with(curl_http_proxy
, "socks4a"))
1128 curl_easy_setopt(result
,
1129 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1130 else if (starts_with(curl_http_proxy
, "socks"))
1131 curl_easy_setopt(result
,
1132 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1133 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1134 else if (starts_with(curl_http_proxy
, "https")) {
1135 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1137 if (http_proxy_ssl_cert
)
1138 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1140 if (http_proxy_ssl_key
)
1141 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1143 if (has_proxy_cert_password())
1144 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1147 if (strstr(curl_http_proxy
, "://"))
1148 credential_from_url(&proxy_auth
, curl_http_proxy
);
1150 struct strbuf url
= STRBUF_INIT
;
1151 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1152 credential_from_url(&proxy_auth
, url
.buf
);
1153 strbuf_release(&url
);
1156 if (!proxy_auth
.host
)
1157 die("Invalid proxy URL '%s'", curl_http_proxy
);
1159 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1160 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1161 var_override(&curl_no_proxy
, getenv("no_proxy"));
1162 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1164 init_curl_proxy_auth(result
);
1166 set_curl_keepalive(result
);
1171 static void set_from_env(const char **var
, const char *envname
)
1173 const char *val
= getenv(envname
);
1178 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1180 char *low_speed_limit
;
1181 char *low_speed_time
;
1182 char *normalized_url
;
1183 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1185 config
.section
= "http";
1187 config
.collect_fn
= http_options
;
1188 config
.cascade_fn
= git_default_config
;
1191 http_is_verbose
= 0;
1192 normalized_url
= url_normalize(url
, &config
.url
);
1194 git_config(urlmatch_config_entry
, &config
);
1195 free(normalized_url
);
1196 string_list_clear(&config
.vars
, 1);
1198 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1199 if (http_ssl_backend
) {
1200 const curl_ssl_backend
**backends
;
1201 struct strbuf buf
= STRBUF_INIT
;
1204 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1205 case CURLSSLSET_UNKNOWN_BACKEND
:
1206 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1207 "Supported SSL backends:"),
1209 for (i
= 0; backends
[i
]; i
++)
1210 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1212 case CURLSSLSET_NO_BACKENDS
:
1213 die(_("Could not set SSL backend to '%s': "
1214 "cURL was built without SSL backends"),
1216 case CURLSSLSET_TOO_LATE
:
1217 die(_("Could not set SSL backend to '%s': already set"),
1225 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1226 die("curl_global_init failed");
1228 http_proactive_auth
= proactive_auth
;
1230 if (remote
&& remote
->http_proxy
)
1231 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1234 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1236 pragma_header
= curl_slist_append(http_copy_default_headers(),
1237 "Pragma: no-cache");
1238 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
1242 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1243 if (http_max_requests
)
1244 max_requests
= atoi(http_max_requests
);
1247 curlm
= curl_multi_init();
1249 die("curl_multi_init failed");
1251 if (getenv("GIT_SSL_NO_VERIFY"))
1252 curl_ssl_verify
= 0;
1254 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1255 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1256 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1257 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1259 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1261 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1262 if (low_speed_limit
)
1263 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1264 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1266 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1268 if (curl_ssl_verify
== -1)
1269 curl_ssl_verify
= 1;
1271 curl_session_count
= 0;
1272 if (max_requests
< 1)
1273 max_requests
= DEFAULT_MAX_REQUESTS
;
1275 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1276 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1277 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1279 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1280 proxy_ssl_cert_password_required
= 1;
1282 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1283 curl_ftp_no_epsv
= 1;
1286 credential_from_url(&http_auth
, url
);
1287 if (!ssl_cert_password_required
&&
1288 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1289 starts_with(url
, "https://"))
1290 ssl_cert_password_required
= 1;
1293 curl_default
= get_curl_handle();
1296 void http_cleanup(void)
1298 struct active_request_slot
*slot
= active_queue_head
;
1300 while (slot
!= NULL
) {
1301 struct active_request_slot
*next
= slot
->next
;
1303 xmulti_remove_handle(slot
);
1304 curl_easy_cleanup(slot
->curl
);
1309 active_queue_head
= NULL
;
1311 curl_easy_cleanup(curl_default
);
1313 curl_multi_cleanup(curlm
);
1314 curl_global_cleanup();
1316 string_list_clear(&extra_http_headers
, 0);
1318 curl_slist_free_all(pragma_header
);
1319 pragma_header
= NULL
;
1321 curl_slist_free_all(no_pragma_header
);
1322 no_pragma_header
= NULL
;
1324 curl_slist_free_all(host_resolutions
);
1325 host_resolutions
= NULL
;
1327 if (curl_http_proxy
) {
1328 free((void *)curl_http_proxy
);
1329 curl_http_proxy
= NULL
;
1332 if (proxy_auth
.password
) {
1333 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1334 FREE_AND_NULL(proxy_auth
.password
);
1337 free((void *)curl_proxyuserpwd
);
1338 curl_proxyuserpwd
= NULL
;
1340 free((void *)http_proxy_authmethod
);
1341 http_proxy_authmethod
= NULL
;
1343 if (cert_auth
.password
) {
1344 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1345 FREE_AND_NULL(cert_auth
.password
);
1347 ssl_cert_password_required
= 0;
1349 if (proxy_cert_auth
.password
) {
1350 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1351 FREE_AND_NULL(proxy_cert_auth
.password
);
1353 proxy_ssl_cert_password_required
= 0;
1355 FREE_AND_NULL(cached_accept_language
);
1358 struct active_request_slot
*get_active_slot(void)
1360 struct active_request_slot
*slot
= active_queue_head
;
1361 struct active_request_slot
*newslot
;
1365 /* Wait for a slot to open up if the queue is full */
1366 while (active_requests
>= max_requests
) {
1367 curl_multi_perform(curlm
, &num_transfers
);
1368 if (num_transfers
< active_requests
)
1369 process_curl_messages();
1372 while (slot
!= NULL
&& slot
->in_use
)
1376 newslot
= xmalloc(sizeof(*newslot
));
1377 newslot
->curl
= NULL
;
1378 newslot
->in_use
= 0;
1379 newslot
->next
= NULL
;
1381 slot
= active_queue_head
;
1383 active_queue_head
= newslot
;
1385 while (slot
->next
!= NULL
)
1387 slot
->next
= newslot
;
1393 slot
->curl
= curl_easy_duphandle(curl_default
);
1394 curl_session_count
++;
1399 slot
->results
= NULL
;
1400 slot
->finished
= NULL
;
1401 slot
->callback_data
= NULL
;
1402 slot
->callback_func
= NULL
;
1403 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1404 if (curl_save_cookies
)
1405 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1406 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1407 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1408 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1409 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1410 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1411 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1412 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1413 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1414 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1415 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1416 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1419 * Default following to off unless "ALWAYS" is configured; this gives
1420 * callers a sane starting point, and they can tweak for individual
1421 * HTTP_FOLLOW_* cases themselves.
1423 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1424 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1426 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1428 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1429 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1430 if (http_auth
.password
|| curl_empty_auth_enabled())
1431 init_curl_http_auth(slot
->curl
);
1436 int start_active_slot(struct active_request_slot
*slot
)
1438 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1441 if (curlm_result
!= CURLM_OK
&&
1442 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1443 warning("curl_multi_add_handle failed: %s",
1444 curl_multi_strerror(curlm_result
));
1451 * We know there must be something to do, since we just added
1454 curl_multi_perform(curlm
, &num_transfers
);
1460 int (*fill
)(void *);
1461 struct fill_chain
*next
;
1464 static struct fill_chain
*fill_cfg
;
1466 void add_fill_function(void *data
, int (*fill
)(void *))
1468 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1469 struct fill_chain
**linkp
= &fill_cfg
;
1470 new_fill
->data
= data
;
1471 new_fill
->fill
= fill
;
1472 new_fill
->next
= NULL
;
1474 linkp
= &(*linkp
)->next
;
1478 void fill_active_slots(void)
1480 struct active_request_slot
*slot
= active_queue_head
;
1482 while (active_requests
< max_requests
) {
1483 struct fill_chain
*fill
;
1484 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1485 if (fill
->fill(fill
->data
))
1492 while (slot
!= NULL
) {
1493 if (!slot
->in_use
&& slot
->curl
!= NULL
1494 && curl_session_count
> min_curl_sessions
) {
1495 curl_easy_cleanup(slot
->curl
);
1497 curl_session_count
--;
1503 void step_active_slots(void)
1506 CURLMcode curlm_result
;
1509 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1510 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1511 if (num_transfers
< active_requests
) {
1512 process_curl_messages();
1513 fill_active_slots();
1517 void run_active_slot(struct active_request_slot
*slot
)
1523 struct timeval select_timeout
;
1526 slot
->finished
= &finished
;
1528 step_active_slots();
1532 curl_multi_timeout(curlm
, &curl_timeout
);
1533 if (curl_timeout
== 0) {
1535 } else if (curl_timeout
== -1) {
1536 select_timeout
.tv_sec
= 0;
1537 select_timeout
.tv_usec
= 50000;
1539 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1540 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1547 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1550 * It can happen that curl_multi_timeout returns a pathologically
1551 * long timeout when curl_multi_fdset returns no file descriptors
1552 * to read. See commit message for more details.
1555 (select_timeout
.tv_sec
> 0 ||
1556 select_timeout
.tv_usec
> 50000)) {
1557 select_timeout
.tv_sec
= 0;
1558 select_timeout
.tv_usec
= 50000;
1561 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1566 * The value of slot->finished we set before the loop was used
1567 * to set our "finished" variable when our request completed.
1569 * 1. The slot may not have been reused for another requst
1570 * yet, in which case it still has &finished.
1572 * 2. The slot may already be in-use to serve another request,
1573 * which can further be divided into two cases:
1575 * (a) If call run_active_slot() hasn't been called for that
1576 * other request, slot->finished would have been cleared
1577 * by get_active_slot() and has NULL.
1579 * (b) If the request did call run_active_slot(), then the
1580 * call would have updated slot->finished at the beginning
1581 * of this function, and with the clearing of the member
1582 * below, we would find that slot->finished is now NULL.
1584 * In all cases, slot->finished has no useful information to
1585 * anybody at this point. Some compilers warn us for
1586 * attempting to smuggle a pointer that is about to become
1587 * invalid, i.e. &finished. We clear it here to assure them.
1589 slot
->finished
= NULL
;
1592 static void release_active_slot(struct active_request_slot
*slot
)
1594 closedown_active_slot(slot
);
1596 xmulti_remove_handle(slot
);
1597 if (curl_session_count
> min_curl_sessions
) {
1598 curl_easy_cleanup(slot
->curl
);
1600 curl_session_count
--;
1603 fill_active_slots();
1606 void finish_all_active_slots(void)
1608 struct active_request_slot
*slot
= active_queue_head
;
1610 while (slot
!= NULL
)
1612 run_active_slot(slot
);
1613 slot
= active_queue_head
;
1619 /* Helpers for modifying and creating URLs */
1620 static inline int needs_quote(int ch
)
1622 if (((ch
>= 'A') && (ch
<= 'Z'))
1623 || ((ch
>= 'a') && (ch
<= 'z'))
1624 || ((ch
>= '0') && (ch
<= '9'))
1632 static char *quote_ref_url(const char *base
, const char *ref
)
1634 struct strbuf buf
= STRBUF_INIT
;
1638 end_url_with_slash(&buf
, base
);
1640 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1641 if (needs_quote(ch
))
1642 strbuf_addf(&buf
, "%%%02x", ch
);
1644 strbuf_addch(&buf
, *cp
);
1646 return strbuf_detach(&buf
, NULL
);
1649 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1651 int only_two_digit_prefix
)
1653 end_url_with_slash(buf
, url
);
1655 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1656 if (!only_two_digit_prefix
)
1657 strbuf_addstr(buf
, hex
+ 2);
1660 char *get_remote_object_url(const char *url
, const char *hex
,
1661 int only_two_digit_prefix
)
1663 struct strbuf buf
= STRBUF_INIT
;
1664 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1665 return strbuf_detach(&buf
, NULL
);
1668 void normalize_curl_result(CURLcode
*result
, long http_code
,
1669 char *errorstr
, size_t errorlen
)
1672 * If we see a failing http code with CURLE_OK, we have turned off
1673 * FAILONERROR (to keep the server's custom error response), and should
1674 * translate the code into failure here.
1676 * Likewise, if we see a redirect (30x code), that means we turned off
1677 * redirect-following, and we should treat the result as an error.
1679 if (*result
== CURLE_OK
&& http_code
>= 300) {
1680 *result
= CURLE_HTTP_RETURNED_ERROR
;
1682 * Normally curl will already have put the "reason phrase"
1683 * from the server into curl_errorstr; unfortunately without
1684 * FAILONERROR it is lost, so we can give only the numeric
1687 xsnprintf(errorstr
, errorlen
,
1688 "The requested URL returned error: %ld",
1693 static int handle_curl_result(struct slot_results
*results
)
1695 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1696 curl_errorstr
, sizeof(curl_errorstr
));
1698 if (results
->curl_result
== CURLE_OK
) {
1699 credential_approve(&http_auth
);
1700 credential_approve(&proxy_auth
);
1701 credential_approve(&cert_auth
);
1703 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1705 * We can't tell from here whether it's a bad path, bad
1706 * certificate, bad password, or something else wrong
1707 * with the certificate. So we reject the credential to
1708 * avoid caching or saving a bad password.
1710 credential_reject(&cert_auth
);
1712 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1713 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1714 return HTTP_NOMATCHPUBLICKEY
;
1716 } else if (missing_target(results
))
1717 return HTTP_MISSING_TARGET
;
1718 else if (results
->http_code
== 401) {
1719 if (http_auth
.username
&& http_auth
.password
) {
1720 credential_reject(&http_auth
);
1723 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1724 if (results
->auth_avail
) {
1725 http_auth_methods
&= results
->auth_avail
;
1726 http_auth_methods_restricted
= 1;
1731 if (results
->http_connectcode
== 407)
1732 credential_reject(&proxy_auth
);
1733 if (!curl_errorstr
[0])
1734 strlcpy(curl_errorstr
,
1735 curl_easy_strerror(results
->curl_result
),
1736 sizeof(curl_errorstr
));
1741 int run_one_slot(struct active_request_slot
*slot
,
1742 struct slot_results
*results
)
1744 slot
->results
= results
;
1745 if (!start_active_slot(slot
)) {
1746 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1747 "failed to start HTTP request");
1748 return HTTP_START_FAILED
;
1751 run_active_slot(slot
);
1752 return handle_curl_result(results
);
1755 struct curl_slist
*http_copy_default_headers(void)
1757 struct curl_slist
*headers
= NULL
;
1758 const struct string_list_item
*item
;
1760 for_each_string_list_item(item
, &extra_http_headers
)
1761 headers
= curl_slist_append(headers
, item
->string
);
1766 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1772 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1774 strbuf_addstr(buf
, ptr
);
1779 * Check for and extract a content-type parameter. "raw"
1780 * should be positioned at the start of the potential
1781 * parameter, with any whitespace already removed.
1783 * "name" is the name of the parameter. The value is appended
1786 static int extract_param(const char *raw
, const char *name
,
1789 size_t len
= strlen(name
);
1791 if (strncasecmp(raw
, name
, len
))
1799 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1800 strbuf_addch(out
, *raw
++);
1805 * Extract a normalized version of the content type, with any
1806 * spaces suppressed, all letters lowercased, and no trailing ";"
1809 * Note that we will silently remove even invalid whitespace. For
1810 * example, "text / plain" is specifically forbidden by RFC 2616,
1811 * but "text/plain" is the only reasonable output, and this keeps
1814 * If the "charset" argument is not NULL, store the value of any
1815 * charset parameter there.
1818 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1819 * "text / plain" -> "text/plain"
1821 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1822 struct strbuf
*charset
)
1827 strbuf_grow(type
, raw
->len
);
1828 for (p
= raw
->buf
; *p
; p
++) {
1835 strbuf_addch(type
, tolower(*p
));
1841 strbuf_reset(charset
);
1843 while (isspace(*p
) || *p
== ';')
1845 if (!extract_param(p
, "charset", charset
))
1847 while (*p
&& !isspace(*p
))
1851 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1852 strbuf_addstr(charset
, "ISO-8859-1");
1855 static void write_accept_language(struct strbuf
*buf
)
1858 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1859 * that, q-value will be smaller than 0.001, the minimum q-value the
1860 * HTTP specification allows. See
1861 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1863 const int MAX_DECIMAL_PLACES
= 3;
1864 const int MAX_LANGUAGE_TAGS
= 1000;
1865 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1866 char **language_tags
= NULL
;
1868 const char *s
= get_preferred_languages();
1870 struct strbuf tag
= STRBUF_INIT
;
1872 /* Don't add Accept-Language header if no language is preferred. */
1877 * Split the colon-separated string of preferred languages into
1878 * language_tags array.
1881 /* collect language tag */
1882 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1883 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1885 /* skip .codeset, @modifier and any other unnecessary parts */
1886 while (*s
&& *s
!= ':')
1891 REALLOC_ARRAY(language_tags
, num_langs
);
1892 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1893 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1898 /* write Accept-Language header into buf */
1900 int last_buf_len
= 0;
1906 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1907 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1909 /* compute decimal_places */
1910 for (max_q
= 1, decimal_places
= 0;
1911 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1912 decimal_places
++, max_q
*= 10)
1915 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1917 strbuf_addstr(buf
, "Accept-Language: ");
1919 for (i
= 0; i
< num_langs
; i
++) {
1921 strbuf_addstr(buf
, ", ");
1923 strbuf_addstr(buf
, language_tags
[i
]);
1926 strbuf_addf(buf
, q_format
, max_q
- i
);
1928 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1929 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1933 last_buf_len
= buf
->len
;
1937 /* free language tags -- last one is a static '*' */
1938 for (i
= 0; i
< num_langs
- 1; i
++)
1939 free(language_tags
[i
]);
1940 free(language_tags
);
1944 * Get an Accept-Language header which indicates user's preferred languages.
1948 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1949 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1950 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1951 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1952 * LANGUAGE= LANG=C -> ""
1954 const char *http_get_accept_language_header(void)
1956 if (!cached_accept_language
) {
1957 struct strbuf buf
= STRBUF_INIT
;
1958 write_accept_language(&buf
);
1960 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1963 return cached_accept_language
;
1966 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1969 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1970 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1973 /* http_request() targets */
1974 #define HTTP_REQUEST_STRBUF 0
1975 #define HTTP_REQUEST_FILE 1
1977 static int http_request(const char *url
,
1978 void *result
, int target
,
1979 const struct http_get_options
*options
)
1981 struct active_request_slot
*slot
;
1982 struct slot_results results
;
1983 struct curl_slist
*headers
= http_copy_default_headers();
1984 struct strbuf buf
= STRBUF_INIT
;
1985 const char *accept_language
;
1988 slot
= get_active_slot();
1989 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1992 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1994 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1995 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
1997 if (target
== HTTP_REQUEST_FILE
) {
1998 off_t posn
= ftello(result
);
1999 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2002 http_opt_request_remainder(slot
->curl
, posn
);
2004 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2008 curl_easy_setopt(slot
->curl
, CURLOPT_HEADERFUNCTION
, fwrite_wwwauth
);
2010 accept_language
= http_get_accept_language_header();
2012 if (accept_language
)
2013 headers
= curl_slist_append(headers
, accept_language
);
2015 strbuf_addstr(&buf
, "Pragma:");
2016 if (options
&& options
->no_cache
)
2017 strbuf_addstr(&buf
, " no-cache");
2018 if (options
&& options
->initial_request
&&
2019 http_follow_config
== HTTP_FOLLOW_INITIAL
)
2020 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
2022 headers
= curl_slist_append(headers
, buf
.buf
);
2024 /* Add additional headers here */
2025 if (options
&& options
->extra_headers
) {
2026 const struct string_list_item
*item
;
2027 for_each_string_list_item(item
, options
->extra_headers
) {
2028 headers
= curl_slist_append(headers
, item
->string
);
2032 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
2033 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
2034 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
2035 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
2037 ret
= run_one_slot(slot
, &results
);
2039 if (options
&& options
->content_type
) {
2040 struct strbuf raw
= STRBUF_INIT
;
2041 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
2042 extract_content_type(&raw
, options
->content_type
,
2044 strbuf_release(&raw
);
2047 if (options
&& options
->effective_url
)
2048 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
2049 options
->effective_url
);
2051 curl_slist_free_all(headers
);
2052 strbuf_release(&buf
);
2058 * Update the "base" url to a more appropriate value, as deduced by
2059 * redirects seen when requesting a URL starting with "url".
2061 * The "asked" parameter is a URL that we asked curl to access, and must begin
2064 * The "got" parameter is the URL that curl reported to us as where we ended
2067 * Returns 1 if we updated the base url, 0 otherwise.
2069 * Our basic strategy is to compare "base" and "asked" to find the bits
2070 * specific to our request. We then strip those bits off of "got" to yield the
2071 * new base. So for example, if our base is "http://example.com/foo.git",
2072 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2073 * with "https://other.example.com/foo.git/info/refs". We would want the
2074 * new URL to become "https://other.example.com/foo.git".
2076 * Note that this assumes a sane redirect scheme. It's entirely possible
2077 * in the example above to end up at a URL that does not even end in
2078 * "info/refs". In such a case we die. There's not much we can do, such a
2079 * scheme is unlikely to represent a real git repository, and failing to
2080 * rewrite the base opens options for malicious redirects to do funny things.
2082 static int update_url_from_redirect(struct strbuf
*base
,
2084 const struct strbuf
*got
)
2089 if (!strcmp(asked
, got
->buf
))
2092 if (!skip_prefix(asked
, base
->buf
, &tail
))
2093 BUG("update_url_from_redirect: %s is not a superset of %s",
2097 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
2098 die(_("unable to update url base from redirection:\n"
2104 strbuf_add(base
, got
->buf
, new_len
);
2109 static int http_request_reauth(const char *url
,
2110 void *result
, int target
,
2111 struct http_get_options
*options
)
2113 int ret
= http_request(url
, result
, target
, options
);
2115 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2118 if (options
&& options
->effective_url
&& options
->base_url
) {
2119 if (update_url_from_redirect(options
->base_url
,
2120 url
, options
->effective_url
)) {
2121 credential_from_url(&http_auth
, options
->base_url
->buf
);
2122 url
= options
->effective_url
->buf
;
2126 if (ret
!= HTTP_REAUTH
)
2130 * The previous request may have put cruft into our output stream; we
2131 * should clear it out before making our next request.
2134 case HTTP_REQUEST_STRBUF
:
2135 strbuf_reset(result
);
2137 case HTTP_REQUEST_FILE
:
2138 if (fflush(result
)) {
2139 error_errno("unable to flush a file");
2140 return HTTP_START_FAILED
;
2143 if (ftruncate(fileno(result
), 0) < 0) {
2144 error_errno("unable to truncate a file");
2145 return HTTP_START_FAILED
;
2149 BUG("Unknown http_request target");
2152 credential_fill(&http_auth
);
2154 return http_request(url
, result
, target
, options
);
2157 int http_get_strbuf(const char *url
,
2158 struct strbuf
*result
,
2159 struct http_get_options
*options
)
2161 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2165 * Downloads a URL and stores the result in the given file.
2167 * If a previous interrupted download is detected (i.e. a previous temporary
2168 * file is still around) the download is resumed.
2170 int http_get_file(const char *url
, const char *filename
,
2171 struct http_get_options
*options
)
2174 struct strbuf tmpfile
= STRBUF_INIT
;
2177 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2178 result
= fopen(tmpfile
.buf
, "a");
2180 error("Unable to open local file %s", tmpfile
.buf
);
2185 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2188 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2191 strbuf_release(&tmpfile
);
2195 int http_fetch_ref(const char *base
, struct ref
*ref
)
2197 struct http_get_options options
= {0};
2199 struct strbuf buffer
= STRBUF_INIT
;
2202 options
.no_cache
= 1;
2204 url
= quote_ref_url(base
, ref
->name
);
2205 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2206 strbuf_rtrim(&buffer
);
2207 if (buffer
.len
== the_hash_algo
->hexsz
)
2208 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2209 else if (starts_with(buffer
.buf
, "ref: ")) {
2210 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2215 strbuf_release(&buffer
);
2220 /* Helpers for fetching packs */
2221 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2224 struct strbuf buf
= STRBUF_INIT
;
2226 if (http_is_verbose
)
2227 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2229 end_url_with_slash(&buf
, base_url
);
2230 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2231 url
= strbuf_detach(&buf
, NULL
);
2233 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2234 tmp
= strbuf_detach(&buf
, NULL
);
2236 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2237 error("Unable to get pack index %s", url
);
2245 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2246 unsigned char *sha1
, const char *base_url
)
2248 struct packed_git
*new_pack
;
2249 char *tmp_idx
= NULL
;
2252 if (has_pack_index(sha1
)) {
2253 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2255 return -1; /* parse_pack_index() already issued error message */
2259 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2263 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2268 return -1; /* parse_pack_index() already issued error message */
2271 ret
= verify_pack_index(new_pack
);
2273 close_pack_index(new_pack
);
2274 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2281 new_pack
->next
= *packs_head
;
2282 *packs_head
= new_pack
;
2286 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2288 struct http_get_options options
= {0};
2292 struct strbuf buf
= STRBUF_INIT
;
2293 struct object_id oid
;
2295 end_url_with_slash(&buf
, base_url
);
2296 strbuf_addstr(&buf
, "objects/info/packs");
2297 url
= strbuf_detach(&buf
, NULL
);
2299 options
.no_cache
= 1;
2300 ret
= http_get_strbuf(url
, &buf
, &options
);
2306 if (skip_prefix(data
, "P pack-", &data
) &&
2307 !parse_oid_hex(data
, &oid
, &data
) &&
2308 skip_prefix(data
, ".pack", &data
) &&
2309 (*data
== '\n' || *data
== '\0')) {
2310 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2312 data
= strchrnul(data
, '\n');
2315 data
++; /* skip past newline */
2323 void release_http_pack_request(struct http_pack_request
*preq
)
2325 if (preq
->packfile
) {
2326 fclose(preq
->packfile
);
2327 preq
->packfile
= NULL
;
2330 strbuf_release(&preq
->tmpfile
);
2335 static const char *default_index_pack_args
[] =
2336 {"index-pack", "--stdin", NULL
};
2338 int finish_http_pack_request(struct http_pack_request
*preq
)
2340 struct child_process ip
= CHILD_PROCESS_INIT
;
2344 fclose(preq
->packfile
);
2345 preq
->packfile
= NULL
;
2347 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2351 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2352 preq
->index_pack_args
:
2353 default_index_pack_args
);
2355 if (preq
->preserve_index_pack_stdout
)
2360 if (run_command(&ip
)) {
2367 unlink(preq
->tmpfile
.buf
);
2371 void http_install_packfile(struct packed_git
*p
,
2372 struct packed_git
**list_to_remove_from
)
2374 struct packed_git
**lst
= list_to_remove_from
;
2377 lst
= &((*lst
)->next
);
2378 *lst
= (*lst
)->next
;
2380 install_packed_git(the_repository
, p
);
2383 struct http_pack_request
*new_http_pack_request(
2384 const unsigned char *packed_git_hash
, const char *base_url
) {
2386 struct strbuf buf
= STRBUF_INIT
;
2388 end_url_with_slash(&buf
, base_url
);
2389 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2390 hash_to_hex(packed_git_hash
));
2391 return new_direct_http_pack_request(packed_git_hash
,
2392 strbuf_detach(&buf
, NULL
));
2395 struct http_pack_request
*new_direct_http_pack_request(
2396 const unsigned char *packed_git_hash
, char *url
)
2398 off_t prev_posn
= 0;
2399 struct http_pack_request
*preq
;
2401 CALLOC_ARRAY(preq
, 1);
2402 strbuf_init(&preq
->tmpfile
, 0);
2406 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2407 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2408 if (!preq
->packfile
) {
2409 error("Unable to open local file %s for pack",
2414 preq
->slot
= get_active_slot();
2415 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2416 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2417 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2418 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
2422 * If there is data present from a previous transfer attempt,
2423 * resume where it left off
2425 prev_posn
= ftello(preq
->packfile
);
2427 if (http_is_verbose
)
2429 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2430 hash_to_hex(packed_git_hash
),
2431 (uintmax_t)prev_posn
);
2432 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2438 strbuf_release(&preq
->tmpfile
);
2444 /* Helpers for fetching objects (loose) */
2445 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2448 unsigned char expn
[4096];
2449 size_t size
= eltsize
* nmemb
;
2451 struct http_object_request
*freq
= data
;
2452 struct active_request_slot
*slot
= freq
->slot
;
2455 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2458 BUG("curl_easy_getinfo for HTTP code failed: %s",
2459 curl_easy_strerror(c
));
2460 if (slot
->http_code
>= 300)
2465 ssize_t retval
= xwrite(freq
->localfile
,
2466 (char *) ptr
+ posn
, size
- posn
);
2468 return posn
/ eltsize
;
2470 } while (posn
< size
);
2472 freq
->stream
.avail_in
= size
;
2473 freq
->stream
.next_in
= (void *)ptr
;
2475 freq
->stream
.next_out
= expn
;
2476 freq
->stream
.avail_out
= sizeof(expn
);
2477 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2478 the_hash_algo
->update_fn(&freq
->c
, expn
,
2479 sizeof(expn
) - freq
->stream
.avail_out
);
2480 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2484 struct http_object_request
*new_http_object_request(const char *base_url
,
2485 const struct object_id
*oid
)
2487 char *hex
= oid_to_hex(oid
);
2488 struct strbuf filename
= STRBUF_INIT
;
2489 struct strbuf prevfile
= STRBUF_INIT
;
2491 char prev_buf
[PREV_BUF_SIZE
];
2492 ssize_t prev_read
= 0;
2493 off_t prev_posn
= 0;
2494 struct http_object_request
*freq
;
2496 CALLOC_ARRAY(freq
, 1);
2497 strbuf_init(&freq
->tmpfile
, 0);
2498 oidcpy(&freq
->oid
, oid
);
2499 freq
->localfile
= -1;
2501 loose_object_path(the_repository
, &filename
, oid
);
2502 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2504 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2505 unlink_or_warn(prevfile
.buf
);
2506 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2507 unlink_or_warn(freq
->tmpfile
.buf
);
2508 strbuf_release(&filename
);
2510 if (freq
->localfile
!= -1)
2511 error("fd leakage in start: %d", freq
->localfile
);
2512 freq
->localfile
= open(freq
->tmpfile
.buf
,
2513 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2515 * This could have failed due to the "lazy directory creation";
2516 * try to mkdir the last path component.
2518 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2519 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2522 mkdir(freq
->tmpfile
.buf
, 0777);
2525 freq
->localfile
= open(freq
->tmpfile
.buf
,
2526 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2529 if (freq
->localfile
< 0) {
2530 error_errno("Couldn't create temporary file %s",
2535 git_inflate_init(&freq
->stream
);
2537 the_hash_algo
->init_fn(&freq
->c
);
2539 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2542 * If a previous temp file is present, process what was already
2545 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2546 if (prevlocal
!= -1) {
2548 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2550 if (fwrite_sha1_file(prev_buf
,
2553 freq
) == prev_read
) {
2554 prev_posn
+= prev_read
;
2559 } while (prev_read
> 0);
2562 unlink_or_warn(prevfile
.buf
);
2563 strbuf_release(&prevfile
);
2566 * Reset inflate/SHA1 if there was an error reading the previous temp
2567 * file; also rewind to the beginning of the local file.
2569 if (prev_read
== -1) {
2570 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2571 git_inflate_init(&freq
->stream
);
2572 the_hash_algo
->init_fn(&freq
->c
);
2575 lseek(freq
->localfile
, 0, SEEK_SET
);
2576 if (ftruncate(freq
->localfile
, 0) < 0) {
2577 error_errno("Couldn't truncate temporary file %s",
2584 freq
->slot
= get_active_slot();
2586 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2587 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2588 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2589 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2590 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2591 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2594 * If we have successfully processed data from a previous fetch
2595 * attempt, only fetch the data we don't already have.
2598 if (http_is_verbose
)
2600 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2601 hex
, (uintmax_t)prev_posn
);
2602 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2608 strbuf_release(&prevfile
);
2614 void process_http_object_request(struct http_object_request
*freq
)
2618 freq
->curl_result
= freq
->slot
->curl_result
;
2619 freq
->http_code
= freq
->slot
->http_code
;
2623 int finish_http_object_request(struct http_object_request
*freq
)
2626 struct strbuf filename
= STRBUF_INIT
;
2628 close(freq
->localfile
);
2629 freq
->localfile
= -1;
2631 process_http_object_request(freq
);
2633 if (freq
->http_code
== 416) {
2634 warning("requested range invalid; we may already have all the data.");
2635 } else if (freq
->curl_result
!= CURLE_OK
) {
2636 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2637 if (st
.st_size
== 0)
2638 unlink_or_warn(freq
->tmpfile
.buf
);
2642 git_inflate_end(&freq
->stream
);
2643 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2644 if (freq
->zret
!= Z_STREAM_END
) {
2645 unlink_or_warn(freq
->tmpfile
.buf
);
2648 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2649 unlink_or_warn(freq
->tmpfile
.buf
);
2652 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2653 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2654 strbuf_release(&filename
);
2656 return freq
->rename
;
2659 void abort_http_object_request(struct http_object_request
*freq
)
2661 unlink_or_warn(freq
->tmpfile
.buf
);
2663 release_http_object_request(freq
);
2666 void release_http_object_request(struct http_object_request
*freq
)
2668 if (freq
->localfile
!= -1) {
2669 close(freq
->localfile
);
2670 freq
->localfile
= -1;
2672 FREE_AND_NULL(freq
->url
);
2674 freq
->slot
->callback_func
= NULL
;
2675 freq
->slot
->callback_data
= NULL
;
2676 release_active_slot(freq
->slot
);
2679 strbuf_release(&freq
->tmpfile
);