msysGit-based Git for Windows 1.x was superseded by Git for Windows 2.x
[git/mingw/4msysgit.git] / http.c
blobec34d61c0d1816cad21dc67d0e2944983389c9e1
1 #include "http.h"
2 #include "pack.h"
3 #include "sideband.h"
4 #include "run-command.h"
5 #include "url.h"
6 #include "urlmatch.h"
7 #include "credential.h"
8 #include "version.h"
9 #include "pkt-line.h"
10 #include "exec_cmd.h"
12 int active_requests;
13 int http_is_verbose;
14 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
16 #if LIBCURL_VERSION_NUM >= 0x070a06
17 #define LIBCURL_CAN_HANDLE_AUTH_ANY
18 #endif
20 static int min_curl_sessions = 1;
21 static int curl_session_count;
22 #ifdef USE_CURL_MULTI
23 static int max_requests = -1;
24 static CURLM *curlm;
25 #endif
26 #ifndef NO_CURL_EASY_DUPHANDLE
27 static CURL *curl_default;
28 #endif
30 #define PREV_BUF_SIZE 4096
31 #define RANGE_HEADER_SIZE 30
33 char curl_errorstr[CURL_ERROR_SIZE];
35 static int curl_ssl_verify = -1;
36 static int curl_ssl_try;
37 static const char *ssl_cert;
38 #if LIBCURL_VERSION_NUM >= 0x070903
39 static const char *ssl_key;
40 #endif
41 #if LIBCURL_VERSION_NUM >= 0x070908
42 static const char *ssl_capath;
43 #endif
44 static const char *ssl_cainfo;
45 static long curl_low_speed_limit = -1;
46 static long curl_low_speed_time = -1;
47 static int curl_ftp_no_epsv;
48 static const char *curl_http_proxy;
49 static const char *curl_cookie_file;
50 static int curl_save_cookies;
51 struct credential http_auth = CREDENTIAL_INIT;
52 static int http_proactive_auth;
53 static const char *user_agent;
55 #if LIBCURL_VERSION_NUM >= 0x071700
56 /* Use CURLOPT_KEYPASSWD as is */
57 #elif LIBCURL_VERSION_NUM >= 0x070903
58 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
59 #else
60 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
61 #endif
63 static struct credential cert_auth = CREDENTIAL_INIT;
64 static int ssl_cert_password_required;
66 static struct curl_slist *pragma_header;
67 static struct curl_slist *no_pragma_header;
69 static struct active_request_slot *active_queue_head;
71 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
73 size_t size = eltsize * nmemb;
74 struct buffer *buffer = buffer_;
76 if (size > buffer->buf.len - buffer->posn)
77 size = buffer->buf.len - buffer->posn;
78 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
79 buffer->posn += size;
81 return size;
84 #ifndef NO_CURL_IOCTL
85 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
87 struct buffer *buffer = clientp;
89 switch (cmd) {
90 case CURLIOCMD_NOP:
91 return CURLIOE_OK;
93 case CURLIOCMD_RESTARTREAD:
94 buffer->posn = 0;
95 return CURLIOE_OK;
97 default:
98 return CURLIOE_UNKNOWNCMD;
101 #endif
103 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
105 size_t size = eltsize * nmemb;
106 struct strbuf *buffer = buffer_;
108 strbuf_add(buffer, ptr, size);
109 return size;
112 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
114 return eltsize * nmemb;
117 #ifdef USE_CURL_MULTI
118 static void process_curl_messages(void)
120 int num_messages;
121 struct active_request_slot *slot;
122 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
124 while (curl_message != NULL) {
125 if (curl_message->msg == CURLMSG_DONE) {
126 int curl_result = curl_message->data.result;
127 slot = active_queue_head;
128 while (slot != NULL &&
129 slot->curl != curl_message->easy_handle)
130 slot = slot->next;
131 if (slot != NULL) {
132 curl_multi_remove_handle(curlm, slot->curl);
133 slot->curl_result = curl_result;
134 finish_active_slot(slot);
135 } else {
136 fprintf(stderr, "Received DONE message for unknown request!\n");
138 } else {
139 fprintf(stderr, "Unknown CURL message received: %d\n",
140 (int)curl_message->msg);
142 curl_message = curl_multi_info_read(curlm, &num_messages);
145 #endif
147 static int git_config_path(const char **result,
148 const char *var, const char *value)
150 if (git_config_string(result, var, value))
151 return 1;
152 #ifdef __MINGW32__
153 if (**result == '/')
154 *result = system_path((*result) + 1);
155 #endif
156 return 0;
159 static int http_options(const char *var, const char *value, void *cb)
161 if (!strcmp("http.sslverify", var)) {
162 curl_ssl_verify = git_config_bool(var, value);
163 return 0;
165 if (!strcmp("http.sslcert", var))
166 return git_config_path(&ssl_cert, var, value);
167 #if LIBCURL_VERSION_NUM >= 0x070903
168 if (!strcmp("http.sslkey", var))
169 return git_config_path(&ssl_key, var, value);
170 #endif
171 #if LIBCURL_VERSION_NUM >= 0x070908
172 if (!strcmp("http.sslcapath", var))
173 return git_config_path(&ssl_capath, var, value);
174 #endif
175 if (!strcmp("http.sslcainfo", var))
176 return git_config_path(&ssl_cainfo, var, value);
177 if (!strcmp("http.sslcertpasswordprotected", var)) {
178 ssl_cert_password_required = git_config_bool(var, value);
179 return 0;
181 if (!strcmp("http.ssltry", var)) {
182 curl_ssl_try = git_config_bool(var, value);
183 return 0;
185 if (!strcmp("http.minsessions", var)) {
186 min_curl_sessions = git_config_int(var, value);
187 #ifndef USE_CURL_MULTI
188 if (min_curl_sessions > 1)
189 min_curl_sessions = 1;
190 #endif
191 return 0;
193 #ifdef USE_CURL_MULTI
194 if (!strcmp("http.maxrequests", var)) {
195 max_requests = git_config_int(var, value);
196 return 0;
198 #endif
199 if (!strcmp("http.lowspeedlimit", var)) {
200 curl_low_speed_limit = (long)git_config_int(var, value);
201 return 0;
203 if (!strcmp("http.lowspeedtime", var)) {
204 curl_low_speed_time = (long)git_config_int(var, value);
205 return 0;
208 if (!strcmp("http.noepsv", var)) {
209 curl_ftp_no_epsv = git_config_bool(var, value);
210 return 0;
212 if (!strcmp("http.proxy", var))
213 return git_config_string(&curl_http_proxy, var, value);
215 if (!strcmp("http.cookiefile", var))
216 return git_config_string(&curl_cookie_file, var, value);
217 if (!strcmp("http.savecookies", var)) {
218 curl_save_cookies = git_config_bool(var, value);
219 return 0;
222 if (!strcmp("http.postbuffer", var)) {
223 http_post_buffer = git_config_int(var, value);
224 if (http_post_buffer < LARGE_PACKET_MAX)
225 http_post_buffer = LARGE_PACKET_MAX;
226 return 0;
229 if (!strcmp("http.useragent", var))
230 return git_config_string(&user_agent, var, value);
232 /* Fall back on the default ones */
233 return git_default_config(var, value, cb);
236 static void init_curl_http_auth(CURL *result)
238 if (!http_auth.username)
239 return;
241 credential_fill(&http_auth);
243 #if LIBCURL_VERSION_NUM >= 0x071301
244 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
245 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
246 #else
248 static struct strbuf up = STRBUF_INIT;
250 * Note that we assume we only ever have a single set of
251 * credentials in a given program run, so we do not have
252 * to worry about updating this buffer, only setting its
253 * initial value.
255 if (!up.len)
256 strbuf_addf(&up, "%s:%s",
257 http_auth.username, http_auth.password);
258 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
260 #endif
263 static int has_cert_password(void)
265 if (ssl_cert == NULL || ssl_cert_password_required != 1)
266 return 0;
267 if (!cert_auth.password) {
268 cert_auth.protocol = xstrdup("cert");
269 cert_auth.username = xstrdup("");
270 cert_auth.path = xstrdup(ssl_cert);
271 credential_fill(&cert_auth);
273 return 1;
276 #if LIBCURL_VERSION_NUM >= 0x071900
277 static void set_curl_keepalive(CURL *c)
279 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
282 #elif LIBCURL_VERSION_NUM >= 0x071000
283 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
285 int ka = 1;
286 int rc;
287 socklen_t len = (socklen_t)sizeof(ka);
289 if (type != CURLSOCKTYPE_IPCXN)
290 return 0;
292 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
293 if (rc < 0)
294 warning("unable to set SO_KEEPALIVE on socket %s",
295 strerror(errno));
297 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
300 static void set_curl_keepalive(CURL *c)
302 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
305 #else
306 static void set_curl_keepalive(CURL *c)
308 /* not supported on older curl versions */
310 #endif
312 static CURL *get_curl_handle(void)
314 CURL *result = curl_easy_init();
316 if (!curl_ssl_verify) {
317 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
318 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
319 } else {
320 /* Verify authenticity of the peer's certificate */
321 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
322 /* The name in the cert must match whom we tried to connect */
323 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
326 #if LIBCURL_VERSION_NUM >= 0x070907
327 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
328 #endif
329 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
330 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
331 #endif
333 if (http_proactive_auth)
334 init_curl_http_auth(result);
336 if (ssl_cert != NULL)
337 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
338 if (has_cert_password())
339 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
340 #if LIBCURL_VERSION_NUM >= 0x070903
341 if (ssl_key != NULL)
342 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
343 #endif
344 #if LIBCURL_VERSION_NUM >= 0x070908
345 if (ssl_capath != NULL)
346 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
347 #endif
348 if (ssl_cainfo != NULL)
349 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
351 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
352 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
353 curl_low_speed_limit);
354 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
355 curl_low_speed_time);
358 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
359 #if LIBCURL_VERSION_NUM >= 0x071301
360 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
361 #elif LIBCURL_VERSION_NUM >= 0x071101
362 curl_easy_setopt(result, CURLOPT_POST301, 1);
363 #endif
365 if (getenv("GIT_CURL_VERBOSE"))
366 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
368 curl_easy_setopt(result, CURLOPT_USERAGENT,
369 user_agent ? user_agent : git_user_agent());
371 if (curl_ftp_no_epsv)
372 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
374 #ifdef CURLOPT_USE_SSL
375 if (curl_ssl_try)
376 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
377 #endif
379 if (curl_http_proxy) {
380 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
381 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
384 set_curl_keepalive(result);
386 return result;
389 static void set_from_env(const char **var, const char *envname)
391 const char *val = getenv(envname);
392 if (val)
393 *var = val;
396 void http_init(struct remote *remote, const char *url, int proactive_auth)
398 char *low_speed_limit;
399 char *low_speed_time;
400 char *normalized_url;
401 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
403 config.section = "http";
404 config.key = NULL;
405 config.collect_fn = http_options;
406 config.cascade_fn = git_default_config;
407 config.cb = NULL;
409 http_is_verbose = 0;
410 normalized_url = url_normalize(url, &config.url);
412 git_config(urlmatch_config_entry, &config);
413 free(normalized_url);
415 curl_global_init(CURL_GLOBAL_ALL);
417 http_proactive_auth = proactive_auth;
419 if (remote && remote->http_proxy)
420 curl_http_proxy = xstrdup(remote->http_proxy);
422 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
423 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
425 #ifdef USE_CURL_MULTI
427 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
428 if (http_max_requests != NULL)
429 max_requests = atoi(http_max_requests);
432 curlm = curl_multi_init();
433 if (curlm == NULL) {
434 fprintf(stderr, "Error creating curl multi handle.\n");
435 exit(1);
437 #endif
439 if (getenv("GIT_SSL_NO_VERIFY"))
440 curl_ssl_verify = 0;
442 set_from_env(&ssl_cert, "GIT_SSL_CERT");
443 #if LIBCURL_VERSION_NUM >= 0x070903
444 set_from_env(&ssl_key, "GIT_SSL_KEY");
445 #endif
446 #if LIBCURL_VERSION_NUM >= 0x070908
447 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
448 #endif
449 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
451 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
453 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
454 if (low_speed_limit != NULL)
455 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
456 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
457 if (low_speed_time != NULL)
458 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
460 if (curl_ssl_verify == -1)
461 curl_ssl_verify = 1;
463 curl_session_count = 0;
464 #ifdef USE_CURL_MULTI
465 if (max_requests < 1)
466 max_requests = DEFAULT_MAX_REQUESTS;
467 #endif
469 if (getenv("GIT_CURL_FTP_NO_EPSV"))
470 curl_ftp_no_epsv = 1;
472 if (url) {
473 credential_from_url(&http_auth, url);
474 if (!ssl_cert_password_required &&
475 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
476 starts_with(url, "https://"))
477 ssl_cert_password_required = 1;
480 #ifndef NO_CURL_EASY_DUPHANDLE
481 curl_default = get_curl_handle();
482 #endif
485 void http_cleanup(void)
487 struct active_request_slot *slot = active_queue_head;
489 while (slot != NULL) {
490 struct active_request_slot *next = slot->next;
491 if (slot->curl != NULL) {
492 #ifdef USE_CURL_MULTI
493 curl_multi_remove_handle(curlm, slot->curl);
494 #endif
495 curl_easy_cleanup(slot->curl);
497 free(slot);
498 slot = next;
500 active_queue_head = NULL;
502 #ifndef NO_CURL_EASY_DUPHANDLE
503 curl_easy_cleanup(curl_default);
504 #endif
506 #ifdef USE_CURL_MULTI
507 curl_multi_cleanup(curlm);
508 #endif
509 curl_global_cleanup();
511 curl_slist_free_all(pragma_header);
512 pragma_header = NULL;
514 curl_slist_free_all(no_pragma_header);
515 no_pragma_header = NULL;
517 if (curl_http_proxy) {
518 free((void *)curl_http_proxy);
519 curl_http_proxy = NULL;
522 if (cert_auth.password != NULL) {
523 memset(cert_auth.password, 0, strlen(cert_auth.password));
524 free(cert_auth.password);
525 cert_auth.password = NULL;
527 ssl_cert_password_required = 0;
530 struct active_request_slot *get_active_slot(void)
532 struct active_request_slot *slot = active_queue_head;
533 struct active_request_slot *newslot;
535 #ifdef USE_CURL_MULTI
536 int num_transfers;
538 /* Wait for a slot to open up if the queue is full */
539 while (active_requests >= max_requests) {
540 curl_multi_perform(curlm, &num_transfers);
541 if (num_transfers < active_requests)
542 process_curl_messages();
544 #endif
546 while (slot != NULL && slot->in_use)
547 slot = slot->next;
549 if (slot == NULL) {
550 newslot = xmalloc(sizeof(*newslot));
551 newslot->curl = NULL;
552 newslot->in_use = 0;
553 newslot->next = NULL;
555 slot = active_queue_head;
556 if (slot == NULL) {
557 active_queue_head = newslot;
558 } else {
559 while (slot->next != NULL)
560 slot = slot->next;
561 slot->next = newslot;
563 slot = newslot;
566 if (slot->curl == NULL) {
567 #ifdef NO_CURL_EASY_DUPHANDLE
568 slot->curl = get_curl_handle();
569 #else
570 slot->curl = curl_easy_duphandle(curl_default);
571 #endif
572 curl_session_count++;
575 active_requests++;
576 slot->in_use = 1;
577 slot->results = NULL;
578 slot->finished = NULL;
579 slot->callback_data = NULL;
580 slot->callback_func = NULL;
581 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
582 if (curl_save_cookies)
583 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
584 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
585 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
586 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
587 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
588 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
589 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
590 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
591 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
592 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
593 if (http_auth.password)
594 init_curl_http_auth(slot->curl);
596 return slot;
599 int start_active_slot(struct active_request_slot *slot)
601 #ifdef USE_CURL_MULTI
602 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
603 int num_transfers;
605 if (curlm_result != CURLM_OK &&
606 curlm_result != CURLM_CALL_MULTI_PERFORM) {
607 active_requests--;
608 slot->in_use = 0;
609 return 0;
613 * We know there must be something to do, since we just added
614 * something.
616 curl_multi_perform(curlm, &num_transfers);
617 #endif
618 return 1;
621 #ifdef USE_CURL_MULTI
622 struct fill_chain {
623 void *data;
624 int (*fill)(void *);
625 struct fill_chain *next;
628 static struct fill_chain *fill_cfg;
630 void add_fill_function(void *data, int (*fill)(void *))
632 struct fill_chain *new = xmalloc(sizeof(*new));
633 struct fill_chain **linkp = &fill_cfg;
634 new->data = data;
635 new->fill = fill;
636 new->next = NULL;
637 while (*linkp)
638 linkp = &(*linkp)->next;
639 *linkp = new;
642 void fill_active_slots(void)
644 struct active_request_slot *slot = active_queue_head;
646 while (active_requests < max_requests) {
647 struct fill_chain *fill;
648 for (fill = fill_cfg; fill; fill = fill->next)
649 if (fill->fill(fill->data))
650 break;
652 if (!fill)
653 break;
656 while (slot != NULL) {
657 if (!slot->in_use && slot->curl != NULL
658 && curl_session_count > min_curl_sessions) {
659 curl_easy_cleanup(slot->curl);
660 slot->curl = NULL;
661 curl_session_count--;
663 slot = slot->next;
667 void step_active_slots(void)
669 int num_transfers;
670 CURLMcode curlm_result;
672 do {
673 curlm_result = curl_multi_perform(curlm, &num_transfers);
674 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
675 if (num_transfers < active_requests) {
676 process_curl_messages();
677 fill_active_slots();
680 #endif
682 void run_active_slot(struct active_request_slot *slot)
684 #ifdef USE_CURL_MULTI
685 fd_set readfds;
686 fd_set writefds;
687 fd_set excfds;
688 int max_fd;
689 struct timeval select_timeout;
690 int finished = 0;
692 slot->finished = &finished;
693 while (!finished) {
694 step_active_slots();
696 if (slot->in_use) {
697 #if LIBCURL_VERSION_NUM >= 0x070f04
698 long curl_timeout;
699 curl_multi_timeout(curlm, &curl_timeout);
700 if (curl_timeout == 0) {
701 continue;
702 } else if (curl_timeout == -1) {
703 select_timeout.tv_sec = 0;
704 select_timeout.tv_usec = 50000;
705 } else {
706 select_timeout.tv_sec = curl_timeout / 1000;
707 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
709 #else
710 select_timeout.tv_sec = 0;
711 select_timeout.tv_usec = 50000;
712 #endif
714 max_fd = -1;
715 FD_ZERO(&readfds);
716 FD_ZERO(&writefds);
717 FD_ZERO(&excfds);
718 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
721 * It can happen that curl_multi_timeout returns a pathologically
722 * long timeout when curl_multi_fdset returns no file descriptors
723 * to read. See commit message for more details.
725 if (max_fd < 0 &&
726 (select_timeout.tv_sec > 0 ||
727 select_timeout.tv_usec > 50000)) {
728 select_timeout.tv_sec = 0;
729 select_timeout.tv_usec = 50000;
732 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
735 #else
736 while (slot->in_use) {
737 slot->curl_result = curl_easy_perform(slot->curl);
738 finish_active_slot(slot);
740 #endif
743 static void closedown_active_slot(struct active_request_slot *slot)
745 active_requests--;
746 slot->in_use = 0;
749 static void release_active_slot(struct active_request_slot *slot)
751 closedown_active_slot(slot);
752 if (slot->curl && curl_session_count > min_curl_sessions) {
753 #ifdef USE_CURL_MULTI
754 curl_multi_remove_handle(curlm, slot->curl);
755 #endif
756 curl_easy_cleanup(slot->curl);
757 slot->curl = NULL;
758 curl_session_count--;
760 #ifdef USE_CURL_MULTI
761 fill_active_slots();
762 #endif
765 void finish_active_slot(struct active_request_slot *slot)
767 closedown_active_slot(slot);
768 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
770 if (slot->finished != NULL)
771 (*slot->finished) = 1;
773 /* Store slot results so they can be read after the slot is reused */
774 if (slot->results != NULL) {
775 slot->results->curl_result = slot->curl_result;
776 slot->results->http_code = slot->http_code;
777 #if LIBCURL_VERSION_NUM >= 0x070a08
778 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
779 &slot->results->auth_avail);
780 #else
781 slot->results->auth_avail = 0;
782 #endif
785 /* Run callback if appropriate */
786 if (slot->callback_func != NULL)
787 slot->callback_func(slot->callback_data);
790 void finish_all_active_slots(void)
792 struct active_request_slot *slot = active_queue_head;
794 while (slot != NULL)
795 if (slot->in_use) {
796 run_active_slot(slot);
797 slot = active_queue_head;
798 } else {
799 slot = slot->next;
803 /* Helpers for modifying and creating URLs */
804 static inline int needs_quote(int ch)
806 if (((ch >= 'A') && (ch <= 'Z'))
807 || ((ch >= 'a') && (ch <= 'z'))
808 || ((ch >= '0') && (ch <= '9'))
809 || (ch == '/')
810 || (ch == '-')
811 || (ch == '.'))
812 return 0;
813 return 1;
816 static char *quote_ref_url(const char *base, const char *ref)
818 struct strbuf buf = STRBUF_INIT;
819 const char *cp;
820 int ch;
822 end_url_with_slash(&buf, base);
824 for (cp = ref; (ch = *cp) != 0; cp++)
825 if (needs_quote(ch))
826 strbuf_addf(&buf, "%%%02x", ch);
827 else
828 strbuf_addch(&buf, *cp);
830 return strbuf_detach(&buf, NULL);
833 void append_remote_object_url(struct strbuf *buf, const char *url,
834 const char *hex,
835 int only_two_digit_prefix)
837 end_url_with_slash(buf, url);
839 strbuf_addf(buf, "objects/%.*s/", 2, hex);
840 if (!only_two_digit_prefix)
841 strbuf_addf(buf, "%s", hex+2);
844 char *get_remote_object_url(const char *url, const char *hex,
845 int only_two_digit_prefix)
847 struct strbuf buf = STRBUF_INIT;
848 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
849 return strbuf_detach(&buf, NULL);
852 int handle_curl_result(struct slot_results *results)
855 * If we see a failing http code with CURLE_OK, we have turned off
856 * FAILONERROR (to keep the server's custom error response), and should
857 * translate the code into failure here.
859 if (results->curl_result == CURLE_OK &&
860 results->http_code >= 400) {
861 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
863 * Normally curl will already have put the "reason phrase"
864 * from the server into curl_errorstr; unfortunately without
865 * FAILONERROR it is lost, so we can give only the numeric
866 * status code.
868 snprintf(curl_errorstr, sizeof(curl_errorstr),
869 "The requested URL returned error: %ld",
870 results->http_code);
873 if (results->curl_result == CURLE_OK) {
874 credential_approve(&http_auth);
875 return HTTP_OK;
876 } else if (missing_target(results))
877 return HTTP_MISSING_TARGET;
878 else if (results->http_code == 401) {
879 if (http_auth.username && http_auth.password) {
880 credential_reject(&http_auth);
881 return HTTP_NOAUTH;
882 } else {
883 return HTTP_REAUTH;
885 } else {
886 #if LIBCURL_VERSION_NUM >= 0x070c00
887 if (!curl_errorstr[0])
888 strlcpy(curl_errorstr,
889 curl_easy_strerror(results->curl_result),
890 sizeof(curl_errorstr));
891 #endif
892 return HTTP_ERROR;
896 int run_one_slot(struct active_request_slot *slot,
897 struct slot_results *results)
899 slot->results = results;
900 if (!start_active_slot(slot)) {
901 snprintf(curl_errorstr, sizeof(curl_errorstr),
902 "failed to start HTTP request");
903 return HTTP_START_FAILED;
906 run_active_slot(slot);
907 return handle_curl_result(results);
910 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
912 char *ptr;
913 CURLcode ret;
915 strbuf_reset(buf);
916 ret = curl_easy_getinfo(curl, info, &ptr);
917 if (!ret && ptr)
918 strbuf_addstr(buf, ptr);
919 return ret;
923 * Check for and extract a content-type parameter. "raw"
924 * should be positioned at the start of the potential
925 * parameter, with any whitespace already removed.
927 * "name" is the name of the parameter. The value is appended
928 * to "out".
930 static int extract_param(const char *raw, const char *name,
931 struct strbuf *out)
933 size_t len = strlen(name);
935 if (strncasecmp(raw, name, len))
936 return -1;
937 raw += len;
939 if (*raw != '=')
940 return -1;
941 raw++;
943 while (*raw && !isspace(*raw) && *raw != ';')
944 strbuf_addch(out, *raw++);
945 return 0;
949 * Extract a normalized version of the content type, with any
950 * spaces suppressed, all letters lowercased, and no trailing ";"
951 * or parameters.
953 * Note that we will silently remove even invalid whitespace. For
954 * example, "text / plain" is specifically forbidden by RFC 2616,
955 * but "text/plain" is the only reasonable output, and this keeps
956 * our code simple.
958 * If the "charset" argument is not NULL, store the value of any
959 * charset parameter there.
961 * Example:
962 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
963 * "text / plain" -> "text/plain"
965 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
966 struct strbuf *charset)
968 const char *p;
970 strbuf_reset(type);
971 strbuf_grow(type, raw->len);
972 for (p = raw->buf; *p; p++) {
973 if (isspace(*p))
974 continue;
975 if (*p == ';') {
976 p++;
977 break;
979 strbuf_addch(type, tolower(*p));
982 if (!charset)
983 return;
985 strbuf_reset(charset);
986 while (*p) {
987 while (isspace(*p) || *p == ';')
988 p++;
989 if (!extract_param(p, "charset", charset))
990 return;
991 while (*p && !isspace(*p))
992 p++;
995 if (!charset->len && starts_with(type->buf, "text/"))
996 strbuf_addstr(charset, "ISO-8859-1");
999 /* http_request() targets */
1000 #define HTTP_REQUEST_STRBUF 0
1001 #define HTTP_REQUEST_FILE 1
1003 static int http_request(const char *url,
1004 void *result, int target,
1005 const struct http_get_options *options)
1007 struct active_request_slot *slot;
1008 struct slot_results results;
1009 struct curl_slist *headers = NULL;
1010 struct strbuf buf = STRBUF_INIT;
1011 int ret;
1013 slot = get_active_slot();
1014 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1016 if (result == NULL) {
1017 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1018 } else {
1019 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1020 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1022 if (target == HTTP_REQUEST_FILE) {
1023 long posn = ftell(result);
1024 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1025 fwrite);
1026 if (posn > 0) {
1027 strbuf_addf(&buf, "Range: bytes=%ld-", posn);
1028 headers = curl_slist_append(headers, buf.buf);
1029 strbuf_reset(&buf);
1031 } else
1032 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1033 fwrite_buffer);
1036 strbuf_addstr(&buf, "Pragma:");
1037 if (options && options->no_cache)
1038 strbuf_addstr(&buf, " no-cache");
1039 if (options && options->keep_error)
1040 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1042 headers = curl_slist_append(headers, buf.buf);
1044 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1045 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1046 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1048 ret = run_one_slot(slot, &results);
1050 if (options && options->content_type) {
1051 struct strbuf raw = STRBUF_INIT;
1052 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1053 extract_content_type(&raw, options->content_type,
1054 options->charset);
1055 strbuf_release(&raw);
1058 if (options && options->effective_url)
1059 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1060 options->effective_url);
1062 curl_slist_free_all(headers);
1063 strbuf_release(&buf);
1065 return ret;
1069 * Update the "base" url to a more appropriate value, as deduced by
1070 * redirects seen when requesting a URL starting with "url".
1072 * The "asked" parameter is a URL that we asked curl to access, and must begin
1073 * with "base".
1075 * The "got" parameter is the URL that curl reported to us as where we ended
1076 * up.
1078 * Returns 1 if we updated the base url, 0 otherwise.
1080 * Our basic strategy is to compare "base" and "asked" to find the bits
1081 * specific to our request. We then strip those bits off of "got" to yield the
1082 * new base. So for example, if our base is "http://example.com/foo.git",
1083 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1084 * with "https://other.example.com/foo.git/info/refs". We would want the
1085 * new URL to become "https://other.example.com/foo.git".
1087 * Note that this assumes a sane redirect scheme. It's entirely possible
1088 * in the example above to end up at a URL that does not even end in
1089 * "info/refs". In such a case we simply punt, as there is not much we can
1090 * do (and such a scheme is unlikely to represent a real git repository,
1091 * which means we are likely about to abort anyway).
1093 static int update_url_from_redirect(struct strbuf *base,
1094 const char *asked,
1095 const struct strbuf *got)
1097 const char *tail;
1098 size_t tail_len;
1100 if (!strcmp(asked, got->buf))
1101 return 0;
1103 if (!skip_prefix(asked, base->buf, &tail))
1104 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1105 asked, base->buf);
1107 tail_len = strlen(tail);
1109 if (got->len < tail_len ||
1110 strcmp(tail, got->buf + got->len - tail_len))
1111 return 0; /* insane redirect scheme */
1113 strbuf_reset(base);
1114 strbuf_add(base, got->buf, got->len - tail_len);
1115 return 1;
1118 static int http_request_reauth(const char *url,
1119 void *result, int target,
1120 struct http_get_options *options)
1122 int ret = http_request(url, result, target, options);
1124 if (options && options->effective_url && options->base_url) {
1125 if (update_url_from_redirect(options->base_url,
1126 url, options->effective_url)) {
1127 credential_from_url(&http_auth, options->base_url->buf);
1128 url = options->effective_url->buf;
1132 if (ret != HTTP_REAUTH)
1133 return ret;
1136 * If we are using KEEP_ERROR, the previous request may have
1137 * put cruft into our output stream; we should clear it out before
1138 * making our next request. We only know how to do this for
1139 * the strbuf case, but that is enough to satisfy current callers.
1141 if (options && options->keep_error) {
1142 switch (target) {
1143 case HTTP_REQUEST_STRBUF:
1144 strbuf_reset(result);
1145 break;
1146 default:
1147 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1151 credential_fill(&http_auth);
1153 return http_request(url, result, target, options);
1156 int http_get_strbuf(const char *url,
1157 struct strbuf *result,
1158 struct http_get_options *options)
1160 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1164 * Downloads a URL and stores the result in the given file.
1166 * If a previous interrupted download is detected (i.e. a previous temporary
1167 * file is still around) the download is resumed.
1169 static int http_get_file(const char *url, const char *filename,
1170 struct http_get_options *options)
1172 int ret;
1173 struct strbuf tmpfile = STRBUF_INIT;
1174 FILE *result;
1176 strbuf_addf(&tmpfile, "%s.temp", filename);
1177 result = fopen(tmpfile.buf, "a");
1178 if (!result) {
1179 error("Unable to open local file %s", tmpfile.buf);
1180 ret = HTTP_ERROR;
1181 goto cleanup;
1184 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1185 fclose(result);
1187 if (ret == HTTP_OK && move_temp_to_file(tmpfile.buf, filename))
1188 ret = HTTP_ERROR;
1189 cleanup:
1190 strbuf_release(&tmpfile);
1191 return ret;
1194 int http_fetch_ref(const char *base, struct ref *ref)
1196 struct http_get_options options = {0};
1197 char *url;
1198 struct strbuf buffer = STRBUF_INIT;
1199 int ret = -1;
1201 options.no_cache = 1;
1203 url = quote_ref_url(base, ref->name);
1204 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1205 strbuf_rtrim(&buffer);
1206 if (buffer.len == 40)
1207 ret = get_sha1_hex(buffer.buf, ref->old_sha1);
1208 else if (starts_with(buffer.buf, "ref: ")) {
1209 ref->symref = xstrdup(buffer.buf + 5);
1210 ret = 0;
1214 strbuf_release(&buffer);
1215 free(url);
1216 return ret;
1219 /* Helpers for fetching packs */
1220 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1222 char *url, *tmp;
1223 struct strbuf buf = STRBUF_INIT;
1225 if (http_is_verbose)
1226 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1228 end_url_with_slash(&buf, base_url);
1229 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1230 url = strbuf_detach(&buf, NULL);
1232 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1233 tmp = strbuf_detach(&buf, NULL);
1235 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1236 error("Unable to get pack index %s", url);
1237 free(tmp);
1238 tmp = NULL;
1241 free(url);
1242 return tmp;
1245 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1246 unsigned char *sha1, const char *base_url)
1248 struct packed_git *new_pack;
1249 char *tmp_idx = NULL;
1250 int ret;
1252 if (has_pack_index(sha1)) {
1253 new_pack = parse_pack_index(sha1, NULL);
1254 if (!new_pack)
1255 return -1; /* parse_pack_index() already issued error message */
1256 goto add_pack;
1259 tmp_idx = fetch_pack_index(sha1, base_url);
1260 if (!tmp_idx)
1261 return -1;
1263 new_pack = parse_pack_index(sha1, tmp_idx);
1264 if (!new_pack) {
1265 unlink(tmp_idx);
1266 free(tmp_idx);
1268 return -1; /* parse_pack_index() already issued error message */
1271 ret = verify_pack_index(new_pack);
1272 if (!ret) {
1273 close_pack_index(new_pack);
1274 ret = move_temp_to_file(tmp_idx, sha1_pack_index_name(sha1));
1276 free(tmp_idx);
1277 if (ret)
1278 return -1;
1280 add_pack:
1281 new_pack->next = *packs_head;
1282 *packs_head = new_pack;
1283 return 0;
1286 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1288 struct http_get_options options = {0};
1289 int ret = 0, i = 0;
1290 char *url, *data;
1291 struct strbuf buf = STRBUF_INIT;
1292 unsigned char sha1[20];
1294 end_url_with_slash(&buf, base_url);
1295 strbuf_addstr(&buf, "objects/info/packs");
1296 url = strbuf_detach(&buf, NULL);
1298 options.no_cache = 1;
1299 ret = http_get_strbuf(url, &buf, &options);
1300 if (ret != HTTP_OK)
1301 goto cleanup;
1303 data = buf.buf;
1304 while (i < buf.len) {
1305 switch (data[i]) {
1306 case 'P':
1307 i++;
1308 if (i + 52 <= buf.len &&
1309 starts_with(data + i, " pack-") &&
1310 starts_with(data + i + 46, ".pack\n")) {
1311 get_sha1_hex(data + i + 6, sha1);
1312 fetch_and_setup_pack_index(packs_head, sha1,
1313 base_url);
1314 i += 51;
1315 break;
1317 default:
1318 while (i < buf.len && data[i] != '\n')
1319 i++;
1321 i++;
1324 cleanup:
1325 free(url);
1326 return ret;
1329 void release_http_pack_request(struct http_pack_request *preq)
1331 if (preq->packfile != NULL) {
1332 fclose(preq->packfile);
1333 preq->packfile = NULL;
1335 if (preq->range_header != NULL) {
1336 curl_slist_free_all(preq->range_header);
1337 preq->range_header = NULL;
1339 preq->slot = NULL;
1340 free(preq->url);
1343 int finish_http_pack_request(struct http_pack_request *preq)
1345 struct packed_git **lst;
1346 struct packed_git *p = preq->target;
1347 char *tmp_idx;
1348 struct child_process ip;
1349 const char *ip_argv[8];
1351 close_pack_index(p);
1353 fclose(preq->packfile);
1354 preq->packfile = NULL;
1356 lst = preq->lst;
1357 while (*lst != p)
1358 lst = &((*lst)->next);
1359 *lst = (*lst)->next;
1361 tmp_idx = xstrdup(preq->tmpfile);
1362 strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1363 ".idx.temp");
1365 ip_argv[0] = "index-pack";
1366 ip_argv[1] = "-o";
1367 ip_argv[2] = tmp_idx;
1368 ip_argv[3] = preq->tmpfile;
1369 ip_argv[4] = NULL;
1371 memset(&ip, 0, sizeof(ip));
1372 ip.argv = ip_argv;
1373 ip.git_cmd = 1;
1374 ip.no_stdin = 1;
1375 ip.no_stdout = 1;
1377 if (run_command(&ip)) {
1378 unlink(preq->tmpfile);
1379 unlink(tmp_idx);
1380 free(tmp_idx);
1381 return -1;
1384 unlink(sha1_pack_index_name(p->sha1));
1386 if (move_temp_to_file(preq->tmpfile, sha1_pack_name(p->sha1))
1387 || move_temp_to_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1388 free(tmp_idx);
1389 return -1;
1392 install_packed_git(p);
1393 free(tmp_idx);
1394 return 0;
1397 struct http_pack_request *new_http_pack_request(
1398 struct packed_git *target, const char *base_url)
1400 long prev_posn = 0;
1401 char range[RANGE_HEADER_SIZE];
1402 struct strbuf buf = STRBUF_INIT;
1403 struct http_pack_request *preq;
1405 preq = xcalloc(1, sizeof(*preq));
1406 preq->target = target;
1408 end_url_with_slash(&buf, base_url);
1409 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1410 sha1_to_hex(target->sha1));
1411 preq->url = strbuf_detach(&buf, NULL);
1413 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1414 sha1_pack_name(target->sha1));
1415 preq->packfile = fopen(preq->tmpfile, "a");
1416 if (!preq->packfile) {
1417 error("Unable to open local file %s for pack",
1418 preq->tmpfile);
1419 goto abort;
1422 preq->slot = get_active_slot();
1423 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1424 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1425 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1426 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1427 no_pragma_header);
1430 * If there is data present from a previous transfer attempt,
1431 * resume where it left off
1433 prev_posn = ftell(preq->packfile);
1434 if (prev_posn>0) {
1435 if (http_is_verbose)
1436 fprintf(stderr,
1437 "Resuming fetch of pack %s at byte %ld\n",
1438 sha1_to_hex(target->sha1), prev_posn);
1439 sprintf(range, "Range: bytes=%ld-", prev_posn);
1440 preq->range_header = curl_slist_append(NULL, range);
1441 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1442 preq->range_header);
1445 return preq;
1447 abort:
1448 free(preq->url);
1449 free(preq);
1450 return NULL;
1453 /* Helpers for fetching objects (loose) */
1454 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1455 void *data)
1457 unsigned char expn[4096];
1458 size_t size = eltsize * nmemb;
1459 int posn = 0;
1460 struct http_object_request *freq =
1461 (struct http_object_request *)data;
1462 do {
1463 ssize_t retval = xwrite(freq->localfile,
1464 (char *) ptr + posn, size - posn);
1465 if (retval < 0)
1466 return posn;
1467 posn += retval;
1468 } while (posn < size);
1470 freq->stream.avail_in = size;
1471 freq->stream.next_in = (void *)ptr;
1472 do {
1473 freq->stream.next_out = expn;
1474 freq->stream.avail_out = sizeof(expn);
1475 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1476 git_SHA1_Update(&freq->c, expn,
1477 sizeof(expn) - freq->stream.avail_out);
1478 } while (freq->stream.avail_in && freq->zret == Z_OK);
1479 return size;
1482 struct http_object_request *new_http_object_request(const char *base_url,
1483 unsigned char *sha1)
1485 char *hex = sha1_to_hex(sha1);
1486 const char *filename;
1487 char prevfile[PATH_MAX];
1488 int prevlocal;
1489 char prev_buf[PREV_BUF_SIZE];
1490 ssize_t prev_read = 0;
1491 long prev_posn = 0;
1492 char range[RANGE_HEADER_SIZE];
1493 struct curl_slist *range_header = NULL;
1494 struct http_object_request *freq;
1496 freq = xcalloc(1, sizeof(*freq));
1497 hashcpy(freq->sha1, sha1);
1498 freq->localfile = -1;
1500 filename = sha1_file_name(sha1);
1501 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1502 "%s.temp", filename);
1504 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1505 unlink_or_warn(prevfile);
1506 rename(freq->tmpfile, prevfile);
1507 unlink_or_warn(freq->tmpfile);
1509 if (freq->localfile != -1)
1510 error("fd leakage in start: %d", freq->localfile);
1511 freq->localfile = open(freq->tmpfile,
1512 O_WRONLY | O_CREAT | O_EXCL, 0666);
1514 * This could have failed due to the "lazy directory creation";
1515 * try to mkdir the last path component.
1517 if (freq->localfile < 0 && errno == ENOENT) {
1518 char *dir = strrchr(freq->tmpfile, '/');
1519 if (dir) {
1520 *dir = 0;
1521 mkdir(freq->tmpfile, 0777);
1522 *dir = '/';
1524 freq->localfile = open(freq->tmpfile,
1525 O_WRONLY | O_CREAT | O_EXCL, 0666);
1528 if (freq->localfile < 0) {
1529 error("Couldn't create temporary file %s: %s",
1530 freq->tmpfile, strerror(errno));
1531 goto abort;
1534 git_inflate_init(&freq->stream);
1536 git_SHA1_Init(&freq->c);
1538 freq->url = get_remote_object_url(base_url, hex, 0);
1541 * If a previous temp file is present, process what was already
1542 * fetched.
1544 prevlocal = open(prevfile, O_RDONLY);
1545 if (prevlocal != -1) {
1546 do {
1547 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1548 if (prev_read>0) {
1549 if (fwrite_sha1_file(prev_buf,
1551 prev_read,
1552 freq) == prev_read) {
1553 prev_posn += prev_read;
1554 } else {
1555 prev_read = -1;
1558 } while (prev_read > 0);
1559 close(prevlocal);
1561 unlink_or_warn(prevfile);
1564 * Reset inflate/SHA1 if there was an error reading the previous temp
1565 * file; also rewind to the beginning of the local file.
1567 if (prev_read == -1) {
1568 memset(&freq->stream, 0, sizeof(freq->stream));
1569 git_inflate_init(&freq->stream);
1570 git_SHA1_Init(&freq->c);
1571 if (prev_posn>0) {
1572 prev_posn = 0;
1573 lseek(freq->localfile, 0, SEEK_SET);
1574 if (ftruncate(freq->localfile, 0) < 0) {
1575 error("Couldn't truncate temporary file %s: %s",
1576 freq->tmpfile, strerror(errno));
1577 goto abort;
1582 freq->slot = get_active_slot();
1584 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1585 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1586 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1587 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1588 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1591 * If we have successfully processed data from a previous fetch
1592 * attempt, only fetch the data we don't already have.
1594 if (prev_posn>0) {
1595 if (http_is_verbose)
1596 fprintf(stderr,
1597 "Resuming fetch of object %s at byte %ld\n",
1598 hex, prev_posn);
1599 sprintf(range, "Range: bytes=%ld-", prev_posn);
1600 range_header = curl_slist_append(range_header, range);
1601 curl_easy_setopt(freq->slot->curl,
1602 CURLOPT_HTTPHEADER, range_header);
1605 return freq;
1607 abort:
1608 free(freq->url);
1609 free(freq);
1610 return NULL;
1613 void process_http_object_request(struct http_object_request *freq)
1615 if (freq->slot == NULL)
1616 return;
1617 freq->curl_result = freq->slot->curl_result;
1618 freq->http_code = freq->slot->http_code;
1619 freq->slot = NULL;
1622 int finish_http_object_request(struct http_object_request *freq)
1624 struct stat st;
1626 close(freq->localfile);
1627 freq->localfile = -1;
1629 process_http_object_request(freq);
1631 if (freq->http_code == 416) {
1632 warning("requested range invalid; we may already have all the data.");
1633 } else if (freq->curl_result != CURLE_OK) {
1634 if (stat(freq->tmpfile, &st) == 0)
1635 if (st.st_size == 0)
1636 unlink_or_warn(freq->tmpfile);
1637 return -1;
1640 git_inflate_end(&freq->stream);
1641 git_SHA1_Final(freq->real_sha1, &freq->c);
1642 if (freq->zret != Z_STREAM_END) {
1643 unlink_or_warn(freq->tmpfile);
1644 return -1;
1646 if (hashcmp(freq->sha1, freq->real_sha1)) {
1647 unlink_or_warn(freq->tmpfile);
1648 return -1;
1650 freq->rename =
1651 move_temp_to_file(freq->tmpfile, sha1_file_name(freq->sha1));
1653 return freq->rename;
1656 void abort_http_object_request(struct http_object_request *freq)
1658 unlink_or_warn(freq->tmpfile);
1660 release_http_object_request(freq);
1663 void release_http_object_request(struct http_object_request *freq)
1665 if (freq->localfile != -1) {
1666 close(freq->localfile);
1667 freq->localfile = -1;
1669 if (freq->url != NULL) {
1670 free(freq->url);
1671 freq->url = NULL;
1673 if (freq->slot != NULL) {
1674 freq->slot->callback_func = NULL;
1675 freq->slot->callback_data = NULL;
1676 release_active_slot(freq->slot);
1677 freq->slot = NULL;