mingw.c: Use the O_BINARY flag to open files
[git/dscho.git] / http.c
bloba7ebbaf94e3be2577f14e7509859ac3b7ce35a61
1 #include "http.h"
2 #include "pack.h"
3 #include "exec_cmd.h"
5 int data_received;
6 int active_requests;
7 int http_is_verbose;
9 #ifdef USE_CURL_MULTI
10 static int max_requests = -1;
11 static CURLM *curlm;
12 #endif
13 #ifndef NO_CURL_EASY_DUPHANDLE
14 static CURL *curl_default;
15 #endif
17 #define PREV_BUF_SIZE 4096
18 #define RANGE_HEADER_SIZE 30
20 char curl_errorstr[CURL_ERROR_SIZE];
22 static int curl_ssl_verify = -1;
23 static const char *ssl_cert;
24 #if LIBCURL_VERSION_NUM >= 0x070903
25 static const char *ssl_key;
26 #endif
27 #if LIBCURL_VERSION_NUM >= 0x070908
28 static const char *ssl_capath;
29 #endif
30 static const char *ssl_cainfo;
31 static long curl_low_speed_limit = -1;
32 static long curl_low_speed_time = -1;
33 static int curl_ftp_no_epsv;
34 static const char *curl_http_proxy;
35 static char *user_name, *user_pass;
37 #if LIBCURL_VERSION_NUM >= 0x071700
38 /* Use CURLOPT_KEYPASSWD as is */
39 #elif LIBCURL_VERSION_NUM >= 0x070903
40 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
41 #else
42 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
43 #endif
45 static char *ssl_cert_password;
46 static int ssl_cert_password_required;
48 static struct curl_slist *pragma_header;
49 static struct curl_slist *no_pragma_header;
51 static struct active_request_slot *active_queue_head;
53 size_t fread_buffer(void *ptr, size_t eltsize, size_t nmemb, void *buffer_)
55 size_t size = eltsize * nmemb;
56 struct buffer *buffer = buffer_;
58 if (size > buffer->buf.len - buffer->posn)
59 size = buffer->buf.len - buffer->posn;
60 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
61 buffer->posn += size;
63 return size;
66 #ifndef NO_CURL_IOCTL
67 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
69 struct buffer *buffer = clientp;
71 switch (cmd) {
72 case CURLIOCMD_NOP:
73 return CURLIOE_OK;
75 case CURLIOCMD_RESTARTREAD:
76 buffer->posn = 0;
77 return CURLIOE_OK;
79 default:
80 return CURLIOE_UNKNOWNCMD;
83 #endif
85 size_t fwrite_buffer(const void *ptr, size_t eltsize, size_t nmemb, void *buffer_)
87 size_t size = eltsize * nmemb;
88 struct strbuf *buffer = buffer_;
90 strbuf_add(buffer, ptr, size);
91 data_received++;
92 return size;
95 size_t fwrite_null(const void *ptr, size_t eltsize, size_t nmemb, void *strbuf)
97 data_received++;
98 return eltsize * nmemb;
101 static void finish_active_slot(struct active_request_slot *slot);
103 #ifdef USE_CURL_MULTI
104 static void process_curl_messages(void)
106 int num_messages;
107 struct active_request_slot *slot;
108 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
110 while (curl_message != NULL) {
111 if (curl_message->msg == CURLMSG_DONE) {
112 int curl_result = curl_message->data.result;
113 slot = active_queue_head;
114 while (slot != NULL &&
115 slot->curl != curl_message->easy_handle)
116 slot = slot->next;
117 if (slot != NULL) {
118 curl_multi_remove_handle(curlm, slot->curl);
119 slot->curl_result = curl_result;
120 finish_active_slot(slot);
121 } else {
122 fprintf(stderr, "Received DONE message for unknown request!\n");
124 } else {
125 fprintf(stderr, "Unknown CURL message received: %d\n",
126 (int)curl_message->msg);
128 curl_message = curl_multi_info_read(curlm, &num_messages);
131 #endif
133 static int git_config_path(const char **result,
134 const char *var, const char *value)
136 if (git_config_string(result, var, value))
137 return 1;
138 *result = system_path(*result);
139 return 0;
142 static int http_options(const char *var, const char *value, void *cb)
144 if (!strcmp("http.sslverify", var)) {
145 curl_ssl_verify = git_config_bool(var, value);
146 return 0;
148 if (!strcmp("http.sslcert", var))
149 return git_config_path(&ssl_cert, var, value);
150 #if LIBCURL_VERSION_NUM >= 0x070903
151 if (!strcmp("http.sslkey", var))
152 return git_config_path(&ssl_key, var, value);
153 #endif
154 #if LIBCURL_VERSION_NUM >= 0x070908
155 if (!strcmp("http.sslcapath", var))
156 return git_config_path(&ssl_capath, var, value);
157 #endif
158 if (!strcmp("http.sslcainfo", var))
159 return git_config_path(&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;
165 #ifdef USE_CURL_MULTI
166 if (!strcmp("http.maxrequests", var)) {
167 max_requests = git_config_int(var, value);
168 return 0;
170 #endif
171 if (!strcmp("http.lowspeedlimit", var)) {
172 curl_low_speed_limit = (long)git_config_int(var, value);
173 return 0;
175 if (!strcmp("http.lowspeedtime", var)) {
176 curl_low_speed_time = (long)git_config_int(var, value);
177 return 0;
180 if (!strcmp("http.noepsv", var)) {
181 curl_ftp_no_epsv = git_config_bool(var, value);
182 return 0;
184 if (!strcmp("http.proxy", var))
185 return git_config_string(&curl_http_proxy, var, value);
187 /* Fall back on the default ones */
188 return git_default_config(var, value, cb);
191 static void init_curl_http_auth(CURL *result)
193 if (user_name) {
194 struct strbuf up = STRBUF_INIT;
195 if (!user_pass)
196 user_pass = xstrdup(getpass("Password: "));
197 strbuf_addf(&up, "%s:%s", user_name, user_pass);
198 curl_easy_setopt(result, CURLOPT_USERPWD,
199 strbuf_detach(&up, NULL));
203 static int has_cert_password(void)
205 if (ssl_cert_password != NULL)
206 return 1;
207 if (ssl_cert == NULL || ssl_cert_password_required != 1)
208 return 0;
209 /* Only prompt the user once. */
210 ssl_cert_password_required = -1;
211 ssl_cert_password = getpass("Certificate Password: ");
212 if (ssl_cert_password != NULL) {
213 ssl_cert_password = xstrdup(ssl_cert_password);
214 return 1;
215 } else
216 return 0;
219 static CURL *get_curl_handle(void)
221 CURL *result = curl_easy_init();
223 if (!curl_ssl_verify) {
224 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
225 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
226 } else {
227 /* Verify authenticity of the peer's certificate */
228 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
229 /* The name in the cert must match whom we tried to connect */
230 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
233 #if LIBCURL_VERSION_NUM >= 0x070907
234 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
235 #endif
237 init_curl_http_auth(result);
239 if (ssl_cert != NULL)
240 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
241 if (has_cert_password())
242 curl_easy_setopt(result, CURLOPT_KEYPASSWD, ssl_cert_password);
243 #if LIBCURL_VERSION_NUM >= 0x070903
244 if (ssl_key != NULL)
245 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
246 #endif
247 #if LIBCURL_VERSION_NUM >= 0x070908
248 if (ssl_capath != NULL)
249 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
250 #endif
251 if (ssl_cainfo != NULL)
252 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
253 curl_easy_setopt(result, CURLOPT_FAILONERROR, 1);
255 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
256 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
257 curl_low_speed_limit);
258 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
259 curl_low_speed_time);
262 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
264 if (getenv("GIT_CURL_VERBOSE"))
265 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
267 curl_easy_setopt(result, CURLOPT_USERAGENT, GIT_USER_AGENT);
269 if (curl_ftp_no_epsv)
270 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
272 if (curl_http_proxy)
273 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
275 return result;
278 static void http_auth_init(const char *url)
280 char *at, *colon, *cp, *slash;
281 int len;
283 cp = strstr(url, "://");
284 if (!cp)
285 return;
288 * Ok, the URL looks like "proto://something". Which one?
289 * "proto://<user>:<pass>@<host>/...",
290 * "proto://<user>@<host>/...", or just
291 * "proto://<host>/..."?
293 cp += 3;
294 at = strchr(cp, '@');
295 colon = strchr(cp, ':');
296 slash = strchrnul(cp, '/');
297 if (!at || slash <= at)
298 return; /* No credentials */
299 if (!colon || at <= colon) {
300 /* Only username */
301 len = at - cp;
302 user_name = xmalloc(len + 1);
303 memcpy(user_name, cp, len);
304 user_name[len] = '\0';
305 user_pass = NULL;
306 } else {
307 len = colon - cp;
308 user_name = xmalloc(len + 1);
309 memcpy(user_name, cp, len);
310 user_name[len] = '\0';
311 len = at - (colon + 1);
312 user_pass = xmalloc(len + 1);
313 memcpy(user_pass, colon + 1, len);
314 user_pass[len] = '\0';
318 static void set_from_env(const char **var, const char *envname)
320 const char *val = getenv(envname);
321 if (val)
322 *var = val;
325 void http_init(struct remote *remote)
327 char *low_speed_limit;
328 char *low_speed_time;
330 http_is_verbose = 0;
332 git_config(http_options, NULL);
334 curl_global_init(CURL_GLOBAL_ALL);
336 if (remote && remote->http_proxy)
337 curl_http_proxy = xstrdup(remote->http_proxy);
339 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
340 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
342 #ifdef USE_CURL_MULTI
344 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
345 if (http_max_requests != NULL)
346 max_requests = atoi(http_max_requests);
349 curlm = curl_multi_init();
350 if (curlm == NULL) {
351 fprintf(stderr, "Error creating curl multi handle.\n");
352 exit(1);
354 #endif
356 if (getenv("GIT_SSL_NO_VERIFY"))
357 curl_ssl_verify = 0;
359 set_from_env(&ssl_cert, "GIT_SSL_CERT");
360 #if LIBCURL_VERSION_NUM >= 0x070903
361 set_from_env(&ssl_key, "GIT_SSL_KEY");
362 #endif
363 #if LIBCURL_VERSION_NUM >= 0x070908
364 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
365 #endif
366 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
368 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
369 if (low_speed_limit != NULL)
370 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
371 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
372 if (low_speed_time != NULL)
373 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
375 if (curl_ssl_verify == -1)
376 curl_ssl_verify = 1;
378 #ifdef USE_CURL_MULTI
379 if (max_requests < 1)
380 max_requests = DEFAULT_MAX_REQUESTS;
381 #endif
383 if (getenv("GIT_CURL_FTP_NO_EPSV"))
384 curl_ftp_no_epsv = 1;
386 if (remote && remote->url && remote->url[0]) {
387 http_auth_init(remote->url[0]);
388 if (!ssl_cert_password_required &&
389 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
390 !prefixcmp(remote->url[0], "https://"))
391 ssl_cert_password_required = 1;
394 #ifndef NO_CURL_EASY_DUPHANDLE
395 curl_default = get_curl_handle();
396 #endif
399 void http_cleanup(void)
401 struct active_request_slot *slot = active_queue_head;
403 while (slot != NULL) {
404 struct active_request_slot *next = slot->next;
405 if (slot->curl != NULL) {
406 #ifdef USE_CURL_MULTI
407 curl_multi_remove_handle(curlm, slot->curl);
408 #endif
409 curl_easy_cleanup(slot->curl);
411 free(slot);
412 slot = next;
414 active_queue_head = NULL;
416 #ifndef NO_CURL_EASY_DUPHANDLE
417 curl_easy_cleanup(curl_default);
418 #endif
420 #ifdef USE_CURL_MULTI
421 curl_multi_cleanup(curlm);
422 #endif
423 curl_global_cleanup();
425 curl_slist_free_all(pragma_header);
426 pragma_header = NULL;
428 curl_slist_free_all(no_pragma_header);
429 no_pragma_header = NULL;
431 if (curl_http_proxy) {
432 free((void *)curl_http_proxy);
433 curl_http_proxy = NULL;
436 if (ssl_cert_password != NULL) {
437 memset(ssl_cert_password, 0, strlen(ssl_cert_password));
438 free(ssl_cert_password);
439 ssl_cert_password = NULL;
441 ssl_cert_password_required = 0;
444 struct active_request_slot *get_active_slot(void)
446 struct active_request_slot *slot = active_queue_head;
447 struct active_request_slot *newslot;
449 #ifdef USE_CURL_MULTI
450 int num_transfers;
452 /* Wait for a slot to open up if the queue is full */
453 while (active_requests >= max_requests) {
454 curl_multi_perform(curlm, &num_transfers);
455 if (num_transfers < active_requests)
456 process_curl_messages();
458 #endif
460 while (slot != NULL && slot->in_use)
461 slot = slot->next;
463 if (slot == NULL) {
464 newslot = xmalloc(sizeof(*newslot));
465 newslot->curl = NULL;
466 newslot->in_use = 0;
467 newslot->next = NULL;
469 slot = active_queue_head;
470 if (slot == NULL) {
471 active_queue_head = newslot;
472 } else {
473 while (slot->next != NULL)
474 slot = slot->next;
475 slot->next = newslot;
477 slot = newslot;
480 if (slot->curl == NULL) {
481 #ifdef NO_CURL_EASY_DUPHANDLE
482 slot->curl = get_curl_handle();
483 #else
484 slot->curl = curl_easy_duphandle(curl_default);
485 #endif
488 active_requests++;
489 slot->in_use = 1;
490 slot->local = NULL;
491 slot->results = NULL;
492 slot->finished = NULL;
493 slot->callback_data = NULL;
494 slot->callback_func = NULL;
495 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
496 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
497 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
498 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
499 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
500 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
501 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
503 return slot;
506 int start_active_slot(struct active_request_slot *slot)
508 #ifdef USE_CURL_MULTI
509 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
510 int num_transfers;
512 if (curlm_result != CURLM_OK &&
513 curlm_result != CURLM_CALL_MULTI_PERFORM) {
514 active_requests--;
515 slot->in_use = 0;
516 return 0;
520 * We know there must be something to do, since we just added
521 * something.
523 curl_multi_perform(curlm, &num_transfers);
524 #endif
525 return 1;
528 #ifdef USE_CURL_MULTI
529 struct fill_chain {
530 void *data;
531 int (*fill)(void *);
532 struct fill_chain *next;
535 static struct fill_chain *fill_cfg;
537 void add_fill_function(void *data, int (*fill)(void *))
539 struct fill_chain *new = xmalloc(sizeof(*new));
540 struct fill_chain **linkp = &fill_cfg;
541 new->data = data;
542 new->fill = fill;
543 new->next = NULL;
544 while (*linkp)
545 linkp = &(*linkp)->next;
546 *linkp = new;
549 void fill_active_slots(void)
551 struct active_request_slot *slot = active_queue_head;
553 while (active_requests < max_requests) {
554 struct fill_chain *fill;
555 for (fill = fill_cfg; fill; fill = fill->next)
556 if (fill->fill(fill->data))
557 break;
559 if (!fill)
560 break;
563 while (slot != NULL) {
564 if (!slot->in_use && slot->curl != NULL) {
565 curl_easy_cleanup(slot->curl);
566 slot->curl = NULL;
568 slot = slot->next;
572 void step_active_slots(void)
574 int num_transfers;
575 CURLMcode curlm_result;
577 do {
578 curlm_result = curl_multi_perform(curlm, &num_transfers);
579 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
580 if (num_transfers < active_requests) {
581 process_curl_messages();
582 fill_active_slots();
585 #endif
587 void run_active_slot(struct active_request_slot *slot)
589 #ifdef USE_CURL_MULTI
590 long last_pos = 0;
591 long current_pos;
592 fd_set readfds;
593 fd_set writefds;
594 fd_set excfds;
595 int max_fd;
596 struct timeval select_timeout;
597 int finished = 0;
599 slot->finished = &finished;
600 while (!finished) {
601 data_received = 0;
602 step_active_slots();
604 if (!data_received && slot->local != NULL) {
605 current_pos = ftell(slot->local);
606 if (current_pos > last_pos)
607 data_received++;
608 last_pos = current_pos;
611 if (slot->in_use && !data_received) {
612 max_fd = 0;
613 FD_ZERO(&readfds);
614 FD_ZERO(&writefds);
615 FD_ZERO(&excfds);
616 select_timeout.tv_sec = 0;
617 select_timeout.tv_usec = 50000;
618 select(max_fd, &readfds, &writefds,
619 &excfds, &select_timeout);
622 #else
623 while (slot->in_use) {
624 slot->curl_result = curl_easy_perform(slot->curl);
625 finish_active_slot(slot);
627 #endif
630 static void closedown_active_slot(struct active_request_slot *slot)
632 active_requests--;
633 slot->in_use = 0;
636 void release_active_slot(struct active_request_slot *slot)
638 closedown_active_slot(slot);
639 if (slot->curl) {
640 #ifdef USE_CURL_MULTI
641 curl_multi_remove_handle(curlm, slot->curl);
642 #endif
643 curl_easy_cleanup(slot->curl);
644 slot->curl = NULL;
646 #ifdef USE_CURL_MULTI
647 fill_active_slots();
648 #endif
651 static void finish_active_slot(struct active_request_slot *slot)
653 closedown_active_slot(slot);
654 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
656 if (slot->finished != NULL)
657 (*slot->finished) = 1;
659 /* Store slot results so they can be read after the slot is reused */
660 if (slot->results != NULL) {
661 slot->results->curl_result = slot->curl_result;
662 slot->results->http_code = slot->http_code;
665 /* Run callback if appropriate */
666 if (slot->callback_func != NULL)
667 slot->callback_func(slot->callback_data);
670 void finish_all_active_slots(void)
672 struct active_request_slot *slot = active_queue_head;
674 while (slot != NULL)
675 if (slot->in_use) {
676 run_active_slot(slot);
677 slot = active_queue_head;
678 } else {
679 slot = slot->next;
683 /* Helpers for modifying and creating URLs */
684 static inline int needs_quote(int ch)
686 if (((ch >= 'A') && (ch <= 'Z'))
687 || ((ch >= 'a') && (ch <= 'z'))
688 || ((ch >= '0') && (ch <= '9'))
689 || (ch == '/')
690 || (ch == '-')
691 || (ch == '.'))
692 return 0;
693 return 1;
696 static inline int hex(int v)
698 if (v < 10)
699 return '0' + v;
700 else
701 return 'A' + v - 10;
704 static void end_url_with_slash(struct strbuf *buf, const char *url)
706 strbuf_addstr(buf, url);
707 if (buf->len && buf->buf[buf->len - 1] != '/')
708 strbuf_addstr(buf, "/");
711 static char *quote_ref_url(const char *base, const char *ref)
713 struct strbuf buf = STRBUF_INIT;
714 const char *cp;
715 int ch;
717 end_url_with_slash(&buf, base);
719 for (cp = ref; (ch = *cp) != 0; cp++)
720 if (needs_quote(ch))
721 strbuf_addf(&buf, "%%%02x", ch);
722 else
723 strbuf_addch(&buf, *cp);
725 return strbuf_detach(&buf, NULL);
728 void append_remote_object_url(struct strbuf *buf, const char *url,
729 const char *hex,
730 int only_two_digit_prefix)
732 strbuf_addf(buf, "%s/objects/%.*s/", url, 2, hex);
733 if (!only_two_digit_prefix)
734 strbuf_addf(buf, "%s", hex+2);
737 char *get_remote_object_url(const char *url, const char *hex,
738 int only_two_digit_prefix)
740 struct strbuf buf = STRBUF_INIT;
741 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
742 return strbuf_detach(&buf, NULL);
745 /* http_request() targets */
746 #define HTTP_REQUEST_STRBUF 0
747 #define HTTP_REQUEST_FILE 1
749 static int http_request(const char *url, void *result, int target, int options)
751 struct active_request_slot *slot;
752 struct slot_results results;
753 struct curl_slist *headers = NULL;
754 struct strbuf buf = STRBUF_INIT;
755 int ret;
757 slot = get_active_slot();
758 slot->results = &results;
759 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
761 if (result == NULL) {
762 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
763 } else {
764 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
765 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
767 if (target == HTTP_REQUEST_FILE) {
768 long posn = ftell(result);
769 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
770 fwrite);
771 if (posn > 0) {
772 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
773 headers = curl_slist_append(headers, buf.buf);
774 strbuf_reset(&buf);
776 slot->local = result;
777 } else
778 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
779 fwrite_buffer);
782 strbuf_addstr(&buf, "Pragma:");
783 if (options & HTTP_NO_CACHE)
784 strbuf_addstr(&buf, " no-cache");
786 headers = curl_slist_append(headers, buf.buf);
788 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
789 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
791 if (start_active_slot(slot)) {
792 run_active_slot(slot);
793 if (results.curl_result == CURLE_OK)
794 ret = HTTP_OK;
795 else if (missing_target(&results))
796 ret = HTTP_MISSING_TARGET;
797 else
798 ret = HTTP_ERROR;
799 } else {
800 error("Unable to start HTTP request for %s", url);
801 ret = HTTP_START_FAILED;
804 slot->local = NULL;
805 curl_slist_free_all(headers);
806 strbuf_release(&buf);
808 return ret;
811 int http_get_strbuf(const char *url, struct strbuf *result, int options)
813 return http_request(url, result, HTTP_REQUEST_STRBUF, options);
816 int http_get_file(const char *url, const char *filename, int options)
818 int ret;
819 struct strbuf tmpfile = STRBUF_INIT;
820 FILE *result;
822 strbuf_addf(&tmpfile, "%s.temp", filename);
823 result = fopen(tmpfile.buf, "a");
824 if (! result) {
825 error("Unable to open local file %s", tmpfile.buf);
826 ret = HTTP_ERROR;
827 goto cleanup;
830 ret = http_request(url, result, HTTP_REQUEST_FILE, options);
831 fclose(result);
833 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
834 ret = HTTP_ERROR;
835 cleanup:
836 strbuf_release(&tmpfile);
837 return ret;
840 int http_error(const char *url, int ret)
842 /* http_request has already handled HTTP_START_FAILED. */
843 if (ret != HTTP_START_FAILED)
844 error("%s while accessing %s\n", curl_errorstr, url);
846 return ret;
849 int http_fetch_ref(const char *base, struct ref *ref)
851 char *url;
852 struct strbuf buffer = STRBUF_INIT;
853 int ret = -1;
855 url = quote_ref_url(base, ref->name);
856 if (http_get_strbuf(url, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
857 strbuf_rtrim(&buffer);
858 if (buffer.len == 40)
859 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
860 else if (!prefixcmp(buffer.buf, "ref: ")) {
861 ref->symref = xstrdup(buffer.buf + 5);
862 ret = 0;
866 strbuf_release(&buffer);
867 free(url);
868 return ret;
871 /* Helpers for fetching packs */
872 static int fetch_pack_index(unsigned char *sha1, const char *base_url)
874 int ret = 0;
875 char *hex = xstrdup(sha1_to_hex(sha1));
876 char *filename;
877 char *url;
878 struct strbuf buf = STRBUF_INIT;
880 /* Don't use the index if the pack isn't there */
881 end_url_with_slash(&buf, base_url);
882 strbuf_addf(&buf, "objects/pack/pack-%s.pack", hex);
883 url = strbuf_detach(&buf, 0);
885 if (http_get_strbuf(url, NULL, 0)) {
886 ret = error("Unable to verify pack %s is available",
887 hex);
888 goto cleanup;
891 if (has_pack_index(sha1)) {
892 ret = 0;
893 goto cleanup;
896 if (http_is_verbose)
897 fprintf(stderr, "Getting index for pack %s\n", hex);
899 end_url_with_slash(&buf, base_url);
900 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hex);
901 url = strbuf_detach(&buf, NULL);
903 filename = sha1_pack_index_name(sha1);
904 if (http_get_file(url, filename, 0) != HTTP_OK)
905 ret = error("Unable to get pack index %s\n", url);
907 cleanup:
908 free(hex);
909 free(url);
910 return ret;
913 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
914 unsigned char *sha1, const char *base_url)
916 struct packed_git *new_pack;
918 if (fetch_pack_index(sha1, base_url))
919 return -1;
921 new_pack = parse_pack_index(sha1);
922 if (!new_pack)
923 return -1; /* parse_pack_index() already issued error message */
924 new_pack->next = *packs_head;
925 *packs_head = new_pack;
926 return 0;
929 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
931 int ret = 0, i = 0;
932 char *url, *data;
933 struct strbuf buf = STRBUF_INIT;
934 unsigned char sha1[20];
936 end_url_with_slash(&buf, base_url);
937 strbuf_addstr(&buf, "objects/info/packs");
938 url = strbuf_detach(&buf, NULL);
940 ret = http_get_strbuf(url, &buf, HTTP_NO_CACHE);
941 if (ret != HTTP_OK)
942 goto cleanup;
944 data = buf.buf;
945 while (i < buf.len) {
946 switch (data[i]) {
947 case 'P':
948 i++;
949 if (i + 52 <= buf.len &&
950 !prefixcmp(data + i, " pack-") &&
951 !prefixcmp(data + i + 46, ".pack\n")) {
952 get_sha1_hex(data + i + 6, sha1);
953 fetch_and_setup_pack_index(packs_head, sha1,
954 base_url);
955 i += 51;
956 break;
958 default:
959 while (i < buf.len && data[i] != '\n')
960 i++;
962 i++;
965 cleanup:
966 free(url);
967 return ret;
970 void release_http_pack_request(struct http_pack_request *preq)
972 if (preq->packfile != NULL) {
973 fclose(preq->packfile);
974 preq->packfile = NULL;
975 preq->slot->local = NULL;
977 if (preq->range_header != NULL) {
978 curl_slist_free_all(preq->range_header);
979 preq->range_header = NULL;
981 preq->slot = NULL;
982 free(preq->url);
985 int finish_http_pack_request(struct http_pack_request *preq)
987 int ret;
988 struct packed_git **lst;
990 preq->target->pack_size = ftell(preq->packfile);
992 if (preq->packfile != NULL) {
993 fclose(preq->packfile);
994 preq->packfile = NULL;
995 preq->slot->local = NULL;
998 ret = move_temp_to_file(preq->tmpfile, preq->filename);
999 if (ret)
1000 return ret;
1002 lst = preq->lst;
1003 while (*lst != preq->target)
1004 lst = &((*lst)->next);
1005 *lst = (*lst)->next;
1007 if (verify_pack(preq->target))
1008 return -1;
1009 install_packed_git(preq->target);
1011 return 0;
1014 struct http_pack_request *new_http_pack_request(
1015 struct packed_git *target, const char *base_url)
1017 char *url;
1018 char *filename;
1019 long prev_posn = 0;
1020 char range[RANGE_HEADER_SIZE];
1021 struct strbuf buf = STRBUF_INIT;
1022 struct http_pack_request *preq;
1024 preq = xmalloc(sizeof(*preq));
1025 preq->target = target;
1026 preq->range_header = NULL;
1028 end_url_with_slash(&buf, base_url);
1029 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1030 sha1_to_hex(target->sha1));
1031 url = strbuf_detach(&buf, NULL);
1032 preq->url = xstrdup(url);
1034 filename = sha1_pack_name(target->sha1);
1035 snprintf(preq->filename, sizeof(preq->filename), "%s", filename);
1036 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp", filename);
1037 preq->packfile = fopen(preq->tmpfile, "a");
1038 if (!preq->packfile) {
1039 error("Unable to open local file %s for pack",
1040 preq->tmpfile);
1041 goto abort;
1044 preq->slot = get_active_slot();
1045 preq->slot->local = preq->packfile;
1046 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1047 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1048 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, url);
1049 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1050 no_pragma_header);
1053 * If there is data present from a previous transfer attempt,
1054 * resume where it left off
1056 prev_posn = ftell(preq->packfile);
1057 if (prev_posn>0) {
1058 if (http_is_verbose)
1059 fprintf(stderr,
1060 "Resuming fetch of pack %s at byte %ld\n",
1061 sha1_to_hex(target->sha1), prev_posn);
1062 sprintf(range, "Range: bytes=%ld-", prev_posn);
1063 preq->range_header = curl_slist_append(NULL, range);
1064 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1065 preq->range_header);
1068 return preq;
1070 abort:
1071 free(filename);
1072 return NULL;
1075 /* Helpers for fetching objects (loose) */
1076 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
1077 void *data)
1079 unsigned char expn[4096];
1080 size_t size = eltsize * nmemb;
1081 int posn = 0;
1082 struct http_object_request *freq =
1083 (struct http_object_request *)data;
1084 do {
1085 ssize_t retval = xwrite(freq->localfile,
1086 (char *) ptr + posn, size - posn);
1087 if (retval < 0)
1088 return posn;
1089 posn += retval;
1090 } while (posn < size);
1092 freq->stream.avail_in = size;
1093 freq->stream.next_in = ptr;
1094 do {
1095 freq->stream.next_out = expn;
1096 freq->stream.avail_out = sizeof(expn);
1097 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1098 git_SHA1_Update(&freq->c, expn,
1099 sizeof(expn) - freq->stream.avail_out);
1100 } while (freq->stream.avail_in && freq->zret == Z_OK);
1101 data_received++;
1102 return size;
1105 struct http_object_request *new_http_object_request(const char *base_url,
1106 unsigned char *sha1)
1108 char *hex = sha1_to_hex(sha1);
1109 char *filename;
1110 char prevfile[PATH_MAX];
1111 char *url;
1112 int prevlocal;
1113 unsigned char prev_buf[PREV_BUF_SIZE];
1114 ssize_t prev_read = 0;
1115 long prev_posn = 0;
1116 char range[RANGE_HEADER_SIZE];
1117 struct curl_slist *range_header = NULL;
1118 struct http_object_request *freq;
1120 freq = xmalloc(sizeof(*freq));
1121 hashcpy(freq->sha1, sha1);
1122 freq->localfile = -1;
1124 filename = sha1_file_name(sha1);
1125 snprintf(freq->filename, sizeof(freq->filename), "%s", filename);
1126 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1127 "%s.temp", filename);
1129 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1130 unlink_or_warn(prevfile);
1131 rename(freq->tmpfile, prevfile);
1132 unlink_or_warn(freq->tmpfile);
1134 if (freq->localfile != -1)
1135 error("fd leakage in start: %d", freq->localfile);
1136 freq->localfile = open(freq->tmpfile,
1137 O_WRONLY | O_CREAT | O_EXCL, 0666);
1139 * This could have failed due to the "lazy directory creation";
1140 * try to mkdir the last path component.
1142 if (freq->localfile < 0 && errno == ENOENT) {
1143 char *dir = strrchr(freq->tmpfile, '/');
1144 if (dir) {
1145 *dir = 0;
1146 mkdir(freq->tmpfile, 0777);
1147 *dir = '/';
1149 freq->localfile = open(freq->tmpfile,
1150 O_WRONLY | O_CREAT | O_EXCL, 0666);
1153 if (freq->localfile < 0) {
1154 error("Couldn't create temporary file %s for %s: %s",
1155 freq->tmpfile, freq->filename, strerror(errno));
1156 goto abort;
1159 memset(&freq->stream, 0, sizeof(freq->stream));
1161 git_inflate_init(&freq->stream);
1163 git_SHA1_Init(&freq->c);
1165 url = get_remote_object_url(base_url, hex, 0);
1166 freq->url = xstrdup(url);
1169 * If a previous temp file is present, process what was already
1170 * fetched.
1172 prevlocal = open(prevfile, O_RDONLY);
1173 if (prevlocal != -1) {
1174 do {
1175 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1176 if (prev_read>0) {
1177 if (fwrite_sha1_file(prev_buf,
1179 prev_read,
1180 freq) == prev_read) {
1181 prev_posn += prev_read;
1182 } else {
1183 prev_read = -1;
1186 } while (prev_read > 0);
1187 close(prevlocal);
1189 unlink_or_warn(prevfile);
1192 * Reset inflate/SHA1 if there was an error reading the previous temp
1193 * file; also rewind to the beginning of the local file.
1195 if (prev_read == -1) {
1196 memset(&freq->stream, 0, sizeof(freq->stream));
1197 git_inflate_init(&freq->stream);
1198 git_SHA1_Init(&freq->c);
1199 if (prev_posn>0) {
1200 prev_posn = 0;
1201 lseek(freq->localfile, 0, SEEK_SET);
1202 ftruncate(freq->localfile, 0);
1206 freq->slot = get_active_slot();
1208 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1209 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1210 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1211 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, url);
1212 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1215 * If we have successfully processed data from a previous fetch
1216 * attempt, only fetch the data we don't already have.
1218 if (prev_posn>0) {
1219 if (http_is_verbose)
1220 fprintf(stderr,
1221 "Resuming fetch of object %s at byte %ld\n",
1222 hex, prev_posn);
1223 sprintf(range, "Range: bytes=%ld-", prev_posn);
1224 range_header = curl_slist_append(range_header, range);
1225 curl_easy_setopt(freq->slot->curl,
1226 CURLOPT_HTTPHEADER, range_header);
1229 return freq;
1231 free(url);
1232 abort:
1233 free(filename);
1234 free(freq);
1235 return NULL;
1238 void process_http_object_request(struct http_object_request *freq)
1240 if (freq->slot == NULL)
1241 return;
1242 freq->curl_result = freq->slot->curl_result;
1243 freq->http_code = freq->slot->http_code;
1244 freq->slot = NULL;
1247 int finish_http_object_request(struct http_object_request *freq)
1249 struct stat st;
1251 close(freq->localfile);
1252 freq->localfile = -1;
1254 process_http_object_request(freq);
1256 if (freq->http_code == 416) {
1257 fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
1258 } else if (freq->curl_result != CURLE_OK) {
1259 if (stat(freq->tmpfile, &st) == 0)
1260 if (st.st_size == 0)
1261 unlink_or_warn(freq->tmpfile);
1262 return -1;
1265 git_inflate_end(&freq->stream);
1266 git_SHA1_Final(freq->real_sha1, &freq->c);
1267 if (freq->zret != Z_STREAM_END) {
1268 unlink_or_warn(freq->tmpfile);
1269 return -1;
1271 if (hashcmp(freq->sha1, freq->real_sha1)) {
1272 unlink_or_warn(freq->tmpfile);
1273 return -1;
1275 freq->rename =
1276 move_temp_to_file(freq->tmpfile, freq->filename);
1278 return freq->rename;
1281 void abort_http_object_request(struct http_object_request *freq)
1283 unlink_or_warn(freq->tmpfile);
1285 release_http_object_request(freq);
1288 void release_http_object_request(struct http_object_request *freq)
1290 if (freq->localfile != -1) {
1291 close(freq->localfile);
1292 freq->localfile = -1;
1294 if (freq->url != NULL) {
1295 free(freq->url);
1296 freq->url = NULL;
1298 freq->slot = NULL;