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;
118 static struct curl_slist *extra_http_headers;
120 static struct active_request_slot *active_queue_head;
122 static char *cached_accept_language;
124 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
126 size_t size = eltsize * nmemb;
127 struct buffer *buffer = buffer_;
129 if (size > buffer->buf.len - buffer->posn)
130 size = buffer->buf.len - buffer->posn;
131 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
132 buffer->posn += size;
137 #ifndef NO_CURL_IOCTL
138 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
140 struct buffer *buffer = clientp;
146 case CURLIOCMD_RESTARTREAD:
151 return CURLIOE_UNKNOWNCMD;
156 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
158 size_t size = eltsize * nmemb;
159 struct strbuf *buffer = buffer_;
161 strbuf_add(buffer, ptr, size);
165 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
167 return eltsize * nmemb;
170 static void closedown_active_slot(struct active_request_slot *slot)
176 static void finish_active_slot(struct active_request_slot *slot)
178 closedown_active_slot(slot);
179 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
181 if (slot->finished != NULL)
182 (*slot->finished) = 1;
184 /* Store slot results so they can be read after the slot is reused */
185 if (slot->results != NULL) {
186 slot->results->curl_result = slot->curl_result;
187 slot->results->http_code = slot->http_code;
188 #if LIBCURL_VERSION_NUM >= 0x070a08
189 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
190 &slot->results->auth_avail);
192 slot->results->auth_avail = 0;
195 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
196 &slot->results->http_connectcode);
199 /* Run callback if appropriate */
200 if (slot->callback_func != NULL)
201 slot->callback_func(slot->callback_data);
204 #ifdef USE_CURL_MULTI
205 static void process_curl_messages(void)
208 struct active_request_slot *slot;
209 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
211 while (curl_message != NULL) {
212 if (curl_message->msg == CURLMSG_DONE) {
213 int curl_result = curl_message->data.result;
214 slot = active_queue_head;
215 while (slot != NULL &&
216 slot->curl != curl_message->easy_handle)
219 curl_multi_remove_handle(curlm, slot->curl);
220 slot->curl_result = curl_result;
221 finish_active_slot(slot);
223 fprintf(stderr, "Received DONE message for unknown request!\n");
226 fprintf(stderr, "Unknown CURL message received: %d\n",
227 (int)curl_message->msg);
229 curl_message = curl_multi_info_read(curlm, &num_messages);
234 static int http_options(const char *var, const char *value, void *cb)
236 if (!strcmp("http.sslverify", var)) {
237 curl_ssl_verify = git_config_bool(var, value);
240 if (!strcmp("http.sslcipherlist", var))
241 return git_config_string(&ssl_cipherlist, var, value);
242 if (!strcmp("http.sslversion", var))
243 return git_config_string(&ssl_version, var, value);
244 if (!strcmp("http.sslcert", var))
245 return git_config_string(&ssl_cert, var, value);
246 #if LIBCURL_VERSION_NUM >= 0x070903
247 if (!strcmp("http.sslkey", var))
248 return git_config_string(&ssl_key, var, value);
250 #if LIBCURL_VERSION_NUM >= 0x070908
251 if (!strcmp("http.sslcapath", var))
252 return git_config_pathname(&ssl_capath, var, value);
254 if (!strcmp("http.sslcainfo", var))
255 return git_config_pathname(&ssl_cainfo, var, value);
256 if (!strcmp("http.sslcertpasswordprotected", var)) {
257 ssl_cert_password_required = git_config_bool(var, value);
260 if (!strcmp("http.ssltry", var)) {
261 curl_ssl_try = git_config_bool(var, value);
264 if (!strcmp("http.minsessions", var)) {
265 min_curl_sessions = git_config_int(var, value);
266 #ifndef USE_CURL_MULTI
267 if (min_curl_sessions > 1)
268 min_curl_sessions = 1;
272 #ifdef USE_CURL_MULTI
273 if (!strcmp("http.maxrequests", var)) {
274 max_requests = git_config_int(var, value);
278 if (!strcmp("http.lowspeedlimit", var)) {
279 curl_low_speed_limit = (long)git_config_int(var, value);
282 if (!strcmp("http.lowspeedtime", var)) {
283 curl_low_speed_time = (long)git_config_int(var, value);
287 if (!strcmp("http.noepsv", var)) {
288 curl_ftp_no_epsv = git_config_bool(var, value);
291 if (!strcmp("http.proxy", var))
292 return git_config_string(&curl_http_proxy, var, value);
294 if (!strcmp("http.proxyauthmethod", var))
295 return git_config_string(&http_proxy_authmethod, var, value);
297 if (!strcmp("http.cookiefile", var))
298 return git_config_pathname(&curl_cookie_file, var, value);
299 if (!strcmp("http.savecookies", var)) {
300 curl_save_cookies = git_config_bool(var, value);
304 if (!strcmp("http.postbuffer", var)) {
305 http_post_buffer = git_config_int(var, value);
306 if (http_post_buffer < LARGE_PACKET_MAX)
307 http_post_buffer = LARGE_PACKET_MAX;
311 if (!strcmp("http.useragent", var))
312 return git_config_string(&user_agent, var, value);
314 if (!strcmp("http.emptyauth", var)) {
315 curl_empty_auth = git_config_bool(var, value);
319 if (!strcmp("http.pinnedpubkey", var)) {
320 #if LIBCURL_VERSION_NUM >= 0x072c00
321 return git_config_pathname(&ssl_pinnedkey, var, value);
323 warning(_("Public key pinning not supported with cURL < 7.44.0"));
328 if (!strcmp("http.extraheader", var)) {
330 return config_error_nonbool(var);
331 } else if (!*value) {
332 curl_slist_free_all(extra_http_headers);
333 extra_http_headers = NULL;
336 curl_slist_append(extra_http_headers, value);
341 /* Fall back on the default ones */
342 return git_default_config(var, value, cb);
345 static void init_curl_http_auth(CURL *result)
347 if (!http_auth.username) {
349 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
353 credential_fill(&http_auth);
355 #if LIBCURL_VERSION_NUM >= 0x071301
356 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
357 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
360 static struct strbuf up = STRBUF_INIT;
362 * Note that we assume we only ever have a single set of
363 * credentials in a given program run, so we do not have
364 * to worry about updating this buffer, only setting its
368 strbuf_addf(&up, "%s:%s",
369 http_auth.username, http_auth.password);
370 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
375 /* *var must be free-able */
376 static void var_override(const char **var, char *value)
380 *var = xstrdup(value);
384 static void set_proxyauth_name_password(CURL *result)
386 #if LIBCURL_VERSION_NUM >= 0x071301
387 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
388 proxy_auth.username);
389 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
390 proxy_auth.password);
392 struct strbuf s = STRBUF_INIT;
394 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
395 strbuf_addch(&s, ':');
396 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
397 curl_proxyuserpwd = strbuf_detach(&s, NULL);
398 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
402 static void init_curl_proxy_auth(CURL *result)
404 if (proxy_auth.username) {
405 if (!proxy_auth.password)
406 credential_fill(&proxy_auth);
407 set_proxyauth_name_password(result);
410 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
412 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
413 if (http_proxy_authmethod) {
415 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
416 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
417 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
418 proxy_authmethods[i].curlauth_param);
422 if (i == ARRAY_SIZE(proxy_authmethods)) {
423 warning("unsupported proxy authentication method %s: using anyauth",
424 http_proxy_authmethod);
425 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
429 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
433 static int has_cert_password(void)
435 if (ssl_cert == NULL || ssl_cert_password_required != 1)
437 if (!cert_auth.password) {
438 cert_auth.protocol = xstrdup("cert");
439 cert_auth.username = xstrdup("");
440 cert_auth.path = xstrdup(ssl_cert);
441 credential_fill(&cert_auth);
446 #if LIBCURL_VERSION_NUM >= 0x071900
447 static void set_curl_keepalive(CURL *c)
449 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
452 #elif LIBCURL_VERSION_NUM >= 0x071000
453 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
457 socklen_t len = (socklen_t)sizeof(ka);
459 if (type != CURLSOCKTYPE_IPCXN)
462 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
464 warning_errno("unable to set SO_KEEPALIVE on socket");
466 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
469 static void set_curl_keepalive(CURL *c)
471 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
475 static void set_curl_keepalive(CURL *c)
477 /* not supported on older curl versions */
481 static void redact_sensitive_header(struct strbuf *header)
483 const char *sensitive_header;
485 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
486 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
487 /* The first token is the type, which is OK to log */
488 while (isspace(*sensitive_header))
490 while (*sensitive_header && !isspace(*sensitive_header))
492 /* Everything else is opaque and possibly sensitive */
493 strbuf_setlen(header, sensitive_header - header->buf);
494 strbuf_addstr(header, " <redacted>");
498 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
500 struct strbuf out = STRBUF_INIT;
501 struct strbuf **headers, **header;
503 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
504 text, (long)size, (long)size);
505 trace_strbuf(&trace_curl, &out);
507 strbuf_add(&out, ptr, size);
508 headers = strbuf_split_max(&out, '\n', 0);
510 for (header = headers; *header; header++) {
511 if (hide_sensitive_header)
512 redact_sensitive_header(*header);
513 strbuf_insert((*header), 0, text, strlen(text));
514 strbuf_insert((*header), strlen(text), ": ", 2);
515 strbuf_rtrim((*header));
516 strbuf_addch((*header), '\n');
517 trace_strbuf(&trace_curl, (*header));
519 strbuf_list_free(headers);
520 strbuf_release(&out);
523 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
526 struct strbuf out = STRBUF_INIT;
527 unsigned int width = 60;
529 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
530 text, (long)size, (long)size);
531 trace_strbuf(&trace_curl, &out);
533 for (i = 0; i < size; i += width) {
537 strbuf_addf(&out, "%s: ", text);
538 for (w = 0; (w < width) && (i + w < size); w++) {
539 unsigned char ch = ptr[i + w];
542 (ch >= 0x20) && (ch < 0x80)
545 strbuf_addch(&out, '\n');
546 trace_strbuf(&trace_curl, &out);
548 strbuf_release(&out);
551 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
554 enum { NO_FILTER = 0, DO_FILTER = 1 };
558 trace_printf_key(&trace_curl, "== Info: %s", data);
559 default: /* we ignore unknown types by default */
562 case CURLINFO_HEADER_OUT:
563 text = "=> Send header";
564 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
566 case CURLINFO_DATA_OUT:
567 text = "=> Send data";
568 curl_dump_data(text, (unsigned char *)data, size);
570 case CURLINFO_SSL_DATA_OUT:
571 text = "=> Send SSL data";
572 curl_dump_data(text, (unsigned char *)data, size);
574 case CURLINFO_HEADER_IN:
575 text = "<= Recv header";
576 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
578 case CURLINFO_DATA_IN:
579 text = "<= Recv data";
580 curl_dump_data(text, (unsigned char *)data, size);
582 case CURLINFO_SSL_DATA_IN:
583 text = "<= Recv SSL data";
584 curl_dump_data(text, (unsigned char *)data, size);
590 void setup_curl_trace(CURL *handle)
592 if (!trace_want(&trace_curl))
594 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
595 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
596 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
600 static CURL *get_curl_handle(void)
602 CURL *result = curl_easy_init();
603 long allowed_protocols = 0;
606 die("curl_easy_init failed");
608 if (!curl_ssl_verify) {
609 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
610 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
612 /* Verify authenticity of the peer's certificate */
613 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
614 /* The name in the cert must match whom we tried to connect */
615 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
618 #if LIBCURL_VERSION_NUM >= 0x070907
619 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
621 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
622 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
625 if (http_proactive_auth)
626 init_curl_http_auth(result);
628 if (getenv("GIT_SSL_VERSION"))
629 ssl_version = getenv("GIT_SSL_VERSION");
630 if (ssl_version && *ssl_version) {
632 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
633 if (!strcmp(ssl_version, sslversions[i].name)) {
634 curl_easy_setopt(result, CURLOPT_SSLVERSION,
635 sslversions[i].ssl_version);
639 if (i == ARRAY_SIZE(sslversions))
640 warning("unsupported ssl version %s: using default",
644 if (getenv("GIT_SSL_CIPHER_LIST"))
645 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
646 if (ssl_cipherlist != NULL && *ssl_cipherlist)
647 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
650 if (ssl_cert != NULL)
651 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
652 if (has_cert_password())
653 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
654 #if LIBCURL_VERSION_NUM >= 0x070903
656 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
658 #if LIBCURL_VERSION_NUM >= 0x070908
659 if (ssl_capath != NULL)
660 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
662 #if LIBCURL_VERSION_NUM >= 0x072c00
663 if (ssl_pinnedkey != NULL)
664 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
666 if (ssl_cainfo != NULL)
667 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
669 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
670 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
671 curl_low_speed_limit);
672 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
673 curl_low_speed_time);
676 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
677 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
678 #if LIBCURL_VERSION_NUM >= 0x071301
679 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
680 #elif LIBCURL_VERSION_NUM >= 0x071101
681 curl_easy_setopt(result, CURLOPT_POST301, 1);
683 #if LIBCURL_VERSION_NUM >= 0x071304
684 if (is_transport_allowed("http"))
685 allowed_protocols |= CURLPROTO_HTTP;
686 if (is_transport_allowed("https"))
687 allowed_protocols |= CURLPROTO_HTTPS;
688 if (is_transport_allowed("ftp"))
689 allowed_protocols |= CURLPROTO_FTP;
690 if (is_transport_allowed("ftps"))
691 allowed_protocols |= CURLPROTO_FTPS;
692 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
694 if (transport_restrict_protocols())
695 warning("protocol restrictions not applied to curl redirects because\n"
696 "your curl version is too old (>= 7.19.4)");
698 if (getenv("GIT_CURL_VERBOSE"))
699 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
700 setup_curl_trace(result);
702 curl_easy_setopt(result, CURLOPT_USERAGENT,
703 user_agent ? user_agent : git_user_agent());
705 if (curl_ftp_no_epsv)
706 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
708 #ifdef CURLOPT_USE_SSL
710 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
714 * CURL also examines these variables as a fallback; but we need to query
715 * them here in order to decide whether to prompt for missing password (cf.
716 * init_curl_proxy_auth()).
718 * Unlike many other common environment variables, these are historically
719 * lowercase only. It appears that CURL did not know this and implemented
720 * only uppercase variants, which was later corrected to take both - with
721 * the exception of http_proxy, which is lowercase only also in CURL. As
722 * the lowercase versions are the historical quasi-standard, they take
723 * precedence here, as in CURL.
725 if (!curl_http_proxy) {
726 if (!strcmp(http_auth.protocol, "https")) {
727 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
728 var_override(&curl_http_proxy, getenv("https_proxy"));
730 var_override(&curl_http_proxy, getenv("http_proxy"));
732 if (!curl_http_proxy) {
733 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
734 var_override(&curl_http_proxy, getenv("all_proxy"));
738 if (curl_http_proxy) {
739 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
740 #if LIBCURL_VERSION_NUM >= 0x071800
741 if (starts_with(curl_http_proxy, "socks5h"))
742 curl_easy_setopt(result,
743 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
744 else if (starts_with(curl_http_proxy, "socks5"))
745 curl_easy_setopt(result,
746 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
747 else if (starts_with(curl_http_proxy, "socks4a"))
748 curl_easy_setopt(result,
749 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
750 else if (starts_with(curl_http_proxy, "socks"))
751 curl_easy_setopt(result,
752 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
754 if (strstr(curl_http_proxy, "://"))
755 credential_from_url(&proxy_auth, curl_http_proxy);
757 struct strbuf url = STRBUF_INIT;
758 strbuf_addf(&url, "http://%s", curl_http_proxy);
759 credential_from_url(&proxy_auth, url.buf);
760 strbuf_release(&url);
763 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
764 #if LIBCURL_VERSION_NUM >= 0x071304
765 var_override(&curl_no_proxy, getenv("NO_PROXY"));
766 var_override(&curl_no_proxy, getenv("no_proxy"));
767 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
770 init_curl_proxy_auth(result);
772 set_curl_keepalive(result);
777 static void set_from_env(const char **var, const char *envname)
779 const char *val = getenv(envname);
784 void http_init(struct remote *remote, const char *url, int proactive_auth)
786 char *low_speed_limit;
787 char *low_speed_time;
788 char *normalized_url;
789 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
791 config.section = "http";
793 config.collect_fn = http_options;
794 config.cascade_fn = git_default_config;
798 normalized_url = url_normalize(url, &config.url);
800 git_config(urlmatch_config_entry, &config);
801 free(normalized_url);
803 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
804 die("curl_global_init failed");
806 http_proactive_auth = proactive_auth;
808 if (remote && remote->http_proxy)
809 curl_http_proxy = xstrdup(remote->http_proxy);
812 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
814 pragma_header = curl_slist_append(http_copy_default_headers(),
816 no_pragma_header = curl_slist_append(http_copy_default_headers(),
819 #ifdef USE_CURL_MULTI
821 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
822 if (http_max_requests != NULL)
823 max_requests = atoi(http_max_requests);
826 curlm = curl_multi_init();
828 die("curl_multi_init failed");
831 if (getenv("GIT_SSL_NO_VERIFY"))
834 set_from_env(&ssl_cert, "GIT_SSL_CERT");
835 #if LIBCURL_VERSION_NUM >= 0x070903
836 set_from_env(&ssl_key, "GIT_SSL_KEY");
838 #if LIBCURL_VERSION_NUM >= 0x070908
839 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
841 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
843 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
845 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
846 if (low_speed_limit != NULL)
847 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
848 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
849 if (low_speed_time != NULL)
850 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
852 if (curl_ssl_verify == -1)
855 curl_session_count = 0;
856 #ifdef USE_CURL_MULTI
857 if (max_requests < 1)
858 max_requests = DEFAULT_MAX_REQUESTS;
861 if (getenv("GIT_CURL_FTP_NO_EPSV"))
862 curl_ftp_no_epsv = 1;
865 credential_from_url(&http_auth, url);
866 if (!ssl_cert_password_required &&
867 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
868 starts_with(url, "https://"))
869 ssl_cert_password_required = 1;
872 #ifndef NO_CURL_EASY_DUPHANDLE
873 curl_default = get_curl_handle();
877 void http_cleanup(void)
879 struct active_request_slot *slot = active_queue_head;
881 while (slot != NULL) {
882 struct active_request_slot *next = slot->next;
883 if (slot->curl != NULL) {
884 #ifdef USE_CURL_MULTI
885 curl_multi_remove_handle(curlm, slot->curl);
887 curl_easy_cleanup(slot->curl);
892 active_queue_head = NULL;
894 #ifndef NO_CURL_EASY_DUPHANDLE
895 curl_easy_cleanup(curl_default);
898 #ifdef USE_CURL_MULTI
899 curl_multi_cleanup(curlm);
901 curl_global_cleanup();
903 curl_slist_free_all(extra_http_headers);
904 extra_http_headers = NULL;
906 curl_slist_free_all(pragma_header);
907 pragma_header = NULL;
909 curl_slist_free_all(no_pragma_header);
910 no_pragma_header = NULL;
912 if (curl_http_proxy) {
913 free((void *)curl_http_proxy);
914 curl_http_proxy = NULL;
917 if (proxy_auth.password) {
918 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
919 free(proxy_auth.password);
920 proxy_auth.password = NULL;
923 free((void *)curl_proxyuserpwd);
924 curl_proxyuserpwd = NULL;
926 free((void *)http_proxy_authmethod);
927 http_proxy_authmethod = NULL;
929 if (cert_auth.password != NULL) {
930 memset(cert_auth.password, 0, strlen(cert_auth.password));
931 free(cert_auth.password);
932 cert_auth.password = NULL;
934 ssl_cert_password_required = 0;
936 free(cached_accept_language);
937 cached_accept_language = NULL;
940 struct active_request_slot *get_active_slot(void)
942 struct active_request_slot *slot = active_queue_head;
943 struct active_request_slot *newslot;
945 #ifdef USE_CURL_MULTI
948 /* Wait for a slot to open up if the queue is full */
949 while (active_requests >= max_requests) {
950 curl_multi_perform(curlm, &num_transfers);
951 if (num_transfers < active_requests)
952 process_curl_messages();
956 while (slot != NULL && slot->in_use)
960 newslot = xmalloc(sizeof(*newslot));
961 newslot->curl = NULL;
963 newslot->next = NULL;
965 slot = active_queue_head;
967 active_queue_head = newslot;
969 while (slot->next != NULL)
971 slot->next = newslot;
976 if (slot->curl == NULL) {
977 #ifdef NO_CURL_EASY_DUPHANDLE
978 slot->curl = get_curl_handle();
980 slot->curl = curl_easy_duphandle(curl_default);
982 curl_session_count++;
987 slot->results = NULL;
988 slot->finished = NULL;
989 slot->callback_data = NULL;
990 slot->callback_func = NULL;
991 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
992 if (curl_save_cookies)
993 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
994 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
995 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
996 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
997 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
998 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
999 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1000 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1001 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1002 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1003 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1005 #if LIBCURL_VERSION_NUM >= 0x070a08
1006 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1008 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1009 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1011 if (http_auth.password || curl_empty_auth)
1012 init_curl_http_auth(slot->curl);
1017 int start_active_slot(struct active_request_slot *slot)
1019 #ifdef USE_CURL_MULTI
1020 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1023 if (curlm_result != CURLM_OK &&
1024 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1031 * We know there must be something to do, since we just added
1034 curl_multi_perform(curlm, &num_transfers);
1039 #ifdef USE_CURL_MULTI
1042 int (*fill)(void *);
1043 struct fill_chain *next;
1046 static struct fill_chain *fill_cfg;
1048 void add_fill_function(void *data, int (*fill)(void *))
1050 struct fill_chain *new = xmalloc(sizeof(*new));
1051 struct fill_chain **linkp = &fill_cfg;
1056 linkp = &(*linkp)->next;
1060 void fill_active_slots(void)
1062 struct active_request_slot *slot = active_queue_head;
1064 while (active_requests < max_requests) {
1065 struct fill_chain *fill;
1066 for (fill = fill_cfg; fill; fill = fill->next)
1067 if (fill->fill(fill->data))
1074 while (slot != NULL) {
1075 if (!slot->in_use && slot->curl != NULL
1076 && curl_session_count > min_curl_sessions) {
1077 curl_easy_cleanup(slot->curl);
1079 curl_session_count--;
1085 void step_active_slots(void)
1088 CURLMcode curlm_result;
1091 curlm_result = curl_multi_perform(curlm, &num_transfers);
1092 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1093 if (num_transfers < active_requests) {
1094 process_curl_messages();
1095 fill_active_slots();
1100 void run_active_slot(struct active_request_slot *slot)
1102 #ifdef USE_CURL_MULTI
1107 struct timeval select_timeout;
1110 slot->finished = &finished;
1112 step_active_slots();
1115 #if LIBCURL_VERSION_NUM >= 0x070f04
1117 curl_multi_timeout(curlm, &curl_timeout);
1118 if (curl_timeout == 0) {
1120 } else if (curl_timeout == -1) {
1121 select_timeout.tv_sec = 0;
1122 select_timeout.tv_usec = 50000;
1124 select_timeout.tv_sec = curl_timeout / 1000;
1125 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1128 select_timeout.tv_sec = 0;
1129 select_timeout.tv_usec = 50000;
1136 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1139 * It can happen that curl_multi_timeout returns a pathologically
1140 * long timeout when curl_multi_fdset returns no file descriptors
1141 * to read. See commit message for more details.
1144 (select_timeout.tv_sec > 0 ||
1145 select_timeout.tv_usec > 50000)) {
1146 select_timeout.tv_sec = 0;
1147 select_timeout.tv_usec = 50000;
1150 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1154 while (slot->in_use) {
1155 slot->curl_result = curl_easy_perform(slot->curl);
1156 finish_active_slot(slot);
1161 static void release_active_slot(struct active_request_slot *slot)
1163 closedown_active_slot(slot);
1164 if (slot->curl && curl_session_count > min_curl_sessions) {
1165 #ifdef USE_CURL_MULTI
1166 curl_multi_remove_handle(curlm, slot->curl);
1168 curl_easy_cleanup(slot->curl);
1170 curl_session_count--;
1172 #ifdef USE_CURL_MULTI
1173 fill_active_slots();
1177 void finish_all_active_slots(void)
1179 struct active_request_slot *slot = active_queue_head;
1181 while (slot != NULL)
1183 run_active_slot(slot);
1184 slot = active_queue_head;
1190 /* Helpers for modifying and creating URLs */
1191 static inline int needs_quote(int ch)
1193 if (((ch >= 'A') && (ch <= 'Z'))
1194 || ((ch >= 'a') && (ch <= 'z'))
1195 || ((ch >= '0') && (ch <= '9'))
1203 static char *quote_ref_url(const char *base, const char *ref)
1205 struct strbuf buf = STRBUF_INIT;
1209 end_url_with_slash(&buf, base);
1211 for (cp = ref; (ch = *cp) != 0; cp++)
1212 if (needs_quote(ch))
1213 strbuf_addf(&buf, "%%%02x", ch);
1215 strbuf_addch(&buf, *cp);
1217 return strbuf_detach(&buf, NULL);
1220 void append_remote_object_url(struct strbuf *buf, const char *url,
1222 int only_two_digit_prefix)
1224 end_url_with_slash(buf, url);
1226 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1227 if (!only_two_digit_prefix)
1228 strbuf_addf(buf, "%s", hex+2);
1231 char *get_remote_object_url(const char *url, const char *hex,
1232 int only_two_digit_prefix)
1234 struct strbuf buf = STRBUF_INIT;
1235 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1236 return strbuf_detach(&buf, NULL);
1239 static int handle_curl_result(struct slot_results *results)
1242 * If we see a failing http code with CURLE_OK, we have turned off
1243 * FAILONERROR (to keep the server's custom error response), and should
1244 * translate the code into failure here.
1246 if (results->curl_result == CURLE_OK &&
1247 results->http_code >= 400) {
1248 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1250 * Normally curl will already have put the "reason phrase"
1251 * from the server into curl_errorstr; unfortunately without
1252 * FAILONERROR it is lost, so we can give only the numeric
1255 snprintf(curl_errorstr, sizeof(curl_errorstr),
1256 "The requested URL returned error: %ld",
1257 results->http_code);
1260 if (results->curl_result == CURLE_OK) {
1261 credential_approve(&http_auth);
1262 if (proxy_auth.password)
1263 credential_approve(&proxy_auth);
1265 } else if (missing_target(results))
1266 return HTTP_MISSING_TARGET;
1267 else if (results->http_code == 401) {
1268 if (http_auth.username && http_auth.password) {
1269 credential_reject(&http_auth);
1272 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1273 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1278 if (results->http_connectcode == 407)
1279 credential_reject(&proxy_auth);
1280 #if LIBCURL_VERSION_NUM >= 0x070c00
1281 if (!curl_errorstr[0])
1282 strlcpy(curl_errorstr,
1283 curl_easy_strerror(results->curl_result),
1284 sizeof(curl_errorstr));
1290 int run_one_slot(struct active_request_slot *slot,
1291 struct slot_results *results)
1293 slot->results = results;
1294 if (!start_active_slot(slot)) {
1295 snprintf(curl_errorstr, sizeof(curl_errorstr),
1296 "failed to start HTTP request");
1297 return HTTP_START_FAILED;
1300 run_active_slot(slot);
1301 return handle_curl_result(results);
1304 struct curl_slist *http_copy_default_headers(void)
1306 struct curl_slist *headers = NULL, *h;
1308 for (h = extra_http_headers; h; h = h->next)
1309 headers = curl_slist_append(headers, h->data);
1314 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1320 ret = curl_easy_getinfo(curl, info, &ptr);
1322 strbuf_addstr(buf, ptr);
1327 * Check for and extract a content-type parameter. "raw"
1328 * should be positioned at the start of the potential
1329 * parameter, with any whitespace already removed.
1331 * "name" is the name of the parameter. The value is appended
1334 static int extract_param(const char *raw, const char *name,
1337 size_t len = strlen(name);
1339 if (strncasecmp(raw, name, len))
1347 while (*raw && !isspace(*raw) && *raw != ';')
1348 strbuf_addch(out, *raw++);
1353 * Extract a normalized version of the content type, with any
1354 * spaces suppressed, all letters lowercased, and no trailing ";"
1357 * Note that we will silently remove even invalid whitespace. For
1358 * example, "text / plain" is specifically forbidden by RFC 2616,
1359 * but "text/plain" is the only reasonable output, and this keeps
1362 * If the "charset" argument is not NULL, store the value of any
1363 * charset parameter there.
1366 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1367 * "text / plain" -> "text/plain"
1369 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1370 struct strbuf *charset)
1375 strbuf_grow(type, raw->len);
1376 for (p = raw->buf; *p; p++) {
1383 strbuf_addch(type, tolower(*p));
1389 strbuf_reset(charset);
1391 while (isspace(*p) || *p == ';')
1393 if (!extract_param(p, "charset", charset))
1395 while (*p && !isspace(*p))
1399 if (!charset->len && starts_with(type->buf, "text/"))
1400 strbuf_addstr(charset, "ISO-8859-1");
1403 static void write_accept_language(struct strbuf *buf)
1406 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1407 * that, q-value will be smaller than 0.001, the minimum q-value the
1408 * HTTP specification allows. See
1409 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1411 const int MAX_DECIMAL_PLACES = 3;
1412 const int MAX_LANGUAGE_TAGS = 1000;
1413 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1414 char **language_tags = NULL;
1416 const char *s = get_preferred_languages();
1418 struct strbuf tag = STRBUF_INIT;
1420 /* Don't add Accept-Language header if no language is preferred. */
1425 * Split the colon-separated string of preferred languages into
1426 * language_tags array.
1429 /* collect language tag */
1430 for (; *s && (isalnum(*s) || *s == '_'); s++)
1431 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1433 /* skip .codeset, @modifier and any other unnecessary parts */
1434 while (*s && *s != ':')
1439 REALLOC_ARRAY(language_tags, num_langs);
1440 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1441 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1446 /* write Accept-Language header into buf */
1448 int last_buf_len = 0;
1454 REALLOC_ARRAY(language_tags, num_langs + 1);
1455 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1457 /* compute decimal_places */
1458 for (max_q = 1, decimal_places = 0;
1459 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1460 decimal_places++, max_q *= 10)
1463 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1465 strbuf_addstr(buf, "Accept-Language: ");
1467 for (i = 0; i < num_langs; i++) {
1469 strbuf_addstr(buf, ", ");
1471 strbuf_addstr(buf, language_tags[i]);
1474 strbuf_addf(buf, q_format, max_q - i);
1476 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1477 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1481 last_buf_len = buf->len;
1485 /* free language tags -- last one is a static '*' */
1486 for (i = 0; i < num_langs - 1; i++)
1487 free(language_tags[i]);
1488 free(language_tags);
1492 * Get an Accept-Language header which indicates user's preferred languages.
1496 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1497 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1498 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1499 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1500 * LANGUAGE= LANG=C -> ""
1502 static const char *get_accept_language(void)
1504 if (!cached_accept_language) {
1505 struct strbuf buf = STRBUF_INIT;
1506 write_accept_language(&buf);
1508 cached_accept_language = strbuf_detach(&buf, NULL);
1511 return cached_accept_language;
1514 static void http_opt_request_remainder(CURL *curl, off_t pos)
1517 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1518 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1521 /* http_request() targets */
1522 #define HTTP_REQUEST_STRBUF 0
1523 #define HTTP_REQUEST_FILE 1
1525 static int http_request(const char *url,
1526 void *result, int target,
1527 const struct http_get_options *options)
1529 struct active_request_slot *slot;
1530 struct slot_results results;
1531 struct curl_slist *headers = http_copy_default_headers();
1532 struct strbuf buf = STRBUF_INIT;
1533 const char *accept_language;
1536 slot = get_active_slot();
1537 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1539 if (result == NULL) {
1540 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1542 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1543 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1545 if (target == HTTP_REQUEST_FILE) {
1546 off_t posn = ftello(result);
1547 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1550 http_opt_request_remainder(slot->curl, posn);
1552 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1556 accept_language = get_accept_language();
1558 if (accept_language)
1559 headers = curl_slist_append(headers, accept_language);
1561 strbuf_addstr(&buf, "Pragma:");
1562 if (options && options->no_cache)
1563 strbuf_addstr(&buf, " no-cache");
1564 if (options && options->keep_error)
1565 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1567 headers = curl_slist_append(headers, buf.buf);
1569 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1570 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1571 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1573 ret = run_one_slot(slot, &results);
1575 if (options && options->content_type) {
1576 struct strbuf raw = STRBUF_INIT;
1577 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1578 extract_content_type(&raw, options->content_type,
1580 strbuf_release(&raw);
1583 if (options && options->effective_url)
1584 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1585 options->effective_url);
1587 curl_slist_free_all(headers);
1588 strbuf_release(&buf);
1594 * Update the "base" url to a more appropriate value, as deduced by
1595 * redirects seen when requesting a URL starting with "url".
1597 * The "asked" parameter is a URL that we asked curl to access, and must begin
1600 * The "got" parameter is the URL that curl reported to us as where we ended
1603 * Returns 1 if we updated the base url, 0 otherwise.
1605 * Our basic strategy is to compare "base" and "asked" to find the bits
1606 * specific to our request. We then strip those bits off of "got" to yield the
1607 * new base. So for example, if our base is "http://example.com/foo.git",
1608 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1609 * with "https://other.example.com/foo.git/info/refs". We would want the
1610 * new URL to become "https://other.example.com/foo.git".
1612 * Note that this assumes a sane redirect scheme. It's entirely possible
1613 * in the example above to end up at a URL that does not even end in
1614 * "info/refs". In such a case we simply punt, as there is not much we can
1615 * do (and such a scheme is unlikely to represent a real git repository,
1616 * which means we are likely about to abort anyway).
1618 static int update_url_from_redirect(struct strbuf *base,
1620 const struct strbuf *got)
1625 if (!strcmp(asked, got->buf))
1628 if (!skip_prefix(asked, base->buf, &tail))
1629 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1632 tail_len = strlen(tail);
1634 if (got->len < tail_len ||
1635 strcmp(tail, got->buf + got->len - tail_len))
1636 return 0; /* insane redirect scheme */
1639 strbuf_add(base, got->buf, got->len - tail_len);
1643 static int http_request_reauth(const char *url,
1644 void *result, int target,
1645 struct http_get_options *options)
1647 int ret = http_request(url, result, target, options);
1649 if (options && options->effective_url && options->base_url) {
1650 if (update_url_from_redirect(options->base_url,
1651 url, options->effective_url)) {
1652 credential_from_url(&http_auth, options->base_url->buf);
1653 url = options->effective_url->buf;
1657 if (ret != HTTP_REAUTH)
1661 * If we are using KEEP_ERROR, the previous request may have
1662 * put cruft into our output stream; we should clear it out before
1663 * making our next request. We only know how to do this for
1664 * the strbuf case, but that is enough to satisfy current callers.
1666 if (options && options->keep_error) {
1668 case HTTP_REQUEST_STRBUF:
1669 strbuf_reset(result);
1672 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1676 credential_fill(&http_auth);
1678 return http_request(url, result, target, options);
1681 int http_get_strbuf(const char *url,
1682 struct strbuf *result,
1683 struct http_get_options *options)
1685 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1689 * Downloads a URL and stores the result in the given file.
1691 * If a previous interrupted download is detected (i.e. a previous temporary
1692 * file is still around) the download is resumed.
1694 static int http_get_file(const char *url, const char *filename,
1695 struct http_get_options *options)
1698 struct strbuf tmpfile = STRBUF_INIT;
1701 strbuf_addf(&tmpfile, "%s.temp", filename);
1702 result = fopen(tmpfile.buf, "a");
1704 error("Unable to open local file %s", tmpfile.buf);
1709 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1712 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1715 strbuf_release(&tmpfile);
1719 int http_fetch_ref(const char *base, struct ref *ref)
1721 struct http_get_options options = {0};
1723 struct strbuf buffer = STRBUF_INIT;
1726 options.no_cache = 1;
1728 url = quote_ref_url(base, ref->name);
1729 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1730 strbuf_rtrim(&buffer);
1731 if (buffer.len == 40)
1732 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1733 else if (starts_with(buffer.buf, "ref: ")) {
1734 ref->symref = xstrdup(buffer.buf + 5);
1739 strbuf_release(&buffer);
1744 /* Helpers for fetching packs */
1745 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1748 struct strbuf buf = STRBUF_INIT;
1750 if (http_is_verbose)
1751 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1753 end_url_with_slash(&buf, base_url);
1754 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1755 url = strbuf_detach(&buf, NULL);
1757 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1758 tmp = strbuf_detach(&buf, NULL);
1760 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1761 error("Unable to get pack index %s", url);
1770 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1771 unsigned char *sha1, const char *base_url)
1773 struct packed_git *new_pack;
1774 char *tmp_idx = NULL;
1777 if (has_pack_index(sha1)) {
1778 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1780 return -1; /* parse_pack_index() already issued error message */
1784 tmp_idx = fetch_pack_index(sha1, base_url);
1788 new_pack = parse_pack_index(sha1, tmp_idx);
1793 return -1; /* parse_pack_index() already issued error message */
1796 ret = verify_pack_index(new_pack);
1798 close_pack_index(new_pack);
1799 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1806 new_pack->next = *packs_head;
1807 *packs_head = new_pack;
1811 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1813 struct http_get_options options = {0};
1816 struct strbuf buf = STRBUF_INIT;
1817 unsigned char sha1[20];
1819 end_url_with_slash(&buf, base_url);
1820 strbuf_addstr(&buf, "objects/info/packs");
1821 url = strbuf_detach(&buf, NULL);
1823 options.no_cache = 1;
1824 ret = http_get_strbuf(url, &buf, &options);
1829 while (i < buf.len) {
1833 if (i + 52 <= buf.len &&
1834 starts_with(data + i, " pack-") &&
1835 starts_with(data + i + 46, ".pack\n")) {
1836 get_sha1_hex(data + i + 6, sha1);
1837 fetch_and_setup_pack_index(packs_head, sha1,
1843 while (i < buf.len && data[i] != '\n')
1854 void release_http_pack_request(struct http_pack_request *preq)
1856 if (preq->packfile != NULL) {
1857 fclose(preq->packfile);
1858 preq->packfile = NULL;
1865 int finish_http_pack_request(struct http_pack_request *preq)
1867 struct packed_git **lst;
1868 struct packed_git *p = preq->target;
1871 struct child_process ip = CHILD_PROCESS_INIT;
1872 const char *ip_argv[8];
1874 close_pack_index(p);
1876 fclose(preq->packfile);
1877 preq->packfile = NULL;
1881 lst = &((*lst)->next);
1882 *lst = (*lst)->next;
1884 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1885 die("BUG: pack tmpfile does not end in .pack.temp?");
1886 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1888 ip_argv[0] = "index-pack";
1890 ip_argv[2] = tmp_idx;
1891 ip_argv[3] = preq->tmpfile;
1899 if (run_command(&ip)) {
1900 unlink(preq->tmpfile);
1906 unlink(sha1_pack_index_name(p->sha1));
1908 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1909 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1914 install_packed_git(p);
1919 struct http_pack_request *new_http_pack_request(
1920 struct packed_git *target, const char *base_url)
1922 off_t prev_posn = 0;
1923 struct strbuf buf = STRBUF_INIT;
1924 struct http_pack_request *preq;
1926 preq = xcalloc(1, sizeof(*preq));
1927 preq->target = target;
1929 end_url_with_slash(&buf, base_url);
1930 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1931 sha1_to_hex(target->sha1));
1932 preq->url = strbuf_detach(&buf, NULL);
1934 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1935 sha1_pack_name(target->sha1));
1936 preq->packfile = fopen(preq->tmpfile, "a");
1937 if (!preq->packfile) {
1938 error("Unable to open local file %s for pack",
1943 preq->slot = get_active_slot();
1944 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1945 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1946 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1947 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1951 * If there is data present from a previous transfer attempt,
1952 * resume where it left off
1954 prev_posn = ftello(preq->packfile);
1956 if (http_is_verbose)
1958 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1959 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1960 http_opt_request_remainder(preq->slot->curl, prev_posn);
1971 /* Helpers for fetching objects (loose) */
1972 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1975 unsigned char expn[4096];
1976 size_t size = eltsize * nmemb;
1978 struct http_object_request *freq = data;
1979 struct active_request_slot *slot = freq->slot;
1982 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
1985 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
1986 curl_easy_strerror(c));
1987 if (slot->http_code >= 400)
1992 ssize_t retval = xwrite(freq->localfile,
1993 (char *) ptr + posn, size - posn);
1997 } while (posn < size);
1999 freq->stream.avail_in = size;
2000 freq->stream.next_in = (void *)ptr;
2002 freq->stream.next_out = expn;
2003 freq->stream.avail_out = sizeof(expn);
2004 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2005 git_SHA1_Update(&freq->c, expn,
2006 sizeof(expn) - freq->stream.avail_out);
2007 } while (freq->stream.avail_in && freq->zret == Z_OK);
2011 struct http_object_request *new_http_object_request(const char *base_url,
2012 unsigned char *sha1)
2014 char *hex = sha1_to_hex(sha1);
2015 const char *filename;
2016 char prevfile[PATH_MAX];
2018 char prev_buf[PREV_BUF_SIZE];
2019 ssize_t prev_read = 0;
2020 off_t prev_posn = 0;
2021 struct http_object_request *freq;
2023 freq = xcalloc(1, sizeof(*freq));
2024 hashcpy(freq->sha1, sha1);
2025 freq->localfile = -1;
2027 filename = sha1_file_name(sha1);
2028 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2029 "%s.temp", filename);
2031 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2032 unlink_or_warn(prevfile);
2033 rename(freq->tmpfile, prevfile);
2034 unlink_or_warn(freq->tmpfile);
2036 if (freq->localfile != -1)
2037 error("fd leakage in start: %d", freq->localfile);
2038 freq->localfile = open(freq->tmpfile,
2039 O_WRONLY | O_CREAT | O_EXCL, 0666);
2041 * This could have failed due to the "lazy directory creation";
2042 * try to mkdir the last path component.
2044 if (freq->localfile < 0 && errno == ENOENT) {
2045 char *dir = strrchr(freq->tmpfile, '/');
2048 mkdir(freq->tmpfile, 0777);
2051 freq->localfile = open(freq->tmpfile,
2052 O_WRONLY | O_CREAT | O_EXCL, 0666);
2055 if (freq->localfile < 0) {
2056 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2060 git_inflate_init(&freq->stream);
2062 git_SHA1_Init(&freq->c);
2064 freq->url = get_remote_object_url(base_url, hex, 0);
2067 * If a previous temp file is present, process what was already
2070 prevlocal = open(prevfile, O_RDONLY);
2071 if (prevlocal != -1) {
2073 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2075 if (fwrite_sha1_file(prev_buf,
2078 freq) == prev_read) {
2079 prev_posn += prev_read;
2084 } while (prev_read > 0);
2087 unlink_or_warn(prevfile);
2090 * Reset inflate/SHA1 if there was an error reading the previous temp
2091 * file; also rewind to the beginning of the local file.
2093 if (prev_read == -1) {
2094 memset(&freq->stream, 0, sizeof(freq->stream));
2095 git_inflate_init(&freq->stream);
2096 git_SHA1_Init(&freq->c);
2099 lseek(freq->localfile, 0, SEEK_SET);
2100 if (ftruncate(freq->localfile, 0) < 0) {
2101 error_errno("Couldn't truncate temporary file %s",
2108 freq->slot = get_active_slot();
2110 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2111 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2112 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2113 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2114 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2115 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2118 * If we have successfully processed data from a previous fetch
2119 * attempt, only fetch the data we don't already have.
2122 if (http_is_verbose)
2124 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2125 hex, (uintmax_t)prev_posn);
2126 http_opt_request_remainder(freq->slot->curl, prev_posn);
2137 void process_http_object_request(struct http_object_request *freq)
2139 if (freq->slot == NULL)
2141 freq->curl_result = freq->slot->curl_result;
2142 freq->http_code = freq->slot->http_code;
2146 int finish_http_object_request(struct http_object_request *freq)
2150 close(freq->localfile);
2151 freq->localfile = -1;
2153 process_http_object_request(freq);
2155 if (freq->http_code == 416) {
2156 warning("requested range invalid; we may already have all the data.");
2157 } else if (freq->curl_result != CURLE_OK) {
2158 if (stat(freq->tmpfile, &st) == 0)
2159 if (st.st_size == 0)
2160 unlink_or_warn(freq->tmpfile);
2164 git_inflate_end(&freq->stream);
2165 git_SHA1_Final(freq->real_sha1, &freq->c);
2166 if (freq->zret != Z_STREAM_END) {
2167 unlink_or_warn(freq->tmpfile);
2170 if (hashcmp(freq->sha1, freq->real_sha1)) {
2171 unlink_or_warn(freq->tmpfile);
2175 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2177 return freq->rename;
2180 void abort_http_object_request(struct http_object_request *freq)
2182 unlink_or_warn(freq->tmpfile);
2184 release_http_object_request(freq);
2187 void release_http_object_request(struct http_object_request *freq)
2189 if (freq->localfile != -1) {
2190 close(freq->localfile);
2191 freq->localfile = -1;
2193 if (freq->url != NULL) {
2197 if (freq->slot != NULL) {
2198 freq->slot->callback_func = NULL;
2199 freq->slot->callback_data = NULL;
2200 release_active_slot(freq->slot);