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