git-remote-mediawiki: do not remove installed files in "clean" target
[git/debian.git] / http.c
blob92aba59082a4ed9aa0c92d8522793abcd332e279
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"
10 int active_requests;
11 int http_is_verbose;
12 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
14 #if LIBCURL_VERSION_NUM >= 0x070a06
15 #define LIBCURL_CAN_HANDLE_AUTH_ANY
16 #endif
18 static int min_curl_sessions = 1;
19 static int curl_session_count;
20 #ifdef USE_CURL_MULTI
21 static int max_requests = -1;
22 static CURLM *curlm;
23 #endif
24 #ifndef NO_CURL_EASY_DUPHANDLE
25 static CURL *curl_default;
26 #endif
28 #define PREV_BUF_SIZE 4096
29 #define RANGE_HEADER_SIZE 30
31 char curl_errorstr[CURL_ERROR_SIZE];
33 static int curl_ssl_verify = -1;
34 static int curl_ssl_try;
35 static const char *ssl_cert;
36 #if LIBCURL_VERSION_NUM >= 0x070903
37 static const char *ssl_key;
38 #endif
39 #if LIBCURL_VERSION_NUM >= 0x070908
40 static const char *ssl_capath;
41 #endif
42 static const char *ssl_cainfo;
43 static long curl_low_speed_limit = -1;
44 static long curl_low_speed_time = -1;
45 static int curl_ftp_no_epsv;
46 static const char *curl_http_proxy;
47 static const char *curl_cookie_file;
48 static struct credential http_auth = CREDENTIAL_INIT;
49 static int http_proactive_auth;
50 static const char *user_agent;
52 #if LIBCURL_VERSION_NUM >= 0x071700
53 /* Use CURLOPT_KEYPASSWD as is */
54 #elif LIBCURL_VERSION_NUM >= 0x070903
55 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
56 #else
57 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
58 #endif
60 static struct credential cert_auth = CREDENTIAL_INIT;
61 static int ssl_cert_password_required;
63 static struct curl_slist *pragma_header;
64 static struct curl_slist *no_pragma_header;
66 static struct active_request_slot *active_queue_head;
68 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
70 size_t size = eltsize * nmemb;
71 struct buffer *buffer = buffer_;
73 if (size > buffer->buf.len - buffer->posn)
74 size = buffer->buf.len - buffer->posn;
75 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
76 buffer->posn += size;
78 return size;
81 #ifndef NO_CURL_IOCTL
82 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
84 struct buffer *buffer = clientp;
86 switch (cmd) {
87 case CURLIOCMD_NOP:
88 return CURLIOE_OK;
90 case CURLIOCMD_RESTARTREAD:
91 buffer->posn = 0;
92 return CURLIOE_OK;
94 default:
95 return CURLIOE_UNKNOWNCMD;
98 #endif
100 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
102 size_t size = eltsize * nmemb;
103 struct strbuf *buffer = buffer_;
105 strbuf_add(buffer, ptr, size);
106 return size;
109 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
111 return eltsize * nmemb;
114 #ifdef USE_CURL_MULTI
115 static void process_curl_messages(void)
117 int num_messages;
118 struct active_request_slot *slot;
119 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
121 while (curl_message != NULL) {
122 if (curl_message->msg == CURLMSG_DONE) {
123 int curl_result = curl_message->data.result;
124 slot = active_queue_head;
125 while (slot != NULL &&
126 slot->curl != curl_message->easy_handle)
127 slot = slot->next;
128 if (slot != NULL) {
129 curl_multi_remove_handle(curlm, slot->curl);
130 slot->curl_result = curl_result;
131 finish_active_slot(slot);
132 } else {
133 fprintf(stderr, "Received DONE message for unknown request!\n");
135 } else {
136 fprintf(stderr, "Unknown CURL message received: %d\n",
137 (int)curl_message->msg);
139 curl_message = curl_multi_info_read(curlm, &num_messages);
142 #endif
144 static int http_options(const char *var, const char *value, void *cb)
146 if (!strcmp("http.sslverify", var)) {
147 curl_ssl_verify = git_config_bool(var, value);
148 return 0;
150 if (!strcmp("http.sslcert", var))
151 return git_config_string(&ssl_cert, var, value);
152 #if LIBCURL_VERSION_NUM >= 0x070903
153 if (!strcmp("http.sslkey", var))
154 return git_config_string(&ssl_key, var, value);
155 #endif
156 #if LIBCURL_VERSION_NUM >= 0x070908
157 if (!strcmp("http.sslcapath", var))
158 return git_config_string(&ssl_capath, var, value);
159 #endif
160 if (!strcmp("http.sslcainfo", var))
161 return git_config_string(&ssl_cainfo, var, value);
162 if (!strcmp("http.sslcertpasswordprotected", var)) {
163 if (git_config_bool(var, value))
164 ssl_cert_password_required = 1;
165 return 0;
167 if (!strcmp("http.ssltry", var)) {
168 curl_ssl_try = git_config_bool(var, value);
169 return 0;
171 if (!strcmp("http.minsessions", var)) {
172 min_curl_sessions = git_config_int(var, value);
173 #ifndef USE_CURL_MULTI
174 if (min_curl_sessions > 1)
175 min_curl_sessions = 1;
176 #endif
177 return 0;
179 #ifdef USE_CURL_MULTI
180 if (!strcmp("http.maxrequests", var)) {
181 max_requests = git_config_int(var, value);
182 return 0;
184 #endif
185 if (!strcmp("http.lowspeedlimit", var)) {
186 curl_low_speed_limit = (long)git_config_int(var, value);
187 return 0;
189 if (!strcmp("http.lowspeedtime", var)) {
190 curl_low_speed_time = (long)git_config_int(var, value);
191 return 0;
194 if (!strcmp("http.noepsv", var)) {
195 curl_ftp_no_epsv = git_config_bool(var, value);
196 return 0;
198 if (!strcmp("http.proxy", var))
199 return git_config_string(&curl_http_proxy, var, value);
201 if (!strcmp("http.cookiefile", var))
202 return git_config_string(&curl_cookie_file, var, value);
204 if (!strcmp("http.postbuffer", var)) {
205 http_post_buffer = git_config_int(var, value);
206 if (http_post_buffer < LARGE_PACKET_MAX)
207 http_post_buffer = LARGE_PACKET_MAX;
208 return 0;
211 if (!strcmp("http.useragent", var))
212 return git_config_string(&user_agent, var, value);
214 /* Fall back on the default ones */
215 return git_default_config(var, value, cb);
218 static void init_curl_http_auth(CURL *result)
220 if (!http_auth.username)
221 return;
223 credential_fill(&http_auth);
225 #if LIBCURL_VERSION_NUM >= 0x071301
226 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
227 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
228 #else
230 static struct strbuf up = STRBUF_INIT;
231 strbuf_reset(&up);
232 strbuf_addf(&up, "%s:%s",
233 http_auth.username, http_auth.password);
234 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
236 #endif
239 static int has_cert_password(void)
241 if (ssl_cert == NULL || ssl_cert_password_required != 1)
242 return 0;
243 if (!cert_auth.password) {
244 cert_auth.protocol = xstrdup("cert");
245 cert_auth.username = xstrdup("");
246 cert_auth.path = xstrdup(ssl_cert);
247 credential_fill(&cert_auth);
249 return 1;
252 static CURL *get_curl_handle(void)
254 CURL *result = curl_easy_init();
256 if (!curl_ssl_verify) {
257 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
258 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
259 } else {
260 /* Verify authenticity of the peer's certificate */
261 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
262 /* The name in the cert must match whom we tried to connect */
263 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
266 #if LIBCURL_VERSION_NUM >= 0x070907
267 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
268 #endif
269 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
270 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
271 #endif
273 if (http_proactive_auth)
274 init_curl_http_auth(result);
276 if (ssl_cert != NULL)
277 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
278 if (has_cert_password())
279 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
280 #if LIBCURL_VERSION_NUM >= 0x070903
281 if (ssl_key != NULL)
282 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
283 #endif
284 #if LIBCURL_VERSION_NUM >= 0x070908
285 if (ssl_capath != NULL)
286 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
287 #endif
288 if (ssl_cainfo != NULL)
289 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
291 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
292 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
293 curl_low_speed_limit);
294 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
295 curl_low_speed_time);
298 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
299 #if LIBCURL_VERSION_NUM >= 0x071301
300 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
301 #elif LIBCURL_VERSION_NUM >= 0x071101
302 curl_easy_setopt(result, CURLOPT_POST301, 1);
303 #endif
305 if (getenv("GIT_CURL_VERBOSE"))
306 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
308 curl_easy_setopt(result, CURLOPT_USERAGENT,
309 user_agent ? user_agent : git_user_agent());
311 if (curl_ftp_no_epsv)
312 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
314 #ifdef CURLOPT_USE_SSL
315 if (curl_ssl_try)
316 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
317 #endif
319 if (curl_http_proxy) {
320 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
321 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
324 return result;
327 static void set_from_env(const char **var, const char *envname)
329 const char *val = getenv(envname);
330 if (val)
331 *var = val;
334 void http_init(struct remote *remote, const char *url, int proactive_auth)
336 char *low_speed_limit;
337 char *low_speed_time;
339 http_is_verbose = 0;
341 git_config(http_options, NULL);
343 curl_global_init(CURL_GLOBAL_ALL);
345 http_proactive_auth = proactive_auth;
347 if (remote && remote->http_proxy)
348 curl_http_proxy = xstrdup(remote->http_proxy);
350 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
351 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
353 #ifdef USE_CURL_MULTI
355 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
356 if (http_max_requests != NULL)
357 max_requests = atoi(http_max_requests);
360 curlm = curl_multi_init();
361 if (curlm == NULL) {
362 fprintf(stderr, "Error creating curl multi handle.\n");
363 exit(1);
365 #endif
367 if (getenv("GIT_SSL_NO_VERIFY"))
368 curl_ssl_verify = 0;
370 set_from_env(&ssl_cert, "GIT_SSL_CERT");
371 #if LIBCURL_VERSION_NUM >= 0x070903
372 set_from_env(&ssl_key, "GIT_SSL_KEY");
373 #endif
374 #if LIBCURL_VERSION_NUM >= 0x070908
375 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
376 #endif
377 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
379 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
381 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
382 if (low_speed_limit != NULL)
383 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
384 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
385 if (low_speed_time != NULL)
386 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
388 if (curl_ssl_verify == -1)
389 curl_ssl_verify = 1;
391 curl_session_count = 0;
392 #ifdef USE_CURL_MULTI
393 if (max_requests < 1)
394 max_requests = DEFAULT_MAX_REQUESTS;
395 #endif
397 if (getenv("GIT_CURL_FTP_NO_EPSV"))
398 curl_ftp_no_epsv = 1;
400 if (url) {
401 credential_from_url(&http_auth, url);
402 if (!ssl_cert_password_required &&
403 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
404 !prefixcmp(url, "https://"))
405 ssl_cert_password_required = 1;
408 #ifndef NO_CURL_EASY_DUPHANDLE
409 curl_default = get_curl_handle();
410 #endif
413 void http_cleanup(void)
415 struct active_request_slot *slot = active_queue_head;
417 while (slot != NULL) {
418 struct active_request_slot *next = slot->next;
419 if (slot->curl != NULL) {
420 #ifdef USE_CURL_MULTI
421 curl_multi_remove_handle(curlm, slot->curl);
422 #endif
423 curl_easy_cleanup(slot->curl);
425 free(slot);
426 slot = next;
428 active_queue_head = NULL;
430 #ifndef NO_CURL_EASY_DUPHANDLE
431 curl_easy_cleanup(curl_default);
432 #endif
434 #ifdef USE_CURL_MULTI
435 curl_multi_cleanup(curlm);
436 #endif
437 curl_global_cleanup();
439 curl_slist_free_all(pragma_header);
440 pragma_header = NULL;
442 curl_slist_free_all(no_pragma_header);
443 no_pragma_header = NULL;
445 if (curl_http_proxy) {
446 free((void *)curl_http_proxy);
447 curl_http_proxy = NULL;
450 if (cert_auth.password != NULL) {
451 memset(cert_auth.password, 0, strlen(cert_auth.password));
452 free(cert_auth.password);
453 cert_auth.password = NULL;
455 ssl_cert_password_required = 0;
458 struct active_request_slot *get_active_slot(void)
460 struct active_request_slot *slot = active_queue_head;
461 struct active_request_slot *newslot;
463 #ifdef USE_CURL_MULTI
464 int num_transfers;
466 /* Wait for a slot to open up if the queue is full */
467 while (active_requests >= max_requests) {
468 curl_multi_perform(curlm, &num_transfers);
469 if (num_transfers < active_requests)
470 process_curl_messages();
472 #endif
474 while (slot != NULL && slot->in_use)
475 slot = slot->next;
477 if (slot == NULL) {
478 newslot = xmalloc(sizeof(*newslot));
479 newslot->curl = NULL;
480 newslot->in_use = 0;
481 newslot->next = NULL;
483 slot = active_queue_head;
484 if (slot == NULL) {
485 active_queue_head = newslot;
486 } else {
487 while (slot->next != NULL)
488 slot = slot->next;
489 slot->next = newslot;
491 slot = newslot;
494 if (slot->curl == NULL) {
495 #ifdef NO_CURL_EASY_DUPHANDLE
496 slot->curl = get_curl_handle();
497 #else
498 slot->curl = curl_easy_duphandle(curl_default);
499 #endif
500 curl_session_count++;
503 active_requests++;
504 slot->in_use = 1;
505 slot->results = NULL;
506 slot->finished = NULL;
507 slot->callback_data = NULL;
508 slot->callback_func = NULL;
509 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
510 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
511 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
512 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
513 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
514 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
515 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
516 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
517 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
518 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
519 if (http_auth.password)
520 init_curl_http_auth(slot->curl);
522 return slot;
525 int start_active_slot(struct active_request_slot *slot)
527 #ifdef USE_CURL_MULTI
528 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
529 int num_transfers;
531 if (curlm_result != CURLM_OK &&
532 curlm_result != CURLM_CALL_MULTI_PERFORM) {
533 active_requests--;
534 slot->in_use = 0;
535 return 0;
539 * We know there must be something to do, since we just added
540 * something.
542 curl_multi_perform(curlm, &num_transfers);
543 #endif
544 return 1;
547 #ifdef USE_CURL_MULTI
548 struct fill_chain {
549 void *data;
550 int (*fill)(void *);
551 struct fill_chain *next;
554 static struct fill_chain *fill_cfg;
556 void add_fill_function(void *data, int (*fill)(void *))
558 struct fill_chain *new = xmalloc(sizeof(*new));
559 struct fill_chain **linkp = &fill_cfg;
560 new->data = data;
561 new->fill = fill;
562 new->next = NULL;
563 while (*linkp)
564 linkp = &(*linkp)->next;
565 *linkp = new;
568 void fill_active_slots(void)
570 struct active_request_slot *slot = active_queue_head;
572 while (active_requests < max_requests) {
573 struct fill_chain *fill;
574 for (fill = fill_cfg; fill; fill = fill->next)
575 if (fill->fill(fill->data))
576 break;
578 if (!fill)
579 break;
582 while (slot != NULL) {
583 if (!slot->in_use && slot->curl != NULL
584 && curl_session_count > min_curl_sessions) {
585 curl_easy_cleanup(slot->curl);
586 slot->curl = NULL;
587 curl_session_count--;
589 slot = slot->next;
593 void step_active_slots(void)
595 int num_transfers;
596 CURLMcode curlm_result;
598 do {
599 curlm_result = curl_multi_perform(curlm, &num_transfers);
600 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
601 if (num_transfers < active_requests) {
602 process_curl_messages();
603 fill_active_slots();
606 #endif
608 void run_active_slot(struct active_request_slot *slot)
610 #ifdef USE_CURL_MULTI
611 fd_set readfds;
612 fd_set writefds;
613 fd_set excfds;
614 int max_fd;
615 struct timeval select_timeout;
616 int finished = 0;
618 slot->finished = &finished;
619 while (!finished) {
620 step_active_slots();
622 if (slot->in_use) {
623 #if LIBCURL_VERSION_NUM >= 0x070f04
624 long curl_timeout;
625 curl_multi_timeout(curlm, &curl_timeout);
626 if (curl_timeout == 0) {
627 continue;
628 } else if (curl_timeout == -1) {
629 select_timeout.tv_sec = 0;
630 select_timeout.tv_usec = 50000;
631 } else {
632 select_timeout.tv_sec = curl_timeout / 1000;
633 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
635 #else
636 select_timeout.tv_sec = 0;
637 select_timeout.tv_usec = 50000;
638 #endif
640 max_fd = -1;
641 FD_ZERO(&readfds);
642 FD_ZERO(&writefds);
643 FD_ZERO(&excfds);
644 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
647 * It can happen that curl_multi_timeout returns a pathologically
648 * long timeout when curl_multi_fdset returns no file descriptors
649 * to read. See commit message for more details.
651 if (max_fd < 0 &&
652 (select_timeout.tv_sec > 0 ||
653 select_timeout.tv_usec > 50000)) {
654 select_timeout.tv_sec = 0;
655 select_timeout.tv_usec = 50000;
658 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
661 #else
662 while (slot->in_use) {
663 slot->curl_result = curl_easy_perform(slot->curl);
664 finish_active_slot(slot);
666 #endif
669 static void closedown_active_slot(struct active_request_slot *slot)
671 active_requests--;
672 slot->in_use = 0;
675 static void release_active_slot(struct active_request_slot *slot)
677 closedown_active_slot(slot);
678 if (slot->curl && curl_session_count > min_curl_sessions) {
679 #ifdef USE_CURL_MULTI
680 curl_multi_remove_handle(curlm, slot->curl);
681 #endif
682 curl_easy_cleanup(slot->curl);
683 slot->curl = NULL;
684 curl_session_count--;
686 #ifdef USE_CURL_MULTI
687 fill_active_slots();
688 #endif
691 void finish_active_slot(struct active_request_slot *slot)
693 closedown_active_slot(slot);
694 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
696 if (slot->finished != NULL)
697 (*slot->finished) = 1;
699 /* Store slot results so they can be read after the slot is reused */
700 if (slot->results != NULL) {
701 slot->results->curl_result = slot->curl_result;
702 slot->results->http_code = slot->http_code;
705 /* Run callback if appropriate */
706 if (slot->callback_func != NULL)
707 slot->callback_func(slot->callback_data);
710 void finish_all_active_slots(void)
712 struct active_request_slot *slot = active_queue_head;
714 while (slot != NULL)
715 if (slot->in_use) {
716 run_active_slot(slot);
717 slot = active_queue_head;
718 } else {
719 slot = slot->next;
723 /* Helpers for modifying and creating URLs */
724 static inline int needs_quote(int ch)
726 if (((ch >= 'A') && (ch <= 'Z'))
727 || ((ch >= 'a') && (ch <= 'z'))
728 || ((ch >= '0') && (ch <= '9'))
729 || (ch == '/')
730 || (ch == '-')
731 || (ch == '.'))
732 return 0;
733 return 1;
736 static char *quote_ref_url(const char *base, const char *ref)
738 struct strbuf buf = STRBUF_INIT;
739 const char *cp;
740 int ch;
742 end_url_with_slash(&buf, base);
744 for (cp = ref; (ch = *cp) != 0; cp++)
745 if (needs_quote(ch))
746 strbuf_addf(&buf, "%%%02x", ch);
747 else
748 strbuf_addch(&buf, *cp);
750 return strbuf_detach(&buf, NULL);
753 void append_remote_object_url(struct strbuf *buf, const char *url,
754 const char *hex,
755 int only_two_digit_prefix)
757 end_url_with_slash(buf, url);
759 strbuf_addf(buf, "objects/%.*s/", 2, hex);
760 if (!only_two_digit_prefix)
761 strbuf_addf(buf, "%s", hex+2);
764 char *get_remote_object_url(const char *url, const char *hex,
765 int only_two_digit_prefix)
767 struct strbuf buf = STRBUF_INIT;
768 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
769 return strbuf_detach(&buf, NULL);
772 int handle_curl_result(struct slot_results *results)
775 * If we see a failing http code with CURLE_OK, we have turned off
776 * FAILONERROR (to keep the server's custom error response), and should
777 * translate the code into failure here.
779 if (results->curl_result == CURLE_OK &&
780 results->http_code >= 400) {
781 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
783 * Normally curl will already have put the "reason phrase"
784 * from the server into curl_errorstr; unfortunately without
785 * FAILONERROR it is lost, so we can give only the numeric
786 * status code.
788 snprintf(curl_errorstr, sizeof(curl_errorstr),
789 "The requested URL returned error: %ld",
790 results->http_code);
793 if (results->curl_result == CURLE_OK) {
794 credential_approve(&http_auth);
795 return HTTP_OK;
796 } else if (missing_target(results))
797 return HTTP_MISSING_TARGET;
798 else if (results->http_code == 401) {
799 if (http_auth.username && http_auth.password) {
800 credential_reject(&http_auth);
801 return HTTP_NOAUTH;
802 } else {
803 credential_fill(&http_auth);
804 return HTTP_REAUTH;
806 } else {
807 #if LIBCURL_VERSION_NUM >= 0x070c00
808 if (!curl_errorstr[0])
809 strlcpy(curl_errorstr,
810 curl_easy_strerror(results->curl_result),
811 sizeof(curl_errorstr));
812 #endif
813 return HTTP_ERROR;
817 /* http_request() targets */
818 #define HTTP_REQUEST_STRBUF 0
819 #define HTTP_REQUEST_FILE 1
821 static int http_request(const char *url, struct strbuf *type,
822 void *result, int target, int options)
824 struct active_request_slot *slot;
825 struct slot_results results;
826 struct curl_slist *headers = NULL;
827 struct strbuf buf = STRBUF_INIT;
828 int ret;
830 slot = get_active_slot();
831 slot->results = &results;
832 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
834 if (result == NULL) {
835 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
836 } else {
837 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
838 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
840 if (target == HTTP_REQUEST_FILE) {
841 long posn = ftell(result);
842 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
843 fwrite);
844 if (posn > 0) {
845 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
846 headers = curl_slist_append(headers, buf.buf);
847 strbuf_reset(&buf);
849 } else
850 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
851 fwrite_buffer);
854 strbuf_addstr(&buf, "Pragma:");
855 if (options & HTTP_NO_CACHE)
856 strbuf_addstr(&buf, " no-cache");
857 if (options & HTTP_KEEP_ERROR)
858 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
860 headers = curl_slist_append(headers, buf.buf);
862 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
863 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
864 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
866 if (start_active_slot(slot)) {
867 run_active_slot(slot);
868 ret = handle_curl_result(&results);
869 } else {
870 snprintf(curl_errorstr, sizeof(curl_errorstr),
871 "failed to start HTTP request");
872 ret = HTTP_START_FAILED;
875 if (type) {
876 char *t;
877 strbuf_reset(type);
878 curl_easy_getinfo(slot->curl, CURLINFO_CONTENT_TYPE, &t);
879 if (t)
880 strbuf_addstr(type, t);
883 curl_slist_free_all(headers);
884 strbuf_release(&buf);
886 return ret;
889 static int http_request_reauth(const char *url,
890 struct strbuf *type,
891 void *result, int target,
892 int options)
894 int ret = http_request(url, type, result, target, options);
895 if (ret != HTTP_REAUTH)
896 return ret;
899 * If we are using KEEP_ERROR, the previous request may have
900 * put cruft into our output stream; we should clear it out before
901 * making our next request. We only know how to do this for
902 * the strbuf case, but that is enough to satisfy current callers.
904 if (options & HTTP_KEEP_ERROR) {
905 switch (target) {
906 case HTTP_REQUEST_STRBUF:
907 strbuf_reset(result);
908 break;
909 default:
910 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
913 return http_request(url, type, result, target, options);
916 int http_get_strbuf(const char *url,
917 struct strbuf *type,
918 struct strbuf *result, int options)
920 return http_request_reauth(url, type, result,
921 HTTP_REQUEST_STRBUF, options);
925 * Downloads a URL and stores the result in the given file.
927 * If a previous interrupted download is detected (i.e. a previous temporary
928 * file is still around) the download is resumed.
930 static int http_get_file(const char *url, const char *filename, int options)
932 int ret;
933 struct strbuf tmpfile = STRBUF_INIT;
934 FILE *result;
936 strbuf_addf(&tmpfile, "%s.temp", filename);
937 result = fopen(tmpfile.buf, "a");
938 if (! result) {
939 error("Unable to open local file %s", tmpfile.buf);
940 ret = HTTP_ERROR;
941 goto cleanup;
944 ret = http_request_reauth(url, NULL, result, HTTP_REQUEST_FILE, options);
945 fclose(result);
947 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
948 ret = HTTP_ERROR;
949 cleanup:
950 strbuf_release(&tmpfile);
951 return ret;
954 int http_fetch_ref(const char *base, struct ref *ref)
956 char *url;
957 struct strbuf buffer = STRBUF_INIT;
958 int ret = -1;
960 url = quote_ref_url(base, ref->name);
961 if (http_get_strbuf(url, NULL, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
962 strbuf_rtrim(&buffer);
963 if (buffer.len == 40)
964 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
965 else if (!prefixcmp(buffer.buf, "ref: ")) {
966 ref->symref = xstrdup(buffer.buf + 5);
967 ret = 0;
971 strbuf_release(&buffer);
972 free(url);
973 return ret;
976 /* Helpers for fetching packs */
977 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
979 char *url, *tmp;
980 struct strbuf buf = STRBUF_INIT;
982 if (http_is_verbose)
983 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
985 end_url_with_slash(&buf, base_url);
986 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
987 url = strbuf_detach(&buf, NULL);
989 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
990 tmp = strbuf_detach(&buf, NULL);
992 if (http_get_file(url, tmp, 0) != HTTP_OK) {
993 error("Unable to get pack index %s", url);
994 free(tmp);
995 tmp = NULL;
998 free(url);
999 return tmp;
1002 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1003 unsigned char *sha1, const char *base_url)
1005 struct packed_git *new_pack;
1006 char *tmp_idx = NULL;
1007 int ret;
1009 if (has_pack_index(sha1)) {
1010 new_pack = parse_pack_index(sha1, NULL);
1011 if (!new_pack)
1012 return -1; /* parse_pack_index() already issued error message */
1013 goto add_pack;
1016 tmp_idx = fetch_pack_index(sha1, base_url);
1017 if (!tmp_idx)
1018 return -1;
1020 new_pack = parse_pack_index(sha1, tmp_idx);
1021 if (!new_pack) {
1022 unlink(tmp_idx);
1023 free(tmp_idx);
1025 return -1; /* parse_pack_index() already issued error message */
1028 ret = verify_pack_index(new_pack);
1029 if (!ret) {
1030 close_pack_index(new_pack);
1031 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1033 free(tmp_idx);
1034 if (ret)
1035 return -1;
1037 add_pack:
1038 new_pack->next = *packs_head;
1039 *packs_head = new_pack;
1040 return 0;
1043 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1045 int ret = 0, i = 0;
1046 char *url, *data;
1047 struct strbuf buf = STRBUF_INIT;
1048 unsigned char sha1[20];
1050 end_url_with_slash(&buf, base_url);
1051 strbuf_addstr(&buf, "objects/info/packs");
1052 url = strbuf_detach(&buf, NULL);
1054 ret = http_get_strbuf(url, NULL, &buf, HTTP_NO_CACHE);
1055 if (ret != HTTP_OK)
1056 goto cleanup;
1058 data = buf.buf;
1059 while (i < buf.len) {
1060 switch (data[i]) {
1061 case 'P':
1062 i++;
1063 if (i + 52 <= buf.len &&
1064 !prefixcmp(data + i, " pack-") &&
1065 !prefixcmp(data + i + 46, ".pack\n")) {
1066 get_sha1_hex(data + i + 6, sha1);
1067 fetch_and_setup_pack_index(packs_head, sha1,
1068 base_url);
1069 i += 51;
1070 break;
1072 default:
1073 while (i < buf.len && data[i] != '\n')
1074 i++;
1076 i++;
1079 cleanup:
1080 free(url);
1081 return ret;
1084 void release_http_pack_request(struct http_pack_request *preq)
1086 if (preq->packfile != NULL) {
1087 fclose(preq->packfile);
1088 preq->packfile = NULL;
1090 if (preq->range_header != NULL) {
1091 curl_slist_free_all(preq->range_header);
1092 preq->range_header = NULL;
1094 preq->slot = NULL;
1095 free(preq->url);
1098 int finish_http_pack_request(struct http_pack_request *preq)
1100 struct packed_git **lst;
1101 struct packed_git *p = preq->target;
1102 char *tmp_idx;
1103 struct child_process ip;
1104 const char *ip_argv[8];
1106 close_pack_index(p);
1108 fclose(preq->packfile);
1109 preq->packfile = NULL;
1111 lst = preq->lst;
1112 while (*lst != p)
1113 lst = &((*lst)->next);
1114 *lst = (*lst)->next;
1116 tmp_idx = xstrdup(preq->tmpfile);
1117 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1118 ".idx.temp");
1120 ip_argv[0] = "index-pack";
1121 ip_argv[1] = "-o";
1122 ip_argv[2] = tmp_idx;
1123 ip_argv[3] = preq->tmpfile;
1124 ip_argv[4] = NULL;
1126 memset(&ip, 0, sizeof(ip));
1127 ip.argv = ip_argv;
1128 ip.git_cmd = 1;
1129 ip.no_stdin = 1;
1130 ip.no_stdout = 1;
1132 if (run_command(&ip)) {
1133 unlink(preq->tmpfile);
1134 unlink(tmp_idx);
1135 free(tmp_idx);
1136 return -1;
1139 unlink(sha1_pack_index_name(p->sha1));
1141 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1142 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1143 free(tmp_idx);
1144 return -1;
1147 install_packed_git(p);
1148 free(tmp_idx);
1149 return 0;
1152 struct http_pack_request *new_http_pack_request(
1153 struct packed_git *target, const char *base_url)
1155 long prev_posn = 0;
1156 char range[RANGE_HEADER_SIZE];
1157 struct strbuf buf = STRBUF_INIT;
1158 struct http_pack_request *preq;
1160 preq = xcalloc(1, sizeof(*preq));
1161 preq->target = target;
1163 end_url_with_slash(&buf, base_url);
1164 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1165 sha1_to_hex(target->sha1));
1166 preq->url = strbuf_detach(&buf, NULL);
1168 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1169 sha1_pack_name(target->sha1));
1170 preq->packfile = fopen(preq->tmpfile, "a");
1171 if (!preq->packfile) {
1172 error("Unable to open local file %s for pack",
1173 preq->tmpfile);
1174 goto abort;
1177 preq->slot = get_active_slot();
1178 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1179 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1180 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1181 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1182 no_pragma_header);
1185 * If there is data present from a previous transfer attempt,
1186 * resume where it left off
1188 prev_posn = ftell(preq->packfile);
1189 if (prev_posn>0) {
1190 if (http_is_verbose)
1191 fprintf(stderr,
1192 "Resuming fetch of pack %s at byte %ld\n",
1193 sha1_to_hex(target->sha1), prev_posn);
1194 sprintf(range, "Range: bytes=%ld-", prev_posn);
1195 preq->range_header = curl_slist_append(NULL, range);
1196 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1197 preq->range_header);
1200 return preq;
1202 abort:
1203 free(preq->url);
1204 free(preq);
1205 return NULL;
1208 /* Helpers for fetching objects (loose) */
1209 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1210 void *data)
1212 unsigned char expn[4096];
1213 size_t size = eltsize * nmemb;
1214 int posn = 0;
1215 struct http_object_request *freq =
1216 (struct http_object_request *)data;
1217 do {
1218 ssize_t retval = xwrite(freq->localfile,
1219 (char *) ptr + posn, size - posn);
1220 if (retval < 0)
1221 return posn;
1222 posn += retval;
1223 } while (posn < size);
1225 freq->stream.avail_in = size;
1226 freq->stream.next_in = (void *)ptr;
1227 do {
1228 freq->stream.next_out = expn;
1229 freq->stream.avail_out = sizeof(expn);
1230 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1231 git_SHA1_Update(&freq->c, expn,
1232 sizeof(expn) - freq->stream.avail_out);
1233 } while (freq->stream.avail_in && freq->zret == Z_OK);
1234 return size;
1237 struct http_object_request *new_http_object_request(const char *base_url,
1238 unsigned char *sha1)
1240 char *hex = sha1_to_hex(sha1);
1241 char *filename;
1242 char prevfile[PATH_MAX];
1243 int prevlocal;
1244 char prev_buf[PREV_BUF_SIZE];
1245 ssize_t prev_read = 0;
1246 long prev_posn = 0;
1247 char range[RANGE_HEADER_SIZE];
1248 struct curl_slist *range_header = NULL;
1249 struct http_object_request *freq;
1251 freq = xcalloc(1, sizeof(*freq));
1252 hashcpy(freq->sha1, sha1);
1253 freq->localfile = -1;
1255 filename = sha1_file_name(sha1);
1256 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1257 "%s.temp", filename);
1259 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1260 unlink_or_warn(prevfile);
1261 rename(freq->tmpfile, prevfile);
1262 unlink_or_warn(freq->tmpfile);
1264 if (freq->localfile != -1)
1265 error("fd leakage in start: %d", freq->localfile);
1266 freq->localfile = open(freq->tmpfile,
1267 O_WRONLY | O_CREAT | O_EXCL, 0666);
1269 * This could have failed due to the "lazy directory creation";
1270 * try to mkdir the last path component.
1272 if (freq->localfile < 0 && errno == ENOENT) {
1273 char *dir = strrchr(freq->tmpfile, '/');
1274 if (dir) {
1275 *dir = 0;
1276 mkdir(freq->tmpfile, 0777);
1277 *dir = '/';
1279 freq->localfile = open(freq->tmpfile,
1280 O_WRONLY | O_CREAT | O_EXCL, 0666);
1283 if (freq->localfile < 0) {
1284 error("Couldn't create temporary file %s: %s",
1285 freq->tmpfile, strerror(errno));
1286 goto abort;
1289 git_inflate_init(&freq->stream);
1291 git_SHA1_Init(&freq->c);
1293 freq->url = get_remote_object_url(base_url, hex, 0);
1296 * If a previous temp file is present, process what was already
1297 * fetched.
1299 prevlocal = open(prevfile, O_RDONLY);
1300 if (prevlocal != -1) {
1301 do {
1302 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1303 if (prev_read>0) {
1304 if (fwrite_sha1_file(prev_buf,
1306 prev_read,
1307 freq) == prev_read) {
1308 prev_posn += prev_read;
1309 } else {
1310 prev_read = -1;
1313 } while (prev_read > 0);
1314 close(prevlocal);
1316 unlink_or_warn(prevfile);
1319 * Reset inflate/SHA1 if there was an error reading the previous temp
1320 * file; also rewind to the beginning of the local file.
1322 if (prev_read == -1) {
1323 memset(&freq->stream, 0, sizeof(freq->stream));
1324 git_inflate_init(&freq->stream);
1325 git_SHA1_Init(&freq->c);
1326 if (prev_posn>0) {
1327 prev_posn = 0;
1328 lseek(freq->localfile, 0, SEEK_SET);
1329 if (ftruncate(freq->localfile, 0) < 0) {
1330 error("Couldn't truncate temporary file %s: %s",
1331 freq->tmpfile, strerror(errno));
1332 goto abort;
1337 freq->slot = get_active_slot();
1339 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1340 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1341 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1342 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1343 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1346 * If we have successfully processed data from a previous fetch
1347 * attempt, only fetch the data we don't already have.
1349 if (prev_posn>0) {
1350 if (http_is_verbose)
1351 fprintf(stderr,
1352 "Resuming fetch of object %s at byte %ld\n",
1353 hex, prev_posn);
1354 sprintf(range, "Range: bytes=%ld-", prev_posn);
1355 range_header = curl_slist_append(range_header, range);
1356 curl_easy_setopt(freq->slot->curl,
1357 CURLOPT_HTTPHEADER, range_header);
1360 return freq;
1362 abort:
1363 free(freq->url);
1364 free(freq);
1365 return NULL;
1368 void process_http_object_request(struct http_object_request *freq)
1370 if (freq->slot == NULL)
1371 return;
1372 freq->curl_result = freq->slot->curl_result;
1373 freq->http_code = freq->slot->http_code;
1374 freq->slot = NULL;
1377 int finish_http_object_request(struct http_object_request *freq)
1379 struct stat st;
1381 close(freq->localfile);
1382 freq->localfile = -1;
1384 process_http_object_request(freq);
1386 if (freq->http_code == 416) {
1387 warning("requested range invalid; we may already have all the data.");
1388 } else if (freq->curl_result != CURLE_OK) {
1389 if (stat(freq->tmpfile, &st) == 0)
1390 if (st.st_size == 0)
1391 unlink_or_warn(freq->tmpfile);
1392 return -1;
1395 git_inflate_end(&freq->stream);
1396 git_SHA1_Final(freq->real_sha1, &freq->c);
1397 if (freq->zret != Z_STREAM_END) {
1398 unlink_or_warn(freq->tmpfile);
1399 return -1;
1401 if (hashcmp(freq->sha1, freq->real_sha1)) {
1402 unlink_or_warn(freq->tmpfile);
1403 return -1;
1405 freq->rename =
1406 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1408 return freq->rename;
1411 void abort_http_object_request(struct http_object_request *freq)
1413 unlink_or_warn(freq->tmpfile);
1415 release_http_object_request(freq);
1418 void release_http_object_request(struct http_object_request *freq)
1420 if (freq->localfile != -1) {
1421 close(freq->localfile);
1422 freq->localfile = -1;
1424 if (freq->url != NULL) {
1425 free(freq->url);
1426 freq->url = NULL;
1428 if (freq->slot != NULL) {
1429 freq->slot->callback_func = NULL;
1430 freq->slot->callback_data = NULL;
1431 release_active_slot(freq->slot);
1432 freq->slot = NULL;