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
18static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
19static int trace_curl_data = 1;
20static struct string_list cookies_to_redact = STRING_LIST_INIT_DUP;
21#if LIBCURL_VERSION_NUM >= 0x070a08
22long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
23#else
24long int git_curl_ipresolve;
25#endif
26int active_requests;
27int http_is_verbose;
28ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
29
30#if LIBCURL_VERSION_NUM >= 0x070a06
31#define LIBCURL_CAN_HANDLE_AUTH_ANY
32#endif
33
34static int min_curl_sessions = 1;
35static int curl_session_count;
36#ifdef USE_CURL_MULTI
37static int max_requests = -1;
38static CURLM *curlm;
39#endif
40#ifndef NO_CURL_EASY_DUPHANDLE
41static CURL *curl_default;
42#endif
43
44#define PREV_BUF_SIZE 4096
45
46char curl_errorstr[CURL_ERROR_SIZE];
47
48static int curl_ssl_verify = -1;
49static int curl_ssl_try;
50static const char *ssl_cert;
51static const char *ssl_cipherlist;
52static const char *ssl_version;
53static struct {
54 const char *name;
55 long ssl_version;
56} sslversions[] = {
57 { "sslv2", CURL_SSLVERSION_SSLv2 },
58 { "sslv3", CURL_SSLVERSION_SSLv3 },
59 { "tlsv1", CURL_SSLVERSION_TLSv1 },
60#if LIBCURL_VERSION_NUM >= 0x072200
61 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
62 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
63 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
64#endif
65};
66#if LIBCURL_VERSION_NUM >= 0x070903
67static const char *ssl_key;
68#endif
69#if LIBCURL_VERSION_NUM >= 0x070908
70static const char *ssl_capath;
71#endif
72#if LIBCURL_VERSION_NUM >= 0x071304
73static const char *curl_no_proxy;
74#endif
75#if LIBCURL_VERSION_NUM >= 0x072c00
76static const char *ssl_pinnedkey;
77#endif
78static const char *ssl_cainfo;
79static long curl_low_speed_limit = -1;
80static long curl_low_speed_time = -1;
81static int curl_ftp_no_epsv;
82static const char *curl_http_proxy;
83static const char *http_proxy_authmethod;
84static struct {
85 const char *name;
86 long curlauth_param;
87} proxy_authmethods[] = {
88 { "basic", CURLAUTH_BASIC },
89 { "digest", CURLAUTH_DIGEST },
90 { "negotiate", CURLAUTH_GSSNEGOTIATE },
91 { "ntlm", CURLAUTH_NTLM },
92#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
93 { "anyauth", CURLAUTH_ANY },
94#endif
95 /*
96 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
97 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
98 * here, too
99 */
100};
101#ifdef CURLGSSAPI_DELEGATION_FLAG
102static const char *curl_deleg;
103static struct {
104 const char *name;
105 long curl_deleg_param;
106} curl_deleg_levels[] = {
107 { "none", CURLGSSAPI_DELEGATION_NONE },
108 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
109 { "always", CURLGSSAPI_DELEGATION_FLAG },
110};
111#endif
112
113static struct credential proxy_auth = CREDENTIAL_INIT;
114static const char *curl_proxyuserpwd;
115static const char *curl_cookie_file;
116static int curl_save_cookies;
117struct credential http_auth = CREDENTIAL_INIT;
118static int http_proactive_auth;
119static const char *user_agent;
120static int curl_empty_auth = -1;
121
122enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
123
124#if LIBCURL_VERSION_NUM >= 0x071700
125/* Use CURLOPT_KEYPASSWD as is */
126#elif LIBCURL_VERSION_NUM >= 0x070903
127#define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
128#else
129#define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
130#endif
131
132static struct credential cert_auth = CREDENTIAL_INIT;
133static int ssl_cert_password_required;
134#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
135static unsigned long http_auth_methods = CURLAUTH_ANY;
136static int http_auth_methods_restricted;
137/* Modes for which empty_auth cannot actually help us. */
138static unsigned long empty_auth_useless =
139 CURLAUTH_BASIC
140#ifdef CURLAUTH_DIGEST_IE
141 | CURLAUTH_DIGEST_IE
142#endif
143 | CURLAUTH_DIGEST;
144#endif
145
146static struct curl_slist *pragma_header;
147static struct curl_slist *no_pragma_header;
148static struct curl_slist *extra_http_headers;
149
150static struct active_request_slot *active_queue_head;
151
152static char *cached_accept_language;
153
154size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
155{
156 size_t size = eltsize * nmemb;
157 struct buffer *buffer = buffer_;
158
159 if (size > buffer->buf.len - buffer->posn)
160 size = buffer->buf.len - buffer->posn;
161 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
162 buffer->posn += size;
163
164 return size;
165}
166
167#ifndef NO_CURL_IOCTL
168curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
169{
170 struct buffer *buffer = clientp;
171
172 switch (cmd) {
173 case CURLIOCMD_NOP:
174 return CURLIOE_OK;
175
176 case CURLIOCMD_RESTARTREAD:
177 buffer->posn = 0;
178 return CURLIOE_OK;
179
180 default:
181 return CURLIOE_UNKNOWNCMD;
182 }
183}
184#endif
185
186size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
187{
188 size_t size = eltsize * nmemb;
189 struct strbuf *buffer = buffer_;
190
191 strbuf_add(buffer, ptr, size);
192 return size;
193}
194
195size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
196{
197 return eltsize * nmemb;
198}
199
200static void closedown_active_slot(struct active_request_slot *slot)
201{
202 active_requests--;
203 slot->in_use = 0;
204}
205
206static void finish_active_slot(struct active_request_slot *slot)
207{
208 closedown_active_slot(slot);
209 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
210
211 if (slot->finished != NULL)
212 (*slot->finished) = 1;
213
214 /* Store slot results so they can be read after the slot is reused */
215 if (slot->results != NULL) {
216 slot->results->curl_result = slot->curl_result;
217 slot->results->http_code = slot->http_code;
218#if LIBCURL_VERSION_NUM >= 0x070a08
219 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
220 &slot->results->auth_avail);
221#else
222 slot->results->auth_avail = 0;
223#endif
224
225 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
226 &slot->results->http_connectcode);
227 }
228
229 /* Run callback if appropriate */
230 if (slot->callback_func != NULL)
231 slot->callback_func(slot->callback_data);
232}
233
234static void xmulti_remove_handle(struct active_request_slot *slot)
235{
236#ifdef USE_CURL_MULTI
237 curl_multi_remove_handle(curlm, slot->curl);
238#endif
239}
240
241#ifdef USE_CURL_MULTI
242static void process_curl_messages(void)
243{
244 int num_messages;
245 struct active_request_slot *slot;
246 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
247
248 while (curl_message != NULL) {
249 if (curl_message->msg == CURLMSG_DONE) {
250 int curl_result = curl_message->data.result;
251 slot = active_queue_head;
252 while (slot != NULL &&
253 slot->curl != curl_message->easy_handle)
254 slot = slot->next;
255 if (slot != NULL) {
256 xmulti_remove_handle(slot);
257 slot->curl_result = curl_result;
258 finish_active_slot(slot);
259 } else {
260 fprintf(stderr, "Received DONE message for unknown request!\n");
261 }
262 } else {
263 fprintf(stderr, "Unknown CURL message received: %d\n",
264 (int)curl_message->msg);
265 }
266 curl_message = curl_multi_info_read(curlm, &num_messages);
267 }
268}
269#endif
270
271static int http_options(const char *var, const char *value, void *cb)
272{
273 if (!strcmp("http.sslverify", var)) {
274 curl_ssl_verify = git_config_bool(var, value);
275 return 0;
276 }
277 if (!strcmp("http.sslcipherlist", var))
278 return git_config_string(&ssl_cipherlist, var, value);
279 if (!strcmp("http.sslversion", var))
280 return git_config_string(&ssl_version, var, value);
281 if (!strcmp("http.sslcert", var))
282 return git_config_pathname(&ssl_cert, var, value);
283#if LIBCURL_VERSION_NUM >= 0x070903
284 if (!strcmp("http.sslkey", var))
285 return git_config_pathname(&ssl_key, var, value);
286#endif
287#if LIBCURL_VERSION_NUM >= 0x070908
288 if (!strcmp("http.sslcapath", var))
289 return git_config_pathname(&ssl_capath, var, value);
290#endif
291 if (!strcmp("http.sslcainfo", var))
292 return git_config_pathname(&ssl_cainfo, var, value);
293 if (!strcmp("http.sslcertpasswordprotected", var)) {
294 ssl_cert_password_required = git_config_bool(var, value);
295 return 0;
296 }
297 if (!strcmp("http.ssltry", var)) {
298 curl_ssl_try = git_config_bool(var, value);
299 return 0;
300 }
301 if (!strcmp("http.minsessions", var)) {
302 min_curl_sessions = git_config_int(var, value);
303#ifndef USE_CURL_MULTI
304 if (min_curl_sessions > 1)
305 min_curl_sessions = 1;
306#endif
307 return 0;
308 }
309#ifdef USE_CURL_MULTI
310 if (!strcmp("http.maxrequests", var)) {
311 max_requests = git_config_int(var, value);
312 return 0;
313 }
314#endif
315 if (!strcmp("http.lowspeedlimit", var)) {
316 curl_low_speed_limit = (long)git_config_int(var, value);
317 return 0;
318 }
319 if (!strcmp("http.lowspeedtime", var)) {
320 curl_low_speed_time = (long)git_config_int(var, value);
321 return 0;
322 }
323
324 if (!strcmp("http.noepsv", var)) {
325 curl_ftp_no_epsv = git_config_bool(var, value);
326 return 0;
327 }
328 if (!strcmp("http.proxy", var))
329 return git_config_string(&curl_http_proxy, var, value);
330
331 if (!strcmp("http.proxyauthmethod", var))
332 return git_config_string(&http_proxy_authmethod, var, value);
333
334 if (!strcmp("http.cookiefile", var))
335 return git_config_pathname(&curl_cookie_file, var, value);
336 if (!strcmp("http.savecookies", var)) {
337 curl_save_cookies = git_config_bool(var, value);
338 return 0;
339 }
340
341 if (!strcmp("http.postbuffer", var)) {
342 http_post_buffer = git_config_ssize_t(var, value);
343 if (http_post_buffer < 0)
344 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
345 if (http_post_buffer < LARGE_PACKET_MAX)
346 http_post_buffer = LARGE_PACKET_MAX;
347 return 0;
348 }
349
350 if (!strcmp("http.useragent", var))
351 return git_config_string(&user_agent, var, value);
352
353 if (!strcmp("http.emptyauth", var)) {
354 if (value && !strcmp("auto", value))
355 curl_empty_auth = -1;
356 else
357 curl_empty_auth = git_config_bool(var, value);
358 return 0;
359 }
360
361 if (!strcmp("http.delegation", var)) {
362#ifdef CURLGSSAPI_DELEGATION_FLAG
363 return git_config_string(&curl_deleg, var, value);
364#else
365 warning(_("Delegation control is not supported with cURL < 7.22.0"));
366 return 0;
367#endif
368 }
369
370 if (!strcmp("http.pinnedpubkey", var)) {
371#if LIBCURL_VERSION_NUM >= 0x072c00
372 return git_config_pathname(&ssl_pinnedkey, var, value);
373#else
374 warning(_("Public key pinning not supported with cURL < 7.44.0"));
375 return 0;
376#endif
377 }
378
379 if (!strcmp("http.extraheader", var)) {
380 if (!value) {
381 return config_error_nonbool(var);
382 } else if (!*value) {
383 curl_slist_free_all(extra_http_headers);
384 extra_http_headers = NULL;
385 } else {
386 extra_http_headers =
387 curl_slist_append(extra_http_headers, value);
388 }
389 return 0;
390 }
391
392 if (!strcmp("http.followredirects", var)) {
393 if (value && !strcmp(value, "initial"))
394 http_follow_config = HTTP_FOLLOW_INITIAL;
395 else if (git_config_bool(var, value))
396 http_follow_config = HTTP_FOLLOW_ALWAYS;
397 else
398 http_follow_config = HTTP_FOLLOW_NONE;
399 return 0;
400 }
401
402 /* Fall back on the default ones */
403 return git_default_config(var, value, cb);
404}
405
406static int curl_empty_auth_enabled(void)
407{
408 if (curl_empty_auth >= 0)
409 return curl_empty_auth;
410
411#ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
412 /*
413 * Our libcurl is too old to do AUTH_ANY in the first place;
414 * just default to turning the feature off.
415 */
416#else
417 /*
418 * In the automatic case, kick in the empty-auth
419 * hack as long as we would potentially try some
420 * method more exotic than "Basic" or "Digest".
421 *
422 * But only do this when this is our second or
423 * subsequent request, as by then we know what
424 * methods are available.
425 */
426 if (http_auth_methods_restricted &&
427 (http_auth_methods & ~empty_auth_useless))
428 return 1;
429#endif
430 return 0;
431}
432
433static void init_curl_http_auth(CURL *result)
434{
435 if (!http_auth.username || !*http_auth.username) {
436 if (curl_empty_auth_enabled())
437 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
438 return;
439 }
440
441 credential_fill(&http_auth);
442
443#if LIBCURL_VERSION_NUM >= 0x071301
444 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
445 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
446#else
447 {
448 static struct strbuf up = STRBUF_INIT;
449 /*
450 * Note that we assume we only ever have a single set of
451 * credentials in a given program run, so we do not have
452 * to worry about updating this buffer, only setting its
453 * initial value.
454 */
455 if (!up.len)
456 strbuf_addf(&up, "%s:%s",
457 http_auth.username, http_auth.password);
458 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
459 }
460#endif
461}
462
463/* *var must be free-able */
464static void var_override(const char **var, char *value)
465{
466 if (value) {
467 free((void *)*var);
468 *var = xstrdup(value);
469 }
470}
471
472static void set_proxyauth_name_password(CURL *result)
473{
474#if LIBCURL_VERSION_NUM >= 0x071301
475 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
476 proxy_auth.username);
477 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
478 proxy_auth.password);
479#else
480 struct strbuf s = STRBUF_INIT;
481
482 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
483 strbuf_addch(&s, ':');
484 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
485 curl_proxyuserpwd = strbuf_detach(&s, NULL);
486 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
487#endif
488}
489
490static void init_curl_proxy_auth(CURL *result)
491{
492 if (proxy_auth.username) {
493 if (!proxy_auth.password)
494 credential_fill(&proxy_auth);
495 set_proxyauth_name_password(result);
496 }
497
498 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
499
500#if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
501 if (http_proxy_authmethod) {
502 int i;
503 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
504 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
505 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
506 proxy_authmethods[i].curlauth_param);
507 break;
508 }
509 }
510 if (i == ARRAY_SIZE(proxy_authmethods)) {
511 warning("unsupported proxy authentication method %s: using anyauth",
512 http_proxy_authmethod);
513 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
514 }
515 }
516 else
517 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
518#endif
519}
520
521static int has_cert_password(void)
522{
523 if (ssl_cert == NULL || ssl_cert_password_required != 1)
524 return 0;
525 if (!cert_auth.password) {
526 cert_auth.protocol = xstrdup("cert");
527 cert_auth.username = xstrdup("");
528 cert_auth.path = xstrdup(ssl_cert);
529 credential_fill(&cert_auth);
530 }
531 return 1;
532}
533
534#if LIBCURL_VERSION_NUM >= 0x071900
535static void set_curl_keepalive(CURL *c)
536{
537 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
538}
539
540#elif LIBCURL_VERSION_NUM >= 0x071000
541static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
542{
543 int ka = 1;
544 int rc;
545 socklen_t len = (socklen_t)sizeof(ka);
546
547 if (type != CURLSOCKTYPE_IPCXN)
548 return 0;
549
550 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
551 if (rc < 0)
552 warning_errno("unable to set SO_KEEPALIVE on socket");
553
554 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
555}
556
557static void set_curl_keepalive(CURL *c)
558{
559 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
560}
561
562#else
563static void set_curl_keepalive(CURL *c)
564{
565 /* not supported on older curl versions */
566}
567#endif
568
569static void redact_sensitive_header(struct strbuf *header)
570{
571 const char *sensitive_header;
572
573 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
574 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
575 /* The first token is the type, which is OK to log */
576 while (isspace(*sensitive_header))
577 sensitive_header++;
578 while (*sensitive_header && !isspace(*sensitive_header))
579 sensitive_header++;
580 /* Everything else is opaque and possibly sensitive */
581 strbuf_setlen(header, sensitive_header - header->buf);
582 strbuf_addstr(header, " <redacted>");
583 } else if (cookies_to_redact.nr &&
584 skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
585 struct strbuf redacted_header = STRBUF_INIT;
586 char *cookie;
587
588 while (isspace(*sensitive_header))
589 sensitive_header++;
590
591 /*
592 * The contents of header starting from sensitive_header will
593 * subsequently be overridden, so it is fine to mutate this
594 * string (hence the assignment to "char *").
595 */
596 cookie = (char *) sensitive_header;
597
598 while (cookie) {
599 char *equals;
600 char *semicolon = strstr(cookie, "; ");
601 if (semicolon)
602 *semicolon = 0;
603 equals = strchrnul(cookie, '=');
604 if (!equals) {
605 /* invalid cookie, just append and continue */
606 strbuf_addstr(&redacted_header, cookie);
607 continue;
608 }
609 *equals = 0; /* temporarily set to NUL for lookup */
610 if (string_list_lookup(&cookies_to_redact, cookie)) {
611 strbuf_addstr(&redacted_header, cookie);
612 strbuf_addstr(&redacted_header, "=<redacted>");
613 } else {
614 *equals = '=';
615 strbuf_addstr(&redacted_header, cookie);
616 }
617 if (semicolon) {
618 /*
619 * There are more cookies. (Or, for some
620 * reason, the input string ends in "; ".)
621 */
622 strbuf_addstr(&redacted_header, "; ");
623 cookie = semicolon + strlen("; ");
624 } else {
625 cookie = NULL;
626 }
627 }
628
629 strbuf_setlen(header, sensitive_header - header->buf);
630 strbuf_addbuf(header, &redacted_header);
631 }
632}
633
634static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
635{
636 struct strbuf out = STRBUF_INIT;
637 struct strbuf **headers, **header;
638
639 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
640 text, (long)size, (long)size);
641 trace_strbuf(&trace_curl, &out);
642 strbuf_reset(&out);
643 strbuf_add(&out, ptr, size);
644 headers = strbuf_split_max(&out, '\n', 0);
645
646 for (header = headers; *header; header++) {
647 if (hide_sensitive_header)
648 redact_sensitive_header(*header);
649 strbuf_insert((*header), 0, text, strlen(text));
650 strbuf_insert((*header), strlen(text), ": ", 2);
651 strbuf_rtrim((*header));
652 strbuf_addch((*header), '\n');
653 trace_strbuf(&trace_curl, (*header));
654 }
655 strbuf_list_free(headers);
656 strbuf_release(&out);
657}
658
659static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
660{
661 size_t i;
662 struct strbuf out = STRBUF_INIT;
663 unsigned int width = 60;
664
665 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
666 text, (long)size, (long)size);
667 trace_strbuf(&trace_curl, &out);
668
669 for (i = 0; i < size; i += width) {
670 size_t w;
671
672 strbuf_reset(&out);
673 strbuf_addf(&out, "%s: ", text);
674 for (w = 0; (w < width) && (i + w < size); w++) {
675 unsigned char ch = ptr[i + w];
676
677 strbuf_addch(&out,
678 (ch >= 0x20) && (ch < 0x80)
679 ? ch : '.');
680 }
681 strbuf_addch(&out, '\n');
682 trace_strbuf(&trace_curl, &out);
683 }
684 strbuf_release(&out);
685}
686
687static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
688{
689 const char *text;
690 enum { NO_FILTER = 0, DO_FILTER = 1 };
691
692 switch (type) {
693 case CURLINFO_TEXT:
694 trace_printf_key(&trace_curl, "== Info: %s", data);
695 break;
696 case CURLINFO_HEADER_OUT:
697 text = "=> Send header";
698 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
699 break;
700 case CURLINFO_DATA_OUT:
701 if (trace_curl_data) {
702 text = "=> Send data";
703 curl_dump_data(text, (unsigned char *)data, size);
704 }
705 break;
706 case CURLINFO_SSL_DATA_OUT:
707 if (trace_curl_data) {
708 text = "=> Send SSL data";
709 curl_dump_data(text, (unsigned char *)data, size);
710 }
711 break;
712 case CURLINFO_HEADER_IN:
713 text = "<= Recv header";
714 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
715 break;
716 case CURLINFO_DATA_IN:
717 if (trace_curl_data) {
718 text = "<= Recv data";
719 curl_dump_data(text, (unsigned char *)data, size);
720 }
721 break;
722 case CURLINFO_SSL_DATA_IN:
723 if (trace_curl_data) {
724 text = "<= Recv SSL data";
725 curl_dump_data(text, (unsigned char *)data, size);
726 }
727 break;
728
729 default: /* we ignore unknown types by default */
730 return 0;
731 }
732 return 0;
733}
734
735void setup_curl_trace(CURL *handle)
736{
737 if (!trace_want(&trace_curl))
738 return;
739 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
740 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
741 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
742}
743
744#ifdef CURLPROTO_HTTP
745static long get_curl_allowed_protocols(int from_user)
746{
747 long allowed_protocols = 0;
748
749 if (is_transport_allowed("http", from_user))
750 allowed_protocols |= CURLPROTO_HTTP;
751 if (is_transport_allowed("https", from_user))
752 allowed_protocols |= CURLPROTO_HTTPS;
753 if (is_transport_allowed("ftp", from_user))
754 allowed_protocols |= CURLPROTO_FTP;
755 if (is_transport_allowed("ftps", from_user))
756 allowed_protocols |= CURLPROTO_FTPS;
757
758 return allowed_protocols;
759}
760#endif
761
762static CURL *get_curl_handle(void)
763{
764 CURL *result = curl_easy_init();
765
766 if (!result)
767 die("curl_easy_init failed");
768
769 if (!curl_ssl_verify) {
770 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
771 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
772 } else {
773 /* Verify authenticity of the peer's certificate */
774 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
775 /* The name in the cert must match whom we tried to connect */
776 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
777 }
778
779#if LIBCURL_VERSION_NUM >= 0x070907
780 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
781#endif
782#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
783 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
784#endif
785
786#ifdef CURLGSSAPI_DELEGATION_FLAG
787 if (curl_deleg) {
788 int i;
789 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
790 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
791 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
792 curl_deleg_levels[i].curl_deleg_param);
793 break;
794 }
795 }
796 if (i == ARRAY_SIZE(curl_deleg_levels))
797 warning("Unknown delegation method '%s': using default",
798 curl_deleg);
799 }
800#endif
801
802 if (http_proactive_auth)
803 init_curl_http_auth(result);
804
805 if (getenv("GIT_SSL_VERSION"))
806 ssl_version = getenv("GIT_SSL_VERSION");
807 if (ssl_version && *ssl_version) {
808 int i;
809 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
810 if (!strcmp(ssl_version, sslversions[i].name)) {
811 curl_easy_setopt(result, CURLOPT_SSLVERSION,
812 sslversions[i].ssl_version);
813 break;
814 }
815 }
816 if (i == ARRAY_SIZE(sslversions))
817 warning("unsupported ssl version %s: using default",
818 ssl_version);
819 }
820
821 if (getenv("GIT_SSL_CIPHER_LIST"))
822 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
823 if (ssl_cipherlist != NULL && *ssl_cipherlist)
824 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
825 ssl_cipherlist);
826
827 if (ssl_cert != NULL)
828 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
829 if (has_cert_password())
830 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
831#if LIBCURL_VERSION_NUM >= 0x070903
832 if (ssl_key != NULL)
833 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
834#endif
835#if LIBCURL_VERSION_NUM >= 0x070908
836 if (ssl_capath != NULL)
837 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
838#endif
839#if LIBCURL_VERSION_NUM >= 0x072c00
840 if (ssl_pinnedkey != NULL)
841 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
842#endif
843 if (ssl_cainfo != NULL)
844 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
845
846 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
847 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
848 curl_low_speed_limit);
849 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
850 curl_low_speed_time);
851 }
852
853 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
854#if LIBCURL_VERSION_NUM >= 0x071301
855 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
856#elif LIBCURL_VERSION_NUM >= 0x071101
857 curl_easy_setopt(result, CURLOPT_POST301, 1);
858#endif
859#ifdef CURLPROTO_HTTP
860 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
861 get_curl_allowed_protocols(0));
862 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
863 get_curl_allowed_protocols(-1));
864#else
865 warning("protocol restrictions not applied to curl redirects because\n"
866 "your curl version is too old (>= 7.19.4)");
867#endif
868 if (getenv("GIT_CURL_VERBOSE"))
869 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
870 setup_curl_trace(result);
871 if (getenv("GIT_TRACE_CURL_NO_DATA"))
872 trace_curl_data = 0;
873 if (getenv("GIT_REDACT_COOKIES")) {
874 string_list_split(&cookies_to_redact,
875 getenv("GIT_REDACT_COOKIES"), ',', -1);
876 string_list_sort(&cookies_to_redact);
877 }
878
879 curl_easy_setopt(result, CURLOPT_USERAGENT,
880 user_agent ? user_agent : git_user_agent());
881
882 if (curl_ftp_no_epsv)
883 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
884
885#ifdef CURLOPT_USE_SSL
886 if (curl_ssl_try)
887 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
888#endif
889
890 /*
891 * CURL also examines these variables as a fallback; but we need to query
892 * them here in order to decide whether to prompt for missing password (cf.
893 * init_curl_proxy_auth()).
894 *
895 * Unlike many other common environment variables, these are historically
896 * lowercase only. It appears that CURL did not know this and implemented
897 * only uppercase variants, which was later corrected to take both - with
898 * the exception of http_proxy, which is lowercase only also in CURL. As
899 * the lowercase versions are the historical quasi-standard, they take
900 * precedence here, as in CURL.
901 */
902 if (!curl_http_proxy) {
903 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
904 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
905 var_override(&curl_http_proxy, getenv("https_proxy"));
906 } else {
907 var_override(&curl_http_proxy, getenv("http_proxy"));
908 }
909 if (!curl_http_proxy) {
910 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
911 var_override(&curl_http_proxy, getenv("all_proxy"));
912 }
913 }
914
915 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
916 /*
917 * Handle case with the empty http.proxy value here to keep
918 * common code clean.
919 * NB: empty option disables proxying at all.
920 */
921 curl_easy_setopt(result, CURLOPT_PROXY, "");
922 } else if (curl_http_proxy) {
923#if LIBCURL_VERSION_NUM >= 0x071800
924 if (starts_with(curl_http_proxy, "socks5h"))
925 curl_easy_setopt(result,
926 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
927 else if (starts_with(curl_http_proxy, "socks5"))
928 curl_easy_setopt(result,
929 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
930 else if (starts_with(curl_http_proxy, "socks4a"))
931 curl_easy_setopt(result,
932 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
933 else if (starts_with(curl_http_proxy, "socks"))
934 curl_easy_setopt(result,
935 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
936#endif
937#if LIBCURL_VERSION_NUM >= 0x073400
938 else if (starts_with(curl_http_proxy, "https"))
939 curl_easy_setopt(result,
940 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
941#endif
942 if (strstr(curl_http_proxy, "://"))
943 credential_from_url(&proxy_auth, curl_http_proxy);
944 else {
945 struct strbuf url = STRBUF_INIT;
946 strbuf_addf(&url, "http://%s", curl_http_proxy);
947 credential_from_url(&proxy_auth, url.buf);
948 strbuf_release(&url);
949 }
950
951 if (!proxy_auth.host)
952 die("Invalid proxy URL '%s'", curl_http_proxy);
953
954 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
955#if LIBCURL_VERSION_NUM >= 0x071304
956 var_override(&curl_no_proxy, getenv("NO_PROXY"));
957 var_override(&curl_no_proxy, getenv("no_proxy"));
958 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
959#endif
960 }
961 init_curl_proxy_auth(result);
962
963 set_curl_keepalive(result);
964
965 return result;
966}
967
968static void set_from_env(const char **var, const char *envname)
969{
970 const char *val = getenv(envname);
971 if (val)
972 *var = val;
973}
974
975void http_init(struct remote *remote, const char *url, int proactive_auth)
976{
977 char *low_speed_limit;
978 char *low_speed_time;
979 char *normalized_url;
980 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
981
982 config.section = "http";
983 config.key = NULL;
984 config.collect_fn = http_options;
985 config.cascade_fn = git_default_config;
986 config.cb = NULL;
987
988 http_is_verbose = 0;
989 normalized_url = url_normalize(url, &config.url);
990
991 git_config(urlmatch_config_entry, &config);
992 free(normalized_url);
993
994 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
995 die("curl_global_init failed");
996
997 http_proactive_auth = proactive_auth;
998
999 if (remote && remote->http_proxy)
1000 curl_http_proxy = xstrdup(remote->http_proxy);
1001
1002 if (remote)
1003 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1004
1005 pragma_header = curl_slist_append(http_copy_default_headers(),
1006 "Pragma: no-cache");
1007 no_pragma_header = curl_slist_append(http_copy_default_headers(),
1008 "Pragma:");
1009
1010#ifdef USE_CURL_MULTI
1011 {
1012 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1013 if (http_max_requests != NULL)
1014 max_requests = atoi(http_max_requests);
1015 }
1016
1017 curlm = curl_multi_init();
1018 if (!curlm)
1019 die("curl_multi_init failed");
1020#endif
1021
1022 if (getenv("GIT_SSL_NO_VERIFY"))
1023 curl_ssl_verify = 0;
1024
1025 set_from_env(&ssl_cert, "GIT_SSL_CERT");
1026#if LIBCURL_VERSION_NUM >= 0x070903
1027 set_from_env(&ssl_key, "GIT_SSL_KEY");
1028#endif
1029#if LIBCURL_VERSION_NUM >= 0x070908
1030 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1031#endif
1032 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1033
1034 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1035
1036 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1037 if (low_speed_limit != NULL)
1038 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1039 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1040 if (low_speed_time != NULL)
1041 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1042
1043 if (curl_ssl_verify == -1)
1044 curl_ssl_verify = 1;
1045
1046 curl_session_count = 0;
1047#ifdef USE_CURL_MULTI
1048 if (max_requests < 1)
1049 max_requests = DEFAULT_MAX_REQUESTS;
1050#endif
1051
1052 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1053 curl_ftp_no_epsv = 1;
1054
1055 if (url) {
1056 credential_from_url(&http_auth, url);
1057 if (!ssl_cert_password_required &&
1058 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1059 starts_with(url, "https://"))
1060 ssl_cert_password_required = 1;
1061 }
1062
1063#ifndef NO_CURL_EASY_DUPHANDLE
1064 curl_default = get_curl_handle();
1065#endif
1066}
1067
1068void http_cleanup(void)
1069{
1070 struct active_request_slot *slot = active_queue_head;
1071
1072 while (slot != NULL) {
1073 struct active_request_slot *next = slot->next;
1074 if (slot->curl != NULL) {
1075 xmulti_remove_handle(slot);
1076 curl_easy_cleanup(slot->curl);
1077 }
1078 free(slot);
1079 slot = next;
1080 }
1081 active_queue_head = NULL;
1082
1083#ifndef NO_CURL_EASY_DUPHANDLE
1084 curl_easy_cleanup(curl_default);
1085#endif
1086
1087#ifdef USE_CURL_MULTI
1088 curl_multi_cleanup(curlm);
1089#endif
1090 curl_global_cleanup();
1091
1092 curl_slist_free_all(extra_http_headers);
1093 extra_http_headers = NULL;
1094
1095 curl_slist_free_all(pragma_header);
1096 pragma_header = NULL;
1097
1098 curl_slist_free_all(no_pragma_header);
1099 no_pragma_header = NULL;
1100
1101 if (curl_http_proxy) {
1102 free((void *)curl_http_proxy);
1103 curl_http_proxy = NULL;
1104 }
1105
1106 if (proxy_auth.password) {
1107 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1108 FREE_AND_NULL(proxy_auth.password);
1109 }
1110
1111 free((void *)curl_proxyuserpwd);
1112 curl_proxyuserpwd = NULL;
1113
1114 free((void *)http_proxy_authmethod);
1115 http_proxy_authmethod = NULL;
1116
1117 if (cert_auth.password != NULL) {
1118 memset(cert_auth.password, 0, strlen(cert_auth.password));
1119 FREE_AND_NULL(cert_auth.password);
1120 }
1121 ssl_cert_password_required = 0;
1122
1123 FREE_AND_NULL(cached_accept_language);
1124}
1125
1126struct active_request_slot *get_active_slot(void)
1127{
1128 struct active_request_slot *slot = active_queue_head;
1129 struct active_request_slot *newslot;
1130
1131#ifdef USE_CURL_MULTI
1132 int num_transfers;
1133
1134 /* Wait for a slot to open up if the queue is full */
1135 while (active_requests >= max_requests) {
1136 curl_multi_perform(curlm, &num_transfers);
1137 if (num_transfers < active_requests)
1138 process_curl_messages();
1139 }
1140#endif
1141
1142 while (slot != NULL && slot->in_use)
1143 slot = slot->next;
1144
1145 if (slot == NULL) {
1146 newslot = xmalloc(sizeof(*newslot));
1147 newslot->curl = NULL;
1148 newslot->in_use = 0;
1149 newslot->next = NULL;
1150
1151 slot = active_queue_head;
1152 if (slot == NULL) {
1153 active_queue_head = newslot;
1154 } else {
1155 while (slot->next != NULL)
1156 slot = slot->next;
1157 slot->next = newslot;
1158 }
1159 slot = newslot;
1160 }
1161
1162 if (slot->curl == NULL) {
1163#ifdef NO_CURL_EASY_DUPHANDLE
1164 slot->curl = get_curl_handle();
1165#else
1166 slot->curl = curl_easy_duphandle(curl_default);
1167#endif
1168 curl_session_count++;
1169 }
1170
1171 active_requests++;
1172 slot->in_use = 1;
1173 slot->results = NULL;
1174 slot->finished = NULL;
1175 slot->callback_data = NULL;
1176 slot->callback_func = NULL;
1177 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1178 if (curl_save_cookies)
1179 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1180 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1181 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1182 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1183 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1184 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1185 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1186 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1187 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1188 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1189 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1190
1191 /*
1192 * Default following to off unless "ALWAYS" is configured; this gives
1193 * callers a sane starting point, and they can tweak for individual
1194 * HTTP_FOLLOW_* cases themselves.
1195 */
1196 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1197 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1198 else
1199 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1200
1201#if LIBCURL_VERSION_NUM >= 0x070a08
1202 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1203#endif
1204#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1205 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1206#endif
1207 if (http_auth.password || curl_empty_auth_enabled())
1208 init_curl_http_auth(slot->curl);
1209
1210 return slot;
1211}
1212
1213int start_active_slot(struct active_request_slot *slot)
1214{
1215#ifdef USE_CURL_MULTI
1216 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1217 int num_transfers;
1218
1219 if (curlm_result != CURLM_OK &&
1220 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1221 warning("curl_multi_add_handle failed: %s",
1222 curl_multi_strerror(curlm_result));
1223 active_requests--;
1224 slot->in_use = 0;
1225 return 0;
1226 }
1227
1228 /*
1229 * We know there must be something to do, since we just added
1230 * something.
1231 */
1232 curl_multi_perform(curlm, &num_transfers);
1233#endif
1234 return 1;
1235}
1236
1237#ifdef USE_CURL_MULTI
1238struct fill_chain {
1239 void *data;
1240 int (*fill)(void *);
1241 struct fill_chain *next;
1242};
1243
1244static struct fill_chain *fill_cfg;
1245
1246void add_fill_function(void *data, int (*fill)(void *))
1247{
1248 struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1249 struct fill_chain **linkp = &fill_cfg;
1250 new_fill->data = data;
1251 new_fill->fill = fill;
1252 new_fill->next = NULL;
1253 while (*linkp)
1254 linkp = &(*linkp)->next;
1255 *linkp = new_fill;
1256}
1257
1258void fill_active_slots(void)
1259{
1260 struct active_request_slot *slot = active_queue_head;
1261
1262 while (active_requests < max_requests) {
1263 struct fill_chain *fill;
1264 for (fill = fill_cfg; fill; fill = fill->next)
1265 if (fill->fill(fill->data))
1266 break;
1267
1268 if (!fill)
1269 break;
1270 }
1271
1272 while (slot != NULL) {
1273 if (!slot->in_use && slot->curl != NULL
1274 && curl_session_count > min_curl_sessions) {
1275 curl_easy_cleanup(slot->curl);
1276 slot->curl = NULL;
1277 curl_session_count--;
1278 }
1279 slot = slot->next;
1280 }
1281}
1282
1283void step_active_slots(void)
1284{
1285 int num_transfers;
1286 CURLMcode curlm_result;
1287
1288 do {
1289 curlm_result = curl_multi_perform(curlm, &num_transfers);
1290 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1291 if (num_transfers < active_requests) {
1292 process_curl_messages();
1293 fill_active_slots();
1294 }
1295}
1296#endif
1297
1298void run_active_slot(struct active_request_slot *slot)
1299{
1300#ifdef USE_CURL_MULTI
1301 fd_set readfds;
1302 fd_set writefds;
1303 fd_set excfds;
1304 int max_fd;
1305 struct timeval select_timeout;
1306 int finished = 0;
1307
1308 slot->finished = &finished;
1309 while (!finished) {
1310 step_active_slots();
1311
1312 if (slot->in_use) {
1313#if LIBCURL_VERSION_NUM >= 0x070f04
1314 long curl_timeout;
1315 curl_multi_timeout(curlm, &curl_timeout);
1316 if (curl_timeout == 0) {
1317 continue;
1318 } else if (curl_timeout == -1) {
1319 select_timeout.tv_sec = 0;
1320 select_timeout.tv_usec = 50000;
1321 } else {
1322 select_timeout.tv_sec = curl_timeout / 1000;
1323 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1324 }
1325#else
1326 select_timeout.tv_sec = 0;
1327 select_timeout.tv_usec = 50000;
1328#endif
1329
1330 max_fd = -1;
1331 FD_ZERO(&readfds);
1332 FD_ZERO(&writefds);
1333 FD_ZERO(&excfds);
1334 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1335
1336 /*
1337 * It can happen that curl_multi_timeout returns a pathologically
1338 * long timeout when curl_multi_fdset returns no file descriptors
1339 * to read. See commit message for more details.
1340 */
1341 if (max_fd < 0 &&
1342 (select_timeout.tv_sec > 0 ||
1343 select_timeout.tv_usec > 50000)) {
1344 select_timeout.tv_sec = 0;
1345 select_timeout.tv_usec = 50000;
1346 }
1347
1348 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1349 }
1350 }
1351#else
1352 while (slot->in_use) {
1353 slot->curl_result = curl_easy_perform(slot->curl);
1354 finish_active_slot(slot);
1355 }
1356#endif
1357}
1358
1359static void release_active_slot(struct active_request_slot *slot)
1360{
1361 closedown_active_slot(slot);
1362 if (slot->curl) {
1363 xmulti_remove_handle(slot);
1364 if (curl_session_count > min_curl_sessions) {
1365 curl_easy_cleanup(slot->curl);
1366 slot->curl = NULL;
1367 curl_session_count--;
1368 }
1369 }
1370#ifdef USE_CURL_MULTI
1371 fill_active_slots();
1372#endif
1373}
1374
1375void finish_all_active_slots(void)
1376{
1377 struct active_request_slot *slot = active_queue_head;
1378
1379 while (slot != NULL)
1380 if (slot->in_use) {
1381 run_active_slot(slot);
1382 slot = active_queue_head;
1383 } else {
1384 slot = slot->next;
1385 }
1386}
1387
1388/* Helpers for modifying and creating URLs */
1389static inline int needs_quote(int ch)
1390{
1391 if (((ch >= 'A') && (ch <= 'Z'))
1392 || ((ch >= 'a') && (ch <= 'z'))
1393 || ((ch >= '0') && (ch <= '9'))
1394 || (ch == '/')
1395 || (ch == '-')
1396 || (ch == '.'))
1397 return 0;
1398 return 1;
1399}
1400
1401static char *quote_ref_url(const char *base, const char *ref)
1402{
1403 struct strbuf buf = STRBUF_INIT;
1404 const char *cp;
1405 int ch;
1406
1407 end_url_with_slash(&buf, base);
1408
1409 for (cp = ref; (ch = *cp) != 0; cp++)
1410 if (needs_quote(ch))
1411 strbuf_addf(&buf, "%%%02x", ch);
1412 else
1413 strbuf_addch(&buf, *cp);
1414
1415 return strbuf_detach(&buf, NULL);
1416}
1417
1418void append_remote_object_url(struct strbuf *buf, const char *url,
1419 const char *hex,
1420 int only_two_digit_prefix)
1421{
1422 end_url_with_slash(buf, url);
1423
1424 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1425 if (!only_two_digit_prefix)
1426 strbuf_addstr(buf, hex + 2);
1427}
1428
1429char *get_remote_object_url(const char *url, const char *hex,
1430 int only_two_digit_prefix)
1431{
1432 struct strbuf buf = STRBUF_INIT;
1433 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1434 return strbuf_detach(&buf, NULL);
1435}
1436
1437static int handle_curl_result(struct slot_results *results)
1438{
1439 /*
1440 * If we see a failing http code with CURLE_OK, we have turned off
1441 * FAILONERROR (to keep the server's custom error response), and should
1442 * translate the code into failure here.
1443 *
1444 * Likewise, if we see a redirect (30x code), that means we turned off
1445 * redirect-following, and we should treat the result as an error.
1446 */
1447 if (results->curl_result == CURLE_OK &&
1448 results->http_code >= 300) {
1449 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1450 /*
1451 * Normally curl will already have put the "reason phrase"
1452 * from the server into curl_errorstr; unfortunately without
1453 * FAILONERROR it is lost, so we can give only the numeric
1454 * status code.
1455 */
1456 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1457 "The requested URL returned error: %ld",
1458 results->http_code);
1459 }
1460
1461 if (results->curl_result == CURLE_OK) {
1462 credential_approve(&http_auth);
1463 if (proxy_auth.password)
1464 credential_approve(&proxy_auth);
1465 return HTTP_OK;
1466 } else if (missing_target(results))
1467 return HTTP_MISSING_TARGET;
1468 else if (results->http_code == 401) {
1469 if (http_auth.username && http_auth.password) {
1470 credential_reject(&http_auth);
1471 return HTTP_NOAUTH;
1472 } else {
1473#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1474 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1475 if (results->auth_avail) {
1476 http_auth_methods &= results->auth_avail;
1477 http_auth_methods_restricted = 1;
1478 }
1479#endif
1480 return HTTP_REAUTH;
1481 }
1482 } else {
1483 if (results->http_connectcode == 407)
1484 credential_reject(&proxy_auth);
1485#if LIBCURL_VERSION_NUM >= 0x070c00
1486 if (!curl_errorstr[0])
1487 strlcpy(curl_errorstr,
1488 curl_easy_strerror(results->curl_result),
1489 sizeof(curl_errorstr));
1490#endif
1491 return HTTP_ERROR;
1492 }
1493}
1494
1495int run_one_slot(struct active_request_slot *slot,
1496 struct slot_results *results)
1497{
1498 slot->results = results;
1499 if (!start_active_slot(slot)) {
1500 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1501 "failed to start HTTP request");
1502 return HTTP_START_FAILED;
1503 }
1504
1505 run_active_slot(slot);
1506 return handle_curl_result(results);
1507}
1508
1509struct curl_slist *http_copy_default_headers(void)
1510{
1511 struct curl_slist *headers = NULL, *h;
1512
1513 for (h = extra_http_headers; h; h = h->next)
1514 headers = curl_slist_append(headers, h->data);
1515
1516 return headers;
1517}
1518
1519static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1520{
1521 char *ptr;
1522 CURLcode ret;
1523
1524 strbuf_reset(buf);
1525 ret = curl_easy_getinfo(curl, info, &ptr);
1526 if (!ret && ptr)
1527 strbuf_addstr(buf, ptr);
1528 return ret;
1529}
1530
1531/*
1532 * Check for and extract a content-type parameter. "raw"
1533 * should be positioned at the start of the potential
1534 * parameter, with any whitespace already removed.
1535 *
1536 * "name" is the name of the parameter. The value is appended
1537 * to "out".
1538 */
1539static int extract_param(const char *raw, const char *name,
1540 struct strbuf *out)
1541{
1542 size_t len = strlen(name);
1543
1544 if (strncasecmp(raw, name, len))
1545 return -1;
1546 raw += len;
1547
1548 if (*raw != '=')
1549 return -1;
1550 raw++;
1551
1552 while (*raw && !isspace(*raw) && *raw != ';')
1553 strbuf_addch(out, *raw++);
1554 return 0;
1555}
1556
1557/*
1558 * Extract a normalized version of the content type, with any
1559 * spaces suppressed, all letters lowercased, and no trailing ";"
1560 * or parameters.
1561 *
1562 * Note that we will silently remove even invalid whitespace. For
1563 * example, "text / plain" is specifically forbidden by RFC 2616,
1564 * but "text/plain" is the only reasonable output, and this keeps
1565 * our code simple.
1566 *
1567 * If the "charset" argument is not NULL, store the value of any
1568 * charset parameter there.
1569 *
1570 * Example:
1571 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1572 * "text / plain" -> "text/plain"
1573 */
1574static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1575 struct strbuf *charset)
1576{
1577 const char *p;
1578
1579 strbuf_reset(type);
1580 strbuf_grow(type, raw->len);
1581 for (p = raw->buf; *p; p++) {
1582 if (isspace(*p))
1583 continue;
1584 if (*p == ';') {
1585 p++;
1586 break;
1587 }
1588 strbuf_addch(type, tolower(*p));
1589 }
1590
1591 if (!charset)
1592 return;
1593
1594 strbuf_reset(charset);
1595 while (*p) {
1596 while (isspace(*p) || *p == ';')
1597 p++;
1598 if (!extract_param(p, "charset", charset))
1599 return;
1600 while (*p && !isspace(*p))
1601 p++;
1602 }
1603
1604 if (!charset->len && starts_with(type->buf, "text/"))
1605 strbuf_addstr(charset, "ISO-8859-1");
1606}
1607
1608static void write_accept_language(struct strbuf *buf)
1609{
1610 /*
1611 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1612 * that, q-value will be smaller than 0.001, the minimum q-value the
1613 * HTTP specification allows. See
1614 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1615 */
1616 const int MAX_DECIMAL_PLACES = 3;
1617 const int MAX_LANGUAGE_TAGS = 1000;
1618 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1619 char **language_tags = NULL;
1620 int num_langs = 0;
1621 const char *s = get_preferred_languages();
1622 int i;
1623 struct strbuf tag = STRBUF_INIT;
1624
1625 /* Don't add Accept-Language header if no language is preferred. */
1626 if (!s)
1627 return;
1628
1629 /*
1630 * Split the colon-separated string of preferred languages into
1631 * language_tags array.
1632 */
1633 do {
1634 /* collect language tag */
1635 for (; *s && (isalnum(*s) || *s == '_'); s++)
1636 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1637
1638 /* skip .codeset, @modifier and any other unnecessary parts */
1639 while (*s && *s != ':')
1640 s++;
1641
1642 if (tag.len) {
1643 num_langs++;
1644 REALLOC_ARRAY(language_tags, num_langs);
1645 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1646 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1647 break;
1648 }
1649 } while (*s++);
1650
1651 /* write Accept-Language header into buf */
1652 if (num_langs) {
1653 int last_buf_len = 0;
1654 int max_q;
1655 int decimal_places;
1656 char q_format[32];
1657
1658 /* add '*' */
1659 REALLOC_ARRAY(language_tags, num_langs + 1);
1660 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1661
1662 /* compute decimal_places */
1663 for (max_q = 1, decimal_places = 0;
1664 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1665 decimal_places++, max_q *= 10)
1666 ;
1667
1668 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1669
1670 strbuf_addstr(buf, "Accept-Language: ");
1671
1672 for (i = 0; i < num_langs; i++) {
1673 if (i > 0)
1674 strbuf_addstr(buf, ", ");
1675
1676 strbuf_addstr(buf, language_tags[i]);
1677
1678 if (i > 0)
1679 strbuf_addf(buf, q_format, max_q - i);
1680
1681 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1682 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1683 break;
1684 }
1685
1686 last_buf_len = buf->len;
1687 }
1688 }
1689
1690 /* free language tags -- last one is a static '*' */
1691 for (i = 0; i < num_langs - 1; i++)
1692 free(language_tags[i]);
1693 free(language_tags);
1694}
1695
1696/*
1697 * Get an Accept-Language header which indicates user's preferred languages.
1698 *
1699 * Examples:
1700 * LANGUAGE= -> ""
1701 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1702 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1703 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1704 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1705 * LANGUAGE= LANG=C -> ""
1706 */
1707static const char *get_accept_language(void)
1708{
1709 if (!cached_accept_language) {
1710 struct strbuf buf = STRBUF_INIT;
1711 write_accept_language(&buf);
1712 if (buf.len > 0)
1713 cached_accept_language = strbuf_detach(&buf, NULL);
1714 }
1715
1716 return cached_accept_language;
1717}
1718
1719static void http_opt_request_remainder(CURL *curl, off_t pos)
1720{
1721 char buf[128];
1722 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1723 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1724}
1725
1726/* http_request() targets */
1727#define HTTP_REQUEST_STRBUF 0
1728#define HTTP_REQUEST_FILE 1
1729
1730static int http_request(const char *url,
1731 void *result, int target,
1732 const struct http_get_options *options)
1733{
1734 struct active_request_slot *slot;
1735 struct slot_results results;
1736 struct curl_slist *headers = http_copy_default_headers();
1737 struct strbuf buf = STRBUF_INIT;
1738 const char *accept_language;
1739 int ret;
1740
1741 slot = get_active_slot();
1742 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1743
1744 if (result == NULL) {
1745 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1746 } else {
1747 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1748 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1749
1750 if (target == HTTP_REQUEST_FILE) {
1751 off_t posn = ftello(result);
1752 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1753 fwrite);
1754 if (posn > 0)
1755 http_opt_request_remainder(slot->curl, posn);
1756 } else
1757 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1758 fwrite_buffer);
1759 }
1760
1761 accept_language = get_accept_language();
1762
1763 if (accept_language)
1764 headers = curl_slist_append(headers, accept_language);
1765
1766 strbuf_addstr(&buf, "Pragma:");
1767 if (options && options->no_cache)
1768 strbuf_addstr(&buf, " no-cache");
1769 if (options && options->keep_error)
1770 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1771 if (options && options->initial_request &&
1772 http_follow_config == HTTP_FOLLOW_INITIAL)
1773 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1774
1775 headers = curl_slist_append(headers, buf.buf);
1776
1777 /* Add additional headers here */
1778 if (options && options->extra_headers) {
1779 const struct string_list_item *item;
1780 for_each_string_list_item(item, options->extra_headers) {
1781 headers = curl_slist_append(headers, item->string);
1782 }
1783 }
1784
1785 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1786 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1787 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1788
1789 ret = run_one_slot(slot, &results);
1790
1791 if (options && options->content_type) {
1792 struct strbuf raw = STRBUF_INIT;
1793 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1794 extract_content_type(&raw, options->content_type,
1795 options->charset);
1796 strbuf_release(&raw);
1797 }
1798
1799 if (options && options->effective_url)
1800 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1801 options->effective_url);
1802
1803 curl_slist_free_all(headers);
1804 strbuf_release(&buf);
1805
1806 return ret;
1807}
1808
1809/*
1810 * Update the "base" url to a more appropriate value, as deduced by
1811 * redirects seen when requesting a URL starting with "url".
1812 *
1813 * The "asked" parameter is a URL that we asked curl to access, and must begin
1814 * with "base".
1815 *
1816 * The "got" parameter is the URL that curl reported to us as where we ended
1817 * up.
1818 *
1819 * Returns 1 if we updated the base url, 0 otherwise.
1820 *
1821 * Our basic strategy is to compare "base" and "asked" to find the bits
1822 * specific to our request. We then strip those bits off of "got" to yield the
1823 * new base. So for example, if our base is "http://example.com/foo.git",
1824 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1825 * with "https://other.example.com/foo.git/info/refs". We would want the
1826 * new URL to become "https://other.example.com/foo.git".
1827 *
1828 * Note that this assumes a sane redirect scheme. It's entirely possible
1829 * in the example above to end up at a URL that does not even end in
1830 * "info/refs". In such a case we die. There's not much we can do, such a
1831 * scheme is unlikely to represent a real git repository, and failing to
1832 * rewrite the base opens options for malicious redirects to do funny things.
1833 */
1834static int update_url_from_redirect(struct strbuf *base,
1835 const char *asked,
1836 const struct strbuf *got)
1837{
1838 const char *tail;
1839 size_t new_len;
1840
1841 if (!strcmp(asked, got->buf))
1842 return 0;
1843
1844 if (!skip_prefix(asked, base->buf, &tail))
1845 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1846 asked, base->buf);
1847
1848 new_len = got->len;
1849 if (!strip_suffix_mem(got->buf, &new_len, tail))
1850 die(_("unable to update url base from redirection:\n"
1851 " asked for: %s\n"
1852 " redirect: %s"),
1853 asked, got->buf);
1854
1855 strbuf_reset(base);
1856 strbuf_add(base, got->buf, new_len);
1857
1858 return 1;
1859}
1860
1861static int http_request_reauth(const char *url,
1862 void *result, int target,
1863 struct http_get_options *options)
1864{
1865 int ret = http_request(url, result, target, options);
1866
1867 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1868 return ret;
1869
1870 if (options && options->effective_url && options->base_url) {
1871 if (update_url_from_redirect(options->base_url,
1872 url, options->effective_url)) {
1873 credential_from_url(&http_auth, options->base_url->buf);
1874 url = options->effective_url->buf;
1875 }
1876 }
1877
1878 if (ret != HTTP_REAUTH)
1879 return ret;
1880
1881 /*
1882 * If we are using KEEP_ERROR, the previous request may have
1883 * put cruft into our output stream; we should clear it out before
1884 * making our next request. We only know how to do this for
1885 * the strbuf case, but that is enough to satisfy current callers.
1886 */
1887 if (options && options->keep_error) {
1888 switch (target) {
1889 case HTTP_REQUEST_STRBUF:
1890 strbuf_reset(result);
1891 break;
1892 default:
1893 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1894 }
1895 }
1896
1897 credential_fill(&http_auth);
1898
1899 return http_request(url, result, target, options);
1900}
1901
1902int http_get_strbuf(const char *url,
1903 struct strbuf *result,
1904 struct http_get_options *options)
1905{
1906 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1907}
1908
1909/*
1910 * Downloads a URL and stores the result in the given file.
1911 *
1912 * If a previous interrupted download is detected (i.e. a previous temporary
1913 * file is still around) the download is resumed.
1914 */
1915static int http_get_file(const char *url, const char *filename,
1916 struct http_get_options *options)
1917{
1918 int ret;
1919 struct strbuf tmpfile = STRBUF_INIT;
1920 FILE *result;
1921
1922 strbuf_addf(&tmpfile, "%s.temp", filename);
1923 result = fopen(tmpfile.buf, "a");
1924 if (!result) {
1925 error("Unable to open local file %s", tmpfile.buf);
1926 ret = HTTP_ERROR;
1927 goto cleanup;
1928 }
1929
1930 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1931 fclose(result);
1932
1933 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1934 ret = HTTP_ERROR;
1935cleanup:
1936 strbuf_release(&tmpfile);
1937 return ret;
1938}
1939
1940int http_fetch_ref(const char *base, struct ref *ref)
1941{
1942 struct http_get_options options = {0};
1943 char *url;
1944 struct strbuf buffer = STRBUF_INIT;
1945 int ret = -1;
1946
1947 options.no_cache = 1;
1948
1949 url = quote_ref_url(base, ref->name);
1950 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1951 strbuf_rtrim(&buffer);
1952 if (buffer.len == 40)
1953 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1954 else if (starts_with(buffer.buf, "ref: ")) {
1955 ref->symref = xstrdup(buffer.buf + 5);
1956 ret = 0;
1957 }
1958 }
1959
1960 strbuf_release(&buffer);
1961 free(url);
1962 return ret;
1963}
1964
1965/* Helpers for fetching packs */
1966static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1967{
1968 char *url, *tmp;
1969 struct strbuf buf = STRBUF_INIT;
1970
1971 if (http_is_verbose)
1972 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1973
1974 end_url_with_slash(&buf, base_url);
1975 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1976 url = strbuf_detach(&buf, NULL);
1977
1978 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1979 tmp = strbuf_detach(&buf, NULL);
1980
1981 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1982 error("Unable to get pack index %s", url);
1983 FREE_AND_NULL(tmp);
1984 }
1985
1986 free(url);
1987 return tmp;
1988}
1989
1990static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1991 unsigned char *sha1, const char *base_url)
1992{
1993 struct packed_git *new_pack;
1994 char *tmp_idx = NULL;
1995 int ret;
1996
1997 if (has_pack_index(sha1)) {
1998 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1999 if (!new_pack)
2000 return -1; /* parse_pack_index() already issued error message */
2001 goto add_pack;
2002 }
2003
2004 tmp_idx = fetch_pack_index(sha1, base_url);
2005 if (!tmp_idx)
2006 return -1;
2007
2008 new_pack = parse_pack_index(sha1, tmp_idx);
2009 if (!new_pack) {
2010 unlink(tmp_idx);
2011 free(tmp_idx);
2012
2013 return -1; /* parse_pack_index() already issued error message */
2014 }
2015
2016 ret = verify_pack_index(new_pack);
2017 if (!ret) {
2018 close_pack_index(new_pack);
2019 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2020 }
2021 free(tmp_idx);
2022 if (ret)
2023 return -1;
2024
2025add_pack:
2026 new_pack->next = *packs_head;
2027 *packs_head = new_pack;
2028 return 0;
2029}
2030
2031int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2032{
2033 struct http_get_options options = {0};
2034 int ret = 0, i = 0;
2035 char *url, *data;
2036 struct strbuf buf = STRBUF_INIT;
2037 unsigned char sha1[20];
2038
2039 end_url_with_slash(&buf, base_url);
2040 strbuf_addstr(&buf, "objects/info/packs");
2041 url = strbuf_detach(&buf, NULL);
2042
2043 options.no_cache = 1;
2044 ret = http_get_strbuf(url, &buf, &options);
2045 if (ret != HTTP_OK)
2046 goto cleanup;
2047
2048 data = buf.buf;
2049 while (i < buf.len) {
2050 switch (data[i]) {
2051 case 'P':
2052 i++;
2053 if (i + 52 <= buf.len &&
2054 starts_with(data + i, " pack-") &&
2055 starts_with(data + i + 46, ".pack\n")) {
2056 get_sha1_hex(data + i + 6, sha1);
2057 fetch_and_setup_pack_index(packs_head, sha1,
2058 base_url);
2059 i += 51;
2060 break;
2061 }
2062 default:
2063 while (i < buf.len && data[i] != '\n')
2064 i++;
2065 }
2066 i++;
2067 }
2068
2069cleanup:
2070 free(url);
2071 return ret;
2072}
2073
2074void release_http_pack_request(struct http_pack_request *preq)
2075{
2076 if (preq->packfile != NULL) {
2077 fclose(preq->packfile);
2078 preq->packfile = NULL;
2079 }
2080 preq->slot = NULL;
2081 free(preq->url);
2082 free(preq);
2083}
2084
2085int finish_http_pack_request(struct http_pack_request *preq)
2086{
2087 struct packed_git **lst;
2088 struct packed_git *p = preq->target;
2089 char *tmp_idx;
2090 size_t len;
2091 struct child_process ip = CHILD_PROCESS_INIT;
2092
2093 close_pack_index(p);
2094
2095 fclose(preq->packfile);
2096 preq->packfile = NULL;
2097
2098 lst = preq->lst;
2099 while (*lst != p)
2100 lst = &((*lst)->next);
2101 *lst = (*lst)->next;
2102
2103 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2104 die("BUG: pack tmpfile does not end in .pack.temp?");
2105 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
2106
2107 argv_array_push(&ip.args, "index-pack");
2108 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2109 argv_array_push(&ip.args, preq->tmpfile);
2110 ip.git_cmd = 1;
2111 ip.no_stdin = 1;
2112 ip.no_stdout = 1;
2113
2114 if (run_command(&ip)) {
2115 unlink(preq->tmpfile);
2116 unlink(tmp_idx);
2117 free(tmp_idx);
2118 return -1;
2119 }
2120
2121 unlink(sha1_pack_index_name(p->sha1));
2122
2123 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2124 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2125 free(tmp_idx);
2126 return -1;
2127 }
2128
2129 install_packed_git(p);
2130 free(tmp_idx);
2131 return 0;
2132}
2133
2134struct http_pack_request *new_http_pack_request(
2135 struct packed_git *target, const char *base_url)
2136{
2137 off_t prev_posn = 0;
2138 struct strbuf buf = STRBUF_INIT;
2139 struct http_pack_request *preq;
2140
2141 preq = xcalloc(1, sizeof(*preq));
2142 preq->target = target;
2143
2144 end_url_with_slash(&buf, base_url);
2145 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2146 sha1_to_hex(target->sha1));
2147 preq->url = strbuf_detach(&buf, NULL);
2148
2149 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2150 sha1_pack_name(target->sha1));
2151 preq->packfile = fopen(preq->tmpfile, "a");
2152 if (!preq->packfile) {
2153 error("Unable to open local file %s for pack",
2154 preq->tmpfile);
2155 goto abort;
2156 }
2157
2158 preq->slot = get_active_slot();
2159 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2160 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2161 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2162 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2163 no_pragma_header);
2164
2165 /*
2166 * If there is data present from a previous transfer attempt,
2167 * resume where it left off
2168 */
2169 prev_posn = ftello(preq->packfile);
2170 if (prev_posn>0) {
2171 if (http_is_verbose)
2172 fprintf(stderr,
2173 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2174 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2175 http_opt_request_remainder(preq->slot->curl, prev_posn);
2176 }
2177
2178 return preq;
2179
2180abort:
2181 free(preq->url);
2182 free(preq);
2183 return NULL;
2184}
2185
2186/* Helpers for fetching objects (loose) */
2187static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2188 void *data)
2189{
2190 unsigned char expn[4096];
2191 size_t size = eltsize * nmemb;
2192 int posn = 0;
2193 struct http_object_request *freq = data;
2194 struct active_request_slot *slot = freq->slot;
2195
2196 if (slot) {
2197 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2198 &slot->http_code);
2199 if (c != CURLE_OK)
2200 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2201 curl_easy_strerror(c));
2202 if (slot->http_code >= 300)
2203 return size;
2204 }
2205
2206 do {
2207 ssize_t retval = xwrite(freq->localfile,
2208 (char *) ptr + posn, size - posn);
2209 if (retval < 0)
2210 return posn;
2211 posn += retval;
2212 } while (posn < size);
2213
2214 freq->stream.avail_in = size;
2215 freq->stream.next_in = (void *)ptr;
2216 do {
2217 freq->stream.next_out = expn;
2218 freq->stream.avail_out = sizeof(expn);
2219 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2220 git_SHA1_Update(&freq->c, expn,
2221 sizeof(expn) - freq->stream.avail_out);
2222 } while (freq->stream.avail_in && freq->zret == Z_OK);
2223 return size;
2224}
2225
2226struct http_object_request *new_http_object_request(const char *base_url,
2227 unsigned char *sha1)
2228{
2229 char *hex = sha1_to_hex(sha1);
2230 struct strbuf filename = STRBUF_INIT;
2231 char prevfile[PATH_MAX];
2232 int prevlocal;
2233 char prev_buf[PREV_BUF_SIZE];
2234 ssize_t prev_read = 0;
2235 off_t prev_posn = 0;
2236 struct http_object_request *freq;
2237
2238 freq = xcalloc(1, sizeof(*freq));
2239 hashcpy(freq->sha1, sha1);
2240 freq->localfile = -1;
2241
2242 sha1_file_name(&filename, sha1);
2243 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2244 "%s.temp", filename.buf);
2245
2246 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename.buf);
2247 unlink_or_warn(prevfile);
2248 rename(freq->tmpfile, prevfile);
2249 unlink_or_warn(freq->tmpfile);
2250 strbuf_release(&filename);
2251
2252 if (freq->localfile != -1)
2253 error("fd leakage in start: %d", freq->localfile);
2254 freq->localfile = open(freq->tmpfile,
2255 O_WRONLY | O_CREAT | O_EXCL, 0666);
2256 /*
2257 * This could have failed due to the "lazy directory creation";
2258 * try to mkdir the last path component.
2259 */
2260 if (freq->localfile < 0 && errno == ENOENT) {
2261 char *dir = strrchr(freq->tmpfile, '/');
2262 if (dir) {
2263 *dir = 0;
2264 mkdir(freq->tmpfile, 0777);
2265 *dir = '/';
2266 }
2267 freq->localfile = open(freq->tmpfile,
2268 O_WRONLY | O_CREAT | O_EXCL, 0666);
2269 }
2270
2271 if (freq->localfile < 0) {
2272 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2273 goto abort;
2274 }
2275
2276 git_inflate_init(&freq->stream);
2277
2278 git_SHA1_Init(&freq->c);
2279
2280 freq->url = get_remote_object_url(base_url, hex, 0);
2281
2282 /*
2283 * If a previous temp file is present, process what was already
2284 * fetched.
2285 */
2286 prevlocal = open(prevfile, O_RDONLY);
2287 if (prevlocal != -1) {
2288 do {
2289 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2290 if (prev_read>0) {
2291 if (fwrite_sha1_file(prev_buf,
2292 1,
2293 prev_read,
2294 freq) == prev_read) {
2295 prev_posn += prev_read;
2296 } else {
2297 prev_read = -1;
2298 }
2299 }
2300 } while (prev_read > 0);
2301 close(prevlocal);
2302 }
2303 unlink_or_warn(prevfile);
2304
2305 /*
2306 * Reset inflate/SHA1 if there was an error reading the previous temp
2307 * file; also rewind to the beginning of the local file.
2308 */
2309 if (prev_read == -1) {
2310 memset(&freq->stream, 0, sizeof(freq->stream));
2311 git_inflate_init(&freq->stream);
2312 git_SHA1_Init(&freq->c);
2313 if (prev_posn>0) {
2314 prev_posn = 0;
2315 lseek(freq->localfile, 0, SEEK_SET);
2316 if (ftruncate(freq->localfile, 0) < 0) {
2317 error_errno("Couldn't truncate temporary file %s",
2318 freq->tmpfile);
2319 goto abort;
2320 }
2321 }
2322 }
2323
2324 freq->slot = get_active_slot();
2325
2326 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2327 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2328 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2329 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2330 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2331 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2332
2333 /*
2334 * If we have successfully processed data from a previous fetch
2335 * attempt, only fetch the data we don't already have.
2336 */
2337 if (prev_posn>0) {
2338 if (http_is_verbose)
2339 fprintf(stderr,
2340 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2341 hex, (uintmax_t)prev_posn);
2342 http_opt_request_remainder(freq->slot->curl, prev_posn);
2343 }
2344
2345 return freq;
2346
2347abort:
2348 free(freq->url);
2349 free(freq);
2350 return NULL;
2351}
2352
2353void process_http_object_request(struct http_object_request *freq)
2354{
2355 if (freq->slot == NULL)
2356 return;
2357 freq->curl_result = freq->slot->curl_result;
2358 freq->http_code = freq->slot->http_code;
2359 freq->slot = NULL;
2360}
2361
2362int finish_http_object_request(struct http_object_request *freq)
2363{
2364 struct stat st;
2365 struct strbuf filename = STRBUF_INIT;
2366
2367 close(freq->localfile);
2368 freq->localfile = -1;
2369
2370 process_http_object_request(freq);
2371
2372 if (freq->http_code == 416) {
2373 warning("requested range invalid; we may already have all the data.");
2374 } else if (freq->curl_result != CURLE_OK) {
2375 if (stat(freq->tmpfile, &st) == 0)
2376 if (st.st_size == 0)
2377 unlink_or_warn(freq->tmpfile);
2378 return -1;
2379 }
2380
2381 git_inflate_end(&freq->stream);
2382 git_SHA1_Final(freq->real_sha1, &freq->c);
2383 if (freq->zret != Z_STREAM_END) {
2384 unlink_or_warn(freq->tmpfile);
2385 return -1;
2386 }
2387 if (hashcmp(freq->sha1, freq->real_sha1)) {
2388 unlink_or_warn(freq->tmpfile);
2389 return -1;
2390 }
2391
2392 sha1_file_name(&filename, freq->sha1);
2393 freq->rename = finalize_object_file(freq->tmpfile, filename.buf);
2394 strbuf_release(&filename);
2395
2396 return freq->rename;
2397}
2398
2399void abort_http_object_request(struct http_object_request *freq)
2400{
2401 unlink_or_warn(freq->tmpfile);
2402
2403 release_http_object_request(freq);
2404}
2405
2406void release_http_object_request(struct http_object_request *freq)
2407{
2408 if (freq->localfile != -1) {
2409 close(freq->localfile);
2410 freq->localfile = -1;
2411 }
2412 if (freq->url != NULL) {
2413 FREE_AND_NULL(freq->url);
2414 }
2415 if (freq->slot != NULL) {
2416 freq->slot->callback_func = NULL;
2417 freq->slot->callback_data = NULL;
2418 release_active_slot(freq->slot);
2419 freq->slot = NULL;
2420 }
2421}