t030[02]: work around CR/LF issue
[git/mingw/4msysgit.git] / http.c
blob3013849db0152d3e3211b8c87a9c5232ac31812b
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 "exec_cmd.h"
9 int active_requests;
10 int http_is_verbose;
11 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
13 #if LIBCURL_VERSION_NUM >= 0x070a06
14 #define LIBCURL_CAN_HANDLE_AUTH_ANY
15 #endif
17 static int min_curl_sessions = 1;
18 static int curl_session_count;
19 #ifdef USE_CURL_MULTI
20 static int max_requests = -1;
21 static CURLM *curlm;
22 #endif
23 #ifndef NO_CURL_EASY_DUPHANDLE
24 static CURL *curl_default;
25 #endif
27 #define PREV_BUF_SIZE 4096
28 #define RANGE_HEADER_SIZE 30
30 char curl_errorstr[CURL_ERROR_SIZE];
32 static int curl_ssl_verify = -1;
33 static const char *ssl_cert;
34 #if LIBCURL_VERSION_NUM >= 0x070903
35 static const char *ssl_key;
36 #endif
37 #if LIBCURL_VERSION_NUM >= 0x070908
38 static const char *ssl_capath;
39 #endif
40 static const char *ssl_cainfo;
41 static long curl_low_speed_limit = -1;
42 static long curl_low_speed_time = -1;
43 static int curl_ftp_no_epsv;
44 static const char *curl_http_proxy;
45 static const char *curl_cookie_file;
46 static struct credential cre_url = CREDENTIAL_INIT;
47 static struct credential http_auth = CREDENTIAL_INIT;
48 static struct credential proxy_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 git_config_path(const char **result,
145 const char *var, const char *value)
147 if (git_config_string(result, var, value))
148 return 1;
149 #ifdef __MINGW32__
150 if (**result == '/')
151 *result = system_path((*result) + 1);
152 #endif
153 return 0;
156 static int http_options(const char *var, const char *value, void *cb)
158 if (!strcmp("http.sslverify", var)) {
159 curl_ssl_verify = git_config_bool(var, value);
160 return 0;
162 if (!strcmp("http.sslcert", var))
163 return git_config_path(&ssl_cert, var, value);
164 #if LIBCURL_VERSION_NUM >= 0x070903
165 if (!strcmp("http.sslkey", var))
166 return git_config_path(&ssl_key, var, value);
167 #endif
168 #if LIBCURL_VERSION_NUM >= 0x070908
169 if (!strcmp("http.sslcapath", var))
170 return git_config_path(&ssl_capath, var, value);
171 #endif
172 if (!strcmp("http.sslcainfo", var))
173 return git_config_path(&ssl_cainfo, var, value);
174 if (!strcmp("http.sslcertpasswordprotected", var)) {
175 if (git_config_bool(var, value))
176 ssl_cert_password_required = 1;
177 return 0;
179 if (!strcmp("http.minsessions", var)) {
180 min_curl_sessions = git_config_int(var, value);
181 #ifndef USE_CURL_MULTI
182 if (min_curl_sessions > 1)
183 min_curl_sessions = 1;
184 #endif
185 return 0;
187 #ifdef USE_CURL_MULTI
188 if (!strcmp("http.maxrequests", var)) {
189 max_requests = git_config_int(var, value);
190 return 0;
192 #endif
193 if (!strcmp("http.lowspeedlimit", var)) {
194 curl_low_speed_limit = (long)git_config_int(var, value);
195 return 0;
197 if (!strcmp("http.lowspeedtime", var)) {
198 curl_low_speed_time = (long)git_config_int(var, value);
199 return 0;
202 if (!strcmp("http.noepsv", var)) {
203 curl_ftp_no_epsv = git_config_bool(var, value);
204 return 0;
206 if (!strcmp("http.proxy", var))
207 return git_config_string(&curl_http_proxy, var, value);
209 if (!strcmp("http.cookiefile", var))
210 return git_config_string(&curl_cookie_file, var, value);
212 if (!strcmp("http.postbuffer", var)) {
213 http_post_buffer = git_config_int(var, value);
214 if (http_post_buffer < LARGE_PACKET_MAX)
215 http_post_buffer = LARGE_PACKET_MAX;
216 return 0;
219 if (!strcmp("http.useragent", var))
220 return git_config_string(&user_agent, var, value);
222 /* Fall back on the default ones */
223 return git_default_config(var, value, cb);
226 static void init_curl_http_auth(CURL *result)
228 if (http_auth.username) {
229 struct strbuf up = STRBUF_INIT;
230 credential_fill(&http_auth);
231 strbuf_addf(&up, "%s:%s",
232 http_auth.username, http_auth.password);
233 curl_easy_setopt(result, CURLOPT_USERPWD,
234 strbuf_detach(&up, NULL));
238 static int has_cert_password(void)
240 if (ssl_cert == NULL || ssl_cert_password_required != 1)
241 return 0;
242 if (!cert_auth.password) {
243 cert_auth.protocol = xstrdup("cert");
244 cert_auth.path = xstrdup(ssl_cert);
245 credential_fill(&cert_auth);
247 return 1;
250 static void set_proxy_auth(CURL *result)
252 if (proxy_auth.username && proxy_auth.password) {
253 #if LIBCURL_VERSION_NUM >= 0x071901
254 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME, proxy_auth.username);
255 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD, proxy_auth.password);
256 #else
257 struct strbuf userpwd = STRBUF_INIT;
258 strbuf_addf(&userpwd, "%s:%s", proxy_auth.username, proxy_auth.password);
259 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, strbuf_detach(&userpwd, NULL));
260 #endif
264 static CURL *get_curl_handle(const char *url)
266 CURL *result = curl_easy_init();
268 if (!curl_ssl_verify) {
269 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
270 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
271 } else {
272 /* Verify authenticity of the peer's certificate */
273 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
274 /* The name in the cert must match whom we tried to connect */
275 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
278 #if LIBCURL_VERSION_NUM >= 0x070907
279 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
280 #endif
281 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
282 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
283 #endif
285 if (http_proactive_auth)
286 init_curl_http_auth(result);
288 if (ssl_cert != NULL)
289 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
290 if (has_cert_password())
291 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
292 #if LIBCURL_VERSION_NUM >= 0x070903
293 if (ssl_key != NULL)
294 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
295 #endif
296 #if LIBCURL_VERSION_NUM >= 0x070908
297 if (ssl_capath != NULL)
298 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
299 #endif
300 if (ssl_cainfo != NULL)
301 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
302 curl_easy_setopt(result, CURLOPT_FAILONERROR, 1);
304 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
305 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
306 curl_low_speed_limit);
307 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
308 curl_low_speed_time);
311 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
312 #if LIBCURL_VERSION_NUM >= 0x071301
313 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
314 #elif LIBCURL_VERSION_NUM >= 0x071101
315 curl_easy_setopt(result, CURLOPT_POST301, 1);
316 #endif
318 if (getenv("GIT_CURL_VERBOSE"))
319 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
321 curl_easy_setopt(result, CURLOPT_USERAGENT,
322 user_agent ? user_agent : GIT_HTTP_USER_AGENT);
324 if (curl_ftp_no_epsv)
325 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
327 if (!curl_http_proxy) {
328 const char *env_proxy, *no_proxy;
329 char *env_proxy_var;
330 int read_http_proxy;
331 struct strbuf buf = STRBUF_INIT;
332 credential_from_url(&cre_url, url);
333 strbuf_addf(&buf, "%s_proxy", cre_url.protocol);
334 env_proxy_var = strbuf_detach(&buf, NULL);
335 env_proxy = getenv(env_proxy_var);
336 if (env_proxy) {
337 read_http_proxy = 1;
338 no_proxy = getenv("no_proxy");
339 if (!no_proxy)
340 no_proxy = getenv("NO_PROXY");
341 if (no_proxy && (!strcmp("*", no_proxy) || strstr(no_proxy, cre_url.host)))
342 read_http_proxy = 0;
344 if (read_http_proxy)
345 curl_http_proxy = xstrdup(env_proxy);
347 free(env_proxy_var);
349 if (curl_http_proxy) {
350 struct strbuf proxyhost = STRBUF_INIT;
352 if (!proxy_auth.host) /* check to parse only once */
353 credential_from_url(&proxy_auth, curl_http_proxy);
355 if (http_proactive_auth && proxy_auth.username && !proxy_auth.password)
356 /* proxy string has username but no password, ask for password */
357 credential_fill(&proxy_auth);
359 strbuf_addf(&proxyhost, "%s://%s", proxy_auth.protocol, proxy_auth.host);
360 curl_easy_setopt(result, CURLOPT_PROXY, strbuf_detach(&proxyhost, NULL));
361 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
362 set_proxy_auth(result);
365 return result;
368 static void set_from_env(const char **var, const char *envname)
370 const char *val = getenv(envname);
371 if (val)
372 *var = val;
375 void http_init(struct remote *remote, const char *url, int proactive_auth)
377 char *low_speed_limit;
378 char *low_speed_time;
380 http_is_verbose = 0;
382 git_config(http_options, NULL);
384 curl_global_init(CURL_GLOBAL_ALL);
386 http_proactive_auth = proactive_auth;
388 if (remote && remote->http_proxy)
389 curl_http_proxy = xstrdup(remote->http_proxy);
391 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
392 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
394 #ifdef USE_CURL_MULTI
396 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
397 if (http_max_requests != NULL)
398 max_requests = atoi(http_max_requests);
401 curlm = curl_multi_init();
402 if (curlm == NULL) {
403 fprintf(stderr, "Error creating curl multi handle.\n");
404 exit(1);
406 #endif
408 if (getenv("GIT_SSL_NO_VERIFY"))
409 curl_ssl_verify = 0;
411 set_from_env(&ssl_cert, "GIT_SSL_CERT");
412 #if LIBCURL_VERSION_NUM >= 0x070903
413 set_from_env(&ssl_key, "GIT_SSL_KEY");
414 #endif
415 #if LIBCURL_VERSION_NUM >= 0x070908
416 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
417 #endif
418 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
420 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
422 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
423 if (low_speed_limit != NULL)
424 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
425 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
426 if (low_speed_time != NULL)
427 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
429 if (curl_ssl_verify == -1)
430 curl_ssl_verify = 1;
432 curl_session_count = 0;
433 #ifdef USE_CURL_MULTI
434 if (max_requests < 1)
435 max_requests = DEFAULT_MAX_REQUESTS;
436 #endif
438 if (getenv("GIT_CURL_FTP_NO_EPSV"))
439 curl_ftp_no_epsv = 1;
441 if (url) {
442 credential_from_url(&http_auth, url);
443 if (!ssl_cert_password_required &&
444 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
445 !prefixcmp(url, "https://"))
446 ssl_cert_password_required = 1;
449 #ifndef NO_CURL_EASY_DUPHANDLE
450 curl_default = get_curl_handle(url);
451 #endif
454 void http_cleanup(void)
456 struct active_request_slot *slot = active_queue_head;
458 while (slot != NULL) {
459 struct active_request_slot *next = slot->next;
460 if (slot->curl != NULL) {
461 #ifdef USE_CURL_MULTI
462 curl_multi_remove_handle(curlm, slot->curl);
463 #endif
464 curl_easy_cleanup(slot->curl);
466 free(slot);
467 slot = next;
469 active_queue_head = NULL;
471 #ifndef NO_CURL_EASY_DUPHANDLE
472 curl_easy_cleanup(curl_default);
473 #endif
475 #ifdef USE_CURL_MULTI
476 curl_multi_cleanup(curlm);
477 #endif
478 curl_global_cleanup();
480 curl_slist_free_all(pragma_header);
481 pragma_header = NULL;
483 curl_slist_free_all(no_pragma_header);
484 no_pragma_header = NULL;
486 if (curl_http_proxy) {
487 free((void *)curl_http_proxy);
488 curl_http_proxy = NULL;
491 if (cert_auth.password != NULL) {
492 memset(cert_auth.password, 0, strlen(cert_auth.password));
493 free(cert_auth.password);
494 cert_auth.password = NULL;
496 ssl_cert_password_required = 0;
499 struct active_request_slot *get_active_slot(const char *url)
501 struct active_request_slot *slot = active_queue_head;
502 struct active_request_slot *newslot;
504 #ifdef USE_CURL_MULTI
505 int num_transfers;
507 /* Wait for a slot to open up if the queue is full */
508 while (active_requests >= max_requests) {
509 curl_multi_perform(curlm, &num_transfers);
510 if (num_transfers < active_requests)
511 process_curl_messages();
513 #endif
515 while (slot != NULL && slot->in_use)
516 slot = slot->next;
518 if (slot == NULL) {
519 newslot = xmalloc(sizeof(*newslot));
520 newslot->curl = NULL;
521 newslot->in_use = 0;
522 newslot->next = NULL;
524 slot = active_queue_head;
525 if (slot == NULL) {
526 active_queue_head = newslot;
527 } else {
528 while (slot->next != NULL)
529 slot = slot->next;
530 slot->next = newslot;
532 slot = newslot;
535 if (slot->curl == NULL) {
536 #ifdef NO_CURL_EASY_DUPHANDLE
537 slot->curl = get_curl_handle(url);
538 #else
539 slot->curl = curl_easy_duphandle(curl_default);
540 #endif
541 curl_session_count++;
544 active_requests++;
545 slot->in_use = 1;
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 fd_set readfds;
650 fd_set writefds;
651 fd_set excfds;
652 int max_fd;
653 struct timeval select_timeout;
654 int finished = 0;
656 slot->finished = &finished;
657 while (!finished) {
658 step_active_slots();
660 if (slot->in_use) {
661 #if LIBCURL_VERSION_NUM >= 0x070f04
662 long curl_timeout;
663 curl_multi_timeout(curlm, &curl_timeout);
664 if (curl_timeout == 0) {
665 continue;
666 } else if (curl_timeout == -1) {
667 select_timeout.tv_sec = 0;
668 select_timeout.tv_usec = 50000;
669 } else {
670 select_timeout.tv_sec = curl_timeout / 1000;
671 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
673 #else
674 select_timeout.tv_sec = 0;
675 select_timeout.tv_usec = 50000;
676 #endif
678 max_fd = -1;
679 FD_ZERO(&readfds);
680 FD_ZERO(&writefds);
681 FD_ZERO(&excfds);
682 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
684 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
687 #else
688 while (slot->in_use) {
689 slot->curl_result = curl_easy_perform(slot->curl);
690 finish_active_slot(slot);
692 #endif
695 static void closedown_active_slot(struct active_request_slot *slot)
697 active_requests--;
698 slot->in_use = 0;
701 static void release_active_slot(struct active_request_slot *slot)
703 closedown_active_slot(slot);
704 if (slot->curl && curl_session_count > min_curl_sessions) {
705 #ifdef USE_CURL_MULTI
706 curl_multi_remove_handle(curlm, slot->curl);
707 #endif
708 curl_easy_cleanup(slot->curl);
709 slot->curl = NULL;
710 curl_session_count--;
712 #ifdef USE_CURL_MULTI
713 fill_active_slots();
714 #endif
717 void finish_active_slot(struct active_request_slot *slot)
719 closedown_active_slot(slot);
720 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
722 if (slot->finished != NULL)
723 (*slot->finished) = 1;
725 /* Store slot results so they can be read after the slot is reused */
726 if (slot->results != NULL) {
727 slot->results->curl_result = slot->curl_result;
728 slot->results->http_code = slot->http_code;
731 /* Run callback if appropriate */
732 if (slot->callback_func != NULL)
733 slot->callback_func(slot->callback_data);
736 void finish_all_active_slots(void)
738 struct active_request_slot *slot = active_queue_head;
740 while (slot != NULL)
741 if (slot->in_use) {
742 run_active_slot(slot);
743 slot = active_queue_head;
744 } else {
745 slot = slot->next;
749 /* Helpers for modifying and creating URLs */
750 static inline int needs_quote(int ch)
752 if (((ch >= 'A') && (ch <= 'Z'))
753 || ((ch >= 'a') && (ch <= 'z'))
754 || ((ch >= '0') && (ch <= '9'))
755 || (ch == '/')
756 || (ch == '-')
757 || (ch == '.'))
758 return 0;
759 return 1;
762 static char *quote_ref_url(const char *base, const char *ref)
764 struct strbuf buf = STRBUF_INIT;
765 const char *cp;
766 int ch;
768 end_url_with_slash(&buf, base);
770 for (cp = ref; (ch = *cp) != 0; cp++)
771 if (needs_quote(ch))
772 strbuf_addf(&buf, "%%%02x", ch);
773 else
774 strbuf_addch(&buf, *cp);
776 return strbuf_detach(&buf, NULL);
779 void append_remote_object_url(struct strbuf *buf, const char *url,
780 const char *hex,
781 int only_two_digit_prefix)
783 end_url_with_slash(buf, url);
785 strbuf_addf(buf, "objects/%.*s/", 2, hex);
786 if (!only_two_digit_prefix)
787 strbuf_addf(buf, "%s", hex+2);
790 char *get_remote_object_url(const char *url, const char *hex,
791 int only_two_digit_prefix)
793 struct strbuf buf = STRBUF_INIT;
794 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
795 return strbuf_detach(&buf, NULL);
798 /* http_request() targets */
799 #define HTTP_REQUEST_STRBUF 0
800 #define HTTP_REQUEST_FILE 1
802 static int http_request(const char *url, void *result, int target, int options)
804 struct active_request_slot *slot;
805 struct slot_results results;
806 struct curl_slist *headers = NULL;
807 struct strbuf buf = STRBUF_INIT;
808 int ret;
810 slot = get_active_slot(url);
811 slot->results = &results;
812 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
814 if (result == NULL) {
815 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
816 } else {
817 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
818 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
820 if (target == HTTP_REQUEST_FILE) {
821 long posn = ftell(result);
822 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
823 fwrite);
824 if (posn > 0) {
825 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
826 headers = curl_slist_append(headers, buf.buf);
827 strbuf_reset(&buf);
829 } else
830 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
831 fwrite_buffer);
834 strbuf_addstr(&buf, "Pragma:");
835 if (options & HTTP_NO_CACHE)
836 strbuf_addstr(&buf, " no-cache");
838 headers = curl_slist_append(headers, buf.buf);
840 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
841 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
843 if (start_active_slot(slot)) {
844 run_active_slot(slot);
845 if (results.curl_result == CURLE_OK)
846 ret = HTTP_OK;
847 else if (missing_target(&results))
848 ret = HTTP_MISSING_TARGET;
849 else if (results.http_code == 401) {
850 if (http_auth.username && http_auth.password) {
851 credential_reject(&http_auth);
852 ret = HTTP_NOAUTH;
853 } else {
854 credential_fill(&http_auth);
855 init_curl_http_auth(slot->curl);
856 ret = HTTP_AUTH_RETRY;
858 } else if (results.http_code == 407) { /* Proxy authentication failure */
859 if (proxy_auth.username && proxy_auth.password) {
860 credential_reject(&proxy_auth);
861 ret = HTTP_NOAUTH;
862 } else {
863 credential_fill(&proxy_auth);
864 set_proxy_auth(slot->curl);
865 ret = HTTP_AUTH_RETRY;
867 } else {
868 if (!curl_errorstr[0])
869 strlcpy(curl_errorstr,
870 curl_easy_strerror(results.curl_result),
871 sizeof(curl_errorstr));
872 ret = HTTP_ERROR;
874 } else {
875 error("Unable to start HTTP request for %s", url);
876 ret = HTTP_START_FAILED;
879 curl_slist_free_all(headers);
880 strbuf_release(&buf);
882 if (ret == HTTP_OK)
883 credential_approve(&http_auth);
885 return ret;
888 static int http_request_reauth(const char *url, void *result, int target,
889 int options)
891 int ret;
893 do {
894 ret = http_request(url, result, target, options);
895 } while (ret == HTTP_AUTH_RETRY);
897 return ret;
900 int http_get_strbuf(const char *url, struct strbuf *result, int options)
902 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
906 * Downloads a URL and stores the result in the given file.
908 * If a previous interrupted download is detected (i.e. a previous temporary
909 * file is still around) the download is resumed.
911 static int http_get_file(const char *url, const char *filename, int options)
913 int ret;
914 struct strbuf tmpfile = STRBUF_INIT;
915 FILE *result;
917 strbuf_addf(&tmpfile, "%s.temp", filename);
918 result = fopen(tmpfile.buf, "a");
919 if (! result) {
920 error("Unable to open local file %s", tmpfile.buf);
921 ret = HTTP_ERROR;
922 goto cleanup;
925 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
926 fclose(result);
928 if ((ret == HTTP_OK) && move_temp_to_file(tmpfile.buf, filename))
929 ret = HTTP_ERROR;
930 cleanup:
931 strbuf_release(&tmpfile);
932 return ret;
935 int http_error(const char *url, int ret)
937 /* http_request has already handled HTTP_START_FAILED. */
938 if (ret != HTTP_START_FAILED)
939 error("%s while accessing %s", curl_errorstr, url);
941 return ret;
944 int http_fetch_ref(const char *base, struct ref *ref)
946 char *url;
947 struct strbuf buffer = STRBUF_INIT;
948 int ret = -1;
950 url = quote_ref_url(base, ref->name);
951 if (http_get_strbuf(url, &buffer, HTTP_NO_CACHE) == HTTP_OK) {
952 strbuf_rtrim(&buffer);
953 if (buffer.len == 40)
954 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
955 else if (!prefixcmp(buffer.buf, "ref: ")) {
956 ref->symref = xstrdup(buffer.buf + 5);
957 ret = 0;
961 strbuf_release(&buffer);
962 free(url);
963 return ret;
966 /* Helpers for fetching packs */
967 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
969 char *url, *tmp;
970 struct strbuf buf = STRBUF_INIT;
972 if (http_is_verbose)
973 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
975 end_url_with_slash(&buf, base_url);
976 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
977 url = strbuf_detach(&buf, NULL);
979 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
980 tmp = strbuf_detach(&buf, NULL);
982 if (http_get_file(url, tmp, 0) != HTTP_OK) {
983 error("Unable to get pack index %s\n", url);
984 free(tmp);
985 tmp = NULL;
988 free(url);
989 return tmp;
992 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
993 unsigned char *sha1, const char *base_url)
995 struct packed_git *new_pack;
996 char *tmp_idx = NULL;
997 int ret;
999 if (has_pack_index(sha1)) {
1000 new_pack = parse_pack_index(sha1, NULL);
1001 if (!new_pack)
1002 return -1; /* parse_pack_index() already issued error message */
1003 goto add_pack;
1006 tmp_idx = fetch_pack_index(sha1, base_url);
1007 if (!tmp_idx)
1008 return -1;
1010 new_pack = parse_pack_index(sha1, tmp_idx);
1011 if (!new_pack) {
1012 unlink(tmp_idx);
1013 free(tmp_idx);
1015 return -1; /* parse_pack_index() already issued error message */
1018 ret = verify_pack_index(new_pack);
1019 if (!ret) {
1020 close_pack_index(new_pack);
1021 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1023 free(tmp_idx);
1024 if (ret)
1025 return -1;
1027 add_pack:
1028 new_pack->next = *packs_head;
1029 *packs_head = new_pack;
1030 return 0;
1033 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1035 int ret = 0, i = 0;
1036 char *url, *data;
1037 struct strbuf buf = STRBUF_INIT;
1038 unsigned char sha1[20];
1040 end_url_with_slash(&buf, base_url);
1041 strbuf_addstr(&buf, "objects/info/packs");
1042 url = strbuf_detach(&buf, NULL);
1044 ret = http_get_strbuf(url, &buf, HTTP_NO_CACHE);
1045 if (ret != HTTP_OK)
1046 goto cleanup;
1048 data = buf.buf;
1049 while (i < buf.len) {
1050 switch (data[i]) {
1051 case 'P':
1052 i++;
1053 if (i + 52 <= buf.len &&
1054 !prefixcmp(data + i, " pack-") &&
1055 !prefixcmp(data + i + 46, ".pack\n")) {
1056 get_sha1_hex(data + i + 6, sha1);
1057 fetch_and_setup_pack_index(packs_head, sha1,
1058 base_url);
1059 i += 51;
1060 break;
1062 default:
1063 while (i < buf.len && data[i] != '\n')
1064 i++;
1066 i++;
1069 cleanup:
1070 free(url);
1071 return ret;
1074 void release_http_pack_request(struct http_pack_request *preq)
1076 if (preq->packfile != NULL) {
1077 fclose(preq->packfile);
1078 preq->packfile = NULL;
1080 if (preq->range_header != NULL) {
1081 curl_slist_free_all(preq->range_header);
1082 preq->range_header = NULL;
1084 preq->slot = NULL;
1085 free(preq->url);
1088 int finish_http_pack_request(struct http_pack_request *preq)
1090 struct packed_git **lst;
1091 struct packed_git *p = preq->target;
1092 char *tmp_idx;
1093 struct child_process ip;
1094 const char *ip_argv[8];
1096 close_pack_index(p);
1098 fclose(preq->packfile);
1099 preq->packfile = NULL;
1101 lst = preq->lst;
1102 while (*lst != p)
1103 lst = &((*lst)->next);
1104 *lst = (*lst)->next;
1106 tmp_idx = xstrdup(preq->tmpfile);
1107 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1108 ".idx.temp");
1110 ip_argv[0] = "index-pack";
1111 ip_argv[1] = "-o";
1112 ip_argv[2] = tmp_idx;
1113 ip_argv[3] = preq->tmpfile;
1114 ip_argv[4] = NULL;
1116 memset(&ip, 0, sizeof(ip));
1117 ip.argv = ip_argv;
1118 ip.git_cmd = 1;
1119 ip.no_stdin = 1;
1120 ip.no_stdout = 1;
1122 if (run_command(&ip)) {
1123 unlink(preq->tmpfile);
1124 unlink(tmp_idx);
1125 free(tmp_idx);
1126 return -1;
1129 unlink(sha1_pack_index_name(p->sha1));
1131 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1132 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1133 free(tmp_idx);
1134 return -1;
1137 install_packed_git(p);
1138 free(tmp_idx);
1139 return 0;
1142 struct http_pack_request *new_http_pack_request(
1143 struct packed_git *target, const char *base_url)
1145 long prev_posn = 0;
1146 char range[RANGE_HEADER_SIZE];
1147 struct strbuf buf = STRBUF_INIT;
1148 struct http_pack_request *preq;
1150 preq = xcalloc(1, sizeof(*preq));
1151 preq->target = target;
1153 end_url_with_slash(&buf, base_url);
1154 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1155 sha1_to_hex(target->sha1));
1156 preq->url = strbuf_detach(&buf, NULL);
1158 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1159 sha1_pack_name(target->sha1));
1160 preq->packfile = fopen(preq->tmpfile, "a");
1161 if (!preq->packfile) {
1162 error("Unable to open local file %s for pack",
1163 preq->tmpfile);
1164 goto abort;
1167 preq->slot = get_active_slot(preq->url);
1168 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1169 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1170 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1171 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1172 no_pragma_header);
1175 * If there is data present from a previous transfer attempt,
1176 * resume where it left off
1178 prev_posn = ftell(preq->packfile);
1179 if (prev_posn>0) {
1180 if (http_is_verbose)
1181 fprintf(stderr,
1182 "Resuming fetch of pack %s at byte %ld\n",
1183 sha1_to_hex(target->sha1), prev_posn);
1184 sprintf(range, "Range: bytes=%ld-", prev_posn);
1185 preq->range_header = curl_slist_append(NULL, range);
1186 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1187 preq->range_header);
1190 return preq;
1192 abort:
1193 free(preq->url);
1194 free(preq);
1195 return NULL;
1198 /* Helpers for fetching objects (loose) */
1199 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1200 void *data)
1202 unsigned char expn[4096];
1203 size_t size = eltsize * nmemb;
1204 int posn = 0;
1205 struct http_object_request *freq =
1206 (struct http_object_request *)data;
1207 do {
1208 ssize_t retval = xwrite(freq->localfile,
1209 (char *) ptr + posn, size - posn);
1210 if (retval < 0)
1211 return posn;
1212 posn += retval;
1213 } while (posn < size);
1215 freq->stream.avail_in = size;
1216 freq->stream.next_in = (void *)ptr;
1217 do {
1218 freq->stream.next_out = expn;
1219 freq->stream.avail_out = sizeof(expn);
1220 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1221 git_SHA1_Update(&freq->c, expn,
1222 sizeof(expn) - freq->stream.avail_out);
1223 } while (freq->stream.avail_in && freq->zret == Z_OK);
1224 return size;
1227 struct http_object_request *new_http_object_request(const char *base_url,
1228 unsigned char *sha1)
1230 char *hex = sha1_to_hex(sha1);
1231 char *filename;
1232 char prevfile[PATH_MAX];
1233 int prevlocal;
1234 char prev_buf[PREV_BUF_SIZE];
1235 ssize_t prev_read = 0;
1236 long prev_posn = 0;
1237 char range[RANGE_HEADER_SIZE];
1238 struct curl_slist *range_header = NULL;
1239 struct http_object_request *freq;
1241 freq = xcalloc(1, sizeof(*freq));
1242 hashcpy(freq->sha1, sha1);
1243 freq->localfile = -1;
1245 filename = sha1_file_name(sha1);
1246 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1247 "%s.temp", filename);
1249 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1250 unlink_or_warn(prevfile);
1251 rename(freq->tmpfile, prevfile);
1252 unlink_or_warn(freq->tmpfile);
1254 if (freq->localfile != -1)
1255 error("fd leakage in start: %d", freq->localfile);
1256 freq->localfile = open(freq->tmpfile,
1257 O_WRONLY | O_CREAT | O_EXCL, 0666);
1259 * This could have failed due to the "lazy directory creation";
1260 * try to mkdir the last path component.
1262 if (freq->localfile < 0 && errno == ENOENT) {
1263 char *dir = strrchr(freq->tmpfile, '/');
1264 if (dir) {
1265 *dir = 0;
1266 mkdir(freq->tmpfile, 0777);
1267 *dir = '/';
1269 freq->localfile = open(freq->tmpfile,
1270 O_WRONLY | O_CREAT | O_EXCL, 0666);
1273 if (freq->localfile < 0) {
1274 error("Couldn't create temporary file %s: %s",
1275 freq->tmpfile, strerror(errno));
1276 goto abort;
1279 git_inflate_init(&freq->stream);
1281 git_SHA1_Init(&freq->c);
1283 freq->url = get_remote_object_url(base_url, hex, 0);
1286 * If a previous temp file is present, process what was already
1287 * fetched.
1289 prevlocal = open(prevfile, O_RDONLY);
1290 if (prevlocal != -1) {
1291 do {
1292 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1293 if (prev_read>0) {
1294 if (fwrite_sha1_file(prev_buf,
1296 prev_read,
1297 freq) == prev_read) {
1298 prev_posn += prev_read;
1299 } else {
1300 prev_read = -1;
1303 } while (prev_read > 0);
1304 close(prevlocal);
1306 unlink_or_warn(prevfile);
1309 * Reset inflate/SHA1 if there was an error reading the previous temp
1310 * file; also rewind to the beginning of the local file.
1312 if (prev_read == -1) {
1313 memset(&freq->stream, 0, sizeof(freq->stream));
1314 git_inflate_init(&freq->stream);
1315 git_SHA1_Init(&freq->c);
1316 if (prev_posn>0) {
1317 prev_posn = 0;
1318 lseek(freq->localfile, 0, SEEK_SET);
1319 if (ftruncate(freq->localfile, 0) < 0) {
1320 error("Couldn't truncate temporary file %s: %s",
1321 freq->tmpfile, strerror(errno));
1322 goto abort;
1327 freq->slot = get_active_slot(freq->url);
1329 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1330 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1331 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1332 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1333 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1336 * If we have successfully processed data from a previous fetch
1337 * attempt, only fetch the data we don't already have.
1339 if (prev_posn>0) {
1340 if (http_is_verbose)
1341 fprintf(stderr,
1342 "Resuming fetch of object %s at byte %ld\n",
1343 hex, prev_posn);
1344 sprintf(range, "Range: bytes=%ld-", prev_posn);
1345 range_header = curl_slist_append(range_header, range);
1346 curl_easy_setopt(freq->slot->curl,
1347 CURLOPT_HTTPHEADER, range_header);
1350 return freq;
1352 abort:
1353 free(freq->url);
1354 free(freq);
1355 return NULL;
1358 void process_http_object_request(struct http_object_request *freq)
1360 if (freq->slot == NULL)
1361 return;
1362 freq->curl_result = freq->slot->curl_result;
1363 freq->http_code = freq->slot->http_code;
1364 freq->slot = NULL;
1367 int finish_http_object_request(struct http_object_request *freq)
1369 struct stat st;
1371 close(freq->localfile);
1372 freq->localfile = -1;
1374 process_http_object_request(freq);
1376 if (freq->http_code == 416) {
1377 warning("requested range invalid; we may already have all the data.");
1378 } else if (freq->curl_result != CURLE_OK) {
1379 if (stat(freq->tmpfile, &st) == 0)
1380 if (st.st_size == 0)
1381 unlink_or_warn(freq->tmpfile);
1382 return -1;
1385 git_inflate_end(&freq->stream);
1386 git_SHA1_Final(freq->real_sha1, &freq->c);
1387 if (freq->zret != Z_STREAM_END) {
1388 unlink_or_warn(freq->tmpfile);
1389 return -1;
1391 if (hashcmp(freq->sha1, freq->real_sha1)) {
1392 unlink_or_warn(freq->tmpfile);
1393 return -1;
1395 freq->rename =
1396 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1398 return freq->rename;
1401 void abort_http_object_request(struct http_object_request *freq)
1403 unlink_or_warn(freq->tmpfile);
1405 release_http_object_request(freq);
1408 void release_http_object_request(struct http_object_request *freq)
1410 if (freq->localfile != -1) {
1411 close(freq->localfile);
1412 freq->localfile = -1;
1414 if (freq->url != NULL) {
1415 free(freq->url);
1416 freq->url = NULL;
1418 if (freq->slot != NULL) {
1419 freq->slot->callback_func = NULL;
1420 freq->slot->callback_data = NULL;
1421 release_active_slot(freq->slot);
1422 freq->slot = NULL;