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