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