Sync with 2.33.8
[git/debian.git] / http.c
blob7247234591c44f03a10d00d19a53548eb659ee28
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 active_request_slot *active_queue_head;
133 static char *cached_accept_language;
135 static char *http_ssl_backend;
137 static int http_schannel_check_revoke = 1;
139 * With the backend being set to `schannel`, setting sslCAinfo would override
140 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
141 * by default.
143 static int http_schannel_use_ssl_cainfo;
145 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
147 size_t size = eltsize * nmemb;
148 struct buffer *buffer = buffer_;
150 if (size > buffer->buf.len - buffer->posn)
151 size = buffer->buf.len - buffer->posn;
152 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
153 buffer->posn += size;
155 return size / eltsize;
158 int seek_buffer(void *clientp, curl_off_t offset, int origin)
160 struct buffer *buffer = clientp;
162 if (origin != SEEK_SET)
163 BUG("seek_buffer only handles SEEK_SET");
164 if (offset < 0 || offset >= buffer->buf.len) {
165 error("curl seek would be outside of buffer");
166 return CURL_SEEKFUNC_FAIL;
169 buffer->posn = offset;
170 return CURL_SEEKFUNC_OK;
173 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
175 size_t size = eltsize * nmemb;
176 struct strbuf *buffer = buffer_;
178 strbuf_add(buffer, ptr, size);
179 return nmemb;
182 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
184 return nmemb;
187 static void closedown_active_slot(struct active_request_slot *slot)
189 active_requests--;
190 slot->in_use = 0;
193 static void finish_active_slot(struct active_request_slot *slot)
195 closedown_active_slot(slot);
196 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
198 if (slot->finished != NULL)
199 (*slot->finished) = 1;
201 /* Store slot results so they can be read after the slot is reused */
202 if (slot->results != NULL) {
203 slot->results->curl_result = slot->curl_result;
204 slot->results->http_code = slot->http_code;
205 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
206 &slot->results->auth_avail);
208 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
209 &slot->results->http_connectcode);
212 /* Run callback if appropriate */
213 if (slot->callback_func != NULL)
214 slot->callback_func(slot->callback_data);
217 static void xmulti_remove_handle(struct active_request_slot *slot)
219 curl_multi_remove_handle(curlm, slot->curl);
222 static void process_curl_messages(void)
224 int num_messages;
225 struct active_request_slot *slot;
226 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
228 while (curl_message != NULL) {
229 if (curl_message->msg == CURLMSG_DONE) {
230 int curl_result = curl_message->data.result;
231 slot = active_queue_head;
232 while (slot != NULL &&
233 slot->curl != curl_message->easy_handle)
234 slot = slot->next;
235 if (slot != NULL) {
236 xmulti_remove_handle(slot);
237 slot->curl_result = curl_result;
238 finish_active_slot(slot);
239 } else {
240 fprintf(stderr, "Received DONE message for unknown request!\n");
242 } else {
243 fprintf(stderr, "Unknown CURL message received: %d\n",
244 (int)curl_message->msg);
246 curl_message = curl_multi_info_read(curlm, &num_messages);
250 static int http_options(const char *var, const char *value, void *cb)
252 if (!strcmp("http.version", var)) {
253 return git_config_string(&curl_http_version, var, value);
255 if (!strcmp("http.sslverify", var)) {
256 curl_ssl_verify = git_config_bool(var, value);
257 return 0;
259 if (!strcmp("http.sslcipherlist", var))
260 return git_config_string(&ssl_cipherlist, var, value);
261 if (!strcmp("http.sslversion", var))
262 return git_config_string(&ssl_version, var, value);
263 if (!strcmp("http.sslcert", var))
264 return git_config_pathname(&ssl_cert, var, value);
265 if (!strcmp("http.sslkey", var))
266 return git_config_pathname(&ssl_key, var, value);
267 if (!strcmp("http.sslcapath", var))
268 return git_config_pathname(&ssl_capath, var, value);
269 if (!strcmp("http.sslcainfo", var))
270 return git_config_pathname(&ssl_cainfo, var, value);
271 if (!strcmp("http.sslcertpasswordprotected", var)) {
272 ssl_cert_password_required = git_config_bool(var, value);
273 return 0;
275 if (!strcmp("http.ssltry", var)) {
276 curl_ssl_try = git_config_bool(var, value);
277 return 0;
279 if (!strcmp("http.sslbackend", var)) {
280 free(http_ssl_backend);
281 http_ssl_backend = xstrdup_or_null(value);
282 return 0;
285 if (!strcmp("http.schannelcheckrevoke", var)) {
286 http_schannel_check_revoke = git_config_bool(var, value);
287 return 0;
290 if (!strcmp("http.schannelusesslcainfo", var)) {
291 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
292 return 0;
295 if (!strcmp("http.minsessions", var)) {
296 min_curl_sessions = git_config_int(var, value);
297 if (min_curl_sessions > 1)
298 min_curl_sessions = 1;
299 return 0;
301 if (!strcmp("http.maxrequests", var)) {
302 max_requests = git_config_int(var, value);
303 return 0;
305 if (!strcmp("http.lowspeedlimit", var)) {
306 curl_low_speed_limit = (long)git_config_int(var, value);
307 return 0;
309 if (!strcmp("http.lowspeedtime", var)) {
310 curl_low_speed_time = (long)git_config_int(var, value);
311 return 0;
314 if (!strcmp("http.noepsv", var)) {
315 curl_ftp_no_epsv = git_config_bool(var, value);
316 return 0;
318 if (!strcmp("http.proxy", var))
319 return git_config_string(&curl_http_proxy, var, value);
321 if (!strcmp("http.proxyauthmethod", var))
322 return git_config_string(&http_proxy_authmethod, var, value);
324 if (!strcmp("http.proxysslcert", var))
325 return git_config_string(&http_proxy_ssl_cert, var, value);
327 if (!strcmp("http.proxysslkey", var))
328 return git_config_string(&http_proxy_ssl_key, var, value);
330 if (!strcmp("http.proxysslcainfo", var))
331 return git_config_string(&http_proxy_ssl_ca_info, var, value);
333 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
334 proxy_ssl_cert_password_required = git_config_bool(var, value);
335 return 0;
338 if (!strcmp("http.cookiefile", var))
339 return git_config_pathname(&curl_cookie_file, var, value);
340 if (!strcmp("http.savecookies", var)) {
341 curl_save_cookies = git_config_bool(var, value);
342 return 0;
345 if (!strcmp("http.postbuffer", var)) {
346 http_post_buffer = git_config_ssize_t(var, value);
347 if (http_post_buffer < 0)
348 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
349 if (http_post_buffer < LARGE_PACKET_MAX)
350 http_post_buffer = LARGE_PACKET_MAX;
351 return 0;
354 if (!strcmp("http.useragent", var))
355 return git_config_string(&user_agent, var, value);
357 if (!strcmp("http.emptyauth", var)) {
358 if (value && !strcmp("auto", value))
359 curl_empty_auth = -1;
360 else
361 curl_empty_auth = git_config_bool(var, value);
362 return 0;
365 if (!strcmp("http.delegation", var)) {
366 #ifdef CURLGSSAPI_DELEGATION_FLAG
367 return git_config_string(&curl_deleg, var, value);
368 #else
369 warning(_("Delegation control is not supported with cURL < 7.22.0"));
370 return 0;
371 #endif
374 if (!strcmp("http.pinnedpubkey", var)) {
375 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
376 return git_config_pathname(&ssl_pinnedkey, var, value);
377 #else
378 warning(_("Public key pinning not supported with cURL < 7.39.0"));
379 return 0;
380 #endif
383 if (!strcmp("http.extraheader", var)) {
384 if (!value) {
385 return config_error_nonbool(var);
386 } else if (!*value) {
387 string_list_clear(&extra_http_headers, 0);
388 } else {
389 string_list_append(&extra_http_headers, value);
391 return 0;
394 if (!strcmp("http.followredirects", var)) {
395 if (value && !strcmp(value, "initial"))
396 http_follow_config = HTTP_FOLLOW_INITIAL;
397 else if (git_config_bool(var, value))
398 http_follow_config = HTTP_FOLLOW_ALWAYS;
399 else
400 http_follow_config = HTTP_FOLLOW_NONE;
401 return 0;
404 /* Fall back on the default ones */
405 return git_default_config(var, value, cb);
408 static int curl_empty_auth_enabled(void)
410 if (curl_empty_auth >= 0)
411 return curl_empty_auth;
414 * In the automatic case, kick in the empty-auth
415 * hack as long as we would potentially try some
416 * method more exotic than "Basic" or "Digest".
418 * But only do this when this is our second or
419 * subsequent request, as by then we know what
420 * methods are available.
422 if (http_auth_methods_restricted &&
423 (http_auth_methods & ~empty_auth_useless))
424 return 1;
425 return 0;
428 static void init_curl_http_auth(CURL *result)
430 if (!http_auth.username || !*http_auth.username) {
431 if (curl_empty_auth_enabled())
432 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
433 return;
436 credential_fill(&http_auth);
438 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
439 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
442 /* *var must be free-able */
443 static void var_override(const char **var, char *value)
445 if (value) {
446 free((void *)*var);
447 *var = xstrdup(value);
451 static void set_proxyauth_name_password(CURL *result)
453 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
454 proxy_auth.username);
455 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
456 proxy_auth.password);
459 static void init_curl_proxy_auth(CURL *result)
461 if (proxy_auth.username) {
462 if (!proxy_auth.password)
463 credential_fill(&proxy_auth);
464 set_proxyauth_name_password(result);
467 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
469 if (http_proxy_authmethod) {
470 int i;
471 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
472 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
473 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
474 proxy_authmethods[i].curlauth_param);
475 break;
478 if (i == ARRAY_SIZE(proxy_authmethods)) {
479 warning("unsupported proxy authentication method %s: using anyauth",
480 http_proxy_authmethod);
481 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
484 else
485 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
488 static int has_cert_password(void)
490 if (ssl_cert == NULL || ssl_cert_password_required != 1)
491 return 0;
492 if (!cert_auth.password) {
493 cert_auth.protocol = xstrdup("cert");
494 cert_auth.host = xstrdup("");
495 cert_auth.username = xstrdup("");
496 cert_auth.path = xstrdup(ssl_cert);
497 credential_fill(&cert_auth);
499 return 1;
502 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
503 static int has_proxy_cert_password(void)
505 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
506 return 0;
507 if (!proxy_cert_auth.password) {
508 proxy_cert_auth.protocol = xstrdup("cert");
509 proxy_cert_auth.host = xstrdup("");
510 proxy_cert_auth.username = xstrdup("");
511 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
512 credential_fill(&proxy_cert_auth);
514 return 1;
516 #endif
518 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
519 static void set_curl_keepalive(CURL *c)
521 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
524 #else
525 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
527 int ka = 1;
528 int rc;
529 socklen_t len = (socklen_t)sizeof(ka);
531 if (type != CURLSOCKTYPE_IPCXN)
532 return 0;
534 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
535 if (rc < 0)
536 warning_errno("unable to set SO_KEEPALIVE on socket");
538 return CURL_SOCKOPT_OK;
541 static void set_curl_keepalive(CURL *c)
543 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
545 #endif
547 static void redact_sensitive_header(struct strbuf *header)
549 const char *sensitive_header;
551 if (trace_curl_redact &&
552 (skip_iprefix(header->buf, "Authorization:", &sensitive_header) ||
553 skip_iprefix(header->buf, "Proxy-Authorization:", &sensitive_header))) {
554 /* The first token is the type, which is OK to log */
555 while (isspace(*sensitive_header))
556 sensitive_header++;
557 while (*sensitive_header && !isspace(*sensitive_header))
558 sensitive_header++;
559 /* Everything else is opaque and possibly sensitive */
560 strbuf_setlen(header, sensitive_header - header->buf);
561 strbuf_addstr(header, " <redacted>");
562 } else if (trace_curl_redact &&
563 skip_iprefix(header->buf, "Cookie:", &sensitive_header)) {
564 struct strbuf redacted_header = STRBUF_INIT;
565 const char *cookie;
567 while (isspace(*sensitive_header))
568 sensitive_header++;
570 cookie = sensitive_header;
572 while (cookie) {
573 char *equals;
574 char *semicolon = strstr(cookie, "; ");
575 if (semicolon)
576 *semicolon = 0;
577 equals = strchrnul(cookie, '=');
578 if (!equals) {
579 /* invalid cookie, just append and continue */
580 strbuf_addstr(&redacted_header, cookie);
581 continue;
583 strbuf_add(&redacted_header, cookie, equals - cookie);
584 strbuf_addstr(&redacted_header, "=<redacted>");
585 if (semicolon) {
587 * There are more cookies. (Or, for some
588 * reason, the input string ends in "; ".)
590 strbuf_addstr(&redacted_header, "; ");
591 cookie = semicolon + strlen("; ");
592 } else {
593 cookie = NULL;
597 strbuf_setlen(header, sensitive_header - header->buf);
598 strbuf_addbuf(header, &redacted_header);
602 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
604 struct strbuf out = STRBUF_INIT;
605 struct strbuf **headers, **header;
607 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
608 text, (long)size, (long)size);
609 trace_strbuf(&trace_curl, &out);
610 strbuf_reset(&out);
611 strbuf_add(&out, ptr, size);
612 headers = strbuf_split_max(&out, '\n', 0);
614 for (header = headers; *header; header++) {
615 if (hide_sensitive_header)
616 redact_sensitive_header(*header);
617 strbuf_insertstr((*header), 0, text);
618 strbuf_insertstr((*header), strlen(text), ": ");
619 strbuf_rtrim((*header));
620 strbuf_addch((*header), '\n');
621 trace_strbuf(&trace_curl, (*header));
623 strbuf_list_free(headers);
624 strbuf_release(&out);
627 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
629 size_t i;
630 struct strbuf out = STRBUF_INIT;
631 unsigned int width = 60;
633 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
634 text, (long)size, (long)size);
635 trace_strbuf(&trace_curl, &out);
637 for (i = 0; i < size; i += width) {
638 size_t w;
640 strbuf_reset(&out);
641 strbuf_addf(&out, "%s: ", text);
642 for (w = 0; (w < width) && (i + w < size); w++) {
643 unsigned char ch = ptr[i + w];
645 strbuf_addch(&out,
646 (ch >= 0x20) && (ch < 0x80)
647 ? ch : '.');
649 strbuf_addch(&out, '\n');
650 trace_strbuf(&trace_curl, &out);
652 strbuf_release(&out);
655 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
657 const char *text;
658 enum { NO_FILTER = 0, DO_FILTER = 1 };
660 switch (type) {
661 case CURLINFO_TEXT:
662 trace_printf_key(&trace_curl, "== Info: %s", data);
663 break;
664 case CURLINFO_HEADER_OUT:
665 text = "=> Send header";
666 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
667 break;
668 case CURLINFO_DATA_OUT:
669 if (trace_curl_data) {
670 text = "=> Send data";
671 curl_dump_data(text, (unsigned char *)data, size);
673 break;
674 case CURLINFO_SSL_DATA_OUT:
675 if (trace_curl_data) {
676 text = "=> Send SSL data";
677 curl_dump_data(text, (unsigned char *)data, size);
679 break;
680 case CURLINFO_HEADER_IN:
681 text = "<= Recv header";
682 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
683 break;
684 case CURLINFO_DATA_IN:
685 if (trace_curl_data) {
686 text = "<= Recv data";
687 curl_dump_data(text, (unsigned char *)data, size);
689 break;
690 case CURLINFO_SSL_DATA_IN:
691 if (trace_curl_data) {
692 text = "<= Recv SSL data";
693 curl_dump_data(text, (unsigned char *)data, size);
695 break;
697 default: /* we ignore unknown types by default */
698 return 0;
700 return 0;
703 void http_trace_curl_no_data(void)
705 trace_override_envvar(&trace_curl, "1");
706 trace_curl_data = 0;
709 void setup_curl_trace(CURL *handle)
711 if (!trace_want(&trace_curl))
712 return;
713 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
714 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
715 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
718 static void proto_list_append(struct strbuf *list, const char *proto)
720 if (!list)
721 return;
722 if (list->len)
723 strbuf_addch(list, ',');
724 strbuf_addstr(list, proto);
727 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
729 long bits = 0;
731 if (is_transport_allowed("http", from_user)) {
732 bits |= CURLPROTO_HTTP;
733 proto_list_append(list, "http");
735 if (is_transport_allowed("https", from_user)) {
736 bits |= CURLPROTO_HTTPS;
737 proto_list_append(list, "https");
739 if (is_transport_allowed("ftp", from_user)) {
740 bits |= CURLPROTO_FTP;
741 proto_list_append(list, "ftp");
743 if (is_transport_allowed("ftps", from_user)) {
744 bits |= CURLPROTO_FTPS;
745 proto_list_append(list, "ftps");
748 return bits;
751 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
752 static int get_curl_http_version_opt(const char *version_string, long *opt)
754 int i;
755 static struct {
756 const char *name;
757 long opt_token;
758 } choice[] = {
759 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
760 { "HTTP/2", CURL_HTTP_VERSION_2 }
763 for (i = 0; i < ARRAY_SIZE(choice); i++) {
764 if (!strcmp(version_string, choice[i].name)) {
765 *opt = choice[i].opt_token;
766 return 0;
770 warning("unknown value given to http.version: '%s'", version_string);
771 return -1; /* not found */
774 #endif
776 static CURL *get_curl_handle(void)
778 CURL *result = curl_easy_init();
780 if (!result)
781 die("curl_easy_init failed");
783 if (!curl_ssl_verify) {
784 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
785 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
786 } else {
787 /* Verify authenticity of the peer's certificate */
788 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
789 /* The name in the cert must match whom we tried to connect */
790 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
793 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
794 if (curl_http_version) {
795 long opt;
796 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
797 /* Set request use http version */
798 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
801 #endif
803 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
804 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
806 #ifdef CURLGSSAPI_DELEGATION_FLAG
807 if (curl_deleg) {
808 int i;
809 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
810 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
811 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
812 curl_deleg_levels[i].curl_deleg_param);
813 break;
816 if (i == ARRAY_SIZE(curl_deleg_levels))
817 warning("Unknown delegation method '%s': using default",
818 curl_deleg);
820 #endif
822 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
823 !http_schannel_check_revoke) {
824 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
825 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
826 #else
827 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
828 #endif
831 if (http_proactive_auth)
832 init_curl_http_auth(result);
834 if (getenv("GIT_SSL_VERSION"))
835 ssl_version = getenv("GIT_SSL_VERSION");
836 if (ssl_version && *ssl_version) {
837 int i;
838 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
839 if (!strcmp(ssl_version, sslversions[i].name)) {
840 curl_easy_setopt(result, CURLOPT_SSLVERSION,
841 sslversions[i].ssl_version);
842 break;
845 if (i == ARRAY_SIZE(sslversions))
846 warning("unsupported ssl version %s: using default",
847 ssl_version);
850 if (getenv("GIT_SSL_CIPHER_LIST"))
851 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
852 if (ssl_cipherlist != NULL && *ssl_cipherlist)
853 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
854 ssl_cipherlist);
856 if (ssl_cert != NULL)
857 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
858 if (has_cert_password())
859 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
860 if (ssl_key != NULL)
861 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
862 if (ssl_capath != NULL)
863 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
864 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
865 if (ssl_pinnedkey != NULL)
866 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
867 #endif
868 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
869 !http_schannel_use_ssl_cainfo) {
870 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
871 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
872 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
873 #endif
874 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
875 if (ssl_cainfo != NULL)
876 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
877 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
878 if (http_proxy_ssl_ca_info != NULL)
879 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
880 #endif
883 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
884 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
885 curl_low_speed_limit);
886 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
887 curl_low_speed_time);
890 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
891 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
893 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
895 struct strbuf buf = STRBUF_INIT;
897 get_curl_allowed_protocols(0, &buf);
898 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
899 strbuf_reset(&buf);
901 get_curl_allowed_protocols(-1, &buf);
902 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
903 strbuf_release(&buf);
905 #else
906 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
907 get_curl_allowed_protocols(0, NULL));
908 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
909 get_curl_allowed_protocols(-1, NULL));
910 #endif
912 if (getenv("GIT_CURL_VERBOSE"))
913 http_trace_curl_no_data();
914 setup_curl_trace(result);
915 if (getenv("GIT_TRACE_CURL_NO_DATA"))
916 trace_curl_data = 0;
917 if (!git_env_bool("GIT_TRACE_REDACT", 1))
918 trace_curl_redact = 0;
920 curl_easy_setopt(result, CURLOPT_USERAGENT,
921 user_agent ? user_agent : git_user_agent());
923 if (curl_ftp_no_epsv)
924 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
926 if (curl_ssl_try)
927 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
930 * CURL also examines these variables as a fallback; but we need to query
931 * them here in order to decide whether to prompt for missing password (cf.
932 * init_curl_proxy_auth()).
934 * Unlike many other common environment variables, these are historically
935 * lowercase only. It appears that CURL did not know this and implemented
936 * only uppercase variants, which was later corrected to take both - with
937 * the exception of http_proxy, which is lowercase only also in CURL. As
938 * the lowercase versions are the historical quasi-standard, they take
939 * precedence here, as in CURL.
941 if (!curl_http_proxy) {
942 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
943 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
944 var_override(&curl_http_proxy, getenv("https_proxy"));
945 } else {
946 var_override(&curl_http_proxy, getenv("http_proxy"));
948 if (!curl_http_proxy) {
949 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
950 var_override(&curl_http_proxy, getenv("all_proxy"));
954 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
956 * Handle case with the empty http.proxy value here to keep
957 * common code clean.
958 * NB: empty option disables proxying at all.
960 curl_easy_setopt(result, CURLOPT_PROXY, "");
961 } else if (curl_http_proxy) {
962 if (starts_with(curl_http_proxy, "socks5h"))
963 curl_easy_setopt(result,
964 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
965 else if (starts_with(curl_http_proxy, "socks5"))
966 curl_easy_setopt(result,
967 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
968 else if (starts_with(curl_http_proxy, "socks4a"))
969 curl_easy_setopt(result,
970 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
971 else if (starts_with(curl_http_proxy, "socks"))
972 curl_easy_setopt(result,
973 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
974 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
975 else if (starts_with(curl_http_proxy, "https")) {
976 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
978 if (http_proxy_ssl_cert)
979 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
981 if (http_proxy_ssl_key)
982 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
984 if (has_proxy_cert_password())
985 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
987 #endif
988 if (strstr(curl_http_proxy, "://"))
989 credential_from_url(&proxy_auth, curl_http_proxy);
990 else {
991 struct strbuf url = STRBUF_INIT;
992 strbuf_addf(&url, "http://%s", curl_http_proxy);
993 credential_from_url(&proxy_auth, url.buf);
994 strbuf_release(&url);
997 if (!proxy_auth.host)
998 die("Invalid proxy URL '%s'", curl_http_proxy);
1000 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1001 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1002 var_override(&curl_no_proxy, getenv("no_proxy"));
1003 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1005 init_curl_proxy_auth(result);
1007 set_curl_keepalive(result);
1009 return result;
1012 static void set_from_env(const char **var, const char *envname)
1014 const char *val = getenv(envname);
1015 if (val)
1016 *var = val;
1019 void http_init(struct remote *remote, const char *url, int proactive_auth)
1021 char *low_speed_limit;
1022 char *low_speed_time;
1023 char *normalized_url;
1024 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1026 config.section = "http";
1027 config.key = NULL;
1028 config.collect_fn = http_options;
1029 config.cascade_fn = git_default_config;
1030 config.cb = NULL;
1032 http_is_verbose = 0;
1033 normalized_url = url_normalize(url, &config.url);
1035 git_config(urlmatch_config_entry, &config);
1036 free(normalized_url);
1037 string_list_clear(&config.vars, 1);
1039 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1040 if (http_ssl_backend) {
1041 const curl_ssl_backend **backends;
1042 struct strbuf buf = STRBUF_INIT;
1043 int i;
1045 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1046 case CURLSSLSET_UNKNOWN_BACKEND:
1047 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1048 "Supported SSL backends:"),
1049 http_ssl_backend);
1050 for (i = 0; backends[i]; i++)
1051 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1052 die("%s", buf.buf);
1053 case CURLSSLSET_NO_BACKENDS:
1054 die(_("Could not set SSL backend to '%s': "
1055 "cURL was built without SSL backends"),
1056 http_ssl_backend);
1057 case CURLSSLSET_TOO_LATE:
1058 die(_("Could not set SSL backend to '%s': already set"),
1059 http_ssl_backend);
1060 case CURLSSLSET_OK:
1061 break; /* Okay! */
1064 #endif
1066 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1067 die("curl_global_init failed");
1069 http_proactive_auth = proactive_auth;
1071 if (remote && remote->http_proxy)
1072 curl_http_proxy = xstrdup(remote->http_proxy);
1074 if (remote)
1075 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1077 pragma_header = curl_slist_append(http_copy_default_headers(),
1078 "Pragma: no-cache");
1079 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1080 "Pragma:");
1083 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1084 if (http_max_requests != NULL)
1085 max_requests = atoi(http_max_requests);
1088 curlm = curl_multi_init();
1089 if (!curlm)
1090 die("curl_multi_init failed");
1092 if (getenv("GIT_SSL_NO_VERIFY"))
1093 curl_ssl_verify = 0;
1095 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1096 set_from_env(&ssl_key, "GIT_SSL_KEY");
1097 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1098 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1100 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1102 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1103 if (low_speed_limit != NULL)
1104 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1105 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1106 if (low_speed_time != NULL)
1107 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1109 if (curl_ssl_verify == -1)
1110 curl_ssl_verify = 1;
1112 curl_session_count = 0;
1113 if (max_requests < 1)
1114 max_requests = DEFAULT_MAX_REQUESTS;
1116 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1117 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1118 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1120 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1121 proxy_ssl_cert_password_required = 1;
1123 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1124 curl_ftp_no_epsv = 1;
1126 if (url) {
1127 credential_from_url(&http_auth, url);
1128 if (!ssl_cert_password_required &&
1129 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1130 starts_with(url, "https://"))
1131 ssl_cert_password_required = 1;
1134 curl_default = get_curl_handle();
1137 void http_cleanup(void)
1139 struct active_request_slot *slot = active_queue_head;
1141 while (slot != NULL) {
1142 struct active_request_slot *next = slot->next;
1143 if (slot->curl != NULL) {
1144 xmulti_remove_handle(slot);
1145 curl_easy_cleanup(slot->curl);
1147 free(slot);
1148 slot = next;
1150 active_queue_head = NULL;
1152 curl_easy_cleanup(curl_default);
1154 curl_multi_cleanup(curlm);
1155 curl_global_cleanup();
1157 string_list_clear(&extra_http_headers, 0);
1159 curl_slist_free_all(pragma_header);
1160 pragma_header = NULL;
1162 curl_slist_free_all(no_pragma_header);
1163 no_pragma_header = NULL;
1165 if (curl_http_proxy) {
1166 free((void *)curl_http_proxy);
1167 curl_http_proxy = NULL;
1170 if (proxy_auth.password) {
1171 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1172 FREE_AND_NULL(proxy_auth.password);
1175 free((void *)curl_proxyuserpwd);
1176 curl_proxyuserpwd = NULL;
1178 free((void *)http_proxy_authmethod);
1179 http_proxy_authmethod = NULL;
1181 if (cert_auth.password != NULL) {
1182 memset(cert_auth.password, 0, strlen(cert_auth.password));
1183 FREE_AND_NULL(cert_auth.password);
1185 ssl_cert_password_required = 0;
1187 if (proxy_cert_auth.password != NULL) {
1188 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1189 FREE_AND_NULL(proxy_cert_auth.password);
1191 proxy_ssl_cert_password_required = 0;
1193 FREE_AND_NULL(cached_accept_language);
1196 struct active_request_slot *get_active_slot(void)
1198 struct active_request_slot *slot = active_queue_head;
1199 struct active_request_slot *newslot;
1201 int num_transfers;
1203 /* Wait for a slot to open up if the queue is full */
1204 while (active_requests >= max_requests) {
1205 curl_multi_perform(curlm, &num_transfers);
1206 if (num_transfers < active_requests)
1207 process_curl_messages();
1210 while (slot != NULL && slot->in_use)
1211 slot = slot->next;
1213 if (slot == NULL) {
1214 newslot = xmalloc(sizeof(*newslot));
1215 newslot->curl = NULL;
1216 newslot->in_use = 0;
1217 newslot->next = NULL;
1219 slot = active_queue_head;
1220 if (slot == NULL) {
1221 active_queue_head = newslot;
1222 } else {
1223 while (slot->next != NULL)
1224 slot = slot->next;
1225 slot->next = newslot;
1227 slot = newslot;
1230 if (slot->curl == NULL) {
1231 slot->curl = curl_easy_duphandle(curl_default);
1232 curl_session_count++;
1235 active_requests++;
1236 slot->in_use = 1;
1237 slot->results = NULL;
1238 slot->finished = NULL;
1239 slot->callback_data = NULL;
1240 slot->callback_func = NULL;
1241 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1242 if (curl_save_cookies)
1243 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1244 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1245 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1246 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1247 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1248 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1249 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1250 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1251 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1252 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1253 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1256 * Default following to off unless "ALWAYS" is configured; this gives
1257 * callers a sane starting point, and they can tweak for individual
1258 * HTTP_FOLLOW_* cases themselves.
1260 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1261 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1262 else
1263 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1265 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1266 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1267 if (http_auth.password || curl_empty_auth_enabled())
1268 init_curl_http_auth(slot->curl);
1270 return slot;
1273 int start_active_slot(struct active_request_slot *slot)
1275 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1276 int num_transfers;
1278 if (curlm_result != CURLM_OK &&
1279 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1280 warning("curl_multi_add_handle failed: %s",
1281 curl_multi_strerror(curlm_result));
1282 active_requests--;
1283 slot->in_use = 0;
1284 return 0;
1288 * We know there must be something to do, since we just added
1289 * something.
1291 curl_multi_perform(curlm, &num_transfers);
1292 return 1;
1295 struct fill_chain {
1296 void *data;
1297 int (*fill)(void *);
1298 struct fill_chain *next;
1301 static struct fill_chain *fill_cfg;
1303 void add_fill_function(void *data, int (*fill)(void *))
1305 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1306 struct fill_chain **linkp = &fill_cfg;
1307 new_fill->data = data;
1308 new_fill->fill = fill;
1309 new_fill->next = NULL;
1310 while (*linkp)
1311 linkp = &(*linkp)->next;
1312 *linkp = new_fill;
1315 void fill_active_slots(void)
1317 struct active_request_slot *slot = active_queue_head;
1319 while (active_requests < max_requests) {
1320 struct fill_chain *fill;
1321 for (fill = fill_cfg; fill; fill = fill->next)
1322 if (fill->fill(fill->data))
1323 break;
1325 if (!fill)
1326 break;
1329 while (slot != NULL) {
1330 if (!slot->in_use && slot->curl != NULL
1331 && curl_session_count > min_curl_sessions) {
1332 curl_easy_cleanup(slot->curl);
1333 slot->curl = NULL;
1334 curl_session_count--;
1336 slot = slot->next;
1340 void step_active_slots(void)
1342 int num_transfers;
1343 CURLMcode curlm_result;
1345 do {
1346 curlm_result = curl_multi_perform(curlm, &num_transfers);
1347 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1348 if (num_transfers < active_requests) {
1349 process_curl_messages();
1350 fill_active_slots();
1354 void run_active_slot(struct active_request_slot *slot)
1356 fd_set readfds;
1357 fd_set writefds;
1358 fd_set excfds;
1359 int max_fd;
1360 struct timeval select_timeout;
1361 int finished = 0;
1363 slot->finished = &finished;
1364 while (!finished) {
1365 step_active_slots();
1367 if (slot->in_use) {
1368 long curl_timeout;
1369 curl_multi_timeout(curlm, &curl_timeout);
1370 if (curl_timeout == 0) {
1371 continue;
1372 } else if (curl_timeout == -1) {
1373 select_timeout.tv_sec = 0;
1374 select_timeout.tv_usec = 50000;
1375 } else {
1376 select_timeout.tv_sec = curl_timeout / 1000;
1377 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1380 max_fd = -1;
1381 FD_ZERO(&readfds);
1382 FD_ZERO(&writefds);
1383 FD_ZERO(&excfds);
1384 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1387 * It can happen that curl_multi_timeout returns a pathologically
1388 * long timeout when curl_multi_fdset returns no file descriptors
1389 * to read. See commit message for more details.
1391 if (max_fd < 0 &&
1392 (select_timeout.tv_sec > 0 ||
1393 select_timeout.tv_usec > 50000)) {
1394 select_timeout.tv_sec = 0;
1395 select_timeout.tv_usec = 50000;
1398 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1403 * The value of slot->finished we set before the loop was used
1404 * to set our "finished" variable when our request completed.
1406 * 1. The slot may not have been reused for another requst
1407 * yet, in which case it still has &finished.
1409 * 2. The slot may already be in-use to serve another request,
1410 * which can further be divided into two cases:
1412 * (a) If call run_active_slot() hasn't been called for that
1413 * other request, slot->finished would have been cleared
1414 * by get_active_slot() and has NULL.
1416 * (b) If the request did call run_active_slot(), then the
1417 * call would have updated slot->finished at the beginning
1418 * of this function, and with the clearing of the member
1419 * below, we would find that slot->finished is now NULL.
1421 * In all cases, slot->finished has no useful information to
1422 * anybody at this point. Some compilers warn us for
1423 * attempting to smuggle a pointer that is about to become
1424 * invalid, i.e. &finished. We clear it here to assure them.
1426 slot->finished = NULL;
1429 static void release_active_slot(struct active_request_slot *slot)
1431 closedown_active_slot(slot);
1432 if (slot->curl) {
1433 xmulti_remove_handle(slot);
1434 if (curl_session_count > min_curl_sessions) {
1435 curl_easy_cleanup(slot->curl);
1436 slot->curl = NULL;
1437 curl_session_count--;
1440 fill_active_slots();
1443 void finish_all_active_slots(void)
1445 struct active_request_slot *slot = active_queue_head;
1447 while (slot != NULL)
1448 if (slot->in_use) {
1449 run_active_slot(slot);
1450 slot = active_queue_head;
1451 } else {
1452 slot = slot->next;
1456 /* Helpers for modifying and creating URLs */
1457 static inline int needs_quote(int ch)
1459 if (((ch >= 'A') && (ch <= 'Z'))
1460 || ((ch >= 'a') && (ch <= 'z'))
1461 || ((ch >= '0') && (ch <= '9'))
1462 || (ch == '/')
1463 || (ch == '-')
1464 || (ch == '.'))
1465 return 0;
1466 return 1;
1469 static char *quote_ref_url(const char *base, const char *ref)
1471 struct strbuf buf = STRBUF_INIT;
1472 const char *cp;
1473 int ch;
1475 end_url_with_slash(&buf, base);
1477 for (cp = ref; (ch = *cp) != 0; cp++)
1478 if (needs_quote(ch))
1479 strbuf_addf(&buf, "%%%02x", ch);
1480 else
1481 strbuf_addch(&buf, *cp);
1483 return strbuf_detach(&buf, NULL);
1486 void append_remote_object_url(struct strbuf *buf, const char *url,
1487 const char *hex,
1488 int only_two_digit_prefix)
1490 end_url_with_slash(buf, url);
1492 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1493 if (!only_two_digit_prefix)
1494 strbuf_addstr(buf, hex + 2);
1497 char *get_remote_object_url(const char *url, const char *hex,
1498 int only_two_digit_prefix)
1500 struct strbuf buf = STRBUF_INIT;
1501 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1502 return strbuf_detach(&buf, NULL);
1505 void normalize_curl_result(CURLcode *result, long http_code,
1506 char *errorstr, size_t errorlen)
1509 * If we see a failing http code with CURLE_OK, we have turned off
1510 * FAILONERROR (to keep the server's custom error response), and should
1511 * translate the code into failure here.
1513 * Likewise, if we see a redirect (30x code), that means we turned off
1514 * redirect-following, and we should treat the result as an error.
1516 if (*result == CURLE_OK && http_code >= 300) {
1517 *result = CURLE_HTTP_RETURNED_ERROR;
1519 * Normally curl will already have put the "reason phrase"
1520 * from the server into curl_errorstr; unfortunately without
1521 * FAILONERROR it is lost, so we can give only the numeric
1522 * status code.
1524 xsnprintf(errorstr, errorlen,
1525 "The requested URL returned error: %ld",
1526 http_code);
1530 static int handle_curl_result(struct slot_results *results)
1532 normalize_curl_result(&results->curl_result, results->http_code,
1533 curl_errorstr, sizeof(curl_errorstr));
1535 if (results->curl_result == CURLE_OK) {
1536 credential_approve(&http_auth);
1537 credential_approve(&proxy_auth);
1538 credential_approve(&cert_auth);
1539 return HTTP_OK;
1540 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1542 * We can't tell from here whether it's a bad path, bad
1543 * certificate, bad password, or something else wrong
1544 * with the certificate. So we reject the credential to
1545 * avoid caching or saving a bad password.
1547 credential_reject(&cert_auth);
1548 return HTTP_NOAUTH;
1549 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1550 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1551 return HTTP_NOMATCHPUBLICKEY;
1552 #endif
1553 } else if (missing_target(results))
1554 return HTTP_MISSING_TARGET;
1555 else if (results->http_code == 401) {
1556 if (http_auth.username && http_auth.password) {
1557 credential_reject(&http_auth);
1558 return HTTP_NOAUTH;
1559 } else {
1560 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1561 if (results->auth_avail) {
1562 http_auth_methods &= results->auth_avail;
1563 http_auth_methods_restricted = 1;
1565 return HTTP_REAUTH;
1567 } else {
1568 if (results->http_connectcode == 407)
1569 credential_reject(&proxy_auth);
1570 if (!curl_errorstr[0])
1571 strlcpy(curl_errorstr,
1572 curl_easy_strerror(results->curl_result),
1573 sizeof(curl_errorstr));
1574 return HTTP_ERROR;
1578 int run_one_slot(struct active_request_slot *slot,
1579 struct slot_results *results)
1581 slot->results = results;
1582 if (!start_active_slot(slot)) {
1583 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1584 "failed to start HTTP request");
1585 return HTTP_START_FAILED;
1588 run_active_slot(slot);
1589 return handle_curl_result(results);
1592 struct curl_slist *http_copy_default_headers(void)
1594 struct curl_slist *headers = NULL;
1595 const struct string_list_item *item;
1597 for_each_string_list_item(item, &extra_http_headers)
1598 headers = curl_slist_append(headers, item->string);
1600 return headers;
1603 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1605 char *ptr;
1606 CURLcode ret;
1608 strbuf_reset(buf);
1609 ret = curl_easy_getinfo(curl, info, &ptr);
1610 if (!ret && ptr)
1611 strbuf_addstr(buf, ptr);
1612 return ret;
1616 * Check for and extract a content-type parameter. "raw"
1617 * should be positioned at the start of the potential
1618 * parameter, with any whitespace already removed.
1620 * "name" is the name of the parameter. The value is appended
1621 * to "out".
1623 static int extract_param(const char *raw, const char *name,
1624 struct strbuf *out)
1626 size_t len = strlen(name);
1628 if (strncasecmp(raw, name, len))
1629 return -1;
1630 raw += len;
1632 if (*raw != '=')
1633 return -1;
1634 raw++;
1636 while (*raw && !isspace(*raw) && *raw != ';')
1637 strbuf_addch(out, *raw++);
1638 return 0;
1642 * Extract a normalized version of the content type, with any
1643 * spaces suppressed, all letters lowercased, and no trailing ";"
1644 * or parameters.
1646 * Note that we will silently remove even invalid whitespace. For
1647 * example, "text / plain" is specifically forbidden by RFC 2616,
1648 * but "text/plain" is the only reasonable output, and this keeps
1649 * our code simple.
1651 * If the "charset" argument is not NULL, store the value of any
1652 * charset parameter there.
1654 * Example:
1655 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1656 * "text / plain" -> "text/plain"
1658 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1659 struct strbuf *charset)
1661 const char *p;
1663 strbuf_reset(type);
1664 strbuf_grow(type, raw->len);
1665 for (p = raw->buf; *p; p++) {
1666 if (isspace(*p))
1667 continue;
1668 if (*p == ';') {
1669 p++;
1670 break;
1672 strbuf_addch(type, tolower(*p));
1675 if (!charset)
1676 return;
1678 strbuf_reset(charset);
1679 while (*p) {
1680 while (isspace(*p) || *p == ';')
1681 p++;
1682 if (!extract_param(p, "charset", charset))
1683 return;
1684 while (*p && !isspace(*p))
1685 p++;
1688 if (!charset->len && starts_with(type->buf, "text/"))
1689 strbuf_addstr(charset, "ISO-8859-1");
1692 static void write_accept_language(struct strbuf *buf)
1695 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1696 * that, q-value will be smaller than 0.001, the minimum q-value the
1697 * HTTP specification allows. See
1698 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1700 const int MAX_DECIMAL_PLACES = 3;
1701 const int MAX_LANGUAGE_TAGS = 1000;
1702 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1703 char **language_tags = NULL;
1704 int num_langs = 0;
1705 const char *s = get_preferred_languages();
1706 int i;
1707 struct strbuf tag = STRBUF_INIT;
1709 /* Don't add Accept-Language header if no language is preferred. */
1710 if (!s)
1711 return;
1714 * Split the colon-separated string of preferred languages into
1715 * language_tags array.
1717 do {
1718 /* collect language tag */
1719 for (; *s && (isalnum(*s) || *s == '_'); s++)
1720 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1722 /* skip .codeset, @modifier and any other unnecessary parts */
1723 while (*s && *s != ':')
1724 s++;
1726 if (tag.len) {
1727 num_langs++;
1728 REALLOC_ARRAY(language_tags, num_langs);
1729 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1730 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1731 break;
1733 } while (*s++);
1735 /* write Accept-Language header into buf */
1736 if (num_langs) {
1737 int last_buf_len = 0;
1738 int max_q;
1739 int decimal_places;
1740 char q_format[32];
1742 /* add '*' */
1743 REALLOC_ARRAY(language_tags, num_langs + 1);
1744 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1746 /* compute decimal_places */
1747 for (max_q = 1, decimal_places = 0;
1748 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1749 decimal_places++, max_q *= 10)
1752 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1754 strbuf_addstr(buf, "Accept-Language: ");
1756 for (i = 0; i < num_langs; i++) {
1757 if (i > 0)
1758 strbuf_addstr(buf, ", ");
1760 strbuf_addstr(buf, language_tags[i]);
1762 if (i > 0)
1763 strbuf_addf(buf, q_format, max_q - i);
1765 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1766 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1767 break;
1770 last_buf_len = buf->len;
1774 /* free language tags -- last one is a static '*' */
1775 for (i = 0; i < num_langs - 1; i++)
1776 free(language_tags[i]);
1777 free(language_tags);
1781 * Get an Accept-Language header which indicates user's preferred languages.
1783 * Examples:
1784 * LANGUAGE= -> ""
1785 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1786 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1787 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1788 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1789 * LANGUAGE= LANG=C -> ""
1791 static const char *get_accept_language(void)
1793 if (!cached_accept_language) {
1794 struct strbuf buf = STRBUF_INIT;
1795 write_accept_language(&buf);
1796 if (buf.len > 0)
1797 cached_accept_language = strbuf_detach(&buf, NULL);
1800 return cached_accept_language;
1803 static void http_opt_request_remainder(CURL *curl, off_t pos)
1805 char buf[128];
1806 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1807 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1810 /* http_request() targets */
1811 #define HTTP_REQUEST_STRBUF 0
1812 #define HTTP_REQUEST_FILE 1
1814 static int http_request(const char *url,
1815 void *result, int target,
1816 const struct http_get_options *options)
1818 struct active_request_slot *slot;
1819 struct slot_results results;
1820 struct curl_slist *headers = http_copy_default_headers();
1821 struct strbuf buf = STRBUF_INIT;
1822 const char *accept_language;
1823 int ret;
1825 slot = get_active_slot();
1826 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1828 if (result == NULL) {
1829 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1830 } else {
1831 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1832 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
1834 if (target == HTTP_REQUEST_FILE) {
1835 off_t posn = ftello(result);
1836 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1837 fwrite);
1838 if (posn > 0)
1839 http_opt_request_remainder(slot->curl, posn);
1840 } else
1841 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1842 fwrite_buffer);
1845 accept_language = get_accept_language();
1847 if (accept_language)
1848 headers = curl_slist_append(headers, accept_language);
1850 strbuf_addstr(&buf, "Pragma:");
1851 if (options && options->no_cache)
1852 strbuf_addstr(&buf, " no-cache");
1853 if (options && options->initial_request &&
1854 http_follow_config == HTTP_FOLLOW_INITIAL)
1855 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1857 headers = curl_slist_append(headers, buf.buf);
1859 /* Add additional headers here */
1860 if (options && options->extra_headers) {
1861 const struct string_list_item *item;
1862 for_each_string_list_item(item, options->extra_headers) {
1863 headers = curl_slist_append(headers, item->string);
1867 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1868 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1869 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1870 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1872 ret = run_one_slot(slot, &results);
1874 if (options && options->content_type) {
1875 struct strbuf raw = STRBUF_INIT;
1876 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1877 extract_content_type(&raw, options->content_type,
1878 options->charset);
1879 strbuf_release(&raw);
1882 if (options && options->effective_url)
1883 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1884 options->effective_url);
1886 curl_slist_free_all(headers);
1887 strbuf_release(&buf);
1889 return ret;
1893 * Update the "base" url to a more appropriate value, as deduced by
1894 * redirects seen when requesting a URL starting with "url".
1896 * The "asked" parameter is a URL that we asked curl to access, and must begin
1897 * with "base".
1899 * The "got" parameter is the URL that curl reported to us as where we ended
1900 * up.
1902 * Returns 1 if we updated the base url, 0 otherwise.
1904 * Our basic strategy is to compare "base" and "asked" to find the bits
1905 * specific to our request. We then strip those bits off of "got" to yield the
1906 * new base. So for example, if our base is "http://example.com/foo.git",
1907 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1908 * with "https://other.example.com/foo.git/info/refs". We would want the
1909 * new URL to become "https://other.example.com/foo.git".
1911 * Note that this assumes a sane redirect scheme. It's entirely possible
1912 * in the example above to end up at a URL that does not even end in
1913 * "info/refs". In such a case we die. There's not much we can do, such a
1914 * scheme is unlikely to represent a real git repository, and failing to
1915 * rewrite the base opens options for malicious redirects to do funny things.
1917 static int update_url_from_redirect(struct strbuf *base,
1918 const char *asked,
1919 const struct strbuf *got)
1921 const char *tail;
1922 size_t new_len;
1924 if (!strcmp(asked, got->buf))
1925 return 0;
1927 if (!skip_prefix(asked, base->buf, &tail))
1928 BUG("update_url_from_redirect: %s is not a superset of %s",
1929 asked, base->buf);
1931 new_len = got->len;
1932 if (!strip_suffix_mem(got->buf, &new_len, tail))
1933 die(_("unable to update url base from redirection:\n"
1934 " asked for: %s\n"
1935 " redirect: %s"),
1936 asked, got->buf);
1938 strbuf_reset(base);
1939 strbuf_add(base, got->buf, new_len);
1941 return 1;
1944 static int http_request_reauth(const char *url,
1945 void *result, int target,
1946 struct http_get_options *options)
1948 int ret = http_request(url, result, target, options);
1950 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1951 return ret;
1953 if (options && options->effective_url && options->base_url) {
1954 if (update_url_from_redirect(options->base_url,
1955 url, options->effective_url)) {
1956 credential_from_url(&http_auth, options->base_url->buf);
1957 url = options->effective_url->buf;
1961 if (ret != HTTP_REAUTH)
1962 return ret;
1965 * The previous request may have put cruft into our output stream; we
1966 * should clear it out before making our next request.
1968 switch (target) {
1969 case HTTP_REQUEST_STRBUF:
1970 strbuf_reset(result);
1971 break;
1972 case HTTP_REQUEST_FILE:
1973 if (fflush(result)) {
1974 error_errno("unable to flush a file");
1975 return HTTP_START_FAILED;
1977 rewind(result);
1978 if (ftruncate(fileno(result), 0) < 0) {
1979 error_errno("unable to truncate a file");
1980 return HTTP_START_FAILED;
1982 break;
1983 default:
1984 BUG("Unknown http_request target");
1987 credential_fill(&http_auth);
1989 return http_request(url, result, target, options);
1992 int http_get_strbuf(const char *url,
1993 struct strbuf *result,
1994 struct http_get_options *options)
1996 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2000 * Downloads a URL and stores the result in the given file.
2002 * If a previous interrupted download is detected (i.e. a previous temporary
2003 * file is still around) the download is resumed.
2005 static int http_get_file(const char *url, const char *filename,
2006 struct http_get_options *options)
2008 int ret;
2009 struct strbuf tmpfile = STRBUF_INIT;
2010 FILE *result;
2012 strbuf_addf(&tmpfile, "%s.temp", filename);
2013 result = fopen(tmpfile.buf, "a");
2014 if (!result) {
2015 error("Unable to open local file %s", tmpfile.buf);
2016 ret = HTTP_ERROR;
2017 goto cleanup;
2020 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2021 fclose(result);
2023 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2024 ret = HTTP_ERROR;
2025 cleanup:
2026 strbuf_release(&tmpfile);
2027 return ret;
2030 int http_fetch_ref(const char *base, struct ref *ref)
2032 struct http_get_options options = {0};
2033 char *url;
2034 struct strbuf buffer = STRBUF_INIT;
2035 int ret = -1;
2037 options.no_cache = 1;
2039 url = quote_ref_url(base, ref->name);
2040 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2041 strbuf_rtrim(&buffer);
2042 if (buffer.len == the_hash_algo->hexsz)
2043 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2044 else if (starts_with(buffer.buf, "ref: ")) {
2045 ref->symref = xstrdup(buffer.buf + 5);
2046 ret = 0;
2050 strbuf_release(&buffer);
2051 free(url);
2052 return ret;
2055 /* Helpers for fetching packs */
2056 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2058 char *url, *tmp;
2059 struct strbuf buf = STRBUF_INIT;
2061 if (http_is_verbose)
2062 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2064 end_url_with_slash(&buf, base_url);
2065 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2066 url = strbuf_detach(&buf, NULL);
2068 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2069 tmp = strbuf_detach(&buf, NULL);
2071 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2072 error("Unable to get pack index %s", url);
2073 FREE_AND_NULL(tmp);
2076 free(url);
2077 return tmp;
2080 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2081 unsigned char *sha1, const char *base_url)
2083 struct packed_git *new_pack;
2084 char *tmp_idx = NULL;
2085 int ret;
2087 if (has_pack_index(sha1)) {
2088 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2089 if (!new_pack)
2090 return -1; /* parse_pack_index() already issued error message */
2091 goto add_pack;
2094 tmp_idx = fetch_pack_index(sha1, base_url);
2095 if (!tmp_idx)
2096 return -1;
2098 new_pack = parse_pack_index(sha1, tmp_idx);
2099 if (!new_pack) {
2100 unlink(tmp_idx);
2101 free(tmp_idx);
2103 return -1; /* parse_pack_index() already issued error message */
2106 ret = verify_pack_index(new_pack);
2107 if (!ret) {
2108 close_pack_index(new_pack);
2109 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2111 free(tmp_idx);
2112 if (ret)
2113 return -1;
2115 add_pack:
2116 new_pack->next = *packs_head;
2117 *packs_head = new_pack;
2118 return 0;
2121 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2123 struct http_get_options options = {0};
2124 int ret = 0;
2125 char *url;
2126 const char *data;
2127 struct strbuf buf = STRBUF_INIT;
2128 struct object_id oid;
2130 end_url_with_slash(&buf, base_url);
2131 strbuf_addstr(&buf, "objects/info/packs");
2132 url = strbuf_detach(&buf, NULL);
2134 options.no_cache = 1;
2135 ret = http_get_strbuf(url, &buf, &options);
2136 if (ret != HTTP_OK)
2137 goto cleanup;
2139 data = buf.buf;
2140 while (*data) {
2141 if (skip_prefix(data, "P pack-", &data) &&
2142 !parse_oid_hex(data, &oid, &data) &&
2143 skip_prefix(data, ".pack", &data) &&
2144 (*data == '\n' || *data == '\0')) {
2145 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2146 } else {
2147 data = strchrnul(data, '\n');
2149 if (*data)
2150 data++; /* skip past newline */
2153 cleanup:
2154 free(url);
2155 return ret;
2158 void release_http_pack_request(struct http_pack_request *preq)
2160 if (preq->packfile != NULL) {
2161 fclose(preq->packfile);
2162 preq->packfile = NULL;
2164 preq->slot = NULL;
2165 strbuf_release(&preq->tmpfile);
2166 free(preq->url);
2167 free(preq);
2170 static const char *default_index_pack_args[] =
2171 {"index-pack", "--stdin", NULL};
2173 int finish_http_pack_request(struct http_pack_request *preq)
2175 struct child_process ip = CHILD_PROCESS_INIT;
2176 int tmpfile_fd;
2177 int ret = 0;
2179 fclose(preq->packfile);
2180 preq->packfile = NULL;
2182 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2184 ip.git_cmd = 1;
2185 ip.in = tmpfile_fd;
2186 ip.argv = preq->index_pack_args ? preq->index_pack_args
2187 : default_index_pack_args;
2189 if (preq->preserve_index_pack_stdout)
2190 ip.out = 0;
2191 else
2192 ip.no_stdout = 1;
2194 if (run_command(&ip)) {
2195 ret = -1;
2196 goto cleanup;
2199 cleanup:
2200 close(tmpfile_fd);
2201 unlink(preq->tmpfile.buf);
2202 return ret;
2205 void http_install_packfile(struct packed_git *p,
2206 struct packed_git **list_to_remove_from)
2208 struct packed_git **lst = list_to_remove_from;
2210 while (*lst != p)
2211 lst = &((*lst)->next);
2212 *lst = (*lst)->next;
2214 install_packed_git(the_repository, p);
2217 struct http_pack_request *new_http_pack_request(
2218 const unsigned char *packed_git_hash, const char *base_url) {
2220 struct strbuf buf = STRBUF_INIT;
2222 end_url_with_slash(&buf, base_url);
2223 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2224 hash_to_hex(packed_git_hash));
2225 return new_direct_http_pack_request(packed_git_hash,
2226 strbuf_detach(&buf, NULL));
2229 struct http_pack_request *new_direct_http_pack_request(
2230 const unsigned char *packed_git_hash, char *url)
2232 off_t prev_posn = 0;
2233 struct http_pack_request *preq;
2235 CALLOC_ARRAY(preq, 1);
2236 strbuf_init(&preq->tmpfile, 0);
2238 preq->url = url;
2240 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2241 preq->packfile = fopen(preq->tmpfile.buf, "a");
2242 if (!preq->packfile) {
2243 error("Unable to open local file %s for pack",
2244 preq->tmpfile.buf);
2245 goto abort;
2248 preq->slot = get_active_slot();
2249 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2250 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2251 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2252 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2253 no_pragma_header);
2256 * If there is data present from a previous transfer attempt,
2257 * resume where it left off
2259 prev_posn = ftello(preq->packfile);
2260 if (prev_posn>0) {
2261 if (http_is_verbose)
2262 fprintf(stderr,
2263 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2264 hash_to_hex(packed_git_hash),
2265 (uintmax_t)prev_posn);
2266 http_opt_request_remainder(preq->slot->curl, prev_posn);
2269 return preq;
2271 abort:
2272 strbuf_release(&preq->tmpfile);
2273 free(preq->url);
2274 free(preq);
2275 return NULL;
2278 /* Helpers for fetching objects (loose) */
2279 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2280 void *data)
2282 unsigned char expn[4096];
2283 size_t size = eltsize * nmemb;
2284 int posn = 0;
2285 struct http_object_request *freq = data;
2286 struct active_request_slot *slot = freq->slot;
2288 if (slot) {
2289 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2290 &slot->http_code);
2291 if (c != CURLE_OK)
2292 BUG("curl_easy_getinfo for HTTP code failed: %s",
2293 curl_easy_strerror(c));
2294 if (slot->http_code >= 300)
2295 return nmemb;
2298 do {
2299 ssize_t retval = xwrite(freq->localfile,
2300 (char *) ptr + posn, size - posn);
2301 if (retval < 0)
2302 return posn / eltsize;
2303 posn += retval;
2304 } while (posn < size);
2306 freq->stream.avail_in = size;
2307 freq->stream.next_in = (void *)ptr;
2308 do {
2309 freq->stream.next_out = expn;
2310 freq->stream.avail_out = sizeof(expn);
2311 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2312 the_hash_algo->update_fn(&freq->c, expn,
2313 sizeof(expn) - freq->stream.avail_out);
2314 } while (freq->stream.avail_in && freq->zret == Z_OK);
2315 return nmemb;
2318 struct http_object_request *new_http_object_request(const char *base_url,
2319 const struct object_id *oid)
2321 char *hex = oid_to_hex(oid);
2322 struct strbuf filename = STRBUF_INIT;
2323 struct strbuf prevfile = STRBUF_INIT;
2324 int prevlocal;
2325 char prev_buf[PREV_BUF_SIZE];
2326 ssize_t prev_read = 0;
2327 off_t prev_posn = 0;
2328 struct http_object_request *freq;
2330 CALLOC_ARRAY(freq, 1);
2331 strbuf_init(&freq->tmpfile, 0);
2332 oidcpy(&freq->oid, oid);
2333 freq->localfile = -1;
2335 loose_object_path(the_repository, &filename, oid);
2336 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2338 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2339 unlink_or_warn(prevfile.buf);
2340 rename(freq->tmpfile.buf, prevfile.buf);
2341 unlink_or_warn(freq->tmpfile.buf);
2342 strbuf_release(&filename);
2344 if (freq->localfile != -1)
2345 error("fd leakage in start: %d", freq->localfile);
2346 freq->localfile = open(freq->tmpfile.buf,
2347 O_WRONLY | O_CREAT | O_EXCL, 0666);
2349 * This could have failed due to the "lazy directory creation";
2350 * try to mkdir the last path component.
2352 if (freq->localfile < 0 && errno == ENOENT) {
2353 char *dir = strrchr(freq->tmpfile.buf, '/');
2354 if (dir) {
2355 *dir = 0;
2356 mkdir(freq->tmpfile.buf, 0777);
2357 *dir = '/';
2359 freq->localfile = open(freq->tmpfile.buf,
2360 O_WRONLY | O_CREAT | O_EXCL, 0666);
2363 if (freq->localfile < 0) {
2364 error_errno("Couldn't create temporary file %s",
2365 freq->tmpfile.buf);
2366 goto abort;
2369 git_inflate_init(&freq->stream);
2371 the_hash_algo->init_fn(&freq->c);
2373 freq->url = get_remote_object_url(base_url, hex, 0);
2376 * If a previous temp file is present, process what was already
2377 * fetched.
2379 prevlocal = open(prevfile.buf, O_RDONLY);
2380 if (prevlocal != -1) {
2381 do {
2382 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2383 if (prev_read>0) {
2384 if (fwrite_sha1_file(prev_buf,
2386 prev_read,
2387 freq) == prev_read) {
2388 prev_posn += prev_read;
2389 } else {
2390 prev_read = -1;
2393 } while (prev_read > 0);
2394 close(prevlocal);
2396 unlink_or_warn(prevfile.buf);
2397 strbuf_release(&prevfile);
2400 * Reset inflate/SHA1 if there was an error reading the previous temp
2401 * file; also rewind to the beginning of the local file.
2403 if (prev_read == -1) {
2404 memset(&freq->stream, 0, sizeof(freq->stream));
2405 git_inflate_init(&freq->stream);
2406 the_hash_algo->init_fn(&freq->c);
2407 if (prev_posn>0) {
2408 prev_posn = 0;
2409 lseek(freq->localfile, 0, SEEK_SET);
2410 if (ftruncate(freq->localfile, 0) < 0) {
2411 error_errno("Couldn't truncate temporary file %s",
2412 freq->tmpfile.buf);
2413 goto abort;
2418 freq->slot = get_active_slot();
2420 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2421 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2422 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2423 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2424 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2425 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2428 * If we have successfully processed data from a previous fetch
2429 * attempt, only fetch the data we don't already have.
2431 if (prev_posn>0) {
2432 if (http_is_verbose)
2433 fprintf(stderr,
2434 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2435 hex, (uintmax_t)prev_posn);
2436 http_opt_request_remainder(freq->slot->curl, prev_posn);
2439 return freq;
2441 abort:
2442 strbuf_release(&prevfile);
2443 free(freq->url);
2444 free(freq);
2445 return NULL;
2448 void process_http_object_request(struct http_object_request *freq)
2450 if (freq->slot == NULL)
2451 return;
2452 freq->curl_result = freq->slot->curl_result;
2453 freq->http_code = freq->slot->http_code;
2454 freq->slot = NULL;
2457 int finish_http_object_request(struct http_object_request *freq)
2459 struct stat st;
2460 struct strbuf filename = STRBUF_INIT;
2462 close(freq->localfile);
2463 freq->localfile = -1;
2465 process_http_object_request(freq);
2467 if (freq->http_code == 416) {
2468 warning("requested range invalid; we may already have all the data.");
2469 } else if (freq->curl_result != CURLE_OK) {
2470 if (stat(freq->tmpfile.buf, &st) == 0)
2471 if (st.st_size == 0)
2472 unlink_or_warn(freq->tmpfile.buf);
2473 return -1;
2476 git_inflate_end(&freq->stream);
2477 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2478 if (freq->zret != Z_STREAM_END) {
2479 unlink_or_warn(freq->tmpfile.buf);
2480 return -1;
2482 if (!oideq(&freq->oid, &freq->real_oid)) {
2483 unlink_or_warn(freq->tmpfile.buf);
2484 return -1;
2486 loose_object_path(the_repository, &filename, &freq->oid);
2487 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2488 strbuf_release(&filename);
2490 return freq->rename;
2493 void abort_http_object_request(struct http_object_request *freq)
2495 unlink_or_warn(freq->tmpfile.buf);
2497 release_http_object_request(freq);
2500 void release_http_object_request(struct http_object_request *freq)
2502 if (freq->localfile != -1) {
2503 close(freq->localfile);
2504 freq->localfile = -1;
2506 FREE_AND_NULL(freq->url);
2507 if (freq->slot != NULL) {
2508 freq->slot->callback_func = NULL;
2509 freq->slot->callback_data = NULL;
2510 release_active_slot(freq->slot);
2511 freq->slot = NULL;
2513 strbuf_release(&freq->tmpfile);