t7003: use rev-parse rather than FS inspection
[git/debian.git] / http.c
blob406410f884e2e5132fae6b2f036e50169b72bec3
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "config.h"
4 #include "pack.h"
5 #include "sideband.h"
6 #include "run-command.h"
7 #include "url.h"
8 #include "urlmatch.h"
9 #include "credential.h"
10 #include "version.h"
11 #include "pkt-line.h"
12 #include "gettext.h"
13 #include "transport.h"
14 #include "packfile.h"
15 #include "protocol.h"
16 #include "string-list.h"
17 #include "object-store.h"
19 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
20 static int trace_curl_data = 1;
21 static int trace_curl_redact = 1;
22 #if LIBCURL_VERSION_NUM >= 0x070a08
23 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
24 #else
25 long int git_curl_ipresolve;
26 #endif
27 int active_requests;
28 int http_is_verbose;
29 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
31 #if LIBCURL_VERSION_NUM >= 0x070a06
32 #define LIBCURL_CAN_HANDLE_AUTH_ANY
33 #endif
35 static int min_curl_sessions = 1;
36 static int curl_session_count;
37 #ifdef USE_CURL_MULTI
38 static int max_requests = -1;
39 static CURLM *curlm;
40 #endif
41 #ifndef NO_CURL_EASY_DUPHANDLE
42 static CURL *curl_default;
43 #endif
45 #define PREV_BUF_SIZE 4096
47 char curl_errorstr[CURL_ERROR_SIZE];
49 static int curl_ssl_verify = -1;
50 static int curl_ssl_try;
51 static const char *curl_http_version = NULL;
52 static const char *ssl_cert;
53 static const char *ssl_cipherlist;
54 static const char *ssl_version;
55 static struct {
56 const char *name;
57 long ssl_version;
58 } sslversions[] = {
59 { "sslv2", CURL_SSLVERSION_SSLv2 },
60 { "sslv3", CURL_SSLVERSION_SSLv3 },
61 { "tlsv1", CURL_SSLVERSION_TLSv1 },
62 #if LIBCURL_VERSION_NUM >= 0x072200
63 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
64 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
65 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
66 #endif
67 #if LIBCURL_VERSION_NUM >= 0x073400
68 { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
69 #endif
71 #if LIBCURL_VERSION_NUM >= 0x070903
72 static const char *ssl_key;
73 #endif
74 #if LIBCURL_VERSION_NUM >= 0x070908
75 static const char *ssl_capath;
76 #endif
77 #if LIBCURL_VERSION_NUM >= 0x071304
78 static const char *curl_no_proxy;
79 #endif
80 #if LIBCURL_VERSION_NUM >= 0x072c00
81 static const char *ssl_pinnedkey;
82 #endif
83 static const char *ssl_cainfo;
84 static long curl_low_speed_limit = -1;
85 static long curl_low_speed_time = -1;
86 static int curl_ftp_no_epsv;
87 static const char *curl_http_proxy;
88 static const char *http_proxy_authmethod;
90 static const char *http_proxy_ssl_cert;
91 static const char *http_proxy_ssl_key;
92 static const char *http_proxy_ssl_ca_info;
93 static struct credential proxy_cert_auth = CREDENTIAL_INIT;
94 static int proxy_ssl_cert_password_required;
96 static struct {
97 const char *name;
98 long curlauth_param;
99 } proxy_authmethods[] = {
100 { "basic", CURLAUTH_BASIC },
101 { "digest", CURLAUTH_DIGEST },
102 { "negotiate", CURLAUTH_GSSNEGOTIATE },
103 { "ntlm", CURLAUTH_NTLM },
104 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
105 { "anyauth", CURLAUTH_ANY },
106 #endif
108 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
109 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
110 * here, too
113 #ifdef CURLGSSAPI_DELEGATION_FLAG
114 static const char *curl_deleg;
115 static struct {
116 const char *name;
117 long curl_deleg_param;
118 } curl_deleg_levels[] = {
119 { "none", CURLGSSAPI_DELEGATION_NONE },
120 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
121 { "always", CURLGSSAPI_DELEGATION_FLAG },
123 #endif
125 static struct credential proxy_auth = CREDENTIAL_INIT;
126 static const char *curl_proxyuserpwd;
127 static const char *curl_cookie_file;
128 static int curl_save_cookies;
129 struct credential http_auth = CREDENTIAL_INIT;
130 static int http_proactive_auth;
131 static const char *user_agent;
132 static int curl_empty_auth = -1;
134 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
136 #if LIBCURL_VERSION_NUM >= 0x071700
137 /* Use CURLOPT_KEYPASSWD as is */
138 #elif LIBCURL_VERSION_NUM >= 0x070903
139 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
140 #else
141 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
142 #endif
144 static struct credential cert_auth = CREDENTIAL_INIT;
145 static int ssl_cert_password_required;
146 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
147 static unsigned long http_auth_methods = CURLAUTH_ANY;
148 static int http_auth_methods_restricted;
149 /* Modes for which empty_auth cannot actually help us. */
150 static unsigned long empty_auth_useless =
151 CURLAUTH_BASIC
152 #ifdef CURLAUTH_DIGEST_IE
153 | CURLAUTH_DIGEST_IE
154 #endif
155 | CURLAUTH_DIGEST;
156 #endif
158 static struct curl_slist *pragma_header;
159 static struct curl_slist *no_pragma_header;
160 static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
162 static struct active_request_slot *active_queue_head;
164 static char *cached_accept_language;
166 static char *http_ssl_backend;
168 static int http_schannel_check_revoke = 1;
170 * With the backend being set to `schannel`, setting sslCAinfo would override
171 * the Certificate Store in cURL v7.60.0 and later, which is not what we want
172 * by default.
174 static int http_schannel_use_ssl_cainfo;
176 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
178 size_t size = eltsize * nmemb;
179 struct buffer *buffer = buffer_;
181 if (size > buffer->buf.len - buffer->posn)
182 size = buffer->buf.len - buffer->posn;
183 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
184 buffer->posn += size;
186 return size / eltsize;
189 #ifndef NO_CURL_IOCTL
190 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
192 struct buffer *buffer = clientp;
194 switch (cmd) {
195 case CURLIOCMD_NOP:
196 return CURLIOE_OK;
198 case CURLIOCMD_RESTARTREAD:
199 buffer->posn = 0;
200 return CURLIOE_OK;
202 default:
203 return CURLIOE_UNKNOWNCMD;
206 #endif
208 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
210 size_t size = eltsize * nmemb;
211 struct strbuf *buffer = buffer_;
213 strbuf_add(buffer, ptr, size);
214 return nmemb;
217 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
219 return nmemb;
222 static void closedown_active_slot(struct active_request_slot *slot)
224 active_requests--;
225 slot->in_use = 0;
228 static void finish_active_slot(struct active_request_slot *slot)
230 closedown_active_slot(slot);
231 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
233 if (slot->finished != NULL)
234 (*slot->finished) = 1;
236 /* Store slot results so they can be read after the slot is reused */
237 if (slot->results != NULL) {
238 slot->results->curl_result = slot->curl_result;
239 slot->results->http_code = slot->http_code;
240 #if LIBCURL_VERSION_NUM >= 0x070a08
241 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
242 &slot->results->auth_avail);
243 #else
244 slot->results->auth_avail = 0;
245 #endif
247 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
248 &slot->results->http_connectcode);
251 /* Run callback if appropriate */
252 if (slot->callback_func != NULL)
253 slot->callback_func(slot->callback_data);
256 static void xmulti_remove_handle(struct active_request_slot *slot)
258 #ifdef USE_CURL_MULTI
259 curl_multi_remove_handle(curlm, slot->curl);
260 #endif
263 #ifdef USE_CURL_MULTI
264 static void process_curl_messages(void)
266 int num_messages;
267 struct active_request_slot *slot;
268 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
270 while (curl_message != NULL) {
271 if (curl_message->msg == CURLMSG_DONE) {
272 int curl_result = curl_message->data.result;
273 slot = active_queue_head;
274 while (slot != NULL &&
275 slot->curl != curl_message->easy_handle)
276 slot = slot->next;
277 if (slot != NULL) {
278 xmulti_remove_handle(slot);
279 slot->curl_result = curl_result;
280 finish_active_slot(slot);
281 } else {
282 fprintf(stderr, "Received DONE message for unknown request!\n");
284 } else {
285 fprintf(stderr, "Unknown CURL message received: %d\n",
286 (int)curl_message->msg);
288 curl_message = curl_multi_info_read(curlm, &num_messages);
291 #endif
293 static int http_options(const char *var, const char *value, void *cb)
295 if (!strcmp("http.version", var)) {
296 return git_config_string(&curl_http_version, var, value);
298 if (!strcmp("http.sslverify", var)) {
299 curl_ssl_verify = git_config_bool(var, value);
300 return 0;
302 if (!strcmp("http.sslcipherlist", var))
303 return git_config_string(&ssl_cipherlist, var, value);
304 if (!strcmp("http.sslversion", var))
305 return git_config_string(&ssl_version, var, value);
306 if (!strcmp("http.sslcert", var))
307 return git_config_pathname(&ssl_cert, var, value);
308 #if LIBCURL_VERSION_NUM >= 0x070903
309 if (!strcmp("http.sslkey", var))
310 return git_config_pathname(&ssl_key, var, value);
311 #endif
312 #if LIBCURL_VERSION_NUM >= 0x070908
313 if (!strcmp("http.sslcapath", var))
314 return git_config_pathname(&ssl_capath, var, value);
315 #endif
316 if (!strcmp("http.sslcainfo", var))
317 return git_config_pathname(&ssl_cainfo, var, value);
318 if (!strcmp("http.sslcertpasswordprotected", var)) {
319 ssl_cert_password_required = git_config_bool(var, value);
320 return 0;
322 if (!strcmp("http.ssltry", var)) {
323 curl_ssl_try = git_config_bool(var, value);
324 return 0;
326 if (!strcmp("http.sslbackend", var)) {
327 free(http_ssl_backend);
328 http_ssl_backend = xstrdup_or_null(value);
329 return 0;
332 if (!strcmp("http.schannelcheckrevoke", var)) {
333 http_schannel_check_revoke = git_config_bool(var, value);
334 return 0;
337 if (!strcmp("http.schannelusesslcainfo", var)) {
338 http_schannel_use_ssl_cainfo = git_config_bool(var, value);
339 return 0;
342 if (!strcmp("http.minsessions", var)) {
343 min_curl_sessions = git_config_int(var, value);
344 #ifndef USE_CURL_MULTI
345 if (min_curl_sessions > 1)
346 min_curl_sessions = 1;
347 #endif
348 return 0;
350 #ifdef USE_CURL_MULTI
351 if (!strcmp("http.maxrequests", var)) {
352 max_requests = git_config_int(var, value);
353 return 0;
355 #endif
356 if (!strcmp("http.lowspeedlimit", var)) {
357 curl_low_speed_limit = (long)git_config_int(var, value);
358 return 0;
360 if (!strcmp("http.lowspeedtime", var)) {
361 curl_low_speed_time = (long)git_config_int(var, value);
362 return 0;
365 if (!strcmp("http.noepsv", var)) {
366 curl_ftp_no_epsv = git_config_bool(var, value);
367 return 0;
369 if (!strcmp("http.proxy", var))
370 return git_config_string(&curl_http_proxy, var, value);
372 if (!strcmp("http.proxyauthmethod", var))
373 return git_config_string(&http_proxy_authmethod, var, value);
375 if (!strcmp("http.proxysslcert", var))
376 return git_config_string(&http_proxy_ssl_cert, var, value);
378 if (!strcmp("http.proxysslkey", var))
379 return git_config_string(&http_proxy_ssl_key, var, value);
381 if (!strcmp("http.proxysslcainfo", var))
382 return git_config_string(&http_proxy_ssl_ca_info, var, value);
384 if (!strcmp("http.proxysslcertpasswordprotected", var)) {
385 proxy_ssl_cert_password_required = git_config_bool(var, value);
386 return 0;
389 if (!strcmp("http.cookiefile", var))
390 return git_config_pathname(&curl_cookie_file, var, value);
391 if (!strcmp("http.savecookies", var)) {
392 curl_save_cookies = git_config_bool(var, value);
393 return 0;
396 if (!strcmp("http.postbuffer", var)) {
397 http_post_buffer = git_config_ssize_t(var, value);
398 if (http_post_buffer < 0)
399 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
400 if (http_post_buffer < LARGE_PACKET_MAX)
401 http_post_buffer = LARGE_PACKET_MAX;
402 return 0;
405 if (!strcmp("http.useragent", var))
406 return git_config_string(&user_agent, var, value);
408 if (!strcmp("http.emptyauth", var)) {
409 if (value && !strcmp("auto", value))
410 curl_empty_auth = -1;
411 else
412 curl_empty_auth = git_config_bool(var, value);
413 return 0;
416 if (!strcmp("http.delegation", var)) {
417 #ifdef CURLGSSAPI_DELEGATION_FLAG
418 return git_config_string(&curl_deleg, var, value);
419 #else
420 warning(_("Delegation control is not supported with cURL < 7.22.0"));
421 return 0;
422 #endif
425 if (!strcmp("http.pinnedpubkey", var)) {
426 #if LIBCURL_VERSION_NUM >= 0x072c00
427 return git_config_pathname(&ssl_pinnedkey, var, value);
428 #else
429 warning(_("Public key pinning not supported with cURL < 7.44.0"));
430 return 0;
431 #endif
434 if (!strcmp("http.extraheader", var)) {
435 if (!value) {
436 return config_error_nonbool(var);
437 } else if (!*value) {
438 string_list_clear(&extra_http_headers, 0);
439 } else {
440 string_list_append(&extra_http_headers, value);
442 return 0;
445 if (!strcmp("http.followredirects", var)) {
446 if (value && !strcmp(value, "initial"))
447 http_follow_config = HTTP_FOLLOW_INITIAL;
448 else if (git_config_bool(var, value))
449 http_follow_config = HTTP_FOLLOW_ALWAYS;
450 else
451 http_follow_config = HTTP_FOLLOW_NONE;
452 return 0;
455 /* Fall back on the default ones */
456 return git_default_config(var, value, cb);
459 static int curl_empty_auth_enabled(void)
461 if (curl_empty_auth >= 0)
462 return curl_empty_auth;
464 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
466 * Our libcurl is too old to do AUTH_ANY in the first place;
467 * just default to turning the feature off.
469 #else
471 * In the automatic case, kick in the empty-auth
472 * hack as long as we would potentially try some
473 * method more exotic than "Basic" or "Digest".
475 * But only do this when this is our second or
476 * subsequent request, as by then we know what
477 * methods are available.
479 if (http_auth_methods_restricted &&
480 (http_auth_methods & ~empty_auth_useless))
481 return 1;
482 #endif
483 return 0;
486 static void init_curl_http_auth(CURL *result)
488 if (!http_auth.username || !*http_auth.username) {
489 if (curl_empty_auth_enabled())
490 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
491 return;
494 credential_fill(&http_auth);
496 #if LIBCURL_VERSION_NUM >= 0x071301
497 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
498 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
499 #else
501 static struct strbuf up = STRBUF_INIT;
503 * Note that we assume we only ever have a single set of
504 * credentials in a given program run, so we do not have
505 * to worry about updating this buffer, only setting its
506 * initial value.
508 if (!up.len)
509 strbuf_addf(&up, "%s:%s",
510 http_auth.username, http_auth.password);
511 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
513 #endif
516 /* *var must be free-able */
517 static void var_override(const char **var, char *value)
519 if (value) {
520 free((void *)*var);
521 *var = xstrdup(value);
525 static void set_proxyauth_name_password(CURL *result)
527 #if LIBCURL_VERSION_NUM >= 0x071301
528 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
529 proxy_auth.username);
530 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
531 proxy_auth.password);
532 #else
533 struct strbuf s = STRBUF_INIT;
535 strbuf_addstr_urlencode(&s, proxy_auth.username,
536 is_rfc3986_unreserved);
537 strbuf_addch(&s, ':');
538 strbuf_addstr_urlencode(&s, proxy_auth.password,
539 is_rfc3986_unreserved);
540 curl_proxyuserpwd = strbuf_detach(&s, NULL);
541 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
542 #endif
545 static void init_curl_proxy_auth(CURL *result)
547 if (proxy_auth.username) {
548 if (!proxy_auth.password)
549 credential_fill(&proxy_auth);
550 set_proxyauth_name_password(result);
553 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
555 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
556 if (http_proxy_authmethod) {
557 int i;
558 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
559 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
560 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
561 proxy_authmethods[i].curlauth_param);
562 break;
565 if (i == ARRAY_SIZE(proxy_authmethods)) {
566 warning("unsupported proxy authentication method %s: using anyauth",
567 http_proxy_authmethod);
568 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
571 else
572 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
573 #endif
576 static int has_cert_password(void)
578 if (ssl_cert == NULL || ssl_cert_password_required != 1)
579 return 0;
580 if (!cert_auth.password) {
581 cert_auth.protocol = xstrdup("cert");
582 cert_auth.host = xstrdup("");
583 cert_auth.username = xstrdup("");
584 cert_auth.path = xstrdup(ssl_cert);
585 credential_fill(&cert_auth);
587 return 1;
590 #if LIBCURL_VERSION_NUM >= 0x073400
591 static int has_proxy_cert_password(void)
593 if (http_proxy_ssl_cert == NULL || proxy_ssl_cert_password_required != 1)
594 return 0;
595 if (!proxy_cert_auth.password) {
596 proxy_cert_auth.protocol = xstrdup("cert");
597 proxy_cert_auth.host = xstrdup("");
598 proxy_cert_auth.username = xstrdup("");
599 proxy_cert_auth.path = xstrdup(http_proxy_ssl_cert);
600 credential_fill(&proxy_cert_auth);
602 return 1;
604 #endif
606 #if LIBCURL_VERSION_NUM >= 0x071900
607 static void set_curl_keepalive(CURL *c)
609 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
612 #elif LIBCURL_VERSION_NUM >= 0x071000
613 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
615 int ka = 1;
616 int rc;
617 socklen_t len = (socklen_t)sizeof(ka);
619 if (type != CURLSOCKTYPE_IPCXN)
620 return 0;
622 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
623 if (rc < 0)
624 warning_errno("unable to set SO_KEEPALIVE on socket");
626 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
629 static void set_curl_keepalive(CURL *c)
631 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
634 #else
635 static void set_curl_keepalive(CURL *c)
637 /* not supported on older curl versions */
639 #endif
641 static void redact_sensitive_header(struct strbuf *header)
643 const char *sensitive_header;
645 if (trace_curl_redact &&
646 (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
647 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header))) {
648 /* The first token is the type, which is OK to log */
649 while (isspace(*sensitive_header))
650 sensitive_header++;
651 while (*sensitive_header && !isspace(*sensitive_header))
652 sensitive_header++;
653 /* Everything else is opaque and possibly sensitive */
654 strbuf_setlen(header, sensitive_header - header->buf);
655 strbuf_addstr(header, " <redacted>");
656 } else if (trace_curl_redact &&
657 skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
658 struct strbuf redacted_header = STRBUF_INIT;
659 const char *cookie;
661 while (isspace(*sensitive_header))
662 sensitive_header++;
664 cookie = sensitive_header;
666 while (cookie) {
667 char *equals;
668 char *semicolon = strstr(cookie, "; ");
669 if (semicolon)
670 *semicolon = 0;
671 equals = strchrnul(cookie, '=');
672 if (!equals) {
673 /* invalid cookie, just append and continue */
674 strbuf_addstr(&redacted_header, cookie);
675 continue;
677 strbuf_add(&redacted_header, cookie, equals - cookie);
678 strbuf_addstr(&redacted_header, "=<redacted>");
679 if (semicolon) {
681 * There are more cookies. (Or, for some
682 * reason, the input string ends in "; ".)
684 strbuf_addstr(&redacted_header, "; ");
685 cookie = semicolon + strlen("; ");
686 } else {
687 cookie = NULL;
691 strbuf_setlen(header, sensitive_header - header->buf);
692 strbuf_addbuf(header, &redacted_header);
696 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
698 struct strbuf out = STRBUF_INIT;
699 struct strbuf **headers, **header;
701 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
702 text, (long)size, (long)size);
703 trace_strbuf(&trace_curl, &out);
704 strbuf_reset(&out);
705 strbuf_add(&out, ptr, size);
706 headers = strbuf_split_max(&out, '\n', 0);
708 for (header = headers; *header; header++) {
709 if (hide_sensitive_header)
710 redact_sensitive_header(*header);
711 strbuf_insertstr((*header), 0, text);
712 strbuf_insertstr((*header), strlen(text), ": ");
713 strbuf_rtrim((*header));
714 strbuf_addch((*header), '\n');
715 trace_strbuf(&trace_curl, (*header));
717 strbuf_list_free(headers);
718 strbuf_release(&out);
721 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
723 size_t i;
724 struct strbuf out = STRBUF_INIT;
725 unsigned int width = 60;
727 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
728 text, (long)size, (long)size);
729 trace_strbuf(&trace_curl, &out);
731 for (i = 0; i < size; i += width) {
732 size_t w;
734 strbuf_reset(&out);
735 strbuf_addf(&out, "%s: ", text);
736 for (w = 0; (w < width) && (i + w < size); w++) {
737 unsigned char ch = ptr[i + w];
739 strbuf_addch(&out,
740 (ch >= 0x20) && (ch < 0x80)
741 ? ch : '.');
743 strbuf_addch(&out, '\n');
744 trace_strbuf(&trace_curl, &out);
746 strbuf_release(&out);
749 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
751 const char *text;
752 enum { NO_FILTER = 0, DO_FILTER = 1 };
754 switch (type) {
755 case CURLINFO_TEXT:
756 trace_printf_key(&trace_curl, "== Info: %s", data);
757 break;
758 case CURLINFO_HEADER_OUT:
759 text = "=> Send header";
760 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
761 break;
762 case CURLINFO_DATA_OUT:
763 if (trace_curl_data) {
764 text = "=> Send data";
765 curl_dump_data(text, (unsigned char *)data, size);
767 break;
768 case CURLINFO_SSL_DATA_OUT:
769 if (trace_curl_data) {
770 text = "=> Send SSL data";
771 curl_dump_data(text, (unsigned char *)data, size);
773 break;
774 case CURLINFO_HEADER_IN:
775 text = "<= Recv header";
776 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
777 break;
778 case CURLINFO_DATA_IN:
779 if (trace_curl_data) {
780 text = "<= Recv data";
781 curl_dump_data(text, (unsigned char *)data, size);
783 break;
784 case CURLINFO_SSL_DATA_IN:
785 if (trace_curl_data) {
786 text = "<= Recv SSL data";
787 curl_dump_data(text, (unsigned char *)data, size);
789 break;
791 default: /* we ignore unknown types by default */
792 return 0;
794 return 0;
797 void http_trace_curl_no_data(void)
799 trace_override_envvar(&trace_curl, "1");
800 trace_curl_data = 0;
803 void setup_curl_trace(CURL *handle)
805 if (!trace_want(&trace_curl))
806 return;
807 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
808 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
809 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
812 #ifdef CURLPROTO_HTTP
813 static long get_curl_allowed_protocols(int from_user)
815 long allowed_protocols = 0;
817 if (is_transport_allowed("http", from_user))
818 allowed_protocols |= CURLPROTO_HTTP;
819 if (is_transport_allowed("https", from_user))
820 allowed_protocols |= CURLPROTO_HTTPS;
821 if (is_transport_allowed("ftp", from_user))
822 allowed_protocols |= CURLPROTO_FTP;
823 if (is_transport_allowed("ftps", from_user))
824 allowed_protocols |= CURLPROTO_FTPS;
826 return allowed_protocols;
828 #endif
830 #if LIBCURL_VERSION_NUM >=0x072f00
831 static int get_curl_http_version_opt(const char *version_string, long *opt)
833 int i;
834 static struct {
835 const char *name;
836 long opt_token;
837 } choice[] = {
838 { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
839 { "HTTP/2", CURL_HTTP_VERSION_2 }
842 for (i = 0; i < ARRAY_SIZE(choice); i++) {
843 if (!strcmp(version_string, choice[i].name)) {
844 *opt = choice[i].opt_token;
845 return 0;
849 warning("unknown value given to http.version: '%s'", version_string);
850 return -1; /* not found */
853 #endif
855 static CURL *get_curl_handle(void)
857 CURL *result = curl_easy_init();
859 if (!result)
860 die("curl_easy_init failed");
862 if (!curl_ssl_verify) {
863 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
864 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
865 } else {
866 /* Verify authenticity of the peer's certificate */
867 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
868 /* The name in the cert must match whom we tried to connect */
869 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
872 #if LIBCURL_VERSION_NUM >= 0x072f00 // 7.47.0
873 if (curl_http_version) {
874 long opt;
875 if (!get_curl_http_version_opt(curl_http_version, &opt)) {
876 /* Set request use http version */
877 curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
880 #endif
882 #if LIBCURL_VERSION_NUM >= 0x070907
883 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
884 #endif
885 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
886 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
887 #endif
889 #ifdef CURLGSSAPI_DELEGATION_FLAG
890 if (curl_deleg) {
891 int i;
892 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
893 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
894 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
895 curl_deleg_levels[i].curl_deleg_param);
896 break;
899 if (i == ARRAY_SIZE(curl_deleg_levels))
900 warning("Unknown delegation method '%s': using default",
901 curl_deleg);
903 #endif
905 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
906 !http_schannel_check_revoke) {
907 #if LIBCURL_VERSION_NUM >= 0x072c00
908 curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
909 #else
910 warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
911 #endif
914 if (http_proactive_auth)
915 init_curl_http_auth(result);
917 if (getenv("GIT_SSL_VERSION"))
918 ssl_version = getenv("GIT_SSL_VERSION");
919 if (ssl_version && *ssl_version) {
920 int i;
921 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
922 if (!strcmp(ssl_version, sslversions[i].name)) {
923 curl_easy_setopt(result, CURLOPT_SSLVERSION,
924 sslversions[i].ssl_version);
925 break;
928 if (i == ARRAY_SIZE(sslversions))
929 warning("unsupported ssl version %s: using default",
930 ssl_version);
933 if (getenv("GIT_SSL_CIPHER_LIST"))
934 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
935 if (ssl_cipherlist != NULL && *ssl_cipherlist)
936 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
937 ssl_cipherlist);
939 if (ssl_cert != NULL)
940 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
941 if (has_cert_password())
942 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
943 #if LIBCURL_VERSION_NUM >= 0x070903
944 if (ssl_key != NULL)
945 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
946 #endif
947 #if LIBCURL_VERSION_NUM >= 0x070908
948 if (ssl_capath != NULL)
949 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
950 #endif
951 #if LIBCURL_VERSION_NUM >= 0x072c00
952 if (ssl_pinnedkey != NULL)
953 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
954 #endif
955 if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
956 !http_schannel_use_ssl_cainfo) {
957 curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
958 #if LIBCURL_VERSION_NUM >= 0x073400
959 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
960 #endif
961 } else if (ssl_cainfo != NULL || http_proxy_ssl_ca_info != NULL) {
962 if (ssl_cainfo != NULL)
963 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
964 #if LIBCURL_VERSION_NUM >= 0x073400
965 if (http_proxy_ssl_ca_info != NULL)
966 curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, http_proxy_ssl_ca_info);
967 #endif
970 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
971 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
972 curl_low_speed_limit);
973 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
974 curl_low_speed_time);
977 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
978 #if LIBCURL_VERSION_NUM >= 0x071301
979 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
980 #elif LIBCURL_VERSION_NUM >= 0x071101
981 curl_easy_setopt(result, CURLOPT_POST301, 1);
982 #endif
983 #ifdef CURLPROTO_HTTP
984 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
985 get_curl_allowed_protocols(0));
986 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
987 get_curl_allowed_protocols(-1));
988 #else
989 warning(_("Protocol restrictions not supported with cURL < 7.19.4"));
990 #endif
991 if (getenv("GIT_CURL_VERBOSE"))
992 http_trace_curl_no_data();
993 setup_curl_trace(result);
994 if (getenv("GIT_TRACE_CURL_NO_DATA"))
995 trace_curl_data = 0;
996 if (!git_env_bool("GIT_TRACE_REDACT", 1))
997 trace_curl_redact = 0;
999 curl_easy_setopt(result, CURLOPT_USERAGENT,
1000 user_agent ? user_agent : git_user_agent());
1002 if (curl_ftp_no_epsv)
1003 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
1005 #ifdef CURLOPT_USE_SSL
1006 if (curl_ssl_try)
1007 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
1008 #endif
1011 * CURL also examines these variables as a fallback; but we need to query
1012 * them here in order to decide whether to prompt for missing password (cf.
1013 * init_curl_proxy_auth()).
1015 * Unlike many other common environment variables, these are historically
1016 * lowercase only. It appears that CURL did not know this and implemented
1017 * only uppercase variants, which was later corrected to take both - with
1018 * the exception of http_proxy, which is lowercase only also in CURL. As
1019 * the lowercase versions are the historical quasi-standard, they take
1020 * precedence here, as in CURL.
1022 if (!curl_http_proxy) {
1023 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
1024 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
1025 var_override(&curl_http_proxy, getenv("https_proxy"));
1026 } else {
1027 var_override(&curl_http_proxy, getenv("http_proxy"));
1029 if (!curl_http_proxy) {
1030 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
1031 var_override(&curl_http_proxy, getenv("all_proxy"));
1035 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
1037 * Handle case with the empty http.proxy value here to keep
1038 * common code clean.
1039 * NB: empty option disables proxying at all.
1041 curl_easy_setopt(result, CURLOPT_PROXY, "");
1042 } else if (curl_http_proxy) {
1043 #if LIBCURL_VERSION_NUM >= 0x071800
1044 if (starts_with(curl_http_proxy, "socks5h"))
1045 curl_easy_setopt(result,
1046 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
1047 else if (starts_with(curl_http_proxy, "socks5"))
1048 curl_easy_setopt(result,
1049 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
1050 else if (starts_with(curl_http_proxy, "socks4a"))
1051 curl_easy_setopt(result,
1052 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
1053 else if (starts_with(curl_http_proxy, "socks"))
1054 curl_easy_setopt(result,
1055 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
1056 #endif
1057 #if LIBCURL_VERSION_NUM >= 0x073400
1058 else if (starts_with(curl_http_proxy, "https")) {
1059 curl_easy_setopt(result, CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
1061 if (http_proxy_ssl_cert)
1062 curl_easy_setopt(result, CURLOPT_PROXY_SSLCERT, http_proxy_ssl_cert);
1064 if (http_proxy_ssl_key)
1065 curl_easy_setopt(result, CURLOPT_PROXY_SSLKEY, http_proxy_ssl_key);
1067 if (has_proxy_cert_password())
1068 curl_easy_setopt(result, CURLOPT_PROXY_KEYPASSWD, proxy_cert_auth.password);
1070 #endif
1071 if (strstr(curl_http_proxy, "://"))
1072 credential_from_url(&proxy_auth, curl_http_proxy);
1073 else {
1074 struct strbuf url = STRBUF_INIT;
1075 strbuf_addf(&url, "http://%s", curl_http_proxy);
1076 credential_from_url(&proxy_auth, url.buf);
1077 strbuf_release(&url);
1080 if (!proxy_auth.host)
1081 die("Invalid proxy URL '%s'", curl_http_proxy);
1083 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
1084 #if LIBCURL_VERSION_NUM >= 0x071304
1085 var_override(&curl_no_proxy, getenv("NO_PROXY"));
1086 var_override(&curl_no_proxy, getenv("no_proxy"));
1087 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
1088 #endif
1090 init_curl_proxy_auth(result);
1092 set_curl_keepalive(result);
1094 return result;
1097 static void set_from_env(const char **var, const char *envname)
1099 const char *val = getenv(envname);
1100 if (val)
1101 *var = val;
1104 void http_init(struct remote *remote, const char *url, int proactive_auth)
1106 char *low_speed_limit;
1107 char *low_speed_time;
1108 char *normalized_url;
1109 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
1111 config.section = "http";
1112 config.key = NULL;
1113 config.collect_fn = http_options;
1114 config.cascade_fn = git_default_config;
1115 config.cb = NULL;
1117 http_is_verbose = 0;
1118 normalized_url = url_normalize(url, &config.url);
1120 git_config(urlmatch_config_entry, &config);
1121 free(normalized_url);
1122 string_list_clear(&config.vars, 1);
1124 #if LIBCURL_VERSION_NUM >= 0x073800
1125 if (http_ssl_backend) {
1126 const curl_ssl_backend **backends;
1127 struct strbuf buf = STRBUF_INIT;
1128 int i;
1130 switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
1131 case CURLSSLSET_UNKNOWN_BACKEND:
1132 strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
1133 "Supported SSL backends:"),
1134 http_ssl_backend);
1135 for (i = 0; backends[i]; i++)
1136 strbuf_addf(&buf, "\n\t%s", backends[i]->name);
1137 die("%s", buf.buf);
1138 case CURLSSLSET_NO_BACKENDS:
1139 die(_("Could not set SSL backend to '%s': "
1140 "cURL was built without SSL backends"),
1141 http_ssl_backend);
1142 case CURLSSLSET_TOO_LATE:
1143 die(_("Could not set SSL backend to '%s': already set"),
1144 http_ssl_backend);
1145 case CURLSSLSET_OK:
1146 break; /* Okay! */
1149 #endif
1151 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
1152 die("curl_global_init failed");
1154 http_proactive_auth = proactive_auth;
1156 if (remote && remote->http_proxy)
1157 curl_http_proxy = xstrdup(remote->http_proxy);
1159 if (remote)
1160 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1162 pragma_header = curl_slist_append(http_copy_default_headers(),
1163 "Pragma: no-cache");
1164 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1165 "Pragma:");
1167 #ifdef USE_CURL_MULTI
1169 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1170 if (http_max_requests != NULL)
1171 max_requests = atoi(http_max_requests);
1174 curlm = curl_multi_init();
1175 if (!curlm)
1176 die("curl_multi_init failed");
1177 #endif
1179 if (getenv("GIT_SSL_NO_VERIFY"))
1180 curl_ssl_verify = 0;
1182 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1183 #if LIBCURL_VERSION_NUM >= 0x070903
1184 set_from_env(&ssl_key, "GIT_SSL_KEY");
1185 #endif
1186 #if LIBCURL_VERSION_NUM >= 0x070908
1187 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1188 #endif
1189 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1191 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1193 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1194 if (low_speed_limit != NULL)
1195 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1196 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1197 if (low_speed_time != NULL)
1198 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1200 if (curl_ssl_verify == -1)
1201 curl_ssl_verify = 1;
1203 curl_session_count = 0;
1204 #ifdef USE_CURL_MULTI
1205 if (max_requests < 1)
1206 max_requests = DEFAULT_MAX_REQUESTS;
1207 #endif
1209 set_from_env(&http_proxy_ssl_cert, "GIT_PROXY_SSL_CERT");
1210 set_from_env(&http_proxy_ssl_key, "GIT_PROXY_SSL_KEY");
1211 set_from_env(&http_proxy_ssl_ca_info, "GIT_PROXY_SSL_CAINFO");
1213 if (getenv("GIT_PROXY_SSL_CERT_PASSWORD_PROTECTED"))
1214 proxy_ssl_cert_password_required = 1;
1216 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1217 curl_ftp_no_epsv = 1;
1219 if (url) {
1220 credential_from_url(&http_auth, url);
1221 if (!ssl_cert_password_required &&
1222 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1223 starts_with(url, "https://"))
1224 ssl_cert_password_required = 1;
1227 #ifndef NO_CURL_EASY_DUPHANDLE
1228 curl_default = get_curl_handle();
1229 #endif
1232 void http_cleanup(void)
1234 struct active_request_slot *slot = active_queue_head;
1236 while (slot != NULL) {
1237 struct active_request_slot *next = slot->next;
1238 if (slot->curl != NULL) {
1239 xmulti_remove_handle(slot);
1240 curl_easy_cleanup(slot->curl);
1242 free(slot);
1243 slot = next;
1245 active_queue_head = NULL;
1247 #ifndef NO_CURL_EASY_DUPHANDLE
1248 curl_easy_cleanup(curl_default);
1249 #endif
1251 #ifdef USE_CURL_MULTI
1252 curl_multi_cleanup(curlm);
1253 #endif
1254 curl_global_cleanup();
1256 string_list_clear(&extra_http_headers, 0);
1258 curl_slist_free_all(pragma_header);
1259 pragma_header = NULL;
1261 curl_slist_free_all(no_pragma_header);
1262 no_pragma_header = NULL;
1264 if (curl_http_proxy) {
1265 free((void *)curl_http_proxy);
1266 curl_http_proxy = NULL;
1269 if (proxy_auth.password) {
1270 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1271 FREE_AND_NULL(proxy_auth.password);
1274 free((void *)curl_proxyuserpwd);
1275 curl_proxyuserpwd = NULL;
1277 free((void *)http_proxy_authmethod);
1278 http_proxy_authmethod = NULL;
1280 if (cert_auth.password != NULL) {
1281 memset(cert_auth.password, 0, strlen(cert_auth.password));
1282 FREE_AND_NULL(cert_auth.password);
1284 ssl_cert_password_required = 0;
1286 if (proxy_cert_auth.password != NULL) {
1287 memset(proxy_cert_auth.password, 0, strlen(proxy_cert_auth.password));
1288 FREE_AND_NULL(proxy_cert_auth.password);
1290 proxy_ssl_cert_password_required = 0;
1292 FREE_AND_NULL(cached_accept_language);
1295 struct active_request_slot *get_active_slot(void)
1297 struct active_request_slot *slot = active_queue_head;
1298 struct active_request_slot *newslot;
1300 #ifdef USE_CURL_MULTI
1301 int num_transfers;
1303 /* Wait for a slot to open up if the queue is full */
1304 while (active_requests >= max_requests) {
1305 curl_multi_perform(curlm, &num_transfers);
1306 if (num_transfers < active_requests)
1307 process_curl_messages();
1309 #endif
1311 while (slot != NULL && slot->in_use)
1312 slot = slot->next;
1314 if (slot == NULL) {
1315 newslot = xmalloc(sizeof(*newslot));
1316 newslot->curl = NULL;
1317 newslot->in_use = 0;
1318 newslot->next = NULL;
1320 slot = active_queue_head;
1321 if (slot == NULL) {
1322 active_queue_head = newslot;
1323 } else {
1324 while (slot->next != NULL)
1325 slot = slot->next;
1326 slot->next = newslot;
1328 slot = newslot;
1331 if (slot->curl == NULL) {
1332 #ifdef NO_CURL_EASY_DUPHANDLE
1333 slot->curl = get_curl_handle();
1334 #else
1335 slot->curl = curl_easy_duphandle(curl_default);
1336 #endif
1337 curl_session_count++;
1340 active_requests++;
1341 slot->in_use = 1;
1342 slot->results = NULL;
1343 slot->finished = NULL;
1344 slot->callback_data = NULL;
1345 slot->callback_func = NULL;
1346 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1347 if (curl_save_cookies)
1348 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1349 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1350 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1351 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1352 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1353 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1354 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1355 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1356 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1357 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1358 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1361 * Default following to off unless "ALWAYS" is configured; this gives
1362 * callers a sane starting point, and they can tweak for individual
1363 * HTTP_FOLLOW_* cases themselves.
1365 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1366 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1367 else
1368 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1370 #if LIBCURL_VERSION_NUM >= 0x070a08
1371 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1372 #endif
1373 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1374 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1375 #endif
1376 if (http_auth.password || curl_empty_auth_enabled())
1377 init_curl_http_auth(slot->curl);
1379 return slot;
1382 int start_active_slot(struct active_request_slot *slot)
1384 #ifdef USE_CURL_MULTI
1385 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1386 int num_transfers;
1388 if (curlm_result != CURLM_OK &&
1389 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1390 warning("curl_multi_add_handle failed: %s",
1391 curl_multi_strerror(curlm_result));
1392 active_requests--;
1393 slot->in_use = 0;
1394 return 0;
1398 * We know there must be something to do, since we just added
1399 * something.
1401 curl_multi_perform(curlm, &num_transfers);
1402 #endif
1403 return 1;
1406 #ifdef USE_CURL_MULTI
1407 struct fill_chain {
1408 void *data;
1409 int (*fill)(void *);
1410 struct fill_chain *next;
1413 static struct fill_chain *fill_cfg;
1415 void add_fill_function(void *data, int (*fill)(void *))
1417 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1418 struct fill_chain **linkp = &fill_cfg;
1419 new_fill->data = data;
1420 new_fill->fill = fill;
1421 new_fill->next = NULL;
1422 while (*linkp)
1423 linkp = &(*linkp)->next;
1424 *linkp = new_fill;
1427 void fill_active_slots(void)
1429 struct active_request_slot *slot = active_queue_head;
1431 while (active_requests < max_requests) {
1432 struct fill_chain *fill;
1433 for (fill = fill_cfg; fill; fill = fill->next)
1434 if (fill->fill(fill->data))
1435 break;
1437 if (!fill)
1438 break;
1441 while (slot != NULL) {
1442 if (!slot->in_use && slot->curl != NULL
1443 && curl_session_count > min_curl_sessions) {
1444 curl_easy_cleanup(slot->curl);
1445 slot->curl = NULL;
1446 curl_session_count--;
1448 slot = slot->next;
1452 void step_active_slots(void)
1454 int num_transfers;
1455 CURLMcode curlm_result;
1457 do {
1458 curlm_result = curl_multi_perform(curlm, &num_transfers);
1459 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1460 if (num_transfers < active_requests) {
1461 process_curl_messages();
1462 fill_active_slots();
1465 #endif
1467 void run_active_slot(struct active_request_slot *slot)
1469 #ifdef USE_CURL_MULTI
1470 fd_set readfds;
1471 fd_set writefds;
1472 fd_set excfds;
1473 int max_fd;
1474 struct timeval select_timeout;
1475 int finished = 0;
1477 slot->finished = &finished;
1478 while (!finished) {
1479 step_active_slots();
1481 if (slot->in_use) {
1482 #if LIBCURL_VERSION_NUM >= 0x070f04
1483 long curl_timeout;
1484 curl_multi_timeout(curlm, &curl_timeout);
1485 if (curl_timeout == 0) {
1486 continue;
1487 } else if (curl_timeout == -1) {
1488 select_timeout.tv_sec = 0;
1489 select_timeout.tv_usec = 50000;
1490 } else {
1491 select_timeout.tv_sec = curl_timeout / 1000;
1492 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1494 #else
1495 select_timeout.tv_sec = 0;
1496 select_timeout.tv_usec = 50000;
1497 #endif
1499 max_fd = -1;
1500 FD_ZERO(&readfds);
1501 FD_ZERO(&writefds);
1502 FD_ZERO(&excfds);
1503 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1506 * It can happen that curl_multi_timeout returns a pathologically
1507 * long timeout when curl_multi_fdset returns no file descriptors
1508 * to read. See commit message for more details.
1510 if (max_fd < 0 &&
1511 (select_timeout.tv_sec > 0 ||
1512 select_timeout.tv_usec > 50000)) {
1513 select_timeout.tv_sec = 0;
1514 select_timeout.tv_usec = 50000;
1517 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1520 #else
1521 while (slot->in_use) {
1522 slot->curl_result = curl_easy_perform(slot->curl);
1523 finish_active_slot(slot);
1525 #endif
1528 static void release_active_slot(struct active_request_slot *slot)
1530 closedown_active_slot(slot);
1531 if (slot->curl) {
1532 xmulti_remove_handle(slot);
1533 if (curl_session_count > min_curl_sessions) {
1534 curl_easy_cleanup(slot->curl);
1535 slot->curl = NULL;
1536 curl_session_count--;
1539 #ifdef USE_CURL_MULTI
1540 fill_active_slots();
1541 #endif
1544 void finish_all_active_slots(void)
1546 struct active_request_slot *slot = active_queue_head;
1548 while (slot != NULL)
1549 if (slot->in_use) {
1550 run_active_slot(slot);
1551 slot = active_queue_head;
1552 } else {
1553 slot = slot->next;
1557 /* Helpers for modifying and creating URLs */
1558 static inline int needs_quote(int ch)
1560 if (((ch >= 'A') && (ch <= 'Z'))
1561 || ((ch >= 'a') && (ch <= 'z'))
1562 || ((ch >= '0') && (ch <= '9'))
1563 || (ch == '/')
1564 || (ch == '-')
1565 || (ch == '.'))
1566 return 0;
1567 return 1;
1570 static char *quote_ref_url(const char *base, const char *ref)
1572 struct strbuf buf = STRBUF_INIT;
1573 const char *cp;
1574 int ch;
1576 end_url_with_slash(&buf, base);
1578 for (cp = ref; (ch = *cp) != 0; cp++)
1579 if (needs_quote(ch))
1580 strbuf_addf(&buf, "%%%02x", ch);
1581 else
1582 strbuf_addch(&buf, *cp);
1584 return strbuf_detach(&buf, NULL);
1587 void append_remote_object_url(struct strbuf *buf, const char *url,
1588 const char *hex,
1589 int only_two_digit_prefix)
1591 end_url_with_slash(buf, url);
1593 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1594 if (!only_two_digit_prefix)
1595 strbuf_addstr(buf, hex + 2);
1598 char *get_remote_object_url(const char *url, const char *hex,
1599 int only_two_digit_prefix)
1601 struct strbuf buf = STRBUF_INIT;
1602 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1603 return strbuf_detach(&buf, NULL);
1606 void normalize_curl_result(CURLcode *result, long http_code,
1607 char *errorstr, size_t errorlen)
1610 * If we see a failing http code with CURLE_OK, we have turned off
1611 * FAILONERROR (to keep the server's custom error response), and should
1612 * translate the code into failure here.
1614 * Likewise, if we see a redirect (30x code), that means we turned off
1615 * redirect-following, and we should treat the result as an error.
1617 if (*result == CURLE_OK && http_code >= 300) {
1618 *result = CURLE_HTTP_RETURNED_ERROR;
1620 * Normally curl will already have put the "reason phrase"
1621 * from the server into curl_errorstr; unfortunately without
1622 * FAILONERROR it is lost, so we can give only the numeric
1623 * status code.
1625 xsnprintf(errorstr, errorlen,
1626 "The requested URL returned error: %ld",
1627 http_code);
1631 static int handle_curl_result(struct slot_results *results)
1633 normalize_curl_result(&results->curl_result, results->http_code,
1634 curl_errorstr, sizeof(curl_errorstr));
1636 if (results->curl_result == CURLE_OK) {
1637 credential_approve(&http_auth);
1638 credential_approve(&proxy_auth);
1639 credential_approve(&cert_auth);
1640 return HTTP_OK;
1641 } else if (results->curl_result == CURLE_SSL_CERTPROBLEM) {
1643 * We can't tell from here whether it's a bad path, bad
1644 * certificate, bad password, or something else wrong
1645 * with the certificate. So we reject the credential to
1646 * avoid caching or saving a bad password.
1648 credential_reject(&cert_auth);
1649 return HTTP_NOAUTH;
1650 } else if (missing_target(results))
1651 return HTTP_MISSING_TARGET;
1652 else if (results->http_code == 401) {
1653 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1654 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1655 if (results->auth_avail) {
1656 http_auth_methods &= results->auth_avail;
1657 http_auth_methods_restricted = 1;
1658 return HTTP_REAUTH;
1660 #endif
1661 if (http_auth.username && http_auth.password) {
1662 credential_reject(&http_auth);
1663 return HTTP_NOAUTH;
1664 } else {
1665 return HTTP_REAUTH;
1667 } else {
1668 if (results->http_connectcode == 407)
1669 credential_reject(&proxy_auth);
1670 #if LIBCURL_VERSION_NUM >= 0x070c00
1671 if (!curl_errorstr[0])
1672 strlcpy(curl_errorstr,
1673 curl_easy_strerror(results->curl_result),
1674 sizeof(curl_errorstr));
1675 #endif
1676 return HTTP_ERROR;
1680 int run_one_slot(struct active_request_slot *slot,
1681 struct slot_results *results)
1683 slot->results = results;
1684 if (!start_active_slot(slot)) {
1685 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1686 "failed to start HTTP request");
1687 return HTTP_START_FAILED;
1690 run_active_slot(slot);
1691 return handle_curl_result(results);
1694 struct curl_slist *http_copy_default_headers(void)
1696 struct curl_slist *headers = NULL;
1697 const struct string_list_item *item;
1699 for_each_string_list_item(item, &extra_http_headers)
1700 headers = curl_slist_append(headers, item->string);
1702 return headers;
1705 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1707 char *ptr;
1708 CURLcode ret;
1710 strbuf_reset(buf);
1711 ret = curl_easy_getinfo(curl, info, &ptr);
1712 if (!ret && ptr)
1713 strbuf_addstr(buf, ptr);
1714 return ret;
1718 * Check for and extract a content-type parameter. "raw"
1719 * should be positioned at the start of the potential
1720 * parameter, with any whitespace already removed.
1722 * "name" is the name of the parameter. The value is appended
1723 * to "out".
1725 static int extract_param(const char *raw, const char *name,
1726 struct strbuf *out)
1728 size_t len = strlen(name);
1730 if (strncasecmp(raw, name, len))
1731 return -1;
1732 raw += len;
1734 if (*raw != '=')
1735 return -1;
1736 raw++;
1738 while (*raw && !isspace(*raw) && *raw != ';')
1739 strbuf_addch(out, *raw++);
1740 return 0;
1744 * Extract a normalized version of the content type, with any
1745 * spaces suppressed, all letters lowercased, and no trailing ";"
1746 * or parameters.
1748 * Note that we will silently remove even invalid whitespace. For
1749 * example, "text / plain" is specifically forbidden by RFC 2616,
1750 * but "text/plain" is the only reasonable output, and this keeps
1751 * our code simple.
1753 * If the "charset" argument is not NULL, store the value of any
1754 * charset parameter there.
1756 * Example:
1757 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1758 * "text / plain" -> "text/plain"
1760 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1761 struct strbuf *charset)
1763 const char *p;
1765 strbuf_reset(type);
1766 strbuf_grow(type, raw->len);
1767 for (p = raw->buf; *p; p++) {
1768 if (isspace(*p))
1769 continue;
1770 if (*p == ';') {
1771 p++;
1772 break;
1774 strbuf_addch(type, tolower(*p));
1777 if (!charset)
1778 return;
1780 strbuf_reset(charset);
1781 while (*p) {
1782 while (isspace(*p) || *p == ';')
1783 p++;
1784 if (!extract_param(p, "charset", charset))
1785 return;
1786 while (*p && !isspace(*p))
1787 p++;
1790 if (!charset->len && starts_with(type->buf, "text/"))
1791 strbuf_addstr(charset, "ISO-8859-1");
1794 static void write_accept_language(struct strbuf *buf)
1797 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1798 * that, q-value will be smaller than 0.001, the minimum q-value the
1799 * HTTP specification allows. See
1800 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1802 const int MAX_DECIMAL_PLACES = 3;
1803 const int MAX_LANGUAGE_TAGS = 1000;
1804 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1805 char **language_tags = NULL;
1806 int num_langs = 0;
1807 const char *s = get_preferred_languages();
1808 int i;
1809 struct strbuf tag = STRBUF_INIT;
1811 /* Don't add Accept-Language header if no language is preferred. */
1812 if (!s)
1813 return;
1816 * Split the colon-separated string of preferred languages into
1817 * language_tags array.
1819 do {
1820 /* collect language tag */
1821 for (; *s && (isalnum(*s) || *s == '_'); s++)
1822 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1824 /* skip .codeset, @modifier and any other unnecessary parts */
1825 while (*s && *s != ':')
1826 s++;
1828 if (tag.len) {
1829 num_langs++;
1830 REALLOC_ARRAY(language_tags, num_langs);
1831 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1832 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1833 break;
1835 } while (*s++);
1837 /* write Accept-Language header into buf */
1838 if (num_langs) {
1839 int last_buf_len = 0;
1840 int max_q;
1841 int decimal_places;
1842 char q_format[32];
1844 /* add '*' */
1845 REALLOC_ARRAY(language_tags, num_langs + 1);
1846 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1848 /* compute decimal_places */
1849 for (max_q = 1, decimal_places = 0;
1850 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1851 decimal_places++, max_q *= 10)
1854 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1856 strbuf_addstr(buf, "Accept-Language: ");
1858 for (i = 0; i < num_langs; i++) {
1859 if (i > 0)
1860 strbuf_addstr(buf, ", ");
1862 strbuf_addstr(buf, language_tags[i]);
1864 if (i > 0)
1865 strbuf_addf(buf, q_format, max_q - i);
1867 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1868 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1869 break;
1872 last_buf_len = buf->len;
1876 /* free language tags -- last one is a static '*' */
1877 for (i = 0; i < num_langs - 1; i++)
1878 free(language_tags[i]);
1879 free(language_tags);
1883 * Get an Accept-Language header which indicates user's preferred languages.
1885 * Examples:
1886 * LANGUAGE= -> ""
1887 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1888 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1889 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1890 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1891 * LANGUAGE= LANG=C -> ""
1893 static const char *get_accept_language(void)
1895 if (!cached_accept_language) {
1896 struct strbuf buf = STRBUF_INIT;
1897 write_accept_language(&buf);
1898 if (buf.len > 0)
1899 cached_accept_language = strbuf_detach(&buf, NULL);
1902 return cached_accept_language;
1905 static void http_opt_request_remainder(CURL *curl, off_t pos)
1907 char buf[128];
1908 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1909 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1912 /* http_request() targets */
1913 #define HTTP_REQUEST_STRBUF 0
1914 #define HTTP_REQUEST_FILE 1
1916 static int http_request(const char *url,
1917 void *result, int target,
1918 const struct http_get_options *options)
1920 struct active_request_slot *slot;
1921 struct slot_results results;
1922 struct curl_slist *headers = http_copy_default_headers();
1923 struct strbuf buf = STRBUF_INIT;
1924 const char *accept_language;
1925 int ret;
1927 slot = get_active_slot();
1928 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1930 if (result == NULL) {
1931 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1932 } else {
1933 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1934 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1936 if (target == HTTP_REQUEST_FILE) {
1937 off_t posn = ftello(result);
1938 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1939 fwrite);
1940 if (posn > 0)
1941 http_opt_request_remainder(slot->curl, posn);
1942 } else
1943 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1944 fwrite_buffer);
1947 accept_language = get_accept_language();
1949 if (accept_language)
1950 headers = curl_slist_append(headers, accept_language);
1952 strbuf_addstr(&buf, "Pragma:");
1953 if (options && options->no_cache)
1954 strbuf_addstr(&buf, " no-cache");
1955 if (options && options->initial_request &&
1956 http_follow_config == HTTP_FOLLOW_INITIAL)
1957 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1959 headers = curl_slist_append(headers, buf.buf);
1961 /* Add additional headers here */
1962 if (options && options->extra_headers) {
1963 const struct string_list_item *item;
1964 for_each_string_list_item(item, options->extra_headers) {
1965 headers = curl_slist_append(headers, item->string);
1969 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1970 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1971 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1972 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1974 ret = run_one_slot(slot, &results);
1976 if (options && options->content_type) {
1977 struct strbuf raw = STRBUF_INIT;
1978 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1979 extract_content_type(&raw, options->content_type,
1980 options->charset);
1981 strbuf_release(&raw);
1984 if (options && options->effective_url)
1985 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1986 options->effective_url);
1988 curl_slist_free_all(headers);
1989 strbuf_release(&buf);
1991 return ret;
1995 * Update the "base" url to a more appropriate value, as deduced by
1996 * redirects seen when requesting a URL starting with "url".
1998 * The "asked" parameter is a URL that we asked curl to access, and must begin
1999 * with "base".
2001 * The "got" parameter is the URL that curl reported to us as where we ended
2002 * up.
2004 * Returns 1 if we updated the base url, 0 otherwise.
2006 * Our basic strategy is to compare "base" and "asked" to find the bits
2007 * specific to our request. We then strip those bits off of "got" to yield the
2008 * new base. So for example, if our base is "http://example.com/foo.git",
2009 * and we ask for "http://example.com/foo.git/info/refs", we might end up
2010 * with "https://other.example.com/foo.git/info/refs". We would want the
2011 * new URL to become "https://other.example.com/foo.git".
2013 * Note that this assumes a sane redirect scheme. It's entirely possible
2014 * in the example above to end up at a URL that does not even end in
2015 * "info/refs". In such a case we die. There's not much we can do, such a
2016 * scheme is unlikely to represent a real git repository, and failing to
2017 * rewrite the base opens options for malicious redirects to do funny things.
2019 static int update_url_from_redirect(struct strbuf *base,
2020 const char *asked,
2021 const struct strbuf *got)
2023 const char *tail;
2024 size_t new_len;
2026 if (!strcmp(asked, got->buf))
2027 return 0;
2029 if (!skip_prefix(asked, base->buf, &tail))
2030 BUG("update_url_from_redirect: %s is not a superset of %s",
2031 asked, base->buf);
2033 new_len = got->len;
2034 if (!strip_suffix_mem(got->buf, &new_len, tail))
2035 die(_("unable to update url base from redirection:\n"
2036 " asked for: %s\n"
2037 " redirect: %s"),
2038 asked, got->buf);
2040 strbuf_reset(base);
2041 strbuf_add(base, got->buf, new_len);
2043 return 1;
2046 static int http_request_reauth(const char *url,
2047 void *result, int target,
2048 struct http_get_options *options)
2050 int ret = http_request(url, result, target, options);
2052 if (ret != HTTP_OK && ret != HTTP_REAUTH)
2053 return ret;
2055 if (options && options->effective_url && options->base_url) {
2056 if (update_url_from_redirect(options->base_url,
2057 url, options->effective_url)) {
2058 credential_from_url(&http_auth, options->base_url->buf);
2059 url = options->effective_url->buf;
2063 if (ret != HTTP_REAUTH)
2064 return ret;
2067 * The previous request may have put cruft into our output stream; we
2068 * should clear it out before making our next request.
2070 switch (target) {
2071 case HTTP_REQUEST_STRBUF:
2072 strbuf_reset(result);
2073 break;
2074 case HTTP_REQUEST_FILE:
2075 if (fflush(result)) {
2076 error_errno("unable to flush a file");
2077 return HTTP_START_FAILED;
2079 rewind(result);
2080 if (ftruncate(fileno(result), 0) < 0) {
2081 error_errno("unable to truncate a file");
2082 return HTTP_START_FAILED;
2084 break;
2085 default:
2086 BUG("Unknown http_request target");
2089 credential_fill(&http_auth);
2091 return http_request(url, result, target, options);
2094 int http_get_strbuf(const char *url,
2095 struct strbuf *result,
2096 struct http_get_options *options)
2098 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
2102 * Downloads a URL and stores the result in the given file.
2104 * If a previous interrupted download is detected (i.e. a previous temporary
2105 * file is still around) the download is resumed.
2107 static int http_get_file(const char *url, const char *filename,
2108 struct http_get_options *options)
2110 int ret;
2111 struct strbuf tmpfile = STRBUF_INIT;
2112 FILE *result;
2114 strbuf_addf(&tmpfile, "%s.temp", filename);
2115 result = fopen(tmpfile.buf, "a");
2116 if (!result) {
2117 error("Unable to open local file %s", tmpfile.buf);
2118 ret = HTTP_ERROR;
2119 goto cleanup;
2122 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
2123 fclose(result);
2125 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
2126 ret = HTTP_ERROR;
2127 cleanup:
2128 strbuf_release(&tmpfile);
2129 return ret;
2132 int http_fetch_ref(const char *base, struct ref *ref)
2134 struct http_get_options options = {0};
2135 char *url;
2136 struct strbuf buffer = STRBUF_INIT;
2137 int ret = -1;
2139 options.no_cache = 1;
2141 url = quote_ref_url(base, ref->name);
2142 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
2143 strbuf_rtrim(&buffer);
2144 if (buffer.len == the_hash_algo->hexsz)
2145 ret = get_oid_hex(buffer.buf, &ref->old_oid);
2146 else if (starts_with(buffer.buf, "ref: ")) {
2147 ref->symref = xstrdup(buffer.buf + 5);
2148 ret = 0;
2152 strbuf_release(&buffer);
2153 free(url);
2154 return ret;
2157 /* Helpers for fetching packs */
2158 static char *fetch_pack_index(unsigned char *hash, const char *base_url)
2160 char *url, *tmp;
2161 struct strbuf buf = STRBUF_INIT;
2163 if (http_is_verbose)
2164 fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
2166 end_url_with_slash(&buf, base_url);
2167 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
2168 url = strbuf_detach(&buf, NULL);
2170 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
2171 tmp = strbuf_detach(&buf, NULL);
2173 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
2174 error("Unable to get pack index %s", url);
2175 FREE_AND_NULL(tmp);
2178 free(url);
2179 return tmp;
2182 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
2183 unsigned char *sha1, const char *base_url)
2185 struct packed_git *new_pack;
2186 char *tmp_idx = NULL;
2187 int ret;
2189 if (has_pack_index(sha1)) {
2190 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2191 if (!new_pack)
2192 return -1; /* parse_pack_index() already issued error message */
2193 goto add_pack;
2196 tmp_idx = fetch_pack_index(sha1, base_url);
2197 if (!tmp_idx)
2198 return -1;
2200 new_pack = parse_pack_index(sha1, tmp_idx);
2201 if (!new_pack) {
2202 unlink(tmp_idx);
2203 free(tmp_idx);
2205 return -1; /* parse_pack_index() already issued error message */
2208 ret = verify_pack_index(new_pack);
2209 if (!ret) {
2210 close_pack_index(new_pack);
2211 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2213 free(tmp_idx);
2214 if (ret)
2215 return -1;
2217 add_pack:
2218 new_pack->next = *packs_head;
2219 *packs_head = new_pack;
2220 return 0;
2223 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2225 struct http_get_options options = {0};
2226 int ret = 0;
2227 char *url;
2228 const char *data;
2229 struct strbuf buf = STRBUF_INIT;
2230 struct object_id oid;
2232 end_url_with_slash(&buf, base_url);
2233 strbuf_addstr(&buf, "objects/info/packs");
2234 url = strbuf_detach(&buf, NULL);
2236 options.no_cache = 1;
2237 ret = http_get_strbuf(url, &buf, &options);
2238 if (ret != HTTP_OK)
2239 goto cleanup;
2241 data = buf.buf;
2242 while (*data) {
2243 if (skip_prefix(data, "P pack-", &data) &&
2244 !parse_oid_hex(data, &oid, &data) &&
2245 skip_prefix(data, ".pack", &data) &&
2246 (*data == '\n' || *data == '\0')) {
2247 fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
2248 } else {
2249 data = strchrnul(data, '\n');
2251 if (*data)
2252 data++; /* skip past newline */
2255 cleanup:
2256 free(url);
2257 return ret;
2260 void release_http_pack_request(struct http_pack_request *preq)
2262 if (preq->packfile != NULL) {
2263 fclose(preq->packfile);
2264 preq->packfile = NULL;
2266 preq->slot = NULL;
2267 strbuf_release(&preq->tmpfile);
2268 free(preq->url);
2269 free(preq);
2272 static const char *default_index_pack_args[] =
2273 {"index-pack", "--stdin", NULL};
2275 int finish_http_pack_request(struct http_pack_request *preq)
2277 struct child_process ip = CHILD_PROCESS_INIT;
2278 int tmpfile_fd;
2279 int ret = 0;
2281 fclose(preq->packfile);
2282 preq->packfile = NULL;
2284 tmpfile_fd = xopen(preq->tmpfile.buf, O_RDONLY);
2286 ip.git_cmd = 1;
2287 ip.in = tmpfile_fd;
2288 ip.argv = preq->index_pack_args ? preq->index_pack_args
2289 : default_index_pack_args;
2291 if (preq->preserve_index_pack_stdout)
2292 ip.out = 0;
2293 else
2294 ip.no_stdout = 1;
2296 if (run_command(&ip)) {
2297 ret = -1;
2298 goto cleanup;
2301 cleanup:
2302 close(tmpfile_fd);
2303 unlink(preq->tmpfile.buf);
2304 return ret;
2307 void http_install_packfile(struct packed_git *p,
2308 struct packed_git **list_to_remove_from)
2310 struct packed_git **lst = list_to_remove_from;
2312 while (*lst != p)
2313 lst = &((*lst)->next);
2314 *lst = (*lst)->next;
2316 install_packed_git(the_repository, p);
2319 struct http_pack_request *new_http_pack_request(
2320 const unsigned char *packed_git_hash, const char *base_url) {
2322 struct strbuf buf = STRBUF_INIT;
2324 end_url_with_slash(&buf, base_url);
2325 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2326 hash_to_hex(packed_git_hash));
2327 return new_direct_http_pack_request(packed_git_hash,
2328 strbuf_detach(&buf, NULL));
2331 struct http_pack_request *new_direct_http_pack_request(
2332 const unsigned char *packed_git_hash, char *url)
2334 off_t prev_posn = 0;
2335 struct http_pack_request *preq;
2337 CALLOC_ARRAY(preq, 1);
2338 strbuf_init(&preq->tmpfile, 0);
2340 preq->url = url;
2342 strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(packed_git_hash));
2343 preq->packfile = fopen(preq->tmpfile.buf, "a");
2344 if (!preq->packfile) {
2345 error("Unable to open local file %s for pack",
2346 preq->tmpfile.buf);
2347 goto abort;
2350 preq->slot = get_active_slot();
2351 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2352 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2353 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2354 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2355 no_pragma_header);
2358 * If there is data present from a previous transfer attempt,
2359 * resume where it left off
2361 prev_posn = ftello(preq->packfile);
2362 if (prev_posn>0) {
2363 if (http_is_verbose)
2364 fprintf(stderr,
2365 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2366 hash_to_hex(packed_git_hash),
2367 (uintmax_t)prev_posn);
2368 http_opt_request_remainder(preq->slot->curl, prev_posn);
2371 return preq;
2373 abort:
2374 strbuf_release(&preq->tmpfile);
2375 free(preq->url);
2376 free(preq);
2377 return NULL;
2380 /* Helpers for fetching objects (loose) */
2381 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2382 void *data)
2384 unsigned char expn[4096];
2385 size_t size = eltsize * nmemb;
2386 int posn = 0;
2387 struct http_object_request *freq = data;
2388 struct active_request_slot *slot = freq->slot;
2390 if (slot) {
2391 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2392 &slot->http_code);
2393 if (c != CURLE_OK)
2394 BUG("curl_easy_getinfo for HTTP code failed: %s",
2395 curl_easy_strerror(c));
2396 if (slot->http_code >= 300)
2397 return nmemb;
2400 do {
2401 ssize_t retval = xwrite(freq->localfile,
2402 (char *) ptr + posn, size - posn);
2403 if (retval < 0)
2404 return posn / eltsize;
2405 posn += retval;
2406 } while (posn < size);
2408 freq->stream.avail_in = size;
2409 freq->stream.next_in = (void *)ptr;
2410 do {
2411 freq->stream.next_out = expn;
2412 freq->stream.avail_out = sizeof(expn);
2413 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2414 the_hash_algo->update_fn(&freq->c, expn,
2415 sizeof(expn) - freq->stream.avail_out);
2416 } while (freq->stream.avail_in && freq->zret == Z_OK);
2417 return nmemb;
2420 struct http_object_request *new_http_object_request(const char *base_url,
2421 const struct object_id *oid)
2423 char *hex = oid_to_hex(oid);
2424 struct strbuf filename = STRBUF_INIT;
2425 struct strbuf prevfile = STRBUF_INIT;
2426 int prevlocal;
2427 char prev_buf[PREV_BUF_SIZE];
2428 ssize_t prev_read = 0;
2429 off_t prev_posn = 0;
2430 struct http_object_request *freq;
2432 CALLOC_ARRAY(freq, 1);
2433 strbuf_init(&freq->tmpfile, 0);
2434 oidcpy(&freq->oid, oid);
2435 freq->localfile = -1;
2437 loose_object_path(the_repository, &filename, oid);
2438 strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
2440 strbuf_addf(&prevfile, "%s.prev", filename.buf);
2441 unlink_or_warn(prevfile.buf);
2442 rename(freq->tmpfile.buf, prevfile.buf);
2443 unlink_or_warn(freq->tmpfile.buf);
2444 strbuf_release(&filename);
2446 if (freq->localfile != -1)
2447 error("fd leakage in start: %d", freq->localfile);
2448 freq->localfile = open(freq->tmpfile.buf,
2449 O_WRONLY | O_CREAT | O_EXCL, 0666);
2451 * This could have failed due to the "lazy directory creation";
2452 * try to mkdir the last path component.
2454 if (freq->localfile < 0 && errno == ENOENT) {
2455 char *dir = strrchr(freq->tmpfile.buf, '/');
2456 if (dir) {
2457 *dir = 0;
2458 mkdir(freq->tmpfile.buf, 0777);
2459 *dir = '/';
2461 freq->localfile = open(freq->tmpfile.buf,
2462 O_WRONLY | O_CREAT | O_EXCL, 0666);
2465 if (freq->localfile < 0) {
2466 error_errno("Couldn't create temporary file %s",
2467 freq->tmpfile.buf);
2468 goto abort;
2471 git_inflate_init(&freq->stream);
2473 the_hash_algo->init_fn(&freq->c);
2475 freq->url = get_remote_object_url(base_url, hex, 0);
2478 * If a previous temp file is present, process what was already
2479 * fetched.
2481 prevlocal = open(prevfile.buf, O_RDONLY);
2482 if (prevlocal != -1) {
2483 do {
2484 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2485 if (prev_read>0) {
2486 if (fwrite_sha1_file(prev_buf,
2488 prev_read,
2489 freq) == prev_read) {
2490 prev_posn += prev_read;
2491 } else {
2492 prev_read = -1;
2495 } while (prev_read > 0);
2496 close(prevlocal);
2498 unlink_or_warn(prevfile.buf);
2499 strbuf_release(&prevfile);
2502 * Reset inflate/SHA1 if there was an error reading the previous temp
2503 * file; also rewind to the beginning of the local file.
2505 if (prev_read == -1) {
2506 memset(&freq->stream, 0, sizeof(freq->stream));
2507 git_inflate_init(&freq->stream);
2508 the_hash_algo->init_fn(&freq->c);
2509 if (prev_posn>0) {
2510 prev_posn = 0;
2511 lseek(freq->localfile, 0, SEEK_SET);
2512 if (ftruncate(freq->localfile, 0) < 0) {
2513 error_errno("Couldn't truncate temporary file %s",
2514 freq->tmpfile.buf);
2515 goto abort;
2520 freq->slot = get_active_slot();
2522 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2523 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2524 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2525 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2526 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2527 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2530 * If we have successfully processed data from a previous fetch
2531 * attempt, only fetch the data we don't already have.
2533 if (prev_posn>0) {
2534 if (http_is_verbose)
2535 fprintf(stderr,
2536 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2537 hex, (uintmax_t)prev_posn);
2538 http_opt_request_remainder(freq->slot->curl, prev_posn);
2541 return freq;
2543 abort:
2544 strbuf_release(&prevfile);
2545 free(freq->url);
2546 free(freq);
2547 return NULL;
2550 void process_http_object_request(struct http_object_request *freq)
2552 if (freq->slot == NULL)
2553 return;
2554 freq->curl_result = freq->slot->curl_result;
2555 freq->http_code = freq->slot->http_code;
2556 freq->slot = NULL;
2559 int finish_http_object_request(struct http_object_request *freq)
2561 struct stat st;
2562 struct strbuf filename = STRBUF_INIT;
2564 close(freq->localfile);
2565 freq->localfile = -1;
2567 process_http_object_request(freq);
2569 if (freq->http_code == 416) {
2570 warning("requested range invalid; we may already have all the data.");
2571 } else if (freq->curl_result != CURLE_OK) {
2572 if (stat(freq->tmpfile.buf, &st) == 0)
2573 if (st.st_size == 0)
2574 unlink_or_warn(freq->tmpfile.buf);
2575 return -1;
2578 git_inflate_end(&freq->stream);
2579 the_hash_algo->final_fn(freq->real_oid.hash, &freq->c);
2580 if (freq->zret != Z_STREAM_END) {
2581 unlink_or_warn(freq->tmpfile.buf);
2582 return -1;
2584 if (!oideq(&freq->oid, &freq->real_oid)) {
2585 unlink_or_warn(freq->tmpfile.buf);
2586 return -1;
2588 loose_object_path(the_repository, &filename, &freq->oid);
2589 freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
2590 strbuf_release(&filename);
2592 return freq->rename;
2595 void abort_http_object_request(struct http_object_request *freq)
2597 unlink_or_warn(freq->tmpfile.buf);
2599 release_http_object_request(freq);
2602 void release_http_object_request(struct http_object_request *freq)
2604 if (freq->localfile != -1) {
2605 close(freq->localfile);
2606 freq->localfile = -1;
2608 FREE_AND_NULL(freq->url);
2609 if (freq->slot != NULL) {
2610 freq->slot->callback_func = NULL;
2611 freq->slot->callback_data = NULL;
2612 release_active_slot(freq->slot);
2613 freq->slot = NULL;
2615 strbuf_release(&freq->tmpfile);