1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
8 #include "run-command.h"
11 #include "credential.h"
16 #include "transport.h"
19 #include "string-list.h"
20 #include "object-file.h"
21 #include "object-store.h"
23 static struct trace_key trace_curl
= TRACE_KEY_INIT(CURL
);
24 static int trace_curl_data
= 1;
25 static int trace_curl_redact
= 1;
26 long int git_curl_ipresolve
= CURL_IPRESOLVE_WHATEVER
;
29 ssize_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
31 static int min_curl_sessions
= 1;
32 static int curl_session_count
;
33 static int max_requests
= -1;
35 static CURL
*curl_default
;
37 #define PREV_BUF_SIZE 4096
39 char curl_errorstr
[CURL_ERROR_SIZE
];
41 static int curl_ssl_verify
= -1;
42 static int curl_ssl_try
;
43 static const char *curl_http_version
= NULL
;
44 static const char *ssl_cert
;
45 static const char *ssl_cipherlist
;
46 static const char *ssl_version
;
51 { "sslv2", CURL_SSLVERSION_SSLv2
},
52 { "sslv3", CURL_SSLVERSION_SSLv3
},
53 { "tlsv1", CURL_SSLVERSION_TLSv1
},
54 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
55 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
56 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
57 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
59 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
60 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3
},
63 static const char *ssl_key
;
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.sslkey", var
))
380 return git_config_pathname(&ssl_key
, var
, value
);
381 if (!strcmp("http.sslcapath", var
))
382 return git_config_pathname(&ssl_capath
, var
, value
);
383 if (!strcmp("http.sslcainfo", var
))
384 return git_config_pathname(&ssl_cainfo
, var
, value
);
385 if (!strcmp("http.sslcertpasswordprotected", var
)) {
386 ssl_cert_password_required
= git_config_bool(var
, value
);
389 if (!strcmp("http.ssltry", var
)) {
390 curl_ssl_try
= git_config_bool(var
, value
);
393 if (!strcmp("http.sslbackend", var
)) {
394 free(http_ssl_backend
);
395 http_ssl_backend
= xstrdup_or_null(value
);
399 if (!strcmp("http.schannelcheckrevoke", var
)) {
400 http_schannel_check_revoke
= git_config_bool(var
, value
);
404 if (!strcmp("http.schannelusesslcainfo", var
)) {
405 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
409 if (!strcmp("http.minsessions", var
)) {
410 min_curl_sessions
= git_config_int(var
, value
);
411 if (min_curl_sessions
> 1)
412 min_curl_sessions
= 1;
415 if (!strcmp("http.maxrequests", var
)) {
416 max_requests
= git_config_int(var
, value
);
419 if (!strcmp("http.lowspeedlimit", var
)) {
420 curl_low_speed_limit
= (long)git_config_int(var
, value
);
423 if (!strcmp("http.lowspeedtime", var
)) {
424 curl_low_speed_time
= (long)git_config_int(var
, value
);
428 if (!strcmp("http.noepsv", var
)) {
429 curl_ftp_no_epsv
= git_config_bool(var
, value
);
432 if (!strcmp("http.proxy", var
))
433 return git_config_string(&curl_http_proxy
, var
, value
);
435 if (!strcmp("http.proxyauthmethod", var
))
436 return git_config_string(&http_proxy_authmethod
, var
, value
);
438 if (!strcmp("http.proxysslcert", var
))
439 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
441 if (!strcmp("http.proxysslkey", var
))
442 return git_config_string(&http_proxy_ssl_key
, var
, value
);
444 if (!strcmp("http.proxysslcainfo", var
))
445 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
447 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
448 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
452 if (!strcmp("http.cookiefile", var
))
453 return git_config_pathname(&curl_cookie_file
, var
, value
);
454 if (!strcmp("http.savecookies", var
)) {
455 curl_save_cookies
= git_config_bool(var
, value
);
459 if (!strcmp("http.postbuffer", var
)) {
460 http_post_buffer
= git_config_ssize_t(var
, value
);
461 if (http_post_buffer
< 0)
462 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
463 if (http_post_buffer
< LARGE_PACKET_MAX
)
464 http_post_buffer
= LARGE_PACKET_MAX
;
468 if (!strcmp("http.useragent", var
))
469 return git_config_string(&user_agent
, var
, value
);
471 if (!strcmp("http.emptyauth", var
)) {
472 if (value
&& !strcmp("auto", value
))
473 curl_empty_auth
= -1;
475 curl_empty_auth
= git_config_bool(var
, value
);
479 if (!strcmp("http.delegation", var
)) {
480 #ifdef CURLGSSAPI_DELEGATION_FLAG
481 return git_config_string(&curl_deleg
, var
, value
);
483 warning(_("Delegation control is not supported with cURL < 7.22.0"));
488 if (!strcmp("http.pinnedpubkey", var
)) {
489 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
490 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
492 warning(_("Public key pinning not supported with cURL < 7.39.0"));
497 if (!strcmp("http.extraheader", var
)) {
499 return config_error_nonbool(var
);
500 } else if (!*value
) {
501 string_list_clear(&extra_http_headers
, 0);
503 string_list_append(&extra_http_headers
, value
);
508 if (!strcmp("http.curloptresolve", var
)) {
510 return config_error_nonbool(var
);
511 } else if (!*value
) {
512 curl_slist_free_all(host_resolutions
);
513 host_resolutions
= NULL
;
515 host_resolutions
= curl_slist_append(host_resolutions
, value
);
520 if (!strcmp("http.followredirects", var
)) {
521 if (value
&& !strcmp(value
, "initial"))
522 http_follow_config
= HTTP_FOLLOW_INITIAL
;
523 else if (git_config_bool(var
, value
))
524 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
526 http_follow_config
= HTTP_FOLLOW_NONE
;
530 /* Fall back on the default ones */
531 return git_default_config(var
, value
, cb
);
534 static int curl_empty_auth_enabled(void)
536 if (curl_empty_auth
>= 0)
537 return curl_empty_auth
;
540 * In the automatic case, kick in the empty-auth
541 * hack as long as we would potentially try some
542 * method more exotic than "Basic" or "Digest".
544 * But only do this when this is our second or
545 * subsequent request, as by then we know what
546 * methods are available.
548 if (http_auth_methods_restricted
&&
549 (http_auth_methods
& ~empty_auth_useless
))
554 static void init_curl_http_auth(CURL
*result
)
556 if (!http_auth
.username
|| !*http_auth
.username
) {
557 if (curl_empty_auth_enabled())
558 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
562 credential_fill(&http_auth
);
564 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
565 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
568 /* *var must be free-able */
569 static void var_override(const char **var
, char *value
)
573 *var
= xstrdup(value
);
577 static void set_proxyauth_name_password(CURL
*result
)
579 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
580 proxy_auth
.username
);
581 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
582 proxy_auth
.password
);
585 static void init_curl_proxy_auth(CURL
*result
)
587 if (proxy_auth
.username
) {
588 if (!proxy_auth
.password
)
589 credential_fill(&proxy_auth
);
590 set_proxyauth_name_password(result
);
593 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
595 if (http_proxy_authmethod
) {
597 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
598 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
599 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
600 proxy_authmethods
[i
].curlauth_param
);
604 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
605 warning("unsupported proxy authentication method %s: using anyauth",
606 http_proxy_authmethod
);
607 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
611 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
614 static int has_cert_password(void)
616 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
618 if (!cert_auth
.password
) {
619 cert_auth
.protocol
= xstrdup("cert");
620 cert_auth
.host
= xstrdup("");
621 cert_auth
.username
= xstrdup("");
622 cert_auth
.path
= xstrdup(ssl_cert
);
623 credential_fill(&cert_auth
);
628 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
629 static int has_proxy_cert_password(void)
631 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
633 if (!proxy_cert_auth
.password
) {
634 proxy_cert_auth
.protocol
= xstrdup("cert");
635 proxy_cert_auth
.host
= xstrdup("");
636 proxy_cert_auth
.username
= xstrdup("");
637 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
638 credential_fill(&proxy_cert_auth
);
644 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
645 static void set_curl_keepalive(CURL
*c
)
647 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
651 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
655 socklen_t len
= (socklen_t
)sizeof(ka
);
657 if (type
!= CURLSOCKTYPE_IPCXN
)
660 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
662 warning_errno("unable to set SO_KEEPALIVE on socket");
664 return CURL_SOCKOPT_OK
;
667 static void set_curl_keepalive(CURL
*c
)
669 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
673 /* Return 1 if redactions have been made, 0 otherwise. */
674 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
677 const char *sensitive_header
;
679 if (trace_curl_redact
&&
680 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
681 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
682 /* The first token is the type, which is OK to log */
683 while (isspace(*sensitive_header
))
685 while (*sensitive_header
&& !isspace(*sensitive_header
))
687 /* Everything else is opaque and possibly sensitive */
688 strbuf_setlen(header
, sensitive_header
- header
->buf
);
689 strbuf_addstr(header
, " <redacted>");
691 } else if (trace_curl_redact
&&
692 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
693 struct strbuf redacted_header
= STRBUF_INIT
;
696 while (isspace(*sensitive_header
))
699 cookie
= sensitive_header
;
703 char *semicolon
= strstr(cookie
, "; ");
706 equals
= strchrnul(cookie
, '=');
708 /* invalid cookie, just append and continue */
709 strbuf_addstr(&redacted_header
, cookie
);
712 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
713 strbuf_addstr(&redacted_header
, "=<redacted>");
716 * There are more cookies. (Or, for some
717 * reason, the input string ends in "; ".)
719 strbuf_addstr(&redacted_header
, "; ");
720 cookie
= semicolon
+ strlen("; ");
726 strbuf_setlen(header
, sensitive_header
- header
->buf
);
727 strbuf_addbuf(header
, &redacted_header
);
733 /* Redact headers in info */
734 static void redact_sensitive_info_header(struct strbuf
*header
)
736 const char *sensitive_header
;
739 * curl's h2h3 prints headers in info, e.g.:
740 * h2h3 [<header-name>: <header-val>]
742 if (trace_curl_redact
&&
743 skip_iprefix(header
->buf
, "h2h3 [", &sensitive_header
)) {
744 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
745 /* redaction ate our closing bracket */
746 strbuf_addch(header
, ']');
751 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
753 struct strbuf out
= STRBUF_INIT
;
754 struct strbuf
**headers
, **header
;
756 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
757 text
, (long)size
, (long)size
);
758 trace_strbuf(&trace_curl
, &out
);
760 strbuf_add(&out
, ptr
, size
);
761 headers
= strbuf_split_max(&out
, '\n', 0);
763 for (header
= headers
; *header
; header
++) {
764 if (hide_sensitive_header
)
765 redact_sensitive_header(*header
, 0);
766 strbuf_insertstr((*header
), 0, text
);
767 strbuf_insertstr((*header
), strlen(text
), ": ");
768 strbuf_rtrim((*header
));
769 strbuf_addch((*header
), '\n');
770 trace_strbuf(&trace_curl
, (*header
));
772 strbuf_list_free(headers
);
773 strbuf_release(&out
);
776 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
779 struct strbuf out
= STRBUF_INIT
;
780 unsigned int width
= 60;
782 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
783 text
, (long)size
, (long)size
);
784 trace_strbuf(&trace_curl
, &out
);
786 for (i
= 0; i
< size
; i
+= width
) {
790 strbuf_addf(&out
, "%s: ", text
);
791 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
792 unsigned char ch
= ptr
[i
+ w
];
795 (ch
>= 0x20) && (ch
< 0x80)
798 strbuf_addch(&out
, '\n');
799 trace_strbuf(&trace_curl
, &out
);
801 strbuf_release(&out
);
804 static void curl_dump_info(char *data
, size_t size
)
806 struct strbuf buf
= STRBUF_INIT
;
808 strbuf_add(&buf
, data
, size
);
810 redact_sensitive_info_header(&buf
);
811 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
813 strbuf_release(&buf
);
816 static int curl_trace(CURL
*handle
, curl_infotype type
, char *data
, size_t size
, void *userp
)
819 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
823 curl_dump_info(data
, size
);
825 case CURLINFO_HEADER_OUT
:
826 text
= "=> Send header";
827 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
829 case CURLINFO_DATA_OUT
:
830 if (trace_curl_data
) {
831 text
= "=> Send data";
832 curl_dump_data(text
, (unsigned char *)data
, size
);
835 case CURLINFO_SSL_DATA_OUT
:
836 if (trace_curl_data
) {
837 text
= "=> Send SSL data";
838 curl_dump_data(text
, (unsigned char *)data
, size
);
841 case CURLINFO_HEADER_IN
:
842 text
= "<= Recv header";
843 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
845 case CURLINFO_DATA_IN
:
846 if (trace_curl_data
) {
847 text
= "<= Recv data";
848 curl_dump_data(text
, (unsigned char *)data
, size
);
851 case CURLINFO_SSL_DATA_IN
:
852 if (trace_curl_data
) {
853 text
= "<= Recv SSL data";
854 curl_dump_data(text
, (unsigned char *)data
, size
);
858 default: /* we ignore unknown types by default */
864 void http_trace_curl_no_data(void)
866 trace_override_envvar(&trace_curl
, "1");
870 void setup_curl_trace(CURL
*handle
)
872 if (!trace_want(&trace_curl
))
874 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
875 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
876 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
879 static void proto_list_append(struct strbuf
*list
, const char *proto
)
884 strbuf_addch(list
, ',');
885 strbuf_addstr(list
, proto
);
888 static long get_curl_allowed_protocols(int from_user
, struct strbuf
*list
)
892 if (is_transport_allowed("http", from_user
)) {
893 bits
|= CURLPROTO_HTTP
;
894 proto_list_append(list
, "http");
896 if (is_transport_allowed("https", from_user
)) {
897 bits
|= CURLPROTO_HTTPS
;
898 proto_list_append(list
, "https");
900 if (is_transport_allowed("ftp", from_user
)) {
901 bits
|= CURLPROTO_FTP
;
902 proto_list_append(list
, "ftp");
904 if (is_transport_allowed("ftps", from_user
)) {
905 bits
|= CURLPROTO_FTPS
;
906 proto_list_append(list
, "ftps");
912 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
913 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
920 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
921 { "HTTP/2", CURL_HTTP_VERSION_2
}
924 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
925 if (!strcmp(version_string
, choice
[i
].name
)) {
926 *opt
= choice
[i
].opt_token
;
931 warning("unknown value given to http.version: '%s'", version_string
);
932 return -1; /* not found */
937 static CURL
*get_curl_handle(void)
939 CURL
*result
= curl_easy_init();
942 die("curl_easy_init failed");
944 if (!curl_ssl_verify
) {
945 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
946 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
948 /* Verify authenticity of the peer's certificate */
949 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
950 /* The name in the cert must match whom we tried to connect */
951 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
954 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
955 if (curl_http_version
) {
957 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
958 /* Set request use http version */
959 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
964 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
965 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
967 #ifdef CURLGSSAPI_DELEGATION_FLAG
970 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
971 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
972 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
973 curl_deleg_levels
[i
].curl_deleg_param
);
977 if (i
== ARRAY_SIZE(curl_deleg_levels
))
978 warning("Unknown delegation method '%s': using default",
983 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
984 !http_schannel_check_revoke
) {
985 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
986 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
988 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
992 if (http_proactive_auth
)
993 init_curl_http_auth(result
);
995 if (getenv("GIT_SSL_VERSION"))
996 ssl_version
= getenv("GIT_SSL_VERSION");
997 if (ssl_version
&& *ssl_version
) {
999 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
1000 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
1001 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
1002 sslversions
[i
].ssl_version
);
1006 if (i
== ARRAY_SIZE(sslversions
))
1007 warning("unsupported ssl version %s: using default",
1011 if (getenv("GIT_SSL_CIPHER_LIST"))
1012 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
1013 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
1014 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
1018 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
1019 if (has_cert_password())
1020 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
1022 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
1024 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
1025 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
1027 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
1029 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
1030 !http_schannel_use_ssl_cainfo
) {
1031 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
1032 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1033 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
1035 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
1037 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
1038 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
1039 if (http_proxy_ssl_ca_info
)
1040 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
1044 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
1045 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
1046 curl_low_speed_limit
);
1047 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
1048 curl_low_speed_time
);
1051 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
1052 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
1054 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
1056 struct strbuf buf
= STRBUF_INIT
;
1058 get_curl_allowed_protocols(0, &buf
);
1059 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS_STR
, buf
.buf
);
1062 get_curl_allowed_protocols(-1, &buf
);
1063 curl_easy_setopt(result
, CURLOPT_PROTOCOLS_STR
, buf
.buf
);
1064 strbuf_release(&buf
);
1067 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
1068 get_curl_allowed_protocols(0, NULL
));
1069 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
1070 get_curl_allowed_protocols(-1, NULL
));
1073 if (getenv("GIT_CURL_VERBOSE"))
1074 http_trace_curl_no_data();
1075 setup_curl_trace(result
);
1076 if (getenv("GIT_TRACE_CURL_NO_DATA"))
1077 trace_curl_data
= 0;
1078 if (!git_env_bool("GIT_TRACE_REDACT", 1))
1079 trace_curl_redact
= 0;
1081 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
1082 user_agent
? user_agent
: git_user_agent());
1084 if (curl_ftp_no_epsv
)
1085 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
1088 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
1091 * CURL also examines these variables as a fallback; but we need to query
1092 * them here in order to decide whether to prompt for missing password (cf.
1093 * init_curl_proxy_auth()).
1095 * Unlike many other common environment variables, these are historically
1096 * lowercase only. It appears that CURL did not know this and implemented
1097 * only uppercase variants, which was later corrected to take both - with
1098 * the exception of http_proxy, which is lowercase only also in CURL. As
1099 * the lowercase versions are the historical quasi-standard, they take
1100 * precedence here, as in CURL.
1102 if (!curl_http_proxy
) {
1103 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
1104 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
1105 var_override(&curl_http_proxy
, getenv("https_proxy"));
1107 var_override(&curl_http_proxy
, getenv("http_proxy"));
1109 if (!curl_http_proxy
) {
1110 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
1111 var_override(&curl_http_proxy
, getenv("all_proxy"));
1115 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1117 * Handle case with the empty http.proxy value here to keep
1118 * common code clean.
1119 * NB: empty option disables proxying at all.
1121 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1122 } else if (curl_http_proxy
) {
1123 if (starts_with(curl_http_proxy
, "socks5h"))
1124 curl_easy_setopt(result
,
1125 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1126 else if (starts_with(curl_http_proxy
, "socks5"))
1127 curl_easy_setopt(result
,
1128 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1129 else if (starts_with(curl_http_proxy
, "socks4a"))
1130 curl_easy_setopt(result
,
1131 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1132 else if (starts_with(curl_http_proxy
, "socks"))
1133 curl_easy_setopt(result
,
1134 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1135 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1136 else if (starts_with(curl_http_proxy
, "https")) {
1137 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1139 if (http_proxy_ssl_cert
)
1140 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1142 if (http_proxy_ssl_key
)
1143 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1145 if (has_proxy_cert_password())
1146 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1149 if (strstr(curl_http_proxy
, "://"))
1150 credential_from_url(&proxy_auth
, curl_http_proxy
);
1152 struct strbuf url
= STRBUF_INIT
;
1153 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1154 credential_from_url(&proxy_auth
, url
.buf
);
1155 strbuf_release(&url
);
1158 if (!proxy_auth
.host
)
1159 die("Invalid proxy URL '%s'", curl_http_proxy
);
1161 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1162 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1163 var_override(&curl_no_proxy
, getenv("no_proxy"));
1164 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1166 init_curl_proxy_auth(result
);
1168 set_curl_keepalive(result
);
1173 static void set_from_env(const char **var
, const char *envname
)
1175 const char *val
= getenv(envname
);
1180 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1182 char *low_speed_limit
;
1183 char *low_speed_time
;
1184 char *normalized_url
;
1185 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1187 config
.section
= "http";
1189 config
.collect_fn
= http_options
;
1190 config
.cascade_fn
= git_default_config
;
1193 http_is_verbose
= 0;
1194 normalized_url
= url_normalize(url
, &config
.url
);
1196 git_config(urlmatch_config_entry
, &config
);
1197 free(normalized_url
);
1198 string_list_clear(&config
.vars
, 1);
1200 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1201 if (http_ssl_backend
) {
1202 const curl_ssl_backend
**backends
;
1203 struct strbuf buf
= STRBUF_INIT
;
1206 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1207 case CURLSSLSET_UNKNOWN_BACKEND
:
1208 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1209 "Supported SSL backends:"),
1211 for (i
= 0; backends
[i
]; i
++)
1212 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1214 case CURLSSLSET_NO_BACKENDS
:
1215 die(_("Could not set SSL backend to '%s': "
1216 "cURL was built without SSL backends"),
1218 case CURLSSLSET_TOO_LATE
:
1219 die(_("Could not set SSL backend to '%s': already set"),
1227 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1228 die("curl_global_init failed");
1230 http_proactive_auth
= proactive_auth
;
1232 if (remote
&& remote
->http_proxy
)
1233 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1236 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1238 pragma_header
= curl_slist_append(http_copy_default_headers(),
1239 "Pragma: no-cache");
1240 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
1244 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1245 if (http_max_requests
)
1246 max_requests
= atoi(http_max_requests
);
1249 curlm
= curl_multi_init();
1251 die("curl_multi_init failed");
1253 if (getenv("GIT_SSL_NO_VERIFY"))
1254 curl_ssl_verify
= 0;
1256 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1257 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1258 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1259 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1261 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1263 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1264 if (low_speed_limit
)
1265 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1266 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1268 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1270 if (curl_ssl_verify
== -1)
1271 curl_ssl_verify
= 1;
1273 curl_session_count
= 0;
1274 if (max_requests
< 1)
1275 max_requests
= DEFAULT_MAX_REQUESTS
;
1277 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1278 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1279 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1281 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1282 proxy_ssl_cert_password_required
= 1;
1284 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1285 curl_ftp_no_epsv
= 1;
1288 credential_from_url(&http_auth
, url
);
1289 if (!ssl_cert_password_required
&&
1290 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1291 starts_with(url
, "https://"))
1292 ssl_cert_password_required
= 1;
1295 curl_default
= get_curl_handle();
1298 void http_cleanup(void)
1300 struct active_request_slot
*slot
= active_queue_head
;
1302 while (slot
!= NULL
) {
1303 struct active_request_slot
*next
= slot
->next
;
1305 xmulti_remove_handle(slot
);
1306 curl_easy_cleanup(slot
->curl
);
1311 active_queue_head
= NULL
;
1313 curl_easy_cleanup(curl_default
);
1315 curl_multi_cleanup(curlm
);
1316 curl_global_cleanup();
1318 string_list_clear(&extra_http_headers
, 0);
1320 curl_slist_free_all(pragma_header
);
1321 pragma_header
= NULL
;
1323 curl_slist_free_all(no_pragma_header
);
1324 no_pragma_header
= NULL
;
1326 curl_slist_free_all(host_resolutions
);
1327 host_resolutions
= NULL
;
1329 if (curl_http_proxy
) {
1330 free((void *)curl_http_proxy
);
1331 curl_http_proxy
= NULL
;
1334 if (proxy_auth
.password
) {
1335 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1336 FREE_AND_NULL(proxy_auth
.password
);
1339 free((void *)curl_proxyuserpwd
);
1340 curl_proxyuserpwd
= NULL
;
1342 free((void *)http_proxy_authmethod
);
1343 http_proxy_authmethod
= NULL
;
1345 if (cert_auth
.password
) {
1346 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1347 FREE_AND_NULL(cert_auth
.password
);
1349 ssl_cert_password_required
= 0;
1351 if (proxy_cert_auth
.password
) {
1352 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1353 FREE_AND_NULL(proxy_cert_auth
.password
);
1355 proxy_ssl_cert_password_required
= 0;
1357 FREE_AND_NULL(cached_accept_language
);
1360 struct active_request_slot
*get_active_slot(void)
1362 struct active_request_slot
*slot
= active_queue_head
;
1363 struct active_request_slot
*newslot
;
1367 /* Wait for a slot to open up if the queue is full */
1368 while (active_requests
>= max_requests
) {
1369 curl_multi_perform(curlm
, &num_transfers
);
1370 if (num_transfers
< active_requests
)
1371 process_curl_messages();
1374 while (slot
!= NULL
&& slot
->in_use
)
1378 newslot
= xmalloc(sizeof(*newslot
));
1379 newslot
->curl
= NULL
;
1380 newslot
->in_use
= 0;
1381 newslot
->next
= NULL
;
1383 slot
= active_queue_head
;
1385 active_queue_head
= newslot
;
1387 while (slot
->next
!= NULL
)
1389 slot
->next
= newslot
;
1395 slot
->curl
= curl_easy_duphandle(curl_default
);
1396 curl_session_count
++;
1401 slot
->results
= NULL
;
1402 slot
->finished
= NULL
;
1403 slot
->callback_data
= NULL
;
1404 slot
->callback_func
= NULL
;
1405 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1406 if (curl_save_cookies
)
1407 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1408 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1409 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1410 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1411 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1412 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1413 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1414 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1415 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1416 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1417 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1418 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1421 * Default following to off unless "ALWAYS" is configured; this gives
1422 * callers a sane starting point, and they can tweak for individual
1423 * HTTP_FOLLOW_* cases themselves.
1425 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1426 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1428 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1430 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1431 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1432 if (http_auth
.password
|| curl_empty_auth_enabled())
1433 init_curl_http_auth(slot
->curl
);
1438 int start_active_slot(struct active_request_slot
*slot
)
1440 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1443 if (curlm_result
!= CURLM_OK
&&
1444 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1445 warning("curl_multi_add_handle failed: %s",
1446 curl_multi_strerror(curlm_result
));
1453 * We know there must be something to do, since we just added
1456 curl_multi_perform(curlm
, &num_transfers
);
1462 int (*fill
)(void *);
1463 struct fill_chain
*next
;
1466 static struct fill_chain
*fill_cfg
;
1468 void add_fill_function(void *data
, int (*fill
)(void *))
1470 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1471 struct fill_chain
**linkp
= &fill_cfg
;
1472 new_fill
->data
= data
;
1473 new_fill
->fill
= fill
;
1474 new_fill
->next
= NULL
;
1476 linkp
= &(*linkp
)->next
;
1480 void fill_active_slots(void)
1482 struct active_request_slot
*slot
= active_queue_head
;
1484 while (active_requests
< max_requests
) {
1485 struct fill_chain
*fill
;
1486 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1487 if (fill
->fill(fill
->data
))
1494 while (slot
!= NULL
) {
1495 if (!slot
->in_use
&& slot
->curl
!= NULL
1496 && curl_session_count
> min_curl_sessions
) {
1497 curl_easy_cleanup(slot
->curl
);
1499 curl_session_count
--;
1505 void step_active_slots(void)
1508 CURLMcode curlm_result
;
1511 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1512 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1513 if (num_transfers
< active_requests
) {
1514 process_curl_messages();
1515 fill_active_slots();
1519 void run_active_slot(struct active_request_slot
*slot
)
1525 struct timeval select_timeout
;
1528 slot
->finished
= &finished
;
1530 step_active_slots();
1534 curl_multi_timeout(curlm
, &curl_timeout
);
1535 if (curl_timeout
== 0) {
1537 } else if (curl_timeout
== -1) {
1538 select_timeout
.tv_sec
= 0;
1539 select_timeout
.tv_usec
= 50000;
1541 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1542 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1549 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1552 * It can happen that curl_multi_timeout returns a pathologically
1553 * long timeout when curl_multi_fdset returns no file descriptors
1554 * to read. See commit message for more details.
1557 (select_timeout
.tv_sec
> 0 ||
1558 select_timeout
.tv_usec
> 50000)) {
1559 select_timeout
.tv_sec
= 0;
1560 select_timeout
.tv_usec
= 50000;
1563 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1568 * The value of slot->finished we set before the loop was used
1569 * to set our "finished" variable when our request completed.
1571 * 1. The slot may not have been reused for another requst
1572 * yet, in which case it still has &finished.
1574 * 2. The slot may already be in-use to serve another request,
1575 * which can further be divided into two cases:
1577 * (a) If call run_active_slot() hasn't been called for that
1578 * other request, slot->finished would have been cleared
1579 * by get_active_slot() and has NULL.
1581 * (b) If the request did call run_active_slot(), then the
1582 * call would have updated slot->finished at the beginning
1583 * of this function, and with the clearing of the member
1584 * below, we would find that slot->finished is now NULL.
1586 * In all cases, slot->finished has no useful information to
1587 * anybody at this point. Some compilers warn us for
1588 * attempting to smuggle a pointer that is about to become
1589 * invalid, i.e. &finished. We clear it here to assure them.
1591 slot
->finished
= NULL
;
1594 static void release_active_slot(struct active_request_slot
*slot
)
1596 closedown_active_slot(slot
);
1598 xmulti_remove_handle(slot
);
1599 if (curl_session_count
> min_curl_sessions
) {
1600 curl_easy_cleanup(slot
->curl
);
1602 curl_session_count
--;
1605 fill_active_slots();
1608 void finish_all_active_slots(void)
1610 struct active_request_slot
*slot
= active_queue_head
;
1612 while (slot
!= NULL
)
1614 run_active_slot(slot
);
1615 slot
= active_queue_head
;
1621 /* Helpers for modifying and creating URLs */
1622 static inline int needs_quote(int ch
)
1624 if (((ch
>= 'A') && (ch
<= 'Z'))
1625 || ((ch
>= 'a') && (ch
<= 'z'))
1626 || ((ch
>= '0') && (ch
<= '9'))
1634 static char *quote_ref_url(const char *base
, const char *ref
)
1636 struct strbuf buf
= STRBUF_INIT
;
1640 end_url_with_slash(&buf
, base
);
1642 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1643 if (needs_quote(ch
))
1644 strbuf_addf(&buf
, "%%%02x", ch
);
1646 strbuf_addch(&buf
, *cp
);
1648 return strbuf_detach(&buf
, NULL
);
1651 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1653 int only_two_digit_prefix
)
1655 end_url_with_slash(buf
, url
);
1657 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1658 if (!only_two_digit_prefix
)
1659 strbuf_addstr(buf
, hex
+ 2);
1662 char *get_remote_object_url(const char *url
, const char *hex
,
1663 int only_two_digit_prefix
)
1665 struct strbuf buf
= STRBUF_INIT
;
1666 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1667 return strbuf_detach(&buf
, NULL
);
1670 void normalize_curl_result(CURLcode
*result
, long http_code
,
1671 char *errorstr
, size_t errorlen
)
1674 * If we see a failing http code with CURLE_OK, we have turned off
1675 * FAILONERROR (to keep the server's custom error response), and should
1676 * translate the code into failure here.
1678 * Likewise, if we see a redirect (30x code), that means we turned off
1679 * redirect-following, and we should treat the result as an error.
1681 if (*result
== CURLE_OK
&& http_code
>= 300) {
1682 *result
= CURLE_HTTP_RETURNED_ERROR
;
1684 * Normally curl will already have put the "reason phrase"
1685 * from the server into curl_errorstr; unfortunately without
1686 * FAILONERROR it is lost, so we can give only the numeric
1689 xsnprintf(errorstr
, errorlen
,
1690 "The requested URL returned error: %ld",
1695 static int handle_curl_result(struct slot_results
*results
)
1697 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1698 curl_errorstr
, sizeof(curl_errorstr
));
1700 if (results
->curl_result
== CURLE_OK
) {
1701 credential_approve(&http_auth
);
1702 credential_approve(&proxy_auth
);
1703 credential_approve(&cert_auth
);
1705 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1707 * We can't tell from here whether it's a bad path, bad
1708 * certificate, bad password, or something else wrong
1709 * with the certificate. So we reject the credential to
1710 * avoid caching or saving a bad password.
1712 credential_reject(&cert_auth
);
1714 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1715 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1716 return HTTP_NOMATCHPUBLICKEY
;
1718 } else if (missing_target(results
))
1719 return HTTP_MISSING_TARGET
;
1720 else if (results
->http_code
== 401) {
1721 if (http_auth
.username
&& http_auth
.password
) {
1722 credential_reject(&http_auth
);
1725 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1726 if (results
->auth_avail
) {
1727 http_auth_methods
&= results
->auth_avail
;
1728 http_auth_methods_restricted
= 1;
1733 if (results
->http_connectcode
== 407)
1734 credential_reject(&proxy_auth
);
1735 if (!curl_errorstr
[0])
1736 strlcpy(curl_errorstr
,
1737 curl_easy_strerror(results
->curl_result
),
1738 sizeof(curl_errorstr
));
1743 int run_one_slot(struct active_request_slot
*slot
,
1744 struct slot_results
*results
)
1746 slot
->results
= results
;
1747 if (!start_active_slot(slot
)) {
1748 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1749 "failed to start HTTP request");
1750 return HTTP_START_FAILED
;
1753 run_active_slot(slot
);
1754 return handle_curl_result(results
);
1757 struct curl_slist
*http_copy_default_headers(void)
1759 struct curl_slist
*headers
= NULL
;
1760 const struct string_list_item
*item
;
1762 for_each_string_list_item(item
, &extra_http_headers
)
1763 headers
= curl_slist_append(headers
, item
->string
);
1768 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1774 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1776 strbuf_addstr(buf
, ptr
);
1781 * Check for and extract a content-type parameter. "raw"
1782 * should be positioned at the start of the potential
1783 * parameter, with any whitespace already removed.
1785 * "name" is the name of the parameter. The value is appended
1788 static int extract_param(const char *raw
, const char *name
,
1791 size_t len
= strlen(name
);
1793 if (strncasecmp(raw
, name
, len
))
1801 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1802 strbuf_addch(out
, *raw
++);
1807 * Extract a normalized version of the content type, with any
1808 * spaces suppressed, all letters lowercased, and no trailing ";"
1811 * Note that we will silently remove even invalid whitespace. For
1812 * example, "text / plain" is specifically forbidden by RFC 2616,
1813 * but "text/plain" is the only reasonable output, and this keeps
1816 * If the "charset" argument is not NULL, store the value of any
1817 * charset parameter there.
1820 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1821 * "text / plain" -> "text/plain"
1823 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1824 struct strbuf
*charset
)
1829 strbuf_grow(type
, raw
->len
);
1830 for (p
= raw
->buf
; *p
; p
++) {
1837 strbuf_addch(type
, tolower(*p
));
1843 strbuf_reset(charset
);
1845 while (isspace(*p
) || *p
== ';')
1847 if (!extract_param(p
, "charset", charset
))
1849 while (*p
&& !isspace(*p
))
1853 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1854 strbuf_addstr(charset
, "ISO-8859-1");
1857 static void write_accept_language(struct strbuf
*buf
)
1860 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1861 * that, q-value will be smaller than 0.001, the minimum q-value the
1862 * HTTP specification allows. See
1863 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1865 const int MAX_DECIMAL_PLACES
= 3;
1866 const int MAX_LANGUAGE_TAGS
= 1000;
1867 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1868 char **language_tags
= NULL
;
1870 const char *s
= get_preferred_languages();
1872 struct strbuf tag
= STRBUF_INIT
;
1874 /* Don't add Accept-Language header if no language is preferred. */
1879 * Split the colon-separated string of preferred languages into
1880 * language_tags array.
1883 /* collect language tag */
1884 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1885 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1887 /* skip .codeset, @modifier and any other unnecessary parts */
1888 while (*s
&& *s
!= ':')
1893 REALLOC_ARRAY(language_tags
, num_langs
);
1894 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1895 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1900 /* write Accept-Language header into buf */
1902 int last_buf_len
= 0;
1908 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1909 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1911 /* compute decimal_places */
1912 for (max_q
= 1, decimal_places
= 0;
1913 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1914 decimal_places
++, max_q
*= 10)
1917 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1919 strbuf_addstr(buf
, "Accept-Language: ");
1921 for (i
= 0; i
< num_langs
; i
++) {
1923 strbuf_addstr(buf
, ", ");
1925 strbuf_addstr(buf
, language_tags
[i
]);
1928 strbuf_addf(buf
, q_format
, max_q
- i
);
1930 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1931 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1935 last_buf_len
= buf
->len
;
1939 /* free language tags -- last one is a static '*' */
1940 for (i
= 0; i
< num_langs
- 1; i
++)
1941 free(language_tags
[i
]);
1942 free(language_tags
);
1946 * Get an Accept-Language header which indicates user's preferred languages.
1950 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1951 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1952 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1953 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1954 * LANGUAGE= LANG=C -> ""
1956 const char *http_get_accept_language_header(void)
1958 if (!cached_accept_language
) {
1959 struct strbuf buf
= STRBUF_INIT
;
1960 write_accept_language(&buf
);
1962 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1965 return cached_accept_language
;
1968 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1971 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1972 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1975 /* http_request() targets */
1976 #define HTTP_REQUEST_STRBUF 0
1977 #define HTTP_REQUEST_FILE 1
1979 static int http_request(const char *url
,
1980 void *result
, int target
,
1981 const struct http_get_options
*options
)
1983 struct active_request_slot
*slot
;
1984 struct slot_results results
;
1985 struct curl_slist
*headers
= http_copy_default_headers();
1986 struct strbuf buf
= STRBUF_INIT
;
1987 const char *accept_language
;
1990 slot
= get_active_slot();
1991 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1994 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1996 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1997 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
1999 if (target
== HTTP_REQUEST_FILE
) {
2000 off_t posn
= ftello(result
);
2001 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2004 http_opt_request_remainder(slot
->curl
, posn
);
2006 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
2010 curl_easy_setopt(slot
->curl
, CURLOPT_HEADERFUNCTION
, fwrite_wwwauth
);
2012 accept_language
= http_get_accept_language_header();
2014 if (accept_language
)
2015 headers
= curl_slist_append(headers
, accept_language
);
2017 strbuf_addstr(&buf
, "Pragma:");
2018 if (options
&& options
->no_cache
)
2019 strbuf_addstr(&buf
, " no-cache");
2020 if (options
&& options
->initial_request
&&
2021 http_follow_config
== HTTP_FOLLOW_INITIAL
)
2022 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
2024 headers
= curl_slist_append(headers
, buf
.buf
);
2026 /* Add additional headers here */
2027 if (options
&& options
->extra_headers
) {
2028 const struct string_list_item
*item
;
2029 for_each_string_list_item(item
, options
->extra_headers
) {
2030 headers
= curl_slist_append(headers
, item
->string
);
2034 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
2035 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
2036 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
2037 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
2039 ret
= run_one_slot(slot
, &results
);
2041 if (options
&& options
->content_type
) {
2042 struct strbuf raw
= STRBUF_INIT
;
2043 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
2044 extract_content_type(&raw
, options
->content_type
,
2046 strbuf_release(&raw
);
2049 if (options
&& options
->effective_url
)
2050 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
2051 options
->effective_url
);
2053 curl_slist_free_all(headers
);
2054 strbuf_release(&buf
);
2060 * Update the "base" url to a more appropriate value, as deduced by
2061 * redirects seen when requesting a URL starting with "url".
2063 * The "asked" parameter is a URL that we asked curl to access, and must begin
2066 * The "got" parameter is the URL that curl reported to us as where we ended
2069 * Returns 1 if we updated the base url, 0 otherwise.
2071 * Our basic strategy is to compare "base" and "asked" to find the bits
2072 * specific to our request. We then strip those bits off of "got" to yield the
2073 * new base. So for example, if our base is "http://example.com/foo.git",
2074 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2075 * with "https://other.example.com/foo.git/info/refs". We would want the
2076 * new URL to become "https://other.example.com/foo.git".
2078 * Note that this assumes a sane redirect scheme. It's entirely possible
2079 * in the example above to end up at a URL that does not even end in
2080 * "info/refs". In such a case we die. There's not much we can do, such a
2081 * scheme is unlikely to represent a real git repository, and failing to
2082 * rewrite the base opens options for malicious redirects to do funny things.
2084 static int update_url_from_redirect(struct strbuf
*base
,
2086 const struct strbuf
*got
)
2091 if (!strcmp(asked
, got
->buf
))
2094 if (!skip_prefix(asked
, base
->buf
, &tail
))
2095 BUG("update_url_from_redirect: %s is not a superset of %s",
2099 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
2100 die(_("unable to update url base from redirection:\n"
2106 strbuf_add(base
, got
->buf
, new_len
);
2111 static int http_request_reauth(const char *url
,
2112 void *result
, int target
,
2113 struct http_get_options
*options
)
2115 int ret
= http_request(url
, result
, target
, options
);
2117 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2120 if (options
&& options
->effective_url
&& options
->base_url
) {
2121 if (update_url_from_redirect(options
->base_url
,
2122 url
, options
->effective_url
)) {
2123 credential_from_url(&http_auth
, options
->base_url
->buf
);
2124 url
= options
->effective_url
->buf
;
2128 if (ret
!= HTTP_REAUTH
)
2132 * The previous request may have put cruft into our output stream; we
2133 * should clear it out before making our next request.
2136 case HTTP_REQUEST_STRBUF
:
2137 strbuf_reset(result
);
2139 case HTTP_REQUEST_FILE
:
2140 if (fflush(result
)) {
2141 error_errno("unable to flush a file");
2142 return HTTP_START_FAILED
;
2145 if (ftruncate(fileno(result
), 0) < 0) {
2146 error_errno("unable to truncate a file");
2147 return HTTP_START_FAILED
;
2151 BUG("Unknown http_request target");
2154 credential_fill(&http_auth
);
2156 return http_request(url
, result
, target
, options
);
2159 int http_get_strbuf(const char *url
,
2160 struct strbuf
*result
,
2161 struct http_get_options
*options
)
2163 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2167 * Downloads a URL and stores the result in the given file.
2169 * If a previous interrupted download is detected (i.e. a previous temporary
2170 * file is still around) the download is resumed.
2172 int http_get_file(const char *url
, const char *filename
,
2173 struct http_get_options
*options
)
2176 struct strbuf tmpfile
= STRBUF_INIT
;
2179 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2180 result
= fopen(tmpfile
.buf
, "a");
2182 error("Unable to open local file %s", tmpfile
.buf
);
2187 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2190 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2193 strbuf_release(&tmpfile
);
2197 int http_fetch_ref(const char *base
, struct ref
*ref
)
2199 struct http_get_options options
= {0};
2201 struct strbuf buffer
= STRBUF_INIT
;
2204 options
.no_cache
= 1;
2206 url
= quote_ref_url(base
, ref
->name
);
2207 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2208 strbuf_rtrim(&buffer
);
2209 if (buffer
.len
== the_hash_algo
->hexsz
)
2210 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2211 else if (starts_with(buffer
.buf
, "ref: ")) {
2212 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2217 strbuf_release(&buffer
);
2222 /* Helpers for fetching packs */
2223 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2226 struct strbuf buf
= STRBUF_INIT
;
2228 if (http_is_verbose
)
2229 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2231 end_url_with_slash(&buf
, base_url
);
2232 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2233 url
= strbuf_detach(&buf
, NULL
);
2235 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2236 tmp
= strbuf_detach(&buf
, NULL
);
2238 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2239 error("Unable to get pack index %s", url
);
2247 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2248 unsigned char *sha1
, const char *base_url
)
2250 struct packed_git
*new_pack
;
2251 char *tmp_idx
= NULL
;
2254 if (has_pack_index(sha1
)) {
2255 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2257 return -1; /* parse_pack_index() already issued error message */
2261 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2265 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2270 return -1; /* parse_pack_index() already issued error message */
2273 ret
= verify_pack_index(new_pack
);
2275 close_pack_index(new_pack
);
2276 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2283 new_pack
->next
= *packs_head
;
2284 *packs_head
= new_pack
;
2288 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2290 struct http_get_options options
= {0};
2294 struct strbuf buf
= STRBUF_INIT
;
2295 struct object_id oid
;
2297 end_url_with_slash(&buf
, base_url
);
2298 strbuf_addstr(&buf
, "objects/info/packs");
2299 url
= strbuf_detach(&buf
, NULL
);
2301 options
.no_cache
= 1;
2302 ret
= http_get_strbuf(url
, &buf
, &options
);
2308 if (skip_prefix(data
, "P pack-", &data
) &&
2309 !parse_oid_hex(data
, &oid
, &data
) &&
2310 skip_prefix(data
, ".pack", &data
) &&
2311 (*data
== '\n' || *data
== '\0')) {
2312 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2314 data
= strchrnul(data
, '\n');
2317 data
++; /* skip past newline */
2325 void release_http_pack_request(struct http_pack_request
*preq
)
2327 if (preq
->packfile
) {
2328 fclose(preq
->packfile
);
2329 preq
->packfile
= NULL
;
2332 strbuf_release(&preq
->tmpfile
);
2337 static const char *default_index_pack_args
[] =
2338 {"index-pack", "--stdin", NULL
};
2340 int finish_http_pack_request(struct http_pack_request
*preq
)
2342 struct child_process ip
= CHILD_PROCESS_INIT
;
2346 fclose(preq
->packfile
);
2347 preq
->packfile
= NULL
;
2349 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2353 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2354 preq
->index_pack_args
:
2355 default_index_pack_args
);
2357 if (preq
->preserve_index_pack_stdout
)
2362 if (run_command(&ip
)) {
2369 unlink(preq
->tmpfile
.buf
);
2373 void http_install_packfile(struct packed_git
*p
,
2374 struct packed_git
**list_to_remove_from
)
2376 struct packed_git
**lst
= list_to_remove_from
;
2379 lst
= &((*lst
)->next
);
2380 *lst
= (*lst
)->next
;
2382 install_packed_git(the_repository
, p
);
2385 struct http_pack_request
*new_http_pack_request(
2386 const unsigned char *packed_git_hash
, const char *base_url
) {
2388 struct strbuf buf
= STRBUF_INIT
;
2390 end_url_with_slash(&buf
, base_url
);
2391 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2392 hash_to_hex(packed_git_hash
));
2393 return new_direct_http_pack_request(packed_git_hash
,
2394 strbuf_detach(&buf
, NULL
));
2397 struct http_pack_request
*new_direct_http_pack_request(
2398 const unsigned char *packed_git_hash
, char *url
)
2400 off_t prev_posn
= 0;
2401 struct http_pack_request
*preq
;
2403 CALLOC_ARRAY(preq
, 1);
2404 strbuf_init(&preq
->tmpfile
, 0);
2408 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2409 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2410 if (!preq
->packfile
) {
2411 error("Unable to open local file %s for pack",
2416 preq
->slot
= get_active_slot();
2417 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2418 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2419 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2420 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
2424 * If there is data present from a previous transfer attempt,
2425 * resume where it left off
2427 prev_posn
= ftello(preq
->packfile
);
2429 if (http_is_verbose
)
2431 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2432 hash_to_hex(packed_git_hash
),
2433 (uintmax_t)prev_posn
);
2434 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2440 strbuf_release(&preq
->tmpfile
);
2446 /* Helpers for fetching objects (loose) */
2447 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2450 unsigned char expn
[4096];
2451 size_t size
= eltsize
* nmemb
;
2453 struct http_object_request
*freq
= data
;
2454 struct active_request_slot
*slot
= freq
->slot
;
2457 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2460 BUG("curl_easy_getinfo for HTTP code failed: %s",
2461 curl_easy_strerror(c
));
2462 if (slot
->http_code
>= 300)
2467 ssize_t retval
= xwrite(freq
->localfile
,
2468 (char *) ptr
+ posn
, size
- posn
);
2470 return posn
/ eltsize
;
2472 } while (posn
< size
);
2474 freq
->stream
.avail_in
= size
;
2475 freq
->stream
.next_in
= (void *)ptr
;
2477 freq
->stream
.next_out
= expn
;
2478 freq
->stream
.avail_out
= sizeof(expn
);
2479 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2480 the_hash_algo
->update_fn(&freq
->c
, expn
,
2481 sizeof(expn
) - freq
->stream
.avail_out
);
2482 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2486 struct http_object_request
*new_http_object_request(const char *base_url
,
2487 const struct object_id
*oid
)
2489 char *hex
= oid_to_hex(oid
);
2490 struct strbuf filename
= STRBUF_INIT
;
2491 struct strbuf prevfile
= STRBUF_INIT
;
2493 char prev_buf
[PREV_BUF_SIZE
];
2494 ssize_t prev_read
= 0;
2495 off_t prev_posn
= 0;
2496 struct http_object_request
*freq
;
2498 CALLOC_ARRAY(freq
, 1);
2499 strbuf_init(&freq
->tmpfile
, 0);
2500 oidcpy(&freq
->oid
, oid
);
2501 freq
->localfile
= -1;
2503 loose_object_path(the_repository
, &filename
, oid
);
2504 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2506 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2507 unlink_or_warn(prevfile
.buf
);
2508 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2509 unlink_or_warn(freq
->tmpfile
.buf
);
2510 strbuf_release(&filename
);
2512 if (freq
->localfile
!= -1)
2513 error("fd leakage in start: %d", freq
->localfile
);
2514 freq
->localfile
= open(freq
->tmpfile
.buf
,
2515 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2517 * This could have failed due to the "lazy directory creation";
2518 * try to mkdir the last path component.
2520 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2521 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2524 mkdir(freq
->tmpfile
.buf
, 0777);
2527 freq
->localfile
= open(freq
->tmpfile
.buf
,
2528 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2531 if (freq
->localfile
< 0) {
2532 error_errno("Couldn't create temporary file %s",
2537 git_inflate_init(&freq
->stream
);
2539 the_hash_algo
->init_fn(&freq
->c
);
2541 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2544 * If a previous temp file is present, process what was already
2547 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2548 if (prevlocal
!= -1) {
2550 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2552 if (fwrite_sha1_file(prev_buf
,
2555 freq
) == prev_read
) {
2556 prev_posn
+= prev_read
;
2561 } while (prev_read
> 0);
2564 unlink_or_warn(prevfile
.buf
);
2565 strbuf_release(&prevfile
);
2568 * Reset inflate/SHA1 if there was an error reading the previous temp
2569 * file; also rewind to the beginning of the local file.
2571 if (prev_read
== -1) {
2572 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2573 git_inflate_init(&freq
->stream
);
2574 the_hash_algo
->init_fn(&freq
->c
);
2577 lseek(freq
->localfile
, 0, SEEK_SET
);
2578 if (ftruncate(freq
->localfile
, 0) < 0) {
2579 error_errno("Couldn't truncate temporary file %s",
2586 freq
->slot
= get_active_slot();
2588 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2589 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2590 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2591 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2592 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2593 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2596 * If we have successfully processed data from a previous fetch
2597 * attempt, only fetch the data we don't already have.
2600 if (http_is_verbose
)
2602 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2603 hex
, (uintmax_t)prev_posn
);
2604 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2610 strbuf_release(&prevfile
);
2616 void process_http_object_request(struct http_object_request
*freq
)
2620 freq
->curl_result
= freq
->slot
->curl_result
;
2621 freq
->http_code
= freq
->slot
->http_code
;
2625 int finish_http_object_request(struct http_object_request
*freq
)
2628 struct strbuf filename
= STRBUF_INIT
;
2630 close(freq
->localfile
);
2631 freq
->localfile
= -1;
2633 process_http_object_request(freq
);
2635 if (freq
->http_code
== 416) {
2636 warning("requested range invalid; we may already have all the data.");
2637 } else if (freq
->curl_result
!= CURLE_OK
) {
2638 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2639 if (st
.st_size
== 0)
2640 unlink_or_warn(freq
->tmpfile
.buf
);
2644 git_inflate_end(&freq
->stream
);
2645 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2646 if (freq
->zret
!= Z_STREAM_END
) {
2647 unlink_or_warn(freq
->tmpfile
.buf
);
2650 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2651 unlink_or_warn(freq
->tmpfile
.buf
);
2654 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2655 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2656 strbuf_release(&filename
);
2658 return freq
->rename
;
2661 void abort_http_object_request(struct http_object_request
*freq
)
2663 unlink_or_warn(freq
->tmpfile
.buf
);
2665 release_http_object_request(freq
);
2668 void release_http_object_request(struct http_object_request
*freq
)
2670 if (freq
->localfile
!= -1) {
2671 close(freq
->localfile
);
2672 freq
->localfile
= -1;
2674 FREE_AND_NULL(freq
->url
);
2676 freq
->slot
->callback_func
= NULL
;
2677 freq
->slot
->callback_data
= NULL
;
2678 release_active_slot(freq
->slot
);
2681 strbuf_release(&freq
->tmpfile
);