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 static void xmulti_remove_handle(struct active_request_slot *slot)
206 #ifdef USE_CURL_MULTI
207 curl_multi_remove_handle(curlm, slot->curl);
211 #ifdef USE_CURL_MULTI
212 static void process_curl_messages(void)
215 struct active_request_slot *slot;
216 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
218 while (curl_message != NULL) {
219 if (curl_message->msg == CURLMSG_DONE) {
220 int curl_result = curl_message->data.result;
221 slot = active_queue_head;
222 while (slot != NULL &&
223 slot->curl != curl_message->easy_handle)
226 xmulti_remove_handle(slot);
227 slot->curl_result = curl_result;
228 finish_active_slot(slot);
230 fprintf(stderr, "Received DONE message for unknown request!\n");
233 fprintf(stderr, "Unknown CURL message received: %d\n",
234 (int)curl_message->msg);
236 curl_message = curl_multi_info_read(curlm, &num_messages);
241 static int http_options(const char *var, const char *value, void *cb)
243 if (!strcmp("http.sslverify", var)) {
244 curl_ssl_verify = git_config_bool(var, value);
247 if (!strcmp("http.sslcipherlist", var))
248 return git_config_string(&ssl_cipherlist, var, value);
249 if (!strcmp("http.sslversion", var))
250 return git_config_string(&ssl_version, var, value);
251 if (!strcmp("http.sslcert", var))
252 return git_config_string(&ssl_cert, var, value);
253 #if LIBCURL_VERSION_NUM >= 0x070903
254 if (!strcmp("http.sslkey", var))
255 return git_config_string(&ssl_key, var, value);
257 #if LIBCURL_VERSION_NUM >= 0x070908
258 if (!strcmp("http.sslcapath", var))
259 return git_config_pathname(&ssl_capath, var, value);
261 if (!strcmp("http.sslcainfo", var))
262 return git_config_pathname(&ssl_cainfo, var, value);
263 if (!strcmp("http.sslcertpasswordprotected", var)) {
264 ssl_cert_password_required = git_config_bool(var, value);
267 if (!strcmp("http.ssltry", var)) {
268 curl_ssl_try = git_config_bool(var, value);
271 if (!strcmp("http.minsessions", var)) {
272 min_curl_sessions = git_config_int(var, value);
273 #ifndef USE_CURL_MULTI
274 if (min_curl_sessions > 1)
275 min_curl_sessions = 1;
279 #ifdef USE_CURL_MULTI
280 if (!strcmp("http.maxrequests", var)) {
281 max_requests = git_config_int(var, value);
285 if (!strcmp("http.lowspeedlimit", var)) {
286 curl_low_speed_limit = (long)git_config_int(var, value);
289 if (!strcmp("http.lowspeedtime", var)) {
290 curl_low_speed_time = (long)git_config_int(var, value);
294 if (!strcmp("http.noepsv", var)) {
295 curl_ftp_no_epsv = git_config_bool(var, value);
298 if (!strcmp("http.proxy", var))
299 return git_config_string(&curl_http_proxy, var, value);
301 if (!strcmp("http.proxyauthmethod", var))
302 return git_config_string(&http_proxy_authmethod, var, value);
304 if (!strcmp("http.cookiefile", var))
305 return git_config_pathname(&curl_cookie_file, var, value);
306 if (!strcmp("http.savecookies", var)) {
307 curl_save_cookies = git_config_bool(var, value);
311 if (!strcmp("http.postbuffer", var)) {
312 http_post_buffer = git_config_int(var, value);
313 if (http_post_buffer < LARGE_PACKET_MAX)
314 http_post_buffer = LARGE_PACKET_MAX;
318 if (!strcmp("http.useragent", var))
319 return git_config_string(&user_agent, var, value);
321 if (!strcmp("http.emptyauth", var)) {
322 curl_empty_auth = git_config_bool(var, value);
326 if (!strcmp("http.pinnedpubkey", var)) {
327 #if LIBCURL_VERSION_NUM >= 0x072c00
328 return git_config_pathname(&ssl_pinnedkey, var, value);
330 warning(_("Public key pinning not supported with cURL < 7.44.0"));
335 if (!strcmp("http.extraheader", var)) {
337 return config_error_nonbool(var);
338 } else if (!*value) {
339 curl_slist_free_all(extra_http_headers);
340 extra_http_headers = NULL;
343 curl_slist_append(extra_http_headers, value);
348 /* Fall back on the default ones */
349 return git_default_config(var, value, cb);
352 static void init_curl_http_auth(CURL *result)
354 if (!http_auth.username) {
356 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
360 credential_fill(&http_auth);
362 #if LIBCURL_VERSION_NUM >= 0x071301
363 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
364 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
367 static struct strbuf up = STRBUF_INIT;
369 * Note that we assume we only ever have a single set of
370 * credentials in a given program run, so we do not have
371 * to worry about updating this buffer, only setting its
375 strbuf_addf(&up, "%s:%s",
376 http_auth.username, http_auth.password);
377 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
382 /* *var must be free-able */
383 static void var_override(const char **var, char *value)
387 *var = xstrdup(value);
391 static void set_proxyauth_name_password(CURL *result)
393 #if LIBCURL_VERSION_NUM >= 0x071301
394 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
395 proxy_auth.username);
396 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
397 proxy_auth.password);
399 struct strbuf s = STRBUF_INIT;
401 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
402 strbuf_addch(&s, ':');
403 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
404 curl_proxyuserpwd = strbuf_detach(&s, NULL);
405 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
409 static void init_curl_proxy_auth(CURL *result)
411 if (proxy_auth.username) {
412 if (!proxy_auth.password)
413 credential_fill(&proxy_auth);
414 set_proxyauth_name_password(result);
417 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
419 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
420 if (http_proxy_authmethod) {
422 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
423 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
424 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
425 proxy_authmethods[i].curlauth_param);
429 if (i == ARRAY_SIZE(proxy_authmethods)) {
430 warning("unsupported proxy authentication method %s: using anyauth",
431 http_proxy_authmethod);
432 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
436 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
440 static int has_cert_password(void)
442 if (ssl_cert == NULL || ssl_cert_password_required != 1)
444 if (!cert_auth.password) {
445 cert_auth.protocol = xstrdup("cert");
446 cert_auth.username = xstrdup("");
447 cert_auth.path = xstrdup(ssl_cert);
448 credential_fill(&cert_auth);
453 #if LIBCURL_VERSION_NUM >= 0x071900
454 static void set_curl_keepalive(CURL *c)
456 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
459 #elif LIBCURL_VERSION_NUM >= 0x071000
460 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
464 socklen_t len = (socklen_t)sizeof(ka);
466 if (type != CURLSOCKTYPE_IPCXN)
469 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
471 warning_errno("unable to set SO_KEEPALIVE on socket");
473 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
476 static void set_curl_keepalive(CURL *c)
478 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
482 static void set_curl_keepalive(CURL *c)
484 /* not supported on older curl versions */
488 static void redact_sensitive_header(struct strbuf *header)
490 const char *sensitive_header;
492 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
493 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
494 /* The first token is the type, which is OK to log */
495 while (isspace(*sensitive_header))
497 while (*sensitive_header && !isspace(*sensitive_header))
499 /* Everything else is opaque and possibly sensitive */
500 strbuf_setlen(header, sensitive_header - header->buf);
501 strbuf_addstr(header, " <redacted>");
505 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
507 struct strbuf out = STRBUF_INIT;
508 struct strbuf **headers, **header;
510 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
511 text, (long)size, (long)size);
512 trace_strbuf(&trace_curl, &out);
514 strbuf_add(&out, ptr, size);
515 headers = strbuf_split_max(&out, '\n', 0);
517 for (header = headers; *header; header++) {
518 if (hide_sensitive_header)
519 redact_sensitive_header(*header);
520 strbuf_insert((*header), 0, text, strlen(text));
521 strbuf_insert((*header), strlen(text), ": ", 2);
522 strbuf_rtrim((*header));
523 strbuf_addch((*header), '\n');
524 trace_strbuf(&trace_curl, (*header));
526 strbuf_list_free(headers);
527 strbuf_release(&out);
530 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
533 struct strbuf out = STRBUF_INIT;
534 unsigned int width = 60;
536 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
537 text, (long)size, (long)size);
538 trace_strbuf(&trace_curl, &out);
540 for (i = 0; i < size; i += width) {
544 strbuf_addf(&out, "%s: ", text);
545 for (w = 0; (w < width) && (i + w < size); w++) {
546 unsigned char ch = ptr[i + w];
549 (ch >= 0x20) && (ch < 0x80)
552 strbuf_addch(&out, '\n');
553 trace_strbuf(&trace_curl, &out);
555 strbuf_release(&out);
558 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
561 enum { NO_FILTER = 0, DO_FILTER = 1 };
565 trace_printf_key(&trace_curl, "== Info: %s", data);
566 default: /* we ignore unknown types by default */
569 case CURLINFO_HEADER_OUT:
570 text = "=> Send header";
571 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
573 case CURLINFO_DATA_OUT:
574 text = "=> Send data";
575 curl_dump_data(text, (unsigned char *)data, size);
577 case CURLINFO_SSL_DATA_OUT:
578 text = "=> Send SSL data";
579 curl_dump_data(text, (unsigned char *)data, size);
581 case CURLINFO_HEADER_IN:
582 text = "<= Recv header";
583 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
585 case CURLINFO_DATA_IN:
586 text = "<= Recv data";
587 curl_dump_data(text, (unsigned char *)data, size);
589 case CURLINFO_SSL_DATA_IN:
590 text = "<= Recv SSL data";
591 curl_dump_data(text, (unsigned char *)data, size);
597 void setup_curl_trace(CURL *handle)
599 if (!trace_want(&trace_curl))
601 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
602 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
603 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
607 static CURL *get_curl_handle(void)
609 CURL *result = curl_easy_init();
610 long allowed_protocols = 0;
613 die("curl_easy_init failed");
615 if (!curl_ssl_verify) {
616 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
617 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
619 /* Verify authenticity of the peer's certificate */
620 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
621 /* The name in the cert must match whom we tried to connect */
622 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
625 #if LIBCURL_VERSION_NUM >= 0x070907
626 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
628 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
629 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
632 if (http_proactive_auth)
633 init_curl_http_auth(result);
635 if (getenv("GIT_SSL_VERSION"))
636 ssl_version = getenv("GIT_SSL_VERSION");
637 if (ssl_version && *ssl_version) {
639 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
640 if (!strcmp(ssl_version, sslversions[i].name)) {
641 curl_easy_setopt(result, CURLOPT_SSLVERSION,
642 sslversions[i].ssl_version);
646 if (i == ARRAY_SIZE(sslversions))
647 warning("unsupported ssl version %s: using default",
651 if (getenv("GIT_SSL_CIPHER_LIST"))
652 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
653 if (ssl_cipherlist != NULL && *ssl_cipherlist)
654 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
657 if (ssl_cert != NULL)
658 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
659 if (has_cert_password())
660 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
661 #if LIBCURL_VERSION_NUM >= 0x070903
663 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
665 #if LIBCURL_VERSION_NUM >= 0x070908
666 if (ssl_capath != NULL)
667 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
669 #if LIBCURL_VERSION_NUM >= 0x072c00
670 if (ssl_pinnedkey != NULL)
671 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
673 if (ssl_cainfo != NULL)
674 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
676 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
677 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
678 curl_low_speed_limit);
679 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
680 curl_low_speed_time);
683 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
684 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
685 #if LIBCURL_VERSION_NUM >= 0x071301
686 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
687 #elif LIBCURL_VERSION_NUM >= 0x071101
688 curl_easy_setopt(result, CURLOPT_POST301, 1);
690 #if LIBCURL_VERSION_NUM >= 0x071304
691 if (is_transport_allowed("http"))
692 allowed_protocols |= CURLPROTO_HTTP;
693 if (is_transport_allowed("https"))
694 allowed_protocols |= CURLPROTO_HTTPS;
695 if (is_transport_allowed("ftp"))
696 allowed_protocols |= CURLPROTO_FTP;
697 if (is_transport_allowed("ftps"))
698 allowed_protocols |= CURLPROTO_FTPS;
699 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
701 if (transport_restrict_protocols())
702 warning("protocol restrictions not applied to curl redirects because\n"
703 "your curl version is too old (>= 7.19.4)");
705 if (getenv("GIT_CURL_VERBOSE"))
706 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
707 setup_curl_trace(result);
709 curl_easy_setopt(result, CURLOPT_USERAGENT,
710 user_agent ? user_agent : git_user_agent());
712 if (curl_ftp_no_epsv)
713 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
715 #ifdef CURLOPT_USE_SSL
717 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
721 * CURL also examines these variables as a fallback; but we need to query
722 * them here in order to decide whether to prompt for missing password (cf.
723 * init_curl_proxy_auth()).
725 * Unlike many other common environment variables, these are historically
726 * lowercase only. It appears that CURL did not know this and implemented
727 * only uppercase variants, which was later corrected to take both - with
728 * the exception of http_proxy, which is lowercase only also in CURL. As
729 * the lowercase versions are the historical quasi-standard, they take
730 * precedence here, as in CURL.
732 if (!curl_http_proxy) {
733 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
734 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
735 var_override(&curl_http_proxy, getenv("https_proxy"));
737 var_override(&curl_http_proxy, getenv("http_proxy"));
739 if (!curl_http_proxy) {
740 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
741 var_override(&curl_http_proxy, getenv("all_proxy"));
745 if (curl_http_proxy) {
746 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
747 #if LIBCURL_VERSION_NUM >= 0x071800
748 if (starts_with(curl_http_proxy, "socks5h"))
749 curl_easy_setopt(result,
750 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
751 else if (starts_with(curl_http_proxy, "socks5"))
752 curl_easy_setopt(result,
753 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
754 else if (starts_with(curl_http_proxy, "socks4a"))
755 curl_easy_setopt(result,
756 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
757 else if (starts_with(curl_http_proxy, "socks"))
758 curl_easy_setopt(result,
759 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
761 if (strstr(curl_http_proxy, "://"))
762 credential_from_url(&proxy_auth, curl_http_proxy);
764 struct strbuf url = STRBUF_INIT;
765 strbuf_addf(&url, "http://%s", curl_http_proxy);
766 credential_from_url(&proxy_auth, url.buf);
767 strbuf_release(&url);
770 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
771 #if LIBCURL_VERSION_NUM >= 0x071304
772 var_override(&curl_no_proxy, getenv("NO_PROXY"));
773 var_override(&curl_no_proxy, getenv("no_proxy"));
774 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
777 init_curl_proxy_auth(result);
779 set_curl_keepalive(result);
784 static void set_from_env(const char **var, const char *envname)
786 const char *val = getenv(envname);
791 void http_init(struct remote *remote, const char *url, int proactive_auth)
793 char *low_speed_limit;
794 char *low_speed_time;
795 char *normalized_url;
796 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
798 config.section = "http";
800 config.collect_fn = http_options;
801 config.cascade_fn = git_default_config;
805 normalized_url = url_normalize(url, &config.url);
807 git_config(urlmatch_config_entry, &config);
808 free(normalized_url);
810 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
811 die("curl_global_init failed");
813 http_proactive_auth = proactive_auth;
815 if (remote && remote->http_proxy)
816 curl_http_proxy = xstrdup(remote->http_proxy);
819 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
821 pragma_header = curl_slist_append(http_copy_default_headers(),
823 no_pragma_header = curl_slist_append(http_copy_default_headers(),
826 #ifdef USE_CURL_MULTI
828 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
829 if (http_max_requests != NULL)
830 max_requests = atoi(http_max_requests);
833 curlm = curl_multi_init();
835 die("curl_multi_init failed");
838 if (getenv("GIT_SSL_NO_VERIFY"))
841 set_from_env(&ssl_cert, "GIT_SSL_CERT");
842 #if LIBCURL_VERSION_NUM >= 0x070903
843 set_from_env(&ssl_key, "GIT_SSL_KEY");
845 #if LIBCURL_VERSION_NUM >= 0x070908
846 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
848 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
850 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
852 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
853 if (low_speed_limit != NULL)
854 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
855 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
856 if (low_speed_time != NULL)
857 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
859 if (curl_ssl_verify == -1)
862 curl_session_count = 0;
863 #ifdef USE_CURL_MULTI
864 if (max_requests < 1)
865 max_requests = DEFAULT_MAX_REQUESTS;
868 if (getenv("GIT_CURL_FTP_NO_EPSV"))
869 curl_ftp_no_epsv = 1;
872 credential_from_url(&http_auth, url);
873 if (!ssl_cert_password_required &&
874 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
875 starts_with(url, "https://"))
876 ssl_cert_password_required = 1;
879 #ifndef NO_CURL_EASY_DUPHANDLE
880 curl_default = get_curl_handle();
884 void http_cleanup(void)
886 struct active_request_slot *slot = active_queue_head;
888 while (slot != NULL) {
889 struct active_request_slot *next = slot->next;
890 if (slot->curl != NULL) {
891 xmulti_remove_handle(slot);
892 curl_easy_cleanup(slot->curl);
897 active_queue_head = NULL;
899 #ifndef NO_CURL_EASY_DUPHANDLE
900 curl_easy_cleanup(curl_default);
903 #ifdef USE_CURL_MULTI
904 curl_multi_cleanup(curlm);
906 curl_global_cleanup();
908 curl_slist_free_all(extra_http_headers);
909 extra_http_headers = NULL;
911 curl_slist_free_all(pragma_header);
912 pragma_header = NULL;
914 curl_slist_free_all(no_pragma_header);
915 no_pragma_header = NULL;
917 if (curl_http_proxy) {
918 free((void *)curl_http_proxy);
919 curl_http_proxy = NULL;
922 if (proxy_auth.password) {
923 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
924 free(proxy_auth.password);
925 proxy_auth.password = NULL;
928 free((void *)curl_proxyuserpwd);
929 curl_proxyuserpwd = NULL;
931 free((void *)http_proxy_authmethod);
932 http_proxy_authmethod = NULL;
934 if (cert_auth.password != NULL) {
935 memset(cert_auth.password, 0, strlen(cert_auth.password));
936 free(cert_auth.password);
937 cert_auth.password = NULL;
939 ssl_cert_password_required = 0;
941 free(cached_accept_language);
942 cached_accept_language = NULL;
945 struct active_request_slot *get_active_slot(void)
947 struct active_request_slot *slot = active_queue_head;
948 struct active_request_slot *newslot;
950 #ifdef USE_CURL_MULTI
953 /* Wait for a slot to open up if the queue is full */
954 while (active_requests >= max_requests) {
955 curl_multi_perform(curlm, &num_transfers);
956 if (num_transfers < active_requests)
957 process_curl_messages();
961 while (slot != NULL && slot->in_use)
965 newslot = xmalloc(sizeof(*newslot));
966 newslot->curl = NULL;
968 newslot->next = NULL;
970 slot = active_queue_head;
972 active_queue_head = newslot;
974 while (slot->next != NULL)
976 slot->next = newslot;
981 if (slot->curl == NULL) {
982 #ifdef NO_CURL_EASY_DUPHANDLE
983 slot->curl = get_curl_handle();
985 slot->curl = curl_easy_duphandle(curl_default);
987 curl_session_count++;
992 slot->results = NULL;
993 slot->finished = NULL;
994 slot->callback_data = NULL;
995 slot->callback_func = NULL;
996 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
997 if (curl_save_cookies)
998 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
999 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1000 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1001 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1002 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1003 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1004 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1005 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1006 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1007 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1008 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1010 #if LIBCURL_VERSION_NUM >= 0x070a08
1011 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1013 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1014 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1016 if (http_auth.password || curl_empty_auth)
1017 init_curl_http_auth(slot->curl);
1022 int start_active_slot(struct active_request_slot *slot)
1024 #ifdef USE_CURL_MULTI
1025 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1028 if (curlm_result != CURLM_OK &&
1029 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1030 warning("curl_multi_add_handle failed: %s",
1031 curl_multi_strerror(curlm_result));
1038 * We know there must be something to do, since we just added
1041 curl_multi_perform(curlm, &num_transfers);
1046 #ifdef USE_CURL_MULTI
1049 int (*fill)(void *);
1050 struct fill_chain *next;
1053 static struct fill_chain *fill_cfg;
1055 void add_fill_function(void *data, int (*fill)(void *))
1057 struct fill_chain *new = xmalloc(sizeof(*new));
1058 struct fill_chain **linkp = &fill_cfg;
1063 linkp = &(*linkp)->next;
1067 void fill_active_slots(void)
1069 struct active_request_slot *slot = active_queue_head;
1071 while (active_requests < max_requests) {
1072 struct fill_chain *fill;
1073 for (fill = fill_cfg; fill; fill = fill->next)
1074 if (fill->fill(fill->data))
1081 while (slot != NULL) {
1082 if (!slot->in_use && slot->curl != NULL
1083 && curl_session_count > min_curl_sessions) {
1084 curl_easy_cleanup(slot->curl);
1086 curl_session_count--;
1092 void step_active_slots(void)
1095 CURLMcode curlm_result;
1098 curlm_result = curl_multi_perform(curlm, &num_transfers);
1099 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1100 if (num_transfers < active_requests) {
1101 process_curl_messages();
1102 fill_active_slots();
1107 void run_active_slot(struct active_request_slot *slot)
1109 #ifdef USE_CURL_MULTI
1114 struct timeval select_timeout;
1117 slot->finished = &finished;
1119 step_active_slots();
1122 #if LIBCURL_VERSION_NUM >= 0x070f04
1124 curl_multi_timeout(curlm, &curl_timeout);
1125 if (curl_timeout == 0) {
1127 } else if (curl_timeout == -1) {
1128 select_timeout.tv_sec = 0;
1129 select_timeout.tv_usec = 50000;
1131 select_timeout.tv_sec = curl_timeout / 1000;
1132 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1135 select_timeout.tv_sec = 0;
1136 select_timeout.tv_usec = 50000;
1143 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1146 * It can happen that curl_multi_timeout returns a pathologically
1147 * long timeout when curl_multi_fdset returns no file descriptors
1148 * to read. See commit message for more details.
1151 (select_timeout.tv_sec > 0 ||
1152 select_timeout.tv_usec > 50000)) {
1153 select_timeout.tv_sec = 0;
1154 select_timeout.tv_usec = 50000;
1157 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1161 while (slot->in_use) {
1162 slot->curl_result = curl_easy_perform(slot->curl);
1163 finish_active_slot(slot);
1168 static void release_active_slot(struct active_request_slot *slot)
1170 closedown_active_slot(slot);
1172 xmulti_remove_handle(slot);
1173 if (curl_session_count > min_curl_sessions) {
1174 curl_easy_cleanup(slot->curl);
1176 curl_session_count--;
1179 #ifdef USE_CURL_MULTI
1180 fill_active_slots();
1184 void finish_all_active_slots(void)
1186 struct active_request_slot *slot = active_queue_head;
1188 while (slot != NULL)
1190 run_active_slot(slot);
1191 slot = active_queue_head;
1197 /* Helpers for modifying and creating URLs */
1198 static inline int needs_quote(int ch)
1200 if (((ch >= 'A') && (ch <= 'Z'))
1201 || ((ch >= 'a') && (ch <= 'z'))
1202 || ((ch >= '0') && (ch <= '9'))
1210 static char *quote_ref_url(const char *base, const char *ref)
1212 struct strbuf buf = STRBUF_INIT;
1216 end_url_with_slash(&buf, base);
1218 for (cp = ref; (ch = *cp) != 0; cp++)
1219 if (needs_quote(ch))
1220 strbuf_addf(&buf, "%%%02x", ch);
1222 strbuf_addch(&buf, *cp);
1224 return strbuf_detach(&buf, NULL);
1227 void append_remote_object_url(struct strbuf *buf, const char *url,
1229 int only_two_digit_prefix)
1231 end_url_with_slash(buf, url);
1233 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1234 if (!only_two_digit_prefix)
1235 strbuf_addstr(buf, hex + 2);
1238 char *get_remote_object_url(const char *url, const char *hex,
1239 int only_two_digit_prefix)
1241 struct strbuf buf = STRBUF_INIT;
1242 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1243 return strbuf_detach(&buf, NULL);
1246 static int handle_curl_result(struct slot_results *results)
1249 * If we see a failing http code with CURLE_OK, we have turned off
1250 * FAILONERROR (to keep the server's custom error response), and should
1251 * translate the code into failure here.
1253 if (results->curl_result == CURLE_OK &&
1254 results->http_code >= 400) {
1255 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1257 * Normally curl will already have put the "reason phrase"
1258 * from the server into curl_errorstr; unfortunately without
1259 * FAILONERROR it is lost, so we can give only the numeric
1262 snprintf(curl_errorstr, sizeof(curl_errorstr),
1263 "The requested URL returned error: %ld",
1264 results->http_code);
1267 if (results->curl_result == CURLE_OK) {
1268 credential_approve(&http_auth);
1269 if (proxy_auth.password)
1270 credential_approve(&proxy_auth);
1272 } else if (missing_target(results))
1273 return HTTP_MISSING_TARGET;
1274 else if (results->http_code == 401) {
1275 if (http_auth.username && http_auth.password) {
1276 credential_reject(&http_auth);
1279 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1280 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1285 if (results->http_connectcode == 407)
1286 credential_reject(&proxy_auth);
1287 #if LIBCURL_VERSION_NUM >= 0x070c00
1288 if (!curl_errorstr[0])
1289 strlcpy(curl_errorstr,
1290 curl_easy_strerror(results->curl_result),
1291 sizeof(curl_errorstr));
1297 int run_one_slot(struct active_request_slot *slot,
1298 struct slot_results *results)
1300 slot->results = results;
1301 if (!start_active_slot(slot)) {
1302 snprintf(curl_errorstr, sizeof(curl_errorstr),
1303 "failed to start HTTP request");
1304 return HTTP_START_FAILED;
1307 run_active_slot(slot);
1308 return handle_curl_result(results);
1311 struct curl_slist *http_copy_default_headers(void)
1313 struct curl_slist *headers = NULL, *h;
1315 for (h = extra_http_headers; h; h = h->next)
1316 headers = curl_slist_append(headers, h->data);
1321 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1327 ret = curl_easy_getinfo(curl, info, &ptr);
1329 strbuf_addstr(buf, ptr);
1334 * Check for and extract a content-type parameter. "raw"
1335 * should be positioned at the start of the potential
1336 * parameter, with any whitespace already removed.
1338 * "name" is the name of the parameter. The value is appended
1341 static int extract_param(const char *raw, const char *name,
1344 size_t len = strlen(name);
1346 if (strncasecmp(raw, name, len))
1354 while (*raw && !isspace(*raw) && *raw != ';')
1355 strbuf_addch(out, *raw++);
1360 * Extract a normalized version of the content type, with any
1361 * spaces suppressed, all letters lowercased, and no trailing ";"
1364 * Note that we will silently remove even invalid whitespace. For
1365 * example, "text / plain" is specifically forbidden by RFC 2616,
1366 * but "text/plain" is the only reasonable output, and this keeps
1369 * If the "charset" argument is not NULL, store the value of any
1370 * charset parameter there.
1373 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1374 * "text / plain" -> "text/plain"
1376 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1377 struct strbuf *charset)
1382 strbuf_grow(type, raw->len);
1383 for (p = raw->buf; *p; p++) {
1390 strbuf_addch(type, tolower(*p));
1396 strbuf_reset(charset);
1398 while (isspace(*p) || *p == ';')
1400 if (!extract_param(p, "charset", charset))
1402 while (*p && !isspace(*p))
1406 if (!charset->len && starts_with(type->buf, "text/"))
1407 strbuf_addstr(charset, "ISO-8859-1");
1410 static void write_accept_language(struct strbuf *buf)
1413 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1414 * that, q-value will be smaller than 0.001, the minimum q-value the
1415 * HTTP specification allows. See
1416 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1418 const int MAX_DECIMAL_PLACES = 3;
1419 const int MAX_LANGUAGE_TAGS = 1000;
1420 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1421 char **language_tags = NULL;
1423 const char *s = get_preferred_languages();
1425 struct strbuf tag = STRBUF_INIT;
1427 /* Don't add Accept-Language header if no language is preferred. */
1432 * Split the colon-separated string of preferred languages into
1433 * language_tags array.
1436 /* collect language tag */
1437 for (; *s && (isalnum(*s) || *s == '_'); s++)
1438 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1440 /* skip .codeset, @modifier and any other unnecessary parts */
1441 while (*s && *s != ':')
1446 REALLOC_ARRAY(language_tags, num_langs);
1447 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1448 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1453 /* write Accept-Language header into buf */
1455 int last_buf_len = 0;
1461 REALLOC_ARRAY(language_tags, num_langs + 1);
1462 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1464 /* compute decimal_places */
1465 for (max_q = 1, decimal_places = 0;
1466 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1467 decimal_places++, max_q *= 10)
1470 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1472 strbuf_addstr(buf, "Accept-Language: ");
1474 for (i = 0; i < num_langs; i++) {
1476 strbuf_addstr(buf, ", ");
1478 strbuf_addstr(buf, language_tags[i]);
1481 strbuf_addf(buf, q_format, max_q - i);
1483 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1484 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1488 last_buf_len = buf->len;
1492 /* free language tags -- last one is a static '*' */
1493 for (i = 0; i < num_langs - 1; i++)
1494 free(language_tags[i]);
1495 free(language_tags);
1499 * Get an Accept-Language header which indicates user's preferred languages.
1503 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1504 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1505 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1506 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1507 * LANGUAGE= LANG=C -> ""
1509 static const char *get_accept_language(void)
1511 if (!cached_accept_language) {
1512 struct strbuf buf = STRBUF_INIT;
1513 write_accept_language(&buf);
1515 cached_accept_language = strbuf_detach(&buf, NULL);
1518 return cached_accept_language;
1521 static void http_opt_request_remainder(CURL *curl, off_t pos)
1524 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1525 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1528 /* http_request() targets */
1529 #define HTTP_REQUEST_STRBUF 0
1530 #define HTTP_REQUEST_FILE 1
1532 static int http_request(const char *url,
1533 void *result, int target,
1534 const struct http_get_options *options)
1536 struct active_request_slot *slot;
1537 struct slot_results results;
1538 struct curl_slist *headers = http_copy_default_headers();
1539 struct strbuf buf = STRBUF_INIT;
1540 const char *accept_language;
1543 slot = get_active_slot();
1544 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1546 if (result == NULL) {
1547 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1549 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1550 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1552 if (target == HTTP_REQUEST_FILE) {
1553 off_t posn = ftello(result);
1554 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1557 http_opt_request_remainder(slot->curl, posn);
1559 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1563 accept_language = get_accept_language();
1565 if (accept_language)
1566 headers = curl_slist_append(headers, accept_language);
1568 strbuf_addstr(&buf, "Pragma:");
1569 if (options && options->no_cache)
1570 strbuf_addstr(&buf, " no-cache");
1571 if (options && options->keep_error)
1572 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1574 headers = curl_slist_append(headers, buf.buf);
1576 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1577 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1578 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1580 ret = run_one_slot(slot, &results);
1582 if (options && options->content_type) {
1583 struct strbuf raw = STRBUF_INIT;
1584 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1585 extract_content_type(&raw, options->content_type,
1587 strbuf_release(&raw);
1590 if (options && options->effective_url)
1591 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1592 options->effective_url);
1594 curl_slist_free_all(headers);
1595 strbuf_release(&buf);
1601 * Update the "base" url to a more appropriate value, as deduced by
1602 * redirects seen when requesting a URL starting with "url".
1604 * The "asked" parameter is a URL that we asked curl to access, and must begin
1607 * The "got" parameter is the URL that curl reported to us as where we ended
1610 * Returns 1 if we updated the base url, 0 otherwise.
1612 * Our basic strategy is to compare "base" and "asked" to find the bits
1613 * specific to our request. We then strip those bits off of "got" to yield the
1614 * new base. So for example, if our base is "http://example.com/foo.git",
1615 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1616 * with "https://other.example.com/foo.git/info/refs". We would want the
1617 * new URL to become "https://other.example.com/foo.git".
1619 * Note that this assumes a sane redirect scheme. It's entirely possible
1620 * in the example above to end up at a URL that does not even end in
1621 * "info/refs". In such a case we simply punt, as there is not much we can
1622 * do (and such a scheme is unlikely to represent a real git repository,
1623 * which means we are likely about to abort anyway).
1625 static int update_url_from_redirect(struct strbuf *base,
1627 const struct strbuf *got)
1632 if (!strcmp(asked, got->buf))
1635 if (!skip_prefix(asked, base->buf, &tail))
1636 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1639 tail_len = strlen(tail);
1641 if (got->len < tail_len ||
1642 strcmp(tail, got->buf + got->len - tail_len))
1643 return 0; /* insane redirect scheme */
1646 strbuf_add(base, got->buf, got->len - tail_len);
1650 static int http_request_reauth(const char *url,
1651 void *result, int target,
1652 struct http_get_options *options)
1654 int ret = http_request(url, result, target, options);
1656 if (options && options->effective_url && options->base_url) {
1657 if (update_url_from_redirect(options->base_url,
1658 url, options->effective_url)) {
1659 credential_from_url(&http_auth, options->base_url->buf);
1660 url = options->effective_url->buf;
1664 if (ret != HTTP_REAUTH)
1668 * If we are using KEEP_ERROR, the previous request may have
1669 * put cruft into our output stream; we should clear it out before
1670 * making our next request. We only know how to do this for
1671 * the strbuf case, but that is enough to satisfy current callers.
1673 if (options && options->keep_error) {
1675 case HTTP_REQUEST_STRBUF:
1676 strbuf_reset(result);
1679 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1683 credential_fill(&http_auth);
1685 return http_request(url, result, target, options);
1688 int http_get_strbuf(const char *url,
1689 struct strbuf *result,
1690 struct http_get_options *options)
1692 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1696 * Downloads a URL and stores the result in the given file.
1698 * If a previous interrupted download is detected (i.e. a previous temporary
1699 * file is still around) the download is resumed.
1701 static int http_get_file(const char *url, const char *filename,
1702 struct http_get_options *options)
1705 struct strbuf tmpfile = STRBUF_INIT;
1708 strbuf_addf(&tmpfile, "%s.temp", filename);
1709 result = fopen(tmpfile.buf, "a");
1711 error("Unable to open local file %s", tmpfile.buf);
1716 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1719 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1722 strbuf_release(&tmpfile);
1726 int http_fetch_ref(const char *base, struct ref *ref)
1728 struct http_get_options options = {0};
1730 struct strbuf buffer = STRBUF_INIT;
1733 options.no_cache = 1;
1735 url = quote_ref_url(base, ref->name);
1736 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1737 strbuf_rtrim(&buffer);
1738 if (buffer.len == 40)
1739 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1740 else if (starts_with(buffer.buf, "ref: ")) {
1741 ref->symref = xstrdup(buffer.buf + 5);
1746 strbuf_release(&buffer);
1751 /* Helpers for fetching packs */
1752 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1755 struct strbuf buf = STRBUF_INIT;
1757 if (http_is_verbose)
1758 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1760 end_url_with_slash(&buf, base_url);
1761 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1762 url = strbuf_detach(&buf, NULL);
1764 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1765 tmp = strbuf_detach(&buf, NULL);
1767 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1768 error("Unable to get pack index %s", url);
1777 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1778 unsigned char *sha1, const char *base_url)
1780 struct packed_git *new_pack;
1781 char *tmp_idx = NULL;
1784 if (has_pack_index(sha1)) {
1785 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1787 return -1; /* parse_pack_index() already issued error message */
1791 tmp_idx = fetch_pack_index(sha1, base_url);
1795 new_pack = parse_pack_index(sha1, tmp_idx);
1800 return -1; /* parse_pack_index() already issued error message */
1803 ret = verify_pack_index(new_pack);
1805 close_pack_index(new_pack);
1806 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1813 new_pack->next = *packs_head;
1814 *packs_head = new_pack;
1818 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1820 struct http_get_options options = {0};
1823 struct strbuf buf = STRBUF_INIT;
1824 unsigned char sha1[20];
1826 end_url_with_slash(&buf, base_url);
1827 strbuf_addstr(&buf, "objects/info/packs");
1828 url = strbuf_detach(&buf, NULL);
1830 options.no_cache = 1;
1831 ret = http_get_strbuf(url, &buf, &options);
1836 while (i < buf.len) {
1840 if (i + 52 <= buf.len &&
1841 starts_with(data + i, " pack-") &&
1842 starts_with(data + i + 46, ".pack\n")) {
1843 get_sha1_hex(data + i + 6, sha1);
1844 fetch_and_setup_pack_index(packs_head, sha1,
1850 while (i < buf.len && data[i] != '\n')
1861 void release_http_pack_request(struct http_pack_request *preq)
1863 if (preq->packfile != NULL) {
1864 fclose(preq->packfile);
1865 preq->packfile = NULL;
1872 int finish_http_pack_request(struct http_pack_request *preq)
1874 struct packed_git **lst;
1875 struct packed_git *p = preq->target;
1878 struct child_process ip = CHILD_PROCESS_INIT;
1879 const char *ip_argv[8];
1881 close_pack_index(p);
1883 fclose(preq->packfile);
1884 preq->packfile = NULL;
1888 lst = &((*lst)->next);
1889 *lst = (*lst)->next;
1891 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1892 die("BUG: pack tmpfile does not end in .pack.temp?");
1893 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1895 ip_argv[0] = "index-pack";
1897 ip_argv[2] = tmp_idx;
1898 ip_argv[3] = preq->tmpfile;
1906 if (run_command(&ip)) {
1907 unlink(preq->tmpfile);
1913 unlink(sha1_pack_index_name(p->sha1));
1915 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1916 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1921 install_packed_git(p);
1926 struct http_pack_request *new_http_pack_request(
1927 struct packed_git *target, const char *base_url)
1929 off_t prev_posn = 0;
1930 struct strbuf buf = STRBUF_INIT;
1931 struct http_pack_request *preq;
1933 preq = xcalloc(1, sizeof(*preq));
1934 preq->target = target;
1936 end_url_with_slash(&buf, base_url);
1937 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1938 sha1_to_hex(target->sha1));
1939 preq->url = strbuf_detach(&buf, NULL);
1941 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1942 sha1_pack_name(target->sha1));
1943 preq->packfile = fopen(preq->tmpfile, "a");
1944 if (!preq->packfile) {
1945 error("Unable to open local file %s for pack",
1950 preq->slot = get_active_slot();
1951 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1952 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1953 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1954 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1958 * If there is data present from a previous transfer attempt,
1959 * resume where it left off
1961 prev_posn = ftello(preq->packfile);
1963 if (http_is_verbose)
1965 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1966 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1967 http_opt_request_remainder(preq->slot->curl, prev_posn);
1978 /* Helpers for fetching objects (loose) */
1979 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1982 unsigned char expn[4096];
1983 size_t size = eltsize * nmemb;
1985 struct http_object_request *freq = data;
1986 struct active_request_slot *slot = freq->slot;
1989 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
1992 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
1993 curl_easy_strerror(c));
1994 if (slot->http_code >= 400)
1999 ssize_t retval = xwrite(freq->localfile,
2000 (char *) ptr + posn, size - posn);
2004 } while (posn < size);
2006 freq->stream.avail_in = size;
2007 freq->stream.next_in = (void *)ptr;
2009 freq->stream.next_out = expn;
2010 freq->stream.avail_out = sizeof(expn);
2011 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2012 git_SHA1_Update(&freq->c, expn,
2013 sizeof(expn) - freq->stream.avail_out);
2014 } while (freq->stream.avail_in && freq->zret == Z_OK);
2018 struct http_object_request *new_http_object_request(const char *base_url,
2019 unsigned char *sha1)
2021 char *hex = sha1_to_hex(sha1);
2022 const char *filename;
2023 char prevfile[PATH_MAX];
2025 char prev_buf[PREV_BUF_SIZE];
2026 ssize_t prev_read = 0;
2027 off_t prev_posn = 0;
2028 struct http_object_request *freq;
2030 freq = xcalloc(1, sizeof(*freq));
2031 hashcpy(freq->sha1, sha1);
2032 freq->localfile = -1;
2034 filename = sha1_file_name(sha1);
2035 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2036 "%s.temp", filename);
2038 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2039 unlink_or_warn(prevfile);
2040 rename(freq->tmpfile, prevfile);
2041 unlink_or_warn(freq->tmpfile);
2043 if (freq->localfile != -1)
2044 error("fd leakage in start: %d", freq->localfile);
2045 freq->localfile = open(freq->tmpfile,
2046 O_WRONLY | O_CREAT | O_EXCL, 0666);
2048 * This could have failed due to the "lazy directory creation";
2049 * try to mkdir the last path component.
2051 if (freq->localfile < 0 && errno == ENOENT) {
2052 char *dir = strrchr(freq->tmpfile, '/');
2055 mkdir(freq->tmpfile, 0777);
2058 freq->localfile = open(freq->tmpfile,
2059 O_WRONLY | O_CREAT | O_EXCL, 0666);
2062 if (freq->localfile < 0) {
2063 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2067 git_inflate_init(&freq->stream);
2069 git_SHA1_Init(&freq->c);
2071 freq->url = get_remote_object_url(base_url, hex, 0);
2074 * If a previous temp file is present, process what was already
2077 prevlocal = open(prevfile, O_RDONLY);
2078 if (prevlocal != -1) {
2080 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2082 if (fwrite_sha1_file(prev_buf,
2085 freq) == prev_read) {
2086 prev_posn += prev_read;
2091 } while (prev_read > 0);
2094 unlink_or_warn(prevfile);
2097 * Reset inflate/SHA1 if there was an error reading the previous temp
2098 * file; also rewind to the beginning of the local file.
2100 if (prev_read == -1) {
2101 memset(&freq->stream, 0, sizeof(freq->stream));
2102 git_inflate_init(&freq->stream);
2103 git_SHA1_Init(&freq->c);
2106 lseek(freq->localfile, 0, SEEK_SET);
2107 if (ftruncate(freq->localfile, 0) < 0) {
2108 error_errno("Couldn't truncate temporary file %s",
2115 freq->slot = get_active_slot();
2117 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2118 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2119 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2120 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2121 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2122 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2125 * If we have successfully processed data from a previous fetch
2126 * attempt, only fetch the data we don't already have.
2129 if (http_is_verbose)
2131 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2132 hex, (uintmax_t)prev_posn);
2133 http_opt_request_remainder(freq->slot->curl, prev_posn);
2144 void process_http_object_request(struct http_object_request *freq)
2146 if (freq->slot == NULL)
2148 freq->curl_result = freq->slot->curl_result;
2149 freq->http_code = freq->slot->http_code;
2153 int finish_http_object_request(struct http_object_request *freq)
2157 close(freq->localfile);
2158 freq->localfile = -1;
2160 process_http_object_request(freq);
2162 if (freq->http_code == 416) {
2163 warning("requested range invalid; we may already have all the data.");
2164 } else if (freq->curl_result != CURLE_OK) {
2165 if (stat(freq->tmpfile, &st) == 0)
2166 if (st.st_size == 0)
2167 unlink_or_warn(freq->tmpfile);
2171 git_inflate_end(&freq->stream);
2172 git_SHA1_Final(freq->real_sha1, &freq->c);
2173 if (freq->zret != Z_STREAM_END) {
2174 unlink_or_warn(freq->tmpfile);
2177 if (hashcmp(freq->sha1, freq->real_sha1)) {
2178 unlink_or_warn(freq->tmpfile);
2182 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2184 return freq->rename;
2187 void abort_http_object_request(struct http_object_request *freq)
2189 unlink_or_warn(freq->tmpfile);
2191 release_http_object_request(freq);
2194 void release_http_object_request(struct http_object_request *freq)
2196 if (freq->localfile != -1) {
2197 close(freq->localfile);
2198 freq->localfile = -1;
2200 if (freq->url != NULL) {
2204 if (freq->slot != NULL) {
2205 freq->slot->callback_func = NULL;
2206 freq->slot->callback_data = NULL;
2207 release_active_slot(freq->slot);