1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
14 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
15 #if LIBCURL_VERSION_NUM >= 0x070a08
16 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
18 long int git_curl_ipresolve;
22 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
24 #if LIBCURL_VERSION_NUM >= 0x070a06
25 #define LIBCURL_CAN_HANDLE_AUTH_ANY
28 static int min_curl_sessions = 1;
29 static int curl_session_count;
31 static int max_requests = -1;
34 #ifndef NO_CURL_EASY_DUPHANDLE
35 static CURL *curl_default;
38 #define PREV_BUF_SIZE 4096
40 char curl_errorstr[CURL_ERROR_SIZE];
42 static int curl_ssl_verify = -1;
43 static int curl_ssl_try;
44 static const char *ssl_cert;
45 static const char *ssl_cipherlist;
46 static const char *ssl_version;
51 { "sslv2", CURL_SSLVERSION_SSLv2 },
52 { "sslv3", CURL_SSLVERSION_SSLv3 },
53 { "tlsv1", CURL_SSLVERSION_TLSv1 },
54 #if LIBCURL_VERSION_NUM >= 0x072200
55 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
56 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
57 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
60 #if LIBCURL_VERSION_NUM >= 0x070903
61 static const char *ssl_key;
63 #if LIBCURL_VERSION_NUM >= 0x070908
64 static const char *ssl_capath;
66 #if LIBCURL_VERSION_NUM >= 0x072c00
67 static const char *ssl_pinnedkey;
69 static const char *ssl_cainfo;
70 static long curl_low_speed_limit = -1;
71 static long curl_low_speed_time = -1;
72 static int curl_ftp_no_epsv;
73 static const char *curl_http_proxy;
74 static const char *curl_no_proxy;
75 static const char *http_proxy_authmethod;
79 } proxy_authmethods[] = {
80 { "basic", CURLAUTH_BASIC },
81 { "digest", CURLAUTH_DIGEST },
82 { "negotiate", CURLAUTH_GSSNEGOTIATE },
83 { "ntlm", CURLAUTH_NTLM },
84 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
85 { "anyauth", CURLAUTH_ANY },
88 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
89 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
93 #if LIBCURL_VERSION_NUM >= 0x071600
94 static const char *curl_deleg;
97 long curl_deleg_param;
98 } curl_deleg_levels[] = {
99 { "none", CURLGSSAPI_DELEGATION_NONE },
100 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
101 { "always", CURLGSSAPI_DELEGATION_FLAG },
105 static struct credential proxy_auth = CREDENTIAL_INIT;
106 static const char *curl_proxyuserpwd;
107 static const char *curl_cookie_file;
108 static int curl_save_cookies;
109 struct credential http_auth = CREDENTIAL_INIT;
110 static int http_proactive_auth;
111 static const char *user_agent;
112 static int curl_empty_auth;
114 #if LIBCURL_VERSION_NUM >= 0x071700
115 /* Use CURLOPT_KEYPASSWD as is */
116 #elif LIBCURL_VERSION_NUM >= 0x070903
117 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
119 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
122 static struct credential cert_auth = CREDENTIAL_INIT;
123 static int ssl_cert_password_required;
124 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
125 static unsigned long http_auth_methods = CURLAUTH_ANY;
128 static struct curl_slist *pragma_header;
129 static struct curl_slist *no_pragma_header;
130 static struct curl_slist *extra_http_headers;
132 static struct active_request_slot *active_queue_head;
134 static char *cached_accept_language;
136 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
138 size_t size = eltsize * nmemb;
139 struct buffer *buffer = buffer_;
141 if (size > buffer->buf.len - buffer->posn)
142 size = buffer->buf.len - buffer->posn;
143 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
144 buffer->posn += size;
149 #ifndef NO_CURL_IOCTL
150 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
152 struct buffer *buffer = clientp;
158 case CURLIOCMD_RESTARTREAD:
163 return CURLIOE_UNKNOWNCMD;
168 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
170 size_t size = eltsize * nmemb;
171 struct strbuf *buffer = buffer_;
173 strbuf_add(buffer, ptr, size);
177 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
179 return eltsize * nmemb;
182 static void closedown_active_slot(struct active_request_slot *slot)
188 static void finish_active_slot(struct active_request_slot *slot)
190 closedown_active_slot(slot);
191 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
193 if (slot->finished != NULL)
194 (*slot->finished) = 1;
196 /* Store slot results so they can be read after the slot is reused */
197 if (slot->results != NULL) {
198 slot->results->curl_result = slot->curl_result;
199 slot->results->http_code = slot->http_code;
200 #if LIBCURL_VERSION_NUM >= 0x070a08
201 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
202 &slot->results->auth_avail);
204 slot->results->auth_avail = 0;
207 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
208 &slot->results->http_connectcode);
211 /* Run callback if appropriate */
212 if (slot->callback_func != NULL)
213 slot->callback_func(slot->callback_data);
216 static void xmulti_remove_handle(struct active_request_slot *slot)
218 #ifdef USE_CURL_MULTI
219 curl_multi_remove_handle(curlm, slot->curl);
223 #ifdef USE_CURL_MULTI
224 static void process_curl_messages(void)
227 struct active_request_slot *slot;
228 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
230 while (curl_message != NULL) {
231 if (curl_message->msg == CURLMSG_DONE) {
232 int curl_result = curl_message->data.result;
233 slot = active_queue_head;
234 while (slot != NULL &&
235 slot->curl != curl_message->easy_handle)
238 xmulti_remove_handle(slot);
239 slot->curl_result = curl_result;
240 finish_active_slot(slot);
242 fprintf(stderr, "Received DONE message for unknown request!\n");
245 fprintf(stderr, "Unknown CURL message received: %d\n",
246 (int)curl_message->msg);
248 curl_message = curl_multi_info_read(curlm, &num_messages);
253 static int http_options(const char *var, const char *value, void *cb)
255 if (!strcmp("http.sslverify", var)) {
256 curl_ssl_verify = git_config_bool(var, value);
259 if (!strcmp("http.sslcipherlist", var))
260 return git_config_string(&ssl_cipherlist, var, value);
261 if (!strcmp("http.sslversion", var))
262 return git_config_string(&ssl_version, var, value);
263 if (!strcmp("http.sslcert", var))
264 return git_config_string(&ssl_cert, var, value);
265 #if LIBCURL_VERSION_NUM >= 0x070903
266 if (!strcmp("http.sslkey", var))
267 return git_config_string(&ssl_key, var, value);
269 #if LIBCURL_VERSION_NUM >= 0x070908
270 if (!strcmp("http.sslcapath", var))
271 return git_config_pathname(&ssl_capath, var, value);
273 if (!strcmp("http.sslcainfo", var))
274 return git_config_pathname(&ssl_cainfo, var, value);
275 if (!strcmp("http.sslcertpasswordprotected", var)) {
276 ssl_cert_password_required = git_config_bool(var, value);
279 if (!strcmp("http.ssltry", var)) {
280 curl_ssl_try = git_config_bool(var, value);
283 if (!strcmp("http.minsessions", var)) {
284 min_curl_sessions = git_config_int(var, value);
285 #ifndef USE_CURL_MULTI
286 if (min_curl_sessions > 1)
287 min_curl_sessions = 1;
291 #ifdef USE_CURL_MULTI
292 if (!strcmp("http.maxrequests", var)) {
293 max_requests = git_config_int(var, value);
297 if (!strcmp("http.lowspeedlimit", var)) {
298 curl_low_speed_limit = (long)git_config_int(var, value);
301 if (!strcmp("http.lowspeedtime", var)) {
302 curl_low_speed_time = (long)git_config_int(var, value);
306 if (!strcmp("http.noepsv", var)) {
307 curl_ftp_no_epsv = git_config_bool(var, value);
310 if (!strcmp("http.proxy", var))
311 return git_config_string(&curl_http_proxy, var, value);
313 if (!strcmp("http.proxyauthmethod", var))
314 return git_config_string(&http_proxy_authmethod, var, value);
316 if (!strcmp("http.cookiefile", var))
317 return git_config_pathname(&curl_cookie_file, var, value);
318 if (!strcmp("http.savecookies", var)) {
319 curl_save_cookies = git_config_bool(var, value);
323 if (!strcmp("http.postbuffer", var)) {
324 http_post_buffer = git_config_int(var, value);
325 if (http_post_buffer < LARGE_PACKET_MAX)
326 http_post_buffer = LARGE_PACKET_MAX;
330 if (!strcmp("http.useragent", var))
331 return git_config_string(&user_agent, var, value);
333 if (!strcmp("http.emptyauth", var)) {
334 curl_empty_auth = git_config_bool(var, value);
338 if (!strcmp("http.delegation", var)) {
339 #if LIBCURL_VERSION_NUM >= 0x071600
340 return git_config_string(&curl_deleg, var, value);
342 warning(_("Delegation control is not supported with cURL < 7.22.0"));
347 if (!strcmp("http.pinnedpubkey", var)) {
348 #if LIBCURL_VERSION_NUM >= 0x072c00
349 return git_config_pathname(&ssl_pinnedkey, var, value);
351 warning(_("Public key pinning not supported with cURL < 7.44.0"));
356 if (!strcmp("http.extraheader", var)) {
358 return config_error_nonbool(var);
359 } else if (!*value) {
360 curl_slist_free_all(extra_http_headers);
361 extra_http_headers = NULL;
364 curl_slist_append(extra_http_headers, value);
369 /* Fall back on the default ones */
370 return git_default_config(var, value, cb);
373 static void init_curl_http_auth(CURL *result)
375 if (!http_auth.username) {
377 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
381 credential_fill(&http_auth);
383 #if LIBCURL_VERSION_NUM >= 0x071301
384 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
385 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
388 static struct strbuf up = STRBUF_INIT;
390 * Note that we assume we only ever have a single set of
391 * credentials in a given program run, so we do not have
392 * to worry about updating this buffer, only setting its
396 strbuf_addf(&up, "%s:%s",
397 http_auth.username, http_auth.password);
398 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
403 /* *var must be free-able */
404 static void var_override(const char **var, char *value)
408 *var = xstrdup(value);
412 static void set_proxyauth_name_password(CURL *result)
414 #if LIBCURL_VERSION_NUM >= 0x071301
415 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
416 proxy_auth.username);
417 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
418 proxy_auth.password);
420 struct strbuf s = STRBUF_INIT;
422 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
423 strbuf_addch(&s, ':');
424 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
425 curl_proxyuserpwd = strbuf_detach(&s, NULL);
426 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
430 static void init_curl_proxy_auth(CURL *result)
432 if (proxy_auth.username) {
433 if (!proxy_auth.password)
434 credential_fill(&proxy_auth);
435 set_proxyauth_name_password(result);
438 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
440 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
441 if (http_proxy_authmethod) {
443 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
444 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
445 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
446 proxy_authmethods[i].curlauth_param);
450 if (i == ARRAY_SIZE(proxy_authmethods)) {
451 warning("unsupported proxy authentication method %s: using anyauth",
452 http_proxy_authmethod);
453 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
457 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
461 static int has_cert_password(void)
463 if (ssl_cert == NULL || ssl_cert_password_required != 1)
465 if (!cert_auth.password) {
466 cert_auth.protocol = xstrdup("cert");
467 cert_auth.username = xstrdup("");
468 cert_auth.path = xstrdup(ssl_cert);
469 credential_fill(&cert_auth);
474 #if LIBCURL_VERSION_NUM >= 0x071900
475 static void set_curl_keepalive(CURL *c)
477 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
480 #elif LIBCURL_VERSION_NUM >= 0x071000
481 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
485 socklen_t len = (socklen_t)sizeof(ka);
487 if (type != CURLSOCKTYPE_IPCXN)
490 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
492 warning_errno("unable to set SO_KEEPALIVE on socket");
494 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
497 static void set_curl_keepalive(CURL *c)
499 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
503 static void set_curl_keepalive(CURL *c)
505 /* not supported on older curl versions */
509 static void redact_sensitive_header(struct strbuf *header)
511 const char *sensitive_header;
513 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
514 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
515 /* The first token is the type, which is OK to log */
516 while (isspace(*sensitive_header))
518 while (*sensitive_header && !isspace(*sensitive_header))
520 /* Everything else is opaque and possibly sensitive */
521 strbuf_setlen(header, sensitive_header - header->buf);
522 strbuf_addstr(header, " <redacted>");
526 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
528 struct strbuf out = STRBUF_INIT;
529 struct strbuf **headers, **header;
531 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
532 text, (long)size, (long)size);
533 trace_strbuf(&trace_curl, &out);
535 strbuf_add(&out, ptr, size);
536 headers = strbuf_split_max(&out, '\n', 0);
538 for (header = headers; *header; header++) {
539 if (hide_sensitive_header)
540 redact_sensitive_header(*header);
541 strbuf_insert((*header), 0, text, strlen(text));
542 strbuf_insert((*header), strlen(text), ": ", 2);
543 strbuf_rtrim((*header));
544 strbuf_addch((*header), '\n');
545 trace_strbuf(&trace_curl, (*header));
547 strbuf_list_free(headers);
548 strbuf_release(&out);
551 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
554 struct strbuf out = STRBUF_INIT;
555 unsigned int width = 60;
557 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
558 text, (long)size, (long)size);
559 trace_strbuf(&trace_curl, &out);
561 for (i = 0; i < size; i += width) {
565 strbuf_addf(&out, "%s: ", text);
566 for (w = 0; (w < width) && (i + w < size); w++) {
567 unsigned char ch = ptr[i + w];
570 (ch >= 0x20) && (ch < 0x80)
573 strbuf_addch(&out, '\n');
574 trace_strbuf(&trace_curl, &out);
576 strbuf_release(&out);
579 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
582 enum { NO_FILTER = 0, DO_FILTER = 1 };
586 trace_printf_key(&trace_curl, "== Info: %s", data);
587 default: /* we ignore unknown types by default */
590 case CURLINFO_HEADER_OUT:
591 text = "=> Send header";
592 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
594 case CURLINFO_DATA_OUT:
595 text = "=> Send data";
596 curl_dump_data(text, (unsigned char *)data, size);
598 case CURLINFO_SSL_DATA_OUT:
599 text = "=> Send SSL data";
600 curl_dump_data(text, (unsigned char *)data, size);
602 case CURLINFO_HEADER_IN:
603 text = "<= Recv header";
604 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
606 case CURLINFO_DATA_IN:
607 text = "<= Recv data";
608 curl_dump_data(text, (unsigned char *)data, size);
610 case CURLINFO_SSL_DATA_IN:
611 text = "<= Recv SSL data";
612 curl_dump_data(text, (unsigned char *)data, size);
618 void setup_curl_trace(CURL *handle)
620 if (!trace_want(&trace_curl))
622 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
623 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
624 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
628 static CURL *get_curl_handle(void)
630 CURL *result = curl_easy_init();
631 long allowed_protocols = 0;
634 die("curl_easy_init failed");
636 if (!curl_ssl_verify) {
637 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
638 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
640 /* Verify authenticity of the peer's certificate */
641 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
642 /* The name in the cert must match whom we tried to connect */
643 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
646 #if LIBCURL_VERSION_NUM >= 0x070907
647 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
649 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
650 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
653 #if LIBCURL_VERSION_NUM >= 0x071600
656 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
657 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
658 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
659 curl_deleg_levels[i].curl_deleg_param);
663 if (i == ARRAY_SIZE(curl_deleg_levels))
664 warning("Unknown delegation method '%s': using default",
669 if (http_proactive_auth)
670 init_curl_http_auth(result);
672 if (getenv("GIT_SSL_VERSION"))
673 ssl_version = getenv("GIT_SSL_VERSION");
674 if (ssl_version && *ssl_version) {
676 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
677 if (!strcmp(ssl_version, sslversions[i].name)) {
678 curl_easy_setopt(result, CURLOPT_SSLVERSION,
679 sslversions[i].ssl_version);
683 if (i == ARRAY_SIZE(sslversions))
684 warning("unsupported ssl version %s: using default",
688 if (getenv("GIT_SSL_CIPHER_LIST"))
689 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
690 if (ssl_cipherlist != NULL && *ssl_cipherlist)
691 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
694 if (ssl_cert != NULL)
695 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
696 if (has_cert_password())
697 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
698 #if LIBCURL_VERSION_NUM >= 0x070903
700 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
702 #if LIBCURL_VERSION_NUM >= 0x070908
703 if (ssl_capath != NULL)
704 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
706 #if LIBCURL_VERSION_NUM >= 0x072c00
707 if (ssl_pinnedkey != NULL)
708 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
710 if (ssl_cainfo != NULL)
711 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
713 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
714 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
715 curl_low_speed_limit);
716 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
717 curl_low_speed_time);
720 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
721 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
722 #if LIBCURL_VERSION_NUM >= 0x071301
723 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
724 #elif LIBCURL_VERSION_NUM >= 0x071101
725 curl_easy_setopt(result, CURLOPT_POST301, 1);
727 #if LIBCURL_VERSION_NUM >= 0x071304
728 if (is_transport_allowed("http"))
729 allowed_protocols |= CURLPROTO_HTTP;
730 if (is_transport_allowed("https"))
731 allowed_protocols |= CURLPROTO_HTTPS;
732 if (is_transport_allowed("ftp"))
733 allowed_protocols |= CURLPROTO_FTP;
734 if (is_transport_allowed("ftps"))
735 allowed_protocols |= CURLPROTO_FTPS;
736 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
738 if (transport_restrict_protocols())
739 warning("protocol restrictions not applied to curl redirects because\n"
740 "your curl version is too old (>= 7.19.4)");
742 if (getenv("GIT_CURL_VERBOSE"))
743 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
744 setup_curl_trace(result);
746 curl_easy_setopt(result, CURLOPT_USERAGENT,
747 user_agent ? user_agent : git_user_agent());
749 if (curl_ftp_no_epsv)
750 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
752 #ifdef CURLOPT_USE_SSL
754 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
758 * CURL also examines these variables as a fallback; but we need to query
759 * them here in order to decide whether to prompt for missing password (cf.
760 * init_curl_proxy_auth()).
762 * Unlike many other common environment variables, these are historically
763 * lowercase only. It appears that CURL did not know this and implemented
764 * only uppercase variants, which was later corrected to take both - with
765 * the exception of http_proxy, which is lowercase only also in CURL. As
766 * the lowercase versions are the historical quasi-standard, they take
767 * precedence here, as in CURL.
769 if (!curl_http_proxy) {
770 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
771 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
772 var_override(&curl_http_proxy, getenv("https_proxy"));
774 var_override(&curl_http_proxy, getenv("http_proxy"));
776 if (!curl_http_proxy) {
777 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
778 var_override(&curl_http_proxy, getenv("all_proxy"));
782 if (curl_http_proxy) {
783 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
784 #if LIBCURL_VERSION_NUM >= 0x071800
785 if (starts_with(curl_http_proxy, "socks5h"))
786 curl_easy_setopt(result,
787 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
788 else if (starts_with(curl_http_proxy, "socks5"))
789 curl_easy_setopt(result,
790 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
791 else if (starts_with(curl_http_proxy, "socks4a"))
792 curl_easy_setopt(result,
793 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
794 else if (starts_with(curl_http_proxy, "socks"))
795 curl_easy_setopt(result,
796 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
798 if (strstr(curl_http_proxy, "://"))
799 credential_from_url(&proxy_auth, curl_http_proxy);
801 struct strbuf url = STRBUF_INIT;
802 strbuf_addf(&url, "http://%s", curl_http_proxy);
803 credential_from_url(&proxy_auth, url.buf);
804 strbuf_release(&url);
807 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
808 #if LIBCURL_VERSION_NUM >= 0x071304
809 var_override(&curl_no_proxy, getenv("NO_PROXY"));
810 var_override(&curl_no_proxy, getenv("no_proxy"));
811 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
814 init_curl_proxy_auth(result);
816 set_curl_keepalive(result);
821 static void set_from_env(const char **var, const char *envname)
823 const char *val = getenv(envname);
828 void http_init(struct remote *remote, const char *url, int proactive_auth)
830 char *low_speed_limit;
831 char *low_speed_time;
832 char *normalized_url;
833 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
835 config.section = "http";
837 config.collect_fn = http_options;
838 config.cascade_fn = git_default_config;
842 normalized_url = url_normalize(url, &config.url);
844 git_config(urlmatch_config_entry, &config);
845 free(normalized_url);
847 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
848 die("curl_global_init failed");
850 http_proactive_auth = proactive_auth;
852 if (remote && remote->http_proxy)
853 curl_http_proxy = xstrdup(remote->http_proxy);
856 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
858 pragma_header = curl_slist_append(http_copy_default_headers(),
860 no_pragma_header = curl_slist_append(http_copy_default_headers(),
863 #ifdef USE_CURL_MULTI
865 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
866 if (http_max_requests != NULL)
867 max_requests = atoi(http_max_requests);
870 curlm = curl_multi_init();
872 die("curl_multi_init failed");
875 if (getenv("GIT_SSL_NO_VERIFY"))
878 set_from_env(&ssl_cert, "GIT_SSL_CERT");
879 #if LIBCURL_VERSION_NUM >= 0x070903
880 set_from_env(&ssl_key, "GIT_SSL_KEY");
882 #if LIBCURL_VERSION_NUM >= 0x070908
883 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
885 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
887 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
889 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
890 if (low_speed_limit != NULL)
891 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
892 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
893 if (low_speed_time != NULL)
894 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
896 if (curl_ssl_verify == -1)
899 curl_session_count = 0;
900 #ifdef USE_CURL_MULTI
901 if (max_requests < 1)
902 max_requests = DEFAULT_MAX_REQUESTS;
905 if (getenv("GIT_CURL_FTP_NO_EPSV"))
906 curl_ftp_no_epsv = 1;
909 credential_from_url(&http_auth, url);
910 if (!ssl_cert_password_required &&
911 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
912 starts_with(url, "https://"))
913 ssl_cert_password_required = 1;
916 #ifndef NO_CURL_EASY_DUPHANDLE
917 curl_default = get_curl_handle();
921 void http_cleanup(void)
923 struct active_request_slot *slot = active_queue_head;
925 while (slot != NULL) {
926 struct active_request_slot *next = slot->next;
927 if (slot->curl != NULL) {
928 xmulti_remove_handle(slot);
929 curl_easy_cleanup(slot->curl);
934 active_queue_head = NULL;
936 #ifndef NO_CURL_EASY_DUPHANDLE
937 curl_easy_cleanup(curl_default);
940 #ifdef USE_CURL_MULTI
941 curl_multi_cleanup(curlm);
943 curl_global_cleanup();
945 curl_slist_free_all(extra_http_headers);
946 extra_http_headers = NULL;
948 curl_slist_free_all(pragma_header);
949 pragma_header = NULL;
951 curl_slist_free_all(no_pragma_header);
952 no_pragma_header = NULL;
954 if (curl_http_proxy) {
955 free((void *)curl_http_proxy);
956 curl_http_proxy = NULL;
959 if (proxy_auth.password) {
960 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
961 free(proxy_auth.password);
962 proxy_auth.password = NULL;
965 free((void *)curl_proxyuserpwd);
966 curl_proxyuserpwd = NULL;
968 free((void *)http_proxy_authmethod);
969 http_proxy_authmethod = NULL;
971 if (cert_auth.password != NULL) {
972 memset(cert_auth.password, 0, strlen(cert_auth.password));
973 free(cert_auth.password);
974 cert_auth.password = NULL;
976 ssl_cert_password_required = 0;
978 free(cached_accept_language);
979 cached_accept_language = NULL;
982 struct active_request_slot *get_active_slot(void)
984 struct active_request_slot *slot = active_queue_head;
985 struct active_request_slot *newslot;
987 #ifdef USE_CURL_MULTI
990 /* Wait for a slot to open up if the queue is full */
991 while (active_requests >= max_requests) {
992 curl_multi_perform(curlm, &num_transfers);
993 if (num_transfers < active_requests)
994 process_curl_messages();
998 while (slot != NULL && slot->in_use)
1002 newslot = xmalloc(sizeof(*newslot));
1003 newslot->curl = NULL;
1004 newslot->in_use = 0;
1005 newslot->next = NULL;
1007 slot = active_queue_head;
1009 active_queue_head = newslot;
1011 while (slot->next != NULL)
1013 slot->next = newslot;
1018 if (slot->curl == NULL) {
1019 #ifdef NO_CURL_EASY_DUPHANDLE
1020 slot->curl = get_curl_handle();
1022 slot->curl = curl_easy_duphandle(curl_default);
1024 curl_session_count++;
1029 slot->results = NULL;
1030 slot->finished = NULL;
1031 slot->callback_data = NULL;
1032 slot->callback_func = NULL;
1033 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1034 if (curl_save_cookies)
1035 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1036 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1037 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1038 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1039 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1040 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1041 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1042 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1043 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1044 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1045 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1047 #if LIBCURL_VERSION_NUM >= 0x070a08
1048 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1050 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1051 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1053 if (http_auth.password || curl_empty_auth)
1054 init_curl_http_auth(slot->curl);
1059 int start_active_slot(struct active_request_slot *slot)
1061 #ifdef USE_CURL_MULTI
1062 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1065 if (curlm_result != CURLM_OK &&
1066 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1067 warning("curl_multi_add_handle failed: %s",
1068 curl_multi_strerror(curlm_result));
1075 * We know there must be something to do, since we just added
1078 curl_multi_perform(curlm, &num_transfers);
1083 #ifdef USE_CURL_MULTI
1086 int (*fill)(void *);
1087 struct fill_chain *next;
1090 static struct fill_chain *fill_cfg;
1092 void add_fill_function(void *data, int (*fill)(void *))
1094 struct fill_chain *new = xmalloc(sizeof(*new));
1095 struct fill_chain **linkp = &fill_cfg;
1100 linkp = &(*linkp)->next;
1104 void fill_active_slots(void)
1106 struct active_request_slot *slot = active_queue_head;
1108 while (active_requests < max_requests) {
1109 struct fill_chain *fill;
1110 for (fill = fill_cfg; fill; fill = fill->next)
1111 if (fill->fill(fill->data))
1118 while (slot != NULL) {
1119 if (!slot->in_use && slot->curl != NULL
1120 && curl_session_count > min_curl_sessions) {
1121 curl_easy_cleanup(slot->curl);
1123 curl_session_count--;
1129 void step_active_slots(void)
1132 CURLMcode curlm_result;
1135 curlm_result = curl_multi_perform(curlm, &num_transfers);
1136 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1137 if (num_transfers < active_requests) {
1138 process_curl_messages();
1139 fill_active_slots();
1144 void run_active_slot(struct active_request_slot *slot)
1146 #ifdef USE_CURL_MULTI
1151 struct timeval select_timeout;
1154 slot->finished = &finished;
1156 step_active_slots();
1159 #if LIBCURL_VERSION_NUM >= 0x070f04
1161 curl_multi_timeout(curlm, &curl_timeout);
1162 if (curl_timeout == 0) {
1164 } else if (curl_timeout == -1) {
1165 select_timeout.tv_sec = 0;
1166 select_timeout.tv_usec = 50000;
1168 select_timeout.tv_sec = curl_timeout / 1000;
1169 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1172 select_timeout.tv_sec = 0;
1173 select_timeout.tv_usec = 50000;
1180 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1183 * It can happen that curl_multi_timeout returns a pathologically
1184 * long timeout when curl_multi_fdset returns no file descriptors
1185 * to read. See commit message for more details.
1188 (select_timeout.tv_sec > 0 ||
1189 select_timeout.tv_usec > 50000)) {
1190 select_timeout.tv_sec = 0;
1191 select_timeout.tv_usec = 50000;
1194 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1198 while (slot->in_use) {
1199 slot->curl_result = curl_easy_perform(slot->curl);
1200 finish_active_slot(slot);
1205 static void release_active_slot(struct active_request_slot *slot)
1207 closedown_active_slot(slot);
1209 xmulti_remove_handle(slot);
1210 if (curl_session_count > min_curl_sessions) {
1211 curl_easy_cleanup(slot->curl);
1213 curl_session_count--;
1216 #ifdef USE_CURL_MULTI
1217 fill_active_slots();
1221 void finish_all_active_slots(void)
1223 struct active_request_slot *slot = active_queue_head;
1225 while (slot != NULL)
1227 run_active_slot(slot);
1228 slot = active_queue_head;
1234 /* Helpers for modifying and creating URLs */
1235 static inline int needs_quote(int ch)
1237 if (((ch >= 'A') && (ch <= 'Z'))
1238 || ((ch >= 'a') && (ch <= 'z'))
1239 || ((ch >= '0') && (ch <= '9'))
1247 static char *quote_ref_url(const char *base, const char *ref)
1249 struct strbuf buf = STRBUF_INIT;
1253 end_url_with_slash(&buf, base);
1255 for (cp = ref; (ch = *cp) != 0; cp++)
1256 if (needs_quote(ch))
1257 strbuf_addf(&buf, "%%%02x", ch);
1259 strbuf_addch(&buf, *cp);
1261 return strbuf_detach(&buf, NULL);
1264 void append_remote_object_url(struct strbuf *buf, const char *url,
1266 int only_two_digit_prefix)
1268 end_url_with_slash(buf, url);
1270 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1271 if (!only_two_digit_prefix)
1272 strbuf_addstr(buf, hex + 2);
1275 char *get_remote_object_url(const char *url, const char *hex,
1276 int only_two_digit_prefix)
1278 struct strbuf buf = STRBUF_INIT;
1279 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1280 return strbuf_detach(&buf, NULL);
1283 static int handle_curl_result(struct slot_results *results)
1286 * If we see a failing http code with CURLE_OK, we have turned off
1287 * FAILONERROR (to keep the server's custom error response), and should
1288 * translate the code into failure here.
1290 if (results->curl_result == CURLE_OK &&
1291 results->http_code >= 400) {
1292 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1294 * Normally curl will already have put the "reason phrase"
1295 * from the server into curl_errorstr; unfortunately without
1296 * FAILONERROR it is lost, so we can give only the numeric
1299 snprintf(curl_errorstr, sizeof(curl_errorstr),
1300 "The requested URL returned error: %ld",
1301 results->http_code);
1304 if (results->curl_result == CURLE_OK) {
1305 credential_approve(&http_auth);
1306 if (proxy_auth.password)
1307 credential_approve(&proxy_auth);
1309 } else if (missing_target(results))
1310 return HTTP_MISSING_TARGET;
1311 else if (results->http_code == 401) {
1312 if (http_auth.username && http_auth.password) {
1313 credential_reject(&http_auth);
1316 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1317 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1322 if (results->http_connectcode == 407)
1323 credential_reject(&proxy_auth);
1324 #if LIBCURL_VERSION_NUM >= 0x070c00
1325 if (!curl_errorstr[0])
1326 strlcpy(curl_errorstr,
1327 curl_easy_strerror(results->curl_result),
1328 sizeof(curl_errorstr));
1334 int run_one_slot(struct active_request_slot *slot,
1335 struct slot_results *results)
1337 slot->results = results;
1338 if (!start_active_slot(slot)) {
1339 snprintf(curl_errorstr, sizeof(curl_errorstr),
1340 "failed to start HTTP request");
1341 return HTTP_START_FAILED;
1344 run_active_slot(slot);
1345 return handle_curl_result(results);
1348 struct curl_slist *http_copy_default_headers(void)
1350 struct curl_slist *headers = NULL, *h;
1352 for (h = extra_http_headers; h; h = h->next)
1353 headers = curl_slist_append(headers, h->data);
1358 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1364 ret = curl_easy_getinfo(curl, info, &ptr);
1366 strbuf_addstr(buf, ptr);
1371 * Check for and extract a content-type parameter. "raw"
1372 * should be positioned at the start of the potential
1373 * parameter, with any whitespace already removed.
1375 * "name" is the name of the parameter. The value is appended
1378 static int extract_param(const char *raw, const char *name,
1381 size_t len = strlen(name);
1383 if (strncasecmp(raw, name, len))
1391 while (*raw && !isspace(*raw) && *raw != ';')
1392 strbuf_addch(out, *raw++);
1397 * Extract a normalized version of the content type, with any
1398 * spaces suppressed, all letters lowercased, and no trailing ";"
1401 * Note that we will silently remove even invalid whitespace. For
1402 * example, "text / plain" is specifically forbidden by RFC 2616,
1403 * but "text/plain" is the only reasonable output, and this keeps
1406 * If the "charset" argument is not NULL, store the value of any
1407 * charset parameter there.
1410 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1411 * "text / plain" -> "text/plain"
1413 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1414 struct strbuf *charset)
1419 strbuf_grow(type, raw->len);
1420 for (p = raw->buf; *p; p++) {
1427 strbuf_addch(type, tolower(*p));
1433 strbuf_reset(charset);
1435 while (isspace(*p) || *p == ';')
1437 if (!extract_param(p, "charset", charset))
1439 while (*p && !isspace(*p))
1443 if (!charset->len && starts_with(type->buf, "text/"))
1444 strbuf_addstr(charset, "ISO-8859-1");
1447 static void write_accept_language(struct strbuf *buf)
1450 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1451 * that, q-value will be smaller than 0.001, the minimum q-value the
1452 * HTTP specification allows. See
1453 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1455 const int MAX_DECIMAL_PLACES = 3;
1456 const int MAX_LANGUAGE_TAGS = 1000;
1457 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1458 char **language_tags = NULL;
1460 const char *s = get_preferred_languages();
1462 struct strbuf tag = STRBUF_INIT;
1464 /* Don't add Accept-Language header if no language is preferred. */
1469 * Split the colon-separated string of preferred languages into
1470 * language_tags array.
1473 /* collect language tag */
1474 for (; *s && (isalnum(*s) || *s == '_'); s++)
1475 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1477 /* skip .codeset, @modifier and any other unnecessary parts */
1478 while (*s && *s != ':')
1483 REALLOC_ARRAY(language_tags, num_langs);
1484 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1485 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1490 /* write Accept-Language header into buf */
1492 int last_buf_len = 0;
1498 REALLOC_ARRAY(language_tags, num_langs + 1);
1499 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1501 /* compute decimal_places */
1502 for (max_q = 1, decimal_places = 0;
1503 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1504 decimal_places++, max_q *= 10)
1507 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1509 strbuf_addstr(buf, "Accept-Language: ");
1511 for (i = 0; i < num_langs; i++) {
1513 strbuf_addstr(buf, ", ");
1515 strbuf_addstr(buf, language_tags[i]);
1518 strbuf_addf(buf, q_format, max_q - i);
1520 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1521 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1525 last_buf_len = buf->len;
1529 /* free language tags -- last one is a static '*' */
1530 for (i = 0; i < num_langs - 1; i++)
1531 free(language_tags[i]);
1532 free(language_tags);
1536 * Get an Accept-Language header which indicates user's preferred languages.
1540 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1541 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1542 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1543 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1544 * LANGUAGE= LANG=C -> ""
1546 static const char *get_accept_language(void)
1548 if (!cached_accept_language) {
1549 struct strbuf buf = STRBUF_INIT;
1550 write_accept_language(&buf);
1552 cached_accept_language = strbuf_detach(&buf, NULL);
1555 return cached_accept_language;
1558 static void http_opt_request_remainder(CURL *curl, off_t pos)
1561 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1562 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1565 /* http_request() targets */
1566 #define HTTP_REQUEST_STRBUF 0
1567 #define HTTP_REQUEST_FILE 1
1569 static int http_request(const char *url,
1570 void *result, int target,
1571 const struct http_get_options *options)
1573 struct active_request_slot *slot;
1574 struct slot_results results;
1575 struct curl_slist *headers = http_copy_default_headers();
1576 struct strbuf buf = STRBUF_INIT;
1577 const char *accept_language;
1580 slot = get_active_slot();
1581 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1583 if (result == NULL) {
1584 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1586 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1587 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1589 if (target == HTTP_REQUEST_FILE) {
1590 off_t posn = ftello(result);
1591 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1594 http_opt_request_remainder(slot->curl, posn);
1596 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1600 accept_language = get_accept_language();
1602 if (accept_language)
1603 headers = curl_slist_append(headers, accept_language);
1605 strbuf_addstr(&buf, "Pragma:");
1606 if (options && options->no_cache)
1607 strbuf_addstr(&buf, " no-cache");
1608 if (options && options->keep_error)
1609 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1611 headers = curl_slist_append(headers, buf.buf);
1613 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1614 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1615 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1617 ret = run_one_slot(slot, &results);
1619 if (options && options->content_type) {
1620 struct strbuf raw = STRBUF_INIT;
1621 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1622 extract_content_type(&raw, options->content_type,
1624 strbuf_release(&raw);
1627 if (options && options->effective_url)
1628 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1629 options->effective_url);
1631 curl_slist_free_all(headers);
1632 strbuf_release(&buf);
1638 * Update the "base" url to a more appropriate value, as deduced by
1639 * redirects seen when requesting a URL starting with "url".
1641 * The "asked" parameter is a URL that we asked curl to access, and must begin
1644 * The "got" parameter is the URL that curl reported to us as where we ended
1647 * Returns 1 if we updated the base url, 0 otherwise.
1649 * Our basic strategy is to compare "base" and "asked" to find the bits
1650 * specific to our request. We then strip those bits off of "got" to yield the
1651 * new base. So for example, if our base is "http://example.com/foo.git",
1652 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1653 * with "https://other.example.com/foo.git/info/refs". We would want the
1654 * new URL to become "https://other.example.com/foo.git".
1656 * Note that this assumes a sane redirect scheme. It's entirely possible
1657 * in the example above to end up at a URL that does not even end in
1658 * "info/refs". In such a case we simply punt, as there is not much we can
1659 * do (and such a scheme is unlikely to represent a real git repository,
1660 * which means we are likely about to abort anyway).
1662 static int update_url_from_redirect(struct strbuf *base,
1664 const struct strbuf *got)
1669 if (!strcmp(asked, got->buf))
1672 if (!skip_prefix(asked, base->buf, &tail))
1673 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1676 tail_len = strlen(tail);
1678 if (got->len < tail_len ||
1679 strcmp(tail, got->buf + got->len - tail_len))
1680 return 0; /* insane redirect scheme */
1683 strbuf_add(base, got->buf, got->len - tail_len);
1687 static int http_request_reauth(const char *url,
1688 void *result, int target,
1689 struct http_get_options *options)
1691 int ret = http_request(url, result, target, options);
1693 if (options && options->effective_url && options->base_url) {
1694 if (update_url_from_redirect(options->base_url,
1695 url, options->effective_url)) {
1696 credential_from_url(&http_auth, options->base_url->buf);
1697 url = options->effective_url->buf;
1701 if (ret != HTTP_REAUTH)
1705 * If we are using KEEP_ERROR, the previous request may have
1706 * put cruft into our output stream; we should clear it out before
1707 * making our next request. We only know how to do this for
1708 * the strbuf case, but that is enough to satisfy current callers.
1710 if (options && options->keep_error) {
1712 case HTTP_REQUEST_STRBUF:
1713 strbuf_reset(result);
1716 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1720 credential_fill(&http_auth);
1722 return http_request(url, result, target, options);
1725 int http_get_strbuf(const char *url,
1726 struct strbuf *result,
1727 struct http_get_options *options)
1729 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1733 * Downloads a URL and stores the result in the given file.
1735 * If a previous interrupted download is detected (i.e. a previous temporary
1736 * file is still around) the download is resumed.
1738 static int http_get_file(const char *url, const char *filename,
1739 struct http_get_options *options)
1742 struct strbuf tmpfile = STRBUF_INIT;
1745 strbuf_addf(&tmpfile, "%s.temp", filename);
1746 result = fopen(tmpfile.buf, "a");
1748 error("Unable to open local file %s", tmpfile.buf);
1753 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1756 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1759 strbuf_release(&tmpfile);
1763 int http_fetch_ref(const char *base, struct ref *ref)
1765 struct http_get_options options = {0};
1767 struct strbuf buffer = STRBUF_INIT;
1770 options.no_cache = 1;
1772 url = quote_ref_url(base, ref->name);
1773 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1774 strbuf_rtrim(&buffer);
1775 if (buffer.len == 40)
1776 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1777 else if (starts_with(buffer.buf, "ref: ")) {
1778 ref->symref = xstrdup(buffer.buf + 5);
1783 strbuf_release(&buffer);
1788 /* Helpers for fetching packs */
1789 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1792 struct strbuf buf = STRBUF_INIT;
1794 if (http_is_verbose)
1795 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1797 end_url_with_slash(&buf, base_url);
1798 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1799 url = strbuf_detach(&buf, NULL);
1801 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1802 tmp = strbuf_detach(&buf, NULL);
1804 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1805 error("Unable to get pack index %s", url);
1814 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1815 unsigned char *sha1, const char *base_url)
1817 struct packed_git *new_pack;
1818 char *tmp_idx = NULL;
1821 if (has_pack_index(sha1)) {
1822 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1824 return -1; /* parse_pack_index() already issued error message */
1828 tmp_idx = fetch_pack_index(sha1, base_url);
1832 new_pack = parse_pack_index(sha1, tmp_idx);
1837 return -1; /* parse_pack_index() already issued error message */
1840 ret = verify_pack_index(new_pack);
1842 close_pack_index(new_pack);
1843 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1850 new_pack->next = *packs_head;
1851 *packs_head = new_pack;
1855 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1857 struct http_get_options options = {0};
1860 struct strbuf buf = STRBUF_INIT;
1861 unsigned char sha1[20];
1863 end_url_with_slash(&buf, base_url);
1864 strbuf_addstr(&buf, "objects/info/packs");
1865 url = strbuf_detach(&buf, NULL);
1867 options.no_cache = 1;
1868 ret = http_get_strbuf(url, &buf, &options);
1873 while (i < buf.len) {
1877 if (i + 52 <= buf.len &&
1878 starts_with(data + i, " pack-") &&
1879 starts_with(data + i + 46, ".pack\n")) {
1880 get_sha1_hex(data + i + 6, sha1);
1881 fetch_and_setup_pack_index(packs_head, sha1,
1887 while (i < buf.len && data[i] != '\n')
1898 void release_http_pack_request(struct http_pack_request *preq)
1900 if (preq->packfile != NULL) {
1901 fclose(preq->packfile);
1902 preq->packfile = NULL;
1909 int finish_http_pack_request(struct http_pack_request *preq)
1911 struct packed_git **lst;
1912 struct packed_git *p = preq->target;
1915 struct child_process ip = CHILD_PROCESS_INIT;
1916 const char *ip_argv[8];
1918 close_pack_index(p);
1920 fclose(preq->packfile);
1921 preq->packfile = NULL;
1925 lst = &((*lst)->next);
1926 *lst = (*lst)->next;
1928 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1929 die("BUG: pack tmpfile does not end in .pack.temp?");
1930 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1932 ip_argv[0] = "index-pack";
1934 ip_argv[2] = tmp_idx;
1935 ip_argv[3] = preq->tmpfile;
1943 if (run_command(&ip)) {
1944 unlink(preq->tmpfile);
1950 unlink(sha1_pack_index_name(p->sha1));
1952 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1953 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1958 install_packed_git(p);
1963 struct http_pack_request *new_http_pack_request(
1964 struct packed_git *target, const char *base_url)
1966 off_t prev_posn = 0;
1967 struct strbuf buf = STRBUF_INIT;
1968 struct http_pack_request *preq;
1970 preq = xcalloc(1, sizeof(*preq));
1971 preq->target = target;
1973 end_url_with_slash(&buf, base_url);
1974 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1975 sha1_to_hex(target->sha1));
1976 preq->url = strbuf_detach(&buf, NULL);
1978 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1979 sha1_pack_name(target->sha1));
1980 preq->packfile = fopen(preq->tmpfile, "a");
1981 if (!preq->packfile) {
1982 error("Unable to open local file %s for pack",
1987 preq->slot = get_active_slot();
1988 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1989 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1990 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1991 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1995 * If there is data present from a previous transfer attempt,
1996 * resume where it left off
1998 prev_posn = ftello(preq->packfile);
2000 if (http_is_verbose)
2002 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2003 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2004 http_opt_request_remainder(preq->slot->curl, prev_posn);
2015 /* Helpers for fetching objects (loose) */
2016 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2019 unsigned char expn[4096];
2020 size_t size = eltsize * nmemb;
2022 struct http_object_request *freq = data;
2023 struct active_request_slot *slot = freq->slot;
2026 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2029 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2030 curl_easy_strerror(c));
2031 if (slot->http_code >= 400)
2036 ssize_t retval = xwrite(freq->localfile,
2037 (char *) ptr + posn, size - posn);
2041 } while (posn < size);
2043 freq->stream.avail_in = size;
2044 freq->stream.next_in = (void *)ptr;
2046 freq->stream.next_out = expn;
2047 freq->stream.avail_out = sizeof(expn);
2048 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2049 git_SHA1_Update(&freq->c, expn,
2050 sizeof(expn) - freq->stream.avail_out);
2051 } while (freq->stream.avail_in && freq->zret == Z_OK);
2055 struct http_object_request *new_http_object_request(const char *base_url,
2056 unsigned char *sha1)
2058 char *hex = sha1_to_hex(sha1);
2059 const char *filename;
2060 char prevfile[PATH_MAX];
2062 char prev_buf[PREV_BUF_SIZE];
2063 ssize_t prev_read = 0;
2064 off_t prev_posn = 0;
2065 struct http_object_request *freq;
2067 freq = xcalloc(1, sizeof(*freq));
2068 hashcpy(freq->sha1, sha1);
2069 freq->localfile = -1;
2071 filename = sha1_file_name(sha1);
2072 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2073 "%s.temp", filename);
2075 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2076 unlink_or_warn(prevfile);
2077 rename(freq->tmpfile, prevfile);
2078 unlink_or_warn(freq->tmpfile);
2080 if (freq->localfile != -1)
2081 error("fd leakage in start: %d", freq->localfile);
2082 freq->localfile = open(freq->tmpfile,
2083 O_WRONLY | O_CREAT | O_EXCL, 0666);
2085 * This could have failed due to the "lazy directory creation";
2086 * try to mkdir the last path component.
2088 if (freq->localfile < 0 && errno == ENOENT) {
2089 char *dir = strrchr(freq->tmpfile, '/');
2092 mkdir(freq->tmpfile, 0777);
2095 freq->localfile = open(freq->tmpfile,
2096 O_WRONLY | O_CREAT | O_EXCL, 0666);
2099 if (freq->localfile < 0) {
2100 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2104 git_inflate_init(&freq->stream);
2106 git_SHA1_Init(&freq->c);
2108 freq->url = get_remote_object_url(base_url, hex, 0);
2111 * If a previous temp file is present, process what was already
2114 prevlocal = open(prevfile, O_RDONLY);
2115 if (prevlocal != -1) {
2117 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2119 if (fwrite_sha1_file(prev_buf,
2122 freq) == prev_read) {
2123 prev_posn += prev_read;
2128 } while (prev_read > 0);
2131 unlink_or_warn(prevfile);
2134 * Reset inflate/SHA1 if there was an error reading the previous temp
2135 * file; also rewind to the beginning of the local file.
2137 if (prev_read == -1) {
2138 memset(&freq->stream, 0, sizeof(freq->stream));
2139 git_inflate_init(&freq->stream);
2140 git_SHA1_Init(&freq->c);
2143 lseek(freq->localfile, 0, SEEK_SET);
2144 if (ftruncate(freq->localfile, 0) < 0) {
2145 error_errno("Couldn't truncate temporary file %s",
2152 freq->slot = get_active_slot();
2154 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2155 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2156 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2157 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2158 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2159 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2162 * If we have successfully processed data from a previous fetch
2163 * attempt, only fetch the data we don't already have.
2166 if (http_is_verbose)
2168 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2169 hex, (uintmax_t)prev_posn);
2170 http_opt_request_remainder(freq->slot->curl, prev_posn);
2181 void process_http_object_request(struct http_object_request *freq)
2183 if (freq->slot == NULL)
2185 freq->curl_result = freq->slot->curl_result;
2186 freq->http_code = freq->slot->http_code;
2190 int finish_http_object_request(struct http_object_request *freq)
2194 close(freq->localfile);
2195 freq->localfile = -1;
2197 process_http_object_request(freq);
2199 if (freq->http_code == 416) {
2200 warning("requested range invalid; we may already have all the data.");
2201 } else if (freq->curl_result != CURLE_OK) {
2202 if (stat(freq->tmpfile, &st) == 0)
2203 if (st.st_size == 0)
2204 unlink_or_warn(freq->tmpfile);
2208 git_inflate_end(&freq->stream);
2209 git_SHA1_Final(freq->real_sha1, &freq->c);
2210 if (freq->zret != Z_STREAM_END) {
2211 unlink_or_warn(freq->tmpfile);
2214 if (hashcmp(freq->sha1, freq->real_sha1)) {
2215 unlink_or_warn(freq->tmpfile);
2219 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2221 return freq->rename;
2224 void abort_http_object_request(struct http_object_request *freq)
2226 unlink_or_warn(freq->tmpfile);
2228 release_http_object_request(freq);
2231 void release_http_object_request(struct http_object_request *freq)
2233 if (freq->localfile != -1) {
2234 close(freq->localfile);
2235 freq->localfile = -1;
2237 if (freq->url != NULL) {
2241 if (freq->slot != NULL) {
2242 freq->slot->callback_func = NULL;
2243 freq->slot->callback_data = NULL;
2244 release_active_slot(freq->slot);