1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
14 #if LIBCURL_VERSION_NUM >= 0x070a08
15 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
17 long int git_curl_ipresolve;
21 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
23 #if LIBCURL_VERSION_NUM >= 0x070a06
24 #define LIBCURL_CAN_HANDLE_AUTH_ANY
27 static int min_curl_sessions = 1;
28 static int curl_session_count;
30 static int max_requests = -1;
33 #ifndef NO_CURL_EASY_DUPHANDLE
34 static CURL *curl_default;
37 #define PREV_BUF_SIZE 4096
39 char curl_errorstr[CURL_ERROR_SIZE];
41 static int curl_ssl_verify = -1;
42 static int curl_ssl_try;
43 static const char *ssl_cert;
44 static const char *ssl_cipherlist;
45 static const char *ssl_version;
50 { "sslv2", CURL_SSLVERSION_SSLv2 },
51 { "sslv3", CURL_SSLVERSION_SSLv3 },
52 { "tlsv1", CURL_SSLVERSION_TLSv1 },
53 #if LIBCURL_VERSION_NUM >= 0x072200
54 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
55 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
56 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
59 #if LIBCURL_VERSION_NUM >= 0x070903
60 static const char *ssl_key;
62 #if LIBCURL_VERSION_NUM >= 0x070908
63 static const char *ssl_capath;
65 #if LIBCURL_VERSION_NUM >= 0x072c00
66 static const char *ssl_pinnedkey;
68 static const char *ssl_cainfo;
69 static long curl_low_speed_limit = -1;
70 static long curl_low_speed_time = -1;
71 static int curl_ftp_no_epsv;
72 static const char *curl_http_proxy;
73 static const char *curl_no_proxy;
74 static const char *http_proxy_authmethod;
78 } proxy_authmethods[] = {
79 { "basic", CURLAUTH_BASIC },
80 { "digest", CURLAUTH_DIGEST },
81 { "negotiate", CURLAUTH_GSSNEGOTIATE },
82 { "ntlm", CURLAUTH_NTLM },
83 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
84 { "anyauth", CURLAUTH_ANY },
87 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
88 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
92 static struct credential proxy_auth = CREDENTIAL_INIT;
93 static const char *curl_proxyuserpwd;
94 static const char *curl_cookie_file;
95 static int curl_save_cookies;
96 struct credential http_auth = CREDENTIAL_INIT;
97 static int http_proactive_auth;
98 static const char *user_agent;
99 static int curl_empty_auth;
101 #if LIBCURL_VERSION_NUM >= 0x071700
102 /* Use CURLOPT_KEYPASSWD as is */
103 #elif LIBCURL_VERSION_NUM >= 0x070903
104 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
106 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
109 static struct credential cert_auth = CREDENTIAL_INIT;
110 static int ssl_cert_password_required;
111 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
112 static unsigned long http_auth_methods = CURLAUTH_ANY;
115 static struct curl_slist *pragma_header;
116 static struct curl_slist *no_pragma_header;
118 static struct active_request_slot *active_queue_head;
120 static char *cached_accept_language;
122 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
124 size_t size = eltsize * nmemb;
125 struct buffer *buffer = buffer_;
127 if (size > buffer->buf.len - buffer->posn)
128 size = buffer->buf.len - buffer->posn;
129 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
130 buffer->posn += size;
135 #ifndef NO_CURL_IOCTL
136 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
138 struct buffer *buffer = clientp;
144 case CURLIOCMD_RESTARTREAD:
149 return CURLIOE_UNKNOWNCMD;
154 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
156 size_t size = eltsize * nmemb;
157 struct strbuf *buffer = buffer_;
159 strbuf_add(buffer, ptr, size);
163 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
165 return eltsize * nmemb;
168 static void closedown_active_slot(struct active_request_slot *slot)
174 static void finish_active_slot(struct active_request_slot *slot)
176 closedown_active_slot(slot);
177 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
179 if (slot->finished != NULL)
180 (*slot->finished) = 1;
182 /* Store slot results so they can be read after the slot is reused */
183 if (slot->results != NULL) {
184 slot->results->curl_result = slot->curl_result;
185 slot->results->http_code = slot->http_code;
186 #if LIBCURL_VERSION_NUM >= 0x070a08
187 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
188 &slot->results->auth_avail);
190 slot->results->auth_avail = 0;
193 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
194 &slot->results->http_connectcode);
197 /* Run callback if appropriate */
198 if (slot->callback_func != NULL)
199 slot->callback_func(slot->callback_data);
202 #ifdef USE_CURL_MULTI
203 static void process_curl_messages(void)
206 struct active_request_slot *slot;
207 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
209 while (curl_message != NULL) {
210 if (curl_message->msg == CURLMSG_DONE) {
211 int curl_result = curl_message->data.result;
212 slot = active_queue_head;
213 while (slot != NULL &&
214 slot->curl != curl_message->easy_handle)
217 curl_multi_remove_handle(curlm, slot->curl);
218 slot->curl_result = curl_result;
219 finish_active_slot(slot);
221 fprintf(stderr, "Received DONE message for unknown request!\n");
224 fprintf(stderr, "Unknown CURL message received: %d\n",
225 (int)curl_message->msg);
227 curl_message = curl_multi_info_read(curlm, &num_messages);
232 static int http_options(const char *var, const char *value, void *cb)
234 if (!strcmp("http.sslverify", var)) {
235 curl_ssl_verify = git_config_bool(var, value);
238 if (!strcmp("http.sslcipherlist", var))
239 return git_config_string(&ssl_cipherlist, var, value);
240 if (!strcmp("http.sslversion", var))
241 return git_config_string(&ssl_version, var, value);
242 if (!strcmp("http.sslcert", var))
243 return git_config_string(&ssl_cert, var, value);
244 #if LIBCURL_VERSION_NUM >= 0x070903
245 if (!strcmp("http.sslkey", var))
246 return git_config_string(&ssl_key, var, value);
248 #if LIBCURL_VERSION_NUM >= 0x070908
249 if (!strcmp("http.sslcapath", var))
250 return git_config_pathname(&ssl_capath, var, value);
252 if (!strcmp("http.sslcainfo", var))
253 return git_config_pathname(&ssl_cainfo, var, value);
254 if (!strcmp("http.sslcertpasswordprotected", var)) {
255 ssl_cert_password_required = git_config_bool(var, value);
258 if (!strcmp("http.ssltry", var)) {
259 curl_ssl_try = git_config_bool(var, value);
262 if (!strcmp("http.minsessions", var)) {
263 min_curl_sessions = git_config_int(var, value);
264 #ifndef USE_CURL_MULTI
265 if (min_curl_sessions > 1)
266 min_curl_sessions = 1;
270 #ifdef USE_CURL_MULTI
271 if (!strcmp("http.maxrequests", var)) {
272 max_requests = git_config_int(var, value);
276 if (!strcmp("http.lowspeedlimit", var)) {
277 curl_low_speed_limit = (long)git_config_int(var, value);
280 if (!strcmp("http.lowspeedtime", var)) {
281 curl_low_speed_time = (long)git_config_int(var, value);
285 if (!strcmp("http.noepsv", var)) {
286 curl_ftp_no_epsv = git_config_bool(var, value);
289 if (!strcmp("http.proxy", var))
290 return git_config_string(&curl_http_proxy, var, value);
292 if (!strcmp("http.proxyauthmethod", var))
293 return git_config_string(&http_proxy_authmethod, var, value);
295 if (!strcmp("http.cookiefile", var))
296 return git_config_string(&curl_cookie_file, var, value);
297 if (!strcmp("http.savecookies", var)) {
298 curl_save_cookies = git_config_bool(var, value);
302 if (!strcmp("http.postbuffer", var)) {
303 http_post_buffer = git_config_int(var, value);
304 if (http_post_buffer < LARGE_PACKET_MAX)
305 http_post_buffer = LARGE_PACKET_MAX;
309 if (!strcmp("http.useragent", var))
310 return git_config_string(&user_agent, var, value);
312 if (!strcmp("http.emptyauth", var)) {
313 curl_empty_auth = git_config_bool(var, value);
317 if (!strcmp("http.pinnedpubkey", var)) {
318 #if LIBCURL_VERSION_NUM >= 0x072c00
319 return git_config_pathname(&ssl_pinnedkey, var, value);
321 warning(_("Public key pinning not supported with cURL < 7.44.0"));
326 /* Fall back on the default ones */
327 return git_default_config(var, value, cb);
330 static void init_curl_http_auth(CURL *result)
332 if (!http_auth.username) {
334 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
338 credential_fill(&http_auth);
340 #if LIBCURL_VERSION_NUM >= 0x071301
341 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
342 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
345 static struct strbuf up = STRBUF_INIT;
347 * Note that we assume we only ever have a single set of
348 * credentials in a given program run, so we do not have
349 * to worry about updating this buffer, only setting its
353 strbuf_addf(&up, "%s:%s",
354 http_auth.username, http_auth.password);
355 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
360 /* *var must be free-able */
361 static void var_override(const char **var, char *value)
365 *var = xstrdup(value);
369 static void set_proxyauth_name_password(CURL *result)
371 #if LIBCURL_VERSION_NUM >= 0x071301
372 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
373 proxy_auth.username);
374 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
375 proxy_auth.password);
377 struct strbuf s = STRBUF_INIT;
379 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
380 strbuf_addch(&s, ':');
381 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
382 curl_proxyuserpwd = strbuf_detach(&s, NULL);
383 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
387 static void init_curl_proxy_auth(CURL *result)
389 if (proxy_auth.username) {
390 if (!proxy_auth.password)
391 credential_fill(&proxy_auth);
392 set_proxyauth_name_password(result);
395 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
397 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
398 if (http_proxy_authmethod) {
400 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
401 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
402 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
403 proxy_authmethods[i].curlauth_param);
407 if (i == ARRAY_SIZE(proxy_authmethods)) {
408 warning("unsupported proxy authentication method %s: using anyauth",
409 http_proxy_authmethod);
410 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
414 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
418 static int has_cert_password(void)
420 if (ssl_cert == NULL || ssl_cert_password_required != 1)
422 if (!cert_auth.password) {
423 cert_auth.protocol = xstrdup("cert");
424 cert_auth.username = xstrdup("");
425 cert_auth.path = xstrdup(ssl_cert);
426 credential_fill(&cert_auth);
431 #if LIBCURL_VERSION_NUM >= 0x071900
432 static void set_curl_keepalive(CURL *c)
434 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
437 #elif LIBCURL_VERSION_NUM >= 0x071000
438 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
442 socklen_t len = (socklen_t)sizeof(ka);
444 if (type != CURLSOCKTYPE_IPCXN)
447 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
449 warning("unable to set SO_KEEPALIVE on socket %s",
452 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
455 static void set_curl_keepalive(CURL *c)
457 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
461 static void set_curl_keepalive(CURL *c)
463 /* not supported on older curl versions */
467 static CURL *get_curl_handle(void)
469 CURL *result = curl_easy_init();
470 long allowed_protocols = 0;
473 die("curl_easy_init failed");
475 if (!curl_ssl_verify) {
476 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
477 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
479 /* Verify authenticity of the peer's certificate */
480 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
481 /* The name in the cert must match whom we tried to connect */
482 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
485 #if LIBCURL_VERSION_NUM >= 0x070907
486 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
488 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
489 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
492 if (http_proactive_auth)
493 init_curl_http_auth(result);
495 if (getenv("GIT_SSL_VERSION"))
496 ssl_version = getenv("GIT_SSL_VERSION");
497 if (ssl_version && *ssl_version) {
499 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
500 if (!strcmp(ssl_version, sslversions[i].name)) {
501 curl_easy_setopt(result, CURLOPT_SSLVERSION,
502 sslversions[i].ssl_version);
506 if (i == ARRAY_SIZE(sslversions))
507 warning("unsupported ssl version %s: using default",
511 if (getenv("GIT_SSL_CIPHER_LIST"))
512 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
513 if (ssl_cipherlist != NULL && *ssl_cipherlist)
514 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
517 if (ssl_cert != NULL)
518 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
519 if (has_cert_password())
520 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
521 #if LIBCURL_VERSION_NUM >= 0x070903
523 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
525 #if LIBCURL_VERSION_NUM >= 0x070908
526 if (ssl_capath != NULL)
527 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
529 #if LIBCURL_VERSION_NUM >= 0x072c00
530 if (ssl_pinnedkey != NULL)
531 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
533 if (ssl_cainfo != NULL)
534 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
536 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
537 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
538 curl_low_speed_limit);
539 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
540 curl_low_speed_time);
543 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
544 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
545 #if LIBCURL_VERSION_NUM >= 0x071301
546 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
547 #elif LIBCURL_VERSION_NUM >= 0x071101
548 curl_easy_setopt(result, CURLOPT_POST301, 1);
550 #if LIBCURL_VERSION_NUM >= 0x071304
551 if (is_transport_allowed("http"))
552 allowed_protocols |= CURLPROTO_HTTP;
553 if (is_transport_allowed("https"))
554 allowed_protocols |= CURLPROTO_HTTPS;
555 if (is_transport_allowed("ftp"))
556 allowed_protocols |= CURLPROTO_FTP;
557 if (is_transport_allowed("ftps"))
558 allowed_protocols |= CURLPROTO_FTPS;
559 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
561 if (transport_restrict_protocols())
562 warning("protocol restrictions not applied to curl redirects because\n"
563 "your curl version is too old (>= 7.19.4)");
566 if (getenv("GIT_CURL_VERBOSE"))
567 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
569 curl_easy_setopt(result, CURLOPT_USERAGENT,
570 user_agent ? user_agent : git_user_agent());
572 if (curl_ftp_no_epsv)
573 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
575 #ifdef CURLOPT_USE_SSL
577 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
581 * CURL also examines these variables as a fallback; but we need to query
582 * them here in order to decide whether to prompt for missing password (cf.
583 * init_curl_proxy_auth()).
585 * Unlike many other common environment variables, these are historically
586 * lowercase only. It appears that CURL did not know this and implemented
587 * only uppercase variants, which was later corrected to take both - with
588 * the exception of http_proxy, which is lowercase only also in CURL. As
589 * the lowercase versions are the historical quasi-standard, they take
590 * precedence here, as in CURL.
592 if (!curl_http_proxy) {
593 if (!strcmp(http_auth.protocol, "https")) {
594 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
595 var_override(&curl_http_proxy, getenv("https_proxy"));
597 var_override(&curl_http_proxy, getenv("http_proxy"));
599 if (!curl_http_proxy) {
600 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
601 var_override(&curl_http_proxy, getenv("all_proxy"));
605 if (curl_http_proxy) {
606 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
607 #if LIBCURL_VERSION_NUM >= 0x071800
608 if (starts_with(curl_http_proxy, "socks5"))
609 curl_easy_setopt(result,
610 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
611 else if (starts_with(curl_http_proxy, "socks4a"))
612 curl_easy_setopt(result,
613 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
614 else if (starts_with(curl_http_proxy, "socks"))
615 curl_easy_setopt(result,
616 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
618 if (strstr(curl_http_proxy, "://"))
619 credential_from_url(&proxy_auth, curl_http_proxy);
621 struct strbuf url = STRBUF_INIT;
622 strbuf_addf(&url, "http://%s", curl_http_proxy);
623 credential_from_url(&proxy_auth, url.buf);
624 strbuf_release(&url);
627 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
628 #if LIBCURL_VERSION_NUM >= 0x071304
629 var_override(&curl_no_proxy, getenv("NO_PROXY"));
630 var_override(&curl_no_proxy, getenv("no_proxy"));
631 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
634 init_curl_proxy_auth(result);
636 set_curl_keepalive(result);
641 static void set_from_env(const char **var, const char *envname)
643 const char *val = getenv(envname);
648 void http_init(struct remote *remote, const char *url, int proactive_auth)
650 char *low_speed_limit;
651 char *low_speed_time;
652 char *normalized_url;
653 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
655 config.section = "http";
657 config.collect_fn = http_options;
658 config.cascade_fn = git_default_config;
662 normalized_url = url_normalize(url, &config.url);
664 git_config(urlmatch_config_entry, &config);
665 free(normalized_url);
667 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
668 die("curl_global_init failed");
670 http_proactive_auth = proactive_auth;
672 if (remote && remote->http_proxy)
673 curl_http_proxy = xstrdup(remote->http_proxy);
676 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
678 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
679 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
681 #ifdef USE_CURL_MULTI
683 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
684 if (http_max_requests != NULL)
685 max_requests = atoi(http_max_requests);
688 curlm = curl_multi_init();
690 die("curl_multi_init failed");
693 if (getenv("GIT_SSL_NO_VERIFY"))
696 set_from_env(&ssl_cert, "GIT_SSL_CERT");
697 #if LIBCURL_VERSION_NUM >= 0x070903
698 set_from_env(&ssl_key, "GIT_SSL_KEY");
700 #if LIBCURL_VERSION_NUM >= 0x070908
701 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
703 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
705 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
707 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
708 if (low_speed_limit != NULL)
709 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
710 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
711 if (low_speed_time != NULL)
712 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
714 if (curl_ssl_verify == -1)
717 curl_session_count = 0;
718 #ifdef USE_CURL_MULTI
719 if (max_requests < 1)
720 max_requests = DEFAULT_MAX_REQUESTS;
723 if (getenv("GIT_CURL_FTP_NO_EPSV"))
724 curl_ftp_no_epsv = 1;
727 credential_from_url(&http_auth, url);
728 if (!ssl_cert_password_required &&
729 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
730 starts_with(url, "https://"))
731 ssl_cert_password_required = 1;
734 #ifndef NO_CURL_EASY_DUPHANDLE
735 curl_default = get_curl_handle();
739 void http_cleanup(void)
741 struct active_request_slot *slot = active_queue_head;
743 while (slot != NULL) {
744 struct active_request_slot *next = slot->next;
745 if (slot->curl != NULL) {
746 #ifdef USE_CURL_MULTI
747 curl_multi_remove_handle(curlm, slot->curl);
749 curl_easy_cleanup(slot->curl);
754 active_queue_head = NULL;
756 #ifndef NO_CURL_EASY_DUPHANDLE
757 curl_easy_cleanup(curl_default);
760 #ifdef USE_CURL_MULTI
761 curl_multi_cleanup(curlm);
763 curl_global_cleanup();
765 curl_slist_free_all(pragma_header);
766 pragma_header = NULL;
768 curl_slist_free_all(no_pragma_header);
769 no_pragma_header = NULL;
771 if (curl_http_proxy) {
772 free((void *)curl_http_proxy);
773 curl_http_proxy = NULL;
776 if (proxy_auth.password) {
777 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
778 free(proxy_auth.password);
779 proxy_auth.password = NULL;
782 free((void *)curl_proxyuserpwd);
783 curl_proxyuserpwd = NULL;
785 free((void *)http_proxy_authmethod);
786 http_proxy_authmethod = NULL;
788 if (cert_auth.password != NULL) {
789 memset(cert_auth.password, 0, strlen(cert_auth.password));
790 free(cert_auth.password);
791 cert_auth.password = NULL;
793 ssl_cert_password_required = 0;
795 free(cached_accept_language);
796 cached_accept_language = NULL;
799 struct active_request_slot *get_active_slot(void)
801 struct active_request_slot *slot = active_queue_head;
802 struct active_request_slot *newslot;
804 #ifdef USE_CURL_MULTI
807 /* Wait for a slot to open up if the queue is full */
808 while (active_requests >= max_requests) {
809 curl_multi_perform(curlm, &num_transfers);
810 if (num_transfers < active_requests)
811 process_curl_messages();
815 while (slot != NULL && slot->in_use)
819 newslot = xmalloc(sizeof(*newslot));
820 newslot->curl = NULL;
822 newslot->next = NULL;
824 slot = active_queue_head;
826 active_queue_head = newslot;
828 while (slot->next != NULL)
830 slot->next = newslot;
835 if (slot->curl == NULL) {
836 #ifdef NO_CURL_EASY_DUPHANDLE
837 slot->curl = get_curl_handle();
839 slot->curl = curl_easy_duphandle(curl_default);
841 curl_session_count++;
846 slot->results = NULL;
847 slot->finished = NULL;
848 slot->callback_data = NULL;
849 slot->callback_func = NULL;
850 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
851 if (curl_save_cookies)
852 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
853 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
854 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
855 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
856 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
857 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
858 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
859 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
860 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
861 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
862 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
864 #if LIBCURL_VERSION_NUM >= 0x070a08
865 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
867 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
868 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
870 if (http_auth.password || curl_empty_auth)
871 init_curl_http_auth(slot->curl);
876 int start_active_slot(struct active_request_slot *slot)
878 #ifdef USE_CURL_MULTI
879 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
882 if (curlm_result != CURLM_OK &&
883 curlm_result != CURLM_CALL_MULTI_PERFORM) {
890 * We know there must be something to do, since we just added
893 curl_multi_perform(curlm, &num_transfers);
898 #ifdef USE_CURL_MULTI
902 struct fill_chain *next;
905 static struct fill_chain *fill_cfg;
907 void add_fill_function(void *data, int (*fill)(void *))
909 struct fill_chain *new = xmalloc(sizeof(*new));
910 struct fill_chain **linkp = &fill_cfg;
915 linkp = &(*linkp)->next;
919 void fill_active_slots(void)
921 struct active_request_slot *slot = active_queue_head;
923 while (active_requests < max_requests) {
924 struct fill_chain *fill;
925 for (fill = fill_cfg; fill; fill = fill->next)
926 if (fill->fill(fill->data))
933 while (slot != NULL) {
934 if (!slot->in_use && slot->curl != NULL
935 && curl_session_count > min_curl_sessions) {
936 curl_easy_cleanup(slot->curl);
938 curl_session_count--;
944 void step_active_slots(void)
947 CURLMcode curlm_result;
950 curlm_result = curl_multi_perform(curlm, &num_transfers);
951 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
952 if (num_transfers < active_requests) {
953 process_curl_messages();
959 void run_active_slot(struct active_request_slot *slot)
961 #ifdef USE_CURL_MULTI
966 struct timeval select_timeout;
969 slot->finished = &finished;
974 #if LIBCURL_VERSION_NUM >= 0x070f04
976 curl_multi_timeout(curlm, &curl_timeout);
977 if (curl_timeout == 0) {
979 } else if (curl_timeout == -1) {
980 select_timeout.tv_sec = 0;
981 select_timeout.tv_usec = 50000;
983 select_timeout.tv_sec = curl_timeout / 1000;
984 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
987 select_timeout.tv_sec = 0;
988 select_timeout.tv_usec = 50000;
995 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
998 * It can happen that curl_multi_timeout returns a pathologically
999 * long timeout when curl_multi_fdset returns no file descriptors
1000 * to read. See commit message for more details.
1003 (select_timeout.tv_sec > 0 ||
1004 select_timeout.tv_usec > 50000)) {
1005 select_timeout.tv_sec = 0;
1006 select_timeout.tv_usec = 50000;
1009 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1013 while (slot->in_use) {
1014 slot->curl_result = curl_easy_perform(slot->curl);
1015 finish_active_slot(slot);
1020 static void release_active_slot(struct active_request_slot *slot)
1022 closedown_active_slot(slot);
1023 if (slot->curl && curl_session_count > min_curl_sessions) {
1024 #ifdef USE_CURL_MULTI
1025 curl_multi_remove_handle(curlm, slot->curl);
1027 curl_easy_cleanup(slot->curl);
1029 curl_session_count--;
1031 #ifdef USE_CURL_MULTI
1032 fill_active_slots();
1036 void finish_all_active_slots(void)
1038 struct active_request_slot *slot = active_queue_head;
1040 while (slot != NULL)
1042 run_active_slot(slot);
1043 slot = active_queue_head;
1049 /* Helpers for modifying and creating URLs */
1050 static inline int needs_quote(int ch)
1052 if (((ch >= 'A') && (ch <= 'Z'))
1053 || ((ch >= 'a') && (ch <= 'z'))
1054 || ((ch >= '0') && (ch <= '9'))
1062 static char *quote_ref_url(const char *base, const char *ref)
1064 struct strbuf buf = STRBUF_INIT;
1068 end_url_with_slash(&buf, base);
1070 for (cp = ref; (ch = *cp) != 0; cp++)
1071 if (needs_quote(ch))
1072 strbuf_addf(&buf, "%%%02x", ch);
1074 strbuf_addch(&buf, *cp);
1076 return strbuf_detach(&buf, NULL);
1079 void append_remote_object_url(struct strbuf *buf, const char *url,
1081 int only_two_digit_prefix)
1083 end_url_with_slash(buf, url);
1085 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1086 if (!only_two_digit_prefix)
1087 strbuf_addf(buf, "%s", hex+2);
1090 char *get_remote_object_url(const char *url, const char *hex,
1091 int only_two_digit_prefix)
1093 struct strbuf buf = STRBUF_INIT;
1094 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1095 return strbuf_detach(&buf, NULL);
1098 static int handle_curl_result(struct slot_results *results)
1101 * If we see a failing http code with CURLE_OK, we have turned off
1102 * FAILONERROR (to keep the server's custom error response), and should
1103 * translate the code into failure here.
1105 if (results->curl_result == CURLE_OK &&
1106 results->http_code >= 400) {
1107 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1109 * Normally curl will already have put the "reason phrase"
1110 * from the server into curl_errorstr; unfortunately without
1111 * FAILONERROR it is lost, so we can give only the numeric
1114 snprintf(curl_errorstr, sizeof(curl_errorstr),
1115 "The requested URL returned error: %ld",
1116 results->http_code);
1119 if (results->curl_result == CURLE_OK) {
1120 credential_approve(&http_auth);
1121 if (proxy_auth.password)
1122 credential_approve(&proxy_auth);
1124 } else if (missing_target(results))
1125 return HTTP_MISSING_TARGET;
1126 else if (results->http_code == 401) {
1127 if (http_auth.username && http_auth.password) {
1128 credential_reject(&http_auth);
1131 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1132 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1137 if (results->http_connectcode == 407)
1138 credential_reject(&proxy_auth);
1139 #if LIBCURL_VERSION_NUM >= 0x070c00
1140 if (!curl_errorstr[0])
1141 strlcpy(curl_errorstr,
1142 curl_easy_strerror(results->curl_result),
1143 sizeof(curl_errorstr));
1149 int run_one_slot(struct active_request_slot *slot,
1150 struct slot_results *results)
1152 slot->results = results;
1153 if (!start_active_slot(slot)) {
1154 snprintf(curl_errorstr, sizeof(curl_errorstr),
1155 "failed to start HTTP request");
1156 return HTTP_START_FAILED;
1159 run_active_slot(slot);
1160 return handle_curl_result(results);
1163 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1169 ret = curl_easy_getinfo(curl, info, &ptr);
1171 strbuf_addstr(buf, ptr);
1176 * Check for and extract a content-type parameter. "raw"
1177 * should be positioned at the start of the potential
1178 * parameter, with any whitespace already removed.
1180 * "name" is the name of the parameter. The value is appended
1183 static int extract_param(const char *raw, const char *name,
1186 size_t len = strlen(name);
1188 if (strncasecmp(raw, name, len))
1196 while (*raw && !isspace(*raw) && *raw != ';')
1197 strbuf_addch(out, *raw++);
1202 * Extract a normalized version of the content type, with any
1203 * spaces suppressed, all letters lowercased, and no trailing ";"
1206 * Note that we will silently remove even invalid whitespace. For
1207 * example, "text / plain" is specifically forbidden by RFC 2616,
1208 * but "text/plain" is the only reasonable output, and this keeps
1211 * If the "charset" argument is not NULL, store the value of any
1212 * charset parameter there.
1215 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1216 * "text / plain" -> "text/plain"
1218 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1219 struct strbuf *charset)
1224 strbuf_grow(type, raw->len);
1225 for (p = raw->buf; *p; p++) {
1232 strbuf_addch(type, tolower(*p));
1238 strbuf_reset(charset);
1240 while (isspace(*p) || *p == ';')
1242 if (!extract_param(p, "charset", charset))
1244 while (*p && !isspace(*p))
1248 if (!charset->len && starts_with(type->buf, "text/"))
1249 strbuf_addstr(charset, "ISO-8859-1");
1252 static void write_accept_language(struct strbuf *buf)
1255 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1256 * that, q-value will be smaller than 0.001, the minimum q-value the
1257 * HTTP specification allows. See
1258 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1260 const int MAX_DECIMAL_PLACES = 3;
1261 const int MAX_LANGUAGE_TAGS = 1000;
1262 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1263 char **language_tags = NULL;
1265 const char *s = get_preferred_languages();
1267 struct strbuf tag = STRBUF_INIT;
1269 /* Don't add Accept-Language header if no language is preferred. */
1274 * Split the colon-separated string of preferred languages into
1275 * language_tags array.
1278 /* collect language tag */
1279 for (; *s && (isalnum(*s) || *s == '_'); s++)
1280 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1282 /* skip .codeset, @modifier and any other unnecessary parts */
1283 while (*s && *s != ':')
1288 REALLOC_ARRAY(language_tags, num_langs);
1289 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1290 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1295 /* write Accept-Language header into buf */
1297 int last_buf_len = 0;
1303 REALLOC_ARRAY(language_tags, num_langs + 1);
1304 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1306 /* compute decimal_places */
1307 for (max_q = 1, decimal_places = 0;
1308 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1309 decimal_places++, max_q *= 10)
1312 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1314 strbuf_addstr(buf, "Accept-Language: ");
1316 for (i = 0; i < num_langs; i++) {
1318 strbuf_addstr(buf, ", ");
1320 strbuf_addstr(buf, language_tags[i]);
1323 strbuf_addf(buf, q_format, max_q - i);
1325 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1326 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1330 last_buf_len = buf->len;
1334 /* free language tags -- last one is a static '*' */
1335 for (i = 0; i < num_langs - 1; i++)
1336 free(language_tags[i]);
1337 free(language_tags);
1341 * Get an Accept-Language header which indicates user's preferred languages.
1345 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1346 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1347 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1348 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1349 * LANGUAGE= LANG=C -> ""
1351 static const char *get_accept_language(void)
1353 if (!cached_accept_language) {
1354 struct strbuf buf = STRBUF_INIT;
1355 write_accept_language(&buf);
1357 cached_accept_language = strbuf_detach(&buf, NULL);
1360 return cached_accept_language;
1363 static void http_opt_request_remainder(CURL *curl, off_t pos)
1366 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1367 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1370 /* http_request() targets */
1371 #define HTTP_REQUEST_STRBUF 0
1372 #define HTTP_REQUEST_FILE 1
1374 static int http_request(const char *url,
1375 void *result, int target,
1376 const struct http_get_options *options)
1378 struct active_request_slot *slot;
1379 struct slot_results results;
1380 struct curl_slist *headers = NULL;
1381 struct strbuf buf = STRBUF_INIT;
1382 const char *accept_language;
1385 slot = get_active_slot();
1386 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1388 if (result == NULL) {
1389 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1391 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1392 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1394 if (target == HTTP_REQUEST_FILE) {
1395 off_t posn = ftello(result);
1396 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1399 http_opt_request_remainder(slot->curl, posn);
1401 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1405 accept_language = get_accept_language();
1407 if (accept_language)
1408 headers = curl_slist_append(headers, accept_language);
1410 strbuf_addstr(&buf, "Pragma:");
1411 if (options && options->no_cache)
1412 strbuf_addstr(&buf, " no-cache");
1413 if (options && options->keep_error)
1414 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1416 headers = curl_slist_append(headers, buf.buf);
1418 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1419 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1420 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1422 ret = run_one_slot(slot, &results);
1424 if (options && options->content_type) {
1425 struct strbuf raw = STRBUF_INIT;
1426 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1427 extract_content_type(&raw, options->content_type,
1429 strbuf_release(&raw);
1432 if (options && options->effective_url)
1433 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1434 options->effective_url);
1436 curl_slist_free_all(headers);
1437 strbuf_release(&buf);
1443 * Update the "base" url to a more appropriate value, as deduced by
1444 * redirects seen when requesting a URL starting with "url".
1446 * The "asked" parameter is a URL that we asked curl to access, and must begin
1449 * The "got" parameter is the URL that curl reported to us as where we ended
1452 * Returns 1 if we updated the base url, 0 otherwise.
1454 * Our basic strategy is to compare "base" and "asked" to find the bits
1455 * specific to our request. We then strip those bits off of "got" to yield the
1456 * new base. So for example, if our base is "http://example.com/foo.git",
1457 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1458 * with "https://other.example.com/foo.git/info/refs". We would want the
1459 * new URL to become "https://other.example.com/foo.git".
1461 * Note that this assumes a sane redirect scheme. It's entirely possible
1462 * in the example above to end up at a URL that does not even end in
1463 * "info/refs". In such a case we simply punt, as there is not much we can
1464 * do (and such a scheme is unlikely to represent a real git repository,
1465 * which means we are likely about to abort anyway).
1467 static int update_url_from_redirect(struct strbuf *base,
1469 const struct strbuf *got)
1474 if (!strcmp(asked, got->buf))
1477 if (!skip_prefix(asked, base->buf, &tail))
1478 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1481 tail_len = strlen(tail);
1483 if (got->len < tail_len ||
1484 strcmp(tail, got->buf + got->len - tail_len))
1485 return 0; /* insane redirect scheme */
1488 strbuf_add(base, got->buf, got->len - tail_len);
1492 static int http_request_reauth(const char *url,
1493 void *result, int target,
1494 struct http_get_options *options)
1496 int ret = http_request(url, result, target, options);
1498 if (options && options->effective_url && options->base_url) {
1499 if (update_url_from_redirect(options->base_url,
1500 url, options->effective_url)) {
1501 credential_from_url(&http_auth, options->base_url->buf);
1502 url = options->effective_url->buf;
1506 if (ret != HTTP_REAUTH)
1510 * If we are using KEEP_ERROR, the previous request may have
1511 * put cruft into our output stream; we should clear it out before
1512 * making our next request. We only know how to do this for
1513 * the strbuf case, but that is enough to satisfy current callers.
1515 if (options && options->keep_error) {
1517 case HTTP_REQUEST_STRBUF:
1518 strbuf_reset(result);
1521 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1525 credential_fill(&http_auth);
1527 return http_request(url, result, target, options);
1530 int http_get_strbuf(const char *url,
1531 struct strbuf *result,
1532 struct http_get_options *options)
1534 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1538 * Downloads a URL and stores the result in the given file.
1540 * If a previous interrupted download is detected (i.e. a previous temporary
1541 * file is still around) the download is resumed.
1543 static int http_get_file(const char *url, const char *filename,
1544 struct http_get_options *options)
1547 struct strbuf tmpfile = STRBUF_INIT;
1550 strbuf_addf(&tmpfile, "%s.temp", filename);
1551 result = fopen(tmpfile.buf, "a");
1553 error("Unable to open local file %s", tmpfile.buf);
1558 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1561 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1564 strbuf_release(&tmpfile);
1568 int http_fetch_ref(const char *base, struct ref *ref)
1570 struct http_get_options options = {0};
1572 struct strbuf buffer = STRBUF_INIT;
1575 options.no_cache = 1;
1577 url = quote_ref_url(base, ref->name);
1578 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1579 strbuf_rtrim(&buffer);
1580 if (buffer.len == 40)
1581 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1582 else if (starts_with(buffer.buf, "ref: ")) {
1583 ref->symref = xstrdup(buffer.buf + 5);
1588 strbuf_release(&buffer);
1593 /* Helpers for fetching packs */
1594 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1597 struct strbuf buf = STRBUF_INIT;
1599 if (http_is_verbose)
1600 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1602 end_url_with_slash(&buf, base_url);
1603 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1604 url = strbuf_detach(&buf, NULL);
1606 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1607 tmp = strbuf_detach(&buf, NULL);
1609 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1610 error("Unable to get pack index %s", url);
1619 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1620 unsigned char *sha1, const char *base_url)
1622 struct packed_git *new_pack;
1623 char *tmp_idx = NULL;
1626 if (has_pack_index(sha1)) {
1627 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1629 return -1; /* parse_pack_index() already issued error message */
1633 tmp_idx = fetch_pack_index(sha1, base_url);
1637 new_pack = parse_pack_index(sha1, tmp_idx);
1642 return -1; /* parse_pack_index() already issued error message */
1645 ret = verify_pack_index(new_pack);
1647 close_pack_index(new_pack);
1648 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1655 new_pack->next = *packs_head;
1656 *packs_head = new_pack;
1660 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1662 struct http_get_options options = {0};
1665 struct strbuf buf = STRBUF_INIT;
1666 unsigned char sha1[20];
1668 end_url_with_slash(&buf, base_url);
1669 strbuf_addstr(&buf, "objects/info/packs");
1670 url = strbuf_detach(&buf, NULL);
1672 options.no_cache = 1;
1673 ret = http_get_strbuf(url, &buf, &options);
1678 while (i < buf.len) {
1682 if (i + 52 <= buf.len &&
1683 starts_with(data + i, " pack-") &&
1684 starts_with(data + i + 46, ".pack\n")) {
1685 get_sha1_hex(data + i + 6, sha1);
1686 fetch_and_setup_pack_index(packs_head, sha1,
1692 while (i < buf.len && data[i] != '\n')
1703 void release_http_pack_request(struct http_pack_request *preq)
1705 if (preq->packfile != NULL) {
1706 fclose(preq->packfile);
1707 preq->packfile = NULL;
1714 int finish_http_pack_request(struct http_pack_request *preq)
1716 struct packed_git **lst;
1717 struct packed_git *p = preq->target;
1720 struct child_process ip = CHILD_PROCESS_INIT;
1721 const char *ip_argv[8];
1723 close_pack_index(p);
1725 fclose(preq->packfile);
1726 preq->packfile = NULL;
1730 lst = &((*lst)->next);
1731 *lst = (*lst)->next;
1733 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1734 die("BUG: pack tmpfile does not end in .pack.temp?");
1735 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1737 ip_argv[0] = "index-pack";
1739 ip_argv[2] = tmp_idx;
1740 ip_argv[3] = preq->tmpfile;
1748 if (run_command(&ip)) {
1749 unlink(preq->tmpfile);
1755 unlink(sha1_pack_index_name(p->sha1));
1757 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1758 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1763 install_packed_git(p);
1768 struct http_pack_request *new_http_pack_request(
1769 struct packed_git *target, const char *base_url)
1771 off_t prev_posn = 0;
1772 struct strbuf buf = STRBUF_INIT;
1773 struct http_pack_request *preq;
1775 preq = xcalloc(1, sizeof(*preq));
1776 preq->target = target;
1778 end_url_with_slash(&buf, base_url);
1779 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1780 sha1_to_hex(target->sha1));
1781 preq->url = strbuf_detach(&buf, NULL);
1783 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1784 sha1_pack_name(target->sha1));
1785 preq->packfile = fopen(preq->tmpfile, "a");
1786 if (!preq->packfile) {
1787 error("Unable to open local file %s for pack",
1792 preq->slot = get_active_slot();
1793 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1794 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1795 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1796 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1800 * If there is data present from a previous transfer attempt,
1801 * resume where it left off
1803 prev_posn = ftello(preq->packfile);
1805 if (http_is_verbose)
1807 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1808 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1809 http_opt_request_remainder(preq->slot->curl, prev_posn);
1820 /* Helpers for fetching objects (loose) */
1821 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1824 unsigned char expn[4096];
1825 size_t size = eltsize * nmemb;
1827 struct http_object_request *freq =
1828 (struct http_object_request *)data;
1830 ssize_t retval = xwrite(freq->localfile,
1831 (char *) ptr + posn, size - posn);
1835 } while (posn < size);
1837 freq->stream.avail_in = size;
1838 freq->stream.next_in = (void *)ptr;
1840 freq->stream.next_out = expn;
1841 freq->stream.avail_out = sizeof(expn);
1842 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1843 git_SHA1_Update(&freq->c, expn,
1844 sizeof(expn) - freq->stream.avail_out);
1845 } while (freq->stream.avail_in && freq->zret == Z_OK);
1849 struct http_object_request *new_http_object_request(const char *base_url,
1850 unsigned char *sha1)
1852 char *hex = sha1_to_hex(sha1);
1853 const char *filename;
1854 char prevfile[PATH_MAX];
1856 char prev_buf[PREV_BUF_SIZE];
1857 ssize_t prev_read = 0;
1858 off_t prev_posn = 0;
1859 struct http_object_request *freq;
1861 freq = xcalloc(1, sizeof(*freq));
1862 hashcpy(freq->sha1, sha1);
1863 freq->localfile = -1;
1865 filename = sha1_file_name(sha1);
1866 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1867 "%s.temp", filename);
1869 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1870 unlink_or_warn(prevfile);
1871 rename(freq->tmpfile, prevfile);
1872 unlink_or_warn(freq->tmpfile);
1874 if (freq->localfile != -1)
1875 error("fd leakage in start: %d", freq->localfile);
1876 freq->localfile = open(freq->tmpfile,
1877 O_WRONLY | O_CREAT | O_EXCL, 0666);
1879 * This could have failed due to the "lazy directory creation";
1880 * try to mkdir the last path component.
1882 if (freq->localfile < 0 && errno == ENOENT) {
1883 char *dir = strrchr(freq->tmpfile, '/');
1886 mkdir(freq->tmpfile, 0777);
1889 freq->localfile = open(freq->tmpfile,
1890 O_WRONLY | O_CREAT | O_EXCL, 0666);
1893 if (freq->localfile < 0) {
1894 error("Couldn't create temporary file %s: %s",
1895 freq->tmpfile, strerror(errno));
1899 git_inflate_init(&freq->stream);
1901 git_SHA1_Init(&freq->c);
1903 freq->url = get_remote_object_url(base_url, hex, 0);
1906 * If a previous temp file is present, process what was already
1909 prevlocal = open(prevfile, O_RDONLY);
1910 if (prevlocal != -1) {
1912 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1914 if (fwrite_sha1_file(prev_buf,
1917 freq) == prev_read) {
1918 prev_posn += prev_read;
1923 } while (prev_read > 0);
1926 unlink_or_warn(prevfile);
1929 * Reset inflate/SHA1 if there was an error reading the previous temp
1930 * file; also rewind to the beginning of the local file.
1932 if (prev_read == -1) {
1933 memset(&freq->stream, 0, sizeof(freq->stream));
1934 git_inflate_init(&freq->stream);
1935 git_SHA1_Init(&freq->c);
1938 lseek(freq->localfile, 0, SEEK_SET);
1939 if (ftruncate(freq->localfile, 0) < 0) {
1940 error("Couldn't truncate temporary file %s: %s",
1941 freq->tmpfile, strerror(errno));
1947 freq->slot = get_active_slot();
1949 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1950 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1951 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1952 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1953 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1956 * If we have successfully processed data from a previous fetch
1957 * attempt, only fetch the data we don't already have.
1960 if (http_is_verbose)
1962 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
1963 hex, (uintmax_t)prev_posn);
1964 http_opt_request_remainder(freq->slot->curl, prev_posn);
1975 void process_http_object_request(struct http_object_request *freq)
1977 if (freq->slot == NULL)
1979 freq->curl_result = freq->slot->curl_result;
1980 freq->http_code = freq->slot->http_code;
1984 int finish_http_object_request(struct http_object_request *freq)
1988 close(freq->localfile);
1989 freq->localfile = -1;
1991 process_http_object_request(freq);
1993 if (freq->http_code == 416) {
1994 warning("requested range invalid; we may already have all the data.");
1995 } else if (freq->curl_result != CURLE_OK) {
1996 if (stat(freq->tmpfile, &st) == 0)
1997 if (st.st_size == 0)
1998 unlink_or_warn(freq->tmpfile);
2002 git_inflate_end(&freq->stream);
2003 git_SHA1_Final(freq->real_sha1, &freq->c);
2004 if (freq->zret != Z_STREAM_END) {
2005 unlink_or_warn(freq->tmpfile);
2008 if (hashcmp(freq->sha1, freq->real_sha1)) {
2009 unlink_or_warn(freq->tmpfile);
2013 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2015 return freq->rename;
2018 void abort_http_object_request(struct http_object_request *freq)
2020 unlink_or_warn(freq->tmpfile);
2022 release_http_object_request(freq);
2025 void release_http_object_request(struct http_object_request *freq)
2027 if (freq->localfile != -1) {
2028 close(freq->localfile);
2029 freq->localfile = -1;
2031 if (freq->url != NULL) {
2035 if (freq->slot != NULL) {
2036 freq->slot->callback_func = NULL;
2037 freq->slot->callback_data = NULL;
2038 release_active_slot(freq->slot);