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