1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
16 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
18 #if LIBCURL_VERSION_NUM >= 0x070a06
19 #define LIBCURL_CAN_HANDLE_AUTH_ANY
22 static int min_curl_sessions = 1;
23 static int curl_session_count;
25 static int max_requests = -1;
28 #ifndef NO_CURL_EASY_DUPHANDLE
29 static CURL *curl_default;
32 #define PREV_BUF_SIZE 4096
34 char curl_errorstr[CURL_ERROR_SIZE];
36 static int curl_ssl_verify = -1;
37 static int curl_ssl_try;
38 static const char *ssl_cert;
39 static const char *ssl_cipherlist;
40 static const char *ssl_version;
45 { "sslv2", CURL_SSLVERSION_SSLv2 },
46 { "sslv3", CURL_SSLVERSION_SSLv3 },
47 { "tlsv1", CURL_SSLVERSION_TLSv1 },
48 #if LIBCURL_VERSION_NUM >= 0x072200
49 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
50 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
51 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
54 #if LIBCURL_VERSION_NUM >= 0x070903
55 static const char *ssl_key;
57 #if LIBCURL_VERSION_NUM >= 0x070908
58 static const char *ssl_capath;
60 #if LIBCURL_VERSION_NUM >= 0x072c00
61 static const char *ssl_pinnedkey;
63 static const char *ssl_cainfo;
64 static long curl_low_speed_limit = -1;
65 static long curl_low_speed_time = -1;
66 static int curl_ftp_no_epsv;
67 static const char *curl_http_proxy;
68 static const char *curl_cookie_file;
69 static int curl_save_cookies;
70 struct credential http_auth = CREDENTIAL_INIT;
71 static int http_proactive_auth;
72 static const char *user_agent;
74 #if LIBCURL_VERSION_NUM >= 0x071700
75 /* Use CURLOPT_KEYPASSWD as is */
76 #elif LIBCURL_VERSION_NUM >= 0x070903
77 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
79 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
82 static struct credential cert_auth = CREDENTIAL_INIT;
83 static int ssl_cert_password_required;
84 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
85 static unsigned long http_auth_methods = CURLAUTH_ANY;
88 static struct curl_slist *pragma_header;
89 static struct curl_slist *no_pragma_header;
91 static struct active_request_slot *active_queue_head;
93 static char *cached_accept_language;
95 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
97 size_t size = eltsize * nmemb;
98 struct buffer *buffer = buffer_;
100 if (size > buffer->buf.len - buffer->posn)
101 size = buffer->buf.len - buffer->posn;
102 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
103 buffer->posn += size;
108 #ifndef NO_CURL_IOCTL
109 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
111 struct buffer *buffer = clientp;
117 case CURLIOCMD_RESTARTREAD:
122 return CURLIOE_UNKNOWNCMD;
127 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
129 size_t size = eltsize * nmemb;
130 struct strbuf *buffer = buffer_;
132 strbuf_add(buffer, ptr, size);
136 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
138 return eltsize * nmemb;
141 static void closedown_active_slot(struct active_request_slot *slot)
147 static void finish_active_slot(struct active_request_slot *slot)
149 closedown_active_slot(slot);
150 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
152 if (slot->finished != NULL)
153 (*slot->finished) = 1;
155 /* Store slot results so they can be read after the slot is reused */
156 if (slot->results != NULL) {
157 slot->results->curl_result = slot->curl_result;
158 slot->results->http_code = slot->http_code;
159 #if LIBCURL_VERSION_NUM >= 0x070a08
160 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
161 &slot->results->auth_avail);
163 slot->results->auth_avail = 0;
167 /* Run callback if appropriate */
168 if (slot->callback_func != NULL)
169 slot->callback_func(slot->callback_data);
172 #ifdef USE_CURL_MULTI
173 static void process_curl_messages(void)
176 struct active_request_slot *slot;
177 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
179 while (curl_message != NULL) {
180 if (curl_message->msg == CURLMSG_DONE) {
181 int curl_result = curl_message->data.result;
182 slot = active_queue_head;
183 while (slot != NULL &&
184 slot->curl != curl_message->easy_handle)
187 curl_multi_remove_handle(curlm, slot->curl);
188 slot->curl_result = curl_result;
189 finish_active_slot(slot);
191 fprintf(stderr, "Received DONE message for unknown request!\n");
194 fprintf(stderr, "Unknown CURL message received: %d\n",
195 (int)curl_message->msg);
197 curl_message = curl_multi_info_read(curlm, &num_messages);
202 static int http_options(const char *var, const char *value, void *cb)
204 if (!strcmp("http.sslverify", var)) {
205 curl_ssl_verify = git_config_bool(var, value);
208 if (!strcmp("http.sslcipherlist", var))
209 return git_config_string(&ssl_cipherlist, var, value);
210 if (!strcmp("http.sslversion", var))
211 return git_config_string(&ssl_version, var, value);
212 if (!strcmp("http.sslcert", var))
213 return git_config_string(&ssl_cert, var, value);
214 #if LIBCURL_VERSION_NUM >= 0x070903
215 if (!strcmp("http.sslkey", var))
216 return git_config_string(&ssl_key, var, value);
218 #if LIBCURL_VERSION_NUM >= 0x070908
219 if (!strcmp("http.sslcapath", var))
220 return git_config_pathname(&ssl_capath, var, value);
222 if (!strcmp("http.sslcainfo", var))
223 return git_config_pathname(&ssl_cainfo, var, value);
224 if (!strcmp("http.sslcertpasswordprotected", var)) {
225 ssl_cert_password_required = git_config_bool(var, value);
228 if (!strcmp("http.ssltry", var)) {
229 curl_ssl_try = git_config_bool(var, value);
232 if (!strcmp("http.minsessions", var)) {
233 min_curl_sessions = git_config_int(var, value);
234 #ifndef USE_CURL_MULTI
235 if (min_curl_sessions > 1)
236 min_curl_sessions = 1;
240 #ifdef USE_CURL_MULTI
241 if (!strcmp("http.maxrequests", var)) {
242 max_requests = git_config_int(var, value);
246 if (!strcmp("http.lowspeedlimit", var)) {
247 curl_low_speed_limit = (long)git_config_int(var, value);
250 if (!strcmp("http.lowspeedtime", var)) {
251 curl_low_speed_time = (long)git_config_int(var, value);
255 if (!strcmp("http.noepsv", var)) {
256 curl_ftp_no_epsv = git_config_bool(var, value);
259 if (!strcmp("http.proxy", var))
260 return git_config_string(&curl_http_proxy, var, value);
262 if (!strcmp("http.cookiefile", var))
263 return git_config_string(&curl_cookie_file, var, value);
264 if (!strcmp("http.savecookies", var)) {
265 curl_save_cookies = git_config_bool(var, value);
269 if (!strcmp("http.postbuffer", var)) {
270 http_post_buffer = git_config_int(var, value);
271 if (http_post_buffer < LARGE_PACKET_MAX)
272 http_post_buffer = LARGE_PACKET_MAX;
276 if (!strcmp("http.useragent", var))
277 return git_config_string(&user_agent, var, value);
279 if (!strcmp("http.pinnedpubkey", var)) {
280 #if LIBCURL_VERSION_NUM >= 0x072c00
281 return git_config_pathname(&ssl_pinnedkey, var, value);
283 warning(_("Public key pinning not supported with cURL < 7.44.0"));
287 /* Fall back on the default ones */
288 return git_default_config(var, value, cb);
291 static void init_curl_http_auth(CURL *result)
293 if (!http_auth.username)
296 credential_fill(&http_auth);
298 #if LIBCURL_VERSION_NUM >= 0x071301
299 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
300 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
303 static struct strbuf up = STRBUF_INIT;
305 * Note that we assume we only ever have a single set of
306 * credentials in a given program run, so we do not have
307 * to worry about updating this buffer, only setting its
311 strbuf_addf(&up, "%s:%s",
312 http_auth.username, http_auth.password);
313 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
318 static int has_cert_password(void)
320 if (ssl_cert == NULL || ssl_cert_password_required != 1)
322 if (!cert_auth.password) {
323 cert_auth.protocol = xstrdup("cert");
324 cert_auth.username = xstrdup("");
325 cert_auth.path = xstrdup(ssl_cert);
326 credential_fill(&cert_auth);
331 #if LIBCURL_VERSION_NUM >= 0x071900
332 static void set_curl_keepalive(CURL *c)
334 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
337 #elif LIBCURL_VERSION_NUM >= 0x071000
338 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
342 socklen_t len = (socklen_t)sizeof(ka);
344 if (type != CURLSOCKTYPE_IPCXN)
347 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
349 warning("unable to set SO_KEEPALIVE on socket %s",
352 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
355 static void set_curl_keepalive(CURL *c)
357 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
361 static void set_curl_keepalive(CURL *c)
363 /* not supported on older curl versions */
367 static CURL *get_curl_handle(void)
369 CURL *result = curl_easy_init();
370 long allowed_protocols = 0;
373 die("curl_easy_init failed");
375 if (!curl_ssl_verify) {
376 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
377 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
379 /* Verify authenticity of the peer's certificate */
380 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
381 /* The name in the cert must match whom we tried to connect */
382 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
385 #if LIBCURL_VERSION_NUM >= 0x070907
386 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
388 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
389 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
392 if (http_proactive_auth)
393 init_curl_http_auth(result);
395 if (getenv("GIT_SSL_VERSION"))
396 ssl_version = getenv("GIT_SSL_VERSION");
397 if (ssl_version && *ssl_version) {
399 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
400 if (!strcmp(ssl_version, sslversions[i].name)) {
401 curl_easy_setopt(result, CURLOPT_SSLVERSION,
402 sslversions[i].ssl_version);
406 if (i == ARRAY_SIZE(sslversions))
407 warning("unsupported ssl version %s: using default",
411 if (getenv("GIT_SSL_CIPHER_LIST"))
412 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
413 if (ssl_cipherlist != NULL && *ssl_cipherlist)
414 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
417 if (ssl_cert != NULL)
418 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
419 if (has_cert_password())
420 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
421 #if LIBCURL_VERSION_NUM >= 0x070903
423 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
425 #if LIBCURL_VERSION_NUM >= 0x070908
426 if (ssl_capath != NULL)
427 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
429 #if LIBCURL_VERSION_NUM >= 0x072c00
430 if (ssl_pinnedkey != NULL)
431 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
433 if (ssl_cainfo != NULL)
434 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
436 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
437 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
438 curl_low_speed_limit);
439 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
440 curl_low_speed_time);
443 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
444 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
445 #if LIBCURL_VERSION_NUM >= 0x071301
446 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
447 #elif LIBCURL_VERSION_NUM >= 0x071101
448 curl_easy_setopt(result, CURLOPT_POST301, 1);
450 #if LIBCURL_VERSION_NUM >= 0x071304
451 if (is_transport_allowed("http"))
452 allowed_protocols |= CURLPROTO_HTTP;
453 if (is_transport_allowed("https"))
454 allowed_protocols |= CURLPROTO_HTTPS;
455 if (is_transport_allowed("ftp"))
456 allowed_protocols |= CURLPROTO_FTP;
457 if (is_transport_allowed("ftps"))
458 allowed_protocols |= CURLPROTO_FTPS;
459 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
461 if (transport_restrict_protocols())
462 warning("protocol restrictions not applied to curl redirects because\n"
463 "your curl version is too old (>= 7.19.4)");
466 if (getenv("GIT_CURL_VERBOSE"))
467 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
469 curl_easy_setopt(result, CURLOPT_USERAGENT,
470 user_agent ? user_agent : git_user_agent());
472 if (curl_ftp_no_epsv)
473 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
475 #ifdef CURLOPT_USE_SSL
477 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
480 if (curl_http_proxy) {
481 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
482 #if LIBCURL_VERSION_NUM >= 0x071800
483 if (starts_with(curl_http_proxy, "socks5"))
484 curl_easy_setopt(result,
485 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
486 else if (starts_with(curl_http_proxy, "socks4a"))
487 curl_easy_setopt(result,
488 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
489 else if (starts_with(curl_http_proxy, "socks"))
490 curl_easy_setopt(result,
491 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
494 #if LIBCURL_VERSION_NUM >= 0x070a07
495 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
498 set_curl_keepalive(result);
503 static void set_from_env(const char **var, const char *envname)
505 const char *val = getenv(envname);
510 void http_init(struct remote *remote, const char *url, int proactive_auth)
512 char *low_speed_limit;
513 char *low_speed_time;
514 char *normalized_url;
515 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
517 config.section = "http";
519 config.collect_fn = http_options;
520 config.cascade_fn = git_default_config;
524 normalized_url = url_normalize(url, &config.url);
526 git_config(urlmatch_config_entry, &config);
527 free(normalized_url);
529 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
530 die("curl_global_init failed");
532 http_proactive_auth = proactive_auth;
534 if (remote && remote->http_proxy)
535 curl_http_proxy = xstrdup(remote->http_proxy);
537 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
538 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
540 #ifdef USE_CURL_MULTI
542 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
543 if (http_max_requests != NULL)
544 max_requests = atoi(http_max_requests);
547 curlm = curl_multi_init();
549 die("curl_multi_init failed");
552 if (getenv("GIT_SSL_NO_VERIFY"))
555 set_from_env(&ssl_cert, "GIT_SSL_CERT");
556 #if LIBCURL_VERSION_NUM >= 0x070903
557 set_from_env(&ssl_key, "GIT_SSL_KEY");
559 #if LIBCURL_VERSION_NUM >= 0x070908
560 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
562 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
564 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
566 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
567 if (low_speed_limit != NULL)
568 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
569 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
570 if (low_speed_time != NULL)
571 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
573 if (curl_ssl_verify == -1)
576 curl_session_count = 0;
577 #ifdef USE_CURL_MULTI
578 if (max_requests < 1)
579 max_requests = DEFAULT_MAX_REQUESTS;
582 if (getenv("GIT_CURL_FTP_NO_EPSV"))
583 curl_ftp_no_epsv = 1;
586 credential_from_url(&http_auth, url);
587 if (!ssl_cert_password_required &&
588 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
589 starts_with(url, "https://"))
590 ssl_cert_password_required = 1;
593 #ifndef NO_CURL_EASY_DUPHANDLE
594 curl_default = get_curl_handle();
598 void http_cleanup(void)
600 struct active_request_slot *slot = active_queue_head;
602 while (slot != NULL) {
603 struct active_request_slot *next = slot->next;
604 if (slot->curl != NULL) {
605 #ifdef USE_CURL_MULTI
606 curl_multi_remove_handle(curlm, slot->curl);
608 curl_easy_cleanup(slot->curl);
613 active_queue_head = NULL;
615 #ifndef NO_CURL_EASY_DUPHANDLE
616 curl_easy_cleanup(curl_default);
619 #ifdef USE_CURL_MULTI
620 curl_multi_cleanup(curlm);
622 curl_global_cleanup();
624 curl_slist_free_all(pragma_header);
625 pragma_header = NULL;
627 curl_slist_free_all(no_pragma_header);
628 no_pragma_header = NULL;
630 if (curl_http_proxy) {
631 free((void *)curl_http_proxy);
632 curl_http_proxy = NULL;
635 if (cert_auth.password != NULL) {
636 memset(cert_auth.password, 0, strlen(cert_auth.password));
637 free(cert_auth.password);
638 cert_auth.password = NULL;
640 ssl_cert_password_required = 0;
642 free(cached_accept_language);
643 cached_accept_language = NULL;
646 struct active_request_slot *get_active_slot(void)
648 struct active_request_slot *slot = active_queue_head;
649 struct active_request_slot *newslot;
651 #ifdef USE_CURL_MULTI
654 /* Wait for a slot to open up if the queue is full */
655 while (active_requests >= max_requests) {
656 curl_multi_perform(curlm, &num_transfers);
657 if (num_transfers < active_requests)
658 process_curl_messages();
662 while (slot != NULL && slot->in_use)
666 newslot = xmalloc(sizeof(*newslot));
667 newslot->curl = NULL;
669 newslot->next = NULL;
671 slot = active_queue_head;
673 active_queue_head = newslot;
675 while (slot->next != NULL)
677 slot->next = newslot;
682 if (slot->curl == NULL) {
683 #ifdef NO_CURL_EASY_DUPHANDLE
684 slot->curl = get_curl_handle();
686 slot->curl = curl_easy_duphandle(curl_default);
688 curl_session_count++;
693 slot->results = NULL;
694 slot->finished = NULL;
695 slot->callback_data = NULL;
696 slot->callback_func = NULL;
697 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
698 if (curl_save_cookies)
699 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
700 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
701 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
702 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
703 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
704 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
705 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
706 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
707 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
708 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
709 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
710 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
711 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
713 if (http_auth.password)
714 init_curl_http_auth(slot->curl);
719 int start_active_slot(struct active_request_slot *slot)
721 #ifdef USE_CURL_MULTI
722 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
725 if (curlm_result != CURLM_OK &&
726 curlm_result != CURLM_CALL_MULTI_PERFORM) {
733 * We know there must be something to do, since we just added
736 curl_multi_perform(curlm, &num_transfers);
741 #ifdef USE_CURL_MULTI
745 struct fill_chain *next;
748 static struct fill_chain *fill_cfg;
750 void add_fill_function(void *data, int (*fill)(void *))
752 struct fill_chain *new = xmalloc(sizeof(*new));
753 struct fill_chain **linkp = &fill_cfg;
758 linkp = &(*linkp)->next;
762 void fill_active_slots(void)
764 struct active_request_slot *slot = active_queue_head;
766 while (active_requests < max_requests) {
767 struct fill_chain *fill;
768 for (fill = fill_cfg; fill; fill = fill->next)
769 if (fill->fill(fill->data))
776 while (slot != NULL) {
777 if (!slot->in_use && slot->curl != NULL
778 && curl_session_count > min_curl_sessions) {
779 curl_easy_cleanup(slot->curl);
781 curl_session_count--;
787 void step_active_slots(void)
790 CURLMcode curlm_result;
793 curlm_result = curl_multi_perform(curlm, &num_transfers);
794 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
795 if (num_transfers < active_requests) {
796 process_curl_messages();
802 void run_active_slot(struct active_request_slot *slot)
804 #ifdef USE_CURL_MULTI
809 struct timeval select_timeout;
812 slot->finished = &finished;
817 #if LIBCURL_VERSION_NUM >= 0x070f04
819 curl_multi_timeout(curlm, &curl_timeout);
820 if (curl_timeout == 0) {
822 } else if (curl_timeout == -1) {
823 select_timeout.tv_sec = 0;
824 select_timeout.tv_usec = 50000;
826 select_timeout.tv_sec = curl_timeout / 1000;
827 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
830 select_timeout.tv_sec = 0;
831 select_timeout.tv_usec = 50000;
838 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
841 * It can happen that curl_multi_timeout returns a pathologically
842 * long timeout when curl_multi_fdset returns no file descriptors
843 * to read. See commit message for more details.
846 (select_timeout.tv_sec > 0 ||
847 select_timeout.tv_usec > 50000)) {
848 select_timeout.tv_sec = 0;
849 select_timeout.tv_usec = 50000;
852 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
856 while (slot->in_use) {
857 slot->curl_result = curl_easy_perform(slot->curl);
858 finish_active_slot(slot);
863 static void release_active_slot(struct active_request_slot *slot)
865 closedown_active_slot(slot);
866 if (slot->curl && curl_session_count > min_curl_sessions) {
867 #ifdef USE_CURL_MULTI
868 curl_multi_remove_handle(curlm, slot->curl);
870 curl_easy_cleanup(slot->curl);
872 curl_session_count--;
874 #ifdef USE_CURL_MULTI
879 void finish_all_active_slots(void)
881 struct active_request_slot *slot = active_queue_head;
885 run_active_slot(slot);
886 slot = active_queue_head;
892 /* Helpers for modifying and creating URLs */
893 static inline int needs_quote(int ch)
895 if (((ch >= 'A') && (ch <= 'Z'))
896 || ((ch >= 'a') && (ch <= 'z'))
897 || ((ch >= '0') && (ch <= '9'))
905 static char *quote_ref_url(const char *base, const char *ref)
907 struct strbuf buf = STRBUF_INIT;
911 end_url_with_slash(&buf, base);
913 for (cp = ref; (ch = *cp) != 0; cp++)
915 strbuf_addf(&buf, "%%%02x", ch);
917 strbuf_addch(&buf, *cp);
919 return strbuf_detach(&buf, NULL);
922 void append_remote_object_url(struct strbuf *buf, const char *url,
924 int only_two_digit_prefix)
926 end_url_with_slash(buf, url);
928 strbuf_addf(buf, "objects/%.*s/", 2, hex);
929 if (!only_two_digit_prefix)
930 strbuf_addf(buf, "%s", hex+2);
933 char *get_remote_object_url(const char *url, const char *hex,
934 int only_two_digit_prefix)
936 struct strbuf buf = STRBUF_INIT;
937 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
938 return strbuf_detach(&buf, NULL);
941 static int handle_curl_result(struct slot_results *results)
944 * If we see a failing http code with CURLE_OK, we have turned off
945 * FAILONERROR (to keep the server's custom error response), and should
946 * translate the code into failure here.
948 if (results->curl_result == CURLE_OK &&
949 results->http_code >= 400) {
950 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
952 * Normally curl will already have put the "reason phrase"
953 * from the server into curl_errorstr; unfortunately without
954 * FAILONERROR it is lost, so we can give only the numeric
957 snprintf(curl_errorstr, sizeof(curl_errorstr),
958 "The requested URL returned error: %ld",
962 if (results->curl_result == CURLE_OK) {
963 credential_approve(&http_auth);
965 } else if (missing_target(results))
966 return HTTP_MISSING_TARGET;
967 else if (results->http_code == 401) {
968 if (http_auth.username && http_auth.password) {
969 credential_reject(&http_auth);
972 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
973 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
978 #if LIBCURL_VERSION_NUM >= 0x070c00
979 if (!curl_errorstr[0])
980 strlcpy(curl_errorstr,
981 curl_easy_strerror(results->curl_result),
982 sizeof(curl_errorstr));
988 int run_one_slot(struct active_request_slot *slot,
989 struct slot_results *results)
991 slot->results = results;
992 if (!start_active_slot(slot)) {
993 snprintf(curl_errorstr, sizeof(curl_errorstr),
994 "failed to start HTTP request");
995 return HTTP_START_FAILED;
998 run_active_slot(slot);
999 return handle_curl_result(results);
1002 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1008 ret = curl_easy_getinfo(curl, info, &ptr);
1010 strbuf_addstr(buf, ptr);
1015 * Check for and extract a content-type parameter. "raw"
1016 * should be positioned at the start of the potential
1017 * parameter, with any whitespace already removed.
1019 * "name" is the name of the parameter. The value is appended
1022 static int extract_param(const char *raw, const char *name,
1025 size_t len = strlen(name);
1027 if (strncasecmp(raw, name, len))
1035 while (*raw && !isspace(*raw) && *raw != ';')
1036 strbuf_addch(out, *raw++);
1041 * Extract a normalized version of the content type, with any
1042 * spaces suppressed, all letters lowercased, and no trailing ";"
1045 * Note that we will silently remove even invalid whitespace. For
1046 * example, "text / plain" is specifically forbidden by RFC 2616,
1047 * but "text/plain" is the only reasonable output, and this keeps
1050 * If the "charset" argument is not NULL, store the value of any
1051 * charset parameter there.
1054 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1055 * "text / plain" -> "text/plain"
1057 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1058 struct strbuf *charset)
1063 strbuf_grow(type, raw->len);
1064 for (p = raw->buf; *p; p++) {
1071 strbuf_addch(type, tolower(*p));
1077 strbuf_reset(charset);
1079 while (isspace(*p) || *p == ';')
1081 if (!extract_param(p, "charset", charset))
1083 while (*p && !isspace(*p))
1087 if (!charset->len && starts_with(type->buf, "text/"))
1088 strbuf_addstr(charset, "ISO-8859-1");
1091 static void write_accept_language(struct strbuf *buf)
1094 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1095 * that, q-value will be smaller than 0.001, the minimum q-value the
1096 * HTTP specification allows. See
1097 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1099 const int MAX_DECIMAL_PLACES = 3;
1100 const int MAX_LANGUAGE_TAGS = 1000;
1101 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1102 char **language_tags = NULL;
1104 const char *s = get_preferred_languages();
1106 struct strbuf tag = STRBUF_INIT;
1108 /* Don't add Accept-Language header if no language is preferred. */
1113 * Split the colon-separated string of preferred languages into
1114 * language_tags array.
1117 /* collect language tag */
1118 for (; *s && (isalnum(*s) || *s == '_'); s++)
1119 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1121 /* skip .codeset, @modifier and any other unnecessary parts */
1122 while (*s && *s != ':')
1127 REALLOC_ARRAY(language_tags, num_langs);
1128 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1129 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1134 /* write Accept-Language header into buf */
1136 int last_buf_len = 0;
1142 REALLOC_ARRAY(language_tags, num_langs + 1);
1143 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1145 /* compute decimal_places */
1146 for (max_q = 1, decimal_places = 0;
1147 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1148 decimal_places++, max_q *= 10)
1151 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1153 strbuf_addstr(buf, "Accept-Language: ");
1155 for (i = 0; i < num_langs; i++) {
1157 strbuf_addstr(buf, ", ");
1159 strbuf_addstr(buf, language_tags[i]);
1162 strbuf_addf(buf, q_format, max_q - i);
1164 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1165 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1169 last_buf_len = buf->len;
1173 /* free language tags -- last one is a static '*' */
1174 for (i = 0; i < num_langs - 1; i++)
1175 free(language_tags[i]);
1176 free(language_tags);
1180 * Get an Accept-Language header which indicates user's preferred languages.
1184 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1185 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1186 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1187 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1188 * LANGUAGE= LANG=C -> ""
1190 static const char *get_accept_language(void)
1192 if (!cached_accept_language) {
1193 struct strbuf buf = STRBUF_INIT;
1194 write_accept_language(&buf);
1196 cached_accept_language = strbuf_detach(&buf, NULL);
1199 return cached_accept_language;
1202 static void http_opt_request_remainder(CURL *curl, off_t pos)
1205 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1206 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1209 /* http_request() targets */
1210 #define HTTP_REQUEST_STRBUF 0
1211 #define HTTP_REQUEST_FILE 1
1213 static int http_request(const char *url,
1214 void *result, int target,
1215 const struct http_get_options *options)
1217 struct active_request_slot *slot;
1218 struct slot_results results;
1219 struct curl_slist *headers = NULL;
1220 struct strbuf buf = STRBUF_INIT;
1221 const char *accept_language;
1224 slot = get_active_slot();
1225 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1227 if (result == NULL) {
1228 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1230 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1231 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1233 if (target == HTTP_REQUEST_FILE) {
1234 off_t posn = ftello(result);
1235 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1238 http_opt_request_remainder(slot->curl, posn);
1240 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1244 accept_language = get_accept_language();
1246 if (accept_language)
1247 headers = curl_slist_append(headers, accept_language);
1249 strbuf_addstr(&buf, "Pragma:");
1250 if (options && options->no_cache)
1251 strbuf_addstr(&buf, " no-cache");
1252 if (options && options->keep_error)
1253 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1255 headers = curl_slist_append(headers, buf.buf);
1257 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1258 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1259 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1261 ret = run_one_slot(slot, &results);
1263 if (options && options->content_type) {
1264 struct strbuf raw = STRBUF_INIT;
1265 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1266 extract_content_type(&raw, options->content_type,
1268 strbuf_release(&raw);
1271 if (options && options->effective_url)
1272 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1273 options->effective_url);
1275 curl_slist_free_all(headers);
1276 strbuf_release(&buf);
1282 * Update the "base" url to a more appropriate value, as deduced by
1283 * redirects seen when requesting a URL starting with "url".
1285 * The "asked" parameter is a URL that we asked curl to access, and must begin
1288 * The "got" parameter is the URL that curl reported to us as where we ended
1291 * Returns 1 if we updated the base url, 0 otherwise.
1293 * Our basic strategy is to compare "base" and "asked" to find the bits
1294 * specific to our request. We then strip those bits off of "got" to yield the
1295 * new base. So for example, if our base is "http://example.com/foo.git",
1296 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1297 * with "https://other.example.com/foo.git/info/refs". We would want the
1298 * new URL to become "https://other.example.com/foo.git".
1300 * Note that this assumes a sane redirect scheme. It's entirely possible
1301 * in the example above to end up at a URL that does not even end in
1302 * "info/refs". In such a case we simply punt, as there is not much we can
1303 * do (and such a scheme is unlikely to represent a real git repository,
1304 * which means we are likely about to abort anyway).
1306 static int update_url_from_redirect(struct strbuf *base,
1308 const struct strbuf *got)
1313 if (!strcmp(asked, got->buf))
1316 if (!skip_prefix(asked, base->buf, &tail))
1317 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1320 tail_len = strlen(tail);
1322 if (got->len < tail_len ||
1323 strcmp(tail, got->buf + got->len - tail_len))
1324 return 0; /* insane redirect scheme */
1327 strbuf_add(base, got->buf, got->len - tail_len);
1331 static int http_request_reauth(const char *url,
1332 void *result, int target,
1333 struct http_get_options *options)
1335 int ret = http_request(url, result, target, options);
1337 if (options && options->effective_url && options->base_url) {
1338 if (update_url_from_redirect(options->base_url,
1339 url, options->effective_url)) {
1340 credential_from_url(&http_auth, options->base_url->buf);
1341 url = options->effective_url->buf;
1345 if (ret != HTTP_REAUTH)
1349 * If we are using KEEP_ERROR, the previous request may have
1350 * put cruft into our output stream; we should clear it out before
1351 * making our next request. We only know how to do this for
1352 * the strbuf case, but that is enough to satisfy current callers.
1354 if (options && options->keep_error) {
1356 case HTTP_REQUEST_STRBUF:
1357 strbuf_reset(result);
1360 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1364 credential_fill(&http_auth);
1366 return http_request(url, result, target, options);
1369 int http_get_strbuf(const char *url,
1370 struct strbuf *result,
1371 struct http_get_options *options)
1373 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1377 * Downloads a URL and stores the result in the given file.
1379 * If a previous interrupted download is detected (i.e. a previous temporary
1380 * file is still around) the download is resumed.
1382 static int http_get_file(const char *url, const char *filename,
1383 struct http_get_options *options)
1386 struct strbuf tmpfile = STRBUF_INIT;
1389 strbuf_addf(&tmpfile, "%s.temp", filename);
1390 result = fopen(tmpfile.buf, "a");
1392 error("Unable to open local file %s", tmpfile.buf);
1397 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1400 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1403 strbuf_release(&tmpfile);
1407 int http_fetch_ref(const char *base, struct ref *ref)
1409 struct http_get_options options = {0};
1411 struct strbuf buffer = STRBUF_INIT;
1414 options.no_cache = 1;
1416 url = quote_ref_url(base, ref->name);
1417 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1418 strbuf_rtrim(&buffer);
1419 if (buffer.len == 40)
1420 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1421 else if (starts_with(buffer.buf, "ref: ")) {
1422 ref->symref = xstrdup(buffer.buf + 5);
1427 strbuf_release(&buffer);
1432 /* Helpers for fetching packs */
1433 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1436 struct strbuf buf = STRBUF_INIT;
1438 if (http_is_verbose)
1439 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1441 end_url_with_slash(&buf, base_url);
1442 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1443 url = strbuf_detach(&buf, NULL);
1445 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1446 tmp = strbuf_detach(&buf, NULL);
1448 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1449 error("Unable to get pack index %s", url);
1458 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1459 unsigned char *sha1, const char *base_url)
1461 struct packed_git *new_pack;
1462 char *tmp_idx = NULL;
1465 if (has_pack_index(sha1)) {
1466 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1468 return -1; /* parse_pack_index() already issued error message */
1472 tmp_idx = fetch_pack_index(sha1, base_url);
1476 new_pack = parse_pack_index(sha1, tmp_idx);
1481 return -1; /* parse_pack_index() already issued error message */
1484 ret = verify_pack_index(new_pack);
1486 close_pack_index(new_pack);
1487 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1494 new_pack->next = *packs_head;
1495 *packs_head = new_pack;
1499 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1501 struct http_get_options options = {0};
1504 struct strbuf buf = STRBUF_INIT;
1505 unsigned char sha1[20];
1507 end_url_with_slash(&buf, base_url);
1508 strbuf_addstr(&buf, "objects/info/packs");
1509 url = strbuf_detach(&buf, NULL);
1511 options.no_cache = 1;
1512 ret = http_get_strbuf(url, &buf, &options);
1517 while (i < buf.len) {
1521 if (i + 52 <= buf.len &&
1522 starts_with(data + i, " pack-") &&
1523 starts_with(data + i + 46, ".pack\n")) {
1524 get_sha1_hex(data + i + 6, sha1);
1525 fetch_and_setup_pack_index(packs_head, sha1,
1531 while (i < buf.len && data[i] != '\n')
1542 void release_http_pack_request(struct http_pack_request *preq)
1544 if (preq->packfile != NULL) {
1545 fclose(preq->packfile);
1546 preq->packfile = NULL;
1553 int finish_http_pack_request(struct http_pack_request *preq)
1555 struct packed_git **lst;
1556 struct packed_git *p = preq->target;
1559 struct child_process ip = CHILD_PROCESS_INIT;
1560 const char *ip_argv[8];
1562 close_pack_index(p);
1564 fclose(preq->packfile);
1565 preq->packfile = NULL;
1569 lst = &((*lst)->next);
1570 *lst = (*lst)->next;
1572 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1573 die("BUG: pack tmpfile does not end in .pack.temp?");
1574 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1576 ip_argv[0] = "index-pack";
1578 ip_argv[2] = tmp_idx;
1579 ip_argv[3] = preq->tmpfile;
1587 if (run_command(&ip)) {
1588 unlink(preq->tmpfile);
1594 unlink(sha1_pack_index_name(p->sha1));
1596 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1597 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1602 install_packed_git(p);
1607 struct http_pack_request *new_http_pack_request(
1608 struct packed_git *target, const char *base_url)
1610 off_t prev_posn = 0;
1611 struct strbuf buf = STRBUF_INIT;
1612 struct http_pack_request *preq;
1614 preq = xcalloc(1, sizeof(*preq));
1615 preq->target = target;
1617 end_url_with_slash(&buf, base_url);
1618 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1619 sha1_to_hex(target->sha1));
1620 preq->url = strbuf_detach(&buf, NULL);
1622 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1623 sha1_pack_name(target->sha1));
1624 preq->packfile = fopen(preq->tmpfile, "a");
1625 if (!preq->packfile) {
1626 error("Unable to open local file %s for pack",
1631 preq->slot = get_active_slot();
1632 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1633 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1634 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1635 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1639 * If there is data present from a previous transfer attempt,
1640 * resume where it left off
1642 prev_posn = ftello(preq->packfile);
1644 if (http_is_verbose)
1646 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1647 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1648 http_opt_request_remainder(preq->slot->curl, prev_posn);
1659 /* Helpers for fetching objects (loose) */
1660 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1663 unsigned char expn[4096];
1664 size_t size = eltsize * nmemb;
1666 struct http_object_request *freq =
1667 (struct http_object_request *)data;
1669 ssize_t retval = xwrite(freq->localfile,
1670 (char *) ptr + posn, size - posn);
1674 } while (posn < size);
1676 freq->stream.avail_in = size;
1677 freq->stream.next_in = (void *)ptr;
1679 freq->stream.next_out = expn;
1680 freq->stream.avail_out = sizeof(expn);
1681 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1682 git_SHA1_Update(&freq->c, expn,
1683 sizeof(expn) - freq->stream.avail_out);
1684 } while (freq->stream.avail_in && freq->zret == Z_OK);
1688 struct http_object_request *new_http_object_request(const char *base_url,
1689 unsigned char *sha1)
1691 char *hex = sha1_to_hex(sha1);
1692 const char *filename;
1693 char prevfile[PATH_MAX];
1695 char prev_buf[PREV_BUF_SIZE];
1696 ssize_t prev_read = 0;
1697 off_t prev_posn = 0;
1698 struct http_object_request *freq;
1700 freq = xcalloc(1, sizeof(*freq));
1701 hashcpy(freq->sha1, sha1);
1702 freq->localfile = -1;
1704 filename = sha1_file_name(sha1);
1705 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1706 "%s.temp", filename);
1708 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1709 unlink_or_warn(prevfile);
1710 rename(freq->tmpfile, prevfile);
1711 unlink_or_warn(freq->tmpfile);
1713 if (freq->localfile != -1)
1714 error("fd leakage in start: %d", freq->localfile);
1715 freq->localfile = open(freq->tmpfile,
1716 O_WRONLY | O_CREAT | O_EXCL, 0666);
1718 * This could have failed due to the "lazy directory creation";
1719 * try to mkdir the last path component.
1721 if (freq->localfile < 0 && errno == ENOENT) {
1722 char *dir = strrchr(freq->tmpfile, '/');
1725 mkdir(freq->tmpfile, 0777);
1728 freq->localfile = open(freq->tmpfile,
1729 O_WRONLY | O_CREAT | O_EXCL, 0666);
1732 if (freq->localfile < 0) {
1733 error("Couldn't create temporary file %s: %s",
1734 freq->tmpfile, strerror(errno));
1738 git_inflate_init(&freq->stream);
1740 git_SHA1_Init(&freq->c);
1742 freq->url = get_remote_object_url(base_url, hex, 0);
1745 * If a previous temp file is present, process what was already
1748 prevlocal = open(prevfile, O_RDONLY);
1749 if (prevlocal != -1) {
1751 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1753 if (fwrite_sha1_file(prev_buf,
1756 freq) == prev_read) {
1757 prev_posn += prev_read;
1762 } while (prev_read > 0);
1765 unlink_or_warn(prevfile);
1768 * Reset inflate/SHA1 if there was an error reading the previous temp
1769 * file; also rewind to the beginning of the local file.
1771 if (prev_read == -1) {
1772 memset(&freq->stream, 0, sizeof(freq->stream));
1773 git_inflate_init(&freq->stream);
1774 git_SHA1_Init(&freq->c);
1777 lseek(freq->localfile, 0, SEEK_SET);
1778 if (ftruncate(freq->localfile, 0) < 0) {
1779 error("Couldn't truncate temporary file %s: %s",
1780 freq->tmpfile, strerror(errno));
1786 freq->slot = get_active_slot();
1788 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1789 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1790 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1791 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1792 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1795 * If we have successfully processed data from a previous fetch
1796 * attempt, only fetch the data we don't already have.
1799 if (http_is_verbose)
1801 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
1802 hex, (uintmax_t)prev_posn);
1803 http_opt_request_remainder(freq->slot->curl, prev_posn);
1814 void process_http_object_request(struct http_object_request *freq)
1816 if (freq->slot == NULL)
1818 freq->curl_result = freq->slot->curl_result;
1819 freq->http_code = freq->slot->http_code;
1823 int finish_http_object_request(struct http_object_request *freq)
1827 close(freq->localfile);
1828 freq->localfile = -1;
1830 process_http_object_request(freq);
1832 if (freq->http_code == 416) {
1833 warning("requested range invalid; we may already have all the data.");
1834 } else if (freq->curl_result != CURLE_OK) {
1835 if (stat(freq->tmpfile, &st) == 0)
1836 if (st.st_size == 0)
1837 unlink_or_warn(freq->tmpfile);
1841 git_inflate_end(&freq->stream);
1842 git_SHA1_Final(freq->real_sha1, &freq->c);
1843 if (freq->zret != Z_STREAM_END) {
1844 unlink_or_warn(freq->tmpfile);
1847 if (hashcmp(freq->sha1, freq->real_sha1)) {
1848 unlink_or_warn(freq->tmpfile);
1852 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
1854 return freq->rename;
1857 void abort_http_object_request(struct http_object_request *freq)
1859 unlink_or_warn(freq->tmpfile);
1861 release_http_object_request(freq);
1864 void release_http_object_request(struct http_object_request *freq)
1866 if (freq->localfile != -1) {
1867 close(freq->localfile);
1868 freq->localfile = -1;
1870 if (freq->url != NULL) {
1874 if (freq->slot != NULL) {
1875 freq->slot->callback_func = NULL;
1876 freq->slot->callback_data = NULL;
1877 release_active_slot(freq->slot);