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