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