Sync with 2.37.7
[git.git] / http.c
blob06de051c532fc2712caaef994575132f81f3a88d
1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
3 #include "http.h"
4 #include "config.h"
5 #include "pack.h"
6 #include "sideband.h"
7 #include "run-command.h"
8 #include "url.h"
9 #include "urlmatch.h"
10 #include "credential.h"
11 #include "version.h"
12 #include "pkt-line.h"
13 #include "gettext.h"
14 #include "transport.h"
15 #include "packfile.h"
16 #include "protocol.h"
17 #include "string-list.h"
18 #include "object-store.h"
20 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
21 static int trace_curl_data = 1;
22 static int trace_curl_redact = 1;
23 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
24 int active_requests;
25 int http_is_verbose;
26 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
28 static int min_curl_sessions = 1;
29 static int curl_session_count;
30 static int max_requests = -1;
31 static CURLM *curlm;
32 static CURL *curl_default;
34 #define PREV_BUF_SIZE 4096
36 char curl_errorstr[CURL_ERROR_SIZE];
38 static int curl_ssl_verify = -1;
39 static int curl_ssl_try;
40 static const char *curl_http_version = NULL;
41 static const char *ssl_cert;
42 static const char *ssl_cipherlist;
43 static const char *ssl_version;
44 static struct {
45 const char *name;
46 long ssl_version;
47 } sslversions[] = {
48 { "sslv2", CURL_SSLVERSION_SSLv2 },
49 { "sslv3", CURL_SSLVERSION_SSLv3 },
50 { "tlsv1", CURL_SSLVERSION_TLSv1 },
51 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
52 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
53 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
54 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
55 #endif
56 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
57 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
58 #endif
60 static const char *ssl_key;
61 static const char *ssl_capath;
62 static const char *curl_no_proxy;
63 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
64 static const char *ssl_pinnedkey;
65 #endif
66 static const char *ssl_cainfo;
67 static long curl_low_speed_limit = -1;
68 static long curl_low_speed_time = -1;
69 static int curl_ftp_no_epsv;
70 static const char *curl_http_proxy;
71 static const char *http_proxy_authmethod;
73 static const char *http_proxy_ssl_cert;
74 static const char *http_proxy_ssl_key;
75 static const char *http_proxy_ssl_ca_info;
76 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
77 static int proxy_ssl_cert_password_required;
79 static struct {
80 const char *name;
81 long curlauth_param;
82 } proxy_authmethods[] = {
83 { "basic", CURLAUTH_BASIC },
84 { "digest", CURLAUTH_DIGEST },
85 { "negotiate", CURLAUTH_GSSNEGOTIATE },
86 { "ntlm", CURLAUTH_NTLM },
87 { "anyauth", CURLAUTH_ANY },
89 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
90 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
91 * here, too
94 #ifdef CURLGSSAPI_DELEGATION_FLAG
95 static const char *curl_deleg;
96 static struct {
97 const char *name;
98 long curl_deleg_param;
99 } curl_deleg_levels[] = {
100 { "none", CURLGSSAPI_DELEGATION_NONE },
101 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
102 { "always", CURLGSSAPI_DELEGATION_FLAG },
104 #endif
106 static struct credential proxy_auth = CREDENTIAL_INIT;
107 static const char *curl_proxyuserpwd;
108 static const char *curl_cookie_file;
109 static int curl_save_cookies;
110 struct credential http_auth = CREDENTIAL_INIT;
111 static int http_proactive_auth;
112 static const char *user_agent;
113 static int curl_empty_auth = -1;
115 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
117 static struct credential cert_auth = CREDENTIAL_INIT;
118 static int ssl_cert_password_required;
119 static unsigned long http_auth_methods = CURLAUTH_ANY;
120 static int http_auth_methods_restricted;
121 /* Modes for which empty_auth cannot actually help us. */
122 static unsigned long empty_auth_useless =
123 CURLAUTH_BASIC
124 | CURLAUTH_DIGEST_IE
125 | CURLAUTH_DIGEST;
127 static struct curl_slist *pragma_header;
128 static struct curl_slist *no_pragma_header;
129 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
131 static struct curl_slist *host_resolutions;
133 static struct active_request_slot *active_queue_head;
135 static char *cached_accept_language;
137 static char *http_ssl_backend;
139 static int http_schannel_check_revoke = 1;
141 * With the backend being set to `schannel`, setting sslCAinfo would override
142 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
143 * by default.
145 static int http_schannel_use_ssl_cainfo;
147 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
149 size_t size = eltsize * nmemb;
150 struct buffer *buffer = buffer_;
152 if (size > buffer->buf.len - buffer->posn)
153 size = buffer->buf.len - buffer->posn;
154 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
155 buffer->posn += size;
157 return size / eltsize;
160 int seek_buffer(void *clientp, curl_off_t offset, int origin)
162 struct buffer *buffer = clientp;
164 if (origin != SEEK_SET)
165 BUG("seek_buffer only handles SEEK_SET");
166 if (offset < 0 || offset >= buffer->buf.len) {
167 error("curl seek would be outside of buffer");
168 return CURL_SEEKFUNC_FAIL;
171 buffer->posn = offset;
172 return CURL_SEEKFUNC_OK;
175 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
177 size_t size = eltsize * nmemb;
178 struct strbuf *buffer = buffer_;
180 strbuf_add(buffer, ptr, size);
181 return nmemb;
184 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
186 return nmemb;
189 static void closedown_active_slot(struct active_request_slot *slot)
191 active_requests--;
192 slot->in_use = 0;
195 static void finish_active_slot(struct active_request_slot *slot)
197 closedown_active_slot(slot);
198 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
200 if (slot->finished)
201 (*slot->finished) = 1;
203 /* Store slot results so they can be read after the slot is reused */
204 if (slot->results) {
205 slot->results->curl_result = slot->curl_result;
206 slot->results->http_code = slot->http_code;
207 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
208 &slot->results->auth_avail);
210 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
211 &slot->results->http_connectcode);
214 /* Run callback if appropriate */
215 if (slot->callback_func)
216 slot->callback_func(slot->callback_data);
219 static void xmulti_remove_handle(struct active_request_slot *slot)
221 curl_multi_remove_handle(curlm, slot->curl);
224 static void process_curl_messages(void)
226 int num_messages;
227 struct active_request_slot *slot;
228 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
230 while (curl_message != NULL) {
231 if (curl_message->msg == CURLMSG_DONE) {
232 int curl_result = curl_message->data.result;
233 slot = active_queue_head;
234 while (slot != NULL &&
235 slot->curl != curl_message->easy_handle)
236 slot = slot->next;
237 if (slot) {
238 xmulti_remove_handle(slot);
239 slot->curl_result = curl_result;
240 finish_active_slot(slot);
241 } else {
242 fprintf(stderr, "Received DONE message for unknown request!\n");
244 } else {
245 fprintf(stderr, "Unknown CURL message received: %d\n",
246 (int)curl_message->msg);
248 curl_message = curl_multi_info_read(curlm, &num_messages);
252 static int http_options(const char *var, const char *value, void *cb)
254 if (!strcmp("http.version", var)) {
255 return git_config_string(&curl_http_version, var, value);
257 if (!strcmp("http.sslverify", var)) {
258 curl_ssl_verify = git_config_bool(var, value);
259 return 0;
261 if (!strcmp("http.sslcipherlist", var))
262 return git_config_string(&ssl_cipherlist, var, value);
263 if (!strcmp("http.sslversion", var))
264 return git_config_string(&ssl_version, var, value);
265 if (!strcmp("http.sslcert", var))
266 return git_config_pathname(&ssl_cert, var, value);
267 if (!strcmp("http.sslkey", var))
268 return git_config_pathname(&ssl_key, var, value);
269 if (!strcmp("http.sslcapath", var))
270 return git_config_pathname(&ssl_capath, var, value);
271 if (!strcmp("http.sslcainfo", var))
272 return git_config_pathname(&ssl_cainfo, var, value);
273 if (!strcmp("http.sslcertpasswordprotected", var)) {
274 ssl_cert_password_required = git_config_bool(var, value);
275 return 0;
277 if (!strcmp("http.ssltry", var)) {
278 curl_ssl_try = git_config_bool(var, value);
279 return 0;
281 if (!strcmp("http.sslbackend", var)) {
282 free(http_ssl_backend);
283 http_ssl_backend = xstrdup_or_null(value);
284 return 0;
287 if (!strcmp("http.schannelcheckrevoke", var)) {
288 http_schannel_check_revoke = git_config_bool(var, value);
289 return 0;
292 if (!strcmp("http.schannelusesslcainfo", var)) {
293 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
294 return 0;
297 if (!strcmp("http.minsessions", var)) {
298 min_curl_sessions = git_config_int(var, value);
299 if (min_curl_sessions > 1)
300 min_curl_sessions = 1;
301 return 0;
303 if (!strcmp("http.maxrequests", var)) {
304 max_requests = git_config_int(var, value);
305 return 0;
307 if (!strcmp("http.lowspeedlimit", var)) {
308 curl_low_speed_limit = (long)git_config_int(var, value);
309 return 0;
311 if (!strcmp("http.lowspeedtime", var)) {
312 curl_low_speed_time = (long)git_config_int(var, value);
313 return 0;
316 if (!strcmp("http.noepsv", var)) {
317 curl_ftp_no_epsv = git_config_bool(var, value);
318 return 0;
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.proxysslcert", var))
327 return git_config_string(&http_proxy_ssl_cert, var, value);
329 if (!strcmp("http.proxysslkey", var))
330 return git_config_string(&http_proxy_ssl_key, var, value);
332 if (!strcmp("http.proxysslcainfo", var))
333 return git_config_string(&http_proxy_ssl_ca_info, var, value);
335 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
336 proxy_ssl_cert_password_required = git_config_bool(var, value);
337 return 0;
340 if (!strcmp("http.cookiefile", var))
341 return git_config_pathname(&curl_cookie_file, var, value);
342 if (!strcmp("http.savecookies", var)) {
343 curl_save_cookies = git_config_bool(var, value);
344 return 0;
347 if (!strcmp("http.postbuffer", var)) {
348 http_post_buffer = git_config_ssize_t(var, value);
349 if (http_post_buffer < 0)
350 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
351 if (http_post_buffer < LARGE_PACKET_MAX)
352 http_post_buffer = LARGE_PACKET_MAX;
353 return 0;
356 if (!strcmp("http.useragent", var))
357 return git_config_string(&user_agent, var, value);
359 if (!strcmp("http.emptyauth", var)) {
360 if (value && !strcmp("auto", value))
361 curl_empty_auth = -1;
362 else
363 curl_empty_auth = git_config_bool(var, value);
364 return 0;
367 if (!strcmp("http.delegation", var)) {
368 #ifdef CURLGSSAPI_DELEGATION_FLAG
369 return git_config_string(&curl_deleg, var, value);
370 #else
371 warning(_("Delegation control is not supported with cURL < 7.22.0"));
372 return 0;
373 #endif
376 if (!strcmp("http.pinnedpubkey", var)) {
377 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
378 return git_config_pathname(&ssl_pinnedkey, var, value);
379 #else
380 warning(_("Public key pinning not supported with cURL < 7.39.0"));
381 return 0;
382 #endif
385 if (!strcmp("http.extraheader", var)) {
386 if (!value) {
387 return config_error_nonbool(var);
388 } else if (!*value) {
389 string_list_clear(&extra_http_headers, 0);
390 } else {
391 string_list_append(&extra_http_headers, value);
393 return 0;
396 if (!strcmp("http.curloptresolve", var)) {
397 if (!value) {
398 return config_error_nonbool(var);
399 } else if (!*value) {
400 curl_slist_free_all(host_resolutions);
401 host_resolutions = NULL;
402 } else {
403 host_resolutions = curl_slist_append(host_resolutions, value);
405 return 0;
408 if (!strcmp("http.followredirects", var)) {
409 if (value && !strcmp(value, "initial"))
410 http_follow_config = HTTP_FOLLOW_INITIAL;
411 else if (git_config_bool(var, value))
412 http_follow_config = HTTP_FOLLOW_ALWAYS;
413 else
414 http_follow_config = HTTP_FOLLOW_NONE;
415 return 0;
418 /* Fall back on the default ones */
419 return git_default_config(var, value, cb);
422 static int curl_empty_auth_enabled(void)
424 if (curl_empty_auth >= 0)
425 return curl_empty_auth;
428 * In the automatic case, kick in the empty-auth
429 * hack as long as we would potentially try some
430 * method more exotic than "Basic" or "Digest".
432 * But only do this when this is our second or
433 * subsequent request, as by then we know what
434 * methods are available.
436 if (http_auth_methods_restricted &&
437 (http_auth_methods & ~empty_auth_useless))
438 return 1;
439 return 0;
442 static void init_curl_http_auth(CURL *result)
444 if (!http_auth.username || !*http_auth.username) {
445 if (curl_empty_auth_enabled())
446 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
447 return;
450 credential_fill(&http_auth);
452 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
453 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
456 /* *var must be free-able */
457 static void var_override(const char **var, char *value)
459 if (value) {
460 free((void *)*var);
461 *var = xstrdup(value);
465 static void set_proxyauth_name_password(CURL *result)
467 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
468 proxy_auth.username);
469 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
470 proxy_auth.password);
473 static void init_curl_proxy_auth(CURL *result)
475 if (proxy_auth.username) {
476 if (!proxy_auth.password)
477 credential_fill(&proxy_auth);
478 set_proxyauth_name_password(result);
481 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
483 if (http_proxy_authmethod) {
484 int i;
485 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
486 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
487 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
488 proxy_authmethods[i].curlauth_param);
489 break;
492 if (i == ARRAY_SIZE(proxy_authmethods)) {
493 warning("unsupported proxy authentication method %s: using anyauth",
494 http_proxy_authmethod);
495 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
498 else
499 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
502 static int has_cert_password(void)
504 if (ssl_cert == NULL || ssl_cert_password_required != 1)
505 return 0;
506 if (!cert_auth.password) {
507 cert_auth.protocol = xstrdup("cert");
508 cert_auth.host = xstrdup("");
509 cert_auth.username = xstrdup("");
510 cert_auth.path = xstrdup(ssl_cert);
511 credential_fill(&cert_auth);
513 return 1;
516 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
517 static int has_proxy_cert_password(void)
519 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
520 return 0;
521 if (!proxy_cert_auth.password) {
522 proxy_cert_auth.protocol = xstrdup("cert");
523 proxy_cert_auth.host = xstrdup("");
524 proxy_cert_auth.username = xstrdup("");
525 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
526 credential_fill(&proxy_cert_auth);
528 return 1;
530 #endif
532 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
533 static void set_curl_keepalive(CURL *c)
535 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
538 #else
539 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
541 int ka = 1;
542 int rc;
543 socklen_t len = (socklen_t)sizeof(ka);
545 if (type != CURLSOCKTYPE_IPCXN)
546 return 0;
548 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
549 if (rc < 0)
550 warning_errno("unable to set SO_KEEPALIVE on socket");
552 return CURL_SOCKOPT_OK;
555 static void set_curl_keepalive(CURL *c)
557 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
559 #endif
561 static void redact_sensitive_header(struct strbuf *header)
563 const char *sensitive_header;
565 if (trace_curl_redact &&
566 (skip_iprefix(header->buf, "Authorization:", &sensitive_header) ||
567 skip_iprefix(header->buf, "Proxy-Authorization:", &sensitive_header))) {
568 /* The first token is the type, which is OK to log */
569 while (isspace(*sensitive_header))
570 sensitive_header++;
571 while (*sensitive_header && !isspace(*sensitive_header))
572 sensitive_header++;
573 /* Everything else is opaque and possibly sensitive */
574 strbuf_setlen(header, sensitive_header - header->buf);
575 strbuf_addstr(header, " <redacted>");
576 } else if (trace_curl_redact &&
577 skip_iprefix(header->buf, "Cookie:", &sensitive_header)) {
578 struct strbuf redacted_header = STRBUF_INIT;
579 const char *cookie;
581 while (isspace(*sensitive_header))
582 sensitive_header++;
584 cookie = sensitive_header;
586 while (cookie) {
587 char *equals;
588 char *semicolon = strstr(cookie, "; ");
589 if (semicolon)
590 *semicolon = 0;
591 equals = strchrnul(cookie, '=');
592 if (!equals) {
593 /* invalid cookie, just append and continue */
594 strbuf_addstr(&redacted_header, cookie);
595 continue;
597 strbuf_add(&redacted_header, cookie, equals - cookie);
598 strbuf_addstr(&redacted_header, "=<redacted>");
599 if (semicolon) {
601 * There are more cookies. (Or, for some
602 * reason, the input string ends in "; ".)
604 strbuf_addstr(&redacted_header, "; ");
605 cookie = semicolon + strlen("; ");
606 } else {
607 cookie = NULL;
611 strbuf_setlen(header, sensitive_header - header->buf);
612 strbuf_addbuf(header, &redacted_header);
616 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
618 struct strbuf out = STRBUF_INIT;
619 struct strbuf **headers, **header;
621 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
622 text, (long)size, (long)size);
623 trace_strbuf(&trace_curl, &out);
624 strbuf_reset(&out);
625 strbuf_add(&out, ptr, size);
626 headers = strbuf_split_max(&out, '\n', 0);
628 for (header = headers; *header; header++) {
629 if (hide_sensitive_header)
630 redact_sensitive_header(*header);
631 strbuf_insertstr((*header), 0, text);
632 strbuf_insertstr((*header), strlen(text), ": ");
633 strbuf_rtrim((*header));
634 strbuf_addch((*header), '\n');
635 trace_strbuf(&trace_curl, (*header));
637 strbuf_list_free(headers);
638 strbuf_release(&out);
641 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
643 size_t i;
644 struct strbuf out = STRBUF_INIT;
645 unsigned int width = 60;
647 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
648 text, (long)size, (long)size);
649 trace_strbuf(&trace_curl, &out);
651 for (i = 0; i < size; i += width) {
652 size_t w;
654 strbuf_reset(&out);
655 strbuf_addf(&out, "%s: ", text);
656 for (w = 0; (w < width) && (i + w < size); w++) {
657 unsigned char ch = ptr[i + w];
659 strbuf_addch(&out,
660 (ch >= 0x20) && (ch < 0x80)
661 ? ch : '.');
663 strbuf_addch(&out, '\n');
664 trace_strbuf(&trace_curl, &out);
666 strbuf_release(&out);
669 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
671 const char *text;
672 enum { NO_FILTER = 0, DO_FILTER = 1 };
674 switch (type) {
675 case CURLINFO_TEXT:
676 trace_printf_key(&trace_curl, "== Info: %s", data);
677 break;
678 case CURLINFO_HEADER_OUT:
679 text = "=> Send header";
680 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
681 break;
682 case CURLINFO_DATA_OUT:
683 if (trace_curl_data) {
684 text = "=> Send data";
685 curl_dump_data(text, (unsigned char *)data, size);
687 break;
688 case CURLINFO_SSL_DATA_OUT:
689 if (trace_curl_data) {
690 text = "=> Send SSL data";
691 curl_dump_data(text, (unsigned char *)data, size);
693 break;
694 case CURLINFO_HEADER_IN:
695 text = "<= Recv header";
696 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
697 break;
698 case CURLINFO_DATA_IN:
699 if (trace_curl_data) {
700 text = "<= Recv data";
701 curl_dump_data(text, (unsigned char *)data, size);
703 break;
704 case CURLINFO_SSL_DATA_IN:
705 if (trace_curl_data) {
706 text = "<= Recv SSL data";
707 curl_dump_data(text, (unsigned char *)data, size);
709 break;
711 default: /* we ignore unknown types by default */
712 return 0;
714 return 0;
717 void http_trace_curl_no_data(void)
719 trace_override_envvar(&trace_curl, "1");
720 trace_curl_data = 0;
723 void setup_curl_trace(CURL *handle)
725 if (!trace_want(&trace_curl))
726 return;
727 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
728 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
729 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
732 static void proto_list_append(struct strbuf *list, const char *proto)
734 if (!list)
735 return;
736 if (list->len)
737 strbuf_addch(list, ',');
738 strbuf_addstr(list, proto);
741 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
743 long bits = 0;
745 if (is_transport_allowed("http", from_user)) {
746 bits |= CURLPROTO_HTTP;
747 proto_list_append(list, "http");
749 if (is_transport_allowed("https", from_user)) {
750 bits |= CURLPROTO_HTTPS;
751 proto_list_append(list, "https");
753 if (is_transport_allowed("ftp", from_user)) {
754 bits |= CURLPROTO_FTP;
755 proto_list_append(list, "ftp");
757 if (is_transport_allowed("ftps", from_user)) {
758 bits |= CURLPROTO_FTPS;
759 proto_list_append(list, "ftps");
762 return bits;
765 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
766 static int get_curl_http_version_opt(const char *version_string, long *opt)
768 int i;
769 static struct {
770 const char *name;
771 long opt_token;
772 } choice[] = {
773 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
774 { "HTTP/2", CURL_HTTP_VERSION_2 }
777 for (i = 0; i < ARRAY_SIZE(choice); i++) {
778 if (!strcmp(version_string, choice[i].name)) {
779 *opt = choice[i].opt_token;
780 return 0;
784 warning("unknown value given to http.version: '%s'", version_string);
785 return -1; /* not found */
788 #endif
790 static CURL *get_curl_handle(void)
792 CURL *result = curl_easy_init();
794 if (!result)
795 die("curl_easy_init failed");
797 if (!curl_ssl_verify) {
798 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
799 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
800 } else {
801 /* Verify authenticity of the peer's certificate */
802 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
803 /* The name in the cert must match whom we tried to connect */
804 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
807 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
808 if (curl_http_version) {
809 long opt;
810 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
811 /* Set request use http version */
812 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
815 #endif
817 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
818 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
820 #ifdef CURLGSSAPI_DELEGATION_FLAG
821 if (curl_deleg) {
822 int i;
823 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
824 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
825 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
826 curl_deleg_levels[i].curl_deleg_param);
827 break;
830 if (i == ARRAY_SIZE(curl_deleg_levels))
831 warning("Unknown delegation method '%s': using default",
832 curl_deleg);
834 #endif
836 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
837 !http_schannel_check_revoke) {
838 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
839 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
840 #else
841 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
842 #endif
845 if (http_proactive_auth)
846 init_curl_http_auth(result);
848 if (getenv("GIT_SSL_VERSION"))
849 ssl_version = getenv("GIT_SSL_VERSION");
850 if (ssl_version && *ssl_version) {
851 int i;
852 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
853 if (!strcmp(ssl_version, sslversions[i].name)) {
854 curl_easy_setopt(result, CURLOPT_SSLVERSION,
855 sslversions[i].ssl_version);
856 break;
859 if (i == ARRAY_SIZE(sslversions))
860 warning("unsupported ssl version %s: using default",
861 ssl_version);
864 if (getenv("GIT_SSL_CIPHER_LIST"))
865 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
866 if (ssl_cipherlist != NULL && *ssl_cipherlist)
867 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
868 ssl_cipherlist);
870 if (ssl_cert)
871 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
872 if (has_cert_password())
873 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
874 if (ssl_key)
875 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
876 if (ssl_capath)
877 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
878 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
879 if (ssl_pinnedkey)
880 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
881 #endif
882 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
883 !http_schannel_use_ssl_cainfo) {
884 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
885 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
886 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
887 #endif
888 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
889 if (ssl_cainfo)
890 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
891 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
892 if (http_proxy_ssl_ca_info)
893 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
894 #endif
897 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
898 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
899 curl_low_speed_limit);
900 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
901 curl_low_speed_time);
904 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
905 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
907 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
909 struct strbuf buf = STRBUF_INIT;
911 get_curl_allowed_protocols(0, &buf);
912 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
913 strbuf_reset(&buf);
915 get_curl_allowed_protocols(-1, &buf);
916 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
917 strbuf_release(&buf);
919 #else
920 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
921 get_curl_allowed_protocols(0, NULL));
922 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
923 get_curl_allowed_protocols(-1, NULL));
924 #endif
926 if (getenv("GIT_CURL_VERBOSE"))
927 http_trace_curl_no_data();
928 setup_curl_trace(result);
929 if (getenv("GIT_TRACE_CURL_NO_DATA"))
930 trace_curl_data = 0;
931 if (!git_env_bool("GIT_TRACE_REDACT", 1))
932 trace_curl_redact = 0;
934 curl_easy_setopt(result, CURLOPT_USERAGENT,
935 user_agent ? user_agent : git_user_agent());
937 if (curl_ftp_no_epsv)
938 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
940 if (curl_ssl_try)
941 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
944 * CURL also examines these variables as a fallback; but we need to query
945 * them here in order to decide whether to prompt for missing password (cf.
946 * init_curl_proxy_auth()).
948 * Unlike many other common environment variables, these are historically
949 * lowercase only. It appears that CURL did not know this and implemented
950 * only uppercase variants, which was later corrected to take both - with
951 * the exception of http_proxy, which is lowercase only also in CURL. As
952 * the lowercase versions are the historical quasi-standard, they take
953 * precedence here, as in CURL.
955 if (!curl_http_proxy) {
956 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
957 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
958 var_override(&curl_http_proxy, getenv("https_proxy"));
959 } else {
960 var_override(&curl_http_proxy, getenv("http_proxy"));
962 if (!curl_http_proxy) {
963 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
964 var_override(&curl_http_proxy, getenv("all_proxy"));
968 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
970 * Handle case with the empty http.proxy value here to keep
971 * common code clean.
972 * NB: empty option disables proxying at all.
974 curl_easy_setopt(result, CURLOPT_PROXY, "");
975 } else if (curl_http_proxy) {
976 if (starts_with(curl_http_proxy, "socks5h"))
977 curl_easy_setopt(result,
978 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
979 else if (starts_with(curl_http_proxy, "socks5"))
980 curl_easy_setopt(result,
981 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
982 else if (starts_with(curl_http_proxy, "socks4a"))
983 curl_easy_setopt(result,
984 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
985 else if (starts_with(curl_http_proxy, "socks"))
986 curl_easy_setopt(result,
987 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
988 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
989 else if (starts_with(curl_http_proxy, "https")) {
990 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
992 if (http_proxy_ssl_cert)
993 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
995 if (http_proxy_ssl_key)
996 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
998 if (has_proxy_cert_password())
999 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1001 #endif
1002 if (strstr(curl_http_proxy, "://"))
1003 credential_from_url(&proxy_auth, curl_http_proxy);
1004 else {
1005 struct strbuf url = STRBUF_INIT;
1006 strbuf_addf(&url, "http://%s", curl_http_proxy);
1007 credential_from_url(&proxy_auth, url.buf);
1008 strbuf_release(&url);
1011 if (!proxy_auth.host)
1012 die("Invalid proxy URL '%s'", curl_http_proxy);
1014 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1015 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1016 var_override(&curl_no_proxy, getenv("no_proxy"));
1017 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1019 init_curl_proxy_auth(result);
1021 set_curl_keepalive(result);
1023 return result;
1026 static void set_from_env(const char **var, const char *envname)
1028 const char *val = getenv(envname);
1029 if (val)
1030 *var = val;
1033 void http_init(struct remote *remote, const char *url, int proactive_auth)
1035 char *low_speed_limit;
1036 char *low_speed_time;
1037 char *normalized_url;
1038 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1040 config.section = "http";
1041 config.key = NULL;
1042 config.collect_fn = http_options;
1043 config.cascade_fn = git_default_config;
1044 config.cb = NULL;
1046 http_is_verbose = 0;
1047 normalized_url = url_normalize(url, &config.url);
1049 git_config(urlmatch_config_entry, &config);
1050 free(normalized_url);
1051 string_list_clear(&config.vars, 1);
1053 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1054 if (http_ssl_backend) {
1055 const curl_ssl_backend **backends;
1056 struct strbuf buf = STRBUF_INIT;
1057 int i;
1059 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1060 case CURLSSLSET_UNKNOWN_BACKEND:
1061 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1062 "Supported SSL backends:"),
1063 http_ssl_backend);
1064 for (i = 0; backends[i]; i++)
1065 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1066 die("%s", buf.buf);
1067 case CURLSSLSET_NO_BACKENDS:
1068 die(_("Could not set SSL backend to '%s': "
1069 "cURL was built without SSL backends"),
1070 http_ssl_backend);
1071 case CURLSSLSET_TOO_LATE:
1072 die(_("Could not set SSL backend to '%s': already set"),
1073 http_ssl_backend);
1074 case CURLSSLSET_OK:
1075 break; /* Okay! */
1078 #endif
1080 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1081 die("curl_global_init failed");
1083 http_proactive_auth = proactive_auth;
1085 if (remote && remote->http_proxy)
1086 curl_http_proxy = xstrdup(remote->http_proxy);
1088 if (remote)
1089 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1091 pragma_header = curl_slist_append(http_copy_default_headers(),
1092 "Pragma: no-cache");
1093 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1094 "Pragma:");
1097 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1098 if (http_max_requests)
1099 max_requests = atoi(http_max_requests);
1102 curlm = curl_multi_init();
1103 if (!curlm)
1104 die("curl_multi_init failed");
1106 if (getenv("GIT_SSL_NO_VERIFY"))
1107 curl_ssl_verify = 0;
1109 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1110 set_from_env(&ssl_key, "GIT_SSL_KEY");
1111 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1112 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1114 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1116 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1117 if (low_speed_limit)
1118 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1119 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1120 if (low_speed_time)
1121 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1123 if (curl_ssl_verify == -1)
1124 curl_ssl_verify = 1;
1126 curl_session_count = 0;
1127 if (max_requests < 1)
1128 max_requests = DEFAULT_MAX_REQUESTS;
1130 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1131 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1132 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1134 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1135 proxy_ssl_cert_password_required = 1;
1137 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1138 curl_ftp_no_epsv = 1;
1140 if (url) {
1141 credential_from_url(&http_auth, url);
1142 if (!ssl_cert_password_required &&
1143 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1144 starts_with(url, "https://"))
1145 ssl_cert_password_required = 1;
1148 curl_default = get_curl_handle();
1151 void http_cleanup(void)
1153 struct active_request_slot *slot = active_queue_head;
1155 while (slot != NULL) {
1156 struct active_request_slot *next = slot->next;
1157 if (slot->curl) {
1158 xmulti_remove_handle(slot);
1159 curl_easy_cleanup(slot->curl);
1161 free(slot);
1162 slot = next;
1164 active_queue_head = NULL;
1166 curl_easy_cleanup(curl_default);
1168 curl_multi_cleanup(curlm);
1169 curl_global_cleanup();
1171 string_list_clear(&extra_http_headers, 0);
1173 curl_slist_free_all(pragma_header);
1174 pragma_header = NULL;
1176 curl_slist_free_all(no_pragma_header);
1177 no_pragma_header = NULL;
1179 curl_slist_free_all(host_resolutions);
1180 host_resolutions = NULL;
1182 if (curl_http_proxy) {
1183 free((void *)curl_http_proxy);
1184 curl_http_proxy = NULL;
1187 if (proxy_auth.password) {
1188 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1189 FREE_AND_NULL(proxy_auth.password);
1192 free((void *)curl_proxyuserpwd);
1193 curl_proxyuserpwd = NULL;
1195 free((void *)http_proxy_authmethod);
1196 http_proxy_authmethod = NULL;
1198 if (cert_auth.password) {
1199 memset(cert_auth.password, 0, strlen(cert_auth.password));
1200 FREE_AND_NULL(cert_auth.password);
1202 ssl_cert_password_required = 0;
1204 if (proxy_cert_auth.password) {
1205 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1206 FREE_AND_NULL(proxy_cert_auth.password);
1208 proxy_ssl_cert_password_required = 0;
1210 FREE_AND_NULL(cached_accept_language);
1213 struct active_request_slot *get_active_slot(void)
1215 struct active_request_slot *slot = active_queue_head;
1216 struct active_request_slot *newslot;
1218 int num_transfers;
1220 /* Wait for a slot to open up if the queue is full */
1221 while (active_requests >= max_requests) {
1222 curl_multi_perform(curlm, &num_transfers);
1223 if (num_transfers < active_requests)
1224 process_curl_messages();
1227 while (slot != NULL && slot->in_use)
1228 slot = slot->next;
1230 if (!slot) {
1231 newslot = xmalloc(sizeof(*newslot));
1232 newslot->curl = NULL;
1233 newslot->in_use = 0;
1234 newslot->next = NULL;
1236 slot = active_queue_head;
1237 if (!slot) {
1238 active_queue_head = newslot;
1239 } else {
1240 while (slot->next != NULL)
1241 slot = slot->next;
1242 slot->next = newslot;
1244 slot = newslot;
1247 if (!slot->curl) {
1248 slot->curl = curl_easy_duphandle(curl_default);
1249 curl_session_count++;
1252 active_requests++;
1253 slot->in_use = 1;
1254 slot->results = NULL;
1255 slot->finished = NULL;
1256 slot->callback_data = NULL;
1257 slot->callback_func = NULL;
1258 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1259 if (curl_save_cookies)
1260 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1261 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1262 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1263 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1264 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1265 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1266 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1267 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1268 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1269 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1270 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1271 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1274 * Default following to off unless "ALWAYS" is configured; this gives
1275 * callers a sane starting point, and they can tweak for individual
1276 * HTTP_FOLLOW_* cases themselves.
1278 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1279 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1280 else
1281 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1283 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1284 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1285 if (http_auth.password || curl_empty_auth_enabled())
1286 init_curl_http_auth(slot->curl);
1288 return slot;
1291 int start_active_slot(struct active_request_slot *slot)
1293 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1294 int num_transfers;
1296 if (curlm_result != CURLM_OK &&
1297 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1298 warning("curl_multi_add_handle failed: %s",
1299 curl_multi_strerror(curlm_result));
1300 active_requests--;
1301 slot->in_use = 0;
1302 return 0;
1306 * We know there must be something to do, since we just added
1307 * something.
1309 curl_multi_perform(curlm, &num_transfers);
1310 return 1;
1313 struct fill_chain {
1314 void *data;
1315 int (*fill)(void *);
1316 struct fill_chain *next;
1319 static struct fill_chain *fill_cfg;
1321 void add_fill_function(void *data, int (*fill)(void *))
1323 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1324 struct fill_chain **linkp = &fill_cfg;
1325 new_fill->data = data;
1326 new_fill->fill = fill;
1327 new_fill->next = NULL;
1328 while (*linkp)
1329 linkp = &(*linkp)->next;
1330 *linkp = new_fill;
1333 void fill_active_slots(void)
1335 struct active_request_slot *slot = active_queue_head;
1337 while (active_requests < max_requests) {
1338 struct fill_chain *fill;
1339 for (fill = fill_cfg; fill; fill = fill->next)
1340 if (fill->fill(fill->data))
1341 break;
1343 if (!fill)
1344 break;
1347 while (slot != NULL) {
1348 if (!slot->in_use && slot->curl != NULL
1349 && curl_session_count > min_curl_sessions) {
1350 curl_easy_cleanup(slot->curl);
1351 slot->curl = NULL;
1352 curl_session_count--;
1354 slot = slot->next;
1358 void step_active_slots(void)
1360 int num_transfers;
1361 CURLMcode curlm_result;
1363 do {
1364 curlm_result = curl_multi_perform(curlm, &num_transfers);
1365 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1366 if (num_transfers < active_requests) {
1367 process_curl_messages();
1368 fill_active_slots();
1372 void run_active_slot(struct active_request_slot *slot)
1374 fd_set readfds;
1375 fd_set writefds;
1376 fd_set excfds;
1377 int max_fd;
1378 struct timeval select_timeout;
1379 int finished = 0;
1381 slot->finished = &finished;
1382 while (!finished) {
1383 step_active_slots();
1385 if (slot->in_use) {
1386 long curl_timeout;
1387 curl_multi_timeout(curlm, &curl_timeout);
1388 if (curl_timeout == 0) {
1389 continue;
1390 } else if (curl_timeout == -1) {
1391 select_timeout.tv_sec = 0;
1392 select_timeout.tv_usec = 50000;
1393 } else {
1394 select_timeout.tv_sec = curl_timeout / 1000;
1395 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1398 max_fd = -1;
1399 FD_ZERO(&readfds);
1400 FD_ZERO(&writefds);
1401 FD_ZERO(&excfds);
1402 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1405 * It can happen that curl_multi_timeout returns a pathologically
1406 * long timeout when curl_multi_fdset returns no file descriptors
1407 * to read. See commit message for more details.
1409 if (max_fd < 0 &&
1410 (select_timeout.tv_sec > 0 ||
1411 select_timeout.tv_usec > 50000)) {
1412 select_timeout.tv_sec = 0;
1413 select_timeout.tv_usec = 50000;
1416 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1421 * The value of slot->finished we set before the loop was used
1422 * to set our "finished" variable when our request completed.
1424 * 1. The slot may not have been reused for another requst
1425 * yet, in which case it still has &finished.
1427 * 2. The slot may already be in-use to serve another request,
1428 * which can further be divided into two cases:
1430 * (a) If call run_active_slot() hasn't been called for that
1431 * other request, slot->finished would have been cleared
1432 * by get_active_slot() and has NULL.
1434 * (b) If the request did call run_active_slot(), then the
1435 * call would have updated slot->finished at the beginning
1436 * of this function, and with the clearing of the member
1437 * below, we would find that slot->finished is now NULL.
1439 * In all cases, slot->finished has no useful information to
1440 * anybody at this point. Some compilers warn us for
1441 * attempting to smuggle a pointer that is about to become
1442 * invalid, i.e. &finished. We clear it here to assure them.
1444 slot->finished = NULL;
1447 static void release_active_slot(struct active_request_slot *slot)
1449 closedown_active_slot(slot);
1450 if (slot->curl) {
1451 xmulti_remove_handle(slot);
1452 if (curl_session_count > min_curl_sessions) {
1453 curl_easy_cleanup(slot->curl);
1454 slot->curl = NULL;
1455 curl_session_count--;
1458 fill_active_slots();
1461 void finish_all_active_slots(void)
1463 struct active_request_slot *slot = active_queue_head;
1465 while (slot != NULL)
1466 if (slot->in_use) {
1467 run_active_slot(slot);
1468 slot = active_queue_head;
1469 } else {
1470 slot = slot->next;
1474 /* Helpers for modifying and creating URLs */
1475 static inline int needs_quote(int ch)
1477 if (((ch >= 'A') && (ch <= 'Z'))
1478 || ((ch >= 'a') && (ch <= 'z'))
1479 || ((ch >= '0') && (ch <= '9'))
1480 || (ch == '/')
1481 || (ch == '-')
1482 || (ch == '.'))
1483 return 0;
1484 return 1;
1487 static char *quote_ref_url(const char *base, const char *ref)
1489 struct strbuf buf = STRBUF_INIT;
1490 const char *cp;
1491 int ch;
1493 end_url_with_slash(&buf, base);
1495 for (cp = ref; (ch = *cp) != 0; cp++)
1496 if (needs_quote(ch))
1497 strbuf_addf(&buf, "%%%02x", ch);
1498 else
1499 strbuf_addch(&buf, *cp);
1501 return strbuf_detach(&buf, NULL);
1504 void append_remote_object_url(struct strbuf *buf, const char *url,
1505 const char *hex,
1506 int only_two_digit_prefix)
1508 end_url_with_slash(buf, url);
1510 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1511 if (!only_two_digit_prefix)
1512 strbuf_addstr(buf, hex + 2);
1515 char *get_remote_object_url(const char *url, const char *hex,
1516 int only_two_digit_prefix)
1518 struct strbuf buf = STRBUF_INIT;
1519 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1520 return strbuf_detach(&buf, NULL);
1523 void normalize_curl_result(CURLcode *result, long http_code,
1524 char *errorstr, size_t errorlen)
1527 * If we see a failing http code with CURLE_OK, we have turned off
1528 * FAILONERROR (to keep the server's custom error response), and should
1529 * translate the code into failure here.
1531 * Likewise, if we see a redirect (30x code), that means we turned off
1532 * redirect-following, and we should treat the result as an error.
1534 if (*result == CURLE_OK && http_code >= 300) {
1535 *result = CURLE_HTTP_RETURNED_ERROR;
1537 * Normally curl will already have put the "reason phrase"
1538 * from the server into curl_errorstr; unfortunately without
1539 * FAILONERROR it is lost, so we can give only the numeric
1540 * status code.
1542 xsnprintf(errorstr, errorlen,
1543 "The requested URL returned error: %ld",
1544 http_code);
1548 static int handle_curl_result(struct slot_results *results)
1550 normalize_curl_result(&results->curl_result, results->http_code,
1551 curl_errorstr, sizeof(curl_errorstr));
1553 if (results->curl_result == CURLE_OK) {
1554 credential_approve(&http_auth);
1555 credential_approve(&proxy_auth);
1556 credential_approve(&cert_auth);
1557 return HTTP_OK;
1558 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1560 * We can't tell from here whether it's a bad path, bad
1561 * certificate, bad password, or something else wrong
1562 * with the certificate. So we reject the credential to
1563 * avoid caching or saving a bad password.
1565 credential_reject(&cert_auth);
1566 return HTTP_NOAUTH;
1567 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1568 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1569 return HTTP_NOMATCHPUBLICKEY;
1570 #endif
1571 } else if (missing_target(results))
1572 return HTTP_MISSING_TARGET;
1573 else if (results->http_code == 401) {
1574 if (http_auth.username && http_auth.password) {
1575 credential_reject(&http_auth);
1576 return HTTP_NOAUTH;
1577 } else {
1578 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1579 if (results->auth_avail) {
1580 http_auth_methods &= results->auth_avail;
1581 http_auth_methods_restricted = 1;
1583 return HTTP_REAUTH;
1585 } else {
1586 if (results->http_connectcode == 407)
1587 credential_reject(&proxy_auth);
1588 if (!curl_errorstr[0])
1589 strlcpy(curl_errorstr,
1590 curl_easy_strerror(results->curl_result),
1591 sizeof(curl_errorstr));
1592 return HTTP_ERROR;
1596 int run_one_slot(struct active_request_slot *slot,
1597 struct slot_results *results)
1599 slot->results = results;
1600 if (!start_active_slot(slot)) {
1601 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1602 "failed to start HTTP request");
1603 return HTTP_START_FAILED;
1606 run_active_slot(slot);
1607 return handle_curl_result(results);
1610 struct curl_slist *http_copy_default_headers(void)
1612 struct curl_slist *headers = NULL;
1613 const struct string_list_item *item;
1615 for_each_string_list_item(item, &extra_http_headers)
1616 headers = curl_slist_append(headers, item->string);
1618 return headers;
1621 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1623 char *ptr;
1624 CURLcode ret;
1626 strbuf_reset(buf);
1627 ret = curl_easy_getinfo(curl, info, &ptr);
1628 if (!ret && ptr)
1629 strbuf_addstr(buf, ptr);
1630 return ret;
1634 * Check for and extract a content-type parameter. "raw"
1635 * should be positioned at the start of the potential
1636 * parameter, with any whitespace already removed.
1638 * "name" is the name of the parameter. The value is appended
1639 * to "out".
1641 static int extract_param(const char *raw, const char *name,
1642 struct strbuf *out)
1644 size_t len = strlen(name);
1646 if (strncasecmp(raw, name, len))
1647 return -1;
1648 raw += len;
1650 if (*raw != '=')
1651 return -1;
1652 raw++;
1654 while (*raw && !isspace(*raw) && *raw != ';')
1655 strbuf_addch(out, *raw++);
1656 return 0;
1660 * Extract a normalized version of the content type, with any
1661 * spaces suppressed, all letters lowercased, and no trailing ";"
1662 * or parameters.
1664 * Note that we will silently remove even invalid whitespace. For
1665 * example, "text / plain" is specifically forbidden by RFC 2616,
1666 * but "text/plain" is the only reasonable output, and this keeps
1667 * our code simple.
1669 * If the "charset" argument is not NULL, store the value of any
1670 * charset parameter there.
1672 * Example:
1673 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1674 * "text / plain" -> "text/plain"
1676 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1677 struct strbuf *charset)
1679 const char *p;
1681 strbuf_reset(type);
1682 strbuf_grow(type, raw->len);
1683 for (p = raw->buf; *p; p++) {
1684 if (isspace(*p))
1685 continue;
1686 if (*p == ';') {
1687 p++;
1688 break;
1690 strbuf_addch(type, tolower(*p));
1693 if (!charset)
1694 return;
1696 strbuf_reset(charset);
1697 while (*p) {
1698 while (isspace(*p) || *p == ';')
1699 p++;
1700 if (!extract_param(p, "charset", charset))
1701 return;
1702 while (*p && !isspace(*p))
1703 p++;
1706 if (!charset->len && starts_with(type->buf, "text/"))
1707 strbuf_addstr(charset, "ISO-8859-1");
1710 static void write_accept_language(struct strbuf *buf)
1713 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1714 * that, q-value will be smaller than 0.001, the minimum q-value the
1715 * HTTP specification allows. See
1716 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1718 const int MAX_DECIMAL_PLACES = 3;
1719 const int MAX_LANGUAGE_TAGS = 1000;
1720 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1721 char **language_tags = NULL;
1722 int num_langs = 0;
1723 const char *s = get_preferred_languages();
1724 int i;
1725 struct strbuf tag = STRBUF_INIT;
1727 /* Don't add Accept-Language header if no language is preferred. */
1728 if (!s)
1729 return;
1732 * Split the colon-separated string of preferred languages into
1733 * language_tags array.
1735 do {
1736 /* collect language tag */
1737 for (; *s && (isalnum(*s) || *s == '_'); s++)
1738 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1740 /* skip .codeset, @modifier and any other unnecessary parts */
1741 while (*s && *s != ':')
1742 s++;
1744 if (tag.len) {
1745 num_langs++;
1746 REALLOC_ARRAY(language_tags, num_langs);
1747 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1748 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1749 break;
1751 } while (*s++);
1753 /* write Accept-Language header into buf */
1754 if (num_langs) {
1755 int last_buf_len = 0;
1756 int max_q;
1757 int decimal_places;
1758 char q_format[32];
1760 /* add '*' */
1761 REALLOC_ARRAY(language_tags, num_langs + 1);
1762 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1764 /* compute decimal_places */
1765 for (max_q = 1, decimal_places = 0;
1766 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1767 decimal_places++, max_q *= 10)
1770 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1772 strbuf_addstr(buf, "Accept-Language: ");
1774 for (i = 0; i < num_langs; i++) {
1775 if (i > 0)
1776 strbuf_addstr(buf, ", ");
1778 strbuf_addstr(buf, language_tags[i]);
1780 if (i > 0)
1781 strbuf_addf(buf, q_format, max_q - i);
1783 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1784 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1785 break;
1788 last_buf_len = buf->len;
1792 /* free language tags -- last one is a static '*' */
1793 for (i = 0; i < num_langs - 1; i++)
1794 free(language_tags[i]);
1795 free(language_tags);
1799 * Get an Accept-Language header which indicates user's preferred languages.
1801 * Examples:
1802 * LANGUAGE= -> ""
1803 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1804 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1805 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1806 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1807 * LANGUAGE= LANG=C -> ""
1809 const char *http_get_accept_language_header(void)
1811 if (!cached_accept_language) {
1812 struct strbuf buf = STRBUF_INIT;
1813 write_accept_language(&buf);
1814 if (buf.len > 0)
1815 cached_accept_language = strbuf_detach(&buf, NULL);
1818 return cached_accept_language;
1821 static void http_opt_request_remainder(CURL *curl, off_t pos)
1823 char buf[128];
1824 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1825 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1828 /* http_request() targets */
1829 #define HTTP_REQUEST_STRBUF 0
1830 #define HTTP_REQUEST_FILE 1
1832 static int http_request(const char *url,
1833 void *result, int target,
1834 const struct http_get_options *options)
1836 struct active_request_slot *slot;
1837 struct slot_results results;
1838 struct curl_slist *headers = http_copy_default_headers();
1839 struct strbuf buf = STRBUF_INIT;
1840 const char *accept_language;
1841 int ret;
1843 slot = get_active_slot();
1844 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1846 if (!result) {
1847 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1848 } else {
1849 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1850 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
1852 if (target == HTTP_REQUEST_FILE) {
1853 off_t posn = ftello(result);
1854 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1855 fwrite);
1856 if (posn > 0)
1857 http_opt_request_remainder(slot->curl, posn);
1858 } else
1859 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1860 fwrite_buffer);
1863 accept_language = http_get_accept_language_header();
1865 if (accept_language)
1866 headers = curl_slist_append(headers, accept_language);
1868 strbuf_addstr(&buf, "Pragma:");
1869 if (options && options->no_cache)
1870 strbuf_addstr(&buf, " no-cache");
1871 if (options && options->initial_request &&
1872 http_follow_config == HTTP_FOLLOW_INITIAL)
1873 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1875 headers = curl_slist_append(headers, buf.buf);
1877 /* Add additional headers here */
1878 if (options && options->extra_headers) {
1879 const struct string_list_item *item;
1880 for_each_string_list_item(item, options->extra_headers) {
1881 headers = curl_slist_append(headers, item->string);
1885 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1886 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1887 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1888 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1890 ret = run_one_slot(slot, &results);
1892 if (options && options->content_type) {
1893 struct strbuf raw = STRBUF_INIT;
1894 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1895 extract_content_type(&raw, options->content_type,
1896 options->charset);
1897 strbuf_release(&raw);
1900 if (options && options->effective_url)
1901 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1902 options->effective_url);
1904 curl_slist_free_all(headers);
1905 strbuf_release(&buf);
1907 return ret;
1911 * Update the "base" url to a more appropriate value, as deduced by
1912 * redirects seen when requesting a URL starting with "url".
1914 * The "asked" parameter is a URL that we asked curl to access, and must begin
1915 * with "base".
1917 * The "got" parameter is the URL that curl reported to us as where we ended
1918 * up.
1920 * Returns 1 if we updated the base url, 0 otherwise.
1922 * Our basic strategy is to compare "base" and "asked" to find the bits
1923 * specific to our request. We then strip those bits off of "got" to yield the
1924 * new base. So for example, if our base is "http://example.com/foo.git",
1925 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1926 * with "https://other.example.com/foo.git/info/refs". We would want the
1927 * new URL to become "https://other.example.com/foo.git".
1929 * Note that this assumes a sane redirect scheme. It's entirely possible
1930 * in the example above to end up at a URL that does not even end in
1931 * "info/refs". In such a case we die. There's not much we can do, such a
1932 * scheme is unlikely to represent a real git repository, and failing to
1933 * rewrite the base opens options for malicious redirects to do funny things.
1935 static int update_url_from_redirect(struct strbuf *base,
1936 const char *asked,
1937 const struct strbuf *got)
1939 const char *tail;
1940 size_t new_len;
1942 if (!strcmp(asked, got->buf))
1943 return 0;
1945 if (!skip_prefix(asked, base->buf, &tail))
1946 BUG("update_url_from_redirect: %s is not a superset of %s",
1947 asked, base->buf);
1949 new_len = got->len;
1950 if (!strip_suffix_mem(got->buf, &new_len, tail))
1951 die(_("unable to update url base from redirection:\n"
1952 " asked for: %s\n"
1953 " redirect: %s"),
1954 asked, got->buf);
1956 strbuf_reset(base);
1957 strbuf_add(base, got->buf, new_len);
1959 return 1;
1962 static int http_request_reauth(const char *url,
1963 void *result, int target,
1964 struct http_get_options *options)
1966 int ret = http_request(url, result, target, options);
1968 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1969 return ret;
1971 if (options && options->effective_url && options->base_url) {
1972 if (update_url_from_redirect(options->base_url,
1973 url, options->effective_url)) {
1974 credential_from_url(&http_auth, options->base_url->buf);
1975 url = options->effective_url->buf;
1979 if (ret != HTTP_REAUTH)
1980 return ret;
1983 * The previous request may have put cruft into our output stream; we
1984 * should clear it out before making our next request.
1986 switch (target) {
1987 case HTTP_REQUEST_STRBUF:
1988 strbuf_reset(result);
1989 break;
1990 case HTTP_REQUEST_FILE:
1991 if (fflush(result)) {
1992 error_errno("unable to flush a file");
1993 return HTTP_START_FAILED;
1995 rewind(result);
1996 if (ftruncate(fileno(result), 0) < 0) {
1997 error_errno("unable to truncate a file");
1998 return HTTP_START_FAILED;
2000 break;
2001 default:
2002 BUG("Unknown http_request target");
2005 credential_fill(&http_auth);
2007 return http_request(url, result, target, options);
2010 int http_get_strbuf(const char *url,
2011 struct strbuf *result,
2012 struct http_get_options *options)
2014 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2018 * Downloads a URL and stores the result in the given file.
2020 * If a previous interrupted download is detected (i.e. a previous temporary
2021 * file is still around) the download is resumed.
2023 int http_get_file(const char *url, const char *filename,
2024 struct http_get_options *options)
2026 int ret;
2027 struct strbuf tmpfile = STRBUF_INIT;
2028 FILE *result;
2030 strbuf_addf(&tmpfile, "%s.temp", filename);
2031 result = fopen(tmpfile.buf, "a");
2032 if (!result) {
2033 error("Unable to open local file %s", tmpfile.buf);
2034 ret = HTTP_ERROR;
2035 goto cleanup;
2038 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2039 fclose(result);
2041 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2042 ret = HTTP_ERROR;
2043 cleanup:
2044 strbuf_release(&tmpfile);
2045 return ret;
2048 int http_fetch_ref(const char *base, struct ref *ref)
2050 struct http_get_options options = {0};
2051 char *url;
2052 struct strbuf buffer = STRBUF_INIT;
2053 int ret = -1;
2055 options.no_cache = 1;
2057 url = quote_ref_url(base, ref->name);
2058 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2059 strbuf_rtrim(&buffer);
2060 if (buffer.len == the_hash_algo->hexsz)
2061 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2062 else if (starts_with(buffer.buf, "ref: ")) {
2063 ref->symref = xstrdup(buffer.buf + 5);
2064 ret = 0;
2068 strbuf_release(&buffer);
2069 free(url);
2070 return ret;
2073 /* Helpers for fetching packs */
2074 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2076 char *url, *tmp;
2077 struct strbuf buf = STRBUF_INIT;
2079 if (http_is_verbose)
2080 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2082 end_url_with_slash(&buf, base_url);
2083 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2084 url = strbuf_detach(&buf, NULL);
2086 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2087 tmp = strbuf_detach(&buf, NULL);
2089 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2090 error("Unable to get pack index %s", url);
2091 FREE_AND_NULL(tmp);
2094 free(url);
2095 return tmp;
2098 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2099 unsigned char *sha1, const char *base_url)
2101 struct packed_git *new_pack;
2102 char *tmp_idx = NULL;
2103 int ret;
2105 if (has_pack_index(sha1)) {
2106 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2107 if (!new_pack)
2108 return -1; /* parse_pack_index() already issued error message */
2109 goto add_pack;
2112 tmp_idx = fetch_pack_index(sha1, base_url);
2113 if (!tmp_idx)
2114 return -1;
2116 new_pack = parse_pack_index(sha1, tmp_idx);
2117 if (!new_pack) {
2118 unlink(tmp_idx);
2119 free(tmp_idx);
2121 return -1; /* parse_pack_index() already issued error message */
2124 ret = verify_pack_index(new_pack);
2125 if (!ret) {
2126 close_pack_index(new_pack);
2127 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2129 free(tmp_idx);
2130 if (ret)
2131 return -1;
2133 add_pack:
2134 new_pack->next = *packs_head;
2135 *packs_head = new_pack;
2136 return 0;
2139 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2141 struct http_get_options options = {0};
2142 int ret = 0;
2143 char *url;
2144 const char *data;
2145 struct strbuf buf = STRBUF_INIT;
2146 struct object_id oid;
2148 end_url_with_slash(&buf, base_url);
2149 strbuf_addstr(&buf, "objects/info/packs");
2150 url = strbuf_detach(&buf, NULL);
2152 options.no_cache = 1;
2153 ret = http_get_strbuf(url, &buf, &options);
2154 if (ret != HTTP_OK)
2155 goto cleanup;
2157 data = buf.buf;
2158 while (*data) {
2159 if (skip_prefix(data, "P pack-", &data) &&
2160 !parse_oid_hex(data, &oid, &data) &&
2161 skip_prefix(data, ".pack", &data) &&
2162 (*data == '\n' || *data == '\0')) {
2163 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2164 } else {
2165 data = strchrnul(data, '\n');
2167 if (*data)
2168 data++; /* skip past newline */
2171 cleanup:
2172 free(url);
2173 return ret;
2176 void release_http_pack_request(struct http_pack_request *preq)
2178 if (preq->packfile) {
2179 fclose(preq->packfile);
2180 preq->packfile = NULL;
2182 preq->slot = NULL;
2183 strbuf_release(&preq->tmpfile);
2184 free(preq->url);
2185 free(preq);
2188 static const char *default_index_pack_args[] =
2189 {"index-pack", "--stdin", NULL};
2191 int finish_http_pack_request(struct http_pack_request *preq)
2193 struct child_process ip = CHILD_PROCESS_INIT;
2194 int tmpfile_fd;
2195 int ret = 0;
2197 fclose(preq->packfile);
2198 preq->packfile = NULL;
2200 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2202 ip.git_cmd = 1;
2203 ip.in = tmpfile_fd;
2204 strvec_pushv(&ip.args, preq->index_pack_args ?
2205 preq->index_pack_args :
2206 default_index_pack_args);
2208 if (preq->preserve_index_pack_stdout)
2209 ip.out = 0;
2210 else
2211 ip.no_stdout = 1;
2213 if (run_command(&ip)) {
2214 ret = -1;
2215 goto cleanup;
2218 cleanup:
2219 close(tmpfile_fd);
2220 unlink(preq->tmpfile.buf);
2221 return ret;
2224 void http_install_packfile(struct packed_git *p,
2225 struct packed_git **list_to_remove_from)
2227 struct packed_git **lst = list_to_remove_from;
2229 while (*lst != p)
2230 lst = &((*lst)->next);
2231 *lst = (*lst)->next;
2233 install_packed_git(the_repository, p);
2236 struct http_pack_request *new_http_pack_request(
2237 const unsigned char *packed_git_hash, const char *base_url) {
2239 struct strbuf buf = STRBUF_INIT;
2241 end_url_with_slash(&buf, base_url);
2242 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2243 hash_to_hex(packed_git_hash));
2244 return new_direct_http_pack_request(packed_git_hash,
2245 strbuf_detach(&buf, NULL));
2248 struct http_pack_request *new_direct_http_pack_request(
2249 const unsigned char *packed_git_hash, char *url)
2251 off_t prev_posn = 0;
2252 struct http_pack_request *preq;
2254 CALLOC_ARRAY(preq, 1);
2255 strbuf_init(&preq->tmpfile, 0);
2257 preq->url = url;
2259 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2260 preq->packfile = fopen(preq->tmpfile.buf, "a");
2261 if (!preq->packfile) {
2262 error("Unable to open local file %s for pack",
2263 preq->tmpfile.buf);
2264 goto abort;
2267 preq->slot = get_active_slot();
2268 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2269 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2270 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2271 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2272 no_pragma_header);
2275 * If there is data present from a previous transfer attempt,
2276 * resume where it left off
2278 prev_posn = ftello(preq->packfile);
2279 if (prev_posn>0) {
2280 if (http_is_verbose)
2281 fprintf(stderr,
2282 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2283 hash_to_hex(packed_git_hash),
2284 (uintmax_t)prev_posn);
2285 http_opt_request_remainder(preq->slot->curl, prev_posn);
2288 return preq;
2290 abort:
2291 strbuf_release(&preq->tmpfile);
2292 free(preq->url);
2293 free(preq);
2294 return NULL;
2297 /* Helpers for fetching objects (loose) */
2298 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2299 void *data)
2301 unsigned char expn[4096];
2302 size_t size = eltsize * nmemb;
2303 int posn = 0;
2304 struct http_object_request *freq = data;
2305 struct active_request_slot *slot = freq->slot;
2307 if (slot) {
2308 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2309 &slot->http_code);
2310 if (c != CURLE_OK)
2311 BUG("curl_easy_getinfo for HTTP code failed: %s",
2312 curl_easy_strerror(c));
2313 if (slot->http_code >= 300)
2314 return nmemb;
2317 do {
2318 ssize_t retval = xwrite(freq->localfile,
2319 (char *) ptr + posn, size - posn);
2320 if (retval < 0)
2321 return posn / eltsize;
2322 posn += retval;
2323 } while (posn < size);
2325 freq->stream.avail_in = size;
2326 freq->stream.next_in = (void *)ptr;
2327 do {
2328 freq->stream.next_out = expn;
2329 freq->stream.avail_out = sizeof(expn);
2330 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2331 the_hash_algo->update_fn(&freq->c, expn,
2332 sizeof(expn) - freq->stream.avail_out);
2333 } while (freq->stream.avail_in && freq->zret == Z_OK);
2334 return nmemb;
2337 struct http_object_request *new_http_object_request(const char *base_url,
2338 const struct object_id *oid)
2340 char *hex = oid_to_hex(oid);
2341 struct strbuf filename = STRBUF_INIT;
2342 struct strbuf prevfile = STRBUF_INIT;
2343 int prevlocal;
2344 char prev_buf[PREV_BUF_SIZE];
2345 ssize_t prev_read = 0;
2346 off_t prev_posn = 0;
2347 struct http_object_request *freq;
2349 CALLOC_ARRAY(freq, 1);
2350 strbuf_init(&freq->tmpfile, 0);
2351 oidcpy(&freq->oid, oid);
2352 freq->localfile = -1;
2354 loose_object_path(the_repository, &filename, oid);
2355 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2357 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2358 unlink_or_warn(prevfile.buf);
2359 rename(freq->tmpfile.buf, prevfile.buf);
2360 unlink_or_warn(freq->tmpfile.buf);
2361 strbuf_release(&filename);
2363 if (freq->localfile != -1)
2364 error("fd leakage in start: %d", freq->localfile);
2365 freq->localfile = open(freq->tmpfile.buf,
2366 O_WRONLY | O_CREAT | O_EXCL, 0666);
2368 * This could have failed due to the "lazy directory creation";
2369 * try to mkdir the last path component.
2371 if (freq->localfile < 0 && errno == ENOENT) {
2372 char *dir = strrchr(freq->tmpfile.buf, '/');
2373 if (dir) {
2374 *dir = 0;
2375 mkdir(freq->tmpfile.buf, 0777);
2376 *dir = '/';
2378 freq->localfile = open(freq->tmpfile.buf,
2379 O_WRONLY | O_CREAT | O_EXCL, 0666);
2382 if (freq->localfile < 0) {
2383 error_errno("Couldn't create temporary file %s",
2384 freq->tmpfile.buf);
2385 goto abort;
2388 git_inflate_init(&freq->stream);
2390 the_hash_algo->init_fn(&freq->c);
2392 freq->url = get_remote_object_url(base_url, hex, 0);
2395 * If a previous temp file is present, process what was already
2396 * fetched.
2398 prevlocal = open(prevfile.buf, O_RDONLY);
2399 if (prevlocal != -1) {
2400 do {
2401 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2402 if (prev_read>0) {
2403 if (fwrite_sha1_file(prev_buf,
2405 prev_read,
2406 freq) == prev_read) {
2407 prev_posn += prev_read;
2408 } else {
2409 prev_read = -1;
2412 } while (prev_read > 0);
2413 close(prevlocal);
2415 unlink_or_warn(prevfile.buf);
2416 strbuf_release(&prevfile);
2419 * Reset inflate/SHA1 if there was an error reading the previous temp
2420 * file; also rewind to the beginning of the local file.
2422 if (prev_read == -1) {
2423 memset(&freq->stream, 0, sizeof(freq->stream));
2424 git_inflate_init(&freq->stream);
2425 the_hash_algo->init_fn(&freq->c);
2426 if (prev_posn>0) {
2427 prev_posn = 0;
2428 lseek(freq->localfile, 0, SEEK_SET);
2429 if (ftruncate(freq->localfile, 0) < 0) {
2430 error_errno("Couldn't truncate temporary file %s",
2431 freq->tmpfile.buf);
2432 goto abort;
2437 freq->slot = get_active_slot();
2439 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2440 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2441 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2442 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2443 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2444 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2447 * If we have successfully processed data from a previous fetch
2448 * attempt, only fetch the data we don't already have.
2450 if (prev_posn>0) {
2451 if (http_is_verbose)
2452 fprintf(stderr,
2453 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2454 hex, (uintmax_t)prev_posn);
2455 http_opt_request_remainder(freq->slot->curl, prev_posn);
2458 return freq;
2460 abort:
2461 strbuf_release(&prevfile);
2462 free(freq->url);
2463 free(freq);
2464 return NULL;
2467 void process_http_object_request(struct http_object_request *freq)
2469 if (!freq->slot)
2470 return;
2471 freq->curl_result = freq->slot->curl_result;
2472 freq->http_code = freq->slot->http_code;
2473 freq->slot = NULL;
2476 int finish_http_object_request(struct http_object_request *freq)
2478 struct stat st;
2479 struct strbuf filename = STRBUF_INIT;
2481 close(freq->localfile);
2482 freq->localfile = -1;
2484 process_http_object_request(freq);
2486 if (freq->http_code == 416) {
2487 warning("requested range invalid; we may already have all the data.");
2488 } else if (freq->curl_result != CURLE_OK) {
2489 if (stat(freq->tmpfile.buf, &st) == 0)
2490 if (st.st_size == 0)
2491 unlink_or_warn(freq->tmpfile.buf);
2492 return -1;
2495 git_inflate_end(&freq->stream);
2496 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2497 if (freq->zret != Z_STREAM_END) {
2498 unlink_or_warn(freq->tmpfile.buf);
2499 return -1;
2501 if (!oideq(&freq->oid, &freq->real_oid)) {
2502 unlink_or_warn(freq->tmpfile.buf);
2503 return -1;
2505 loose_object_path(the_repository, &filename, &freq->oid);
2506 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2507 strbuf_release(&filename);
2509 return freq->rename;
2512 void abort_http_object_request(struct http_object_request *freq)
2514 unlink_or_warn(freq->tmpfile.buf);
2516 release_http_object_request(freq);
2519 void release_http_object_request(struct http_object_request *freq)
2521 if (freq->localfile != -1) {
2522 close(freq->localfile);
2523 freq->localfile = -1;
2525 FREE_AND_NULL(freq->url);
2526 if (freq->slot) {
2527 freq->slot->callback_func = NULL;
2528 freq->slot->callback_data = NULL;
2529 release_active_slot(freq->slot);
2530 freq->slot = NULL;
2532 strbuf_release(&freq->tmpfile);