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