1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
7 #include "run-command.h"
10 #include "credential.h"
14 #include "transport.h"
17 #include "string-list.h"
18 #include "object-store.h"
20 static struct trace_key trace_curl
= TRACE_KEY_INIT(CURL
);
21 static int trace_curl_data
= 1;
22 static int trace_curl_redact
= 1;
23 long int git_curl_ipresolve
= CURL_IPRESOLVE_WHATEVER
;
26 ssize_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
28 static int min_curl_sessions
= 1;
29 static int curl_session_count
;
30 static int max_requests
= -1;
32 static CURL
*curl_default
;
34 #define PREV_BUF_SIZE 4096
36 char curl_errorstr
[CURL_ERROR_SIZE
];
38 static int curl_ssl_verify
= -1;
39 static int curl_ssl_try
;
40 static const char *curl_http_version
= NULL
;
41 static const char *ssl_cert
;
42 static const char *ssl_cipherlist
;
43 static const char *ssl_version
;
48 { "sslv2", CURL_SSLVERSION_SSLv2
},
49 { "sslv3", CURL_SSLVERSION_SSLv3
},
50 { "tlsv1", CURL_SSLVERSION_TLSv1
},
51 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
52 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
53 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
54 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
56 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
57 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3
},
60 static const char *ssl_key
;
61 static const char *ssl_capath
;
62 static const char *curl_no_proxy
;
63 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
64 static const char *ssl_pinnedkey
;
66 static const char *ssl_cainfo
;
67 static long curl_low_speed_limit
= -1;
68 static long curl_low_speed_time
= -1;
69 static int curl_ftp_no_epsv
;
70 static const char *curl_http_proxy
;
71 static const char *http_proxy_authmethod
;
73 static const char *http_proxy_ssl_cert
;
74 static const char *http_proxy_ssl_key
;
75 static const char *http_proxy_ssl_ca_info
;
76 static struct credential proxy_cert_auth
= CREDENTIAL_INIT
;
77 static int proxy_ssl_cert_password_required
;
82 } proxy_authmethods
[] = {
83 { "basic", CURLAUTH_BASIC
},
84 { "digest", CURLAUTH_DIGEST
},
85 { "negotiate", CURLAUTH_GSSNEGOTIATE
},
86 { "ntlm", CURLAUTH_NTLM
},
87 { "anyauth", CURLAUTH_ANY
},
89 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
90 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
94 #ifdef CURLGSSAPI_DELEGATION_FLAG
95 static const char *curl_deleg
;
98 long curl_deleg_param
;
99 } curl_deleg_levels
[] = {
100 { "none", CURLGSSAPI_DELEGATION_NONE
},
101 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG
},
102 { "always", CURLGSSAPI_DELEGATION_FLAG
},
106 static struct credential proxy_auth
= CREDENTIAL_INIT
;
107 static const char *curl_proxyuserpwd
;
108 static const char *curl_cookie_file
;
109 static int curl_save_cookies
;
110 struct credential http_auth
= CREDENTIAL_INIT
;
111 static int http_proactive_auth
;
112 static const char *user_agent
;
113 static int curl_empty_auth
= -1;
115 enum http_follow_config http_follow_config
= HTTP_FOLLOW_INITIAL
;
117 static struct credential cert_auth
= CREDENTIAL_INIT
;
118 static int ssl_cert_password_required
;
119 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
120 static int http_auth_methods_restricted
;
121 /* Modes for which empty_auth cannot actually help us. */
122 static unsigned long empty_auth_useless
=
127 static struct curl_slist
*pragma_header
;
128 static struct curl_slist
*no_pragma_header
;
129 static struct string_list extra_http_headers
= STRING_LIST_INIT_DUP
;
131 static struct curl_slist
*host_resolutions
;
133 static struct active_request_slot
*active_queue_head
;
135 static char *cached_accept_language
;
137 static char *http_ssl_backend
;
139 static int http_schannel_check_revoke
= 1;
141 * With the backend being set to `schannel`, setting sslCAinfo would override
142 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
145 static int http_schannel_use_ssl_cainfo
;
147 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
149 size_t size
= eltsize
* nmemb
;
150 struct buffer
*buffer
= buffer_
;
152 if (size
> buffer
->buf
.len
- buffer
->posn
)
153 size
= buffer
->buf
.len
- buffer
->posn
;
154 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
155 buffer
->posn
+= size
;
157 return size
/ eltsize
;
160 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
162 struct buffer
*buffer
= clientp
;
168 case CURLIOCMD_RESTARTREAD
:
173 return CURLIOE_UNKNOWNCMD
;
177 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
179 size_t size
= eltsize
* nmemb
;
180 struct strbuf
*buffer
= buffer_
;
182 strbuf_add(buffer
, ptr
, size
);
186 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
191 static void closedown_active_slot(struct active_request_slot
*slot
)
197 static void finish_active_slot(struct active_request_slot
*slot
)
199 closedown_active_slot(slot
);
200 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
203 (*slot
->finished
) = 1;
205 /* Store slot results so they can be read after the slot is reused */
207 slot
->results
->curl_result
= slot
->curl_result
;
208 slot
->results
->http_code
= slot
->http_code
;
209 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
210 &slot
->results
->auth_avail
);
212 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CONNECTCODE
,
213 &slot
->results
->http_connectcode
);
216 /* Run callback if appropriate */
217 if (slot
->callback_func
)
218 slot
->callback_func(slot
->callback_data
);
221 static void xmulti_remove_handle(struct active_request_slot
*slot
)
223 curl_multi_remove_handle(curlm
, slot
->curl
);
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
);
254 static int http_options(const char *var
, const char *value
, void *cb
)
256 if (!strcmp("http.version", var
)) {
257 return git_config_string(&curl_http_version
, var
, value
);
259 if (!strcmp("http.sslverify", var
)) {
260 curl_ssl_verify
= git_config_bool(var
, value
);
263 if (!strcmp("http.sslcipherlist", var
))
264 return git_config_string(&ssl_cipherlist
, var
, value
);
265 if (!strcmp("http.sslversion", var
))
266 return git_config_string(&ssl_version
, var
, value
);
267 if (!strcmp("http.sslcert", var
))
268 return git_config_pathname(&ssl_cert
, var
, value
);
269 if (!strcmp("http.sslkey", var
))
270 return git_config_pathname(&ssl_key
, var
, value
);
271 if (!strcmp("http.sslcapath", var
))
272 return git_config_pathname(&ssl_capath
, var
, value
);
273 if (!strcmp("http.sslcainfo", var
))
274 return git_config_pathname(&ssl_cainfo
, var
, value
);
275 if (!strcmp("http.sslcertpasswordprotected", var
)) {
276 ssl_cert_password_required
= git_config_bool(var
, value
);
279 if (!strcmp("http.ssltry", var
)) {
280 curl_ssl_try
= git_config_bool(var
, value
);
283 if (!strcmp("http.sslbackend", var
)) {
284 free(http_ssl_backend
);
285 http_ssl_backend
= xstrdup_or_null(value
);
289 if (!strcmp("http.schannelcheckrevoke", var
)) {
290 http_schannel_check_revoke
= git_config_bool(var
, value
);
294 if (!strcmp("http.schannelusesslcainfo", var
)) {
295 http_schannel_use_ssl_cainfo
= git_config_bool(var
, value
);
299 if (!strcmp("http.minsessions", var
)) {
300 min_curl_sessions
= git_config_int(var
, value
);
301 if (min_curl_sessions
> 1)
302 min_curl_sessions
= 1;
305 if (!strcmp("http.maxrequests", var
)) {
306 max_requests
= git_config_int(var
, value
);
309 if (!strcmp("http.lowspeedlimit", var
)) {
310 curl_low_speed_limit
= (long)git_config_int(var
, value
);
313 if (!strcmp("http.lowspeedtime", var
)) {
314 curl_low_speed_time
= (long)git_config_int(var
, value
);
318 if (!strcmp("http.noepsv", var
)) {
319 curl_ftp_no_epsv
= git_config_bool(var
, value
);
322 if (!strcmp("http.proxy", var
))
323 return git_config_string(&curl_http_proxy
, var
, value
);
325 if (!strcmp("http.proxyauthmethod", var
))
326 return git_config_string(&http_proxy_authmethod
, var
, value
);
328 if (!strcmp("http.proxysslcert", var
))
329 return git_config_string(&http_proxy_ssl_cert
, var
, value
);
331 if (!strcmp("http.proxysslkey", var
))
332 return git_config_string(&http_proxy_ssl_key
, var
, value
);
334 if (!strcmp("http.proxysslcainfo", var
))
335 return git_config_string(&http_proxy_ssl_ca_info
, var
, value
);
337 if (!strcmp("http.proxysslcertpasswordprotected", var
)) {
338 proxy_ssl_cert_password_required
= git_config_bool(var
, value
);
342 if (!strcmp("http.cookiefile", var
))
343 return git_config_pathname(&curl_cookie_file
, var
, value
);
344 if (!strcmp("http.savecookies", var
)) {
345 curl_save_cookies
= git_config_bool(var
, value
);
349 if (!strcmp("http.postbuffer", var
)) {
350 http_post_buffer
= git_config_ssize_t(var
, value
);
351 if (http_post_buffer
< 0)
352 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX
);
353 if (http_post_buffer
< LARGE_PACKET_MAX
)
354 http_post_buffer
= LARGE_PACKET_MAX
;
358 if (!strcmp("http.useragent", var
))
359 return git_config_string(&user_agent
, var
, value
);
361 if (!strcmp("http.emptyauth", var
)) {
362 if (value
&& !strcmp("auto", value
))
363 curl_empty_auth
= -1;
365 curl_empty_auth
= git_config_bool(var
, value
);
369 if (!strcmp("http.delegation", var
)) {
370 #ifdef CURLGSSAPI_DELEGATION_FLAG
371 return git_config_string(&curl_deleg
, var
, value
);
373 warning(_("Delegation control is not supported with cURL < 7.22.0"));
378 if (!strcmp("http.pinnedpubkey", var
)) {
379 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
380 return git_config_pathname(&ssl_pinnedkey
, var
, value
);
382 warning(_("Public key pinning not supported with cURL < 7.39.0"));
387 if (!strcmp("http.extraheader", var
)) {
389 return config_error_nonbool(var
);
390 } else if (!*value
) {
391 string_list_clear(&extra_http_headers
, 0);
393 string_list_append(&extra_http_headers
, value
);
398 if (!strcmp("http.curloptresolve", var
)) {
400 return config_error_nonbool(var
);
401 } else if (!*value
) {
402 curl_slist_free_all(host_resolutions
);
403 host_resolutions
= NULL
;
405 host_resolutions
= curl_slist_append(host_resolutions
, value
);
410 if (!strcmp("http.followredirects", var
)) {
411 if (value
&& !strcmp(value
, "initial"))
412 http_follow_config
= HTTP_FOLLOW_INITIAL
;
413 else if (git_config_bool(var
, value
))
414 http_follow_config
= HTTP_FOLLOW_ALWAYS
;
416 http_follow_config
= HTTP_FOLLOW_NONE
;
420 /* Fall back on the default ones */
421 return git_default_config(var
, value
, cb
);
424 static int curl_empty_auth_enabled(void)
426 if (curl_empty_auth
>= 0)
427 return curl_empty_auth
;
430 * In the automatic case, kick in the empty-auth
431 * hack as long as we would potentially try some
432 * method more exotic than "Basic" or "Digest".
434 * But only do this when this is our second or
435 * subsequent request, as by then we know what
436 * methods are available.
438 if (http_auth_methods_restricted
&&
439 (http_auth_methods
& ~empty_auth_useless
))
444 static void init_curl_http_auth(CURL
*result
)
446 if (!http_auth
.username
|| !*http_auth
.username
) {
447 if (curl_empty_auth_enabled())
448 curl_easy_setopt(result
, CURLOPT_USERPWD
, ":");
452 credential_fill(&http_auth
);
454 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
455 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
458 /* *var must be free-able */
459 static void var_override(const char **var
, char *value
)
463 *var
= xstrdup(value
);
467 static void set_proxyauth_name_password(CURL
*result
)
469 curl_easy_setopt(result
, CURLOPT_PROXYUSERNAME
,
470 proxy_auth
.username
);
471 curl_easy_setopt(result
, CURLOPT_PROXYPASSWORD
,
472 proxy_auth
.password
);
475 static void init_curl_proxy_auth(CURL
*result
)
477 if (proxy_auth
.username
) {
478 if (!proxy_auth
.password
)
479 credential_fill(&proxy_auth
);
480 set_proxyauth_name_password(result
);
483 var_override(&http_proxy_authmethod
, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
485 if (http_proxy_authmethod
) {
487 for (i
= 0; i
< ARRAY_SIZE(proxy_authmethods
); i
++) {
488 if (!strcmp(http_proxy_authmethod
, proxy_authmethods
[i
].name
)) {
489 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
,
490 proxy_authmethods
[i
].curlauth_param
);
494 if (i
== ARRAY_SIZE(proxy_authmethods
)) {
495 warning("unsupported proxy authentication method %s: using anyauth",
496 http_proxy_authmethod
);
497 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
501 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
504 static int has_cert_password(void)
506 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
508 if (!cert_auth
.password
) {
509 cert_auth
.protocol
= xstrdup("cert");
510 cert_auth
.host
= xstrdup("");
511 cert_auth
.username
= xstrdup("");
512 cert_auth
.path
= xstrdup(ssl_cert
);
513 credential_fill(&cert_auth
);
518 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
519 static int has_proxy_cert_password(void)
521 if (http_proxy_ssl_cert
== NULL
|| proxy_ssl_cert_password_required
!= 1)
523 if (!proxy_cert_auth
.password
) {
524 proxy_cert_auth
.protocol
= xstrdup("cert");
525 proxy_cert_auth
.host
= xstrdup("");
526 proxy_cert_auth
.username
= xstrdup("");
527 proxy_cert_auth
.path
= xstrdup(http_proxy_ssl_cert
);
528 credential_fill(&proxy_cert_auth
);
534 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
535 static void set_curl_keepalive(CURL
*c
)
537 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
541 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
545 socklen_t len
= (socklen_t
)sizeof(ka
);
547 if (type
!= CURLSOCKTYPE_IPCXN
)
550 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
552 warning_errno("unable to set SO_KEEPALIVE on socket");
554 return CURL_SOCKOPT_OK
;
557 static void set_curl_keepalive(CURL
*c
)
559 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
563 /* Return 1 if redactions have been made, 0 otherwise. */
564 static int redact_sensitive_header(struct strbuf
*header
, size_t offset
)
567 const char *sensitive_header
;
569 if (trace_curl_redact
&&
570 (skip_iprefix(header
->buf
+ offset
, "Authorization:", &sensitive_header
) ||
571 skip_iprefix(header
->buf
+ offset
, "Proxy-Authorization:", &sensitive_header
))) {
572 /* The first token is the type, which is OK to log */
573 while (isspace(*sensitive_header
))
575 while (*sensitive_header
&& !isspace(*sensitive_header
))
577 /* Everything else is opaque and possibly sensitive */
578 strbuf_setlen(header
, sensitive_header
- header
->buf
);
579 strbuf_addstr(header
, " <redacted>");
581 } else if (trace_curl_redact
&&
582 skip_iprefix(header
->buf
+ offset
, "Cookie:", &sensitive_header
)) {
583 struct strbuf redacted_header
= STRBUF_INIT
;
586 while (isspace(*sensitive_header
))
589 cookie
= sensitive_header
;
593 char *semicolon
= strstr(cookie
, "; ");
596 equals
= strchrnul(cookie
, '=');
598 /* invalid cookie, just append and continue */
599 strbuf_addstr(&redacted_header
, cookie
);
602 strbuf_add(&redacted_header
, cookie
, equals
- cookie
);
603 strbuf_addstr(&redacted_header
, "=<redacted>");
606 * There are more cookies. (Or, for some
607 * reason, the input string ends in "; ".)
609 strbuf_addstr(&redacted_header
, "; ");
610 cookie
= semicolon
+ strlen("; ");
616 strbuf_setlen(header
, sensitive_header
- header
->buf
);
617 strbuf_addbuf(header
, &redacted_header
);
623 static int match_curl_h2_trace(const char *line
, const char **out
)
628 * curl prior to 8.1.0 gives us:
630 * h2h3 [<header-name>: <header-val>]
632 * Starting in 8.1.0, the first token became just "h2".
634 if (skip_iprefix(line
, "h2h3 [", out
) ||
635 skip_iprefix(line
, "h2 [", out
))
640 * [HTTP/2] [<stream-id>] [<header-name>: <header-val>]
641 * where <stream-id> is numeric.
643 if (skip_iprefix(line
, "[HTTP/2] [", &p
)) {
646 if (skip_prefix(p
, "] [", out
))
653 /* Redact headers in info */
654 static void redact_sensitive_info_header(struct strbuf
*header
)
656 const char *sensitive_header
;
658 if (trace_curl_redact
&&
659 match_curl_h2_trace(header
->buf
, &sensitive_header
)) {
660 if (redact_sensitive_header(header
, sensitive_header
- header
->buf
)) {
661 /* redaction ate our closing bracket */
662 strbuf_addch(header
, ']');
667 static void curl_dump_header(const char *text
, unsigned char *ptr
, size_t size
, int hide_sensitive_header
)
669 struct strbuf out
= STRBUF_INIT
;
670 struct strbuf
**headers
, **header
;
672 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
673 text
, (long)size
, (long)size
);
674 trace_strbuf(&trace_curl
, &out
);
676 strbuf_add(&out
, ptr
, size
);
677 headers
= strbuf_split_max(&out
, '\n', 0);
679 for (header
= headers
; *header
; header
++) {
680 if (hide_sensitive_header
)
681 redact_sensitive_header(*header
, 0);
682 strbuf_insertstr((*header
), 0, text
);
683 strbuf_insertstr((*header
), strlen(text
), ": ");
684 strbuf_rtrim((*header
));
685 strbuf_addch((*header
), '\n');
686 trace_strbuf(&trace_curl
, (*header
));
688 strbuf_list_free(headers
);
689 strbuf_release(&out
);
692 static void curl_dump_data(const char *text
, unsigned char *ptr
, size_t size
)
695 struct strbuf out
= STRBUF_INIT
;
696 unsigned int width
= 60;
698 strbuf_addf(&out
, "%s, %10.10ld bytes (0x%8.8lx)\n",
699 text
, (long)size
, (long)size
);
700 trace_strbuf(&trace_curl
, &out
);
702 for (i
= 0; i
< size
; i
+= width
) {
706 strbuf_addf(&out
, "%s: ", text
);
707 for (w
= 0; (w
< width
) && (i
+ w
< size
); w
++) {
708 unsigned char ch
= ptr
[i
+ w
];
711 (ch
>= 0x20) && (ch
< 0x80)
714 strbuf_addch(&out
, '\n');
715 trace_strbuf(&trace_curl
, &out
);
717 strbuf_release(&out
);
720 static void curl_dump_info(char *data
, size_t size
)
722 struct strbuf buf
= STRBUF_INIT
;
724 strbuf_add(&buf
, data
, size
);
726 redact_sensitive_info_header(&buf
);
727 trace_printf_key(&trace_curl
, "== Info: %s", buf
.buf
);
729 strbuf_release(&buf
);
732 static int curl_trace(CURL
*handle
, curl_infotype type
, char *data
, size_t size
, void *userp
)
735 enum { NO_FILTER
= 0, DO_FILTER
= 1 };
739 curl_dump_info(data
, size
);
741 case CURLINFO_HEADER_OUT
:
742 text
= "=> Send header";
743 curl_dump_header(text
, (unsigned char *)data
, size
, DO_FILTER
);
745 case CURLINFO_DATA_OUT
:
746 if (trace_curl_data
) {
747 text
= "=> Send data";
748 curl_dump_data(text
, (unsigned char *)data
, size
);
751 case CURLINFO_SSL_DATA_OUT
:
752 if (trace_curl_data
) {
753 text
= "=> Send SSL data";
754 curl_dump_data(text
, (unsigned char *)data
, size
);
757 case CURLINFO_HEADER_IN
:
758 text
= "<= Recv header";
759 curl_dump_header(text
, (unsigned char *)data
, size
, NO_FILTER
);
761 case CURLINFO_DATA_IN
:
762 if (trace_curl_data
) {
763 text
= "<= Recv data";
764 curl_dump_data(text
, (unsigned char *)data
, size
);
767 case CURLINFO_SSL_DATA_IN
:
768 if (trace_curl_data
) {
769 text
= "<= Recv SSL data";
770 curl_dump_data(text
, (unsigned char *)data
, size
);
774 default: /* we ignore unknown types by default */
780 void http_trace_curl_no_data(void)
782 trace_override_envvar(&trace_curl
, "1");
786 void setup_curl_trace(CURL
*handle
)
788 if (!trace_want(&trace_curl
))
790 curl_easy_setopt(handle
, CURLOPT_VERBOSE
, 1L);
791 curl_easy_setopt(handle
, CURLOPT_DEBUGFUNCTION
, curl_trace
);
792 curl_easy_setopt(handle
, CURLOPT_DEBUGDATA
, NULL
);
795 static long get_curl_allowed_protocols(int from_user
)
797 long allowed_protocols
= 0;
799 if (is_transport_allowed("http", from_user
))
800 allowed_protocols
|= CURLPROTO_HTTP
;
801 if (is_transport_allowed("https", from_user
))
802 allowed_protocols
|= CURLPROTO_HTTPS
;
803 if (is_transport_allowed("ftp", from_user
))
804 allowed_protocols
|= CURLPROTO_FTP
;
805 if (is_transport_allowed("ftps", from_user
))
806 allowed_protocols
|= CURLPROTO_FTPS
;
808 return allowed_protocols
;
811 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
812 static int get_curl_http_version_opt(const char *version_string
, long *opt
)
819 { "HTTP/1.1", CURL_HTTP_VERSION_1_1
},
820 { "HTTP/2", CURL_HTTP_VERSION_2
}
823 for (i
= 0; i
< ARRAY_SIZE(choice
); i
++) {
824 if (!strcmp(version_string
, choice
[i
].name
)) {
825 *opt
= choice
[i
].opt_token
;
830 warning("unknown value given to http.version: '%s'", version_string
);
831 return -1; /* not found */
836 static CURL
*get_curl_handle(void)
838 CURL
*result
= curl_easy_init();
841 die("curl_easy_init failed");
843 if (!curl_ssl_verify
) {
844 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
845 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
847 /* Verify authenticity of the peer's certificate */
848 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
849 /* The name in the cert must match whom we tried to connect */
850 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
853 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
854 if (curl_http_version
) {
856 if (!get_curl_http_version_opt(curl_http_version
, &opt
)) {
857 /* Set request use http version */
858 curl_easy_setopt(result
, CURLOPT_HTTP_VERSION
, opt
);
863 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
864 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
866 #ifdef CURLGSSAPI_DELEGATION_FLAG
869 for (i
= 0; i
< ARRAY_SIZE(curl_deleg_levels
); i
++) {
870 if (!strcmp(curl_deleg
, curl_deleg_levels
[i
].name
)) {
871 curl_easy_setopt(result
, CURLOPT_GSSAPI_DELEGATION
,
872 curl_deleg_levels
[i
].curl_deleg_param
);
876 if (i
== ARRAY_SIZE(curl_deleg_levels
))
877 warning("Unknown delegation method '%s': using default",
882 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
883 !http_schannel_check_revoke
) {
884 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
885 curl_easy_setopt(result
, CURLOPT_SSL_OPTIONS
, CURLSSLOPT_NO_REVOKE
);
887 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
891 if (http_proactive_auth
)
892 init_curl_http_auth(result
);
894 if (getenv("GIT_SSL_VERSION"))
895 ssl_version
= getenv("GIT_SSL_VERSION");
896 if (ssl_version
&& *ssl_version
) {
898 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
899 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
900 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
901 sslversions
[i
].ssl_version
);
905 if (i
== ARRAY_SIZE(sslversions
))
906 warning("unsupported ssl version %s: using default",
910 if (getenv("GIT_SSL_CIPHER_LIST"))
911 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
912 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
913 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
917 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
918 if (has_cert_password())
919 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
921 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
923 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
924 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
926 curl_easy_setopt(result
, CURLOPT_PINNEDPUBLICKEY
, ssl_pinnedkey
);
928 if (http_ssl_backend
&& !strcmp("schannel", http_ssl_backend
) &&
929 !http_schannel_use_ssl_cainfo
) {
930 curl_easy_setopt(result
, CURLOPT_CAINFO
, NULL
);
931 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
932 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, NULL
);
934 } else if (ssl_cainfo
!= NULL
|| http_proxy_ssl_ca_info
!= NULL
) {
936 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
937 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
938 if (http_proxy_ssl_ca_info
)
939 curl_easy_setopt(result
, CURLOPT_PROXY_CAINFO
, http_proxy_ssl_ca_info
);
943 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
944 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
945 curl_low_speed_limit
);
946 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
947 curl_low_speed_time
);
950 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
951 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
952 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
,
953 get_curl_allowed_protocols(0));
954 curl_easy_setopt(result
, CURLOPT_PROTOCOLS
,
955 get_curl_allowed_protocols(-1));
956 if (getenv("GIT_CURL_VERBOSE"))
957 http_trace_curl_no_data();
958 setup_curl_trace(result
);
959 if (getenv("GIT_TRACE_CURL_NO_DATA"))
961 if (!git_env_bool("GIT_TRACE_REDACT", 1))
962 trace_curl_redact
= 0;
964 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
965 user_agent
? user_agent
: git_user_agent());
967 if (curl_ftp_no_epsv
)
968 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
971 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
974 * CURL also examines these variables as a fallback; but we need to query
975 * them here in order to decide whether to prompt for missing password (cf.
976 * init_curl_proxy_auth()).
978 * Unlike many other common environment variables, these are historically
979 * lowercase only. It appears that CURL did not know this and implemented
980 * only uppercase variants, which was later corrected to take both - with
981 * the exception of http_proxy, which is lowercase only also in CURL. As
982 * the lowercase versions are the historical quasi-standard, they take
983 * precedence here, as in CURL.
985 if (!curl_http_proxy
) {
986 if (http_auth
.protocol
&& !strcmp(http_auth
.protocol
, "https")) {
987 var_override(&curl_http_proxy
, getenv("HTTPS_PROXY"));
988 var_override(&curl_http_proxy
, getenv("https_proxy"));
990 var_override(&curl_http_proxy
, getenv("http_proxy"));
992 if (!curl_http_proxy
) {
993 var_override(&curl_http_proxy
, getenv("ALL_PROXY"));
994 var_override(&curl_http_proxy
, getenv("all_proxy"));
998 if (curl_http_proxy
&& curl_http_proxy
[0] == '\0') {
1000 * Handle case with the empty http.proxy value here to keep
1001 * common code clean.
1002 * NB: empty option disables proxying at all.
1004 curl_easy_setopt(result
, CURLOPT_PROXY
, "");
1005 } else if (curl_http_proxy
) {
1006 if (starts_with(curl_http_proxy
, "socks5h"))
1007 curl_easy_setopt(result
,
1008 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5_HOSTNAME
);
1009 else if (starts_with(curl_http_proxy
, "socks5"))
1010 curl_easy_setopt(result
,
1011 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
1012 else if (starts_with(curl_http_proxy
, "socks4a"))
1013 curl_easy_setopt(result
,
1014 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
1015 else if (starts_with(curl_http_proxy
, "socks"))
1016 curl_easy_setopt(result
,
1017 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
1018 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1019 else if (starts_with(curl_http_proxy
, "https")) {
1020 curl_easy_setopt(result
, CURLOPT_PROXYTYPE
, CURLPROXY_HTTPS
);
1022 if (http_proxy_ssl_cert
)
1023 curl_easy_setopt(result
, CURLOPT_PROXY_SSLCERT
, http_proxy_ssl_cert
);
1025 if (http_proxy_ssl_key
)
1026 curl_easy_setopt(result
, CURLOPT_PROXY_SSLKEY
, http_proxy_ssl_key
);
1028 if (has_proxy_cert_password())
1029 curl_easy_setopt(result
, CURLOPT_PROXY_KEYPASSWD
, proxy_cert_auth
.password
);
1032 if (strstr(curl_http_proxy
, "://"))
1033 credential_from_url(&proxy_auth
, curl_http_proxy
);
1035 struct strbuf url
= STRBUF_INIT
;
1036 strbuf_addf(&url
, "http://%s", curl_http_proxy
);
1037 credential_from_url(&proxy_auth
, url
.buf
);
1038 strbuf_release(&url
);
1041 if (!proxy_auth
.host
)
1042 die("Invalid proxy URL '%s'", curl_http_proxy
);
1044 curl_easy_setopt(result
, CURLOPT_PROXY
, proxy_auth
.host
);
1045 var_override(&curl_no_proxy
, getenv("NO_PROXY"));
1046 var_override(&curl_no_proxy
, getenv("no_proxy"));
1047 curl_easy_setopt(result
, CURLOPT_NOPROXY
, curl_no_proxy
);
1049 init_curl_proxy_auth(result
);
1051 set_curl_keepalive(result
);
1056 static void set_from_env(const char **var
, const char *envname
)
1058 const char *val
= getenv(envname
);
1063 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
1065 char *low_speed_limit
;
1066 char *low_speed_time
;
1067 char *normalized_url
;
1068 struct urlmatch_config config
= URLMATCH_CONFIG_INIT
;
1070 config
.section
= "http";
1072 config
.collect_fn
= http_options
;
1073 config
.cascade_fn
= git_default_config
;
1076 http_is_verbose
= 0;
1077 normalized_url
= url_normalize(url
, &config
.url
);
1079 git_config(urlmatch_config_entry
, &config
);
1080 free(normalized_url
);
1081 string_list_clear(&config
.vars
, 1);
1083 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1084 if (http_ssl_backend
) {
1085 const curl_ssl_backend
**backends
;
1086 struct strbuf buf
= STRBUF_INIT
;
1089 switch (curl_global_sslset(-1, http_ssl_backend
, &backends
)) {
1090 case CURLSSLSET_UNKNOWN_BACKEND
:
1091 strbuf_addf(&buf
, _("Unsupported SSL backend '%s'. "
1092 "Supported SSL backends:"),
1094 for (i
= 0; backends
[i
]; i
++)
1095 strbuf_addf(&buf
, "\n\t%s", backends
[i
]->name
);
1097 case CURLSSLSET_NO_BACKENDS
:
1098 die(_("Could not set SSL backend to '%s': "
1099 "cURL was built without SSL backends"),
1101 case CURLSSLSET_TOO_LATE
:
1102 die(_("Could not set SSL backend to '%s': already set"),
1110 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1111 die("curl_global_init failed");
1113 http_proactive_auth
= proactive_auth
;
1115 if (remote
&& remote
->http_proxy
)
1116 curl_http_proxy
= xstrdup(remote
->http_proxy
);
1119 var_override(&http_proxy_authmethod
, remote
->http_proxy_authmethod
);
1121 pragma_header
= curl_slist_append(http_copy_default_headers(),
1122 "Pragma: no-cache");
1123 no_pragma_header
= curl_slist_append(http_copy_default_headers(),
1127 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
1128 if (http_max_requests
)
1129 max_requests
= atoi(http_max_requests
);
1132 curlm
= curl_multi_init();
1134 die("curl_multi_init failed");
1136 if (getenv("GIT_SSL_NO_VERIFY"))
1137 curl_ssl_verify
= 0;
1139 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
1140 set_from_env(&ssl_key
, "GIT_SSL_KEY");
1141 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
1142 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
1144 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
1146 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1147 if (low_speed_limit
)
1148 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
1149 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
1151 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
1153 if (curl_ssl_verify
== -1)
1154 curl_ssl_verify
= 1;
1156 curl_session_count
= 0;
1157 if (max_requests
< 1)
1158 max_requests
= DEFAULT_MAX_REQUESTS
;
1160 set_from_env(&http_proxy_ssl_cert
, "GIT_PROXY_SSL_CERT");
1161 set_from_env(&http_proxy_ssl_key
, "GIT_PROXY_SSL_KEY");
1162 set_from_env(&http_proxy_ssl_ca_info
, "GIT_PROXY_SSL_CAINFO");
1164 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1165 proxy_ssl_cert_password_required
= 1;
1167 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1168 curl_ftp_no_epsv
= 1;
1171 credential_from_url(&http_auth
, url
);
1172 if (!ssl_cert_password_required
&&
1173 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1174 starts_with(url
, "https://"))
1175 ssl_cert_password_required
= 1;
1178 curl_default
= get_curl_handle();
1181 void http_cleanup(void)
1183 struct active_request_slot
*slot
= active_queue_head
;
1185 while (slot
!= NULL
) {
1186 struct active_request_slot
*next
= slot
->next
;
1188 xmulti_remove_handle(slot
);
1189 curl_easy_cleanup(slot
->curl
);
1194 active_queue_head
= NULL
;
1196 curl_easy_cleanup(curl_default
);
1198 curl_multi_cleanup(curlm
);
1199 curl_global_cleanup();
1201 string_list_clear(&extra_http_headers
, 0);
1203 curl_slist_free_all(pragma_header
);
1204 pragma_header
= NULL
;
1206 curl_slist_free_all(no_pragma_header
);
1207 no_pragma_header
= NULL
;
1209 curl_slist_free_all(host_resolutions
);
1210 host_resolutions
= NULL
;
1212 if (curl_http_proxy
) {
1213 free((void *)curl_http_proxy
);
1214 curl_http_proxy
= NULL
;
1217 if (proxy_auth
.password
) {
1218 memset(proxy_auth
.password
, 0, strlen(proxy_auth
.password
));
1219 FREE_AND_NULL(proxy_auth
.password
);
1222 free((void *)curl_proxyuserpwd
);
1223 curl_proxyuserpwd
= NULL
;
1225 free((void *)http_proxy_authmethod
);
1226 http_proxy_authmethod
= NULL
;
1228 if (cert_auth
.password
) {
1229 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
1230 FREE_AND_NULL(cert_auth
.password
);
1232 ssl_cert_password_required
= 0;
1234 if (proxy_cert_auth
.password
) {
1235 memset(proxy_cert_auth
.password
, 0, strlen(proxy_cert_auth
.password
));
1236 FREE_AND_NULL(proxy_cert_auth
.password
);
1238 proxy_ssl_cert_password_required
= 0;
1240 FREE_AND_NULL(cached_accept_language
);
1243 struct active_request_slot
*get_active_slot(void)
1245 struct active_request_slot
*slot
= active_queue_head
;
1246 struct active_request_slot
*newslot
;
1250 /* Wait for a slot to open up if the queue is full */
1251 while (active_requests
>= max_requests
) {
1252 curl_multi_perform(curlm
, &num_transfers
);
1253 if (num_transfers
< active_requests
)
1254 process_curl_messages();
1257 while (slot
!= NULL
&& slot
->in_use
)
1261 newslot
= xmalloc(sizeof(*newslot
));
1262 newslot
->curl
= NULL
;
1263 newslot
->in_use
= 0;
1264 newslot
->next
= NULL
;
1266 slot
= active_queue_head
;
1268 active_queue_head
= newslot
;
1270 while (slot
->next
!= NULL
)
1272 slot
->next
= newslot
;
1278 slot
->curl
= curl_easy_duphandle(curl_default
);
1279 curl_session_count
++;
1284 slot
->results
= NULL
;
1285 slot
->finished
= NULL
;
1286 slot
->callback_data
= NULL
;
1287 slot
->callback_func
= NULL
;
1288 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
1289 if (curl_save_cookies
)
1290 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
1291 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
1292 curl_easy_setopt(slot
->curl
, CURLOPT_RESOLVE
, host_resolutions
);
1293 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
1294 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
1295 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
1296 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
1297 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
1298 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
1299 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1300 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
1301 curl_easy_setopt(slot
->curl
, CURLOPT_RANGE
, NULL
);
1304 * Default following to off unless "ALWAYS" is configured; this gives
1305 * callers a sane starting point, and they can tweak for individual
1306 * HTTP_FOLLOW_* cases themselves.
1308 if (http_follow_config
== HTTP_FOLLOW_ALWAYS
)
1309 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1311 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 0);
1313 curl_easy_setopt(slot
->curl
, CURLOPT_IPRESOLVE
, git_curl_ipresolve
);
1314 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
1315 if (http_auth
.password
|| curl_empty_auth_enabled())
1316 init_curl_http_auth(slot
->curl
);
1321 int start_active_slot(struct active_request_slot
*slot
)
1323 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
1326 if (curlm_result
!= CURLM_OK
&&
1327 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
1328 warning("curl_multi_add_handle failed: %s",
1329 curl_multi_strerror(curlm_result
));
1336 * We know there must be something to do, since we just added
1339 curl_multi_perform(curlm
, &num_transfers
);
1345 int (*fill
)(void *);
1346 struct fill_chain
*next
;
1349 static struct fill_chain
*fill_cfg
;
1351 void add_fill_function(void *data
, int (*fill
)(void *))
1353 struct fill_chain
*new_fill
= xmalloc(sizeof(*new_fill
));
1354 struct fill_chain
**linkp
= &fill_cfg
;
1355 new_fill
->data
= data
;
1356 new_fill
->fill
= fill
;
1357 new_fill
->next
= NULL
;
1359 linkp
= &(*linkp
)->next
;
1363 void fill_active_slots(void)
1365 struct active_request_slot
*slot
= active_queue_head
;
1367 while (active_requests
< max_requests
) {
1368 struct fill_chain
*fill
;
1369 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
1370 if (fill
->fill(fill
->data
))
1377 while (slot
!= NULL
) {
1378 if (!slot
->in_use
&& slot
->curl
!= NULL
1379 && curl_session_count
> min_curl_sessions
) {
1380 curl_easy_cleanup(slot
->curl
);
1382 curl_session_count
--;
1388 void step_active_slots(void)
1391 CURLMcode curlm_result
;
1394 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
1395 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
1396 if (num_transfers
< active_requests
) {
1397 process_curl_messages();
1398 fill_active_slots();
1402 void run_active_slot(struct active_request_slot
*slot
)
1408 struct timeval select_timeout
;
1411 slot
->finished
= &finished
;
1413 step_active_slots();
1417 curl_multi_timeout(curlm
, &curl_timeout
);
1418 if (curl_timeout
== 0) {
1420 } else if (curl_timeout
== -1) {
1421 select_timeout
.tv_sec
= 0;
1422 select_timeout
.tv_usec
= 50000;
1424 select_timeout
.tv_sec
= curl_timeout
/ 1000;
1425 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
1432 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
1435 * It can happen that curl_multi_timeout returns a pathologically
1436 * long timeout when curl_multi_fdset returns no file descriptors
1437 * to read. See commit message for more details.
1440 (select_timeout
.tv_sec
> 0 ||
1441 select_timeout
.tv_usec
> 50000)) {
1442 select_timeout
.tv_sec
= 0;
1443 select_timeout
.tv_usec
= 50000;
1446 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
1451 * The value of slot->finished we set before the loop was used
1452 * to set our "finished" variable when our request completed.
1454 * 1. The slot may not have been reused for another requst
1455 * yet, in which case it still has &finished.
1457 * 2. The slot may already be in-use to serve another request,
1458 * which can further be divided into two cases:
1460 * (a) If call run_active_slot() hasn't been called for that
1461 * other request, slot->finished would have been cleared
1462 * by get_active_slot() and has NULL.
1464 * (b) If the request did call run_active_slot(), then the
1465 * call would have updated slot->finished at the beginning
1466 * of this function, and with the clearing of the member
1467 * below, we would find that slot->finished is now NULL.
1469 * In all cases, slot->finished has no useful information to
1470 * anybody at this point. Some compilers warn us for
1471 * attempting to smuggle a pointer that is about to become
1472 * invalid, i.e. &finished. We clear it here to assure them.
1474 slot
->finished
= NULL
;
1477 static void release_active_slot(struct active_request_slot
*slot
)
1479 closedown_active_slot(slot
);
1481 xmulti_remove_handle(slot
);
1482 if (curl_session_count
> min_curl_sessions
) {
1483 curl_easy_cleanup(slot
->curl
);
1485 curl_session_count
--;
1488 fill_active_slots();
1491 void finish_all_active_slots(void)
1493 struct active_request_slot
*slot
= active_queue_head
;
1495 while (slot
!= NULL
)
1497 run_active_slot(slot
);
1498 slot
= active_queue_head
;
1504 /* Helpers for modifying and creating URLs */
1505 static inline int needs_quote(int ch
)
1507 if (((ch
>= 'A') && (ch
<= 'Z'))
1508 || ((ch
>= 'a') && (ch
<= 'z'))
1509 || ((ch
>= '0') && (ch
<= '9'))
1517 static char *quote_ref_url(const char *base
, const char *ref
)
1519 struct strbuf buf
= STRBUF_INIT
;
1523 end_url_with_slash(&buf
, base
);
1525 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
1526 if (needs_quote(ch
))
1527 strbuf_addf(&buf
, "%%%02x", ch
);
1529 strbuf_addch(&buf
, *cp
);
1531 return strbuf_detach(&buf
, NULL
);
1534 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
1536 int only_two_digit_prefix
)
1538 end_url_with_slash(buf
, url
);
1540 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
1541 if (!only_two_digit_prefix
)
1542 strbuf_addstr(buf
, hex
+ 2);
1545 char *get_remote_object_url(const char *url
, const char *hex
,
1546 int only_two_digit_prefix
)
1548 struct strbuf buf
= STRBUF_INIT
;
1549 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
1550 return strbuf_detach(&buf
, NULL
);
1553 void normalize_curl_result(CURLcode
*result
, long http_code
,
1554 char *errorstr
, size_t errorlen
)
1557 * If we see a failing http code with CURLE_OK, we have turned off
1558 * FAILONERROR (to keep the server's custom error response), and should
1559 * translate the code into failure here.
1561 * Likewise, if we see a redirect (30x code), that means we turned off
1562 * redirect-following, and we should treat the result as an error.
1564 if (*result
== CURLE_OK
&& http_code
>= 300) {
1565 *result
= CURLE_HTTP_RETURNED_ERROR
;
1567 * Normally curl will already have put the "reason phrase"
1568 * from the server into curl_errorstr; unfortunately without
1569 * FAILONERROR it is lost, so we can give only the numeric
1572 xsnprintf(errorstr
, errorlen
,
1573 "The requested URL returned error: %ld",
1578 static int handle_curl_result(struct slot_results
*results
)
1580 normalize_curl_result(&results
->curl_result
, results
->http_code
,
1581 curl_errorstr
, sizeof(curl_errorstr
));
1583 if (results
->curl_result
== CURLE_OK
) {
1584 credential_approve(&http_auth
);
1585 credential_approve(&proxy_auth
);
1586 credential_approve(&cert_auth
);
1588 } else if (results
->curl_result
== CURLE_SSL_CERTPROBLEM
) {
1590 * We can't tell from here whether it's a bad path, bad
1591 * certificate, bad password, or something else wrong
1592 * with the certificate. So we reject the credential to
1593 * avoid caching or saving a bad password.
1595 credential_reject(&cert_auth
);
1597 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1598 } else if (results
->curl_result
== CURLE_SSL_PINNEDPUBKEYNOTMATCH
) {
1599 return HTTP_NOMATCHPUBLICKEY
;
1601 } else if (missing_target(results
))
1602 return HTTP_MISSING_TARGET
;
1603 else if (results
->http_code
== 401) {
1604 if (http_auth
.username
&& http_auth
.password
) {
1605 credential_reject(&http_auth
);
1608 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
1609 if (results
->auth_avail
) {
1610 http_auth_methods
&= results
->auth_avail
;
1611 http_auth_methods_restricted
= 1;
1616 if (results
->http_connectcode
== 407)
1617 credential_reject(&proxy_auth
);
1618 if (!curl_errorstr
[0])
1619 strlcpy(curl_errorstr
,
1620 curl_easy_strerror(results
->curl_result
),
1621 sizeof(curl_errorstr
));
1626 int run_one_slot(struct active_request_slot
*slot
,
1627 struct slot_results
*results
)
1629 slot
->results
= results
;
1630 if (!start_active_slot(slot
)) {
1631 xsnprintf(curl_errorstr
, sizeof(curl_errorstr
),
1632 "failed to start HTTP request");
1633 return HTTP_START_FAILED
;
1636 run_active_slot(slot
);
1637 return handle_curl_result(results
);
1640 struct curl_slist
*http_copy_default_headers(void)
1642 struct curl_slist
*headers
= NULL
;
1643 const struct string_list_item
*item
;
1645 for_each_string_list_item(item
, &extra_http_headers
)
1646 headers
= curl_slist_append(headers
, item
->string
);
1651 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
1657 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1659 strbuf_addstr(buf
, ptr
);
1664 * Check for and extract a content-type parameter. "raw"
1665 * should be positioned at the start of the potential
1666 * parameter, with any whitespace already removed.
1668 * "name" is the name of the parameter. The value is appended
1671 static int extract_param(const char *raw
, const char *name
,
1674 size_t len
= strlen(name
);
1676 if (strncasecmp(raw
, name
, len
))
1684 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1685 strbuf_addch(out
, *raw
++);
1690 * Extract a normalized version of the content type, with any
1691 * spaces suppressed, all letters lowercased, and no trailing ";"
1694 * Note that we will silently remove even invalid whitespace. For
1695 * example, "text / plain" is specifically forbidden by RFC 2616,
1696 * but "text/plain" is the only reasonable output, and this keeps
1699 * If the "charset" argument is not NULL, store the value of any
1700 * charset parameter there.
1703 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1704 * "text / plain" -> "text/plain"
1706 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1707 struct strbuf
*charset
)
1712 strbuf_grow(type
, raw
->len
);
1713 for (p
= raw
->buf
; *p
; p
++) {
1720 strbuf_addch(type
, tolower(*p
));
1726 strbuf_reset(charset
);
1728 while (isspace(*p
) || *p
== ';')
1730 if (!extract_param(p
, "charset", charset
))
1732 while (*p
&& !isspace(*p
))
1736 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1737 strbuf_addstr(charset
, "ISO-8859-1");
1740 static void write_accept_language(struct strbuf
*buf
)
1743 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1744 * that, q-value will be smaller than 0.001, the minimum q-value the
1745 * HTTP specification allows. See
1746 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1748 const int MAX_DECIMAL_PLACES
= 3;
1749 const int MAX_LANGUAGE_TAGS
= 1000;
1750 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1751 char **language_tags
= NULL
;
1753 const char *s
= get_preferred_languages();
1755 struct strbuf tag
= STRBUF_INIT
;
1757 /* Don't add Accept-Language header if no language is preferred. */
1762 * Split the colon-separated string of preferred languages into
1763 * language_tags array.
1766 /* collect language tag */
1767 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1768 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1770 /* skip .codeset, @modifier and any other unnecessary parts */
1771 while (*s
&& *s
!= ':')
1776 REALLOC_ARRAY(language_tags
, num_langs
);
1777 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1778 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1783 /* write Accept-Language header into buf */
1785 int last_buf_len
= 0;
1791 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1792 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1794 /* compute decimal_places */
1795 for (max_q
= 1, decimal_places
= 0;
1796 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1797 decimal_places
++, max_q
*= 10)
1800 xsnprintf(q_format
, sizeof(q_format
), ";q=0.%%0%dd", decimal_places
);
1802 strbuf_addstr(buf
, "Accept-Language: ");
1804 for (i
= 0; i
< num_langs
; i
++) {
1806 strbuf_addstr(buf
, ", ");
1808 strbuf_addstr(buf
, language_tags
[i
]);
1811 strbuf_addf(buf
, q_format
, max_q
- i
);
1813 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1814 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1818 last_buf_len
= buf
->len
;
1822 /* free language tags -- last one is a static '*' */
1823 for (i
= 0; i
< num_langs
- 1; i
++)
1824 free(language_tags
[i
]);
1825 free(language_tags
);
1829 * Get an Accept-Language header which indicates user's preferred languages.
1833 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1834 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1835 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1836 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1837 * LANGUAGE= LANG=C -> ""
1839 const char *http_get_accept_language_header(void)
1841 if (!cached_accept_language
) {
1842 struct strbuf buf
= STRBUF_INIT
;
1843 write_accept_language(&buf
);
1845 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1848 return cached_accept_language
;
1851 static void http_opt_request_remainder(CURL
*curl
, off_t pos
)
1854 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
"-", (uintmax_t)pos
);
1855 curl_easy_setopt(curl
, CURLOPT_RANGE
, buf
);
1858 /* http_request() targets */
1859 #define HTTP_REQUEST_STRBUF 0
1860 #define HTTP_REQUEST_FILE 1
1862 static int http_request(const char *url
,
1863 void *result
, int target
,
1864 const struct http_get_options
*options
)
1866 struct active_request_slot
*slot
;
1867 struct slot_results results
;
1868 struct curl_slist
*headers
= http_copy_default_headers();
1869 struct strbuf buf
= STRBUF_INIT
;
1870 const char *accept_language
;
1873 slot
= get_active_slot();
1874 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1877 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1879 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1880 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEDATA
, result
);
1882 if (target
== HTTP_REQUEST_FILE
) {
1883 off_t posn
= ftello(result
);
1884 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1887 http_opt_request_remainder(slot
->curl
, posn
);
1889 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1893 accept_language
= http_get_accept_language_header();
1895 if (accept_language
)
1896 headers
= curl_slist_append(headers
, accept_language
);
1898 strbuf_addstr(&buf
, "Pragma:");
1899 if (options
&& options
->no_cache
)
1900 strbuf_addstr(&buf
, " no-cache");
1901 if (options
&& options
->initial_request
&&
1902 http_follow_config
== HTTP_FOLLOW_INITIAL
)
1903 curl_easy_setopt(slot
->curl
, CURLOPT_FOLLOWLOCATION
, 1);
1905 headers
= curl_slist_append(headers
, buf
.buf
);
1907 /* Add additional headers here */
1908 if (options
&& options
->extra_headers
) {
1909 const struct string_list_item
*item
;
1910 for_each_string_list_item(item
, options
->extra_headers
) {
1911 headers
= curl_slist_append(headers
, item
->string
);
1915 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1916 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1917 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "");
1918 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1920 ret
= run_one_slot(slot
, &results
);
1922 if (options
&& options
->content_type
) {
1923 struct strbuf raw
= STRBUF_INIT
;
1924 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1925 extract_content_type(&raw
, options
->content_type
,
1927 strbuf_release(&raw
);
1930 if (options
&& options
->effective_url
)
1931 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1932 options
->effective_url
);
1934 curl_slist_free_all(headers
);
1935 strbuf_release(&buf
);
1941 * Update the "base" url to a more appropriate value, as deduced by
1942 * redirects seen when requesting a URL starting with "url".
1944 * The "asked" parameter is a URL that we asked curl to access, and must begin
1947 * The "got" parameter is the URL that curl reported to us as where we ended
1950 * Returns 1 if we updated the base url, 0 otherwise.
1952 * Our basic strategy is to compare "base" and "asked" to find the bits
1953 * specific to our request. We then strip those bits off of "got" to yield the
1954 * new base. So for example, if our base is "http://example.com/foo.git",
1955 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1956 * with "https://other.example.com/foo.git/info/refs". We would want the
1957 * new URL to become "https://other.example.com/foo.git".
1959 * Note that this assumes a sane redirect scheme. It's entirely possible
1960 * in the example above to end up at a URL that does not even end in
1961 * "info/refs". In such a case we die. There's not much we can do, such a
1962 * scheme is unlikely to represent a real git repository, and failing to
1963 * rewrite the base opens options for malicious redirects to do funny things.
1965 static int update_url_from_redirect(struct strbuf
*base
,
1967 const struct strbuf
*got
)
1972 if (!strcmp(asked
, got
->buf
))
1975 if (!skip_prefix(asked
, base
->buf
, &tail
))
1976 BUG("update_url_from_redirect: %s is not a superset of %s",
1980 if (!strip_suffix_mem(got
->buf
, &new_len
, tail
))
1981 die(_("unable to update url base from redirection:\n"
1987 strbuf_add(base
, got
->buf
, new_len
);
1992 static int http_request_reauth(const char *url
,
1993 void *result
, int target
,
1994 struct http_get_options
*options
)
1996 int ret
= http_request(url
, result
, target
, options
);
1998 if (ret
!= HTTP_OK
&& ret
!= HTTP_REAUTH
)
2001 if (options
&& options
->effective_url
&& options
->base_url
) {
2002 if (update_url_from_redirect(options
->base_url
,
2003 url
, options
->effective_url
)) {
2004 credential_from_url(&http_auth
, options
->base_url
->buf
);
2005 url
= options
->effective_url
->buf
;
2009 if (ret
!= HTTP_REAUTH
)
2013 * The previous request may have put cruft into our output stream; we
2014 * should clear it out before making our next request.
2017 case HTTP_REQUEST_STRBUF
:
2018 strbuf_reset(result
);
2020 case HTTP_REQUEST_FILE
:
2021 if (fflush(result
)) {
2022 error_errno("unable to flush a file");
2023 return HTTP_START_FAILED
;
2026 if (ftruncate(fileno(result
), 0) < 0) {
2027 error_errno("unable to truncate a file");
2028 return HTTP_START_FAILED
;
2032 BUG("Unknown http_request target");
2035 credential_fill(&http_auth
);
2037 return http_request(url
, result
, target
, options
);
2040 int http_get_strbuf(const char *url
,
2041 struct strbuf
*result
,
2042 struct http_get_options
*options
)
2044 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
2048 * Downloads a URL and stores the result in the given file.
2050 * If a previous interrupted download is detected (i.e. a previous temporary
2051 * file is still around) the download is resumed.
2053 int http_get_file(const char *url
, const char *filename
,
2054 struct http_get_options
*options
)
2057 struct strbuf tmpfile
= STRBUF_INIT
;
2060 strbuf_addf(&tmpfile
, "%s.temp", filename
);
2061 result
= fopen(tmpfile
.buf
, "a");
2063 error("Unable to open local file %s", tmpfile
.buf
);
2068 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
2071 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
2074 strbuf_release(&tmpfile
);
2078 int http_fetch_ref(const char *base
, struct ref
*ref
)
2080 struct http_get_options options
= {0};
2082 struct strbuf buffer
= STRBUF_INIT
;
2085 options
.no_cache
= 1;
2087 url
= quote_ref_url(base
, ref
->name
);
2088 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
2089 strbuf_rtrim(&buffer
);
2090 if (buffer
.len
== the_hash_algo
->hexsz
)
2091 ret
= get_oid_hex(buffer
.buf
, &ref
->old_oid
);
2092 else if (starts_with(buffer
.buf
, "ref: ")) {
2093 ref
->symref
= xstrdup(buffer
.buf
+ 5);
2098 strbuf_release(&buffer
);
2103 /* Helpers for fetching packs */
2104 static char *fetch_pack_index(unsigned char *hash
, const char *base_url
)
2107 struct strbuf buf
= STRBUF_INIT
;
2109 if (http_is_verbose
)
2110 fprintf(stderr
, "Getting index for pack %s\n", hash_to_hex(hash
));
2112 end_url_with_slash(&buf
, base_url
);
2113 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", hash_to_hex(hash
));
2114 url
= strbuf_detach(&buf
, NULL
);
2116 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(hash
));
2117 tmp
= strbuf_detach(&buf
, NULL
);
2119 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
2120 error("Unable to get pack index %s", url
);
2128 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
2129 unsigned char *sha1
, const char *base_url
)
2131 struct packed_git
*new_pack
;
2132 char *tmp_idx
= NULL
;
2135 if (has_pack_index(sha1
)) {
2136 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
2138 return -1; /* parse_pack_index() already issued error message */
2142 tmp_idx
= fetch_pack_index(sha1
, base_url
);
2146 new_pack
= parse_pack_index(sha1
, tmp_idx
);
2151 return -1; /* parse_pack_index() already issued error message */
2154 ret
= verify_pack_index(new_pack
);
2156 close_pack_index(new_pack
);
2157 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
2164 new_pack
->next
= *packs_head
;
2165 *packs_head
= new_pack
;
2169 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
2171 struct http_get_options options
= {0};
2175 struct strbuf buf
= STRBUF_INIT
;
2176 struct object_id oid
;
2178 end_url_with_slash(&buf
, base_url
);
2179 strbuf_addstr(&buf
, "objects/info/packs");
2180 url
= strbuf_detach(&buf
, NULL
);
2182 options
.no_cache
= 1;
2183 ret
= http_get_strbuf(url
, &buf
, &options
);
2189 if (skip_prefix(data
, "P pack-", &data
) &&
2190 !parse_oid_hex(data
, &oid
, &data
) &&
2191 skip_prefix(data
, ".pack", &data
) &&
2192 (*data
== '\n' || *data
== '\0')) {
2193 fetch_and_setup_pack_index(packs_head
, oid
.hash
, base_url
);
2195 data
= strchrnul(data
, '\n');
2198 data
++; /* skip past newline */
2206 void release_http_pack_request(struct http_pack_request
*preq
)
2208 if (preq
->packfile
) {
2209 fclose(preq
->packfile
);
2210 preq
->packfile
= NULL
;
2213 strbuf_release(&preq
->tmpfile
);
2218 static const char *default_index_pack_args
[] =
2219 {"index-pack", "--stdin", NULL
};
2221 int finish_http_pack_request(struct http_pack_request
*preq
)
2223 struct child_process ip
= CHILD_PROCESS_INIT
;
2227 fclose(preq
->packfile
);
2228 preq
->packfile
= NULL
;
2230 tmpfile_fd
= xopen(preq
->tmpfile
.buf
, O_RDONLY
);
2234 strvec_pushv(&ip
.args
, preq
->index_pack_args
?
2235 preq
->index_pack_args
:
2236 default_index_pack_args
);
2238 if (preq
->preserve_index_pack_stdout
)
2243 if (run_command(&ip
)) {
2250 unlink(preq
->tmpfile
.buf
);
2254 void http_install_packfile(struct packed_git
*p
,
2255 struct packed_git
**list_to_remove_from
)
2257 struct packed_git
**lst
= list_to_remove_from
;
2260 lst
= &((*lst
)->next
);
2261 *lst
= (*lst
)->next
;
2263 install_packed_git(the_repository
, p
);
2266 struct http_pack_request
*new_http_pack_request(
2267 const unsigned char *packed_git_hash
, const char *base_url
) {
2269 struct strbuf buf
= STRBUF_INIT
;
2271 end_url_with_slash(&buf
, base_url
);
2272 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
2273 hash_to_hex(packed_git_hash
));
2274 return new_direct_http_pack_request(packed_git_hash
,
2275 strbuf_detach(&buf
, NULL
));
2278 struct http_pack_request
*new_direct_http_pack_request(
2279 const unsigned char *packed_git_hash
, char *url
)
2281 off_t prev_posn
= 0;
2282 struct http_pack_request
*preq
;
2284 CALLOC_ARRAY(preq
, 1);
2285 strbuf_init(&preq
->tmpfile
, 0);
2289 strbuf_addf(&preq
->tmpfile
, "%s.temp", sha1_pack_name(packed_git_hash
));
2290 preq
->packfile
= fopen(preq
->tmpfile
.buf
, "a");
2291 if (!preq
->packfile
) {
2292 error("Unable to open local file %s for pack",
2297 preq
->slot
= get_active_slot();
2298 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEDATA
, preq
->packfile
);
2299 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
2300 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
2301 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
2305 * If there is data present from a previous transfer attempt,
2306 * resume where it left off
2308 prev_posn
= ftello(preq
->packfile
);
2310 if (http_is_verbose
)
2312 "Resuming fetch of pack %s at byte %"PRIuMAX
"\n",
2313 hash_to_hex(packed_git_hash
),
2314 (uintmax_t)prev_posn
);
2315 http_opt_request_remainder(preq
->slot
->curl
, prev_posn
);
2321 strbuf_release(&preq
->tmpfile
);
2327 /* Helpers for fetching objects (loose) */
2328 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
2331 unsigned char expn
[4096];
2332 size_t size
= eltsize
* nmemb
;
2334 struct http_object_request
*freq
= data
;
2335 struct active_request_slot
*slot
= freq
->slot
;
2338 CURLcode c
= curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
,
2341 BUG("curl_easy_getinfo for HTTP code failed: %s",
2342 curl_easy_strerror(c
));
2343 if (slot
->http_code
>= 300)
2348 ssize_t retval
= xwrite(freq
->localfile
,
2349 (char *) ptr
+ posn
, size
- posn
);
2351 return posn
/ eltsize
;
2353 } while (posn
< size
);
2355 freq
->stream
.avail_in
= size
;
2356 freq
->stream
.next_in
= (void *)ptr
;
2358 freq
->stream
.next_out
= expn
;
2359 freq
->stream
.avail_out
= sizeof(expn
);
2360 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
2361 the_hash_algo
->update_fn(&freq
->c
, expn
,
2362 sizeof(expn
) - freq
->stream
.avail_out
);
2363 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
2367 struct http_object_request
*new_http_object_request(const char *base_url
,
2368 const struct object_id
*oid
)
2370 char *hex
= oid_to_hex(oid
);
2371 struct strbuf filename
= STRBUF_INIT
;
2372 struct strbuf prevfile
= STRBUF_INIT
;
2374 char prev_buf
[PREV_BUF_SIZE
];
2375 ssize_t prev_read
= 0;
2376 off_t prev_posn
= 0;
2377 struct http_object_request
*freq
;
2379 CALLOC_ARRAY(freq
, 1);
2380 strbuf_init(&freq
->tmpfile
, 0);
2381 oidcpy(&freq
->oid
, oid
);
2382 freq
->localfile
= -1;
2384 loose_object_path(the_repository
, &filename
, oid
);
2385 strbuf_addf(&freq
->tmpfile
, "%s.temp", filename
.buf
);
2387 strbuf_addf(&prevfile
, "%s.prev", filename
.buf
);
2388 unlink_or_warn(prevfile
.buf
);
2389 rename(freq
->tmpfile
.buf
, prevfile
.buf
);
2390 unlink_or_warn(freq
->tmpfile
.buf
);
2391 strbuf_release(&filename
);
2393 if (freq
->localfile
!= -1)
2394 error("fd leakage in start: %d", freq
->localfile
);
2395 freq
->localfile
= open(freq
->tmpfile
.buf
,
2396 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2398 * This could have failed due to the "lazy directory creation";
2399 * try to mkdir the last path component.
2401 if (freq
->localfile
< 0 && errno
== ENOENT
) {
2402 char *dir
= strrchr(freq
->tmpfile
.buf
, '/');
2405 mkdir(freq
->tmpfile
.buf
, 0777);
2408 freq
->localfile
= open(freq
->tmpfile
.buf
,
2409 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
2412 if (freq
->localfile
< 0) {
2413 error_errno("Couldn't create temporary file %s",
2418 git_inflate_init(&freq
->stream
);
2420 the_hash_algo
->init_fn(&freq
->c
);
2422 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
2425 * If a previous temp file is present, process what was already
2428 prevlocal
= open(prevfile
.buf
, O_RDONLY
);
2429 if (prevlocal
!= -1) {
2431 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
2433 if (fwrite_sha1_file(prev_buf
,
2436 freq
) == prev_read
) {
2437 prev_posn
+= prev_read
;
2442 } while (prev_read
> 0);
2445 unlink_or_warn(prevfile
.buf
);
2446 strbuf_release(&prevfile
);
2449 * Reset inflate/SHA1 if there was an error reading the previous temp
2450 * file; also rewind to the beginning of the local file.
2452 if (prev_read
== -1) {
2453 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
2454 git_inflate_init(&freq
->stream
);
2455 the_hash_algo
->init_fn(&freq
->c
);
2458 lseek(freq
->localfile
, 0, SEEK_SET
);
2459 if (ftruncate(freq
->localfile
, 0) < 0) {
2460 error_errno("Couldn't truncate temporary file %s",
2467 freq
->slot
= get_active_slot();
2469 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEDATA
, freq
);
2470 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FAILONERROR
, 0);
2471 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
2472 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
2473 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
2474 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
2477 * If we have successfully processed data from a previous fetch
2478 * attempt, only fetch the data we don't already have.
2481 if (http_is_verbose
)
2483 "Resuming fetch of object %s at byte %"PRIuMAX
"\n",
2484 hex
, (uintmax_t)prev_posn
);
2485 http_opt_request_remainder(freq
->slot
->curl
, prev_posn
);
2491 strbuf_release(&prevfile
);
2497 void process_http_object_request(struct http_object_request
*freq
)
2501 freq
->curl_result
= freq
->slot
->curl_result
;
2502 freq
->http_code
= freq
->slot
->http_code
;
2506 int finish_http_object_request(struct http_object_request
*freq
)
2509 struct strbuf filename
= STRBUF_INIT
;
2511 close(freq
->localfile
);
2512 freq
->localfile
= -1;
2514 process_http_object_request(freq
);
2516 if (freq
->http_code
== 416) {
2517 warning("requested range invalid; we may already have all the data.");
2518 } else if (freq
->curl_result
!= CURLE_OK
) {
2519 if (stat(freq
->tmpfile
.buf
, &st
) == 0)
2520 if (st
.st_size
== 0)
2521 unlink_or_warn(freq
->tmpfile
.buf
);
2525 git_inflate_end(&freq
->stream
);
2526 the_hash_algo
->final_oid_fn(&freq
->real_oid
, &freq
->c
);
2527 if (freq
->zret
!= Z_STREAM_END
) {
2528 unlink_or_warn(freq
->tmpfile
.buf
);
2531 if (!oideq(&freq
->oid
, &freq
->real_oid
)) {
2532 unlink_or_warn(freq
->tmpfile
.buf
);
2535 loose_object_path(the_repository
, &filename
, &freq
->oid
);
2536 freq
->rename
= finalize_object_file(freq
->tmpfile
.buf
, filename
.buf
);
2537 strbuf_release(&filename
);
2539 return freq
->rename
;
2542 void abort_http_object_request(struct http_object_request
*freq
)
2544 unlink_or_warn(freq
->tmpfile
.buf
);
2546 release_http_object_request(freq
);
2549 void release_http_object_request(struct http_object_request
*freq
)
2551 if (freq
->localfile
!= -1) {
2552 close(freq
->localfile
);
2553 freq
->localfile
= -1;
2555 FREE_AND_NULL(freq
->url
);
2557 freq
->slot
->callback_func
= NULL
;
2558 freq
->slot
->callback_data
= NULL
;
2559 release_active_slot(freq
->slot
);
2562 strbuf_release(&freq
->tmpfile
);