Merge branch 'en/header-cleanup'
[git/debian.git] / http.c
blob86b0745af9076a8a683ab37948336f49e2d73292
1 #include "git-compat-util.h"
2 #include "git-curl-compat.h"
3 #include "hex.h"
4 #include "http.h"
5 #include "config.h"
6 #include "pack.h"
7 #include "sideband.h"
8 #include "run-command.h"
9 #include "url.h"
10 #include "urlmatch.h"
11 #include "credential.h"
12 #include "version.h"
13 #include "pkt-line.h"
14 #include "gettext.h"
15 #include "transport.h"
16 #include "packfile.h"
17 #include "protocol.h"
18 #include "string-list.h"
19 #include "object-store.h"
21 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
22 static int trace_curl_data = 1;
23 static int trace_curl_redact = 1;
24 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
25 int active_requests;
26 int http_is_verbose;
27 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
29 static int min_curl_sessions = 1;
30 static int curl_session_count;
31 static int max_requests = -1;
32 static CURLM *curlm;
33 static CURL *curl_default;
35 #define PREV_BUF_SIZE 4096
37 char curl_errorstr[CURL_ERROR_SIZE];
39 static int curl_ssl_verify = -1;
40 static int curl_ssl_try;
41 static const char *curl_http_version = NULL;
42 static const char *ssl_cert;
43 static const char *ssl_cipherlist;
44 static const char *ssl_version;
45 static struct {
46 const char *name;
47 long ssl_version;
48 } sslversions[] = {
49 { "sslv2", CURL_SSLVERSION_SSLv2 },
50 { "sslv3", CURL_SSLVERSION_SSLv3 },
51 { "tlsv1", CURL_SSLVERSION_TLSv1 },
52 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_0
53 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
54 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
55 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
56 #endif
57 #ifdef GIT_CURL_HAVE_CURL_SSLVERSION_TLSv1_3
58 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
59 #endif
61 static const char *ssl_key;
62 static const char *ssl_capath;
63 static const char *curl_no_proxy;
64 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
65 static const char *ssl_pinnedkey;
66 #endif
67 static const char *ssl_cainfo;
68 static long curl_low_speed_limit = -1;
69 static long curl_low_speed_time = -1;
70 static int curl_ftp_no_epsv;
71 static const char *curl_http_proxy;
72 static const char *http_proxy_authmethod;
74 static const char *http_proxy_ssl_cert;
75 static const char *http_proxy_ssl_key;
76 static const char *http_proxy_ssl_ca_info;
77 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
78 static int proxy_ssl_cert_password_required;
80 static struct {
81 const char *name;
82 long curlauth_param;
83 } proxy_authmethods[] = {
84 { "basic", CURLAUTH_BASIC },
85 { "digest", CURLAUTH_DIGEST },
86 { "negotiate", CURLAUTH_GSSNEGOTIATE },
87 { "ntlm", CURLAUTH_NTLM },
88 { "anyauth", CURLAUTH_ANY },
90 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
91 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
92 * here, too
95 #ifdef CURLGSSAPI_DELEGATION_FLAG
96 static const char *curl_deleg;
97 static struct {
98 const char *name;
99 long curl_deleg_param;
100 } curl_deleg_levels[] = {
101 { "none", CURLGSSAPI_DELEGATION_NONE },
102 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
103 { "always", CURLGSSAPI_DELEGATION_FLAG },
105 #endif
107 static struct credential proxy_auth = CREDENTIAL_INIT;
108 static const char *curl_proxyuserpwd;
109 static const char *curl_cookie_file;
110 static int curl_save_cookies;
111 struct credential http_auth = CREDENTIAL_INIT;
112 static int http_proactive_auth;
113 static const char *user_agent;
114 static int curl_empty_auth = -1;
116 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
118 static struct credential cert_auth = CREDENTIAL_INIT;
119 static int ssl_cert_password_required;
120 static unsigned long http_auth_methods = CURLAUTH_ANY;
121 static int http_auth_methods_restricted;
122 /* Modes for which empty_auth cannot actually help us. */
123 static unsigned long empty_auth_useless =
124 CURLAUTH_BASIC
125 | CURLAUTH_DIGEST_IE
126 | CURLAUTH_DIGEST;
128 static struct curl_slist *pragma_header;
129 static struct curl_slist *no_pragma_header;
130 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
132 static struct curl_slist *host_resolutions;
134 static struct active_request_slot *active_queue_head;
136 static char *cached_accept_language;
138 static char *http_ssl_backend;
140 static int http_schannel_check_revoke = 1;
142 * With the backend being set to `schannel`, setting sslCAinfo would override
143 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
144 * by default.
146 static int http_schannel_use_ssl_cainfo;
148 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
150 size_t size = eltsize * nmemb;
151 struct buffer *buffer = buffer_;
153 if (size > buffer->buf.len - buffer->posn)
154 size = buffer->buf.len - buffer->posn;
155 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
156 buffer->posn += size;
158 return size / eltsize;
161 int seek_buffer(void *clientp, curl_off_t offset, int origin)
163 struct buffer *buffer = clientp;
165 if (origin != SEEK_SET)
166 BUG("seek_buffer only handles SEEK_SET");
167 if (offset < 0 || offset >= buffer->buf.len) {
168 error("curl seek would be outside of buffer");
169 return CURL_SEEKFUNC_FAIL;
172 buffer->posn = offset;
173 return CURL_SEEKFUNC_OK;
176 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
178 size_t size = eltsize * nmemb;
179 struct strbuf *buffer = buffer_;
181 strbuf_add(buffer, ptr, size);
182 return nmemb;
185 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
187 return nmemb;
190 static void closedown_active_slot(struct active_request_slot *slot)
192 active_requests--;
193 slot->in_use = 0;
196 static void finish_active_slot(struct active_request_slot *slot)
198 closedown_active_slot(slot);
199 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
201 if (slot->finished)
202 (*slot->finished) = 1;
204 /* Store slot results so they can be read after the slot is reused */
205 if (slot->results) {
206 slot->results->curl_result = slot->curl_result;
207 slot->results->http_code = slot->http_code;
208 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
209 &slot->results->auth_avail);
211 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
212 &slot->results->http_connectcode);
215 /* Run callback if appropriate */
216 if (slot->callback_func)
217 slot->callback_func(slot->callback_data);
220 static void xmulti_remove_handle(struct active_request_slot *slot)
222 curl_multi_remove_handle(curlm, slot->curl);
225 static void process_curl_messages(void)
227 int num_messages;
228 struct active_request_slot *slot;
229 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
231 while (curl_message != NULL) {
232 if (curl_message->msg == CURLMSG_DONE) {
233 int curl_result = curl_message->data.result;
234 slot = active_queue_head;
235 while (slot != NULL &&
236 slot->curl != curl_message->easy_handle)
237 slot = slot->next;
238 if (slot) {
239 xmulti_remove_handle(slot);
240 slot->curl_result = curl_result;
241 finish_active_slot(slot);
242 } else {
243 fprintf(stderr, "Received DONE message for unknown request!\n");
245 } else {
246 fprintf(stderr, "Unknown CURL message received: %d\n",
247 (int)curl_message->msg);
249 curl_message = curl_multi_info_read(curlm, &num_messages);
253 static int http_options(const char *var, const char *value, void *cb)
255 if (!strcmp("http.version", var)) {
256 return git_config_string(&curl_http_version, var, value);
258 if (!strcmp("http.sslverify", var)) {
259 curl_ssl_verify = git_config_bool(var, value);
260 return 0;
262 if (!strcmp("http.sslcipherlist", var))
263 return git_config_string(&ssl_cipherlist, var, value);
264 if (!strcmp("http.sslversion", var))
265 return git_config_string(&ssl_version, var, value);
266 if (!strcmp("http.sslcert", var))
267 return git_config_pathname(&ssl_cert, var, value);
268 if (!strcmp("http.sslkey", var))
269 return git_config_pathname(&ssl_key, var, value);
270 if (!strcmp("http.sslcapath", var))
271 return git_config_pathname(&ssl_capath, var, value);
272 if (!strcmp("http.sslcainfo", var))
273 return git_config_pathname(&ssl_cainfo, var, value);
274 if (!strcmp("http.sslcertpasswordprotected", var)) {
275 ssl_cert_password_required = git_config_bool(var, value);
276 return 0;
278 if (!strcmp("http.ssltry", var)) {
279 curl_ssl_try = git_config_bool(var, value);
280 return 0;
282 if (!strcmp("http.sslbackend", var)) {
283 free(http_ssl_backend);
284 http_ssl_backend = xstrdup_or_null(value);
285 return 0;
288 if (!strcmp("http.schannelcheckrevoke", var)) {
289 http_schannel_check_revoke = git_config_bool(var, value);
290 return 0;
293 if (!strcmp("http.schannelusesslcainfo", var)) {
294 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
295 return 0;
298 if (!strcmp("http.minsessions", var)) {
299 min_curl_sessions = git_config_int(var, value);
300 if (min_curl_sessions > 1)
301 min_curl_sessions = 1;
302 return 0;
304 if (!strcmp("http.maxrequests", var)) {
305 max_requests = git_config_int(var, value);
306 return 0;
308 if (!strcmp("http.lowspeedlimit", var)) {
309 curl_low_speed_limit = (long)git_config_int(var, value);
310 return 0;
312 if (!strcmp("http.lowspeedtime", var)) {
313 curl_low_speed_time = (long)git_config_int(var, value);
314 return 0;
317 if (!strcmp("http.noepsv", var)) {
318 curl_ftp_no_epsv = git_config_bool(var, value);
319 return 0;
321 if (!strcmp("http.proxy", var))
322 return git_config_string(&curl_http_proxy, var, value);
324 if (!strcmp("http.proxyauthmethod", var))
325 return git_config_string(&http_proxy_authmethod, var, value);
327 if (!strcmp("http.proxysslcert", var))
328 return git_config_string(&http_proxy_ssl_cert, var, value);
330 if (!strcmp("http.proxysslkey", var))
331 return git_config_string(&http_proxy_ssl_key, var, value);
333 if (!strcmp("http.proxysslcainfo", var))
334 return git_config_string(&http_proxy_ssl_ca_info, var, value);
336 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
337 proxy_ssl_cert_password_required = git_config_bool(var, value);
338 return 0;
341 if (!strcmp("http.cookiefile", var))
342 return git_config_pathname(&curl_cookie_file, var, value);
343 if (!strcmp("http.savecookies", var)) {
344 curl_save_cookies = git_config_bool(var, value);
345 return 0;
348 if (!strcmp("http.postbuffer", var)) {
349 http_post_buffer = git_config_ssize_t(var, value);
350 if (http_post_buffer < 0)
351 warning(_("negative value for http.postBuffer; defaulting to %d"), LARGE_PACKET_MAX);
352 if (http_post_buffer < LARGE_PACKET_MAX)
353 http_post_buffer = LARGE_PACKET_MAX;
354 return 0;
357 if (!strcmp("http.useragent", var))
358 return git_config_string(&user_agent, var, value);
360 if (!strcmp("http.emptyauth", var)) {
361 if (value && !strcmp("auto", value))
362 curl_empty_auth = -1;
363 else
364 curl_empty_auth = git_config_bool(var, value);
365 return 0;
368 if (!strcmp("http.delegation", var)) {
369 #ifdef CURLGSSAPI_DELEGATION_FLAG
370 return git_config_string(&curl_deleg, var, value);
371 #else
372 warning(_("Delegation control is not supported with cURL < 7.22.0"));
373 return 0;
374 #endif
377 if (!strcmp("http.pinnedpubkey", var)) {
378 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
379 return git_config_pathname(&ssl_pinnedkey, var, value);
380 #else
381 warning(_("Public key pinning not supported with cURL < 7.39.0"));
382 return 0;
383 #endif
386 if (!strcmp("http.extraheader", var)) {
387 if (!value) {
388 return config_error_nonbool(var);
389 } else if (!*value) {
390 string_list_clear(&extra_http_headers, 0);
391 } else {
392 string_list_append(&extra_http_headers, value);
394 return 0;
397 if (!strcmp("http.curloptresolve", var)) {
398 if (!value) {
399 return config_error_nonbool(var);
400 } else if (!*value) {
401 curl_slist_free_all(host_resolutions);
402 host_resolutions = NULL;
403 } else {
404 host_resolutions = curl_slist_append(host_resolutions, value);
406 return 0;
409 if (!strcmp("http.followredirects", var)) {
410 if (value && !strcmp(value, "initial"))
411 http_follow_config = HTTP_FOLLOW_INITIAL;
412 else if (git_config_bool(var, value))
413 http_follow_config = HTTP_FOLLOW_ALWAYS;
414 else
415 http_follow_config = HTTP_FOLLOW_NONE;
416 return 0;
419 /* Fall back on the default ones */
420 return git_default_config(var, value, cb);
423 static int curl_empty_auth_enabled(void)
425 if (curl_empty_auth >= 0)
426 return curl_empty_auth;
429 * In the automatic case, kick in the empty-auth
430 * hack as long as we would potentially try some
431 * method more exotic than "Basic" or "Digest".
433 * But only do this when this is our second or
434 * subsequent request, as by then we know what
435 * methods are available.
437 if (http_auth_methods_restricted &&
438 (http_auth_methods & ~empty_auth_useless))
439 return 1;
440 return 0;
443 static void init_curl_http_auth(CURL *result)
445 if (!http_auth.username || !*http_auth.username) {
446 if (curl_empty_auth_enabled())
447 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
448 return;
451 credential_fill(&http_auth);
453 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
454 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
457 /* *var must be free-able */
458 static void var_override(const char **var, char *value)
460 if (value) {
461 free((void *)*var);
462 *var = xstrdup(value);
466 static void set_proxyauth_name_password(CURL *result)
468 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
469 proxy_auth.username);
470 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
471 proxy_auth.password);
474 static void init_curl_proxy_auth(CURL *result)
476 if (proxy_auth.username) {
477 if (!proxy_auth.password)
478 credential_fill(&proxy_auth);
479 set_proxyauth_name_password(result);
482 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
484 if (http_proxy_authmethod) {
485 int i;
486 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
487 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
488 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
489 proxy_authmethods[i].curlauth_param);
490 break;
493 if (i == ARRAY_SIZE(proxy_authmethods)) {
494 warning("unsupported proxy authentication method %s: using anyauth",
495 http_proxy_authmethod);
496 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
499 else
500 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
503 static int has_cert_password(void)
505 if (ssl_cert == NULL || ssl_cert_password_required != 1)
506 return 0;
507 if (!cert_auth.password) {
508 cert_auth.protocol = xstrdup("cert");
509 cert_auth.host = xstrdup("");
510 cert_auth.username = xstrdup("");
511 cert_auth.path = xstrdup(ssl_cert);
512 credential_fill(&cert_auth);
514 return 1;
517 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
518 static int has_proxy_cert_password(void)
520 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
521 return 0;
522 if (!proxy_cert_auth.password) {
523 proxy_cert_auth.protocol = xstrdup("cert");
524 proxy_cert_auth.host = xstrdup("");
525 proxy_cert_auth.username = xstrdup("");
526 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
527 credential_fill(&proxy_cert_auth);
529 return 1;
531 #endif
533 #ifdef GITCURL_HAVE_CURLOPT_TCP_KEEPALIVE
534 static void set_curl_keepalive(CURL *c)
536 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
539 #else
540 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
542 int ka = 1;
543 int rc;
544 socklen_t len = (socklen_t)sizeof(ka);
546 if (type != CURLSOCKTYPE_IPCXN)
547 return 0;
549 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
550 if (rc < 0)
551 warning_errno("unable to set SO_KEEPALIVE on socket");
553 return CURL_SOCKOPT_OK;
556 static void set_curl_keepalive(CURL *c)
558 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
560 #endif
562 /* Return 1 if redactions have been made, 0 otherwise. */
563 static int redact_sensitive_header(struct strbuf *header, size_t offset)
565 int ret = 0;
566 const char *sensitive_header;
568 if (trace_curl_redact &&
569 (skip_iprefix(header->buf + offset, "Authorization:", &sensitive_header) ||
570 skip_iprefix(header->buf + offset, "Proxy-Authorization:", &sensitive_header))) {
571 /* The first token is the type, which is OK to log */
572 while (isspace(*sensitive_header))
573 sensitive_header++;
574 while (*sensitive_header && !isspace(*sensitive_header))
575 sensitive_header++;
576 /* Everything else is opaque and possibly sensitive */
577 strbuf_setlen(header, sensitive_header - header->buf);
578 strbuf_addstr(header, " <redacted>");
579 ret = 1;
580 } else if (trace_curl_redact &&
581 skip_iprefix(header->buf + offset, "Cookie:", &sensitive_header)) {
582 struct strbuf redacted_header = STRBUF_INIT;
583 const char *cookie;
585 while (isspace(*sensitive_header))
586 sensitive_header++;
588 cookie = sensitive_header;
590 while (cookie) {
591 char *equals;
592 char *semicolon = strstr(cookie, "; ");
593 if (semicolon)
594 *semicolon = 0;
595 equals = strchrnul(cookie, '=');
596 if (!equals) {
597 /* invalid cookie, just append and continue */
598 strbuf_addstr(&redacted_header, cookie);
599 continue;
601 strbuf_add(&redacted_header, cookie, equals - cookie);
602 strbuf_addstr(&redacted_header, "=<redacted>");
603 if (semicolon) {
605 * There are more cookies. (Or, for some
606 * reason, the input string ends in "; ".)
608 strbuf_addstr(&redacted_header, "; ");
609 cookie = semicolon + strlen("; ");
610 } else {
611 cookie = NULL;
615 strbuf_setlen(header, sensitive_header - header->buf);
616 strbuf_addbuf(header, &redacted_header);
617 ret = 1;
619 return ret;
622 /* Redact headers in info */
623 static void redact_sensitive_info_header(struct strbuf *header)
625 const char *sensitive_header;
628 * curl's h2h3 prints headers in info, e.g.:
629 * h2h3 [<header-name>: <header-val>]
631 if (trace_curl_redact &&
632 skip_iprefix(header->buf, "h2h3 [", &sensitive_header)) {
633 if (redact_sensitive_header(header, sensitive_header - header->buf)) {
634 /* redaction ate our closing bracket */
635 strbuf_addch(header, ']');
640 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
642 struct strbuf out = STRBUF_INIT;
643 struct strbuf **headers, **header;
645 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
646 text, (long)size, (long)size);
647 trace_strbuf(&trace_curl, &out);
648 strbuf_reset(&out);
649 strbuf_add(&out, ptr, size);
650 headers = strbuf_split_max(&out, '\n', 0);
652 for (header = headers; *header; header++) {
653 if (hide_sensitive_header)
654 redact_sensitive_header(*header, 0);
655 strbuf_insertstr((*header), 0, text);
656 strbuf_insertstr((*header), strlen(text), ": ");
657 strbuf_rtrim((*header));
658 strbuf_addch((*header), '\n');
659 trace_strbuf(&trace_curl, (*header));
661 strbuf_list_free(headers);
662 strbuf_release(&out);
665 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
667 size_t i;
668 struct strbuf out = STRBUF_INIT;
669 unsigned int width = 60;
671 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
672 text, (long)size, (long)size);
673 trace_strbuf(&trace_curl, &out);
675 for (i = 0; i < size; i += width) {
676 size_t w;
678 strbuf_reset(&out);
679 strbuf_addf(&out, "%s: ", text);
680 for (w = 0; (w < width) && (i + w < size); w++) {
681 unsigned char ch = ptr[i + w];
683 strbuf_addch(&out,
684 (ch >= 0x20) && (ch < 0x80)
685 ? ch : '.');
687 strbuf_addch(&out, '\n');
688 trace_strbuf(&trace_curl, &out);
690 strbuf_release(&out);
693 static void curl_dump_info(char *data, size_t size)
695 struct strbuf buf = STRBUF_INIT;
697 strbuf_add(&buf, data, size);
699 redact_sensitive_info_header(&buf);
700 trace_printf_key(&trace_curl, "== Info: %s", buf.buf);
702 strbuf_release(&buf);
705 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
707 const char *text;
708 enum { NO_FILTER = 0, DO_FILTER = 1 };
710 switch (type) {
711 case CURLINFO_TEXT:
712 curl_dump_info(data, size);
713 break;
714 case CURLINFO_HEADER_OUT:
715 text = "=> Send header";
716 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
717 break;
718 case CURLINFO_DATA_OUT:
719 if (trace_curl_data) {
720 text = "=> Send data";
721 curl_dump_data(text, (unsigned char *)data, size);
723 break;
724 case CURLINFO_SSL_DATA_OUT:
725 if (trace_curl_data) {
726 text = "=> Send SSL data";
727 curl_dump_data(text, (unsigned char *)data, size);
729 break;
730 case CURLINFO_HEADER_IN:
731 text = "<= Recv header";
732 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
733 break;
734 case CURLINFO_DATA_IN:
735 if (trace_curl_data) {
736 text = "<= Recv data";
737 curl_dump_data(text, (unsigned char *)data, size);
739 break;
740 case CURLINFO_SSL_DATA_IN:
741 if (trace_curl_data) {
742 text = "<= Recv SSL data";
743 curl_dump_data(text, (unsigned char *)data, size);
745 break;
747 default: /* we ignore unknown types by default */
748 return 0;
750 return 0;
753 void http_trace_curl_no_data(void)
755 trace_override_envvar(&trace_curl, "1");
756 trace_curl_data = 0;
759 void setup_curl_trace(CURL *handle)
761 if (!trace_want(&trace_curl))
762 return;
763 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
764 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
765 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
768 static void proto_list_append(struct strbuf *list, const char *proto)
770 if (!list)
771 return;
772 if (list->len)
773 strbuf_addch(list, ',');
774 strbuf_addstr(list, proto);
777 static long get_curl_allowed_protocols(int from_user, struct strbuf *list)
779 long bits = 0;
781 if (is_transport_allowed("http", from_user)) {
782 bits |= CURLPROTO_HTTP;
783 proto_list_append(list, "http");
785 if (is_transport_allowed("https", from_user)) {
786 bits |= CURLPROTO_HTTPS;
787 proto_list_append(list, "https");
789 if (is_transport_allowed("ftp", from_user)) {
790 bits |= CURLPROTO_FTP;
791 proto_list_append(list, "ftp");
793 if (is_transport_allowed("ftps", from_user)) {
794 bits |= CURLPROTO_FTPS;
795 proto_list_append(list, "ftps");
798 return bits;
801 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
802 static int get_curl_http_version_opt(const char *version_string, long *opt)
804 int i;
805 static struct {
806 const char *name;
807 long opt_token;
808 } choice[] = {
809 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
810 { "HTTP/2", CURL_HTTP_VERSION_2 }
813 for (i = 0; i < ARRAY_SIZE(choice); i++) {
814 if (!strcmp(version_string, choice[i].name)) {
815 *opt = choice[i].opt_token;
816 return 0;
820 warning("unknown value given to http.version: '%s'", version_string);
821 return -1; /* not found */
824 #endif
826 static CURL *get_curl_handle(void)
828 CURL *result = curl_easy_init();
830 if (!result)
831 die("curl_easy_init failed");
833 if (!curl_ssl_verify) {
834 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
835 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
836 } else {
837 /* Verify authenticity of the peer's certificate */
838 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
839 /* The name in the cert must match whom we tried to connect */
840 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
843 #ifdef GIT_CURL_HAVE_CURL_HTTP_VERSION_2
844 if (curl_http_version) {
845 long opt;
846 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
847 /* Set request use http version */
848 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
851 #endif
853 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
854 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
856 #ifdef CURLGSSAPI_DELEGATION_FLAG
857 if (curl_deleg) {
858 int i;
859 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
860 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
861 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
862 curl_deleg_levels[i].curl_deleg_param);
863 break;
866 if (i == ARRAY_SIZE(curl_deleg_levels))
867 warning("Unknown delegation method '%s': using default",
868 curl_deleg);
870 #endif
872 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
873 !http_schannel_check_revoke) {
874 #ifdef GIT_CURL_HAVE_CURLSSLOPT_NO_REVOKE
875 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
876 #else
877 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
878 #endif
881 if (http_proactive_auth)
882 init_curl_http_auth(result);
884 if (getenv("GIT_SSL_VERSION"))
885 ssl_version = getenv("GIT_SSL_VERSION");
886 if (ssl_version && *ssl_version) {
887 int i;
888 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
889 if (!strcmp(ssl_version, sslversions[i].name)) {
890 curl_easy_setopt(result, CURLOPT_SSLVERSION,
891 sslversions[i].ssl_version);
892 break;
895 if (i == ARRAY_SIZE(sslversions))
896 warning("unsupported ssl version %s: using default",
897 ssl_version);
900 if (getenv("GIT_SSL_CIPHER_LIST"))
901 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
902 if (ssl_cipherlist != NULL && *ssl_cipherlist)
903 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
904 ssl_cipherlist);
906 if (ssl_cert)
907 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
908 if (has_cert_password())
909 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
910 if (ssl_key)
911 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
912 if (ssl_capath)
913 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
914 #ifdef GIT_CURL_HAVE_CURLOPT_PINNEDPUBLICKEY
915 if (ssl_pinnedkey)
916 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
917 #endif
918 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
919 !http_schannel_use_ssl_cainfo) {
920 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
921 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
922 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
923 #endif
924 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
925 if (ssl_cainfo)
926 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
927 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_CAINFO
928 if (http_proxy_ssl_ca_info)
929 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
930 #endif
933 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
934 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
935 curl_low_speed_limit);
936 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
937 curl_low_speed_time);
940 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
941 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
943 #ifdef GIT_CURL_HAVE_CURLOPT_PROTOCOLS_STR
945 struct strbuf buf = STRBUF_INIT;
947 get_curl_allowed_protocols(0, &buf);
948 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS_STR, buf.buf);
949 strbuf_reset(&buf);
951 get_curl_allowed_protocols(-1, &buf);
952 curl_easy_setopt(result, CURLOPT_PROTOCOLS_STR, buf.buf);
953 strbuf_release(&buf);
955 #else
956 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
957 get_curl_allowed_protocols(0, NULL));
958 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
959 get_curl_allowed_protocols(-1, NULL));
960 #endif
962 if (getenv("GIT_CURL_VERBOSE"))
963 http_trace_curl_no_data();
964 setup_curl_trace(result);
965 if (getenv("GIT_TRACE_CURL_NO_DATA"))
966 trace_curl_data = 0;
967 if (!git_env_bool("GIT_TRACE_REDACT", 1))
968 trace_curl_redact = 0;
970 curl_easy_setopt(result, CURLOPT_USERAGENT,
971 user_agent ? user_agent : git_user_agent());
973 if (curl_ftp_no_epsv)
974 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
976 if (curl_ssl_try)
977 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
980 * CURL also examines these variables as a fallback; but we need to query
981 * them here in order to decide whether to prompt for missing password (cf.
982 * init_curl_proxy_auth()).
984 * Unlike many other common environment variables, these are historically
985 * lowercase only. It appears that CURL did not know this and implemented
986 * only uppercase variants, which was later corrected to take both - with
987 * the exception of http_proxy, which is lowercase only also in CURL. As
988 * the lowercase versions are the historical quasi-standard, they take
989 * precedence here, as in CURL.
991 if (!curl_http_proxy) {
992 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
993 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
994 var_override(&curl_http_proxy, getenv("https_proxy"));
995 } else {
996 var_override(&curl_http_proxy, getenv("http_proxy"));
998 if (!curl_http_proxy) {
999 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1000 var_override(&curl_http_proxy, getenv("all_proxy"));
1004 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1006 * Handle case with the empty http.proxy value here to keep
1007 * common code clean.
1008 * NB: empty option disables proxying at all.
1010 curl_easy_setopt(result, CURLOPT_PROXY, "");
1011 } else if (curl_http_proxy) {
1012 if (starts_with(curl_http_proxy, "socks5h"))
1013 curl_easy_setopt(result,
1014 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1015 else if (starts_with(curl_http_proxy, "socks5"))
1016 curl_easy_setopt(result,
1017 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1018 else if (starts_with(curl_http_proxy, "socks4a"))
1019 curl_easy_setopt(result,
1020 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1021 else if (starts_with(curl_http_proxy, "socks"))
1022 curl_easy_setopt(result,
1023 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1024 #ifdef GIT_CURL_HAVE_CURLOPT_PROXY_KEYPASSWD
1025 else if (starts_with(curl_http_proxy, "https")) {
1026 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1028 if (http_proxy_ssl_cert)
1029 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1031 if (http_proxy_ssl_key)
1032 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1034 if (has_proxy_cert_password())
1035 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1037 #endif
1038 if (strstr(curl_http_proxy, "://"))
1039 credential_from_url(&proxy_auth, curl_http_proxy);
1040 else {
1041 struct strbuf url = STRBUF_INIT;
1042 strbuf_addf(&url, "http://%s", curl_http_proxy);
1043 credential_from_url(&proxy_auth, url.buf);
1044 strbuf_release(&url);
1047 if (!proxy_auth.host)
1048 die("Invalid proxy URL '%s'", curl_http_proxy);
1050 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1051 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1052 var_override(&curl_no_proxy, getenv("no_proxy"));
1053 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1055 init_curl_proxy_auth(result);
1057 set_curl_keepalive(result);
1059 return result;
1062 static void set_from_env(const char **var, const char *envname)
1064 const char *val = getenv(envname);
1065 if (val)
1066 *var = val;
1069 void http_init(struct remote *remote, const char *url, int proactive_auth)
1071 char *low_speed_limit;
1072 char *low_speed_time;
1073 char *normalized_url;
1074 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
1076 config.section = "http";
1077 config.key = NULL;
1078 config.collect_fn = http_options;
1079 config.cascade_fn = git_default_config;
1080 config.cb = NULL;
1082 http_is_verbose = 0;
1083 normalized_url = url_normalize(url, &config.url);
1085 git_config(urlmatch_config_entry, &config);
1086 free(normalized_url);
1087 string_list_clear(&config.vars, 1);
1089 #ifdef GIT_CURL_HAVE_CURLSSLSET_NO_BACKENDS
1090 if (http_ssl_backend) {
1091 const curl_ssl_backend **backends;
1092 struct strbuf buf = STRBUF_INIT;
1093 int i;
1095 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1096 case CURLSSLSET_UNKNOWN_BACKEND:
1097 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1098 "Supported SSL backends:"),
1099 http_ssl_backend);
1100 for (i = 0; backends[i]; i++)
1101 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1102 die("%s", buf.buf);
1103 case CURLSSLSET_NO_BACKENDS:
1104 die(_("Could not set SSL backend to '%s': "
1105 "cURL was built without SSL backends"),
1106 http_ssl_backend);
1107 case CURLSSLSET_TOO_LATE:
1108 die(_("Could not set SSL backend to '%s': already set"),
1109 http_ssl_backend);
1110 case CURLSSLSET_OK:
1111 break; /* Okay! */
1114 #endif
1116 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1117 die("curl_global_init failed");
1119 http_proactive_auth = proactive_auth;
1121 if (remote && remote->http_proxy)
1122 curl_http_proxy = xstrdup(remote->http_proxy);
1124 if (remote)
1125 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1127 pragma_header = curl_slist_append(http_copy_default_headers(),
1128 "Pragma: no-cache");
1129 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1130 "Pragma:");
1133 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1134 if (http_max_requests)
1135 max_requests = atoi(http_max_requests);
1138 curlm = curl_multi_init();
1139 if (!curlm)
1140 die("curl_multi_init failed");
1142 if (getenv("GIT_SSL_NO_VERIFY"))
1143 curl_ssl_verify = 0;
1145 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1146 set_from_env(&ssl_key, "GIT_SSL_KEY");
1147 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1148 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1150 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1152 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1153 if (low_speed_limit)
1154 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1155 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1156 if (low_speed_time)
1157 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1159 if (curl_ssl_verify == -1)
1160 curl_ssl_verify = 1;
1162 curl_session_count = 0;
1163 if (max_requests < 1)
1164 max_requests = DEFAULT_MAX_REQUESTS;
1166 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1167 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1168 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1170 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1171 proxy_ssl_cert_password_required = 1;
1173 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1174 curl_ftp_no_epsv = 1;
1176 if (url) {
1177 credential_from_url(&http_auth, url);
1178 if (!ssl_cert_password_required &&
1179 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1180 starts_with(url, "https://"))
1181 ssl_cert_password_required = 1;
1184 curl_default = get_curl_handle();
1187 void http_cleanup(void)
1189 struct active_request_slot *slot = active_queue_head;
1191 while (slot != NULL) {
1192 struct active_request_slot *next = slot->next;
1193 if (slot->curl) {
1194 xmulti_remove_handle(slot);
1195 curl_easy_cleanup(slot->curl);
1197 free(slot);
1198 slot = next;
1200 active_queue_head = NULL;
1202 curl_easy_cleanup(curl_default);
1204 curl_multi_cleanup(curlm);
1205 curl_global_cleanup();
1207 string_list_clear(&extra_http_headers, 0);
1209 curl_slist_free_all(pragma_header);
1210 pragma_header = NULL;
1212 curl_slist_free_all(no_pragma_header);
1213 no_pragma_header = NULL;
1215 curl_slist_free_all(host_resolutions);
1216 host_resolutions = NULL;
1218 if (curl_http_proxy) {
1219 free((void *)curl_http_proxy);
1220 curl_http_proxy = NULL;
1223 if (proxy_auth.password) {
1224 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1225 FREE_AND_NULL(proxy_auth.password);
1228 free((void *)curl_proxyuserpwd);
1229 curl_proxyuserpwd = NULL;
1231 free((void *)http_proxy_authmethod);
1232 http_proxy_authmethod = NULL;
1234 if (cert_auth.password) {
1235 memset(cert_auth.password, 0, strlen(cert_auth.password));
1236 FREE_AND_NULL(cert_auth.password);
1238 ssl_cert_password_required = 0;
1240 if (proxy_cert_auth.password) {
1241 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1242 FREE_AND_NULL(proxy_cert_auth.password);
1244 proxy_ssl_cert_password_required = 0;
1246 FREE_AND_NULL(cached_accept_language);
1249 struct active_request_slot *get_active_slot(void)
1251 struct active_request_slot *slot = active_queue_head;
1252 struct active_request_slot *newslot;
1254 int num_transfers;
1256 /* Wait for a slot to open up if the queue is full */
1257 while (active_requests >= max_requests) {
1258 curl_multi_perform(curlm, &num_transfers);
1259 if (num_transfers < active_requests)
1260 process_curl_messages();
1263 while (slot != NULL && slot->in_use)
1264 slot = slot->next;
1266 if (!slot) {
1267 newslot = xmalloc(sizeof(*newslot));
1268 newslot->curl = NULL;
1269 newslot->in_use = 0;
1270 newslot->next = NULL;
1272 slot = active_queue_head;
1273 if (!slot) {
1274 active_queue_head = newslot;
1275 } else {
1276 while (slot->next != NULL)
1277 slot = slot->next;
1278 slot->next = newslot;
1280 slot = newslot;
1283 if (!slot->curl) {
1284 slot->curl = curl_easy_duphandle(curl_default);
1285 curl_session_count++;
1288 active_requests++;
1289 slot->in_use = 1;
1290 slot->results = NULL;
1291 slot->finished = NULL;
1292 slot->callback_data = NULL;
1293 slot->callback_func = NULL;
1294 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1295 if (curl_save_cookies)
1296 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1297 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1298 curl_easy_setopt(slot->curl, CURLOPT_RESOLVE, host_resolutions);
1299 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1300 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1301 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1302 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1303 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1304 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1305 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1306 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1307 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1310 * Default following to off unless "ALWAYS" is configured; this gives
1311 * callers a sane starting point, and they can tweak for individual
1312 * HTTP_FOLLOW_* cases themselves.
1314 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1315 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1316 else
1317 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1319 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1320 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1321 if (http_auth.password || curl_empty_auth_enabled())
1322 init_curl_http_auth(slot->curl);
1324 return slot;
1327 int start_active_slot(struct active_request_slot *slot)
1329 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1330 int num_transfers;
1332 if (curlm_result != CURLM_OK &&
1333 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1334 warning("curl_multi_add_handle failed: %s",
1335 curl_multi_strerror(curlm_result));
1336 active_requests--;
1337 slot->in_use = 0;
1338 return 0;
1342 * We know there must be something to do, since we just added
1343 * something.
1345 curl_multi_perform(curlm, &num_transfers);
1346 return 1;
1349 struct fill_chain {
1350 void *data;
1351 int (*fill)(void *);
1352 struct fill_chain *next;
1355 static struct fill_chain *fill_cfg;
1357 void add_fill_function(void *data, int (*fill)(void *))
1359 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1360 struct fill_chain **linkp = &fill_cfg;
1361 new_fill->data = data;
1362 new_fill->fill = fill;
1363 new_fill->next = NULL;
1364 while (*linkp)
1365 linkp = &(*linkp)->next;
1366 *linkp = new_fill;
1369 void fill_active_slots(void)
1371 struct active_request_slot *slot = active_queue_head;
1373 while (active_requests < max_requests) {
1374 struct fill_chain *fill;
1375 for (fill = fill_cfg; fill; fill = fill->next)
1376 if (fill->fill(fill->data))
1377 break;
1379 if (!fill)
1380 break;
1383 while (slot != NULL) {
1384 if (!slot->in_use && slot->curl != NULL
1385 && curl_session_count > min_curl_sessions) {
1386 curl_easy_cleanup(slot->curl);
1387 slot->curl = NULL;
1388 curl_session_count--;
1390 slot = slot->next;
1394 void step_active_slots(void)
1396 int num_transfers;
1397 CURLMcode curlm_result;
1399 do {
1400 curlm_result = curl_multi_perform(curlm, &num_transfers);
1401 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1402 if (num_transfers < active_requests) {
1403 process_curl_messages();
1404 fill_active_slots();
1408 void run_active_slot(struct active_request_slot *slot)
1410 fd_set readfds;
1411 fd_set writefds;
1412 fd_set excfds;
1413 int max_fd;
1414 struct timeval select_timeout;
1415 int finished = 0;
1417 slot->finished = &finished;
1418 while (!finished) {
1419 step_active_slots();
1421 if (slot->in_use) {
1422 long curl_timeout;
1423 curl_multi_timeout(curlm, &curl_timeout);
1424 if (curl_timeout == 0) {
1425 continue;
1426 } else if (curl_timeout == -1) {
1427 select_timeout.tv_sec = 0;
1428 select_timeout.tv_usec = 50000;
1429 } else {
1430 select_timeout.tv_sec = curl_timeout / 1000;
1431 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1434 max_fd = -1;
1435 FD_ZERO(&readfds);
1436 FD_ZERO(&writefds);
1437 FD_ZERO(&excfds);
1438 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1441 * It can happen that curl_multi_timeout returns a pathologically
1442 * long timeout when curl_multi_fdset returns no file descriptors
1443 * to read. See commit message for more details.
1445 if (max_fd < 0 &&
1446 (select_timeout.tv_sec > 0 ||
1447 select_timeout.tv_usec > 50000)) {
1448 select_timeout.tv_sec = 0;
1449 select_timeout.tv_usec = 50000;
1452 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1457 * The value of slot->finished we set before the loop was used
1458 * to set our "finished" variable when our request completed.
1460 * 1. The slot may not have been reused for another requst
1461 * yet, in which case it still has &finished.
1463 * 2. The slot may already be in-use to serve another request,
1464 * which can further be divided into two cases:
1466 * (a) If call run_active_slot() hasn't been called for that
1467 * other request, slot->finished would have been cleared
1468 * by get_active_slot() and has NULL.
1470 * (b) If the request did call run_active_slot(), then the
1471 * call would have updated slot->finished at the beginning
1472 * of this function, and with the clearing of the member
1473 * below, we would find that slot->finished is now NULL.
1475 * In all cases, slot->finished has no useful information to
1476 * anybody at this point. Some compilers warn us for
1477 * attempting to smuggle a pointer that is about to become
1478 * invalid, i.e. &finished. We clear it here to assure them.
1480 slot->finished = NULL;
1483 static void release_active_slot(struct active_request_slot *slot)
1485 closedown_active_slot(slot);
1486 if (slot->curl) {
1487 xmulti_remove_handle(slot);
1488 if (curl_session_count > min_curl_sessions) {
1489 curl_easy_cleanup(slot->curl);
1490 slot->curl = NULL;
1491 curl_session_count--;
1494 fill_active_slots();
1497 void finish_all_active_slots(void)
1499 struct active_request_slot *slot = active_queue_head;
1501 while (slot != NULL)
1502 if (slot->in_use) {
1503 run_active_slot(slot);
1504 slot = active_queue_head;
1505 } else {
1506 slot = slot->next;
1510 /* Helpers for modifying and creating URLs */
1511 static inline int needs_quote(int ch)
1513 if (((ch >= 'A') && (ch <= 'Z'))
1514 || ((ch >= 'a') && (ch <= 'z'))
1515 || ((ch >= '0') && (ch <= '9'))
1516 || (ch == '/')
1517 || (ch == '-')
1518 || (ch == '.'))
1519 return 0;
1520 return 1;
1523 static char *quote_ref_url(const char *base, const char *ref)
1525 struct strbuf buf = STRBUF_INIT;
1526 const char *cp;
1527 int ch;
1529 end_url_with_slash(&buf, base);
1531 for (cp = ref; (ch = *cp) != 0; cp++)
1532 if (needs_quote(ch))
1533 strbuf_addf(&buf, "%%%02x", ch);
1534 else
1535 strbuf_addch(&buf, *cp);
1537 return strbuf_detach(&buf, NULL);
1540 void append_remote_object_url(struct strbuf *buf, const char *url,
1541 const char *hex,
1542 int only_two_digit_prefix)
1544 end_url_with_slash(buf, url);
1546 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1547 if (!only_two_digit_prefix)
1548 strbuf_addstr(buf, hex + 2);
1551 char *get_remote_object_url(const char *url, const char *hex,
1552 int only_two_digit_prefix)
1554 struct strbuf buf = STRBUF_INIT;
1555 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1556 return strbuf_detach(&buf, NULL);
1559 void normalize_curl_result(CURLcode *result, long http_code,
1560 char *errorstr, size_t errorlen)
1563 * If we see a failing http code with CURLE_OK, we have turned off
1564 * FAILONERROR (to keep the server's custom error response), and should
1565 * translate the code into failure here.
1567 * Likewise, if we see a redirect (30x code), that means we turned off
1568 * redirect-following, and we should treat the result as an error.
1570 if (*result == CURLE_OK && http_code >= 300) {
1571 *result = CURLE_HTTP_RETURNED_ERROR;
1573 * Normally curl will already have put the "reason phrase"
1574 * from the server into curl_errorstr; unfortunately without
1575 * FAILONERROR it is lost, so we can give only the numeric
1576 * status code.
1578 xsnprintf(errorstr, errorlen,
1579 "The requested URL returned error: %ld",
1580 http_code);
1584 static int handle_curl_result(struct slot_results *results)
1586 normalize_curl_result(&results->curl_result, results->http_code,
1587 curl_errorstr, sizeof(curl_errorstr));
1589 if (results->curl_result == CURLE_OK) {
1590 credential_approve(&http_auth);
1591 credential_approve(&proxy_auth);
1592 credential_approve(&cert_auth);
1593 return HTTP_OK;
1594 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1596 * We can't tell from here whether it's a bad path, bad
1597 * certificate, bad password, or something else wrong
1598 * with the certificate. So we reject the credential to
1599 * avoid caching or saving a bad password.
1601 credential_reject(&cert_auth);
1602 return HTTP_NOAUTH;
1603 #ifdef GIT_CURL_HAVE_CURLE_SSL_PINNEDPUBKEYNOTMATCH
1604 } else if (results->curl_result == CURLE_SSL_PINNEDPUBKEYNOTMATCH) {
1605 return HTTP_NOMATCHPUBLICKEY;
1606 #endif
1607 } else if (missing_target(results))
1608 return HTTP_MISSING_TARGET;
1609 else if (results->http_code == 401) {
1610 if (http_auth.username && http_auth.password) {
1611 credential_reject(&http_auth);
1612 return HTTP_NOAUTH;
1613 } else {
1614 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1615 if (results->auth_avail) {
1616 http_auth_methods &= results->auth_avail;
1617 http_auth_methods_restricted = 1;
1619 return HTTP_REAUTH;
1621 } else {
1622 if (results->http_connectcode == 407)
1623 credential_reject(&proxy_auth);
1624 if (!curl_errorstr[0])
1625 strlcpy(curl_errorstr,
1626 curl_easy_strerror(results->curl_result),
1627 sizeof(curl_errorstr));
1628 return HTTP_ERROR;
1632 int run_one_slot(struct active_request_slot *slot,
1633 struct slot_results *results)
1635 slot->results = results;
1636 if (!start_active_slot(slot)) {
1637 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1638 "failed to start HTTP request");
1639 return HTTP_START_FAILED;
1642 run_active_slot(slot);
1643 return handle_curl_result(results);
1646 struct curl_slist *http_copy_default_headers(void)
1648 struct curl_slist *headers = NULL;
1649 const struct string_list_item *item;
1651 for_each_string_list_item(item, &extra_http_headers)
1652 headers = curl_slist_append(headers, item->string);
1654 return headers;
1657 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1659 char *ptr;
1660 CURLcode ret;
1662 strbuf_reset(buf);
1663 ret = curl_easy_getinfo(curl, info, &ptr);
1664 if (!ret && ptr)
1665 strbuf_addstr(buf, ptr);
1666 return ret;
1670 * Check for and extract a content-type parameter. "raw"
1671 * should be positioned at the start of the potential
1672 * parameter, with any whitespace already removed.
1674 * "name" is the name of the parameter. The value is appended
1675 * to "out".
1677 static int extract_param(const char *raw, const char *name,
1678 struct strbuf *out)
1680 size_t len = strlen(name);
1682 if (strncasecmp(raw, name, len))
1683 return -1;
1684 raw += len;
1686 if (*raw != '=')
1687 return -1;
1688 raw++;
1690 while (*raw && !isspace(*raw) && *raw != ';')
1691 strbuf_addch(out, *raw++);
1692 return 0;
1696 * Extract a normalized version of the content type, with any
1697 * spaces suppressed, all letters lowercased, and no trailing ";"
1698 * or parameters.
1700 * Note that we will silently remove even invalid whitespace. For
1701 * example, "text / plain" is specifically forbidden by RFC 2616,
1702 * but "text/plain" is the only reasonable output, and this keeps
1703 * our code simple.
1705 * If the "charset" argument is not NULL, store the value of any
1706 * charset parameter there.
1708 * Example:
1709 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1710 * "text / plain" -> "text/plain"
1712 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1713 struct strbuf *charset)
1715 const char *p;
1717 strbuf_reset(type);
1718 strbuf_grow(type, raw->len);
1719 for (p = raw->buf; *p; p++) {
1720 if (isspace(*p))
1721 continue;
1722 if (*p == ';') {
1723 p++;
1724 break;
1726 strbuf_addch(type, tolower(*p));
1729 if (!charset)
1730 return;
1732 strbuf_reset(charset);
1733 while (*p) {
1734 while (isspace(*p) || *p == ';')
1735 p++;
1736 if (!extract_param(p, "charset", charset))
1737 return;
1738 while (*p && !isspace(*p))
1739 p++;
1742 if (!charset->len && starts_with(type->buf, "text/"))
1743 strbuf_addstr(charset, "ISO-8859-1");
1746 static void write_accept_language(struct strbuf *buf)
1749 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1750 * that, q-value will be smaller than 0.001, the minimum q-value the
1751 * HTTP specification allows. See
1752 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1754 const int MAX_DECIMAL_PLACES = 3;
1755 const int MAX_LANGUAGE_TAGS = 1000;
1756 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1757 char **language_tags = NULL;
1758 int num_langs = 0;
1759 const char *s = get_preferred_languages();
1760 int i;
1761 struct strbuf tag = STRBUF_INIT;
1763 /* Don't add Accept-Language header if no language is preferred. */
1764 if (!s)
1765 return;
1768 * Split the colon-separated string of preferred languages into
1769 * language_tags array.
1771 do {
1772 /* collect language tag */
1773 for (; *s && (isalnum(*s) || *s == '_'); s++)
1774 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1776 /* skip .codeset, @modifier and any other unnecessary parts */
1777 while (*s && *s != ':')
1778 s++;
1780 if (tag.len) {
1781 num_langs++;
1782 REALLOC_ARRAY(language_tags, num_langs);
1783 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1784 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1785 break;
1787 } while (*s++);
1789 /* write Accept-Language header into buf */
1790 if (num_langs) {
1791 int last_buf_len = 0;
1792 int max_q;
1793 int decimal_places;
1794 char q_format[32];
1796 /* add '*' */
1797 REALLOC_ARRAY(language_tags, num_langs + 1);
1798 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1800 /* compute decimal_places */
1801 for (max_q = 1, decimal_places = 0;
1802 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1803 decimal_places++, max_q *= 10)
1806 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1808 strbuf_addstr(buf, "Accept-Language: ");
1810 for (i = 0; i < num_langs; i++) {
1811 if (i > 0)
1812 strbuf_addstr(buf, ", ");
1814 strbuf_addstr(buf, language_tags[i]);
1816 if (i > 0)
1817 strbuf_addf(buf, q_format, max_q - i);
1819 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1820 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1821 break;
1824 last_buf_len = buf->len;
1828 /* free language tags -- last one is a static '*' */
1829 for (i = 0; i < num_langs - 1; i++)
1830 free(language_tags[i]);
1831 free(language_tags);
1835 * Get an Accept-Language header which indicates user's preferred languages.
1837 * Examples:
1838 * LANGUAGE= -> ""
1839 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1840 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1841 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1842 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1843 * LANGUAGE= LANG=C -> ""
1845 const char *http_get_accept_language_header(void)
1847 if (!cached_accept_language) {
1848 struct strbuf buf = STRBUF_INIT;
1849 write_accept_language(&buf);
1850 if (buf.len > 0)
1851 cached_accept_language = strbuf_detach(&buf, NULL);
1854 return cached_accept_language;
1857 static void http_opt_request_remainder(CURL *curl, off_t pos)
1859 char buf[128];
1860 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1861 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1864 /* http_request() targets */
1865 #define HTTP_REQUEST_STRBUF 0
1866 #define HTTP_REQUEST_FILE 1
1868 static int http_request(const char *url,
1869 void *result, int target,
1870 const struct http_get_options *options)
1872 struct active_request_slot *slot;
1873 struct slot_results results;
1874 struct curl_slist *headers = http_copy_default_headers();
1875 struct strbuf buf = STRBUF_INIT;
1876 const char *accept_language;
1877 int ret;
1879 slot = get_active_slot();
1880 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1882 if (!result) {
1883 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1884 } else {
1885 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1886 curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, result);
1888 if (target == HTTP_REQUEST_FILE) {
1889 off_t posn = ftello(result);
1890 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1891 fwrite);
1892 if (posn > 0)
1893 http_opt_request_remainder(slot->curl, posn);
1894 } else
1895 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1896 fwrite_buffer);
1899 accept_language = http_get_accept_language_header();
1901 if (accept_language)
1902 headers = curl_slist_append(headers, accept_language);
1904 strbuf_addstr(&buf, "Pragma:");
1905 if (options && options->no_cache)
1906 strbuf_addstr(&buf, " no-cache");
1907 if (options && options->initial_request &&
1908 http_follow_config == HTTP_FOLLOW_INITIAL)
1909 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1911 headers = curl_slist_append(headers, buf.buf);
1913 /* Add additional headers here */
1914 if (options && options->extra_headers) {
1915 const struct string_list_item *item;
1916 for_each_string_list_item(item, options->extra_headers) {
1917 headers = curl_slist_append(headers, item->string);
1921 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1922 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1923 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1924 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1926 ret = run_one_slot(slot, &results);
1928 if (options && options->content_type) {
1929 struct strbuf raw = STRBUF_INIT;
1930 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1931 extract_content_type(&raw, options->content_type,
1932 options->charset);
1933 strbuf_release(&raw);
1936 if (options && options->effective_url)
1937 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1938 options->effective_url);
1940 curl_slist_free_all(headers);
1941 strbuf_release(&buf);
1943 return ret;
1947 * Update the "base" url to a more appropriate value, as deduced by
1948 * redirects seen when requesting a URL starting with "url".
1950 * The "asked" parameter is a URL that we asked curl to access, and must begin
1951 * with "base".
1953 * The "got" parameter is the URL that curl reported to us as where we ended
1954 * up.
1956 * Returns 1 if we updated the base url, 0 otherwise.
1958 * Our basic strategy is to compare "base" and "asked" to find the bits
1959 * specific to our request. We then strip those bits off of "got" to yield the
1960 * new base. So for example, if our base is "http://example.com/foo.git",
1961 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1962 * with "https://other.example.com/foo.git/info/refs". We would want the
1963 * new URL to become "https://other.example.com/foo.git".
1965 * Note that this assumes a sane redirect scheme. It's entirely possible
1966 * in the example above to end up at a URL that does not even end in
1967 * "info/refs". In such a case we die. There's not much we can do, such a
1968 * scheme is unlikely to represent a real git repository, and failing to
1969 * rewrite the base opens options for malicious redirects to do funny things.
1971 static int update_url_from_redirect(struct strbuf *base,
1972 const char *asked,
1973 const struct strbuf *got)
1975 const char *tail;
1976 size_t new_len;
1978 if (!strcmp(asked, got->buf))
1979 return 0;
1981 if (!skip_prefix(asked, base->buf, &tail))
1982 BUG("update_url_from_redirect: %s is not a superset of %s",
1983 asked, base->buf);
1985 new_len = got->len;
1986 if (!strip_suffix_mem(got->buf, &new_len, tail))
1987 die(_("unable to update url base from redirection:\n"
1988 " asked for: %s\n"
1989 " redirect: %s"),
1990 asked, got->buf);
1992 strbuf_reset(base);
1993 strbuf_add(base, got->buf, new_len);
1995 return 1;
1998 static int http_request_reauth(const char *url,
1999 void *result, int target,
2000 struct http_get_options *options)
2002 int ret = http_request(url, result, target, options);
2004 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2005 return ret;
2007 if (options && options->effective_url && options->base_url) {
2008 if (update_url_from_redirect(options->base_url,
2009 url, options->effective_url)) {
2010 credential_from_url(&http_auth, options->base_url->buf);
2011 url = options->effective_url->buf;
2015 if (ret != HTTP_REAUTH)
2016 return ret;
2019 * The previous request may have put cruft into our output stream; we
2020 * should clear it out before making our next request.
2022 switch (target) {
2023 case HTTP_REQUEST_STRBUF:
2024 strbuf_reset(result);
2025 break;
2026 case HTTP_REQUEST_FILE:
2027 if (fflush(result)) {
2028 error_errno("unable to flush a file");
2029 return HTTP_START_FAILED;
2031 rewind(result);
2032 if (ftruncate(fileno(result), 0) < 0) {
2033 error_errno("unable to truncate a file");
2034 return HTTP_START_FAILED;
2036 break;
2037 default:
2038 BUG("Unknown http_request target");
2041 credential_fill(&http_auth);
2043 return http_request(url, result, target, options);
2046 int http_get_strbuf(const char *url,
2047 struct strbuf *result,
2048 struct http_get_options *options)
2050 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2054 * Downloads a URL and stores the result in the given file.
2056 * If a previous interrupted download is detected (i.e. a previous temporary
2057 * file is still around) the download is resumed.
2059 int http_get_file(const char *url, const char *filename,
2060 struct http_get_options *options)
2062 int ret;
2063 struct strbuf tmpfile = STRBUF_INIT;
2064 FILE *result;
2066 strbuf_addf(&tmpfile, "%s.temp", filename);
2067 result = fopen(tmpfile.buf, "a");
2068 if (!result) {
2069 error("Unable to open local file %s", tmpfile.buf);
2070 ret = HTTP_ERROR;
2071 goto cleanup;
2074 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2075 fclose(result);
2077 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2078 ret = HTTP_ERROR;
2079 cleanup:
2080 strbuf_release(&tmpfile);
2081 return ret;
2084 int http_fetch_ref(const char *base, struct ref *ref)
2086 struct http_get_options options = {0};
2087 char *url;
2088 struct strbuf buffer = STRBUF_INIT;
2089 int ret = -1;
2091 options.no_cache = 1;
2093 url = quote_ref_url(base, ref->name);
2094 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2095 strbuf_rtrim(&buffer);
2096 if (buffer.len == the_hash_algo->hexsz)
2097 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2098 else if (starts_with(buffer.buf, "ref: ")) {
2099 ref->symref = xstrdup(buffer.buf + 5);
2100 ret = 0;
2104 strbuf_release(&buffer);
2105 free(url);
2106 return ret;
2109 /* Helpers for fetching packs */
2110 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2112 char *url, *tmp;
2113 struct strbuf buf = STRBUF_INIT;
2115 if (http_is_verbose)
2116 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2118 end_url_with_slash(&buf, base_url);
2119 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2120 url = strbuf_detach(&buf, NULL);
2122 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2123 tmp = strbuf_detach(&buf, NULL);
2125 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2126 error("Unable to get pack index %s", url);
2127 FREE_AND_NULL(tmp);
2130 free(url);
2131 return tmp;
2134 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2135 unsigned char *sha1, const char *base_url)
2137 struct packed_git *new_pack;
2138 char *tmp_idx = NULL;
2139 int ret;
2141 if (has_pack_index(sha1)) {
2142 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2143 if (!new_pack)
2144 return -1; /* parse_pack_index() already issued error message */
2145 goto add_pack;
2148 tmp_idx = fetch_pack_index(sha1, base_url);
2149 if (!tmp_idx)
2150 return -1;
2152 new_pack = parse_pack_index(sha1, tmp_idx);
2153 if (!new_pack) {
2154 unlink(tmp_idx);
2155 free(tmp_idx);
2157 return -1; /* parse_pack_index() already issued error message */
2160 ret = verify_pack_index(new_pack);
2161 if (!ret) {
2162 close_pack_index(new_pack);
2163 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2165 free(tmp_idx);
2166 if (ret)
2167 return -1;
2169 add_pack:
2170 new_pack->next = *packs_head;
2171 *packs_head = new_pack;
2172 return 0;
2175 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2177 struct http_get_options options = {0};
2178 int ret = 0;
2179 char *url;
2180 const char *data;
2181 struct strbuf buf = STRBUF_INIT;
2182 struct object_id oid;
2184 end_url_with_slash(&buf, base_url);
2185 strbuf_addstr(&buf, "objects/info/packs");
2186 url = strbuf_detach(&buf, NULL);
2188 options.no_cache = 1;
2189 ret = http_get_strbuf(url, &buf, &options);
2190 if (ret != HTTP_OK)
2191 goto cleanup;
2193 data = buf.buf;
2194 while (*data) {
2195 if (skip_prefix(data, "P pack-", &data) &&
2196 !parse_oid_hex(data, &oid, &data) &&
2197 skip_prefix(data, ".pack", &data) &&
2198 (*data == '\n' || *data == '\0')) {
2199 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2200 } else {
2201 data = strchrnul(data, '\n');
2203 if (*data)
2204 data++; /* skip past newline */
2207 cleanup:
2208 free(url);
2209 return ret;
2212 void release_http_pack_request(struct http_pack_request *preq)
2214 if (preq->packfile) {
2215 fclose(preq->packfile);
2216 preq->packfile = NULL;
2218 preq->slot = NULL;
2219 strbuf_release(&preq->tmpfile);
2220 free(preq->url);
2221 free(preq);
2224 static const char *default_index_pack_args[] =
2225 {"index-pack", "--stdin", NULL};
2227 int finish_http_pack_request(struct http_pack_request *preq)
2229 struct child_process ip = CHILD_PROCESS_INIT;
2230 int tmpfile_fd;
2231 int ret = 0;
2233 fclose(preq->packfile);
2234 preq->packfile = NULL;
2236 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2238 ip.git_cmd = 1;
2239 ip.in = tmpfile_fd;
2240 strvec_pushv(&ip.args, preq->index_pack_args ?
2241 preq->index_pack_args :
2242 default_index_pack_args);
2244 if (preq->preserve_index_pack_stdout)
2245 ip.out = 0;
2246 else
2247 ip.no_stdout = 1;
2249 if (run_command(&ip)) {
2250 ret = -1;
2251 goto cleanup;
2254 cleanup:
2255 close(tmpfile_fd);
2256 unlink(preq->tmpfile.buf);
2257 return ret;
2260 void http_install_packfile(struct packed_git *p,
2261 struct packed_git **list_to_remove_from)
2263 struct packed_git **lst = list_to_remove_from;
2265 while (*lst != p)
2266 lst = &((*lst)->next);
2267 *lst = (*lst)->next;
2269 install_packed_git(the_repository, p);
2272 struct http_pack_request *new_http_pack_request(
2273 const unsigned char *packed_git_hash, const char *base_url) {
2275 struct strbuf buf = STRBUF_INIT;
2277 end_url_with_slash(&buf, base_url);
2278 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2279 hash_to_hex(packed_git_hash));
2280 return new_direct_http_pack_request(packed_git_hash,
2281 strbuf_detach(&buf, NULL));
2284 struct http_pack_request *new_direct_http_pack_request(
2285 const unsigned char *packed_git_hash, char *url)
2287 off_t prev_posn = 0;
2288 struct http_pack_request *preq;
2290 CALLOC_ARRAY(preq, 1);
2291 strbuf_init(&preq->tmpfile, 0);
2293 preq->url = url;
2295 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2296 preq->packfile = fopen(preq->tmpfile.buf, "a");
2297 if (!preq->packfile) {
2298 error("Unable to open local file %s for pack",
2299 preq->tmpfile.buf);
2300 goto abort;
2303 preq->slot = get_active_slot();
2304 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEDATA, preq->packfile);
2305 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2306 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2307 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2308 no_pragma_header);
2311 * If there is data present from a previous transfer attempt,
2312 * resume where it left off
2314 prev_posn = ftello(preq->packfile);
2315 if (prev_posn>0) {
2316 if (http_is_verbose)
2317 fprintf(stderr,
2318 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2319 hash_to_hex(packed_git_hash),
2320 (uintmax_t)prev_posn);
2321 http_opt_request_remainder(preq->slot->curl, prev_posn);
2324 return preq;
2326 abort:
2327 strbuf_release(&preq->tmpfile);
2328 free(preq->url);
2329 free(preq);
2330 return NULL;
2333 /* Helpers for fetching objects (loose) */
2334 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2335 void *data)
2337 unsigned char expn[4096];
2338 size_t size = eltsize * nmemb;
2339 int posn = 0;
2340 struct http_object_request *freq = data;
2341 struct active_request_slot *slot = freq->slot;
2343 if (slot) {
2344 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2345 &slot->http_code);
2346 if (c != CURLE_OK)
2347 BUG("curl_easy_getinfo for HTTP code failed: %s",
2348 curl_easy_strerror(c));
2349 if (slot->http_code >= 300)
2350 return nmemb;
2353 do {
2354 ssize_t retval = xwrite(freq->localfile,
2355 (char *) ptr + posn, size - posn);
2356 if (retval < 0)
2357 return posn / eltsize;
2358 posn += retval;
2359 } while (posn < size);
2361 freq->stream.avail_in = size;
2362 freq->stream.next_in = (void *)ptr;
2363 do {
2364 freq->stream.next_out = expn;
2365 freq->stream.avail_out = sizeof(expn);
2366 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2367 the_hash_algo->update_fn(&freq->c, expn,
2368 sizeof(expn) - freq->stream.avail_out);
2369 } while (freq->stream.avail_in && freq->zret == Z_OK);
2370 return nmemb;
2373 struct http_object_request *new_http_object_request(const char *base_url,
2374 const struct object_id *oid)
2376 char *hex = oid_to_hex(oid);
2377 struct strbuf filename = STRBUF_INIT;
2378 struct strbuf prevfile = STRBUF_INIT;
2379 int prevlocal;
2380 char prev_buf[PREV_BUF_SIZE];
2381 ssize_t prev_read = 0;
2382 off_t prev_posn = 0;
2383 struct http_object_request *freq;
2385 CALLOC_ARRAY(freq, 1);
2386 strbuf_init(&freq->tmpfile, 0);
2387 oidcpy(&freq->oid, oid);
2388 freq->localfile = -1;
2390 loose_object_path(the_repository, &filename, oid);
2391 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2393 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2394 unlink_or_warn(prevfile.buf);
2395 rename(freq->tmpfile.buf, prevfile.buf);
2396 unlink_or_warn(freq->tmpfile.buf);
2397 strbuf_release(&filename);
2399 if (freq->localfile != -1)
2400 error("fd leakage in start: %d", freq->localfile);
2401 freq->localfile = open(freq->tmpfile.buf,
2402 O_WRONLY | O_CREAT | O_EXCL, 0666);
2404 * This could have failed due to the "lazy directory creation";
2405 * try to mkdir the last path component.
2407 if (freq->localfile < 0 && errno == ENOENT) {
2408 char *dir = strrchr(freq->tmpfile.buf, '/');
2409 if (dir) {
2410 *dir = 0;
2411 mkdir(freq->tmpfile.buf, 0777);
2412 *dir = '/';
2414 freq->localfile = open(freq->tmpfile.buf,
2415 O_WRONLY | O_CREAT | O_EXCL, 0666);
2418 if (freq->localfile < 0) {
2419 error_errno("Couldn't create temporary file %s",
2420 freq->tmpfile.buf);
2421 goto abort;
2424 git_inflate_init(&freq->stream);
2426 the_hash_algo->init_fn(&freq->c);
2428 freq->url = get_remote_object_url(base_url, hex, 0);
2431 * If a previous temp file is present, process what was already
2432 * fetched.
2434 prevlocal = open(prevfile.buf, O_RDONLY);
2435 if (prevlocal != -1) {
2436 do {
2437 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2438 if (prev_read>0) {
2439 if (fwrite_sha1_file(prev_buf,
2441 prev_read,
2442 freq) == prev_read) {
2443 prev_posn += prev_read;
2444 } else {
2445 prev_read = -1;
2448 } while (prev_read > 0);
2449 close(prevlocal);
2451 unlink_or_warn(prevfile.buf);
2452 strbuf_release(&prevfile);
2455 * Reset inflate/SHA1 if there was an error reading the previous temp
2456 * file; also rewind to the beginning of the local file.
2458 if (prev_read == -1) {
2459 memset(&freq->stream, 0, sizeof(freq->stream));
2460 git_inflate_init(&freq->stream);
2461 the_hash_algo->init_fn(&freq->c);
2462 if (prev_posn>0) {
2463 prev_posn = 0;
2464 lseek(freq->localfile, 0, SEEK_SET);
2465 if (ftruncate(freq->localfile, 0) < 0) {
2466 error_errno("Couldn't truncate temporary file %s",
2467 freq->tmpfile.buf);
2468 goto abort;
2473 freq->slot = get_active_slot();
2475 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEDATA, freq);
2476 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2477 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2478 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2479 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2480 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2483 * If we have successfully processed data from a previous fetch
2484 * attempt, only fetch the data we don't already have.
2486 if (prev_posn>0) {
2487 if (http_is_verbose)
2488 fprintf(stderr,
2489 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2490 hex, (uintmax_t)prev_posn);
2491 http_opt_request_remainder(freq->slot->curl, prev_posn);
2494 return freq;
2496 abort:
2497 strbuf_release(&prevfile);
2498 free(freq->url);
2499 free(freq);
2500 return NULL;
2503 void process_http_object_request(struct http_object_request *freq)
2505 if (!freq->slot)
2506 return;
2507 freq->curl_result = freq->slot->curl_result;
2508 freq->http_code = freq->slot->http_code;
2509 freq->slot = NULL;
2512 int finish_http_object_request(struct http_object_request *freq)
2514 struct stat st;
2515 struct strbuf filename = STRBUF_INIT;
2517 close(freq->localfile);
2518 freq->localfile = -1;
2520 process_http_object_request(freq);
2522 if (freq->http_code == 416) {
2523 warning("requested range invalid; we may already have all the data.");
2524 } else if (freq->curl_result != CURLE_OK) {
2525 if (stat(freq->tmpfile.buf, &st) == 0)
2526 if (st.st_size == 0)
2527 unlink_or_warn(freq->tmpfile.buf);
2528 return -1;
2531 git_inflate_end(&freq->stream);
2532 the_hash_algo->final_oid_fn(&freq->real_oid, &freq->c);
2533 if (freq->zret != Z_STREAM_END) {
2534 unlink_or_warn(freq->tmpfile.buf);
2535 return -1;
2537 if (!oideq(&freq->oid, &freq->real_oid)) {
2538 unlink_or_warn(freq->tmpfile.buf);
2539 return -1;
2541 loose_object_path(the_repository, &filename, &freq->oid);
2542 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2543 strbuf_release(&filename);
2545 return freq->rename;
2548 void abort_http_object_request(struct http_object_request *freq)
2550 unlink_or_warn(freq->tmpfile.buf);
2552 release_http_object_request(freq);
2555 void release_http_object_request(struct http_object_request *freq)
2557 if (freq->localfile != -1) {
2558 close(freq->localfile);
2559 freq->localfile = -1;
2561 FREE_AND_NULL(freq->url);
2562 if (freq->slot) {
2563 freq->slot->callback_func = NULL;
2564 freq->slot->callback_data = NULL;
2565 release_active_slot(freq->slot);
2566 freq->slot = NULL;
2568 strbuf_release(&freq->tmpfile);