1 #include "git-compat-util.h"
6 #include "run-command.h"
9 #include "credential.h"
13 #include "transport.h"
16 #include "string-list.h"
18 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
19 static int trace_curl_data = 1;
20 static struct string_list cookies_to_redact = STRING_LIST_INIT_DUP;
21 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
24 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
26 static int min_curl_sessions = 1;
27 static int curl_session_count;
28 static int max_requests = -1;
30 static CURL *curl_default;
32 #define PREV_BUF_SIZE 4096
34 char curl_errorstr[CURL_ERROR_SIZE];
36 static int curl_ssl_verify = -1;
37 static int curl_ssl_try;
38 static const char *ssl_cert;
39 static const char *ssl_cipherlist;
40 static const char *ssl_version;
45 { "sslv2", CURL_SSLVERSION_SSLv2 },
46 { "sslv3", CURL_SSLVERSION_SSLv3 },
47 { "tlsv1", CURL_SSLVERSION_TLSv1 },
48 #if LIBCURL_VERSION_NUM >= 0x072200
49 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
50 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
51 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
54 static const char *ssl_key;
55 static const char *ssl_capath;
56 #if LIBCURL_VERSION_NUM >= 0x072c00
57 static const char *ssl_pinnedkey;
59 static const char *ssl_cainfo;
60 static long curl_low_speed_limit = -1;
61 static long curl_low_speed_time = -1;
62 static int curl_ftp_no_epsv;
63 static const char *curl_http_proxy;
64 static const char *curl_no_proxy;
65 static const char *http_proxy_authmethod;
69 } proxy_authmethods[] = {
70 { "basic", CURLAUTH_BASIC },
71 { "digest", CURLAUTH_DIGEST },
72 { "negotiate", CURLAUTH_GSSNEGOTIATE },
73 { "ntlm", CURLAUTH_NTLM },
74 { "anyauth", CURLAUTH_ANY },
76 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
77 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
81 #ifdef CURLGSSAPI_DELEGATION_FLAG
82 static const char *curl_deleg;
85 long curl_deleg_param;
86 } curl_deleg_levels[] = {
87 { "none", CURLGSSAPI_DELEGATION_NONE },
88 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
89 { "always", CURLGSSAPI_DELEGATION_FLAG },
93 static struct credential proxy_auth = CREDENTIAL_INIT;
94 static const char *curl_proxyuserpwd;
95 static const char *curl_cookie_file;
96 static int curl_save_cookies;
97 struct credential http_auth = CREDENTIAL_INIT;
98 static int http_proactive_auth;
99 static const char *user_agent;
100 static int curl_empty_auth = -1;
102 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
104 static struct credential cert_auth = CREDENTIAL_INIT;
105 static int ssl_cert_password_required;
106 static unsigned long http_auth_methods = CURLAUTH_ANY;
107 static int http_auth_methods_restricted;
108 /* Modes for which empty_auth cannot actually help us. */
109 static unsigned long empty_auth_useless =
114 static struct curl_slist *pragma_header;
115 static struct curl_slist *no_pragma_header;
116 static struct curl_slist *extra_http_headers;
118 static struct active_request_slot *active_queue_head;
120 static char *cached_accept_language;
122 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
124 size_t size = eltsize * nmemb;
125 struct buffer *buffer = buffer_;
127 if (size > buffer->buf.len - buffer->posn)
128 size = buffer->buf.len - buffer->posn;
129 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
130 buffer->posn += size;
135 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
137 struct buffer *buffer = clientp;
143 case CURLIOCMD_RESTARTREAD:
148 return CURLIOE_UNKNOWNCMD;
152 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
154 size_t size = eltsize * nmemb;
155 struct strbuf *buffer = buffer_;
157 strbuf_add(buffer, ptr, size);
161 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
163 return eltsize * nmemb;
166 static void closedown_active_slot(struct active_request_slot *slot)
172 static void finish_active_slot(struct active_request_slot *slot)
174 closedown_active_slot(slot);
175 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
177 if (slot->finished != NULL)
178 (*slot->finished) = 1;
180 /* Store slot results so they can be read after the slot is reused */
181 if (slot->results != NULL) {
182 slot->results->curl_result = slot->curl_result;
183 slot->results->http_code = slot->http_code;
184 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
185 &slot->results->auth_avail);
187 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
188 &slot->results->http_connectcode);
191 /* Run callback if appropriate */
192 if (slot->callback_func != NULL)
193 slot->callback_func(slot->callback_data);
196 static void xmulti_remove_handle(struct active_request_slot *slot)
198 curl_multi_remove_handle(curlm, slot->curl);
201 static void process_curl_messages(void)
204 struct active_request_slot *slot;
205 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
207 while (curl_message != NULL) {
208 if (curl_message->msg == CURLMSG_DONE) {
209 int curl_result = curl_message->data.result;
210 slot = active_queue_head;
211 while (slot != NULL &&
212 slot->curl != curl_message->easy_handle)
215 xmulti_remove_handle(slot);
216 slot->curl_result = curl_result;
217 finish_active_slot(slot);
219 fprintf(stderr, "Received DONE message for unknown request!\n");
222 fprintf(stderr, "Unknown CURL message received: %d\n",
223 (int)curl_message->msg);
225 curl_message = curl_multi_info_read(curlm, &num_messages);
229 static int http_options(const char *var, const char *value, void *cb)
231 if (!strcmp("http.sslverify", var)) {
232 curl_ssl_verify = git_config_bool(var, value);
235 if (!strcmp("http.sslcipherlist", var))
236 return git_config_string(&ssl_cipherlist, var, value);
237 if (!strcmp("http.sslversion", var))
238 return git_config_string(&ssl_version, var, value);
239 if (!strcmp("http.sslcert", var))
240 return git_config_pathname(&ssl_cert, var, value);
241 if (!strcmp("http.sslkey", var))
242 return git_config_pathname(&ssl_key, var, value);
243 if (!strcmp("http.sslcapath", var))
244 return git_config_pathname(&ssl_capath, var, value);
245 if (!strcmp("http.sslcainfo", var))
246 return git_config_pathname(&ssl_cainfo, var, value);
247 if (!strcmp("http.sslcertpasswordprotected", var)) {
248 ssl_cert_password_required = git_config_bool(var, value);
251 if (!strcmp("http.ssltry", var)) {
252 curl_ssl_try = git_config_bool(var, value);
255 if (!strcmp("http.minsessions", var)) {
256 min_curl_sessions = git_config_int(var, value);
257 if (min_curl_sessions > 1)
258 min_curl_sessions = 1;
261 if (!strcmp("http.maxrequests", var)) {
262 max_requests = git_config_int(var, value);
265 if (!strcmp("http.lowspeedlimit", var)) {
266 curl_low_speed_limit = (long)git_config_int(var, value);
269 if (!strcmp("http.lowspeedtime", var)) {
270 curl_low_speed_time = (long)git_config_int(var, value);
274 if (!strcmp("http.noepsv", var)) {
275 curl_ftp_no_epsv = git_config_bool(var, value);
278 if (!strcmp("http.proxy", var))
279 return git_config_string(&curl_http_proxy, var, value);
281 if (!strcmp("http.proxyauthmethod", var))
282 return git_config_string(&http_proxy_authmethod, var, value);
284 if (!strcmp("http.cookiefile", var))
285 return git_config_pathname(&curl_cookie_file, var, value);
286 if (!strcmp("http.savecookies", var)) {
287 curl_save_cookies = git_config_bool(var, value);
291 if (!strcmp("http.postbuffer", var)) {
292 http_post_buffer = git_config_ssize_t(var, value);
293 if (http_post_buffer < 0)
294 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
295 if (http_post_buffer < LARGE_PACKET_MAX)
296 http_post_buffer = LARGE_PACKET_MAX;
300 if (!strcmp("http.useragent", var))
301 return git_config_string(&user_agent, var, value);
303 if (!strcmp("http.emptyauth", var)) {
304 if (value && !strcmp("auto", value))
305 curl_empty_auth = -1;
307 curl_empty_auth = git_config_bool(var, value);
311 if (!strcmp("http.delegation", var)) {
312 #ifdef CURLGSSAPI_DELEGATION_FLAG
313 return git_config_string(&curl_deleg, var, value);
315 warning(_("Delegation control is not supported with cURL < 7.22.0"));
320 if (!strcmp("http.pinnedpubkey", var)) {
321 #if LIBCURL_VERSION_NUM >= 0x072c00
322 return git_config_pathname(&ssl_pinnedkey, var, value);
324 warning(_("Public key pinning not supported with cURL < 7.44.0"));
329 if (!strcmp("http.extraheader", var)) {
331 return config_error_nonbool(var);
332 } else if (!*value) {
333 curl_slist_free_all(extra_http_headers);
334 extra_http_headers = NULL;
337 curl_slist_append(extra_http_headers, value);
342 if (!strcmp("http.followredirects", var)) {
343 if (value && !strcmp(value, "initial"))
344 http_follow_config = HTTP_FOLLOW_INITIAL;
345 else if (git_config_bool(var, value))
346 http_follow_config = HTTP_FOLLOW_ALWAYS;
348 http_follow_config = HTTP_FOLLOW_NONE;
352 /* Fall back on the default ones */
353 return git_default_config(var, value, cb);
356 static int curl_empty_auth_enabled(void)
358 if (curl_empty_auth >= 0)
359 return curl_empty_auth;
362 * In the automatic case, kick in the empty-auth
363 * hack as long as we would potentially try some
364 * method more exotic than "Basic" or "Digest".
366 * But only do this when this is our second or
367 * subsequent request, as by then we know what
368 * methods are available.
370 if (http_auth_methods_restricted &&
371 (http_auth_methods & ~empty_auth_useless))
376 static void init_curl_http_auth(CURL *result)
378 if (!http_auth.username || !*http_auth.username) {
379 if (curl_empty_auth_enabled())
380 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
384 credential_fill(&http_auth);
386 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
387 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
390 /* *var must be free-able */
391 static void var_override(const char **var, char *value)
395 *var = xstrdup(value);
399 static void set_proxyauth_name_password(CURL *result)
401 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
402 proxy_auth.username);
403 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
404 proxy_auth.password);
407 static void init_curl_proxy_auth(CURL *result)
409 if (proxy_auth.username) {
410 if (!proxy_auth.password)
411 credential_fill(&proxy_auth);
412 set_proxyauth_name_password(result);
415 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
417 if (http_proxy_authmethod) {
419 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
420 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
421 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
422 proxy_authmethods[i].curlauth_param);
426 if (i == ARRAY_SIZE(proxy_authmethods)) {
427 warning("unsupported proxy authentication method %s: using anyauth",
428 http_proxy_authmethod);
429 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
433 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
436 static int has_cert_password(void)
438 if (ssl_cert == NULL || ssl_cert_password_required != 1)
440 if (!cert_auth.password) {
441 cert_auth.protocol = xstrdup("cert");
442 cert_auth.username = xstrdup("");
443 cert_auth.path = xstrdup(ssl_cert);
444 credential_fill(&cert_auth);
449 #if LIBCURL_VERSION_NUM >= 0x071900
450 static void set_curl_keepalive(CURL *c)
452 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
456 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
460 socklen_t len = (socklen_t)sizeof(ka);
462 if (type != CURLSOCKTYPE_IPCXN)
465 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
467 warning_errno("unable to set SO_KEEPALIVE on socket");
469 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
472 static void set_curl_keepalive(CURL *c)
474 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
478 static void redact_sensitive_header(struct strbuf *header)
480 const char *sensitive_header;
482 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
483 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
484 /* The first token is the type, which is OK to log */
485 while (isspace(*sensitive_header))
487 while (*sensitive_header && !isspace(*sensitive_header))
489 /* Everything else is opaque and possibly sensitive */
490 strbuf_setlen(header, sensitive_header - header->buf);
491 strbuf_addstr(header, " <redacted>");
492 } else if (cookies_to_redact.nr &&
493 skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
494 struct strbuf redacted_header = STRBUF_INIT;
497 while (isspace(*sensitive_header))
501 * The contents of header starting from sensitive_header will
502 * subsequently be overridden, so it is fine to mutate this
503 * string (hence the assignment to "char *").
505 cookie = (char *) sensitive_header;
509 char *semicolon = strstr(cookie, "; ");
512 equals = strchrnul(cookie, '=');
514 /* invalid cookie, just append and continue */
515 strbuf_addstr(&redacted_header, cookie);
518 *equals = 0; /* temporarily set to NUL for lookup */
519 if (string_list_lookup(&cookies_to_redact, cookie)) {
520 strbuf_addstr(&redacted_header, cookie);
521 strbuf_addstr(&redacted_header, "=<redacted>");
524 strbuf_addstr(&redacted_header, cookie);
528 * There are more cookies. (Or, for some
529 * reason, the input string ends in "; ".)
531 strbuf_addstr(&redacted_header, "; ");
532 cookie = semicolon + strlen("; ");
538 strbuf_setlen(header, sensitive_header - header->buf);
539 strbuf_addbuf(header, &redacted_header);
543 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
545 struct strbuf out = STRBUF_INIT;
546 struct strbuf **headers, **header;
548 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
549 text, (long)size, (long)size);
550 trace_strbuf(&trace_curl, &out);
552 strbuf_add(&out, ptr, size);
553 headers = strbuf_split_max(&out, '\n', 0);
555 for (header = headers; *header; header++) {
556 if (hide_sensitive_header)
557 redact_sensitive_header(*header);
558 strbuf_insert((*header), 0, text, strlen(text));
559 strbuf_insert((*header), strlen(text), ": ", 2);
560 strbuf_rtrim((*header));
561 strbuf_addch((*header), '\n');
562 trace_strbuf(&trace_curl, (*header));
564 strbuf_list_free(headers);
565 strbuf_release(&out);
568 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
571 struct strbuf out = STRBUF_INIT;
572 unsigned int width = 60;
574 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
575 text, (long)size, (long)size);
576 trace_strbuf(&trace_curl, &out);
578 for (i = 0; i < size; i += width) {
582 strbuf_addf(&out, "%s: ", text);
583 for (w = 0; (w < width) && (i + w < size); w++) {
584 unsigned char ch = ptr[i + w];
587 (ch >= 0x20) && (ch < 0x80)
590 strbuf_addch(&out, '\n');
591 trace_strbuf(&trace_curl, &out);
593 strbuf_release(&out);
596 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
599 enum { NO_FILTER = 0, DO_FILTER = 1 };
603 trace_printf_key(&trace_curl, "== Info: %s", data);
605 case CURLINFO_HEADER_OUT:
606 text = "=> Send header";
607 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
609 case CURLINFO_DATA_OUT:
610 if (trace_curl_data) {
611 text = "=> Send data";
612 curl_dump_data(text, (unsigned char *)data, size);
615 case CURLINFO_SSL_DATA_OUT:
616 if (trace_curl_data) {
617 text = "=> Send SSL data";
618 curl_dump_data(text, (unsigned char *)data, size);
621 case CURLINFO_HEADER_IN:
622 text = "<= Recv header";
623 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
625 case CURLINFO_DATA_IN:
626 if (trace_curl_data) {
627 text = "<= Recv data";
628 curl_dump_data(text, (unsigned char *)data, size);
631 case CURLINFO_SSL_DATA_IN:
632 if (trace_curl_data) {
633 text = "<= Recv SSL data";
634 curl_dump_data(text, (unsigned char *)data, size);
638 default: /* we ignore unknown types by default */
644 void setup_curl_trace(CURL *handle)
646 if (!trace_want(&trace_curl))
648 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
649 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
650 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
653 #ifdef CURLPROTO_HTTP
654 static long get_curl_allowed_protocols(int from_user)
656 long allowed_protocols = 0;
658 if (is_transport_allowed("http", from_user))
659 allowed_protocols |= CURLPROTO_HTTP;
660 if (is_transport_allowed("https", from_user))
661 allowed_protocols |= CURLPROTO_HTTPS;
662 if (is_transport_allowed("ftp", from_user))
663 allowed_protocols |= CURLPROTO_FTP;
664 if (is_transport_allowed("ftps", from_user))
665 allowed_protocols |= CURLPROTO_FTPS;
667 return allowed_protocols;
671 static CURL *get_curl_handle(void)
673 CURL *result = curl_easy_init();
676 die("curl_easy_init failed");
678 if (!curl_ssl_verify) {
679 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
680 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
682 /* Verify authenticity of the peer's certificate */
683 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
684 /* The name in the cert must match whom we tried to connect */
685 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
688 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
689 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
691 #ifdef CURLGSSAPI_DELEGATION_FLAG
694 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
695 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
696 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
697 curl_deleg_levels[i].curl_deleg_param);
701 if (i == ARRAY_SIZE(curl_deleg_levels))
702 warning("Unknown delegation method '%s': using default",
707 if (http_proactive_auth)
708 init_curl_http_auth(result);
710 if (getenv("GIT_SSL_VERSION"))
711 ssl_version = getenv("GIT_SSL_VERSION");
712 if (ssl_version && *ssl_version) {
714 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
715 if (!strcmp(ssl_version, sslversions[i].name)) {
716 curl_easy_setopt(result, CURLOPT_SSLVERSION,
717 sslversions[i].ssl_version);
721 if (i == ARRAY_SIZE(sslversions))
722 warning("unsupported ssl version %s: using default",
726 if (getenv("GIT_SSL_CIPHER_LIST"))
727 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
728 if (ssl_cipherlist != NULL && *ssl_cipherlist)
729 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
732 if (ssl_cert != NULL)
733 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
734 if (has_cert_password())
735 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
737 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
738 if (ssl_capath != NULL)
739 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
740 #if LIBCURL_VERSION_NUM >= 0x072c00
741 if (ssl_pinnedkey != NULL)
742 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
744 if (ssl_cainfo != NULL)
745 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
747 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
748 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
749 curl_low_speed_limit);
750 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
751 curl_low_speed_time);
754 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
755 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
756 curl_easy_setopt(result, CURLOPT_POST301, 1);
757 #ifdef CURLPROTO_HTTP
758 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
759 get_curl_allowed_protocols(0));
760 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
761 get_curl_allowed_protocols(-1));
763 warning("protocol restrictions not applied to curl redirects because\n"
764 "your curl version is too old and lack CURLPROTO_HTTP etc.");
766 if (getenv("GIT_CURL_VERBOSE"))
767 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
768 setup_curl_trace(result);
769 if (getenv("GIT_TRACE_CURL_NO_DATA"))
771 if (getenv("GIT_REDACT_COOKIES")) {
772 string_list_split(&cookies_to_redact,
773 getenv("GIT_REDACT_COOKIES"), ',', -1);
774 string_list_sort(&cookies_to_redact);
777 curl_easy_setopt(result, CURLOPT_USERAGENT,
778 user_agent ? user_agent : git_user_agent());
780 if (curl_ftp_no_epsv)
781 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
784 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
787 * CURL also examines these variables as a fallback; but we need to query
788 * them here in order to decide whether to prompt for missing password (cf.
789 * init_curl_proxy_auth()).
791 * Unlike many other common environment variables, these are historically
792 * lowercase only. It appears that CURL did not know this and implemented
793 * only uppercase variants, which was later corrected to take both - with
794 * the exception of http_proxy, which is lowercase only also in CURL. As
795 * the lowercase versions are the historical quasi-standard, they take
796 * precedence here, as in CURL.
798 if (!curl_http_proxy) {
799 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
800 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
801 var_override(&curl_http_proxy, getenv("https_proxy"));
803 var_override(&curl_http_proxy, getenv("http_proxy"));
805 if (!curl_http_proxy) {
806 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
807 var_override(&curl_http_proxy, getenv("all_proxy"));
811 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
813 * Handle case with the empty http.proxy value here to keep
815 * NB: empty option disables proxying at all.
817 curl_easy_setopt(result, CURLOPT_PROXY, "");
818 } else if (curl_http_proxy) {
819 #if LIBCURL_VERSION_NUM >= 0x071800
820 if (starts_with(curl_http_proxy, "socks5h"))
821 curl_easy_setopt(result,
822 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
823 else if (starts_with(curl_http_proxy, "socks5"))
824 curl_easy_setopt(result,
825 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
826 else if (starts_with(curl_http_proxy, "socks4a"))
827 curl_easy_setopt(result,
828 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
829 else if (starts_with(curl_http_proxy, "socks"))
830 curl_easy_setopt(result,
831 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
833 #if LIBCURL_VERSION_NUM >= 0x073400
834 else if (starts_with(curl_http_proxy, "https"))
835 curl_easy_setopt(result,
836 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
838 if (strstr(curl_http_proxy, "://"))
839 credential_from_url(&proxy_auth, curl_http_proxy);
841 struct strbuf url = STRBUF_INIT;
842 strbuf_addf(&url, "http://%s", curl_http_proxy);
843 credential_from_url(&proxy_auth, url.buf);
844 strbuf_release(&url);
847 if (!proxy_auth.host)
848 die("Invalid proxy URL '%s'", curl_http_proxy);
850 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
851 var_override(&curl_no_proxy, getenv("NO_PROXY"));
852 var_override(&curl_no_proxy, getenv("no_proxy"));
853 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
855 init_curl_proxy_auth(result);
857 set_curl_keepalive(result);
862 static void set_from_env(const char **var, const char *envname)
864 const char *val = getenv(envname);
869 void http_init(struct remote *remote, const char *url, int proactive_auth)
871 char *low_speed_limit;
872 char *low_speed_time;
873 char *normalized_url;
874 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
876 config.section = "http";
878 config.collect_fn = http_options;
879 config.cascade_fn = git_default_config;
883 normalized_url = url_normalize(url, &config.url);
885 git_config(urlmatch_config_entry, &config);
886 free(normalized_url);
888 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
889 die("curl_global_init failed");
891 http_proactive_auth = proactive_auth;
893 if (remote && remote->http_proxy)
894 curl_http_proxy = xstrdup(remote->http_proxy);
897 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
899 pragma_header = curl_slist_append(http_copy_default_headers(),
901 no_pragma_header = curl_slist_append(http_copy_default_headers(),
905 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
906 if (http_max_requests != NULL)
907 max_requests = atoi(http_max_requests);
910 curlm = curl_multi_init();
912 die("curl_multi_init failed");
914 if (getenv("GIT_SSL_NO_VERIFY"))
917 set_from_env(&ssl_cert, "GIT_SSL_CERT");
918 set_from_env(&ssl_key, "GIT_SSL_KEY");
919 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
920 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
922 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
924 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
925 if (low_speed_limit != NULL)
926 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
927 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
928 if (low_speed_time != NULL)
929 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
931 if (curl_ssl_verify == -1)
934 curl_session_count = 0;
935 if (max_requests < 1)
936 max_requests = DEFAULT_MAX_REQUESTS;
938 if (getenv("GIT_CURL_FTP_NO_EPSV"))
939 curl_ftp_no_epsv = 1;
942 credential_from_url(&http_auth, url);
943 if (!ssl_cert_password_required &&
944 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
945 starts_with(url, "https://"))
946 ssl_cert_password_required = 1;
949 curl_default = get_curl_handle();
952 void http_cleanup(void)
954 struct active_request_slot *slot = active_queue_head;
956 while (slot != NULL) {
957 struct active_request_slot *next = slot->next;
958 if (slot->curl != NULL) {
959 xmulti_remove_handle(slot);
960 curl_easy_cleanup(slot->curl);
965 active_queue_head = NULL;
967 curl_easy_cleanup(curl_default);
969 curl_multi_cleanup(curlm);
970 curl_global_cleanup();
972 curl_slist_free_all(extra_http_headers);
973 extra_http_headers = NULL;
975 curl_slist_free_all(pragma_header);
976 pragma_header = NULL;
978 curl_slist_free_all(no_pragma_header);
979 no_pragma_header = NULL;
981 if (curl_http_proxy) {
982 free((void *)curl_http_proxy);
983 curl_http_proxy = NULL;
986 if (proxy_auth.password) {
987 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
988 FREE_AND_NULL(proxy_auth.password);
991 free((void *)curl_proxyuserpwd);
992 curl_proxyuserpwd = NULL;
994 free((void *)http_proxy_authmethod);
995 http_proxy_authmethod = NULL;
997 if (cert_auth.password != NULL) {
998 memset(cert_auth.password, 0, strlen(cert_auth.password));
999 FREE_AND_NULL(cert_auth.password);
1001 ssl_cert_password_required = 0;
1003 FREE_AND_NULL(cached_accept_language);
1006 struct active_request_slot *get_active_slot(void)
1008 struct active_request_slot *slot = active_queue_head;
1009 struct active_request_slot *newslot;
1013 /* Wait for a slot to open up if the queue is full */
1014 while (active_requests >= max_requests) {
1015 curl_multi_perform(curlm, &num_transfers);
1016 if (num_transfers < active_requests)
1017 process_curl_messages();
1020 while (slot != NULL && slot->in_use)
1024 newslot = xmalloc(sizeof(*newslot));
1025 newslot->curl = NULL;
1026 newslot->in_use = 0;
1027 newslot->next = NULL;
1029 slot = active_queue_head;
1031 active_queue_head = newslot;
1033 while (slot->next != NULL)
1035 slot->next = newslot;
1040 if (slot->curl == NULL) {
1041 slot->curl = curl_easy_duphandle(curl_default);
1042 curl_session_count++;
1047 slot->results = NULL;
1048 slot->finished = NULL;
1049 slot->callback_data = NULL;
1050 slot->callback_func = NULL;
1051 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1052 if (curl_save_cookies)
1053 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1054 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1055 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1056 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1057 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1058 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1059 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1060 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1061 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1062 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1063 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1066 * Default following to off unless "ALWAYS" is configured; this gives
1067 * callers a sane starting point, and they can tweak for individual
1068 * HTTP_FOLLOW_* cases themselves.
1070 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1071 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1073 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1075 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1076 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1077 if (http_auth.password || curl_empty_auth_enabled())
1078 init_curl_http_auth(slot->curl);
1083 int start_active_slot(struct active_request_slot *slot)
1085 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1088 if (curlm_result != CURLM_OK &&
1089 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1090 warning("curl_multi_add_handle failed: %s",
1091 curl_multi_strerror(curlm_result));
1098 * We know there must be something to do, since we just added
1101 curl_multi_perform(curlm, &num_transfers);
1107 int (*fill)(void *);
1108 struct fill_chain *next;
1111 static struct fill_chain *fill_cfg;
1113 void add_fill_function(void *data, int (*fill)(void *))
1115 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1116 struct fill_chain **linkp = &fill_cfg;
1117 new_fill->data = data;
1118 new_fill->fill = fill;
1119 new_fill->next = NULL;
1121 linkp = &(*linkp)->next;
1125 void fill_active_slots(void)
1127 struct active_request_slot *slot = active_queue_head;
1129 while (active_requests < max_requests) {
1130 struct fill_chain *fill;
1131 for (fill = fill_cfg; fill; fill = fill->next)
1132 if (fill->fill(fill->data))
1139 while (slot != NULL) {
1140 if (!slot->in_use && slot->curl != NULL
1141 && curl_session_count > min_curl_sessions) {
1142 curl_easy_cleanup(slot->curl);
1144 curl_session_count--;
1150 void step_active_slots(void)
1153 CURLMcode curlm_result;
1156 curlm_result = curl_multi_perform(curlm, &num_transfers);
1157 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1158 if (num_transfers < active_requests) {
1159 process_curl_messages();
1160 fill_active_slots();
1164 void run_active_slot(struct active_request_slot *slot)
1170 struct timeval select_timeout;
1173 slot->finished = &finished;
1175 step_active_slots();
1179 curl_multi_timeout(curlm, &curl_timeout);
1180 if (curl_timeout == 0) {
1182 } else if (curl_timeout == -1) {
1183 select_timeout.tv_sec = 0;
1184 select_timeout.tv_usec = 50000;
1186 select_timeout.tv_sec = curl_timeout / 1000;
1187 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1194 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1197 * It can happen that curl_multi_timeout returns a pathologically
1198 * long timeout when curl_multi_fdset returns no file descriptors
1199 * to read. See commit message for more details.
1202 (select_timeout.tv_sec > 0 ||
1203 select_timeout.tv_usec > 50000)) {
1204 select_timeout.tv_sec = 0;
1205 select_timeout.tv_usec = 50000;
1208 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1213 static void release_active_slot(struct active_request_slot *slot)
1215 closedown_active_slot(slot);
1217 xmulti_remove_handle(slot);
1218 if (curl_session_count > min_curl_sessions) {
1219 curl_easy_cleanup(slot->curl);
1221 curl_session_count--;
1224 fill_active_slots();
1227 void finish_all_active_slots(void)
1229 struct active_request_slot *slot = active_queue_head;
1231 while (slot != NULL)
1233 run_active_slot(slot);
1234 slot = active_queue_head;
1240 /* Helpers for modifying and creating URLs */
1241 static inline int needs_quote(int ch)
1243 if (((ch >= 'A') && (ch <= 'Z'))
1244 || ((ch >= 'a') && (ch <= 'z'))
1245 || ((ch >= '0') && (ch <= '9'))
1253 static char *quote_ref_url(const char *base, const char *ref)
1255 struct strbuf buf = STRBUF_INIT;
1259 end_url_with_slash(&buf, base);
1261 for (cp = ref; (ch = *cp) != 0; cp++)
1262 if (needs_quote(ch))
1263 strbuf_addf(&buf, "%%%02x", ch);
1265 strbuf_addch(&buf, *cp);
1267 return strbuf_detach(&buf, NULL);
1270 void append_remote_object_url(struct strbuf *buf, const char *url,
1272 int only_two_digit_prefix)
1274 end_url_with_slash(buf, url);
1276 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1277 if (!only_two_digit_prefix)
1278 strbuf_addstr(buf, hex + 2);
1281 char *get_remote_object_url(const char *url, const char *hex,
1282 int only_two_digit_prefix)
1284 struct strbuf buf = STRBUF_INIT;
1285 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1286 return strbuf_detach(&buf, NULL);
1289 static int handle_curl_result(struct slot_results *results)
1292 * If we see a failing http code with CURLE_OK, we have turned off
1293 * FAILONERROR (to keep the server's custom error response), and should
1294 * translate the code into failure here.
1296 * Likewise, if we see a redirect (30x code), that means we turned off
1297 * redirect-following, and we should treat the result as an error.
1299 if (results->curl_result == CURLE_OK &&
1300 results->http_code >= 300) {
1301 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1303 * Normally curl will already have put the "reason phrase"
1304 * from the server into curl_errorstr; unfortunately without
1305 * FAILONERROR it is lost, so we can give only the numeric
1308 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1309 "The requested URL returned error: %ld",
1310 results->http_code);
1313 if (results->curl_result == CURLE_OK) {
1314 credential_approve(&http_auth);
1315 if (proxy_auth.password)
1316 credential_approve(&proxy_auth);
1318 } else if (missing_target(results))
1319 return HTTP_MISSING_TARGET;
1320 else if (results->http_code == 401) {
1321 if (http_auth.username && http_auth.password) {
1322 credential_reject(&http_auth);
1325 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1326 if (results->auth_avail) {
1327 http_auth_methods &= results->auth_avail;
1328 http_auth_methods_restricted = 1;
1333 if (results->http_connectcode == 407)
1334 credential_reject(&proxy_auth);
1335 if (!curl_errorstr[0])
1336 strlcpy(curl_errorstr,
1337 curl_easy_strerror(results->curl_result),
1338 sizeof(curl_errorstr));
1343 int run_one_slot(struct active_request_slot *slot,
1344 struct slot_results *results)
1346 slot->results = results;
1347 if (!start_active_slot(slot)) {
1348 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1349 "failed to start HTTP request");
1350 return HTTP_START_FAILED;
1353 run_active_slot(slot);
1354 return handle_curl_result(results);
1357 struct curl_slist *http_copy_default_headers(void)
1359 struct curl_slist *headers = NULL, *h;
1361 for (h = extra_http_headers; h; h = h->next)
1362 headers = curl_slist_append(headers, h->data);
1367 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1373 ret = curl_easy_getinfo(curl, info, &ptr);
1375 strbuf_addstr(buf, ptr);
1380 * Check for and extract a content-type parameter. "raw"
1381 * should be positioned at the start of the potential
1382 * parameter, with any whitespace already removed.
1384 * "name" is the name of the parameter. The value is appended
1387 static int extract_param(const char *raw, const char *name,
1390 size_t len = strlen(name);
1392 if (strncasecmp(raw, name, len))
1400 while (*raw && !isspace(*raw) && *raw != ';')
1401 strbuf_addch(out, *raw++);
1406 * Extract a normalized version of the content type, with any
1407 * spaces suppressed, all letters lowercased, and no trailing ";"
1410 * Note that we will silently remove even invalid whitespace. For
1411 * example, "text / plain" is specifically forbidden by RFC 2616,
1412 * but "text/plain" is the only reasonable output, and this keeps
1415 * If the "charset" argument is not NULL, store the value of any
1416 * charset parameter there.
1419 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1420 * "text / plain" -> "text/plain"
1422 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1423 struct strbuf *charset)
1428 strbuf_grow(type, raw->len);
1429 for (p = raw->buf; *p; p++) {
1436 strbuf_addch(type, tolower(*p));
1442 strbuf_reset(charset);
1444 while (isspace(*p) || *p == ';')
1446 if (!extract_param(p, "charset", charset))
1448 while (*p && !isspace(*p))
1452 if (!charset->len && starts_with(type->buf, "text/"))
1453 strbuf_addstr(charset, "ISO-8859-1");
1456 static void write_accept_language(struct strbuf *buf)
1459 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1460 * that, q-value will be smaller than 0.001, the minimum q-value the
1461 * HTTP specification allows. See
1462 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1464 const int MAX_DECIMAL_PLACES = 3;
1465 const int MAX_LANGUAGE_TAGS = 1000;
1466 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1467 char **language_tags = NULL;
1469 const char *s = get_preferred_languages();
1471 struct strbuf tag = STRBUF_INIT;
1473 /* Don't add Accept-Language header if no language is preferred. */
1478 * Split the colon-separated string of preferred languages into
1479 * language_tags array.
1482 /* collect language tag */
1483 for (; *s && (isalnum(*s) || *s == '_'); s++)
1484 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1486 /* skip .codeset, @modifier and any other unnecessary parts */
1487 while (*s && *s != ':')
1492 REALLOC_ARRAY(language_tags, num_langs);
1493 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1494 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1499 /* write Accept-Language header into buf */
1501 int last_buf_len = 0;
1507 REALLOC_ARRAY(language_tags, num_langs + 1);
1508 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1510 /* compute decimal_places */
1511 for (max_q = 1, decimal_places = 0;
1512 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1513 decimal_places++, max_q *= 10)
1516 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1518 strbuf_addstr(buf, "Accept-Language: ");
1520 for (i = 0; i < num_langs; i++) {
1522 strbuf_addstr(buf, ", ");
1524 strbuf_addstr(buf, language_tags[i]);
1527 strbuf_addf(buf, q_format, max_q - i);
1529 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1530 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1534 last_buf_len = buf->len;
1538 /* free language tags -- last one is a static '*' */
1539 for (i = 0; i < num_langs - 1; i++)
1540 free(language_tags[i]);
1541 free(language_tags);
1545 * Get an Accept-Language header which indicates user's preferred languages.
1549 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1550 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1551 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1552 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1553 * LANGUAGE= LANG=C -> ""
1555 static const char *get_accept_language(void)
1557 if (!cached_accept_language) {
1558 struct strbuf buf = STRBUF_INIT;
1559 write_accept_language(&buf);
1561 cached_accept_language = strbuf_detach(&buf, NULL);
1564 return cached_accept_language;
1567 static void http_opt_request_remainder(CURL *curl, off_t pos)
1570 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1571 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1574 /* http_request() targets */
1575 #define HTTP_REQUEST_STRBUF 0
1576 #define HTTP_REQUEST_FILE 1
1578 static int http_request(const char *url,
1579 void *result, int target,
1580 const struct http_get_options *options)
1582 struct active_request_slot *slot;
1583 struct slot_results results;
1584 struct curl_slist *headers = http_copy_default_headers();
1585 struct strbuf buf = STRBUF_INIT;
1586 const char *accept_language;
1589 slot = get_active_slot();
1590 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1592 if (result == NULL) {
1593 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1595 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1596 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1598 if (target == HTTP_REQUEST_FILE) {
1599 off_t posn = ftello(result);
1600 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1603 http_opt_request_remainder(slot->curl, posn);
1605 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1609 accept_language = get_accept_language();
1611 if (accept_language)
1612 headers = curl_slist_append(headers, accept_language);
1614 strbuf_addstr(&buf, "Pragma:");
1615 if (options && options->no_cache)
1616 strbuf_addstr(&buf, " no-cache");
1617 if (options && options->keep_error)
1618 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1619 if (options && options->initial_request &&
1620 http_follow_config == HTTP_FOLLOW_INITIAL)
1621 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1623 headers = curl_slist_append(headers, buf.buf);
1625 /* Add additional headers here */
1626 if (options && options->extra_headers) {
1627 const struct string_list_item *item;
1628 for_each_string_list_item(item, options->extra_headers) {
1629 headers = curl_slist_append(headers, item->string);
1633 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1634 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1635 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1637 ret = run_one_slot(slot, &results);
1639 if (options && options->content_type) {
1640 struct strbuf raw = STRBUF_INIT;
1641 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1642 extract_content_type(&raw, options->content_type,
1644 strbuf_release(&raw);
1647 if (options && options->effective_url)
1648 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1649 options->effective_url);
1651 curl_slist_free_all(headers);
1652 strbuf_release(&buf);
1658 * Update the "base" url to a more appropriate value, as deduced by
1659 * redirects seen when requesting a URL starting with "url".
1661 * The "asked" parameter is a URL that we asked curl to access, and must begin
1664 * The "got" parameter is the URL that curl reported to us as where we ended
1667 * Returns 1 if we updated the base url, 0 otherwise.
1669 * Our basic strategy is to compare "base" and "asked" to find the bits
1670 * specific to our request. We then strip those bits off of "got" to yield the
1671 * new base. So for example, if our base is "http://example.com/foo.git",
1672 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1673 * with "https://other.example.com/foo.git/info/refs". We would want the
1674 * new URL to become "https://other.example.com/foo.git".
1676 * Note that this assumes a sane redirect scheme. It's entirely possible
1677 * in the example above to end up at a URL that does not even end in
1678 * "info/refs". In such a case we die. There's not much we can do, such a
1679 * scheme is unlikely to represent a real git repository, and failing to
1680 * rewrite the base opens options for malicious redirects to do funny things.
1682 static int update_url_from_redirect(struct strbuf *base,
1684 const struct strbuf *got)
1689 if (!strcmp(asked, got->buf))
1692 if (!skip_prefix(asked, base->buf, &tail))
1693 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1697 if (!strip_suffix_mem(got->buf, &new_len, tail))
1698 die(_("unable to update url base from redirection:\n"
1704 strbuf_add(base, got->buf, new_len);
1709 static int http_request_reauth(const char *url,
1710 void *result, int target,
1711 struct http_get_options *options)
1713 int ret = http_request(url, result, target, options);
1715 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1718 if (options && options->effective_url && options->base_url) {
1719 if (update_url_from_redirect(options->base_url,
1720 url, options->effective_url)) {
1721 credential_from_url(&http_auth, options->base_url->buf);
1722 url = options->effective_url->buf;
1726 if (ret != HTTP_REAUTH)
1730 * If we are using KEEP_ERROR, the previous request may have
1731 * put cruft into our output stream; we should clear it out before
1732 * making our next request. We only know how to do this for
1733 * the strbuf case, but that is enough to satisfy current callers.
1735 if (options && options->keep_error) {
1737 case HTTP_REQUEST_STRBUF:
1738 strbuf_reset(result);
1741 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1745 credential_fill(&http_auth);
1747 return http_request(url, result, target, options);
1750 int http_get_strbuf(const char *url,
1751 struct strbuf *result,
1752 struct http_get_options *options)
1754 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1758 * Downloads a URL and stores the result in the given file.
1760 * If a previous interrupted download is detected (i.e. a previous temporary
1761 * file is still around) the download is resumed.
1763 static int http_get_file(const char *url, const char *filename,
1764 struct http_get_options *options)
1767 struct strbuf tmpfile = STRBUF_INIT;
1770 strbuf_addf(&tmpfile, "%s.temp", filename);
1771 result = fopen(tmpfile.buf, "a");
1773 error("Unable to open local file %s", tmpfile.buf);
1778 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1781 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1784 strbuf_release(&tmpfile);
1788 int http_fetch_ref(const char *base, struct ref *ref)
1790 struct http_get_options options = {0};
1792 struct strbuf buffer = STRBUF_INIT;
1795 options.no_cache = 1;
1797 url = quote_ref_url(base, ref->name);
1798 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1799 strbuf_rtrim(&buffer);
1800 if (buffer.len == 40)
1801 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1802 else if (starts_with(buffer.buf, "ref: ")) {
1803 ref->symref = xstrdup(buffer.buf + 5);
1808 strbuf_release(&buffer);
1813 /* Helpers for fetching packs */
1814 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1817 struct strbuf buf = STRBUF_INIT;
1819 if (http_is_verbose)
1820 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1822 end_url_with_slash(&buf, base_url);
1823 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1824 url = strbuf_detach(&buf, NULL);
1826 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1827 tmp = strbuf_detach(&buf, NULL);
1829 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1830 error("Unable to get pack index %s", url);
1838 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1839 unsigned char *sha1, const char *base_url)
1841 struct packed_git *new_pack;
1842 char *tmp_idx = NULL;
1845 if (has_pack_index(sha1)) {
1846 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1848 return -1; /* parse_pack_index() already issued error message */
1852 tmp_idx = fetch_pack_index(sha1, base_url);
1856 new_pack = parse_pack_index(sha1, tmp_idx);
1861 return -1; /* parse_pack_index() already issued error message */
1864 ret = verify_pack_index(new_pack);
1866 close_pack_index(new_pack);
1867 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1874 new_pack->next = *packs_head;
1875 *packs_head = new_pack;
1879 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1881 struct http_get_options options = {0};
1884 struct strbuf buf = STRBUF_INIT;
1885 unsigned char sha1[20];
1887 end_url_with_slash(&buf, base_url);
1888 strbuf_addstr(&buf, "objects/info/packs");
1889 url = strbuf_detach(&buf, NULL);
1891 options.no_cache = 1;
1892 ret = http_get_strbuf(url, &buf, &options);
1897 while (i < buf.len) {
1901 if (i + 52 <= buf.len &&
1902 starts_with(data + i, " pack-") &&
1903 starts_with(data + i + 46, ".pack\n")) {
1904 get_sha1_hex(data + i + 6, sha1);
1905 fetch_and_setup_pack_index(packs_head, sha1,
1911 while (i < buf.len && data[i] != '\n')
1922 void release_http_pack_request(struct http_pack_request *preq)
1924 if (preq->packfile != NULL) {
1925 fclose(preq->packfile);
1926 preq->packfile = NULL;
1933 int finish_http_pack_request(struct http_pack_request *preq)
1935 struct packed_git **lst;
1936 struct packed_git *p = preq->target;
1939 struct child_process ip = CHILD_PROCESS_INIT;
1941 close_pack_index(p);
1943 fclose(preq->packfile);
1944 preq->packfile = NULL;
1948 lst = &((*lst)->next);
1949 *lst = (*lst)->next;
1951 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1952 die("BUG: pack tmpfile does not end in .pack.temp?");
1953 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1955 argv_array_push(&ip.args, "index-pack");
1956 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
1957 argv_array_push(&ip.args, preq->tmpfile);
1962 if (run_command(&ip)) {
1963 unlink(preq->tmpfile);
1969 unlink(sha1_pack_index_name(p->sha1));
1971 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1972 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1977 install_packed_git(p);
1982 struct http_pack_request *new_http_pack_request(
1983 struct packed_git *target, const char *base_url)
1985 off_t prev_posn = 0;
1986 struct strbuf buf = STRBUF_INIT;
1987 struct http_pack_request *preq;
1989 preq = xcalloc(1, sizeof(*preq));
1990 preq->target = target;
1992 end_url_with_slash(&buf, base_url);
1993 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1994 sha1_to_hex(target->sha1));
1995 preq->url = strbuf_detach(&buf, NULL);
1997 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1998 sha1_pack_name(target->sha1));
1999 preq->packfile = fopen(preq->tmpfile, "a");
2000 if (!preq->packfile) {
2001 error("Unable to open local file %s for pack",
2006 preq->slot = get_active_slot();
2007 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2008 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2009 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2010 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2014 * If there is data present from a previous transfer attempt,
2015 * resume where it left off
2017 prev_posn = ftello(preq->packfile);
2019 if (http_is_verbose)
2021 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2022 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2023 http_opt_request_remainder(preq->slot->curl, prev_posn);
2034 /* Helpers for fetching objects (loose) */
2035 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2038 unsigned char expn[4096];
2039 size_t size = eltsize * nmemb;
2041 struct http_object_request *freq = data;
2042 struct active_request_slot *slot = freq->slot;
2045 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2048 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2049 curl_easy_strerror(c));
2050 if (slot->http_code >= 300)
2055 ssize_t retval = xwrite(freq->localfile,
2056 (char *) ptr + posn, size - posn);
2060 } while (posn < size);
2062 freq->stream.avail_in = size;
2063 freq->stream.next_in = (void *)ptr;
2065 freq->stream.next_out = expn;
2066 freq->stream.avail_out = sizeof(expn);
2067 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2068 git_SHA1_Update(&freq->c, expn,
2069 sizeof(expn) - freq->stream.avail_out);
2070 } while (freq->stream.avail_in && freq->zret == Z_OK);
2074 struct http_object_request *new_http_object_request(const char *base_url,
2075 unsigned char *sha1)
2077 char *hex = sha1_to_hex(sha1);
2078 struct strbuf filename = STRBUF_INIT;
2079 char prevfile[PATH_MAX];
2081 char prev_buf[PREV_BUF_SIZE];
2082 ssize_t prev_read = 0;
2083 off_t prev_posn = 0;
2084 struct http_object_request *freq;
2086 freq = xcalloc(1, sizeof(*freq));
2087 hashcpy(freq->sha1, sha1);
2088 freq->localfile = -1;
2090 sha1_file_name(&filename, sha1);
2091 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2092 "%s.temp", filename.buf);
2094 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename.buf);
2095 unlink_or_warn(prevfile);
2096 rename(freq->tmpfile, prevfile);
2097 unlink_or_warn(freq->tmpfile);
2098 strbuf_release(&filename);
2100 if (freq->localfile != -1)
2101 error("fd leakage in start: %d", freq->localfile);
2102 freq->localfile = open(freq->tmpfile,
2103 O_WRONLY | O_CREAT | O_EXCL, 0666);
2105 * This could have failed due to the "lazy directory creation";
2106 * try to mkdir the last path component.
2108 if (freq->localfile < 0 && errno == ENOENT) {
2109 char *dir = strrchr(freq->tmpfile, '/');
2112 mkdir(freq->tmpfile, 0777);
2115 freq->localfile = open(freq->tmpfile,
2116 O_WRONLY | O_CREAT | O_EXCL, 0666);
2119 if (freq->localfile < 0) {
2120 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2124 git_inflate_init(&freq->stream);
2126 git_SHA1_Init(&freq->c);
2128 freq->url = get_remote_object_url(base_url, hex, 0);
2131 * If a previous temp file is present, process what was already
2134 prevlocal = open(prevfile, O_RDONLY);
2135 if (prevlocal != -1) {
2137 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2139 if (fwrite_sha1_file(prev_buf,
2142 freq) == prev_read) {
2143 prev_posn += prev_read;
2148 } while (prev_read > 0);
2151 unlink_or_warn(prevfile);
2154 * Reset inflate/SHA1 if there was an error reading the previous temp
2155 * file; also rewind to the beginning of the local file.
2157 if (prev_read == -1) {
2158 memset(&freq->stream, 0, sizeof(freq->stream));
2159 git_inflate_init(&freq->stream);
2160 git_SHA1_Init(&freq->c);
2163 lseek(freq->localfile, 0, SEEK_SET);
2164 if (ftruncate(freq->localfile, 0) < 0) {
2165 error_errno("Couldn't truncate temporary file %s",
2172 freq->slot = get_active_slot();
2174 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2175 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2176 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2177 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2178 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2179 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2182 * If we have successfully processed data from a previous fetch
2183 * attempt, only fetch the data we don't already have.
2186 if (http_is_verbose)
2188 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2189 hex, (uintmax_t)prev_posn);
2190 http_opt_request_remainder(freq->slot->curl, prev_posn);
2201 void process_http_object_request(struct http_object_request *freq)
2203 if (freq->slot == NULL)
2205 freq->curl_result = freq->slot->curl_result;
2206 freq->http_code = freq->slot->http_code;
2210 int finish_http_object_request(struct http_object_request *freq)
2213 struct strbuf filename = STRBUF_INIT;
2215 close(freq->localfile);
2216 freq->localfile = -1;
2218 process_http_object_request(freq);
2220 if (freq->http_code == 416) {
2221 warning("requested range invalid; we may already have all the data.");
2222 } else if (freq->curl_result != CURLE_OK) {
2223 if (stat(freq->tmpfile, &st) == 0)
2224 if (st.st_size == 0)
2225 unlink_or_warn(freq->tmpfile);
2229 git_inflate_end(&freq->stream);
2230 git_SHA1_Final(freq->real_sha1, &freq->c);
2231 if (freq->zret != Z_STREAM_END) {
2232 unlink_or_warn(freq->tmpfile);
2235 if (hashcmp(freq->sha1, freq->real_sha1)) {
2236 unlink_or_warn(freq->tmpfile);
2240 sha1_file_name(&filename, freq->sha1);
2241 freq->rename = finalize_object_file(freq->tmpfile, filename.buf);
2242 strbuf_release(&filename);
2244 return freq->rename;
2247 void abort_http_object_request(struct http_object_request *freq)
2249 unlink_or_warn(freq->tmpfile);
2251 release_http_object_request(freq);
2254 void release_http_object_request(struct http_object_request *freq)
2256 if (freq->localfile != -1) {
2257 close(freq->localfile);
2258 freq->localfile = -1;
2260 if (freq->url != NULL) {
2261 FREE_AND_NULL(freq->url);
2263 if (freq->slot != NULL) {
2264 freq->slot->callback_func = NULL;
2265 freq->slot->callback_data = NULL;
2266 release_active_slot(freq->slot);