Revert "archive: honor tar.umask even for pax headers"
[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 #ifdef USE_CURL_MULTI
118 static void process_curl_messages(void)
119 {
120         int num_messages;
121         struct active_request_slot *slot;
122         CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
123
124         while (curl_message != NULL) {
125                 if (curl_message->msg == CURLMSG_DONE) {
126                         int curl_result = curl_message->data.result;
127                         slot = active_queue_head;
128                         while (slot != NULL &&
129                                slot->curl != curl_message->easy_handle)
130                                 slot = slot->next;
131                         if (slot != NULL) {
132                                 curl_multi_remove_handle(curlm, slot->curl);
133                                 slot->curl_result = curl_result;
134                                 finish_active_slot(slot);
135                         } else {
136                                 fprintf(stderr, "Received DONE message for unknown request!\n");
137                         }
138                 } else {
139                         fprintf(stderr, "Unknown CURL message received: %d\n",
140                                 (int)curl_message->msg);
141                 }
142                 curl_message = curl_multi_info_read(curlm, &num_messages);
143         }
144 }
145 #endif
146
147 static int http_options(const char *var, const char *value, void *cb)
148 {
149         if (!strcmp("http.sslverify", var)) {
150                 curl_ssl_verify = git_config_bool(var, value);
151                 return 0;
152         }
153         if (!strcmp("http.sslcert", var))
154                 return git_config_string(&ssl_cert, var, value);
155 #if LIBCURL_VERSION_NUM >= 0x070903
156         if (!strcmp("http.sslkey", var))
157                 return git_config_string(&ssl_key, var, value);
158 #endif
159 #if LIBCURL_VERSION_NUM >= 0x070908
160         if (!strcmp("http.sslcapath", var))
161                 return git_config_string(&ssl_capath, var, value);
162 #endif
163         if (!strcmp("http.sslcainfo", var))
164                 return git_config_string(&ssl_cainfo, var, value);
165         if (!strcmp("http.sslcertpasswordprotected", var)) {
166                 ssl_cert_password_required = git_config_bool(var, value);
167                 return 0;
168         }
169         if (!strcmp("http.ssltry", var)) {
170                 curl_ssl_try = git_config_bool(var, value);
171                 return 0;
172         }
173         if (!strcmp("http.minsessions", var)) {
174                 min_curl_sessions = git_config_int(var, value);
175 #ifndef USE_CURL_MULTI
176                 if (min_curl_sessions > 1)
177                         min_curl_sessions = 1;
178 #endif
179                 return 0;
180         }
181 #ifdef USE_CURL_MULTI
182         if (!strcmp("http.maxrequests", var)) {
183                 max_requests = git_config_int(var, value);
184                 return 0;
185         }
186 #endif
187         if (!strcmp("http.lowspeedlimit", var)) {
188                 curl_low_speed_limit = (long)git_config_int(var, value);
189                 return 0;
190         }
191         if (!strcmp("http.lowspeedtime", var)) {
192                 curl_low_speed_time = (long)git_config_int(var, value);
193                 return 0;
194         }
195
196         if (!strcmp("http.noepsv", var)) {
197                 curl_ftp_no_epsv = git_config_bool(var, value);
198                 return 0;
199         }
200         if (!strcmp("http.proxy", var))
201                 return git_config_string(&curl_http_proxy, var, value);
202
203         if (!strcmp("http.cookiefile", var))
204                 return git_config_string(&curl_cookie_file, var, value);
205         if (!strcmp("http.savecookies", var)) {
206                 curl_save_cookies = git_config_bool(var, value);
207                 return 0;
208         }
209
210         if (!strcmp("http.postbuffer", var)) {
211                 http_post_buffer = git_config_int(var, value);
212                 if (http_post_buffer < LARGE_PACKET_MAX)
213                         http_post_buffer = LARGE_PACKET_MAX;
214                 return 0;
215         }
216
217         if (!strcmp("http.useragent", var))
218                 return git_config_string(&user_agent, var, value);
219
220         /* Fall back on the default ones */
221         return git_default_config(var, value, cb);
222 }
223
224 static void init_curl_http_auth(CURL *result)
225 {
226         if (!http_auth.username)
227                 return;
228
229         credential_fill(&http_auth);
230
231 #if LIBCURL_VERSION_NUM >= 0x071301
232         curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
233         curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
234 #else
235         {
236                 static struct strbuf up = STRBUF_INIT;
237                 /*
238                  * Note that we assume we only ever have a single set of
239                  * credentials in a given program run, so we do not have
240                  * to worry about updating this buffer, only setting its
241                  * initial value.
242                  */
243                 if (!up.len)
244                         strbuf_addf(&up, "%s:%s",
245                                 http_auth.username, http_auth.password);
246                 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
247         }
248 #endif
249 }
250
251 static int has_cert_password(void)
252 {
253         if (ssl_cert == NULL || ssl_cert_password_required != 1)
254                 return 0;
255         if (!cert_auth.password) {
256                 cert_auth.protocol = xstrdup("cert");
257                 cert_auth.username = xstrdup("");
258                 cert_auth.path = xstrdup(ssl_cert);
259                 credential_fill(&cert_auth);
260         }
261         return 1;
262 }
263
264 #if LIBCURL_VERSION_NUM >= 0x071900
265 static void set_curl_keepalive(CURL *c)
266 {
267         curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
268 }
269
270 #elif LIBCURL_VERSION_NUM >= 0x071000
271 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
272 {
273         int ka = 1;
274         int rc;
275         socklen_t len = (socklen_t)sizeof(ka);
276
277         if (type != CURLSOCKTYPE_IPCXN)
278                 return 0;
279
280         rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
281         if (rc < 0)
282                 warning("unable to set SO_KEEPALIVE on socket %s",
283                         strerror(errno));
284
285         return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
286 }
287
288 static void set_curl_keepalive(CURL *c)
289 {
290         curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
291 }
292
293 #else
294 static void set_curl_keepalive(CURL *c)
295 {
296         /* not supported on older curl versions */
297 }
298 #endif
299
300 static CURL *get_curl_handle(void)
301 {
302         CURL *result = curl_easy_init();
303
304         if (!result)
305                 die("curl_easy_init failed");
306
307         if (!curl_ssl_verify) {
308                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
309                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
310         } else {
311                 /* Verify authenticity of the peer's certificate */
312                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
313                 /* The name in the cert must match whom we tried to connect */
314                 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
315         }
316
317 #if LIBCURL_VERSION_NUM >= 0x070907
318         curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
319 #endif
320 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
321         curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
322 #endif
323
324         if (http_proactive_auth)
325                 init_curl_http_auth(result);
326
327         if (ssl_cert != NULL)
328                 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
329         if (has_cert_password())
330                 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
331 #if LIBCURL_VERSION_NUM >= 0x070903
332         if (ssl_key != NULL)
333                 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
334 #endif
335 #if LIBCURL_VERSION_NUM >= 0x070908
336         if (ssl_capath != NULL)
337                 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
338 #endif
339         if (ssl_cainfo != NULL)
340                 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
341
342         if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
343                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
344                                  curl_low_speed_limit);
345                 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
346                                  curl_low_speed_time);
347         }
348
349         curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
350 #if LIBCURL_VERSION_NUM >= 0x071301
351         curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
352 #elif LIBCURL_VERSION_NUM >= 0x071101
353         curl_easy_setopt(result, CURLOPT_POST301, 1);
354 #endif
355
356         if (getenv("GIT_CURL_VERBOSE"))
357                 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
358
359         curl_easy_setopt(result, CURLOPT_USERAGENT,
360                 user_agent ? user_agent : git_user_agent());
361
362         if (curl_ftp_no_epsv)
363                 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
364
365 #ifdef CURLOPT_USE_SSL
366         if (curl_ssl_try)
367                 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
368 #endif
369
370         if (curl_http_proxy) {
371                 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
372                 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
373         }
374
375         set_curl_keepalive(result);
376
377         return result;
378 }
379
380 static void set_from_env(const char **var, const char *envname)
381 {
382         const char *val = getenv(envname);
383         if (val)
384                 *var = val;
385 }
386
387 void http_init(struct remote *remote, const char *url, int proactive_auth)
388 {
389         char *low_speed_limit;
390         char *low_speed_time;
391         char *normalized_url;
392         struct urlmatch_config config = { STRING_LIST_INIT_DUP };
393
394         config.section = "http";
395         config.key = NULL;
396         config.collect_fn = http_options;
397         config.cascade_fn = git_default_config;
398         config.cb = NULL;
399
400         http_is_verbose = 0;
401         normalized_url = url_normalize(url, &config.url);
402
403         git_config(urlmatch_config_entry, &config);
404         free(normalized_url);
405
406         if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
407                 die("curl_global_init failed");
408
409         http_proactive_auth = proactive_auth;
410
411         if (remote && remote->http_proxy)
412                 curl_http_proxy = xstrdup(remote->http_proxy);
413
414         pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
415         no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
416
417 #ifdef USE_CURL_MULTI
418         {
419                 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
420                 if (http_max_requests != NULL)
421                         max_requests = atoi(http_max_requests);
422         }
423
424         curlm = curl_multi_init();
425         if (!curlm)
426                 die("curl_multi_init failed");
427 #endif
428
429         if (getenv("GIT_SSL_NO_VERIFY"))
430                 curl_ssl_verify = 0;
431
432         set_from_env(&ssl_cert, "GIT_SSL_CERT");
433 #if LIBCURL_VERSION_NUM >= 0x070903
434         set_from_env(&ssl_key, "GIT_SSL_KEY");
435 #endif
436 #if LIBCURL_VERSION_NUM >= 0x070908
437         set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
438 #endif
439         set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
440
441         set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
442
443         low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
444         if (low_speed_limit != NULL)
445                 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
446         low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
447         if (low_speed_time != NULL)
448                 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
449
450         if (curl_ssl_verify == -1)
451                 curl_ssl_verify = 1;
452
453         curl_session_count = 0;
454 #ifdef USE_CURL_MULTI
455         if (max_requests < 1)
456                 max_requests = DEFAULT_MAX_REQUESTS;
457 #endif
458
459         if (getenv("GIT_CURL_FTP_NO_EPSV"))
460                 curl_ftp_no_epsv = 1;
461
462         if (url) {
463                 credential_from_url(&http_auth, url);
464                 if (!ssl_cert_password_required &&
465                     getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
466                     starts_with(url, "https://"))
467                         ssl_cert_password_required = 1;
468         }
469
470 #ifndef NO_CURL_EASY_DUPHANDLE
471         curl_default = get_curl_handle();
472 #endif
473 }
474
475 void http_cleanup(void)
476 {
477         struct active_request_slot *slot = active_queue_head;
478
479         while (slot != NULL) {
480                 struct active_request_slot *next = slot->next;
481                 if (slot->curl != NULL) {
482 #ifdef USE_CURL_MULTI
483                         curl_multi_remove_handle(curlm, slot->curl);
484 #endif
485                         curl_easy_cleanup(slot->curl);
486                 }
487                 free(slot);
488                 slot = next;
489         }
490         active_queue_head = NULL;
491
492 #ifndef NO_CURL_EASY_DUPHANDLE
493         curl_easy_cleanup(curl_default);
494 #endif
495
496 #ifdef USE_CURL_MULTI
497         curl_multi_cleanup(curlm);
498 #endif
499         curl_global_cleanup();
500
501         curl_slist_free_all(pragma_header);
502         pragma_header = NULL;
503
504         curl_slist_free_all(no_pragma_header);
505         no_pragma_header = NULL;
506
507         if (curl_http_proxy) {
508                 free((void *)curl_http_proxy);
509                 curl_http_proxy = NULL;
510         }
511
512         if (cert_auth.password != NULL) {
513                 memset(cert_auth.password, 0, strlen(cert_auth.password));
514                 free(cert_auth.password);
515                 cert_auth.password = NULL;
516         }
517         ssl_cert_password_required = 0;
518 }
519
520 struct active_request_slot *get_active_slot(void)
521 {
522         struct active_request_slot *slot = active_queue_head;
523         struct active_request_slot *newslot;
524
525 #ifdef USE_CURL_MULTI
526         int num_transfers;
527
528         /* Wait for a slot to open up if the queue is full */
529         while (active_requests >= max_requests) {
530                 curl_multi_perform(curlm, &num_transfers);
531                 if (num_transfers < active_requests)
532                         process_curl_messages();
533         }
534 #endif
535
536         while (slot != NULL && slot->in_use)
537                 slot = slot->next;
538
539         if (slot == NULL) {
540                 newslot = xmalloc(sizeof(*newslot));
541                 newslot->curl = NULL;
542                 newslot->in_use = 0;
543                 newslot->next = NULL;
544
545                 slot = active_queue_head;
546                 if (slot == NULL) {
547                         active_queue_head = newslot;
548                 } else {
549                         while (slot->next != NULL)
550                                 slot = slot->next;
551                         slot->next = newslot;
552                 }
553                 slot = newslot;
554         }
555
556         if (slot->curl == NULL) {
557 #ifdef NO_CURL_EASY_DUPHANDLE
558                 slot->curl = get_curl_handle();
559 #else
560                 slot->curl = curl_easy_duphandle(curl_default);
561 #endif
562                 curl_session_count++;
563         }
564
565         active_requests++;
566         slot->in_use = 1;
567         slot->results = NULL;
568         slot->finished = NULL;
569         slot->callback_data = NULL;
570         slot->callback_func = NULL;
571         curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
572         if (curl_save_cookies)
573                 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
574         curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
575         curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
576         curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
577         curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
578         curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
579         curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
580         curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
581         curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
582         curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
583         if (http_auth.password)
584                 init_curl_http_auth(slot->curl);
585
586         return slot;
587 }
588
589 int start_active_slot(struct active_request_slot *slot)
590 {
591 #ifdef USE_CURL_MULTI
592         CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
593         int num_transfers;
594
595         if (curlm_result != CURLM_OK &&
596             curlm_result != CURLM_CALL_MULTI_PERFORM) {
597                 active_requests--;
598                 slot->in_use = 0;
599                 return 0;
600         }
601
602         /*
603          * We know there must be something to do, since we just added
604          * something.
605          */
606         curl_multi_perform(curlm, &num_transfers);
607 #endif
608         return 1;
609 }
610
611 #ifdef USE_CURL_MULTI
612 struct fill_chain {
613         void *data;
614         int (*fill)(void *);
615         struct fill_chain *next;
616 };
617
618 static struct fill_chain *fill_cfg;
619
620 void add_fill_function(void *data, int (*fill)(void *))
621 {
622         struct fill_chain *new = xmalloc(sizeof(*new));
623         struct fill_chain **linkp = &fill_cfg;
624         new->data = data;
625         new->fill = fill;
626         new->next = NULL;
627         while (*linkp)
628                 linkp = &(*linkp)->next;
629         *linkp = new;
630 }
631
632 void fill_active_slots(void)
633 {
634         struct active_request_slot *slot = active_queue_head;
635
636         while (active_requests < max_requests) {
637                 struct fill_chain *fill;
638                 for (fill = fill_cfg; fill; fill = fill->next)
639                         if (fill->fill(fill->data))
640                                 break;
641
642                 if (!fill)
643                         break;
644         }
645
646         while (slot != NULL) {
647                 if (!slot->in_use && slot->curl != NULL
648                         && curl_session_count > min_curl_sessions) {
649                         curl_easy_cleanup(slot->curl);
650                         slot->curl = NULL;
651                         curl_session_count--;
652                 }
653                 slot = slot->next;
654         }
655 }
656
657 void step_active_slots(void)
658 {
659         int num_transfers;
660         CURLMcode curlm_result;
661
662         do {
663                 curlm_result = curl_multi_perform(curlm, &num_transfers);
664         } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
665         if (num_transfers < active_requests) {
666                 process_curl_messages();
667                 fill_active_slots();
668         }
669 }
670 #endif
671
672 void run_active_slot(struct active_request_slot *slot)
673 {
674 #ifdef USE_CURL_MULTI
675         fd_set readfds;
676         fd_set writefds;
677         fd_set excfds;
678         int max_fd;
679         struct timeval select_timeout;
680         int finished = 0;
681
682         slot->finished = &finished;
683         while (!finished) {
684                 step_active_slots();
685
686                 if (slot->in_use) {
687 #if LIBCURL_VERSION_NUM >= 0x070f04
688                         long curl_timeout;
689                         curl_multi_timeout(curlm, &curl_timeout);
690                         if (curl_timeout == 0) {
691                                 continue;
692                         } else if (curl_timeout == -1) {
693                                 select_timeout.tv_sec  = 0;
694                                 select_timeout.tv_usec = 50000;
695                         } else {
696                                 select_timeout.tv_sec  =  curl_timeout / 1000;
697                                 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
698                         }
699 #else
700                         select_timeout.tv_sec  = 0;
701                         select_timeout.tv_usec = 50000;
702 #endif
703
704                         max_fd = -1;
705                         FD_ZERO(&readfds);
706                         FD_ZERO(&writefds);
707                         FD_ZERO(&excfds);
708                         curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
709
710                         /*
711                          * It can happen that curl_multi_timeout returns a pathologically
712                          * long timeout when curl_multi_fdset returns no file descriptors
713                          * to read.  See commit message for more details.
714                          */
715                         if (max_fd < 0 &&
716                             (select_timeout.tv_sec > 0 ||
717                              select_timeout.tv_usec > 50000)) {
718                                 select_timeout.tv_sec  = 0;
719                                 select_timeout.tv_usec = 50000;
720                         }
721
722                         select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
723                 }
724         }
725 #else
726         while (slot->in_use) {
727                 slot->curl_result = curl_easy_perform(slot->curl);
728                 finish_active_slot(slot);
729         }
730 #endif
731 }
732
733 static void closedown_active_slot(struct active_request_slot *slot)
734 {
735         active_requests--;
736         slot->in_use = 0;
737 }
738
739 static void release_active_slot(struct active_request_slot *slot)
740 {
741         closedown_active_slot(slot);
742         if (slot->curl && curl_session_count > min_curl_sessions) {
743 #ifdef USE_CURL_MULTI
744                 curl_multi_remove_handle(curlm, slot->curl);
745 #endif
746                 curl_easy_cleanup(slot->curl);
747                 slot->curl = NULL;
748                 curl_session_count--;
749         }
750 #ifdef USE_CURL_MULTI
751         fill_active_slots();
752 #endif
753 }
754
755 void finish_active_slot(struct active_request_slot *slot)
756 {
757         closedown_active_slot(slot);
758         curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
759
760         if (slot->finished != NULL)
761                 (*slot->finished) = 1;
762
763         /* Store slot results so they can be read after the slot is reused */
764         if (slot->results != NULL) {
765                 slot->results->curl_result = slot->curl_result;
766                 slot->results->http_code = slot->http_code;
767 #if LIBCURL_VERSION_NUM >= 0x070a08
768                 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
769                                   &slot->results->auth_avail);
770 #else
771                 slot->results->auth_avail = 0;
772 #endif
773         }
774
775         /* Run callback if appropriate */
776         if (slot->callback_func != NULL)
777                 slot->callback_func(slot->callback_data);
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 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 }