1 #include "git-compat-util.h"
6 #include "run-command.h"
9 #include "credential.h"
13 #include "transport.h"
16 #include "string-list.h"
17 #include "object-store.h"
19 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
20 static int trace_curl_data = 1;
21 static struct string_list cookies_to_redact = STRING_LIST_INIT_DUP;
22 #if LIBCURL_VERSION_NUM >= 0x070a08
23 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
25 long int git_curl_ipresolve;
29 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
31 #if LIBCURL_VERSION_NUM >= 0x070a06
32 #define LIBCURL_CAN_HANDLE_AUTH_ANY
35 static int min_curl_sessions = 1;
36 static int curl_session_count;
38 static int max_requests = -1;
41 #ifndef NO_CURL_EASY_DUPHANDLE
42 static CURL *curl_default;
45 #define PREV_BUF_SIZE 4096
47 char curl_errorstr[CURL_ERROR_SIZE];
49 static int curl_ssl_verify = -1;
50 static int curl_ssl_try;
51 static const char *ssl_cert;
52 static const char *ssl_cipherlist;
53 static const char *ssl_version;
58 { "sslv2", CURL_SSLVERSION_SSLv2 },
59 { "sslv3", CURL_SSLVERSION_SSLv3 },
60 { "tlsv1", CURL_SSLVERSION_TLSv1 },
61 #if LIBCURL_VERSION_NUM >= 0x072200
62 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
63 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
64 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
67 #if LIBCURL_VERSION_NUM >= 0x070903
68 static const char *ssl_key;
70 #if LIBCURL_VERSION_NUM >= 0x070908
71 static const char *ssl_capath;
73 #if LIBCURL_VERSION_NUM >= 0x071304
74 static const char *curl_no_proxy;
76 #if LIBCURL_VERSION_NUM >= 0x072c00
77 static const char *ssl_pinnedkey;
79 static const char *ssl_cainfo;
80 static long curl_low_speed_limit = -1;
81 static long curl_low_speed_time = -1;
82 static int curl_ftp_no_epsv;
83 static const char *curl_http_proxy;
84 static const char *http_proxy_authmethod;
88 } proxy_authmethods[] = {
89 { "basic", CURLAUTH_BASIC },
90 { "digest", CURLAUTH_DIGEST },
91 { "negotiate", CURLAUTH_GSSNEGOTIATE },
92 { "ntlm", CURLAUTH_NTLM },
93 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
94 { "anyauth", CURLAUTH_ANY },
97 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
98 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
102 #ifdef CURLGSSAPI_DELEGATION_FLAG
103 static const char *curl_deleg;
106 long curl_deleg_param;
107 } curl_deleg_levels[] = {
108 { "none", CURLGSSAPI_DELEGATION_NONE },
109 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
110 { "always", CURLGSSAPI_DELEGATION_FLAG },
114 static struct credential proxy_auth = CREDENTIAL_INIT;
115 static const char *curl_proxyuserpwd;
116 static const char *curl_cookie_file;
117 static int curl_save_cookies;
118 struct credential http_auth = CREDENTIAL_INIT;
119 static int http_proactive_auth;
120 static const char *user_agent;
121 static int curl_empty_auth = -1;
123 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
125 #if LIBCURL_VERSION_NUM >= 0x071700
126 /* Use CURLOPT_KEYPASSWD as is */
127 #elif LIBCURL_VERSION_NUM >= 0x070903
128 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
130 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
133 static struct credential cert_auth = CREDENTIAL_INIT;
134 static int ssl_cert_password_required;
135 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
136 static unsigned long http_auth_methods = CURLAUTH_ANY;
137 static int http_auth_methods_restricted;
138 /* Modes for which empty_auth cannot actually help us. */
139 static unsigned long empty_auth_useless =
141 #ifdef CURLAUTH_DIGEST_IE
147 static struct curl_slist *pragma_header;
148 static struct curl_slist *no_pragma_header;
149 static struct curl_slist *extra_http_headers;
151 static struct active_request_slot *active_queue_head;
153 static char *cached_accept_language;
155 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
157 size_t size = eltsize * nmemb;
158 struct buffer *buffer = buffer_;
160 if (size > buffer->buf.len - buffer->posn)
161 size = buffer->buf.len - buffer->posn;
162 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
163 buffer->posn += size;
168 #ifndef NO_CURL_IOCTL
169 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
171 struct buffer *buffer = clientp;
177 case CURLIOCMD_RESTARTREAD:
182 return CURLIOE_UNKNOWNCMD;
187 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
189 size_t size = eltsize * nmemb;
190 struct strbuf *buffer = buffer_;
192 strbuf_add(buffer, ptr, size);
196 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
198 return eltsize * nmemb;
201 static void closedown_active_slot(struct active_request_slot *slot)
207 static void finish_active_slot(struct active_request_slot *slot)
209 closedown_active_slot(slot);
210 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
212 if (slot->finished != NULL)
213 (*slot->finished) = 1;
215 /* Store slot results so they can be read after the slot is reused */
216 if (slot->results != NULL) {
217 slot->results->curl_result = slot->curl_result;
218 slot->results->http_code = slot->http_code;
219 #if LIBCURL_VERSION_NUM >= 0x070a08
220 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
221 &slot->results->auth_avail);
223 slot->results->auth_avail = 0;
226 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
227 &slot->results->http_connectcode);
230 /* Run callback if appropriate */
231 if (slot->callback_func != NULL)
232 slot->callback_func(slot->callback_data);
235 static void xmulti_remove_handle(struct active_request_slot *slot)
237 #ifdef USE_CURL_MULTI
238 curl_multi_remove_handle(curlm, slot->curl);
242 #ifdef USE_CURL_MULTI
243 static void process_curl_messages(void)
246 struct active_request_slot *slot;
247 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
249 while (curl_message != NULL) {
250 if (curl_message->msg == CURLMSG_DONE) {
251 int curl_result = curl_message->data.result;
252 slot = active_queue_head;
253 while (slot != NULL &&
254 slot->curl != curl_message->easy_handle)
257 xmulti_remove_handle(slot);
258 slot->curl_result = curl_result;
259 finish_active_slot(slot);
261 fprintf(stderr, "Received DONE message for unknown request!\n");
264 fprintf(stderr, "Unknown CURL message received: %d\n",
265 (int)curl_message->msg);
267 curl_message = curl_multi_info_read(curlm, &num_messages);
272 static int http_options(const char *var, const char *value, void *cb)
274 if (!strcmp("http.sslverify", var)) {
275 curl_ssl_verify = git_config_bool(var, value);
278 if (!strcmp("http.sslcipherlist", var))
279 return git_config_string(&ssl_cipherlist, var, value);
280 if (!strcmp("http.sslversion", var))
281 return git_config_string(&ssl_version, var, value);
282 if (!strcmp("http.sslcert", var))
283 return git_config_pathname(&ssl_cert, var, value);
284 #if LIBCURL_VERSION_NUM >= 0x070903
285 if (!strcmp("http.sslkey", var))
286 return git_config_pathname(&ssl_key, var, value);
288 #if LIBCURL_VERSION_NUM >= 0x070908
289 if (!strcmp("http.sslcapath", var))
290 return git_config_pathname(&ssl_capath, var, value);
292 if (!strcmp("http.sslcainfo", var))
293 return git_config_pathname(&ssl_cainfo, var, value);
294 if (!strcmp("http.sslcertpasswordprotected", var)) {
295 ssl_cert_password_required = git_config_bool(var, value);
298 if (!strcmp("http.ssltry", var)) {
299 curl_ssl_try = git_config_bool(var, value);
302 if (!strcmp("http.minsessions", var)) {
303 min_curl_sessions = git_config_int(var, value);
304 #ifndef USE_CURL_MULTI
305 if (min_curl_sessions > 1)
306 min_curl_sessions = 1;
310 #ifdef USE_CURL_MULTI
311 if (!strcmp("http.maxrequests", var)) {
312 max_requests = git_config_int(var, value);
316 if (!strcmp("http.lowspeedlimit", var)) {
317 curl_low_speed_limit = (long)git_config_int(var, value);
320 if (!strcmp("http.lowspeedtime", var)) {
321 curl_low_speed_time = (long)git_config_int(var, value);
325 if (!strcmp("http.noepsv", var)) {
326 curl_ftp_no_epsv = git_config_bool(var, value);
329 if (!strcmp("http.proxy", var))
330 return git_config_string(&curl_http_proxy, var, value);
332 if (!strcmp("http.proxyauthmethod", var))
333 return git_config_string(&http_proxy_authmethod, var, value);
335 if (!strcmp("http.cookiefile", var))
336 return git_config_pathname(&curl_cookie_file, var, value);
337 if (!strcmp("http.savecookies", var)) {
338 curl_save_cookies = git_config_bool(var, value);
342 if (!strcmp("http.postbuffer", var)) {
343 http_post_buffer = git_config_ssize_t(var, value);
344 if (http_post_buffer < 0)
345 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
346 if (http_post_buffer < LARGE_PACKET_MAX)
347 http_post_buffer = LARGE_PACKET_MAX;
351 if (!strcmp("http.useragent", var))
352 return git_config_string(&user_agent, var, value);
354 if (!strcmp("http.emptyauth", var)) {
355 if (value && !strcmp("auto", value))
356 curl_empty_auth = -1;
358 curl_empty_auth = git_config_bool(var, value);
362 if (!strcmp("http.delegation", var)) {
363 #ifdef CURLGSSAPI_DELEGATION_FLAG
364 return git_config_string(&curl_deleg, var, value);
366 warning(_("Delegation control is not supported with cURL < 7.22.0"));
371 if (!strcmp("http.pinnedpubkey", var)) {
372 #if LIBCURL_VERSION_NUM >= 0x072c00
373 return git_config_pathname(&ssl_pinnedkey, var, value);
375 warning(_("Public key pinning not supported with cURL < 7.44.0"));
380 if (!strcmp("http.extraheader", var)) {
382 return config_error_nonbool(var);
383 } else if (!*value) {
384 curl_slist_free_all(extra_http_headers);
385 extra_http_headers = NULL;
388 curl_slist_append(extra_http_headers, value);
393 if (!strcmp("http.followredirects", var)) {
394 if (value && !strcmp(value, "initial"))
395 http_follow_config = HTTP_FOLLOW_INITIAL;
396 else if (git_config_bool(var, value))
397 http_follow_config = HTTP_FOLLOW_ALWAYS;
399 http_follow_config = HTTP_FOLLOW_NONE;
403 /* Fall back on the default ones */
404 return git_default_config(var, value, cb);
407 static int curl_empty_auth_enabled(void)
409 if (curl_empty_auth >= 0)
410 return curl_empty_auth;
412 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
414 * Our libcurl is too old to do AUTH_ANY in the first place;
415 * just default to turning the feature off.
419 * In the automatic case, kick in the empty-auth
420 * hack as long as we would potentially try some
421 * method more exotic than "Basic" or "Digest".
423 * But only do this when this is our second or
424 * subsequent request, as by then we know what
425 * methods are available.
427 if (http_auth_methods_restricted &&
428 (http_auth_methods & ~empty_auth_useless))
434 static void init_curl_http_auth(CURL *result)
436 if (!http_auth.username || !*http_auth.username) {
437 if (curl_empty_auth_enabled())
438 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
442 credential_fill(&http_auth);
444 #if LIBCURL_VERSION_NUM >= 0x071301
445 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
446 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
449 static struct strbuf up = STRBUF_INIT;
451 * Note that we assume we only ever have a single set of
452 * credentials in a given program run, so we do not have
453 * to worry about updating this buffer, only setting its
457 strbuf_addf(&up, "%s:%s",
458 http_auth.username, http_auth.password);
459 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
464 /* *var must be free-able */
465 static void var_override(const char **var, char *value)
469 *var = xstrdup(value);
473 static void set_proxyauth_name_password(CURL *result)
475 #if LIBCURL_VERSION_NUM >= 0x071301
476 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
477 proxy_auth.username);
478 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
479 proxy_auth.password);
481 struct strbuf s = STRBUF_INIT;
483 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
484 strbuf_addch(&s, ':');
485 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
486 curl_proxyuserpwd = strbuf_detach(&s, NULL);
487 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
491 static void init_curl_proxy_auth(CURL *result)
493 if (proxy_auth.username) {
494 if (!proxy_auth.password)
495 credential_fill(&proxy_auth);
496 set_proxyauth_name_password(result);
499 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
501 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
502 if (http_proxy_authmethod) {
504 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
505 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
506 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
507 proxy_authmethods[i].curlauth_param);
511 if (i == ARRAY_SIZE(proxy_authmethods)) {
512 warning("unsupported proxy authentication method %s: using anyauth",
513 http_proxy_authmethod);
514 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
518 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
522 static int has_cert_password(void)
524 if (ssl_cert == NULL || ssl_cert_password_required != 1)
526 if (!cert_auth.password) {
527 cert_auth.protocol = xstrdup("cert");
528 cert_auth.username = xstrdup("");
529 cert_auth.path = xstrdup(ssl_cert);
530 credential_fill(&cert_auth);
535 #if LIBCURL_VERSION_NUM >= 0x071900
536 static void set_curl_keepalive(CURL *c)
538 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
541 #elif LIBCURL_VERSION_NUM >= 0x071000
542 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
546 socklen_t len = (socklen_t)sizeof(ka);
548 if (type != CURLSOCKTYPE_IPCXN)
551 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
553 warning_errno("unable to set SO_KEEPALIVE on socket");
555 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
558 static void set_curl_keepalive(CURL *c)
560 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
564 static void set_curl_keepalive(CURL *c)
566 /* not supported on older curl versions */
570 static void redact_sensitive_header(struct strbuf *header)
572 const char *sensitive_header;
574 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
575 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
576 /* The first token is the type, which is OK to log */
577 while (isspace(*sensitive_header))
579 while (*sensitive_header && !isspace(*sensitive_header))
581 /* Everything else is opaque and possibly sensitive */
582 strbuf_setlen(header, sensitive_header - header->buf);
583 strbuf_addstr(header, " <redacted>");
584 } else if (cookies_to_redact.nr &&
585 skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
586 struct strbuf redacted_header = STRBUF_INIT;
589 while (isspace(*sensitive_header))
593 * The contents of header starting from sensitive_header will
594 * subsequently be overridden, so it is fine to mutate this
595 * string (hence the assignment to "char *").
597 cookie = (char *) sensitive_header;
601 char *semicolon = strstr(cookie, "; ");
604 equals = strchrnul(cookie, '=');
606 /* invalid cookie, just append and continue */
607 strbuf_addstr(&redacted_header, cookie);
610 *equals = 0; /* temporarily set to NUL for lookup */
611 if (string_list_lookup(&cookies_to_redact, cookie)) {
612 strbuf_addstr(&redacted_header, cookie);
613 strbuf_addstr(&redacted_header, "=<redacted>");
616 strbuf_addstr(&redacted_header, cookie);
620 * There are more cookies. (Or, for some
621 * reason, the input string ends in "; ".)
623 strbuf_addstr(&redacted_header, "; ");
624 cookie = semicolon + strlen("; ");
630 strbuf_setlen(header, sensitive_header - header->buf);
631 strbuf_addbuf(header, &redacted_header);
635 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
637 struct strbuf out = STRBUF_INIT;
638 struct strbuf **headers, **header;
640 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
641 text, (long)size, (long)size);
642 trace_strbuf(&trace_curl, &out);
644 strbuf_add(&out, ptr, size);
645 headers = strbuf_split_max(&out, '\n', 0);
647 for (header = headers; *header; header++) {
648 if (hide_sensitive_header)
649 redact_sensitive_header(*header);
650 strbuf_insert((*header), 0, text, strlen(text));
651 strbuf_insert((*header), strlen(text), ": ", 2);
652 strbuf_rtrim((*header));
653 strbuf_addch((*header), '\n');
654 trace_strbuf(&trace_curl, (*header));
656 strbuf_list_free(headers);
657 strbuf_release(&out);
660 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
663 struct strbuf out = STRBUF_INIT;
664 unsigned int width = 60;
666 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
667 text, (long)size, (long)size);
668 trace_strbuf(&trace_curl, &out);
670 for (i = 0; i < size; i += width) {
674 strbuf_addf(&out, "%s: ", text);
675 for (w = 0; (w < width) && (i + w < size); w++) {
676 unsigned char ch = ptr[i + w];
679 (ch >= 0x20) && (ch < 0x80)
682 strbuf_addch(&out, '\n');
683 trace_strbuf(&trace_curl, &out);
685 strbuf_release(&out);
688 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
691 enum { NO_FILTER = 0, DO_FILTER = 1 };
695 trace_printf_key(&trace_curl, "== Info: %s", data);
697 case CURLINFO_HEADER_OUT:
698 text = "=> Send header";
699 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
701 case CURLINFO_DATA_OUT:
702 if (trace_curl_data) {
703 text = "=> Send data";
704 curl_dump_data(text, (unsigned char *)data, size);
707 case CURLINFO_SSL_DATA_OUT:
708 if (trace_curl_data) {
709 text = "=> Send SSL data";
710 curl_dump_data(text, (unsigned char *)data, size);
713 case CURLINFO_HEADER_IN:
714 text = "<= Recv header";
715 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
717 case CURLINFO_DATA_IN:
718 if (trace_curl_data) {
719 text = "<= Recv data";
720 curl_dump_data(text, (unsigned char *)data, size);
723 case CURLINFO_SSL_DATA_IN:
724 if (trace_curl_data) {
725 text = "<= Recv SSL data";
726 curl_dump_data(text, (unsigned char *)data, size);
730 default: /* we ignore unknown types by default */
736 void setup_curl_trace(CURL *handle)
738 if (!trace_want(&trace_curl))
740 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
741 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
742 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
745 #ifdef CURLPROTO_HTTP
746 static long get_curl_allowed_protocols(int from_user)
748 long allowed_protocols = 0;
750 if (is_transport_allowed("http", from_user))
751 allowed_protocols |= CURLPROTO_HTTP;
752 if (is_transport_allowed("https", from_user))
753 allowed_protocols |= CURLPROTO_HTTPS;
754 if (is_transport_allowed("ftp", from_user))
755 allowed_protocols |= CURLPROTO_FTP;
756 if (is_transport_allowed("ftps", from_user))
757 allowed_protocols |= CURLPROTO_FTPS;
759 return allowed_protocols;
763 static CURL *get_curl_handle(void)
765 CURL *result = curl_easy_init();
768 die("curl_easy_init failed");
770 if (!curl_ssl_verify) {
771 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
772 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
774 /* Verify authenticity of the peer's certificate */
775 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
776 /* The name in the cert must match whom we tried to connect */
777 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
780 #if LIBCURL_VERSION_NUM >= 0x070907
781 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
783 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
784 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
787 #ifdef CURLGSSAPI_DELEGATION_FLAG
790 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
791 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
792 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
793 curl_deleg_levels[i].curl_deleg_param);
797 if (i == ARRAY_SIZE(curl_deleg_levels))
798 warning("Unknown delegation method '%s': using default",
803 if (http_proactive_auth)
804 init_curl_http_auth(result);
806 if (getenv("GIT_SSL_VERSION"))
807 ssl_version = getenv("GIT_SSL_VERSION");
808 if (ssl_version && *ssl_version) {
810 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
811 if (!strcmp(ssl_version, sslversions[i].name)) {
812 curl_easy_setopt(result, CURLOPT_SSLVERSION,
813 sslversions[i].ssl_version);
817 if (i == ARRAY_SIZE(sslversions))
818 warning("unsupported ssl version %s: using default",
822 if (getenv("GIT_SSL_CIPHER_LIST"))
823 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
824 if (ssl_cipherlist != NULL && *ssl_cipherlist)
825 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
828 if (ssl_cert != NULL)
829 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
830 if (has_cert_password())
831 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
832 #if LIBCURL_VERSION_NUM >= 0x070903
834 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
836 #if LIBCURL_VERSION_NUM >= 0x070908
837 if (ssl_capath != NULL)
838 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
840 #if LIBCURL_VERSION_NUM >= 0x072c00
841 if (ssl_pinnedkey != NULL)
842 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
844 if (ssl_cainfo != NULL)
845 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
847 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
848 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
849 curl_low_speed_limit);
850 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
851 curl_low_speed_time);
854 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
855 #if LIBCURL_VERSION_NUM >= 0x071301
856 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
857 #elif LIBCURL_VERSION_NUM >= 0x071101
858 curl_easy_setopt(result, CURLOPT_POST301, 1);
860 #ifdef CURLPROTO_HTTP
861 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
862 get_curl_allowed_protocols(0));
863 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
864 get_curl_allowed_protocols(-1));
866 warning("protocol restrictions not applied to curl redirects because\n"
867 "your curl version is too old (>= 7.19.4)");
869 if (getenv("GIT_CURL_VERBOSE"))
870 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
871 setup_curl_trace(result);
872 if (getenv("GIT_TRACE_CURL_NO_DATA"))
874 if (getenv("GIT_REDACT_COOKIES")) {
875 string_list_split(&cookies_to_redact,
876 getenv("GIT_REDACT_COOKIES"), ',', -1);
877 string_list_sort(&cookies_to_redact);
880 curl_easy_setopt(result, CURLOPT_USERAGENT,
881 user_agent ? user_agent : git_user_agent());
883 if (curl_ftp_no_epsv)
884 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
886 #ifdef CURLOPT_USE_SSL
888 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
892 * CURL also examines these variables as a fallback; but we need to query
893 * them here in order to decide whether to prompt for missing password (cf.
894 * init_curl_proxy_auth()).
896 * Unlike many other common environment variables, these are historically
897 * lowercase only. It appears that CURL did not know this and implemented
898 * only uppercase variants, which was later corrected to take both - with
899 * the exception of http_proxy, which is lowercase only also in CURL. As
900 * the lowercase versions are the historical quasi-standard, they take
901 * precedence here, as in CURL.
903 if (!curl_http_proxy) {
904 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
905 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
906 var_override(&curl_http_proxy, getenv("https_proxy"));
908 var_override(&curl_http_proxy, getenv("http_proxy"));
910 if (!curl_http_proxy) {
911 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
912 var_override(&curl_http_proxy, getenv("all_proxy"));
916 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
918 * Handle case with the empty http.proxy value here to keep
920 * NB: empty option disables proxying at all.
922 curl_easy_setopt(result, CURLOPT_PROXY, "");
923 } else if (curl_http_proxy) {
924 #if LIBCURL_VERSION_NUM >= 0x071800
925 if (starts_with(curl_http_proxy, "socks5h"))
926 curl_easy_setopt(result,
927 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
928 else if (starts_with(curl_http_proxy, "socks5"))
929 curl_easy_setopt(result,
930 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
931 else if (starts_with(curl_http_proxy, "socks4a"))
932 curl_easy_setopt(result,
933 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
934 else if (starts_with(curl_http_proxy, "socks"))
935 curl_easy_setopt(result,
936 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
938 #if LIBCURL_VERSION_NUM >= 0x073400
939 else if (starts_with(curl_http_proxy, "https"))
940 curl_easy_setopt(result,
941 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
943 if (strstr(curl_http_proxy, "://"))
944 credential_from_url(&proxy_auth, curl_http_proxy);
946 struct strbuf url = STRBUF_INIT;
947 strbuf_addf(&url, "http://%s", curl_http_proxy);
948 credential_from_url(&proxy_auth, url.buf);
949 strbuf_release(&url);
952 if (!proxy_auth.host)
953 die("Invalid proxy URL '%s'", curl_http_proxy);
955 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
956 #if LIBCURL_VERSION_NUM >= 0x071304
957 var_override(&curl_no_proxy, getenv("NO_PROXY"));
958 var_override(&curl_no_proxy, getenv("no_proxy"));
959 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
962 init_curl_proxy_auth(result);
964 set_curl_keepalive(result);
969 static void set_from_env(const char **var, const char *envname)
971 const char *val = getenv(envname);
976 static void protocol_http_header(void)
978 if (get_protocol_version_config() > 0) {
979 struct strbuf protocol_header = STRBUF_INIT;
981 strbuf_addf(&protocol_header, GIT_PROTOCOL_HEADER ": version=%d",
982 get_protocol_version_config());
985 extra_http_headers = curl_slist_append(extra_http_headers,
986 protocol_header.buf);
987 strbuf_release(&protocol_header);
991 void http_init(struct remote *remote, const char *url, int proactive_auth)
993 char *low_speed_limit;
994 char *low_speed_time;
995 char *normalized_url;
996 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
998 config.section = "http";
1000 config.collect_fn = http_options;
1001 config.cascade_fn = git_default_config;
1004 http_is_verbose = 0;
1005 normalized_url = url_normalize(url, &config.url);
1007 git_config(urlmatch_config_entry, &config);
1008 free(normalized_url);
1010 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1011 die("curl_global_init failed");
1013 http_proactive_auth = proactive_auth;
1015 if (remote && remote->http_proxy)
1016 curl_http_proxy = xstrdup(remote->http_proxy);
1019 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1021 protocol_http_header();
1023 pragma_header = curl_slist_append(http_copy_default_headers(),
1024 "Pragma: no-cache");
1025 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1028 #ifdef USE_CURL_MULTI
1030 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1031 if (http_max_requests != NULL)
1032 max_requests = atoi(http_max_requests);
1035 curlm = curl_multi_init();
1037 die("curl_multi_init failed");
1040 if (getenv("GIT_SSL_NO_VERIFY"))
1041 curl_ssl_verify = 0;
1043 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1044 #if LIBCURL_VERSION_NUM >= 0x070903
1045 set_from_env(&ssl_key, "GIT_SSL_KEY");
1047 #if LIBCURL_VERSION_NUM >= 0x070908
1048 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1050 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1052 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1054 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1055 if (low_speed_limit != NULL)
1056 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1057 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1058 if (low_speed_time != NULL)
1059 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1061 if (curl_ssl_verify == -1)
1062 curl_ssl_verify = 1;
1064 curl_session_count = 0;
1065 #ifdef USE_CURL_MULTI
1066 if (max_requests < 1)
1067 max_requests = DEFAULT_MAX_REQUESTS;
1070 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1071 curl_ftp_no_epsv = 1;
1074 credential_from_url(&http_auth, url);
1075 if (!ssl_cert_password_required &&
1076 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1077 starts_with(url, "https://"))
1078 ssl_cert_password_required = 1;
1081 #ifndef NO_CURL_EASY_DUPHANDLE
1082 curl_default = get_curl_handle();
1086 void http_cleanup(void)
1088 struct active_request_slot *slot = active_queue_head;
1090 while (slot != NULL) {
1091 struct active_request_slot *next = slot->next;
1092 if (slot->curl != NULL) {
1093 xmulti_remove_handle(slot);
1094 curl_easy_cleanup(slot->curl);
1099 active_queue_head = NULL;
1101 #ifndef NO_CURL_EASY_DUPHANDLE
1102 curl_easy_cleanup(curl_default);
1105 #ifdef USE_CURL_MULTI
1106 curl_multi_cleanup(curlm);
1108 curl_global_cleanup();
1110 curl_slist_free_all(extra_http_headers);
1111 extra_http_headers = NULL;
1113 curl_slist_free_all(pragma_header);
1114 pragma_header = NULL;
1116 curl_slist_free_all(no_pragma_header);
1117 no_pragma_header = NULL;
1119 if (curl_http_proxy) {
1120 free((void *)curl_http_proxy);
1121 curl_http_proxy = NULL;
1124 if (proxy_auth.password) {
1125 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1126 FREE_AND_NULL(proxy_auth.password);
1129 free((void *)curl_proxyuserpwd);
1130 curl_proxyuserpwd = NULL;
1132 free((void *)http_proxy_authmethod);
1133 http_proxy_authmethod = NULL;
1135 if (cert_auth.password != NULL) {
1136 memset(cert_auth.password, 0, strlen(cert_auth.password));
1137 FREE_AND_NULL(cert_auth.password);
1139 ssl_cert_password_required = 0;
1141 FREE_AND_NULL(cached_accept_language);
1144 struct active_request_slot *get_active_slot(void)
1146 struct active_request_slot *slot = active_queue_head;
1147 struct active_request_slot *newslot;
1149 #ifdef USE_CURL_MULTI
1152 /* Wait for a slot to open up if the queue is full */
1153 while (active_requests >= max_requests) {
1154 curl_multi_perform(curlm, &num_transfers);
1155 if (num_transfers < active_requests)
1156 process_curl_messages();
1160 while (slot != NULL && slot->in_use)
1164 newslot = xmalloc(sizeof(*newslot));
1165 newslot->curl = NULL;
1166 newslot->in_use = 0;
1167 newslot->next = NULL;
1169 slot = active_queue_head;
1171 active_queue_head = newslot;
1173 while (slot->next != NULL)
1175 slot->next = newslot;
1180 if (slot->curl == NULL) {
1181 #ifdef NO_CURL_EASY_DUPHANDLE
1182 slot->curl = get_curl_handle();
1184 slot->curl = curl_easy_duphandle(curl_default);
1186 curl_session_count++;
1191 slot->results = NULL;
1192 slot->finished = NULL;
1193 slot->callback_data = NULL;
1194 slot->callback_func = NULL;
1195 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1196 if (curl_save_cookies)
1197 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1198 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1199 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1200 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1201 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1202 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1203 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1204 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1205 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1206 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1207 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1210 * Default following to off unless "ALWAYS" is configured; this gives
1211 * callers a sane starting point, and they can tweak for individual
1212 * HTTP_FOLLOW_* cases themselves.
1214 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1215 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1217 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1219 #if LIBCURL_VERSION_NUM >= 0x070a08
1220 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1222 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1223 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1225 if (http_auth.password || curl_empty_auth_enabled())
1226 init_curl_http_auth(slot->curl);
1231 int start_active_slot(struct active_request_slot *slot)
1233 #ifdef USE_CURL_MULTI
1234 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1237 if (curlm_result != CURLM_OK &&
1238 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1239 warning("curl_multi_add_handle failed: %s",
1240 curl_multi_strerror(curlm_result));
1247 * We know there must be something to do, since we just added
1250 curl_multi_perform(curlm, &num_transfers);
1255 #ifdef USE_CURL_MULTI
1258 int (*fill)(void *);
1259 struct fill_chain *next;
1262 static struct fill_chain *fill_cfg;
1264 void add_fill_function(void *data, int (*fill)(void *))
1266 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1267 struct fill_chain **linkp = &fill_cfg;
1268 new_fill->data = data;
1269 new_fill->fill = fill;
1270 new_fill->next = NULL;
1272 linkp = &(*linkp)->next;
1276 void fill_active_slots(void)
1278 struct active_request_slot *slot = active_queue_head;
1280 while (active_requests < max_requests) {
1281 struct fill_chain *fill;
1282 for (fill = fill_cfg; fill; fill = fill->next)
1283 if (fill->fill(fill->data))
1290 while (slot != NULL) {
1291 if (!slot->in_use && slot->curl != NULL
1292 && curl_session_count > min_curl_sessions) {
1293 curl_easy_cleanup(slot->curl);
1295 curl_session_count--;
1301 void step_active_slots(void)
1304 CURLMcode curlm_result;
1307 curlm_result = curl_multi_perform(curlm, &num_transfers);
1308 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1309 if (num_transfers < active_requests) {
1310 process_curl_messages();
1311 fill_active_slots();
1316 void run_active_slot(struct active_request_slot *slot)
1318 #ifdef USE_CURL_MULTI
1323 struct timeval select_timeout;
1326 slot->finished = &finished;
1328 step_active_slots();
1331 #if LIBCURL_VERSION_NUM >= 0x070f04
1333 curl_multi_timeout(curlm, &curl_timeout);
1334 if (curl_timeout == 0) {
1336 } else if (curl_timeout == -1) {
1337 select_timeout.tv_sec = 0;
1338 select_timeout.tv_usec = 50000;
1340 select_timeout.tv_sec = curl_timeout / 1000;
1341 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1344 select_timeout.tv_sec = 0;
1345 select_timeout.tv_usec = 50000;
1352 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1355 * It can happen that curl_multi_timeout returns a pathologically
1356 * long timeout when curl_multi_fdset returns no file descriptors
1357 * to read. See commit message for more details.
1360 (select_timeout.tv_sec > 0 ||
1361 select_timeout.tv_usec > 50000)) {
1362 select_timeout.tv_sec = 0;
1363 select_timeout.tv_usec = 50000;
1366 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1370 while (slot->in_use) {
1371 slot->curl_result = curl_easy_perform(slot->curl);
1372 finish_active_slot(slot);
1377 static void release_active_slot(struct active_request_slot *slot)
1379 closedown_active_slot(slot);
1381 xmulti_remove_handle(slot);
1382 if (curl_session_count > min_curl_sessions) {
1383 curl_easy_cleanup(slot->curl);
1385 curl_session_count--;
1388 #ifdef USE_CURL_MULTI
1389 fill_active_slots();
1393 void finish_all_active_slots(void)
1395 struct active_request_slot *slot = active_queue_head;
1397 while (slot != NULL)
1399 run_active_slot(slot);
1400 slot = active_queue_head;
1406 /* Helpers for modifying and creating URLs */
1407 static inline int needs_quote(int ch)
1409 if (((ch >= 'A') && (ch <= 'Z'))
1410 || ((ch >= 'a') && (ch <= 'z'))
1411 || ((ch >= '0') && (ch <= '9'))
1419 static char *quote_ref_url(const char *base, const char *ref)
1421 struct strbuf buf = STRBUF_INIT;
1425 end_url_with_slash(&buf, base);
1427 for (cp = ref; (ch = *cp) != 0; cp++)
1428 if (needs_quote(ch))
1429 strbuf_addf(&buf, "%%%02x", ch);
1431 strbuf_addch(&buf, *cp);
1433 return strbuf_detach(&buf, NULL);
1436 void append_remote_object_url(struct strbuf *buf, const char *url,
1438 int only_two_digit_prefix)
1440 end_url_with_slash(buf, url);
1442 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1443 if (!only_two_digit_prefix)
1444 strbuf_addstr(buf, hex + 2);
1447 char *get_remote_object_url(const char *url, const char *hex,
1448 int only_two_digit_prefix)
1450 struct strbuf buf = STRBUF_INIT;
1451 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1452 return strbuf_detach(&buf, NULL);
1455 static int handle_curl_result(struct slot_results *results)
1458 * If we see a failing http code with CURLE_OK, we have turned off
1459 * FAILONERROR (to keep the server's custom error response), and should
1460 * translate the code into failure here.
1462 * Likewise, if we see a redirect (30x code), that means we turned off
1463 * redirect-following, and we should treat the result as an error.
1465 if (results->curl_result == CURLE_OK &&
1466 results->http_code >= 300) {
1467 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1469 * Normally curl will already have put the "reason phrase"
1470 * from the server into curl_errorstr; unfortunately without
1471 * FAILONERROR it is lost, so we can give only the numeric
1474 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1475 "The requested URL returned error: %ld",
1476 results->http_code);
1479 if (results->curl_result == CURLE_OK) {
1480 credential_approve(&http_auth);
1481 if (proxy_auth.password)
1482 credential_approve(&proxy_auth);
1484 } else if (missing_target(results))
1485 return HTTP_MISSING_TARGET;
1486 else if (results->http_code == 401) {
1487 if (http_auth.username && http_auth.password) {
1488 credential_reject(&http_auth);
1491 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1492 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1493 if (results->auth_avail) {
1494 http_auth_methods &= results->auth_avail;
1495 http_auth_methods_restricted = 1;
1501 if (results->http_connectcode == 407)
1502 credential_reject(&proxy_auth);
1503 #if LIBCURL_VERSION_NUM >= 0x070c00
1504 if (!curl_errorstr[0])
1505 strlcpy(curl_errorstr,
1506 curl_easy_strerror(results->curl_result),
1507 sizeof(curl_errorstr));
1513 int run_one_slot(struct active_request_slot *slot,
1514 struct slot_results *results)
1516 slot->results = results;
1517 if (!start_active_slot(slot)) {
1518 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1519 "failed to start HTTP request");
1520 return HTTP_START_FAILED;
1523 run_active_slot(slot);
1524 return handle_curl_result(results);
1527 struct curl_slist *http_copy_default_headers(void)
1529 struct curl_slist *headers = NULL, *h;
1531 for (h = extra_http_headers; h; h = h->next)
1532 headers = curl_slist_append(headers, h->data);
1537 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1543 ret = curl_easy_getinfo(curl, info, &ptr);
1545 strbuf_addstr(buf, ptr);
1550 * Check for and extract a content-type parameter. "raw"
1551 * should be positioned at the start of the potential
1552 * parameter, with any whitespace already removed.
1554 * "name" is the name of the parameter. The value is appended
1557 static int extract_param(const char *raw, const char *name,
1560 size_t len = strlen(name);
1562 if (strncasecmp(raw, name, len))
1570 while (*raw && !isspace(*raw) && *raw != ';')
1571 strbuf_addch(out, *raw++);
1576 * Extract a normalized version of the content type, with any
1577 * spaces suppressed, all letters lowercased, and no trailing ";"
1580 * Note that we will silently remove even invalid whitespace. For
1581 * example, "text / plain" is specifically forbidden by RFC 2616,
1582 * but "text/plain" is the only reasonable output, and this keeps
1585 * If the "charset" argument is not NULL, store the value of any
1586 * charset parameter there.
1589 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1590 * "text / plain" -> "text/plain"
1592 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1593 struct strbuf *charset)
1598 strbuf_grow(type, raw->len);
1599 for (p = raw->buf; *p; p++) {
1606 strbuf_addch(type, tolower(*p));
1612 strbuf_reset(charset);
1614 while (isspace(*p) || *p == ';')
1616 if (!extract_param(p, "charset", charset))
1618 while (*p && !isspace(*p))
1622 if (!charset->len && starts_with(type->buf, "text/"))
1623 strbuf_addstr(charset, "ISO-8859-1");
1626 static void write_accept_language(struct strbuf *buf)
1629 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1630 * that, q-value will be smaller than 0.001, the minimum q-value the
1631 * HTTP specification allows. See
1632 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1634 const int MAX_DECIMAL_PLACES = 3;
1635 const int MAX_LANGUAGE_TAGS = 1000;
1636 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1637 char **language_tags = NULL;
1639 const char *s = get_preferred_languages();
1641 struct strbuf tag = STRBUF_INIT;
1643 /* Don't add Accept-Language header if no language is preferred. */
1648 * Split the colon-separated string of preferred languages into
1649 * language_tags array.
1652 /* collect language tag */
1653 for (; *s && (isalnum(*s) || *s == '_'); s++)
1654 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1656 /* skip .codeset, @modifier and any other unnecessary parts */
1657 while (*s && *s != ':')
1662 REALLOC_ARRAY(language_tags, num_langs);
1663 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1664 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1669 /* write Accept-Language header into buf */
1671 int last_buf_len = 0;
1677 REALLOC_ARRAY(language_tags, num_langs + 1);
1678 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1680 /* compute decimal_places */
1681 for (max_q = 1, decimal_places = 0;
1682 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1683 decimal_places++, max_q *= 10)
1686 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1688 strbuf_addstr(buf, "Accept-Language: ");
1690 for (i = 0; i < num_langs; i++) {
1692 strbuf_addstr(buf, ", ");
1694 strbuf_addstr(buf, language_tags[i]);
1697 strbuf_addf(buf, q_format, max_q - i);
1699 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1700 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1704 last_buf_len = buf->len;
1708 /* free language tags -- last one is a static '*' */
1709 for (i = 0; i < num_langs - 1; i++)
1710 free(language_tags[i]);
1711 free(language_tags);
1715 * Get an Accept-Language header which indicates user's preferred languages.
1719 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1720 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1721 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1722 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1723 * LANGUAGE= LANG=C -> ""
1725 static const char *get_accept_language(void)
1727 if (!cached_accept_language) {
1728 struct strbuf buf = STRBUF_INIT;
1729 write_accept_language(&buf);
1731 cached_accept_language = strbuf_detach(&buf, NULL);
1734 return cached_accept_language;
1737 static void http_opt_request_remainder(CURL *curl, off_t pos)
1740 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1741 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1744 /* http_request() targets */
1745 #define HTTP_REQUEST_STRBUF 0
1746 #define HTTP_REQUEST_FILE 1
1748 static int http_request(const char *url,
1749 void *result, int target,
1750 const struct http_get_options *options)
1752 struct active_request_slot *slot;
1753 struct slot_results results;
1754 struct curl_slist *headers = http_copy_default_headers();
1755 struct strbuf buf = STRBUF_INIT;
1756 const char *accept_language;
1759 slot = get_active_slot();
1760 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1762 if (result == NULL) {
1763 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1765 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1766 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1768 if (target == HTTP_REQUEST_FILE) {
1769 off_t posn = ftello(result);
1770 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1773 http_opt_request_remainder(slot->curl, posn);
1775 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1779 accept_language = get_accept_language();
1781 if (accept_language)
1782 headers = curl_slist_append(headers, accept_language);
1784 strbuf_addstr(&buf, "Pragma:");
1785 if (options && options->no_cache)
1786 strbuf_addstr(&buf, " no-cache");
1787 if (options && options->keep_error)
1788 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1789 if (options && options->initial_request &&
1790 http_follow_config == HTTP_FOLLOW_INITIAL)
1791 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1793 headers = curl_slist_append(headers, buf.buf);
1795 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1796 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1797 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1799 ret = run_one_slot(slot, &results);
1801 if (options && options->content_type) {
1802 struct strbuf raw = STRBUF_INIT;
1803 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1804 extract_content_type(&raw, options->content_type,
1806 strbuf_release(&raw);
1809 if (options && options->effective_url)
1810 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1811 options->effective_url);
1813 curl_slist_free_all(headers);
1814 strbuf_release(&buf);
1820 * Update the "base" url to a more appropriate value, as deduced by
1821 * redirects seen when requesting a URL starting with "url".
1823 * The "asked" parameter is a URL that we asked curl to access, and must begin
1826 * The "got" parameter is the URL that curl reported to us as where we ended
1829 * Returns 1 if we updated the base url, 0 otherwise.
1831 * Our basic strategy is to compare "base" and "asked" to find the bits
1832 * specific to our request. We then strip those bits off of "got" to yield the
1833 * new base. So for example, if our base is "http://example.com/foo.git",
1834 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1835 * with "https://other.example.com/foo.git/info/refs". We would want the
1836 * new URL to become "https://other.example.com/foo.git".
1838 * Note that this assumes a sane redirect scheme. It's entirely possible
1839 * in the example above to end up at a URL that does not even end in
1840 * "info/refs". In such a case we die. There's not much we can do, such a
1841 * scheme is unlikely to represent a real git repository, and failing to
1842 * rewrite the base opens options for malicious redirects to do funny things.
1844 static int update_url_from_redirect(struct strbuf *base,
1846 const struct strbuf *got)
1851 if (!strcmp(asked, got->buf))
1854 if (!skip_prefix(asked, base->buf, &tail))
1855 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1859 if (!strip_suffix_mem(got->buf, &new_len, tail))
1860 die(_("unable to update url base from redirection:\n"
1866 strbuf_add(base, got->buf, new_len);
1871 static int http_request_reauth(const char *url,
1872 void *result, int target,
1873 struct http_get_options *options)
1875 int ret = http_request(url, result, target, options);
1877 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1880 if (options && options->effective_url && options->base_url) {
1881 if (update_url_from_redirect(options->base_url,
1882 url, options->effective_url)) {
1883 credential_from_url(&http_auth, options->base_url->buf);
1884 url = options->effective_url->buf;
1888 if (ret != HTTP_REAUTH)
1892 * If we are using KEEP_ERROR, the previous request may have
1893 * put cruft into our output stream; we should clear it out before
1894 * making our next request. We only know how to do this for
1895 * the strbuf case, but that is enough to satisfy current callers.
1897 if (options && options->keep_error) {
1899 case HTTP_REQUEST_STRBUF:
1900 strbuf_reset(result);
1903 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1907 credential_fill(&http_auth);
1909 return http_request(url, result, target, options);
1912 int http_get_strbuf(const char *url,
1913 struct strbuf *result,
1914 struct http_get_options *options)
1916 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1920 * Downloads a URL and stores the result in the given file.
1922 * If a previous interrupted download is detected (i.e. a previous temporary
1923 * file is still around) the download is resumed.
1925 static int http_get_file(const char *url, const char *filename,
1926 struct http_get_options *options)
1929 struct strbuf tmpfile = STRBUF_INIT;
1932 strbuf_addf(&tmpfile, "%s.temp", filename);
1933 result = fopen(tmpfile.buf, "a");
1935 error("Unable to open local file %s", tmpfile.buf);
1940 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1943 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1946 strbuf_release(&tmpfile);
1950 int http_fetch_ref(const char *base, struct ref *ref)
1952 struct http_get_options options = {0};
1954 struct strbuf buffer = STRBUF_INIT;
1957 options.no_cache = 1;
1959 url = quote_ref_url(base, ref->name);
1960 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1961 strbuf_rtrim(&buffer);
1962 if (buffer.len == 40)
1963 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1964 else if (starts_with(buffer.buf, "ref: ")) {
1965 ref->symref = xstrdup(buffer.buf + 5);
1970 strbuf_release(&buffer);
1975 /* Helpers for fetching packs */
1976 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1979 struct strbuf buf = STRBUF_INIT;
1981 if (http_is_verbose)
1982 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1984 end_url_with_slash(&buf, base_url);
1985 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1986 url = strbuf_detach(&buf, NULL);
1988 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1989 tmp = strbuf_detach(&buf, NULL);
1991 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1992 error("Unable to get pack index %s", url);
2000 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2001 unsigned char *sha1, const char *base_url)
2003 struct packed_git *new_pack;
2004 char *tmp_idx = NULL;
2007 if (has_pack_index(sha1)) {
2008 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2010 return -1; /* parse_pack_index() already issued error message */
2014 tmp_idx = fetch_pack_index(sha1, base_url);
2018 new_pack = parse_pack_index(sha1, tmp_idx);
2023 return -1; /* parse_pack_index() already issued error message */
2026 ret = verify_pack_index(new_pack);
2028 close_pack_index(new_pack);
2029 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2036 new_pack->next = *packs_head;
2037 *packs_head = new_pack;
2041 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2043 struct http_get_options options = {0};
2046 struct strbuf buf = STRBUF_INIT;
2047 unsigned char sha1[20];
2049 end_url_with_slash(&buf, base_url);
2050 strbuf_addstr(&buf, "objects/info/packs");
2051 url = strbuf_detach(&buf, NULL);
2053 options.no_cache = 1;
2054 ret = http_get_strbuf(url, &buf, &options);
2059 while (i < buf.len) {
2063 if (i + 52 <= buf.len &&
2064 starts_with(data + i, " pack-") &&
2065 starts_with(data + i + 46, ".pack\n")) {
2066 get_sha1_hex(data + i + 6, sha1);
2067 fetch_and_setup_pack_index(packs_head, sha1,
2073 while (i < buf.len && data[i] != '\n')
2084 void release_http_pack_request(struct http_pack_request *preq)
2086 if (preq->packfile != NULL) {
2087 fclose(preq->packfile);
2088 preq->packfile = NULL;
2095 int finish_http_pack_request(struct http_pack_request *preq)
2097 struct packed_git **lst;
2098 struct packed_git *p = preq->target;
2101 struct child_process ip = CHILD_PROCESS_INIT;
2103 close_pack_index(p);
2105 fclose(preq->packfile);
2106 preq->packfile = NULL;
2110 lst = &((*lst)->next);
2111 *lst = (*lst)->next;
2113 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2114 die("BUG: pack tmpfile does not end in .pack.temp?");
2115 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
2117 argv_array_push(&ip.args, "index-pack");
2118 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2119 argv_array_push(&ip.args, preq->tmpfile);
2124 if (run_command(&ip)) {
2125 unlink(preq->tmpfile);
2131 unlink(sha1_pack_index_name(p->sha1));
2133 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2134 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2139 install_packed_git(the_repository, p);
2144 struct http_pack_request *new_http_pack_request(
2145 struct packed_git *target, const char *base_url)
2147 off_t prev_posn = 0;
2148 struct strbuf buf = STRBUF_INIT;
2149 struct http_pack_request *preq;
2151 preq = xcalloc(1, sizeof(*preq));
2152 preq->target = target;
2154 end_url_with_slash(&buf, base_url);
2155 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2156 sha1_to_hex(target->sha1));
2157 preq->url = strbuf_detach(&buf, NULL);
2159 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2160 sha1_pack_name(target->sha1));
2161 preq->packfile = fopen(preq->tmpfile, "a");
2162 if (!preq->packfile) {
2163 error("Unable to open local file %s for pack",
2168 preq->slot = get_active_slot();
2169 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2170 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2171 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2172 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2176 * If there is data present from a previous transfer attempt,
2177 * resume where it left off
2179 prev_posn = ftello(preq->packfile);
2181 if (http_is_verbose)
2183 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2184 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2185 http_opt_request_remainder(preq->slot->curl, prev_posn);
2196 /* Helpers for fetching objects (loose) */
2197 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2200 unsigned char expn[4096];
2201 size_t size = eltsize * nmemb;
2203 struct http_object_request *freq = data;
2204 struct active_request_slot *slot = freq->slot;
2207 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2210 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2211 curl_easy_strerror(c));
2212 if (slot->http_code >= 300)
2217 ssize_t retval = xwrite(freq->localfile,
2218 (char *) ptr + posn, size - posn);
2222 } while (posn < size);
2224 freq->stream.avail_in = size;
2225 freq->stream.next_in = (void *)ptr;
2227 freq->stream.next_out = expn;
2228 freq->stream.avail_out = sizeof(expn);
2229 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2230 git_SHA1_Update(&freq->c, expn,
2231 sizeof(expn) - freq->stream.avail_out);
2232 } while (freq->stream.avail_in && freq->zret == Z_OK);
2236 struct http_object_request *new_http_object_request(const char *base_url,
2237 unsigned char *sha1)
2239 char *hex = sha1_to_hex(sha1);
2240 struct strbuf filename = STRBUF_INIT;
2241 char prevfile[PATH_MAX];
2243 char prev_buf[PREV_BUF_SIZE];
2244 ssize_t prev_read = 0;
2245 off_t prev_posn = 0;
2246 struct http_object_request *freq;
2248 freq = xcalloc(1, sizeof(*freq));
2249 hashcpy(freq->sha1, sha1);
2250 freq->localfile = -1;
2252 sha1_file_name(the_repository, &filename, sha1);
2253 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2254 "%s.temp", filename.buf);
2256 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename.buf);
2257 unlink_or_warn(prevfile);
2258 rename(freq->tmpfile, prevfile);
2259 unlink_or_warn(freq->tmpfile);
2260 strbuf_release(&filename);
2262 if (freq->localfile != -1)
2263 error("fd leakage in start: %d", freq->localfile);
2264 freq->localfile = open(freq->tmpfile,
2265 O_WRONLY | O_CREAT | O_EXCL, 0666);
2267 * This could have failed due to the "lazy directory creation";
2268 * try to mkdir the last path component.
2270 if (freq->localfile < 0 && errno == ENOENT) {
2271 char *dir = strrchr(freq->tmpfile, '/');
2274 mkdir(freq->tmpfile, 0777);
2277 freq->localfile = open(freq->tmpfile,
2278 O_WRONLY | O_CREAT | O_EXCL, 0666);
2281 if (freq->localfile < 0) {
2282 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2286 git_inflate_init(&freq->stream);
2288 git_SHA1_Init(&freq->c);
2290 freq->url = get_remote_object_url(base_url, hex, 0);
2293 * If a previous temp file is present, process what was already
2296 prevlocal = open(prevfile, O_RDONLY);
2297 if (prevlocal != -1) {
2299 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2301 if (fwrite_sha1_file(prev_buf,
2304 freq) == prev_read) {
2305 prev_posn += prev_read;
2310 } while (prev_read > 0);
2313 unlink_or_warn(prevfile);
2316 * Reset inflate/SHA1 if there was an error reading the previous temp
2317 * file; also rewind to the beginning of the local file.
2319 if (prev_read == -1) {
2320 memset(&freq->stream, 0, sizeof(freq->stream));
2321 git_inflate_init(&freq->stream);
2322 git_SHA1_Init(&freq->c);
2325 lseek(freq->localfile, 0, SEEK_SET);
2326 if (ftruncate(freq->localfile, 0) < 0) {
2327 error_errno("Couldn't truncate temporary file %s",
2334 freq->slot = get_active_slot();
2336 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2337 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2338 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2339 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2340 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2341 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2344 * If we have successfully processed data from a previous fetch
2345 * attempt, only fetch the data we don't already have.
2348 if (http_is_verbose)
2350 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2351 hex, (uintmax_t)prev_posn);
2352 http_opt_request_remainder(freq->slot->curl, prev_posn);
2363 void process_http_object_request(struct http_object_request *freq)
2365 if (freq->slot == NULL)
2367 freq->curl_result = freq->slot->curl_result;
2368 freq->http_code = freq->slot->http_code;
2372 int finish_http_object_request(struct http_object_request *freq)
2375 struct strbuf filename = STRBUF_INIT;
2377 close(freq->localfile);
2378 freq->localfile = -1;
2380 process_http_object_request(freq);
2382 if (freq->http_code == 416) {
2383 warning("requested range invalid; we may already have all the data.");
2384 } else if (freq->curl_result != CURLE_OK) {
2385 if (stat(freq->tmpfile, &st) == 0)
2386 if (st.st_size == 0)
2387 unlink_or_warn(freq->tmpfile);
2391 git_inflate_end(&freq->stream);
2392 git_SHA1_Final(freq->real_sha1, &freq->c);
2393 if (freq->zret != Z_STREAM_END) {
2394 unlink_or_warn(freq->tmpfile);
2397 if (hashcmp(freq->sha1, freq->real_sha1)) {
2398 unlink_or_warn(freq->tmpfile);
2401 sha1_file_name(the_repository, &filename, freq->sha1);
2402 freq->rename = finalize_object_file(freq->tmpfile, filename.buf);
2403 strbuf_release(&filename);
2405 return freq->rename;
2408 void abort_http_object_request(struct http_object_request *freq)
2410 unlink_or_warn(freq->tmpfile);
2412 release_http_object_request(freq);
2415 void release_http_object_request(struct http_object_request *freq)
2417 if (freq->localfile != -1) {
2418 close(freq->localfile);
2419 freq->localfile = -1;
2421 if (freq->url != NULL) {
2422 FREE_AND_NULL(freq->url);
2424 if (freq->slot != NULL) {
2425 freq->slot->callback_func = NULL;
2426 freq->slot->callback_data = NULL;
2427 release_active_slot(freq->slot);