Win32: Unicode arguments (incoming)
[git/mingw/4msysgit.git] / http.c
blob82848373278d8630507df65db8b787d6faae570c
1 #include "http.h"
2 #include "pack.h"
3 #include "sideband.h"
4 #include "run-command.h"
5 #include "url.h"
6 #include "credential.h"
7 #include "version.h"
8 #include "pkt-line.h"
9 #include "exec_cmd.h"
11 int active_requests;
12 int http_is_verbose;
13 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
15 #if LIBCURL_VERSION_NUM >= 0x070a06
16 #define LIBCURL_CAN_HANDLE_AUTH_ANY
17 #endif
19 static int min_curl_sessions = 1;
20 static int curl_session_count;
21 #ifdef USE_CURL_MULTI
22 static int max_requests = -1;
23 static CURLM *curlm;
24 #endif
25 #ifndef NO_CURL_EASY_DUPHANDLE
26 static CURL *curl_default;
27 #endif
29 #define PREV_BUF_SIZE 4096
30 #define RANGE_HEADER_SIZE 30
32 char curl_errorstr[CURL_ERROR_SIZE];
34 static int curl_ssl_verify = -1;
35 static int curl_ssl_try;
36 static const char *ssl_cert;
37 #if LIBCURL_VERSION_NUM >= 0x070903
38 static const char *ssl_key;
39 #endif
40 #if LIBCURL_VERSION_NUM >= 0x070908
41 static const char *ssl_capath;
42 #endif
43 static const char *ssl_cainfo;
44 static long curl_low_speed_limit = -1;
45 static long curl_low_speed_time = -1;
46 static int curl_ftp_no_epsv;
47 static const char *curl_http_proxy;
48 static const char *curl_cookie_file;
49 static struct credential http_auth = CREDENTIAL_INIT;
50 static int http_proactive_auth;
51 static const char *user_agent;
53 #if LIBCURL_VERSION_NUM >= 0x071700
54 /* Use CURLOPT_KEYPASSWD as is */
55 #elif LIBCURL_VERSION_NUM >= 0x070903
56 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
57 #else
58 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
59 #endif
61 static struct credential cert_auth = CREDENTIAL_INIT;
62 static int ssl_cert_password_required;
64 static struct curl_slist *pragma_header;
65 static struct curl_slist *no_pragma_header;
67 static struct active_request_slot *active_queue_head;
69 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
71 size_t size = eltsize * nmemb;
72 struct buffer *buffer = buffer_;
74 if (size > buffer->buf.len - buffer->posn)
75 size = buffer->buf.len - buffer->posn;
76 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
77 buffer->posn += size;
79 return size;
82 #ifndef NO_CURL_IOCTL
83 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
85 struct buffer *buffer = clientp;
87 switch (cmd) {
88 case CURLIOCMD_NOP:
89 return CURLIOE_OK;
91 case CURLIOCMD_RESTARTREAD:
92 buffer->posn = 0;
93 return CURLIOE_OK;
95 default:
96 return CURLIOE_UNKNOWNCMD;
99 #endif
101 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
103 size_t size = eltsize * nmemb;
104 struct strbuf *buffer = buffer_;
106 strbuf_add(buffer, ptr, size);
107 return size;
110 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
112 return eltsize * nmemb;
115 #ifdef USE_CURL_MULTI
116 static void process_curl_messages(void)
118 int num_messages;
119 struct active_request_slot *slot;
120 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
122 while (curl_message != NULL) {
123 if (curl_message->msg == CURLMSG_DONE) {
124 int curl_result = curl_message->data.result;
125 slot = active_queue_head;
126 while (slot != NULL &&
127 slot->curl != curl_message->easy_handle)
128 slot = slot->next;
129 if (slot != NULL) {
130 curl_multi_remove_handle(curlm, slot->curl);
131 slot->curl_result = curl_result;
132 finish_active_slot(slot);
133 } else {
134 fprintf(stderr, "Received DONE message for unknown request!\n");
136 } else {
137 fprintf(stderr, "Unknown CURL message received: %d\n",
138 (int)curl_message->msg);
140 curl_message = curl_multi_info_read(curlm, &num_messages);
143 #endif
145 static int git_config_path(const char **result,
146 const char *var, const char *value)
148 if (git_config_string(result, var, value))
149 return 1;
150 #ifdef __MINGW32__
151 if (**result == '/')
152 *result = system_path((*result) + 1);
153 #endif
154 return 0;
157 static int http_options(const char *var, const char *value, void *cb)
159 if (!strcmp("http.sslverify", var)) {
160 curl_ssl_verify = git_config_bool(var, value);
161 return 0;
163 if (!strcmp("http.sslcert", var))
164 return git_config_path(&ssl_cert, var, value);
165 #if LIBCURL_VERSION_NUM >= 0x070903
166 if (!strcmp("http.sslkey", var))
167 return git_config_path(&ssl_key, var, value);
168 #endif
169 #if LIBCURL_VERSION_NUM >= 0x070908
170 if (!strcmp("http.sslcapath", var))
171 return git_config_path(&ssl_capath, var, value);
172 #endif
173 if (!strcmp("http.sslcainfo", var))
174 return git_config_path(&ssl_cainfo, var, value);
175 if (!strcmp("http.sslcertpasswordprotected", var)) {
176 if (git_config_bool(var, value))
177 ssl_cert_password_required = 1;
178 return 0;
180 if (!strcmp("http.ssltry", var)) {
181 curl_ssl_try = git_config_bool(var, value);
182 return 0;
184 if (!strcmp("http.minsessions", var)) {
185 min_curl_sessions = git_config_int(var, value);
186 #ifndef USE_CURL_MULTI
187 if (min_curl_sessions > 1)
188 min_curl_sessions = 1;
189 #endif
190 return 0;
192 #ifdef USE_CURL_MULTI
193 if (!strcmp("http.maxrequests", var)) {
194 max_requests = git_config_int(var, value);
195 return 0;
197 #endif
198 if (!strcmp("http.lowspeedlimit", var)) {
199 curl_low_speed_limit = (long)git_config_int(var, value);
200 return 0;
202 if (!strcmp("http.lowspeedtime", var)) {
203 curl_low_speed_time = (long)git_config_int(var, value);
204 return 0;
207 if (!strcmp("http.noepsv", var)) {
208 curl_ftp_no_epsv = git_config_bool(var, value);
209 return 0;
211 if (!strcmp("http.proxy", var))
212 return git_config_string(&curl_http_proxy, var, value);
214 if (!strcmp("http.cookiefile", var))
215 return git_config_string(&curl_cookie_file, var, value);
217 if (!strcmp("http.postbuffer", var)) {
218 http_post_buffer = git_config_int(var, value);
219 if (http_post_buffer < LARGE_PACKET_MAX)
220 http_post_buffer = LARGE_PACKET_MAX;
221 return 0;
224 if (!strcmp("http.useragent", var))
225 return git_config_string(&user_agent, var, value);
227 /* Fall back on the default ones */
228 return git_default_config(var, value, cb);
231 static void init_curl_http_auth(CURL *result)
233 if (!http_auth.username)
234 return;
236 credential_fill(&http_auth);
238 #if LIBCURL_VERSION_NUM >= 0x071301
239 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
240 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
241 #else
243 static struct strbuf up = STRBUF_INIT;
245 * Note that we assume we only ever have a single set of
246 * credentials in a given program run, so we do not have
247 * to worry about updating this buffer, only setting its
248 * initial value.
250 if (!up.len)
251 strbuf_addf(&up, "%s:%s",
252 http_auth.username, http_auth.password);
253 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
255 #endif
258 static int has_cert_password(void)
260 if (ssl_cert == NULL || ssl_cert_password_required != 1)
261 return 0;
262 if (!cert_auth.password) {
263 cert_auth.protocol = xstrdup("cert");
264 cert_auth.username = xstrdup("");
265 cert_auth.path = xstrdup(ssl_cert);
266 credential_fill(&cert_auth);
268 return 1;
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 (http_proactive_auth)
293 init_curl_http_auth(result);
295 if (ssl_cert != NULL)
296 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
297 if (has_cert_password())
298 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
299 #if LIBCURL_VERSION_NUM >= 0x070903
300 if (ssl_key != NULL)
301 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
302 #endif
303 #if LIBCURL_VERSION_NUM >= 0x070908
304 if (ssl_capath != NULL)
305 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
306 #endif
307 if (ssl_cainfo != NULL)
308 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
310 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
311 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
312 curl_low_speed_limit);
313 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
314 curl_low_speed_time);
317 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
318 #if LIBCURL_VERSION_NUM >= 0x071301
319 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
320 #elif LIBCURL_VERSION_NUM >= 0x071101
321 curl_easy_setopt(result, CURLOPT_POST301, 1);
322 #endif
324 if (getenv("GIT_CURL_VERBOSE"))
325 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
327 curl_easy_setopt(result, CURLOPT_USERAGENT,
328 user_agent ? user_agent : git_user_agent());
330 if (curl_ftp_no_epsv)
331 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
333 #ifdef CURLOPT_USE_SSL
334 if (curl_ssl_try)
335 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
336 #endif
338 if (curl_http_proxy) {
339 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
340 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
343 return result;
346 static void set_from_env(const char **var, const char *envname)
348 const char *val = getenv(envname);
349 if (val)
350 *var = val;
353 void http_init(struct remote *remote, const char *url, int proactive_auth)
355 char *low_speed_limit;
356 char *low_speed_time;
358 http_is_verbose = 0;
360 git_config(http_options, NULL);
362 curl_global_init(CURL_GLOBAL_ALL);
364 http_proactive_auth = proactive_auth;
366 if (remote && remote->http_proxy)
367 curl_http_proxy = xstrdup(remote->http_proxy);
369 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
370 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
372 #ifdef USE_CURL_MULTI
374 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
375 if (http_max_requests != NULL)
376 max_requests = atoi(http_max_requests);
379 curlm = curl_multi_init();
380 if (curlm == NULL) {
381 fprintf(stderr, "Error creating curl multi handle.\n");
382 exit(1);
384 #endif
386 if (getenv("GIT_SSL_NO_VERIFY"))
387 curl_ssl_verify = 0;
389 set_from_env(&ssl_cert, "GIT_SSL_CERT");
390 #if LIBCURL_VERSION_NUM >= 0x070903
391 set_from_env(&ssl_key, "GIT_SSL_KEY");
392 #endif
393 #if LIBCURL_VERSION_NUM >= 0x070908
394 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
395 #endif
396 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
398 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
400 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
401 if (low_speed_limit != NULL)
402 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
403 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
404 if (low_speed_time != NULL)
405 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
407 if (curl_ssl_verify == -1)
408 curl_ssl_verify = 1;
410 curl_session_count = 0;
411 #ifdef USE_CURL_MULTI
412 if (max_requests < 1)
413 max_requests = DEFAULT_MAX_REQUESTS;
414 #endif
416 if (getenv("GIT_CURL_FTP_NO_EPSV"))
417 curl_ftp_no_epsv = 1;
419 if (url) {
420 credential_from_url(&http_auth, url);
421 if (!ssl_cert_password_required &&
422 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
423 !prefixcmp(url, "https://"))
424 ssl_cert_password_required = 1;
427 #ifndef NO_CURL_EASY_DUPHANDLE
428 curl_default = get_curl_handle();
429 #endif
432 void http_cleanup(void)
434 struct active_request_slot *slot = active_queue_head;
436 while (slot != NULL) {
437 struct active_request_slot *next = slot->next;
438 if (slot->curl != NULL) {
439 #ifdef USE_CURL_MULTI
440 curl_multi_remove_handle(curlm, slot->curl);
441 #endif
442 curl_easy_cleanup(slot->curl);
444 free(slot);
445 slot = next;
447 active_queue_head = NULL;
449 #ifndef NO_CURL_EASY_DUPHANDLE
450 curl_easy_cleanup(curl_default);
451 #endif
453 #ifdef USE_CURL_MULTI
454 curl_multi_cleanup(curlm);
455 #endif
456 curl_global_cleanup();
458 curl_slist_free_all(pragma_header);
459 pragma_header = NULL;
461 curl_slist_free_all(no_pragma_header);
462 no_pragma_header = NULL;
464 if (curl_http_proxy) {
465 free((void *)curl_http_proxy);
466 curl_http_proxy = NULL;
469 if (cert_auth.password != NULL) {
470 memset(cert_auth.password, 0, strlen(cert_auth.password));
471 free(cert_auth.password);
472 cert_auth.password = NULL;
474 ssl_cert_password_required = 0;
477 struct active_request_slot *get_active_slot(void)
479 struct active_request_slot *slot = active_queue_head;
480 struct active_request_slot *newslot;
482 #ifdef USE_CURL_MULTI
483 int num_transfers;
485 /* Wait for a slot to open up if the queue is full */
486 while (active_requests >= max_requests) {
487 curl_multi_perform(curlm, &num_transfers);
488 if (num_transfers < active_requests)
489 process_curl_messages();
491 #endif
493 while (slot != NULL && slot->in_use)
494 slot = slot->next;
496 if (slot == NULL) {
497 newslot = xmalloc(sizeof(*newslot));
498 newslot->curl = NULL;
499 newslot->in_use = 0;
500 newslot->next = NULL;
502 slot = active_queue_head;
503 if (slot == NULL) {
504 active_queue_head = newslot;
505 } else {
506 while (slot->next != NULL)
507 slot = slot->next;
508 slot->next = newslot;
510 slot = newslot;
513 if (slot->curl == NULL) {
514 #ifdef NO_CURL_EASY_DUPHANDLE
515 slot->curl = get_curl_handle();
516 #else
517 slot->curl = curl_easy_duphandle(curl_default);
518 #endif
519 curl_session_count++;
522 active_requests++;
523 slot->in_use = 1;
524 slot->results = NULL;
525 slot->finished = NULL;
526 slot->callback_data = NULL;
527 slot->callback_func = NULL;
528 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
529 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
530 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
531 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
532 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
533 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
534 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
535 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
536 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
537 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
538 if (http_auth.password)
539 init_curl_http_auth(slot->curl);
541 return slot;
544 int start_active_slot(struct active_request_slot *slot)
546 #ifdef USE_CURL_MULTI
547 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
548 int num_transfers;
550 if (curlm_result != CURLM_OK &&
551 curlm_result != CURLM_CALL_MULTI_PERFORM) {
552 active_requests--;
553 slot->in_use = 0;
554 return 0;
558 * We know there must be something to do, since we just added
559 * something.
561 curl_multi_perform(curlm, &num_transfers);
562 #endif
563 return 1;
566 #ifdef USE_CURL_MULTI
567 struct fill_chain {
568 void *data;
569 int (*fill)(void *);
570 struct fill_chain *next;
573 static struct fill_chain *fill_cfg;
575 void add_fill_function(void *data, int (*fill)(void *))
577 struct fill_chain *new = xmalloc(sizeof(*new));
578 struct fill_chain **linkp = &fill_cfg;
579 new->data = data;
580 new->fill = fill;
581 new->next = NULL;
582 while (*linkp)
583 linkp = &(*linkp)->next;
584 *linkp = new;
587 void fill_active_slots(void)
589 struct active_request_slot *slot = active_queue_head;
591 while (active_requests < max_requests) {
592 struct fill_chain *fill;
593 for (fill = fill_cfg; fill; fill = fill->next)
594 if (fill->fill(fill->data))
595 break;
597 if (!fill)
598 break;
601 while (slot != NULL) {
602 if (!slot->in_use && slot->curl != NULL
603 && curl_session_count > min_curl_sessions) {
604 curl_easy_cleanup(slot->curl);
605 slot->curl = NULL;
606 curl_session_count--;
608 slot = slot->next;
612 void step_active_slots(void)
614 int num_transfers;
615 CURLMcode curlm_result;
617 do {
618 curlm_result = curl_multi_perform(curlm, &num_transfers);
619 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
620 if (num_transfers < active_requests) {
621 process_curl_messages();
622 fill_active_slots();
625 #endif
627 void run_active_slot(struct active_request_slot *slot)
629 #ifdef USE_CURL_MULTI
630 fd_set readfds;
631 fd_set writefds;
632 fd_set excfds;
633 int max_fd;
634 struct timeval select_timeout;
635 int finished = 0;
637 slot->finished = &finished;
638 while (!finished) {
639 step_active_slots();
641 if (slot->in_use) {
642 #if LIBCURL_VERSION_NUM >= 0x070f04
643 long curl_timeout;
644 curl_multi_timeout(curlm, &curl_timeout);
645 if (curl_timeout == 0) {
646 continue;
647 } else if (curl_timeout == -1) {
648 select_timeout.tv_sec = 0;
649 select_timeout.tv_usec = 50000;
650 } else {
651 select_timeout.tv_sec = curl_timeout / 1000;
652 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
654 #else
655 select_timeout.tv_sec = 0;
656 select_timeout.tv_usec = 50000;
657 #endif
659 max_fd = -1;
660 FD_ZERO(&readfds);
661 FD_ZERO(&writefds);
662 FD_ZERO(&excfds);
663 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
666 * It can happen that curl_multi_timeout returns a pathologically
667 * long timeout when curl_multi_fdset returns no file descriptors
668 * to read. See commit message for more details.
670 if (max_fd < 0 &&
671 (select_timeout.tv_sec > 0 ||
672 select_timeout.tv_usec > 50000)) {
673 select_timeout.tv_sec = 0;
674 select_timeout.tv_usec = 50000;
677 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
680 #else
681 while (slot->in_use) {
682 slot->curl_result = curl_easy_perform(slot->curl);
683 finish_active_slot(slot);
685 #endif
688 static void closedown_active_slot(struct active_request_slot *slot)
690 active_requests--;
691 slot->in_use = 0;
694 static void release_active_slot(struct active_request_slot *slot)
696 closedown_active_slot(slot);
697 if (slot->curl && curl_session_count > min_curl_sessions) {
698 #ifdef USE_CURL_MULTI
699 curl_multi_remove_handle(curlm, slot->curl);
700 #endif
701 curl_easy_cleanup(slot->curl);
702 slot->curl = NULL;
703 curl_session_count--;
705 #ifdef USE_CURL_MULTI
706 fill_active_slots();
707 #endif
710 void finish_active_slot(struct active_request_slot *slot)
712 closedown_active_slot(slot);
713 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
715 if (slot->finished != NULL)
716 (*slot->finished) = 1;
718 /* Store slot results so they can be read after the slot is reused */
719 if (slot->results != NULL) {
720 slot->results->curl_result = slot->curl_result;
721 slot->results->http_code = slot->http_code;
724 /* Run callback if appropriate */
725 if (slot->callback_func != NULL)
726 slot->callback_func(slot->callback_data);
729 void finish_all_active_slots(void)
731 struct active_request_slot *slot = active_queue_head;
733 while (slot != NULL)
734 if (slot->in_use) {
735 run_active_slot(slot);
736 slot = active_queue_head;
737 } else {
738 slot = slot->next;
742 /* Helpers for modifying and creating URLs */
743 static inline int needs_quote(int ch)
745 if (((ch >= 'A') && (ch <= 'Z'))
746 || ((ch >= 'a') && (ch <= 'z'))
747 || ((ch >= '0') && (ch <= '9'))
748 || (ch == '/')
749 || (ch == '-')
750 || (ch == '.'))
751 return 0;
752 return 1;
755 static char *quote_ref_url(const char *base, const char *ref)
757 struct strbuf buf = STRBUF_INIT;
758 const char *cp;
759 int ch;
761 end_url_with_slash(&buf, base);
763 for (cp = ref; (ch = *cp) != 0; cp++)
764 if (needs_quote(ch))
765 strbuf_addf(&buf, "%%%02x", ch);
766 else
767 strbuf_addch(&buf, *cp);
769 return strbuf_detach(&buf, NULL);
772 void append_remote_object_url(struct strbuf *buf, const char *url,
773 const char *hex,
774 int only_two_digit_prefix)
776 end_url_with_slash(buf, url);
778 strbuf_addf(buf, "objects/%.*s/", 2, hex);
779 if (!only_two_digit_prefix)
780 strbuf_addf(buf, "%s", hex+2);
783 char *get_remote_object_url(const char *url, const char *hex,
784 int only_two_digit_prefix)
786 struct strbuf buf = STRBUF_INIT;
787 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
788 return strbuf_detach(&buf, NULL);
791 int handle_curl_result(struct slot_results *results)
794 * If we see a failing http code with CURLE_OK, we have turned off
795 * FAILONERROR (to keep the server's custom error response), and should
796 * translate the code into failure here.
798 if (results->curl_result == CURLE_OK &&
799 results->http_code >= 400) {
800 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
802 * Normally curl will already have put the "reason phrase"
803 * from the server into curl_errorstr; unfortunately without
804 * FAILONERROR it is lost, so we can give only the numeric
805 * status code.
807 snprintf(curl_errorstr, sizeof(curl_errorstr),
808 "The requested URL returned error: %ld",
809 results->http_code);
812 if (results->curl_result == CURLE_OK) {
813 credential_approve(&http_auth);
814 return HTTP_OK;
815 } else if (missing_target(results))
816 return HTTP_MISSING_TARGET;
817 else if (results->http_code == 401) {
818 if (http_auth.username && http_auth.password) {
819 credential_reject(&http_auth);
820 return HTTP_NOAUTH;
821 } else {
822 credential_fill(&http_auth);
823 return HTTP_REAUTH;
825 } else {
826 #if LIBCURL_VERSION_NUM >= 0x070c00
827 if (!curl_errorstr[0])
828 strlcpy(curl_errorstr,
829 curl_easy_strerror(results->curl_result),
830 sizeof(curl_errorstr));
831 #endif
832 return HTTP_ERROR;
836 /* http_request() targets */
837 #define HTTP_REQUEST_STRBUF 0
838 #define HTTP_REQUEST_FILE 1
840 static int http_request(const char *url, struct strbuf *type,
841 void *result, int target, int options)
843 struct active_request_slot *slot;
844 struct slot_results results;
845 struct curl_slist *headers = NULL;
846 struct strbuf buf = STRBUF_INIT;
847 int ret;
849 slot = get_active_slot();
850 slot->results = &results;
851 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
853 if (result == NULL) {
854 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
855 } else {
856 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
857 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
859 if (target == HTTP_REQUEST_FILE) {
860 long posn = ftell(result);
861 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
862 fwrite);
863 if (posn > 0) {
864 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
865 headers = curl_slist_append(headers, buf.buf);
866 strbuf_reset(&buf);
868 } else
869 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
870 fwrite_buffer);
873 strbuf_addstr(&buf, "Pragma:");
874 if (options & HTTP_NO_CACHE)
875 strbuf_addstr(&buf, " no-cache");
876 if (options & HTTP_KEEP_ERROR)
877 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
879 headers = curl_slist_append(headers, buf.buf);
881 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
882 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
883 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
885 if (start_active_slot(slot)) {
886 run_active_slot(slot);
887 ret = handle_curl_result(&results);
888 } else {
889 snprintf(curl_errorstr, sizeof(curl_errorstr),
890 "failed to start HTTP request");
891 ret = HTTP_START_FAILED;
894 if (type) {
895 char *t;
896 strbuf_reset(type);
897 curl_easy_getinfo(slot->curl, CURLINFO_CONTENT_TYPE, &t);
898 if (t)
899 strbuf_addstr(type, t);
902 curl_slist_free_all(headers);
903 strbuf_release(&buf);
905 return ret;
908 static int http_request_reauth(const char *url,
909 struct strbuf *type,
910 void *result, int target,
911 int options)
913 int ret = http_request(url, type, result, target, options);
914 if (ret != HTTP_REAUTH)
915 return ret;
918 * If we are using KEEP_ERROR, the previous request may have
919 * put cruft into our output stream; we should clear it out before
920 * making our next request. We only know how to do this for
921 * the strbuf case, but that is enough to satisfy current callers.
923 if (options & HTTP_KEEP_ERROR) {
924 switch (target) {
925 case HTTP_REQUEST_STRBUF:
926 strbuf_reset(result);
927 break;
928 default:
929 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
932 return http_request(url, type, result, target, options);
935 int http_get_strbuf(const char *url,
936 struct strbuf *type,
937 struct strbuf *result, int options)
939 return http_request_reauth(url, type, result,
940 HTTP_REQUEST_STRBUF, options);
944 * Downloads a URL and stores the result in the given file.
946 * If a previous interrupted download is detected (i.e. a previous temporary
947 * file is still around) the download is resumed.
949 static int http_get_file(const char *url, const char *filename, int options)
951 int ret;
952 struct strbuf tmpfile = STRBUF_INIT;
953 FILE *result;
955 strbuf_addf(&tmpfile, "%s.temp", filename);
956 result = fopen(tmpfile.buf, "a");
957 if (! result) {
958 error("Unable to open local file %s", tmpfile.buf);
959 ret = HTTP_ERROR;
960 goto cleanup;
963 ret = http_request_reauth(url, NULL, result, HTTP_REQUEST_FILE, options);
964 fclose(result);
966 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
967 ret = HTTP_ERROR;
968 cleanup:
969 strbuf_release(&tmpfile);
970 return ret;
973 int http_fetch_ref(const char *base, struct ref *ref)
975 char *url;
976 struct strbuf buffer = STRBUF_INIT;
977 int ret = -1;
979 url = quote_ref_url(base, ref->name);
980 if (http_get_strbuf(url, NULL, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
981 strbuf_rtrim(&buffer);
982 if (buffer.len == 40)
983 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
984 else if (!prefixcmp(buffer.buf, "ref: ")) {
985 ref->symref = xstrdup(buffer.buf + 5);
986 ret = 0;
990 strbuf_release(&buffer);
991 free(url);
992 return ret;
995 /* Helpers for fetching packs */
996 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
998 char *url, *tmp;
999 struct strbuf buf = STRBUF_INIT;
1001 if (http_is_verbose)
1002 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1004 end_url_with_slash(&buf, base_url);
1005 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1006 url = strbuf_detach(&buf, NULL);
1008 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1009 tmp = strbuf_detach(&buf, NULL);
1011 if (http_get_file(url, tmp, 0) != HTTP_OK) {
1012 error("Unable to get pack index %s", url);
1013 free(tmp);
1014 tmp = NULL;
1017 free(url);
1018 return tmp;
1021 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1022 unsigned char *sha1, const char *base_url)
1024 struct packed_git *new_pack;
1025 char *tmp_idx = NULL;
1026 int ret;
1028 if (has_pack_index(sha1)) {
1029 new_pack = parse_pack_index(sha1, NULL);
1030 if (!new_pack)
1031 return -1; /* parse_pack_index() already issued error message */
1032 goto add_pack;
1035 tmp_idx = fetch_pack_index(sha1, base_url);
1036 if (!tmp_idx)
1037 return -1;
1039 new_pack = parse_pack_index(sha1, tmp_idx);
1040 if (!new_pack) {
1041 unlink(tmp_idx);
1042 free(tmp_idx);
1044 return -1; /* parse_pack_index() already issued error message */
1047 ret = verify_pack_index(new_pack);
1048 if (!ret) {
1049 close_pack_index(new_pack);
1050 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1052 free(tmp_idx);
1053 if (ret)
1054 return -1;
1056 add_pack:
1057 new_pack->next = *packs_head;
1058 *packs_head = new_pack;
1059 return 0;
1062 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1064 int ret = 0, i = 0;
1065 char *url, *data;
1066 struct strbuf buf = STRBUF_INIT;
1067 unsigned char sha1[20];
1069 end_url_with_slash(&buf, base_url);
1070 strbuf_addstr(&buf, "objects/info/packs");
1071 url = strbuf_detach(&buf, NULL);
1073 ret = http_get_strbuf(url, NULL, &buf, HTTP_NO_CACHE);
1074 if (ret != HTTP_OK)
1075 goto cleanup;
1077 data = buf.buf;
1078 while (i < buf.len) {
1079 switch (data[i]) {
1080 case 'P':
1081 i++;
1082 if (i + 52 <= buf.len &&
1083 !prefixcmp(data + i, " pack-") &&
1084 !prefixcmp(data + i + 46, ".pack\n")) {
1085 get_sha1_hex(data + i + 6, sha1);
1086 fetch_and_setup_pack_index(packs_head, sha1,
1087 base_url);
1088 i += 51;
1089 break;
1091 default:
1092 while (i < buf.len && data[i] != '\n')
1093 i++;
1095 i++;
1098 cleanup:
1099 free(url);
1100 return ret;
1103 void release_http_pack_request(struct http_pack_request *preq)
1105 if (preq->packfile != NULL) {
1106 fclose(preq->packfile);
1107 preq->packfile = NULL;
1109 if (preq->range_header != NULL) {
1110 curl_slist_free_all(preq->range_header);
1111 preq->range_header = NULL;
1113 preq->slot = NULL;
1114 free(preq->url);
1117 int finish_http_pack_request(struct http_pack_request *preq)
1119 struct packed_git **lst;
1120 struct packed_git *p = preq->target;
1121 char *tmp_idx;
1122 struct child_process ip;
1123 const char *ip_argv[8];
1125 close_pack_index(p);
1127 fclose(preq->packfile);
1128 preq->packfile = NULL;
1130 lst = preq->lst;
1131 while (*lst != p)
1132 lst = &((*lst)->next);
1133 *lst = (*lst)->next;
1135 tmp_idx = xstrdup(preq->tmpfile);
1136 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1137 ".idx.temp");
1139 ip_argv[0] = "index-pack";
1140 ip_argv[1] = "-o";
1141 ip_argv[2] = tmp_idx;
1142 ip_argv[3] = preq->tmpfile;
1143 ip_argv[4] = NULL;
1145 memset(&ip, 0, sizeof(ip));
1146 ip.argv = ip_argv;
1147 ip.git_cmd = 1;
1148 ip.no_stdin = 1;
1149 ip.no_stdout = 1;
1151 if (run_command(&ip)) {
1152 unlink(preq->tmpfile);
1153 unlink(tmp_idx);
1154 free(tmp_idx);
1155 return -1;
1158 unlink(sha1_pack_index_name(p->sha1));
1160 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1161 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1162 free(tmp_idx);
1163 return -1;
1166 install_packed_git(p);
1167 free(tmp_idx);
1168 return 0;
1171 struct http_pack_request *new_http_pack_request(
1172 struct packed_git *target, const char *base_url)
1174 long prev_posn = 0;
1175 char range[RANGE_HEADER_SIZE];
1176 struct strbuf buf = STRBUF_INIT;
1177 struct http_pack_request *preq;
1179 preq = xcalloc(1, sizeof(*preq));
1180 preq->target = target;
1182 end_url_with_slash(&buf, base_url);
1183 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1184 sha1_to_hex(target->sha1));
1185 preq->url = strbuf_detach(&buf, NULL);
1187 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1188 sha1_pack_name(target->sha1));
1189 preq->packfile = fopen(preq->tmpfile, "a");
1190 if (!preq->packfile) {
1191 error("Unable to open local file %s for pack",
1192 preq->tmpfile);
1193 goto abort;
1196 preq->slot = get_active_slot();
1197 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1198 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1199 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1200 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1201 no_pragma_header);
1204 * If there is data present from a previous transfer attempt,
1205 * resume where it left off
1207 prev_posn = ftell(preq->packfile);
1208 if (prev_posn>0) {
1209 if (http_is_verbose)
1210 fprintf(stderr,
1211 "Resuming fetch of pack %s at byte %ld\n",
1212 sha1_to_hex(target->sha1), prev_posn);
1213 sprintf(range, "Range: bytes=%ld-", prev_posn);
1214 preq->range_header = curl_slist_append(NULL, range);
1215 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1216 preq->range_header);
1219 return preq;
1221 abort:
1222 free(preq->url);
1223 free(preq);
1224 return NULL;
1227 /* Helpers for fetching objects (loose) */
1228 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1229 void *data)
1231 unsigned char expn[4096];
1232 size_t size = eltsize * nmemb;
1233 int posn = 0;
1234 struct http_object_request *freq =
1235 (struct http_object_request *)data;
1236 do {
1237 ssize_t retval = xwrite(freq->localfile,
1238 (char *) ptr + posn, size - posn);
1239 if (retval < 0)
1240 return posn;
1241 posn += retval;
1242 } while (posn < size);
1244 freq->stream.avail_in = size;
1245 freq->stream.next_in = (void *)ptr;
1246 do {
1247 freq->stream.next_out = expn;
1248 freq->stream.avail_out = sizeof(expn);
1249 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1250 git_SHA1_Update(&freq->c, expn,
1251 sizeof(expn) - freq->stream.avail_out);
1252 } while (freq->stream.avail_in && freq->zret == Z_OK);
1253 return size;
1256 struct http_object_request *new_http_object_request(const char *base_url,
1257 unsigned char *sha1)
1259 char *hex = sha1_to_hex(sha1);
1260 char *filename;
1261 char prevfile[PATH_MAX];
1262 int prevlocal;
1263 char prev_buf[PREV_BUF_SIZE];
1264 ssize_t prev_read = 0;
1265 long prev_posn = 0;
1266 char range[RANGE_HEADER_SIZE];
1267 struct curl_slist *range_header = NULL;
1268 struct http_object_request *freq;
1270 freq = xcalloc(1, sizeof(*freq));
1271 hashcpy(freq->sha1, sha1);
1272 freq->localfile = -1;
1274 filename = sha1_file_name(sha1);
1275 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1276 "%s.temp", filename);
1278 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1279 unlink_or_warn(prevfile);
1280 rename(freq->tmpfile, prevfile);
1281 unlink_or_warn(freq->tmpfile);
1283 if (freq->localfile != -1)
1284 error("fd leakage in start: %d", freq->localfile);
1285 freq->localfile = open(freq->tmpfile,
1286 O_WRONLY | O_CREAT | O_EXCL, 0666);
1288 * This could have failed due to the "lazy directory creation";
1289 * try to mkdir the last path component.
1291 if (freq->localfile < 0 && errno == ENOENT) {
1292 char *dir = strrchr(freq->tmpfile, '/');
1293 if (dir) {
1294 *dir = 0;
1295 mkdir(freq->tmpfile, 0777);
1296 *dir = '/';
1298 freq->localfile = open(freq->tmpfile,
1299 O_WRONLY | O_CREAT | O_EXCL, 0666);
1302 if (freq->localfile < 0) {
1303 error("Couldn't create temporary file %s: %s",
1304 freq->tmpfile, strerror(errno));
1305 goto abort;
1308 git_inflate_init(&freq->stream);
1310 git_SHA1_Init(&freq->c);
1312 freq->url = get_remote_object_url(base_url, hex, 0);
1315 * If a previous temp file is present, process what was already
1316 * fetched.
1318 prevlocal = open(prevfile, O_RDONLY);
1319 if (prevlocal != -1) {
1320 do {
1321 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1322 if (prev_read>0) {
1323 if (fwrite_sha1_file(prev_buf,
1325 prev_read,
1326 freq) == prev_read) {
1327 prev_posn += prev_read;
1328 } else {
1329 prev_read = -1;
1332 } while (prev_read > 0);
1333 close(prevlocal);
1335 unlink_or_warn(prevfile);
1338 * Reset inflate/SHA1 if there was an error reading the previous temp
1339 * file; also rewind to the beginning of the local file.
1341 if (prev_read == -1) {
1342 memset(&freq->stream, 0, sizeof(freq->stream));
1343 git_inflate_init(&freq->stream);
1344 git_SHA1_Init(&freq->c);
1345 if (prev_posn>0) {
1346 prev_posn = 0;
1347 lseek(freq->localfile, 0, SEEK_SET);
1348 if (ftruncate(freq->localfile, 0) < 0) {
1349 error("Couldn't truncate temporary file %s: %s",
1350 freq->tmpfile, strerror(errno));
1351 goto abort;
1356 freq->slot = get_active_slot();
1358 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1359 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1360 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1361 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1362 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1365 * If we have successfully processed data from a previous fetch
1366 * attempt, only fetch the data we don't already have.
1368 if (prev_posn>0) {
1369 if (http_is_verbose)
1370 fprintf(stderr,
1371 "Resuming fetch of object %s at byte %ld\n",
1372 hex, prev_posn);
1373 sprintf(range, "Range: bytes=%ld-", prev_posn);
1374 range_header = curl_slist_append(range_header, range);
1375 curl_easy_setopt(freq->slot->curl,
1376 CURLOPT_HTTPHEADER, range_header);
1379 return freq;
1381 abort:
1382 free(freq->url);
1383 free(freq);
1384 return NULL;
1387 void process_http_object_request(struct http_object_request *freq)
1389 if (freq->slot == NULL)
1390 return;
1391 freq->curl_result = freq->slot->curl_result;
1392 freq->http_code = freq->slot->http_code;
1393 freq->slot = NULL;
1396 int finish_http_object_request(struct http_object_request *freq)
1398 struct stat st;
1400 close(freq->localfile);
1401 freq->localfile = -1;
1403 process_http_object_request(freq);
1405 if (freq->http_code == 416) {
1406 warning("requested range invalid; we may already have all the data.");
1407 } else if (freq->curl_result != CURLE_OK) {
1408 if (stat(freq->tmpfile, &st) == 0)
1409 if (st.st_size == 0)
1410 unlink_or_warn(freq->tmpfile);
1411 return -1;
1414 git_inflate_end(&freq->stream);
1415 git_SHA1_Final(freq->real_sha1, &freq->c);
1416 if (freq->zret != Z_STREAM_END) {
1417 unlink_or_warn(freq->tmpfile);
1418 return -1;
1420 if (hashcmp(freq->sha1, freq->real_sha1)) {
1421 unlink_or_warn(freq->tmpfile);
1422 return -1;
1424 freq->rename =
1425 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1427 return freq->rename;
1430 void abort_http_object_request(struct http_object_request *freq)
1432 unlink_or_warn(freq->tmpfile);
1434 release_http_object_request(freq);
1437 void release_http_object_request(struct http_object_request *freq)
1439 if (freq->localfile != -1) {
1440 close(freq->localfile);
1441 freq->localfile = -1;
1443 if (freq->url != NULL) {
1444 free(freq->url);
1445 freq->url = NULL;
1447 if (freq->slot != NULL) {
1448 freq->slot->callback_func = NULL;
1449 freq->slot->callback_data = NULL;
1450 release_active_slot(freq->slot);
1451 freq->slot = NULL;