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