1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
14 static struct trace_key trace_curl
= TRACE_KEY_INIT(CURL
);
15 #if LIBCURL_VERSION_NUM >= 0x070a08
16 long int git_curl_ipresolve
= CURL_IPRESOLVE_WHATEVER
;
18 long int git_curl_ipresolve
;
22 size_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
24 #if LIBCURL_VERSION_NUM >= 0x070a06
25 #define LIBCURL_CAN_HANDLE_AUTH_ANY
28 static int min_curl_sessions
= 1;
29 static int curl_session_count
;
31 static int max_requests
= -1;
34 #ifndef NO_CURL_EASY_DUPHANDLE
35 static CURL
*curl_default
;
38 #define PREV_BUF_SIZE 4096
40 char curl_errorstr
[CURL_ERROR_SIZE
];
42 static int curl_ssl_verify
= -1;
43 static int curl_ssl_try
;
44 static const char *ssl_cert
;
45 static const char *ssl_cipherlist
;
46 static const char *ssl_version
;
51 { "sslv2", CURL_SSLVERSION_SSLv2
},
52 { "sslv3", CURL_SSLVERSION_SSLv3
},
53 { "tlsv1", CURL_SSLVERSION_TLSv1
},
54 #if LIBCURL_VERSION_NUM >= 0x072200
55 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
56 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
57 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
60 #if LIBCURL_VERSION_NUM >= 0x070903
61 static const char *ssl_key
;
63 #if LIBCURL_VERSION_NUM >= 0x070908
64 static const char *ssl_capath
;
66 #if LIBCURL_VERSION_NUM >= 0x072c00
67 static const char *ssl_pinnedkey
;
69 static const char *ssl_cainfo
;
70 static long curl_low_speed_limit
= -1;
71 static long curl_low_speed_time
= -1;
72 static int curl_ftp_no_epsv
;
73 static const char *curl_http_proxy
;
74 static const char *curl_no_proxy
;
75 static const char *http_proxy_authmethod
;
79 } proxy_authmethods
[] = {
80 { "basic", CURLAUTH_BASIC
},
81 { "digest", CURLAUTH_DIGEST
},
82 { "negotiate", CURLAUTH_GSSNEGOTIATE
},
83 { "ntlm", CURLAUTH_NTLM
},
84 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
85 { "anyauth", CURLAUTH_ANY
},
88 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
89 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
93 #if LIBCURL_VERSION_NUM >= 0x071600
94 static const char *curl_deleg
;
97 long curl_deleg_param
;
98 } curl_deleg_levels
[] = {
99 { "none", CURLGSSAPI_DELEGATION_NONE
},
100 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG
},
101 { "always", CURLGSSAPI_DELEGATION_FLAG
},
105 static struct credential proxy_auth
= CREDENTIAL_INIT
;
106 static const char *curl_proxyuserpwd
;
107 static const char *curl_cookie_file
;
108 static int curl_save_cookies
;
109 struct credential http_auth
= CREDENTIAL_INIT
;
110 static int http_proactive_auth
;
111 static const char *user_agent
;
112 static int curl_empty_auth
;
114 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
116 #if LIBCURL_VERSION_NUM >= 0x071700
117 /* Use CURLOPT_KEYPASSWD as is */
118 #elif LIBCURL_VERSION_NUM >= 0x070903
119 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
121 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
124 static struct credential cert_auth
= CREDENTIAL_INIT
;
125 static int ssl_cert_password_required
;
126 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
127 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
130 static struct curl_slist
*pragma_header
;
131 static struct curl_slist
*no_pragma_header
;
132 static struct curl_slist
*extra_http_headers
;
134 static struct active_request_slot
*active_queue_head
;
136 static char *cached_accept_language
;
138 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
140 size_t size
= eltsize
* nmemb
;
141 struct buffer
*buffer
= buffer_
;
143 if (size
> buffer
->buf
.len
- buffer
->posn
)
144 size
= buffer
->buf
.len
- buffer
->posn
;
145 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
146 buffer
->posn
+= size
;
151 #ifndef NO_CURL_IOCTL
152 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
154 struct buffer
*buffer
= clientp
;
160 case CURLIOCMD_RESTARTREAD
:
165 return CURLIOE_UNKNOWNCMD
;
170 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
172 size_t size
= eltsize
* nmemb
;
173 struct strbuf
*buffer
= buffer_
;
175 strbuf_add(buffer
, ptr
, size
);
179 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
181 return eltsize
* nmemb
;
184 static void closedown_active_slot(struct active_request_slot
*slot
)
190 static void finish_active_slot(struct active_request_slot
*slot
)
192 closedown_active_slot(slot
);
193 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
195 if (slot
->finished
!= NULL
)
196 (*slot
->finished
) = 1;
198 /* Store slot results so they can be read after the slot is reused */
199 if (slot
->results
!= NULL
) {
200 slot
->results
->curl_result
= slot
->curl_result
;
201 slot
->results
->http_code
= slot
->http_code
;
202 #if LIBCURL_VERSION_NUM >= 0x070a08
203 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
204 &slot
->results
->auth_avail
);
206 slot
->results
->auth_avail
= 0;
209 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
210 &slot
->results
->http_connectcode
);
213 /* Run callback if appropriate */
214 if (slot
->callback_func
!= NULL
)
215 slot
->callback_func(slot
->callback_data
);
218 static void xmulti_remove_handle(struct active_request_slot
*slot
)
220 #ifdef USE_CURL_MULTI
221 curl_multi_remove_handle(curlm
, slot
->curl
);
225 #ifdef USE_CURL_MULTI
226 static void process_curl_messages(void)
229 struct active_request_slot
*slot
;
230 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
232 while (curl_message
!= NULL
) {
233 if (curl_message
->msg
== CURLMSG_DONE
) {
234 int curl_result
= curl_message
->data
.result
;
235 slot
= active_queue_head
;
236 while (slot
!= NULL
&&
237 slot
->curl
!= curl_message
->easy_handle
)
240 xmulti_remove_handle(slot
);
241 slot
->curl_result
= curl_result
;
242 finish_active_slot(slot
);
244 fprintf(stderr
, "Received DONE message for unknown request!\n");
247 fprintf(stderr
, "Unknown CURL message received: %d\n",
248 (int)curl_message
->msg
);
250 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
255 static int http_options(const char *var
, const char *value
, void *cb
)
257 if (!strcmp("http.sslverify", var
)) {
258 curl_ssl_verify
= git_config_bool(var
, value
);
261 if (!strcmp("http.sslcipherlist", var
))
262 return git_config_string(&ssl_cipherlist
, var
, value
);
263 if (!strcmp("http.sslversion", var
))
264 return git_config_string(&ssl_version
, var
, value
);
265 if (!strcmp("http.sslcert", var
))
266 return git_config_string(&ssl_cert
, var
, value
);
267 #if LIBCURL_VERSION_NUM >= 0x070903
268 if (!strcmp("http.sslkey", var
))
269 return git_config_string(&ssl_key
, var
, value
);
271 #if LIBCURL_VERSION_NUM >= 0x070908
272 if (!strcmp("http.sslcapath", var
))
273 return git_config_pathname(&ssl_capath
, var
, value
);
275 if (!strcmp("http.sslcainfo", var
))
276 return git_config_pathname(&ssl_cainfo
, var
, value
);
277 if (!strcmp("http.sslcertpasswordprotected", var
)) {
278 ssl_cert_password_required
= git_config_bool(var
, value
);
281 if (!strcmp("http.ssltry", var
)) {
282 curl_ssl_try
= git_config_bool(var
, value
);
285 if (!strcmp("http.minsessions", var
)) {
286 min_curl_sessions
= git_config_int(var
, value
);
287 #ifndef USE_CURL_MULTI
288 if (min_curl_sessions
> 1)
289 min_curl_sessions
= 1;
293 #ifdef USE_CURL_MULTI
294 if (!strcmp("http.maxrequests", var
)) {
295 max_requests
= git_config_int(var
, value
);
299 if (!strcmp("http.lowspeedlimit", var
)) {
300 curl_low_speed_limit
= (long)git_config_int(var
, value
);
303 if (!strcmp("http.lowspeedtime", var
)) {
304 curl_low_speed_time
= (long)git_config_int(var
, value
);
308 if (!strcmp("http.noepsv", var
)) {
309 curl_ftp_no_epsv
= git_config_bool(var
, value
);
312 if (!strcmp("http.proxy", var
))
313 return git_config_string(&curl_http_proxy
, var
, value
);
315 if (!strcmp("http.proxyauthmethod", var
))
316 return git_config_string(&http_proxy_authmethod
, var
, value
);
318 if (!strcmp("http.cookiefile", var
))
319 return git_config_pathname(&curl_cookie_file
, var
, value
);
320 if (!strcmp("http.savecookies", var
)) {
321 curl_save_cookies
= git_config_bool(var
, value
);
325 if (!strcmp("http.postbuffer", var
)) {
326 http_post_buffer
= git_config_int(var
, value
);
327 if (http_post_buffer
< LARGE_PACKET_MAX
)
328 http_post_buffer
= LARGE_PACKET_MAX
;
332 if (!strcmp("http.useragent", var
))
333 return git_config_string(&user_agent
, var
, value
);
335 if (!strcmp("http.emptyauth", var
)) {
336 curl_empty_auth
= git_config_bool(var
, value
);
340 if (!strcmp("http.delegation", var
)) {
341 #if LIBCURL_VERSION_NUM >= 0x071600
342 return git_config_string(&curl_deleg
, var
, value
);
344 warning(_("Delegation control is not supported with cURL < 7.22.0"));
349 if (!strcmp("http.pinnedpubkey", var
)) {
350 #if LIBCURL_VERSION_NUM >= 0x072c00
351 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
353 warning(_("Public key pinning not supported with cURL < 7.44.0"));
358 if (!strcmp("http.extraheader", var
)) {
360 return config_error_nonbool(var
);
361 } else if (!*value
) {
362 curl_slist_free_all(extra_http_headers
);
363 extra_http_headers
= NULL
;
366 curl_slist_append(extra_http_headers
, value
);
371 if (!strcmp("http.followredirects", var
)) {
372 if (value
&& !strcmp(value
, "initial"))
373 http_follow_config
= HTTP_FOLLOW_INITIAL
;
374 else if (git_config_bool(var
, value
))
375 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
377 http_follow_config
= HTTP_FOLLOW_NONE
;
381 /* Fall back on the default ones */
382 return git_default_config(var
, value
, cb
);
385 static void init_curl_http_auth(CURL
*result
)
387 if (!http_auth
.username
|| !*http_auth
.username
) {
389 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
393 credential_fill(&http_auth
);
395 #if LIBCURL_VERSION_NUM >= 0x071301
396 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
397 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
400 static struct strbuf up
= STRBUF_INIT
;
402 * Note that we assume we only ever have a single set of
403 * credentials in a given program run, so we do not have
404 * to worry about updating this buffer, only setting its
408 strbuf_addf(&up
, "%s:%s",
409 http_auth
.username
, http_auth
.password
);
410 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
415 /* *var must be free-able */
416 static void var_override(const char **var
, char *value
)
420 *var
= xstrdup(value
);
424 static void set_proxyauth_name_password(CURL
*result
)
426 #if LIBCURL_VERSION_NUM >= 0x071301
427 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
428 proxy_auth
.username
);
429 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
430 proxy_auth
.password
);
432 struct strbuf s
= STRBUF_INIT
;
434 strbuf_addstr_urlencode(&s
, proxy_auth
.username
, 1);
435 strbuf_addch(&s
, ':');
436 strbuf_addstr_urlencode(&s
, proxy_auth
.password
, 1);
437 curl_proxyuserpwd
= strbuf_detach(&s
, NULL
);
438 curl_easy_setopt(result
, CURLOPT_PROXYUSERPWD
, curl_proxyuserpwd
);
442 static void init_curl_proxy_auth(CURL
*result
)
444 if (proxy_auth
.username
) {
445 if (!proxy_auth
.password
)
446 credential_fill(&proxy_auth
);
447 set_proxyauth_name_password(result
);
450 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
452 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
453 if (http_proxy_authmethod
) {
455 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
456 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
457 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
458 proxy_authmethods
[i
].curlauth_param
);
462 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
463 warning("unsupported proxy authentication method %s: using anyauth",
464 http_proxy_authmethod
);
465 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
469 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
473 static int has_cert_password(void)
475 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
477 if (!cert_auth
.password
) {
478 cert_auth
.protocol
= xstrdup("cert");
479 cert_auth
.username
= xstrdup("");
480 cert_auth
.path
= xstrdup(ssl_cert
);
481 credential_fill(&cert_auth
);
486 #if LIBCURL_VERSION_NUM >= 0x071900
487 static void set_curl_keepalive(CURL
*c
)
489 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
492 #elif LIBCURL_VERSION_NUM >= 0x071000
493 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
497 socklen_t len
= (socklen_t
)sizeof(ka
);
499 if (type
!= CURLSOCKTYPE_IPCXN
)
502 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
504 warning_errno("unable to set SO_KEEPALIVE on socket");
506 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
509 static void set_curl_keepalive(CURL
*c
)
511 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
515 static void set_curl_keepalive(CURL
*c
)
517 /* not supported on older curl versions */
521 static void redact_sensitive_header(struct strbuf
*header
)
523 const char *sensitive_header
;
525 if (skip_prefix(header
->buf
, "Authorization:", &sensitive_header
) ||
526 skip_prefix(header
->buf
, "Proxy-Authorization:", &sensitive_header
)) {
527 /* The first token is the type, which is OK to log */
528 while (isspace(*sensitive_header
))
530 while (*sensitive_header
&& !isspace(*sensitive_header
))
532 /* Everything else is opaque and possibly sensitive */
533 strbuf_setlen(header
, sensitive_header
- header
->buf
);
534 strbuf_addstr(header
, " <redacted>");
538 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
540 struct strbuf out
= STRBUF_INIT
;
541 struct strbuf
**headers
, **header
;
543 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
544 text
, (long)size
, (long)size
);
545 trace_strbuf(&trace_curl
, &out
);
547 strbuf_add(&out
, ptr
, size
);
548 headers
= strbuf_split_max(&out
, '\n', 0);
550 for (header
= headers
; *header
; header
++) {
551 if (hide_sensitive_header
)
552 redact_sensitive_header(*header
);
553 strbuf_insert((*header
), 0, text
, strlen(text
));
554 strbuf_insert((*header
), strlen(text
), ": ", 2);
555 strbuf_rtrim((*header
));
556 strbuf_addch((*header
), '\n');
557 trace_strbuf(&trace_curl
, (*header
));
559 strbuf_list_free(headers
);
560 strbuf_release(&out
);
563 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
566 struct strbuf out
= STRBUF_INIT
;
567 unsigned int width
= 60;
569 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
570 text
, (long)size
, (long)size
);
571 trace_strbuf(&trace_curl
, &out
);
573 for (i
= 0; i
< size
; i
+= width
) {
577 strbuf_addf(&out
, "%s: ", text
);
578 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
579 unsigned char ch
= ptr
[i
+ w
];
582 (ch
>= 0x20) && (ch
< 0x80)
585 strbuf_addch(&out
, '\n');
586 trace_strbuf(&trace_curl
, &out
);
588 strbuf_release(&out
);
591 static int curl_trace(CURL
*handle
, curl_infotype type
, char *data
, size_t size
, void *userp
)
594 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
598 trace_printf_key(&trace_curl
, "== Info: %s", data
);
599 default: /* we ignore unknown types by default */
602 case CURLINFO_HEADER_OUT
:
603 text
= "=> Send header";
604 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
606 case CURLINFO_DATA_OUT
:
607 text
= "=> Send data";
608 curl_dump_data(text
, (unsigned char *)data
, size
);
610 case CURLINFO_SSL_DATA_OUT
:
611 text
= "=> Send SSL data";
612 curl_dump_data(text
, (unsigned char *)data
, size
);
614 case CURLINFO_HEADER_IN
:
615 text
= "<= Recv header";
616 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
618 case CURLINFO_DATA_IN
:
619 text
= "<= Recv data";
620 curl_dump_data(text
, (unsigned char *)data
, size
);
622 case CURLINFO_SSL_DATA_IN
:
623 text
= "<= Recv SSL data";
624 curl_dump_data(text
, (unsigned char *)data
, size
);
630 void setup_curl_trace(CURL
*handle
)
632 if (!trace_want(&trace_curl
))
634 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
635 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
636 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
640 static CURL
*get_curl_handle(void)
642 CURL
*result
= curl_easy_init();
643 long allowed_protocols
= 0;
646 die("curl_easy_init failed");
648 if (!curl_ssl_verify
) {
649 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
650 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
652 /* Verify authenticity of the peer's certificate */
653 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
654 /* The name in the cert must match whom we tried to connect */
655 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
658 #if LIBCURL_VERSION_NUM >= 0x070907
659 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
661 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
662 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
665 #if LIBCURL_VERSION_NUM >= 0x071600
668 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
669 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
670 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
671 curl_deleg_levels
[i
].curl_deleg_param
);
675 if (i
== ARRAY_SIZE(curl_deleg_levels
))
676 warning("Unknown delegation method '%s': using default",
681 if (http_proactive_auth
)
682 init_curl_http_auth(result
);
684 if (getenv("GIT_SSL_VERSION"))
685 ssl_version
= getenv("GIT_SSL_VERSION");
686 if (ssl_version
&& *ssl_version
) {
688 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
689 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
690 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
691 sslversions
[i
].ssl_version
);
695 if (i
== ARRAY_SIZE(sslversions
))
696 warning("unsupported ssl version %s: using default",
700 if (getenv("GIT_SSL_CIPHER_LIST"))
701 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
702 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
703 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
706 if (ssl_cert
!= NULL
)
707 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
708 if (has_cert_password())
709 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
710 #if LIBCURL_VERSION_NUM >= 0x070903
712 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
714 #if LIBCURL_VERSION_NUM >= 0x070908
715 if (ssl_capath
!= NULL
)
716 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
718 #if LIBCURL_VERSION_NUM >= 0x072c00
719 if (ssl_pinnedkey
!= NULL
)
720 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
722 if (ssl_cainfo
!= NULL
)
723 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
725 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
726 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
727 curl_low_speed_limit
);
728 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
729 curl_low_speed_time
);
732 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
733 #if LIBCURL_VERSION_NUM >= 0x071301
734 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
735 #elif LIBCURL_VERSION_NUM >= 0x071101
736 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
738 #if LIBCURL_VERSION_NUM >= 0x071304
739 if (is_transport_allowed("http"))
740 allowed_protocols
|= CURLPROTO_HTTP
;
741 if (is_transport_allowed("https"))
742 allowed_protocols
|= CURLPROTO_HTTPS
;
743 if (is_transport_allowed("ftp"))
744 allowed_protocols
|= CURLPROTO_FTP
;
745 if (is_transport_allowed("ftps"))
746 allowed_protocols
|= CURLPROTO_FTPS
;
747 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
748 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
, allowed_protocols
);
750 if (transport_restrict_protocols())
751 warning("protocol restrictions not applied to curl redirects because\n"
752 "your curl version is too old (>= 7.19.4)");
754 if (getenv("GIT_CURL_VERBOSE"))
755 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1L);
756 setup_curl_trace(result
);
758 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
759 user_agent
? user_agent
: git_user_agent());
761 if (curl_ftp_no_epsv
)
762 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
764 #ifdef CURLOPT_USE_SSL
766 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
770 * CURL also examines these variables as a fallback; but we need to query
771 * them here in order to decide whether to prompt for missing password (cf.
772 * init_curl_proxy_auth()).
774 * Unlike many other common environment variables, these are historically
775 * lowercase only. It appears that CURL did not know this and implemented
776 * only uppercase variants, which was later corrected to take both - with
777 * the exception of http_proxy, which is lowercase only also in CURL. As
778 * the lowercase versions are the historical quasi-standard, they take
779 * precedence here, as in CURL.
781 if (!curl_http_proxy
) {
782 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
783 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
784 var_override(&curl_http_proxy
, getenv("https_proxy"));
786 var_override(&curl_http_proxy
, getenv("http_proxy"));
788 if (!curl_http_proxy
) {
789 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
790 var_override(&curl_http_proxy
, getenv("all_proxy"));
794 if (curl_http_proxy
) {
795 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
796 #if LIBCURL_VERSION_NUM >= 0x071800
797 if (starts_with(curl_http_proxy
, "socks5h"))
798 curl_easy_setopt(result
,
799 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
800 else if (starts_with(curl_http_proxy
, "socks5"))
801 curl_easy_setopt(result
,
802 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
803 else if (starts_with(curl_http_proxy
, "socks4a"))
804 curl_easy_setopt(result
,
805 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
806 else if (starts_with(curl_http_proxy
, "socks"))
807 curl_easy_setopt(result
,
808 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
810 if (strstr(curl_http_proxy
, "://"))
811 credential_from_url(&proxy_auth
, curl_http_proxy
);
813 struct strbuf url
= STRBUF_INIT
;
814 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
815 credential_from_url(&proxy_auth
, url
.buf
);
816 strbuf_release(&url
);
819 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
820 #if LIBCURL_VERSION_NUM >= 0x071304
821 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
822 var_override(&curl_no_proxy
, getenv("no_proxy"));
823 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
826 init_curl_proxy_auth(result
);
828 set_curl_keepalive(result
);
833 static void set_from_env(const char **var
, const char *envname
)
835 const char *val
= getenv(envname
);
840 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
842 char *low_speed_limit
;
843 char *low_speed_time
;
844 char *normalized_url
;
845 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
847 config
.section
= "http";
849 config
.collect_fn
= http_options
;
850 config
.cascade_fn
= git_default_config
;
854 normalized_url
= url_normalize(url
, &config
.url
);
856 git_config(urlmatch_config_entry
, &config
);
857 free(normalized_url
);
859 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
860 die("curl_global_init failed");
862 http_proactive_auth
= proactive_auth
;
864 if (remote
&& remote
->http_proxy
)
865 curl_http_proxy
= xstrdup(remote
->http_proxy
);
868 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
870 pragma_header
= curl_slist_append(http_copy_default_headers(),
872 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
875 #ifdef USE_CURL_MULTI
877 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
878 if (http_max_requests
!= NULL
)
879 max_requests
= atoi(http_max_requests
);
882 curlm
= curl_multi_init();
884 die("curl_multi_init failed");
887 if (getenv("GIT_SSL_NO_VERIFY"))
890 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
891 #if LIBCURL_VERSION_NUM >= 0x070903
892 set_from_env(&ssl_key
, "GIT_SSL_KEY");
894 #if LIBCURL_VERSION_NUM >= 0x070908
895 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
897 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
899 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
901 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
902 if (low_speed_limit
!= NULL
)
903 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
904 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
905 if (low_speed_time
!= NULL
)
906 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
908 if (curl_ssl_verify
== -1)
911 curl_session_count
= 0;
912 #ifdef USE_CURL_MULTI
913 if (max_requests
< 1)
914 max_requests
= DEFAULT_MAX_REQUESTS
;
917 if (getenv("GIT_CURL_FTP_NO_EPSV"))
918 curl_ftp_no_epsv
= 1;
921 credential_from_url(&http_auth
, url
);
922 if (!ssl_cert_password_required
&&
923 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
924 starts_with(url
, "https://"))
925 ssl_cert_password_required
= 1;
928 #ifndef NO_CURL_EASY_DUPHANDLE
929 curl_default
= get_curl_handle();
933 void http_cleanup(void)
935 struct active_request_slot
*slot
= active_queue_head
;
937 while (slot
!= NULL
) {
938 struct active_request_slot
*next
= slot
->next
;
939 if (slot
->curl
!= NULL
) {
940 xmulti_remove_handle(slot
);
941 curl_easy_cleanup(slot
->curl
);
946 active_queue_head
= NULL
;
948 #ifndef NO_CURL_EASY_DUPHANDLE
949 curl_easy_cleanup(curl_default
);
952 #ifdef USE_CURL_MULTI
953 curl_multi_cleanup(curlm
);
955 curl_global_cleanup();
957 curl_slist_free_all(extra_http_headers
);
958 extra_http_headers
= NULL
;
960 curl_slist_free_all(pragma_header
);
961 pragma_header
= NULL
;
963 curl_slist_free_all(no_pragma_header
);
964 no_pragma_header
= NULL
;
966 if (curl_http_proxy
) {
967 free((void *)curl_http_proxy
);
968 curl_http_proxy
= NULL
;
971 if (proxy_auth
.password
) {
972 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
973 free(proxy_auth
.password
);
974 proxy_auth
.password
= NULL
;
977 free((void *)curl_proxyuserpwd
);
978 curl_proxyuserpwd
= NULL
;
980 free((void *)http_proxy_authmethod
);
981 http_proxy_authmethod
= NULL
;
983 if (cert_auth
.password
!= NULL
) {
984 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
985 free(cert_auth
.password
);
986 cert_auth
.password
= NULL
;
988 ssl_cert_password_required
= 0;
990 free(cached_accept_language
);
991 cached_accept_language
= NULL
;
994 struct active_request_slot
*get_active_slot(void)
996 struct active_request_slot
*slot
= active_queue_head
;
997 struct active_request_slot
*newslot
;
999 #ifdef USE_CURL_MULTI
1002 /* Wait for a slot to open up if the queue is full */
1003 while (active_requests
>= max_requests
) {
1004 curl_multi_perform(curlm
, &num_transfers
);
1005 if (num_transfers
< active_requests
)
1006 process_curl_messages();
1010 while (slot
!= NULL
&& slot
->in_use
)
1014 newslot
= xmalloc(sizeof(*newslot
));
1015 newslot
->curl
= NULL
;
1016 newslot
->in_use
= 0;
1017 newslot
->next
= NULL
;
1019 slot
= active_queue_head
;
1021 active_queue_head
= newslot
;
1023 while (slot
->next
!= NULL
)
1025 slot
->next
= newslot
;
1030 if (slot
->curl
== NULL
) {
1031 #ifdef NO_CURL_EASY_DUPHANDLE
1032 slot
->curl
= get_curl_handle();
1034 slot
->curl
= curl_easy_duphandle(curl_default
);
1036 curl_session_count
++;
1041 slot
->results
= NULL
;
1042 slot
->finished
= NULL
;
1043 slot
->callback_data
= NULL
;
1044 slot
->callback_func
= NULL
;
1045 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1046 if (curl_save_cookies
)
1047 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1048 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1049 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1050 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1051 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1052 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1053 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1054 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1055 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1056 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1057 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1060 * Default following to off unless "ALWAYS" is configured; this gives
1061 * callers a sane starting point, and they can tweak for individual
1062 * HTTP_FOLLOW_* cases themselves.
1064 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1065 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1067 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1069 #if LIBCURL_VERSION_NUM >= 0x070a08
1070 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1072 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1073 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1075 if (http_auth
.password
|| curl_empty_auth
)
1076 init_curl_http_auth(slot
->curl
);
1081 int start_active_slot(struct active_request_slot
*slot
)
1083 #ifdef USE_CURL_MULTI
1084 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1087 if (curlm_result
!= CURLM_OK
&&
1088 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1089 warning("curl_multi_add_handle failed: %s",
1090 curl_multi_strerror(curlm_result
));
1097 * We know there must be something to do, since we just added
1100 curl_multi_perform(curlm
, &num_transfers
);
1105 #ifdef USE_CURL_MULTI
1108 int (*fill
)(void *);
1109 struct fill_chain
*next
;
1112 static struct fill_chain
*fill_cfg
;
1114 void add_fill_function(void *data
, int (*fill
)(void *))
1116 struct fill_chain
*new = xmalloc(sizeof(*new));
1117 struct fill_chain
**linkp
= &fill_cfg
;
1122 linkp
= &(*linkp
)->next
;
1126 void fill_active_slots(void)
1128 struct active_request_slot
*slot
= active_queue_head
;
1130 while (active_requests
< max_requests
) {
1131 struct fill_chain
*fill
;
1132 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1133 if (fill
->fill(fill
->data
))
1140 while (slot
!= NULL
) {
1141 if (!slot
->in_use
&& slot
->curl
!= NULL
1142 && curl_session_count
> min_curl_sessions
) {
1143 curl_easy_cleanup(slot
->curl
);
1145 curl_session_count
--;
1151 void step_active_slots(void)
1154 CURLMcode curlm_result
;
1157 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1158 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1159 if (num_transfers
< active_requests
) {
1160 process_curl_messages();
1161 fill_active_slots();
1166 void run_active_slot(struct active_request_slot
*slot
)
1168 #ifdef USE_CURL_MULTI
1173 struct timeval select_timeout
;
1176 slot
->finished
= &finished
;
1178 step_active_slots();
1181 #if LIBCURL_VERSION_NUM >= 0x070f04
1183 curl_multi_timeout(curlm
, &curl_timeout
);
1184 if (curl_timeout
== 0) {
1186 } else if (curl_timeout
== -1) {
1187 select_timeout
.tv_sec
= 0;
1188 select_timeout
.tv_usec
= 50000;
1190 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1191 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1194 select_timeout
.tv_sec
= 0;
1195 select_timeout
.tv_usec
= 50000;
1202 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1205 * It can happen that curl_multi_timeout returns a pathologically
1206 * long timeout when curl_multi_fdset returns no file descriptors
1207 * to read. See commit message for more details.
1210 (select_timeout
.tv_sec
> 0 ||
1211 select_timeout
.tv_usec
> 50000)) {
1212 select_timeout
.tv_sec
= 0;
1213 select_timeout
.tv_usec
= 50000;
1216 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1220 while (slot
->in_use
) {
1221 slot
->curl_result
= curl_easy_perform(slot
->curl
);
1222 finish_active_slot(slot
);
1227 static void release_active_slot(struct active_request_slot
*slot
)
1229 closedown_active_slot(slot
);
1231 xmulti_remove_handle(slot
);
1232 if (curl_session_count
> min_curl_sessions
) {
1233 curl_easy_cleanup(slot
->curl
);
1235 curl_session_count
--;
1238 #ifdef USE_CURL_MULTI
1239 fill_active_slots();
1243 void finish_all_active_slots(void)
1245 struct active_request_slot
*slot
= active_queue_head
;
1247 while (slot
!= NULL
)
1249 run_active_slot(slot
);
1250 slot
= active_queue_head
;
1256 /* Helpers for modifying and creating URLs */
1257 static inline int needs_quote(int ch
)
1259 if (((ch
>= 'A') && (ch
<= 'Z'))
1260 || ((ch
>= 'a') && (ch
<= 'z'))
1261 || ((ch
>= '0') && (ch
<= '9'))
1269 static char *quote_ref_url(const char *base
, const char *ref
)
1271 struct strbuf buf
= STRBUF_INIT
;
1275 end_url_with_slash(&buf
, base
);
1277 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1278 if (needs_quote(ch
))
1279 strbuf_addf(&buf
, "%%%02x", ch
);
1281 strbuf_addch(&buf
, *cp
);
1283 return strbuf_detach(&buf
, NULL
);
1286 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1288 int only_two_digit_prefix
)
1290 end_url_with_slash(buf
, url
);
1292 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1293 if (!only_two_digit_prefix
)
1294 strbuf_addstr(buf
, hex
+ 2);
1297 char *get_remote_object_url(const char *url
, const char *hex
,
1298 int only_two_digit_prefix
)
1300 struct strbuf buf
= STRBUF_INIT
;
1301 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1302 return strbuf_detach(&buf
, NULL
);
1305 static int handle_curl_result(struct slot_results
*results
)
1308 * If we see a failing http code with CURLE_OK, we have turned off
1309 * FAILONERROR (to keep the server's custom error response), and should
1310 * translate the code into failure here.
1312 * Likewise, if we see a redirect (30x code), that means we turned off
1313 * redirect-following, and we should treat the result as an error.
1315 if (results
->curl_result
== CURLE_OK
&&
1316 results
->http_code
>= 300) {
1317 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
1319 * Normally curl will already have put the "reason phrase"
1320 * from the server into curl_errorstr; unfortunately without
1321 * FAILONERROR it is lost, so we can give only the numeric
1324 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1325 "The requested URL returned error: %ld",
1326 results
->http_code
);
1329 if (results
->curl_result
== CURLE_OK
) {
1330 credential_approve(&http_auth
);
1331 if (proxy_auth
.password
)
1332 credential_approve(&proxy_auth
);
1334 } else if (missing_target(results
))
1335 return HTTP_MISSING_TARGET
;
1336 else if (results
->http_code
== 401) {
1337 if (http_auth
.username
&& http_auth
.password
) {
1338 credential_reject(&http_auth
);
1341 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1342 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1343 if (results
->auth_avail
)
1344 http_auth_methods
&= results
->auth_avail
;
1349 if (results
->http_connectcode
== 407)
1350 credential_reject(&proxy_auth
);
1351 #if LIBCURL_VERSION_NUM >= 0x070c00
1352 if (!curl_errorstr
[0])
1353 strlcpy(curl_errorstr
,
1354 curl_easy_strerror(results
->curl_result
),
1355 sizeof(curl_errorstr
));
1361 int run_one_slot(struct active_request_slot
*slot
,
1362 struct slot_results
*results
)
1364 slot
->results
= results
;
1365 if (!start_active_slot(slot
)) {
1366 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1367 "failed to start HTTP request");
1368 return HTTP_START_FAILED
;
1371 run_active_slot(slot
);
1372 return handle_curl_result(results
);
1375 struct curl_slist
*http_copy_default_headers(void)
1377 struct curl_slist
*headers
= NULL
, *h
;
1379 for (h
= extra_http_headers
; h
; h
= h
->next
)
1380 headers
= curl_slist_append(headers
, h
->data
);
1385 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1391 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1393 strbuf_addstr(buf
, ptr
);
1398 * Check for and extract a content-type parameter. "raw"
1399 * should be positioned at the start of the potential
1400 * parameter, with any whitespace already removed.
1402 * "name" is the name of the parameter. The value is appended
1405 static int extract_param(const char *raw
, const char *name
,
1408 size_t len
= strlen(name
);
1410 if (strncasecmp(raw
, name
, len
))
1418 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1419 strbuf_addch(out
, *raw
++);
1424 * Extract a normalized version of the content type, with any
1425 * spaces suppressed, all letters lowercased, and no trailing ";"
1428 * Note that we will silently remove even invalid whitespace. For
1429 * example, "text / plain" is specifically forbidden by RFC 2616,
1430 * but "text/plain" is the only reasonable output, and this keeps
1433 * If the "charset" argument is not NULL, store the value of any
1434 * charset parameter there.
1437 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1438 * "text / plain" -> "text/plain"
1440 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1441 struct strbuf
*charset
)
1446 strbuf_grow(type
, raw
->len
);
1447 for (p
= raw
->buf
; *p
; p
++) {
1454 strbuf_addch(type
, tolower(*p
));
1460 strbuf_reset(charset
);
1462 while (isspace(*p
) || *p
== ';')
1464 if (!extract_param(p
, "charset", charset
))
1466 while (*p
&& !isspace(*p
))
1470 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1471 strbuf_addstr(charset
, "ISO-8859-1");
1474 static void write_accept_language(struct strbuf
*buf
)
1477 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1478 * that, q-value will be smaller than 0.001, the minimum q-value the
1479 * HTTP specification allows. See
1480 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1482 const int MAX_DECIMAL_PLACES
= 3;
1483 const int MAX_LANGUAGE_TAGS
= 1000;
1484 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1485 char **language_tags
= NULL
;
1487 const char *s
= get_preferred_languages();
1489 struct strbuf tag
= STRBUF_INIT
;
1491 /* Don't add Accept-Language header if no language is preferred. */
1496 * Split the colon-separated string of preferred languages into
1497 * language_tags array.
1500 /* collect language tag */
1501 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1502 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1504 /* skip .codeset, @modifier and any other unnecessary parts */
1505 while (*s
&& *s
!= ':')
1510 REALLOC_ARRAY(language_tags
, num_langs
);
1511 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1512 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1517 /* write Accept-Language header into buf */
1519 int last_buf_len
= 0;
1525 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1526 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1528 /* compute decimal_places */
1529 for (max_q
= 1, decimal_places
= 0;
1530 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1531 decimal_places
++, max_q
*= 10)
1534 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1536 strbuf_addstr(buf
, "Accept-Language: ");
1538 for (i
= 0; i
< num_langs
; i
++) {
1540 strbuf_addstr(buf
, ", ");
1542 strbuf_addstr(buf
, language_tags
[i
]);
1545 strbuf_addf(buf
, q_format
, max_q
- i
);
1547 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1548 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1552 last_buf_len
= buf
->len
;
1556 /* free language tags -- last one is a static '*' */
1557 for (i
= 0; i
< num_langs
- 1; i
++)
1558 free(language_tags
[i
]);
1559 free(language_tags
);
1563 * Get an Accept-Language header which indicates user's preferred languages.
1567 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1568 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1569 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1570 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1571 * LANGUAGE= LANG=C -> ""
1573 static const char *get_accept_language(void)
1575 if (!cached_accept_language
) {
1576 struct strbuf buf
= STRBUF_INIT
;
1577 write_accept_language(&buf
);
1579 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1582 return cached_accept_language
;
1585 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1588 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1589 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1592 /* http_request() targets */
1593 #define HTTP_REQUEST_STRBUF 0
1594 #define HTTP_REQUEST_FILE 1
1596 static int http_request(const char *url
,
1597 void *result
, int target
,
1598 const struct http_get_options
*options
)
1600 struct active_request_slot
*slot
;
1601 struct slot_results results
;
1602 struct curl_slist
*headers
= http_copy_default_headers();
1603 struct strbuf buf
= STRBUF_INIT
;
1604 const char *accept_language
;
1607 slot
= get_active_slot();
1608 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1610 if (result
== NULL
) {
1611 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1613 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1614 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1616 if (target
== HTTP_REQUEST_FILE
) {
1617 off_t posn
= ftello(result
);
1618 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1621 http_opt_request_remainder(slot
->curl
, posn
);
1623 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1627 accept_language
= get_accept_language();
1629 if (accept_language
)
1630 headers
= curl_slist_append(headers
, accept_language
);
1632 strbuf_addstr(&buf
, "Pragma:");
1633 if (options
&& options
->no_cache
)
1634 strbuf_addstr(&buf
, " no-cache");
1635 if (options
&& options
->keep_error
)
1636 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1637 if (options
&& options
->initial_request
&&
1638 http_follow_config
== HTTP_FOLLOW_INITIAL
)
1639 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1641 headers
= curl_slist_append(headers
, buf
.buf
);
1643 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1644 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1645 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1647 ret
= run_one_slot(slot
, &results
);
1649 if (options
&& options
->content_type
) {
1650 struct strbuf raw
= STRBUF_INIT
;
1651 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1652 extract_content_type(&raw
, options
->content_type
,
1654 strbuf_release(&raw
);
1657 if (options
&& options
->effective_url
)
1658 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1659 options
->effective_url
);
1661 curl_slist_free_all(headers
);
1662 strbuf_release(&buf
);
1668 * Update the "base" url to a more appropriate value, as deduced by
1669 * redirects seen when requesting a URL starting with "url".
1671 * The "asked" parameter is a URL that we asked curl to access, and must begin
1674 * The "got" parameter is the URL that curl reported to us as where we ended
1677 * Returns 1 if we updated the base url, 0 otherwise.
1679 * Our basic strategy is to compare "base" and "asked" to find the bits
1680 * specific to our request. We then strip those bits off of "got" to yield the
1681 * new base. So for example, if our base is "http://example.com/foo.git",
1682 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1683 * with "https://other.example.com/foo.git/info/refs". We would want the
1684 * new URL to become "https://other.example.com/foo.git".
1686 * Note that this assumes a sane redirect scheme. It's entirely possible
1687 * in the example above to end up at a URL that does not even end in
1688 * "info/refs". In such a case we die. There's not much we can do, such a
1689 * scheme is unlikely to represent a real git repository, and failing to
1690 * rewrite the base opens options for malicious redirects to do funny things.
1692 static int update_url_from_redirect(struct strbuf
*base
,
1694 const struct strbuf
*got
)
1699 if (!strcmp(asked
, got
->buf
))
1702 if (!skip_prefix(asked
, base
->buf
, &tail
))
1703 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1707 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
1708 die(_("unable to update url base from redirection:\n"
1714 strbuf_add(base
, got
->buf
, new_len
);
1719 static int http_request_reauth(const char *url
,
1720 void *result
, int target
,
1721 struct http_get_options
*options
)
1723 int ret
= http_request(url
, result
, target
, options
);
1725 if (options
&& options
->effective_url
&& options
->base_url
) {
1726 if (update_url_from_redirect(options
->base_url
,
1727 url
, options
->effective_url
)) {
1728 credential_from_url(&http_auth
, options
->base_url
->buf
);
1729 url
= options
->effective_url
->buf
;
1733 if (ret
!= HTTP_REAUTH
)
1737 * If we are using KEEP_ERROR, the previous request may have
1738 * put cruft into our output stream; we should clear it out before
1739 * making our next request. We only know how to do this for
1740 * the strbuf case, but that is enough to satisfy current callers.
1742 if (options
&& options
->keep_error
) {
1744 case HTTP_REQUEST_STRBUF
:
1745 strbuf_reset(result
);
1748 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1752 credential_fill(&http_auth
);
1754 return http_request(url
, result
, target
, options
);
1757 int http_get_strbuf(const char *url
,
1758 struct strbuf
*result
,
1759 struct http_get_options
*options
)
1761 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1765 * Downloads a URL and stores the result in the given file.
1767 * If a previous interrupted download is detected (i.e. a previous temporary
1768 * file is still around) the download is resumed.
1770 static int http_get_file(const char *url
, const char *filename
,
1771 struct http_get_options
*options
)
1774 struct strbuf tmpfile
= STRBUF_INIT
;
1777 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1778 result
= fopen(tmpfile
.buf
, "a");
1780 error("Unable to open local file %s", tmpfile
.buf
);
1785 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1788 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1791 strbuf_release(&tmpfile
);
1795 int http_fetch_ref(const char *base
, struct ref
*ref
)
1797 struct http_get_options options
= {0};
1799 struct strbuf buffer
= STRBUF_INIT
;
1802 options
.no_cache
= 1;
1804 url
= quote_ref_url(base
, ref
->name
);
1805 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1806 strbuf_rtrim(&buffer
);
1807 if (buffer
.len
== 40)
1808 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
1809 else if (starts_with(buffer
.buf
, "ref: ")) {
1810 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1815 strbuf_release(&buffer
);
1820 /* Helpers for fetching packs */
1821 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1824 struct strbuf buf
= STRBUF_INIT
;
1826 if (http_is_verbose
)
1827 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1829 end_url_with_slash(&buf
, base_url
);
1830 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1831 url
= strbuf_detach(&buf
, NULL
);
1833 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1834 tmp
= strbuf_detach(&buf
, NULL
);
1836 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1837 error("Unable to get pack index %s", url
);
1846 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1847 unsigned char *sha1
, const char *base_url
)
1849 struct packed_git
*new_pack
;
1850 char *tmp_idx
= NULL
;
1853 if (has_pack_index(sha1
)) {
1854 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1856 return -1; /* parse_pack_index() already issued error message */
1860 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1864 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1869 return -1; /* parse_pack_index() already issued error message */
1872 ret
= verify_pack_index(new_pack
);
1874 close_pack_index(new_pack
);
1875 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1882 new_pack
->next
= *packs_head
;
1883 *packs_head
= new_pack
;
1887 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1889 struct http_get_options options
= {0};
1892 struct strbuf buf
= STRBUF_INIT
;
1893 unsigned char sha1
[20];
1895 end_url_with_slash(&buf
, base_url
);
1896 strbuf_addstr(&buf
, "objects/info/packs");
1897 url
= strbuf_detach(&buf
, NULL
);
1899 options
.no_cache
= 1;
1900 ret
= http_get_strbuf(url
, &buf
, &options
);
1905 while (i
< buf
.len
) {
1909 if (i
+ 52 <= buf
.len
&&
1910 starts_with(data
+ i
, " pack-") &&
1911 starts_with(data
+ i
+ 46, ".pack\n")) {
1912 get_sha1_hex(data
+ i
+ 6, sha1
);
1913 fetch_and_setup_pack_index(packs_head
, sha1
,
1919 while (i
< buf
.len
&& data
[i
] != '\n')
1930 void release_http_pack_request(struct http_pack_request
*preq
)
1932 if (preq
->packfile
!= NULL
) {
1933 fclose(preq
->packfile
);
1934 preq
->packfile
= NULL
;
1941 int finish_http_pack_request(struct http_pack_request
*preq
)
1943 struct packed_git
**lst
;
1944 struct packed_git
*p
= preq
->target
;
1947 struct child_process ip
= CHILD_PROCESS_INIT
;
1948 const char *ip_argv
[8];
1950 close_pack_index(p
);
1952 fclose(preq
->packfile
);
1953 preq
->packfile
= NULL
;
1957 lst
= &((*lst
)->next
);
1958 *lst
= (*lst
)->next
;
1960 if (!strip_suffix(preq
->tmpfile
, ".pack.temp", &len
))
1961 die("BUG: pack tmpfile does not end in .pack.temp?");
1962 tmp_idx
= xstrfmt("%.*s.idx.temp", (int)len
, preq
->tmpfile
);
1964 ip_argv
[0] = "index-pack";
1966 ip_argv
[2] = tmp_idx
;
1967 ip_argv
[3] = preq
->tmpfile
;
1975 if (run_command(&ip
)) {
1976 unlink(preq
->tmpfile
);
1982 unlink(sha1_pack_index_name(p
->sha1
));
1984 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1985 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1990 install_packed_git(p
);
1995 struct http_pack_request
*new_http_pack_request(
1996 struct packed_git
*target
, const char *base_url
)
1998 off_t prev_posn
= 0;
1999 struct strbuf buf
= STRBUF_INIT
;
2000 struct http_pack_request
*preq
;
2002 preq
= xcalloc(1, sizeof(*preq
));
2003 preq
->target
= target
;
2005 end_url_with_slash(&buf
, base_url
);
2006 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2007 sha1_to_hex(target
->sha1
));
2008 preq
->url
= strbuf_detach(&buf
, NULL
);
2010 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
2011 sha1_pack_name(target
->sha1
));
2012 preq
->packfile
= fopen(preq
->tmpfile
, "a");
2013 if (!preq
->packfile
) {
2014 error("Unable to open local file %s for pack",
2019 preq
->slot
= get_active_slot();
2020 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
2021 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2022 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2023 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
2027 * If there is data present from a previous transfer attempt,
2028 * resume where it left off
2030 prev_posn
= ftello(preq
->packfile
);
2032 if (http_is_verbose
)
2034 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2035 sha1_to_hex(target
->sha1
), (uintmax_t)prev_posn
);
2036 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2047 /* Helpers for fetching objects (loose) */
2048 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2051 unsigned char expn
[4096];
2052 size_t size
= eltsize
* nmemb
;
2054 struct http_object_request
*freq
= data
;
2055 struct active_request_slot
*slot
= freq
->slot
;
2058 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2061 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2062 curl_easy_strerror(c
));
2063 if (slot
->http_code
>= 300)
2068 ssize_t retval
= xwrite(freq
->localfile
,
2069 (char *) ptr
+ posn
, size
- posn
);
2073 } while (posn
< size
);
2075 freq
->stream
.avail_in
= size
;
2076 freq
->stream
.next_in
= (void *)ptr
;
2078 freq
->stream
.next_out
= expn
;
2079 freq
->stream
.avail_out
= sizeof(expn
);
2080 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2081 git_SHA1_Update(&freq
->c
, expn
,
2082 sizeof(expn
) - freq
->stream
.avail_out
);
2083 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2087 struct http_object_request
*new_http_object_request(const char *base_url
,
2088 unsigned char *sha1
)
2090 char *hex
= sha1_to_hex(sha1
);
2091 const char *filename
;
2092 char prevfile
[PATH_MAX
];
2094 char prev_buf
[PREV_BUF_SIZE
];
2095 ssize_t prev_read
= 0;
2096 off_t prev_posn
= 0;
2097 struct http_object_request
*freq
;
2099 freq
= xcalloc(1, sizeof(*freq
));
2100 hashcpy(freq
->sha1
, sha1
);
2101 freq
->localfile
= -1;
2103 filename
= sha1_file_name(sha1
);
2104 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
2105 "%s.temp", filename
);
2107 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
2108 unlink_or_warn(prevfile
);
2109 rename(freq
->tmpfile
, prevfile
);
2110 unlink_or_warn(freq
->tmpfile
);
2112 if (freq
->localfile
!= -1)
2113 error("fd leakage in start: %d", freq
->localfile
);
2114 freq
->localfile
= open(freq
->tmpfile
,
2115 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2117 * This could have failed due to the "lazy directory creation";
2118 * try to mkdir the last path component.
2120 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2121 char *dir
= strrchr(freq
->tmpfile
, '/');
2124 mkdir(freq
->tmpfile
, 0777);
2127 freq
->localfile
= open(freq
->tmpfile
,
2128 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2131 if (freq
->localfile
< 0) {
2132 error_errno("Couldn't create temporary file %s", freq
->tmpfile
);
2136 git_inflate_init(&freq
->stream
);
2138 git_SHA1_Init(&freq
->c
);
2140 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2143 * If a previous temp file is present, process what was already
2146 prevlocal
= open(prevfile
, O_RDONLY
);
2147 if (prevlocal
!= -1) {
2149 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2151 if (fwrite_sha1_file(prev_buf
,
2154 freq
) == prev_read
) {
2155 prev_posn
+= prev_read
;
2160 } while (prev_read
> 0);
2163 unlink_or_warn(prevfile
);
2166 * Reset inflate/SHA1 if there was an error reading the previous temp
2167 * file; also rewind to the beginning of the local file.
2169 if (prev_read
== -1) {
2170 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2171 git_inflate_init(&freq
->stream
);
2172 git_SHA1_Init(&freq
->c
);
2175 lseek(freq
->localfile
, 0, SEEK_SET
);
2176 if (ftruncate(freq
->localfile
, 0) < 0) {
2177 error_errno("Couldn't truncate temporary file %s",
2184 freq
->slot
= get_active_slot();
2186 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
2187 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2188 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2189 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2190 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2191 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2194 * If we have successfully processed data from a previous fetch
2195 * attempt, only fetch the data we don't already have.
2198 if (http_is_verbose
)
2200 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2201 hex
, (uintmax_t)prev_posn
);
2202 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2213 void process_http_object_request(struct http_object_request
*freq
)
2215 if (freq
->slot
== NULL
)
2217 freq
->curl_result
= freq
->slot
->curl_result
;
2218 freq
->http_code
= freq
->slot
->http_code
;
2222 int finish_http_object_request(struct http_object_request
*freq
)
2226 close(freq
->localfile
);
2227 freq
->localfile
= -1;
2229 process_http_object_request(freq
);
2231 if (freq
->http_code
== 416) {
2232 warning("requested range invalid; we may already have all the data.");
2233 } else if (freq
->curl_result
!= CURLE_OK
) {
2234 if (stat(freq
->tmpfile
, &st
) == 0)
2235 if (st
.st_size
== 0)
2236 unlink_or_warn(freq
->tmpfile
);
2240 git_inflate_end(&freq
->stream
);
2241 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
2242 if (freq
->zret
!= Z_STREAM_END
) {
2243 unlink_or_warn(freq
->tmpfile
);
2246 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
2247 unlink_or_warn(freq
->tmpfile
);
2251 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
2253 return freq
->rename
;
2256 void abort_http_object_request(struct http_object_request
*freq
)
2258 unlink_or_warn(freq
->tmpfile
);
2260 release_http_object_request(freq
);
2263 void release_http_object_request(struct http_object_request
*freq
)
2265 if (freq
->localfile
!= -1) {
2266 close(freq
->localfile
);
2267 freq
->localfile
= -1;
2269 if (freq
->url
!= NULL
) {
2273 if (freq
->slot
!= NULL
) {
2274 freq
->slot
->callback_func
= NULL
;
2275 freq
->slot
->callback_data
= NULL
;
2276 release_active_slot(freq
->slot
);