1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
14 #if LIBCURL_VERSION_NUM >= 0x070a08
15 long int git_curl_ipresolve
= CURL_IPRESOLVE_WHATEVER
;
17 long int git_curl_ipresolve
;
21 size_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
23 #if LIBCURL_VERSION_NUM >= 0x070a06
24 #define LIBCURL_CAN_HANDLE_AUTH_ANY
27 static int min_curl_sessions
= 1;
28 static int curl_session_count
;
30 static int max_requests
= -1;
33 #ifndef NO_CURL_EASY_DUPHANDLE
34 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 *ssl_cert
;
44 static const char *ssl_cipherlist
;
45 static const char *ssl_version
;
50 { "sslv2", CURL_SSLVERSION_SSLv2
},
51 { "sslv3", CURL_SSLVERSION_SSLv3
},
52 { "tlsv1", CURL_SSLVERSION_TLSv1
},
53 #if LIBCURL_VERSION_NUM >= 0x072200
54 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
55 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
56 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
59 #if LIBCURL_VERSION_NUM >= 0x070903
60 static const char *ssl_key
;
62 #if LIBCURL_VERSION_NUM >= 0x070908
63 static const char *ssl_capath
;
65 #if LIBCURL_VERSION_NUM >= 0x072c00
66 static const char *ssl_pinnedkey
;
68 static const char *ssl_cainfo
;
69 static long curl_low_speed_limit
= -1;
70 static long curl_low_speed_time
= -1;
71 static int curl_ftp_no_epsv
;
72 static const char *curl_http_proxy
;
73 static const char *curl_no_proxy
;
74 static const char *http_proxy_authmethod
;
78 } proxy_authmethods
[] = {
79 { "basic", CURLAUTH_BASIC
},
80 { "digest", CURLAUTH_DIGEST
},
81 { "negotiate", CURLAUTH_GSSNEGOTIATE
},
82 { "ntlm", CURLAUTH_NTLM
},
83 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
84 { "anyauth", CURLAUTH_ANY
},
87 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
88 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
92 static struct credential proxy_auth
= CREDENTIAL_INIT
;
93 static const char *curl_proxyuserpwd
;
94 static const char *curl_cookie_file
;
95 static int curl_save_cookies
;
96 struct credential http_auth
= CREDENTIAL_INIT
;
97 static int http_proactive_auth
;
98 static const char *user_agent
;
99 static int curl_empty_auth
;
101 #if LIBCURL_VERSION_NUM >= 0x071700
102 /* Use CURLOPT_KEYPASSWD as is */
103 #elif LIBCURL_VERSION_NUM >= 0x070903
104 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
106 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
109 static struct credential cert_auth
= CREDENTIAL_INIT
;
110 static int ssl_cert_password_required
;
111 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
112 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
115 static struct curl_slist
*pragma_header
;
116 static struct curl_slist
*no_pragma_header
;
117 static struct curl_slist
*extra_http_headers
;
119 static struct active_request_slot
*active_queue_head
;
121 static char *cached_accept_language
;
123 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
125 size_t size
= eltsize
* nmemb
;
126 struct buffer
*buffer
= buffer_
;
128 if (size
> buffer
->buf
.len
- buffer
->posn
)
129 size
= buffer
->buf
.len
- buffer
->posn
;
130 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
131 buffer
->posn
+= size
;
136 #ifndef NO_CURL_IOCTL
137 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
139 struct buffer
*buffer
= clientp
;
145 case CURLIOCMD_RESTARTREAD
:
150 return CURLIOE_UNKNOWNCMD
;
155 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
157 size_t size
= eltsize
* nmemb
;
158 struct strbuf
*buffer
= buffer_
;
160 strbuf_add(buffer
, ptr
, size
);
164 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
166 return eltsize
* nmemb
;
169 static void closedown_active_slot(struct active_request_slot
*slot
)
175 static void finish_active_slot(struct active_request_slot
*slot
)
177 closedown_active_slot(slot
);
178 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
180 if (slot
->finished
!= NULL
)
181 (*slot
->finished
) = 1;
183 /* Store slot results so they can be read after the slot is reused */
184 if (slot
->results
!= NULL
) {
185 slot
->results
->curl_result
= slot
->curl_result
;
186 slot
->results
->http_code
= slot
->http_code
;
187 #if LIBCURL_VERSION_NUM >= 0x070a08
188 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
189 &slot
->results
->auth_avail
);
191 slot
->results
->auth_avail
= 0;
194 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
195 &slot
->results
->http_connectcode
);
198 /* Run callback if appropriate */
199 if (slot
->callback_func
!= NULL
)
200 slot
->callback_func(slot
->callback_data
);
203 #ifdef USE_CURL_MULTI
204 static void process_curl_messages(void)
207 struct active_request_slot
*slot
;
208 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
210 while (curl_message
!= NULL
) {
211 if (curl_message
->msg
== CURLMSG_DONE
) {
212 int curl_result
= curl_message
->data
.result
;
213 slot
= active_queue_head
;
214 while (slot
!= NULL
&&
215 slot
->curl
!= curl_message
->easy_handle
)
218 curl_multi_remove_handle(curlm
, slot
->curl
);
219 slot
->curl_result
= curl_result
;
220 finish_active_slot(slot
);
222 fprintf(stderr
, "Received DONE message for unknown request!\n");
225 fprintf(stderr
, "Unknown CURL message received: %d\n",
226 (int)curl_message
->msg
);
228 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
233 static int http_options(const char *var
, const char *value
, void *cb
)
235 if (!strcmp("http.sslverify", var
)) {
236 curl_ssl_verify
= git_config_bool(var
, value
);
239 if (!strcmp("http.sslcipherlist", var
))
240 return git_config_string(&ssl_cipherlist
, var
, value
);
241 if (!strcmp("http.sslversion", var
))
242 return git_config_string(&ssl_version
, var
, value
);
243 if (!strcmp("http.sslcert", var
))
244 return git_config_string(&ssl_cert
, var
, value
);
245 #if LIBCURL_VERSION_NUM >= 0x070903
246 if (!strcmp("http.sslkey", var
))
247 return git_config_string(&ssl_key
, var
, value
);
249 #if LIBCURL_VERSION_NUM >= 0x070908
250 if (!strcmp("http.sslcapath", var
))
251 return git_config_pathname(&ssl_capath
, var
, value
);
253 if (!strcmp("http.sslcainfo", var
))
254 return git_config_pathname(&ssl_cainfo
, var
, value
);
255 if (!strcmp("http.sslcertpasswordprotected", var
)) {
256 ssl_cert_password_required
= git_config_bool(var
, value
);
259 if (!strcmp("http.ssltry", var
)) {
260 curl_ssl_try
= git_config_bool(var
, value
);
263 if (!strcmp("http.minsessions", var
)) {
264 min_curl_sessions
= git_config_int(var
, value
);
265 #ifndef USE_CURL_MULTI
266 if (min_curl_sessions
> 1)
267 min_curl_sessions
= 1;
271 #ifdef USE_CURL_MULTI
272 if (!strcmp("http.maxrequests", var
)) {
273 max_requests
= git_config_int(var
, value
);
277 if (!strcmp("http.lowspeedlimit", var
)) {
278 curl_low_speed_limit
= (long)git_config_int(var
, value
);
281 if (!strcmp("http.lowspeedtime", var
)) {
282 curl_low_speed_time
= (long)git_config_int(var
, value
);
286 if (!strcmp("http.noepsv", var
)) {
287 curl_ftp_no_epsv
= git_config_bool(var
, value
);
290 if (!strcmp("http.proxy", var
))
291 return git_config_string(&curl_http_proxy
, var
, value
);
293 if (!strcmp("http.proxyauthmethod", var
))
294 return git_config_string(&http_proxy_authmethod
, var
, value
);
296 if (!strcmp("http.cookiefile", var
))
297 return git_config_string(&curl_cookie_file
, var
, value
);
298 if (!strcmp("http.savecookies", var
)) {
299 curl_save_cookies
= git_config_bool(var
, value
);
303 if (!strcmp("http.postbuffer", var
)) {
304 http_post_buffer
= git_config_int(var
, value
);
305 if (http_post_buffer
< LARGE_PACKET_MAX
)
306 http_post_buffer
= LARGE_PACKET_MAX
;
310 if (!strcmp("http.useragent", var
))
311 return git_config_string(&user_agent
, var
, value
);
313 if (!strcmp("http.emptyauth", var
)) {
314 curl_empty_auth
= git_config_bool(var
, value
);
318 if (!strcmp("http.pinnedpubkey", var
)) {
319 #if LIBCURL_VERSION_NUM >= 0x072c00
320 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
322 warning(_("Public key pinning not supported with cURL < 7.44.0"));
327 if (!strcmp("http.extraheader", var
)) {
329 return config_error_nonbool(var
);
330 } else if (!*value
) {
331 curl_slist_free_all(extra_http_headers
);
332 extra_http_headers
= NULL
;
335 curl_slist_append(extra_http_headers
, value
);
340 /* Fall back on the default ones */
341 return git_default_config(var
, value
, cb
);
344 static void init_curl_http_auth(CURL
*result
)
346 if (!http_auth
.username
) {
348 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
352 credential_fill(&http_auth
);
354 #if LIBCURL_VERSION_NUM >= 0x071301
355 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
356 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
359 static struct strbuf up
= STRBUF_INIT
;
361 * Note that we assume we only ever have a single set of
362 * credentials in a given program run, so we do not have
363 * to worry about updating this buffer, only setting its
367 strbuf_addf(&up
, "%s:%s",
368 http_auth
.username
, http_auth
.password
);
369 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
374 /* *var must be free-able */
375 static void var_override(const char **var
, char *value
)
379 *var
= xstrdup(value
);
383 static void set_proxyauth_name_password(CURL
*result
)
385 #if LIBCURL_VERSION_NUM >= 0x071301
386 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
387 proxy_auth
.username
);
388 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
389 proxy_auth
.password
);
391 struct strbuf s
= STRBUF_INIT
;
393 strbuf_addstr_urlencode(&s
, proxy_auth
.username
, 1);
394 strbuf_addch(&s
, ':');
395 strbuf_addstr_urlencode(&s
, proxy_auth
.password
, 1);
396 curl_proxyuserpwd
= strbuf_detach(&s
, NULL
);
397 curl_easy_setopt(result
, CURLOPT_PROXYUSERPWD
, curl_proxyuserpwd
);
401 static void init_curl_proxy_auth(CURL
*result
)
403 if (proxy_auth
.username
) {
404 if (!proxy_auth
.password
)
405 credential_fill(&proxy_auth
);
406 set_proxyauth_name_password(result
);
409 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
411 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
412 if (http_proxy_authmethod
) {
414 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
415 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
416 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
417 proxy_authmethods
[i
].curlauth_param
);
421 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
422 warning("unsupported proxy authentication method %s: using anyauth",
423 http_proxy_authmethod
);
424 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
428 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
432 static int has_cert_password(void)
434 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
436 if (!cert_auth
.password
) {
437 cert_auth
.protocol
= xstrdup("cert");
438 cert_auth
.username
= xstrdup("");
439 cert_auth
.path
= xstrdup(ssl_cert
);
440 credential_fill(&cert_auth
);
445 #if LIBCURL_VERSION_NUM >= 0x071900
446 static void set_curl_keepalive(CURL
*c
)
448 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
451 #elif LIBCURL_VERSION_NUM >= 0x071000
452 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
456 socklen_t len
= (socklen_t
)sizeof(ka
);
458 if (type
!= CURLSOCKTYPE_IPCXN
)
461 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
463 warning("unable to set SO_KEEPALIVE on socket %s",
466 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
469 static void set_curl_keepalive(CURL
*c
)
471 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
475 static void set_curl_keepalive(CURL
*c
)
477 /* not supported on older curl versions */
481 static CURL
*get_curl_handle(void)
483 CURL
*result
= curl_easy_init();
484 long allowed_protocols
= 0;
487 die("curl_easy_init failed");
489 if (!curl_ssl_verify
) {
490 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
491 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
493 /* Verify authenticity of the peer's certificate */
494 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
495 /* The name in the cert must match whom we tried to connect */
496 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
499 #if LIBCURL_VERSION_NUM >= 0x070907
500 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
502 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
503 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
506 if (http_proactive_auth
)
507 init_curl_http_auth(result
);
509 if (getenv("GIT_SSL_VERSION"))
510 ssl_version
= getenv("GIT_SSL_VERSION");
511 if (ssl_version
&& *ssl_version
) {
513 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
514 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
515 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
516 sslversions
[i
].ssl_version
);
520 if (i
== ARRAY_SIZE(sslversions
))
521 warning("unsupported ssl version %s: using default",
525 if (getenv("GIT_SSL_CIPHER_LIST"))
526 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
527 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
528 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
531 if (ssl_cert
!= NULL
)
532 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
533 if (has_cert_password())
534 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
535 #if LIBCURL_VERSION_NUM >= 0x070903
537 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
539 #if LIBCURL_VERSION_NUM >= 0x070908
540 if (ssl_capath
!= NULL
)
541 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
543 #if LIBCURL_VERSION_NUM >= 0x072c00
544 if (ssl_pinnedkey
!= NULL
)
545 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
547 if (ssl_cainfo
!= NULL
)
548 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
550 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
551 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
552 curl_low_speed_limit
);
553 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
554 curl_low_speed_time
);
557 curl_easy_setopt(result
, CURLOPT_FOLLOWLOCATION
, 1);
558 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
559 #if LIBCURL_VERSION_NUM >= 0x071301
560 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
561 #elif LIBCURL_VERSION_NUM >= 0x071101
562 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
564 #if LIBCURL_VERSION_NUM >= 0x071304
565 if (is_transport_allowed("http"))
566 allowed_protocols
|= CURLPROTO_HTTP
;
567 if (is_transport_allowed("https"))
568 allowed_protocols
|= CURLPROTO_HTTPS
;
569 if (is_transport_allowed("ftp"))
570 allowed_protocols
|= CURLPROTO_FTP
;
571 if (is_transport_allowed("ftps"))
572 allowed_protocols
|= CURLPROTO_FTPS
;
573 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
575 if (transport_restrict_protocols())
576 warning("protocol restrictions not applied to curl redirects because\n"
577 "your curl version is too old (>= 7.19.4)");
580 if (getenv("GIT_CURL_VERBOSE"))
581 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1);
583 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
584 user_agent
? user_agent
: git_user_agent());
586 if (curl_ftp_no_epsv
)
587 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
589 #ifdef CURLOPT_USE_SSL
591 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
595 * CURL also examines these variables as a fallback; but we need to query
596 * them here in order to decide whether to prompt for missing password (cf.
597 * init_curl_proxy_auth()).
599 * Unlike many other common environment variables, these are historically
600 * lowercase only. It appears that CURL did not know this and implemented
601 * only uppercase variants, which was later corrected to take both - with
602 * the exception of http_proxy, which is lowercase only also in CURL. As
603 * the lowercase versions are the historical quasi-standard, they take
604 * precedence here, as in CURL.
606 if (!curl_http_proxy
) {
607 if (!strcmp(http_auth
.protocol
, "https")) {
608 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
609 var_override(&curl_http_proxy
, getenv("https_proxy"));
611 var_override(&curl_http_proxy
, getenv("http_proxy"));
613 if (!curl_http_proxy
) {
614 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
615 var_override(&curl_http_proxy
, getenv("all_proxy"));
619 if (curl_http_proxy
) {
620 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
621 #if LIBCURL_VERSION_NUM >= 0x071800
622 if (starts_with(curl_http_proxy
, "socks5"))
623 curl_easy_setopt(result
,
624 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
625 else if (starts_with(curl_http_proxy
, "socks4a"))
626 curl_easy_setopt(result
,
627 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
628 else if (starts_with(curl_http_proxy
, "socks"))
629 curl_easy_setopt(result
,
630 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
632 if (strstr(curl_http_proxy
, "://"))
633 credential_from_url(&proxy_auth
, curl_http_proxy
);
635 struct strbuf url
= STRBUF_INIT
;
636 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
637 credential_from_url(&proxy_auth
, url
.buf
);
638 strbuf_release(&url
);
641 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
642 #if LIBCURL_VERSION_NUM >= 0x071304
643 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
644 var_override(&curl_no_proxy
, getenv("no_proxy"));
645 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
648 init_curl_proxy_auth(result
);
650 set_curl_keepalive(result
);
655 static void set_from_env(const char **var
, const char *envname
)
657 const char *val
= getenv(envname
);
662 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
664 char *low_speed_limit
;
665 char *low_speed_time
;
666 char *normalized_url
;
667 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
669 config
.section
= "http";
671 config
.collect_fn
= http_options
;
672 config
.cascade_fn
= git_default_config
;
676 normalized_url
= url_normalize(url
, &config
.url
);
678 git_config(urlmatch_config_entry
, &config
);
679 free(normalized_url
);
681 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
682 die("curl_global_init failed");
684 http_proactive_auth
= proactive_auth
;
686 if (remote
&& remote
->http_proxy
)
687 curl_http_proxy
= xstrdup(remote
->http_proxy
);
690 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
692 pragma_header
= curl_slist_append(http_copy_default_headers(),
694 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
697 #ifdef USE_CURL_MULTI
699 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
700 if (http_max_requests
!= NULL
)
701 max_requests
= atoi(http_max_requests
);
704 curlm
= curl_multi_init();
706 die("curl_multi_init failed");
709 if (getenv("GIT_SSL_NO_VERIFY"))
712 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
713 #if LIBCURL_VERSION_NUM >= 0x070903
714 set_from_env(&ssl_key
, "GIT_SSL_KEY");
716 #if LIBCURL_VERSION_NUM >= 0x070908
717 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
719 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
721 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
723 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
724 if (low_speed_limit
!= NULL
)
725 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
726 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
727 if (low_speed_time
!= NULL
)
728 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
730 if (curl_ssl_verify
== -1)
733 curl_session_count
= 0;
734 #ifdef USE_CURL_MULTI
735 if (max_requests
< 1)
736 max_requests
= DEFAULT_MAX_REQUESTS
;
739 if (getenv("GIT_CURL_FTP_NO_EPSV"))
740 curl_ftp_no_epsv
= 1;
743 credential_from_url(&http_auth
, url
);
744 if (!ssl_cert_password_required
&&
745 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
746 starts_with(url
, "https://"))
747 ssl_cert_password_required
= 1;
750 #ifndef NO_CURL_EASY_DUPHANDLE
751 curl_default
= get_curl_handle();
755 void http_cleanup(void)
757 struct active_request_slot
*slot
= active_queue_head
;
759 while (slot
!= NULL
) {
760 struct active_request_slot
*next
= slot
->next
;
761 if (slot
->curl
!= NULL
) {
762 #ifdef USE_CURL_MULTI
763 curl_multi_remove_handle(curlm
, slot
->curl
);
765 curl_easy_cleanup(slot
->curl
);
770 active_queue_head
= NULL
;
772 #ifndef NO_CURL_EASY_DUPHANDLE
773 curl_easy_cleanup(curl_default
);
776 #ifdef USE_CURL_MULTI
777 curl_multi_cleanup(curlm
);
779 curl_global_cleanup();
781 curl_slist_free_all(extra_http_headers
);
782 extra_http_headers
= NULL
;
784 curl_slist_free_all(pragma_header
);
785 pragma_header
= NULL
;
787 curl_slist_free_all(no_pragma_header
);
788 no_pragma_header
= NULL
;
790 if (curl_http_proxy
) {
791 free((void *)curl_http_proxy
);
792 curl_http_proxy
= NULL
;
795 if (proxy_auth
.password
) {
796 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
797 free(proxy_auth
.password
);
798 proxy_auth
.password
= NULL
;
801 free((void *)curl_proxyuserpwd
);
802 curl_proxyuserpwd
= NULL
;
804 free((void *)http_proxy_authmethod
);
805 http_proxy_authmethod
= NULL
;
807 if (cert_auth
.password
!= NULL
) {
808 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
809 free(cert_auth
.password
);
810 cert_auth
.password
= NULL
;
812 ssl_cert_password_required
= 0;
814 free(cached_accept_language
);
815 cached_accept_language
= NULL
;
818 struct active_request_slot
*get_active_slot(void)
820 struct active_request_slot
*slot
= active_queue_head
;
821 struct active_request_slot
*newslot
;
823 #ifdef USE_CURL_MULTI
826 /* Wait for a slot to open up if the queue is full */
827 while (active_requests
>= max_requests
) {
828 curl_multi_perform(curlm
, &num_transfers
);
829 if (num_transfers
< active_requests
)
830 process_curl_messages();
834 while (slot
!= NULL
&& slot
->in_use
)
838 newslot
= xmalloc(sizeof(*newslot
));
839 newslot
->curl
= NULL
;
841 newslot
->next
= NULL
;
843 slot
= active_queue_head
;
845 active_queue_head
= newslot
;
847 while (slot
->next
!= NULL
)
849 slot
->next
= newslot
;
854 if (slot
->curl
== NULL
) {
855 #ifdef NO_CURL_EASY_DUPHANDLE
856 slot
->curl
= get_curl_handle();
858 slot
->curl
= curl_easy_duphandle(curl_default
);
860 curl_session_count
++;
865 slot
->results
= NULL
;
866 slot
->finished
= NULL
;
867 slot
->callback_data
= NULL
;
868 slot
->callback_func
= NULL
;
869 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
870 if (curl_save_cookies
)
871 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
872 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
873 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
874 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
875 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
876 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
877 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
878 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
879 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
880 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
881 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
883 #if LIBCURL_VERSION_NUM >= 0x070a08
884 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
886 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
887 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
889 if (http_auth
.password
|| curl_empty_auth
)
890 init_curl_http_auth(slot
->curl
);
895 int start_active_slot(struct active_request_slot
*slot
)
897 #ifdef USE_CURL_MULTI
898 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
901 if (curlm_result
!= CURLM_OK
&&
902 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
909 * We know there must be something to do, since we just added
912 curl_multi_perform(curlm
, &num_transfers
);
917 #ifdef USE_CURL_MULTI
921 struct fill_chain
*next
;
924 static struct fill_chain
*fill_cfg
;
926 void add_fill_function(void *data
, int (*fill
)(void *))
928 struct fill_chain
*new = xmalloc(sizeof(*new));
929 struct fill_chain
**linkp
= &fill_cfg
;
934 linkp
= &(*linkp
)->next
;
938 void fill_active_slots(void)
940 struct active_request_slot
*slot
= active_queue_head
;
942 while (active_requests
< max_requests
) {
943 struct fill_chain
*fill
;
944 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
945 if (fill
->fill(fill
->data
))
952 while (slot
!= NULL
) {
953 if (!slot
->in_use
&& slot
->curl
!= NULL
954 && curl_session_count
> min_curl_sessions
) {
955 curl_easy_cleanup(slot
->curl
);
957 curl_session_count
--;
963 void step_active_slots(void)
966 CURLMcode curlm_result
;
969 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
970 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
971 if (num_transfers
< active_requests
) {
972 process_curl_messages();
978 void run_active_slot(struct active_request_slot
*slot
)
980 #ifdef USE_CURL_MULTI
985 struct timeval select_timeout
;
988 slot
->finished
= &finished
;
993 #if LIBCURL_VERSION_NUM >= 0x070f04
995 curl_multi_timeout(curlm
, &curl_timeout
);
996 if (curl_timeout
== 0) {
998 } else if (curl_timeout
== -1) {
999 select_timeout
.tv_sec
= 0;
1000 select_timeout
.tv_usec
= 50000;
1002 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1003 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1006 select_timeout
.tv_sec
= 0;
1007 select_timeout
.tv_usec
= 50000;
1014 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1017 * It can happen that curl_multi_timeout returns a pathologically
1018 * long timeout when curl_multi_fdset returns no file descriptors
1019 * to read. See commit message for more details.
1022 (select_timeout
.tv_sec
> 0 ||
1023 select_timeout
.tv_usec
> 50000)) {
1024 select_timeout
.tv_sec
= 0;
1025 select_timeout
.tv_usec
= 50000;
1028 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1032 while (slot
->in_use
) {
1033 slot
->curl_result
= curl_easy_perform(slot
->curl
);
1034 finish_active_slot(slot
);
1039 static void release_active_slot(struct active_request_slot
*slot
)
1041 closedown_active_slot(slot
);
1042 if (slot
->curl
&& curl_session_count
> min_curl_sessions
) {
1043 #ifdef USE_CURL_MULTI
1044 curl_multi_remove_handle(curlm
, slot
->curl
);
1046 curl_easy_cleanup(slot
->curl
);
1048 curl_session_count
--;
1050 #ifdef USE_CURL_MULTI
1051 fill_active_slots();
1055 void finish_all_active_slots(void)
1057 struct active_request_slot
*slot
= active_queue_head
;
1059 while (slot
!= NULL
)
1061 run_active_slot(slot
);
1062 slot
= active_queue_head
;
1068 /* Helpers for modifying and creating URLs */
1069 static inline int needs_quote(int ch
)
1071 if (((ch
>= 'A') && (ch
<= 'Z'))
1072 || ((ch
>= 'a') && (ch
<= 'z'))
1073 || ((ch
>= '0') && (ch
<= '9'))
1081 static char *quote_ref_url(const char *base
, const char *ref
)
1083 struct strbuf buf
= STRBUF_INIT
;
1087 end_url_with_slash(&buf
, base
);
1089 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1090 if (needs_quote(ch
))
1091 strbuf_addf(&buf
, "%%%02x", ch
);
1093 strbuf_addch(&buf
, *cp
);
1095 return strbuf_detach(&buf
, NULL
);
1098 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1100 int only_two_digit_prefix
)
1102 end_url_with_slash(buf
, url
);
1104 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1105 if (!only_two_digit_prefix
)
1106 strbuf_addf(buf
, "%s", hex
+2);
1109 char *get_remote_object_url(const char *url
, const char *hex
,
1110 int only_two_digit_prefix
)
1112 struct strbuf buf
= STRBUF_INIT
;
1113 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1114 return strbuf_detach(&buf
, NULL
);
1117 static int handle_curl_result(struct slot_results
*results
)
1120 * If we see a failing http code with CURLE_OK, we have turned off
1121 * FAILONERROR (to keep the server's custom error response), and should
1122 * translate the code into failure here.
1124 if (results
->curl_result
== CURLE_OK
&&
1125 results
->http_code
>= 400) {
1126 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
1128 * Normally curl will already have put the "reason phrase"
1129 * from the server into curl_errorstr; unfortunately without
1130 * FAILONERROR it is lost, so we can give only the numeric
1133 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1134 "The requested URL returned error: %ld",
1135 results
->http_code
);
1138 if (results
->curl_result
== CURLE_OK
) {
1139 credential_approve(&http_auth
);
1140 if (proxy_auth
.password
)
1141 credential_approve(&proxy_auth
);
1143 } else if (missing_target(results
))
1144 return HTTP_MISSING_TARGET
;
1145 else if (results
->http_code
== 401) {
1146 if (http_auth
.username
&& http_auth
.password
) {
1147 credential_reject(&http_auth
);
1150 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1151 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1156 if (results
->http_connectcode
== 407)
1157 credential_reject(&proxy_auth
);
1158 #if LIBCURL_VERSION_NUM >= 0x070c00
1159 if (!curl_errorstr
[0])
1160 strlcpy(curl_errorstr
,
1161 curl_easy_strerror(results
->curl_result
),
1162 sizeof(curl_errorstr
));
1168 int run_one_slot(struct active_request_slot
*slot
,
1169 struct slot_results
*results
)
1171 slot
->results
= results
;
1172 if (!start_active_slot(slot
)) {
1173 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1174 "failed to start HTTP request");
1175 return HTTP_START_FAILED
;
1178 run_active_slot(slot
);
1179 return handle_curl_result(results
);
1182 struct curl_slist
*http_copy_default_headers(void)
1184 struct curl_slist
*headers
= NULL
, *h
;
1186 for (h
= extra_http_headers
; h
; h
= h
->next
)
1187 headers
= curl_slist_append(headers
, h
->data
);
1192 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1198 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1200 strbuf_addstr(buf
, ptr
);
1205 * Check for and extract a content-type parameter. "raw"
1206 * should be positioned at the start of the potential
1207 * parameter, with any whitespace already removed.
1209 * "name" is the name of the parameter. The value is appended
1212 static int extract_param(const char *raw
, const char *name
,
1215 size_t len
= strlen(name
);
1217 if (strncasecmp(raw
, name
, len
))
1225 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1226 strbuf_addch(out
, *raw
++);
1231 * Extract a normalized version of the content type, with any
1232 * spaces suppressed, all letters lowercased, and no trailing ";"
1235 * Note that we will silently remove even invalid whitespace. For
1236 * example, "text / plain" is specifically forbidden by RFC 2616,
1237 * but "text/plain" is the only reasonable output, and this keeps
1240 * If the "charset" argument is not NULL, store the value of any
1241 * charset parameter there.
1244 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1245 * "text / plain" -> "text/plain"
1247 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1248 struct strbuf
*charset
)
1253 strbuf_grow(type
, raw
->len
);
1254 for (p
= raw
->buf
; *p
; p
++) {
1261 strbuf_addch(type
, tolower(*p
));
1267 strbuf_reset(charset
);
1269 while (isspace(*p
) || *p
== ';')
1271 if (!extract_param(p
, "charset", charset
))
1273 while (*p
&& !isspace(*p
))
1277 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1278 strbuf_addstr(charset
, "ISO-8859-1");
1281 static void write_accept_language(struct strbuf
*buf
)
1284 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1285 * that, q-value will be smaller than 0.001, the minimum q-value the
1286 * HTTP specification allows. See
1287 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1289 const int MAX_DECIMAL_PLACES
= 3;
1290 const int MAX_LANGUAGE_TAGS
= 1000;
1291 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1292 char **language_tags
= NULL
;
1294 const char *s
= get_preferred_languages();
1296 struct strbuf tag
= STRBUF_INIT
;
1298 /* Don't add Accept-Language header if no language is preferred. */
1303 * Split the colon-separated string of preferred languages into
1304 * language_tags array.
1307 /* collect language tag */
1308 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1309 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1311 /* skip .codeset, @modifier and any other unnecessary parts */
1312 while (*s
&& *s
!= ':')
1317 REALLOC_ARRAY(language_tags
, num_langs
);
1318 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1319 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1324 /* write Accept-Language header into buf */
1326 int last_buf_len
= 0;
1332 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1333 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1335 /* compute decimal_places */
1336 for (max_q
= 1, decimal_places
= 0;
1337 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1338 decimal_places
++, max_q
*= 10)
1341 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1343 strbuf_addstr(buf
, "Accept-Language: ");
1345 for (i
= 0; i
< num_langs
; i
++) {
1347 strbuf_addstr(buf
, ", ");
1349 strbuf_addstr(buf
, language_tags
[i
]);
1352 strbuf_addf(buf
, q_format
, max_q
- i
);
1354 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1355 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1359 last_buf_len
= buf
->len
;
1363 /* free language tags -- last one is a static '*' */
1364 for (i
= 0; i
< num_langs
- 1; i
++)
1365 free(language_tags
[i
]);
1366 free(language_tags
);
1370 * Get an Accept-Language header which indicates user's preferred languages.
1374 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1375 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1376 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1377 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1378 * LANGUAGE= LANG=C -> ""
1380 static const char *get_accept_language(void)
1382 if (!cached_accept_language
) {
1383 struct strbuf buf
= STRBUF_INIT
;
1384 write_accept_language(&buf
);
1386 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1389 return cached_accept_language
;
1392 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1395 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1396 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1399 /* http_request() targets */
1400 #define HTTP_REQUEST_STRBUF 0
1401 #define HTTP_REQUEST_FILE 1
1403 static int http_request(const char *url
,
1404 void *result
, int target
,
1405 const struct http_get_options
*options
)
1407 struct active_request_slot
*slot
;
1408 struct slot_results results
;
1409 struct curl_slist
*headers
= http_copy_default_headers();
1410 struct strbuf buf
= STRBUF_INIT
;
1411 const char *accept_language
;
1414 slot
= get_active_slot();
1415 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1417 if (result
== NULL
) {
1418 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1420 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1421 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1423 if (target
== HTTP_REQUEST_FILE
) {
1424 off_t posn
= ftello(result
);
1425 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1428 http_opt_request_remainder(slot
->curl
, posn
);
1430 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1434 accept_language
= get_accept_language();
1436 if (accept_language
)
1437 headers
= curl_slist_append(headers
, accept_language
);
1439 strbuf_addstr(&buf
, "Pragma:");
1440 if (options
&& options
->no_cache
)
1441 strbuf_addstr(&buf
, " no-cache");
1442 if (options
&& options
->keep_error
)
1443 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1445 headers
= curl_slist_append(headers
, buf
.buf
);
1447 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1448 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1449 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1451 ret
= run_one_slot(slot
, &results
);
1453 if (options
&& options
->content_type
) {
1454 struct strbuf raw
= STRBUF_INIT
;
1455 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1456 extract_content_type(&raw
, options
->content_type
,
1458 strbuf_release(&raw
);
1461 if (options
&& options
->effective_url
)
1462 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1463 options
->effective_url
);
1465 curl_slist_free_all(headers
);
1466 strbuf_release(&buf
);
1472 * Update the "base" url to a more appropriate value, as deduced by
1473 * redirects seen when requesting a URL starting with "url".
1475 * The "asked" parameter is a URL that we asked curl to access, and must begin
1478 * The "got" parameter is the URL that curl reported to us as where we ended
1481 * Returns 1 if we updated the base url, 0 otherwise.
1483 * Our basic strategy is to compare "base" and "asked" to find the bits
1484 * specific to our request. We then strip those bits off of "got" to yield the
1485 * new base. So for example, if our base is "http://example.com/foo.git",
1486 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1487 * with "https://other.example.com/foo.git/info/refs". We would want the
1488 * new URL to become "https://other.example.com/foo.git".
1490 * Note that this assumes a sane redirect scheme. It's entirely possible
1491 * in the example above to end up at a URL that does not even end in
1492 * "info/refs". In such a case we simply punt, as there is not much we can
1493 * do (and such a scheme is unlikely to represent a real git repository,
1494 * which means we are likely about to abort anyway).
1496 static int update_url_from_redirect(struct strbuf
*base
,
1498 const struct strbuf
*got
)
1503 if (!strcmp(asked
, got
->buf
))
1506 if (!skip_prefix(asked
, base
->buf
, &tail
))
1507 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1510 tail_len
= strlen(tail
);
1512 if (got
->len
< tail_len
||
1513 strcmp(tail
, got
->buf
+ got
->len
- tail_len
))
1514 return 0; /* insane redirect scheme */
1517 strbuf_add(base
, got
->buf
, got
->len
- tail_len
);
1521 static int http_request_reauth(const char *url
,
1522 void *result
, int target
,
1523 struct http_get_options
*options
)
1525 int ret
= http_request(url
, result
, target
, options
);
1527 if (options
&& options
->effective_url
&& options
->base_url
) {
1528 if (update_url_from_redirect(options
->base_url
,
1529 url
, options
->effective_url
)) {
1530 credential_from_url(&http_auth
, options
->base_url
->buf
);
1531 url
= options
->effective_url
->buf
;
1535 if (ret
!= HTTP_REAUTH
)
1539 * If we are using KEEP_ERROR, the previous request may have
1540 * put cruft into our output stream; we should clear it out before
1541 * making our next request. We only know how to do this for
1542 * the strbuf case, but that is enough to satisfy current callers.
1544 if (options
&& options
->keep_error
) {
1546 case HTTP_REQUEST_STRBUF
:
1547 strbuf_reset(result
);
1550 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1554 credential_fill(&http_auth
);
1556 return http_request(url
, result
, target
, options
);
1559 int http_get_strbuf(const char *url
,
1560 struct strbuf
*result
,
1561 struct http_get_options
*options
)
1563 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1567 * Downloads a URL and stores the result in the given file.
1569 * If a previous interrupted download is detected (i.e. a previous temporary
1570 * file is still around) the download is resumed.
1572 static int http_get_file(const char *url
, const char *filename
,
1573 struct http_get_options
*options
)
1576 struct strbuf tmpfile
= STRBUF_INIT
;
1579 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1580 result
= fopen(tmpfile
.buf
, "a");
1582 error("Unable to open local file %s", tmpfile
.buf
);
1587 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1590 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1593 strbuf_release(&tmpfile
);
1597 int http_fetch_ref(const char *base
, struct ref
*ref
)
1599 struct http_get_options options
= {0};
1601 struct strbuf buffer
= STRBUF_INIT
;
1604 options
.no_cache
= 1;
1606 url
= quote_ref_url(base
, ref
->name
);
1607 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1608 strbuf_rtrim(&buffer
);
1609 if (buffer
.len
== 40)
1610 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
1611 else if (starts_with(buffer
.buf
, "ref: ")) {
1612 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1617 strbuf_release(&buffer
);
1622 /* Helpers for fetching packs */
1623 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1626 struct strbuf buf
= STRBUF_INIT
;
1628 if (http_is_verbose
)
1629 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1631 end_url_with_slash(&buf
, base_url
);
1632 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1633 url
= strbuf_detach(&buf
, NULL
);
1635 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1636 tmp
= strbuf_detach(&buf
, NULL
);
1638 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1639 error("Unable to get pack index %s", url
);
1648 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1649 unsigned char *sha1
, const char *base_url
)
1651 struct packed_git
*new_pack
;
1652 char *tmp_idx
= NULL
;
1655 if (has_pack_index(sha1
)) {
1656 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1658 return -1; /* parse_pack_index() already issued error message */
1662 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1666 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1671 return -1; /* parse_pack_index() already issued error message */
1674 ret
= verify_pack_index(new_pack
);
1676 close_pack_index(new_pack
);
1677 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1684 new_pack
->next
= *packs_head
;
1685 *packs_head
= new_pack
;
1689 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1691 struct http_get_options options
= {0};
1694 struct strbuf buf
= STRBUF_INIT
;
1695 unsigned char sha1
[20];
1697 end_url_with_slash(&buf
, base_url
);
1698 strbuf_addstr(&buf
, "objects/info/packs");
1699 url
= strbuf_detach(&buf
, NULL
);
1701 options
.no_cache
= 1;
1702 ret
= http_get_strbuf(url
, &buf
, &options
);
1707 while (i
< buf
.len
) {
1711 if (i
+ 52 <= buf
.len
&&
1712 starts_with(data
+ i
, " pack-") &&
1713 starts_with(data
+ i
+ 46, ".pack\n")) {
1714 get_sha1_hex(data
+ i
+ 6, sha1
);
1715 fetch_and_setup_pack_index(packs_head
, sha1
,
1721 while (i
< buf
.len
&& data
[i
] != '\n')
1732 void release_http_pack_request(struct http_pack_request
*preq
)
1734 if (preq
->packfile
!= NULL
) {
1735 fclose(preq
->packfile
);
1736 preq
->packfile
= NULL
;
1743 int finish_http_pack_request(struct http_pack_request
*preq
)
1745 struct packed_git
**lst
;
1746 struct packed_git
*p
= preq
->target
;
1749 struct child_process ip
= CHILD_PROCESS_INIT
;
1750 const char *ip_argv
[8];
1752 close_pack_index(p
);
1754 fclose(preq
->packfile
);
1755 preq
->packfile
= NULL
;
1759 lst
= &((*lst
)->next
);
1760 *lst
= (*lst
)->next
;
1762 if (!strip_suffix(preq
->tmpfile
, ".pack.temp", &len
))
1763 die("BUG: pack tmpfile does not end in .pack.temp?");
1764 tmp_idx
= xstrfmt("%.*s.idx.temp", (int)len
, preq
->tmpfile
);
1766 ip_argv
[0] = "index-pack";
1768 ip_argv
[2] = tmp_idx
;
1769 ip_argv
[3] = preq
->tmpfile
;
1777 if (run_command(&ip
)) {
1778 unlink(preq
->tmpfile
);
1784 unlink(sha1_pack_index_name(p
->sha1
));
1786 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1787 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1792 install_packed_git(p
);
1797 struct http_pack_request
*new_http_pack_request(
1798 struct packed_git
*target
, const char *base_url
)
1800 off_t prev_posn
= 0;
1801 struct strbuf buf
= STRBUF_INIT
;
1802 struct http_pack_request
*preq
;
1804 preq
= xcalloc(1, sizeof(*preq
));
1805 preq
->target
= target
;
1807 end_url_with_slash(&buf
, base_url
);
1808 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1809 sha1_to_hex(target
->sha1
));
1810 preq
->url
= strbuf_detach(&buf
, NULL
);
1812 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1813 sha1_pack_name(target
->sha1
));
1814 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1815 if (!preq
->packfile
) {
1816 error("Unable to open local file %s for pack",
1821 preq
->slot
= get_active_slot();
1822 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1823 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1824 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1825 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1829 * If there is data present from a previous transfer attempt,
1830 * resume where it left off
1832 prev_posn
= ftello(preq
->packfile
);
1834 if (http_is_verbose
)
1836 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
1837 sha1_to_hex(target
->sha1
), (uintmax_t)prev_posn
);
1838 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
1849 /* Helpers for fetching objects (loose) */
1850 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
1853 unsigned char expn
[4096];
1854 size_t size
= eltsize
* nmemb
;
1856 struct http_object_request
*freq
=
1857 (struct http_object_request
*)data
;
1859 ssize_t retval
= xwrite(freq
->localfile
,
1860 (char *) ptr
+ posn
, size
- posn
);
1864 } while (posn
< size
);
1866 freq
->stream
.avail_in
= size
;
1867 freq
->stream
.next_in
= (void *)ptr
;
1869 freq
->stream
.next_out
= expn
;
1870 freq
->stream
.avail_out
= sizeof(expn
);
1871 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
1872 git_SHA1_Update(&freq
->c
, expn
,
1873 sizeof(expn
) - freq
->stream
.avail_out
);
1874 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
1878 struct http_object_request
*new_http_object_request(const char *base_url
,
1879 unsigned char *sha1
)
1881 char *hex
= sha1_to_hex(sha1
);
1882 const char *filename
;
1883 char prevfile
[PATH_MAX
];
1885 char prev_buf
[PREV_BUF_SIZE
];
1886 ssize_t prev_read
= 0;
1887 off_t prev_posn
= 0;
1888 struct http_object_request
*freq
;
1890 freq
= xcalloc(1, sizeof(*freq
));
1891 hashcpy(freq
->sha1
, sha1
);
1892 freq
->localfile
= -1;
1894 filename
= sha1_file_name(sha1
);
1895 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
1896 "%s.temp", filename
);
1898 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
1899 unlink_or_warn(prevfile
);
1900 rename(freq
->tmpfile
, prevfile
);
1901 unlink_or_warn(freq
->tmpfile
);
1903 if (freq
->localfile
!= -1)
1904 error("fd leakage in start: %d", freq
->localfile
);
1905 freq
->localfile
= open(freq
->tmpfile
,
1906 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1908 * This could have failed due to the "lazy directory creation";
1909 * try to mkdir the last path component.
1911 if (freq
->localfile
< 0 && errno
== ENOENT
) {
1912 char *dir
= strrchr(freq
->tmpfile
, '/');
1915 mkdir(freq
->tmpfile
, 0777);
1918 freq
->localfile
= open(freq
->tmpfile
,
1919 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1922 if (freq
->localfile
< 0) {
1923 error("Couldn't create temporary file %s: %s",
1924 freq
->tmpfile
, strerror(errno
));
1928 git_inflate_init(&freq
->stream
);
1930 git_SHA1_Init(&freq
->c
);
1932 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
1935 * If a previous temp file is present, process what was already
1938 prevlocal
= open(prevfile
, O_RDONLY
);
1939 if (prevlocal
!= -1) {
1941 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
1943 if (fwrite_sha1_file(prev_buf
,
1946 freq
) == prev_read
) {
1947 prev_posn
+= prev_read
;
1952 } while (prev_read
> 0);
1955 unlink_or_warn(prevfile
);
1958 * Reset inflate/SHA1 if there was an error reading the previous temp
1959 * file; also rewind to the beginning of the local file.
1961 if (prev_read
== -1) {
1962 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
1963 git_inflate_init(&freq
->stream
);
1964 git_SHA1_Init(&freq
->c
);
1967 lseek(freq
->localfile
, 0, SEEK_SET
);
1968 if (ftruncate(freq
->localfile
, 0) < 0) {
1969 error("Couldn't truncate temporary file %s: %s",
1970 freq
->tmpfile
, strerror(errno
));
1976 freq
->slot
= get_active_slot();
1978 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
1979 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
1980 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
1981 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
1982 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
1985 * If we have successfully processed data from a previous fetch
1986 * attempt, only fetch the data we don't already have.
1989 if (http_is_verbose
)
1991 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
1992 hex
, (uintmax_t)prev_posn
);
1993 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2004 void process_http_object_request(struct http_object_request
*freq
)
2006 if (freq
->slot
== NULL
)
2008 freq
->curl_result
= freq
->slot
->curl_result
;
2009 freq
->http_code
= freq
->slot
->http_code
;
2013 int finish_http_object_request(struct http_object_request
*freq
)
2017 close(freq
->localfile
);
2018 freq
->localfile
= -1;
2020 process_http_object_request(freq
);
2022 if (freq
->http_code
== 416) {
2023 warning("requested range invalid; we may already have all the data.");
2024 } else if (freq
->curl_result
!= CURLE_OK
) {
2025 if (stat(freq
->tmpfile
, &st
) == 0)
2026 if (st
.st_size
== 0)
2027 unlink_or_warn(freq
->tmpfile
);
2031 git_inflate_end(&freq
->stream
);
2032 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
2033 if (freq
->zret
!= Z_STREAM_END
) {
2034 unlink_or_warn(freq
->tmpfile
);
2037 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
2038 unlink_or_warn(freq
->tmpfile
);
2042 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
2044 return freq
->rename
;
2047 void abort_http_object_request(struct http_object_request
*freq
)
2049 unlink_or_warn(freq
->tmpfile
);
2051 release_http_object_request(freq
);
2054 void release_http_object_request(struct http_object_request
*freq
)
2056 if (freq
->localfile
!= -1) {
2057 close(freq
->localfile
);
2058 freq
->localfile
= -1;
2060 if (freq
->url
!= NULL
) {
2064 if (freq
->slot
!= NULL
) {
2065 freq
->slot
->callback_func
= NULL
;
2066 freq
->slot
->callback_data
= NULL
;
2067 release_active_slot(freq
->slot
);