http-push: enable "proactive auth"
[git/mingw.git] / http.c
blob7e454f7787b8b9ca3b023be7e5c37cbf7367fc20
1 #include "http.h"
2 #include "pack.h"
3 #include "sideband.h"
4 #include "run-command.h"
5 #include "url.h"
7 int data_received;
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 int http_proactive_auth;
47 static const char *user_agent;
49 #if LIBCURL_VERSION_NUM >= 0x071700
50 /* Use CURLOPT_KEYPASSWD as is */
51 #elif LIBCURL_VERSION_NUM >= 0x070903
52 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
53 #else
54 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
55 #endif
57 static char *ssl_cert_password;
58 static int ssl_cert_password_required;
60 static struct curl_slist *pragma_header;
61 static struct curl_slist *no_pragma_header;
63 static struct active_request_slot *active_queue_head;
65 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
67 size_t size = eltsize * nmemb;
68 struct buffer *buffer = buffer_;
70 if (size > buffer->buf.len - buffer->posn)
71 size = buffer->buf.len - buffer->posn;
72 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
73 buffer->posn += size;
75 return size;
78 #ifndef NO_CURL_IOCTL
79 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
81 struct buffer *buffer = clientp;
83 switch (cmd) {
84 case CURLIOCMD_NOP:
85 return CURLIOE_OK;
87 case CURLIOCMD_RESTARTREAD:
88 buffer->posn = 0;
89 return CURLIOE_OK;
91 default:
92 return CURLIOE_UNKNOWNCMD;
95 #endif
97 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
99 size_t size = eltsize * nmemb;
100 struct strbuf *buffer = buffer_;
102 strbuf_add(buffer, ptr, size);
103 data_received++;
104 return size;
107 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
109 data_received++;
110 return eltsize * nmemb;
113 #ifdef USE_CURL_MULTI
114 static void process_curl_messages(void)
116 int num_messages;
117 struct active_request_slot *slot;
118 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
120 while (curl_message != NULL) {
121 if (curl_message->msg == CURLMSG_DONE) {
122 int curl_result = curl_message->data.result;
123 slot = active_queue_head;
124 while (slot != NULL &&
125 slot->curl != curl_message->easy_handle)
126 slot = slot->next;
127 if (slot != NULL) {
128 curl_multi_remove_handle(curlm, slot->curl);
129 slot->curl_result = curl_result;
130 finish_active_slot(slot);
131 } else {
132 fprintf(stderr, "Received DONE message for unknown request!\n");
134 } else {
135 fprintf(stderr, "Unknown CURL message received: %d\n",
136 (int)curl_message->msg);
138 curl_message = curl_multi_info_read(curlm, &num_messages);
141 #endif
143 static char *git_getpass_with_description(const char *what, const char *desc)
145 struct strbuf prompt = STRBUF_INIT;
146 char *r;
148 if (desc)
149 strbuf_addf(&prompt, "%s for '%s': ", what, desc);
150 else
151 strbuf_addf(&prompt, "%s: ", what);
153 * NEEDSWORK: for usernames, we should do something less magical that
154 * actually echoes the characters. However, we need to read from
155 * /dev/tty and not stdio, which is not portable (but getpass will do
156 * it for us). http.c uses the same workaround.
158 r = git_getpass(prompt.buf);
160 strbuf_release(&prompt);
161 return xstrdup(r);
164 static int http_options(const char *var, const char *value, void *cb)
166 if (!strcmp("http.sslverify", var)) {
167 curl_ssl_verify = git_config_bool(var, value);
168 return 0;
170 if (!strcmp("http.sslcert", var))
171 return git_config_string(&ssl_cert, var, value);
172 #if LIBCURL_VERSION_NUM >= 0x070903
173 if (!strcmp("http.sslkey", var))
174 return git_config_string(&ssl_key, var, value);
175 #endif
176 #if LIBCURL_VERSION_NUM >= 0x070908
177 if (!strcmp("http.sslcapath", var))
178 return git_config_string(&ssl_capath, var, value);
179 #endif
180 if (!strcmp("http.sslcainfo", var))
181 return git_config_string(&ssl_cainfo, var, value);
182 if (!strcmp("http.sslcertpasswordprotected", var)) {
183 if (git_config_bool(var, value))
184 ssl_cert_password_required = 1;
185 return 0;
187 if (!strcmp("http.minsessions", var)) {
188 min_curl_sessions = git_config_int(var, value);
189 #ifndef USE_CURL_MULTI
190 if (min_curl_sessions > 1)
191 min_curl_sessions = 1;
192 #endif
193 return 0;
195 #ifdef USE_CURL_MULTI
196 if (!strcmp("http.maxrequests", var)) {
197 max_requests = git_config_int(var, value);
198 return 0;
200 #endif
201 if (!strcmp("http.lowspeedlimit", var)) {
202 curl_low_speed_limit = (long)git_config_int(var, value);
203 return 0;
205 if (!strcmp("http.lowspeedtime", var)) {
206 curl_low_speed_time = (long)git_config_int(var, value);
207 return 0;
210 if (!strcmp("http.noepsv", var)) {
211 curl_ftp_no_epsv = git_config_bool(var, value);
212 return 0;
214 if (!strcmp("http.proxy", var))
215 return git_config_string(&curl_http_proxy, var, value);
217 if (!strcmp("http.cookiefile", var))
218 return git_config_string(&curl_cookie_file, var, value);
220 if (!strcmp("http.postbuffer", var)) {
221 http_post_buffer = git_config_int(var, value);
222 if (http_post_buffer < LARGE_PACKET_MAX)
223 http_post_buffer = LARGE_PACKET_MAX;
224 return 0;
227 if (!strcmp("http.useragent", var))
228 return git_config_string(&user_agent, var, value);
230 /* Fall back on the default ones */
231 return git_default_config(var, value, cb);
234 static void init_curl_http_auth(CURL *result)
236 if (user_name) {
237 struct strbuf up = STRBUF_INIT;
238 if (!user_pass)
239 user_pass = xstrdup(git_getpass_with_description("Password", description));
240 strbuf_addf(&up, "%s:%s", user_name, user_pass);
241 curl_easy_setopt(result, CURLOPT_USERPWD,
242 strbuf_detach(&up, NULL));
246 static int has_cert_password(void)
248 if (ssl_cert_password != NULL)
249 return 1;
250 if (ssl_cert == NULL || ssl_cert_password_required != 1)
251 return 0;
252 /* Only prompt the user once. */
253 ssl_cert_password_required = -1;
254 ssl_cert_password = git_getpass_with_description("Certificate Password", description);
255 if (ssl_cert_password != NULL) {
256 ssl_cert_password = xstrdup(ssl_cert_password);
257 return 1;
258 } else
259 return 0;
262 static CURL *get_curl_handle(void)
264 CURL *result = curl_easy_init();
266 if (!curl_ssl_verify) {
267 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
268 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
269 } else {
270 /* Verify authenticity of the peer's certificate */
271 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
272 /* The name in the cert must match whom we tried to connect */
273 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
276 #if LIBCURL_VERSION_NUM >= 0x070907
277 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
278 #endif
279 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
280 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
281 #endif
283 if (http_proactive_auth)
284 init_curl_http_auth(result);
286 if (ssl_cert != NULL)
287 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
288 if (has_cert_password())
289 curl_easy_setopt(result, CURLOPT_KEYPASSWD, ssl_cert_password);
290 #if LIBCURL_VERSION_NUM >= 0x070903
291 if (ssl_key != NULL)
292 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
293 #endif
294 #if LIBCURL_VERSION_NUM >= 0x070908
295 if (ssl_capath != NULL)
296 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
297 #endif
298 if (ssl_cainfo != NULL)
299 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
300 curl_easy_setopt(result, CURLOPT_FAILONERROR, 1);
302 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
303 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
304 curl_low_speed_limit);
305 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
306 curl_low_speed_time);
309 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
310 #if LIBCURL_VERSION_NUM >= 0x071301
311 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
312 #elif LIBCURL_VERSION_NUM >= 0x071101
313 curl_easy_setopt(result, CURLOPT_POST301, 1);
314 #endif
316 if (getenv("GIT_CURL_VERBOSE"))
317 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
319 curl_easy_setopt(result, CURLOPT_USERAGENT,
320 user_agent ? user_agent : GIT_HTTP_USER_AGENT);
322 if (curl_ftp_no_epsv)
323 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
325 if (curl_http_proxy)
326 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
328 return result;
331 static void http_auth_init(const char *url)
333 const char *at, *colon, *cp, *slash, *host;
335 cp = strstr(url, "://");
336 if (!cp)
337 return;
340 * Ok, the URL looks like "proto://something". Which one?
341 * "proto://<user>:<pass>@<host>/...",
342 * "proto://<user>@<host>/...", or just
343 * "proto://<host>/..."?
345 cp += 3;
346 at = strchr(cp, '@');
347 colon = strchr(cp, ':');
348 slash = strchrnul(cp, '/');
349 if (!at || slash <= at) {
350 /* No credentials, but we may have to ask for some later */
351 host = cp;
353 else if (!colon || at <= colon) {
354 /* Only username */
355 user_name = url_decode_mem(cp, at - cp);
356 user_pass = NULL;
357 host = at + 1;
358 } else {
359 user_name = url_decode_mem(cp, colon - cp);
360 user_pass = url_decode_mem(colon + 1, at - (colon + 1));
361 host = at + 1;
364 description = url_decode_mem(host, slash - host);
367 static void set_from_env(const char **var, const char *envname)
369 const char *val = getenv(envname);
370 if (val)
371 *var = val;
374 void http_init(struct remote *remote, const char *url, int proactive_auth)
376 char *low_speed_limit;
377 char *low_speed_time;
379 http_is_verbose = 0;
381 git_config(http_options, NULL);
383 curl_global_init(CURL_GLOBAL_ALL);
385 http_proactive_auth = proactive_auth;
387 if (remote && remote->http_proxy)
388 curl_http_proxy = xstrdup(remote->http_proxy);
390 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
391 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
393 #ifdef USE_CURL_MULTI
395 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
396 if (http_max_requests != NULL)
397 max_requests = atoi(http_max_requests);
400 curlm = curl_multi_init();
401 if (curlm == NULL) {
402 fprintf(stderr, "Error creating curl multi handle.\n");
403 exit(1);
405 #endif
407 if (getenv("GIT_SSL_NO_VERIFY"))
408 curl_ssl_verify = 0;
410 set_from_env(&ssl_cert, "GIT_SSL_CERT");
411 #if LIBCURL_VERSION_NUM >= 0x070903
412 set_from_env(&ssl_key, "GIT_SSL_KEY");
413 #endif
414 #if LIBCURL_VERSION_NUM >= 0x070908
415 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
416 #endif
417 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
419 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
421 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
422 if (low_speed_limit != NULL)
423 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
424 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
425 if (low_speed_time != NULL)
426 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
428 if (curl_ssl_verify == -1)
429 curl_ssl_verify = 1;
431 curl_session_count = 0;
432 #ifdef USE_CURL_MULTI
433 if (max_requests < 1)
434 max_requests = DEFAULT_MAX_REQUESTS;
435 #endif
437 if (getenv("GIT_CURL_FTP_NO_EPSV"))
438 curl_ftp_no_epsv = 1;
440 if (url) {
441 http_auth_init(url);
442 if (!ssl_cert_password_required &&
443 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
444 !prefixcmp(url, "https://"))
445 ssl_cert_password_required = 1;
448 #ifndef NO_CURL_EASY_DUPHANDLE
449 curl_default = get_curl_handle();
450 #endif
453 void http_cleanup(void)
455 struct active_request_slot *slot = active_queue_head;
457 while (slot != NULL) {
458 struct active_request_slot *next = slot->next;
459 if (slot->curl != NULL) {
460 #ifdef USE_CURL_MULTI
461 curl_multi_remove_handle(curlm, slot->curl);
462 #endif
463 curl_easy_cleanup(slot->curl);
465 free(slot);
466 slot = next;
468 active_queue_head = NULL;
470 #ifndef NO_CURL_EASY_DUPHANDLE
471 curl_easy_cleanup(curl_default);
472 #endif
474 #ifdef USE_CURL_MULTI
475 curl_multi_cleanup(curlm);
476 #endif
477 curl_global_cleanup();
479 curl_slist_free_all(pragma_header);
480 pragma_header = NULL;
482 curl_slist_free_all(no_pragma_header);
483 no_pragma_header = NULL;
485 if (curl_http_proxy) {
486 free((void *)curl_http_proxy);
487 curl_http_proxy = NULL;
490 if (ssl_cert_password != NULL) {
491 memset(ssl_cert_password, 0, strlen(ssl_cert_password));
492 free(ssl_cert_password);
493 ssl_cert_password = NULL;
495 ssl_cert_password_required = 0;
498 struct active_request_slot *get_active_slot(void)
500 struct active_request_slot *slot = active_queue_head;
501 struct active_request_slot *newslot;
503 #ifdef USE_CURL_MULTI
504 int num_transfers;
506 /* Wait for a slot to open up if the queue is full */
507 while (active_requests >= max_requests) {
508 curl_multi_perform(curlm, &num_transfers);
509 if (num_transfers < active_requests)
510 process_curl_messages();
512 #endif
514 while (slot != NULL && slot->in_use)
515 slot = slot->next;
517 if (slot == NULL) {
518 newslot = xmalloc(sizeof(*newslot));
519 newslot->curl = NULL;
520 newslot->in_use = 0;
521 newslot->next = NULL;
523 slot = active_queue_head;
524 if (slot == NULL) {
525 active_queue_head = newslot;
526 } else {
527 while (slot->next != NULL)
528 slot = slot->next;
529 slot->next = newslot;
531 slot = newslot;
534 if (slot->curl == NULL) {
535 #ifdef NO_CURL_EASY_DUPHANDLE
536 slot->curl = get_curl_handle();
537 #else
538 slot->curl = curl_easy_duphandle(curl_default);
539 #endif
540 curl_session_count++;
543 active_requests++;
544 slot->in_use = 1;
545 slot->local = NULL;
546 slot->results = NULL;
547 slot->finished = NULL;
548 slot->callback_data = NULL;
549 slot->callback_func = NULL;
550 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
551 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
552 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
553 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
554 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
555 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
556 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
557 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
558 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
560 return slot;
563 int start_active_slot(struct active_request_slot *slot)
565 #ifdef USE_CURL_MULTI
566 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
567 int num_transfers;
569 if (curlm_result != CURLM_OK &&
570 curlm_result != CURLM_CALL_MULTI_PERFORM) {
571 active_requests--;
572 slot->in_use = 0;
573 return 0;
577 * We know there must be something to do, since we just added
578 * something.
580 curl_multi_perform(curlm, &num_transfers);
581 #endif
582 return 1;
585 #ifdef USE_CURL_MULTI
586 struct fill_chain {
587 void *data;
588 int (*fill)(void *);
589 struct fill_chain *next;
592 static struct fill_chain *fill_cfg;
594 void add_fill_function(void *data, int (*fill)(void *))
596 struct fill_chain *new = xmalloc(sizeof(*new));
597 struct fill_chain **linkp = &fill_cfg;
598 new->data = data;
599 new->fill = fill;
600 new->next = NULL;
601 while (*linkp)
602 linkp = &(*linkp)->next;
603 *linkp = new;
606 void fill_active_slots(void)
608 struct active_request_slot *slot = active_queue_head;
610 while (active_requests < max_requests) {
611 struct fill_chain *fill;
612 for (fill = fill_cfg; fill; fill = fill->next)
613 if (fill->fill(fill->data))
614 break;
616 if (!fill)
617 break;
620 while (slot != NULL) {
621 if (!slot->in_use && slot->curl != NULL
622 && curl_session_count > min_curl_sessions) {
623 curl_easy_cleanup(slot->curl);
624 slot->curl = NULL;
625 curl_session_count--;
627 slot = slot->next;
631 void step_active_slots(void)
633 int num_transfers;
634 CURLMcode curlm_result;
636 do {
637 curlm_result = curl_multi_perform(curlm, &num_transfers);
638 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
639 if (num_transfers < active_requests) {
640 process_curl_messages();
641 fill_active_slots();
644 #endif
646 void run_active_slot(struct active_request_slot *slot)
648 #ifdef USE_CURL_MULTI
649 long last_pos = 0;
650 long current_pos;
651 fd_set readfds;
652 fd_set writefds;
653 fd_set excfds;
654 int max_fd;
655 struct timeval select_timeout;
656 int finished = 0;
658 slot->finished = &finished;
659 while (!finished) {
660 data_received = 0;
661 step_active_slots();
663 if (!data_received && slot->local != NULL) {
664 current_pos = ftell(slot->local);
665 if (current_pos > last_pos)
666 data_received++;
667 last_pos = current_pos;
670 if (slot->in_use && !data_received) {
671 max_fd = 0;
672 FD_ZERO(&readfds);
673 FD_ZERO(&writefds);
674 FD_ZERO(&excfds);
675 select_timeout.tv_sec = 0;
676 select_timeout.tv_usec = 50000;
677 select(max_fd, &readfds, &writefds,
678 &excfds, &select_timeout);
681 #else
682 while (slot->in_use) {
683 slot->curl_result = curl_easy_perform(slot->curl);
684 finish_active_slot(slot);
686 #endif
689 static void closedown_active_slot(struct active_request_slot *slot)
691 active_requests--;
692 slot->in_use = 0;
695 static void release_active_slot(struct active_request_slot *slot)
697 closedown_active_slot(slot);
698 if (slot->curl && curl_session_count > min_curl_sessions) {
699 #ifdef USE_CURL_MULTI
700 curl_multi_remove_handle(curlm, slot->curl);
701 #endif
702 curl_easy_cleanup(slot->curl);
703 slot->curl = NULL;
704 curl_session_count--;
706 #ifdef USE_CURL_MULTI
707 fill_active_slots();
708 #endif
711 void finish_active_slot(struct active_request_slot *slot)
713 closedown_active_slot(slot);
714 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
716 if (slot->finished != NULL)
717 (*slot->finished) = 1;
719 /* Store slot results so they can be read after the slot is reused */
720 if (slot->results != NULL) {
721 slot->results->curl_result = slot->curl_result;
722 slot->results->http_code = slot->http_code;
725 /* Run callback if appropriate */
726 if (slot->callback_func != NULL)
727 slot->callback_func(slot->callback_data);
730 void finish_all_active_slots(void)
732 struct active_request_slot *slot = active_queue_head;
734 while (slot != NULL)
735 if (slot->in_use) {
736 run_active_slot(slot);
737 slot = active_queue_head;
738 } else {
739 slot = slot->next;
743 /* Helpers for modifying and creating URLs */
744 static inline int needs_quote(int ch)
746 if (((ch >= 'A') && (ch <= 'Z'))
747 || ((ch >= 'a') && (ch <= 'z'))
748 || ((ch >= '0') && (ch <= '9'))
749 || (ch == '/')
750 || (ch == '-')
751 || (ch == '.'))
752 return 0;
753 return 1;
756 static char *quote_ref_url(const char *base, const char *ref)
758 struct strbuf buf = STRBUF_INIT;
759 const char *cp;
760 int ch;
762 end_url_with_slash(&buf, base);
764 for (cp = ref; (ch = *cp) != 0; cp++)
765 if (needs_quote(ch))
766 strbuf_addf(&buf, "%%%02x", ch);
767 else
768 strbuf_addch(&buf, *cp);
770 return strbuf_detach(&buf, NULL);
773 void append_remote_object_url(struct strbuf *buf, const char *url,
774 const char *hex,
775 int only_two_digit_prefix)
777 end_url_with_slash(buf, url);
779 strbuf_addf(buf, "objects/%.*s/", 2, hex);
780 if (!only_two_digit_prefix)
781 strbuf_addf(buf, "%s", hex+2);
784 char *get_remote_object_url(const char *url, const char *hex,
785 int only_two_digit_prefix)
787 struct strbuf buf = STRBUF_INIT;
788 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
789 return strbuf_detach(&buf, NULL);
792 /* http_request() targets */
793 #define HTTP_REQUEST_STRBUF 0
794 #define HTTP_REQUEST_FILE 1
796 static int http_request(const char *url, void *result, int target, int options)
798 struct active_request_slot *slot;
799 struct slot_results results;
800 struct curl_slist *headers = NULL;
801 struct strbuf buf = STRBUF_INIT;
802 int ret;
804 slot = get_active_slot();
805 slot->results = &results;
806 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
808 if (result == NULL) {
809 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
810 } else {
811 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
812 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
814 if (target == HTTP_REQUEST_FILE) {
815 long posn = ftell(result);
816 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
817 fwrite);
818 if (posn > 0) {
819 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
820 headers = curl_slist_append(headers, buf.buf);
821 strbuf_reset(&buf);
823 slot->local = result;
824 } else
825 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
826 fwrite_buffer);
829 strbuf_addstr(&buf, "Pragma:");
830 if (options & HTTP_NO_CACHE)
831 strbuf_addstr(&buf, " no-cache");
833 headers = curl_slist_append(headers, buf.buf);
835 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
836 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
838 if (start_active_slot(slot)) {
839 run_active_slot(slot);
840 if (results.curl_result == CURLE_OK)
841 ret = HTTP_OK;
842 else if (missing_target(&results))
843 ret = HTTP_MISSING_TARGET;
844 else if (results.http_code == 401) {
845 if (user_name && user_pass) {
846 ret = HTTP_NOAUTH;
847 } else {
849 * git_getpass is needed here because its very likely stdin/stdout are
850 * pipes to our parent process. So we instead need to use /dev/tty,
851 * but that is non-portable. Using git_getpass() can at least be stubbed
852 * on other platforms with a different implementation if/when necessary.
854 if (!user_name)
855 user_name = xstrdup(git_getpass_with_description("Username", description));
856 init_curl_http_auth(slot->curl);
857 ret = HTTP_REAUTH;
859 } else {
860 if (!curl_errorstr[0])
861 strlcpy(curl_errorstr,
862 curl_easy_strerror(results.curl_result),
863 sizeof(curl_errorstr));
864 ret = HTTP_ERROR;
866 } else {
867 error("Unable to start HTTP request for %s", url);
868 ret = HTTP_START_FAILED;
871 slot->local = NULL;
872 curl_slist_free_all(headers);
873 strbuf_release(&buf);
875 return ret;
878 static int http_request_reauth(const char *url, void *result, int target,
879 int options)
881 int ret = http_request(url, result, target, options);
882 if (ret != HTTP_REAUTH)
883 return ret;
884 return http_request(url, result, target, options);
887 int http_get_strbuf(const char *url, struct strbuf *result, int options)
889 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
893 * Downloads an url and stores the result in the given file.
895 * If a previous interrupted download is detected (i.e. a previous temporary
896 * file is still around) the download is resumed.
898 static int http_get_file(const char *url, const char *filename, int options)
900 int ret;
901 struct strbuf tmpfile = STRBUF_INIT;
902 FILE *result;
904 strbuf_addf(&tmpfile, "%s.temp", filename);
905 result = fopen(tmpfile.buf, "a");
906 if (! result) {
907 error("Unable to open local file %s", tmpfile.buf);
908 ret = HTTP_ERROR;
909 goto cleanup;
912 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
913 fclose(result);
915 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
916 ret = HTTP_ERROR;
917 cleanup:
918 strbuf_release(&tmpfile);
919 return ret;
922 int http_error(const char *url, int ret)
924 /* http_request has already handled HTTP_START_FAILED. */
925 if (ret != HTTP_START_FAILED)
926 error("%s while accessing %s", curl_errorstr, url);
928 return ret;
931 int http_fetch_ref(const char *base, struct ref *ref)
933 char *url;
934 struct strbuf buffer = STRBUF_INIT;
935 int ret = -1;
937 url = quote_ref_url(base, ref->name);
938 if (http_get_strbuf(url, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
939 strbuf_rtrim(&buffer);
940 if (buffer.len == 40)
941 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
942 else if (!prefixcmp(buffer.buf, "ref: ")) {
943 ref->symref = xstrdup(buffer.buf + 5);
944 ret = 0;
948 strbuf_release(&buffer);
949 free(url);
950 return ret;
953 /* Helpers for fetching packs */
954 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
956 char *url, *tmp;
957 struct strbuf buf = STRBUF_INIT;
959 if (http_is_verbose)
960 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
962 end_url_with_slash(&buf, base_url);
963 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
964 url = strbuf_detach(&buf, NULL);
966 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
967 tmp = strbuf_detach(&buf, NULL);
969 if (http_get_file(url, tmp, 0) != HTTP_OK) {
970 error("Unable to get pack index %s\n", url);
971 free(tmp);
972 tmp = NULL;
975 free(url);
976 return tmp;
979 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
980 unsigned char *sha1, const char *base_url)
982 struct packed_git *new_pack;
983 char *tmp_idx = NULL;
984 int ret;
986 if (has_pack_index(sha1)) {
987 new_pack = parse_pack_index(sha1, NULL);
988 if (!new_pack)
989 return -1; /* parse_pack_index() already issued error message */
990 goto add_pack;
993 tmp_idx = fetch_pack_index(sha1, base_url);
994 if (!tmp_idx)
995 return -1;
997 new_pack = parse_pack_index(sha1, tmp_idx);
998 if (!new_pack) {
999 unlink(tmp_idx);
1000 free(tmp_idx);
1002 return -1; /* parse_pack_index() already issued error message */
1005 ret = verify_pack_index(new_pack);
1006 if (!ret) {
1007 close_pack_index(new_pack);
1008 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1010 free(tmp_idx);
1011 if (ret)
1012 return -1;
1014 add_pack:
1015 new_pack->next = *packs_head;
1016 *packs_head = new_pack;
1017 return 0;
1020 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1022 int ret = 0, i = 0;
1023 char *url, *data;
1024 struct strbuf buf = STRBUF_INIT;
1025 unsigned char sha1[20];
1027 end_url_with_slash(&buf, base_url);
1028 strbuf_addstr(&buf, "objects/info/packs");
1029 url = strbuf_detach(&buf, NULL);
1031 ret = http_get_strbuf(url, &buf, HTTP_NO_CACHE);
1032 if (ret != HTTP_OK)
1033 goto cleanup;
1035 data = buf.buf;
1036 while (i < buf.len) {
1037 switch (data[i]) {
1038 case 'P':
1039 i++;
1040 if (i + 52 <= buf.len &&
1041 !prefixcmp(data + i, " pack-") &&
1042 !prefixcmp(data + i + 46, ".pack\n")) {
1043 get_sha1_hex(data + i + 6, sha1);
1044 fetch_and_setup_pack_index(packs_head, sha1,
1045 base_url);
1046 i += 51;
1047 break;
1049 default:
1050 while (i < buf.len && data[i] != '\n')
1051 i++;
1053 i++;
1056 cleanup:
1057 free(url);
1058 return ret;
1061 void release_http_pack_request(struct http_pack_request *preq)
1063 if (preq->packfile != NULL) {
1064 fclose(preq->packfile);
1065 preq->packfile = NULL;
1066 preq->slot->local = NULL;
1068 if (preq->range_header != NULL) {
1069 curl_slist_free_all(preq->range_header);
1070 preq->range_header = NULL;
1072 preq->slot = NULL;
1073 free(preq->url);
1076 int finish_http_pack_request(struct http_pack_request *preq)
1078 struct packed_git **lst;
1079 struct packed_git *p = preq->target;
1080 char *tmp_idx;
1081 struct child_process ip;
1082 const char *ip_argv[8];
1084 close_pack_index(p);
1086 fclose(preq->packfile);
1087 preq->packfile = NULL;
1088 preq->slot->local = NULL;
1090 lst = preq->lst;
1091 while (*lst != p)
1092 lst = &((*lst)->next);
1093 *lst = (*lst)->next;
1095 tmp_idx = xstrdup(preq->tmpfile);
1096 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1097 ".idx.temp");
1099 ip_argv[0] = "index-pack";
1100 ip_argv[1] = "-o";
1101 ip_argv[2] = tmp_idx;
1102 ip_argv[3] = preq->tmpfile;
1103 ip_argv[4] = NULL;
1105 memset(&ip, 0, sizeof(ip));
1106 ip.argv = ip_argv;
1107 ip.git_cmd = 1;
1108 ip.no_stdin = 1;
1109 ip.no_stdout = 1;
1111 if (run_command(&ip)) {
1112 unlink(preq->tmpfile);
1113 unlink(tmp_idx);
1114 free(tmp_idx);
1115 return -1;
1118 unlink(sha1_pack_index_name(p->sha1));
1120 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1121 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1122 free(tmp_idx);
1123 return -1;
1126 install_packed_git(p);
1127 free(tmp_idx);
1128 return 0;
1131 struct http_pack_request *new_http_pack_request(
1132 struct packed_git *target, const char *base_url)
1134 long prev_posn = 0;
1135 char range[RANGE_HEADER_SIZE];
1136 struct strbuf buf = STRBUF_INIT;
1137 struct http_pack_request *preq;
1139 preq = xcalloc(1, sizeof(*preq));
1140 preq->target = target;
1142 end_url_with_slash(&buf, base_url);
1143 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1144 sha1_to_hex(target->sha1));
1145 preq->url = strbuf_detach(&buf, NULL);
1147 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1148 sha1_pack_name(target->sha1));
1149 preq->packfile = fopen(preq->tmpfile, "a");
1150 if (!preq->packfile) {
1151 error("Unable to open local file %s for pack",
1152 preq->tmpfile);
1153 goto abort;
1156 preq->slot = get_active_slot();
1157 preq->slot->local = preq->packfile;
1158 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1159 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1160 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1161 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1162 no_pragma_header);
1165 * If there is data present from a previous transfer attempt,
1166 * resume where it left off
1168 prev_posn = ftell(preq->packfile);
1169 if (prev_posn>0) {
1170 if (http_is_verbose)
1171 fprintf(stderr,
1172 "Resuming fetch of pack %s at byte %ld\n",
1173 sha1_to_hex(target->sha1), prev_posn);
1174 sprintf(range, "Range: bytes=%ld-", prev_posn);
1175 preq->range_header = curl_slist_append(NULL, range);
1176 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1177 preq->range_header);
1180 return preq;
1182 abort:
1183 free(preq->url);
1184 free(preq);
1185 return NULL;
1188 /* Helpers for fetching objects (loose) */
1189 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1190 void *data)
1192 unsigned char expn[4096];
1193 size_t size = eltsize * nmemb;
1194 int posn = 0;
1195 struct http_object_request *freq =
1196 (struct http_object_request *)data;
1197 do {
1198 ssize_t retval = xwrite(freq->localfile,
1199 (char *) ptr + posn, size - posn);
1200 if (retval < 0)
1201 return posn;
1202 posn += retval;
1203 } while (posn < size);
1205 freq->stream.avail_in = size;
1206 freq->stream.next_in = (void *)ptr;
1207 do {
1208 freq->stream.next_out = expn;
1209 freq->stream.avail_out = sizeof(expn);
1210 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1211 git_SHA1_Update(&freq->c, expn,
1212 sizeof(expn) - freq->stream.avail_out);
1213 } while (freq->stream.avail_in && freq->zret == Z_OK);
1214 data_received++;
1215 return size;
1218 struct http_object_request *new_http_object_request(const char *base_url,
1219 unsigned char *sha1)
1221 char *hex = sha1_to_hex(sha1);
1222 char *filename;
1223 char prevfile[PATH_MAX];
1224 int prevlocal;
1225 char prev_buf[PREV_BUF_SIZE];
1226 ssize_t prev_read = 0;
1227 long prev_posn = 0;
1228 char range[RANGE_HEADER_SIZE];
1229 struct curl_slist *range_header = NULL;
1230 struct http_object_request *freq;
1232 freq = xcalloc(1, sizeof(*freq));
1233 hashcpy(freq->sha1, sha1);
1234 freq->localfile = -1;
1236 filename = sha1_file_name(sha1);
1237 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1238 "%s.temp", filename);
1240 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1241 unlink_or_warn(prevfile);
1242 rename(freq->tmpfile, prevfile);
1243 unlink_or_warn(freq->tmpfile);
1245 if (freq->localfile != -1)
1246 error("fd leakage in start: %d", freq->localfile);
1247 freq->localfile = open(freq->tmpfile,
1248 O_WRONLY | O_CREAT | O_EXCL, 0666);
1250 * This could have failed due to the "lazy directory creation";
1251 * try to mkdir the last path component.
1253 if (freq->localfile < 0 && errno == ENOENT) {
1254 char *dir = strrchr(freq->tmpfile, '/');
1255 if (dir) {
1256 *dir = 0;
1257 mkdir(freq->tmpfile, 0777);
1258 *dir = '/';
1260 freq->localfile = open(freq->tmpfile,
1261 O_WRONLY | O_CREAT | O_EXCL, 0666);
1264 if (freq->localfile < 0) {
1265 error("Couldn't create temporary file %s: %s",
1266 freq->tmpfile, strerror(errno));
1267 goto abort;
1270 git_inflate_init(&freq->stream);
1272 git_SHA1_Init(&freq->c);
1274 freq->url = get_remote_object_url(base_url, hex, 0);
1277 * If a previous temp file is present, process what was already
1278 * fetched.
1280 prevlocal = open(prevfile, O_RDONLY);
1281 if (prevlocal != -1) {
1282 do {
1283 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1284 if (prev_read>0) {
1285 if (fwrite_sha1_file(prev_buf,
1287 prev_read,
1288 freq) == prev_read) {
1289 prev_posn += prev_read;
1290 } else {
1291 prev_read = -1;
1294 } while (prev_read > 0);
1295 close(prevlocal);
1297 unlink_or_warn(prevfile);
1300 * Reset inflate/SHA1 if there was an error reading the previous temp
1301 * file; also rewind to the beginning of the local file.
1303 if (prev_read == -1) {
1304 memset(&freq->stream, 0, sizeof(freq->stream));
1305 git_inflate_init(&freq->stream);
1306 git_SHA1_Init(&freq->c);
1307 if (prev_posn>0) {
1308 prev_posn = 0;
1309 lseek(freq->localfile, 0, SEEK_SET);
1310 if (ftruncate(freq->localfile, 0) < 0) {
1311 error("Couldn't truncate temporary file %s: %s",
1312 freq->tmpfile, strerror(errno));
1313 goto abort;
1318 freq->slot = get_active_slot();
1320 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1321 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1322 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1323 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1324 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1327 * If we have successfully processed data from a previous fetch
1328 * attempt, only fetch the data we don't already have.
1330 if (prev_posn>0) {
1331 if (http_is_verbose)
1332 fprintf(stderr,
1333 "Resuming fetch of object %s at byte %ld\n",
1334 hex, prev_posn);
1335 sprintf(range, "Range: bytes=%ld-", prev_posn);
1336 range_header = curl_slist_append(range_header, range);
1337 curl_easy_setopt(freq->slot->curl,
1338 CURLOPT_HTTPHEADER, range_header);
1341 return freq;
1343 abort:
1344 free(freq->url);
1345 free(freq);
1346 return NULL;
1349 void process_http_object_request(struct http_object_request *freq)
1351 if (freq->slot == NULL)
1352 return;
1353 freq->curl_result = freq->slot->curl_result;
1354 freq->http_code = freq->slot->http_code;
1355 freq->slot = NULL;
1358 int finish_http_object_request(struct http_object_request *freq)
1360 struct stat st;
1362 close(freq->localfile);
1363 freq->localfile = -1;
1365 process_http_object_request(freq);
1367 if (freq->http_code == 416) {
1368 warning("requested range invalid; we may already have all the data.");
1369 } else if (freq->curl_result != CURLE_OK) {
1370 if (stat(freq->tmpfile, &st) == 0)
1371 if (st.st_size == 0)
1372 unlink_or_warn(freq->tmpfile);
1373 return -1;
1376 git_inflate_end(&freq->stream);
1377 git_SHA1_Final(freq->real_sha1, &freq->c);
1378 if (freq->zret != Z_STREAM_END) {
1379 unlink_or_warn(freq->tmpfile);
1380 return -1;
1382 if (hashcmp(freq->sha1, freq->real_sha1)) {
1383 unlink_or_warn(freq->tmpfile);
1384 return -1;
1386 freq->rename =
1387 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1389 return freq->rename;
1392 void abort_http_object_request(struct http_object_request *freq)
1394 unlink_or_warn(freq->tmpfile);
1396 release_http_object_request(freq);
1399 void release_http_object_request(struct http_object_request *freq)
1401 if (freq->localfile != -1) {
1402 close(freq->localfile);
1403 freq->localfile = -1;
1405 if (freq->url != NULL) {
1406 free(freq->url);
1407 freq->url = NULL;
1409 if (freq->slot != NULL) {
1410 freq->slot->callback_func = NULL;
1411 freq->slot->callback_data = NULL;
1412 release_active_slot(freq->slot);
1413 freq->slot = NULL;