Make the MSVC projects use PDB/IDB files named after the project
[git/dscho.git] / http.c
blob968520b8c4217631e32a985b59d17d79272f2bed
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 end_url_with_slash(buf, url);
734 strbuf_addf(buf, "objects/%.*s/", 2, hex);
735 if (!only_two_digit_prefix)
736 strbuf_addf(buf, "%s", hex+2);
739 char *get_remote_object_url(const char *url, const char *hex,
740 int only_two_digit_prefix)
742 struct strbuf buf = STRBUF_INIT;
743 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
744 return strbuf_detach(&buf, NULL);
747 /* http_request() targets */
748 #define HTTP_REQUEST_STRBUF 0
749 #define HTTP_REQUEST_FILE 1
751 static int http_request(const char *url, void *result, int target, int options)
753 struct active_request_slot *slot;
754 struct slot_results results;
755 struct curl_slist *headers = NULL;
756 struct strbuf buf = STRBUF_INIT;
757 int ret;
759 slot = get_active_slot();
760 slot->results = &results;
761 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
763 if (result == NULL) {
764 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
765 } else {
766 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
767 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
769 if (target == HTTP_REQUEST_FILE) {
770 long posn = ftell(result);
771 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
772 fwrite);
773 if (posn > 0) {
774 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
775 headers = curl_slist_append(headers, buf.buf);
776 strbuf_reset(&buf);
778 slot->local = result;
779 } else
780 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
781 fwrite_buffer);
784 strbuf_addstr(&buf, "Pragma:");
785 if (options & HTTP_NO_CACHE)
786 strbuf_addstr(&buf, " no-cache");
788 headers = curl_slist_append(headers, buf.buf);
790 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
791 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
793 if (start_active_slot(slot)) {
794 run_active_slot(slot);
795 if (results.curl_result == CURLE_OK)
796 ret = HTTP_OK;
797 else if (missing_target(&results))
798 ret = HTTP_MISSING_TARGET;
799 else
800 ret = HTTP_ERROR;
801 } else {
802 error("Unable to start HTTP request for %s", url);
803 ret = HTTP_START_FAILED;
806 slot->local = NULL;
807 curl_slist_free_all(headers);
808 strbuf_release(&buf);
810 return ret;
813 int http_get_strbuf(const char *url, struct strbuf *result, int options)
815 return http_request(url, result, HTTP_REQUEST_STRBUF, options);
818 int http_get_file(const char *url, const char *filename, int options)
820 int ret;
821 struct strbuf tmpfile = STRBUF_INIT;
822 FILE *result;
824 strbuf_addf(&tmpfile, "%s.temp", filename);
825 result = fopen(tmpfile.buf, "a");
826 if (! result) {
827 error("Unable to open local file %s", tmpfile.buf);
828 ret = HTTP_ERROR;
829 goto cleanup;
832 ret = http_request(url, result, HTTP_REQUEST_FILE, options);
833 fclose(result);
835 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
836 ret = HTTP_ERROR;
837 cleanup:
838 strbuf_release(&tmpfile);
839 return ret;
842 int http_error(const char *url, int ret)
844 /* http_request has already handled HTTP_START_FAILED. */
845 if (ret != HTTP_START_FAILED)
846 error("%s while accessing %s\n", curl_errorstr, url);
848 return ret;
851 int http_fetch_ref(const char *base, struct ref *ref)
853 char *url;
854 struct strbuf buffer = STRBUF_INIT;
855 int ret = -1;
857 url = quote_ref_url(base, ref->name);
858 if (http_get_strbuf(url, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
859 strbuf_rtrim(&buffer);
860 if (buffer.len == 40)
861 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
862 else if (!prefixcmp(buffer.buf, "ref: ")) {
863 ref->symref = xstrdup(buffer.buf + 5);
864 ret = 0;
868 strbuf_release(&buffer);
869 free(url);
870 return ret;
873 /* Helpers for fetching packs */
874 static int fetch_pack_index(unsigned char *sha1, const char *base_url)
876 int ret = 0;
877 char *hex = xstrdup(sha1_to_hex(sha1));
878 char *filename;
879 char *url = NULL;
880 struct strbuf buf = STRBUF_INIT;
882 if (has_pack_index(sha1)) {
883 ret = 0;
884 goto cleanup;
887 if (http_is_verbose)
888 fprintf(stderr, "Getting index for pack %s\n", hex);
890 end_url_with_slash(&buf, base_url);
891 strbuf_addf(&buf, "objects/pack/pack-%s.idx", hex);
892 url = strbuf_detach(&buf, NULL);
894 filename = sha1_pack_index_name(sha1);
895 if (http_get_file(url, filename, 0) != HTTP_OK)
896 ret = error("Unable to get pack index %s\n", url);
898 cleanup:
899 free(hex);
900 free(url);
901 return ret;
904 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
905 unsigned char *sha1, const char *base_url)
907 struct packed_git *new_pack;
909 if (fetch_pack_index(sha1, base_url))
910 return -1;
912 new_pack = parse_pack_index(sha1);
913 if (!new_pack)
914 return -1; /* parse_pack_index() already issued error message */
915 new_pack->next = *packs_head;
916 *packs_head = new_pack;
917 return 0;
920 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
922 int ret = 0, i = 0;
923 char *url, *data;
924 struct strbuf buf = STRBUF_INIT;
925 unsigned char sha1[20];
927 end_url_with_slash(&buf, base_url);
928 strbuf_addstr(&buf, "objects/info/packs");
929 url = strbuf_detach(&buf, NULL);
931 ret = http_get_strbuf(url, &buf, HTTP_NO_CACHE);
932 if (ret != HTTP_OK)
933 goto cleanup;
935 data = buf.buf;
936 while (i < buf.len) {
937 switch (data[i]) {
938 case 'P':
939 i++;
940 if (i + 52 <= buf.len &&
941 !prefixcmp(data + i, " pack-") &&
942 !prefixcmp(data + i + 46, ".pack\n")) {
943 get_sha1_hex(data + i + 6, sha1);
944 fetch_and_setup_pack_index(packs_head, sha1,
945 base_url);
946 i += 51;
947 break;
949 default:
950 while (i < buf.len && data[i] != '\n')
951 i++;
953 i++;
956 cleanup:
957 free(url);
958 return ret;
961 void release_http_pack_request(struct http_pack_request *preq)
963 if (preq->packfile != NULL) {
964 fclose(preq->packfile);
965 preq->packfile = NULL;
966 preq->slot->local = NULL;
968 if (preq->range_header != NULL) {
969 curl_slist_free_all(preq->range_header);
970 preq->range_header = NULL;
972 preq->slot = NULL;
973 free(preq->url);
976 int finish_http_pack_request(struct http_pack_request *preq)
978 int ret;
979 struct packed_git **lst;
981 preq->target->pack_size = ftell(preq->packfile);
983 if (preq->packfile != NULL) {
984 fclose(preq->packfile);
985 preq->packfile = NULL;
986 preq->slot->local = NULL;
989 ret = move_temp_to_file(preq->tmpfile, preq->filename);
990 if (ret)
991 return ret;
993 lst = preq->lst;
994 while (*lst != preq->target)
995 lst = &((*lst)->next);
996 *lst = (*lst)->next;
998 if (verify_pack(preq->target))
999 return -1;
1000 install_packed_git(preq->target);
1002 return 0;
1005 struct http_pack_request *new_http_pack_request(
1006 struct packed_git *target, const char *base_url)
1008 char *filename;
1009 long prev_posn = 0;
1010 char range[RANGE_HEADER_SIZE];
1011 struct strbuf buf = STRBUF_INIT;
1012 struct http_pack_request *preq;
1014 preq = xmalloc(sizeof(*preq));
1015 preq->target = target;
1016 preq->range_header = NULL;
1018 end_url_with_slash(&buf, base_url);
1019 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1020 sha1_to_hex(target->sha1));
1021 preq->url = strbuf_detach(&buf, NULL);
1023 filename = sha1_pack_name(target->sha1);
1024 snprintf(preq->filename, sizeof(preq->filename), "%s", filename);
1025 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp", filename);
1026 preq->packfile = fopen(preq->tmpfile, "a");
1027 if (!preq->packfile) {
1028 error("Unable to open local file %s for pack",
1029 preq->tmpfile);
1030 goto abort;
1033 preq->slot = get_active_slot();
1034 preq->slot->local = preq->packfile;
1035 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1036 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1037 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1038 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1039 no_pragma_header);
1042 * If there is data present from a previous transfer attempt,
1043 * resume where it left off
1045 prev_posn = ftell(preq->packfile);
1046 if (prev_posn>0) {
1047 if (http_is_verbose)
1048 fprintf(stderr,
1049 "Resuming fetch of pack %s at byte %ld\n",
1050 sha1_to_hex(target->sha1), prev_posn);
1051 sprintf(range, "Range: bytes=%ld-", prev_posn);
1052 preq->range_header = curl_slist_append(NULL, range);
1053 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1054 preq->range_header);
1057 return preq;
1059 abort:
1060 free(filename);
1061 free(preq->url);
1062 free(preq);
1063 return NULL;
1066 /* Helpers for fetching objects (loose) */
1067 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
1068 void *data)
1070 unsigned char expn[4096];
1071 size_t size = eltsize * nmemb;
1072 int posn = 0;
1073 struct http_object_request *freq =
1074 (struct http_object_request *)data;
1075 do {
1076 ssize_t retval = xwrite(freq->localfile,
1077 (char *) ptr + posn, size - posn);
1078 if (retval < 0)
1079 return posn;
1080 posn += retval;
1081 } while (posn < size);
1083 freq->stream.avail_in = size;
1084 freq->stream.next_in = ptr;
1085 do {
1086 freq->stream.next_out = expn;
1087 freq->stream.avail_out = sizeof(expn);
1088 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1089 git_SHA1_Update(&freq->c, expn,
1090 sizeof(expn) - freq->stream.avail_out);
1091 } while (freq->stream.avail_in && freq->zret == Z_OK);
1092 data_received++;
1093 return size;
1096 struct http_object_request *new_http_object_request(const char *base_url,
1097 unsigned char *sha1)
1099 char *hex = sha1_to_hex(sha1);
1100 char *filename;
1101 char prevfile[PATH_MAX];
1102 int prevlocal;
1103 unsigned char prev_buf[PREV_BUF_SIZE];
1104 ssize_t prev_read = 0;
1105 long prev_posn = 0;
1106 char range[RANGE_HEADER_SIZE];
1107 struct curl_slist *range_header = NULL;
1108 struct http_object_request *freq;
1110 freq = xmalloc(sizeof(*freq));
1111 hashcpy(freq->sha1, sha1);
1112 freq->localfile = -1;
1114 filename = sha1_file_name(sha1);
1115 snprintf(freq->filename, sizeof(freq->filename), "%s", filename);
1116 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1117 "%s.temp", filename);
1119 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1120 unlink_or_warn(prevfile);
1121 rename(freq->tmpfile, prevfile);
1122 unlink_or_warn(freq->tmpfile);
1124 if (freq->localfile != -1)
1125 error("fd leakage in start: %d", freq->localfile);
1126 freq->localfile = open(freq->tmpfile,
1127 O_WRONLY | O_CREAT | O_EXCL, 0666);
1129 * This could have failed due to the "lazy directory creation";
1130 * try to mkdir the last path component.
1132 if (freq->localfile < 0 && errno == ENOENT) {
1133 char *dir = strrchr(freq->tmpfile, '/');
1134 if (dir) {
1135 *dir = 0;
1136 mkdir(freq->tmpfile, 0777);
1137 *dir = '/';
1139 freq->localfile = open(freq->tmpfile,
1140 O_WRONLY | O_CREAT | O_EXCL, 0666);
1143 if (freq->localfile < 0) {
1144 error("Couldn't create temporary file %s for %s: %s",
1145 freq->tmpfile, freq->filename, strerror(errno));
1146 goto abort;
1149 memset(&freq->stream, 0, sizeof(freq->stream));
1151 git_inflate_init(&freq->stream);
1153 git_SHA1_Init(&freq->c);
1155 freq->url = get_remote_object_url(base_url, hex, 0);
1158 * If a previous temp file is present, process what was already
1159 * fetched.
1161 prevlocal = open(prevfile, O_RDONLY);
1162 if (prevlocal != -1) {
1163 do {
1164 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1165 if (prev_read>0) {
1166 if (fwrite_sha1_file(prev_buf,
1168 prev_read,
1169 freq) == prev_read) {
1170 prev_posn += prev_read;
1171 } else {
1172 prev_read = -1;
1175 } while (prev_read > 0);
1176 close(prevlocal);
1178 unlink_or_warn(prevfile);
1181 * Reset inflate/SHA1 if there was an error reading the previous temp
1182 * file; also rewind to the beginning of the local file.
1184 if (prev_read == -1) {
1185 memset(&freq->stream, 0, sizeof(freq->stream));
1186 git_inflate_init(&freq->stream);
1187 git_SHA1_Init(&freq->c);
1188 if (prev_posn>0) {
1189 prev_posn = 0;
1190 lseek(freq->localfile, 0, SEEK_SET);
1191 if (ftruncate(freq->localfile, 0) < 0) {
1192 error("Couldn't truncate temporary file %s for %s: %s",
1193 freq->tmpfile, freq->filename, strerror(errno));
1194 goto abort;
1199 freq->slot = get_active_slot();
1201 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1202 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1203 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1204 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1205 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1208 * If we have successfully processed data from a previous fetch
1209 * attempt, only fetch the data we don't already have.
1211 if (prev_posn>0) {
1212 if (http_is_verbose)
1213 fprintf(stderr,
1214 "Resuming fetch of object %s at byte %ld\n",
1215 hex, prev_posn);
1216 sprintf(range, "Range: bytes=%ld-", prev_posn);
1217 range_header = curl_slist_append(range_header, range);
1218 curl_easy_setopt(freq->slot->curl,
1219 CURLOPT_HTTPHEADER, range_header);
1222 return freq;
1224 abort:
1225 free(filename);
1226 free(freq->url);
1227 free(freq);
1228 return NULL;
1231 void process_http_object_request(struct http_object_request *freq)
1233 if (freq->slot == NULL)
1234 return;
1235 freq->curl_result = freq->slot->curl_result;
1236 freq->http_code = freq->slot->http_code;
1237 freq->slot = NULL;
1240 int finish_http_object_request(struct http_object_request *freq)
1242 struct stat st;
1244 close(freq->localfile);
1245 freq->localfile = -1;
1247 process_http_object_request(freq);
1249 if (freq->http_code == 416) {
1250 fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
1251 } else if (freq->curl_result != CURLE_OK) {
1252 if (stat(freq->tmpfile, &st) == 0)
1253 if (st.st_size == 0)
1254 unlink_or_warn(freq->tmpfile);
1255 return -1;
1258 git_inflate_end(&freq->stream);
1259 git_SHA1_Final(freq->real_sha1, &freq->c);
1260 if (freq->zret != Z_STREAM_END) {
1261 unlink_or_warn(freq->tmpfile);
1262 return -1;
1264 if (hashcmp(freq->sha1, freq->real_sha1)) {
1265 unlink_or_warn(freq->tmpfile);
1266 return -1;
1268 freq->rename =
1269 move_temp_to_file(freq->tmpfile, freq->filename);
1271 return freq->rename;
1274 void abort_http_object_request(struct http_object_request *freq)
1276 unlink_or_warn(freq->tmpfile);
1278 release_http_object_request(freq);
1281 void release_http_object_request(struct http_object_request *freq)
1283 if (freq->localfile != -1) {
1284 close(freq->localfile);
1285 freq->localfile = -1;
1287 if (freq->url != NULL) {
1288 free(freq->url);
1289 freq->url = NULL;
1291 if (freq->slot != NULL) {
1292 freq->slot->callback_func = NULL;
1293 freq->slot->callback_data = NULL;
1294 release_active_slot(freq->slot);
1295 freq->slot = NULL;