connect & http: support -4 and -6 switches for remote operations
[git] / http.c
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "pack.h"
4 #include "sideband.h"
5 #include "run-command.h"
6 #include "url.h"
7 #include "urlmatch.h"
8 #include "credential.h"
9 #include "version.h"
10 #include "pkt-line.h"
11 #include "gettext.h"
12 #include "transport.h"
13
14 #if LIBCURL_VERSION_NUM >= 0x070a08
15 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
16 #else
17 long int git_curl_ipresolve;
18 #endif
19 int active_requests;
20 int http_is_verbose;
21 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
22
23 #if LIBCURL_VERSION_NUM >= 0x070a06
24 #define LIBCURL_CAN_HANDLE_AUTH_ANY
25 #endif
26
27 static int min_curl_sessions = 1;
28 static int curl_session_count;
29 #ifdef USE_CURL_MULTI
30 static int max_requests = -1;
31 static CURLM *curlm;
32 #endif
33 #ifndef NO_CURL_EASY_DUPHANDLE
34 static CURL *curl_default;
35 #endif
36
37 #define PREV_BUF_SIZE 4096
38
39 char curl_errorstr[CURL_ERROR_SIZE];
40
41 static int curl_ssl_verify = -1;
42 static int curl_ssl_try;
43 static const char *ssl_cert;
44 static const char *ssl_cipherlist;
45 static const char *ssl_version;
46 static struct {
47         const char *name;
48         long ssl_version;
49 } sslversions[] = {
50         { "sslv2", CURL_SSLVERSION_SSLv2 },
51         { "sslv3", CURL_SSLVERSION_SSLv3 },
52         { "tlsv1", CURL_SSLVERSION_TLSv1 },
53 #if LIBCURL_VERSION_NUM >= 0x072200
54         { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
55         { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
56         { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
57 #endif
58 };
59 #if LIBCURL_VERSION_NUM >= 0x070903
60 static const char *ssl_key;
61 #endif
62 #if LIBCURL_VERSION_NUM >= 0x070908
63 static const char *ssl_capath;
64 #endif
65 static const char *ssl_cainfo;
66 static long curl_low_speed_limit = -1;
67 static long curl_low_speed_time = -1;
68 static int curl_ftp_no_epsv;
69 static const char *curl_http_proxy;
70 static const char *curl_cookie_file;
71 static int curl_save_cookies;
72 struct credential http_auth = CREDENTIAL_INIT;
73 static int http_proactive_auth;
74 static const char *user_agent;
75
76 #if LIBCURL_VERSION_NUM >= 0x071700
77 /* Use CURLOPT_KEYPASSWD as is */
78 #elif LIBCURL_VERSION_NUM >= 0x070903
79 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
80 #else
81 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
82 #endif
83
84 static struct credential cert_auth = CREDENTIAL_INIT;
85 static int ssl_cert_password_required;
86 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
87 static unsigned long http_auth_methods = CURLAUTH_ANY;
88 #endif
89
90 static struct curl_slist *pragma_header;
91 static struct curl_slist *no_pragma_header;
92
93 static struct active_request_slot *active_queue_head;
94
95 static char *cached_accept_language;
96
97 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
98 {
99         size_t size = eltsize * nmemb;
100         struct buffer *buffer = buffer_;
101
102         if (size > buffer->buf.len - buffer->posn)
103                 size = buffer->buf.len - buffer->posn;
104         memcpy(ptr, buffer->buf.buf + buffer->posn, size);
105         buffer->posn += size;
106
107         return size;
108 }
109
110 #ifndef NO_CURL_IOCTL
111 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
112 {
113         struct buffer *buffer = clientp;
114
115         switch (cmd) {
116         case CURLIOCMD_NOP:
117                 return CURLIOE_OK;
118
119         case CURLIOCMD_RESTARTREAD:
120                 buffer->posn = 0;
121                 return CURLIOE_OK;
122
123         default:
124                 return CURLIOE_UNKNOWNCMD;
125         }
126 }
127 #endif
128
129 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
130 {
131         size_t size = eltsize * nmemb;
132         struct strbuf *buffer = buffer_;
133
134         strbuf_add(buffer, ptr, size);
135         return size;
136 }
137
138 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
139 {
140         return eltsize * nmemb;
141 }
142
143 static void closedown_active_slot(struct active_request_slot *slot)
144 {
145         active_requests--;
146         slot->in_use = 0;
147 }
148
149 static void finish_active_slot(struct active_request_slot *slot)
150 {
151         closedown_active_slot(slot);
152         curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
153
154         if (slot->finished != NULL)
155                 (*slot->finished) = 1;
156
157         /* Store slot results so they can be read after the slot is reused */
158         if (slot->results != NULL) {
159                 slot->results->curl_result = slot->curl_result;
160                 slot->results->http_code = slot->http_code;
161 #if LIBCURL_VERSION_NUM >= 0x070a08
162                 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
163                                   &slot->results->auth_avail);
164 #else
165                 slot->results->auth_avail = 0;
166 #endif
167         }
168
169         /* Run callback if appropriate */
170         if (slot->callback_func != NULL)
171                 slot->callback_func(slot->callback_data);
172 }
173
174 #ifdef USE_CURL_MULTI
175 static void process_curl_messages(void)
176 {
177         int num_messages;
178         struct active_request_slot *slot;
179         CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
180
181         while (curl_message != NULL) {
182                 if (curl_message->msg == CURLMSG_DONE) {
183                         int curl_result = curl_message->data.result;
184                         slot = active_queue_head;
185                         while (slot != NULL &&
186                                slot->curl != curl_message->easy_handle)
187                                 slot = slot->next;
188                         if (slot != NULL) {
189                                 curl_multi_remove_handle(curlm, slot->curl);
190                                 slot->curl_result = curl_result;
191                                 finish_active_slot(slot);
192                         } else {
193                                 fprintf(stderr, "Received DONE message for unknown request!\n");
194                         }
195                 } else {
196                         fprintf(stderr, "Unknown CURL message received: %d\n",
197                                 (int)curl_message->msg);
198                 }
199                 curl_message = curl_multi_info_read(curlm, &num_messages);
200         }
201 }
202 #endif
203
204 static int http_options(const char *var, const char *value, void *cb)
205 {
206         if (!strcmp("http.sslverify", var)) {
207                 curl_ssl_verify = git_config_bool(var, value);
208                 return 0;
209         }
210         if (!strcmp("http.sslcipherlist", var))
211                 return git_config_string(&ssl_cipherlist, var, value);
212         if (!strcmp("http.sslversion", var))
213                 return git_config_string(&ssl_version, var, value);
214         if (!strcmp("http.sslcert", var))
215                 return git_config_string(&ssl_cert, var, value);
216 #if LIBCURL_VERSION_NUM >= 0x070903
217         if (!strcmp("http.sslkey", var))
218                 return git_config_string(&ssl_key, var, value);
219 #endif
220 #if LIBCURL_VERSION_NUM >= 0x070908
221         if (!strcmp("http.sslcapath", var))
222                 return git_config_pathname(&ssl_capath, var, value);
223 #endif
224         if (!strcmp("http.sslcainfo", var))
225                 return git_config_pathname(&ssl_cainfo, var, value);
226         if (!strcmp("http.sslcertpasswordprotected", var)) {
227                 ssl_cert_password_required = git_config_bool(var, value);
228                 return 0;
229         }
230         if (!strcmp("http.ssltry", var)) {
231                 curl_ssl_try = git_config_bool(var, value);
232                 return 0;
233         }
234         if (!strcmp("http.minsessions", var)) {
235                 min_curl_sessions = git_config_int(var, value);
236 #ifndef USE_CURL_MULTI
237                 if (min_curl_sessions > 1)
238                         min_curl_sessions = 1;
239 #endif
240                 return 0;
241         }
242 #ifdef USE_CURL_MULTI
243         if (!strcmp("http.maxrequests", var)) {
244                 max_requests = git_config_int(var, value);
245                 return 0;
246         }
247 #endif
248         if (!strcmp("http.lowspeedlimit", var)) {
249                 curl_low_speed_limit = (long)git_config_int(var, value);
250                 return 0;
251         }
252         if (!strcmp("http.lowspeedtime", var)) {
253                 curl_low_speed_time = (long)git_config_int(var, value);
254                 return 0;
255         }
256
257         if (!strcmp("http.noepsv", var)) {
258                 curl_ftp_no_epsv = git_config_bool(var, value);
259                 return 0;
260         }
261         if (!strcmp("http.proxy", var))
262                 return git_config_string(&curl_http_proxy, var, value);
263
264         if (!strcmp("http.cookiefile", var))
265                 return git_config_string(&curl_cookie_file, var, value);
266         if (!strcmp("http.savecookies", var)) {
267                 curl_save_cookies = git_config_bool(var, value);
268                 return 0;
269         }
270
271         if (!strcmp("http.postbuffer", var)) {
272                 http_post_buffer = git_config_int(var, value);
273                 if (http_post_buffer < LARGE_PACKET_MAX)
274                         http_post_buffer = LARGE_PACKET_MAX;
275                 return 0;
276         }
277
278         if (!strcmp("http.useragent", var))
279                 return git_config_string(&user_agent, var, value);
280
281         /* Fall back on the default ones */
282         return git_default_config(var, value, cb);
283 }
284
285 static void init_curl_http_auth(CURL *result)
286 {
287         if (!http_auth.username)
288                 return;
289
290         credential_fill(&http_auth);
291
292 #if LIBCURL_VERSION_NUM >= 0x071301
293         curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
294         curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
295 #else
296         {
297                 static struct strbuf up = STRBUF_INIT;
298                 /*
299                  * Note that we assume we only ever have a single set of
300                  * credentials in a given program run, so we do not have
301                  * to worry about updating this buffer, only setting its
302                  * initial value.
303                  */
304                 if (!up.len)
305                         strbuf_addf(&up, "%s:%s",
306                                 http_auth.username, http_auth.password);
307                 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
308         }
309 #endif
310 }
311
312 static int has_cert_password(void)
313 {
314         if (ssl_cert == NULL || ssl_cert_password_required != 1)
315                 return 0;
316         if (!cert_auth.password) {
317                 cert_auth.protocol = xstrdup("cert");
318                 cert_auth.username = xstrdup("");
319                 cert_auth.path = xstrdup(ssl_cert);
320                 credential_fill(&cert_auth);
321         }
322         return 1;
323 }
324
325 #if LIBCURL_VERSION_NUM >= 0x071900
326 static void set_curl_keepalive(CURL *c)
327 {
328         curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
329 }
330
331 #elif LIBCURL_VERSION_NUM >= 0x071000
332 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
333 {
334         int ka = 1;
335         int rc;
336         socklen_t len = (socklen_t)sizeof(ka);
337
338         if (type != CURLSOCKTYPE_IPCXN)
339                 return 0;
340
341         rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
342         if (rc < 0)
343                 warning("unable to set SO_KEEPALIVE on socket %s",
344                         strerror(errno));
345
346         return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
347 }
348
349 static void set_curl_keepalive(CURL *c)
350 {
351         curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
352 }
353
354 #else
355 static void set_curl_keepalive(CURL *c)
356 {
357         /* not supported on older curl versions */
358 }
359 #endif
360
361 static CURL *get_curl_handle(void)
362 {
363         CURL *result = curl_easy_init();
364         long allowed_protocols = 0;
365
366         if (!result)
367                 die("curl_easy_init failed");
368
369         if (!curl_ssl_verify) {
370                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
371                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
372         } else {
373                 /* Verify authenticity of the peer's certificate */
374                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
375                 /* The name in the cert must match whom we tried to connect */
376                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
377         }
378
379 #if LIBCURL_VERSION_NUM >= 0x070907
380         curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
381 #endif
382 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
383         curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
384 #endif
385
386         if (http_proactive_auth)
387                 init_curl_http_auth(result);
388
389         if (getenv("GIT_SSL_VERSION"))
390                 ssl_version = getenv("GIT_SSL_VERSION");
391         if (ssl_version && *ssl_version) {
392                 int i;
393                 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
394                         if (!strcmp(ssl_version, sslversions[i].name)) {
395                                 curl_easy_setopt(result, CURLOPT_SSLVERSION,
396                                                  sslversions[i].ssl_version);
397                                 break;
398                         }
399                 }
400                 if (i == ARRAY_SIZE(sslversions))
401                         warning("unsupported ssl version %s: using default",
402                                 ssl_version);
403         }
404
405         if (getenv("GIT_SSL_CIPHER_LIST"))
406                 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
407         if (ssl_cipherlist != NULL && *ssl_cipherlist)
408                 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
409                                 ssl_cipherlist);
410
411         if (ssl_cert != NULL)
412                 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
413         if (has_cert_password())
414                 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
415 #if LIBCURL_VERSION_NUM >= 0x070903
416         if (ssl_key != NULL)
417                 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
418 #endif
419 #if LIBCURL_VERSION_NUM >= 0x070908
420         if (ssl_capath != NULL)
421                 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
422 #endif
423         if (ssl_cainfo != NULL)
424                 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
425
426         if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
427                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
428                                  curl_low_speed_limit);
429                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
430                                  curl_low_speed_time);
431         }
432
433         curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
434         curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
435 #if LIBCURL_VERSION_NUM >= 0x071301
436         curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
437 #elif LIBCURL_VERSION_NUM >= 0x071101
438         curl_easy_setopt(result, CURLOPT_POST301, 1);
439 #endif
440 #if LIBCURL_VERSION_NUM >= 0x071304
441         if (is_transport_allowed("http"))
442                 allowed_protocols |= CURLPROTO_HTTP;
443         if (is_transport_allowed("https"))
444                 allowed_protocols |= CURLPROTO_HTTPS;
445         if (is_transport_allowed("ftp"))
446                 allowed_protocols |= CURLPROTO_FTP;
447         if (is_transport_allowed("ftps"))
448                 allowed_protocols |= CURLPROTO_FTPS;
449         curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
450 #else
451         if (transport_restrict_protocols())
452                 warning("protocol restrictions not applied to curl redirects because\n"
453                         "your curl version is too old (>= 7.19.4)");
454 #endif
455
456         if (getenv("GIT_CURL_VERBOSE"))
457                 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
458
459         curl_easy_setopt(result, CURLOPT_USERAGENT,
460                 user_agent ? user_agent : git_user_agent());
461
462         if (curl_ftp_no_epsv)
463                 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
464
465 #ifdef CURLOPT_USE_SSL
466         if (curl_ssl_try)
467                 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
468 #endif
469
470         if (curl_http_proxy) {
471                 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
472 #if LIBCURL_VERSION_NUM >= 0x071800
473                 if (starts_with(curl_http_proxy, "socks5"))
474                         curl_easy_setopt(result,
475                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
476                 else if (starts_with(curl_http_proxy, "socks4a"))
477                         curl_easy_setopt(result,
478                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
479                 else if (starts_with(curl_http_proxy, "socks"))
480                         curl_easy_setopt(result,
481                                 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
482 #endif
483         }
484 #if LIBCURL_VERSION_NUM >= 0x070a07
485         curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
486 #endif
487
488         set_curl_keepalive(result);
489
490         return result;
491 }
492
493 static void set_from_env(const char **var, const char *envname)
494 {
495         const char *val = getenv(envname);
496         if (val)
497                 *var = val;
498 }
499
500 void http_init(struct remote *remote, const char *url, int proactive_auth)
501 {
502         char *low_speed_limit;
503         char *low_speed_time;
504         char *normalized_url;
505         struct urlmatch_config config = { STRING_LIST_INIT_DUP };
506
507         config.section = "http";
508         config.key = NULL;
509         config.collect_fn = http_options;
510         config.cascade_fn = git_default_config;
511         config.cb = NULL;
512
513         http_is_verbose = 0;
514         normalized_url = url_normalize(url, &config.url);
515
516         git_config(urlmatch_config_entry, &config);
517         free(normalized_url);
518
519         if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
520                 die("curl_global_init failed");
521
522         http_proactive_auth = proactive_auth;
523
524         if (remote && remote->http_proxy)
525                 curl_http_proxy = xstrdup(remote->http_proxy);
526
527         pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
528         no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
529
530 #ifdef USE_CURL_MULTI
531         {
532                 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
533                 if (http_max_requests != NULL)
534                         max_requests = atoi(http_max_requests);
535         }
536
537         curlm = curl_multi_init();
538         if (!curlm)
539                 die("curl_multi_init failed");
540 #endif
541
542         if (getenv("GIT_SSL_NO_VERIFY"))
543                 curl_ssl_verify = 0;
544
545         set_from_env(&ssl_cert, "GIT_SSL_CERT");
546 #if LIBCURL_VERSION_NUM >= 0x070903
547         set_from_env(&ssl_key, "GIT_SSL_KEY");
548 #endif
549 #if LIBCURL_VERSION_NUM >= 0x070908
550         set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
551 #endif
552         set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
553
554         set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
555
556         low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
557         if (low_speed_limit != NULL)
558                 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
559         low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
560         if (low_speed_time != NULL)
561                 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
562
563         if (curl_ssl_verify == -1)
564                 curl_ssl_verify = 1;
565
566         curl_session_count = 0;
567 #ifdef USE_CURL_MULTI
568         if (max_requests < 1)
569                 max_requests = DEFAULT_MAX_REQUESTS;
570 #endif
571
572         if (getenv("GIT_CURL_FTP_NO_EPSV"))
573                 curl_ftp_no_epsv = 1;
574
575         if (url) {
576                 credential_from_url(&http_auth, url);
577                 if (!ssl_cert_password_required &&
578                     getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
579                     starts_with(url, "https://"))
580                         ssl_cert_password_required = 1;
581         }
582
583 #ifndef NO_CURL_EASY_DUPHANDLE
584         curl_default = get_curl_handle();
585 #endif
586 }
587
588 void http_cleanup(void)
589 {
590         struct active_request_slot *slot = active_queue_head;
591
592         while (slot != NULL) {
593                 struct active_request_slot *next = slot->next;
594                 if (slot->curl != NULL) {
595 #ifdef USE_CURL_MULTI
596                         curl_multi_remove_handle(curlm, slot->curl);
597 #endif
598                         curl_easy_cleanup(slot->curl);
599                 }
600                 free(slot);
601                 slot = next;
602         }
603         active_queue_head = NULL;
604
605 #ifndef NO_CURL_EASY_DUPHANDLE
606         curl_easy_cleanup(curl_default);
607 #endif
608
609 #ifdef USE_CURL_MULTI
610         curl_multi_cleanup(curlm);
611 #endif
612         curl_global_cleanup();
613
614         curl_slist_free_all(pragma_header);
615         pragma_header = NULL;
616
617         curl_slist_free_all(no_pragma_header);
618         no_pragma_header = NULL;
619
620         if (curl_http_proxy) {
621                 free((void *)curl_http_proxy);
622                 curl_http_proxy = NULL;
623         }
624
625         if (cert_auth.password != NULL) {
626                 memset(cert_auth.password, 0, strlen(cert_auth.password));
627                 free(cert_auth.password);
628                 cert_auth.password = NULL;
629         }
630         ssl_cert_password_required = 0;
631
632         free(cached_accept_language);
633         cached_accept_language = NULL;
634 }
635
636 struct active_request_slot *get_active_slot(void)
637 {
638         struct active_request_slot *slot = active_queue_head;
639         struct active_request_slot *newslot;
640
641 #ifdef USE_CURL_MULTI
642         int num_transfers;
643
644         /* Wait for a slot to open up if the queue is full */
645         while (active_requests >= max_requests) {
646                 curl_multi_perform(curlm, &num_transfers);
647                 if (num_transfers < active_requests)
648                         process_curl_messages();
649         }
650 #endif
651
652         while (slot != NULL && slot->in_use)
653                 slot = slot->next;
654
655         if (slot == NULL) {
656                 newslot = xmalloc(sizeof(*newslot));
657                 newslot->curl = NULL;
658                 newslot->in_use = 0;
659                 newslot->next = NULL;
660
661                 slot = active_queue_head;
662                 if (slot == NULL) {
663                         active_queue_head = newslot;
664                 } else {
665                         while (slot->next != NULL)
666                                 slot = slot->next;
667                         slot->next = newslot;
668                 }
669                 slot = newslot;
670         }
671
672         if (slot->curl == NULL) {
673 #ifdef NO_CURL_EASY_DUPHANDLE
674                 slot->curl = get_curl_handle();
675 #else
676                 slot->curl = curl_easy_duphandle(curl_default);
677 #endif
678                 curl_session_count++;
679         }
680
681         active_requests++;
682         slot->in_use = 1;
683         slot->results = NULL;
684         slot->finished = NULL;
685         slot->callback_data = NULL;
686         slot->callback_func = NULL;
687         curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
688         if (curl_save_cookies)
689                 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
690         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
691         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
692         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
693         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
694         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
695         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
696         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
697         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
698         curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
699         curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
700
701 #if LIBCURL_VERSION_NUM >= 0x070a08
702         curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
703 #endif
704 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
705         curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
706 #endif
707         if (http_auth.password)
708                 init_curl_http_auth(slot->curl);
709
710         return slot;
711 }
712
713 int start_active_slot(struct active_request_slot *slot)
714 {
715 #ifdef USE_CURL_MULTI
716         CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
717         int num_transfers;
718
719         if (curlm_result != CURLM_OK &&
720             curlm_result != CURLM_CALL_MULTI_PERFORM) {
721                 active_requests--;
722                 slot->in_use = 0;
723                 return 0;
724         }
725
726         /*
727          * We know there must be something to do, since we just added
728          * something.
729          */
730         curl_multi_perform(curlm, &num_transfers);
731 #endif
732         return 1;
733 }
734
735 #ifdef USE_CURL_MULTI
736 struct fill_chain {
737         void *data;
738         int (*fill)(void *);
739         struct fill_chain *next;
740 };
741
742 static struct fill_chain *fill_cfg;
743
744 void add_fill_function(void *data, int (*fill)(void *))
745 {
746         struct fill_chain *new = xmalloc(sizeof(*new));
747         struct fill_chain **linkp = &fill_cfg;
748         new->data = data;
749         new->fill = fill;
750         new->next = NULL;
751         while (*linkp)
752                 linkp = &(*linkp)->next;
753         *linkp = new;
754 }
755
756 void fill_active_slots(void)
757 {
758         struct active_request_slot *slot = active_queue_head;
759
760         while (active_requests < max_requests) {
761                 struct fill_chain *fill;
762                 for (fill = fill_cfg; fill; fill = fill->next)
763                         if (fill->fill(fill->data))
764                                 break;
765
766                 if (!fill)
767                         break;
768         }
769
770         while (slot != NULL) {
771                 if (!slot->in_use && slot->curl != NULL
772                         && curl_session_count > min_curl_sessions) {
773                         curl_easy_cleanup(slot->curl);
774                         slot->curl = NULL;
775                         curl_session_count--;
776                 }
777                 slot = slot->next;
778         }
779 }
780
781 void step_active_slots(void)
782 {
783         int num_transfers;
784         CURLMcode curlm_result;
785
786         do {
787                 curlm_result = curl_multi_perform(curlm, &num_transfers);
788         } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
789         if (num_transfers < active_requests) {
790                 process_curl_messages();
791                 fill_active_slots();
792         }
793 }
794 #endif
795
796 void run_active_slot(struct active_request_slot *slot)
797 {
798 #ifdef USE_CURL_MULTI
799         fd_set readfds;
800         fd_set writefds;
801         fd_set excfds;
802         int max_fd;
803         struct timeval select_timeout;
804         int finished = 0;
805
806         slot->finished = &finished;
807         while (!finished) {
808                 step_active_slots();
809
810                 if (slot->in_use) {
811 #if LIBCURL_VERSION_NUM >= 0x070f04
812                         long curl_timeout;
813                         curl_multi_timeout(curlm, &curl_timeout);
814                         if (curl_timeout == 0) {
815                                 continue;
816                         } else if (curl_timeout == -1) {
817                                 select_timeout.tv_sec  = 0;
818                                 select_timeout.tv_usec = 50000;
819                         } else {
820                                 select_timeout.tv_sec  =  curl_timeout / 1000;
821                                 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
822                         }
823 #else
824                         select_timeout.tv_sec  = 0;
825                         select_timeout.tv_usec = 50000;
826 #endif
827
828                         max_fd = -1;
829                         FD_ZERO(&readfds);
830                         FD_ZERO(&writefds);
831                         FD_ZERO(&excfds);
832                         curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
833
834                         /*
835                          * It can happen that curl_multi_timeout returns a pathologically
836                          * long timeout when curl_multi_fdset returns no file descriptors
837                          * to read.  See commit message for more details.
838                          */
839                         if (max_fd < 0 &&
840                             (select_timeout.tv_sec > 0 ||
841                              select_timeout.tv_usec > 50000)) {
842                                 select_timeout.tv_sec  = 0;
843                                 select_timeout.tv_usec = 50000;
844                         }
845
846                         select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
847                 }
848         }
849 #else
850         while (slot->in_use) {
851                 slot->curl_result = curl_easy_perform(slot->curl);
852                 finish_active_slot(slot);
853         }
854 #endif
855 }
856
857 static void release_active_slot(struct active_request_slot *slot)
858 {
859         closedown_active_slot(slot);
860         if (slot->curl && curl_session_count > min_curl_sessions) {
861 #ifdef USE_CURL_MULTI
862                 curl_multi_remove_handle(curlm, slot->curl);
863 #endif
864                 curl_easy_cleanup(slot->curl);
865                 slot->curl = NULL;
866                 curl_session_count--;
867         }
868 #ifdef USE_CURL_MULTI
869         fill_active_slots();
870 #endif
871 }
872
873 void finish_all_active_slots(void)
874 {
875         struct active_request_slot *slot = active_queue_head;
876
877         while (slot != NULL)
878                 if (slot->in_use) {
879                         run_active_slot(slot);
880                         slot = active_queue_head;
881                 } else {
882                         slot = slot->next;
883                 }
884 }
885
886 /* Helpers for modifying and creating URLs */
887 static inline int needs_quote(int ch)
888 {
889         if (((ch >= 'A') && (ch <= 'Z'))
890                         || ((ch >= 'a') && (ch <= 'z'))
891                         || ((ch >= '0') && (ch <= '9'))
892                         || (ch == '/')
893                         || (ch == '-')
894                         || (ch == '.'))
895                 return 0;
896         return 1;
897 }
898
899 static char *quote_ref_url(const char *base, const char *ref)
900 {
901         struct strbuf buf = STRBUF_INIT;
902         const char *cp;
903         int ch;
904
905         end_url_with_slash(&buf, base);
906
907         for (cp = ref; (ch = *cp) != 0; cp++)
908                 if (needs_quote(ch))
909                         strbuf_addf(&buf, "%%%02x", ch);
910                 else
911                         strbuf_addch(&buf, *cp);
912
913         return strbuf_detach(&buf, NULL);
914 }
915
916 void append_remote_object_url(struct strbuf *buf, const char *url,
917                               const char *hex,
918                               int only_two_digit_prefix)
919 {
920         end_url_with_slash(buf, url);
921
922         strbuf_addf(buf, "objects/%.*s/", 2, hex);
923         if (!only_two_digit_prefix)
924                 strbuf_addf(buf, "%s", hex+2);
925 }
926
927 char *get_remote_object_url(const char *url, const char *hex,
928                             int only_two_digit_prefix)
929 {
930         struct strbuf buf = STRBUF_INIT;
931         append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
932         return strbuf_detach(&buf, NULL);
933 }
934
935 static int handle_curl_result(struct slot_results *results)
936 {
937         /*
938          * If we see a failing http code with CURLE_OK, we have turned off
939          * FAILONERROR (to keep the server's custom error response), and should
940          * translate the code into failure here.
941          */
942         if (results->curl_result == CURLE_OK &&
943             results->http_code >= 400) {
944                 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
945                 /*
946                  * Normally curl will already have put the "reason phrase"
947                  * from the server into curl_errorstr; unfortunately without
948                  * FAILONERROR it is lost, so we can give only the numeric
949                  * status code.
950                  */
951                 snprintf(curl_errorstr, sizeof(curl_errorstr),
952                          "The requested URL returned error: %ld",
953                          results->http_code);
954         }
955
956         if (results->curl_result == CURLE_OK) {
957                 credential_approve(&http_auth);
958                 return HTTP_OK;
959         } else if (missing_target(results))
960                 return HTTP_MISSING_TARGET;
961         else if (results->http_code == 401) {
962                 if (http_auth.username && http_auth.password) {
963                         credential_reject(&http_auth);
964                         return HTTP_NOAUTH;
965                 } else {
966 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
967                         http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
968 #endif
969                         return HTTP_REAUTH;
970                 }
971         } else {
972 #if LIBCURL_VERSION_NUM >= 0x070c00
973                 if (!curl_errorstr[0])
974                         strlcpy(curl_errorstr,
975                                 curl_easy_strerror(results->curl_result),
976                                 sizeof(curl_errorstr));
977 #endif
978                 return HTTP_ERROR;
979         }
980 }
981
982 int run_one_slot(struct active_request_slot *slot,
983                  struct slot_results *results)
984 {
985         slot->results = results;
986         if (!start_active_slot(slot)) {
987                 snprintf(curl_errorstr, sizeof(curl_errorstr),
988                          "failed to start HTTP request");
989                 return HTTP_START_FAILED;
990         }
991
992         run_active_slot(slot);
993         return handle_curl_result(results);
994 }
995
996 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
997 {
998         char *ptr;
999         CURLcode ret;
1000
1001         strbuf_reset(buf);
1002         ret = curl_easy_getinfo(curl, info, &ptr);
1003         if (!ret && ptr)
1004                 strbuf_addstr(buf, ptr);
1005         return ret;
1006 }
1007
1008 /*
1009  * Check for and extract a content-type parameter. "raw"
1010  * should be positioned at the start of the potential
1011  * parameter, with any whitespace already removed.
1012  *
1013  * "name" is the name of the parameter. The value is appended
1014  * to "out".
1015  */
1016 static int extract_param(const char *raw, const char *name,
1017                          struct strbuf *out)
1018 {
1019         size_t len = strlen(name);
1020
1021         if (strncasecmp(raw, name, len))
1022                 return -1;
1023         raw += len;
1024
1025         if (*raw != '=')
1026                 return -1;
1027         raw++;
1028
1029         while (*raw && !isspace(*raw) && *raw != ';')
1030                 strbuf_addch(out, *raw++);
1031         return 0;
1032 }
1033
1034 /*
1035  * Extract a normalized version of the content type, with any
1036  * spaces suppressed, all letters lowercased, and no trailing ";"
1037  * or parameters.
1038  *
1039  * Note that we will silently remove even invalid whitespace. For
1040  * example, "text / plain" is specifically forbidden by RFC 2616,
1041  * but "text/plain" is the only reasonable output, and this keeps
1042  * our code simple.
1043  *
1044  * If the "charset" argument is not NULL, store the value of any
1045  * charset parameter there.
1046  *
1047  * Example:
1048  *   "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1049  *   "text / plain" -> "text/plain"
1050  */
1051 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1052                                  struct strbuf *charset)
1053 {
1054         const char *p;
1055
1056         strbuf_reset(type);
1057         strbuf_grow(type, raw->len);
1058         for (p = raw->buf; *p; p++) {
1059                 if (isspace(*p))
1060                         continue;
1061                 if (*p == ';') {
1062                         p++;
1063                         break;
1064                 }
1065                 strbuf_addch(type, tolower(*p));
1066         }
1067
1068         if (!charset)
1069                 return;
1070
1071         strbuf_reset(charset);
1072         while (*p) {
1073                 while (isspace(*p) || *p == ';')
1074                         p++;
1075                 if (!extract_param(p, "charset", charset))
1076                         return;
1077                 while (*p && !isspace(*p))
1078                         p++;
1079         }
1080
1081         if (!charset->len && starts_with(type->buf, "text/"))
1082                 strbuf_addstr(charset, "ISO-8859-1");
1083 }
1084
1085 static void write_accept_language(struct strbuf *buf)
1086 {
1087         /*
1088          * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1089          * that, q-value will be smaller than 0.001, the minimum q-value the
1090          * HTTP specification allows. See
1091          * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1092          */
1093         const int MAX_DECIMAL_PLACES = 3;
1094         const int MAX_LANGUAGE_TAGS = 1000;
1095         const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1096         char **language_tags = NULL;
1097         int num_langs = 0;
1098         const char *s = get_preferred_languages();
1099         int i;
1100         struct strbuf tag = STRBUF_INIT;
1101
1102         /* Don't add Accept-Language header if no language is preferred. */
1103         if (!s)
1104                 return;
1105
1106         /*
1107          * Split the colon-separated string of preferred languages into
1108          * language_tags array.
1109          */
1110         do {
1111                 /* collect language tag */
1112                 for (; *s && (isalnum(*s) || *s == '_'); s++)
1113                         strbuf_addch(&tag, *s == '_' ? '-' : *s);
1114
1115                 /* skip .codeset, @modifier and any other unnecessary parts */
1116                 while (*s && *s != ':')
1117                         s++;
1118
1119                 if (tag.len) {
1120                         num_langs++;
1121                         REALLOC_ARRAY(language_tags, num_langs);
1122                         language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1123                         if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1124                                 break;
1125                 }
1126         } while (*s++);
1127
1128         /* write Accept-Language header into buf */
1129         if (num_langs) {
1130                 int last_buf_len = 0;
1131                 int max_q;
1132                 int decimal_places;
1133                 char q_format[32];
1134
1135                 /* add '*' */
1136                 REALLOC_ARRAY(language_tags, num_langs + 1);
1137                 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1138
1139                 /* compute decimal_places */
1140                 for (max_q = 1, decimal_places = 0;
1141                      max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1142                      decimal_places++, max_q *= 10)
1143                         ;
1144
1145                 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1146
1147                 strbuf_addstr(buf, "Accept-Language: ");
1148
1149                 for (i = 0; i < num_langs; i++) {
1150                         if (i > 0)
1151                                 strbuf_addstr(buf, ", ");
1152
1153                         strbuf_addstr(buf, language_tags[i]);
1154
1155                         if (i > 0)
1156                                 strbuf_addf(buf, q_format, max_q - i);
1157
1158                         if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1159                                 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1160                                 break;
1161                         }
1162
1163                         last_buf_len = buf->len;
1164                 }
1165         }
1166
1167         /* free language tags -- last one is a static '*' */
1168         for (i = 0; i < num_langs - 1; i++)
1169                 free(language_tags[i]);
1170         free(language_tags);
1171 }
1172
1173 /*
1174  * Get an Accept-Language header which indicates user's preferred languages.
1175  *
1176  * Examples:
1177  *   LANGUAGE= -> ""
1178  *   LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1179  *   LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1180  *   LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1181  *   LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1182  *   LANGUAGE= LANG=C -> ""
1183  */
1184 static const char *get_accept_language(void)
1185 {
1186         if (!cached_accept_language) {
1187                 struct strbuf buf = STRBUF_INIT;
1188                 write_accept_language(&buf);
1189                 if (buf.len > 0)
1190                         cached_accept_language = strbuf_detach(&buf, NULL);
1191         }
1192
1193         return cached_accept_language;
1194 }
1195
1196 static void http_opt_request_remainder(CURL *curl, off_t pos)
1197 {
1198         char buf[128];
1199         xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1200         curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1201 }
1202
1203 /* http_request() targets */
1204 #define HTTP_REQUEST_STRBUF     0
1205 #define HTTP_REQUEST_FILE       1
1206
1207 static int http_request(const char *url,
1208                         void *result, int target,
1209                         const struct http_get_options *options)
1210 {
1211         struct active_request_slot *slot;
1212         struct slot_results results;
1213         struct curl_slist *headers = NULL;
1214         struct strbuf buf = STRBUF_INIT;
1215         const char *accept_language;
1216         int ret;
1217
1218         slot = get_active_slot();
1219         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1220
1221         if (result == NULL) {
1222                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1223         } else {
1224                 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1225                 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1226
1227                 if (target == HTTP_REQUEST_FILE) {
1228                         off_t posn = ftello(result);
1229                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1230                                          fwrite);
1231                         if (posn > 0)
1232                                 http_opt_request_remainder(slot->curl, posn);
1233                 } else
1234                         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1235                                          fwrite_buffer);
1236         }
1237
1238         accept_language = get_accept_language();
1239
1240         if (accept_language)
1241                 headers = curl_slist_append(headers, accept_language);
1242
1243         strbuf_addstr(&buf, "Pragma:");
1244         if (options && options->no_cache)
1245                 strbuf_addstr(&buf, " no-cache");
1246         if (options && options->keep_error)
1247                 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1248
1249         headers = curl_slist_append(headers, buf.buf);
1250
1251         curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1252         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1253         curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1254
1255         ret = run_one_slot(slot, &results);
1256
1257         if (options && options->content_type) {
1258                 struct strbuf raw = STRBUF_INIT;
1259                 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1260                 extract_content_type(&raw, options->content_type,
1261                                      options->charset);
1262                 strbuf_release(&raw);
1263         }
1264
1265         if (options && options->effective_url)
1266                 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1267                                 options->effective_url);
1268
1269         curl_slist_free_all(headers);
1270         strbuf_release(&buf);
1271
1272         return ret;
1273 }
1274
1275 /*
1276  * Update the "base" url to a more appropriate value, as deduced by
1277  * redirects seen when requesting a URL starting with "url".
1278  *
1279  * The "asked" parameter is a URL that we asked curl to access, and must begin
1280  * with "base".
1281  *
1282  * The "got" parameter is the URL that curl reported to us as where we ended
1283  * up.
1284  *
1285  * Returns 1 if we updated the base url, 0 otherwise.
1286  *
1287  * Our basic strategy is to compare "base" and "asked" to find the bits
1288  * specific to our request. We then strip those bits off of "got" to yield the
1289  * new base. So for example, if our base is "http://example.com/foo.git",
1290  * and we ask for "http://example.com/foo.git/info/refs", we might end up
1291  * with "https://other.example.com/foo.git/info/refs". We would want the
1292  * new URL to become "https://other.example.com/foo.git".
1293  *
1294  * Note that this assumes a sane redirect scheme. It's entirely possible
1295  * in the example above to end up at a URL that does not even end in
1296  * "info/refs".  In such a case we simply punt, as there is not much we can
1297  * do (and such a scheme is unlikely to represent a real git repository,
1298  * which means we are likely about to abort anyway).
1299  */
1300 static int update_url_from_redirect(struct strbuf *base,
1301                                     const char *asked,
1302                                     const struct strbuf *got)
1303 {
1304         const char *tail;
1305         size_t tail_len;
1306
1307         if (!strcmp(asked, got->buf))
1308                 return 0;
1309
1310         if (!skip_prefix(asked, base->buf, &tail))
1311                 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1312                     asked, base->buf);
1313
1314         tail_len = strlen(tail);
1315
1316         if (got->len < tail_len ||
1317             strcmp(tail, got->buf + got->len - tail_len))
1318                 return 0; /* insane redirect scheme */
1319
1320         strbuf_reset(base);
1321         strbuf_add(base, got->buf, got->len - tail_len);
1322         return 1;
1323 }
1324
1325 static int http_request_reauth(const char *url,
1326                                void *result, int target,
1327                                struct http_get_options *options)
1328 {
1329         int ret = http_request(url, result, target, options);
1330
1331         if (options && options->effective_url && options->base_url) {
1332                 if (update_url_from_redirect(options->base_url,
1333                                              url, options->effective_url)) {
1334                         credential_from_url(&http_auth, options->base_url->buf);
1335                         url = options->effective_url->buf;
1336                 }
1337         }
1338
1339         if (ret != HTTP_REAUTH)
1340                 return ret;
1341
1342         /*
1343          * If we are using KEEP_ERROR, the previous request may have
1344          * put cruft into our output stream; we should clear it out before
1345          * making our next request. We only know how to do this for
1346          * the strbuf case, but that is enough to satisfy current callers.
1347          */
1348         if (options && options->keep_error) {
1349                 switch (target) {
1350                 case HTTP_REQUEST_STRBUF:
1351                         strbuf_reset(result);
1352                         break;
1353                 default:
1354                         die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1355                 }
1356         }
1357
1358         credential_fill(&http_auth);
1359
1360         return http_request(url, result, target, options);
1361 }
1362
1363 int http_get_strbuf(const char *url,
1364                     struct strbuf *result,
1365                     struct http_get_options *options)
1366 {
1367         return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1368 }
1369
1370 /*
1371  * Downloads a URL and stores the result in the given file.
1372  *
1373  * If a previous interrupted download is detected (i.e. a previous temporary
1374  * file is still around) the download is resumed.
1375  */
1376 static int http_get_file(const char *url, const char *filename,
1377                          struct http_get_options *options)
1378 {
1379         int ret;
1380         struct strbuf tmpfile = STRBUF_INIT;
1381         FILE *result;
1382
1383         strbuf_addf(&tmpfile, "%s.temp", filename);
1384         result = fopen(tmpfile.buf, "a");
1385         if (!result) {
1386                 error("Unable to open local file %s", tmpfile.buf);
1387                 ret = HTTP_ERROR;
1388                 goto cleanup;
1389         }
1390
1391         ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1392         fclose(result);
1393
1394         if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1395                 ret = HTTP_ERROR;
1396 cleanup:
1397         strbuf_release(&tmpfile);
1398         return ret;
1399 }
1400
1401 int http_fetch_ref(const char *base, struct ref *ref)
1402 {
1403         struct http_get_options options = {0};
1404         char *url;
1405         struct strbuf buffer = STRBUF_INIT;
1406         int ret = -1;
1407
1408         options.no_cache = 1;
1409
1410         url = quote_ref_url(base, ref->name);
1411         if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1412                 strbuf_rtrim(&buffer);
1413                 if (buffer.len == 40)
1414                         ret = get_oid_hex(buffer.buf, &ref->old_oid);
1415                 else if (starts_with(buffer.buf, "ref: ")) {
1416                         ref->symref = xstrdup(buffer.buf + 5);
1417                         ret = 0;
1418                 }
1419         }
1420
1421         strbuf_release(&buffer);
1422         free(url);
1423         return ret;
1424 }
1425
1426 /* Helpers for fetching packs */
1427 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1428 {
1429         char *url, *tmp;
1430         struct strbuf buf = STRBUF_INIT;
1431
1432         if (http_is_verbose)
1433                 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1434
1435         end_url_with_slash(&buf, base_url);
1436         strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1437         url = strbuf_detach(&buf, NULL);
1438
1439         strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1440         tmp = strbuf_detach(&buf, NULL);
1441
1442         if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1443                 error("Unable to get pack index %s", url);
1444                 free(tmp);
1445                 tmp = NULL;
1446         }
1447
1448         free(url);
1449         return tmp;
1450 }
1451
1452 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1453         unsigned char *sha1, const char *base_url)
1454 {
1455         struct packed_git *new_pack;
1456         char *tmp_idx = NULL;
1457         int ret;
1458
1459         if (has_pack_index(sha1)) {
1460                 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1461                 if (!new_pack)
1462                         return -1; /* parse_pack_index() already issued error message */
1463                 goto add_pack;
1464         }
1465
1466         tmp_idx = fetch_pack_index(sha1, base_url);
1467         if (!tmp_idx)
1468                 return -1;
1469
1470         new_pack = parse_pack_index(sha1, tmp_idx);
1471         if (!new_pack) {
1472                 unlink(tmp_idx);
1473                 free(tmp_idx);
1474
1475                 return -1; /* parse_pack_index() already issued error message */
1476         }
1477
1478         ret = verify_pack_index(new_pack);
1479         if (!ret) {
1480                 close_pack_index(new_pack);
1481                 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1482         }
1483         free(tmp_idx);
1484         if (ret)
1485                 return -1;
1486
1487 add_pack:
1488         new_pack->next = *packs_head;
1489         *packs_head = new_pack;
1490         return 0;
1491 }
1492
1493 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1494 {
1495         struct http_get_options options = {0};
1496         int ret = 0, i = 0;
1497         char *url, *data;
1498         struct strbuf buf = STRBUF_INIT;
1499         unsigned char sha1[20];
1500
1501         end_url_with_slash(&buf, base_url);
1502         strbuf_addstr(&buf, "objects/info/packs");
1503         url = strbuf_detach(&buf, NULL);
1504
1505         options.no_cache = 1;
1506         ret = http_get_strbuf(url, &buf, &options);
1507         if (ret != HTTP_OK)
1508                 goto cleanup;
1509
1510         data = buf.buf;
1511         while (i < buf.len) {
1512                 switch (data[i]) {
1513                 case 'P':
1514                         i++;
1515                         if (i + 52 <= buf.len &&
1516                             starts_with(data + i, " pack-") &&
1517                             starts_with(data + i + 46, ".pack\n")) {
1518                                 get_sha1_hex(data + i + 6, sha1);
1519                                 fetch_and_setup_pack_index(packs_head, sha1,
1520                                                       base_url);
1521                                 i += 51;
1522                                 break;
1523                         }
1524                 default:
1525                         while (i < buf.len && data[i] != '\n')
1526                                 i++;
1527                 }
1528                 i++;
1529         }
1530
1531 cleanup:
1532         free(url);
1533         return ret;
1534 }
1535
1536 void release_http_pack_request(struct http_pack_request *preq)
1537 {
1538         if (preq->packfile != NULL) {
1539                 fclose(preq->packfile);
1540                 preq->packfile = NULL;
1541         }
1542         preq->slot = NULL;
1543         free(preq->url);
1544         free(preq);
1545 }
1546
1547 int finish_http_pack_request(struct http_pack_request *preq)
1548 {
1549         struct packed_git **lst;
1550         struct packed_git *p = preq->target;
1551         char *tmp_idx;
1552         size_t len;
1553         struct child_process ip = CHILD_PROCESS_INIT;
1554         const char *ip_argv[8];
1555
1556         close_pack_index(p);
1557
1558         fclose(preq->packfile);
1559         preq->packfile = NULL;
1560
1561         lst = preq->lst;
1562         while (*lst != p)
1563                 lst = &((*lst)->next);
1564         *lst = (*lst)->next;
1565
1566         if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1567                 die("BUG: pack tmpfile does not end in .pack.temp?");
1568         tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1569
1570         ip_argv[0] = "index-pack";
1571         ip_argv[1] = "-o";
1572         ip_argv[2] = tmp_idx;
1573         ip_argv[3] = preq->tmpfile;
1574         ip_argv[4] = NULL;
1575
1576         ip.argv = ip_argv;
1577         ip.git_cmd = 1;
1578         ip.no_stdin = 1;
1579         ip.no_stdout = 1;
1580
1581         if (run_command(&ip)) {
1582                 unlink(preq->tmpfile);
1583                 unlink(tmp_idx);
1584                 free(tmp_idx);
1585                 return -1;
1586         }
1587
1588         unlink(sha1_pack_index_name(p->sha1));
1589
1590         if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1591          || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1592                 free(tmp_idx);
1593                 return -1;
1594         }
1595
1596         install_packed_git(p);
1597         free(tmp_idx);
1598         return 0;
1599 }
1600
1601 struct http_pack_request *new_http_pack_request(
1602         struct packed_git *target, const char *base_url)
1603 {
1604         off_t prev_posn = 0;
1605         struct strbuf buf = STRBUF_INIT;
1606         struct http_pack_request *preq;
1607
1608         preq = xcalloc(1, sizeof(*preq));
1609         preq->target = target;
1610
1611         end_url_with_slash(&buf, base_url);
1612         strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1613                 sha1_to_hex(target->sha1));
1614         preq->url = strbuf_detach(&buf, NULL);
1615
1616         snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1617                 sha1_pack_name(target->sha1));
1618         preq->packfile = fopen(preq->tmpfile, "a");
1619         if (!preq->packfile) {
1620                 error("Unable to open local file %s for pack",
1621                       preq->tmpfile);
1622                 goto abort;
1623         }
1624
1625         preq->slot = get_active_slot();
1626         curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1627         curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1628         curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1629         curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1630                 no_pragma_header);
1631
1632         /*
1633          * If there is data present from a previous transfer attempt,
1634          * resume where it left off
1635          */
1636         prev_posn = ftello(preq->packfile);
1637         if (prev_posn>0) {
1638                 if (http_is_verbose)
1639                         fprintf(stderr,
1640                                 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1641                                 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1642                 http_opt_request_remainder(preq->slot->curl, prev_posn);
1643         }
1644
1645         return preq;
1646
1647 abort:
1648         free(preq->url);
1649         free(preq);
1650         return NULL;
1651 }
1652
1653 /* Helpers for fetching objects (loose) */
1654 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1655                                void *data)
1656 {
1657         unsigned char expn[4096];
1658         size_t size = eltsize * nmemb;
1659         int posn = 0;
1660         struct http_object_request *freq =
1661                 (struct http_object_request *)data;
1662         do {
1663                 ssize_t retval = xwrite(freq->localfile,
1664                                         (char *) ptr + posn, size - posn);
1665                 if (retval < 0)
1666                         return posn;
1667                 posn += retval;
1668         } while (posn < size);
1669
1670         freq->stream.avail_in = size;
1671         freq->stream.next_in = (void *)ptr;
1672         do {
1673                 freq->stream.next_out = expn;
1674                 freq->stream.avail_out = sizeof(expn);
1675                 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1676                 git_SHA1_Update(&freq->c, expn,
1677                                 sizeof(expn) - freq->stream.avail_out);
1678         } while (freq->stream.avail_in && freq->zret == Z_OK);
1679         return size;
1680 }
1681
1682 struct http_object_request *new_http_object_request(const char *base_url,
1683         unsigned char *sha1)
1684 {
1685         char *hex = sha1_to_hex(sha1);
1686         const char *filename;
1687         char prevfile[PATH_MAX];
1688         int prevlocal;
1689         char prev_buf[PREV_BUF_SIZE];
1690         ssize_t prev_read = 0;
1691         off_t prev_posn = 0;
1692         struct http_object_request *freq;
1693
1694         freq = xcalloc(1, sizeof(*freq));
1695         hashcpy(freq->sha1, sha1);
1696         freq->localfile = -1;
1697
1698         filename = sha1_file_name(sha1);
1699         snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1700                  "%s.temp", filename);
1701
1702         snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1703         unlink_or_warn(prevfile);
1704         rename(freq->tmpfile, prevfile);
1705         unlink_or_warn(freq->tmpfile);
1706
1707         if (freq->localfile != -1)
1708                 error("fd leakage in start: %d", freq->localfile);
1709         freq->localfile = open(freq->tmpfile,
1710                                O_WRONLY | O_CREAT | O_EXCL, 0666);
1711         /*
1712          * This could have failed due to the "lazy directory creation";
1713          * try to mkdir the last path component.
1714          */
1715         if (freq->localfile < 0 && errno == ENOENT) {
1716                 char *dir = strrchr(freq->tmpfile, '/');
1717                 if (dir) {
1718                         *dir = 0;
1719                         mkdir(freq->tmpfile, 0777);
1720                         *dir = '/';
1721                 }
1722                 freq->localfile = open(freq->tmpfile,
1723                                        O_WRONLY | O_CREAT | O_EXCL, 0666);
1724         }
1725
1726         if (freq->localfile < 0) {
1727                 error("Couldn't create temporary file %s: %s",
1728                       freq->tmpfile, strerror(errno));
1729                 goto abort;
1730         }
1731
1732         git_inflate_init(&freq->stream);
1733
1734         git_SHA1_Init(&freq->c);
1735
1736         freq->url = get_remote_object_url(base_url, hex, 0);
1737
1738         /*
1739          * If a previous temp file is present, process what was already
1740          * fetched.
1741          */
1742         prevlocal = open(prevfile, O_RDONLY);
1743         if (prevlocal != -1) {
1744                 do {
1745                         prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1746                         if (prev_read>0) {
1747                                 if (fwrite_sha1_file(prev_buf,
1748                                                      1,
1749                                                      prev_read,
1750                                                      freq) == prev_read) {
1751                                         prev_posn += prev_read;
1752                                 } else {
1753                                         prev_read = -1;
1754                                 }
1755                         }
1756                 } while (prev_read > 0);
1757                 close(prevlocal);
1758         }
1759         unlink_or_warn(prevfile);
1760
1761         /*
1762          * Reset inflate/SHA1 if there was an error reading the previous temp
1763          * file; also rewind to the beginning of the local file.
1764          */
1765         if (prev_read == -1) {
1766                 memset(&freq->stream, 0, sizeof(freq->stream));
1767                 git_inflate_init(&freq->stream);
1768                 git_SHA1_Init(&freq->c);
1769                 if (prev_posn>0) {
1770                         prev_posn = 0;
1771                         lseek(freq->localfile, 0, SEEK_SET);
1772                         if (ftruncate(freq->localfile, 0) < 0) {
1773                                 error("Couldn't truncate temporary file %s: %s",
1774                                           freq->tmpfile, strerror(errno));
1775                                 goto abort;
1776                         }
1777                 }
1778         }
1779
1780         freq->slot = get_active_slot();
1781
1782         curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1783         curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1784         curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1785         curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1786         curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1787
1788         /*
1789          * If we have successfully processed data from a previous fetch
1790          * attempt, only fetch the data we don't already have.
1791          */
1792         if (prev_posn>0) {
1793                 if (http_is_verbose)
1794                         fprintf(stderr,
1795                                 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
1796                                 hex, (uintmax_t)prev_posn);
1797                 http_opt_request_remainder(freq->slot->curl, prev_posn);
1798         }
1799
1800         return freq;
1801
1802 abort:
1803         free(freq->url);
1804         free(freq);
1805         return NULL;
1806 }
1807
1808 void process_http_object_request(struct http_object_request *freq)
1809 {
1810         if (freq->slot == NULL)
1811                 return;
1812         freq->curl_result = freq->slot->curl_result;
1813         freq->http_code = freq->slot->http_code;
1814         freq->slot = NULL;
1815 }
1816
1817 int finish_http_object_request(struct http_object_request *freq)
1818 {
1819         struct stat st;
1820
1821         close(freq->localfile);
1822         freq->localfile = -1;
1823
1824         process_http_object_request(freq);
1825
1826         if (freq->http_code == 416) {
1827                 warning("requested range invalid; we may already have all the data.");
1828         } else if (freq->curl_result != CURLE_OK) {
1829                 if (stat(freq->tmpfile, &st) == 0)
1830                         if (st.st_size == 0)
1831                                 unlink_or_warn(freq->tmpfile);
1832                 return -1;
1833         }
1834
1835         git_inflate_end(&freq->stream);
1836         git_SHA1_Final(freq->real_sha1, &freq->c);
1837         if (freq->zret != Z_STREAM_END) {
1838                 unlink_or_warn(freq->tmpfile);
1839                 return -1;
1840         }
1841         if (hashcmp(freq->sha1, freq->real_sha1)) {
1842                 unlink_or_warn(freq->tmpfile);
1843                 return -1;
1844         }
1845         freq->rename =
1846                 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
1847
1848         return freq->rename;
1849 }
1850
1851 void abort_http_object_request(struct http_object_request *freq)
1852 {
1853         unlink_or_warn(freq->tmpfile);
1854
1855         release_http_object_request(freq);
1856 }
1857
1858 void release_http_object_request(struct http_object_request *freq)
1859 {
1860         if (freq->localfile != -1) {
1861                 close(freq->localfile);
1862                 freq->localfile = -1;
1863         }
1864         if (freq->url != NULL) {
1865                 free(freq->url);
1866                 freq->url = NULL;
1867         }
1868         if (freq->slot != NULL) {
1869                 freq->slot->callback_func = NULL;
1870                 freq->slot->callback_data = NULL;
1871                 release_active_slot(freq->slot);
1872                 freq->slot = NULL;
1873         }
1874 }