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