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 #if LIBCURL_VERSION_NUM >= 0x071700
115 /* Use CURLOPT_KEYPASSWD as is */
116 #elif LIBCURL_VERSION_NUM >= 0x070903
117 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
119 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
122 static struct credential cert_auth
= CREDENTIAL_INIT
;
123 static int ssl_cert_password_required
;
124 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
125 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
128 static struct curl_slist
*pragma_header
;
129 static struct curl_slist
*no_pragma_header
;
130 static struct curl_slist
*extra_http_headers
;
132 static struct active_request_slot
*active_queue_head
;
134 static char *cached_accept_language
;
136 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
138 size_t size
= eltsize
* nmemb
;
139 struct buffer
*buffer
= buffer_
;
141 if (size
> buffer
->buf
.len
- buffer
->posn
)
142 size
= buffer
->buf
.len
- buffer
->posn
;
143 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
144 buffer
->posn
+= size
;
149 #ifndef NO_CURL_IOCTL
150 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
152 struct buffer
*buffer
= clientp
;
158 case CURLIOCMD_RESTARTREAD
:
163 return CURLIOE_UNKNOWNCMD
;
168 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
170 size_t size
= eltsize
* nmemb
;
171 struct strbuf
*buffer
= buffer_
;
173 strbuf_add(buffer
, ptr
, size
);
177 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
179 return eltsize
* nmemb
;
182 static void closedown_active_slot(struct active_request_slot
*slot
)
188 static void finish_active_slot(struct active_request_slot
*slot
)
190 closedown_active_slot(slot
);
191 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
193 if (slot
->finished
!= NULL
)
194 (*slot
->finished
) = 1;
196 /* Store slot results so they can be read after the slot is reused */
197 if (slot
->results
!= NULL
) {
198 slot
->results
->curl_result
= slot
->curl_result
;
199 slot
->results
->http_code
= slot
->http_code
;
200 #if LIBCURL_VERSION_NUM >= 0x070a08
201 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
202 &slot
->results
->auth_avail
);
204 slot
->results
->auth_avail
= 0;
207 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
208 &slot
->results
->http_connectcode
);
211 /* Run callback if appropriate */
212 if (slot
->callback_func
!= NULL
)
213 slot
->callback_func(slot
->callback_data
);
216 #ifdef USE_CURL_MULTI
217 static void process_curl_messages(void)
220 struct active_request_slot
*slot
;
221 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
223 while (curl_message
!= NULL
) {
224 if (curl_message
->msg
== CURLMSG_DONE
) {
225 int curl_result
= curl_message
->data
.result
;
226 slot
= active_queue_head
;
227 while (slot
!= NULL
&&
228 slot
->curl
!= curl_message
->easy_handle
)
231 curl_multi_remove_handle(curlm
, slot
->curl
);
232 slot
->curl_result
= curl_result
;
233 finish_active_slot(slot
);
235 fprintf(stderr
, "Received DONE message for unknown request!\n");
238 fprintf(stderr
, "Unknown CURL message received: %d\n",
239 (int)curl_message
->msg
);
241 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
246 static int http_options(const char *var
, const char *value
, void *cb
)
248 if (!strcmp("http.sslverify", var
)) {
249 curl_ssl_verify
= git_config_bool(var
, value
);
252 if (!strcmp("http.sslcipherlist", var
))
253 return git_config_string(&ssl_cipherlist
, var
, value
);
254 if (!strcmp("http.sslversion", var
))
255 return git_config_string(&ssl_version
, var
, value
);
256 if (!strcmp("http.sslcert", var
))
257 return git_config_string(&ssl_cert
, var
, value
);
258 #if LIBCURL_VERSION_NUM >= 0x070903
259 if (!strcmp("http.sslkey", var
))
260 return git_config_string(&ssl_key
, var
, value
);
262 #if LIBCURL_VERSION_NUM >= 0x070908
263 if (!strcmp("http.sslcapath", var
))
264 return git_config_pathname(&ssl_capath
, var
, value
);
266 if (!strcmp("http.sslcainfo", var
))
267 return git_config_pathname(&ssl_cainfo
, var
, value
);
268 if (!strcmp("http.sslcertpasswordprotected", var
)) {
269 ssl_cert_password_required
= git_config_bool(var
, value
);
272 if (!strcmp("http.ssltry", var
)) {
273 curl_ssl_try
= git_config_bool(var
, value
);
276 if (!strcmp("http.minsessions", var
)) {
277 min_curl_sessions
= git_config_int(var
, value
);
278 #ifndef USE_CURL_MULTI
279 if (min_curl_sessions
> 1)
280 min_curl_sessions
= 1;
284 #ifdef USE_CURL_MULTI
285 if (!strcmp("http.maxrequests", var
)) {
286 max_requests
= git_config_int(var
, value
);
290 if (!strcmp("http.lowspeedlimit", var
)) {
291 curl_low_speed_limit
= (long)git_config_int(var
, value
);
294 if (!strcmp("http.lowspeedtime", var
)) {
295 curl_low_speed_time
= (long)git_config_int(var
, value
);
299 if (!strcmp("http.noepsv", var
)) {
300 curl_ftp_no_epsv
= git_config_bool(var
, value
);
303 if (!strcmp("http.proxy", var
))
304 return git_config_string(&curl_http_proxy
, var
, value
);
306 if (!strcmp("http.proxyauthmethod", var
))
307 return git_config_string(&http_proxy_authmethod
, var
, value
);
309 if (!strcmp("http.cookiefile", var
))
310 return git_config_pathname(&curl_cookie_file
, var
, value
);
311 if (!strcmp("http.savecookies", var
)) {
312 curl_save_cookies
= git_config_bool(var
, value
);
316 if (!strcmp("http.postbuffer", var
)) {
317 http_post_buffer
= git_config_int(var
, value
);
318 if (http_post_buffer
< LARGE_PACKET_MAX
)
319 http_post_buffer
= LARGE_PACKET_MAX
;
323 if (!strcmp("http.useragent", var
))
324 return git_config_string(&user_agent
, var
, value
);
326 if (!strcmp("http.emptyauth", var
)) {
327 curl_empty_auth
= git_config_bool(var
, value
);
331 if (!strcmp("http.delegation", var
)) {
332 #if LIBCURL_VERSION_NUM >= 0x071600
333 return git_config_string(&curl_deleg
, var
, value
);
335 warning(_("Delegation control is not supported with cURL < 7.22.0"));
340 if (!strcmp("http.pinnedpubkey", var
)) {
341 #if LIBCURL_VERSION_NUM >= 0x072c00
342 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
344 warning(_("Public key pinning not supported with cURL < 7.44.0"));
349 if (!strcmp("http.extraheader", var
)) {
351 return config_error_nonbool(var
);
352 } else if (!*value
) {
353 curl_slist_free_all(extra_http_headers
);
354 extra_http_headers
= NULL
;
357 curl_slist_append(extra_http_headers
, value
);
362 /* Fall back on the default ones */
363 return git_default_config(var
, value
, cb
);
366 static void init_curl_http_auth(CURL
*result
)
368 if (!http_auth
.username
) {
370 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
374 credential_fill(&http_auth
);
376 #if LIBCURL_VERSION_NUM >= 0x071301
377 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
378 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
381 static struct strbuf up
= STRBUF_INIT
;
383 * Note that we assume we only ever have a single set of
384 * credentials in a given program run, so we do not have
385 * to worry about updating this buffer, only setting its
389 strbuf_addf(&up
, "%s:%s",
390 http_auth
.username
, http_auth
.password
);
391 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
396 /* *var must be free-able */
397 static void var_override(const char **var
, char *value
)
401 *var
= xstrdup(value
);
405 static void set_proxyauth_name_password(CURL
*result
)
407 #if LIBCURL_VERSION_NUM >= 0x071301
408 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
409 proxy_auth
.username
);
410 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
411 proxy_auth
.password
);
413 struct strbuf s
= STRBUF_INIT
;
415 strbuf_addstr_urlencode(&s
, proxy_auth
.username
, 1);
416 strbuf_addch(&s
, ':');
417 strbuf_addstr_urlencode(&s
, proxy_auth
.password
, 1);
418 curl_proxyuserpwd
= strbuf_detach(&s
, NULL
);
419 curl_easy_setopt(result
, CURLOPT_PROXYUSERPWD
, curl_proxyuserpwd
);
423 static void init_curl_proxy_auth(CURL
*result
)
425 if (proxy_auth
.username
) {
426 if (!proxy_auth
.password
)
427 credential_fill(&proxy_auth
);
428 set_proxyauth_name_password(result
);
431 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
433 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
434 if (http_proxy_authmethod
) {
436 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
437 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
438 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
439 proxy_authmethods
[i
].curlauth_param
);
443 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
444 warning("unsupported proxy authentication method %s: using anyauth",
445 http_proxy_authmethod
);
446 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
450 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
454 static int has_cert_password(void)
456 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
458 if (!cert_auth
.password
) {
459 cert_auth
.protocol
= xstrdup("cert");
460 cert_auth
.username
= xstrdup("");
461 cert_auth
.path
= xstrdup(ssl_cert
);
462 credential_fill(&cert_auth
);
467 #if LIBCURL_VERSION_NUM >= 0x071900
468 static void set_curl_keepalive(CURL
*c
)
470 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
473 #elif LIBCURL_VERSION_NUM >= 0x071000
474 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
478 socklen_t len
= (socklen_t
)sizeof(ka
);
480 if (type
!= CURLSOCKTYPE_IPCXN
)
483 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
485 warning_errno("unable to set SO_KEEPALIVE on socket");
487 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
490 static void set_curl_keepalive(CURL
*c
)
492 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
496 static void set_curl_keepalive(CURL
*c
)
498 /* not supported on older curl versions */
502 static void redact_sensitive_header(struct strbuf
*header
)
504 const char *sensitive_header
;
506 if (skip_prefix(header
->buf
, "Authorization:", &sensitive_header
) ||
507 skip_prefix(header
->buf
, "Proxy-Authorization:", &sensitive_header
)) {
508 /* The first token is the type, which is OK to log */
509 while (isspace(*sensitive_header
))
511 while (*sensitive_header
&& !isspace(*sensitive_header
))
513 /* Everything else is opaque and possibly sensitive */
514 strbuf_setlen(header
, sensitive_header
- header
->buf
);
515 strbuf_addstr(header
, " <redacted>");
519 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
521 struct strbuf out
= STRBUF_INIT
;
522 struct strbuf
**headers
, **header
;
524 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
525 text
, (long)size
, (long)size
);
526 trace_strbuf(&trace_curl
, &out
);
528 strbuf_add(&out
, ptr
, size
);
529 headers
= strbuf_split_max(&out
, '\n', 0);
531 for (header
= headers
; *header
; header
++) {
532 if (hide_sensitive_header
)
533 redact_sensitive_header(*header
);
534 strbuf_insert((*header
), 0, text
, strlen(text
));
535 strbuf_insert((*header
), strlen(text
), ": ", 2);
536 strbuf_rtrim((*header
));
537 strbuf_addch((*header
), '\n');
538 trace_strbuf(&trace_curl
, (*header
));
540 strbuf_list_free(headers
);
541 strbuf_release(&out
);
544 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
547 struct strbuf out
= STRBUF_INIT
;
548 unsigned int width
= 60;
550 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
551 text
, (long)size
, (long)size
);
552 trace_strbuf(&trace_curl
, &out
);
554 for (i
= 0; i
< size
; i
+= width
) {
558 strbuf_addf(&out
, "%s: ", text
);
559 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
560 unsigned char ch
= ptr
[i
+ w
];
563 (ch
>= 0x20) && (ch
< 0x80)
566 strbuf_addch(&out
, '\n');
567 trace_strbuf(&trace_curl
, &out
);
569 strbuf_release(&out
);
572 static int curl_trace(CURL
*handle
, curl_infotype type
, char *data
, size_t size
, void *userp
)
575 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
579 trace_printf_key(&trace_curl
, "== Info: %s", data
);
580 default: /* we ignore unknown types by default */
583 case CURLINFO_HEADER_OUT
:
584 text
= "=> Send header";
585 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
587 case CURLINFO_DATA_OUT
:
588 text
= "=> Send data";
589 curl_dump_data(text
, (unsigned char *)data
, size
);
591 case CURLINFO_SSL_DATA_OUT
:
592 text
= "=> Send SSL data";
593 curl_dump_data(text
, (unsigned char *)data
, size
);
595 case CURLINFO_HEADER_IN
:
596 text
= "<= Recv header";
597 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
599 case CURLINFO_DATA_IN
:
600 text
= "<= Recv data";
601 curl_dump_data(text
, (unsigned char *)data
, size
);
603 case CURLINFO_SSL_DATA_IN
:
604 text
= "<= Recv SSL data";
605 curl_dump_data(text
, (unsigned char *)data
, size
);
611 void setup_curl_trace(CURL
*handle
)
613 if (!trace_want(&trace_curl
))
615 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
616 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
617 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
621 static CURL
*get_curl_handle(void)
623 CURL
*result
= curl_easy_init();
624 long allowed_protocols
= 0;
627 die("curl_easy_init failed");
629 if (!curl_ssl_verify
) {
630 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
631 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
633 /* Verify authenticity of the peer's certificate */
634 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
635 /* The name in the cert must match whom we tried to connect */
636 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
639 #if LIBCURL_VERSION_NUM >= 0x070907
640 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
642 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
643 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
646 #if LIBCURL_VERSION_NUM >= 0x071600
649 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
650 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
651 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
652 curl_deleg_levels
[i
].curl_deleg_param
);
656 if (i
== ARRAY_SIZE(curl_deleg_levels
))
657 warning("Unknown delegation method '%s': using default",
662 if (http_proactive_auth
)
663 init_curl_http_auth(result
);
665 if (getenv("GIT_SSL_VERSION"))
666 ssl_version
= getenv("GIT_SSL_VERSION");
667 if (ssl_version
&& *ssl_version
) {
669 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
670 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
671 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
672 sslversions
[i
].ssl_version
);
676 if (i
== ARRAY_SIZE(sslversions
))
677 warning("unsupported ssl version %s: using default",
681 if (getenv("GIT_SSL_CIPHER_LIST"))
682 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
683 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
684 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
687 if (ssl_cert
!= NULL
)
688 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
689 if (has_cert_password())
690 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
691 #if LIBCURL_VERSION_NUM >= 0x070903
693 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
695 #if LIBCURL_VERSION_NUM >= 0x070908
696 if (ssl_capath
!= NULL
)
697 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
699 #if LIBCURL_VERSION_NUM >= 0x072c00
700 if (ssl_pinnedkey
!= NULL
)
701 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
703 if (ssl_cainfo
!= NULL
)
704 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
706 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
707 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
708 curl_low_speed_limit
);
709 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
710 curl_low_speed_time
);
713 curl_easy_setopt(result
, CURLOPT_FOLLOWLOCATION
, 1);
714 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
715 #if LIBCURL_VERSION_NUM >= 0x071301
716 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
717 #elif LIBCURL_VERSION_NUM >= 0x071101
718 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
720 #if LIBCURL_VERSION_NUM >= 0x071304
721 if (is_transport_allowed("http"))
722 allowed_protocols
|= CURLPROTO_HTTP
;
723 if (is_transport_allowed("https"))
724 allowed_protocols
|= CURLPROTO_HTTPS
;
725 if (is_transport_allowed("ftp"))
726 allowed_protocols
|= CURLPROTO_FTP
;
727 if (is_transport_allowed("ftps"))
728 allowed_protocols
|= CURLPROTO_FTPS
;
729 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
731 if (transport_restrict_protocols())
732 warning("protocol restrictions not applied to curl redirects because\n"
733 "your curl version is too old (>= 7.19.4)");
735 if (getenv("GIT_CURL_VERBOSE"))
736 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1L);
737 setup_curl_trace(result
);
739 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
740 user_agent
? user_agent
: git_user_agent());
742 if (curl_ftp_no_epsv
)
743 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
745 #ifdef CURLOPT_USE_SSL
747 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
751 * CURL also examines these variables as a fallback; but we need to query
752 * them here in order to decide whether to prompt for missing password (cf.
753 * init_curl_proxy_auth()).
755 * Unlike many other common environment variables, these are historically
756 * lowercase only. It appears that CURL did not know this and implemented
757 * only uppercase variants, which was later corrected to take both - with
758 * the exception of http_proxy, which is lowercase only also in CURL. As
759 * the lowercase versions are the historical quasi-standard, they take
760 * precedence here, as in CURL.
762 if (!curl_http_proxy
) {
763 if (!strcmp(http_auth
.protocol
, "https")) {
764 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
765 var_override(&curl_http_proxy
, getenv("https_proxy"));
767 var_override(&curl_http_proxy
, getenv("http_proxy"));
769 if (!curl_http_proxy
) {
770 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
771 var_override(&curl_http_proxy
, getenv("all_proxy"));
775 if (curl_http_proxy
) {
776 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
777 #if LIBCURL_VERSION_NUM >= 0x071800
778 if (starts_with(curl_http_proxy
, "socks5h"))
779 curl_easy_setopt(result
,
780 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
781 else if (starts_with(curl_http_proxy
, "socks5"))
782 curl_easy_setopt(result
,
783 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
784 else if (starts_with(curl_http_proxy
, "socks4a"))
785 curl_easy_setopt(result
,
786 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
787 else if (starts_with(curl_http_proxy
, "socks"))
788 curl_easy_setopt(result
,
789 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
791 if (strstr(curl_http_proxy
, "://"))
792 credential_from_url(&proxy_auth
, curl_http_proxy
);
794 struct strbuf url
= STRBUF_INIT
;
795 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
796 credential_from_url(&proxy_auth
, url
.buf
);
797 strbuf_release(&url
);
800 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
801 #if LIBCURL_VERSION_NUM >= 0x071304
802 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
803 var_override(&curl_no_proxy
, getenv("no_proxy"));
804 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
807 init_curl_proxy_auth(result
);
809 set_curl_keepalive(result
);
814 static void set_from_env(const char **var
, const char *envname
)
816 const char *val
= getenv(envname
);
821 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
823 char *low_speed_limit
;
824 char *low_speed_time
;
825 char *normalized_url
;
826 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
828 config
.section
= "http";
830 config
.collect_fn
= http_options
;
831 config
.cascade_fn
= git_default_config
;
835 normalized_url
= url_normalize(url
, &config
.url
);
837 git_config(urlmatch_config_entry
, &config
);
838 free(normalized_url
);
840 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
841 die("curl_global_init failed");
843 http_proactive_auth
= proactive_auth
;
845 if (remote
&& remote
->http_proxy
)
846 curl_http_proxy
= xstrdup(remote
->http_proxy
);
849 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
851 pragma_header
= curl_slist_append(http_copy_default_headers(),
853 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
856 #ifdef USE_CURL_MULTI
858 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
859 if (http_max_requests
!= NULL
)
860 max_requests
= atoi(http_max_requests
);
863 curlm
= curl_multi_init();
865 die("curl_multi_init failed");
868 if (getenv("GIT_SSL_NO_VERIFY"))
871 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
872 #if LIBCURL_VERSION_NUM >= 0x070903
873 set_from_env(&ssl_key
, "GIT_SSL_KEY");
875 #if LIBCURL_VERSION_NUM >= 0x070908
876 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
878 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
880 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
882 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
883 if (low_speed_limit
!= NULL
)
884 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
885 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
886 if (low_speed_time
!= NULL
)
887 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
889 if (curl_ssl_verify
== -1)
892 curl_session_count
= 0;
893 #ifdef USE_CURL_MULTI
894 if (max_requests
< 1)
895 max_requests
= DEFAULT_MAX_REQUESTS
;
898 if (getenv("GIT_CURL_FTP_NO_EPSV"))
899 curl_ftp_no_epsv
= 1;
902 credential_from_url(&http_auth
, url
);
903 if (!ssl_cert_password_required
&&
904 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
905 starts_with(url
, "https://"))
906 ssl_cert_password_required
= 1;
909 #ifndef NO_CURL_EASY_DUPHANDLE
910 curl_default
= get_curl_handle();
914 void http_cleanup(void)
916 struct active_request_slot
*slot
= active_queue_head
;
918 while (slot
!= NULL
) {
919 struct active_request_slot
*next
= slot
->next
;
920 if (slot
->curl
!= NULL
) {
921 #ifdef USE_CURL_MULTI
922 curl_multi_remove_handle(curlm
, slot
->curl
);
924 curl_easy_cleanup(slot
->curl
);
929 active_queue_head
= NULL
;
931 #ifndef NO_CURL_EASY_DUPHANDLE
932 curl_easy_cleanup(curl_default
);
935 #ifdef USE_CURL_MULTI
936 curl_multi_cleanup(curlm
);
938 curl_global_cleanup();
940 curl_slist_free_all(extra_http_headers
);
941 extra_http_headers
= NULL
;
943 curl_slist_free_all(pragma_header
);
944 pragma_header
= NULL
;
946 curl_slist_free_all(no_pragma_header
);
947 no_pragma_header
= NULL
;
949 if (curl_http_proxy
) {
950 free((void *)curl_http_proxy
);
951 curl_http_proxy
= NULL
;
954 if (proxy_auth
.password
) {
955 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
956 free(proxy_auth
.password
);
957 proxy_auth
.password
= NULL
;
960 free((void *)curl_proxyuserpwd
);
961 curl_proxyuserpwd
= NULL
;
963 free((void *)http_proxy_authmethod
);
964 http_proxy_authmethod
= NULL
;
966 if (cert_auth
.password
!= NULL
) {
967 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
968 free(cert_auth
.password
);
969 cert_auth
.password
= NULL
;
971 ssl_cert_password_required
= 0;
973 free(cached_accept_language
);
974 cached_accept_language
= NULL
;
977 struct active_request_slot
*get_active_slot(void)
979 struct active_request_slot
*slot
= active_queue_head
;
980 struct active_request_slot
*newslot
;
982 #ifdef USE_CURL_MULTI
985 /* Wait for a slot to open up if the queue is full */
986 while (active_requests
>= max_requests
) {
987 curl_multi_perform(curlm
, &num_transfers
);
988 if (num_transfers
< active_requests
)
989 process_curl_messages();
993 while (slot
!= NULL
&& slot
->in_use
)
997 newslot
= xmalloc(sizeof(*newslot
));
998 newslot
->curl
= NULL
;
1000 newslot
->next
= NULL
;
1002 slot
= active_queue_head
;
1004 active_queue_head
= newslot
;
1006 while (slot
->next
!= NULL
)
1008 slot
->next
= newslot
;
1013 if (slot
->curl
== NULL
) {
1014 #ifdef NO_CURL_EASY_DUPHANDLE
1015 slot
->curl
= get_curl_handle();
1017 slot
->curl
= curl_easy_duphandle(curl_default
);
1019 curl_session_count
++;
1024 slot
->results
= NULL
;
1025 slot
->finished
= NULL
;
1026 slot
->callback_data
= NULL
;
1027 slot
->callback_func
= NULL
;
1028 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1029 if (curl_save_cookies
)
1030 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1031 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1032 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1033 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1034 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1035 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1036 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1037 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1038 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1039 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1040 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1042 #if LIBCURL_VERSION_NUM >= 0x070a08
1043 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1045 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1046 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1048 if (http_auth
.password
|| curl_empty_auth
)
1049 init_curl_http_auth(slot
->curl
);
1054 int start_active_slot(struct active_request_slot
*slot
)
1056 #ifdef USE_CURL_MULTI
1057 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1060 if (curlm_result
!= CURLM_OK
&&
1061 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1068 * We know there must be something to do, since we just added
1071 curl_multi_perform(curlm
, &num_transfers
);
1076 #ifdef USE_CURL_MULTI
1079 int (*fill
)(void *);
1080 struct fill_chain
*next
;
1083 static struct fill_chain
*fill_cfg
;
1085 void add_fill_function(void *data
, int (*fill
)(void *))
1087 struct fill_chain
*new = xmalloc(sizeof(*new));
1088 struct fill_chain
**linkp
= &fill_cfg
;
1093 linkp
= &(*linkp
)->next
;
1097 void fill_active_slots(void)
1099 struct active_request_slot
*slot
= active_queue_head
;
1101 while (active_requests
< max_requests
) {
1102 struct fill_chain
*fill
;
1103 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1104 if (fill
->fill(fill
->data
))
1111 while (slot
!= NULL
) {
1112 if (!slot
->in_use
&& slot
->curl
!= NULL
1113 && curl_session_count
> min_curl_sessions
) {
1114 curl_easy_cleanup(slot
->curl
);
1116 curl_session_count
--;
1122 void step_active_slots(void)
1125 CURLMcode curlm_result
;
1128 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1129 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1130 if (num_transfers
< active_requests
) {
1131 process_curl_messages();
1132 fill_active_slots();
1137 void run_active_slot(struct active_request_slot
*slot
)
1139 #ifdef USE_CURL_MULTI
1144 struct timeval select_timeout
;
1147 slot
->finished
= &finished
;
1149 step_active_slots();
1152 #if LIBCURL_VERSION_NUM >= 0x070f04
1154 curl_multi_timeout(curlm
, &curl_timeout
);
1155 if (curl_timeout
== 0) {
1157 } else if (curl_timeout
== -1) {
1158 select_timeout
.tv_sec
= 0;
1159 select_timeout
.tv_usec
= 50000;
1161 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1162 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1165 select_timeout
.tv_sec
= 0;
1166 select_timeout
.tv_usec
= 50000;
1173 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1176 * It can happen that curl_multi_timeout returns a pathologically
1177 * long timeout when curl_multi_fdset returns no file descriptors
1178 * to read. See commit message for more details.
1181 (select_timeout
.tv_sec
> 0 ||
1182 select_timeout
.tv_usec
> 50000)) {
1183 select_timeout
.tv_sec
= 0;
1184 select_timeout
.tv_usec
= 50000;
1187 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1191 while (slot
->in_use
) {
1192 slot
->curl_result
= curl_easy_perform(slot
->curl
);
1193 finish_active_slot(slot
);
1198 static void release_active_slot(struct active_request_slot
*slot
)
1200 closedown_active_slot(slot
);
1201 if (slot
->curl
&& curl_session_count
> min_curl_sessions
) {
1202 #ifdef USE_CURL_MULTI
1203 curl_multi_remove_handle(curlm
, slot
->curl
);
1205 curl_easy_cleanup(slot
->curl
);
1207 curl_session_count
--;
1209 #ifdef USE_CURL_MULTI
1210 fill_active_slots();
1214 void finish_all_active_slots(void)
1216 struct active_request_slot
*slot
= active_queue_head
;
1218 while (slot
!= NULL
)
1220 run_active_slot(slot
);
1221 slot
= active_queue_head
;
1227 /* Helpers for modifying and creating URLs */
1228 static inline int needs_quote(int ch
)
1230 if (((ch
>= 'A') && (ch
<= 'Z'))
1231 || ((ch
>= 'a') && (ch
<= 'z'))
1232 || ((ch
>= '0') && (ch
<= '9'))
1240 static char *quote_ref_url(const char *base
, const char *ref
)
1242 struct strbuf buf
= STRBUF_INIT
;
1246 end_url_with_slash(&buf
, base
);
1248 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1249 if (needs_quote(ch
))
1250 strbuf_addf(&buf
, "%%%02x", ch
);
1252 strbuf_addch(&buf
, *cp
);
1254 return strbuf_detach(&buf
, NULL
);
1257 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1259 int only_two_digit_prefix
)
1261 end_url_with_slash(buf
, url
);
1263 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1264 if (!only_two_digit_prefix
)
1265 strbuf_addstr(buf
, hex
+ 2);
1268 char *get_remote_object_url(const char *url
, const char *hex
,
1269 int only_two_digit_prefix
)
1271 struct strbuf buf
= STRBUF_INIT
;
1272 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1273 return strbuf_detach(&buf
, NULL
);
1276 static int handle_curl_result(struct slot_results
*results
)
1279 * If we see a failing http code with CURLE_OK, we have turned off
1280 * FAILONERROR (to keep the server's custom error response), and should
1281 * translate the code into failure here.
1283 if (results
->curl_result
== CURLE_OK
&&
1284 results
->http_code
>= 400) {
1285 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
1287 * Normally curl will already have put the "reason phrase"
1288 * from the server into curl_errorstr; unfortunately without
1289 * FAILONERROR it is lost, so we can give only the numeric
1292 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1293 "The requested URL returned error: %ld",
1294 results
->http_code
);
1297 if (results
->curl_result
== CURLE_OK
) {
1298 credential_approve(&http_auth
);
1299 if (proxy_auth
.password
)
1300 credential_approve(&proxy_auth
);
1302 } else if (missing_target(results
))
1303 return HTTP_MISSING_TARGET
;
1304 else if (results
->http_code
== 401) {
1305 if (http_auth
.username
&& http_auth
.password
) {
1306 credential_reject(&http_auth
);
1309 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1310 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1315 if (results
->http_connectcode
== 407)
1316 credential_reject(&proxy_auth
);
1317 #if LIBCURL_VERSION_NUM >= 0x070c00
1318 if (!curl_errorstr
[0])
1319 strlcpy(curl_errorstr
,
1320 curl_easy_strerror(results
->curl_result
),
1321 sizeof(curl_errorstr
));
1327 int run_one_slot(struct active_request_slot
*slot
,
1328 struct slot_results
*results
)
1330 slot
->results
= results
;
1331 if (!start_active_slot(slot
)) {
1332 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
1333 "failed to start HTTP request");
1334 return HTTP_START_FAILED
;
1337 run_active_slot(slot
);
1338 return handle_curl_result(results
);
1341 struct curl_slist
*http_copy_default_headers(void)
1343 struct curl_slist
*headers
= NULL
, *h
;
1345 for (h
= extra_http_headers
; h
; h
= h
->next
)
1346 headers
= curl_slist_append(headers
, h
->data
);
1351 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1357 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1359 strbuf_addstr(buf
, ptr
);
1364 * Check for and extract a content-type parameter. "raw"
1365 * should be positioned at the start of the potential
1366 * parameter, with any whitespace already removed.
1368 * "name" is the name of the parameter. The value is appended
1371 static int extract_param(const char *raw
, const char *name
,
1374 size_t len
= strlen(name
);
1376 if (strncasecmp(raw
, name
, len
))
1384 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1385 strbuf_addch(out
, *raw
++);
1390 * Extract a normalized version of the content type, with any
1391 * spaces suppressed, all letters lowercased, and no trailing ";"
1394 * Note that we will silently remove even invalid whitespace. For
1395 * example, "text / plain" is specifically forbidden by RFC 2616,
1396 * but "text/plain" is the only reasonable output, and this keeps
1399 * If the "charset" argument is not NULL, store the value of any
1400 * charset parameter there.
1403 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1404 * "text / plain" -> "text/plain"
1406 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1407 struct strbuf
*charset
)
1412 strbuf_grow(type
, raw
->len
);
1413 for (p
= raw
->buf
; *p
; p
++) {
1420 strbuf_addch(type
, tolower(*p
));
1426 strbuf_reset(charset
);
1428 while (isspace(*p
) || *p
== ';')
1430 if (!extract_param(p
, "charset", charset
))
1432 while (*p
&& !isspace(*p
))
1436 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1437 strbuf_addstr(charset
, "ISO-8859-1");
1440 static void write_accept_language(struct strbuf
*buf
)
1443 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1444 * that, q-value will be smaller than 0.001, the minimum q-value the
1445 * HTTP specification allows. See
1446 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1448 const int MAX_DECIMAL_PLACES
= 3;
1449 const int MAX_LANGUAGE_TAGS
= 1000;
1450 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1451 char **language_tags
= NULL
;
1453 const char *s
= get_preferred_languages();
1455 struct strbuf tag
= STRBUF_INIT
;
1457 /* Don't add Accept-Language header if no language is preferred. */
1462 * Split the colon-separated string of preferred languages into
1463 * language_tags array.
1466 /* collect language tag */
1467 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1468 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1470 /* skip .codeset, @modifier and any other unnecessary parts */
1471 while (*s
&& *s
!= ':')
1476 REALLOC_ARRAY(language_tags
, num_langs
);
1477 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1478 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1483 /* write Accept-Language header into buf */
1485 int last_buf_len
= 0;
1491 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1492 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1494 /* compute decimal_places */
1495 for (max_q
= 1, decimal_places
= 0;
1496 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1497 decimal_places
++, max_q
*= 10)
1500 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1502 strbuf_addstr(buf
, "Accept-Language: ");
1504 for (i
= 0; i
< num_langs
; i
++) {
1506 strbuf_addstr(buf
, ", ");
1508 strbuf_addstr(buf
, language_tags
[i
]);
1511 strbuf_addf(buf
, q_format
, max_q
- i
);
1513 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1514 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1518 last_buf_len
= buf
->len
;
1522 /* free language tags -- last one is a static '*' */
1523 for (i
= 0; i
< num_langs
- 1; i
++)
1524 free(language_tags
[i
]);
1525 free(language_tags
);
1529 * Get an Accept-Language header which indicates user's preferred languages.
1533 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1534 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1535 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1536 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1537 * LANGUAGE= LANG=C -> ""
1539 static const char *get_accept_language(void)
1541 if (!cached_accept_language
) {
1542 struct strbuf buf
= STRBUF_INIT
;
1543 write_accept_language(&buf
);
1545 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1548 return cached_accept_language
;
1551 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1554 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1555 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1558 /* http_request() targets */
1559 #define HTTP_REQUEST_STRBUF 0
1560 #define HTTP_REQUEST_FILE 1
1562 static int http_request(const char *url
,
1563 void *result
, int target
,
1564 const struct http_get_options
*options
)
1566 struct active_request_slot
*slot
;
1567 struct slot_results results
;
1568 struct curl_slist
*headers
= http_copy_default_headers();
1569 struct strbuf buf
= STRBUF_INIT
;
1570 const char *accept_language
;
1573 slot
= get_active_slot();
1574 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1576 if (result
== NULL
) {
1577 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1579 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1580 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1582 if (target
== HTTP_REQUEST_FILE
) {
1583 off_t posn
= ftello(result
);
1584 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1587 http_opt_request_remainder(slot
->curl
, posn
);
1589 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1593 accept_language
= get_accept_language();
1595 if (accept_language
)
1596 headers
= curl_slist_append(headers
, accept_language
);
1598 strbuf_addstr(&buf
, "Pragma:");
1599 if (options
&& options
->no_cache
)
1600 strbuf_addstr(&buf
, " no-cache");
1601 if (options
&& options
->keep_error
)
1602 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1604 headers
= curl_slist_append(headers
, buf
.buf
);
1606 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1607 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1608 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1610 ret
= run_one_slot(slot
, &results
);
1612 if (options
&& options
->content_type
) {
1613 struct strbuf raw
= STRBUF_INIT
;
1614 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1615 extract_content_type(&raw
, options
->content_type
,
1617 strbuf_release(&raw
);
1620 if (options
&& options
->effective_url
)
1621 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1622 options
->effective_url
);
1624 curl_slist_free_all(headers
);
1625 strbuf_release(&buf
);
1631 * Update the "base" url to a more appropriate value, as deduced by
1632 * redirects seen when requesting a URL starting with "url".
1634 * The "asked" parameter is a URL that we asked curl to access, and must begin
1637 * The "got" parameter is the URL that curl reported to us as where we ended
1640 * Returns 1 if we updated the base url, 0 otherwise.
1642 * Our basic strategy is to compare "base" and "asked" to find the bits
1643 * specific to our request. We then strip those bits off of "got" to yield the
1644 * new base. So for example, if our base is "http://example.com/foo.git",
1645 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1646 * with "https://other.example.com/foo.git/info/refs". We would want the
1647 * new URL to become "https://other.example.com/foo.git".
1649 * Note that this assumes a sane redirect scheme. It's entirely possible
1650 * in the example above to end up at a URL that does not even end in
1651 * "info/refs". In such a case we simply punt, as there is not much we can
1652 * do (and such a scheme is unlikely to represent a real git repository,
1653 * which means we are likely about to abort anyway).
1655 static int update_url_from_redirect(struct strbuf
*base
,
1657 const struct strbuf
*got
)
1662 if (!strcmp(asked
, got
->buf
))
1665 if (!skip_prefix(asked
, base
->buf
, &tail
))
1666 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1669 tail_len
= strlen(tail
);
1671 if (got
->len
< tail_len
||
1672 strcmp(tail
, got
->buf
+ got
->len
- tail_len
))
1673 return 0; /* insane redirect scheme */
1676 strbuf_add(base
, got
->buf
, got
->len
- tail_len
);
1680 static int http_request_reauth(const char *url
,
1681 void *result
, int target
,
1682 struct http_get_options
*options
)
1684 int ret
= http_request(url
, result
, target
, options
);
1686 if (options
&& options
->effective_url
&& options
->base_url
) {
1687 if (update_url_from_redirect(options
->base_url
,
1688 url
, options
->effective_url
)) {
1689 credential_from_url(&http_auth
, options
->base_url
->buf
);
1690 url
= options
->effective_url
->buf
;
1694 if (ret
!= HTTP_REAUTH
)
1698 * If we are using KEEP_ERROR, the previous request may have
1699 * put cruft into our output stream; we should clear it out before
1700 * making our next request. We only know how to do this for
1701 * the strbuf case, but that is enough to satisfy current callers.
1703 if (options
&& options
->keep_error
) {
1705 case HTTP_REQUEST_STRBUF
:
1706 strbuf_reset(result
);
1709 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1713 credential_fill(&http_auth
);
1715 return http_request(url
, result
, target
, options
);
1718 int http_get_strbuf(const char *url
,
1719 struct strbuf
*result
,
1720 struct http_get_options
*options
)
1722 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1726 * Downloads a URL and stores the result in the given file.
1728 * If a previous interrupted download is detected (i.e. a previous temporary
1729 * file is still around) the download is resumed.
1731 static int http_get_file(const char *url
, const char *filename
,
1732 struct http_get_options
*options
)
1735 struct strbuf tmpfile
= STRBUF_INIT
;
1738 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1739 result
= fopen(tmpfile
.buf
, "a");
1741 error("Unable to open local file %s", tmpfile
.buf
);
1746 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1749 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1752 strbuf_release(&tmpfile
);
1756 int http_fetch_ref(const char *base
, struct ref
*ref
)
1758 struct http_get_options options
= {0};
1760 struct strbuf buffer
= STRBUF_INIT
;
1763 options
.no_cache
= 1;
1765 url
= quote_ref_url(base
, ref
->name
);
1766 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1767 strbuf_rtrim(&buffer
);
1768 if (buffer
.len
== 40)
1769 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
1770 else if (starts_with(buffer
.buf
, "ref: ")) {
1771 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1776 strbuf_release(&buffer
);
1781 /* Helpers for fetching packs */
1782 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1785 struct strbuf buf
= STRBUF_INIT
;
1787 if (http_is_verbose
)
1788 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1790 end_url_with_slash(&buf
, base_url
);
1791 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1792 url
= strbuf_detach(&buf
, NULL
);
1794 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1795 tmp
= strbuf_detach(&buf
, NULL
);
1797 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1798 error("Unable to get pack index %s", url
);
1807 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1808 unsigned char *sha1
, const char *base_url
)
1810 struct packed_git
*new_pack
;
1811 char *tmp_idx
= NULL
;
1814 if (has_pack_index(sha1
)) {
1815 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1817 return -1; /* parse_pack_index() already issued error message */
1821 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1825 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1830 return -1; /* parse_pack_index() already issued error message */
1833 ret
= verify_pack_index(new_pack
);
1835 close_pack_index(new_pack
);
1836 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1843 new_pack
->next
= *packs_head
;
1844 *packs_head
= new_pack
;
1848 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1850 struct http_get_options options
= {0};
1853 struct strbuf buf
= STRBUF_INIT
;
1854 unsigned char sha1
[20];
1856 end_url_with_slash(&buf
, base_url
);
1857 strbuf_addstr(&buf
, "objects/info/packs");
1858 url
= strbuf_detach(&buf
, NULL
);
1860 options
.no_cache
= 1;
1861 ret
= http_get_strbuf(url
, &buf
, &options
);
1866 while (i
< buf
.len
) {
1870 if (i
+ 52 <= buf
.len
&&
1871 starts_with(data
+ i
, " pack-") &&
1872 starts_with(data
+ i
+ 46, ".pack\n")) {
1873 get_sha1_hex(data
+ i
+ 6, sha1
);
1874 fetch_and_setup_pack_index(packs_head
, sha1
,
1880 while (i
< buf
.len
&& data
[i
] != '\n')
1891 void release_http_pack_request(struct http_pack_request
*preq
)
1893 if (preq
->packfile
!= NULL
) {
1894 fclose(preq
->packfile
);
1895 preq
->packfile
= NULL
;
1902 int finish_http_pack_request(struct http_pack_request
*preq
)
1904 struct packed_git
**lst
;
1905 struct packed_git
*p
= preq
->target
;
1908 struct child_process ip
= CHILD_PROCESS_INIT
;
1909 const char *ip_argv
[8];
1911 close_pack_index(p
);
1913 fclose(preq
->packfile
);
1914 preq
->packfile
= NULL
;
1918 lst
= &((*lst
)->next
);
1919 *lst
= (*lst
)->next
;
1921 if (!strip_suffix(preq
->tmpfile
, ".pack.temp", &len
))
1922 die("BUG: pack tmpfile does not end in .pack.temp?");
1923 tmp_idx
= xstrfmt("%.*s.idx.temp", (int)len
, preq
->tmpfile
);
1925 ip_argv
[0] = "index-pack";
1927 ip_argv
[2] = tmp_idx
;
1928 ip_argv
[3] = preq
->tmpfile
;
1936 if (run_command(&ip
)) {
1937 unlink(preq
->tmpfile
);
1943 unlink(sha1_pack_index_name(p
->sha1
));
1945 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1946 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1951 install_packed_git(p
);
1956 struct http_pack_request
*new_http_pack_request(
1957 struct packed_git
*target
, const char *base_url
)
1959 off_t prev_posn
= 0;
1960 struct strbuf buf
= STRBUF_INIT
;
1961 struct http_pack_request
*preq
;
1963 preq
= xcalloc(1, sizeof(*preq
));
1964 preq
->target
= target
;
1966 end_url_with_slash(&buf
, base_url
);
1967 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1968 sha1_to_hex(target
->sha1
));
1969 preq
->url
= strbuf_detach(&buf
, NULL
);
1971 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1972 sha1_pack_name(target
->sha1
));
1973 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1974 if (!preq
->packfile
) {
1975 error("Unable to open local file %s for pack",
1980 preq
->slot
= get_active_slot();
1981 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1982 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1983 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1984 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1988 * If there is data present from a previous transfer attempt,
1989 * resume where it left off
1991 prev_posn
= ftello(preq
->packfile
);
1993 if (http_is_verbose
)
1995 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
1996 sha1_to_hex(target
->sha1
), (uintmax_t)prev_posn
);
1997 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2008 /* Helpers for fetching objects (loose) */
2009 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2012 unsigned char expn
[4096];
2013 size_t size
= eltsize
* nmemb
;
2015 struct http_object_request
*freq
= data
;
2016 struct active_request_slot
*slot
= freq
->slot
;
2019 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2022 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2023 curl_easy_strerror(c
));
2024 if (slot
->http_code
>= 400)
2029 ssize_t retval
= xwrite(freq
->localfile
,
2030 (char *) ptr
+ posn
, size
- posn
);
2034 } while (posn
< size
);
2036 freq
->stream
.avail_in
= size
;
2037 freq
->stream
.next_in
= (void *)ptr
;
2039 freq
->stream
.next_out
= expn
;
2040 freq
->stream
.avail_out
= sizeof(expn
);
2041 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2042 git_SHA1_Update(&freq
->c
, expn
,
2043 sizeof(expn
) - freq
->stream
.avail_out
);
2044 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2048 struct http_object_request
*new_http_object_request(const char *base_url
,
2049 unsigned char *sha1
)
2051 char *hex
= sha1_to_hex(sha1
);
2052 const char *filename
;
2053 char prevfile
[PATH_MAX
];
2055 char prev_buf
[PREV_BUF_SIZE
];
2056 ssize_t prev_read
= 0;
2057 off_t prev_posn
= 0;
2058 struct http_object_request
*freq
;
2060 freq
= xcalloc(1, sizeof(*freq
));
2061 hashcpy(freq
->sha1
, sha1
);
2062 freq
->localfile
= -1;
2064 filename
= sha1_file_name(sha1
);
2065 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
2066 "%s.temp", filename
);
2068 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
2069 unlink_or_warn(prevfile
);
2070 rename(freq
->tmpfile
, prevfile
);
2071 unlink_or_warn(freq
->tmpfile
);
2073 if (freq
->localfile
!= -1)
2074 error("fd leakage in start: %d", freq
->localfile
);
2075 freq
->localfile
= open(freq
->tmpfile
,
2076 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2078 * This could have failed due to the "lazy directory creation";
2079 * try to mkdir the last path component.
2081 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2082 char *dir
= strrchr(freq
->tmpfile
, '/');
2085 mkdir(freq
->tmpfile
, 0777);
2088 freq
->localfile
= open(freq
->tmpfile
,
2089 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2092 if (freq
->localfile
< 0) {
2093 error_errno("Couldn't create temporary file %s", freq
->tmpfile
);
2097 git_inflate_init(&freq
->stream
);
2099 git_SHA1_Init(&freq
->c
);
2101 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2104 * If a previous temp file is present, process what was already
2107 prevlocal
= open(prevfile
, O_RDONLY
);
2108 if (prevlocal
!= -1) {
2110 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2112 if (fwrite_sha1_file(prev_buf
,
2115 freq
) == prev_read
) {
2116 prev_posn
+= prev_read
;
2121 } while (prev_read
> 0);
2124 unlink_or_warn(prevfile
);
2127 * Reset inflate/SHA1 if there was an error reading the previous temp
2128 * file; also rewind to the beginning of the local file.
2130 if (prev_read
== -1) {
2131 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2132 git_inflate_init(&freq
->stream
);
2133 git_SHA1_Init(&freq
->c
);
2136 lseek(freq
->localfile
, 0, SEEK_SET
);
2137 if (ftruncate(freq
->localfile
, 0) < 0) {
2138 error_errno("Couldn't truncate temporary file %s",
2145 freq
->slot
= get_active_slot();
2147 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
2148 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2149 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2150 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2151 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2152 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2155 * If we have successfully processed data from a previous fetch
2156 * attempt, only fetch the data we don't already have.
2159 if (http_is_verbose
)
2161 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2162 hex
, (uintmax_t)prev_posn
);
2163 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2174 void process_http_object_request(struct http_object_request
*freq
)
2176 if (freq
->slot
== NULL
)
2178 freq
->curl_result
= freq
->slot
->curl_result
;
2179 freq
->http_code
= freq
->slot
->http_code
;
2183 int finish_http_object_request(struct http_object_request
*freq
)
2187 close(freq
->localfile
);
2188 freq
->localfile
= -1;
2190 process_http_object_request(freq
);
2192 if (freq
->http_code
== 416) {
2193 warning("requested range invalid; we may already have all the data.");
2194 } else if (freq
->curl_result
!= CURLE_OK
) {
2195 if (stat(freq
->tmpfile
, &st
) == 0)
2196 if (st
.st_size
== 0)
2197 unlink_or_warn(freq
->tmpfile
);
2201 git_inflate_end(&freq
->stream
);
2202 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
2203 if (freq
->zret
!= Z_STREAM_END
) {
2204 unlink_or_warn(freq
->tmpfile
);
2207 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
2208 unlink_or_warn(freq
->tmpfile
);
2212 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
2214 return freq
->rename
;
2217 void abort_http_object_request(struct http_object_request
*freq
)
2219 unlink_or_warn(freq
->tmpfile
);
2221 release_http_object_request(freq
);
2224 void release_http_object_request(struct http_object_request
*freq
)
2226 if (freq
->localfile
!= -1) {
2227 close(freq
->localfile
);
2228 freq
->localfile
= -1;
2230 if (freq
->url
!= NULL
) {
2234 if (freq
->slot
!= NULL
) {
2235 freq
->slot
->callback_func
= NULL
;
2236 freq
->slot
->callback_data
= NULL
;
2237 release_active_slot(freq
->slot
);