http: fix an unused variable warning for 'curl_no_proxy'
[git/gitster.git] / http.c
blobb930c0e628594eb6724ffeeae05fc705372fba0b
1 #include "git-compat-util.h"
2 #include "http.h"
3 #include "config.h"
4 #include "pack.h"
5 #include "sideband.h"
6 #include "run-command.h"
7 #include "url.h"
8 #include "urlmatch.h"
9 #include "credential.h"
10 #include "version.h"
11 #include "pkt-line.h"
12 #include "gettext.h"
13 #include "transport.h"
14 #include "packfile.h"
15 #include "protocol.h"
17 static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
18 #if LIBCURL_VERSION_NUM >= 0x070a08
19 long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
20 #else
21 long int git_curl_ipresolve;
22 #endif
23 int active_requests;
24 int http_is_verbose;
25 ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
27 #if LIBCURL_VERSION_NUM >= 0x070a06
28 #define LIBCURL_CAN_HANDLE_AUTH_ANY
29 #endif
31 static int min_curl_sessions = 1;
32 static int curl_session_count;
33 #ifdef USE_CURL_MULTI
34 static int max_requests = -1;
35 static CURLM *curlm;
36 #endif
37 #ifndef NO_CURL_EASY_DUPHANDLE
38 static CURL *curl_default;
39 #endif
41 #define PREV_BUF_SIZE 4096
43 char curl_errorstr[CURL_ERROR_SIZE];
45 static int curl_ssl_verify = -1;
46 static int curl_ssl_try;
47 static const char *ssl_cert;
48 static const char *ssl_cipherlist;
49 static const char *ssl_version;
50 static struct {
51 const char *name;
52 long ssl_version;
53 } sslversions[] = {
54 { "sslv2", CURL_SSLVERSION_SSLv2 },
55 { "sslv3", CURL_SSLVERSION_SSLv3 },
56 { "tlsv1", CURL_SSLVERSION_TLSv1 },
57 #if LIBCURL_VERSION_NUM >= 0x072200
58 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
59 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
60 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
61 #endif
63 #if LIBCURL_VERSION_NUM >= 0x070903
64 static const char *ssl_key;
65 #endif
66 #if LIBCURL_VERSION_NUM >= 0x070908
67 static const char *ssl_capath;
68 #endif
69 #if LIBCURL_VERSION_NUM >= 0x071304
70 static const char *curl_no_proxy;
71 #endif
72 #if LIBCURL_VERSION_NUM >= 0x072c00
73 static const char *ssl_pinnedkey;
74 #endif
75 static const char *ssl_cainfo;
76 static long curl_low_speed_limit = -1;
77 static long curl_low_speed_time = -1;
78 static int curl_ftp_no_epsv;
79 static const char *curl_http_proxy;
80 static const char *http_proxy_authmethod;
81 static struct {
82 const char *name;
83 long curlauth_param;
84 } proxy_authmethods[] = {
85 { "basic", CURLAUTH_BASIC },
86 { "digest", CURLAUTH_DIGEST },
87 { "negotiate", CURLAUTH_GSSNEGOTIATE },
88 { "ntlm", CURLAUTH_NTLM },
89 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
90 { "anyauth", CURLAUTH_ANY },
91 #endif
93 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
94 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
95 * here, too
98 #ifdef CURLGSSAPI_DELEGATION_FLAG
99 static const char *curl_deleg;
100 static struct {
101 const char *name;
102 long curl_deleg_param;
103 } curl_deleg_levels[] = {
104 { "none", CURLGSSAPI_DELEGATION_NONE },
105 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
106 { "always", CURLGSSAPI_DELEGATION_FLAG },
108 #endif
110 static struct credential proxy_auth = CREDENTIAL_INIT;
111 static const char *curl_proxyuserpwd;
112 static const char *curl_cookie_file;
113 static int curl_save_cookies;
114 struct credential http_auth = CREDENTIAL_INIT;
115 static int http_proactive_auth;
116 static const char *user_agent;
117 static int curl_empty_auth = -1;
119 enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
121 #if LIBCURL_VERSION_NUM >= 0x071700
122 /* Use CURLOPT_KEYPASSWD as is */
123 #elif LIBCURL_VERSION_NUM >= 0x070903
124 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
125 #else
126 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
127 #endif
129 static struct credential cert_auth = CREDENTIAL_INIT;
130 static int ssl_cert_password_required;
131 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
132 static unsigned long http_auth_methods = CURLAUTH_ANY;
133 static int http_auth_methods_restricted;
134 /* Modes for which empty_auth cannot actually help us. */
135 static unsigned long empty_auth_useless =
136 CURLAUTH_BASIC
137 #ifdef CURLAUTH_DIGEST_IE
138 | CURLAUTH_DIGEST_IE
139 #endif
140 | CURLAUTH_DIGEST;
141 #endif
143 static struct curl_slist *pragma_header;
144 static struct curl_slist *no_pragma_header;
145 static struct curl_slist *extra_http_headers;
147 static struct active_request_slot *active_queue_head;
149 static char *cached_accept_language;
151 size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
153 size_t size = eltsize * nmemb;
154 struct buffer *buffer = buffer_;
156 if (size > buffer->buf.len - buffer->posn)
157 size = buffer->buf.len - buffer->posn;
158 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
159 buffer->posn += size;
161 return size;
164 #ifndef NO_CURL_IOCTL
165 curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
167 struct buffer *buffer = clientp;
169 switch (cmd) {
170 case CURLIOCMD_NOP:
171 return CURLIOE_OK;
173 case CURLIOCMD_RESTARTREAD:
174 buffer->posn = 0;
175 return CURLIOE_OK;
177 default:
178 return CURLIOE_UNKNOWNCMD;
181 #endif
183 size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
185 size_t size = eltsize * nmemb;
186 struct strbuf *buffer = buffer_;
188 strbuf_add(buffer, ptr, size);
189 return size;
192 size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
194 return eltsize * nmemb;
197 static void closedown_active_slot(struct active_request_slot *slot)
199 active_requests--;
200 slot->in_use = 0;
203 static void finish_active_slot(struct active_request_slot *slot)
205 closedown_active_slot(slot);
206 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
208 if (slot->finished != NULL)
209 (*slot->finished) = 1;
211 /* Store slot results so they can be read after the slot is reused */
212 if (slot->results != NULL) {
213 slot->results->curl_result = slot->curl_result;
214 slot->results->http_code = slot->http_code;
215 #if LIBCURL_VERSION_NUM >= 0x070a08
216 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
217 &slot->results->auth_avail);
218 #else
219 slot->results->auth_avail = 0;
220 #endif
222 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
223 &slot->results->http_connectcode);
226 /* Run callback if appropriate */
227 if (slot->callback_func != NULL)
228 slot->callback_func(slot->callback_data);
231 static void xmulti_remove_handle(struct active_request_slot *slot)
233 #ifdef USE_CURL_MULTI
234 curl_multi_remove_handle(curlm, slot->curl);
235 #endif
238 #ifdef USE_CURL_MULTI
239 static void process_curl_messages(void)
241 int num_messages;
242 struct active_request_slot *slot;
243 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
245 while (curl_message != NULL) {
246 if (curl_message->msg == CURLMSG_DONE) {
247 int curl_result = curl_message->data.result;
248 slot = active_queue_head;
249 while (slot != NULL &&
250 slot->curl != curl_message->easy_handle)
251 slot = slot->next;
252 if (slot != NULL) {
253 xmulti_remove_handle(slot);
254 slot->curl_result = curl_result;
255 finish_active_slot(slot);
256 } else {
257 fprintf(stderr, "Received DONE message for unknown request!\n");
259 } else {
260 fprintf(stderr, "Unknown CURL message received: %d\n",
261 (int)curl_message->msg);
263 curl_message = curl_multi_info_read(curlm, &num_messages);
266 #endif
268 static int http_options(const char *var, const char *value, void *cb)
270 if (!strcmp("http.sslverify", var)) {
271 curl_ssl_verify = git_config_bool(var, value);
272 return 0;
274 if (!strcmp("http.sslcipherlist", var))
275 return git_config_string(&ssl_cipherlist, var, value);
276 if (!strcmp("http.sslversion", var))
277 return git_config_string(&ssl_version, var, value);
278 if (!strcmp("http.sslcert", var))
279 return git_config_pathname(&ssl_cert, var, value);
280 #if LIBCURL_VERSION_NUM >= 0x070903
281 if (!strcmp("http.sslkey", var))
282 return git_config_pathname(&ssl_key, var, value);
283 #endif
284 #if LIBCURL_VERSION_NUM >= 0x070908
285 if (!strcmp("http.sslcapath", var))
286 return git_config_pathname(&ssl_capath, var, value);
287 #endif
288 if (!strcmp("http.sslcainfo", var))
289 return git_config_pathname(&ssl_cainfo, var, value);
290 if (!strcmp("http.sslcertpasswordprotected", var)) {
291 ssl_cert_password_required = git_config_bool(var, value);
292 return 0;
294 if (!strcmp("http.ssltry", var)) {
295 curl_ssl_try = git_config_bool(var, value);
296 return 0;
298 if (!strcmp("http.minsessions", var)) {
299 min_curl_sessions = git_config_int(var, value);
300 #ifndef USE_CURL_MULTI
301 if (min_curl_sessions > 1)
302 min_curl_sessions = 1;
303 #endif
304 return 0;
306 #ifdef USE_CURL_MULTI
307 if (!strcmp("http.maxrequests", var)) {
308 max_requests = git_config_int(var, value);
309 return 0;
311 #endif
312 if (!strcmp("http.lowspeedlimit", var)) {
313 curl_low_speed_limit = (long)git_config_int(var, value);
314 return 0;
316 if (!strcmp("http.lowspeedtime", var)) {
317 curl_low_speed_time = (long)git_config_int(var, value);
318 return 0;
321 if (!strcmp("http.noepsv", var)) {
322 curl_ftp_no_epsv = git_config_bool(var, value);
323 return 0;
325 if (!strcmp("http.proxy", var))
326 return git_config_string(&curl_http_proxy, var, value);
328 if (!strcmp("http.proxyauthmethod", var))
329 return git_config_string(&http_proxy_authmethod, var, value);
331 if (!strcmp("http.cookiefile", var))
332 return git_config_pathname(&curl_cookie_file, var, value);
333 if (!strcmp("http.savecookies", var)) {
334 curl_save_cookies = git_config_bool(var, value);
335 return 0;
338 if (!strcmp("http.postbuffer", var)) {
339 http_post_buffer = git_config_ssize_t(var, value);
340 if (http_post_buffer < 0)
341 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
342 if (http_post_buffer < LARGE_PACKET_MAX)
343 http_post_buffer = LARGE_PACKET_MAX;
344 return 0;
347 if (!strcmp("http.useragent", var))
348 return git_config_string(&user_agent, var, value);
350 if (!strcmp("http.emptyauth", var)) {
351 if (value && !strcmp("auto", value))
352 curl_empty_auth = -1;
353 else
354 curl_empty_auth = git_config_bool(var, value);
355 return 0;
358 if (!strcmp("http.delegation", var)) {
359 #ifdef CURLGSSAPI_DELEGATION_FLAG
360 return git_config_string(&curl_deleg, var, value);
361 #else
362 warning(_("Delegation control is not supported with cURL < 7.22.0"));
363 return 0;
364 #endif
367 if (!strcmp("http.pinnedpubkey", var)) {
368 #if LIBCURL_VERSION_NUM >= 0x072c00
369 return git_config_pathname(&ssl_pinnedkey, var, value);
370 #else
371 warning(_("Public key pinning not supported with cURL < 7.44.0"));
372 return 0;
373 #endif
376 if (!strcmp("http.extraheader", var)) {
377 if (!value) {
378 return config_error_nonbool(var);
379 } else if (!*value) {
380 curl_slist_free_all(extra_http_headers);
381 extra_http_headers = NULL;
382 } else {
383 extra_http_headers =
384 curl_slist_append(extra_http_headers, value);
386 return 0;
389 if (!strcmp("http.followredirects", var)) {
390 if (value && !strcmp(value, "initial"))
391 http_follow_config = HTTP_FOLLOW_INITIAL;
392 else if (git_config_bool(var, value))
393 http_follow_config = HTTP_FOLLOW_ALWAYS;
394 else
395 http_follow_config = HTTP_FOLLOW_NONE;
396 return 0;
399 /* Fall back on the default ones */
400 return git_default_config(var, value, cb);
403 static int curl_empty_auth_enabled(void)
405 if (curl_empty_auth >= 0)
406 return curl_empty_auth;
408 #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
410 * Our libcurl is too old to do AUTH_ANY in the first place;
411 * just default to turning the feature off.
413 #else
415 * In the automatic case, kick in the empty-auth
416 * hack as long as we would potentially try some
417 * method more exotic than "Basic" or "Digest".
419 * But only do this when this is our second or
420 * subsequent request, as by then we know what
421 * methods are available.
423 if (http_auth_methods_restricted &&
424 (http_auth_methods & ~empty_auth_useless))
425 return 1;
426 #endif
427 return 0;
430 static void init_curl_http_auth(CURL *result)
432 if (!http_auth.username || !*http_auth.username) {
433 if (curl_empty_auth_enabled())
434 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
435 return;
438 credential_fill(&http_auth);
440 #if LIBCURL_VERSION_NUM >= 0x071301
441 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
442 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
443 #else
445 static struct strbuf up = STRBUF_INIT;
447 * Note that we assume we only ever have a single set of
448 * credentials in a given program run, so we do not have
449 * to worry about updating this buffer, only setting its
450 * initial value.
452 if (!up.len)
453 strbuf_addf(&up, "%s:%s",
454 http_auth.username, http_auth.password);
455 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
457 #endif
460 /* *var must be free-able */
461 static void var_override(const char **var, char *value)
463 if (value) {
464 free((void *)*var);
465 *var = xstrdup(value);
469 static void set_proxyauth_name_password(CURL *result)
471 #if LIBCURL_VERSION_NUM >= 0x071301
472 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
473 proxy_auth.username);
474 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
475 proxy_auth.password);
476 #else
477 struct strbuf s = STRBUF_INIT;
479 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
480 strbuf_addch(&s, ':');
481 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
482 curl_proxyuserpwd = strbuf_detach(&s, NULL);
483 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
484 #endif
487 static void init_curl_proxy_auth(CURL *result)
489 if (proxy_auth.username) {
490 if (!proxy_auth.password)
491 credential_fill(&proxy_auth);
492 set_proxyauth_name_password(result);
495 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
497 #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
498 if (http_proxy_authmethod) {
499 int i;
500 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
501 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
502 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
503 proxy_authmethods[i].curlauth_param);
504 break;
507 if (i == ARRAY_SIZE(proxy_authmethods)) {
508 warning("unsupported proxy authentication method %s: using anyauth",
509 http_proxy_authmethod);
510 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
513 else
514 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
515 #endif
518 static int has_cert_password(void)
520 if (ssl_cert == NULL || ssl_cert_password_required != 1)
521 return 0;
522 if (!cert_auth.password) {
523 cert_auth.protocol = xstrdup("cert");
524 cert_auth.username = xstrdup("");
525 cert_auth.path = xstrdup(ssl_cert);
526 credential_fill(&cert_auth);
528 return 1;
531 #if LIBCURL_VERSION_NUM >= 0x071900
532 static void set_curl_keepalive(CURL *c)
534 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
537 #elif LIBCURL_VERSION_NUM >= 0x071000
538 static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
540 int ka = 1;
541 int rc;
542 socklen_t len = (socklen_t)sizeof(ka);
544 if (type != CURLSOCKTYPE_IPCXN)
545 return 0;
547 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
548 if (rc < 0)
549 warning_errno("unable to set SO_KEEPALIVE on socket");
551 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
554 static void set_curl_keepalive(CURL *c)
556 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
559 #else
560 static void set_curl_keepalive(CURL *c)
562 /* not supported on older curl versions */
564 #endif
566 static void redact_sensitive_header(struct strbuf *header)
568 const char *sensitive_header;
570 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
571 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
572 /* The first token is the type, which is OK to log */
573 while (isspace(*sensitive_header))
574 sensitive_header++;
575 while (*sensitive_header && !isspace(*sensitive_header))
576 sensitive_header++;
577 /* Everything else is opaque and possibly sensitive */
578 strbuf_setlen(header, sensitive_header - header->buf);
579 strbuf_addstr(header, " <redacted>");
583 static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
585 struct strbuf out = STRBUF_INIT;
586 struct strbuf **headers, **header;
588 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
589 text, (long)size, (long)size);
590 trace_strbuf(&trace_curl, &out);
591 strbuf_reset(&out);
592 strbuf_add(&out, ptr, size);
593 headers = strbuf_split_max(&out, '\n', 0);
595 for (header = headers; *header; header++) {
596 if (hide_sensitive_header)
597 redact_sensitive_header(*header);
598 strbuf_insert((*header), 0, text, strlen(text));
599 strbuf_insert((*header), strlen(text), ": ", 2);
600 strbuf_rtrim((*header));
601 strbuf_addch((*header), '\n');
602 trace_strbuf(&trace_curl, (*header));
604 strbuf_list_free(headers);
605 strbuf_release(&out);
608 static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
610 size_t i;
611 struct strbuf out = STRBUF_INIT;
612 unsigned int width = 60;
614 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
615 text, (long)size, (long)size);
616 trace_strbuf(&trace_curl, &out);
618 for (i = 0; i < size; i += width) {
619 size_t w;
621 strbuf_reset(&out);
622 strbuf_addf(&out, "%s: ", text);
623 for (w = 0; (w < width) && (i + w < size); w++) {
624 unsigned char ch = ptr[i + w];
626 strbuf_addch(&out,
627 (ch >= 0x20) && (ch < 0x80)
628 ? ch : '.');
630 strbuf_addch(&out, '\n');
631 trace_strbuf(&trace_curl, &out);
633 strbuf_release(&out);
636 static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
638 const char *text;
639 enum { NO_FILTER = 0, DO_FILTER = 1 };
641 switch (type) {
642 case CURLINFO_TEXT:
643 trace_printf_key(&trace_curl, "== Info: %s", data);
644 break;
645 case CURLINFO_HEADER_OUT:
646 text = "=> Send header";
647 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
648 break;
649 case CURLINFO_DATA_OUT:
650 text = "=> Send data";
651 curl_dump_data(text, (unsigned char *)data, size);
652 break;
653 case CURLINFO_SSL_DATA_OUT:
654 text = "=> Send SSL data";
655 curl_dump_data(text, (unsigned char *)data, size);
656 break;
657 case CURLINFO_HEADER_IN:
658 text = "<= Recv header";
659 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
660 break;
661 case CURLINFO_DATA_IN:
662 text = "<= Recv data";
663 curl_dump_data(text, (unsigned char *)data, size);
664 break;
665 case CURLINFO_SSL_DATA_IN:
666 text = "<= Recv SSL data";
667 curl_dump_data(text, (unsigned char *)data, size);
668 break;
670 default: /* we ignore unknown types by default */
671 return 0;
673 return 0;
676 void setup_curl_trace(CURL *handle)
678 if (!trace_want(&trace_curl))
679 return;
680 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
681 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
682 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
685 #ifdef CURLPROTO_HTTP
686 static long get_curl_allowed_protocols(int from_user)
688 long allowed_protocols = 0;
690 if (is_transport_allowed("http", from_user))
691 allowed_protocols |= CURLPROTO_HTTP;
692 if (is_transport_allowed("https", from_user))
693 allowed_protocols |= CURLPROTO_HTTPS;
694 if (is_transport_allowed("ftp", from_user))
695 allowed_protocols |= CURLPROTO_FTP;
696 if (is_transport_allowed("ftps", from_user))
697 allowed_protocols |= CURLPROTO_FTPS;
699 return allowed_protocols;
701 #endif
703 static CURL *get_curl_handle(void)
705 CURL *result = curl_easy_init();
707 if (!result)
708 die("curl_easy_init failed");
710 if (!curl_ssl_verify) {
711 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
712 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
713 } else {
714 /* Verify authenticity of the peer's certificate */
715 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
716 /* The name in the cert must match whom we tried to connect */
717 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
720 #if LIBCURL_VERSION_NUM >= 0x070907
721 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
722 #endif
723 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
724 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
725 #endif
727 #ifdef CURLGSSAPI_DELEGATION_FLAG
728 if (curl_deleg) {
729 int i;
730 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
731 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
732 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
733 curl_deleg_levels[i].curl_deleg_param);
734 break;
737 if (i == ARRAY_SIZE(curl_deleg_levels))
738 warning("Unknown delegation method '%s': using default",
739 curl_deleg);
741 #endif
743 if (http_proactive_auth)
744 init_curl_http_auth(result);
746 if (getenv("GIT_SSL_VERSION"))
747 ssl_version = getenv("GIT_SSL_VERSION");
748 if (ssl_version && *ssl_version) {
749 int i;
750 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
751 if (!strcmp(ssl_version, sslversions[i].name)) {
752 curl_easy_setopt(result, CURLOPT_SSLVERSION,
753 sslversions[i].ssl_version);
754 break;
757 if (i == ARRAY_SIZE(sslversions))
758 warning("unsupported ssl version %s: using default",
759 ssl_version);
762 if (getenv("GIT_SSL_CIPHER_LIST"))
763 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
764 if (ssl_cipherlist != NULL && *ssl_cipherlist)
765 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
766 ssl_cipherlist);
768 if (ssl_cert != NULL)
769 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
770 if (has_cert_password())
771 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
772 #if LIBCURL_VERSION_NUM >= 0x070903
773 if (ssl_key != NULL)
774 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
775 #endif
776 #if LIBCURL_VERSION_NUM >= 0x070908
777 if (ssl_capath != NULL)
778 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
779 #endif
780 #if LIBCURL_VERSION_NUM >= 0x072c00
781 if (ssl_pinnedkey != NULL)
782 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
783 #endif
784 if (ssl_cainfo != NULL)
785 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
787 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
788 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
789 curl_low_speed_limit);
790 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
791 curl_low_speed_time);
794 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
795 #if LIBCURL_VERSION_NUM >= 0x071301
796 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
797 #elif LIBCURL_VERSION_NUM >= 0x071101
798 curl_easy_setopt(result, CURLOPT_POST301, 1);
799 #endif
800 #ifdef CURLPROTO_HTTP
801 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
802 get_curl_allowed_protocols(0));
803 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
804 get_curl_allowed_protocols(-1));
805 #else
806 warning("protocol restrictions not applied to curl redirects because\n"
807 "your curl version is too old (>= 7.19.4)");
808 #endif
809 if (getenv("GIT_CURL_VERBOSE"))
810 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
811 setup_curl_trace(result);
813 curl_easy_setopt(result, CURLOPT_USERAGENT,
814 user_agent ? user_agent : git_user_agent());
816 if (curl_ftp_no_epsv)
817 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
819 #ifdef CURLOPT_USE_SSL
820 if (curl_ssl_try)
821 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
822 #endif
825 * CURL also examines these variables as a fallback; but we need to query
826 * them here in order to decide whether to prompt for missing password (cf.
827 * init_curl_proxy_auth()).
829 * Unlike many other common environment variables, these are historically
830 * lowercase only. It appears that CURL did not know this and implemented
831 * only uppercase variants, which was later corrected to take both - with
832 * the exception of http_proxy, which is lowercase only also in CURL. As
833 * the lowercase versions are the historical quasi-standard, they take
834 * precedence here, as in CURL.
836 if (!curl_http_proxy) {
837 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
838 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
839 var_override(&curl_http_proxy, getenv("https_proxy"));
840 } else {
841 var_override(&curl_http_proxy, getenv("http_proxy"));
843 if (!curl_http_proxy) {
844 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
845 var_override(&curl_http_proxy, getenv("all_proxy"));
849 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
851 * Handle case with the empty http.proxy value here to keep
852 * common code clean.
853 * NB: empty option disables proxying at all.
855 curl_easy_setopt(result, CURLOPT_PROXY, "");
856 } else if (curl_http_proxy) {
857 #if LIBCURL_VERSION_NUM >= 0x071800
858 if (starts_with(curl_http_proxy, "socks5h"))
859 curl_easy_setopt(result,
860 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
861 else if (starts_with(curl_http_proxy, "socks5"))
862 curl_easy_setopt(result,
863 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
864 else if (starts_with(curl_http_proxy, "socks4a"))
865 curl_easy_setopt(result,
866 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
867 else if (starts_with(curl_http_proxy, "socks"))
868 curl_easy_setopt(result,
869 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
870 #endif
871 #if LIBCURL_VERSION_NUM >= 0x073400
872 else if (starts_with(curl_http_proxy, "https"))
873 curl_easy_setopt(result,
874 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
875 #endif
876 if (strstr(curl_http_proxy, "://"))
877 credential_from_url(&proxy_auth, curl_http_proxy);
878 else {
879 struct strbuf url = STRBUF_INIT;
880 strbuf_addf(&url, "http://%s", curl_http_proxy);
881 credential_from_url(&proxy_auth, url.buf);
882 strbuf_release(&url);
885 if (!proxy_auth.host)
886 die("Invalid proxy URL '%s'", curl_http_proxy);
888 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
889 #if LIBCURL_VERSION_NUM >= 0x071304
890 var_override(&curl_no_proxy, getenv("NO_PROXY"));
891 var_override(&curl_no_proxy, getenv("no_proxy"));
892 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
893 #endif
895 init_curl_proxy_auth(result);
897 set_curl_keepalive(result);
899 return result;
902 static void set_from_env(const char **var, const char *envname)
904 const char *val = getenv(envname);
905 if (val)
906 *var = val;
909 static void protocol_http_header(void)
911 if (get_protocol_version_config() > 0) {
912 struct strbuf protocol_header = STRBUF_INIT;
914 strbuf_addf(&protocol_header, GIT_PROTOCOL_HEADER ": version=%d",
915 get_protocol_version_config());
918 extra_http_headers = curl_slist_append(extra_http_headers,
919 protocol_header.buf);
920 strbuf_release(&protocol_header);
924 void http_init(struct remote *remote, const char *url, int proactive_auth)
926 char *low_speed_limit;
927 char *low_speed_time;
928 char *normalized_url;
929 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
931 config.section = "http";
932 config.key = NULL;
933 config.collect_fn = http_options;
934 config.cascade_fn = git_default_config;
935 config.cb = NULL;
937 http_is_verbose = 0;
938 normalized_url = url_normalize(url, &config.url);
940 git_config(urlmatch_config_entry, &config);
941 free(normalized_url);
943 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
944 die("curl_global_init failed");
946 http_proactive_auth = proactive_auth;
948 if (remote && remote->http_proxy)
949 curl_http_proxy = xstrdup(remote->http_proxy);
951 if (remote)
952 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
954 protocol_http_header();
956 pragma_header = curl_slist_append(http_copy_default_headers(),
957 "Pragma: no-cache");
958 no_pragma_header = curl_slist_append(http_copy_default_headers(),
959 "Pragma:");
961 #ifdef USE_CURL_MULTI
963 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
964 if (http_max_requests != NULL)
965 max_requests = atoi(http_max_requests);
968 curlm = curl_multi_init();
969 if (!curlm)
970 die("curl_multi_init failed");
971 #endif
973 if (getenv("GIT_SSL_NO_VERIFY"))
974 curl_ssl_verify = 0;
976 set_from_env(&ssl_cert, "GIT_SSL_CERT");
977 #if LIBCURL_VERSION_NUM >= 0x070903
978 set_from_env(&ssl_key, "GIT_SSL_KEY");
979 #endif
980 #if LIBCURL_VERSION_NUM >= 0x070908
981 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
982 #endif
983 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
985 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
987 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
988 if (low_speed_limit != NULL)
989 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
990 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
991 if (low_speed_time != NULL)
992 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
994 if (curl_ssl_verify == -1)
995 curl_ssl_verify = 1;
997 curl_session_count = 0;
998 #ifdef USE_CURL_MULTI
999 if (max_requests < 1)
1000 max_requests = DEFAULT_MAX_REQUESTS;
1001 #endif
1003 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1004 curl_ftp_no_epsv = 1;
1006 if (url) {
1007 credential_from_url(&http_auth, url);
1008 if (!ssl_cert_password_required &&
1009 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1010 starts_with(url, "https://"))
1011 ssl_cert_password_required = 1;
1014 #ifndef NO_CURL_EASY_DUPHANDLE
1015 curl_default = get_curl_handle();
1016 #endif
1019 void http_cleanup(void)
1021 struct active_request_slot *slot = active_queue_head;
1023 while (slot != NULL) {
1024 struct active_request_slot *next = slot->next;
1025 if (slot->curl != NULL) {
1026 xmulti_remove_handle(slot);
1027 curl_easy_cleanup(slot->curl);
1029 free(slot);
1030 slot = next;
1032 active_queue_head = NULL;
1034 #ifndef NO_CURL_EASY_DUPHANDLE
1035 curl_easy_cleanup(curl_default);
1036 #endif
1038 #ifdef USE_CURL_MULTI
1039 curl_multi_cleanup(curlm);
1040 #endif
1041 curl_global_cleanup();
1043 curl_slist_free_all(extra_http_headers);
1044 extra_http_headers = NULL;
1046 curl_slist_free_all(pragma_header);
1047 pragma_header = NULL;
1049 curl_slist_free_all(no_pragma_header);
1050 no_pragma_header = NULL;
1052 if (curl_http_proxy) {
1053 free((void *)curl_http_proxy);
1054 curl_http_proxy = NULL;
1057 if (proxy_auth.password) {
1058 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1059 FREE_AND_NULL(proxy_auth.password);
1062 free((void *)curl_proxyuserpwd);
1063 curl_proxyuserpwd = NULL;
1065 free((void *)http_proxy_authmethod);
1066 http_proxy_authmethod = NULL;
1068 if (cert_auth.password != NULL) {
1069 memset(cert_auth.password, 0, strlen(cert_auth.password));
1070 FREE_AND_NULL(cert_auth.password);
1072 ssl_cert_password_required = 0;
1074 FREE_AND_NULL(cached_accept_language);
1077 struct active_request_slot *get_active_slot(void)
1079 struct active_request_slot *slot = active_queue_head;
1080 struct active_request_slot *newslot;
1082 #ifdef USE_CURL_MULTI
1083 int num_transfers;
1085 /* Wait for a slot to open up if the queue is full */
1086 while (active_requests >= max_requests) {
1087 curl_multi_perform(curlm, &num_transfers);
1088 if (num_transfers < active_requests)
1089 process_curl_messages();
1091 #endif
1093 while (slot != NULL && slot->in_use)
1094 slot = slot->next;
1096 if (slot == NULL) {
1097 newslot = xmalloc(sizeof(*newslot));
1098 newslot->curl = NULL;
1099 newslot->in_use = 0;
1100 newslot->next = NULL;
1102 slot = active_queue_head;
1103 if (slot == NULL) {
1104 active_queue_head = newslot;
1105 } else {
1106 while (slot->next != NULL)
1107 slot = slot->next;
1108 slot->next = newslot;
1110 slot = newslot;
1113 if (slot->curl == NULL) {
1114 #ifdef NO_CURL_EASY_DUPHANDLE
1115 slot->curl = get_curl_handle();
1116 #else
1117 slot->curl = curl_easy_duphandle(curl_default);
1118 #endif
1119 curl_session_count++;
1122 active_requests++;
1123 slot->in_use = 1;
1124 slot->results = NULL;
1125 slot->finished = NULL;
1126 slot->callback_data = NULL;
1127 slot->callback_func = NULL;
1128 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1129 if (curl_save_cookies)
1130 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1131 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1132 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1133 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1134 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1135 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1136 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1137 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1138 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1139 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1140 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1143 * Default following to off unless "ALWAYS" is configured; this gives
1144 * callers a sane starting point, and they can tweak for individual
1145 * HTTP_FOLLOW_* cases themselves.
1147 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1148 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1149 else
1150 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1152 #if LIBCURL_VERSION_NUM >= 0x070a08
1153 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1154 #endif
1155 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1156 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1157 #endif
1158 if (http_auth.password || curl_empty_auth_enabled())
1159 init_curl_http_auth(slot->curl);
1161 return slot;
1164 int start_active_slot(struct active_request_slot *slot)
1166 #ifdef USE_CURL_MULTI
1167 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1168 int num_transfers;
1170 if (curlm_result != CURLM_OK &&
1171 curlm_result != CURLM_CALL_MULTI_PERFORM) {
1172 warning("curl_multi_add_handle failed: %s",
1173 curl_multi_strerror(curlm_result));
1174 active_requests--;
1175 slot->in_use = 0;
1176 return 0;
1180 * We know there must be something to do, since we just added
1181 * something.
1183 curl_multi_perform(curlm, &num_transfers);
1184 #endif
1185 return 1;
1188 #ifdef USE_CURL_MULTI
1189 struct fill_chain {
1190 void *data;
1191 int (*fill)(void *);
1192 struct fill_chain *next;
1195 static struct fill_chain *fill_cfg;
1197 void add_fill_function(void *data, int (*fill)(void *))
1199 struct fill_chain *new = xmalloc(sizeof(*new));
1200 struct fill_chain **linkp = &fill_cfg;
1201 new->data = data;
1202 new->fill = fill;
1203 new->next = NULL;
1204 while (*linkp)
1205 linkp = &(*linkp)->next;
1206 *linkp = new;
1209 void fill_active_slots(void)
1211 struct active_request_slot *slot = active_queue_head;
1213 while (active_requests < max_requests) {
1214 struct fill_chain *fill;
1215 for (fill = fill_cfg; fill; fill = fill->next)
1216 if (fill->fill(fill->data))
1217 break;
1219 if (!fill)
1220 break;
1223 while (slot != NULL) {
1224 if (!slot->in_use && slot->curl != NULL
1225 && curl_session_count > min_curl_sessions) {
1226 curl_easy_cleanup(slot->curl);
1227 slot->curl = NULL;
1228 curl_session_count--;
1230 slot = slot->next;
1234 void step_active_slots(void)
1236 int num_transfers;
1237 CURLMcode curlm_result;
1239 do {
1240 curlm_result = curl_multi_perform(curlm, &num_transfers);
1241 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1242 if (num_transfers < active_requests) {
1243 process_curl_messages();
1244 fill_active_slots();
1247 #endif
1249 void run_active_slot(struct active_request_slot *slot)
1251 #ifdef USE_CURL_MULTI
1252 fd_set readfds;
1253 fd_set writefds;
1254 fd_set excfds;
1255 int max_fd;
1256 struct timeval select_timeout;
1257 int finished = 0;
1259 slot->finished = &finished;
1260 while (!finished) {
1261 step_active_slots();
1263 if (slot->in_use) {
1264 #if LIBCURL_VERSION_NUM >= 0x070f04
1265 long curl_timeout;
1266 curl_multi_timeout(curlm, &curl_timeout);
1267 if (curl_timeout == 0) {
1268 continue;
1269 } else if (curl_timeout == -1) {
1270 select_timeout.tv_sec = 0;
1271 select_timeout.tv_usec = 50000;
1272 } else {
1273 select_timeout.tv_sec = curl_timeout / 1000;
1274 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1276 #else
1277 select_timeout.tv_sec = 0;
1278 select_timeout.tv_usec = 50000;
1279 #endif
1281 max_fd = -1;
1282 FD_ZERO(&readfds);
1283 FD_ZERO(&writefds);
1284 FD_ZERO(&excfds);
1285 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1288 * It can happen that curl_multi_timeout returns a pathologically
1289 * long timeout when curl_multi_fdset returns no file descriptors
1290 * to read. See commit message for more details.
1292 if (max_fd < 0 &&
1293 (select_timeout.tv_sec > 0 ||
1294 select_timeout.tv_usec > 50000)) {
1295 select_timeout.tv_sec = 0;
1296 select_timeout.tv_usec = 50000;
1299 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1302 #else
1303 while (slot->in_use) {
1304 slot->curl_result = curl_easy_perform(slot->curl);
1305 finish_active_slot(slot);
1307 #endif
1310 static void release_active_slot(struct active_request_slot *slot)
1312 closedown_active_slot(slot);
1313 if (slot->curl) {
1314 xmulti_remove_handle(slot);
1315 if (curl_session_count > min_curl_sessions) {
1316 curl_easy_cleanup(slot->curl);
1317 slot->curl = NULL;
1318 curl_session_count--;
1321 #ifdef USE_CURL_MULTI
1322 fill_active_slots();
1323 #endif
1326 void finish_all_active_slots(void)
1328 struct active_request_slot *slot = active_queue_head;
1330 while (slot != NULL)
1331 if (slot->in_use) {
1332 run_active_slot(slot);
1333 slot = active_queue_head;
1334 } else {
1335 slot = slot->next;
1339 /* Helpers for modifying and creating URLs */
1340 static inline int needs_quote(int ch)
1342 if (((ch >= 'A') && (ch <= 'Z'))
1343 || ((ch >= 'a') && (ch <= 'z'))
1344 || ((ch >= '0') && (ch <= '9'))
1345 || (ch == '/')
1346 || (ch == '-')
1347 || (ch == '.'))
1348 return 0;
1349 return 1;
1352 static char *quote_ref_url(const char *base, const char *ref)
1354 struct strbuf buf = STRBUF_INIT;
1355 const char *cp;
1356 int ch;
1358 end_url_with_slash(&buf, base);
1360 for (cp = ref; (ch = *cp) != 0; cp++)
1361 if (needs_quote(ch))
1362 strbuf_addf(&buf, "%%%02x", ch);
1363 else
1364 strbuf_addch(&buf, *cp);
1366 return strbuf_detach(&buf, NULL);
1369 void append_remote_object_url(struct strbuf *buf, const char *url,
1370 const char *hex,
1371 int only_two_digit_prefix)
1373 end_url_with_slash(buf, url);
1375 strbuf_addf(buf, "objects/%.*s/", 2, hex);
1376 if (!only_two_digit_prefix)
1377 strbuf_addstr(buf, hex + 2);
1380 char *get_remote_object_url(const char *url, const char *hex,
1381 int only_two_digit_prefix)
1383 struct strbuf buf = STRBUF_INIT;
1384 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1385 return strbuf_detach(&buf, NULL);
1388 static int handle_curl_result(struct slot_results *results)
1391 * If we see a failing http code with CURLE_OK, we have turned off
1392 * FAILONERROR (to keep the server's custom error response), and should
1393 * translate the code into failure here.
1395 * Likewise, if we see a redirect (30x code), that means we turned off
1396 * redirect-following, and we should treat the result as an error.
1398 if (results->curl_result == CURLE_OK &&
1399 results->http_code >= 300) {
1400 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1402 * Normally curl will already have put the "reason phrase"
1403 * from the server into curl_errorstr; unfortunately without
1404 * FAILONERROR it is lost, so we can give only the numeric
1405 * status code.
1407 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1408 "The requested URL returned error: %ld",
1409 results->http_code);
1412 if (results->curl_result == CURLE_OK) {
1413 credential_approve(&http_auth);
1414 if (proxy_auth.password)
1415 credential_approve(&proxy_auth);
1416 return HTTP_OK;
1417 } else if (missing_target(results))
1418 return HTTP_MISSING_TARGET;
1419 else if (results->http_code == 401) {
1420 if (http_auth.username && http_auth.password) {
1421 credential_reject(&http_auth);
1422 return HTTP_NOAUTH;
1423 } else {
1424 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1425 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1426 if (results->auth_avail) {
1427 http_auth_methods &= results->auth_avail;
1428 http_auth_methods_restricted = 1;
1430 #endif
1431 return HTTP_REAUTH;
1433 } else {
1434 if (results->http_connectcode == 407)
1435 credential_reject(&proxy_auth);
1436 #if LIBCURL_VERSION_NUM >= 0x070c00
1437 if (!curl_errorstr[0])
1438 strlcpy(curl_errorstr,
1439 curl_easy_strerror(results->curl_result),
1440 sizeof(curl_errorstr));
1441 #endif
1442 return HTTP_ERROR;
1446 int run_one_slot(struct active_request_slot *slot,
1447 struct slot_results *results)
1449 slot->results = results;
1450 if (!start_active_slot(slot)) {
1451 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1452 "failed to start HTTP request");
1453 return HTTP_START_FAILED;
1456 run_active_slot(slot);
1457 return handle_curl_result(results);
1460 struct curl_slist *http_copy_default_headers(void)
1462 struct curl_slist *headers = NULL, *h;
1464 for (h = extra_http_headers; h; h = h->next)
1465 headers = curl_slist_append(headers, h->data);
1467 return headers;
1470 static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1472 char *ptr;
1473 CURLcode ret;
1475 strbuf_reset(buf);
1476 ret = curl_easy_getinfo(curl, info, &ptr);
1477 if (!ret && ptr)
1478 strbuf_addstr(buf, ptr);
1479 return ret;
1483 * Check for and extract a content-type parameter. "raw"
1484 * should be positioned at the start of the potential
1485 * parameter, with any whitespace already removed.
1487 * "name" is the name of the parameter. The value is appended
1488 * to "out".
1490 static int extract_param(const char *raw, const char *name,
1491 struct strbuf *out)
1493 size_t len = strlen(name);
1495 if (strncasecmp(raw, name, len))
1496 return -1;
1497 raw += len;
1499 if (*raw != '=')
1500 return -1;
1501 raw++;
1503 while (*raw && !isspace(*raw) && *raw != ';')
1504 strbuf_addch(out, *raw++);
1505 return 0;
1509 * Extract a normalized version of the content type, with any
1510 * spaces suppressed, all letters lowercased, and no trailing ";"
1511 * or parameters.
1513 * Note that we will silently remove even invalid whitespace. For
1514 * example, "text / plain" is specifically forbidden by RFC 2616,
1515 * but "text/plain" is the only reasonable output, and this keeps
1516 * our code simple.
1518 * If the "charset" argument is not NULL, store the value of any
1519 * charset parameter there.
1521 * Example:
1522 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1523 * "text / plain" -> "text/plain"
1525 static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1526 struct strbuf *charset)
1528 const char *p;
1530 strbuf_reset(type);
1531 strbuf_grow(type, raw->len);
1532 for (p = raw->buf; *p; p++) {
1533 if (isspace(*p))
1534 continue;
1535 if (*p == ';') {
1536 p++;
1537 break;
1539 strbuf_addch(type, tolower(*p));
1542 if (!charset)
1543 return;
1545 strbuf_reset(charset);
1546 while (*p) {
1547 while (isspace(*p) || *p == ';')
1548 p++;
1549 if (!extract_param(p, "charset", charset))
1550 return;
1551 while (*p && !isspace(*p))
1552 p++;
1555 if (!charset->len && starts_with(type->buf, "text/"))
1556 strbuf_addstr(charset, "ISO-8859-1");
1559 static void write_accept_language(struct strbuf *buf)
1562 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1563 * that, q-value will be smaller than 0.001, the minimum q-value the
1564 * HTTP specification allows. See
1565 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1567 const int MAX_DECIMAL_PLACES = 3;
1568 const int MAX_LANGUAGE_TAGS = 1000;
1569 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1570 char **language_tags = NULL;
1571 int num_langs = 0;
1572 const char *s = get_preferred_languages();
1573 int i;
1574 struct strbuf tag = STRBUF_INIT;
1576 /* Don't add Accept-Language header if no language is preferred. */
1577 if (!s)
1578 return;
1581 * Split the colon-separated string of preferred languages into
1582 * language_tags array.
1584 do {
1585 /* collect language tag */
1586 for (; *s && (isalnum(*s) || *s == '_'); s++)
1587 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1589 /* skip .codeset, @modifier and any other unnecessary parts */
1590 while (*s && *s != ':')
1591 s++;
1593 if (tag.len) {
1594 num_langs++;
1595 REALLOC_ARRAY(language_tags, num_langs);
1596 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1597 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1598 break;
1600 } while (*s++);
1602 /* write Accept-Language header into buf */
1603 if (num_langs) {
1604 int last_buf_len = 0;
1605 int max_q;
1606 int decimal_places;
1607 char q_format[32];
1609 /* add '*' */
1610 REALLOC_ARRAY(language_tags, num_langs + 1);
1611 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1613 /* compute decimal_places */
1614 for (max_q = 1, decimal_places = 0;
1615 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1616 decimal_places++, max_q *= 10)
1619 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1621 strbuf_addstr(buf, "Accept-Language: ");
1623 for (i = 0; i < num_langs; i++) {
1624 if (i > 0)
1625 strbuf_addstr(buf, ", ");
1627 strbuf_addstr(buf, language_tags[i]);
1629 if (i > 0)
1630 strbuf_addf(buf, q_format, max_q - i);
1632 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1633 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1634 break;
1637 last_buf_len = buf->len;
1641 /* free language tags -- last one is a static '*' */
1642 for (i = 0; i < num_langs - 1; i++)
1643 free(language_tags[i]);
1644 free(language_tags);
1648 * Get an Accept-Language header which indicates user's preferred languages.
1650 * Examples:
1651 * LANGUAGE= -> ""
1652 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1653 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1654 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1655 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1656 * LANGUAGE= LANG=C -> ""
1658 static const char *get_accept_language(void)
1660 if (!cached_accept_language) {
1661 struct strbuf buf = STRBUF_INIT;
1662 write_accept_language(&buf);
1663 if (buf.len > 0)
1664 cached_accept_language = strbuf_detach(&buf, NULL);
1667 return cached_accept_language;
1670 static void http_opt_request_remainder(CURL *curl, off_t pos)
1672 char buf[128];
1673 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1674 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1677 /* http_request() targets */
1678 #define HTTP_REQUEST_STRBUF 0
1679 #define HTTP_REQUEST_FILE 1
1681 static int http_request(const char *url,
1682 void *result, int target,
1683 const struct http_get_options *options)
1685 struct active_request_slot *slot;
1686 struct slot_results results;
1687 struct curl_slist *headers = http_copy_default_headers();
1688 struct strbuf buf = STRBUF_INIT;
1689 const char *accept_language;
1690 int ret;
1692 slot = get_active_slot();
1693 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1695 if (result == NULL) {
1696 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1697 } else {
1698 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1699 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1701 if (target == HTTP_REQUEST_FILE) {
1702 off_t posn = ftello(result);
1703 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1704 fwrite);
1705 if (posn > 0)
1706 http_opt_request_remainder(slot->curl, posn);
1707 } else
1708 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1709 fwrite_buffer);
1712 accept_language = get_accept_language();
1714 if (accept_language)
1715 headers = curl_slist_append(headers, accept_language);
1717 strbuf_addstr(&buf, "Pragma:");
1718 if (options && options->no_cache)
1719 strbuf_addstr(&buf, " no-cache");
1720 if (options && options->keep_error)
1721 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1722 if (options && options->initial_request &&
1723 http_follow_config == HTTP_FOLLOW_INITIAL)
1724 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1726 headers = curl_slist_append(headers, buf.buf);
1728 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1729 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1730 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1732 ret = run_one_slot(slot, &results);
1734 if (options && options->content_type) {
1735 struct strbuf raw = STRBUF_INIT;
1736 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1737 extract_content_type(&raw, options->content_type,
1738 options->charset);
1739 strbuf_release(&raw);
1742 if (options && options->effective_url)
1743 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1744 options->effective_url);
1746 curl_slist_free_all(headers);
1747 strbuf_release(&buf);
1749 return ret;
1753 * Update the "base" url to a more appropriate value, as deduced by
1754 * redirects seen when requesting a URL starting with "url".
1756 * The "asked" parameter is a URL that we asked curl to access, and must begin
1757 * with "base".
1759 * The "got" parameter is the URL that curl reported to us as where we ended
1760 * up.
1762 * Returns 1 if we updated the base url, 0 otherwise.
1764 * Our basic strategy is to compare "base" and "asked" to find the bits
1765 * specific to our request. We then strip those bits off of "got" to yield the
1766 * new base. So for example, if our base is "http://example.com/foo.git",
1767 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1768 * with "https://other.example.com/foo.git/info/refs". We would want the
1769 * new URL to become "https://other.example.com/foo.git".
1771 * Note that this assumes a sane redirect scheme. It's entirely possible
1772 * in the example above to end up at a URL that does not even end in
1773 * "info/refs". In such a case we die. There's not much we can do, such a
1774 * scheme is unlikely to represent a real git repository, and failing to
1775 * rewrite the base opens options for malicious redirects to do funny things.
1777 static int update_url_from_redirect(struct strbuf *base,
1778 const char *asked,
1779 const struct strbuf *got)
1781 const char *tail;
1782 size_t new_len;
1784 if (!strcmp(asked, got->buf))
1785 return 0;
1787 if (!skip_prefix(asked, base->buf, &tail))
1788 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1789 asked, base->buf);
1791 new_len = got->len;
1792 if (!strip_suffix_mem(got->buf, &new_len, tail))
1793 die(_("unable to update url base from redirection:\n"
1794 " asked for: %s\n"
1795 " redirect: %s"),
1796 asked, got->buf);
1798 strbuf_reset(base);
1799 strbuf_add(base, got->buf, new_len);
1801 return 1;
1804 static int http_request_reauth(const char *url,
1805 void *result, int target,
1806 struct http_get_options *options)
1808 int ret = http_request(url, result, target, options);
1810 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1811 return ret;
1813 if (options && options->effective_url && options->base_url) {
1814 if (update_url_from_redirect(options->base_url,
1815 url, options->effective_url)) {
1816 credential_from_url(&http_auth, options->base_url->buf);
1817 url = options->effective_url->buf;
1821 if (ret != HTTP_REAUTH)
1822 return ret;
1825 * If we are using KEEP_ERROR, the previous request may have
1826 * put cruft into our output stream; we should clear it out before
1827 * making our next request. We only know how to do this for
1828 * the strbuf case, but that is enough to satisfy current callers.
1830 if (options && options->keep_error) {
1831 switch (target) {
1832 case HTTP_REQUEST_STRBUF:
1833 strbuf_reset(result);
1834 break;
1835 default:
1836 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1840 credential_fill(&http_auth);
1842 return http_request(url, result, target, options);
1845 int http_get_strbuf(const char *url,
1846 struct strbuf *result,
1847 struct http_get_options *options)
1849 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1853 * Downloads a URL and stores the result in the given file.
1855 * If a previous interrupted download is detected (i.e. a previous temporary
1856 * file is still around) the download is resumed.
1858 static int http_get_file(const char *url, const char *filename,
1859 struct http_get_options *options)
1861 int ret;
1862 struct strbuf tmpfile = STRBUF_INIT;
1863 FILE *result;
1865 strbuf_addf(&tmpfile, "%s.temp", filename);
1866 result = fopen(tmpfile.buf, "a");
1867 if (!result) {
1868 error("Unable to open local file %s", tmpfile.buf);
1869 ret = HTTP_ERROR;
1870 goto cleanup;
1873 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1874 fclose(result);
1876 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1877 ret = HTTP_ERROR;
1878 cleanup:
1879 strbuf_release(&tmpfile);
1880 return ret;
1883 int http_fetch_ref(const char *base, struct ref *ref)
1885 struct http_get_options options = {0};
1886 char *url;
1887 struct strbuf buffer = STRBUF_INIT;
1888 int ret = -1;
1890 options.no_cache = 1;
1892 url = quote_ref_url(base, ref->name);
1893 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1894 strbuf_rtrim(&buffer);
1895 if (buffer.len == 40)
1896 ret = get_oid_hex(buffer.buf, &ref->old_oid);
1897 else if (starts_with(buffer.buf, "ref: ")) {
1898 ref->symref = xstrdup(buffer.buf + 5);
1899 ret = 0;
1903 strbuf_release(&buffer);
1904 free(url);
1905 return ret;
1908 /* Helpers for fetching packs */
1909 static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1911 char *url, *tmp;
1912 struct strbuf buf = STRBUF_INIT;
1914 if (http_is_verbose)
1915 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1917 end_url_with_slash(&buf, base_url);
1918 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1919 url = strbuf_detach(&buf, NULL);
1921 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1922 tmp = strbuf_detach(&buf, NULL);
1924 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1925 error("Unable to get pack index %s", url);
1926 FREE_AND_NULL(tmp);
1929 free(url);
1930 return tmp;
1933 static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1934 unsigned char *sha1, const char *base_url)
1936 struct packed_git *new_pack;
1937 char *tmp_idx = NULL;
1938 int ret;
1940 if (has_pack_index(sha1)) {
1941 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1942 if (!new_pack)
1943 return -1; /* parse_pack_index() already issued error message */
1944 goto add_pack;
1947 tmp_idx = fetch_pack_index(sha1, base_url);
1948 if (!tmp_idx)
1949 return -1;
1951 new_pack = parse_pack_index(sha1, tmp_idx);
1952 if (!new_pack) {
1953 unlink(tmp_idx);
1954 free(tmp_idx);
1956 return -1; /* parse_pack_index() already issued error message */
1959 ret = verify_pack_index(new_pack);
1960 if (!ret) {
1961 close_pack_index(new_pack);
1962 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1964 free(tmp_idx);
1965 if (ret)
1966 return -1;
1968 add_pack:
1969 new_pack->next = *packs_head;
1970 *packs_head = new_pack;
1971 return 0;
1974 int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1976 struct http_get_options options = {0};
1977 int ret = 0, i = 0;
1978 char *url, *data;
1979 struct strbuf buf = STRBUF_INIT;
1980 unsigned char sha1[20];
1982 end_url_with_slash(&buf, base_url);
1983 strbuf_addstr(&buf, "objects/info/packs");
1984 url = strbuf_detach(&buf, NULL);
1986 options.no_cache = 1;
1987 ret = http_get_strbuf(url, &buf, &options);
1988 if (ret != HTTP_OK)
1989 goto cleanup;
1991 data = buf.buf;
1992 while (i < buf.len) {
1993 switch (data[i]) {
1994 case 'P':
1995 i++;
1996 if (i + 52 <= buf.len &&
1997 starts_with(data + i, " pack-") &&
1998 starts_with(data + i + 46, ".pack\n")) {
1999 get_sha1_hex(data + i + 6, sha1);
2000 fetch_and_setup_pack_index(packs_head, sha1,
2001 base_url);
2002 i += 51;
2003 break;
2005 default:
2006 while (i < buf.len && data[i] != '\n')
2007 i++;
2009 i++;
2012 cleanup:
2013 free(url);
2014 return ret;
2017 void release_http_pack_request(struct http_pack_request *preq)
2019 if (preq->packfile != NULL) {
2020 fclose(preq->packfile);
2021 preq->packfile = NULL;
2023 preq->slot = NULL;
2024 free(preq->url);
2025 free(preq);
2028 int finish_http_pack_request(struct http_pack_request *preq)
2030 struct packed_git **lst;
2031 struct packed_git *p = preq->target;
2032 char *tmp_idx;
2033 size_t len;
2034 struct child_process ip = CHILD_PROCESS_INIT;
2036 close_pack_index(p);
2038 fclose(preq->packfile);
2039 preq->packfile = NULL;
2041 lst = preq->lst;
2042 while (*lst != p)
2043 lst = &((*lst)->next);
2044 *lst = (*lst)->next;
2046 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2047 die("BUG: pack tmpfile does not end in .pack.temp?");
2048 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
2050 argv_array_push(&ip.args, "index-pack");
2051 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2052 argv_array_push(&ip.args, preq->tmpfile);
2053 ip.git_cmd = 1;
2054 ip.no_stdin = 1;
2055 ip.no_stdout = 1;
2057 if (run_command(&ip)) {
2058 unlink(preq->tmpfile);
2059 unlink(tmp_idx);
2060 free(tmp_idx);
2061 return -1;
2064 unlink(sha1_pack_index_name(p->sha1));
2066 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2067 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2068 free(tmp_idx);
2069 return -1;
2072 install_packed_git(p);
2073 free(tmp_idx);
2074 return 0;
2077 struct http_pack_request *new_http_pack_request(
2078 struct packed_git *target, const char *base_url)
2080 off_t prev_posn = 0;
2081 struct strbuf buf = STRBUF_INIT;
2082 struct http_pack_request *preq;
2084 preq = xcalloc(1, sizeof(*preq));
2085 preq->target = target;
2087 end_url_with_slash(&buf, base_url);
2088 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2089 sha1_to_hex(target->sha1));
2090 preq->url = strbuf_detach(&buf, NULL);
2092 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2093 sha1_pack_name(target->sha1));
2094 preq->packfile = fopen(preq->tmpfile, "a");
2095 if (!preq->packfile) {
2096 error("Unable to open local file %s for pack",
2097 preq->tmpfile);
2098 goto abort;
2101 preq->slot = get_active_slot();
2102 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2103 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2104 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2105 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2106 no_pragma_header);
2109 * If there is data present from a previous transfer attempt,
2110 * resume where it left off
2112 prev_posn = ftello(preq->packfile);
2113 if (prev_posn>0) {
2114 if (http_is_verbose)
2115 fprintf(stderr,
2116 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2117 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2118 http_opt_request_remainder(preq->slot->curl, prev_posn);
2121 return preq;
2123 abort:
2124 free(preq->url);
2125 free(preq);
2126 return NULL;
2129 /* Helpers for fetching objects (loose) */
2130 static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2131 void *data)
2133 unsigned char expn[4096];
2134 size_t size = eltsize * nmemb;
2135 int posn = 0;
2136 struct http_object_request *freq = data;
2137 struct active_request_slot *slot = freq->slot;
2139 if (slot) {
2140 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2141 &slot->http_code);
2142 if (c != CURLE_OK)
2143 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2144 curl_easy_strerror(c));
2145 if (slot->http_code >= 300)
2146 return size;
2149 do {
2150 ssize_t retval = xwrite(freq->localfile,
2151 (char *) ptr + posn, size - posn);
2152 if (retval < 0)
2153 return posn;
2154 posn += retval;
2155 } while (posn < size);
2157 freq->stream.avail_in = size;
2158 freq->stream.next_in = (void *)ptr;
2159 do {
2160 freq->stream.next_out = expn;
2161 freq->stream.avail_out = sizeof(expn);
2162 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2163 git_SHA1_Update(&freq->c, expn,
2164 sizeof(expn) - freq->stream.avail_out);
2165 } while (freq->stream.avail_in && freq->zret == Z_OK);
2166 return size;
2169 struct http_object_request *new_http_object_request(const char *base_url,
2170 unsigned char *sha1)
2172 char *hex = sha1_to_hex(sha1);
2173 const char *filename;
2174 char prevfile[PATH_MAX];
2175 int prevlocal;
2176 char prev_buf[PREV_BUF_SIZE];
2177 ssize_t prev_read = 0;
2178 off_t prev_posn = 0;
2179 struct http_object_request *freq;
2181 freq = xcalloc(1, sizeof(*freq));
2182 hashcpy(freq->sha1, sha1);
2183 freq->localfile = -1;
2185 filename = sha1_file_name(sha1);
2186 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2187 "%s.temp", filename);
2189 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2190 unlink_or_warn(prevfile);
2191 rename(freq->tmpfile, prevfile);
2192 unlink_or_warn(freq->tmpfile);
2194 if (freq->localfile != -1)
2195 error("fd leakage in start: %d", freq->localfile);
2196 freq->localfile = open(freq->tmpfile,
2197 O_WRONLY | O_CREAT | O_EXCL, 0666);
2199 * This could have failed due to the "lazy directory creation";
2200 * try to mkdir the last path component.
2202 if (freq->localfile < 0 && errno == ENOENT) {
2203 char *dir = strrchr(freq->tmpfile, '/');
2204 if (dir) {
2205 *dir = 0;
2206 mkdir(freq->tmpfile, 0777);
2207 *dir = '/';
2209 freq->localfile = open(freq->tmpfile,
2210 O_WRONLY | O_CREAT | O_EXCL, 0666);
2213 if (freq->localfile < 0) {
2214 error_errno("Couldn't create temporary file %s", freq->tmpfile);
2215 goto abort;
2218 git_inflate_init(&freq->stream);
2220 git_SHA1_Init(&freq->c);
2222 freq->url = get_remote_object_url(base_url, hex, 0);
2225 * If a previous temp file is present, process what was already
2226 * fetched.
2228 prevlocal = open(prevfile, O_RDONLY);
2229 if (prevlocal != -1) {
2230 do {
2231 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2232 if (prev_read>0) {
2233 if (fwrite_sha1_file(prev_buf,
2235 prev_read,
2236 freq) == prev_read) {
2237 prev_posn += prev_read;
2238 } else {
2239 prev_read = -1;
2242 } while (prev_read > 0);
2243 close(prevlocal);
2245 unlink_or_warn(prevfile);
2248 * Reset inflate/SHA1 if there was an error reading the previous temp
2249 * file; also rewind to the beginning of the local file.
2251 if (prev_read == -1) {
2252 memset(&freq->stream, 0, sizeof(freq->stream));
2253 git_inflate_init(&freq->stream);
2254 git_SHA1_Init(&freq->c);
2255 if (prev_posn>0) {
2256 prev_posn = 0;
2257 lseek(freq->localfile, 0, SEEK_SET);
2258 if (ftruncate(freq->localfile, 0) < 0) {
2259 error_errno("Couldn't truncate temporary file %s",
2260 freq->tmpfile);
2261 goto abort;
2266 freq->slot = get_active_slot();
2268 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2269 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2270 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2271 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2272 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2273 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2276 * If we have successfully processed data from a previous fetch
2277 * attempt, only fetch the data we don't already have.
2279 if (prev_posn>0) {
2280 if (http_is_verbose)
2281 fprintf(stderr,
2282 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2283 hex, (uintmax_t)prev_posn);
2284 http_opt_request_remainder(freq->slot->curl, prev_posn);
2287 return freq;
2289 abort:
2290 free(freq->url);
2291 free(freq);
2292 return NULL;
2295 void process_http_object_request(struct http_object_request *freq)
2297 if (freq->slot == NULL)
2298 return;
2299 freq->curl_result = freq->slot->curl_result;
2300 freq->http_code = freq->slot->http_code;
2301 freq->slot = NULL;
2304 int finish_http_object_request(struct http_object_request *freq)
2306 struct stat st;
2308 close(freq->localfile);
2309 freq->localfile = -1;
2311 process_http_object_request(freq);
2313 if (freq->http_code == 416) {
2314 warning("requested range invalid; we may already have all the data.");
2315 } else if (freq->curl_result != CURLE_OK) {
2316 if (stat(freq->tmpfile, &st) == 0)
2317 if (st.st_size == 0)
2318 unlink_or_warn(freq->tmpfile);
2319 return -1;
2322 git_inflate_end(&freq->stream);
2323 git_SHA1_Final(freq->real_sha1, &freq->c);
2324 if (freq->zret != Z_STREAM_END) {
2325 unlink_or_warn(freq->tmpfile);
2326 return -1;
2328 if (hashcmp(freq->sha1, freq->real_sha1)) {
2329 unlink_or_warn(freq->tmpfile);
2330 return -1;
2332 freq->rename =
2333 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
2335 return freq->rename;
2338 void abort_http_object_request(struct http_object_request *freq)
2340 unlink_or_warn(freq->tmpfile);
2342 release_http_object_request(freq);
2345 void release_http_object_request(struct http_object_request *freq)
2347 if (freq->localfile != -1) {
2348 close(freq->localfile);
2349 freq->localfile = -1;
2351 if (freq->url != NULL) {
2352 FREE_AND_NULL(freq->url);
2354 if (freq->slot != NULL) {
2355 freq->slot->callback_func = NULL;
2356 freq->slot->callback_data = NULL;
2357 release_active_slot(freq->slot);
2358 freq->slot = NULL;