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