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 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
103 #if LIBCURL_VERSION_NUM >= 0x071700
104 /* Use CURLOPT_KEYPASSWD as is */
105 #elif LIBCURL_VERSION_NUM >= 0x070903
106 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
108 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
111 static struct credential cert_auth
= CREDENTIAL_INIT
;
112 static int ssl_cert_password_required
;
113 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
114 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
117 static struct curl_slist
*pragma_header
;
118 static struct curl_slist
*no_pragma_header
;
119 static struct curl_slist
*extra_http_headers
;
121 static struct active_request_slot
*active_queue_head
;
123 static char *cached_accept_language
;
125 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
127 size_t size
= eltsize
* nmemb
;
128 struct buffer
*buffer
= buffer_
;
130 if (size
> buffer
->buf
.len
- buffer
->posn
)
131 size
= buffer
->buf
.len
- buffer
->posn
;
132 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
133 buffer
->posn
+= size
;
138 #ifndef NO_CURL_IOCTL
139 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
141 struct buffer
*buffer
= clientp
;
147 case CURLIOCMD_RESTARTREAD
:
152 return CURLIOE_UNKNOWNCMD
;
157 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
159 size_t size
= eltsize
* nmemb
;
160 struct strbuf
*buffer
= buffer_
;
162 strbuf_add(buffer
, ptr
, size
);
166 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
168 return eltsize
* nmemb
;
171 static void closedown_active_slot(struct active_request_slot
*slot
)
177 static void finish_active_slot(struct active_request_slot
*slot
)
179 closedown_active_slot(slot
);
180 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
182 if (slot
->finished
!= NULL
)
183 (*slot
->finished
) = 1;
185 /* Store slot results so they can be read after the slot is reused */
186 if (slot
->results
!= NULL
) {
187 slot
->results
->curl_result
= slot
->curl_result
;
188 slot
->results
->http_code
= slot
->http_code
;
189 #if LIBCURL_VERSION_NUM >= 0x070a08
190 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
191 &slot
->results
->auth_avail
);
193 slot
->results
->auth_avail
= 0;
196 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
197 &slot
->results
->http_connectcode
);
200 /* Run callback if appropriate */
201 if (slot
->callback_func
!= NULL
)
202 slot
->callback_func(slot
->callback_data
);
205 #ifdef USE_CURL_MULTI
206 static void process_curl_messages(void)
209 struct active_request_slot
*slot
;
210 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
212 while (curl_message
!= NULL
) {
213 if (curl_message
->msg
== CURLMSG_DONE
) {
214 int curl_result
= curl_message
->data
.result
;
215 slot
= active_queue_head
;
216 while (slot
!= NULL
&&
217 slot
->curl
!= curl_message
->easy_handle
)
220 curl_multi_remove_handle(curlm
, slot
->curl
);
221 slot
->curl_result
= curl_result
;
222 finish_active_slot(slot
);
224 fprintf(stderr
, "Received DONE message for unknown request!\n");
227 fprintf(stderr
, "Unknown CURL message received: %d\n",
228 (int)curl_message
->msg
);
230 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
235 static int http_options(const char *var
, const char *value
, void *cb
)
237 if (!strcmp("http.sslverify", var
)) {
238 curl_ssl_verify
= git_config_bool(var
, value
);
241 if (!strcmp("http.sslcipherlist", var
))
242 return git_config_string(&ssl_cipherlist
, var
, value
);
243 if (!strcmp("http.sslversion", var
))
244 return git_config_string(&ssl_version
, var
, value
);
245 if (!strcmp("http.sslcert", var
))
246 return git_config_string(&ssl_cert
, var
, value
);
247 #if LIBCURL_VERSION_NUM >= 0x070903
248 if (!strcmp("http.sslkey", var
))
249 return git_config_string(&ssl_key
, var
, value
);
251 #if LIBCURL_VERSION_NUM >= 0x070908
252 if (!strcmp("http.sslcapath", var
))
253 return git_config_pathname(&ssl_capath
, var
, value
);
255 if (!strcmp("http.sslcainfo", var
))
256 return git_config_pathname(&ssl_cainfo
, var
, value
);
257 if (!strcmp("http.sslcertpasswordprotected", var
)) {
258 ssl_cert_password_required
= git_config_bool(var
, value
);
261 if (!strcmp("http.ssltry", var
)) {
262 curl_ssl_try
= git_config_bool(var
, value
);
265 if (!strcmp("http.minsessions", var
)) {
266 min_curl_sessions
= git_config_int(var
, value
);
267 #ifndef USE_CURL_MULTI
268 if (min_curl_sessions
> 1)
269 min_curl_sessions
= 1;
273 #ifdef USE_CURL_MULTI
274 if (!strcmp("http.maxrequests", var
)) {
275 max_requests
= git_config_int(var
, value
);
279 if (!strcmp("http.lowspeedlimit", var
)) {
280 curl_low_speed_limit
= (long)git_config_int(var
, value
);
283 if (!strcmp("http.lowspeedtime", var
)) {
284 curl_low_speed_time
= (long)git_config_int(var
, value
);
288 if (!strcmp("http.noepsv", var
)) {
289 curl_ftp_no_epsv
= git_config_bool(var
, value
);
292 if (!strcmp("http.proxy", var
))
293 return git_config_string(&curl_http_proxy
, var
, value
);
295 if (!strcmp("http.proxyauthmethod", var
))
296 return git_config_string(&http_proxy_authmethod
, var
, value
);
298 if (!strcmp("http.cookiefile", var
))
299 return git_config_pathname(&curl_cookie_file
, var
, value
);
300 if (!strcmp("http.savecookies", var
)) {
301 curl_save_cookies
= git_config_bool(var
, value
);
305 if (!strcmp("http.postbuffer", var
)) {
306 http_post_buffer
= git_config_int(var
, value
);
307 if (http_post_buffer
< LARGE_PACKET_MAX
)
308 http_post_buffer
= LARGE_PACKET_MAX
;
312 if (!strcmp("http.useragent", var
))
313 return git_config_string(&user_agent
, var
, value
);
315 if (!strcmp("http.emptyauth", var
)) {
316 curl_empty_auth
= git_config_bool(var
, value
);
320 if (!strcmp("http.pinnedpubkey", var
)) {
321 #if LIBCURL_VERSION_NUM >= 0x072c00
322 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
324 warning(_("Public key pinning not supported with cURL < 7.44.0"));
329 if (!strcmp("http.extraheader", var
)) {
331 return config_error_nonbool(var
);
332 } else if (!*value
) {
333 curl_slist_free_all(extra_http_headers
);
334 extra_http_headers
= NULL
;
337 curl_slist_append(extra_http_headers
, value
);
342 if (!strcmp("http.followredirects", var
)) {
343 if (value
&& !strcmp(value
, "initial"))
344 http_follow_config
= HTTP_FOLLOW_INITIAL
;
345 else if (git_config_bool(var
, value
))
346 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
348 http_follow_config
= HTTP_FOLLOW_NONE
;
352 /* Fall back on the default ones */
353 return git_default_config(var
, value
, cb
);
356 static void init_curl_http_auth(CURL
*result
)
358 if (!http_auth
.username
) {
360 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
364 credential_fill(&http_auth
);
366 #if LIBCURL_VERSION_NUM >= 0x071301
367 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
368 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
371 static struct strbuf up
= STRBUF_INIT
;
373 * Note that we assume we only ever have a single set of
374 * credentials in a given program run, so we do not have
375 * to worry about updating this buffer, only setting its
379 strbuf_addf(&up
, "%s:%s",
380 http_auth
.username
, http_auth
.password
);
381 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
386 /* *var must be free-able */
387 static void var_override(const char **var
, char *value
)
391 *var
= xstrdup(value
);
395 static void set_proxyauth_name_password(CURL
*result
)
397 #if LIBCURL_VERSION_NUM >= 0x071301
398 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
399 proxy_auth
.username
);
400 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
401 proxy_auth
.password
);
403 struct strbuf s
= STRBUF_INIT
;
405 strbuf_addstr_urlencode(&s
, proxy_auth
.username
, 1);
406 strbuf_addch(&s
, ':');
407 strbuf_addstr_urlencode(&s
, proxy_auth
.password
, 1);
408 curl_proxyuserpwd
= strbuf_detach(&s
, NULL
);
409 curl_easy_setopt(result
, CURLOPT_PROXYUSERPWD
, curl_proxyuserpwd
);
413 static void init_curl_proxy_auth(CURL
*result
)
415 if (proxy_auth
.username
) {
416 if (!proxy_auth
.password
)
417 credential_fill(&proxy_auth
);
418 set_proxyauth_name_password(result
);
421 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
423 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
424 if (http_proxy_authmethod
) {
426 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
427 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
428 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
429 proxy_authmethods
[i
].curlauth_param
);
433 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
434 warning("unsupported proxy authentication method %s: using anyauth",
435 http_proxy_authmethod
);
436 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
440 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
444 static int has_cert_password(void)
446 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
448 if (!cert_auth
.password
) {
449 cert_auth
.protocol
= xstrdup("cert");
450 cert_auth
.username
= xstrdup("");
451 cert_auth
.path
= xstrdup(ssl_cert
);
452 credential_fill(&cert_auth
);
457 #if LIBCURL_VERSION_NUM >= 0x071900
458 static void set_curl_keepalive(CURL
*c
)
460 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
463 #elif LIBCURL_VERSION_NUM >= 0x071000
464 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
468 socklen_t len
= (socklen_t
)sizeof(ka
);
470 if (type
!= CURLSOCKTYPE_IPCXN
)
473 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
475 warning_errno("unable to set SO_KEEPALIVE on socket");
477 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
480 static void set_curl_keepalive(CURL
*c
)
482 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
486 static void set_curl_keepalive(CURL
*c
)
488 /* not supported on older curl versions */
492 static CURL
*get_curl_handle(void)
494 CURL
*result
= curl_easy_init();
495 long allowed_protocols
= 0;
498 die("curl_easy_init failed");
500 if (!curl_ssl_verify
) {
501 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
502 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
504 /* Verify authenticity of the peer's certificate */
505 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
506 /* The name in the cert must match whom we tried to connect */
507 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
510 #if LIBCURL_VERSION_NUM >= 0x070907
511 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
513 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
514 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
517 if (http_proactive_auth
)
518 init_curl_http_auth(result
);
520 if (getenv("GIT_SSL_VERSION"))
521 ssl_version
= getenv("GIT_SSL_VERSION");
522 if (ssl_version
&& *ssl_version
) {
524 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
525 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
526 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
527 sslversions
[i
].ssl_version
);
531 if (i
== ARRAY_SIZE(sslversions
))
532 warning("unsupported ssl version %s: using default",
536 if (getenv("GIT_SSL_CIPHER_LIST"))
537 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
538 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
539 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
542 if (ssl_cert
!= NULL
)
543 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
544 if (has_cert_password())
545 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
546 #if LIBCURL_VERSION_NUM >= 0x070903
548 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
550 #if LIBCURL_VERSION_NUM >= 0x070908
551 if (ssl_capath
!= NULL
)
552 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
554 #if LIBCURL_VERSION_NUM >= 0x072c00
555 if (ssl_pinnedkey
!= NULL
)
556 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
558 if (ssl_cainfo
!= NULL
)
559 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
561 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
562 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
563 curl_low_speed_limit
);
564 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
565 curl_low_speed_time
);
568 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
569 #if LIBCURL_VERSION_NUM >= 0x071301
570 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
571 #elif LIBCURL_VERSION_NUM >= 0x071101
572 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
574 #if LIBCURL_VERSION_NUM >= 0x071304
575 if (is_transport_allowed("http"))
576 allowed_protocols
|= CURLPROTO_HTTP
;
577 if (is_transport_allowed("https"))
578 allowed_protocols
|= CURLPROTO_HTTPS
;
579 if (is_transport_allowed("ftp"))
580 allowed_protocols
|= CURLPROTO_FTP
;
581 if (is_transport_allowed("ftps"))
582 allowed_protocols
|= CURLPROTO_FTPS
;
583 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
584 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
, allowed_protocols
);
586 if (transport_restrict_protocols())
587 warning("protocol restrictions not applied to curl redirects because\n"
588 "your curl version is too old (>= 7.19.4)");
591 if (getenv("GIT_CURL_VERBOSE"))
592 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1);
594 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
595 user_agent
? user_agent
: git_user_agent());
597 if (curl_ftp_no_epsv
)
598 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
600 #ifdef CURLOPT_USE_SSL
602 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
606 * CURL also examines these variables as a fallback; but we need to query
607 * them here in order to decide whether to prompt for missing password (cf.
608 * init_curl_proxy_auth()).
610 * Unlike many other common environment variables, these are historically
611 * lowercase only. It appears that CURL did not know this and implemented
612 * only uppercase variants, which was later corrected to take both - with
613 * the exception of http_proxy, which is lowercase only also in CURL. As
614 * the lowercase versions are the historical quasi-standard, they take
615 * precedence here, as in CURL.
617 if (!curl_http_proxy
) {
618 if (!strcmp(http_auth
.protocol
, "https")) {
619 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
620 var_override(&curl_http_proxy
, getenv("https_proxy"));
622 var_override(&curl_http_proxy
, getenv("http_proxy"));
624 if (!curl_http_proxy
) {
625 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
626 var_override(&curl_http_proxy
, getenv("all_proxy"));
630 if (curl_http_proxy
) {
631 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
632 #if LIBCURL_VERSION_NUM >= 0x071800
633 if (starts_with(curl_http_proxy
, "socks5h"))
634 curl_easy_setopt(result
,
635 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
636 else if (starts_with(curl_http_proxy
, "socks5"))
637 curl_easy_setopt(result
,
638 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
639 else if (starts_with(curl_http_proxy
, "socks4a"))
640 curl_easy_setopt(result
,
641 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
642 else if (starts_with(curl_http_proxy
, "socks"))
643 curl_easy_setopt(result
,
644 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
646 if (strstr(curl_http_proxy
, "://"))
647 credential_from_url(&proxy_auth
, curl_http_proxy
);
649 struct strbuf url
= STRBUF_INIT
;
650 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
651 credential_from_url(&proxy_auth
, url
.buf
);
652 strbuf_release(&url
);
655 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
656 #if LIBCURL_VERSION_NUM >= 0x071304
657 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
658 var_override(&curl_no_proxy
, getenv("no_proxy"));
659 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
662 init_curl_proxy_auth(result
);
664 set_curl_keepalive(result
);
669 static void set_from_env(const char **var
, const char *envname
)
671 const char *val
= getenv(envname
);
676 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
678 char *low_speed_limit
;
679 char *low_speed_time
;
680 char *normalized_url
;
681 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
683 config
.section
= "http";
685 config
.collect_fn
= http_options
;
686 config
.cascade_fn
= git_default_config
;
690 normalized_url
= url_normalize(url
, &config
.url
);
692 git_config(urlmatch_config_entry
, &config
);
693 free(normalized_url
);
695 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
696 die("curl_global_init failed");
698 http_proactive_auth
= proactive_auth
;
700 if (remote
&& remote
->http_proxy
)
701 curl_http_proxy
= xstrdup(remote
->http_proxy
);
704 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
706 pragma_header
= curl_slist_append(http_copy_default_headers(),
708 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
711 #ifdef USE_CURL_MULTI
713 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
714 if (http_max_requests
!= NULL
)
715 max_requests
= atoi(http_max_requests
);
718 curlm
= curl_multi_init();
720 die("curl_multi_init failed");
723 if (getenv("GIT_SSL_NO_VERIFY"))
726 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
727 #if LIBCURL_VERSION_NUM >= 0x070903
728 set_from_env(&ssl_key
, "GIT_SSL_KEY");
730 #if LIBCURL_VERSION_NUM >= 0x070908
731 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
733 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
735 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
737 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
738 if (low_speed_limit
!= NULL
)
739 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
740 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
741 if (low_speed_time
!= NULL
)
742 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
744 if (curl_ssl_verify
== -1)
747 curl_session_count
= 0;
748 #ifdef USE_CURL_MULTI
749 if (max_requests
< 1)
750 max_requests
= DEFAULT_MAX_REQUESTS
;
753 if (getenv("GIT_CURL_FTP_NO_EPSV"))
754 curl_ftp_no_epsv
= 1;
757 credential_from_url(&http_auth
, url
);
758 if (!ssl_cert_password_required
&&
759 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
760 starts_with(url
, "https://"))
761 ssl_cert_password_required
= 1;
764 #ifndef NO_CURL_EASY_DUPHANDLE
765 curl_default
= get_curl_handle();
769 void http_cleanup(void)
771 struct active_request_slot
*slot
= active_queue_head
;
773 while (slot
!= NULL
) {
774 struct active_request_slot
*next
= slot
->next
;
775 if (slot
->curl
!= NULL
) {
776 #ifdef USE_CURL_MULTI
777 curl_multi_remove_handle(curlm
, slot
->curl
);
779 curl_easy_cleanup(slot
->curl
);
784 active_queue_head
= NULL
;
786 #ifndef NO_CURL_EASY_DUPHANDLE
787 curl_easy_cleanup(curl_default
);
790 #ifdef USE_CURL_MULTI
791 curl_multi_cleanup(curlm
);
793 curl_global_cleanup();
795 curl_slist_free_all(extra_http_headers
);
796 extra_http_headers
= NULL
;
798 curl_slist_free_all(pragma_header
);
799 pragma_header
= NULL
;
801 curl_slist_free_all(no_pragma_header
);
802 no_pragma_header
= NULL
;
804 if (curl_http_proxy
) {
805 free((void *)curl_http_proxy
);
806 curl_http_proxy
= NULL
;
809 if (proxy_auth
.password
) {
810 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
811 free(proxy_auth
.password
);
812 proxy_auth
.password
= NULL
;
815 free((void *)curl_proxyuserpwd
);
816 curl_proxyuserpwd
= NULL
;
818 free((void *)http_proxy_authmethod
);
819 http_proxy_authmethod
= NULL
;
821 if (cert_auth
.password
!= NULL
) {
822 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
823 free(cert_auth
.password
);
824 cert_auth
.password
= NULL
;
826 ssl_cert_password_required
= 0;
828 free(cached_accept_language
);
829 cached_accept_language
= NULL
;
832 struct active_request_slot
*get_active_slot(void)
834 struct active_request_slot
*slot
= active_queue_head
;
835 struct active_request_slot
*newslot
;
837 #ifdef USE_CURL_MULTI
840 /* Wait for a slot to open up if the queue is full */
841 while (active_requests
>= max_requests
) {
842 curl_multi_perform(curlm
, &num_transfers
);
843 if (num_transfers
< active_requests
)
844 process_curl_messages();
848 while (slot
!= NULL
&& slot
->in_use
)
852 newslot
= xmalloc(sizeof(*newslot
));
853 newslot
->curl
= NULL
;
855 newslot
->next
= NULL
;
857 slot
= active_queue_head
;
859 active_queue_head
= newslot
;
861 while (slot
->next
!= NULL
)
863 slot
->next
= newslot
;
868 if (slot
->curl
== NULL
) {
869 #ifdef NO_CURL_EASY_DUPHANDLE
870 slot
->curl
= get_curl_handle();
872 slot
->curl
= curl_easy_duphandle(curl_default
);
874 curl_session_count
++;
879 slot
->results
= NULL
;
880 slot
->finished
= NULL
;
881 slot
->callback_data
= NULL
;
882 slot
->callback_func
= NULL
;
883 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
884 if (curl_save_cookies
)
885 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
886 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
887 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
888 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
889 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
890 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
891 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
892 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
893 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
894 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
895 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
898 * Default following to off unless "ALWAYS" is configured; this gives
899 * callers a sane starting point, and they can tweak for individual
900 * HTTP_FOLLOW_* cases themselves.
902 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
903 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
905 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
907 #if LIBCURL_VERSION_NUM >= 0x070a08
908 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
910 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
911 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
913 if (http_auth
.password
|| curl_empty_auth
)
914 init_curl_http_auth(slot
->curl
);
919 int start_active_slot(struct active_request_slot
*slot
)
921 #ifdef USE_CURL_MULTI
922 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
925 if (curlm_result
!= CURLM_OK
&&
926 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
933 * We know there must be something to do, since we just added
936 curl_multi_perform(curlm
, &num_transfers
);
941 #ifdef USE_CURL_MULTI
945 struct fill_chain
*next
;
948 static struct fill_chain
*fill_cfg
;
950 void add_fill_function(void *data
, int (*fill
)(void *))
952 struct fill_chain
*new = xmalloc(sizeof(*new));
953 struct fill_chain
**linkp
= &fill_cfg
;
958 linkp
= &(*linkp
)->next
;
962 void fill_active_slots(void)
964 struct active_request_slot
*slot
= active_queue_head
;
966 while (active_requests
< max_requests
) {
967 struct fill_chain
*fill
;
968 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
969 if (fill
->fill(fill
->data
))
976 while (slot
!= NULL
) {
977 if (!slot
->in_use
&& slot
->curl
!= NULL
978 && curl_session_count
> min_curl_sessions
) {
979 curl_easy_cleanup(slot
->curl
);
981 curl_session_count
--;
987 void step_active_slots(void)
990 CURLMcode curlm_result
;
993 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
994 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
995 if (num_transfers
< active_requests
) {
996 process_curl_messages();
1002 void run_active_slot(struct active_request_slot
*slot
)
1004 #ifdef USE_CURL_MULTI
1009 struct timeval select_timeout
;
1012 slot
->finished
= &finished
;
1014 step_active_slots();
1017 #if LIBCURL_VERSION_NUM >= 0x070f04
1019 curl_multi_timeout(curlm
, &curl_timeout
);
1020 if (curl_timeout
== 0) {
1022 } else if (curl_timeout
== -1) {
1023 select_timeout
.tv_sec
= 0;
1024 select_timeout
.tv_usec
= 50000;
1026 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1027 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1030 select_timeout
.tv_sec
= 0;
1031 select_timeout
.tv_usec
= 50000;
1038 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1041 * It can happen that curl_multi_timeout returns a pathologically
1042 * long timeout when curl_multi_fdset returns no file descriptors
1043 * to read. See commit message for more details.
1046 (select_timeout
.tv_sec
> 0 ||
1047 select_timeout
.tv_usec
> 50000)) {
1048 select_timeout
.tv_sec
= 0;
1049 select_timeout
.tv_usec
= 50000;
1052 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1056 while (slot
->in_use
) {
1057 slot
->curl_result
= curl_easy_perform(slot
->curl
);
1058 finish_active_slot(slot
);
1063 static void release_active_slot(struct active_request_slot
*slot
)
1065 closedown_active_slot(slot
);
1066 if (slot
->curl
&& curl_session_count
> min_curl_sessions
) {
1067 #ifdef USE_CURL_MULTI
1068 curl_multi_remove_handle(curlm
, slot
->curl
);
1070 curl_easy_cleanup(slot
->curl
);
1072 curl_session_count
--;
1074 #ifdef USE_CURL_MULTI
1075 fill_active_slots();
1079 void finish_all_active_slots(void)
1081 struct active_request_slot
*slot
= active_queue_head
;
1083 while (slot
!= NULL
)
1085 run_active_slot(slot
);
1086 slot
= active_queue_head
;
1092 /* Helpers for modifying and creating URLs */
1093 static inline int needs_quote(int ch
)
1095 if (((ch
>= 'A') && (ch
<= 'Z'))
1096 || ((ch
>= 'a') && (ch
<= 'z'))
1097 || ((ch
>= '0') && (ch
<= '9'))
1105 static char *quote_ref_url(const char *base
, const char *ref
)
1107 struct strbuf buf
= STRBUF_INIT
;
1111 end_url_with_slash(&buf
, base
);
1113 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1114 if (needs_quote(ch
))
1115 strbuf_addf(&buf
, "%%%02x", ch
);
1117 strbuf_addch(&buf
, *cp
);
1119 return strbuf_detach(&buf
, NULL
);
1122 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1124 int only_two_digit_prefix
)
1126 end_url_with_slash(buf
, url
);
1128 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1129 if (!only_two_digit_prefix
)
1130 strbuf_addstr(buf
, hex
+ 2);
1133 char *get_remote_object_url(const char *url
, const char *hex
,
1134 int only_two_digit_prefix
)
1136 struct strbuf buf
= STRBUF_INIT
;
1137 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1138 return strbuf_detach(&buf
, NULL
);
1141 static int handle_curl_result(struct slot_results
*results
)
1144 * If we see a failing http code with CURLE_OK, we have turned off
1145 * FAILONERROR (to keep the server's custom error response), and should
1146 * translate the code into failure here.
1148 * Likewise, if we see a redirect (30x code), that means we turned off
1149 * redirect-following, and we should treat the result as an error.
1151 if (results
->curl_result
== CURLE_OK
&&
1152 results
->http_code
>= 300) {
1153 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
1155 * Normally curl will already have put the "reason phrase"
1156 * from the server into curl_errorstr; unfortunately without
1157 * FAILONERROR it is lost, so we can give only the numeric
1160 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1161 "The requested URL returned error: %ld",
1162 results
->http_code
);
1165 if (results
->curl_result
== CURLE_OK
) {
1166 credential_approve(&http_auth
);
1167 if (proxy_auth
.password
)
1168 credential_approve(&proxy_auth
);
1170 } else if (missing_target(results
))
1171 return HTTP_MISSING_TARGET
;
1172 else if (results
->http_code
== 401) {
1173 if (http_auth
.username
&& http_auth
.password
) {
1174 credential_reject(&http_auth
);
1177 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1178 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1183 if (results
->http_connectcode
== 407)
1184 credential_reject(&proxy_auth
);
1185 #if LIBCURL_VERSION_NUM >= 0x070c00
1186 if (!curl_errorstr
[0])
1187 strlcpy(curl_errorstr
,
1188 curl_easy_strerror(results
->curl_result
),
1189 sizeof(curl_errorstr
));
1195 int run_one_slot(struct active_request_slot
*slot
,
1196 struct slot_results
*results
)
1198 slot
->results
= results
;
1199 if (!start_active_slot(slot
)) {
1200 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1201 "failed to start HTTP request");
1202 return HTTP_START_FAILED
;
1205 run_active_slot(slot
);
1206 return handle_curl_result(results
);
1209 struct curl_slist
*http_copy_default_headers(void)
1211 struct curl_slist
*headers
= NULL
, *h
;
1213 for (h
= extra_http_headers
; h
; h
= h
->next
)
1214 headers
= curl_slist_append(headers
, h
->data
);
1219 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1225 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1227 strbuf_addstr(buf
, ptr
);
1232 * Check for and extract a content-type parameter. "raw"
1233 * should be positioned at the start of the potential
1234 * parameter, with any whitespace already removed.
1236 * "name" is the name of the parameter. The value is appended
1239 static int extract_param(const char *raw
, const char *name
,
1242 size_t len
= strlen(name
);
1244 if (strncasecmp(raw
, name
, len
))
1252 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1253 strbuf_addch(out
, *raw
++);
1258 * Extract a normalized version of the content type, with any
1259 * spaces suppressed, all letters lowercased, and no trailing ";"
1262 * Note that we will silently remove even invalid whitespace. For
1263 * example, "text / plain" is specifically forbidden by RFC 2616,
1264 * but "text/plain" is the only reasonable output, and this keeps
1267 * If the "charset" argument is not NULL, store the value of any
1268 * charset parameter there.
1271 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1272 * "text / plain" -> "text/plain"
1274 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1275 struct strbuf
*charset
)
1280 strbuf_grow(type
, raw
->len
);
1281 for (p
= raw
->buf
; *p
; p
++) {
1288 strbuf_addch(type
, tolower(*p
));
1294 strbuf_reset(charset
);
1296 while (isspace(*p
) || *p
== ';')
1298 if (!extract_param(p
, "charset", charset
))
1300 while (*p
&& !isspace(*p
))
1304 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1305 strbuf_addstr(charset
, "ISO-8859-1");
1308 static void write_accept_language(struct strbuf
*buf
)
1311 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1312 * that, q-value will be smaller than 0.001, the minimum q-value the
1313 * HTTP specification allows. See
1314 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1316 const int MAX_DECIMAL_PLACES
= 3;
1317 const int MAX_LANGUAGE_TAGS
= 1000;
1318 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1319 char **language_tags
= NULL
;
1321 const char *s
= get_preferred_languages();
1323 struct strbuf tag
= STRBUF_INIT
;
1325 /* Don't add Accept-Language header if no language is preferred. */
1330 * Split the colon-separated string of preferred languages into
1331 * language_tags array.
1334 /* collect language tag */
1335 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1336 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1338 /* skip .codeset, @modifier and any other unnecessary parts */
1339 while (*s
&& *s
!= ':')
1344 REALLOC_ARRAY(language_tags
, num_langs
);
1345 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1346 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1351 /* write Accept-Language header into buf */
1353 int last_buf_len
= 0;
1359 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1360 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1362 /* compute decimal_places */
1363 for (max_q
= 1, decimal_places
= 0;
1364 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1365 decimal_places
++, max_q
*= 10)
1368 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1370 strbuf_addstr(buf
, "Accept-Language: ");
1372 for (i
= 0; i
< num_langs
; i
++) {
1374 strbuf_addstr(buf
, ", ");
1376 strbuf_addstr(buf
, language_tags
[i
]);
1379 strbuf_addf(buf
, q_format
, max_q
- i
);
1381 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1382 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1386 last_buf_len
= buf
->len
;
1390 /* free language tags -- last one is a static '*' */
1391 for (i
= 0; i
< num_langs
- 1; i
++)
1392 free(language_tags
[i
]);
1393 free(language_tags
);
1397 * Get an Accept-Language header which indicates user's preferred languages.
1401 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1402 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1403 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1404 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1405 * LANGUAGE= LANG=C -> ""
1407 static const char *get_accept_language(void)
1409 if (!cached_accept_language
) {
1410 struct strbuf buf
= STRBUF_INIT
;
1411 write_accept_language(&buf
);
1413 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1416 return cached_accept_language
;
1419 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1422 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1423 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1426 /* http_request() targets */
1427 #define HTTP_REQUEST_STRBUF 0
1428 #define HTTP_REQUEST_FILE 1
1430 static int http_request(const char *url
,
1431 void *result
, int target
,
1432 const struct http_get_options
*options
)
1434 struct active_request_slot
*slot
;
1435 struct slot_results results
;
1436 struct curl_slist
*headers
= http_copy_default_headers();
1437 struct strbuf buf
= STRBUF_INIT
;
1438 const char *accept_language
;
1441 slot
= get_active_slot();
1442 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1444 if (result
== NULL
) {
1445 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1447 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1448 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1450 if (target
== HTTP_REQUEST_FILE
) {
1451 off_t posn
= ftello(result
);
1452 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1455 http_opt_request_remainder(slot
->curl
, posn
);
1457 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1461 accept_language
= get_accept_language();
1463 if (accept_language
)
1464 headers
= curl_slist_append(headers
, accept_language
);
1466 strbuf_addstr(&buf
, "Pragma:");
1467 if (options
&& options
->no_cache
)
1468 strbuf_addstr(&buf
, " no-cache");
1469 if (options
&& options
->keep_error
)
1470 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1471 if (options
&& options
->initial_request
&&
1472 http_follow_config
== HTTP_FOLLOW_INITIAL
)
1473 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1475 headers
= curl_slist_append(headers
, buf
.buf
);
1477 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1478 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1479 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1481 ret
= run_one_slot(slot
, &results
);
1483 if (options
&& options
->content_type
) {
1484 struct strbuf raw
= STRBUF_INIT
;
1485 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1486 extract_content_type(&raw
, options
->content_type
,
1488 strbuf_release(&raw
);
1491 if (options
&& options
->effective_url
)
1492 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1493 options
->effective_url
);
1495 curl_slist_free_all(headers
);
1496 strbuf_release(&buf
);
1502 * Update the "base" url to a more appropriate value, as deduced by
1503 * redirects seen when requesting a URL starting with "url".
1505 * The "asked" parameter is a URL that we asked curl to access, and must begin
1508 * The "got" parameter is the URL that curl reported to us as where we ended
1511 * Returns 1 if we updated the base url, 0 otherwise.
1513 * Our basic strategy is to compare "base" and "asked" to find the bits
1514 * specific to our request. We then strip those bits off of "got" to yield the
1515 * new base. So for example, if our base is "http://example.com/foo.git",
1516 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1517 * with "https://other.example.com/foo.git/info/refs". We would want the
1518 * new URL to become "https://other.example.com/foo.git".
1520 * Note that this assumes a sane redirect scheme. It's entirely possible
1521 * in the example above to end up at a URL that does not even end in
1522 * "info/refs". In such a case we die. There's not much we can do, such a
1523 * scheme is unlikely to represent a real git repository, and failing to
1524 * rewrite the base opens options for malicious redirects to do funny things.
1526 static int update_url_from_redirect(struct strbuf
*base
,
1528 const struct strbuf
*got
)
1533 if (!strcmp(asked
, got
->buf
))
1536 if (!skip_prefix(asked
, base
->buf
, &tail
))
1537 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1541 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
1542 die(_("unable to update url base from redirection:\n"
1548 strbuf_add(base
, got
->buf
, new_len
);
1553 static int http_request_reauth(const char *url
,
1554 void *result
, int target
,
1555 struct http_get_options
*options
)
1557 int ret
= http_request(url
, result
, target
, options
);
1559 if (options
&& options
->effective_url
&& options
->base_url
) {
1560 if (update_url_from_redirect(options
->base_url
,
1561 url
, options
->effective_url
)) {
1562 credential_from_url(&http_auth
, options
->base_url
->buf
);
1563 url
= options
->effective_url
->buf
;
1567 if (ret
!= HTTP_REAUTH
)
1571 * If we are using KEEP_ERROR, the previous request may have
1572 * put cruft into our output stream; we should clear it out before
1573 * making our next request. We only know how to do this for
1574 * the strbuf case, but that is enough to satisfy current callers.
1576 if (options
&& options
->keep_error
) {
1578 case HTTP_REQUEST_STRBUF
:
1579 strbuf_reset(result
);
1582 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1586 credential_fill(&http_auth
);
1588 return http_request(url
, result
, target
, options
);
1591 int http_get_strbuf(const char *url
,
1592 struct strbuf
*result
,
1593 struct http_get_options
*options
)
1595 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1599 * Downloads a URL and stores the result in the given file.
1601 * If a previous interrupted download is detected (i.e. a previous temporary
1602 * file is still around) the download is resumed.
1604 static int http_get_file(const char *url
, const char *filename
,
1605 struct http_get_options
*options
)
1608 struct strbuf tmpfile
= STRBUF_INIT
;
1611 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1612 result
= fopen(tmpfile
.buf
, "a");
1614 error("Unable to open local file %s", tmpfile
.buf
);
1619 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1622 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1625 strbuf_release(&tmpfile
);
1629 int http_fetch_ref(const char *base
, struct ref
*ref
)
1631 struct http_get_options options
= {0};
1633 struct strbuf buffer
= STRBUF_INIT
;
1636 options
.no_cache
= 1;
1638 url
= quote_ref_url(base
, ref
->name
);
1639 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1640 strbuf_rtrim(&buffer
);
1641 if (buffer
.len
== 40)
1642 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
1643 else if (starts_with(buffer
.buf
, "ref: ")) {
1644 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1649 strbuf_release(&buffer
);
1654 /* Helpers for fetching packs */
1655 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1658 struct strbuf buf
= STRBUF_INIT
;
1660 if (http_is_verbose
)
1661 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1663 end_url_with_slash(&buf
, base_url
);
1664 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1665 url
= strbuf_detach(&buf
, NULL
);
1667 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1668 tmp
= strbuf_detach(&buf
, NULL
);
1670 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1671 error("Unable to get pack index %s", url
);
1680 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1681 unsigned char *sha1
, const char *base_url
)
1683 struct packed_git
*new_pack
;
1684 char *tmp_idx
= NULL
;
1687 if (has_pack_index(sha1
)) {
1688 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1690 return -1; /* parse_pack_index() already issued error message */
1694 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1698 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1703 return -1; /* parse_pack_index() already issued error message */
1706 ret
= verify_pack_index(new_pack
);
1708 close_pack_index(new_pack
);
1709 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1716 new_pack
->next
= *packs_head
;
1717 *packs_head
= new_pack
;
1721 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1723 struct http_get_options options
= {0};
1726 struct strbuf buf
= STRBUF_INIT
;
1727 unsigned char sha1
[20];
1729 end_url_with_slash(&buf
, base_url
);
1730 strbuf_addstr(&buf
, "objects/info/packs");
1731 url
= strbuf_detach(&buf
, NULL
);
1733 options
.no_cache
= 1;
1734 ret
= http_get_strbuf(url
, &buf
, &options
);
1739 while (i
< buf
.len
) {
1743 if (i
+ 52 <= buf
.len
&&
1744 starts_with(data
+ i
, " pack-") &&
1745 starts_with(data
+ i
+ 46, ".pack\n")) {
1746 get_sha1_hex(data
+ i
+ 6, sha1
);
1747 fetch_and_setup_pack_index(packs_head
, sha1
,
1753 while (i
< buf
.len
&& data
[i
] != '\n')
1764 void release_http_pack_request(struct http_pack_request
*preq
)
1766 if (preq
->packfile
!= NULL
) {
1767 fclose(preq
->packfile
);
1768 preq
->packfile
= NULL
;
1775 int finish_http_pack_request(struct http_pack_request
*preq
)
1777 struct packed_git
**lst
;
1778 struct packed_git
*p
= preq
->target
;
1781 struct child_process ip
= CHILD_PROCESS_INIT
;
1782 const char *ip_argv
[8];
1784 close_pack_index(p
);
1786 fclose(preq
->packfile
);
1787 preq
->packfile
= NULL
;
1791 lst
= &((*lst
)->next
);
1792 *lst
= (*lst
)->next
;
1794 if (!strip_suffix(preq
->tmpfile
, ".pack.temp", &len
))
1795 die("BUG: pack tmpfile does not end in .pack.temp?");
1796 tmp_idx
= xstrfmt("%.*s.idx.temp", (int)len
, preq
->tmpfile
);
1798 ip_argv
[0] = "index-pack";
1800 ip_argv
[2] = tmp_idx
;
1801 ip_argv
[3] = preq
->tmpfile
;
1809 if (run_command(&ip
)) {
1810 unlink(preq
->tmpfile
);
1816 unlink(sha1_pack_index_name(p
->sha1
));
1818 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1819 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1824 install_packed_git(p
);
1829 struct http_pack_request
*new_http_pack_request(
1830 struct packed_git
*target
, const char *base_url
)
1832 off_t prev_posn
= 0;
1833 struct strbuf buf
= STRBUF_INIT
;
1834 struct http_pack_request
*preq
;
1836 preq
= xcalloc(1, sizeof(*preq
));
1837 preq
->target
= target
;
1839 end_url_with_slash(&buf
, base_url
);
1840 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1841 sha1_to_hex(target
->sha1
));
1842 preq
->url
= strbuf_detach(&buf
, NULL
);
1844 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1845 sha1_pack_name(target
->sha1
));
1846 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1847 if (!preq
->packfile
) {
1848 error("Unable to open local file %s for pack",
1853 preq
->slot
= get_active_slot();
1854 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1855 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1856 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1857 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1861 * If there is data present from a previous transfer attempt,
1862 * resume where it left off
1864 prev_posn
= ftello(preq
->packfile
);
1866 if (http_is_verbose
)
1868 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
1869 sha1_to_hex(target
->sha1
), (uintmax_t)prev_posn
);
1870 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
1881 /* Helpers for fetching objects (loose) */
1882 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
1885 unsigned char expn
[4096];
1886 size_t size
= eltsize
* nmemb
;
1888 struct http_object_request
*freq
=
1889 (struct http_object_request
*)data
;
1891 ssize_t retval
= xwrite(freq
->localfile
,
1892 (char *) ptr
+ posn
, size
- posn
);
1896 } while (posn
< size
);
1898 freq
->stream
.avail_in
= size
;
1899 freq
->stream
.next_in
= (void *)ptr
;
1901 freq
->stream
.next_out
= expn
;
1902 freq
->stream
.avail_out
= sizeof(expn
);
1903 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
1904 git_SHA1_Update(&freq
->c
, expn
,
1905 sizeof(expn
) - freq
->stream
.avail_out
);
1906 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
1910 struct http_object_request
*new_http_object_request(const char *base_url
,
1911 unsigned char *sha1
)
1913 char *hex
= sha1_to_hex(sha1
);
1914 const char *filename
;
1915 char prevfile
[PATH_MAX
];
1917 char prev_buf
[PREV_BUF_SIZE
];
1918 ssize_t prev_read
= 0;
1919 off_t prev_posn
= 0;
1920 struct http_object_request
*freq
;
1922 freq
= xcalloc(1, sizeof(*freq
));
1923 hashcpy(freq
->sha1
, sha1
);
1924 freq
->localfile
= -1;
1926 filename
= sha1_file_name(sha1
);
1927 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
1928 "%s.temp", filename
);
1930 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
1931 unlink_or_warn(prevfile
);
1932 rename(freq
->tmpfile
, prevfile
);
1933 unlink_or_warn(freq
->tmpfile
);
1935 if (freq
->localfile
!= -1)
1936 error("fd leakage in start: %d", freq
->localfile
);
1937 freq
->localfile
= open(freq
->tmpfile
,
1938 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1940 * This could have failed due to the "lazy directory creation";
1941 * try to mkdir the last path component.
1943 if (freq
->localfile
< 0 && errno
== ENOENT
) {
1944 char *dir
= strrchr(freq
->tmpfile
, '/');
1947 mkdir(freq
->tmpfile
, 0777);
1950 freq
->localfile
= open(freq
->tmpfile
,
1951 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1954 if (freq
->localfile
< 0) {
1955 error_errno("Couldn't create temporary file %s", freq
->tmpfile
);
1959 git_inflate_init(&freq
->stream
);
1961 git_SHA1_Init(&freq
->c
);
1963 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
1966 * If a previous temp file is present, process what was already
1969 prevlocal
= open(prevfile
, O_RDONLY
);
1970 if (prevlocal
!= -1) {
1972 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
1974 if (fwrite_sha1_file(prev_buf
,
1977 freq
) == prev_read
) {
1978 prev_posn
+= prev_read
;
1983 } while (prev_read
> 0);
1986 unlink_or_warn(prevfile
);
1989 * Reset inflate/SHA1 if there was an error reading the previous temp
1990 * file; also rewind to the beginning of the local file.
1992 if (prev_read
== -1) {
1993 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
1994 git_inflate_init(&freq
->stream
);
1995 git_SHA1_Init(&freq
->c
);
1998 lseek(freq
->localfile
, 0, SEEK_SET
);
1999 if (ftruncate(freq
->localfile
, 0) < 0) {
2000 error_errno("Couldn't truncate temporary file %s",
2007 freq
->slot
= get_active_slot();
2009 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
2010 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2011 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2012 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2013 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2016 * If we have successfully processed data from a previous fetch
2017 * attempt, only fetch the data we don't already have.
2020 if (http_is_verbose
)
2022 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2023 hex
, (uintmax_t)prev_posn
);
2024 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2035 void process_http_object_request(struct http_object_request
*freq
)
2037 if (freq
->slot
== NULL
)
2039 freq
->curl_result
= freq
->slot
->curl_result
;
2040 freq
->http_code
= freq
->slot
->http_code
;
2044 int finish_http_object_request(struct http_object_request
*freq
)
2048 close(freq
->localfile
);
2049 freq
->localfile
= -1;
2051 process_http_object_request(freq
);
2053 if (freq
->http_code
== 416) {
2054 warning("requested range invalid; we may already have all the data.");
2055 } else if (freq
->curl_result
!= CURLE_OK
) {
2056 if (stat(freq
->tmpfile
, &st
) == 0)
2057 if (st
.st_size
== 0)
2058 unlink_or_warn(freq
->tmpfile
);
2062 git_inflate_end(&freq
->stream
);
2063 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
2064 if (freq
->zret
!= Z_STREAM_END
) {
2065 unlink_or_warn(freq
->tmpfile
);
2068 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
2069 unlink_or_warn(freq
->tmpfile
);
2073 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
2075 return freq
->rename
;
2078 void abort_http_object_request(struct http_object_request
*freq
)
2080 unlink_or_warn(freq
->tmpfile
);
2082 release_http_object_request(freq
);
2085 void release_http_object_request(struct http_object_request
*freq
)
2087 if (freq
->localfile
!= -1) {
2088 close(freq
->localfile
);
2089 freq
->localfile
= -1;
2091 if (freq
->url
!= NULL
) {
2095 if (freq
->slot
!= NULL
) {
2096 freq
->slot
->callback_func
= NULL
;
2097 freq
->slot
->callback_data
= NULL
;
2098 release_active_slot(freq
->slot
);