unix-socket: do not let close() or chdir() clobber errno during cleanup
[git/gitweb.git] / http.c
blob917a1ae7d088f56cd704acb60a5eefa02bb72edc
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"
8 int data_received;
9 int active_requests;
10 int http_is_verbose;
11 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
13 #if LIBCURL_VERSION_NUM >= 0x070a06
14 #define LIBCURL_CAN_HANDLE_AUTH_ANY
15 #endif
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
27 #define PREV_BUF_SIZE 4096
28 #define RANGE_HEADER_SIZE 30
30 char curl_errorstr[CURL_ERROR_SIZE];
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 const char *user_agent;
49 #if LIBCURL_VERSION_NUM >= 0x071700
50 /* Use CURLOPT_KEYPASSWD as is */
51 #elif LIBCURL_VERSION_NUM >= 0x070903
52 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
53 #else
54 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
55 #endif
57 static struct credential cert_auth = CREDENTIAL_INIT;
58 static int ssl_cert_password_required;
60 static struct curl_slist *pragma_header;
61 static struct curl_slist *no_pragma_header;
63 static struct active_request_slot *active_queue_head;
65 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
67 size_t size = eltsize * nmemb;
68 struct buffer *buffer = buffer_;
70 if (size > buffer->buf.len - buffer->posn)
71 size = buffer->buf.len - buffer->posn;
72 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
73 buffer->posn += size;
75 return size;
78 #ifndef NO_CURL_IOCTL
79 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
81 struct buffer *buffer = clientp;
83 switch (cmd) {
84 case CURLIOCMD_NOP:
85 return CURLIOE_OK;
87 case CURLIOCMD_RESTARTREAD:
88 buffer->posn = 0;
89 return CURLIOE_OK;
91 default:
92 return CURLIOE_UNKNOWNCMD;
95 #endif
97 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
99 size_t size = eltsize * nmemb;
100 struct strbuf *buffer = buffer_;
102 strbuf_add(buffer, ptr, size);
103 data_received++;
104 return size;
107 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
109 data_received++;
110 return eltsize * nmemb;
113 #ifdef USE_CURL_MULTI
114 static void process_curl_messages(void)
116 int num_messages;
117 struct active_request_slot *slot;
118 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
120 while (curl_message != NULL) {
121 if (curl_message->msg == CURLMSG_DONE) {
122 int curl_result = curl_message->data.result;
123 slot = active_queue_head;
124 while (slot != NULL &&
125 slot->curl != curl_message->easy_handle)
126 slot = slot->next;
127 if (slot != NULL) {
128 curl_multi_remove_handle(curlm, slot->curl);
129 slot->curl_result = curl_result;
130 finish_active_slot(slot);
131 } else {
132 fprintf(stderr, "Received DONE message for unknown request!\n");
134 } else {
135 fprintf(stderr, "Unknown CURL message received: %d\n",
136 (int)curl_message->msg);
138 curl_message = curl_multi_info_read(curlm, &num_messages);
141 #endif
143 static int http_options(const char *var, const char *value, void *cb)
145 if (!strcmp("http.sslverify", var)) {
146 curl_ssl_verify = git_config_bool(var, value);
147 return 0;
149 if (!strcmp("http.sslcert", var))
150 return git_config_string(&ssl_cert, var, value);
151 #if LIBCURL_VERSION_NUM >= 0x070903
152 if (!strcmp("http.sslkey", var))
153 return git_config_string(&ssl_key, var, value);
154 #endif
155 #if LIBCURL_VERSION_NUM >= 0x070908
156 if (!strcmp("http.sslcapath", var))
157 return git_config_string(&ssl_capath, var, value);
158 #endif
159 if (!strcmp("http.sslcainfo", var))
160 return git_config_string(&ssl_cainfo, var, value);
161 if (!strcmp("http.sslcertpasswordprotected", var)) {
162 if (git_config_bool(var, value))
163 ssl_cert_password_required = 1;
164 return 0;
166 if (!strcmp("http.minsessions", var)) {
167 min_curl_sessions = git_config_int(var, value);
168 #ifndef USE_CURL_MULTI
169 if (min_curl_sessions > 1)
170 min_curl_sessions = 1;
171 #endif
172 return 0;
174 #ifdef USE_CURL_MULTI
175 if (!strcmp("http.maxrequests", var)) {
176 max_requests = git_config_int(var, value);
177 return 0;
179 #endif
180 if (!strcmp("http.lowspeedlimit", var)) {
181 curl_low_speed_limit = (long)git_config_int(var, value);
182 return 0;
184 if (!strcmp("http.lowspeedtime", var)) {
185 curl_low_speed_time = (long)git_config_int(var, value);
186 return 0;
189 if (!strcmp("http.noepsv", var)) {
190 curl_ftp_no_epsv = git_config_bool(var, value);
191 return 0;
193 if (!strcmp("http.proxy", var))
194 return git_config_string(&curl_http_proxy, var, value);
196 if (!strcmp("http.cookiefile", var))
197 return git_config_string(&curl_cookie_file, var, value);
199 if (!strcmp("http.postbuffer", var)) {
200 http_post_buffer = git_config_int(var, value);
201 if (http_post_buffer < LARGE_PACKET_MAX)
202 http_post_buffer = LARGE_PACKET_MAX;
203 return 0;
206 if (!strcmp("http.useragent", var))
207 return git_config_string(&user_agent, var, value);
209 /* Fall back on the default ones */
210 return git_default_config(var, value, cb);
213 static void init_curl_http_auth(CURL *result)
215 if (http_auth.username) {
216 struct strbuf up = STRBUF_INIT;
217 credential_fill(&http_auth);
218 strbuf_addf(&up, "%s:%s",
219 http_auth.username, http_auth.password);
220 curl_easy_setopt(result, CURLOPT_USERPWD,
221 strbuf_detach(&up, NULL));
225 static int has_cert_password(void)
227 if (ssl_cert == NULL || ssl_cert_password_required != 1)
228 return 0;
229 if (!cert_auth.password) {
230 cert_auth.protocol = xstrdup("cert");
231 cert_auth.path = xstrdup(ssl_cert);
232 credential_fill(&cert_auth);
234 return 1;
237 static CURL *get_curl_handle(void)
239 CURL *result = curl_easy_init();
241 if (!curl_ssl_verify) {
242 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
243 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
244 } else {
245 /* Verify authenticity of the peer's certificate */
246 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
247 /* The name in the cert must match whom we tried to connect */
248 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
251 #if LIBCURL_VERSION_NUM >= 0x070907
252 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
253 #endif
254 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
255 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
256 #endif
258 if (ssl_cert != NULL)
259 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
260 if (has_cert_password())
261 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
262 #if LIBCURL_VERSION_NUM >= 0x070903
263 if (ssl_key != NULL)
264 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
265 #endif
266 #if LIBCURL_VERSION_NUM >= 0x070908
267 if (ssl_capath != NULL)
268 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
269 #endif
270 if (ssl_cainfo != NULL)
271 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
272 curl_easy_setopt(result, CURLOPT_FAILONERROR, 1);
274 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
275 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
276 curl_low_speed_limit);
277 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
278 curl_low_speed_time);
281 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
282 #if LIBCURL_VERSION_NUM >= 0x071301
283 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
284 #elif LIBCURL_VERSION_NUM >= 0x071101
285 curl_easy_setopt(result, CURLOPT_POST301, 1);
286 #endif
288 if (getenv("GIT_CURL_VERBOSE"))
289 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
291 curl_easy_setopt(result, CURLOPT_USERAGENT,
292 user_agent ? user_agent : GIT_HTTP_USER_AGENT);
294 if (curl_ftp_no_epsv)
295 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
297 if (curl_http_proxy)
298 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
300 return result;
303 static void set_from_env(const char **var, const char *envname)
305 const char *val = getenv(envname);
306 if (val)
307 *var = val;
310 void http_init(struct remote *remote, const char *url)
312 char *low_speed_limit;
313 char *low_speed_time;
315 http_is_verbose = 0;
317 git_config(http_options, NULL);
319 curl_global_init(CURL_GLOBAL_ALL);
321 if (remote && remote->http_proxy)
322 curl_http_proxy = xstrdup(remote->http_proxy);
324 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
325 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
327 #ifdef USE_CURL_MULTI
329 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
330 if (http_max_requests != NULL)
331 max_requests = atoi(http_max_requests);
334 curlm = curl_multi_init();
335 if (curlm == NULL) {
336 fprintf(stderr, "Error creating curl multi handle.\n");
337 exit(1);
339 #endif
341 if (getenv("GIT_SSL_NO_VERIFY"))
342 curl_ssl_verify = 0;
344 set_from_env(&ssl_cert, "GIT_SSL_CERT");
345 #if LIBCURL_VERSION_NUM >= 0x070903
346 set_from_env(&ssl_key, "GIT_SSL_KEY");
347 #endif
348 #if LIBCURL_VERSION_NUM >= 0x070908
349 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
350 #endif
351 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
353 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
355 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
356 if (low_speed_limit != NULL)
357 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
358 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
359 if (low_speed_time != NULL)
360 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
362 if (curl_ssl_verify == -1)
363 curl_ssl_verify = 1;
365 curl_session_count = 0;
366 #ifdef USE_CURL_MULTI
367 if (max_requests < 1)
368 max_requests = DEFAULT_MAX_REQUESTS;
369 #endif
371 if (getenv("GIT_CURL_FTP_NO_EPSV"))
372 curl_ftp_no_epsv = 1;
374 if (url) {
375 credential_from_url(&http_auth, url);
376 if (!ssl_cert_password_required &&
377 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
378 !prefixcmp(url, "https://"))
379 ssl_cert_password_required = 1;
382 #ifndef NO_CURL_EASY_DUPHANDLE
383 curl_default = get_curl_handle();
384 #endif
387 void http_cleanup(void)
389 struct active_request_slot *slot = active_queue_head;
391 while (slot != NULL) {
392 struct active_request_slot *next = slot->next;
393 if (slot->curl != NULL) {
394 #ifdef USE_CURL_MULTI
395 curl_multi_remove_handle(curlm, slot->curl);
396 #endif
397 curl_easy_cleanup(slot->curl);
399 free(slot);
400 slot = next;
402 active_queue_head = NULL;
404 #ifndef NO_CURL_EASY_DUPHANDLE
405 curl_easy_cleanup(curl_default);
406 #endif
408 #ifdef USE_CURL_MULTI
409 curl_multi_cleanup(curlm);
410 #endif
411 curl_global_cleanup();
413 curl_slist_free_all(pragma_header);
414 pragma_header = NULL;
416 curl_slist_free_all(no_pragma_header);
417 no_pragma_header = NULL;
419 if (curl_http_proxy) {
420 free((void *)curl_http_proxy);
421 curl_http_proxy = NULL;
424 if (cert_auth.password != NULL) {
425 memset(cert_auth.password, 0, strlen(cert_auth.password));
426 free(cert_auth.password);
427 cert_auth.password = NULL;
429 ssl_cert_password_required = 0;
432 struct active_request_slot *get_active_slot(void)
434 struct active_request_slot *slot = active_queue_head;
435 struct active_request_slot *newslot;
437 #ifdef USE_CURL_MULTI
438 int num_transfers;
440 /* Wait for a slot to open up if the queue is full */
441 while (active_requests >= max_requests) {
442 curl_multi_perform(curlm, &num_transfers);
443 if (num_transfers < active_requests)
444 process_curl_messages();
446 #endif
448 while (slot != NULL && slot->in_use)
449 slot = slot->next;
451 if (slot == NULL) {
452 newslot = xmalloc(sizeof(*newslot));
453 newslot->curl = NULL;
454 newslot->in_use = 0;
455 newslot->next = NULL;
457 slot = active_queue_head;
458 if (slot == NULL) {
459 active_queue_head = newslot;
460 } else {
461 while (slot->next != NULL)
462 slot = slot->next;
463 slot->next = newslot;
465 slot = newslot;
468 if (slot->curl == NULL) {
469 #ifdef NO_CURL_EASY_DUPHANDLE
470 slot->curl = get_curl_handle();
471 #else
472 slot->curl = curl_easy_duphandle(curl_default);
473 #endif
474 curl_session_count++;
477 active_requests++;
478 slot->in_use = 1;
479 slot->local = NULL;
480 slot->results = NULL;
481 slot->finished = NULL;
482 slot->callback_data = NULL;
483 slot->callback_func = NULL;
484 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
485 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
486 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
487 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
488 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
489 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
490 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
491 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
492 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
494 return slot;
497 int start_active_slot(struct active_request_slot *slot)
499 #ifdef USE_CURL_MULTI
500 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
501 int num_transfers;
503 if (curlm_result != CURLM_OK &&
504 curlm_result != CURLM_CALL_MULTI_PERFORM) {
505 active_requests--;
506 slot->in_use = 0;
507 return 0;
511 * We know there must be something to do, since we just added
512 * something.
514 curl_multi_perform(curlm, &num_transfers);
515 #endif
516 return 1;
519 #ifdef USE_CURL_MULTI
520 struct fill_chain {
521 void *data;
522 int (*fill)(void *);
523 struct fill_chain *next;
526 static struct fill_chain *fill_cfg;
528 void add_fill_function(void *data, int (*fill)(void *))
530 struct fill_chain *new = xmalloc(sizeof(*new));
531 struct fill_chain **linkp = &fill_cfg;
532 new->data = data;
533 new->fill = fill;
534 new->next = NULL;
535 while (*linkp)
536 linkp = &(*linkp)->next;
537 *linkp = new;
540 void fill_active_slots(void)
542 struct active_request_slot *slot = active_queue_head;
544 while (active_requests < max_requests) {
545 struct fill_chain *fill;
546 for (fill = fill_cfg; fill; fill = fill->next)
547 if (fill->fill(fill->data))
548 break;
550 if (!fill)
551 break;
554 while (slot != NULL) {
555 if (!slot->in_use && slot->curl != NULL
556 && curl_session_count > min_curl_sessions) {
557 curl_easy_cleanup(slot->curl);
558 slot->curl = NULL;
559 curl_session_count--;
561 slot = slot->next;
565 void step_active_slots(void)
567 int num_transfers;
568 CURLMcode curlm_result;
570 do {
571 curlm_result = curl_multi_perform(curlm, &num_transfers);
572 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
573 if (num_transfers < active_requests) {
574 process_curl_messages();
575 fill_active_slots();
578 #endif
580 void run_active_slot(struct active_request_slot *slot)
582 #ifdef USE_CURL_MULTI
583 long last_pos = 0;
584 long current_pos;
585 fd_set readfds;
586 fd_set writefds;
587 fd_set excfds;
588 int max_fd;
589 struct timeval select_timeout;
590 int finished = 0;
592 slot->finished = &finished;
593 while (!finished) {
594 data_received = 0;
595 step_active_slots();
597 if (!data_received && slot->local != NULL) {
598 current_pos = ftell(slot->local);
599 if (current_pos > last_pos)
600 data_received++;
601 last_pos = current_pos;
604 if (slot->in_use && !data_received) {
605 max_fd = 0;
606 FD_ZERO(&readfds);
607 FD_ZERO(&writefds);
608 FD_ZERO(&excfds);
609 select_timeout.tv_sec = 0;
610 select_timeout.tv_usec = 50000;
611 select(max_fd, &readfds, &writefds,
612 &excfds, &select_timeout);
615 #else
616 while (slot->in_use) {
617 slot->curl_result = curl_easy_perform(slot->curl);
618 finish_active_slot(slot);
620 #endif
623 static void closedown_active_slot(struct active_request_slot *slot)
625 active_requests--;
626 slot->in_use = 0;
629 static void release_active_slot(struct active_request_slot *slot)
631 closedown_active_slot(slot);
632 if (slot->curl && curl_session_count > min_curl_sessions) {
633 #ifdef USE_CURL_MULTI
634 curl_multi_remove_handle(curlm, slot->curl);
635 #endif
636 curl_easy_cleanup(slot->curl);
637 slot->curl = NULL;
638 curl_session_count--;
640 #ifdef USE_CURL_MULTI
641 fill_active_slots();
642 #endif
645 void finish_active_slot(struct active_request_slot *slot)
647 closedown_active_slot(slot);
648 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
650 if (slot->finished != NULL)
651 (*slot->finished) = 1;
653 /* Store slot results so they can be read after the slot is reused */
654 if (slot->results != NULL) {
655 slot->results->curl_result = slot->curl_result;
656 slot->results->http_code = slot->http_code;
659 /* Run callback if appropriate */
660 if (slot->callback_func != NULL)
661 slot->callback_func(slot->callback_data);
664 void finish_all_active_slots(void)
666 struct active_request_slot *slot = active_queue_head;
668 while (slot != NULL)
669 if (slot->in_use) {
670 run_active_slot(slot);
671 slot = active_queue_head;
672 } else {
673 slot = slot->next;
677 /* Helpers for modifying and creating URLs */
678 static inline int needs_quote(int ch)
680 if (((ch >= 'A') && (ch <= 'Z'))
681 || ((ch >= 'a') && (ch <= 'z'))
682 || ((ch >= '0') && (ch <= '9'))
683 || (ch == '/')
684 || (ch == '-')
685 || (ch == '.'))
686 return 0;
687 return 1;
690 static char *quote_ref_url(const char *base, const char *ref)
692 struct strbuf buf = STRBUF_INIT;
693 const char *cp;
694 int ch;
696 end_url_with_slash(&buf, base);
698 for (cp = ref; (ch = *cp) != 0; cp++)
699 if (needs_quote(ch))
700 strbuf_addf(&buf, "%%%02x", ch);
701 else
702 strbuf_addch(&buf, *cp);
704 return strbuf_detach(&buf, NULL);
707 void append_remote_object_url(struct strbuf *buf, const char *url,
708 const char *hex,
709 int only_two_digit_prefix)
711 end_url_with_slash(buf, url);
713 strbuf_addf(buf, "objects/%.*s/", 2, hex);
714 if (!only_two_digit_prefix)
715 strbuf_addf(buf, "%s", hex+2);
718 char *get_remote_object_url(const char *url, const char *hex,
719 int only_two_digit_prefix)
721 struct strbuf buf = STRBUF_INIT;
722 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
723 return strbuf_detach(&buf, NULL);
726 /* http_request() targets */
727 #define HTTP_REQUEST_STRBUF 0
728 #define HTTP_REQUEST_FILE 1
730 static int http_request(const char *url, void *result, int target, int options)
732 struct active_request_slot *slot;
733 struct slot_results results;
734 struct curl_slist *headers = NULL;
735 struct strbuf buf = STRBUF_INIT;
736 int ret;
738 slot = get_active_slot();
739 slot->results = &results;
740 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
742 if (result == NULL) {
743 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
744 } else {
745 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
746 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
748 if (target == HTTP_REQUEST_FILE) {
749 long posn = ftell(result);
750 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
751 fwrite);
752 if (posn > 0) {
753 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
754 headers = curl_slist_append(headers, buf.buf);
755 strbuf_reset(&buf);
757 slot->local = result;
758 } else
759 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
760 fwrite_buffer);
763 strbuf_addstr(&buf, "Pragma:");
764 if (options & HTTP_NO_CACHE)
765 strbuf_addstr(&buf, " no-cache");
767 headers = curl_slist_append(headers, buf.buf);
769 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
770 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
772 if (start_active_slot(slot)) {
773 run_active_slot(slot);
774 if (results.curl_result == CURLE_OK)
775 ret = HTTP_OK;
776 else if (missing_target(&results))
777 ret = HTTP_MISSING_TARGET;
778 else if (results.http_code == 401) {
779 if (http_auth.username && http_auth.password) {
780 credential_reject(&http_auth);
781 ret = HTTP_NOAUTH;
782 } else {
783 credential_fill(&http_auth);
784 init_curl_http_auth(slot->curl);
785 ret = HTTP_REAUTH;
787 } else {
788 if (!curl_errorstr[0])
789 strlcpy(curl_errorstr,
790 curl_easy_strerror(results.curl_result),
791 sizeof(curl_errorstr));
792 ret = HTTP_ERROR;
794 } else {
795 error("Unable to start HTTP request for %s", url);
796 ret = HTTP_START_FAILED;
799 slot->local = NULL;
800 curl_slist_free_all(headers);
801 strbuf_release(&buf);
803 if (ret == HTTP_OK)
804 credential_approve(&http_auth);
806 return ret;
809 static int http_request_reauth(const char *url, void *result, int target,
810 int options)
812 int ret = http_request(url, result, target, options);
813 if (ret != HTTP_REAUTH)
814 return ret;
815 return http_request(url, result, target, options);
818 int http_get_strbuf(const char *url, struct strbuf *result, int options)
820 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
824 * Downloads an url and stores the result in the given file.
826 * If a previous interrupted download is detected (i.e. a previous temporary
827 * file is still around) the download is resumed.
829 static int http_get_file(const char *url, const char *filename, int options)
831 int ret;
832 struct strbuf tmpfile = STRBUF_INIT;
833 FILE *result;
835 strbuf_addf(&tmpfile, "%s.temp", filename);
836 result = fopen(tmpfile.buf, "a");
837 if (! result) {
838 error("Unable to open local file %s", tmpfile.buf);
839 ret = HTTP_ERROR;
840 goto cleanup;
843 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
844 fclose(result);
846 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
847 ret = HTTP_ERROR;
848 cleanup:
849 strbuf_release(&tmpfile);
850 return ret;
853 int http_error(const char *url, int ret)
855 /* http_request has already handled HTTP_START_FAILED. */
856 if (ret != HTTP_START_FAILED)
857 error("%s while accessing %s", curl_errorstr, url);
859 return ret;
862 int http_fetch_ref(const char *base, struct ref *ref)
864 char *url;
865 struct strbuf buffer = STRBUF_INIT;
866 int ret = -1;
868 url = quote_ref_url(base, ref->name);
869 if (http_get_strbuf(url, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
870 strbuf_rtrim(&buffer);
871 if (buffer.len == 40)
872 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
873 else if (!prefixcmp(buffer.buf, "ref: ")) {
874 ref->symref = xstrdup(buffer.buf + 5);
875 ret = 0;
879 strbuf_release(&buffer);
880 free(url);
881 return ret;
884 /* Helpers for fetching packs */
885 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
887 char *url, *tmp;
888 struct strbuf buf = STRBUF_INIT;
890 if (http_is_verbose)
891 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
893 end_url_with_slash(&buf, base_url);
894 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
895 url = strbuf_detach(&buf, NULL);
897 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
898 tmp = strbuf_detach(&buf, NULL);
900 if (http_get_file(url, tmp, 0) != HTTP_OK) {
901 error("Unable to get pack index %s\n", url);
902 free(tmp);
903 tmp = NULL;
906 free(url);
907 return tmp;
910 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
911 unsigned char *sha1, const char *base_url)
913 struct packed_git *new_pack;
914 char *tmp_idx = NULL;
915 int ret;
917 if (has_pack_index(sha1)) {
918 new_pack = parse_pack_index(sha1, NULL);
919 if (!new_pack)
920 return -1; /* parse_pack_index() already issued error message */
921 goto add_pack;
924 tmp_idx = fetch_pack_index(sha1, base_url);
925 if (!tmp_idx)
926 return -1;
928 new_pack = parse_pack_index(sha1, tmp_idx);
929 if (!new_pack) {
930 unlink(tmp_idx);
931 free(tmp_idx);
933 return -1; /* parse_pack_index() already issued error message */
936 ret = verify_pack_index(new_pack);
937 if (!ret) {
938 close_pack_index(new_pack);
939 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
941 free(tmp_idx);
942 if (ret)
943 return -1;
945 add_pack:
946 new_pack->next = *packs_head;
947 *packs_head = new_pack;
948 return 0;
951 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
953 int ret = 0, i = 0;
954 char *url, *data;
955 struct strbuf buf = STRBUF_INIT;
956 unsigned char sha1[20];
958 end_url_with_slash(&buf, base_url);
959 strbuf_addstr(&buf, "objects/info/packs");
960 url = strbuf_detach(&buf, NULL);
962 ret = http_get_strbuf(url, &buf, HTTP_NO_CACHE);
963 if (ret != HTTP_OK)
964 goto cleanup;
966 data = buf.buf;
967 while (i < buf.len) {
968 switch (data[i]) {
969 case 'P':
970 i++;
971 if (i + 52 <= buf.len &&
972 !prefixcmp(data + i, " pack-") &&
973 !prefixcmp(data + i + 46, ".pack\n")) {
974 get_sha1_hex(data + i + 6, sha1);
975 fetch_and_setup_pack_index(packs_head, sha1,
976 base_url);
977 i += 51;
978 break;
980 default:
981 while (i < buf.len && data[i] != '\n')
982 i++;
984 i++;
987 cleanup:
988 free(url);
989 return ret;
992 void release_http_pack_request(struct http_pack_request *preq)
994 if (preq->packfile != NULL) {
995 fclose(preq->packfile);
996 preq->packfile = NULL;
997 preq->slot->local = NULL;
999 if (preq->range_header != NULL) {
1000 curl_slist_free_all(preq->range_header);
1001 preq->range_header = NULL;
1003 preq->slot = NULL;
1004 free(preq->url);
1007 int finish_http_pack_request(struct http_pack_request *preq)
1009 struct packed_git **lst;
1010 struct packed_git *p = preq->target;
1011 char *tmp_idx;
1012 struct child_process ip;
1013 const char *ip_argv[8];
1015 close_pack_index(p);
1017 fclose(preq->packfile);
1018 preq->packfile = NULL;
1019 preq->slot->local = NULL;
1021 lst = preq->lst;
1022 while (*lst != p)
1023 lst = &((*lst)->next);
1024 *lst = (*lst)->next;
1026 tmp_idx = xstrdup(preq->tmpfile);
1027 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1028 ".idx.temp");
1030 ip_argv[0] = "index-pack";
1031 ip_argv[1] = "-o";
1032 ip_argv[2] = tmp_idx;
1033 ip_argv[3] = preq->tmpfile;
1034 ip_argv[4] = NULL;
1036 memset(&ip, 0, sizeof(ip));
1037 ip.argv = ip_argv;
1038 ip.git_cmd = 1;
1039 ip.no_stdin = 1;
1040 ip.no_stdout = 1;
1042 if (run_command(&ip)) {
1043 unlink(preq->tmpfile);
1044 unlink(tmp_idx);
1045 free(tmp_idx);
1046 return -1;
1049 unlink(sha1_pack_index_name(p->sha1));
1051 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1052 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1053 free(tmp_idx);
1054 return -1;
1057 install_packed_git(p);
1058 free(tmp_idx);
1059 return 0;
1062 struct http_pack_request *new_http_pack_request(
1063 struct packed_git *target, const char *base_url)
1065 long prev_posn = 0;
1066 char range[RANGE_HEADER_SIZE];
1067 struct strbuf buf = STRBUF_INIT;
1068 struct http_pack_request *preq;
1070 preq = xcalloc(1, sizeof(*preq));
1071 preq->target = target;
1073 end_url_with_slash(&buf, base_url);
1074 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1075 sha1_to_hex(target->sha1));
1076 preq->url = strbuf_detach(&buf, NULL);
1078 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1079 sha1_pack_name(target->sha1));
1080 preq->packfile = fopen(preq->tmpfile, "a");
1081 if (!preq->packfile) {
1082 error("Unable to open local file %s for pack",
1083 preq->tmpfile);
1084 goto abort;
1087 preq->slot = get_active_slot();
1088 preq->slot->local = preq->packfile;
1089 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1090 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1091 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1092 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1093 no_pragma_header);
1096 * If there is data present from a previous transfer attempt,
1097 * resume where it left off
1099 prev_posn = ftell(preq->packfile);
1100 if (prev_posn>0) {
1101 if (http_is_verbose)
1102 fprintf(stderr,
1103 "Resuming fetch of pack %s at byte %ld\n",
1104 sha1_to_hex(target->sha1), prev_posn);
1105 sprintf(range, "Range: bytes=%ld-", prev_posn);
1106 preq->range_header = curl_slist_append(NULL, range);
1107 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1108 preq->range_header);
1111 return preq;
1113 abort:
1114 free(preq->url);
1115 free(preq);
1116 return NULL;
1119 /* Helpers for fetching objects (loose) */
1120 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1121 void *data)
1123 unsigned char expn[4096];
1124 size_t size = eltsize * nmemb;
1125 int posn = 0;
1126 struct http_object_request *freq =
1127 (struct http_object_request *)data;
1128 do {
1129 ssize_t retval = xwrite(freq->localfile,
1130 (char *) ptr + posn, size - posn);
1131 if (retval < 0)
1132 return posn;
1133 posn += retval;
1134 } while (posn < size);
1136 freq->stream.avail_in = size;
1137 freq->stream.next_in = (void *)ptr;
1138 do {
1139 freq->stream.next_out = expn;
1140 freq->stream.avail_out = sizeof(expn);
1141 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1142 git_SHA1_Update(&freq->c, expn,
1143 sizeof(expn) - freq->stream.avail_out);
1144 } while (freq->stream.avail_in && freq->zret == Z_OK);
1145 data_received++;
1146 return size;
1149 struct http_object_request *new_http_object_request(const char *base_url,
1150 unsigned char *sha1)
1152 char *hex = sha1_to_hex(sha1);
1153 char *filename;
1154 char prevfile[PATH_MAX];
1155 int prevlocal;
1156 char prev_buf[PREV_BUF_SIZE];
1157 ssize_t prev_read = 0;
1158 long prev_posn = 0;
1159 char range[RANGE_HEADER_SIZE];
1160 struct curl_slist *range_header = NULL;
1161 struct http_object_request *freq;
1163 freq = xcalloc(1, sizeof(*freq));
1164 hashcpy(freq->sha1, sha1);
1165 freq->localfile = -1;
1167 filename = sha1_file_name(sha1);
1168 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1169 "%s.temp", filename);
1171 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1172 unlink_or_warn(prevfile);
1173 rename(freq->tmpfile, prevfile);
1174 unlink_or_warn(freq->tmpfile);
1176 if (freq->localfile != -1)
1177 error("fd leakage in start: %d", freq->localfile);
1178 freq->localfile = open(freq->tmpfile,
1179 O_WRONLY | O_CREAT | O_EXCL, 0666);
1181 * This could have failed due to the "lazy directory creation";
1182 * try to mkdir the last path component.
1184 if (freq->localfile < 0 && errno == ENOENT) {
1185 char *dir = strrchr(freq->tmpfile, '/');
1186 if (dir) {
1187 *dir = 0;
1188 mkdir(freq->tmpfile, 0777);
1189 *dir = '/';
1191 freq->localfile = open(freq->tmpfile,
1192 O_WRONLY | O_CREAT | O_EXCL, 0666);
1195 if (freq->localfile < 0) {
1196 error("Couldn't create temporary file %s: %s",
1197 freq->tmpfile, strerror(errno));
1198 goto abort;
1201 git_inflate_init(&freq->stream);
1203 git_SHA1_Init(&freq->c);
1205 freq->url = get_remote_object_url(base_url, hex, 0);
1208 * If a previous temp file is present, process what was already
1209 * fetched.
1211 prevlocal = open(prevfile, O_RDONLY);
1212 if (prevlocal != -1) {
1213 do {
1214 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1215 if (prev_read>0) {
1216 if (fwrite_sha1_file(prev_buf,
1218 prev_read,
1219 freq) == prev_read) {
1220 prev_posn += prev_read;
1221 } else {
1222 prev_read = -1;
1225 } while (prev_read > 0);
1226 close(prevlocal);
1228 unlink_or_warn(prevfile);
1231 * Reset inflate/SHA1 if there was an error reading the previous temp
1232 * file; also rewind to the beginning of the local file.
1234 if (prev_read == -1) {
1235 memset(&freq->stream, 0, sizeof(freq->stream));
1236 git_inflate_init(&freq->stream);
1237 git_SHA1_Init(&freq->c);
1238 if (prev_posn>0) {
1239 prev_posn = 0;
1240 lseek(freq->localfile, 0, SEEK_SET);
1241 if (ftruncate(freq->localfile, 0) < 0) {
1242 error("Couldn't truncate temporary file %s: %s",
1243 freq->tmpfile, strerror(errno));
1244 goto abort;
1249 freq->slot = get_active_slot();
1251 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1252 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1253 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1254 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1255 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1258 * If we have successfully processed data from a previous fetch
1259 * attempt, only fetch the data we don't already have.
1261 if (prev_posn>0) {
1262 if (http_is_verbose)
1263 fprintf(stderr,
1264 "Resuming fetch of object %s at byte %ld\n",
1265 hex, prev_posn);
1266 sprintf(range, "Range: bytes=%ld-", prev_posn);
1267 range_header = curl_slist_append(range_header, range);
1268 curl_easy_setopt(freq->slot->curl,
1269 CURLOPT_HTTPHEADER, range_header);
1272 return freq;
1274 abort:
1275 free(freq->url);
1276 free(freq);
1277 return NULL;
1280 void process_http_object_request(struct http_object_request *freq)
1282 if (freq->slot == NULL)
1283 return;
1284 freq->curl_result = freq->slot->curl_result;
1285 freq->http_code = freq->slot->http_code;
1286 freq->slot = NULL;
1289 int finish_http_object_request(struct http_object_request *freq)
1291 struct stat st;
1293 close(freq->localfile);
1294 freq->localfile = -1;
1296 process_http_object_request(freq);
1298 if (freq->http_code == 416) {
1299 warning("requested range invalid; we may already have all the data.");
1300 } else if (freq->curl_result != CURLE_OK) {
1301 if (stat(freq->tmpfile, &st) == 0)
1302 if (st.st_size == 0)
1303 unlink_or_warn(freq->tmpfile);
1304 return -1;
1307 git_inflate_end(&freq->stream);
1308 git_SHA1_Final(freq->real_sha1, &freq->c);
1309 if (freq->zret != Z_STREAM_END) {
1310 unlink_or_warn(freq->tmpfile);
1311 return -1;
1313 if (hashcmp(freq->sha1, freq->real_sha1)) {
1314 unlink_or_warn(freq->tmpfile);
1315 return -1;
1317 freq->rename =
1318 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1320 return freq->rename;
1323 void abort_http_object_request(struct http_object_request *freq)
1325 unlink_or_warn(freq->tmpfile);
1327 release_http_object_request(freq);
1330 void release_http_object_request(struct http_object_request *freq)
1332 if (freq->localfile != -1) {
1333 close(freq->localfile);
1334 freq->localfile = -1;
1336 if (freq->url != NULL) {
1337 free(freq->url);
1338 freq->url = NULL;
1340 if (freq->slot != NULL) {
1341 freq->slot->callback_func = NULL;
1342 freq->slot->callback_data = NULL;
1343 release_active_slot(freq->slot);
1344 freq->slot = NULL;