1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
7 #include "run-command.h"
10 #include "credential.h"
14 #include "transport.h"
17 #include "string-list.h"
18 #include "object-store.h"
20 static struct trace_key trace_curl
= TRACE_KEY_INIT(CURL
);
21 static int trace_curl_data
= 1;
22 static int trace_curl_redact
= 1;
23 long int git_curl_ipresolve
= CURL_IPRESOLVE_WHATEVER
;
26 ssize_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
28 static int min_curl_sessions
= 1;
29 static int curl_session_count
;
30 static int max_requests
= -1;
32 static CURL
*curl_default
;
34 #define PREV_BUF_SIZE 4096
36 char curl_errorstr
[CURL_ERROR_SIZE
];
38 static int curl_ssl_verify
= -1;
39 static int curl_ssl_try
;
40 static const char *curl_http_version
= NULL
;
41 static const char *ssl_cert
;
42 static const char *ssl_cipherlist
;
43 static const char *ssl_version
;
48 { "sslv2", CURL_SSLVERSION_SSLv2
},
49 { "sslv3", CURL_SSLVERSION_SSLv3
},
50 { "tlsv1", CURL_SSLVERSION_TLSv1
},
51 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
52 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
53 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
54 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
56 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
57 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3
},
60 static const char *ssl_key
;
61 static const char *ssl_capath
;
62 static const char *curl_no_proxy
;
63 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
64 static const char *ssl_pinnedkey
;
66 static const char *ssl_cainfo
;
67 static long curl_low_speed_limit
= -1;
68 static long curl_low_speed_time
= -1;
69 static int curl_ftp_no_epsv
;
70 static const char *curl_http_proxy
;
71 static const char *http_proxy_authmethod
;
73 static const char *http_proxy_ssl_cert
;
74 static const char *http_proxy_ssl_key
;
75 static const char *http_proxy_ssl_ca_info
;
76 static struct credential proxy_cert_auth
= CREDENTIAL_INIT
;
77 static int proxy_ssl_cert_password_required
;
82 } proxy_authmethods
[] = {
83 { "basic", CURLAUTH_BASIC
},
84 { "digest", CURLAUTH_DIGEST
},
85 { "negotiate", CURLAUTH_GSSNEGOTIATE
},
86 { "ntlm", CURLAUTH_NTLM
},
87 { "anyauth", CURLAUTH_ANY
},
89 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
90 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
94 #ifdef CURLGSSAPI_DELEGATION_FLAG
95 static const char *curl_deleg
;
98 long curl_deleg_param
;
99 } curl_deleg_levels
[] = {
100 { "none", CURLGSSAPI_DELEGATION_NONE
},
101 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG
},
102 { "always", CURLGSSAPI_DELEGATION_FLAG
},
106 static struct credential proxy_auth
= CREDENTIAL_INIT
;
107 static const char *curl_proxyuserpwd
;
108 static const char *curl_cookie_file
;
109 static int curl_save_cookies
;
110 struct credential http_auth
= CREDENTIAL_INIT
;
111 static int http_proactive_auth
;
112 static const char *user_agent
;
113 static int curl_empty_auth
= -1;
115 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
117 static struct credential cert_auth
= CREDENTIAL_INIT
;
118 static int ssl_cert_password_required
;
119 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
120 static int http_auth_methods_restricted
;
121 /* Modes for which empty_auth cannot actually help us. */
122 static unsigned long empty_auth_useless
=
127 static struct curl_slist
*pragma_header
;
128 static struct curl_slist
*no_pragma_header
;
129 static struct string_list extra_http_headers
= STRING_LIST_INIT_DUP
;
131 static struct curl_slist
*host_resolutions
;
133 static struct active_request_slot
*active_queue_head
;
135 static char *cached_accept_language
;
137 static char *http_ssl_backend
;
139 static int http_schannel_check_revoke
= 1;
141 * With the backend being set to `schannel`, setting sslCAinfo would override
142 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
145 static int http_schannel_use_ssl_cainfo
;
147 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
149 size_t size
= eltsize
* nmemb
;
150 struct buffer
*buffer
= buffer_
;
152 if (size
> buffer
->buf
.len
- buffer
->posn
)
153 size
= buffer
->buf
.len
- buffer
->posn
;
154 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
155 buffer
->posn
+= size
;
157 return size
/ eltsize
;
160 int seek_buffer(void *clientp
, curl_off_t offset
, int origin
)
162 struct buffer
*buffer
= clientp
;
164 if (origin
!= SEEK_SET
)
165 BUG("seek_buffer only handles SEEK_SET");
166 if (offset
< 0 || offset
>= buffer
->buf
.len
) {
167 error("curl seek would be outside of buffer");
168 return CURL_SEEKFUNC_FAIL
;
171 buffer
->posn
= offset
;
172 return CURL_SEEKFUNC_OK
;
175 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
177 size_t size
= eltsize
* nmemb
;
178 struct strbuf
*buffer
= buffer_
;
180 strbuf_add(buffer
, ptr
, size
);
184 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
189 static void closedown_active_slot(struct active_request_slot
*slot
)
195 static void finish_active_slot(struct active_request_slot
*slot
)
197 closedown_active_slot(slot
);
198 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
201 (*slot
->finished
) = 1;
203 /* Store slot results so they can be read after the slot is reused */
205 slot
->results
->curl_result
= slot
->curl_result
;
206 slot
->results
->http_code
= slot
->http_code
;
207 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
208 &slot
->results
->auth_avail
);
210 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
211 &slot
->results
->http_connectcode
);
214 /* Run callback if appropriate */
215 if (slot
->callback_func
)
216 slot
->callback_func(slot
->callback_data
);
219 static void xmulti_remove_handle(struct active_request_slot
*slot
)
221 curl_multi_remove_handle(curlm
, slot
->curl
);
224 static void process_curl_messages(void)
227 struct active_request_slot
*slot
;
228 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
230 while (curl_message
!= NULL
) {
231 if (curl_message
->msg
== CURLMSG_DONE
) {
232 int curl_result
= curl_message
->data
.result
;
233 slot
= active_queue_head
;
234 while (slot
!= NULL
&&
235 slot
->curl
!= curl_message
->easy_handle
)
238 xmulti_remove_handle(slot
);
239 slot
->curl_result
= curl_result
;
240 finish_active_slot(slot
);
242 fprintf(stderr
, "Received DONE message for unknown request!\n");
245 fprintf(stderr
, "Unknown CURL message received: %d\n",
246 (int)curl_message
->msg
);
248 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
252 static int http_options(const char *var
, const char *value
, void *cb
)
254 if (!strcmp("http.version", var
)) {
255 return git_config_string(&curl_http_version
, var
, value
);
257 if (!strcmp("http.sslverify", var
)) {
258 curl_ssl_verify
= git_config_bool(var
, value
);
261 if (!strcmp("http.sslcipherlist", var
))
262 return git_config_string(&ssl_cipherlist
, var
, value
);
263 if (!strcmp("http.sslversion", var
))
264 return git_config_string(&ssl_version
, var
, value
);
265 if (!strcmp("http.sslcert", var
))
266 return git_config_pathname(&ssl_cert
, var
, value
);
267 if (!strcmp("http.sslkey", var
))
268 return git_config_pathname(&ssl_key
, var
, value
);
269 if (!strcmp("http.sslcapath", var
))
270 return git_config_pathname(&ssl_capath
, var
, value
);
271 if (!strcmp("http.sslcainfo", var
))
272 return git_config_pathname(&ssl_cainfo
, var
, value
);
273 if (!strcmp("http.sslcertpasswordprotected", var
)) {
274 ssl_cert_password_required
= git_config_bool(var
, value
);
277 if (!strcmp("http.ssltry", var
)) {
278 curl_ssl_try
= git_config_bool(var
, value
);
281 if (!strcmp("http.sslbackend", var
)) {
282 free(http_ssl_backend
);
283 http_ssl_backend
= xstrdup_or_null(value
);
287 if (!strcmp("http.schannelcheckrevoke", var
)) {
288 http_schannel_check_revoke
= git_config_bool(var
, value
);
292 if (!strcmp("http.schannelusesslcainfo", var
)) {
293 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
297 if (!strcmp("http.minsessions", var
)) {
298 min_curl_sessions
= git_config_int(var
, value
);
299 if (min_curl_sessions
> 1)
300 min_curl_sessions
= 1;
303 if (!strcmp("http.maxrequests", var
)) {
304 max_requests
= git_config_int(var
, value
);
307 if (!strcmp("http.lowspeedlimit", var
)) {
308 curl_low_speed_limit
= (long)git_config_int(var
, value
);
311 if (!strcmp("http.lowspeedtime", var
)) {
312 curl_low_speed_time
= (long)git_config_int(var
, value
);
316 if (!strcmp("http.noepsv", var
)) {
317 curl_ftp_no_epsv
= git_config_bool(var
, value
);
320 if (!strcmp("http.proxy", var
))
321 return git_config_string(&curl_http_proxy
, var
, value
);
323 if (!strcmp("http.proxyauthmethod", var
))
324 return git_config_string(&http_proxy_authmethod
, var
, value
);
326 if (!strcmp("http.proxysslcert", var
))
327 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
329 if (!strcmp("http.proxysslkey", var
))
330 return git_config_string(&http_proxy_ssl_key
, var
, value
);
332 if (!strcmp("http.proxysslcainfo", var
))
333 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
335 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
336 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
340 if (!strcmp("http.cookiefile", var
))
341 return git_config_pathname(&curl_cookie_file
, var
, value
);
342 if (!strcmp("http.savecookies", var
)) {
343 curl_save_cookies
= git_config_bool(var
, value
);
347 if (!strcmp("http.postbuffer", var
)) {
348 http_post_buffer
= git_config_ssize_t(var
, value
);
349 if (http_post_buffer
< 0)
350 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
351 if (http_post_buffer
< LARGE_PACKET_MAX
)
352 http_post_buffer
= LARGE_PACKET_MAX
;
356 if (!strcmp("http.useragent", var
))
357 return git_config_string(&user_agent
, var
, value
);
359 if (!strcmp("http.emptyauth", var
)) {
360 if (value
&& !strcmp("auto", value
))
361 curl_empty_auth
= -1;
363 curl_empty_auth
= git_config_bool(var
, value
);
367 if (!strcmp("http.delegation", var
)) {
368 #ifdef CURLGSSAPI_DELEGATION_FLAG
369 return git_config_string(&curl_deleg
, var
, value
);
371 warning(_("Delegation control is not supported with cURL < 7.22.0"));
376 if (!strcmp("http.pinnedpubkey", var
)) {
377 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
378 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
380 warning(_("Public key pinning not supported with cURL < 7.39.0"));
385 if (!strcmp("http.extraheader", var
)) {
387 return config_error_nonbool(var
);
388 } else if (!*value
) {
389 string_list_clear(&extra_http_headers
, 0);
391 string_list_append(&extra_http_headers
, value
);
396 if (!strcmp("http.curloptresolve", var
)) {
398 return config_error_nonbool(var
);
399 } else if (!*value
) {
400 curl_slist_free_all(host_resolutions
);
401 host_resolutions
= NULL
;
403 host_resolutions
= curl_slist_append(host_resolutions
, value
);
408 if (!strcmp("http.followredirects", var
)) {
409 if (value
&& !strcmp(value
, "initial"))
410 http_follow_config
= HTTP_FOLLOW_INITIAL
;
411 else if (git_config_bool(var
, value
))
412 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
414 http_follow_config
= HTTP_FOLLOW_NONE
;
418 /* Fall back on the default ones */
419 return git_default_config(var
, value
, cb
);
422 static int curl_empty_auth_enabled(void)
424 if (curl_empty_auth
>= 0)
425 return curl_empty_auth
;
428 * In the automatic case, kick in the empty-auth
429 * hack as long as we would potentially try some
430 * method more exotic than "Basic" or "Digest".
432 * But only do this when this is our second or
433 * subsequent request, as by then we know what
434 * methods are available.
436 if (http_auth_methods_restricted
&&
437 (http_auth_methods
& ~empty_auth_useless
))
442 static void init_curl_http_auth(CURL
*result
)
444 if (!http_auth
.username
|| !*http_auth
.username
) {
445 if (curl_empty_auth_enabled())
446 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
450 credential_fill(&http_auth
);
452 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
453 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
456 /* *var must be free-able */
457 static void var_override(const char **var
, char *value
)
461 *var
= xstrdup(value
);
465 static void set_proxyauth_name_password(CURL
*result
)
467 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
468 proxy_auth
.username
);
469 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
470 proxy_auth
.password
);
473 static void init_curl_proxy_auth(CURL
*result
)
475 if (proxy_auth
.username
) {
476 if (!proxy_auth
.password
)
477 credential_fill(&proxy_auth
);
478 set_proxyauth_name_password(result
);
481 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
483 if (http_proxy_authmethod
) {
485 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
486 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
487 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
488 proxy_authmethods
[i
].curlauth_param
);
492 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
493 warning("unsupported proxy authentication method %s: using anyauth",
494 http_proxy_authmethod
);
495 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
499 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
502 static int has_cert_password(void)
504 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
506 if (!cert_auth
.password
) {
507 cert_auth
.protocol
= xstrdup("cert");
508 cert_auth
.host
= xstrdup("");
509 cert_auth
.username
= xstrdup("");
510 cert_auth
.path
= xstrdup(ssl_cert
);
511 credential_fill(&cert_auth
);
516 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
517 static int has_proxy_cert_password(void)
519 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
521 if (!proxy_cert_auth
.password
) {
522 proxy_cert_auth
.protocol
= xstrdup("cert");
523 proxy_cert_auth
.host
= xstrdup("");
524 proxy_cert_auth
.username
= xstrdup("");
525 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
526 credential_fill(&proxy_cert_auth
);
532 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
533 static void set_curl_keepalive(CURL
*c
)
535 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
539 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
543 socklen_t len
= (socklen_t
)sizeof(ka
);
545 if (type
!= CURLSOCKTYPE_IPCXN
)
548 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
550 warning_errno("unable to set SO_KEEPALIVE on socket");
552 return CURL_SOCKOPT_OK
;
555 static void set_curl_keepalive(CURL
*c
)
557 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
561 /* Return 1 if redactions have been made, 0 otherwise. */
562 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
565 const char *sensitive_header
;
567 if (trace_curl_redact
&&
568 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
569 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
570 /* The first token is the type, which is OK to log */
571 while (isspace(*sensitive_header
))
573 while (*sensitive_header
&& !isspace(*sensitive_header
))
575 /* Everything else is opaque and possibly sensitive */
576 strbuf_setlen(header
, sensitive_header
- header
->buf
);
577 strbuf_addstr(header
, " <redacted>");
579 } else if (trace_curl_redact
&&
580 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
581 struct strbuf redacted_header
= STRBUF_INIT
;
584 while (isspace(*sensitive_header
))
587 cookie
= sensitive_header
;
591 char *semicolon
= strstr(cookie
, "; ");
594 equals
= strchrnul(cookie
, '=');
596 /* invalid cookie, just append and continue */
597 strbuf_addstr(&redacted_header
, cookie
);
600 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
601 strbuf_addstr(&redacted_header
, "=<redacted>");
604 * There are more cookies. (Or, for some
605 * reason, the input string ends in "; ".)
607 strbuf_addstr(&redacted_header
, "; ");
608 cookie
= semicolon
+ strlen("; ");
614 strbuf_setlen(header
, sensitive_header
- header
->buf
);
615 strbuf_addbuf(header
, &redacted_header
);
621 /* Redact headers in info */
622 static void redact_sensitive_info_header(struct strbuf
*header
)
624 const char *sensitive_header
;
627 * curl's h2h3 prints headers in info, e.g.:
628 * h2h3 [<header-name>: <header-val>]
630 if (trace_curl_redact
&&
631 skip_iprefix(header
->buf
, "h2h3 [", &sensitive_header
)) {
632 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
633 /* redaction ate our closing bracket */
634 strbuf_addch(header
, ']');
639 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
641 struct strbuf out
= STRBUF_INIT
;
642 struct strbuf
**headers
, **header
;
644 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
645 text
, (long)size
, (long)size
);
646 trace_strbuf(&trace_curl
, &out
);
648 strbuf_add(&out
, ptr
, size
);
649 headers
= strbuf_split_max(&out
, '\n', 0);
651 for (header
= headers
; *header
; header
++) {
652 if (hide_sensitive_header
)
653 redact_sensitive_header(*header
, 0);
654 strbuf_insertstr((*header
), 0, text
);
655 strbuf_insertstr((*header
), strlen(text
), ": ");
656 strbuf_rtrim((*header
));
657 strbuf_addch((*header
), '\n');
658 trace_strbuf(&trace_curl
, (*header
));
660 strbuf_list_free(headers
);
661 strbuf_release(&out
);
664 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
667 struct strbuf out
= STRBUF_INIT
;
668 unsigned int width
= 60;
670 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
671 text
, (long)size
, (long)size
);
672 trace_strbuf(&trace_curl
, &out
);
674 for (i
= 0; i
< size
; i
+= width
) {
678 strbuf_addf(&out
, "%s: ", text
);
679 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
680 unsigned char ch
= ptr
[i
+ w
];
683 (ch
>= 0x20) && (ch
< 0x80)
686 strbuf_addch(&out
, '\n');
687 trace_strbuf(&trace_curl
, &out
);
689 strbuf_release(&out
);
692 static void curl_dump_info(char *data
, size_t size
)
694 struct strbuf buf
= STRBUF_INIT
;
696 strbuf_add(&buf
, data
, size
);
698 redact_sensitive_info_header(&buf
);
699 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
701 strbuf_release(&buf
);
704 static int curl_trace(CURL
*handle
, curl_infotype type
, char *data
, size_t size
, void *userp
)
707 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
711 curl_dump_info(data
, size
);
713 case CURLINFO_HEADER_OUT
:
714 text
= "=> Send header";
715 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
717 case CURLINFO_DATA_OUT
:
718 if (trace_curl_data
) {
719 text
= "=> Send data";
720 curl_dump_data(text
, (unsigned char *)data
, size
);
723 case CURLINFO_SSL_DATA_OUT
:
724 if (trace_curl_data
) {
725 text
= "=> Send SSL data";
726 curl_dump_data(text
, (unsigned char *)data
, size
);
729 case CURLINFO_HEADER_IN
:
730 text
= "<= Recv header";
731 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
733 case CURLINFO_DATA_IN
:
734 if (trace_curl_data
) {
735 text
= "<= Recv data";
736 curl_dump_data(text
, (unsigned char *)data
, size
);
739 case CURLINFO_SSL_DATA_IN
:
740 if (trace_curl_data
) {
741 text
= "<= Recv SSL data";
742 curl_dump_data(text
, (unsigned char *)data
, size
);
746 default: /* we ignore unknown types by default */
752 void http_trace_curl_no_data(void)
754 trace_override_envvar(&trace_curl
, "1");
758 void setup_curl_trace(CURL
*handle
)
760 if (!trace_want(&trace_curl
))
762 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
763 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
764 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
767 static void proto_list_append(struct strbuf
*list
, const char *proto
)
772 strbuf_addch(list
, ',');
773 strbuf_addstr(list
, proto
);
776 static long get_curl_allowed_protocols(int from_user
, struct strbuf
*list
)
780 if (is_transport_allowed("http", from_user
)) {
781 bits
|= CURLPROTO_HTTP
;
782 proto_list_append(list
, "http");
784 if (is_transport_allowed("https", from_user
)) {
785 bits
|= CURLPROTO_HTTPS
;
786 proto_list_append(list
, "https");
788 if (is_transport_allowed("ftp", from_user
)) {
789 bits
|= CURLPROTO_FTP
;
790 proto_list_append(list
, "ftp");
792 if (is_transport_allowed("ftps", from_user
)) {
793 bits
|= CURLPROTO_FTPS
;
794 proto_list_append(list
, "ftps");
800 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
801 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
808 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
809 { "HTTP/2", CURL_HTTP_VERSION_2
}
812 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
813 if (!strcmp(version_string
, choice
[i
].name
)) {
814 *opt
= choice
[i
].opt_token
;
819 warning("unknown value given to http.version: '%s'", version_string
);
820 return -1; /* not found */
825 static CURL
*get_curl_handle(void)
827 CURL
*result
= curl_easy_init();
830 die("curl_easy_init failed");
832 if (!curl_ssl_verify
) {
833 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
834 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
836 /* Verify authenticity of the peer's certificate */
837 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
838 /* The name in the cert must match whom we tried to connect */
839 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
842 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
843 if (curl_http_version
) {
845 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
846 /* Set request use http version */
847 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
852 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
853 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
855 #ifdef CURLGSSAPI_DELEGATION_FLAG
858 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
859 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
860 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
861 curl_deleg_levels
[i
].curl_deleg_param
);
865 if (i
== ARRAY_SIZE(curl_deleg_levels
))
866 warning("Unknown delegation method '%s': using default",
871 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
872 !http_schannel_check_revoke
) {
873 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
874 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
876 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
880 if (http_proactive_auth
)
881 init_curl_http_auth(result
);
883 if (getenv("GIT_SSL_VERSION"))
884 ssl_version
= getenv("GIT_SSL_VERSION");
885 if (ssl_version
&& *ssl_version
) {
887 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
888 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
889 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
890 sslversions
[i
].ssl_version
);
894 if (i
== ARRAY_SIZE(sslversions
))
895 warning("unsupported ssl version %s: using default",
899 if (getenv("GIT_SSL_CIPHER_LIST"))
900 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
901 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
902 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
906 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
907 if (has_cert_password())
908 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
910 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
912 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
913 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
915 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
917 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
918 !http_schannel_use_ssl_cainfo
) {
919 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
920 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
921 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
923 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
925 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
926 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
927 if (http_proxy_ssl_ca_info
)
928 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
932 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
933 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
934 curl_low_speed_limit
);
935 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
936 curl_low_speed_time
);
939 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
940 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
942 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
944 struct strbuf buf
= STRBUF_INIT
;
946 get_curl_allowed_protocols(0, &buf
);
947 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS_STR
, buf
.buf
);
950 get_curl_allowed_protocols(-1, &buf
);
951 curl_easy_setopt(result
, CURLOPT_PROTOCOLS_STR
, buf
.buf
);
952 strbuf_release(&buf
);
955 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
956 get_curl_allowed_protocols(0, NULL
));
957 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
958 get_curl_allowed_protocols(-1, NULL
));
961 if (getenv("GIT_CURL_VERBOSE"))
962 http_trace_curl_no_data();
963 setup_curl_trace(result
);
964 if (getenv("GIT_TRACE_CURL_NO_DATA"))
966 if (!git_env_bool("GIT_TRACE_REDACT", 1))
967 trace_curl_redact
= 0;
969 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
970 user_agent
? user_agent
: git_user_agent());
972 if (curl_ftp_no_epsv
)
973 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
976 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
979 * CURL also examines these variables as a fallback; but we need to query
980 * them here in order to decide whether to prompt for missing password (cf.
981 * init_curl_proxy_auth()).
983 * Unlike many other common environment variables, these are historically
984 * lowercase only. It appears that CURL did not know this and implemented
985 * only uppercase variants, which was later corrected to take both - with
986 * the exception of http_proxy, which is lowercase only also in CURL. As
987 * the lowercase versions are the historical quasi-standard, they take
988 * precedence here, as in CURL.
990 if (!curl_http_proxy
) {
991 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
992 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
993 var_override(&curl_http_proxy
, getenv("https_proxy"));
995 var_override(&curl_http_proxy
, getenv("http_proxy"));
997 if (!curl_http_proxy
) {
998 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
999 var_override(&curl_http_proxy
, getenv("all_proxy"));
1003 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1005 * Handle case with the empty http.proxy value here to keep
1006 * common code clean.
1007 * NB: empty option disables proxying at all.
1009 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1010 } else if (curl_http_proxy
) {
1011 if (starts_with(curl_http_proxy
, "socks5h"))
1012 curl_easy_setopt(result
,
1013 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1014 else if (starts_with(curl_http_proxy
, "socks5"))
1015 curl_easy_setopt(result
,
1016 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1017 else if (starts_with(curl_http_proxy
, "socks4a"))
1018 curl_easy_setopt(result
,
1019 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1020 else if (starts_with(curl_http_proxy
, "socks"))
1021 curl_easy_setopt(result
,
1022 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1023 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1024 else if (starts_with(curl_http_proxy
, "https")) {
1025 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1027 if (http_proxy_ssl_cert
)
1028 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1030 if (http_proxy_ssl_key
)
1031 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1033 if (has_proxy_cert_password())
1034 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1037 if (strstr(curl_http_proxy
, "://"))
1038 credential_from_url(&proxy_auth
, curl_http_proxy
);
1040 struct strbuf url
= STRBUF_INIT
;
1041 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1042 credential_from_url(&proxy_auth
, url
.buf
);
1043 strbuf_release(&url
);
1046 if (!proxy_auth
.host
)
1047 die("Invalid proxy URL '%s'", curl_http_proxy
);
1049 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1050 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1051 var_override(&curl_no_proxy
, getenv("no_proxy"));
1052 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1054 init_curl_proxy_auth(result
);
1056 set_curl_keepalive(result
);
1061 static void set_from_env(const char **var
, const char *envname
)
1063 const char *val
= getenv(envname
);
1068 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1070 char *low_speed_limit
;
1071 char *low_speed_time
;
1072 char *normalized_url
;
1073 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1075 config
.section
= "http";
1077 config
.collect_fn
= http_options
;
1078 config
.cascade_fn
= git_default_config
;
1081 http_is_verbose
= 0;
1082 normalized_url
= url_normalize(url
, &config
.url
);
1084 git_config(urlmatch_config_entry
, &config
);
1085 free(normalized_url
);
1086 string_list_clear(&config
.vars
, 1);
1088 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1089 if (http_ssl_backend
) {
1090 const curl_ssl_backend
**backends
;
1091 struct strbuf buf
= STRBUF_INIT
;
1094 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1095 case CURLSSLSET_UNKNOWN_BACKEND
:
1096 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1097 "Supported SSL backends:"),
1099 for (i
= 0; backends
[i
]; i
++)
1100 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1102 case CURLSSLSET_NO_BACKENDS
:
1103 die(_("Could not set SSL backend to '%s': "
1104 "cURL was built without SSL backends"),
1106 case CURLSSLSET_TOO_LATE
:
1107 die(_("Could not set SSL backend to '%s': already set"),
1115 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1116 die("curl_global_init failed");
1118 http_proactive_auth
= proactive_auth
;
1120 if (remote
&& remote
->http_proxy
)
1121 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1124 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1126 pragma_header
= curl_slist_append(http_copy_default_headers(),
1127 "Pragma: no-cache");
1128 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
1132 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1133 if (http_max_requests
)
1134 max_requests
= atoi(http_max_requests
);
1137 curlm
= curl_multi_init();
1139 die("curl_multi_init failed");
1141 if (getenv("GIT_SSL_NO_VERIFY"))
1142 curl_ssl_verify
= 0;
1144 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1145 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1146 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1147 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1149 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1151 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1152 if (low_speed_limit
)
1153 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1154 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1156 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1158 if (curl_ssl_verify
== -1)
1159 curl_ssl_verify
= 1;
1161 curl_session_count
= 0;
1162 if (max_requests
< 1)
1163 max_requests
= DEFAULT_MAX_REQUESTS
;
1165 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1166 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1167 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1169 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1170 proxy_ssl_cert_password_required
= 1;
1172 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1173 curl_ftp_no_epsv
= 1;
1176 credential_from_url(&http_auth
, url
);
1177 if (!ssl_cert_password_required
&&
1178 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1179 starts_with(url
, "https://"))
1180 ssl_cert_password_required
= 1;
1183 curl_default
= get_curl_handle();
1186 void http_cleanup(void)
1188 struct active_request_slot
*slot
= active_queue_head
;
1190 while (slot
!= NULL
) {
1191 struct active_request_slot
*next
= slot
->next
;
1193 xmulti_remove_handle(slot
);
1194 curl_easy_cleanup(slot
->curl
);
1199 active_queue_head
= NULL
;
1201 curl_easy_cleanup(curl_default
);
1203 curl_multi_cleanup(curlm
);
1204 curl_global_cleanup();
1206 string_list_clear(&extra_http_headers
, 0);
1208 curl_slist_free_all(pragma_header
);
1209 pragma_header
= NULL
;
1211 curl_slist_free_all(no_pragma_header
);
1212 no_pragma_header
= NULL
;
1214 curl_slist_free_all(host_resolutions
);
1215 host_resolutions
= NULL
;
1217 if (curl_http_proxy
) {
1218 free((void *)curl_http_proxy
);
1219 curl_http_proxy
= NULL
;
1222 if (proxy_auth
.password
) {
1223 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1224 FREE_AND_NULL(proxy_auth
.password
);
1227 free((void *)curl_proxyuserpwd
);
1228 curl_proxyuserpwd
= NULL
;
1230 free((void *)http_proxy_authmethod
);
1231 http_proxy_authmethod
= NULL
;
1233 if (cert_auth
.password
) {
1234 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1235 FREE_AND_NULL(cert_auth
.password
);
1237 ssl_cert_password_required
= 0;
1239 if (proxy_cert_auth
.password
) {
1240 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1241 FREE_AND_NULL(proxy_cert_auth
.password
);
1243 proxy_ssl_cert_password_required
= 0;
1245 FREE_AND_NULL(cached_accept_language
);
1248 struct active_request_slot
*get_active_slot(void)
1250 struct active_request_slot
*slot
= active_queue_head
;
1251 struct active_request_slot
*newslot
;
1255 /* Wait for a slot to open up if the queue is full */
1256 while (active_requests
>= max_requests
) {
1257 curl_multi_perform(curlm
, &num_transfers
);
1258 if (num_transfers
< active_requests
)
1259 process_curl_messages();
1262 while (slot
!= NULL
&& slot
->in_use
)
1266 newslot
= xmalloc(sizeof(*newslot
));
1267 newslot
->curl
= NULL
;
1268 newslot
->in_use
= 0;
1269 newslot
->next
= NULL
;
1271 slot
= active_queue_head
;
1273 active_queue_head
= newslot
;
1275 while (slot
->next
!= NULL
)
1277 slot
->next
= newslot
;
1283 slot
->curl
= curl_easy_duphandle(curl_default
);
1284 curl_session_count
++;
1289 slot
->results
= NULL
;
1290 slot
->finished
= NULL
;
1291 slot
->callback_data
= NULL
;
1292 slot
->callback_func
= NULL
;
1293 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1294 if (curl_save_cookies
)
1295 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1296 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1297 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1298 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1299 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1300 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1301 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1302 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1303 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1304 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1305 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1306 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1309 * Default following to off unless "ALWAYS" is configured; this gives
1310 * callers a sane starting point, and they can tweak for individual
1311 * HTTP_FOLLOW_* cases themselves.
1313 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1314 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1316 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1318 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1319 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1320 if (http_auth
.password
|| curl_empty_auth_enabled())
1321 init_curl_http_auth(slot
->curl
);
1326 int start_active_slot(struct active_request_slot
*slot
)
1328 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1331 if (curlm_result
!= CURLM_OK
&&
1332 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1333 warning("curl_multi_add_handle failed: %s",
1334 curl_multi_strerror(curlm_result
));
1341 * We know there must be something to do, since we just added
1344 curl_multi_perform(curlm
, &num_transfers
);
1350 int (*fill
)(void *);
1351 struct fill_chain
*next
;
1354 static struct fill_chain
*fill_cfg
;
1356 void add_fill_function(void *data
, int (*fill
)(void *))
1358 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1359 struct fill_chain
**linkp
= &fill_cfg
;
1360 new_fill
->data
= data
;
1361 new_fill
->fill
= fill
;
1362 new_fill
->next
= NULL
;
1364 linkp
= &(*linkp
)->next
;
1368 void fill_active_slots(void)
1370 struct active_request_slot
*slot
= active_queue_head
;
1372 while (active_requests
< max_requests
) {
1373 struct fill_chain
*fill
;
1374 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1375 if (fill
->fill(fill
->data
))
1382 while (slot
!= NULL
) {
1383 if (!slot
->in_use
&& slot
->curl
!= NULL
1384 && curl_session_count
> min_curl_sessions
) {
1385 curl_easy_cleanup(slot
->curl
);
1387 curl_session_count
--;
1393 void step_active_slots(void)
1396 CURLMcode curlm_result
;
1399 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1400 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1401 if (num_transfers
< active_requests
) {
1402 process_curl_messages();
1403 fill_active_slots();
1407 void run_active_slot(struct active_request_slot
*slot
)
1413 struct timeval select_timeout
;
1416 slot
->finished
= &finished
;
1418 step_active_slots();
1422 curl_multi_timeout(curlm
, &curl_timeout
);
1423 if (curl_timeout
== 0) {
1425 } else if (curl_timeout
== -1) {
1426 select_timeout
.tv_sec
= 0;
1427 select_timeout
.tv_usec
= 50000;
1429 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1430 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1437 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1440 * It can happen that curl_multi_timeout returns a pathologically
1441 * long timeout when curl_multi_fdset returns no file descriptors
1442 * to read. See commit message for more details.
1445 (select_timeout
.tv_sec
> 0 ||
1446 select_timeout
.tv_usec
> 50000)) {
1447 select_timeout
.tv_sec
= 0;
1448 select_timeout
.tv_usec
= 50000;
1451 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1456 * The value of slot->finished we set before the loop was used
1457 * to set our "finished" variable when our request completed.
1459 * 1. The slot may not have been reused for another requst
1460 * yet, in which case it still has &finished.
1462 * 2. The slot may already be in-use to serve another request,
1463 * which can further be divided into two cases:
1465 * (a) If call run_active_slot() hasn't been called for that
1466 * other request, slot->finished would have been cleared
1467 * by get_active_slot() and has NULL.
1469 * (b) If the request did call run_active_slot(), then the
1470 * call would have updated slot->finished at the beginning
1471 * of this function, and with the clearing of the member
1472 * below, we would find that slot->finished is now NULL.
1474 * In all cases, slot->finished has no useful information to
1475 * anybody at this point. Some compilers warn us for
1476 * attempting to smuggle a pointer that is about to become
1477 * invalid, i.e. &finished. We clear it here to assure them.
1479 slot
->finished
= NULL
;
1482 static void release_active_slot(struct active_request_slot
*slot
)
1484 closedown_active_slot(slot
);
1486 xmulti_remove_handle(slot
);
1487 if (curl_session_count
> min_curl_sessions
) {
1488 curl_easy_cleanup(slot
->curl
);
1490 curl_session_count
--;
1493 fill_active_slots();
1496 void finish_all_active_slots(void)
1498 struct active_request_slot
*slot
= active_queue_head
;
1500 while (slot
!= NULL
)
1502 run_active_slot(slot
);
1503 slot
= active_queue_head
;
1509 /* Helpers for modifying and creating URLs */
1510 static inline int needs_quote(int ch
)
1512 if (((ch
>= 'A') && (ch
<= 'Z'))
1513 || ((ch
>= 'a') && (ch
<= 'z'))
1514 || ((ch
>= '0') && (ch
<= '9'))
1522 static char *quote_ref_url(const char *base
, const char *ref
)
1524 struct strbuf buf
= STRBUF_INIT
;
1528 end_url_with_slash(&buf
, base
);
1530 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1531 if (needs_quote(ch
))
1532 strbuf_addf(&buf
, "%%%02x", ch
);
1534 strbuf_addch(&buf
, *cp
);
1536 return strbuf_detach(&buf
, NULL
);
1539 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1541 int only_two_digit_prefix
)
1543 end_url_with_slash(buf
, url
);
1545 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1546 if (!only_two_digit_prefix
)
1547 strbuf_addstr(buf
, hex
+ 2);
1550 char *get_remote_object_url(const char *url
, const char *hex
,
1551 int only_two_digit_prefix
)
1553 struct strbuf buf
= STRBUF_INIT
;
1554 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1555 return strbuf_detach(&buf
, NULL
);
1558 void normalize_curl_result(CURLcode
*result
, long http_code
,
1559 char *errorstr
, size_t errorlen
)
1562 * If we see a failing http code with CURLE_OK, we have turned off
1563 * FAILONERROR (to keep the server's custom error response), and should
1564 * translate the code into failure here.
1566 * Likewise, if we see a redirect (30x code), that means we turned off
1567 * redirect-following, and we should treat the result as an error.
1569 if (*result
== CURLE_OK
&& http_code
>= 300) {
1570 *result
= CURLE_HTTP_RETURNED_ERROR
;
1572 * Normally curl will already have put the "reason phrase"
1573 * from the server into curl_errorstr; unfortunately without
1574 * FAILONERROR it is lost, so we can give only the numeric
1577 xsnprintf(errorstr
, errorlen
,
1578 "The requested URL returned error: %ld",
1583 static int handle_curl_result(struct slot_results
*results
)
1585 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1586 curl_errorstr
, sizeof(curl_errorstr
));
1588 if (results
->curl_result
== CURLE_OK
) {
1589 credential_approve(&http_auth
);
1590 credential_approve(&proxy_auth
);
1591 credential_approve(&cert_auth
);
1593 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1595 * We can't tell from here whether it's a bad path, bad
1596 * certificate, bad password, or something else wrong
1597 * with the certificate. So we reject the credential to
1598 * avoid caching or saving a bad password.
1600 credential_reject(&cert_auth
);
1602 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1603 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1604 return HTTP_NOMATCHPUBLICKEY
;
1606 } else if (missing_target(results
))
1607 return HTTP_MISSING_TARGET
;
1608 else if (results
->http_code
== 401) {
1609 if (http_auth
.username
&& http_auth
.password
) {
1610 credential_reject(&http_auth
);
1613 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1614 if (results
->auth_avail
) {
1615 http_auth_methods
&= results
->auth_avail
;
1616 http_auth_methods_restricted
= 1;
1621 if (results
->http_connectcode
== 407)
1622 credential_reject(&proxy_auth
);
1623 if (!curl_errorstr
[0])
1624 strlcpy(curl_errorstr
,
1625 curl_easy_strerror(results
->curl_result
),
1626 sizeof(curl_errorstr
));
1631 int run_one_slot(struct active_request_slot
*slot
,
1632 struct slot_results
*results
)
1634 slot
->results
= results
;
1635 if (!start_active_slot(slot
)) {
1636 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1637 "failed to start HTTP request");
1638 return HTTP_START_FAILED
;
1641 run_active_slot(slot
);
1642 return handle_curl_result(results
);
1645 struct curl_slist
*http_copy_default_headers(void)
1647 struct curl_slist
*headers
= NULL
;
1648 const struct string_list_item
*item
;
1650 for_each_string_list_item(item
, &extra_http_headers
)
1651 headers
= curl_slist_append(headers
, item
->string
);
1656 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1662 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1664 strbuf_addstr(buf
, ptr
);
1669 * Check for and extract a content-type parameter. "raw"
1670 * should be positioned at the start of the potential
1671 * parameter, with any whitespace already removed.
1673 * "name" is the name of the parameter. The value is appended
1676 static int extract_param(const char *raw
, const char *name
,
1679 size_t len
= strlen(name
);
1681 if (strncasecmp(raw
, name
, len
))
1689 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1690 strbuf_addch(out
, *raw
++);
1695 * Extract a normalized version of the content type, with any
1696 * spaces suppressed, all letters lowercased, and no trailing ";"
1699 * Note that we will silently remove even invalid whitespace. For
1700 * example, "text / plain" is specifically forbidden by RFC 2616,
1701 * but "text/plain" is the only reasonable output, and this keeps
1704 * If the "charset" argument is not NULL, store the value of any
1705 * charset parameter there.
1708 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1709 * "text / plain" -> "text/plain"
1711 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1712 struct strbuf
*charset
)
1717 strbuf_grow(type
, raw
->len
);
1718 for (p
= raw
->buf
; *p
; p
++) {
1725 strbuf_addch(type
, tolower(*p
));
1731 strbuf_reset(charset
);
1733 while (isspace(*p
) || *p
== ';')
1735 if (!extract_param(p
, "charset", charset
))
1737 while (*p
&& !isspace(*p
))
1741 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1742 strbuf_addstr(charset
, "ISO-8859-1");
1745 static void write_accept_language(struct strbuf
*buf
)
1748 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1749 * that, q-value will be smaller than 0.001, the minimum q-value the
1750 * HTTP specification allows. See
1751 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1753 const int MAX_DECIMAL_PLACES
= 3;
1754 const int MAX_LANGUAGE_TAGS
= 1000;
1755 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1756 char **language_tags
= NULL
;
1758 const char *s
= get_preferred_languages();
1760 struct strbuf tag
= STRBUF_INIT
;
1762 /* Don't add Accept-Language header if no language is preferred. */
1767 * Split the colon-separated string of preferred languages into
1768 * language_tags array.
1771 /* collect language tag */
1772 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1773 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1775 /* skip .codeset, @modifier and any other unnecessary parts */
1776 while (*s
&& *s
!= ':')
1781 REALLOC_ARRAY(language_tags
, num_langs
);
1782 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1783 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1788 /* write Accept-Language header into buf */
1790 int last_buf_len
= 0;
1796 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1797 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1799 /* compute decimal_places */
1800 for (max_q
= 1, decimal_places
= 0;
1801 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1802 decimal_places
++, max_q
*= 10)
1805 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1807 strbuf_addstr(buf
, "Accept-Language: ");
1809 for (i
= 0; i
< num_langs
; i
++) {
1811 strbuf_addstr(buf
, ", ");
1813 strbuf_addstr(buf
, language_tags
[i
]);
1816 strbuf_addf(buf
, q_format
, max_q
- i
);
1818 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1819 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1823 last_buf_len
= buf
->len
;
1827 /* free language tags -- last one is a static '*' */
1828 for (i
= 0; i
< num_langs
- 1; i
++)
1829 free(language_tags
[i
]);
1830 free(language_tags
);
1834 * Get an Accept-Language header which indicates user's preferred languages.
1838 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1839 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1840 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1841 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1842 * LANGUAGE= LANG=C -> ""
1844 const char *http_get_accept_language_header(void)
1846 if (!cached_accept_language
) {
1847 struct strbuf buf
= STRBUF_INIT
;
1848 write_accept_language(&buf
);
1850 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1853 return cached_accept_language
;
1856 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1859 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1860 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1863 /* http_request() targets */
1864 #define HTTP_REQUEST_STRBUF 0
1865 #define HTTP_REQUEST_FILE 1
1867 static int http_request(const char *url
,
1868 void *result
, int target
,
1869 const struct http_get_options
*options
)
1871 struct active_request_slot
*slot
;
1872 struct slot_results results
;
1873 struct curl_slist
*headers
= http_copy_default_headers();
1874 struct strbuf buf
= STRBUF_INIT
;
1875 const char *accept_language
;
1878 slot
= get_active_slot();
1879 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1882 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1884 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1885 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
1887 if (target
== HTTP_REQUEST_FILE
) {
1888 off_t posn
= ftello(result
);
1889 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1892 http_opt_request_remainder(slot
->curl
, posn
);
1894 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1898 accept_language
= http_get_accept_language_header();
1900 if (accept_language
)
1901 headers
= curl_slist_append(headers
, accept_language
);
1903 strbuf_addstr(&buf
, "Pragma:");
1904 if (options
&& options
->no_cache
)
1905 strbuf_addstr(&buf
, " no-cache");
1906 if (options
&& options
->initial_request
&&
1907 http_follow_config
== HTTP_FOLLOW_INITIAL
)
1908 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1910 headers
= curl_slist_append(headers
, buf
.buf
);
1912 /* Add additional headers here */
1913 if (options
&& options
->extra_headers
) {
1914 const struct string_list_item
*item
;
1915 for_each_string_list_item(item
, options
->extra_headers
) {
1916 headers
= curl_slist_append(headers
, item
->string
);
1920 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1921 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1922 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
1923 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1925 ret
= run_one_slot(slot
, &results
);
1927 if (options
&& options
->content_type
) {
1928 struct strbuf raw
= STRBUF_INIT
;
1929 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1930 extract_content_type(&raw
, options
->content_type
,
1932 strbuf_release(&raw
);
1935 if (options
&& options
->effective_url
)
1936 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1937 options
->effective_url
);
1939 curl_slist_free_all(headers
);
1940 strbuf_release(&buf
);
1946 * Update the "base" url to a more appropriate value, as deduced by
1947 * redirects seen when requesting a URL starting with "url".
1949 * The "asked" parameter is a URL that we asked curl to access, and must begin
1952 * The "got" parameter is the URL that curl reported to us as where we ended
1955 * Returns 1 if we updated the base url, 0 otherwise.
1957 * Our basic strategy is to compare "base" and "asked" to find the bits
1958 * specific to our request. We then strip those bits off of "got" to yield the
1959 * new base. So for example, if our base is "http://example.com/foo.git",
1960 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1961 * with "https://other.example.com/foo.git/info/refs". We would want the
1962 * new URL to become "https://other.example.com/foo.git".
1964 * Note that this assumes a sane redirect scheme. It's entirely possible
1965 * in the example above to end up at a URL that does not even end in
1966 * "info/refs". In such a case we die. There's not much we can do, such a
1967 * scheme is unlikely to represent a real git repository, and failing to
1968 * rewrite the base opens options for malicious redirects to do funny things.
1970 static int update_url_from_redirect(struct strbuf
*base
,
1972 const struct strbuf
*got
)
1977 if (!strcmp(asked
, got
->buf
))
1980 if (!skip_prefix(asked
, base
->buf
, &tail
))
1981 BUG("update_url_from_redirect: %s is not a superset of %s",
1985 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
1986 die(_("unable to update url base from redirection:\n"
1992 strbuf_add(base
, got
->buf
, new_len
);
1997 static int http_request_reauth(const char *url
,
1998 void *result
, int target
,
1999 struct http_get_options
*options
)
2001 int ret
= http_request(url
, result
, target
, options
);
2003 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2006 if (options
&& options
->effective_url
&& options
->base_url
) {
2007 if (update_url_from_redirect(options
->base_url
,
2008 url
, options
->effective_url
)) {
2009 credential_from_url(&http_auth
, options
->base_url
->buf
);
2010 url
= options
->effective_url
->buf
;
2014 if (ret
!= HTTP_REAUTH
)
2018 * The previous request may have put cruft into our output stream; we
2019 * should clear it out before making our next request.
2022 case HTTP_REQUEST_STRBUF
:
2023 strbuf_reset(result
);
2025 case HTTP_REQUEST_FILE
:
2026 if (fflush(result
)) {
2027 error_errno("unable to flush a file");
2028 return HTTP_START_FAILED
;
2031 if (ftruncate(fileno(result
), 0) < 0) {
2032 error_errno("unable to truncate a file");
2033 return HTTP_START_FAILED
;
2037 BUG("Unknown http_request target");
2040 credential_fill(&http_auth
);
2042 return http_request(url
, result
, target
, options
);
2045 int http_get_strbuf(const char *url
,
2046 struct strbuf
*result
,
2047 struct http_get_options
*options
)
2049 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2053 * Downloads a URL and stores the result in the given file.
2055 * If a previous interrupted download is detected (i.e. a previous temporary
2056 * file is still around) the download is resumed.
2058 int http_get_file(const char *url
, const char *filename
,
2059 struct http_get_options
*options
)
2062 struct strbuf tmpfile
= STRBUF_INIT
;
2065 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2066 result
= fopen(tmpfile
.buf
, "a");
2068 error("Unable to open local file %s", tmpfile
.buf
);
2073 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2076 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2079 strbuf_release(&tmpfile
);
2083 int http_fetch_ref(const char *base
, struct ref
*ref
)
2085 struct http_get_options options
= {0};
2087 struct strbuf buffer
= STRBUF_INIT
;
2090 options
.no_cache
= 1;
2092 url
= quote_ref_url(base
, ref
->name
);
2093 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2094 strbuf_rtrim(&buffer
);
2095 if (buffer
.len
== the_hash_algo
->hexsz
)
2096 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2097 else if (starts_with(buffer
.buf
, "ref: ")) {
2098 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2103 strbuf_release(&buffer
);
2108 /* Helpers for fetching packs */
2109 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2112 struct strbuf buf
= STRBUF_INIT
;
2114 if (http_is_verbose
)
2115 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2117 end_url_with_slash(&buf
, base_url
);
2118 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2119 url
= strbuf_detach(&buf
, NULL
);
2121 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2122 tmp
= strbuf_detach(&buf
, NULL
);
2124 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2125 error("Unable to get pack index %s", url
);
2133 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2134 unsigned char *sha1
, const char *base_url
)
2136 struct packed_git
*new_pack
;
2137 char *tmp_idx
= NULL
;
2140 if (has_pack_index(sha1
)) {
2141 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2143 return -1; /* parse_pack_index() already issued error message */
2147 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2151 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2156 return -1; /* parse_pack_index() already issued error message */
2159 ret
= verify_pack_index(new_pack
);
2161 close_pack_index(new_pack
);
2162 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2169 new_pack
->next
= *packs_head
;
2170 *packs_head
= new_pack
;
2174 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2176 struct http_get_options options
= {0};
2180 struct strbuf buf
= STRBUF_INIT
;
2181 struct object_id oid
;
2183 end_url_with_slash(&buf
, base_url
);
2184 strbuf_addstr(&buf
, "objects/info/packs");
2185 url
= strbuf_detach(&buf
, NULL
);
2187 options
.no_cache
= 1;
2188 ret
= http_get_strbuf(url
, &buf
, &options
);
2194 if (skip_prefix(data
, "P pack-", &data
) &&
2195 !parse_oid_hex(data
, &oid
, &data
) &&
2196 skip_prefix(data
, ".pack", &data
) &&
2197 (*data
== '\n' || *data
== '\0')) {
2198 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2200 data
= strchrnul(data
, '\n');
2203 data
++; /* skip past newline */
2211 void release_http_pack_request(struct http_pack_request
*preq
)
2213 if (preq
->packfile
) {
2214 fclose(preq
->packfile
);
2215 preq
->packfile
= NULL
;
2218 strbuf_release(&preq
->tmpfile
);
2223 static const char *default_index_pack_args
[] =
2224 {"index-pack", "--stdin", NULL
};
2226 int finish_http_pack_request(struct http_pack_request
*preq
)
2228 struct child_process ip
= CHILD_PROCESS_INIT
;
2232 fclose(preq
->packfile
);
2233 preq
->packfile
= NULL
;
2235 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2239 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2240 preq
->index_pack_args
:
2241 default_index_pack_args
);
2243 if (preq
->preserve_index_pack_stdout
)
2248 if (run_command(&ip
)) {
2255 unlink(preq
->tmpfile
.buf
);
2259 void http_install_packfile(struct packed_git
*p
,
2260 struct packed_git
**list_to_remove_from
)
2262 struct packed_git
**lst
= list_to_remove_from
;
2265 lst
= &((*lst
)->next
);
2266 *lst
= (*lst
)->next
;
2268 install_packed_git(the_repository
, p
);
2271 struct http_pack_request
*new_http_pack_request(
2272 const unsigned char *packed_git_hash
, const char *base_url
) {
2274 struct strbuf buf
= STRBUF_INIT
;
2276 end_url_with_slash(&buf
, base_url
);
2277 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2278 hash_to_hex(packed_git_hash
));
2279 return new_direct_http_pack_request(packed_git_hash
,
2280 strbuf_detach(&buf
, NULL
));
2283 struct http_pack_request
*new_direct_http_pack_request(
2284 const unsigned char *packed_git_hash
, char *url
)
2286 off_t prev_posn
= 0;
2287 struct http_pack_request
*preq
;
2289 CALLOC_ARRAY(preq
, 1);
2290 strbuf_init(&preq
->tmpfile
, 0);
2294 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2295 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2296 if (!preq
->packfile
) {
2297 error("Unable to open local file %s for pack",
2302 preq
->slot
= get_active_slot();
2303 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2304 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2305 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2306 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
2310 * If there is data present from a previous transfer attempt,
2311 * resume where it left off
2313 prev_posn
= ftello(preq
->packfile
);
2315 if (http_is_verbose
)
2317 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2318 hash_to_hex(packed_git_hash
),
2319 (uintmax_t)prev_posn
);
2320 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2326 strbuf_release(&preq
->tmpfile
);
2332 /* Helpers for fetching objects (loose) */
2333 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2336 unsigned char expn
[4096];
2337 size_t size
= eltsize
* nmemb
;
2339 struct http_object_request
*freq
= data
;
2340 struct active_request_slot
*slot
= freq
->slot
;
2343 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2346 BUG("curl_easy_getinfo for HTTP code failed: %s",
2347 curl_easy_strerror(c
));
2348 if (slot
->http_code
>= 300)
2353 ssize_t retval
= xwrite(freq
->localfile
,
2354 (char *) ptr
+ posn
, size
- posn
);
2356 return posn
/ eltsize
;
2358 } while (posn
< size
);
2360 freq
->stream
.avail_in
= size
;
2361 freq
->stream
.next_in
= (void *)ptr
;
2363 freq
->stream
.next_out
= expn
;
2364 freq
->stream
.avail_out
= sizeof(expn
);
2365 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2366 the_hash_algo
->update_fn(&freq
->c
, expn
,
2367 sizeof(expn
) - freq
->stream
.avail_out
);
2368 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2372 struct http_object_request
*new_http_object_request(const char *base_url
,
2373 const struct object_id
*oid
)
2375 char *hex
= oid_to_hex(oid
);
2376 struct strbuf filename
= STRBUF_INIT
;
2377 struct strbuf prevfile
= STRBUF_INIT
;
2379 char prev_buf
[PREV_BUF_SIZE
];
2380 ssize_t prev_read
= 0;
2381 off_t prev_posn
= 0;
2382 struct http_object_request
*freq
;
2384 CALLOC_ARRAY(freq
, 1);
2385 strbuf_init(&freq
->tmpfile
, 0);
2386 oidcpy(&freq
->oid
, oid
);
2387 freq
->localfile
= -1;
2389 loose_object_path(the_repository
, &filename
, oid
);
2390 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2392 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2393 unlink_or_warn(prevfile
.buf
);
2394 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2395 unlink_or_warn(freq
->tmpfile
.buf
);
2396 strbuf_release(&filename
);
2398 if (freq
->localfile
!= -1)
2399 error("fd leakage in start: %d", freq
->localfile
);
2400 freq
->localfile
= open(freq
->tmpfile
.buf
,
2401 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2403 * This could have failed due to the "lazy directory creation";
2404 * try to mkdir the last path component.
2406 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2407 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2410 mkdir(freq
->tmpfile
.buf
, 0777);
2413 freq
->localfile
= open(freq
->tmpfile
.buf
,
2414 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2417 if (freq
->localfile
< 0) {
2418 error_errno("Couldn't create temporary file %s",
2423 git_inflate_init(&freq
->stream
);
2425 the_hash_algo
->init_fn(&freq
->c
);
2427 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2430 * If a previous temp file is present, process what was already
2433 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2434 if (prevlocal
!= -1) {
2436 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2438 if (fwrite_sha1_file(prev_buf
,
2441 freq
) == prev_read
) {
2442 prev_posn
+= prev_read
;
2447 } while (prev_read
> 0);
2450 unlink_or_warn(prevfile
.buf
);
2451 strbuf_release(&prevfile
);
2454 * Reset inflate/SHA1 if there was an error reading the previous temp
2455 * file; also rewind to the beginning of the local file.
2457 if (prev_read
== -1) {
2458 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2459 git_inflate_init(&freq
->stream
);
2460 the_hash_algo
->init_fn(&freq
->c
);
2463 lseek(freq
->localfile
, 0, SEEK_SET
);
2464 if (ftruncate(freq
->localfile
, 0) < 0) {
2465 error_errno("Couldn't truncate temporary file %s",
2472 freq
->slot
= get_active_slot();
2474 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2475 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2476 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2477 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2478 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2479 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2482 * If we have successfully processed data from a previous fetch
2483 * attempt, only fetch the data we don't already have.
2486 if (http_is_verbose
)
2488 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2489 hex
, (uintmax_t)prev_posn
);
2490 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2496 strbuf_release(&prevfile
);
2502 void process_http_object_request(struct http_object_request
*freq
)
2506 freq
->curl_result
= freq
->slot
->curl_result
;
2507 freq
->http_code
= freq
->slot
->http_code
;
2511 int finish_http_object_request(struct http_object_request
*freq
)
2514 struct strbuf filename
= STRBUF_INIT
;
2516 close(freq
->localfile
);
2517 freq
->localfile
= -1;
2519 process_http_object_request(freq
);
2521 if (freq
->http_code
== 416) {
2522 warning("requested range invalid; we may already have all the data.");
2523 } else if (freq
->curl_result
!= CURLE_OK
) {
2524 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2525 if (st
.st_size
== 0)
2526 unlink_or_warn(freq
->tmpfile
.buf
);
2530 git_inflate_end(&freq
->stream
);
2531 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2532 if (freq
->zret
!= Z_STREAM_END
) {
2533 unlink_or_warn(freq
->tmpfile
.buf
);
2536 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2537 unlink_or_warn(freq
->tmpfile
.buf
);
2540 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2541 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2542 strbuf_release(&filename
);
2544 return freq
->rename
;
2547 void abort_http_object_request(struct http_object_request
*freq
)
2549 unlink_or_warn(freq
->tmpfile
.buf
);
2551 release_http_object_request(freq
);
2554 void release_http_object_request(struct http_object_request
*freq
)
2556 if (freq
->localfile
!= -1) {
2557 close(freq
->localfile
);
2558 freq
->localfile
= -1;
2560 FREE_AND_NULL(freq
->url
);
2562 freq
->slot
->callback_func
= NULL
;
2563 freq
->slot
->callback_data
= NULL
;
2564 release_active_slot(freq
->slot
);
2567 strbuf_release(&freq
->tmpfile
);