1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
14 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
15 #if LIBCURL_VERSION_NUM >= 0x070a08
16 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
18 long int git_curl_ipresolve;
22 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
24 #if LIBCURL_VERSION_NUM >= 0x070a06
25 #define LIBCURL_CAN_HANDLE_AUTH_ANY
28 static int min_curl_sessions = 1;
29 static int curl_session_count;
31 static int max_requests = -1;
34 #ifndef NO_CURL_EASY_DUPHANDLE
35 static CURL *curl_default;
38 #define PREV_BUF_SIZE 4096
40 char curl_errorstr[CURL_ERROR_SIZE];
42 static int curl_ssl_verify = -1;
43 static int curl_ssl_try;
44 static const char *ssl_cert;
45 static const char *ssl_cipherlist;
46 static const char *ssl_version;
51 { "sslv2", CURL_SSLVERSION_SSLv2 },
52 { "sslv3", CURL_SSLVERSION_SSLv3 },
53 { "tlsv1", CURL_SSLVERSION_TLSv1 },
54 #if LIBCURL_VERSION_NUM >= 0x072200
55 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
56 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
57 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
60 #if LIBCURL_VERSION_NUM >= 0x070903
61 static const char *ssl_key;
63 #if LIBCURL_VERSION_NUM >= 0x070908
64 static const char *ssl_capath;
66 #if LIBCURL_VERSION_NUM >= 0x072c00
67 static const char *ssl_pinnedkey;
69 static const char *ssl_cainfo;
70 static long curl_low_speed_limit = -1;
71 static long curl_low_speed_time = -1;
72 static int curl_ftp_no_epsv;
73 static const char *curl_http_proxy;
74 static const char *curl_no_proxy;
75 static const char *http_proxy_authmethod;
79 } proxy_authmethods[] = {
80 { "basic", CURLAUTH_BASIC },
81 { "digest", CURLAUTH_DIGEST },
82 { "negotiate", CURLAUTH_GSSNEGOTIATE },
83 { "ntlm", CURLAUTH_NTLM },
84 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
85 { "anyauth", CURLAUTH_ANY },
88 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
89 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
93 #if LIBCURL_VERSION_NUM >= 0x071600
94 static const char *curl_deleg;
97 long curl_deleg_param;
98 } curl_deleg_levels[] = {
99 { "none", CURLGSSAPI_DELEGATION_NONE },
100 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
101 { "always", CURLGSSAPI_DELEGATION_FLAG },
105 static struct credential proxy_auth = CREDENTIAL_INIT;
106 static const char *curl_proxyuserpwd;
107 static const char *curl_cookie_file;
108 static int curl_save_cookies;
109 struct credential http_auth = CREDENTIAL_INIT;
110 static int http_proactive_auth;
111 static const char *user_agent;
112 static int curl_empty_auth = -1;
114 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
116 #if LIBCURL_VERSION_NUM >= 0x071700
117 /* Use CURLOPT_KEYPASSWD as is */
118 #elif LIBCURL_VERSION_NUM >= 0x070903
119 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
121 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
124 static struct credential cert_auth = CREDENTIAL_INIT;
125 static int ssl_cert_password_required;
126 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
127 static unsigned long http_auth_methods = CURLAUTH_ANY;
128 static int http_auth_methods_restricted;
129 /* Modes for which empty_auth cannot actually help us. */
130 static unsigned long empty_auth_useless =
132 #ifdef CURLAUTH_DIGEST_IE
138 static struct curl_slist *pragma_header;
139 static struct curl_slist *no_pragma_header;
140 static struct curl_slist *extra_http_headers;
142 static struct active_request_slot *active_queue_head;
144 static char *cached_accept_language;
146 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
148 size_t size = eltsize * nmemb;
149 struct buffer *buffer = buffer_;
151 if (size > buffer->buf.len - buffer->posn)
152 size = buffer->buf.len - buffer->posn;
153 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
154 buffer->posn += size;
159 #ifndef NO_CURL_IOCTL
160 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
162 struct buffer *buffer = clientp;
168 case CURLIOCMD_RESTARTREAD:
173 return CURLIOE_UNKNOWNCMD;
178 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
180 size_t size = eltsize * nmemb;
181 struct strbuf *buffer = buffer_;
183 strbuf_add(buffer, ptr, size);
187 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
189 return eltsize * nmemb;
192 static void closedown_active_slot(struct active_request_slot *slot)
198 static void finish_active_slot(struct active_request_slot *slot)
200 closedown_active_slot(slot);
201 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
203 if (slot->finished != NULL)
204 (*slot->finished) = 1;
206 /* Store slot results so they can be read after the slot is reused */
207 if (slot->results != NULL) {
208 slot->results->curl_result = slot->curl_result;
209 slot->results->http_code = slot->http_code;
210 #if LIBCURL_VERSION_NUM >= 0x070a08
211 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
212 &slot->results->auth_avail);
214 slot->results->auth_avail = 0;
217 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
218 &slot->results->http_connectcode);
221 /* Run callback if appropriate */
222 if (slot->callback_func != NULL)
223 slot->callback_func(slot->callback_data);
226 static void xmulti_remove_handle(struct active_request_slot *slot)
228 #ifdef USE_CURL_MULTI
229 curl_multi_remove_handle(curlm, slot->curl);
233 #ifdef USE_CURL_MULTI
234 static void process_curl_messages(void)
237 struct active_request_slot *slot;
238 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
240 while (curl_message != NULL) {
241 if (curl_message->msg == CURLMSG_DONE) {
242 int curl_result = curl_message->data.result;
243 slot = active_queue_head;
244 while (slot != NULL &&
245 slot->curl != curl_message->easy_handle)
248 xmulti_remove_handle(slot);
249 slot->curl_result = curl_result;
250 finish_active_slot(slot);
252 fprintf(stderr, "Received DONE message for unknown request!\n");
255 fprintf(stderr, "Unknown CURL message received: %d\n",
256 (int)curl_message->msg);
258 curl_message = curl_multi_info_read(curlm, &num_messages);
263 static int http_options(const char *var, const char *value, void *cb)
265 if (!strcmp("http.sslverify", var)) {
266 curl_ssl_verify = git_config_bool(var, value);
269 if (!strcmp("http.sslcipherlist", var))
270 return git_config_string(&ssl_cipherlist, var, value);
271 if (!strcmp("http.sslversion", var))
272 return git_config_string(&ssl_version, var, value);
273 if (!strcmp("http.sslcert", var))
274 return git_config_string(&ssl_cert, var, value);
275 #if LIBCURL_VERSION_NUM >= 0x070903
276 if (!strcmp("http.sslkey", var))
277 return git_config_string(&ssl_key, var, value);
279 #if LIBCURL_VERSION_NUM >= 0x070908
280 if (!strcmp("http.sslcapath", var))
281 return git_config_pathname(&ssl_capath, var, value);
283 if (!strcmp("http.sslcainfo", var))
284 return git_config_pathname(&ssl_cainfo, var, value);
285 if (!strcmp("http.sslcertpasswordprotected", var)) {
286 ssl_cert_password_required = git_config_bool(var, value);
289 if (!strcmp("http.ssltry", var)) {
290 curl_ssl_try = git_config_bool(var, value);
293 if (!strcmp("http.minsessions", var)) {
294 min_curl_sessions = git_config_int(var, value);
295 #ifndef USE_CURL_MULTI
296 if (min_curl_sessions > 1)
297 min_curl_sessions = 1;
301 #ifdef USE_CURL_MULTI
302 if (!strcmp("http.maxrequests", var)) {
303 max_requests = git_config_int(var, value);
307 if (!strcmp("http.lowspeedlimit", var)) {
308 curl_low_speed_limit = (long)git_config_int(var, value);
311 if (!strcmp("http.lowspeedtime", var)) {
312 curl_low_speed_time = (long)git_config_int(var, value);
316 if (!strcmp("http.noepsv", var)) {
317 curl_ftp_no_epsv = git_config_bool(var, value);
320 if (!strcmp("http.proxy", var))
321 return git_config_string(&curl_http_proxy, var, value);
323 if (!strcmp("http.proxyauthmethod", var))
324 return git_config_string(&http_proxy_authmethod, var, value);
326 if (!strcmp("http.cookiefile", var))
327 return git_config_pathname(&curl_cookie_file, var, value);
328 if (!strcmp("http.savecookies", var)) {
329 curl_save_cookies = git_config_bool(var, value);
333 if (!strcmp("http.postbuffer", var)) {
334 http_post_buffer = git_config_int(var, value);
335 if (http_post_buffer < LARGE_PACKET_MAX)
336 http_post_buffer = LARGE_PACKET_MAX;
340 if (!strcmp("http.useragent", var))
341 return git_config_string(&user_agent, var, value);
343 if (!strcmp("http.emptyauth", var)) {
344 if (value && !strcmp("auto", value))
345 curl_empty_auth = -1;
347 curl_empty_auth = git_config_bool(var, value);
351 if (!strcmp("http.delegation", var)) {
352 #if LIBCURL_VERSION_NUM >= 0x071600
353 return git_config_string(&curl_deleg, var, value);
355 warning(_("Delegation control is not supported with cURL < 7.22.0"));
360 if (!strcmp("http.pinnedpubkey", var)) {
361 #if LIBCURL_VERSION_NUM >= 0x072c00
362 return git_config_pathname(&ssl_pinnedkey, var, value);
364 warning(_("Public key pinning not supported with cURL < 7.44.0"));
369 if (!strcmp("http.extraheader", var)) {
371 return config_error_nonbool(var);
372 } else if (!*value) {
373 curl_slist_free_all(extra_http_headers);
374 extra_http_headers = NULL;
377 curl_slist_append(extra_http_headers, value);
382 if (!strcmp("http.followredirects", var)) {
383 if (value && !strcmp(value, "initial"))
384 http_follow_config = HTTP_FOLLOW_INITIAL;
385 else if (git_config_bool(var, value))
386 http_follow_config = HTTP_FOLLOW_ALWAYS;
388 http_follow_config = HTTP_FOLLOW_NONE;
392 /* Fall back on the default ones */
393 return git_default_config(var, value, cb);
396 static int curl_empty_auth_enabled(void)
398 if (curl_empty_auth >= 0)
399 return curl_empty_auth;
401 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
403 * Our libcurl is too old to do AUTH_ANY in the first place;
404 * just default to turning the feature off.
408 * In the automatic case, kick in the empty-auth
409 * hack as long as we would potentially try some
410 * method more exotic than "Basic" or "Digest".
412 * But only do this when this is our second or
413 * subsequent request, as by then we know what
414 * methods are available.
416 if (http_auth_methods_restricted &&
417 (http_auth_methods & ~empty_auth_useless))
423 static void init_curl_http_auth(CURL *result)
425 if (!http_auth.username || !*http_auth.username) {
426 if (curl_empty_auth_enabled())
427 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
431 credential_fill(&http_auth);
433 #if LIBCURL_VERSION_NUM >= 0x071301
434 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
435 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
438 static struct strbuf up = STRBUF_INIT;
440 * Note that we assume we only ever have a single set of
441 * credentials in a given program run, so we do not have
442 * to worry about updating this buffer, only setting its
446 strbuf_addf(&up, "%s:%s",
447 http_auth.username, http_auth.password);
448 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
453 /* *var must be free-able */
454 static void var_override(const char **var, char *value)
458 *var = xstrdup(value);
462 static void set_proxyauth_name_password(CURL *result)
464 #if LIBCURL_VERSION_NUM >= 0x071301
465 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
466 proxy_auth.username);
467 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
468 proxy_auth.password);
470 struct strbuf s = STRBUF_INIT;
472 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
473 strbuf_addch(&s, ':');
474 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
475 curl_proxyuserpwd = strbuf_detach(&s, NULL);
476 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
480 static void init_curl_proxy_auth(CURL *result)
482 if (proxy_auth.username) {
483 if (!proxy_auth.password)
484 credential_fill(&proxy_auth);
485 set_proxyauth_name_password(result);
488 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
490 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
491 if (http_proxy_authmethod) {
493 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
494 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
495 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
496 proxy_authmethods[i].curlauth_param);
500 if (i == ARRAY_SIZE(proxy_authmethods)) {
501 warning("unsupported proxy authentication method %s: using anyauth",
502 http_proxy_authmethod);
503 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
507 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
511 static int has_cert_password(void)
513 if (ssl_cert == NULL || ssl_cert_password_required != 1)
515 if (!cert_auth.password) {
516 cert_auth.protocol = xstrdup("cert");
517 cert_auth.username = xstrdup("");
518 cert_auth.path = xstrdup(ssl_cert);
519 credential_fill(&cert_auth);
524 #if LIBCURL_VERSION_NUM >= 0x071900
525 static void set_curl_keepalive(CURL *c)
527 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
530 #elif LIBCURL_VERSION_NUM >= 0x071000
531 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
535 socklen_t len = (socklen_t)sizeof(ka);
537 if (type != CURLSOCKTYPE_IPCXN)
540 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
542 warning_errno("unable to set SO_KEEPALIVE on socket");
544 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
547 static void set_curl_keepalive(CURL *c)
549 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
553 static void set_curl_keepalive(CURL *c)
555 /* not supported on older curl versions */
559 static void redact_sensitive_header(struct strbuf *header)
561 const char *sensitive_header;
563 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
564 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
565 /* The first token is the type, which is OK to log */
566 while (isspace(*sensitive_header))
568 while (*sensitive_header && !isspace(*sensitive_header))
570 /* Everything else is opaque and possibly sensitive */
571 strbuf_setlen(header, sensitive_header - header->buf);
572 strbuf_addstr(header, " <redacted>");
576 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
578 struct strbuf out = STRBUF_INIT;
579 struct strbuf **headers, **header;
581 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
582 text, (long)size, (long)size);
583 trace_strbuf(&trace_curl, &out);
585 strbuf_add(&out, ptr, size);
586 headers = strbuf_split_max(&out, '\n', 0);
588 for (header = headers; *header; header++) {
589 if (hide_sensitive_header)
590 redact_sensitive_header(*header);
591 strbuf_insert((*header), 0, text, strlen(text));
592 strbuf_insert((*header), strlen(text), ": ", 2);
593 strbuf_rtrim((*header));
594 strbuf_addch((*header), '\n');
595 trace_strbuf(&trace_curl, (*header));
597 strbuf_list_free(headers);
598 strbuf_release(&out);
601 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
604 struct strbuf out = STRBUF_INIT;
605 unsigned int width = 60;
607 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
608 text, (long)size, (long)size);
609 trace_strbuf(&trace_curl, &out);
611 for (i = 0; i < size; i += width) {
615 strbuf_addf(&out, "%s: ", text);
616 for (w = 0; (w < width) && (i + w < size); w++) {
617 unsigned char ch = ptr[i + w];
620 (ch >= 0x20) && (ch < 0x80)
623 strbuf_addch(&out, '\n');
624 trace_strbuf(&trace_curl, &out);
626 strbuf_release(&out);
629 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
632 enum { NO_FILTER = 0, DO_FILTER = 1 };
636 trace_printf_key(&trace_curl, "== Info: %s", data);
637 default: /* we ignore unknown types by default */
640 case CURLINFO_HEADER_OUT:
641 text = "=> Send header";
642 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
644 case CURLINFO_DATA_OUT:
645 text = "=> Send data";
646 curl_dump_data(text, (unsigned char *)data, size);
648 case CURLINFO_SSL_DATA_OUT:
649 text = "=> Send SSL data";
650 curl_dump_data(text, (unsigned char *)data, size);
652 case CURLINFO_HEADER_IN:
653 text = "<= Recv header";
654 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
656 case CURLINFO_DATA_IN:
657 text = "<= Recv data";
658 curl_dump_data(text, (unsigned char *)data, size);
660 case CURLINFO_SSL_DATA_IN:
661 text = "<= Recv SSL data";
662 curl_dump_data(text, (unsigned char *)data, size);
668 void setup_curl_trace(CURL *handle)
670 if (!trace_want(&trace_curl))
672 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
673 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
674 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
677 static long get_curl_allowed_protocols(int from_user)
679 long allowed_protocols = 0;
681 if (is_transport_allowed("http", from_user))
682 allowed_protocols |= CURLPROTO_HTTP;
683 if (is_transport_allowed("https", from_user))
684 allowed_protocols |= CURLPROTO_HTTPS;
685 if (is_transport_allowed("ftp", from_user))
686 allowed_protocols |= CURLPROTO_FTP;
687 if (is_transport_allowed("ftps", from_user))
688 allowed_protocols |= CURLPROTO_FTPS;
690 return allowed_protocols;
693 static CURL *get_curl_handle(void)
695 CURL *result = curl_easy_init();
698 die("curl_easy_init failed");
700 if (!curl_ssl_verify) {
701 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
702 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
704 /* Verify authenticity of the peer's certificate */
705 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
706 /* The name in the cert must match whom we tried to connect */
707 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
710 #if LIBCURL_VERSION_NUM >= 0x070907
711 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
713 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
714 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
717 #if LIBCURL_VERSION_NUM >= 0x071600
720 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
721 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
722 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
723 curl_deleg_levels[i].curl_deleg_param);
727 if (i == ARRAY_SIZE(curl_deleg_levels))
728 warning("Unknown delegation method '%s': using default",
733 if (http_proactive_auth)
734 init_curl_http_auth(result);
736 if (getenv("GIT_SSL_VERSION"))
737 ssl_version = getenv("GIT_SSL_VERSION");
738 if (ssl_version && *ssl_version) {
740 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
741 if (!strcmp(ssl_version, sslversions[i].name)) {
742 curl_easy_setopt(result, CURLOPT_SSLVERSION,
743 sslversions[i].ssl_version);
747 if (i == ARRAY_SIZE(sslversions))
748 warning("unsupported ssl version %s: using default",
752 if (getenv("GIT_SSL_CIPHER_LIST"))
753 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
754 if (ssl_cipherlist != NULL && *ssl_cipherlist)
755 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
758 if (ssl_cert != NULL)
759 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
760 if (has_cert_password())
761 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
762 #if LIBCURL_VERSION_NUM >= 0x070903
764 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
766 #if LIBCURL_VERSION_NUM >= 0x070908
767 if (ssl_capath != NULL)
768 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
770 #if LIBCURL_VERSION_NUM >= 0x072c00
771 if (ssl_pinnedkey != NULL)
772 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
774 if (ssl_cainfo != NULL)
775 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
777 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
778 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
779 curl_low_speed_limit);
780 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
781 curl_low_speed_time);
784 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
785 #if LIBCURL_VERSION_NUM >= 0x071301
786 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
787 #elif LIBCURL_VERSION_NUM >= 0x071101
788 curl_easy_setopt(result, CURLOPT_POST301, 1);
790 #if LIBCURL_VERSION_NUM >= 0x071304
791 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
792 get_curl_allowed_protocols(0));
793 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
794 get_curl_allowed_protocols(-1));
796 warning("protocol restrictions not applied to curl redirects because\n"
797 "your curl version is too old (>= 7.19.4)");
799 if (getenv("GIT_CURL_VERBOSE"))
800 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
801 setup_curl_trace(result);
803 curl_easy_setopt(result, CURLOPT_USERAGENT,
804 user_agent ? user_agent : git_user_agent());
806 if (curl_ftp_no_epsv)
807 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
809 #ifdef CURLOPT_USE_SSL
811 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
815 * CURL also examines these variables as a fallback; but we need to query
816 * them here in order to decide whether to prompt for missing password (cf.
817 * init_curl_proxy_auth()).
819 * Unlike many other common environment variables, these are historically
820 * lowercase only. It appears that CURL did not know this and implemented
821 * only uppercase variants, which was later corrected to take both - with
822 * the exception of http_proxy, which is lowercase only also in CURL. As
823 * the lowercase versions are the historical quasi-standard, they take
824 * precedence here, as in CURL.
826 if (!curl_http_proxy) {
827 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
828 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
829 var_override(&curl_http_proxy, getenv("https_proxy"));
831 var_override(&curl_http_proxy, getenv("http_proxy"));
833 if (!curl_http_proxy) {
834 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
835 var_override(&curl_http_proxy, getenv("all_proxy"));
839 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
841 * Handle case with the empty http.proxy value here to keep
843 * NB: empty option disables proxying at all.
845 curl_easy_setopt(result, CURLOPT_PROXY, "");
846 } else if (curl_http_proxy) {
847 #if LIBCURL_VERSION_NUM >= 0x071800
848 if (starts_with(curl_http_proxy, "socks5h"))
849 curl_easy_setopt(result,
850 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
851 else if (starts_with(curl_http_proxy, "socks5"))
852 curl_easy_setopt(result,
853 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
854 else if (starts_with(curl_http_proxy, "socks4a"))
855 curl_easy_setopt(result,
856 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
857 else if (starts_with(curl_http_proxy, "socks"))
858 curl_easy_setopt(result,
859 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
861 if (strstr(curl_http_proxy, "://"))
862 credential_from_url(&proxy_auth, curl_http_proxy);
864 struct strbuf url = STRBUF_INIT;
865 strbuf_addf(&url, "http://%s", curl_http_proxy);
866 credential_from_url(&proxy_auth, url.buf);
867 strbuf_release(&url);
870 if (!proxy_auth.host)
871 die("Invalid proxy URL '%s'", curl_http_proxy);
873 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
874 #if LIBCURL_VERSION_NUM >= 0x071304
875 var_override(&curl_no_proxy, getenv("NO_PROXY"));
876 var_override(&curl_no_proxy, getenv("no_proxy"));
877 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
880 init_curl_proxy_auth(result);
882 set_curl_keepalive(result);
887 static void set_from_env(const char **var, const char *envname)
889 const char *val = getenv(envname);
894 void http_init(struct remote *remote, const char *url, int proactive_auth)
896 char *low_speed_limit;
897 char *low_speed_time;
898 char *normalized_url;
899 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
901 config.section = "http";
903 config.collect_fn = http_options;
904 config.cascade_fn = git_default_config;
908 normalized_url = url_normalize(url, &config.url);
910 git_config(urlmatch_config_entry, &config);
911 free(normalized_url);
913 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
914 die("curl_global_init failed");
916 http_proactive_auth = proactive_auth;
918 if (remote && remote->http_proxy)
919 curl_http_proxy = xstrdup(remote->http_proxy);
922 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
924 pragma_header = curl_slist_append(http_copy_default_headers(),
926 no_pragma_header = curl_slist_append(http_copy_default_headers(),
929 #ifdef USE_CURL_MULTI
931 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
932 if (http_max_requests != NULL)
933 max_requests = atoi(http_max_requests);
936 curlm = curl_multi_init();
938 die("curl_multi_init failed");
941 if (getenv("GIT_SSL_NO_VERIFY"))
944 set_from_env(&ssl_cert, "GIT_SSL_CERT");
945 #if LIBCURL_VERSION_NUM >= 0x070903
946 set_from_env(&ssl_key, "GIT_SSL_KEY");
948 #if LIBCURL_VERSION_NUM >= 0x070908
949 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
951 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
953 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
955 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
956 if (low_speed_limit != NULL)
957 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
958 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
959 if (low_speed_time != NULL)
960 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
962 if (curl_ssl_verify == -1)
965 curl_session_count = 0;
966 #ifdef USE_CURL_MULTI
967 if (max_requests < 1)
968 max_requests = DEFAULT_MAX_REQUESTS;
971 if (getenv("GIT_CURL_FTP_NO_EPSV"))
972 curl_ftp_no_epsv = 1;
975 credential_from_url(&http_auth, url);
976 if (!ssl_cert_password_required &&
977 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
978 starts_with(url, "https://"))
979 ssl_cert_password_required = 1;
982 #ifndef NO_CURL_EASY_DUPHANDLE
983 curl_default = get_curl_handle();
987 void http_cleanup(void)
989 struct active_request_slot *slot = active_queue_head;
991 while (slot != NULL) {
992 struct active_request_slot *next = slot->next;
993 if (slot->curl != NULL) {
994 xmulti_remove_handle(slot);
995 curl_easy_cleanup(slot->curl);
1000 active_queue_head = NULL;
1002 #ifndef NO_CURL_EASY_DUPHANDLE
1003 curl_easy_cleanup(curl_default);
1006 #ifdef USE_CURL_MULTI
1007 curl_multi_cleanup(curlm);
1009 curl_global_cleanup();
1011 curl_slist_free_all(extra_http_headers);
1012 extra_http_headers = NULL;
1014 curl_slist_free_all(pragma_header);
1015 pragma_header = NULL;
1017 curl_slist_free_all(no_pragma_header);
1018 no_pragma_header = NULL;
1020 if (curl_http_proxy) {
1021 free((void *)curl_http_proxy);
1022 curl_http_proxy = NULL;
1025 if (proxy_auth.password) {
1026 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1027 free(proxy_auth.password);
1028 proxy_auth.password = NULL;
1031 free((void *)curl_proxyuserpwd);
1032 curl_proxyuserpwd = NULL;
1034 free((void *)http_proxy_authmethod);
1035 http_proxy_authmethod = NULL;
1037 if (cert_auth.password != NULL) {
1038 memset(cert_auth.password, 0, strlen(cert_auth.password));
1039 free(cert_auth.password);
1040 cert_auth.password = NULL;
1042 ssl_cert_password_required = 0;
1044 free(cached_accept_language);
1045 cached_accept_language = NULL;
1048 struct active_request_slot *get_active_slot(void)
1050 struct active_request_slot *slot = active_queue_head;
1051 struct active_request_slot *newslot;
1053 #ifdef USE_CURL_MULTI
1056 /* Wait for a slot to open up if the queue is full */
1057 while (active_requests >= max_requests) {
1058 curl_multi_perform(curlm, &num_transfers);
1059 if (num_transfers < active_requests)
1060 process_curl_messages();
1064 while (slot != NULL && slot->in_use)
1068 newslot = xmalloc(sizeof(*newslot));
1069 newslot->curl = NULL;
1070 newslot->in_use = 0;
1071 newslot->next = NULL;
1073 slot = active_queue_head;
1075 active_queue_head = newslot;
1077 while (slot->next != NULL)
1079 slot->next = newslot;
1084 if (slot->curl == NULL) {
1085 #ifdef NO_CURL_EASY_DUPHANDLE
1086 slot->curl = get_curl_handle();
1088 slot->curl = curl_easy_duphandle(curl_default);
1090 curl_session_count++;
1095 slot->results = NULL;
1096 slot->finished = NULL;
1097 slot->callback_data = NULL;
1098 slot->callback_func = NULL;
1099 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1100 if (curl_save_cookies)
1101 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1102 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1103 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1104 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1105 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1106 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1107 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1108 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1109 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1110 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1111 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1114 * Default following to off unless "ALWAYS" is configured; this gives
1115 * callers a sane starting point, and they can tweak for individual
1116 * HTTP_FOLLOW_* cases themselves.
1118 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1119 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1121 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1123 #if LIBCURL_VERSION_NUM >= 0x070a08
1124 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1126 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1127 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1129 if (http_auth.password || curl_empty_auth_enabled())
1130 init_curl_http_auth(slot->curl);
1135 int start_active_slot(struct active_request_slot *slot)
1137 #ifdef USE_CURL_MULTI
1138 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1141 if (curlm_result != CURLM_OK &&
1142 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1143 warning("curl_multi_add_handle failed: %s",
1144 curl_multi_strerror(curlm_result));
1151 * We know there must be something to do, since we just added
1154 curl_multi_perform(curlm, &num_transfers);
1159 #ifdef USE_CURL_MULTI
1162 int (*fill)(void *);
1163 struct fill_chain *next;
1166 static struct fill_chain *fill_cfg;
1168 void add_fill_function(void *data, int (*fill)(void *))
1170 struct fill_chain *new = xmalloc(sizeof(*new));
1171 struct fill_chain **linkp = &fill_cfg;
1176 linkp = &(*linkp)->next;
1180 void fill_active_slots(void)
1182 struct active_request_slot *slot = active_queue_head;
1184 while (active_requests < max_requests) {
1185 struct fill_chain *fill;
1186 for (fill = fill_cfg; fill; fill = fill->next)
1187 if (fill->fill(fill->data))
1194 while (slot != NULL) {
1195 if (!slot->in_use && slot->curl != NULL
1196 && curl_session_count > min_curl_sessions) {
1197 curl_easy_cleanup(slot->curl);
1199 curl_session_count--;
1205 void step_active_slots(void)
1208 CURLMcode curlm_result;
1211 curlm_result = curl_multi_perform(curlm, &num_transfers);
1212 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1213 if (num_transfers < active_requests) {
1214 process_curl_messages();
1215 fill_active_slots();
1220 void run_active_slot(struct active_request_slot *slot)
1222 #ifdef USE_CURL_MULTI
1227 struct timeval select_timeout;
1230 slot->finished = &finished;
1232 step_active_slots();
1235 #if LIBCURL_VERSION_NUM >= 0x070f04
1237 curl_multi_timeout(curlm, &curl_timeout);
1238 if (curl_timeout == 0) {
1240 } else if (curl_timeout == -1) {
1241 select_timeout.tv_sec = 0;
1242 select_timeout.tv_usec = 50000;
1244 select_timeout.tv_sec = curl_timeout / 1000;
1245 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1248 select_timeout.tv_sec = 0;
1249 select_timeout.tv_usec = 50000;
1256 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1259 * It can happen that curl_multi_timeout returns a pathologically
1260 * long timeout when curl_multi_fdset returns no file descriptors
1261 * to read. See commit message for more details.
1264 (select_timeout.tv_sec > 0 ||
1265 select_timeout.tv_usec > 50000)) {
1266 select_timeout.tv_sec = 0;
1267 select_timeout.tv_usec = 50000;
1270 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1274 while (slot->in_use) {
1275 slot->curl_result = curl_easy_perform(slot->curl);
1276 finish_active_slot(slot);
1281 static void release_active_slot(struct active_request_slot *slot)
1283 closedown_active_slot(slot);
1285 xmulti_remove_handle(slot);
1286 if (curl_session_count > min_curl_sessions) {
1287 curl_easy_cleanup(slot->curl);
1289 curl_session_count--;
1292 #ifdef USE_CURL_MULTI
1293 fill_active_slots();
1297 void finish_all_active_slots(void)
1299 struct active_request_slot *slot = active_queue_head;
1301 while (slot != NULL)
1303 run_active_slot(slot);
1304 slot = active_queue_head;
1310 /* Helpers for modifying and creating URLs */
1311 static inline int needs_quote(int ch)
1313 if (((ch >= 'A') && (ch <= 'Z'))
1314 || ((ch >= 'a') && (ch <= 'z'))
1315 || ((ch >= '0') && (ch <= '9'))
1323 static char *quote_ref_url(const char *base, const char *ref)
1325 struct strbuf buf = STRBUF_INIT;
1329 end_url_with_slash(&buf, base);
1331 for (cp = ref; (ch = *cp) != 0; cp++)
1332 if (needs_quote(ch))
1333 strbuf_addf(&buf, "%%%02x", ch);
1335 strbuf_addch(&buf, *cp);
1337 return strbuf_detach(&buf, NULL);
1340 void append_remote_object_url(struct strbuf *buf, const char *url,
1342 int only_two_digit_prefix)
1344 end_url_with_slash(buf, url);
1346 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1347 if (!only_two_digit_prefix)
1348 strbuf_addstr(buf, hex + 2);
1351 char *get_remote_object_url(const char *url, const char *hex,
1352 int only_two_digit_prefix)
1354 struct strbuf buf = STRBUF_INIT;
1355 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1356 return strbuf_detach(&buf, NULL);
1359 static int handle_curl_result(struct slot_results *results)
1362 * If we see a failing http code with CURLE_OK, we have turned off
1363 * FAILONERROR (to keep the server's custom error response), and should
1364 * translate the code into failure here.
1366 * Likewise, if we see a redirect (30x code), that means we turned off
1367 * redirect-following, and we should treat the result as an error.
1369 if (results->curl_result == CURLE_OK &&
1370 results->http_code >= 300) {
1371 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1373 * Normally curl will already have put the "reason phrase"
1374 * from the server into curl_errorstr; unfortunately without
1375 * FAILONERROR it is lost, so we can give only the numeric
1378 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1379 "The requested URL returned error: %ld",
1380 results->http_code);
1383 if (results->curl_result == CURLE_OK) {
1384 credential_approve(&http_auth);
1385 if (proxy_auth.password)
1386 credential_approve(&proxy_auth);
1388 } else if (missing_target(results))
1389 return HTTP_MISSING_TARGET;
1390 else if (results->http_code == 401) {
1391 if (http_auth.username && http_auth.password) {
1392 credential_reject(&http_auth);
1395 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1396 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1397 if (results->auth_avail) {
1398 http_auth_methods &= results->auth_avail;
1399 http_auth_methods_restricted = 1;
1405 if (results->http_connectcode == 407)
1406 credential_reject(&proxy_auth);
1407 #if LIBCURL_VERSION_NUM >= 0x070c00
1408 if (!curl_errorstr[0])
1409 strlcpy(curl_errorstr,
1410 curl_easy_strerror(results->curl_result),
1411 sizeof(curl_errorstr));
1417 int run_one_slot(struct active_request_slot *slot,
1418 struct slot_results *results)
1420 slot->results = results;
1421 if (!start_active_slot(slot)) {
1422 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1423 "failed to start HTTP request");
1424 return HTTP_START_FAILED;
1427 run_active_slot(slot);
1428 return handle_curl_result(results);
1431 struct curl_slist *http_copy_default_headers(void)
1433 struct curl_slist *headers = NULL, *h;
1435 for (h = extra_http_headers; h; h = h->next)
1436 headers = curl_slist_append(headers, h->data);
1441 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1447 ret = curl_easy_getinfo(curl, info, &ptr);
1449 strbuf_addstr(buf, ptr);
1454 * Check for and extract a content-type parameter. "raw"
1455 * should be positioned at the start of the potential
1456 * parameter, with any whitespace already removed.
1458 * "name" is the name of the parameter. The value is appended
1461 static int extract_param(const char *raw, const char *name,
1464 size_t len = strlen(name);
1466 if (strncasecmp(raw, name, len))
1474 while (*raw && !isspace(*raw) && *raw != ';')
1475 strbuf_addch(out, *raw++);
1480 * Extract a normalized version of the content type, with any
1481 * spaces suppressed, all letters lowercased, and no trailing ";"
1484 * Note that we will silently remove even invalid whitespace. For
1485 * example, "text / plain" is specifically forbidden by RFC 2616,
1486 * but "text/plain" is the only reasonable output, and this keeps
1489 * If the "charset" argument is not NULL, store the value of any
1490 * charset parameter there.
1493 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1494 * "text / plain" -> "text/plain"
1496 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1497 struct strbuf *charset)
1502 strbuf_grow(type, raw->len);
1503 for (p = raw->buf; *p; p++) {
1510 strbuf_addch(type, tolower(*p));
1516 strbuf_reset(charset);
1518 while (isspace(*p) || *p == ';')
1520 if (!extract_param(p, "charset", charset))
1522 while (*p && !isspace(*p))
1526 if (!charset->len && starts_with(type->buf, "text/"))
1527 strbuf_addstr(charset, "ISO-8859-1");
1530 static void write_accept_language(struct strbuf *buf)
1533 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1534 * that, q-value will be smaller than 0.001, the minimum q-value the
1535 * HTTP specification allows. See
1536 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1538 const int MAX_DECIMAL_PLACES = 3;
1539 const int MAX_LANGUAGE_TAGS = 1000;
1540 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1541 char **language_tags = NULL;
1543 const char *s = get_preferred_languages();
1545 struct strbuf tag = STRBUF_INIT;
1547 /* Don't add Accept-Language header if no language is preferred. */
1552 * Split the colon-separated string of preferred languages into
1553 * language_tags array.
1556 /* collect language tag */
1557 for (; *s && (isalnum(*s) || *s == '_'); s++)
1558 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1560 /* skip .codeset, @modifier and any other unnecessary parts */
1561 while (*s && *s != ':')
1566 REALLOC_ARRAY(language_tags, num_langs);
1567 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1568 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1573 /* write Accept-Language header into buf */
1575 int last_buf_len = 0;
1581 REALLOC_ARRAY(language_tags, num_langs + 1);
1582 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1584 /* compute decimal_places */
1585 for (max_q = 1, decimal_places = 0;
1586 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1587 decimal_places++, max_q *= 10)
1590 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1592 strbuf_addstr(buf, "Accept-Language: ");
1594 for (i = 0; i < num_langs; i++) {
1596 strbuf_addstr(buf, ", ");
1598 strbuf_addstr(buf, language_tags[i]);
1601 strbuf_addf(buf, q_format, max_q - i);
1603 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1604 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1608 last_buf_len = buf->len;
1612 /* free language tags -- last one is a static '*' */
1613 for (i = 0; i < num_langs - 1; i++)
1614 free(language_tags[i]);
1615 free(language_tags);
1619 * Get an Accept-Language header which indicates user's preferred languages.
1623 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1624 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1625 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1626 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1627 * LANGUAGE= LANG=C -> ""
1629 static const char *get_accept_language(void)
1631 if (!cached_accept_language) {
1632 struct strbuf buf = STRBUF_INIT;
1633 write_accept_language(&buf);
1635 cached_accept_language = strbuf_detach(&buf, NULL);
1638 return cached_accept_language;
1641 static void http_opt_request_remainder(CURL *curl, off_t pos)
1644 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1645 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1648 /* http_request() targets */
1649 #define HTTP_REQUEST_STRBUF 0
1650 #define HTTP_REQUEST_FILE 1
1652 static int http_request(const char *url,
1653 void *result, int target,
1654 const struct http_get_options *options)
1656 struct active_request_slot *slot;
1657 struct slot_results results;
1658 struct curl_slist *headers = http_copy_default_headers();
1659 struct strbuf buf = STRBUF_INIT;
1660 const char *accept_language;
1663 slot = get_active_slot();
1664 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1666 if (result == NULL) {
1667 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1669 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1670 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1672 if (target == HTTP_REQUEST_FILE) {
1673 off_t posn = ftello(result);
1674 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1677 http_opt_request_remainder(slot->curl, posn);
1679 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1683 accept_language = get_accept_language();
1685 if (accept_language)
1686 headers = curl_slist_append(headers, accept_language);
1688 strbuf_addstr(&buf, "Pragma:");
1689 if (options && options->no_cache)
1690 strbuf_addstr(&buf, " no-cache");
1691 if (options && options->keep_error)
1692 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1693 if (options && options->initial_request &&
1694 http_follow_config == HTTP_FOLLOW_INITIAL)
1695 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1697 headers = curl_slist_append(headers, buf.buf);
1699 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1700 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1701 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1703 ret = run_one_slot(slot, &results);
1705 if (options && options->content_type) {
1706 struct strbuf raw = STRBUF_INIT;
1707 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1708 extract_content_type(&raw, options->content_type,
1710 strbuf_release(&raw);
1713 if (options && options->effective_url)
1714 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1715 options->effective_url);
1717 curl_slist_free_all(headers);
1718 strbuf_release(&buf);
1724 * Update the "base" url to a more appropriate value, as deduced by
1725 * redirects seen when requesting a URL starting with "url".
1727 * The "asked" parameter is a URL that we asked curl to access, and must begin
1730 * The "got" parameter is the URL that curl reported to us as where we ended
1733 * Returns 1 if we updated the base url, 0 otherwise.
1735 * Our basic strategy is to compare "base" and "asked" to find the bits
1736 * specific to our request. We then strip those bits off of "got" to yield the
1737 * new base. So for example, if our base is "http://example.com/foo.git",
1738 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1739 * with "https://other.example.com/foo.git/info/refs". We would want the
1740 * new URL to become "https://other.example.com/foo.git".
1742 * Note that this assumes a sane redirect scheme. It's entirely possible
1743 * in the example above to end up at a URL that does not even end in
1744 * "info/refs". In such a case we die. There's not much we can do, such a
1745 * scheme is unlikely to represent a real git repository, and failing to
1746 * rewrite the base opens options for malicious redirects to do funny things.
1748 static int update_url_from_redirect(struct strbuf *base,
1750 const struct strbuf *got)
1755 if (!strcmp(asked, got->buf))
1758 if (!skip_prefix(asked, base->buf, &tail))
1759 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1763 if (!strip_suffix_mem(got->buf, &new_len, tail))
1764 die(_("unable to update url base from redirection:\n"
1770 strbuf_add(base, got->buf, new_len);
1775 static int http_request_reauth(const char *url,
1776 void *result, int target,
1777 struct http_get_options *options)
1779 int ret = http_request(url, result, target, options);
1781 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1784 if (options && options->effective_url && options->base_url) {
1785 if (update_url_from_redirect(options->base_url,
1786 url, options->effective_url)) {
1787 credential_from_url(&http_auth, options->base_url->buf);
1788 url = options->effective_url->buf;
1792 if (ret != HTTP_REAUTH)
1796 * If we are using KEEP_ERROR, the previous request may have
1797 * put cruft into our output stream; we should clear it out before
1798 * making our next request. We only know how to do this for
1799 * the strbuf case, but that is enough to satisfy current callers.
1801 if (options && options->keep_error) {
1803 case HTTP_REQUEST_STRBUF:
1804 strbuf_reset(result);
1807 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1811 credential_fill(&http_auth);
1813 return http_request(url, result, target, options);
1816 int http_get_strbuf(const char *url,
1817 struct strbuf *result,
1818 struct http_get_options *options)
1820 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1824 * Downloads a URL and stores the result in the given file.
1826 * If a previous interrupted download is detected (i.e. a previous temporary
1827 * file is still around) the download is resumed.
1829 static int http_get_file(const char *url, const char *filename,
1830 struct http_get_options *options)
1833 struct strbuf tmpfile = STRBUF_INIT;
1836 strbuf_addf(&tmpfile, "%s.temp", filename);
1837 result = fopen(tmpfile.buf, "a");
1839 error("Unable to open local file %s", tmpfile.buf);
1844 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1847 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1850 strbuf_release(&tmpfile);
1854 int http_fetch_ref(const char *base, struct ref *ref)
1856 struct http_get_options options = {0};
1858 struct strbuf buffer = STRBUF_INIT;
1861 options.no_cache = 1;
1863 url = quote_ref_url(base, ref->name);
1864 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1865 strbuf_rtrim(&buffer);
1866 if (buffer.len == 40)
1867 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1868 else if (starts_with(buffer.buf, "ref: ")) {
1869 ref->symref = xstrdup(buffer.buf + 5);
1874 strbuf_release(&buffer);
1879 /* Helpers for fetching packs */
1880 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1883 struct strbuf buf = STRBUF_INIT;
1885 if (http_is_verbose)
1886 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1888 end_url_with_slash(&buf, base_url);
1889 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1890 url = strbuf_detach(&buf, NULL);
1892 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1893 tmp = strbuf_detach(&buf, NULL);
1895 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1896 error("Unable to get pack index %s", url);
1905 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1906 unsigned char *sha1, const char *base_url)
1908 struct packed_git *new_pack;
1909 char *tmp_idx = NULL;
1912 if (has_pack_index(sha1)) {
1913 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1915 return -1; /* parse_pack_index() already issued error message */
1919 tmp_idx = fetch_pack_index(sha1, base_url);
1923 new_pack = parse_pack_index(sha1, tmp_idx);
1928 return -1; /* parse_pack_index() already issued error message */
1931 ret = verify_pack_index(new_pack);
1933 close_pack_index(new_pack);
1934 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1941 new_pack->next = *packs_head;
1942 *packs_head = new_pack;
1946 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1948 struct http_get_options options = {0};
1951 struct strbuf buf = STRBUF_INIT;
1952 unsigned char sha1[20];
1954 end_url_with_slash(&buf, base_url);
1955 strbuf_addstr(&buf, "objects/info/packs");
1956 url = strbuf_detach(&buf, NULL);
1958 options.no_cache = 1;
1959 ret = http_get_strbuf(url, &buf, &options);
1964 while (i < buf.len) {
1968 if (i + 52 <= buf.len &&
1969 starts_with(data + i, " pack-") &&
1970 starts_with(data + i + 46, ".pack\n")) {
1971 get_sha1_hex(data + i + 6, sha1);
1972 fetch_and_setup_pack_index(packs_head, sha1,
1978 while (i < buf.len && data[i] != '\n')
1989 void release_http_pack_request(struct http_pack_request *preq)
1991 if (preq->packfile != NULL) {
1992 fclose(preq->packfile);
1993 preq->packfile = NULL;
2000 int finish_http_pack_request(struct http_pack_request *preq)
2002 struct packed_git **lst;
2003 struct packed_git *p = preq->target;
2006 struct child_process ip = CHILD_PROCESS_INIT;
2007 const char *ip_argv[8];
2009 close_pack_index(p);
2011 fclose(preq->packfile);
2012 preq->packfile = NULL;
2016 lst = &((*lst)->next);
2017 *lst = (*lst)->next;
2019 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2020 die("BUG: pack tmpfile does not end in .pack.temp?");
2021 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
2023 ip_argv[0] = "index-pack";
2025 ip_argv[2] = tmp_idx;
2026 ip_argv[3] = preq->tmpfile;
2034 if (run_command(&ip)) {
2035 unlink(preq->tmpfile);
2041 unlink(sha1_pack_index_name(p->sha1));
2043 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2044 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2049 install_packed_git(p);
2054 struct http_pack_request *new_http_pack_request(
2055 struct packed_git *target, const char *base_url)
2057 off_t prev_posn = 0;
2058 struct strbuf buf = STRBUF_INIT;
2059 struct http_pack_request *preq;
2061 preq = xcalloc(1, sizeof(*preq));
2062 preq->target = target;
2064 end_url_with_slash(&buf, base_url);
2065 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2066 sha1_to_hex(target->sha1));
2067 preq->url = strbuf_detach(&buf, NULL);
2069 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2070 sha1_pack_name(target->sha1));
2071 preq->packfile = fopen(preq->tmpfile, "a");
2072 if (!preq->packfile) {
2073 error("Unable to open local file %s for pack",
2078 preq->slot = get_active_slot();
2079 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2080 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2081 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2082 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2086 * If there is data present from a previous transfer attempt,
2087 * resume where it left off
2089 prev_posn = ftello(preq->packfile);
2091 if (http_is_verbose)
2093 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2094 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2095 http_opt_request_remainder(preq->slot->curl, prev_posn);
2106 /* Helpers for fetching objects (loose) */
2107 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2110 unsigned char expn[4096];
2111 size_t size = eltsize * nmemb;
2113 struct http_object_request *freq = data;
2114 struct active_request_slot *slot = freq->slot;
2117 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2120 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2121 curl_easy_strerror(c));
2122 if (slot->http_code >= 300)
2127 ssize_t retval = xwrite(freq->localfile,
2128 (char *) ptr + posn, size - posn);
2132 } while (posn < size);
2134 freq->stream.avail_in = size;
2135 freq->stream.next_in = (void *)ptr;
2137 freq->stream.next_out = expn;
2138 freq->stream.avail_out = sizeof(expn);
2139 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2140 git_SHA1_Update(&freq->c, expn,
2141 sizeof(expn) - freq->stream.avail_out);
2142 } while (freq->stream.avail_in && freq->zret == Z_OK);
2146 struct http_object_request *new_http_object_request(const char *base_url,
2147 unsigned char *sha1)
2149 char *hex = sha1_to_hex(sha1);
2150 const char *filename;
2151 char prevfile[PATH_MAX];
2153 char prev_buf[PREV_BUF_SIZE];
2154 ssize_t prev_read = 0;
2155 off_t prev_posn = 0;
2156 struct http_object_request *freq;
2158 freq = xcalloc(1, sizeof(*freq));
2159 hashcpy(freq->sha1, sha1);
2160 freq->localfile = -1;
2162 filename = sha1_file_name(sha1);
2163 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2164 "%s.temp", filename);
2166 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2167 unlink_or_warn(prevfile);
2168 rename(freq->tmpfile, prevfile);
2169 unlink_or_warn(freq->tmpfile);
2171 if (freq->localfile != -1)
2172 error("fd leakage in start: %d", freq->localfile);
2173 freq->localfile = open(freq->tmpfile,
2174 O_WRONLY | O_CREAT | O_EXCL, 0666);
2176 * This could have failed due to the "lazy directory creation";
2177 * try to mkdir the last path component.
2179 if (freq->localfile < 0 && errno == ENOENT) {
2180 char *dir = strrchr(freq->tmpfile, '/');
2183 mkdir(freq->tmpfile, 0777);
2186 freq->localfile = open(freq->tmpfile,
2187 O_WRONLY | O_CREAT | O_EXCL, 0666);
2190 if (freq->localfile < 0) {
2191 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2195 git_inflate_init(&freq->stream);
2197 git_SHA1_Init(&freq->c);
2199 freq->url = get_remote_object_url(base_url, hex, 0);
2202 * If a previous temp file is present, process what was already
2205 prevlocal = open(prevfile, O_RDONLY);
2206 if (prevlocal != -1) {
2208 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2210 if (fwrite_sha1_file(prev_buf,
2213 freq) == prev_read) {
2214 prev_posn += prev_read;
2219 } while (prev_read > 0);
2222 unlink_or_warn(prevfile);
2225 * Reset inflate/SHA1 if there was an error reading the previous temp
2226 * file; also rewind to the beginning of the local file.
2228 if (prev_read == -1) {
2229 memset(&freq->stream, 0, sizeof(freq->stream));
2230 git_inflate_init(&freq->stream);
2231 git_SHA1_Init(&freq->c);
2234 lseek(freq->localfile, 0, SEEK_SET);
2235 if (ftruncate(freq->localfile, 0) < 0) {
2236 error_errno("Couldn't truncate temporary file %s",
2243 freq->slot = get_active_slot();
2245 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2246 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2247 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2248 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2249 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2250 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2253 * If we have successfully processed data from a previous fetch
2254 * attempt, only fetch the data we don't already have.
2257 if (http_is_verbose)
2259 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2260 hex, (uintmax_t)prev_posn);
2261 http_opt_request_remainder(freq->slot->curl, prev_posn);
2272 void process_http_object_request(struct http_object_request *freq)
2274 if (freq->slot == NULL)
2276 freq->curl_result = freq->slot->curl_result;
2277 freq->http_code = freq->slot->http_code;
2281 int finish_http_object_request(struct http_object_request *freq)
2285 close(freq->localfile);
2286 freq->localfile = -1;
2288 process_http_object_request(freq);
2290 if (freq->http_code == 416) {
2291 warning("requested range invalid; we may already have all the data.");
2292 } else if (freq->curl_result != CURLE_OK) {
2293 if (stat(freq->tmpfile, &st) == 0)
2294 if (st.st_size == 0)
2295 unlink_or_warn(freq->tmpfile);
2299 git_inflate_end(&freq->stream);
2300 git_SHA1_Final(freq->real_sha1, &freq->c);
2301 if (freq->zret != Z_STREAM_END) {
2302 unlink_or_warn(freq->tmpfile);
2305 if (hashcmp(freq->sha1, freq->real_sha1)) {
2306 unlink_or_warn(freq->tmpfile);
2310 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2312 return freq->rename;
2315 void abort_http_object_request(struct http_object_request *freq)
2317 unlink_or_warn(freq->tmpfile);
2319 release_http_object_request(freq);
2322 void release_http_object_request(struct http_object_request *freq)
2324 if (freq->localfile != -1) {
2325 close(freq->localfile);
2326 freq->localfile = -1;
2328 if (freq->url != NULL) {
2332 if (freq->slot != NULL) {
2333 freq->slot->callback_func = NULL;
2334 freq->slot->callback_data = NULL;
2335 release_active_slot(freq->slot);