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