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 static struct credential proxy_auth = CREDENTIAL_INIT;
94 static const char *curl_proxyuserpwd;
95 static const char *curl_cookie_file;
96 static int curl_save_cookies;
97 struct credential http_auth = CREDENTIAL_INIT;
98 static int http_proactive_auth;
99 static const char *user_agent;
100 static int curl_empty_auth;
102 #if LIBCURL_VERSION_NUM >= 0x071700
103 /* Use CURLOPT_KEYPASSWD as is */
104 #elif LIBCURL_VERSION_NUM >= 0x070903
105 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
107 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
110 static struct credential cert_auth = CREDENTIAL_INIT;
111 static int ssl_cert_password_required;
112 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
113 static unsigned long http_auth_methods = CURLAUTH_ANY;
116 static struct curl_slist *pragma_header;
117 static struct curl_slist *no_pragma_header;
119 static struct active_request_slot *active_queue_head;
121 static char *cached_accept_language;
123 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
125 size_t size = eltsize * nmemb;
126 struct buffer *buffer = buffer_;
128 if (size > buffer->buf.len - buffer->posn)
129 size = buffer->buf.len - buffer->posn;
130 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
131 buffer->posn += size;
136 #ifndef NO_CURL_IOCTL
137 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
139 struct buffer *buffer = clientp;
145 case CURLIOCMD_RESTARTREAD:
150 return CURLIOE_UNKNOWNCMD;
155 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
157 size_t size = eltsize * nmemb;
158 struct strbuf *buffer = buffer_;
160 strbuf_add(buffer, ptr, size);
164 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
166 return eltsize * nmemb;
169 static void closedown_active_slot(struct active_request_slot *slot)
175 static void finish_active_slot(struct active_request_slot *slot)
177 closedown_active_slot(slot);
178 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
180 if (slot->finished != NULL)
181 (*slot->finished) = 1;
183 /* Store slot results so they can be read after the slot is reused */
184 if (slot->results != NULL) {
185 slot->results->curl_result = slot->curl_result;
186 slot->results->http_code = slot->http_code;
187 #if LIBCURL_VERSION_NUM >= 0x070a08
188 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
189 &slot->results->auth_avail);
191 slot->results->auth_avail = 0;
194 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
195 &slot->results->http_connectcode);
198 /* Run callback if appropriate */
199 if (slot->callback_func != NULL)
200 slot->callback_func(slot->callback_data);
203 #ifdef USE_CURL_MULTI
204 static void process_curl_messages(void)
207 struct active_request_slot *slot;
208 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
210 while (curl_message != NULL) {
211 if (curl_message->msg == CURLMSG_DONE) {
212 int curl_result = curl_message->data.result;
213 slot = active_queue_head;
214 while (slot != NULL &&
215 slot->curl != curl_message->easy_handle)
218 curl_multi_remove_handle(curlm, slot->curl);
219 slot->curl_result = curl_result;
220 finish_active_slot(slot);
222 fprintf(stderr, "Received DONE message for unknown request!\n");
225 fprintf(stderr, "Unknown CURL message received: %d\n",
226 (int)curl_message->msg);
228 curl_message = curl_multi_info_read(curlm, &num_messages);
233 static int http_options(const char *var, const char *value, void *cb)
235 if (!strcmp("http.sslverify", var)) {
236 curl_ssl_verify = git_config_bool(var, value);
239 if (!strcmp("http.sslcipherlist", var))
240 return git_config_string(&ssl_cipherlist, var, value);
241 if (!strcmp("http.sslversion", var))
242 return git_config_string(&ssl_version, var, value);
243 if (!strcmp("http.sslcert", var))
244 return git_config_string(&ssl_cert, var, value);
245 #if LIBCURL_VERSION_NUM >= 0x070903
246 if (!strcmp("http.sslkey", var))
247 return git_config_string(&ssl_key, var, value);
249 #if LIBCURL_VERSION_NUM >= 0x070908
250 if (!strcmp("http.sslcapath", var))
251 return git_config_pathname(&ssl_capath, var, value);
253 if (!strcmp("http.sslcainfo", var))
254 return git_config_pathname(&ssl_cainfo, var, value);
255 if (!strcmp("http.sslcertpasswordprotected", var)) {
256 ssl_cert_password_required = git_config_bool(var, value);
259 if (!strcmp("http.ssltry", var)) {
260 curl_ssl_try = git_config_bool(var, value);
263 if (!strcmp("http.minsessions", var)) {
264 min_curl_sessions = git_config_int(var, value);
265 #ifndef USE_CURL_MULTI
266 if (min_curl_sessions > 1)
267 min_curl_sessions = 1;
271 #ifdef USE_CURL_MULTI
272 if (!strcmp("http.maxrequests", var)) {
273 max_requests = git_config_int(var, value);
277 if (!strcmp("http.lowspeedlimit", var)) {
278 curl_low_speed_limit = (long)git_config_int(var, value);
281 if (!strcmp("http.lowspeedtime", var)) {
282 curl_low_speed_time = (long)git_config_int(var, value);
286 if (!strcmp("http.noepsv", var)) {
287 curl_ftp_no_epsv = git_config_bool(var, value);
290 if (!strcmp("http.proxy", var))
291 return git_config_string(&curl_http_proxy, var, value);
293 if (!strcmp("http.proxyauthmethod", var))
294 return git_config_string(&http_proxy_authmethod, var, value);
296 if (!strcmp("http.cookiefile", var))
297 return git_config_string(&curl_cookie_file, var, value);
298 if (!strcmp("http.savecookies", var)) {
299 curl_save_cookies = git_config_bool(var, value);
303 if (!strcmp("http.postbuffer", var)) {
304 http_post_buffer = git_config_int(var, value);
305 if (http_post_buffer < LARGE_PACKET_MAX)
306 http_post_buffer = LARGE_PACKET_MAX;
310 if (!strcmp("http.useragent", var))
311 return git_config_string(&user_agent, var, value);
313 if (!strcmp("http.emptyauth", var)) {
314 curl_empty_auth = git_config_bool(var, value);
318 if (!strcmp("http.pinnedpubkey", var)) {
319 #if LIBCURL_VERSION_NUM >= 0x072c00
320 return git_config_pathname(&ssl_pinnedkey, var, value);
322 warning(_("Public key pinning not supported with cURL < 7.44.0"));
327 /* Fall back on the default ones */
328 return git_default_config(var, value, cb);
331 static void init_curl_http_auth(CURL *result)
333 if (!http_auth.username) {
335 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
339 credential_fill(&http_auth);
341 #if LIBCURL_VERSION_NUM >= 0x071301
342 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
343 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
346 static struct strbuf up = STRBUF_INIT;
348 * Note that we assume we only ever have a single set of
349 * credentials in a given program run, so we do not have
350 * to worry about updating this buffer, only setting its
354 strbuf_addf(&up, "%s:%s",
355 http_auth.username, http_auth.password);
356 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
361 /* *var must be free-able */
362 static void var_override(const char **var, char *value)
366 *var = xstrdup(value);
370 static void set_proxyauth_name_password(CURL *result)
372 #if LIBCURL_VERSION_NUM >= 0x071301
373 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
374 proxy_auth.username);
375 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
376 proxy_auth.password);
378 struct strbuf s = STRBUF_INIT;
380 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
381 strbuf_addch(&s, ':');
382 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
383 curl_proxyuserpwd = strbuf_detach(&s, NULL);
384 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
388 static void init_curl_proxy_auth(CURL *result)
390 if (proxy_auth.username) {
391 if (!proxy_auth.password)
392 credential_fill(&proxy_auth);
393 set_proxyauth_name_password(result);
396 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
398 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
399 if (http_proxy_authmethod) {
401 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
402 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
403 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
404 proxy_authmethods[i].curlauth_param);
408 if (i == ARRAY_SIZE(proxy_authmethods)) {
409 warning("unsupported proxy authentication method %s: using anyauth",
410 http_proxy_authmethod);
411 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
415 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
419 static int has_cert_password(void)
421 if (ssl_cert == NULL || ssl_cert_password_required != 1)
423 if (!cert_auth.password) {
424 cert_auth.protocol = xstrdup("cert");
425 cert_auth.username = xstrdup("");
426 cert_auth.path = xstrdup(ssl_cert);
427 credential_fill(&cert_auth);
432 #if LIBCURL_VERSION_NUM >= 0x071900
433 static void set_curl_keepalive(CURL *c)
435 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
438 #elif LIBCURL_VERSION_NUM >= 0x071000
439 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
443 socklen_t len = (socklen_t)sizeof(ka);
445 if (type != CURLSOCKTYPE_IPCXN)
448 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
450 warning("unable to set SO_KEEPALIVE on socket %s",
453 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
456 static void set_curl_keepalive(CURL *c)
458 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
462 static void set_curl_keepalive(CURL *c)
464 /* not supported on older curl versions */
468 static void redact_sensitive_header(struct strbuf *header)
470 const char *sensitive_header;
472 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
473 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
474 /* The first token is the type, which is OK to log */
475 while (isspace(*sensitive_header))
477 while (*sensitive_header && !isspace(*sensitive_header))
479 /* Everything else is opaque and possibly sensitive */
480 strbuf_setlen(header, sensitive_header - header->buf);
481 strbuf_addstr(header, " <redacted>");
485 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
487 struct strbuf out = STRBUF_INIT;
488 struct strbuf **headers, **header;
490 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
491 text, (long)size, (long)size);
492 trace_strbuf(&trace_curl, &out);
494 strbuf_add(&out, ptr, size);
495 headers = strbuf_split_max(&out, '\n', 0);
497 for (header = headers; *header; header++) {
498 if (hide_sensitive_header)
499 redact_sensitive_header(*header);
500 strbuf_insert((*header), 0, text, strlen(text));
501 strbuf_insert((*header), strlen(text), ": ", 2);
502 strbuf_rtrim((*header));
503 strbuf_addch((*header), '\n');
504 trace_strbuf(&trace_curl, (*header));
506 strbuf_list_free(headers);
507 strbuf_release(&out);
510 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
513 struct strbuf out = STRBUF_INIT;
514 unsigned int width = 60;
516 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
517 text, (long)size, (long)size);
518 trace_strbuf(&trace_curl, &out);
520 for (i = 0; i < size; i += width) {
524 strbuf_addf(&out, "%s: ", text);
525 for (w = 0; (w < width) && (i + w < size); w++) {
526 unsigned char ch = ptr[i + w];
529 (ch >= 0x20) && (ch < 0x80)
532 strbuf_addch(&out, '\n');
533 trace_strbuf(&trace_curl, &out);
535 strbuf_release(&out);
538 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
541 enum { NO_FILTER = 0, DO_FILTER = 1 };
545 trace_printf_key(&trace_curl, "== Info: %s", data);
546 default: /* we ignore unknown types by default */
549 case CURLINFO_HEADER_OUT:
550 text = "=> Send header";
551 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
553 case CURLINFO_DATA_OUT:
554 text = "=> Send data";
555 curl_dump_data(text, (unsigned char *)data, size);
557 case CURLINFO_SSL_DATA_OUT:
558 text = "=> Send SSL data";
559 curl_dump_data(text, (unsigned char *)data, size);
561 case CURLINFO_HEADER_IN:
562 text = "<= Recv header";
563 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
565 case CURLINFO_DATA_IN:
566 text = "<= Recv data";
567 curl_dump_data(text, (unsigned char *)data, size);
569 case CURLINFO_SSL_DATA_IN:
570 text = "<= Recv SSL data";
571 curl_dump_data(text, (unsigned char *)data, size);
577 void setup_curl_trace(CURL *handle)
579 if (!trace_want(&trace_curl))
581 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
582 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
583 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
587 static CURL *get_curl_handle(void)
589 CURL *result = curl_easy_init();
590 long allowed_protocols = 0;
593 die("curl_easy_init failed");
595 if (!curl_ssl_verify) {
596 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
597 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
599 /* Verify authenticity of the peer's certificate */
600 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
601 /* The name in the cert must match whom we tried to connect */
602 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
605 #if LIBCURL_VERSION_NUM >= 0x070907
606 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
608 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
609 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
612 if (http_proactive_auth)
613 init_curl_http_auth(result);
615 if (getenv("GIT_SSL_VERSION"))
616 ssl_version = getenv("GIT_SSL_VERSION");
617 if (ssl_version && *ssl_version) {
619 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
620 if (!strcmp(ssl_version, sslversions[i].name)) {
621 curl_easy_setopt(result, CURLOPT_SSLVERSION,
622 sslversions[i].ssl_version);
626 if (i == ARRAY_SIZE(sslversions))
627 warning("unsupported ssl version %s: using default",
631 if (getenv("GIT_SSL_CIPHER_LIST"))
632 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
633 if (ssl_cipherlist != NULL && *ssl_cipherlist)
634 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
637 if (ssl_cert != NULL)
638 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
639 if (has_cert_password())
640 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
641 #if LIBCURL_VERSION_NUM >= 0x070903
643 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
645 #if LIBCURL_VERSION_NUM >= 0x070908
646 if (ssl_capath != NULL)
647 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
649 #if LIBCURL_VERSION_NUM >= 0x072c00
650 if (ssl_pinnedkey != NULL)
651 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
653 if (ssl_cainfo != NULL)
654 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
656 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
657 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
658 curl_low_speed_limit);
659 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
660 curl_low_speed_time);
663 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
664 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
665 #if LIBCURL_VERSION_NUM >= 0x071301
666 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
667 #elif LIBCURL_VERSION_NUM >= 0x071101
668 curl_easy_setopt(result, CURLOPT_POST301, 1);
670 #if LIBCURL_VERSION_NUM >= 0x071304
671 if (is_transport_allowed("http"))
672 allowed_protocols |= CURLPROTO_HTTP;
673 if (is_transport_allowed("https"))
674 allowed_protocols |= CURLPROTO_HTTPS;
675 if (is_transport_allowed("ftp"))
676 allowed_protocols |= CURLPROTO_FTP;
677 if (is_transport_allowed("ftps"))
678 allowed_protocols |= CURLPROTO_FTPS;
679 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
681 if (transport_restrict_protocols())
682 warning("protocol restrictions not applied to curl redirects because\n"
683 "your curl version is too old (>= 7.19.4)");
685 if (getenv("GIT_CURL_VERBOSE"))
686 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
687 setup_curl_trace(result);
689 curl_easy_setopt(result, CURLOPT_USERAGENT,
690 user_agent ? user_agent : git_user_agent());
692 if (curl_ftp_no_epsv)
693 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
695 #ifdef CURLOPT_USE_SSL
697 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
701 * CURL also examines these variables as a fallback; but we need to query
702 * them here in order to decide whether to prompt for missing password (cf.
703 * init_curl_proxy_auth()).
705 * Unlike many other common environment variables, these are historically
706 * lowercase only. It appears that CURL did not know this and implemented
707 * only uppercase variants, which was later corrected to take both - with
708 * the exception of http_proxy, which is lowercase only also in CURL. As
709 * the lowercase versions are the historical quasi-standard, they take
710 * precedence here, as in CURL.
712 if (!curl_http_proxy) {
713 if (!strcmp(http_auth.protocol, "https")) {
714 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
715 var_override(&curl_http_proxy, getenv("https_proxy"));
717 var_override(&curl_http_proxy, getenv("http_proxy"));
719 if (!curl_http_proxy) {
720 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
721 var_override(&curl_http_proxy, getenv("all_proxy"));
725 if (curl_http_proxy) {
726 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
727 #if LIBCURL_VERSION_NUM >= 0x071800
728 if (starts_with(curl_http_proxy, "socks5"))
729 curl_easy_setopt(result,
730 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
731 else if (starts_with(curl_http_proxy, "socks4a"))
732 curl_easy_setopt(result,
733 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
734 else if (starts_with(curl_http_proxy, "socks"))
735 curl_easy_setopt(result,
736 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
738 if (strstr(curl_http_proxy, "://"))
739 credential_from_url(&proxy_auth, curl_http_proxy);
741 struct strbuf url = STRBUF_INIT;
742 strbuf_addf(&url, "http://%s", curl_http_proxy);
743 credential_from_url(&proxy_auth, url.buf);
744 strbuf_release(&url);
747 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
748 #if LIBCURL_VERSION_NUM >= 0x071304
749 var_override(&curl_no_proxy, getenv("NO_PROXY"));
750 var_override(&curl_no_proxy, getenv("no_proxy"));
751 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
754 init_curl_proxy_auth(result);
756 set_curl_keepalive(result);
761 static void set_from_env(const char **var, const char *envname)
763 const char *val = getenv(envname);
768 void http_init(struct remote *remote, const char *url, int proactive_auth)
770 char *low_speed_limit;
771 char *low_speed_time;
772 char *normalized_url;
773 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
775 config.section = "http";
777 config.collect_fn = http_options;
778 config.cascade_fn = git_default_config;
782 normalized_url = url_normalize(url, &config.url);
784 git_config(urlmatch_config_entry, &config);
785 free(normalized_url);
787 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
788 die("curl_global_init failed");
790 http_proactive_auth = proactive_auth;
792 if (remote && remote->http_proxy)
793 curl_http_proxy = xstrdup(remote->http_proxy);
796 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
798 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
799 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
801 #ifdef USE_CURL_MULTI
803 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
804 if (http_max_requests != NULL)
805 max_requests = atoi(http_max_requests);
808 curlm = curl_multi_init();
810 die("curl_multi_init failed");
813 if (getenv("GIT_SSL_NO_VERIFY"))
816 set_from_env(&ssl_cert, "GIT_SSL_CERT");
817 #if LIBCURL_VERSION_NUM >= 0x070903
818 set_from_env(&ssl_key, "GIT_SSL_KEY");
820 #if LIBCURL_VERSION_NUM >= 0x070908
821 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
823 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
825 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
827 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
828 if (low_speed_limit != NULL)
829 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
830 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
831 if (low_speed_time != NULL)
832 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
834 if (curl_ssl_verify == -1)
837 curl_session_count = 0;
838 #ifdef USE_CURL_MULTI
839 if (max_requests < 1)
840 max_requests = DEFAULT_MAX_REQUESTS;
843 if (getenv("GIT_CURL_FTP_NO_EPSV"))
844 curl_ftp_no_epsv = 1;
847 credential_from_url(&http_auth, url);
848 if (!ssl_cert_password_required &&
849 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
850 starts_with(url, "https://"))
851 ssl_cert_password_required = 1;
854 #ifndef NO_CURL_EASY_DUPHANDLE
855 curl_default = get_curl_handle();
859 void http_cleanup(void)
861 struct active_request_slot *slot = active_queue_head;
863 while (slot != NULL) {
864 struct active_request_slot *next = slot->next;
865 if (slot->curl != NULL) {
866 #ifdef USE_CURL_MULTI
867 curl_multi_remove_handle(curlm, slot->curl);
869 curl_easy_cleanup(slot->curl);
874 active_queue_head = NULL;
876 #ifndef NO_CURL_EASY_DUPHANDLE
877 curl_easy_cleanup(curl_default);
880 #ifdef USE_CURL_MULTI
881 curl_multi_cleanup(curlm);
883 curl_global_cleanup();
885 curl_slist_free_all(pragma_header);
886 pragma_header = NULL;
888 curl_slist_free_all(no_pragma_header);
889 no_pragma_header = NULL;
891 if (curl_http_proxy) {
892 free((void *)curl_http_proxy);
893 curl_http_proxy = NULL;
896 if (proxy_auth.password) {
897 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
898 free(proxy_auth.password);
899 proxy_auth.password = NULL;
902 free((void *)curl_proxyuserpwd);
903 curl_proxyuserpwd = NULL;
905 free((void *)http_proxy_authmethod);
906 http_proxy_authmethod = NULL;
908 if (cert_auth.password != NULL) {
909 memset(cert_auth.password, 0, strlen(cert_auth.password));
910 free(cert_auth.password);
911 cert_auth.password = NULL;
913 ssl_cert_password_required = 0;
915 free(cached_accept_language);
916 cached_accept_language = NULL;
919 struct active_request_slot *get_active_slot(void)
921 struct active_request_slot *slot = active_queue_head;
922 struct active_request_slot *newslot;
924 #ifdef USE_CURL_MULTI
927 /* Wait for a slot to open up if the queue is full */
928 while (active_requests >= max_requests) {
929 curl_multi_perform(curlm, &num_transfers);
930 if (num_transfers < active_requests)
931 process_curl_messages();
935 while (slot != NULL && slot->in_use)
939 newslot = xmalloc(sizeof(*newslot));
940 newslot->curl = NULL;
942 newslot->next = NULL;
944 slot = active_queue_head;
946 active_queue_head = newslot;
948 while (slot->next != NULL)
950 slot->next = newslot;
955 if (slot->curl == NULL) {
956 #ifdef NO_CURL_EASY_DUPHANDLE
957 slot->curl = get_curl_handle();
959 slot->curl = curl_easy_duphandle(curl_default);
961 curl_session_count++;
966 slot->results = NULL;
967 slot->finished = NULL;
968 slot->callback_data = NULL;
969 slot->callback_func = NULL;
970 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
971 if (curl_save_cookies)
972 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
973 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
974 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
975 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
976 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
977 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
978 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
979 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
980 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
981 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
982 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
984 #if LIBCURL_VERSION_NUM >= 0x070a08
985 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
987 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
988 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
990 if (http_auth.password || curl_empty_auth)
991 init_curl_http_auth(slot->curl);
996 int start_active_slot(struct active_request_slot *slot)
998 #ifdef USE_CURL_MULTI
999 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1002 if (curlm_result != CURLM_OK &&
1003 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1010 * We know there must be something to do, since we just added
1013 curl_multi_perform(curlm, &num_transfers);
1018 #ifdef USE_CURL_MULTI
1021 int (*fill)(void *);
1022 struct fill_chain *next;
1025 static struct fill_chain *fill_cfg;
1027 void add_fill_function(void *data, int (*fill)(void *))
1029 struct fill_chain *new = xmalloc(sizeof(*new));
1030 struct fill_chain **linkp = &fill_cfg;
1035 linkp = &(*linkp)->next;
1039 void fill_active_slots(void)
1041 struct active_request_slot *slot = active_queue_head;
1043 while (active_requests < max_requests) {
1044 struct fill_chain *fill;
1045 for (fill = fill_cfg; fill; fill = fill->next)
1046 if (fill->fill(fill->data))
1053 while (slot != NULL) {
1054 if (!slot->in_use && slot->curl != NULL
1055 && curl_session_count > min_curl_sessions) {
1056 curl_easy_cleanup(slot->curl);
1058 curl_session_count--;
1064 void step_active_slots(void)
1067 CURLMcode curlm_result;
1070 curlm_result = curl_multi_perform(curlm, &num_transfers);
1071 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1072 if (num_transfers < active_requests) {
1073 process_curl_messages();
1074 fill_active_slots();
1079 void run_active_slot(struct active_request_slot *slot)
1081 #ifdef USE_CURL_MULTI
1086 struct timeval select_timeout;
1089 slot->finished = &finished;
1091 step_active_slots();
1094 #if LIBCURL_VERSION_NUM >= 0x070f04
1096 curl_multi_timeout(curlm, &curl_timeout);
1097 if (curl_timeout == 0) {
1099 } else if (curl_timeout == -1) {
1100 select_timeout.tv_sec = 0;
1101 select_timeout.tv_usec = 50000;
1103 select_timeout.tv_sec = curl_timeout / 1000;
1104 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1107 select_timeout.tv_sec = 0;
1108 select_timeout.tv_usec = 50000;
1115 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1118 * It can happen that curl_multi_timeout returns a pathologically
1119 * long timeout when curl_multi_fdset returns no file descriptors
1120 * to read. See commit message for more details.
1123 (select_timeout.tv_sec > 0 ||
1124 select_timeout.tv_usec > 50000)) {
1125 select_timeout.tv_sec = 0;
1126 select_timeout.tv_usec = 50000;
1129 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1133 while (slot->in_use) {
1134 slot->curl_result = curl_easy_perform(slot->curl);
1135 finish_active_slot(slot);
1140 static void release_active_slot(struct active_request_slot *slot)
1142 closedown_active_slot(slot);
1143 if (slot->curl && curl_session_count > min_curl_sessions) {
1144 #ifdef USE_CURL_MULTI
1145 curl_multi_remove_handle(curlm, slot->curl);
1147 curl_easy_cleanup(slot->curl);
1149 curl_session_count--;
1151 #ifdef USE_CURL_MULTI
1152 fill_active_slots();
1156 void finish_all_active_slots(void)
1158 struct active_request_slot *slot = active_queue_head;
1160 while (slot != NULL)
1162 run_active_slot(slot);
1163 slot = active_queue_head;
1169 /* Helpers for modifying and creating URLs */
1170 static inline int needs_quote(int ch)
1172 if (((ch >= 'A') && (ch <= 'Z'))
1173 || ((ch >= 'a') && (ch <= 'z'))
1174 || ((ch >= '0') && (ch <= '9'))
1182 static char *quote_ref_url(const char *base, const char *ref)
1184 struct strbuf buf = STRBUF_INIT;
1188 end_url_with_slash(&buf, base);
1190 for (cp = ref; (ch = *cp) != 0; cp++)
1191 if (needs_quote(ch))
1192 strbuf_addf(&buf, "%%%02x", ch);
1194 strbuf_addch(&buf, *cp);
1196 return strbuf_detach(&buf, NULL);
1199 void append_remote_object_url(struct strbuf *buf, const char *url,
1201 int only_two_digit_prefix)
1203 end_url_with_slash(buf, url);
1205 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1206 if (!only_two_digit_prefix)
1207 strbuf_addf(buf, "%s", hex+2);
1210 char *get_remote_object_url(const char *url, const char *hex,
1211 int only_two_digit_prefix)
1213 struct strbuf buf = STRBUF_INIT;
1214 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1215 return strbuf_detach(&buf, NULL);
1218 static int handle_curl_result(struct slot_results *results)
1221 * If we see a failing http code with CURLE_OK, we have turned off
1222 * FAILONERROR (to keep the server's custom error response), and should
1223 * translate the code into failure here.
1225 if (results->curl_result == CURLE_OK &&
1226 results->http_code >= 400) {
1227 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1229 * Normally curl will already have put the "reason phrase"
1230 * from the server into curl_errorstr; unfortunately without
1231 * FAILONERROR it is lost, so we can give only the numeric
1234 snprintf(curl_errorstr, sizeof(curl_errorstr),
1235 "The requested URL returned error: %ld",
1236 results->http_code);
1239 if (results->curl_result == CURLE_OK) {
1240 credential_approve(&http_auth);
1241 if (proxy_auth.password)
1242 credential_approve(&proxy_auth);
1244 } else if (missing_target(results))
1245 return HTTP_MISSING_TARGET;
1246 else if (results->http_code == 401) {
1247 if (http_auth.username && http_auth.password) {
1248 credential_reject(&http_auth);
1251 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1252 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1257 if (results->http_connectcode == 407)
1258 credential_reject(&proxy_auth);
1259 #if LIBCURL_VERSION_NUM >= 0x070c00
1260 if (!curl_errorstr[0])
1261 strlcpy(curl_errorstr,
1262 curl_easy_strerror(results->curl_result),
1263 sizeof(curl_errorstr));
1269 int run_one_slot(struct active_request_slot *slot,
1270 struct slot_results *results)
1272 slot->results = results;
1273 if (!start_active_slot(slot)) {
1274 snprintf(curl_errorstr, sizeof(curl_errorstr),
1275 "failed to start HTTP request");
1276 return HTTP_START_FAILED;
1279 run_active_slot(slot);
1280 return handle_curl_result(results);
1283 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1289 ret = curl_easy_getinfo(curl, info, &ptr);
1291 strbuf_addstr(buf, ptr);
1296 * Check for and extract a content-type parameter. "raw"
1297 * should be positioned at the start of the potential
1298 * parameter, with any whitespace already removed.
1300 * "name" is the name of the parameter. The value is appended
1303 static int extract_param(const char *raw, const char *name,
1306 size_t len = strlen(name);
1308 if (strncasecmp(raw, name, len))
1316 while (*raw && !isspace(*raw) && *raw != ';')
1317 strbuf_addch(out, *raw++);
1322 * Extract a normalized version of the content type, with any
1323 * spaces suppressed, all letters lowercased, and no trailing ";"
1326 * Note that we will silently remove even invalid whitespace. For
1327 * example, "text / plain" is specifically forbidden by RFC 2616,
1328 * but "text/plain" is the only reasonable output, and this keeps
1331 * If the "charset" argument is not NULL, store the value of any
1332 * charset parameter there.
1335 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1336 * "text / plain" -> "text/plain"
1338 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1339 struct strbuf *charset)
1344 strbuf_grow(type, raw->len);
1345 for (p = raw->buf; *p; p++) {
1352 strbuf_addch(type, tolower(*p));
1358 strbuf_reset(charset);
1360 while (isspace(*p) || *p == ';')
1362 if (!extract_param(p, "charset", charset))
1364 while (*p && !isspace(*p))
1368 if (!charset->len && starts_with(type->buf, "text/"))
1369 strbuf_addstr(charset, "ISO-8859-1");
1372 static void write_accept_language(struct strbuf *buf)
1375 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1376 * that, q-value will be smaller than 0.001, the minimum q-value the
1377 * HTTP specification allows. See
1378 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1380 const int MAX_DECIMAL_PLACES = 3;
1381 const int MAX_LANGUAGE_TAGS = 1000;
1382 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1383 char **language_tags = NULL;
1385 const char *s = get_preferred_languages();
1387 struct strbuf tag = STRBUF_INIT;
1389 /* Don't add Accept-Language header if no language is preferred. */
1394 * Split the colon-separated string of preferred languages into
1395 * language_tags array.
1398 /* collect language tag */
1399 for (; *s && (isalnum(*s) || *s == '_'); s++)
1400 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1402 /* skip .codeset, @modifier and any other unnecessary parts */
1403 while (*s && *s != ':')
1408 REALLOC_ARRAY(language_tags, num_langs);
1409 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1410 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1415 /* write Accept-Language header into buf */
1417 int last_buf_len = 0;
1423 REALLOC_ARRAY(language_tags, num_langs + 1);
1424 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1426 /* compute decimal_places */
1427 for (max_q = 1, decimal_places = 0;
1428 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1429 decimal_places++, max_q *= 10)
1432 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1434 strbuf_addstr(buf, "Accept-Language: ");
1436 for (i = 0; i < num_langs; i++) {
1438 strbuf_addstr(buf, ", ");
1440 strbuf_addstr(buf, language_tags[i]);
1443 strbuf_addf(buf, q_format, max_q - i);
1445 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1446 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1450 last_buf_len = buf->len;
1454 /* free language tags -- last one is a static '*' */
1455 for (i = 0; i < num_langs - 1; i++)
1456 free(language_tags[i]);
1457 free(language_tags);
1461 * Get an Accept-Language header which indicates user's preferred languages.
1465 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1466 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1467 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1468 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1469 * LANGUAGE= LANG=C -> ""
1471 static const char *get_accept_language(void)
1473 if (!cached_accept_language) {
1474 struct strbuf buf = STRBUF_INIT;
1475 write_accept_language(&buf);
1477 cached_accept_language = strbuf_detach(&buf, NULL);
1480 return cached_accept_language;
1483 static void http_opt_request_remainder(CURL *curl, off_t pos)
1486 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1487 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1490 /* http_request() targets */
1491 #define HTTP_REQUEST_STRBUF 0
1492 #define HTTP_REQUEST_FILE 1
1494 static int http_request(const char *url,
1495 void *result, int target,
1496 const struct http_get_options *options)
1498 struct active_request_slot *slot;
1499 struct slot_results results;
1500 struct curl_slist *headers = NULL;
1501 struct strbuf buf = STRBUF_INIT;
1502 const char *accept_language;
1505 slot = get_active_slot();
1506 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1508 if (result == NULL) {
1509 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1511 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1512 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1514 if (target == HTTP_REQUEST_FILE) {
1515 off_t posn = ftello(result);
1516 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1519 http_opt_request_remainder(slot->curl, posn);
1521 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1525 accept_language = get_accept_language();
1527 if (accept_language)
1528 headers = curl_slist_append(headers, accept_language);
1530 strbuf_addstr(&buf, "Pragma:");
1531 if (options && options->no_cache)
1532 strbuf_addstr(&buf, " no-cache");
1533 if (options && options->keep_error)
1534 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1536 headers = curl_slist_append(headers, buf.buf);
1538 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1539 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1540 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1542 ret = run_one_slot(slot, &results);
1544 if (options && options->content_type) {
1545 struct strbuf raw = STRBUF_INIT;
1546 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1547 extract_content_type(&raw, options->content_type,
1549 strbuf_release(&raw);
1552 if (options && options->effective_url)
1553 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1554 options->effective_url);
1556 curl_slist_free_all(headers);
1557 strbuf_release(&buf);
1563 * Update the "base" url to a more appropriate value, as deduced by
1564 * redirects seen when requesting a URL starting with "url".
1566 * The "asked" parameter is a URL that we asked curl to access, and must begin
1569 * The "got" parameter is the URL that curl reported to us as where we ended
1572 * Returns 1 if we updated the base url, 0 otherwise.
1574 * Our basic strategy is to compare "base" and "asked" to find the bits
1575 * specific to our request. We then strip those bits off of "got" to yield the
1576 * new base. So for example, if our base is "http://example.com/foo.git",
1577 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1578 * with "https://other.example.com/foo.git/info/refs". We would want the
1579 * new URL to become "https://other.example.com/foo.git".
1581 * Note that this assumes a sane redirect scheme. It's entirely possible
1582 * in the example above to end up at a URL that does not even end in
1583 * "info/refs". In such a case we simply punt, as there is not much we can
1584 * do (and such a scheme is unlikely to represent a real git repository,
1585 * which means we are likely about to abort anyway).
1587 static int update_url_from_redirect(struct strbuf *base,
1589 const struct strbuf *got)
1594 if (!strcmp(asked, got->buf))
1597 if (!skip_prefix(asked, base->buf, &tail))
1598 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1601 tail_len = strlen(tail);
1603 if (got->len < tail_len ||
1604 strcmp(tail, got->buf + got->len - tail_len))
1605 return 0; /* insane redirect scheme */
1608 strbuf_add(base, got->buf, got->len - tail_len);
1612 static int http_request_reauth(const char *url,
1613 void *result, int target,
1614 struct http_get_options *options)
1616 int ret = http_request(url, result, target, options);
1618 if (options && options->effective_url && options->base_url) {
1619 if (update_url_from_redirect(options->base_url,
1620 url, options->effective_url)) {
1621 credential_from_url(&http_auth, options->base_url->buf);
1622 url = options->effective_url->buf;
1626 if (ret != HTTP_REAUTH)
1630 * If we are using KEEP_ERROR, the previous request may have
1631 * put cruft into our output stream; we should clear it out before
1632 * making our next request. We only know how to do this for
1633 * the strbuf case, but that is enough to satisfy current callers.
1635 if (options && options->keep_error) {
1637 case HTTP_REQUEST_STRBUF:
1638 strbuf_reset(result);
1641 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1645 credential_fill(&http_auth);
1647 return http_request(url, result, target, options);
1650 int http_get_strbuf(const char *url,
1651 struct strbuf *result,
1652 struct http_get_options *options)
1654 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1658 * Downloads a URL and stores the result in the given file.
1660 * If a previous interrupted download is detected (i.e. a previous temporary
1661 * file is still around) the download is resumed.
1663 static int http_get_file(const char *url, const char *filename,
1664 struct http_get_options *options)
1667 struct strbuf tmpfile = STRBUF_INIT;
1670 strbuf_addf(&tmpfile, "%s.temp", filename);
1671 result = fopen(tmpfile.buf, "a");
1673 error("Unable to open local file %s", tmpfile.buf);
1678 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1681 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1684 strbuf_release(&tmpfile);
1688 int http_fetch_ref(const char *base, struct ref *ref)
1690 struct http_get_options options = {0};
1692 struct strbuf buffer = STRBUF_INIT;
1695 options.no_cache = 1;
1697 url = quote_ref_url(base, ref->name);
1698 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1699 strbuf_rtrim(&buffer);
1700 if (buffer.len == 40)
1701 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1702 else if (starts_with(buffer.buf, "ref: ")) {
1703 ref->symref = xstrdup(buffer.buf + 5);
1708 strbuf_release(&buffer);
1713 /* Helpers for fetching packs */
1714 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1717 struct strbuf buf = STRBUF_INIT;
1719 if (http_is_verbose)
1720 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1722 end_url_with_slash(&buf, base_url);
1723 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1724 url = strbuf_detach(&buf, NULL);
1726 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1727 tmp = strbuf_detach(&buf, NULL);
1729 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1730 error("Unable to get pack index %s", url);
1739 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1740 unsigned char *sha1, const char *base_url)
1742 struct packed_git *new_pack;
1743 char *tmp_idx = NULL;
1746 if (has_pack_index(sha1)) {
1747 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1749 return -1; /* parse_pack_index() already issued error message */
1753 tmp_idx = fetch_pack_index(sha1, base_url);
1757 new_pack = parse_pack_index(sha1, tmp_idx);
1762 return -1; /* parse_pack_index() already issued error message */
1765 ret = verify_pack_index(new_pack);
1767 close_pack_index(new_pack);
1768 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1775 new_pack->next = *packs_head;
1776 *packs_head = new_pack;
1780 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1782 struct http_get_options options = {0};
1785 struct strbuf buf = STRBUF_INIT;
1786 unsigned char sha1[20];
1788 end_url_with_slash(&buf, base_url);
1789 strbuf_addstr(&buf, "objects/info/packs");
1790 url = strbuf_detach(&buf, NULL);
1792 options.no_cache = 1;
1793 ret = http_get_strbuf(url, &buf, &options);
1798 while (i < buf.len) {
1802 if (i + 52 <= buf.len &&
1803 starts_with(data + i, " pack-") &&
1804 starts_with(data + i + 46, ".pack\n")) {
1805 get_sha1_hex(data + i + 6, sha1);
1806 fetch_and_setup_pack_index(packs_head, sha1,
1812 while (i < buf.len && data[i] != '\n')
1823 void release_http_pack_request(struct http_pack_request *preq)
1825 if (preq->packfile != NULL) {
1826 fclose(preq->packfile);
1827 preq->packfile = NULL;
1834 int finish_http_pack_request(struct http_pack_request *preq)
1836 struct packed_git **lst;
1837 struct packed_git *p = preq->target;
1840 struct child_process ip = CHILD_PROCESS_INIT;
1841 const char *ip_argv[8];
1843 close_pack_index(p);
1845 fclose(preq->packfile);
1846 preq->packfile = NULL;
1850 lst = &((*lst)->next);
1851 *lst = (*lst)->next;
1853 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1854 die("BUG: pack tmpfile does not end in .pack.temp?");
1855 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1857 ip_argv[0] = "index-pack";
1859 ip_argv[2] = tmp_idx;
1860 ip_argv[3] = preq->tmpfile;
1868 if (run_command(&ip)) {
1869 unlink(preq->tmpfile);
1875 unlink(sha1_pack_index_name(p->sha1));
1877 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1878 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1883 install_packed_git(p);
1888 struct http_pack_request *new_http_pack_request(
1889 struct packed_git *target, const char *base_url)
1891 off_t prev_posn = 0;
1892 struct strbuf buf = STRBUF_INIT;
1893 struct http_pack_request *preq;
1895 preq = xcalloc(1, sizeof(*preq));
1896 preq->target = target;
1898 end_url_with_slash(&buf, base_url);
1899 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1900 sha1_to_hex(target->sha1));
1901 preq->url = strbuf_detach(&buf, NULL);
1903 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1904 sha1_pack_name(target->sha1));
1905 preq->packfile = fopen(preq->tmpfile, "a");
1906 if (!preq->packfile) {
1907 error("Unable to open local file %s for pack",
1912 preq->slot = get_active_slot();
1913 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1914 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1915 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1916 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1920 * If there is data present from a previous transfer attempt,
1921 * resume where it left off
1923 prev_posn = ftello(preq->packfile);
1925 if (http_is_verbose)
1927 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1928 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1929 http_opt_request_remainder(preq->slot->curl, prev_posn);
1940 /* Helpers for fetching objects (loose) */
1941 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1944 unsigned char expn[4096];
1945 size_t size = eltsize * nmemb;
1947 struct http_object_request *freq =
1948 (struct http_object_request *)data;
1950 ssize_t retval = xwrite(freq->localfile,
1951 (char *) ptr + posn, size - posn);
1955 } while (posn < size);
1957 freq->stream.avail_in = size;
1958 freq->stream.next_in = (void *)ptr;
1960 freq->stream.next_out = expn;
1961 freq->stream.avail_out = sizeof(expn);
1962 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1963 git_SHA1_Update(&freq->c, expn,
1964 sizeof(expn) - freq->stream.avail_out);
1965 } while (freq->stream.avail_in && freq->zret == Z_OK);
1969 struct http_object_request *new_http_object_request(const char *base_url,
1970 unsigned char *sha1)
1972 char *hex = sha1_to_hex(sha1);
1973 const char *filename;
1974 char prevfile[PATH_MAX];
1976 char prev_buf[PREV_BUF_SIZE];
1977 ssize_t prev_read = 0;
1978 off_t prev_posn = 0;
1979 struct http_object_request *freq;
1981 freq = xcalloc(1, sizeof(*freq));
1982 hashcpy(freq->sha1, sha1);
1983 freq->localfile = -1;
1985 filename = sha1_file_name(sha1);
1986 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1987 "%s.temp", filename);
1989 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1990 unlink_or_warn(prevfile);
1991 rename(freq->tmpfile, prevfile);
1992 unlink_or_warn(freq->tmpfile);
1994 if (freq->localfile != -1)
1995 error("fd leakage in start: %d", freq->localfile);
1996 freq->localfile = open(freq->tmpfile,
1997 O_WRONLY | O_CREAT | O_EXCL, 0666);
1999 * This could have failed due to the "lazy directory creation";
2000 * try to mkdir the last path component.
2002 if (freq->localfile < 0 && errno == ENOENT) {
2003 char *dir = strrchr(freq->tmpfile, '/');
2006 mkdir(freq->tmpfile, 0777);
2009 freq->localfile = open(freq->tmpfile,
2010 O_WRONLY | O_CREAT | O_EXCL, 0666);
2013 if (freq->localfile < 0) {
2014 error("Couldn't create temporary file %s: %s",
2015 freq->tmpfile, strerror(errno));
2019 git_inflate_init(&freq->stream);
2021 git_SHA1_Init(&freq->c);
2023 freq->url = get_remote_object_url(base_url, hex, 0);
2026 * If a previous temp file is present, process what was already
2029 prevlocal = open(prevfile, O_RDONLY);
2030 if (prevlocal != -1) {
2032 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2034 if (fwrite_sha1_file(prev_buf,
2037 freq) == prev_read) {
2038 prev_posn += prev_read;
2043 } while (prev_read > 0);
2046 unlink_or_warn(prevfile);
2049 * Reset inflate/SHA1 if there was an error reading the previous temp
2050 * file; also rewind to the beginning of the local file.
2052 if (prev_read == -1) {
2053 memset(&freq->stream, 0, sizeof(freq->stream));
2054 git_inflate_init(&freq->stream);
2055 git_SHA1_Init(&freq->c);
2058 lseek(freq->localfile, 0, SEEK_SET);
2059 if (ftruncate(freq->localfile, 0) < 0) {
2060 error("Couldn't truncate temporary file %s: %s",
2061 freq->tmpfile, strerror(errno));
2067 freq->slot = get_active_slot();
2069 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2070 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2071 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2072 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2073 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2076 * If we have successfully processed data from a previous fetch
2077 * attempt, only fetch the data we don't already have.
2080 if (http_is_verbose)
2082 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2083 hex, (uintmax_t)prev_posn);
2084 http_opt_request_remainder(freq->slot->curl, prev_posn);
2095 void process_http_object_request(struct http_object_request *freq)
2097 if (freq->slot == NULL)
2099 freq->curl_result = freq->slot->curl_result;
2100 freq->http_code = freq->slot->http_code;
2104 int finish_http_object_request(struct http_object_request *freq)
2108 close(freq->localfile);
2109 freq->localfile = -1;
2111 process_http_object_request(freq);
2113 if (freq->http_code == 416) {
2114 warning("requested range invalid; we may already have all the data.");
2115 } else if (freq->curl_result != CURLE_OK) {
2116 if (stat(freq->tmpfile, &st) == 0)
2117 if (st.st_size == 0)
2118 unlink_or_warn(freq->tmpfile);
2122 git_inflate_end(&freq->stream);
2123 git_SHA1_Final(freq->real_sha1, &freq->c);
2124 if (freq->zret != Z_STREAM_END) {
2125 unlink_or_warn(freq->tmpfile);
2128 if (hashcmp(freq->sha1, freq->real_sha1)) {
2129 unlink_or_warn(freq->tmpfile);
2133 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2135 return freq->rename;
2138 void abort_http_object_request(struct http_object_request *freq)
2140 unlink_or_warn(freq->tmpfile);
2142 release_http_object_request(freq);
2145 void release_http_object_request(struct http_object_request *freq)
2147 if (freq->localfile != -1) {
2148 close(freq->localfile);
2149 freq->localfile = -1;
2151 if (freq->url != NULL) {
2155 if (freq->slot != NULL) {
2156 freq->slot->callback_func = NULL;
2157 freq->slot->callback_data = NULL;
2158 release_active_slot(freq->slot);