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 #if LIBCURL_VERSION_NUM >= 0x070a08
22 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
24 long int git_curl_ipresolve;
28 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
30 #if LIBCURL_VERSION_NUM >= 0x070a06
31 #define LIBCURL_CAN_HANDLE_AUTH_ANY
34 static int min_curl_sessions = 1;
35 static int curl_session_count;
37 static int max_requests = -1;
40 #ifndef NO_CURL_EASY_DUPHANDLE
41 static CURL *curl_default;
44 #define PREV_BUF_SIZE 4096
46 char curl_errorstr[CURL_ERROR_SIZE];
48 static int curl_ssl_verify = -1;
49 static int curl_ssl_try;
50 static const char *ssl_cert;
51 static const char *ssl_cipherlist;
52 static const char *ssl_version;
57 { "sslv2", CURL_SSLVERSION_SSLv2 },
58 { "sslv3", CURL_SSLVERSION_SSLv3 },
59 { "tlsv1", CURL_SSLVERSION_TLSv1 },
60 #if LIBCURL_VERSION_NUM >= 0x072200
61 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
62 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
63 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
66 #if LIBCURL_VERSION_NUM >= 0x070903
67 static const char *ssl_key;
69 #if LIBCURL_VERSION_NUM >= 0x070908
70 static const char *ssl_capath;
72 #if LIBCURL_VERSION_NUM >= 0x072c00
73 static const char *ssl_pinnedkey;
75 static const char *ssl_cainfo;
76 static long curl_low_speed_limit = -1;
77 static long curl_low_speed_time = -1;
78 static int curl_ftp_no_epsv;
79 static const char *curl_http_proxy;
80 static const char *curl_no_proxy;
81 static const char *http_proxy_authmethod;
85 } proxy_authmethods[] = {
86 { "basic", CURLAUTH_BASIC },
87 { "digest", CURLAUTH_DIGEST },
88 { "negotiate", CURLAUTH_GSSNEGOTIATE },
89 { "ntlm", CURLAUTH_NTLM },
90 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
91 { "anyauth", CURLAUTH_ANY },
94 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
95 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
99 #ifdef CURLGSSAPI_DELEGATION_FLAG
100 static const char *curl_deleg;
103 long curl_deleg_param;
104 } curl_deleg_levels[] = {
105 { "none", CURLGSSAPI_DELEGATION_NONE },
106 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
107 { "always", CURLGSSAPI_DELEGATION_FLAG },
111 static struct credential proxy_auth = CREDENTIAL_INIT;
112 static const char *curl_proxyuserpwd;
113 static const char *curl_cookie_file;
114 static int curl_save_cookies;
115 struct credential http_auth = CREDENTIAL_INIT;
116 static int http_proactive_auth;
117 static const char *user_agent;
118 static int curl_empty_auth = -1;
120 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
122 #if LIBCURL_VERSION_NUM >= 0x071700
123 /* Use CURLOPT_KEYPASSWD as is */
124 #elif LIBCURL_VERSION_NUM >= 0x070903
125 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
127 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
130 static struct credential cert_auth = CREDENTIAL_INIT;
131 static int ssl_cert_password_required;
132 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
133 static unsigned long http_auth_methods = CURLAUTH_ANY;
134 static int http_auth_methods_restricted;
135 /* Modes for which empty_auth cannot actually help us. */
136 static unsigned long empty_auth_useless =
138 #ifdef CURLAUTH_DIGEST_IE
144 static struct curl_slist *pragma_header;
145 static struct curl_slist *no_pragma_header;
146 static struct curl_slist *extra_http_headers;
148 static struct active_request_slot *active_queue_head;
150 static char *cached_accept_language;
152 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
154 size_t size = eltsize * nmemb;
155 struct buffer *buffer = buffer_;
157 if (size > buffer->buf.len - buffer->posn)
158 size = buffer->buf.len - buffer->posn;
159 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
160 buffer->posn += size;
165 #ifndef NO_CURL_IOCTL
166 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
168 struct buffer *buffer = clientp;
174 case CURLIOCMD_RESTARTREAD:
179 return CURLIOE_UNKNOWNCMD;
184 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
186 size_t size = eltsize * nmemb;
187 struct strbuf *buffer = buffer_;
189 strbuf_add(buffer, ptr, size);
193 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
195 return eltsize * nmemb;
198 static void closedown_active_slot(struct active_request_slot *slot)
204 static void finish_active_slot(struct active_request_slot *slot)
206 closedown_active_slot(slot);
207 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
209 if (slot->finished != NULL)
210 (*slot->finished) = 1;
212 /* Store slot results so they can be read after the slot is reused */
213 if (slot->results != NULL) {
214 slot->results->curl_result = slot->curl_result;
215 slot->results->http_code = slot->http_code;
216 #if LIBCURL_VERSION_NUM >= 0x070a08
217 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
218 &slot->results->auth_avail);
220 slot->results->auth_avail = 0;
223 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
224 &slot->results->http_connectcode);
227 /* Run callback if appropriate */
228 if (slot->callback_func != NULL)
229 slot->callback_func(slot->callback_data);
232 static void xmulti_remove_handle(struct active_request_slot *slot)
234 #ifdef USE_CURL_MULTI
235 curl_multi_remove_handle(curlm, slot->curl);
239 #ifdef USE_CURL_MULTI
240 static void process_curl_messages(void)
243 struct active_request_slot *slot;
244 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
246 while (curl_message != NULL) {
247 if (curl_message->msg == CURLMSG_DONE) {
248 int curl_result = curl_message->data.result;
249 slot = active_queue_head;
250 while (slot != NULL &&
251 slot->curl != curl_message->easy_handle)
254 xmulti_remove_handle(slot);
255 slot->curl_result = curl_result;
256 finish_active_slot(slot);
258 fprintf(stderr, "Received DONE message for unknown request!\n");
261 fprintf(stderr, "Unknown CURL message received: %d\n",
262 (int)curl_message->msg);
264 curl_message = curl_multi_info_read(curlm, &num_messages);
269 static int http_options(const char *var, const char *value, void *cb)
271 if (!strcmp("http.sslverify", var)) {
272 curl_ssl_verify = git_config_bool(var, value);
275 if (!strcmp("http.sslcipherlist", var))
276 return git_config_string(&ssl_cipherlist, var, value);
277 if (!strcmp("http.sslversion", var))
278 return git_config_string(&ssl_version, var, value);
279 if (!strcmp("http.sslcert", var))
280 return git_config_pathname(&ssl_cert, var, value);
281 #if LIBCURL_VERSION_NUM >= 0x070903
282 if (!strcmp("http.sslkey", var))
283 return git_config_pathname(&ssl_key, var, value);
285 #if LIBCURL_VERSION_NUM >= 0x070908
286 if (!strcmp("http.sslcapath", var))
287 return git_config_pathname(&ssl_capath, var, value);
289 if (!strcmp("http.sslcainfo", var))
290 return git_config_pathname(&ssl_cainfo, var, value);
291 if (!strcmp("http.sslcertpasswordprotected", var)) {
292 ssl_cert_password_required = git_config_bool(var, value);
295 if (!strcmp("http.ssltry", var)) {
296 curl_ssl_try = git_config_bool(var, value);
299 if (!strcmp("http.minsessions", var)) {
300 min_curl_sessions = git_config_int(var, value);
301 #ifndef USE_CURL_MULTI
302 if (min_curl_sessions > 1)
303 min_curl_sessions = 1;
307 #ifdef USE_CURL_MULTI
308 if (!strcmp("http.maxrequests", var)) {
309 max_requests = git_config_int(var, value);
313 if (!strcmp("http.lowspeedlimit", var)) {
314 curl_low_speed_limit = (long)git_config_int(var, value);
317 if (!strcmp("http.lowspeedtime", var)) {
318 curl_low_speed_time = (long)git_config_int(var, value);
322 if (!strcmp("http.noepsv", var)) {
323 curl_ftp_no_epsv = git_config_bool(var, value);
326 if (!strcmp("http.proxy", var))
327 return git_config_string(&curl_http_proxy, var, value);
329 if (!strcmp("http.proxyauthmethod", var))
330 return git_config_string(&http_proxy_authmethod, var, value);
332 if (!strcmp("http.cookiefile", var))
333 return git_config_pathname(&curl_cookie_file, var, value);
334 if (!strcmp("http.savecookies", var)) {
335 curl_save_cookies = git_config_bool(var, value);
339 if (!strcmp("http.postbuffer", var)) {
340 http_post_buffer = git_config_ssize_t(var, value);
341 if (http_post_buffer < 0)
342 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
343 if (http_post_buffer < LARGE_PACKET_MAX)
344 http_post_buffer = LARGE_PACKET_MAX;
348 if (!strcmp("http.useragent", var))
349 return git_config_string(&user_agent, var, value);
351 if (!strcmp("http.emptyauth", var)) {
352 if (value && !strcmp("auto", value))
353 curl_empty_auth = -1;
355 curl_empty_auth = git_config_bool(var, value);
359 if (!strcmp("http.delegation", var)) {
360 #ifdef CURLGSSAPI_DELEGATION_FLAG
361 return git_config_string(&curl_deleg, var, value);
363 warning(_("Delegation control is not supported with cURL < 7.22.0"));
368 if (!strcmp("http.pinnedpubkey", var)) {
369 #if LIBCURL_VERSION_NUM >= 0x072c00
370 return git_config_pathname(&ssl_pinnedkey, var, value);
372 warning(_("Public key pinning not supported with cURL < 7.44.0"));
377 if (!strcmp("http.extraheader", var)) {
379 return config_error_nonbool(var);
380 } else if (!*value) {
381 curl_slist_free_all(extra_http_headers);
382 extra_http_headers = NULL;
385 curl_slist_append(extra_http_headers, value);
390 if (!strcmp("http.followredirects", var)) {
391 if (value && !strcmp(value, "initial"))
392 http_follow_config = HTTP_FOLLOW_INITIAL;
393 else if (git_config_bool(var, value))
394 http_follow_config = HTTP_FOLLOW_ALWAYS;
396 http_follow_config = HTTP_FOLLOW_NONE;
400 /* Fall back on the default ones */
401 return git_default_config(var, value, cb);
404 static int curl_empty_auth_enabled(void)
406 if (curl_empty_auth >= 0)
407 return curl_empty_auth;
409 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
411 * Our libcurl is too old to do AUTH_ANY in the first place;
412 * just default to turning the feature off.
416 * In the automatic case, kick in the empty-auth
417 * hack as long as we would potentially try some
418 * method more exotic than "Basic" or "Digest".
420 * But only do this when this is our second or
421 * subsequent request, as by then we know what
422 * methods are available.
424 if (http_auth_methods_restricted &&
425 (http_auth_methods & ~empty_auth_useless))
431 static void init_curl_http_auth(CURL *result)
433 if (!http_auth.username || !*http_auth.username) {
434 if (curl_empty_auth_enabled())
435 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
439 credential_fill(&http_auth);
441 #if LIBCURL_VERSION_NUM >= 0x071301
442 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
443 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
446 static struct strbuf up = STRBUF_INIT;
448 * Note that we assume we only ever have a single set of
449 * credentials in a given program run, so we do not have
450 * to worry about updating this buffer, only setting its
454 strbuf_addf(&up, "%s:%s",
455 http_auth.username, http_auth.password);
456 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
461 /* *var must be free-able */
462 static void var_override(const char **var, char *value)
466 *var = xstrdup(value);
470 static void set_proxyauth_name_password(CURL *result)
472 #if LIBCURL_VERSION_NUM >= 0x071301
473 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
474 proxy_auth.username);
475 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
476 proxy_auth.password);
478 struct strbuf s = STRBUF_INIT;
480 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
481 strbuf_addch(&s, ':');
482 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
483 curl_proxyuserpwd = strbuf_detach(&s, NULL);
484 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
488 static void init_curl_proxy_auth(CURL *result)
490 if (proxy_auth.username) {
491 if (!proxy_auth.password)
492 credential_fill(&proxy_auth);
493 set_proxyauth_name_password(result);
496 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
498 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
499 if (http_proxy_authmethod) {
501 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
502 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
503 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
504 proxy_authmethods[i].curlauth_param);
508 if (i == ARRAY_SIZE(proxy_authmethods)) {
509 warning("unsupported proxy authentication method %s: using anyauth",
510 http_proxy_authmethod);
511 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
515 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
519 static int has_cert_password(void)
521 if (ssl_cert == NULL || ssl_cert_password_required != 1)
523 if (!cert_auth.password) {
524 cert_auth.protocol = xstrdup("cert");
525 cert_auth.username = xstrdup("");
526 cert_auth.path = xstrdup(ssl_cert);
527 credential_fill(&cert_auth);
532 #if LIBCURL_VERSION_NUM >= 0x071900
533 static void set_curl_keepalive(CURL *c)
535 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
538 #elif LIBCURL_VERSION_NUM >= 0x071000
539 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
543 socklen_t len = (socklen_t)sizeof(ka);
545 if (type != CURLSOCKTYPE_IPCXN)
548 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
550 warning_errno("unable to set SO_KEEPALIVE on socket");
552 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
555 static void set_curl_keepalive(CURL *c)
557 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
561 static void set_curl_keepalive(CURL *c)
563 /* not supported on older curl versions */
567 static void redact_sensitive_header(struct strbuf *header)
569 const char *sensitive_header;
571 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
572 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
573 /* The first token is the type, which is OK to log */
574 while (isspace(*sensitive_header))
576 while (*sensitive_header && !isspace(*sensitive_header))
578 /* Everything else is opaque and possibly sensitive */
579 strbuf_setlen(header, sensitive_header - header->buf);
580 strbuf_addstr(header, " <redacted>");
581 } else if (cookies_to_redact.nr &&
582 skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
583 struct strbuf redacted_header = STRBUF_INIT;
586 while (isspace(*sensitive_header))
590 * The contents of header starting from sensitive_header will
591 * subsequently be overridden, so it is fine to mutate this
592 * string (hence the assignment to "char *").
594 cookie = (char *) sensitive_header;
598 char *semicolon = strstr(cookie, "; ");
601 equals = strchrnul(cookie, '=');
603 /* invalid cookie, just append and continue */
604 strbuf_addstr(&redacted_header, cookie);
607 *equals = 0; /* temporarily set to NUL for lookup */
608 if (string_list_lookup(&cookies_to_redact, cookie)) {
609 strbuf_addstr(&redacted_header, cookie);
610 strbuf_addstr(&redacted_header, "=<redacted>");
613 strbuf_addstr(&redacted_header, cookie);
617 * There are more cookies. (Or, for some
618 * reason, the input string ends in "; ".)
620 strbuf_addstr(&redacted_header, "; ");
621 cookie = semicolon + strlen("; ");
627 strbuf_setlen(header, sensitive_header - header->buf);
628 strbuf_addbuf(header, &redacted_header);
632 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
634 struct strbuf out = STRBUF_INIT;
635 struct strbuf **headers, **header;
637 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
638 text, (long)size, (long)size);
639 trace_strbuf(&trace_curl, &out);
641 strbuf_add(&out, ptr, size);
642 headers = strbuf_split_max(&out, '\n', 0);
644 for (header = headers; *header; header++) {
645 if (hide_sensitive_header)
646 redact_sensitive_header(*header);
647 strbuf_insert((*header), 0, text, strlen(text));
648 strbuf_insert((*header), strlen(text), ": ", 2);
649 strbuf_rtrim((*header));
650 strbuf_addch((*header), '\n');
651 trace_strbuf(&trace_curl, (*header));
653 strbuf_list_free(headers);
654 strbuf_release(&out);
657 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
660 struct strbuf out = STRBUF_INIT;
661 unsigned int width = 60;
663 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
664 text, (long)size, (long)size);
665 trace_strbuf(&trace_curl, &out);
667 for (i = 0; i < size; i += width) {
671 strbuf_addf(&out, "%s: ", text);
672 for (w = 0; (w < width) && (i + w < size); w++) {
673 unsigned char ch = ptr[i + w];
676 (ch >= 0x20) && (ch < 0x80)
679 strbuf_addch(&out, '\n');
680 trace_strbuf(&trace_curl, &out);
682 strbuf_release(&out);
685 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
688 enum { NO_FILTER = 0, DO_FILTER = 1 };
692 trace_printf_key(&trace_curl, "== Info: %s", data);
694 case CURLINFO_HEADER_OUT:
695 text = "=> Send header";
696 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
698 case CURLINFO_DATA_OUT:
699 if (trace_curl_data) {
700 text = "=> Send data";
701 curl_dump_data(text, (unsigned char *)data, size);
704 case CURLINFO_SSL_DATA_OUT:
705 if (trace_curl_data) {
706 text = "=> Send SSL data";
707 curl_dump_data(text, (unsigned char *)data, size);
710 case CURLINFO_HEADER_IN:
711 text = "<= Recv header";
712 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
714 case CURLINFO_DATA_IN:
715 if (trace_curl_data) {
716 text = "<= Recv data";
717 curl_dump_data(text, (unsigned char *)data, size);
720 case CURLINFO_SSL_DATA_IN:
721 if (trace_curl_data) {
722 text = "<= Recv SSL data";
723 curl_dump_data(text, (unsigned char *)data, size);
727 default: /* we ignore unknown types by default */
733 void setup_curl_trace(CURL *handle)
735 if (!trace_want(&trace_curl))
737 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
738 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
739 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
742 #ifdef CURLPROTO_HTTP
743 static long get_curl_allowed_protocols(int from_user)
745 long allowed_protocols = 0;
747 if (is_transport_allowed("http", from_user))
748 allowed_protocols |= CURLPROTO_HTTP;
749 if (is_transport_allowed("https", from_user))
750 allowed_protocols |= CURLPROTO_HTTPS;
751 if (is_transport_allowed("ftp", from_user))
752 allowed_protocols |= CURLPROTO_FTP;
753 if (is_transport_allowed("ftps", from_user))
754 allowed_protocols |= CURLPROTO_FTPS;
756 return allowed_protocols;
760 static CURL *get_curl_handle(void)
762 CURL *result = curl_easy_init();
765 die("curl_easy_init failed");
767 if (!curl_ssl_verify) {
768 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
769 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
771 /* Verify authenticity of the peer's certificate */
772 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
773 /* The name in the cert must match whom we tried to connect */
774 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
777 #if LIBCURL_VERSION_NUM >= 0x070907
778 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
780 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
781 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
784 #ifdef CURLGSSAPI_DELEGATION_FLAG
787 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
788 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
789 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
790 curl_deleg_levels[i].curl_deleg_param);
794 if (i == ARRAY_SIZE(curl_deleg_levels))
795 warning("Unknown delegation method '%s': using default",
800 if (http_proactive_auth)
801 init_curl_http_auth(result);
803 if (getenv("GIT_SSL_VERSION"))
804 ssl_version = getenv("GIT_SSL_VERSION");
805 if (ssl_version && *ssl_version) {
807 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
808 if (!strcmp(ssl_version, sslversions[i].name)) {
809 curl_easy_setopt(result, CURLOPT_SSLVERSION,
810 sslversions[i].ssl_version);
814 if (i == ARRAY_SIZE(sslversions))
815 warning("unsupported ssl version %s: using default",
819 if (getenv("GIT_SSL_CIPHER_LIST"))
820 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
821 if (ssl_cipherlist != NULL && *ssl_cipherlist)
822 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
825 if (ssl_cert != NULL)
826 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
827 if (has_cert_password())
828 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
829 #if LIBCURL_VERSION_NUM >= 0x070903
831 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
833 #if LIBCURL_VERSION_NUM >= 0x070908
834 if (ssl_capath != NULL)
835 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
837 #if LIBCURL_VERSION_NUM >= 0x072c00
838 if (ssl_pinnedkey != NULL)
839 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
841 if (ssl_cainfo != NULL)
842 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
844 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
845 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
846 curl_low_speed_limit);
847 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
848 curl_low_speed_time);
851 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
852 #if LIBCURL_VERSION_NUM >= 0x071301
853 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
854 #elif LIBCURL_VERSION_NUM >= 0x071101
855 curl_easy_setopt(result, CURLOPT_POST301, 1);
857 #ifdef CURLPROTO_HTTP
858 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
859 get_curl_allowed_protocols(0));
860 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
861 get_curl_allowed_protocols(-1));
863 warning("protocol restrictions not applied to curl redirects because\n"
864 "your curl version is too old (>= 7.19.4)");
866 if (getenv("GIT_CURL_VERBOSE"))
867 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
868 setup_curl_trace(result);
869 if (getenv("GIT_TRACE_CURL_NO_DATA"))
871 if (getenv("GIT_REDACT_COOKIES")) {
872 string_list_split(&cookies_to_redact,
873 getenv("GIT_REDACT_COOKIES"), ',', -1);
874 string_list_sort(&cookies_to_redact);
877 curl_easy_setopt(result, CURLOPT_USERAGENT,
878 user_agent ? user_agent : git_user_agent());
880 if (curl_ftp_no_epsv)
881 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
883 #ifdef CURLOPT_USE_SSL
885 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
889 * CURL also examines these variables as a fallback; but we need to query
890 * them here in order to decide whether to prompt for missing password (cf.
891 * init_curl_proxy_auth()).
893 * Unlike many other common environment variables, these are historically
894 * lowercase only. It appears that CURL did not know this and implemented
895 * only uppercase variants, which was later corrected to take both - with
896 * the exception of http_proxy, which is lowercase only also in CURL. As
897 * the lowercase versions are the historical quasi-standard, they take
898 * precedence here, as in CURL.
900 if (!curl_http_proxy) {
901 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
902 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
903 var_override(&curl_http_proxy, getenv("https_proxy"));
905 var_override(&curl_http_proxy, getenv("http_proxy"));
907 if (!curl_http_proxy) {
908 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
909 var_override(&curl_http_proxy, getenv("all_proxy"));
913 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
915 * Handle case with the empty http.proxy value here to keep
917 * NB: empty option disables proxying at all.
919 curl_easy_setopt(result, CURLOPT_PROXY, "");
920 } else if (curl_http_proxy) {
921 #if LIBCURL_VERSION_NUM >= 0x071800
922 if (starts_with(curl_http_proxy, "socks5h"))
923 curl_easy_setopt(result,
924 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
925 else if (starts_with(curl_http_proxy, "socks5"))
926 curl_easy_setopt(result,
927 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
928 else if (starts_with(curl_http_proxy, "socks4a"))
929 curl_easy_setopt(result,
930 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
931 else if (starts_with(curl_http_proxy, "socks"))
932 curl_easy_setopt(result,
933 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
935 #if LIBCURL_VERSION_NUM >= 0x073400
936 else if (starts_with(curl_http_proxy, "https"))
937 curl_easy_setopt(result,
938 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
940 if (strstr(curl_http_proxy, "://"))
941 credential_from_url(&proxy_auth, curl_http_proxy);
943 struct strbuf url = STRBUF_INIT;
944 strbuf_addf(&url, "http://%s", curl_http_proxy);
945 credential_from_url(&proxy_auth, url.buf);
946 strbuf_release(&url);
949 if (!proxy_auth.host)
950 die("Invalid proxy URL '%s'", curl_http_proxy);
952 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
953 #if LIBCURL_VERSION_NUM >= 0x071304
954 var_override(&curl_no_proxy, getenv("NO_PROXY"));
955 var_override(&curl_no_proxy, getenv("no_proxy"));
956 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
959 init_curl_proxy_auth(result);
961 set_curl_keepalive(result);
966 static void set_from_env(const char **var, const char *envname)
968 const char *val = getenv(envname);
973 static void protocol_http_header(void)
975 if (get_protocol_version_config() > 0) {
976 struct strbuf protocol_header = STRBUF_INIT;
978 strbuf_addf(&protocol_header, GIT_PROTOCOL_HEADER ": version=%d",
979 get_protocol_version_config());
982 extra_http_headers = curl_slist_append(extra_http_headers,
983 protocol_header.buf);
984 strbuf_release(&protocol_header);
988 void http_init(struct remote *remote, const char *url, int proactive_auth)
990 char *low_speed_limit;
991 char *low_speed_time;
992 char *normalized_url;
993 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
995 config.section = "http";
997 config.collect_fn = http_options;
998 config.cascade_fn = git_default_config;
1001 http_is_verbose = 0;
1002 normalized_url = url_normalize(url, &config.url);
1004 git_config(urlmatch_config_entry, &config);
1005 free(normalized_url);
1007 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1008 die("curl_global_init failed");
1010 http_proactive_auth = proactive_auth;
1012 if (remote && remote->http_proxy)
1013 curl_http_proxy = xstrdup(remote->http_proxy);
1016 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1018 protocol_http_header();
1020 pragma_header = curl_slist_append(http_copy_default_headers(),
1021 "Pragma: no-cache");
1022 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1025 #ifdef USE_CURL_MULTI
1027 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1028 if (http_max_requests != NULL)
1029 max_requests = atoi(http_max_requests);
1032 curlm = curl_multi_init();
1034 die("curl_multi_init failed");
1037 if (getenv("GIT_SSL_NO_VERIFY"))
1038 curl_ssl_verify = 0;
1040 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1041 #if LIBCURL_VERSION_NUM >= 0x070903
1042 set_from_env(&ssl_key, "GIT_SSL_KEY");
1044 #if LIBCURL_VERSION_NUM >= 0x070908
1045 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1047 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1049 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1051 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1052 if (low_speed_limit != NULL)
1053 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1054 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1055 if (low_speed_time != NULL)
1056 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1058 if (curl_ssl_verify == -1)
1059 curl_ssl_verify = 1;
1061 curl_session_count = 0;
1062 #ifdef USE_CURL_MULTI
1063 if (max_requests < 1)
1064 max_requests = DEFAULT_MAX_REQUESTS;
1067 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1068 curl_ftp_no_epsv = 1;
1071 credential_from_url(&http_auth, url);
1072 if (!ssl_cert_password_required &&
1073 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1074 starts_with(url, "https://"))
1075 ssl_cert_password_required = 1;
1078 #ifndef NO_CURL_EASY_DUPHANDLE
1079 curl_default = get_curl_handle();
1083 void http_cleanup(void)
1085 struct active_request_slot *slot = active_queue_head;
1087 while (slot != NULL) {
1088 struct active_request_slot *next = slot->next;
1089 if (slot->curl != NULL) {
1090 xmulti_remove_handle(slot);
1091 curl_easy_cleanup(slot->curl);
1096 active_queue_head = NULL;
1098 #ifndef NO_CURL_EASY_DUPHANDLE
1099 curl_easy_cleanup(curl_default);
1102 #ifdef USE_CURL_MULTI
1103 curl_multi_cleanup(curlm);
1105 curl_global_cleanup();
1107 curl_slist_free_all(extra_http_headers);
1108 extra_http_headers = NULL;
1110 curl_slist_free_all(pragma_header);
1111 pragma_header = NULL;
1113 curl_slist_free_all(no_pragma_header);
1114 no_pragma_header = NULL;
1116 if (curl_http_proxy) {
1117 free((void *)curl_http_proxy);
1118 curl_http_proxy = NULL;
1121 if (proxy_auth.password) {
1122 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1123 FREE_AND_NULL(proxy_auth.password);
1126 free((void *)curl_proxyuserpwd);
1127 curl_proxyuserpwd = NULL;
1129 free((void *)http_proxy_authmethod);
1130 http_proxy_authmethod = NULL;
1132 if (cert_auth.password != NULL) {
1133 memset(cert_auth.password, 0, strlen(cert_auth.password));
1134 FREE_AND_NULL(cert_auth.password);
1136 ssl_cert_password_required = 0;
1138 FREE_AND_NULL(cached_accept_language);
1141 struct active_request_slot *get_active_slot(void)
1143 struct active_request_slot *slot = active_queue_head;
1144 struct active_request_slot *newslot;
1146 #ifdef USE_CURL_MULTI
1149 /* Wait for a slot to open up if the queue is full */
1150 while (active_requests >= max_requests) {
1151 curl_multi_perform(curlm, &num_transfers);
1152 if (num_transfers < active_requests)
1153 process_curl_messages();
1157 while (slot != NULL && slot->in_use)
1161 newslot = xmalloc(sizeof(*newslot));
1162 newslot->curl = NULL;
1163 newslot->in_use = 0;
1164 newslot->next = NULL;
1166 slot = active_queue_head;
1168 active_queue_head = newslot;
1170 while (slot->next != NULL)
1172 slot->next = newslot;
1177 if (slot->curl == NULL) {
1178 #ifdef NO_CURL_EASY_DUPHANDLE
1179 slot->curl = get_curl_handle();
1181 slot->curl = curl_easy_duphandle(curl_default);
1183 curl_session_count++;
1188 slot->results = NULL;
1189 slot->finished = NULL;
1190 slot->callback_data = NULL;
1191 slot->callback_func = NULL;
1192 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1193 if (curl_save_cookies)
1194 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1195 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1196 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1197 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1198 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1199 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1200 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1201 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1202 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1203 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1204 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1207 * Default following to off unless "ALWAYS" is configured; this gives
1208 * callers a sane starting point, and they can tweak for individual
1209 * HTTP_FOLLOW_* cases themselves.
1211 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1212 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1214 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1216 #if LIBCURL_VERSION_NUM >= 0x070a08
1217 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1219 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1220 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1222 if (http_auth.password || curl_empty_auth_enabled())
1223 init_curl_http_auth(slot->curl);
1228 int start_active_slot(struct active_request_slot *slot)
1230 #ifdef USE_CURL_MULTI
1231 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1234 if (curlm_result != CURLM_OK &&
1235 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1236 warning("curl_multi_add_handle failed: %s",
1237 curl_multi_strerror(curlm_result));
1244 * We know there must be something to do, since we just added
1247 curl_multi_perform(curlm, &num_transfers);
1252 #ifdef USE_CURL_MULTI
1255 int (*fill)(void *);
1256 struct fill_chain *next;
1259 static struct fill_chain *fill_cfg;
1261 void add_fill_function(void *data, int (*fill)(void *))
1263 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1264 struct fill_chain **linkp = &fill_cfg;
1265 new_fill->data = data;
1266 new_fill->fill = fill;
1267 new_fill->next = NULL;
1269 linkp = &(*linkp)->next;
1273 void fill_active_slots(void)
1275 struct active_request_slot *slot = active_queue_head;
1277 while (active_requests < max_requests) {
1278 struct fill_chain *fill;
1279 for (fill = fill_cfg; fill; fill = fill->next)
1280 if (fill->fill(fill->data))
1287 while (slot != NULL) {
1288 if (!slot->in_use && slot->curl != NULL
1289 && curl_session_count > min_curl_sessions) {
1290 curl_easy_cleanup(slot->curl);
1292 curl_session_count--;
1298 void step_active_slots(void)
1301 CURLMcode curlm_result;
1304 curlm_result = curl_multi_perform(curlm, &num_transfers);
1305 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1306 if (num_transfers < active_requests) {
1307 process_curl_messages();
1308 fill_active_slots();
1313 void run_active_slot(struct active_request_slot *slot)
1315 #ifdef USE_CURL_MULTI
1320 struct timeval select_timeout;
1323 slot->finished = &finished;
1325 step_active_slots();
1328 #if LIBCURL_VERSION_NUM >= 0x070f04
1330 curl_multi_timeout(curlm, &curl_timeout);
1331 if (curl_timeout == 0) {
1333 } else if (curl_timeout == -1) {
1334 select_timeout.tv_sec = 0;
1335 select_timeout.tv_usec = 50000;
1337 select_timeout.tv_sec = curl_timeout / 1000;
1338 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1341 select_timeout.tv_sec = 0;
1342 select_timeout.tv_usec = 50000;
1349 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1352 * It can happen that curl_multi_timeout returns a pathologically
1353 * long timeout when curl_multi_fdset returns no file descriptors
1354 * to read. See commit message for more details.
1357 (select_timeout.tv_sec > 0 ||
1358 select_timeout.tv_usec > 50000)) {
1359 select_timeout.tv_sec = 0;
1360 select_timeout.tv_usec = 50000;
1363 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1367 while (slot->in_use) {
1368 slot->curl_result = curl_easy_perform(slot->curl);
1369 finish_active_slot(slot);
1374 static void release_active_slot(struct active_request_slot *slot)
1376 closedown_active_slot(slot);
1378 xmulti_remove_handle(slot);
1379 if (curl_session_count > min_curl_sessions) {
1380 curl_easy_cleanup(slot->curl);
1382 curl_session_count--;
1385 #ifdef USE_CURL_MULTI
1386 fill_active_slots();
1390 void finish_all_active_slots(void)
1392 struct active_request_slot *slot = active_queue_head;
1394 while (slot != NULL)
1396 run_active_slot(slot);
1397 slot = active_queue_head;
1403 /* Helpers for modifying and creating URLs */
1404 static inline int needs_quote(int ch)
1406 if (((ch >= 'A') && (ch <= 'Z'))
1407 || ((ch >= 'a') && (ch <= 'z'))
1408 || ((ch >= '0') && (ch <= '9'))
1416 static char *quote_ref_url(const char *base, const char *ref)
1418 struct strbuf buf = STRBUF_INIT;
1422 end_url_with_slash(&buf, base);
1424 for (cp = ref; (ch = *cp) != 0; cp++)
1425 if (needs_quote(ch))
1426 strbuf_addf(&buf, "%%%02x", ch);
1428 strbuf_addch(&buf, *cp);
1430 return strbuf_detach(&buf, NULL);
1433 void append_remote_object_url(struct strbuf *buf, const char *url,
1435 int only_two_digit_prefix)
1437 end_url_with_slash(buf, url);
1439 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1440 if (!only_two_digit_prefix)
1441 strbuf_addstr(buf, hex + 2);
1444 char *get_remote_object_url(const char *url, const char *hex,
1445 int only_two_digit_prefix)
1447 struct strbuf buf = STRBUF_INIT;
1448 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1449 return strbuf_detach(&buf, NULL);
1452 static int handle_curl_result(struct slot_results *results)
1455 * If we see a failing http code with CURLE_OK, we have turned off
1456 * FAILONERROR (to keep the server's custom error response), and should
1457 * translate the code into failure here.
1459 * Likewise, if we see a redirect (30x code), that means we turned off
1460 * redirect-following, and we should treat the result as an error.
1462 if (results->curl_result == CURLE_OK &&
1463 results->http_code >= 300) {
1464 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1466 * Normally curl will already have put the "reason phrase"
1467 * from the server into curl_errorstr; unfortunately without
1468 * FAILONERROR it is lost, so we can give only the numeric
1471 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1472 "The requested URL returned error: %ld",
1473 results->http_code);
1476 if (results->curl_result == CURLE_OK) {
1477 credential_approve(&http_auth);
1478 if (proxy_auth.password)
1479 credential_approve(&proxy_auth);
1481 } else if (missing_target(results))
1482 return HTTP_MISSING_TARGET;
1483 else if (results->http_code == 401) {
1484 if (http_auth.username && http_auth.password) {
1485 credential_reject(&http_auth);
1488 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1489 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1490 if (results->auth_avail) {
1491 http_auth_methods &= results->auth_avail;
1492 http_auth_methods_restricted = 1;
1498 if (results->http_connectcode == 407)
1499 credential_reject(&proxy_auth);
1500 #if LIBCURL_VERSION_NUM >= 0x070c00
1501 if (!curl_errorstr[0])
1502 strlcpy(curl_errorstr,
1503 curl_easy_strerror(results->curl_result),
1504 sizeof(curl_errorstr));
1510 int run_one_slot(struct active_request_slot *slot,
1511 struct slot_results *results)
1513 slot->results = results;
1514 if (!start_active_slot(slot)) {
1515 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1516 "failed to start HTTP request");
1517 return HTTP_START_FAILED;
1520 run_active_slot(slot);
1521 return handle_curl_result(results);
1524 struct curl_slist *http_copy_default_headers(void)
1526 struct curl_slist *headers = NULL, *h;
1528 for (h = extra_http_headers; h; h = h->next)
1529 headers = curl_slist_append(headers, h->data);
1534 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1540 ret = curl_easy_getinfo(curl, info, &ptr);
1542 strbuf_addstr(buf, ptr);
1547 * Check for and extract a content-type parameter. "raw"
1548 * should be positioned at the start of the potential
1549 * parameter, with any whitespace already removed.
1551 * "name" is the name of the parameter. The value is appended
1554 static int extract_param(const char *raw, const char *name,
1557 size_t len = strlen(name);
1559 if (strncasecmp(raw, name, len))
1567 while (*raw && !isspace(*raw) && *raw != ';')
1568 strbuf_addch(out, *raw++);
1573 * Extract a normalized version of the content type, with any
1574 * spaces suppressed, all letters lowercased, and no trailing ";"
1577 * Note that we will silently remove even invalid whitespace. For
1578 * example, "text / plain" is specifically forbidden by RFC 2616,
1579 * but "text/plain" is the only reasonable output, and this keeps
1582 * If the "charset" argument is not NULL, store the value of any
1583 * charset parameter there.
1586 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1587 * "text / plain" -> "text/plain"
1589 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1590 struct strbuf *charset)
1595 strbuf_grow(type, raw->len);
1596 for (p = raw->buf; *p; p++) {
1603 strbuf_addch(type, tolower(*p));
1609 strbuf_reset(charset);
1611 while (isspace(*p) || *p == ';')
1613 if (!extract_param(p, "charset", charset))
1615 while (*p && !isspace(*p))
1619 if (!charset->len && starts_with(type->buf, "text/"))
1620 strbuf_addstr(charset, "ISO-8859-1");
1623 static void write_accept_language(struct strbuf *buf)
1626 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1627 * that, q-value will be smaller than 0.001, the minimum q-value the
1628 * HTTP specification allows. See
1629 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1631 const int MAX_DECIMAL_PLACES = 3;
1632 const int MAX_LANGUAGE_TAGS = 1000;
1633 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1634 char **language_tags = NULL;
1636 const char *s = get_preferred_languages();
1638 struct strbuf tag = STRBUF_INIT;
1640 /* Don't add Accept-Language header if no language is preferred. */
1645 * Split the colon-separated string of preferred languages into
1646 * language_tags array.
1649 /* collect language tag */
1650 for (; *s && (isalnum(*s) || *s == '_'); s++)
1651 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1653 /* skip .codeset, @modifier and any other unnecessary parts */
1654 while (*s && *s != ':')
1659 REALLOC_ARRAY(language_tags, num_langs);
1660 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1661 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1666 /* write Accept-Language header into buf */
1668 int last_buf_len = 0;
1674 REALLOC_ARRAY(language_tags, num_langs + 1);
1675 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1677 /* compute decimal_places */
1678 for (max_q = 1, decimal_places = 0;
1679 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1680 decimal_places++, max_q *= 10)
1683 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1685 strbuf_addstr(buf, "Accept-Language: ");
1687 for (i = 0; i < num_langs; i++) {
1689 strbuf_addstr(buf, ", ");
1691 strbuf_addstr(buf, language_tags[i]);
1694 strbuf_addf(buf, q_format, max_q - i);
1696 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1697 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1701 last_buf_len = buf->len;
1705 /* free language tags -- last one is a static '*' */
1706 for (i = 0; i < num_langs - 1; i++)
1707 free(language_tags[i]);
1708 free(language_tags);
1712 * Get an Accept-Language header which indicates user's preferred languages.
1716 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1717 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1718 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1719 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1720 * LANGUAGE= LANG=C -> ""
1722 static const char *get_accept_language(void)
1724 if (!cached_accept_language) {
1725 struct strbuf buf = STRBUF_INIT;
1726 write_accept_language(&buf);
1728 cached_accept_language = strbuf_detach(&buf, NULL);
1731 return cached_accept_language;
1734 static void http_opt_request_remainder(CURL *curl, off_t pos)
1737 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1738 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1741 /* http_request() targets */
1742 #define HTTP_REQUEST_STRBUF 0
1743 #define HTTP_REQUEST_FILE 1
1745 static int http_request(const char *url,
1746 void *result, int target,
1747 const struct http_get_options *options)
1749 struct active_request_slot *slot;
1750 struct slot_results results;
1751 struct curl_slist *headers = http_copy_default_headers();
1752 struct strbuf buf = STRBUF_INIT;
1753 const char *accept_language;
1756 slot = get_active_slot();
1757 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1759 if (result == NULL) {
1760 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1762 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1763 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1765 if (target == HTTP_REQUEST_FILE) {
1766 off_t posn = ftello(result);
1767 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1770 http_opt_request_remainder(slot->curl, posn);
1772 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1776 accept_language = get_accept_language();
1778 if (accept_language)
1779 headers = curl_slist_append(headers, accept_language);
1781 strbuf_addstr(&buf, "Pragma:");
1782 if (options && options->no_cache)
1783 strbuf_addstr(&buf, " no-cache");
1784 if (options && options->keep_error)
1785 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1786 if (options && options->initial_request &&
1787 http_follow_config == HTTP_FOLLOW_INITIAL)
1788 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1790 headers = curl_slist_append(headers, buf.buf);
1792 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1793 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1794 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1796 ret = run_one_slot(slot, &results);
1798 if (options && options->content_type) {
1799 struct strbuf raw = STRBUF_INIT;
1800 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1801 extract_content_type(&raw, options->content_type,
1803 strbuf_release(&raw);
1806 if (options && options->effective_url)
1807 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1808 options->effective_url);
1810 curl_slist_free_all(headers);
1811 strbuf_release(&buf);
1817 * Update the "base" url to a more appropriate value, as deduced by
1818 * redirects seen when requesting a URL starting with "url".
1820 * The "asked" parameter is a URL that we asked curl to access, and must begin
1823 * The "got" parameter is the URL that curl reported to us as where we ended
1826 * Returns 1 if we updated the base url, 0 otherwise.
1828 * Our basic strategy is to compare "base" and "asked" to find the bits
1829 * specific to our request. We then strip those bits off of "got" to yield the
1830 * new base. So for example, if our base is "http://example.com/foo.git",
1831 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1832 * with "https://other.example.com/foo.git/info/refs". We would want the
1833 * new URL to become "https://other.example.com/foo.git".
1835 * Note that this assumes a sane redirect scheme. It's entirely possible
1836 * in the example above to end up at a URL that does not even end in
1837 * "info/refs". In such a case we die. There's not much we can do, such a
1838 * scheme is unlikely to represent a real git repository, and failing to
1839 * rewrite the base opens options for malicious redirects to do funny things.
1841 static int update_url_from_redirect(struct strbuf *base,
1843 const struct strbuf *got)
1848 if (!strcmp(asked, got->buf))
1851 if (!skip_prefix(asked, base->buf, &tail))
1852 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1856 if (!strip_suffix_mem(got->buf, &new_len, tail))
1857 die(_("unable to update url base from redirection:\n"
1863 strbuf_add(base, got->buf, new_len);
1868 static int http_request_reauth(const char *url,
1869 void *result, int target,
1870 struct http_get_options *options)
1872 int ret = http_request(url, result, target, options);
1874 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1877 if (options && options->effective_url && options->base_url) {
1878 if (update_url_from_redirect(options->base_url,
1879 url, options->effective_url)) {
1880 credential_from_url(&http_auth, options->base_url->buf);
1881 url = options->effective_url->buf;
1885 if (ret != HTTP_REAUTH)
1889 * If we are using KEEP_ERROR, the previous request may have
1890 * put cruft into our output stream; we should clear it out before
1891 * making our next request. We only know how to do this for
1892 * the strbuf case, but that is enough to satisfy current callers.
1894 if (options && options->keep_error) {
1896 case HTTP_REQUEST_STRBUF:
1897 strbuf_reset(result);
1900 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1904 credential_fill(&http_auth);
1906 return http_request(url, result, target, options);
1909 int http_get_strbuf(const char *url,
1910 struct strbuf *result,
1911 struct http_get_options *options)
1913 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1917 * Downloads a URL and stores the result in the given file.
1919 * If a previous interrupted download is detected (i.e. a previous temporary
1920 * file is still around) the download is resumed.
1922 static int http_get_file(const char *url, const char *filename,
1923 struct http_get_options *options)
1926 struct strbuf tmpfile = STRBUF_INIT;
1929 strbuf_addf(&tmpfile, "%s.temp", filename);
1930 result = fopen(tmpfile.buf, "a");
1932 error("Unable to open local file %s", tmpfile.buf);
1937 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1940 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1943 strbuf_release(&tmpfile);
1947 int http_fetch_ref(const char *base, struct ref *ref)
1949 struct http_get_options options = {0};
1951 struct strbuf buffer = STRBUF_INIT;
1954 options.no_cache = 1;
1956 url = quote_ref_url(base, ref->name);
1957 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1958 strbuf_rtrim(&buffer);
1959 if (buffer.len == 40)
1960 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1961 else if (starts_with(buffer.buf, "ref: ")) {
1962 ref->symref = xstrdup(buffer.buf + 5);
1967 strbuf_release(&buffer);
1972 /* Helpers for fetching packs */
1973 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1976 struct strbuf buf = STRBUF_INIT;
1978 if (http_is_verbose)
1979 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1981 end_url_with_slash(&buf, base_url);
1982 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1983 url = strbuf_detach(&buf, NULL);
1985 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1986 tmp = strbuf_detach(&buf, NULL);
1988 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1989 error("Unable to get pack index %s", url);
1997 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1998 unsigned char *sha1, const char *base_url)
2000 struct packed_git *new_pack;
2001 char *tmp_idx = NULL;
2004 if (has_pack_index(sha1)) {
2005 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2007 return -1; /* parse_pack_index() already issued error message */
2011 tmp_idx = fetch_pack_index(sha1, base_url);
2015 new_pack = parse_pack_index(sha1, tmp_idx);
2020 return -1; /* parse_pack_index() already issued error message */
2023 ret = verify_pack_index(new_pack);
2025 close_pack_index(new_pack);
2026 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2033 new_pack->next = *packs_head;
2034 *packs_head = new_pack;
2038 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2040 struct http_get_options options = {0};
2043 struct strbuf buf = STRBUF_INIT;
2044 unsigned char sha1[20];
2046 end_url_with_slash(&buf, base_url);
2047 strbuf_addstr(&buf, "objects/info/packs");
2048 url = strbuf_detach(&buf, NULL);
2050 options.no_cache = 1;
2051 ret = http_get_strbuf(url, &buf, &options);
2056 while (i < buf.len) {
2060 if (i + 52 <= buf.len &&
2061 starts_with(data + i, " pack-") &&
2062 starts_with(data + i + 46, ".pack\n")) {
2063 get_sha1_hex(data + i + 6, sha1);
2064 fetch_and_setup_pack_index(packs_head, sha1,
2070 while (i < buf.len && data[i] != '\n')
2081 void release_http_pack_request(struct http_pack_request *preq)
2083 if (preq->packfile != NULL) {
2084 fclose(preq->packfile);
2085 preq->packfile = NULL;
2092 int finish_http_pack_request(struct http_pack_request *preq)
2094 struct packed_git **lst;
2095 struct packed_git *p = preq->target;
2098 struct child_process ip = CHILD_PROCESS_INIT;
2100 close_pack_index(p);
2102 fclose(preq->packfile);
2103 preq->packfile = NULL;
2107 lst = &((*lst)->next);
2108 *lst = (*lst)->next;
2110 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2111 die("BUG: pack tmpfile does not end in .pack.temp?");
2112 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
2114 argv_array_push(&ip.args, "index-pack");
2115 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2116 argv_array_push(&ip.args, preq->tmpfile);
2121 if (run_command(&ip)) {
2122 unlink(preq->tmpfile);
2128 unlink(sha1_pack_index_name(p->sha1));
2130 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2131 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2136 install_packed_git(p);
2141 struct http_pack_request *new_http_pack_request(
2142 struct packed_git *target, const char *base_url)
2144 off_t prev_posn = 0;
2145 struct strbuf buf = STRBUF_INIT;
2146 struct http_pack_request *preq;
2148 preq = xcalloc(1, sizeof(*preq));
2149 preq->target = target;
2151 end_url_with_slash(&buf, base_url);
2152 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2153 sha1_to_hex(target->sha1));
2154 preq->url = strbuf_detach(&buf, NULL);
2156 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2157 sha1_pack_name(target->sha1));
2158 preq->packfile = fopen(preq->tmpfile, "a");
2159 if (!preq->packfile) {
2160 error("Unable to open local file %s for pack",
2165 preq->slot = get_active_slot();
2166 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2167 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2168 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2169 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2173 * If there is data present from a previous transfer attempt,
2174 * resume where it left off
2176 prev_posn = ftello(preq->packfile);
2178 if (http_is_verbose)
2180 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2181 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2182 http_opt_request_remainder(preq->slot->curl, prev_posn);
2193 /* Helpers for fetching objects (loose) */
2194 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2197 unsigned char expn[4096];
2198 size_t size = eltsize * nmemb;
2200 struct http_object_request *freq = data;
2201 struct active_request_slot *slot = freq->slot;
2204 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2207 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2208 curl_easy_strerror(c));
2209 if (slot->http_code >= 300)
2214 ssize_t retval = xwrite(freq->localfile,
2215 (char *) ptr + posn, size - posn);
2219 } while (posn < size);
2221 freq->stream.avail_in = size;
2222 freq->stream.next_in = (void *)ptr;
2224 freq->stream.next_out = expn;
2225 freq->stream.avail_out = sizeof(expn);
2226 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2227 git_SHA1_Update(&freq->c, expn,
2228 sizeof(expn) - freq->stream.avail_out);
2229 } while (freq->stream.avail_in && freq->zret == Z_OK);
2233 struct http_object_request *new_http_object_request(const char *base_url,
2234 unsigned char *sha1)
2236 char *hex = sha1_to_hex(sha1);
2237 struct strbuf filename = STRBUF_INIT;
2238 char prevfile[PATH_MAX];
2240 char prev_buf[PREV_BUF_SIZE];
2241 ssize_t prev_read = 0;
2242 off_t prev_posn = 0;
2243 struct http_object_request *freq;
2245 freq = xcalloc(1, sizeof(*freq));
2246 hashcpy(freq->sha1, sha1);
2247 freq->localfile = -1;
2249 sha1_file_name(&filename, sha1);
2250 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2251 "%s.temp", filename.buf);
2253 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename.buf);
2254 unlink_or_warn(prevfile);
2255 rename(freq->tmpfile, prevfile);
2256 unlink_or_warn(freq->tmpfile);
2257 strbuf_release(&filename);
2259 if (freq->localfile != -1)
2260 error("fd leakage in start: %d", freq->localfile);
2261 freq->localfile = open(freq->tmpfile,
2262 O_WRONLY | O_CREAT | O_EXCL, 0666);
2264 * This could have failed due to the "lazy directory creation";
2265 * try to mkdir the last path component.
2267 if (freq->localfile < 0 && errno == ENOENT) {
2268 char *dir = strrchr(freq->tmpfile, '/');
2271 mkdir(freq->tmpfile, 0777);
2274 freq->localfile = open(freq->tmpfile,
2275 O_WRONLY | O_CREAT | O_EXCL, 0666);
2278 if (freq->localfile < 0) {
2279 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2283 git_inflate_init(&freq->stream);
2285 git_SHA1_Init(&freq->c);
2287 freq->url = get_remote_object_url(base_url, hex, 0);
2290 * If a previous temp file is present, process what was already
2293 prevlocal = open(prevfile, O_RDONLY);
2294 if (prevlocal != -1) {
2296 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2298 if (fwrite_sha1_file(prev_buf,
2301 freq) == prev_read) {
2302 prev_posn += prev_read;
2307 } while (prev_read > 0);
2310 unlink_or_warn(prevfile);
2313 * Reset inflate/SHA1 if there was an error reading the previous temp
2314 * file; also rewind to the beginning of the local file.
2316 if (prev_read == -1) {
2317 memset(&freq->stream, 0, sizeof(freq->stream));
2318 git_inflate_init(&freq->stream);
2319 git_SHA1_Init(&freq->c);
2322 lseek(freq->localfile, 0, SEEK_SET);
2323 if (ftruncate(freq->localfile, 0) < 0) {
2324 error_errno("Couldn't truncate temporary file %s",
2331 freq->slot = get_active_slot();
2333 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2334 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2335 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2336 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2337 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2338 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2341 * If we have successfully processed data from a previous fetch
2342 * attempt, only fetch the data we don't already have.
2345 if (http_is_verbose)
2347 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2348 hex, (uintmax_t)prev_posn);
2349 http_opt_request_remainder(freq->slot->curl, prev_posn);
2360 void process_http_object_request(struct http_object_request *freq)
2362 if (freq->slot == NULL)
2364 freq->curl_result = freq->slot->curl_result;
2365 freq->http_code = freq->slot->http_code;
2369 int finish_http_object_request(struct http_object_request *freq)
2372 struct strbuf filename = STRBUF_INIT;
2374 close(freq->localfile);
2375 freq->localfile = -1;
2377 process_http_object_request(freq);
2379 if (freq->http_code == 416) {
2380 warning("requested range invalid; we may already have all the data.");
2381 } else if (freq->curl_result != CURLE_OK) {
2382 if (stat(freq->tmpfile, &st) == 0)
2383 if (st.st_size == 0)
2384 unlink_or_warn(freq->tmpfile);
2388 git_inflate_end(&freq->stream);
2389 git_SHA1_Final(freq->real_sha1, &freq->c);
2390 if (freq->zret != Z_STREAM_END) {
2391 unlink_or_warn(freq->tmpfile);
2394 if (hashcmp(freq->sha1, freq->real_sha1)) {
2395 unlink_or_warn(freq->tmpfile);
2399 sha1_file_name(&filename, freq->sha1);
2400 freq->rename = finalize_object_file(freq->tmpfile, filename.buf);
2401 strbuf_release(&filename);
2403 return freq->rename;
2406 void abort_http_object_request(struct http_object_request *freq)
2408 unlink_or_warn(freq->tmpfile);
2410 release_http_object_request(freq);
2413 void release_http_object_request(struct http_object_request *freq)
2415 if (freq->localfile != -1) {
2416 close(freq->localfile);
2417 freq->localfile = -1;
2419 if (freq->url != NULL) {
2420 FREE_AND_NULL(freq->url);
2422 if (freq->slot != NULL) {
2423 freq->slot->callback_func = NULL;
2424 freq->slot->callback_data = NULL;
2425 release_active_slot(freq->slot);