ref-filter.c: mark strings for translation
[git.git] / http.c
blob1d5e3bbd11ae0e7dc0e682d3914e07cc13a0ce14
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "pack.h"
4 #include "sideband.h"
5 #include "run-command.h"
6 #include "url.h"
7 #include "urlmatch.h"
8 #include "credential.h"
9 #include "version.h"
10 #include "pkt-line.h"
11 #include "gettext.h"
12 #include "transport.h"
14 #if LIBCURL_VERSION_NUM >= 0x070a08
15 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
16 #else
17 long int git_curl_ipresolve;
18 #endif
19 int active_requests;
20 int http_is_verbose;
21 size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
23 #if LIBCURL_VERSION_NUM >= 0x070a06
24 #define LIBCURL_CAN_HANDLE_AUTH_ANY
25 #endif
27 static int min_curl_sessions = 1;
28 static int curl_session_count;
29 #ifdef USE_CURL_MULTI
30 static int max_requests = -1;
31 static CURLM *curlm;
32 #endif
33 #ifndef NO_CURL_EASY_DUPHANDLE
34 static CURL *curl_default;
35 #endif
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;
46 static struct {
47 const char *name;
48 long ssl_version;
49 } sslversions[] = {
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 },
57 #endif
59 #if LIBCURL_VERSION_NUM >= 0x070903
60 static const char *ssl_key;
61 #endif
62 #if LIBCURL_VERSION_NUM >= 0x070908
63 static const char *ssl_capath;
64 #endif
65 #if LIBCURL_VERSION_NUM >= 0x072c00
66 static const char *ssl_pinnedkey;
67 #endif
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 *http_proxy_authmethod;
74 static struct {
75 const char *name;
76 long curlauth_param;
77 } proxy_authmethods[] = {
78 { "basic", CURLAUTH_BASIC },
79 { "digest", CURLAUTH_DIGEST },
80 { "negotiate", CURLAUTH_GSSNEGOTIATE },
81 { "ntlm", CURLAUTH_NTLM },
82 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
83 { "anyauth", CURLAUTH_ANY },
84 #endif
86 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
87 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
88 * here, too
91 static struct credential proxy_auth = CREDENTIAL_INIT;
92 static const char *curl_proxyuserpwd;
93 static const char *curl_cookie_file;
94 static int curl_save_cookies;
95 struct credential http_auth = CREDENTIAL_INIT;
96 static int http_proactive_auth;
97 static const char *user_agent;
98 static int curl_empty_auth;
100 #if LIBCURL_VERSION_NUM >= 0x071700
101 /* Use CURLOPT_KEYPASSWD as is */
102 #elif LIBCURL_VERSION_NUM >= 0x070903
103 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
104 #else
105 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
106 #endif
108 static struct credential cert_auth = CREDENTIAL_INIT;
109 static int ssl_cert_password_required;
110 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
111 static unsigned long http_auth_methods = CURLAUTH_ANY;
112 #endif
114 static struct curl_slist *pragma_header;
115 static struct curl_slist *no_pragma_header;
117 static struct active_request_slot *active_queue_head;
119 static char *cached_accept_language;
121 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
123 size_t size = eltsize * nmemb;
124 struct buffer *buffer = buffer_;
126 if (size > buffer->buf.len - buffer->posn)
127 size = buffer->buf.len - buffer->posn;
128 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
129 buffer->posn += size;
131 return size;
134 #ifndef NO_CURL_IOCTL
135 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
137 struct buffer *buffer = clientp;
139 switch (cmd) {
140 case CURLIOCMD_NOP:
141 return CURLIOE_OK;
143 case CURLIOCMD_RESTARTREAD:
144 buffer->posn = 0;
145 return CURLIOE_OK;
147 default:
148 return CURLIOE_UNKNOWNCMD;
151 #endif
153 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
155 size_t size = eltsize * nmemb;
156 struct strbuf *buffer = buffer_;
158 strbuf_add(buffer, ptr, size);
159 return size;
162 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
164 return eltsize * nmemb;
167 static void closedown_active_slot(struct active_request_slot *slot)
169 active_requests--;
170 slot->in_use = 0;
173 static void finish_active_slot(struct active_request_slot *slot)
175 closedown_active_slot(slot);
176 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
178 if (slot->finished != NULL)
179 (*slot->finished) = 1;
181 /* Store slot results so they can be read after the slot is reused */
182 if (slot->results != NULL) {
183 slot->results->curl_result = slot->curl_result;
184 slot->results->http_code = slot->http_code;
185 #if LIBCURL_VERSION_NUM >= 0x070a08
186 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
187 &slot->results->auth_avail);
188 #else
189 slot->results->auth_avail = 0;
190 #endif
192 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
193 &slot->results->http_connectcode);
196 /* Run callback if appropriate */
197 if (slot->callback_func != NULL)
198 slot->callback_func(slot->callback_data);
201 #ifdef USE_CURL_MULTI
202 static void process_curl_messages(void)
204 int num_messages;
205 struct active_request_slot *slot;
206 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
208 while (curl_message != NULL) {
209 if (curl_message->msg == CURLMSG_DONE) {
210 int curl_result = curl_message->data.result;
211 slot = active_queue_head;
212 while (slot != NULL &&
213 slot->curl != curl_message->easy_handle)
214 slot = slot->next;
215 if (slot != NULL) {
216 curl_multi_remove_handle(curlm, slot->curl);
217 slot->curl_result = curl_result;
218 finish_active_slot(slot);
219 } else {
220 fprintf(stderr, "Received DONE message for unknown request!\n");
222 } else {
223 fprintf(stderr, "Unknown CURL message received: %d\n",
224 (int)curl_message->msg);
226 curl_message = curl_multi_info_read(curlm, &num_messages);
229 #endif
231 static int http_options(const char *var, const char *value, void *cb)
233 if (!strcmp("http.sslverify", var)) {
234 curl_ssl_verify = git_config_bool(var, value);
235 return 0;
237 if (!strcmp("http.sslcipherlist", var))
238 return git_config_string(&ssl_cipherlist, var, value);
239 if (!strcmp("http.sslversion", var))
240 return git_config_string(&ssl_version, var, value);
241 if (!strcmp("http.sslcert", var))
242 return git_config_string(&ssl_cert, var, value);
243 #if LIBCURL_VERSION_NUM >= 0x070903
244 if (!strcmp("http.sslkey", var))
245 return git_config_string(&ssl_key, var, value);
246 #endif
247 #if LIBCURL_VERSION_NUM >= 0x070908
248 if (!strcmp("http.sslcapath", var))
249 return git_config_pathname(&ssl_capath, var, value);
250 #endif
251 if (!strcmp("http.sslcainfo", var))
252 return git_config_pathname(&ssl_cainfo, var, value);
253 if (!strcmp("http.sslcertpasswordprotected", var)) {
254 ssl_cert_password_required = git_config_bool(var, value);
255 return 0;
257 if (!strcmp("http.ssltry", var)) {
258 curl_ssl_try = git_config_bool(var, value);
259 return 0;
261 if (!strcmp("http.minsessions", var)) {
262 min_curl_sessions = git_config_int(var, value);
263 #ifndef USE_CURL_MULTI
264 if (min_curl_sessions > 1)
265 min_curl_sessions = 1;
266 #endif
267 return 0;
269 #ifdef USE_CURL_MULTI
270 if (!strcmp("http.maxrequests", var)) {
271 max_requests = git_config_int(var, value);
272 return 0;
274 #endif
275 if (!strcmp("http.lowspeedlimit", var)) {
276 curl_low_speed_limit = (long)git_config_int(var, value);
277 return 0;
279 if (!strcmp("http.lowspeedtime", var)) {
280 curl_low_speed_time = (long)git_config_int(var, value);
281 return 0;
284 if (!strcmp("http.noepsv", var)) {
285 curl_ftp_no_epsv = git_config_bool(var, value);
286 return 0;
288 if (!strcmp("http.proxy", var))
289 return git_config_string(&curl_http_proxy, var, value);
291 if (!strcmp("http.proxyauthmethod", var))
292 return git_config_string(&http_proxy_authmethod, var, value);
294 if (!strcmp("http.cookiefile", var))
295 return git_config_string(&curl_cookie_file, var, value);
296 if (!strcmp("http.savecookies", var)) {
297 curl_save_cookies = git_config_bool(var, value);
298 return 0;
301 if (!strcmp("http.postbuffer", var)) {
302 http_post_buffer = git_config_int(var, value);
303 if (http_post_buffer < LARGE_PACKET_MAX)
304 http_post_buffer = LARGE_PACKET_MAX;
305 return 0;
308 if (!strcmp("http.useragent", var))
309 return git_config_string(&user_agent, var, value);
311 if (!strcmp("http.emptyauth", var)) {
312 curl_empty_auth = git_config_bool(var, value);
313 return 0;
316 if (!strcmp("http.pinnedpubkey", var)) {
317 #if LIBCURL_VERSION_NUM >= 0x072c00
318 return git_config_pathname(&ssl_pinnedkey, var, value);
319 #else
320 warning(_("Public key pinning not supported with cURL < 7.44.0"));
321 return 0;
322 #endif
325 /* Fall back on the default ones */
326 return git_default_config(var, value, cb);
329 static void init_curl_http_auth(CURL *result)
331 if (!http_auth.username) {
332 if (curl_empty_auth)
333 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
334 return;
337 credential_fill(&http_auth);
339 #if LIBCURL_VERSION_NUM >= 0x071301
340 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
341 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
342 #else
344 static struct strbuf up = STRBUF_INIT;
346 * Note that we assume we only ever have a single set of
347 * credentials in a given program run, so we do not have
348 * to worry about updating this buffer, only setting its
349 * initial value.
351 if (!up.len)
352 strbuf_addf(&up, "%s:%s",
353 http_auth.username, http_auth.password);
354 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
356 #endif
359 /* *var must be free-able */
360 static void var_override(const char **var, char *value)
362 if (value) {
363 free((void *)*var);
364 *var = xstrdup(value);
368 static void set_proxyauth_name_password(CURL *result)
370 #if LIBCURL_VERSION_NUM >= 0x071301
371 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
372 proxy_auth.username);
373 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
374 proxy_auth.password);
375 #else
376 struct strbuf s = STRBUF_INIT;
378 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
379 strbuf_addch(&s, ':');
380 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
381 curl_proxyuserpwd = strbuf_detach(&s, NULL);
382 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
383 #endif
386 static void init_curl_proxy_auth(CURL *result)
388 if (proxy_auth.username) {
389 if (!proxy_auth.password)
390 credential_fill(&proxy_auth);
391 set_proxyauth_name_password(result);
394 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
396 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
397 if (http_proxy_authmethod) {
398 int i;
399 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
400 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
401 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
402 proxy_authmethods[i].curlauth_param);
403 break;
406 if (i == ARRAY_SIZE(proxy_authmethods)) {
407 warning("unsupported proxy authentication method %s: using anyauth",
408 http_proxy_authmethod);
409 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
412 else
413 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
414 #endif
417 static int has_cert_password(void)
419 if (ssl_cert == NULL || ssl_cert_password_required != 1)
420 return 0;
421 if (!cert_auth.password) {
422 cert_auth.protocol = xstrdup("cert");
423 cert_auth.username = xstrdup("");
424 cert_auth.path = xstrdup(ssl_cert);
425 credential_fill(&cert_auth);
427 return 1;
430 #if LIBCURL_VERSION_NUM >= 0x071900
431 static void set_curl_keepalive(CURL *c)
433 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
436 #elif LIBCURL_VERSION_NUM >= 0x071000
437 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
439 int ka = 1;
440 int rc;
441 socklen_t len = (socklen_t)sizeof(ka);
443 if (type != CURLSOCKTYPE_IPCXN)
444 return 0;
446 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
447 if (rc < 0)
448 warning("unable to set SO_KEEPALIVE on socket %s",
449 strerror(errno));
451 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
454 static void set_curl_keepalive(CURL *c)
456 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
459 #else
460 static void set_curl_keepalive(CURL *c)
462 /* not supported on older curl versions */
464 #endif
466 static CURL *get_curl_handle(void)
468 CURL *result = curl_easy_init();
469 long allowed_protocols = 0;
471 if (!result)
472 die("curl_easy_init failed");
474 if (!curl_ssl_verify) {
475 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
476 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
477 } else {
478 /* Verify authenticity of the peer's certificate */
479 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
480 /* The name in the cert must match whom we tried to connect */
481 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
484 #if LIBCURL_VERSION_NUM >= 0x070907
485 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
486 #endif
487 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
488 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
489 #endif
491 if (http_proactive_auth)
492 init_curl_http_auth(result);
494 if (getenv("GIT_SSL_VERSION"))
495 ssl_version = getenv("GIT_SSL_VERSION");
496 if (ssl_version && *ssl_version) {
497 int i;
498 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
499 if (!strcmp(ssl_version, sslversions[i].name)) {
500 curl_easy_setopt(result, CURLOPT_SSLVERSION,
501 sslversions[i].ssl_version);
502 break;
505 if (i == ARRAY_SIZE(sslversions))
506 warning("unsupported ssl version %s: using default",
507 ssl_version);
510 if (getenv("GIT_SSL_CIPHER_LIST"))
511 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
512 if (ssl_cipherlist != NULL && *ssl_cipherlist)
513 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
514 ssl_cipherlist);
516 if (ssl_cert != NULL)
517 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
518 if (has_cert_password())
519 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
520 #if LIBCURL_VERSION_NUM >= 0x070903
521 if (ssl_key != NULL)
522 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
523 #endif
524 #if LIBCURL_VERSION_NUM >= 0x070908
525 if (ssl_capath != NULL)
526 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
527 #endif
528 #if LIBCURL_VERSION_NUM >= 0x072c00
529 if (ssl_pinnedkey != NULL)
530 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
531 #endif
532 if (ssl_cainfo != NULL)
533 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
535 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
536 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
537 curl_low_speed_limit);
538 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
539 curl_low_speed_time);
542 curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
543 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
544 #if LIBCURL_VERSION_NUM >= 0x071301
545 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
546 #elif LIBCURL_VERSION_NUM >= 0x071101
547 curl_easy_setopt(result, CURLOPT_POST301, 1);
548 #endif
549 #if LIBCURL_VERSION_NUM >= 0x071304
550 if (is_transport_allowed("http"))
551 allowed_protocols |= CURLPROTO_HTTP;
552 if (is_transport_allowed("https"))
553 allowed_protocols |= CURLPROTO_HTTPS;
554 if (is_transport_allowed("ftp"))
555 allowed_protocols |= CURLPROTO_FTP;
556 if (is_transport_allowed("ftps"))
557 allowed_protocols |= CURLPROTO_FTPS;
558 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
559 #else
560 if (transport_restrict_protocols())
561 warning("protocol restrictions not applied to curl redirects because\n"
562 "your curl version is too old (>= 7.19.4)");
563 #endif
565 if (getenv("GIT_CURL_VERBOSE"))
566 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
568 curl_easy_setopt(result, CURLOPT_USERAGENT,
569 user_agent ? user_agent : git_user_agent());
571 if (curl_ftp_no_epsv)
572 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
574 #ifdef CURLOPT_USE_SSL
575 if (curl_ssl_try)
576 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
577 #endif
580 * CURL also examines these variables as a fallback; but we need to query
581 * them here in order to decide whether to prompt for missing password (cf.
582 * init_curl_proxy_auth()).
584 * Unlike many other common environment variables, these are historically
585 * lowercase only. It appears that CURL did not know this and implemented
586 * only uppercase variants, which was later corrected to take both - with
587 * the exception of http_proxy, which is lowercase only also in CURL. As
588 * the lowercase versions are the historical quasi-standard, they take
589 * precedence here, as in CURL.
591 if (!curl_http_proxy) {
592 if (!strcmp(http_auth.protocol, "https")) {
593 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
594 var_override(&curl_http_proxy, getenv("https_proxy"));
595 } else {
596 var_override(&curl_http_proxy, getenv("http_proxy"));
598 if (!curl_http_proxy) {
599 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
600 var_override(&curl_http_proxy, getenv("all_proxy"));
604 if (curl_http_proxy) {
605 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
606 #if LIBCURL_VERSION_NUM >= 0x071800
607 if (starts_with(curl_http_proxy, "socks5"))
608 curl_easy_setopt(result,
609 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
610 else if (starts_with(curl_http_proxy, "socks4a"))
611 curl_easy_setopt(result,
612 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
613 else if (starts_with(curl_http_proxy, "socks"))
614 curl_easy_setopt(result,
615 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
616 #endif
617 if (strstr(curl_http_proxy, "://"))
618 credential_from_url(&proxy_auth, curl_http_proxy);
619 else {
620 struct strbuf url = STRBUF_INIT;
621 strbuf_addf(&url, "http://%s", curl_http_proxy);
622 credential_from_url(&proxy_auth, url.buf);
623 strbuf_release(&url);
626 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
628 init_curl_proxy_auth(result);
630 set_curl_keepalive(result);
632 return result;
635 static void set_from_env(const char **var, const char *envname)
637 const char *val = getenv(envname);
638 if (val)
639 *var = val;
642 void http_init(struct remote *remote, const char *url, int proactive_auth)
644 char *low_speed_limit;
645 char *low_speed_time;
646 char *normalized_url;
647 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
649 config.section = "http";
650 config.key = NULL;
651 config.collect_fn = http_options;
652 config.cascade_fn = git_default_config;
653 config.cb = NULL;
655 http_is_verbose = 0;
656 normalized_url = url_normalize(url, &config.url);
658 git_config(urlmatch_config_entry, &config);
659 free(normalized_url);
661 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
662 die("curl_global_init failed");
664 http_proactive_auth = proactive_auth;
666 if (remote && remote->http_proxy)
667 curl_http_proxy = xstrdup(remote->http_proxy);
669 if (remote)
670 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
672 pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
673 no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
675 #ifdef USE_CURL_MULTI
677 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
678 if (http_max_requests != NULL)
679 max_requests = atoi(http_max_requests);
682 curlm = curl_multi_init();
683 if (!curlm)
684 die("curl_multi_init failed");
685 #endif
687 if (getenv("GIT_SSL_NO_VERIFY"))
688 curl_ssl_verify = 0;
690 set_from_env(&ssl_cert, "GIT_SSL_CERT");
691 #if LIBCURL_VERSION_NUM >= 0x070903
692 set_from_env(&ssl_key, "GIT_SSL_KEY");
693 #endif
694 #if LIBCURL_VERSION_NUM >= 0x070908
695 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
696 #endif
697 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
699 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
701 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
702 if (low_speed_limit != NULL)
703 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
704 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
705 if (low_speed_time != NULL)
706 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
708 if (curl_ssl_verify == -1)
709 curl_ssl_verify = 1;
711 curl_session_count = 0;
712 #ifdef USE_CURL_MULTI
713 if (max_requests < 1)
714 max_requests = DEFAULT_MAX_REQUESTS;
715 #endif
717 if (getenv("GIT_CURL_FTP_NO_EPSV"))
718 curl_ftp_no_epsv = 1;
720 if (url) {
721 credential_from_url(&http_auth, url);
722 if (!ssl_cert_password_required &&
723 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
724 starts_with(url, "https://"))
725 ssl_cert_password_required = 1;
728 #ifndef NO_CURL_EASY_DUPHANDLE
729 curl_default = get_curl_handle();
730 #endif
733 void http_cleanup(void)
735 struct active_request_slot *slot = active_queue_head;
737 while (slot != NULL) {
738 struct active_request_slot *next = slot->next;
739 if (slot->curl != NULL) {
740 #ifdef USE_CURL_MULTI
741 curl_multi_remove_handle(curlm, slot->curl);
742 #endif
743 curl_easy_cleanup(slot->curl);
745 free(slot);
746 slot = next;
748 active_queue_head = NULL;
750 #ifndef NO_CURL_EASY_DUPHANDLE
751 curl_easy_cleanup(curl_default);
752 #endif
754 #ifdef USE_CURL_MULTI
755 curl_multi_cleanup(curlm);
756 #endif
757 curl_global_cleanup();
759 curl_slist_free_all(pragma_header);
760 pragma_header = NULL;
762 curl_slist_free_all(no_pragma_header);
763 no_pragma_header = NULL;
765 if (curl_http_proxy) {
766 free((void *)curl_http_proxy);
767 curl_http_proxy = NULL;
770 if (proxy_auth.password) {
771 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
772 free(proxy_auth.password);
773 proxy_auth.password = NULL;
776 free((void *)curl_proxyuserpwd);
777 curl_proxyuserpwd = NULL;
779 free((void *)http_proxy_authmethod);
780 http_proxy_authmethod = NULL;
782 if (cert_auth.password != NULL) {
783 memset(cert_auth.password, 0, strlen(cert_auth.password));
784 free(cert_auth.password);
785 cert_auth.password = NULL;
787 ssl_cert_password_required = 0;
789 free(cached_accept_language);
790 cached_accept_language = NULL;
793 struct active_request_slot *get_active_slot(void)
795 struct active_request_slot *slot = active_queue_head;
796 struct active_request_slot *newslot;
798 #ifdef USE_CURL_MULTI
799 int num_transfers;
801 /* Wait for a slot to open up if the queue is full */
802 while (active_requests >= max_requests) {
803 curl_multi_perform(curlm, &num_transfers);
804 if (num_transfers < active_requests)
805 process_curl_messages();
807 #endif
809 while (slot != NULL && slot->in_use)
810 slot = slot->next;
812 if (slot == NULL) {
813 newslot = xmalloc(sizeof(*newslot));
814 newslot->curl = NULL;
815 newslot->in_use = 0;
816 newslot->next = NULL;
818 slot = active_queue_head;
819 if (slot == NULL) {
820 active_queue_head = newslot;
821 } else {
822 while (slot->next != NULL)
823 slot = slot->next;
824 slot->next = newslot;
826 slot = newslot;
829 if (slot->curl == NULL) {
830 #ifdef NO_CURL_EASY_DUPHANDLE
831 slot->curl = get_curl_handle();
832 #else
833 slot->curl = curl_easy_duphandle(curl_default);
834 #endif
835 curl_session_count++;
838 active_requests++;
839 slot->in_use = 1;
840 slot->results = NULL;
841 slot->finished = NULL;
842 slot->callback_data = NULL;
843 slot->callback_func = NULL;
844 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
845 if (curl_save_cookies)
846 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
847 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
848 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
849 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
850 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
851 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
852 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
853 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
854 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
855 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
856 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
858 #if LIBCURL_VERSION_NUM >= 0x070a08
859 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
860 #endif
861 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
862 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
863 #endif
864 if (http_auth.password || curl_empty_auth)
865 init_curl_http_auth(slot->curl);
867 return slot;
870 int start_active_slot(struct active_request_slot *slot)
872 #ifdef USE_CURL_MULTI
873 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
874 int num_transfers;
876 if (curlm_result != CURLM_OK &&
877 curlm_result != CURLM_CALL_MULTI_PERFORM) {
878 active_requests--;
879 slot->in_use = 0;
880 return 0;
884 * We know there must be something to do, since we just added
885 * something.
887 curl_multi_perform(curlm, &num_transfers);
888 #endif
889 return 1;
892 #ifdef USE_CURL_MULTI
893 struct fill_chain {
894 void *data;
895 int (*fill)(void *);
896 struct fill_chain *next;
899 static struct fill_chain *fill_cfg;
901 void add_fill_function(void *data, int (*fill)(void *))
903 struct fill_chain *new = xmalloc(sizeof(*new));
904 struct fill_chain **linkp = &fill_cfg;
905 new->data = data;
906 new->fill = fill;
907 new->next = NULL;
908 while (*linkp)
909 linkp = &(*linkp)->next;
910 *linkp = new;
913 void fill_active_slots(void)
915 struct active_request_slot *slot = active_queue_head;
917 while (active_requests < max_requests) {
918 struct fill_chain *fill;
919 for (fill = fill_cfg; fill; fill = fill->next)
920 if (fill->fill(fill->data))
921 break;
923 if (!fill)
924 break;
927 while (slot != NULL) {
928 if (!slot->in_use && slot->curl != NULL
929 && curl_session_count > min_curl_sessions) {
930 curl_easy_cleanup(slot->curl);
931 slot->curl = NULL;
932 curl_session_count--;
934 slot = slot->next;
938 void step_active_slots(void)
940 int num_transfers;
941 CURLMcode curlm_result;
943 do {
944 curlm_result = curl_multi_perform(curlm, &num_transfers);
945 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
946 if (num_transfers < active_requests) {
947 process_curl_messages();
948 fill_active_slots();
951 #endif
953 void run_active_slot(struct active_request_slot *slot)
955 #ifdef USE_CURL_MULTI
956 fd_set readfds;
957 fd_set writefds;
958 fd_set excfds;
959 int max_fd;
960 struct timeval select_timeout;
961 int finished = 0;
963 slot->finished = &finished;
964 while (!finished) {
965 step_active_slots();
967 if (slot->in_use) {
968 #if LIBCURL_VERSION_NUM >= 0x070f04
969 long curl_timeout;
970 curl_multi_timeout(curlm, &curl_timeout);
971 if (curl_timeout == 0) {
972 continue;
973 } else if (curl_timeout == -1) {
974 select_timeout.tv_sec = 0;
975 select_timeout.tv_usec = 50000;
976 } else {
977 select_timeout.tv_sec = curl_timeout / 1000;
978 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
980 #else
981 select_timeout.tv_sec = 0;
982 select_timeout.tv_usec = 50000;
983 #endif
985 max_fd = -1;
986 FD_ZERO(&readfds);
987 FD_ZERO(&writefds);
988 FD_ZERO(&excfds);
989 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
992 * It can happen that curl_multi_timeout returns a pathologically
993 * long timeout when curl_multi_fdset returns no file descriptors
994 * to read. See commit message for more details.
996 if (max_fd < 0 &&
997 (select_timeout.tv_sec > 0 ||
998 select_timeout.tv_usec > 50000)) {
999 select_timeout.tv_sec = 0;
1000 select_timeout.tv_usec = 50000;
1003 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1006 #else
1007 while (slot->in_use) {
1008 slot->curl_result = curl_easy_perform(slot->curl);
1009 finish_active_slot(slot);
1011 #endif
1014 static void release_active_slot(struct active_request_slot *slot)
1016 closedown_active_slot(slot);
1017 if (slot->curl && curl_session_count > min_curl_sessions) {
1018 #ifdef USE_CURL_MULTI
1019 curl_multi_remove_handle(curlm, slot->curl);
1020 #endif
1021 curl_easy_cleanup(slot->curl);
1022 slot->curl = NULL;
1023 curl_session_count--;
1025 #ifdef USE_CURL_MULTI
1026 fill_active_slots();
1027 #endif
1030 void finish_all_active_slots(void)
1032 struct active_request_slot *slot = active_queue_head;
1034 while (slot != NULL)
1035 if (slot->in_use) {
1036 run_active_slot(slot);
1037 slot = active_queue_head;
1038 } else {
1039 slot = slot->next;
1043 /* Helpers for modifying and creating URLs */
1044 static inline int needs_quote(int ch)
1046 if (((ch >= 'A') && (ch <= 'Z'))
1047 || ((ch >= 'a') && (ch <= 'z'))
1048 || ((ch >= '0') && (ch <= '9'))
1049 || (ch == '/')
1050 || (ch == '-')
1051 || (ch == '.'))
1052 return 0;
1053 return 1;
1056 static char *quote_ref_url(const char *base, const char *ref)
1058 struct strbuf buf = STRBUF_INIT;
1059 const char *cp;
1060 int ch;
1062 end_url_with_slash(&buf, base);
1064 for (cp = ref; (ch = *cp) != 0; cp++)
1065 if (needs_quote(ch))
1066 strbuf_addf(&buf, "%%%02x", ch);
1067 else
1068 strbuf_addch(&buf, *cp);
1070 return strbuf_detach(&buf, NULL);
1073 void append_remote_object_url(struct strbuf *buf, const char *url,
1074 const char *hex,
1075 int only_two_digit_prefix)
1077 end_url_with_slash(buf, url);
1079 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1080 if (!only_two_digit_prefix)
1081 strbuf_addf(buf, "%s", hex+2);
1084 char *get_remote_object_url(const char *url, const char *hex,
1085 int only_two_digit_prefix)
1087 struct strbuf buf = STRBUF_INIT;
1088 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1089 return strbuf_detach(&buf, NULL);
1092 static int handle_curl_result(struct slot_results *results)
1095 * If we see a failing http code with CURLE_OK, we have turned off
1096 * FAILONERROR (to keep the server's custom error response), and should
1097 * translate the code into failure here.
1099 if (results->curl_result == CURLE_OK &&
1100 results->http_code >= 400) {
1101 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1103 * Normally curl will already have put the "reason phrase"
1104 * from the server into curl_errorstr; unfortunately without
1105 * FAILONERROR it is lost, so we can give only the numeric
1106 * status code.
1108 snprintf(curl_errorstr, sizeof(curl_errorstr),
1109 "The requested URL returned error: %ld",
1110 results->http_code);
1113 if (results->curl_result == CURLE_OK) {
1114 credential_approve(&http_auth);
1115 if (proxy_auth.password)
1116 credential_approve(&proxy_auth);
1117 return HTTP_OK;
1118 } else if (missing_target(results))
1119 return HTTP_MISSING_TARGET;
1120 else if (results->http_code == 401) {
1121 if (http_auth.username && http_auth.password) {
1122 credential_reject(&http_auth);
1123 return HTTP_NOAUTH;
1124 } else {
1125 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1126 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1127 #endif
1128 return HTTP_REAUTH;
1130 } else {
1131 if (results->http_connectcode == 407)
1132 credential_reject(&proxy_auth);
1133 #if LIBCURL_VERSION_NUM >= 0x070c00
1134 if (!curl_errorstr[0])
1135 strlcpy(curl_errorstr,
1136 curl_easy_strerror(results->curl_result),
1137 sizeof(curl_errorstr));
1138 #endif
1139 return HTTP_ERROR;
1143 int run_one_slot(struct active_request_slot *slot,
1144 struct slot_results *results)
1146 slot->results = results;
1147 if (!start_active_slot(slot)) {
1148 snprintf(curl_errorstr, sizeof(curl_errorstr),
1149 "failed to start HTTP request");
1150 return HTTP_START_FAILED;
1153 run_active_slot(slot);
1154 return handle_curl_result(results);
1157 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1159 char *ptr;
1160 CURLcode ret;
1162 strbuf_reset(buf);
1163 ret = curl_easy_getinfo(curl, info, &ptr);
1164 if (!ret && ptr)
1165 strbuf_addstr(buf, ptr);
1166 return ret;
1170 * Check for and extract a content-type parameter. "raw"
1171 * should be positioned at the start of the potential
1172 * parameter, with any whitespace already removed.
1174 * "name" is the name of the parameter. The value is appended
1175 * to "out".
1177 static int extract_param(const char *raw, const char *name,
1178 struct strbuf *out)
1180 size_t len = strlen(name);
1182 if (strncasecmp(raw, name, len))
1183 return -1;
1184 raw += len;
1186 if (*raw != '=')
1187 return -1;
1188 raw++;
1190 while (*raw && !isspace(*raw) && *raw != ';')
1191 strbuf_addch(out, *raw++);
1192 return 0;
1196 * Extract a normalized version of the content type, with any
1197 * spaces suppressed, all letters lowercased, and no trailing ";"
1198 * or parameters.
1200 * Note that we will silently remove even invalid whitespace. For
1201 * example, "text / plain" is specifically forbidden by RFC 2616,
1202 * but "text/plain" is the only reasonable output, and this keeps
1203 * our code simple.
1205 * If the "charset" argument is not NULL, store the value of any
1206 * charset parameter there.
1208 * Example:
1209 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1210 * "text / plain" -> "text/plain"
1212 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1213 struct strbuf *charset)
1215 const char *p;
1217 strbuf_reset(type);
1218 strbuf_grow(type, raw->len);
1219 for (p = raw->buf; *p; p++) {
1220 if (isspace(*p))
1221 continue;
1222 if (*p == ';') {
1223 p++;
1224 break;
1226 strbuf_addch(type, tolower(*p));
1229 if (!charset)
1230 return;
1232 strbuf_reset(charset);
1233 while (*p) {
1234 while (isspace(*p) || *p == ';')
1235 p++;
1236 if (!extract_param(p, "charset", charset))
1237 return;
1238 while (*p && !isspace(*p))
1239 p++;
1242 if (!charset->len && starts_with(type->buf, "text/"))
1243 strbuf_addstr(charset, "ISO-8859-1");
1246 static void write_accept_language(struct strbuf *buf)
1249 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1250 * that, q-value will be smaller than 0.001, the minimum q-value the
1251 * HTTP specification allows. See
1252 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1254 const int MAX_DECIMAL_PLACES = 3;
1255 const int MAX_LANGUAGE_TAGS = 1000;
1256 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1257 char **language_tags = NULL;
1258 int num_langs = 0;
1259 const char *s = get_preferred_languages();
1260 int i;
1261 struct strbuf tag = STRBUF_INIT;
1263 /* Don't add Accept-Language header if no language is preferred. */
1264 if (!s)
1265 return;
1268 * Split the colon-separated string of preferred languages into
1269 * language_tags array.
1271 do {
1272 /* collect language tag */
1273 for (; *s && (isalnum(*s) || *s == '_'); s++)
1274 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1276 /* skip .codeset, @modifier and any other unnecessary parts */
1277 while (*s && *s != ':')
1278 s++;
1280 if (tag.len) {
1281 num_langs++;
1282 REALLOC_ARRAY(language_tags, num_langs);
1283 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1284 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1285 break;
1287 } while (*s++);
1289 /* write Accept-Language header into buf */
1290 if (num_langs) {
1291 int last_buf_len = 0;
1292 int max_q;
1293 int decimal_places;
1294 char q_format[32];
1296 /* add '*' */
1297 REALLOC_ARRAY(language_tags, num_langs + 1);
1298 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1300 /* compute decimal_places */
1301 for (max_q = 1, decimal_places = 0;
1302 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1303 decimal_places++, max_q *= 10)
1306 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1308 strbuf_addstr(buf, "Accept-Language: ");
1310 for (i = 0; i < num_langs; i++) {
1311 if (i > 0)
1312 strbuf_addstr(buf, ", ");
1314 strbuf_addstr(buf, language_tags[i]);
1316 if (i > 0)
1317 strbuf_addf(buf, q_format, max_q - i);
1319 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1320 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1321 break;
1324 last_buf_len = buf->len;
1328 /* free language tags -- last one is a static '*' */
1329 for (i = 0; i < num_langs - 1; i++)
1330 free(language_tags[i]);
1331 free(language_tags);
1335 * Get an Accept-Language header which indicates user's preferred languages.
1337 * Examples:
1338 * LANGUAGE= -> ""
1339 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1340 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1341 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1342 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1343 * LANGUAGE= LANG=C -> ""
1345 static const char *get_accept_language(void)
1347 if (!cached_accept_language) {
1348 struct strbuf buf = STRBUF_INIT;
1349 write_accept_language(&buf);
1350 if (buf.len > 0)
1351 cached_accept_language = strbuf_detach(&buf, NULL);
1354 return cached_accept_language;
1357 static void http_opt_request_remainder(CURL *curl, off_t pos)
1359 char buf[128];
1360 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1361 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1364 /* http_request() targets */
1365 #define HTTP_REQUEST_STRBUF 0
1366 #define HTTP_REQUEST_FILE 1
1368 static int http_request(const char *url,
1369 void *result, int target,
1370 const struct http_get_options *options)
1372 struct active_request_slot *slot;
1373 struct slot_results results;
1374 struct curl_slist *headers = NULL;
1375 struct strbuf buf = STRBUF_INIT;
1376 const char *accept_language;
1377 int ret;
1379 slot = get_active_slot();
1380 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1382 if (result == NULL) {
1383 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1384 } else {
1385 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1386 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1388 if (target == HTTP_REQUEST_FILE) {
1389 off_t posn = ftello(result);
1390 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1391 fwrite);
1392 if (posn > 0)
1393 http_opt_request_remainder(slot->curl, posn);
1394 } else
1395 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1396 fwrite_buffer);
1399 accept_language = get_accept_language();
1401 if (accept_language)
1402 headers = curl_slist_append(headers, accept_language);
1404 strbuf_addstr(&buf, "Pragma:");
1405 if (options && options->no_cache)
1406 strbuf_addstr(&buf, " no-cache");
1407 if (options && options->keep_error)
1408 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1410 headers = curl_slist_append(headers, buf.buf);
1412 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1413 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1414 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1416 ret = run_one_slot(slot, &results);
1418 if (options && options->content_type) {
1419 struct strbuf raw = STRBUF_INIT;
1420 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1421 extract_content_type(&raw, options->content_type,
1422 options->charset);
1423 strbuf_release(&raw);
1426 if (options && options->effective_url)
1427 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1428 options->effective_url);
1430 curl_slist_free_all(headers);
1431 strbuf_release(&buf);
1433 return ret;
1437 * Update the "base" url to a more appropriate value, as deduced by
1438 * redirects seen when requesting a URL starting with "url".
1440 * The "asked" parameter is a URL that we asked curl to access, and must begin
1441 * with "base".
1443 * The "got" parameter is the URL that curl reported to us as where we ended
1444 * up.
1446 * Returns 1 if we updated the base url, 0 otherwise.
1448 * Our basic strategy is to compare "base" and "asked" to find the bits
1449 * specific to our request. We then strip those bits off of "got" to yield the
1450 * new base. So for example, if our base is "http://example.com/foo.git",
1451 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1452 * with "https://other.example.com/foo.git/info/refs". We would want the
1453 * new URL to become "https://other.example.com/foo.git".
1455 * Note that this assumes a sane redirect scheme. It's entirely possible
1456 * in the example above to end up at a URL that does not even end in
1457 * "info/refs". In such a case we simply punt, as there is not much we can
1458 * do (and such a scheme is unlikely to represent a real git repository,
1459 * which means we are likely about to abort anyway).
1461 static int update_url_from_redirect(struct strbuf *base,
1462 const char *asked,
1463 const struct strbuf *got)
1465 const char *tail;
1466 size_t tail_len;
1468 if (!strcmp(asked, got->buf))
1469 return 0;
1471 if (!skip_prefix(asked, base->buf, &tail))
1472 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1473 asked, base->buf);
1475 tail_len = strlen(tail);
1477 if (got->len < tail_len ||
1478 strcmp(tail, got->buf + got->len - tail_len))
1479 return 0; /* insane redirect scheme */
1481 strbuf_reset(base);
1482 strbuf_add(base, got->buf, got->len - tail_len);
1483 return 1;
1486 static int http_request_reauth(const char *url,
1487 void *result, int target,
1488 struct http_get_options *options)
1490 int ret = http_request(url, result, target, options);
1492 if (options && options->effective_url && options->base_url) {
1493 if (update_url_from_redirect(options->base_url,
1494 url, options->effective_url)) {
1495 credential_from_url(&http_auth, options->base_url->buf);
1496 url = options->effective_url->buf;
1500 if (ret != HTTP_REAUTH)
1501 return ret;
1504 * If we are using KEEP_ERROR, the previous request may have
1505 * put cruft into our output stream; we should clear it out before
1506 * making our next request. We only know how to do this for
1507 * the strbuf case, but that is enough to satisfy current callers.
1509 if (options && options->keep_error) {
1510 switch (target) {
1511 case HTTP_REQUEST_STRBUF:
1512 strbuf_reset(result);
1513 break;
1514 default:
1515 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1519 credential_fill(&http_auth);
1521 return http_request(url, result, target, options);
1524 int http_get_strbuf(const char *url,
1525 struct strbuf *result,
1526 struct http_get_options *options)
1528 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1532 * Downloads a URL and stores the result in the given file.
1534 * If a previous interrupted download is detected (i.e. a previous temporary
1535 * file is still around) the download is resumed.
1537 static int http_get_file(const char *url, const char *filename,
1538 struct http_get_options *options)
1540 int ret;
1541 struct strbuf tmpfile = STRBUF_INIT;
1542 FILE *result;
1544 strbuf_addf(&tmpfile, "%s.temp", filename);
1545 result = fopen(tmpfile.buf, "a");
1546 if (!result) {
1547 error("Unable to open local file %s", tmpfile.buf);
1548 ret = HTTP_ERROR;
1549 goto cleanup;
1552 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1553 fclose(result);
1555 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1556 ret = HTTP_ERROR;
1557 cleanup:
1558 strbuf_release(&tmpfile);
1559 return ret;
1562 int http_fetch_ref(const char *base, struct ref *ref)
1564 struct http_get_options options = {0};
1565 char *url;
1566 struct strbuf buffer = STRBUF_INIT;
1567 int ret = -1;
1569 options.no_cache = 1;
1571 url = quote_ref_url(base, ref->name);
1572 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1573 strbuf_rtrim(&buffer);
1574 if (buffer.len == 40)
1575 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1576 else if (starts_with(buffer.buf, "ref: ")) {
1577 ref->symref = xstrdup(buffer.buf + 5);
1578 ret = 0;
1582 strbuf_release(&buffer);
1583 free(url);
1584 return ret;
1587 /* Helpers for fetching packs */
1588 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1590 char *url, *tmp;
1591 struct strbuf buf = STRBUF_INIT;
1593 if (http_is_verbose)
1594 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1596 end_url_with_slash(&buf, base_url);
1597 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1598 url = strbuf_detach(&buf, NULL);
1600 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1601 tmp = strbuf_detach(&buf, NULL);
1603 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1604 error("Unable to get pack index %s", url);
1605 free(tmp);
1606 tmp = NULL;
1609 free(url);
1610 return tmp;
1613 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1614 unsigned char *sha1, const char *base_url)
1616 struct packed_git *new_pack;
1617 char *tmp_idx = NULL;
1618 int ret;
1620 if (has_pack_index(sha1)) {
1621 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1622 if (!new_pack)
1623 return -1; /* parse_pack_index() already issued error message */
1624 goto add_pack;
1627 tmp_idx = fetch_pack_index(sha1, base_url);
1628 if (!tmp_idx)
1629 return -1;
1631 new_pack = parse_pack_index(sha1, tmp_idx);
1632 if (!new_pack) {
1633 unlink(tmp_idx);
1634 free(tmp_idx);
1636 return -1; /* parse_pack_index() already issued error message */
1639 ret = verify_pack_index(new_pack);
1640 if (!ret) {
1641 close_pack_index(new_pack);
1642 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1644 free(tmp_idx);
1645 if (ret)
1646 return -1;
1648 add_pack:
1649 new_pack->next = *packs_head;
1650 *packs_head = new_pack;
1651 return 0;
1654 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1656 struct http_get_options options = {0};
1657 int ret = 0, i = 0;
1658 char *url, *data;
1659 struct strbuf buf = STRBUF_INIT;
1660 unsigned char sha1[20];
1662 end_url_with_slash(&buf, base_url);
1663 strbuf_addstr(&buf, "objects/info/packs");
1664 url = strbuf_detach(&buf, NULL);
1666 options.no_cache = 1;
1667 ret = http_get_strbuf(url, &buf, &options);
1668 if (ret != HTTP_OK)
1669 goto cleanup;
1671 data = buf.buf;
1672 while (i < buf.len) {
1673 switch (data[i]) {
1674 case 'P':
1675 i++;
1676 if (i + 52 <= buf.len &&
1677 starts_with(data + i, " pack-") &&
1678 starts_with(data + i + 46, ".pack\n")) {
1679 get_sha1_hex(data + i + 6, sha1);
1680 fetch_and_setup_pack_index(packs_head, sha1,
1681 base_url);
1682 i += 51;
1683 break;
1685 default:
1686 while (i < buf.len && data[i] != '\n')
1687 i++;
1689 i++;
1692 cleanup:
1693 free(url);
1694 return ret;
1697 void release_http_pack_request(struct http_pack_request *preq)
1699 if (preq->packfile != NULL) {
1700 fclose(preq->packfile);
1701 preq->packfile = NULL;
1703 preq->slot = NULL;
1704 free(preq->url);
1705 free(preq);
1708 int finish_http_pack_request(struct http_pack_request *preq)
1710 struct packed_git **lst;
1711 struct packed_git *p = preq->target;
1712 char *tmp_idx;
1713 size_t len;
1714 struct child_process ip = CHILD_PROCESS_INIT;
1715 const char *ip_argv[8];
1717 close_pack_index(p);
1719 fclose(preq->packfile);
1720 preq->packfile = NULL;
1722 lst = preq->lst;
1723 while (*lst != p)
1724 lst = &((*lst)->next);
1725 *lst = (*lst)->next;
1727 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1728 die("BUG: pack tmpfile does not end in .pack.temp?");
1729 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
1731 ip_argv[0] = "index-pack";
1732 ip_argv[1] = "-o";
1733 ip_argv[2] = tmp_idx;
1734 ip_argv[3] = preq->tmpfile;
1735 ip_argv[4] = NULL;
1737 ip.argv = ip_argv;
1738 ip.git_cmd = 1;
1739 ip.no_stdin = 1;
1740 ip.no_stdout = 1;
1742 if (run_command(&ip)) {
1743 unlink(preq->tmpfile);
1744 unlink(tmp_idx);
1745 free(tmp_idx);
1746 return -1;
1749 unlink(sha1_pack_index_name(p->sha1));
1751 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1752 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1753 free(tmp_idx);
1754 return -1;
1757 install_packed_git(p);
1758 free(tmp_idx);
1759 return 0;
1762 struct http_pack_request *new_http_pack_request(
1763 struct packed_git *target, const char *base_url)
1765 off_t prev_posn = 0;
1766 struct strbuf buf = STRBUF_INIT;
1767 struct http_pack_request *preq;
1769 preq = xcalloc(1, sizeof(*preq));
1770 preq->target = target;
1772 end_url_with_slash(&buf, base_url);
1773 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1774 sha1_to_hex(target->sha1));
1775 preq->url = strbuf_detach(&buf, NULL);
1777 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1778 sha1_pack_name(target->sha1));
1779 preq->packfile = fopen(preq->tmpfile, "a");
1780 if (!preq->packfile) {
1781 error("Unable to open local file %s for pack",
1782 preq->tmpfile);
1783 goto abort;
1786 preq->slot = get_active_slot();
1787 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1788 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1789 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1790 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1791 no_pragma_header);
1794 * If there is data present from a previous transfer attempt,
1795 * resume where it left off
1797 prev_posn = ftello(preq->packfile);
1798 if (prev_posn>0) {
1799 if (http_is_verbose)
1800 fprintf(stderr,
1801 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1802 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
1803 http_opt_request_remainder(preq->slot->curl, prev_posn);
1806 return preq;
1808 abort:
1809 free(preq->url);
1810 free(preq);
1811 return NULL;
1814 /* Helpers for fetching objects (loose) */
1815 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1816 void *data)
1818 unsigned char expn[4096];
1819 size_t size = eltsize * nmemb;
1820 int posn = 0;
1821 struct http_object_request *freq =
1822 (struct http_object_request *)data;
1823 do {
1824 ssize_t retval = xwrite(freq->localfile,
1825 (char *) ptr + posn, size - posn);
1826 if (retval < 0)
1827 return posn;
1828 posn += retval;
1829 } while (posn < size);
1831 freq->stream.avail_in = size;
1832 freq->stream.next_in = (void *)ptr;
1833 do {
1834 freq->stream.next_out = expn;
1835 freq->stream.avail_out = sizeof(expn);
1836 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1837 git_SHA1_Update(&freq->c, expn,
1838 sizeof(expn) - freq->stream.avail_out);
1839 } while (freq->stream.avail_in && freq->zret == Z_OK);
1840 return size;
1843 struct http_object_request *new_http_object_request(const char *base_url,
1844 unsigned char *sha1)
1846 char *hex = sha1_to_hex(sha1);
1847 const char *filename;
1848 char prevfile[PATH_MAX];
1849 int prevlocal;
1850 char prev_buf[PREV_BUF_SIZE];
1851 ssize_t prev_read = 0;
1852 off_t prev_posn = 0;
1853 struct http_object_request *freq;
1855 freq = xcalloc(1, sizeof(*freq));
1856 hashcpy(freq->sha1, sha1);
1857 freq->localfile = -1;
1859 filename = sha1_file_name(sha1);
1860 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1861 "%s.temp", filename);
1863 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1864 unlink_or_warn(prevfile);
1865 rename(freq->tmpfile, prevfile);
1866 unlink_or_warn(freq->tmpfile);
1868 if (freq->localfile != -1)
1869 error("fd leakage in start: %d", freq->localfile);
1870 freq->localfile = open(freq->tmpfile,
1871 O_WRONLY | O_CREAT | O_EXCL, 0666);
1873 * This could have failed due to the "lazy directory creation";
1874 * try to mkdir the last path component.
1876 if (freq->localfile < 0 && errno == ENOENT) {
1877 char *dir = strrchr(freq->tmpfile, '/');
1878 if (dir) {
1879 *dir = 0;
1880 mkdir(freq->tmpfile, 0777);
1881 *dir = '/';
1883 freq->localfile = open(freq->tmpfile,
1884 O_WRONLY | O_CREAT | O_EXCL, 0666);
1887 if (freq->localfile < 0) {
1888 error("Couldn't create temporary file %s: %s",
1889 freq->tmpfile, strerror(errno));
1890 goto abort;
1893 git_inflate_init(&freq->stream);
1895 git_SHA1_Init(&freq->c);
1897 freq->url = get_remote_object_url(base_url, hex, 0);
1900 * If a previous temp file is present, process what was already
1901 * fetched.
1903 prevlocal = open(prevfile, O_RDONLY);
1904 if (prevlocal != -1) {
1905 do {
1906 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1907 if (prev_read>0) {
1908 if (fwrite_sha1_file(prev_buf,
1910 prev_read,
1911 freq) == prev_read) {
1912 prev_posn += prev_read;
1913 } else {
1914 prev_read = -1;
1917 } while (prev_read > 0);
1918 close(prevlocal);
1920 unlink_or_warn(prevfile);
1923 * Reset inflate/SHA1 if there was an error reading the previous temp
1924 * file; also rewind to the beginning of the local file.
1926 if (prev_read == -1) {
1927 memset(&freq->stream, 0, sizeof(freq->stream));
1928 git_inflate_init(&freq->stream);
1929 git_SHA1_Init(&freq->c);
1930 if (prev_posn>0) {
1931 prev_posn = 0;
1932 lseek(freq->localfile, 0, SEEK_SET);
1933 if (ftruncate(freq->localfile, 0) < 0) {
1934 error("Couldn't truncate temporary file %s: %s",
1935 freq->tmpfile, strerror(errno));
1936 goto abort;
1941 freq->slot = get_active_slot();
1943 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1944 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1945 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1946 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1947 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1950 * If we have successfully processed data from a previous fetch
1951 * attempt, only fetch the data we don't already have.
1953 if (prev_posn>0) {
1954 if (http_is_verbose)
1955 fprintf(stderr,
1956 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
1957 hex, (uintmax_t)prev_posn);
1958 http_opt_request_remainder(freq->slot->curl, prev_posn);
1961 return freq;
1963 abort:
1964 free(freq->url);
1965 free(freq);
1966 return NULL;
1969 void process_http_object_request(struct http_object_request *freq)
1971 if (freq->slot == NULL)
1972 return;
1973 freq->curl_result = freq->slot->curl_result;
1974 freq->http_code = freq->slot->http_code;
1975 freq->slot = NULL;
1978 int finish_http_object_request(struct http_object_request *freq)
1980 struct stat st;
1982 close(freq->localfile);
1983 freq->localfile = -1;
1985 process_http_object_request(freq);
1987 if (freq->http_code == 416) {
1988 warning("requested range invalid; we may already have all the data.");
1989 } else if (freq->curl_result != CURLE_OK) {
1990 if (stat(freq->tmpfile, &st) == 0)
1991 if (st.st_size == 0)
1992 unlink_or_warn(freq->tmpfile);
1993 return -1;
1996 git_inflate_end(&freq->stream);
1997 git_SHA1_Final(freq->real_sha1, &freq->c);
1998 if (freq->zret != Z_STREAM_END) {
1999 unlink_or_warn(freq->tmpfile);
2000 return -1;
2002 if (hashcmp(freq->sha1, freq->real_sha1)) {
2003 unlink_or_warn(freq->tmpfile);
2004 return -1;
2006 freq->rename =
2007 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2009 return freq->rename;
2012 void abort_http_object_request(struct http_object_request *freq)
2014 unlink_or_warn(freq->tmpfile);
2016 release_http_object_request(freq);
2019 void release_http_object_request(struct http_object_request *freq)
2021 if (freq->localfile != -1) {
2022 close(freq->localfile);
2023 freq->localfile = -1;
2025 if (freq->url != NULL) {
2026 free(freq->url);
2027 freq->url = NULL;
2029 if (freq->slot != NULL) {
2030 freq->slot->callback_func = NULL;
2031 freq->slot->callback_data = NULL;
2032 release_active_slot(freq->slot);
2033 freq->slot = NULL;