mingw: do not hide bare repositories
[git/dscho.git] / http.c
blobf3b2c90cdd065c5cc7a21f4449f9de6b7a1efaa8
1 #include "http.h"
2 #include "pack.h"
3 #include "sideband.h"
4 #include "run-command.h"
5 #include "url.h"
6 #include "exec_cmd.h"
8 int active_requests;
9 int http_is_verbose;
10 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
12 #if LIBCURL_VERSION_NUM >= 0x070a06
13 #define LIBCURL_CAN_HANDLE_AUTH_ANY
14 #endif
16 static int min_curl_sessions = 1;
17 static int curl_session_count;
18 #ifdef USE_CURL_MULTI
19 static int max_requests = -1;
20 static CURLM *curlm;
21 #endif
22 #ifndef NO_CURL_EASY_DUPHANDLE
23 static CURL *curl_default;
24 #endif
26 #define PREV_BUF_SIZE 4096
27 #define RANGE_HEADER_SIZE 30
29 char curl_errorstr[CURL_ERROR_SIZE];
31 static int curl_ssl_verify = -1;
32 static const char *ssl_cert;
33 #if LIBCURL_VERSION_NUM >= 0x070903
34 static const char *ssl_key;
35 #endif
36 #if LIBCURL_VERSION_NUM >= 0x070908
37 static const char *ssl_capath;
38 #endif
39 static const char *ssl_cainfo;
40 static long curl_low_speed_limit = -1;
41 static long curl_low_speed_time = -1;
42 static int curl_ftp_no_epsv;
43 static const char *curl_http_proxy;
44 static const char *curl_cookie_file;
45 static char *user_name, *user_pass, *description;
46 static const char *user_agent;
48 #if LIBCURL_VERSION_NUM >= 0x071700
49 /* Use CURLOPT_KEYPASSWD as is */
50 #elif LIBCURL_VERSION_NUM >= 0x070903
51 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
52 #else
53 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
54 #endif
56 static char *ssl_cert_password;
57 static int ssl_cert_password_required;
59 static struct curl_slist *pragma_header;
60 static struct curl_slist *no_pragma_header;
62 static struct active_request_slot *active_queue_head;
64 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
66 size_t size = eltsize * nmemb;
67 struct buffer *buffer = buffer_;
69 if (size > buffer->buf.len - buffer->posn)
70 size = buffer->buf.len - buffer->posn;
71 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
72 buffer->posn += size;
74 return size;
77 #ifndef NO_CURL_IOCTL
78 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
80 struct buffer *buffer = clientp;
82 switch (cmd) {
83 case CURLIOCMD_NOP:
84 return CURLIOE_OK;
86 case CURLIOCMD_RESTARTREAD:
87 buffer->posn = 0;
88 return CURLIOE_OK;
90 default:
91 return CURLIOE_UNKNOWNCMD;
94 #endif
96 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
98 size_t size = eltsize * nmemb;
99 struct strbuf *buffer = buffer_;
101 strbuf_add(buffer, ptr, size);
102 return size;
105 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
107 return eltsize * nmemb;
110 #ifdef USE_CURL_MULTI
111 static void process_curl_messages(void)
113 int num_messages;
114 struct active_request_slot *slot;
115 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
117 while (curl_message != NULL) {
118 if (curl_message->msg == CURLMSG_DONE) {
119 int curl_result = curl_message->data.result;
120 slot = active_queue_head;
121 while (slot != NULL &&
122 slot->curl != curl_message->easy_handle)
123 slot = slot->next;
124 if (slot != NULL) {
125 curl_multi_remove_handle(curlm, slot->curl);
126 slot->curl_result = curl_result;
127 finish_active_slot(slot);
128 } else {
129 fprintf(stderr, "Received DONE message for unknown request!\n");
131 } else {
132 fprintf(stderr, "Unknown CURL message received: %d\n",
133 (int)curl_message->msg);
135 curl_message = curl_multi_info_read(curlm, &num_messages);
138 #endif
140 static char *git_getpass_with_description(const char *what, const char *desc)
142 struct strbuf prompt = STRBUF_INIT;
143 char *r;
145 if (desc)
146 strbuf_addf(&prompt, "%s for '%s': ", what, desc);
147 else
148 strbuf_addf(&prompt, "%s: ", what);
150 * NEEDSWORK: for usernames, we should do something less magical that
151 * actually echoes the characters. However, we need to read from
152 * /dev/tty and not stdio, which is not portable (but getpass will do
153 * it for us). http.c uses the same workaround.
155 r = git_getpass(prompt.buf);
157 strbuf_release(&prompt);
158 return xstrdup(r);
161 static int git_config_path(const char **result,
162 const char *var, const char *value)
164 if (git_config_string(result, var, value))
165 return 1;
166 #ifdef __MINGW32__
167 if (**result == '/')
168 *result = system_path((*result) + 1);
169 #endif
170 return 0;
173 static int http_options(const char *var, const char *value, void *cb)
175 if (!strcmp("http.sslverify", var)) {
176 curl_ssl_verify = git_config_bool(var, value);
177 return 0;
179 if (!strcmp("http.sslcert", var))
180 return git_config_path(&ssl_cert, var, value);
181 #if LIBCURL_VERSION_NUM >= 0x070903
182 if (!strcmp("http.sslkey", var))
183 return git_config_path(&ssl_key, var, value);
184 #endif
185 #if LIBCURL_VERSION_NUM >= 0x070908
186 if (!strcmp("http.sslcapath", var))
187 return git_config_path(&ssl_capath, var, value);
188 #endif
189 if (!strcmp("http.sslcainfo", var))
190 return git_config_path(&ssl_cainfo, var, value);
191 if (!strcmp("http.sslcertpasswordprotected", var)) {
192 if (git_config_bool(var, value))
193 ssl_cert_password_required = 1;
194 return 0;
196 if (!strcmp("http.minsessions", var)) {
197 min_curl_sessions = git_config_int(var, value);
198 #ifndef USE_CURL_MULTI
199 if (min_curl_sessions > 1)
200 min_curl_sessions = 1;
201 #endif
202 return 0;
204 #ifdef USE_CURL_MULTI
205 if (!strcmp("http.maxrequests", var)) {
206 max_requests = git_config_int(var, value);
207 return 0;
209 #endif
210 if (!strcmp("http.lowspeedlimit", var)) {
211 curl_low_speed_limit = (long)git_config_int(var, value);
212 return 0;
214 if (!strcmp("http.lowspeedtime", var)) {
215 curl_low_speed_time = (long)git_config_int(var, value);
216 return 0;
219 if (!strcmp("http.noepsv", var)) {
220 curl_ftp_no_epsv = git_config_bool(var, value);
221 return 0;
223 if (!strcmp("http.proxy", var))
224 return git_config_string(&curl_http_proxy, var, value);
226 if (!strcmp("http.cookiefile", var))
227 return git_config_string(&curl_cookie_file, var, value);
229 if (!strcmp("http.postbuffer", var)) {
230 http_post_buffer = git_config_int(var, value);
231 if (http_post_buffer < LARGE_PACKET_MAX)
232 http_post_buffer = LARGE_PACKET_MAX;
233 return 0;
236 if (!strcmp("http.useragent", var))
237 return git_config_string(&user_agent, var, value);
239 /* Fall back on the default ones */
240 return git_default_config(var, value, cb);
243 static void init_curl_http_auth(CURL *result)
245 if (user_name) {
246 struct strbuf up = STRBUF_INIT;
247 if (!user_pass)
248 user_pass = xstrdup(git_getpass_with_description("Password", description));
249 strbuf_addf(&up, "%s:%s", user_name, user_pass);
250 curl_easy_setopt(result, CURLOPT_USERPWD,
251 strbuf_detach(&up, NULL));
255 static int has_cert_password(void)
257 if (ssl_cert_password != NULL)
258 return 1;
259 if (ssl_cert == NULL || ssl_cert_password_required != 1)
260 return 0;
261 /* Only prompt the user once. */
262 ssl_cert_password_required = -1;
263 ssl_cert_password = git_getpass_with_description("Certificate Password", description);
264 if (ssl_cert_password != NULL) {
265 ssl_cert_password = xstrdup(ssl_cert_password);
266 return 1;
267 } else
268 return 0;
271 static CURL *get_curl_handle(void)
273 CURL *result = curl_easy_init();
275 if (!curl_ssl_verify) {
276 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
277 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
278 } else {
279 /* Verify authenticity of the peer's certificate */
280 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
281 /* The name in the cert must match whom we tried to connect */
282 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
285 #if LIBCURL_VERSION_NUM >= 0x070907
286 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
287 #endif
288 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
289 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
290 #endif
292 if (ssl_cert != NULL)
293 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
294 if (has_cert_password())
295 curl_easy_setopt(result, CURLOPT_KEYPASSWD, ssl_cert_password);
296 #if LIBCURL_VERSION_NUM >= 0x070903
297 if (ssl_key != NULL)
298 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
299 #endif
300 #if LIBCURL_VERSION_NUM >= 0x070908
301 if (ssl_capath != NULL)
302 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
303 #endif
304 if (ssl_cainfo != NULL)
305 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
306 curl_easy_setopt(result, CURLOPT_FAILONERROR, 1);
308 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
309 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
310 curl_low_speed_limit);
311 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
312 curl_low_speed_time);
315 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
316 #if LIBCURL_VERSION_NUM >= 0x071301
317 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
318 #elif LIBCURL_VERSION_NUM >= 0x071101
319 curl_easy_setopt(result, CURLOPT_POST301, 1);
320 #endif
322 if (getenv("GIT_CURL_VERBOSE"))
323 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
325 curl_easy_setopt(result, CURLOPT_USERAGENT,
326 user_agent ? user_agent : GIT_HTTP_USER_AGENT);
328 if (curl_ftp_no_epsv)
329 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
331 if (curl_http_proxy)
332 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
334 return result;
337 static void http_auth_init(const char *url)
339 const char *at, *colon, *cp, *slash, *host;
341 cp = strstr(url, "://");
342 if (!cp)
343 return;
346 * Ok, the URL looks like "proto://something". Which one?
347 * "proto://<user>:<pass>@<host>/...",
348 * "proto://<user>@<host>/...", or just
349 * "proto://<host>/..."?
351 cp += 3;
352 at = strchr(cp, '@');
353 colon = strchr(cp, ':');
354 slash = strchrnul(cp, '/');
355 if (!at || slash <= at) {
356 /* No credentials, but we may have to ask for some later */
357 host = cp;
359 else if (!colon || at <= colon) {
360 /* Only username */
361 user_name = url_decode_mem(cp, at - cp);
362 user_pass = NULL;
363 host = at + 1;
364 } else {
365 user_name = url_decode_mem(cp, colon - cp);
366 user_pass = url_decode_mem(colon + 1, at - (colon + 1));
367 host = at + 1;
370 description = url_decode_mem(host, slash - host);
373 static void set_from_env(const char **var, const char *envname)
375 const char *val = getenv(envname);
376 if (val)
377 *var = val;
380 void http_init(struct remote *remote, const char *url)
382 char *low_speed_limit;
383 char *low_speed_time;
385 http_is_verbose = 0;
387 git_config(http_options, NULL);
389 curl_global_init(CURL_GLOBAL_ALL);
391 if (remote && remote->http_proxy)
392 curl_http_proxy = xstrdup(remote->http_proxy);
394 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
395 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
397 #ifdef USE_CURL_MULTI
399 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
400 if (http_max_requests != NULL)
401 max_requests = atoi(http_max_requests);
404 curlm = curl_multi_init();
405 if (curlm == NULL) {
406 fprintf(stderr, "Error creating curl multi handle.\n");
407 exit(1);
409 #endif
411 if (getenv("GIT_SSL_NO_VERIFY"))
412 curl_ssl_verify = 0;
414 set_from_env(&ssl_cert, "GIT_SSL_CERT");
415 #if LIBCURL_VERSION_NUM >= 0x070903
416 set_from_env(&ssl_key, "GIT_SSL_KEY");
417 #endif
418 #if LIBCURL_VERSION_NUM >= 0x070908
419 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
420 #endif
421 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
423 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
425 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
426 if (low_speed_limit != NULL)
427 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
428 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
429 if (low_speed_time != NULL)
430 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
432 if (curl_ssl_verify == -1)
433 curl_ssl_verify = 1;
435 curl_session_count = 0;
436 #ifdef USE_CURL_MULTI
437 if (max_requests < 1)
438 max_requests = DEFAULT_MAX_REQUESTS;
439 #endif
441 if (getenv("GIT_CURL_FTP_NO_EPSV"))
442 curl_ftp_no_epsv = 1;
444 if (url) {
445 http_auth_init(url);
446 if (!ssl_cert_password_required &&
447 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
448 !prefixcmp(url, "https://"))
449 ssl_cert_password_required = 1;
452 #ifndef NO_CURL_EASY_DUPHANDLE
453 curl_default = get_curl_handle();
454 #endif
457 void http_cleanup(void)
459 struct active_request_slot *slot = active_queue_head;
461 while (slot != NULL) {
462 struct active_request_slot *next = slot->next;
463 if (slot->curl != NULL) {
464 #ifdef USE_CURL_MULTI
465 curl_multi_remove_handle(curlm, slot->curl);
466 #endif
467 curl_easy_cleanup(slot->curl);
469 free(slot);
470 slot = next;
472 active_queue_head = NULL;
474 #ifndef NO_CURL_EASY_DUPHANDLE
475 curl_easy_cleanup(curl_default);
476 #endif
478 #ifdef USE_CURL_MULTI
479 curl_multi_cleanup(curlm);
480 #endif
481 curl_global_cleanup();
483 curl_slist_free_all(pragma_header);
484 pragma_header = NULL;
486 curl_slist_free_all(no_pragma_header);
487 no_pragma_header = NULL;
489 if (curl_http_proxy) {
490 free((void *)curl_http_proxy);
491 curl_http_proxy = NULL;
494 if (ssl_cert_password != NULL) {
495 memset(ssl_cert_password, 0, strlen(ssl_cert_password));
496 free(ssl_cert_password);
497 ssl_cert_password = NULL;
499 ssl_cert_password_required = 0;
502 struct active_request_slot *get_active_slot(void)
504 struct active_request_slot *slot = active_queue_head;
505 struct active_request_slot *newslot;
507 #ifdef USE_CURL_MULTI
508 int num_transfers;
510 /* Wait for a slot to open up if the queue is full */
511 while (active_requests >= max_requests) {
512 curl_multi_perform(curlm, &num_transfers);
513 if (num_transfers < active_requests)
514 process_curl_messages();
516 #endif
518 while (slot != NULL && slot->in_use)
519 slot = slot->next;
521 if (slot == NULL) {
522 newslot = xmalloc(sizeof(*newslot));
523 newslot->curl = NULL;
524 newslot->in_use = 0;
525 newslot->next = NULL;
527 slot = active_queue_head;
528 if (slot == NULL) {
529 active_queue_head = newslot;
530 } else {
531 while (slot->next != NULL)
532 slot = slot->next;
533 slot->next = newslot;
535 slot = newslot;
538 if (slot->curl == NULL) {
539 #ifdef NO_CURL_EASY_DUPHANDLE
540 slot->curl = get_curl_handle();
541 #else
542 slot->curl = curl_easy_duphandle(curl_default);
543 #endif
544 curl_session_count++;
547 active_requests++;
548 slot->in_use = 1;
549 slot->results = NULL;
550 slot->finished = NULL;
551 slot->callback_data = NULL;
552 slot->callback_func = NULL;
553 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
554 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
555 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
556 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
557 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
558 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
559 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
560 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
561 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
563 return slot;
566 int start_active_slot(struct active_request_slot *slot)
568 #ifdef USE_CURL_MULTI
569 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
570 int num_transfers;
572 if (curlm_result != CURLM_OK &&
573 curlm_result != CURLM_CALL_MULTI_PERFORM) {
574 active_requests--;
575 slot->in_use = 0;
576 return 0;
580 * We know there must be something to do, since we just added
581 * something.
583 curl_multi_perform(curlm, &num_transfers);
584 #endif
585 return 1;
588 #ifdef USE_CURL_MULTI
589 struct fill_chain {
590 void *data;
591 int (*fill)(void *);
592 struct fill_chain *next;
595 static struct fill_chain *fill_cfg;
597 void add_fill_function(void *data, int (*fill)(void *))
599 struct fill_chain *new = xmalloc(sizeof(*new));
600 struct fill_chain **linkp = &fill_cfg;
601 new->data = data;
602 new->fill = fill;
603 new->next = NULL;
604 while (*linkp)
605 linkp = &(*linkp)->next;
606 *linkp = new;
609 void fill_active_slots(void)
611 struct active_request_slot *slot = active_queue_head;
613 while (active_requests < max_requests) {
614 struct fill_chain *fill;
615 for (fill = fill_cfg; fill; fill = fill->next)
616 if (fill->fill(fill->data))
617 break;
619 if (!fill)
620 break;
623 while (slot != NULL) {
624 if (!slot->in_use && slot->curl != NULL
625 && curl_session_count > min_curl_sessions) {
626 curl_easy_cleanup(slot->curl);
627 slot->curl = NULL;
628 curl_session_count--;
630 slot = slot->next;
634 void step_active_slots(void)
636 int num_transfers;
637 CURLMcode curlm_result;
639 do {
640 curlm_result = curl_multi_perform(curlm, &num_transfers);
641 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
642 if (num_transfers < active_requests) {
643 process_curl_messages();
644 fill_active_slots();
647 #endif
649 void run_active_slot(struct active_request_slot *slot)
651 #ifdef USE_CURL_MULTI
652 fd_set readfds;
653 fd_set writefds;
654 fd_set excfds;
655 int max_fd;
656 struct timeval select_timeout;
657 int finished = 0;
659 slot->finished = &finished;
660 while (!finished) {
661 step_active_slots();
663 if (slot->in_use) {
664 #if LIBCURL_VERSION_NUM >= 0x070f04
665 long curl_timeout;
666 curl_multi_timeout(curlm, &curl_timeout);
667 if (curl_timeout == 0) {
668 continue;
669 } else if (curl_timeout == -1) {
670 select_timeout.tv_sec = 0;
671 select_timeout.tv_usec = 50000;
672 } else {
673 select_timeout.tv_sec = curl_timeout / 1000;
674 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
676 #else
677 select_timeout.tv_sec = 0;
678 select_timeout.tv_usec = 50000;
679 #endif
681 max_fd = -1;
682 FD_ZERO(&readfds);
683 FD_ZERO(&writefds);
684 FD_ZERO(&excfds);
685 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
687 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
690 #else
691 while (slot->in_use) {
692 slot->curl_result = curl_easy_perform(slot->curl);
693 finish_active_slot(slot);
695 #endif
698 static void closedown_active_slot(struct active_request_slot *slot)
700 active_requests--;
701 slot->in_use = 0;
704 static void release_active_slot(struct active_request_slot *slot)
706 closedown_active_slot(slot);
707 if (slot->curl && curl_session_count > min_curl_sessions) {
708 #ifdef USE_CURL_MULTI
709 curl_multi_remove_handle(curlm, slot->curl);
710 #endif
711 curl_easy_cleanup(slot->curl);
712 slot->curl = NULL;
713 curl_session_count--;
715 #ifdef USE_CURL_MULTI
716 fill_active_slots();
717 #endif
720 void finish_active_slot(struct active_request_slot *slot)
722 closedown_active_slot(slot);
723 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
725 if (slot->finished != NULL)
726 (*slot->finished) = 1;
728 /* Store slot results so they can be read after the slot is reused */
729 if (slot->results != NULL) {
730 slot->results->curl_result = slot->curl_result;
731 slot->results->http_code = slot->http_code;
734 /* Run callback if appropriate */
735 if (slot->callback_func != NULL)
736 slot->callback_func(slot->callback_data);
739 void finish_all_active_slots(void)
741 struct active_request_slot *slot = active_queue_head;
743 while (slot != NULL)
744 if (slot->in_use) {
745 run_active_slot(slot);
746 slot = active_queue_head;
747 } else {
748 slot = slot->next;
752 /* Helpers for modifying and creating URLs */
753 static inline int needs_quote(int ch)
755 if (((ch >= 'A') && (ch <= 'Z'))
756 || ((ch >= 'a') && (ch <= 'z'))
757 || ((ch >= '0') && (ch <= '9'))
758 || (ch == '/')
759 || (ch == '-')
760 || (ch == '.'))
761 return 0;
762 return 1;
765 static char *quote_ref_url(const char *base, const char *ref)
767 struct strbuf buf = STRBUF_INIT;
768 const char *cp;
769 int ch;
771 end_url_with_slash(&buf, base);
773 for (cp = ref; (ch = *cp) != 0; cp++)
774 if (needs_quote(ch))
775 strbuf_addf(&buf, "%%%02x", ch);
776 else
777 strbuf_addch(&buf, *cp);
779 return strbuf_detach(&buf, NULL);
782 void append_remote_object_url(struct strbuf *buf, const char *url,
783 const char *hex,
784 int only_two_digit_prefix)
786 end_url_with_slash(buf, url);
788 strbuf_addf(buf, "objects/%.*s/", 2, hex);
789 if (!only_two_digit_prefix)
790 strbuf_addf(buf, "%s", hex+2);
793 char *get_remote_object_url(const char *url, const char *hex,
794 int only_two_digit_prefix)
796 struct strbuf buf = STRBUF_INIT;
797 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
798 return strbuf_detach(&buf, NULL);
801 /* http_request() targets */
802 #define HTTP_REQUEST_STRBUF 0
803 #define HTTP_REQUEST_FILE 1
805 static int http_request(const char *url, void *result, int target, int options)
807 struct active_request_slot *slot;
808 struct slot_results results;
809 struct curl_slist *headers = NULL;
810 struct strbuf buf = STRBUF_INIT;
811 int ret;
813 slot = get_active_slot();
814 slot->results = &results;
815 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
817 if (result == NULL) {
818 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
819 } else {
820 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
821 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
823 if (target == HTTP_REQUEST_FILE) {
824 long posn = ftell(result);
825 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
826 fwrite);
827 if (posn > 0) {
828 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
829 headers = curl_slist_append(headers, buf.buf);
830 strbuf_reset(&buf);
832 } else
833 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
834 fwrite_buffer);
837 strbuf_addstr(&buf, "Pragma:");
838 if (options & HTTP_NO_CACHE)
839 strbuf_addstr(&buf, " no-cache");
841 headers = curl_slist_append(headers, buf.buf);
843 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
844 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
846 if (start_active_slot(slot)) {
847 run_active_slot(slot);
848 if (results.curl_result == CURLE_OK)
849 ret = HTTP_OK;
850 else if (missing_target(&results))
851 ret = HTTP_MISSING_TARGET;
852 else if (results.http_code == 401) {
853 if (user_name && user_pass) {
854 ret = HTTP_NOAUTH;
855 } else {
857 * git_getpass is needed here because its very likely stdin/stdout are
858 * pipes to our parent process. So we instead need to use /dev/tty,
859 * but that is non-portable. Using git_getpass() can at least be stubbed
860 * on other platforms with a different implementation if/when necessary.
862 if (!user_name)
863 user_name = xstrdup(git_getpass_with_description("Username", description));
864 init_curl_http_auth(slot->curl);
865 ret = HTTP_REAUTH;
867 } else {
868 if (!curl_errorstr[0])
869 strlcpy(curl_errorstr,
870 curl_easy_strerror(results.curl_result),
871 sizeof(curl_errorstr));
872 ret = HTTP_ERROR;
874 } else {
875 error("Unable to start HTTP request for %s", url);
876 ret = HTTP_START_FAILED;
879 curl_slist_free_all(headers);
880 strbuf_release(&buf);
882 return ret;
885 static int http_request_reauth(const char *url, void *result, int target,
886 int options)
888 int ret = http_request(url, result, target, options);
889 if (ret != HTTP_REAUTH)
890 return ret;
891 return http_request(url, result, target, options);
894 int http_get_strbuf(const char *url, struct strbuf *result, int options)
896 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
900 * Downloads an url and stores the result in the given file.
902 * If a previous interrupted download is detected (i.e. a previous temporary
903 * file is still around) the download is resumed.
905 static int http_get_file(const char *url, const char *filename, int options)
907 int ret;
908 struct strbuf tmpfile = STRBUF_INIT;
909 FILE *result;
911 strbuf_addf(&tmpfile, "%s.temp", filename);
912 result = fopen(tmpfile.buf, "a");
913 if (! result) {
914 error("Unable to open local file %s", tmpfile.buf);
915 ret = HTTP_ERROR;
916 goto cleanup;
919 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
920 fclose(result);
922 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
923 ret = HTTP_ERROR;
924 cleanup:
925 strbuf_release(&tmpfile);
926 return ret;
929 int http_error(const char *url, int ret)
931 /* http_request has already handled HTTP_START_FAILED. */
932 if (ret != HTTP_START_FAILED)
933 error("%s while accessing %s", curl_errorstr, url);
935 return ret;
938 int http_fetch_ref(const char *base, struct ref *ref)
940 char *url;
941 struct strbuf buffer = STRBUF_INIT;
942 int ret = -1;
944 url = quote_ref_url(base, ref->name);
945 if (http_get_strbuf(url, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
946 strbuf_rtrim(&buffer);
947 if (buffer.len == 40)
948 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
949 else if (!prefixcmp(buffer.buf, "ref: ")) {
950 ref->symref = xstrdup(buffer.buf + 5);
951 ret = 0;
955 strbuf_release(&buffer);
956 free(url);
957 return ret;
960 /* Helpers for fetching packs */
961 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
963 char *url, *tmp;
964 struct strbuf buf = STRBUF_INIT;
966 if (http_is_verbose)
967 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
969 end_url_with_slash(&buf, base_url);
970 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
971 url = strbuf_detach(&buf, NULL);
973 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
974 tmp = strbuf_detach(&buf, NULL);
976 if (http_get_file(url, tmp, 0) != HTTP_OK) {
977 error("Unable to get pack index %s\n", url);
978 free(tmp);
979 tmp = NULL;
982 free(url);
983 return tmp;
986 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
987 unsigned char *sha1, const char *base_url)
989 struct packed_git *new_pack;
990 char *tmp_idx = NULL;
991 int ret;
993 if (has_pack_index(sha1)) {
994 new_pack = parse_pack_index(sha1, NULL);
995 if (!new_pack)
996 return -1; /* parse_pack_index() already issued error message */
997 goto add_pack;
1000 tmp_idx = fetch_pack_index(sha1, base_url);
1001 if (!tmp_idx)
1002 return -1;
1004 new_pack = parse_pack_index(sha1, tmp_idx);
1005 if (!new_pack) {
1006 unlink(tmp_idx);
1007 free(tmp_idx);
1009 return -1; /* parse_pack_index() already issued error message */
1012 ret = verify_pack_index(new_pack);
1013 if (!ret) {
1014 close_pack_index(new_pack);
1015 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1017 free(tmp_idx);
1018 if (ret)
1019 return -1;
1021 add_pack:
1022 new_pack->next = *packs_head;
1023 *packs_head = new_pack;
1024 return 0;
1027 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1029 int ret = 0, i = 0;
1030 char *url, *data;
1031 struct strbuf buf = STRBUF_INIT;
1032 unsigned char sha1[20];
1034 end_url_with_slash(&buf, base_url);
1035 strbuf_addstr(&buf, "objects/info/packs");
1036 url = strbuf_detach(&buf, NULL);
1038 ret = http_get_strbuf(url, &buf, HTTP_NO_CACHE);
1039 if (ret != HTTP_OK)
1040 goto cleanup;
1042 data = buf.buf;
1043 while (i < buf.len) {
1044 switch (data[i]) {
1045 case 'P':
1046 i++;
1047 if (i + 52 <= buf.len &&
1048 !prefixcmp(data + i, " pack-") &&
1049 !prefixcmp(data + i + 46, ".pack\n")) {
1050 get_sha1_hex(data + i + 6, sha1);
1051 fetch_and_setup_pack_index(packs_head, sha1,
1052 base_url);
1053 i += 51;
1054 break;
1056 default:
1057 while (i < buf.len && data[i] != '\n')
1058 i++;
1060 i++;
1063 cleanup:
1064 free(url);
1065 return ret;
1068 void release_http_pack_request(struct http_pack_request *preq)
1070 if (preq->packfile != NULL) {
1071 fclose(preq->packfile);
1072 preq->packfile = NULL;
1074 if (preq->range_header != NULL) {
1075 curl_slist_free_all(preq->range_header);
1076 preq->range_header = NULL;
1078 preq->slot = NULL;
1079 free(preq->url);
1082 int finish_http_pack_request(struct http_pack_request *preq)
1084 struct packed_git **lst;
1085 struct packed_git *p = preq->target;
1086 char *tmp_idx;
1087 struct child_process ip;
1088 const char *ip_argv[8];
1090 close_pack_index(p);
1092 fclose(preq->packfile);
1093 preq->packfile = NULL;
1095 lst = preq->lst;
1096 while (*lst != p)
1097 lst = &((*lst)->next);
1098 *lst = (*lst)->next;
1100 tmp_idx = xstrdup(preq->tmpfile);
1101 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1102 ".idx.temp");
1104 ip_argv[0] = "index-pack";
1105 ip_argv[1] = "-o";
1106 ip_argv[2] = tmp_idx;
1107 ip_argv[3] = preq->tmpfile;
1108 ip_argv[4] = NULL;
1110 memset(&ip, 0, sizeof(ip));
1111 ip.argv = ip_argv;
1112 ip.git_cmd = 1;
1113 ip.no_stdin = 1;
1114 ip.no_stdout = 1;
1116 if (run_command(&ip)) {
1117 unlink(preq->tmpfile);
1118 unlink(tmp_idx);
1119 free(tmp_idx);
1120 return -1;
1123 unlink(sha1_pack_index_name(p->sha1));
1125 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1126 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1127 free(tmp_idx);
1128 return -1;
1131 install_packed_git(p);
1132 free(tmp_idx);
1133 return 0;
1136 struct http_pack_request *new_http_pack_request(
1137 struct packed_git *target, const char *base_url)
1139 long prev_posn = 0;
1140 char range[RANGE_HEADER_SIZE];
1141 struct strbuf buf = STRBUF_INIT;
1142 struct http_pack_request *preq;
1144 preq = xcalloc(1, sizeof(*preq));
1145 preq->target = target;
1147 end_url_with_slash(&buf, base_url);
1148 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1149 sha1_to_hex(target->sha1));
1150 preq->url = strbuf_detach(&buf, NULL);
1152 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1153 sha1_pack_name(target->sha1));
1154 preq->packfile = fopen(preq->tmpfile, "a");
1155 if (!preq->packfile) {
1156 error("Unable to open local file %s for pack",
1157 preq->tmpfile);
1158 goto abort;
1161 preq->slot = get_active_slot();
1162 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1163 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1164 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1165 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1166 no_pragma_header);
1169 * If there is data present from a previous transfer attempt,
1170 * resume where it left off
1172 prev_posn = ftell(preq->packfile);
1173 if (prev_posn>0) {
1174 if (http_is_verbose)
1175 fprintf(stderr,
1176 "Resuming fetch of pack %s at byte %ld\n",
1177 sha1_to_hex(target->sha1), prev_posn);
1178 sprintf(range, "Range: bytes=%ld-", prev_posn);
1179 preq->range_header = curl_slist_append(NULL, range);
1180 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1181 preq->range_header);
1184 return preq;
1186 abort:
1187 free(preq->url);
1188 free(preq);
1189 return NULL;
1192 /* Helpers for fetching objects (loose) */
1193 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1194 void *data)
1196 unsigned char expn[4096];
1197 size_t size = eltsize * nmemb;
1198 int posn = 0;
1199 struct http_object_request *freq =
1200 (struct http_object_request *)data;
1201 do {
1202 ssize_t retval = xwrite(freq->localfile,
1203 (char *) ptr + posn, size - posn);
1204 if (retval < 0)
1205 return posn;
1206 posn += retval;
1207 } while (posn < size);
1209 freq->stream.avail_in = size;
1210 freq->stream.next_in = (void *)ptr;
1211 do {
1212 freq->stream.next_out = expn;
1213 freq->stream.avail_out = sizeof(expn);
1214 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1215 git_SHA1_Update(&freq->c, expn,
1216 sizeof(expn) - freq->stream.avail_out);
1217 } while (freq->stream.avail_in && freq->zret == Z_OK);
1218 return size;
1221 struct http_object_request *new_http_object_request(const char *base_url,
1222 unsigned char *sha1)
1224 char *hex = sha1_to_hex(sha1);
1225 char *filename;
1226 char prevfile[PATH_MAX];
1227 int prevlocal;
1228 char prev_buf[PREV_BUF_SIZE];
1229 ssize_t prev_read = 0;
1230 long prev_posn = 0;
1231 char range[RANGE_HEADER_SIZE];
1232 struct curl_slist *range_header = NULL;
1233 struct http_object_request *freq;
1235 freq = xcalloc(1, sizeof(*freq));
1236 hashcpy(freq->sha1, sha1);
1237 freq->localfile = -1;
1239 filename = sha1_file_name(sha1);
1240 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1241 "%s.temp", filename);
1243 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1244 unlink_or_warn(prevfile);
1245 rename(freq->tmpfile, prevfile);
1246 unlink_or_warn(freq->tmpfile);
1248 if (freq->localfile != -1)
1249 error("fd leakage in start: %d", freq->localfile);
1250 freq->localfile = open(freq->tmpfile,
1251 O_WRONLY | O_CREAT | O_EXCL, 0666);
1253 * This could have failed due to the "lazy directory creation";
1254 * try to mkdir the last path component.
1256 if (freq->localfile < 0 && errno == ENOENT) {
1257 char *dir = strrchr(freq->tmpfile, '/');
1258 if (dir) {
1259 *dir = 0;
1260 mkdir(freq->tmpfile, 0777);
1261 *dir = '/';
1263 freq->localfile = open(freq->tmpfile,
1264 O_WRONLY | O_CREAT | O_EXCL, 0666);
1267 if (freq->localfile < 0) {
1268 error("Couldn't create temporary file %s: %s",
1269 freq->tmpfile, strerror(errno));
1270 goto abort;
1273 git_inflate_init(&freq->stream);
1275 git_SHA1_Init(&freq->c);
1277 freq->url = get_remote_object_url(base_url, hex, 0);
1280 * If a previous temp file is present, process what was already
1281 * fetched.
1283 prevlocal = open(prevfile, O_RDONLY);
1284 if (prevlocal != -1) {
1285 do {
1286 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1287 if (prev_read>0) {
1288 if (fwrite_sha1_file(prev_buf,
1290 prev_read,
1291 freq) == prev_read) {
1292 prev_posn += prev_read;
1293 } else {
1294 prev_read = -1;
1297 } while (prev_read > 0);
1298 close(prevlocal);
1300 unlink_or_warn(prevfile);
1303 * Reset inflate/SHA1 if there was an error reading the previous temp
1304 * file; also rewind to the beginning of the local file.
1306 if (prev_read == -1) {
1307 memset(&freq->stream, 0, sizeof(freq->stream));
1308 git_inflate_init(&freq->stream);
1309 git_SHA1_Init(&freq->c);
1310 if (prev_posn>0) {
1311 prev_posn = 0;
1312 lseek(freq->localfile, 0, SEEK_SET);
1313 if (ftruncate(freq->localfile, 0) < 0) {
1314 error("Couldn't truncate temporary file %s: %s",
1315 freq->tmpfile, strerror(errno));
1316 goto abort;
1321 freq->slot = get_active_slot();
1323 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1324 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1325 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1326 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1327 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1330 * If we have successfully processed data from a previous fetch
1331 * attempt, only fetch the data we don't already have.
1333 if (prev_posn>0) {
1334 if (http_is_verbose)
1335 fprintf(stderr,
1336 "Resuming fetch of object %s at byte %ld\n",
1337 hex, prev_posn);
1338 sprintf(range, "Range: bytes=%ld-", prev_posn);
1339 range_header = curl_slist_append(range_header, range);
1340 curl_easy_setopt(freq->slot->curl,
1341 CURLOPT_HTTPHEADER, range_header);
1344 return freq;
1346 abort:
1347 free(freq->url);
1348 free(freq);
1349 return NULL;
1352 void process_http_object_request(struct http_object_request *freq)
1354 if (freq->slot == NULL)
1355 return;
1356 freq->curl_result = freq->slot->curl_result;
1357 freq->http_code = freq->slot->http_code;
1358 freq->slot = NULL;
1361 int finish_http_object_request(struct http_object_request *freq)
1363 struct stat st;
1365 close(freq->localfile);
1366 freq->localfile = -1;
1368 process_http_object_request(freq);
1370 if (freq->http_code == 416) {
1371 warning("requested range invalid; we may already have all the data.");
1372 } else if (freq->curl_result != CURLE_OK) {
1373 if (stat(freq->tmpfile, &st) == 0)
1374 if (st.st_size == 0)
1375 unlink_or_warn(freq->tmpfile);
1376 return -1;
1379 git_inflate_end(&freq->stream);
1380 git_SHA1_Final(freq->real_sha1, &freq->c);
1381 if (freq->zret != Z_STREAM_END) {
1382 unlink_or_warn(freq->tmpfile);
1383 return -1;
1385 if (hashcmp(freq->sha1, freq->real_sha1)) {
1386 unlink_or_warn(freq->tmpfile);
1387 return -1;
1389 freq->rename =
1390 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1392 return freq->rename;
1395 void abort_http_object_request(struct http_object_request *freq)
1397 unlink_or_warn(freq->tmpfile);
1399 release_http_object_request(freq);
1402 void release_http_object_request(struct http_object_request *freq)
1404 if (freq->localfile != -1) {
1405 close(freq->localfile);
1406 freq->localfile = -1;
1408 if (freq->url != NULL) {
1409 free(freq->url);
1410 freq->url = NULL;
1412 if (freq->slot != NULL) {
1413 freq->slot->callback_func = NULL;
1414 freq->slot->callback_data = NULL;
1415 release_active_slot(freq->slot);
1416 freq->slot = NULL;