entry: rename 'new' variables
[git/git.git] / http.c
CommitLineData
1c4b6604 1#include "git-compat-util.h"
29508e1e 2#include "http.h"
b2141fc1 3#include "config.h"
2264dfa5 4#include "pack.h"
de1a2fdd 5#include "sideband.h"
fe72d420 6#include "run-command.h"
f39f72d8 7#include "url.h"
6a56993b 8#include "urlmatch.h"
148bb6a7 9#include "credential.h"
745c7c8e 10#include "version.h"
047ec602 11#include "pkt-line.h"
93f7d910 12#include "gettext.h"
f4113cac 13#include "transport.h"
4f39cd82 14#include "packfile.h"
19113a26 15#include "protocol.h"
29508e1e 16
74c682d3 17static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
c915f11e
EW
18#if LIBCURL_VERSION_NUM >= 0x070a08
19long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
20#else
21long int git_curl_ipresolve;
22#endif
4251ccbd 23int active_requests;
e9176745 24int http_is_verbose;
37ee680d 25ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
29508e1e 26
b8ac9230
MS
27#if LIBCURL_VERSION_NUM >= 0x070a06
28#define LIBCURL_CAN_HANDLE_AUTH_ANY
29#endif
30
ad75ebe5
TRC
31static int min_curl_sessions = 1;
32static int curl_session_count;
29508e1e 33#ifdef USE_CURL_MULTI
cc3530e8
MH
34static int max_requests = -1;
35static CURLM *curlm;
29508e1e
NH
36#endif
37#ifndef NO_CURL_EASY_DUPHANDLE
cc3530e8 38static CURL *curl_default;
29508e1e 39#endif
5424bc55
TRC
40
41#define PREV_BUF_SIZE 4096
5424bc55 42
29508e1e
NH
43char curl_errorstr[CURL_ERROR_SIZE];
44
cc3530e8 45static int curl_ssl_verify = -1;
4bc444eb 46static int curl_ssl_try;
4251ccbd 47static const char *ssl_cert;
f6f2a9e4 48static const char *ssl_cipherlist;
01861cb7
EP
49static const char *ssl_version;
50static 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
62};
ef52aafa 63#if LIBCURL_VERSION_NUM >= 0x070903
4251ccbd 64static const char *ssl_key;
29508e1e
NH
65#endif
66#if LIBCURL_VERSION_NUM >= 0x070908
4251ccbd 67static const char *ssl_capath;
29508e1e 68#endif
aeff8a61
CE
69#if LIBCURL_VERSION_NUM >= 0x072c00
70static const char *ssl_pinnedkey;
71#endif
4251ccbd 72static const char *ssl_cainfo;
cc3530e8
MH
73static long curl_low_speed_limit = -1;
74static long curl_low_speed_time = -1;
4251ccbd
JH
75static int curl_ftp_no_epsv;
76static const char *curl_http_proxy;
d445fda4 77static const char *curl_no_proxy;
ef976395
KF
78static const char *http_proxy_authmethod;
79static struct {
80 const char *name;
81 long curlauth_param;
82} proxy_authmethods[] = {
83 { "basic", CURLAUTH_BASIC },
84 { "digest", CURLAUTH_DIGEST },
85 { "negotiate", CURLAUTH_GSSNEGOTIATE },
86 { "ntlm", CURLAUTH_NTLM },
87#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
88 { "anyauth", CURLAUTH_ANY },
89#endif
90 /*
91 * CURLAUTH_DIGEST_IE has no corresponding command-line option in
92 * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
93 * here, too
94 */
95};
dd5df538 96#ifdef CURLGSSAPI_DELEGATION_FLAG
26a7b234
PS
97static const char *curl_deleg;
98static struct {
99 const char *name;
100 long curl_deleg_param;
101} curl_deleg_levels[] = {
102 { "none", CURLGSSAPI_DELEGATION_NONE },
103 { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
104 { "always", CURLGSSAPI_DELEGATION_FLAG },
105};
106#endif
107
372370f1
KF
108static struct credential proxy_auth = CREDENTIAL_INIT;
109static const char *curl_proxyuserpwd;
bcfb95dd 110static const char *curl_cookie_file;
912b2acf 111static int curl_save_cookies;
2501aff8 112struct credential http_auth = CREDENTIAL_INIT;
a4ddbc33 113static int http_proactive_auth;
b1d1058c 114static const char *user_agent;
40a18fc7 115static int curl_empty_auth = -1;
29508e1e 116
50d34137
JK
117enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
118
30dd9163
ML
119#if LIBCURL_VERSION_NUM >= 0x071700
120/* Use CURLOPT_KEYPASSWD as is */
121#elif LIBCURL_VERSION_NUM >= 0x070903
122#define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
123#else
124#define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
125#endif
126
148bb6a7 127static struct credential cert_auth = CREDENTIAL_INIT;
30dd9163 128static int ssl_cert_password_required;
4dbe6646 129#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
130static unsigned long http_auth_methods = CURLAUTH_ANY;
40a18fc7
JK
131static int http_auth_methods_restricted;
132/* Modes for which empty_auth cannot actually help us. */
133static unsigned long empty_auth_useless =
134 CURLAUTH_BASIC
135#ifdef CURLAUTH_DIGEST_IE
136 | CURLAUTH_DIGEST_IE
137#endif
138 | CURLAUTH_DIGEST;
4dbe6646 139#endif
30dd9163 140
cc3530e8 141static struct curl_slist *pragma_header;
5424bc55 142static struct curl_slist *no_pragma_header;
8cb01e2f 143static struct curl_slist *extra_http_headers;
e9176745 144
4251ccbd 145static struct active_request_slot *active_queue_head;
29508e1e 146
f18604bb
YE
147static char *cached_accept_language;
148
a04ff3ec 149size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
29508e1e
NH
150{
151 size_t size = eltsize * nmemb;
f444e528
JH
152 struct buffer *buffer = buffer_;
153
028c2976
MH
154 if (size > buffer->buf.len - buffer->posn)
155 size = buffer->buf.len - buffer->posn;
156 memcpy(ptr, buffer->buf.buf + buffer->posn, size);
29508e1e 157 buffer->posn += size;
028c2976 158
29508e1e
NH
159 return size;
160}
161
3944ba0c
MS
162#ifndef NO_CURL_IOCTL
163curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
164{
165 struct buffer *buffer = clientp;
166
167 switch (cmd) {
168 case CURLIOCMD_NOP:
169 return CURLIOE_OK;
170
171 case CURLIOCMD_RESTARTREAD:
172 buffer->posn = 0;
173 return CURLIOE_OK;
174
175 default:
176 return CURLIOE_UNKNOWNCMD;
177 }
178}
179#endif
180
a04ff3ec 181size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
29508e1e
NH
182{
183 size_t size = eltsize * nmemb;
f444e528
JH
184 struct strbuf *buffer = buffer_;
185
028c2976 186 strbuf_add(buffer, ptr, size);
29508e1e
NH
187 return size;
188}
189
a04ff3ec 190size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
29508e1e 191{
29508e1e
NH
192 return eltsize * nmemb;
193}
194
b90a3d7b
JH
195static void closedown_active_slot(struct active_request_slot *slot)
196{
197 active_requests--;
198 slot->in_use = 0;
199}
200
201static void finish_active_slot(struct active_request_slot *slot)
202{
203 closedown_active_slot(slot);
204 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
205
206 if (slot->finished != NULL)
207 (*slot->finished) = 1;
208
209 /* Store slot results so they can be read after the slot is reused */
210 if (slot->results != NULL) {
211 slot->results->curl_result = slot->curl_result;
212 slot->results->http_code = slot->http_code;
213#if LIBCURL_VERSION_NUM >= 0x070a08
214 curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
215 &slot->results->auth_avail);
216#else
217 slot->results->auth_avail = 0;
218#endif
372370f1
KF
219
220 curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
221 &slot->results->http_connectcode);
b90a3d7b
JH
222 }
223
224 /* Run callback if appropriate */
225 if (slot->callback_func != NULL)
226 slot->callback_func(slot->callback_data);
227}
228
d8b6b84d
EW
229static void xmulti_remove_handle(struct active_request_slot *slot)
230{
231#ifdef USE_CURL_MULTI
232 curl_multi_remove_handle(curlm, slot->curl);
233#endif
234}
235
29508e1e
NH
236#ifdef USE_CURL_MULTI
237static void process_curl_messages(void)
238{
239 int num_messages;
240 struct active_request_slot *slot;
241 CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
242
243 while (curl_message != NULL) {
244 if (curl_message->msg == CURLMSG_DONE) {
245 int curl_result = curl_message->data.result;
246 slot = active_queue_head;
247 while (slot != NULL &&
248 slot->curl != curl_message->easy_handle)
249 slot = slot->next;
250 if (slot != NULL) {
d8b6b84d 251 xmulti_remove_handle(slot);
29508e1e
NH
252 slot->curl_result = curl_result;
253 finish_active_slot(slot);
254 } else {
255 fprintf(stderr, "Received DONE message for unknown request!\n");
256 }
257 } else {
258 fprintf(stderr, "Unknown CURL message received: %d\n",
259 (int)curl_message->msg);
260 }
261 curl_message = curl_multi_info_read(curlm, &num_messages);
262 }
263}
264#endif
265
ef90d6d4 266static int http_options(const char *var, const char *value, void *cb)
29508e1e
NH
267{
268 if (!strcmp("http.sslverify", var)) {
7059cd99 269 curl_ssl_verify = git_config_bool(var, value);
29508e1e
NH
270 return 0;
271 }
f6f2a9e4
LKS
272 if (!strcmp("http.sslcipherlist", var))
273 return git_config_string(&ssl_cipherlist, var, value);
01861cb7
EP
274 if (!strcmp("http.sslversion", var))
275 return git_config_string(&ssl_version, var, value);
7059cd99 276 if (!strcmp("http.sslcert", var))
8d154964 277 return git_config_pathname(&ssl_cert, var, value);
ef52aafa 278#if LIBCURL_VERSION_NUM >= 0x070903
7059cd99 279 if (!strcmp("http.sslkey", var))
8d154964 280 return git_config_pathname(&ssl_key, var, value);
29508e1e
NH
281#endif
282#if LIBCURL_VERSION_NUM >= 0x070908
7059cd99 283 if (!strcmp("http.sslcapath", var))
bf9acba2 284 return git_config_pathname(&ssl_capath, var, value);
29508e1e 285#endif
7059cd99 286 if (!strcmp("http.sslcainfo", var))
bf9acba2 287 return git_config_pathname(&ssl_cainfo, var, value);
754ae192 288 if (!strcmp("http.sslcertpasswordprotected", var)) {
3f4ccd2b 289 ssl_cert_password_required = git_config_bool(var, value);
754ae192
ML
290 return 0;
291 }
4bc444eb
MV
292 if (!strcmp("http.ssltry", var)) {
293 curl_ssl_try = git_config_bool(var, value);
294 return 0;
295 }
ad75ebe5
TRC
296 if (!strcmp("http.minsessions", var)) {
297 min_curl_sessions = git_config_int(var, value);
298#ifndef USE_CURL_MULTI
299 if (min_curl_sessions > 1)
300 min_curl_sessions = 1;
301#endif
302 return 0;
303 }
a6080a0a 304#ifdef USE_CURL_MULTI
29508e1e 305 if (!strcmp("http.maxrequests", var)) {
7059cd99 306 max_requests = git_config_int(var, value);
29508e1e
NH
307 return 0;
308 }
309#endif
29508e1e 310 if (!strcmp("http.lowspeedlimit", var)) {
7059cd99 311 curl_low_speed_limit = (long)git_config_int(var, value);
29508e1e
NH
312 return 0;
313 }
314 if (!strcmp("http.lowspeedtime", var)) {
7059cd99 315 curl_low_speed_time = (long)git_config_int(var, value);
29508e1e
NH
316 return 0;
317 }
318
3ea099d4
SK
319 if (!strcmp("http.noepsv", var)) {
320 curl_ftp_no_epsv = git_config_bool(var, value);
321 return 0;
322 }
7059cd99
JH
323 if (!strcmp("http.proxy", var))
324 return git_config_string(&curl_http_proxy, var, value);
3ea099d4 325
ef976395
KF
326 if (!strcmp("http.proxyauthmethod", var))
327 return git_config_string(&http_proxy_authmethod, var, value);
328
bcfb95dd 329 if (!strcmp("http.cookiefile", var))
e5a39ad8 330 return git_config_pathname(&curl_cookie_file, var, value);
912b2acf
DB
331 if (!strcmp("http.savecookies", var)) {
332 curl_save_cookies = git_config_bool(var, value);
333 return 0;
334 }
bcfb95dd 335
de1a2fdd 336 if (!strcmp("http.postbuffer", var)) {
37ee680d
DT
337 http_post_buffer = git_config_ssize_t(var, value);
338 if (http_post_buffer < 0)
339 warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
de1a2fdd
SP
340 if (http_post_buffer < LARGE_PACKET_MAX)
341 http_post_buffer = LARGE_PACKET_MAX;
342 return 0;
343 }
344
b1d1058c
SO
345 if (!strcmp("http.useragent", var))
346 return git_config_string(&user_agent, var, value);
347
121061f6 348 if (!strcmp("http.emptyauth", var)) {
40a18fc7
JK
349 if (value && !strcmp("auto", value))
350 curl_empty_auth = -1;
351 else
352 curl_empty_auth = git_config_bool(var, value);
121061f6 353 return 0;
354 }
355
26a7b234 356 if (!strcmp("http.delegation", var)) {
dd5df538 357#ifdef CURLGSSAPI_DELEGATION_FLAG
26a7b234
PS
358 return git_config_string(&curl_deleg, var, value);
359#else
360 warning(_("Delegation control is not supported with cURL < 7.22.0"));
361 return 0;
362#endif
363 }
364
aeff8a61
CE
365 if (!strcmp("http.pinnedpubkey", var)) {
366#if LIBCURL_VERSION_NUM >= 0x072c00
367 return git_config_pathname(&ssl_pinnedkey, var, value);
368#else
369 warning(_("Public key pinning not supported with cURL < 7.44.0"));
370 return 0;
371#endif
372 }
e79112d2 373
8cb01e2f
JS
374 if (!strcmp("http.extraheader", var)) {
375 if (!value) {
376 return config_error_nonbool(var);
377 } else if (!*value) {
378 curl_slist_free_all(extra_http_headers);
379 extra_http_headers = NULL;
380 } else {
381 extra_http_headers =
382 curl_slist_append(extra_http_headers, value);
383 }
384 return 0;
385 }
386
50d34137
JK
387 if (!strcmp("http.followredirects", var)) {
388 if (value && !strcmp(value, "initial"))
389 http_follow_config = HTTP_FOLLOW_INITIAL;
390 else if (git_config_bool(var, value))
391 http_follow_config = HTTP_FOLLOW_ALWAYS;
392 else
393 http_follow_config = HTTP_FOLLOW_NONE;
394 return 0;
395 }
396
29508e1e 397 /* Fall back on the default ones */
ef90d6d4 398 return git_default_config(var, value, cb);
29508e1e
NH
399}
400
40a18fc7
JK
401static int curl_empty_auth_enabled(void)
402{
403 if (curl_empty_auth >= 0)
404 return curl_empty_auth;
405
406#ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
407 /*
408 * Our libcurl is too old to do AUTH_ANY in the first place;
409 * just default to turning the feature off.
410 */
411#else
412 /*
413 * In the automatic case, kick in the empty-auth
414 * hack as long as we would potentially try some
415 * method more exotic than "Basic" or "Digest".
416 *
417 * But only do this when this is our second or
418 * subsequent request, as by then we know what
419 * methods are available.
420 */
421 if (http_auth_methods_restricted &&
422 (http_auth_methods & ~empty_auth_useless))
423 return 1;
424#endif
425 return 0;
426}
427
c33976cb
JH
428static void init_curl_http_auth(CURL *result)
429{
5275c308 430 if (!http_auth.username || !*http_auth.username) {
40a18fc7 431 if (curl_empty_auth_enabled())
121061f6 432 curl_easy_setopt(result, CURLOPT_USERPWD, ":");
6f4c347c 433 return;
121061f6 434 }
6f4c347c
JK
435
436 credential_fill(&http_auth);
437
438#if LIBCURL_VERSION_NUM >= 0x071301
439 curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
440 curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
441#else
442 {
aa0834a0 443 static struct strbuf up = STRBUF_INIT;
a94cf2cb
BC
444 /*
445 * Note that we assume we only ever have a single set of
446 * credentials in a given program run, so we do not have
447 * to worry about updating this buffer, only setting its
448 * initial value.
449 */
450 if (!up.len)
451 strbuf_addf(&up, "%s:%s",
452 http_auth.username, http_auth.password);
aa0834a0 453 curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
c33976cb 454 }
6f4c347c 455#endif
c33976cb
JH
456}
457
ef976395
KF
458/* *var must be free-able */
459static void var_override(const char **var, char *value)
460{
461 if (value) {
462 free((void *)*var);
463 *var = xstrdup(value);
464 }
465}
466
372370f1
KF
467static void set_proxyauth_name_password(CURL *result)
468{
469#if LIBCURL_VERSION_NUM >= 0x071301
470 curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
471 proxy_auth.username);
472 curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
473 proxy_auth.password);
474#else
475 struct strbuf s = STRBUF_INIT;
476
477 strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
478 strbuf_addch(&s, ':');
479 strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
480 curl_proxyuserpwd = strbuf_detach(&s, NULL);
481 curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
482#endif
483}
484
ef976395
KF
485static void init_curl_proxy_auth(CURL *result)
486{
372370f1
KF
487 if (proxy_auth.username) {
488 if (!proxy_auth.password)
489 credential_fill(&proxy_auth);
490 set_proxyauth_name_password(result);
491 }
492
ef976395
KF
493 var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
494
495#if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
496 if (http_proxy_authmethod) {
497 int i;
498 for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
499 if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
500 curl_easy_setopt(result, CURLOPT_PROXYAUTH,
501 proxy_authmethods[i].curlauth_param);
502 break;
503 }
504 }
505 if (i == ARRAY_SIZE(proxy_authmethods)) {
506 warning("unsupported proxy authentication method %s: using anyauth",
507 http_proxy_authmethod);
508 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
509 }
510 }
511 else
512 curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
513#endif
514}
515
30dd9163
ML
516static int has_cert_password(void)
517{
30dd9163
ML
518 if (ssl_cert == NULL || ssl_cert_password_required != 1)
519 return 0;
148bb6a7
JK
520 if (!cert_auth.password) {
521 cert_auth.protocol = xstrdup("cert");
75e9a405 522 cert_auth.username = xstrdup("");
148bb6a7
JK
523 cert_auth.path = xstrdup(ssl_cert);
524 credential_fill(&cert_auth);
525 }
526 return 1;
30dd9163
ML
527}
528
47ce1153
JK
529#if LIBCURL_VERSION_NUM >= 0x071900
530static void set_curl_keepalive(CURL *c)
531{
532 curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
533}
534
535#elif LIBCURL_VERSION_NUM >= 0x071000
a15d069a
EW
536static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
537{
538 int ka = 1;
539 int rc;
540 socklen_t len = (socklen_t)sizeof(ka);
541
542 if (type != CURLSOCKTYPE_IPCXN)
543 return 0;
544
545 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
546 if (rc < 0)
d2e255ee 547 warning_errno("unable to set SO_KEEPALIVE on socket");
a15d069a
EW
548
549 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
550}
551
47ce1153
JK
552static void set_curl_keepalive(CURL *c)
553{
554 curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
555}
556
557#else
558static void set_curl_keepalive(CURL *c)
559{
560 /* not supported on older curl versions */
561}
562#endif
563
74c682d3
EP
564static void redact_sensitive_header(struct strbuf *header)
565{
566 const char *sensitive_header;
567
568 if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
569 skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
570 /* The first token is the type, which is OK to log */
571 while (isspace(*sensitive_header))
572 sensitive_header++;
573 while (*sensitive_header && !isspace(*sensitive_header))
574 sensitive_header++;
575 /* Everything else is opaque and possibly sensitive */
576 strbuf_setlen(header, sensitive_header - header->buf);
577 strbuf_addstr(header, " <redacted>");
578 }
579}
580
581static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
582{
583 struct strbuf out = STRBUF_INIT;
584 struct strbuf **headers, **header;
585
586 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
587 text, (long)size, (long)size);
588 trace_strbuf(&trace_curl, &out);
589 strbuf_reset(&out);
590 strbuf_add(&out, ptr, size);
591 headers = strbuf_split_max(&out, '\n', 0);
592
593 for (header = headers; *header; header++) {
594 if (hide_sensitive_header)
595 redact_sensitive_header(*header);
596 strbuf_insert((*header), 0, text, strlen(text));
597 strbuf_insert((*header), strlen(text), ": ", 2);
598 strbuf_rtrim((*header));
599 strbuf_addch((*header), '\n');
600 trace_strbuf(&trace_curl, (*header));
601 }
602 strbuf_list_free(headers);
603 strbuf_release(&out);
604}
605
606static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
607{
608 size_t i;
609 struct strbuf out = STRBUF_INIT;
610 unsigned int width = 60;
611
612 strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
613 text, (long)size, (long)size);
614 trace_strbuf(&trace_curl, &out);
615
616 for (i = 0; i < size; i += width) {
617 size_t w;
618
619 strbuf_reset(&out);
620 strbuf_addf(&out, "%s: ", text);
621 for (w = 0; (w < width) && (i + w < size); w++) {
622 unsigned char ch = ptr[i + w];
623
624 strbuf_addch(&out,
625 (ch >= 0x20) && (ch < 0x80)
626 ? ch : '.');
627 }
628 strbuf_addch(&out, '\n');
629 trace_strbuf(&trace_curl, &out);
630 }
631 strbuf_release(&out);
632}
633
634static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
635{
636 const char *text;
637 enum { NO_FILTER = 0, DO_FILTER = 1 };
638
639 switch (type) {
640 case CURLINFO_TEXT:
641 trace_printf_key(&trace_curl, "== Info: %s", data);
d0e99839 642 break;
74c682d3
EP
643 case CURLINFO_HEADER_OUT:
644 text = "=> Send header";
645 curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
646 break;
647 case CURLINFO_DATA_OUT:
648 text = "=> Send data";
649 curl_dump_data(text, (unsigned char *)data, size);
650 break;
651 case CURLINFO_SSL_DATA_OUT:
652 text = "=> Send SSL data";
653 curl_dump_data(text, (unsigned char *)data, size);
654 break;
655 case CURLINFO_HEADER_IN:
656 text = "<= Recv header";
657 curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
658 break;
659 case CURLINFO_DATA_IN:
660 text = "<= Recv data";
661 curl_dump_data(text, (unsigned char *)data, size);
662 break;
663 case CURLINFO_SSL_DATA_IN:
664 text = "<= Recv SSL data";
665 curl_dump_data(text, (unsigned char *)data, size);
666 break;
d0e99839
JK
667
668 default: /* we ignore unknown types by default */
669 return 0;
74c682d3
EP
670 }
671 return 0;
672}
673
674void setup_curl_trace(CURL *handle)
675{
676 if (!trace_want(&trace_curl))
677 return;
678 curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
679 curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
680 curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
681}
682
f18777ba 683#ifdef CURLPROTO_HTTP
a768a022 684static long get_curl_allowed_protocols(int from_user)
aeae4db1
BW
685{
686 long allowed_protocols = 0;
687
a768a022 688 if (is_transport_allowed("http", from_user))
aeae4db1 689 allowed_protocols |= CURLPROTO_HTTP;
a768a022 690 if (is_transport_allowed("https", from_user))
aeae4db1 691 allowed_protocols |= CURLPROTO_HTTPS;
a768a022 692 if (is_transport_allowed("ftp", from_user))
aeae4db1 693 allowed_protocols |= CURLPROTO_FTP;
a768a022 694 if (is_transport_allowed("ftps", from_user))
aeae4db1
BW
695 allowed_protocols |= CURLPROTO_FTPS;
696
697 return allowed_protocols;
698}
f18777ba 699#endif
74c682d3 700
4251ccbd 701static CURL *get_curl_handle(void)
11979b98 702{
4251ccbd 703 CURL *result = curl_easy_init();
11979b98 704
faa3807c
BR
705 if (!result)
706 die("curl_easy_init failed");
707
a5ccc597
JH
708 if (!curl_ssl_verify) {
709 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
710 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
711 } else {
712 /* Verify authenticity of the peer's certificate */
713 curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
714 /* The name in the cert must match whom we tried to connect */
715 curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
716 }
717
11979b98
JH
718#if LIBCURL_VERSION_NUM >= 0x070907
719 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
720#endif
b8ac9230 721#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
525ecd26 722 curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
b8ac9230 723#endif
11979b98 724
dd5df538 725#ifdef CURLGSSAPI_DELEGATION_FLAG
26a7b234
PS
726 if (curl_deleg) {
727 int i;
728 for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
729 if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
730 curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
731 curl_deleg_levels[i].curl_deleg_param);
732 break;
733 }
734 }
735 if (i == ARRAY_SIZE(curl_deleg_levels))
736 warning("Unknown delegation method '%s': using default",
737 curl_deleg);
738 }
739#endif
740
a4ddbc33
JK
741 if (http_proactive_auth)
742 init_curl_http_auth(result);
743
01861cb7
EP
744 if (getenv("GIT_SSL_VERSION"))
745 ssl_version = getenv("GIT_SSL_VERSION");
746 if (ssl_version && *ssl_version) {
747 int i;
748 for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
749 if (!strcmp(ssl_version, sslversions[i].name)) {
750 curl_easy_setopt(result, CURLOPT_SSLVERSION,
751 sslversions[i].ssl_version);
752 break;
753 }
754 }
755 if (i == ARRAY_SIZE(sslversions))
756 warning("unsupported ssl version %s: using default",
757 ssl_version);
758 }
759
f6f2a9e4
LKS
760 if (getenv("GIT_SSL_CIPHER_LIST"))
761 ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
f6f2a9e4
LKS
762 if (ssl_cipherlist != NULL && *ssl_cipherlist)
763 curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
764 ssl_cipherlist);
765
11979b98
JH
766 if (ssl_cert != NULL)
767 curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
30dd9163 768 if (has_cert_password())
148bb6a7 769 curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
ef52aafa 770#if LIBCURL_VERSION_NUM >= 0x070903
11979b98
JH
771 if (ssl_key != NULL)
772 curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
773#endif
774#if LIBCURL_VERSION_NUM >= 0x070908
775 if (ssl_capath != NULL)
776 curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
aeff8a61
CE
777#endif
778#if LIBCURL_VERSION_NUM >= 0x072c00
779 if (ssl_pinnedkey != NULL)
780 curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
11979b98
JH
781#endif
782 if (ssl_cainfo != NULL)
783 curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
11979b98
JH
784
785 if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
786 curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
787 curl_low_speed_limit);
788 curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
789 curl_low_speed_time);
790 }
791
b2581164 792 curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
311e2ea0
TRC
793#if LIBCURL_VERSION_NUM >= 0x071301
794 curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
795#elif LIBCURL_VERSION_NUM >= 0x071101
796 curl_easy_setopt(result, CURLOPT_POST301, 1);
797#endif
f18777ba 798#ifdef CURLPROTO_HTTP
aeae4db1 799 curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
a768a022 800 get_curl_allowed_protocols(0));
aeae4db1 801 curl_easy_setopt(result, CURLOPT_PROTOCOLS,
a768a022 802 get_curl_allowed_protocols(-1));
f4113cac 803#else
f962ddf6
BW
804 warning("protocol restrictions not applied to curl redirects because\n"
805 "your curl version is too old (>= 7.19.4)");
f4113cac 806#endif
7982d74e 807 if (getenv("GIT_CURL_VERBOSE"))
74c682d3
EP
808 curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
809 setup_curl_trace(result);
7982d74e 810
b1d1058c 811 curl_easy_setopt(result, CURLOPT_USERAGENT,
745c7c8e 812 user_agent ? user_agent : git_user_agent());
20fc9bc5 813
3ea099d4
SK
814 if (curl_ftp_no_epsv)
815 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
816
4bc444eb
MV
817#ifdef CURLOPT_USE_SSL
818 if (curl_ssl_try)
819 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
820#endif
821
372370f1
KF
822 /*
823 * CURL also examines these variables as a fallback; but we need to query
824 * them here in order to decide whether to prompt for missing password (cf.
825 * init_curl_proxy_auth()).
826 *
827 * Unlike many other common environment variables, these are historically
828 * lowercase only. It appears that CURL did not know this and implemented
829 * only uppercase variants, which was later corrected to take both - with
830 * the exception of http_proxy, which is lowercase only also in CURL. As
831 * the lowercase versions are the historical quasi-standard, they take
832 * precedence here, as in CURL.
833 */
834 if (!curl_http_proxy) {
d63ed6ef 835 if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
372370f1
KF
836 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
837 var_override(&curl_http_proxy, getenv("https_proxy"));
838 } else {
839 var_override(&curl_http_proxy, getenv("http_proxy"));
840 }
841 if (!curl_http_proxy) {
842 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
843 var_override(&curl_http_proxy, getenv("all_proxy"));
844 }
845 }
846
57415089
SR
847 if (curl_http_proxy && curl_http_proxy[0] == '\0') {
848 /*
849 * Handle case with the empty http.proxy value here to keep
850 * common code clean.
851 * NB: empty option disables proxying at all.
852 */
853 curl_easy_setopt(result, CURLOPT_PROXY, "");
854 } else if (curl_http_proxy) {
6d7afe07 855#if LIBCURL_VERSION_NUM >= 0x071800
87f8a0b2
JH
856 if (starts_with(curl_http_proxy, "socks5h"))
857 curl_easy_setopt(result,
858 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
859 else if (starts_with(curl_http_proxy, "socks5"))
6d7afe07
PT
860 curl_easy_setopt(result,
861 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
862 else if (starts_with(curl_http_proxy, "socks4a"))
863 curl_easy_setopt(result,
864 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
865 else if (starts_with(curl_http_proxy, "socks"))
866 curl_easy_setopt(result,
867 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
82b6803a
WS
868#endif
869#if LIBCURL_VERSION_NUM >= 0x073400
870 else if (starts_with(curl_http_proxy, "https"))
871 curl_easy_setopt(result,
872 CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
6d7afe07 873#endif
372370f1
KF
874 if (strstr(curl_http_proxy, "://"))
875 credential_from_url(&proxy_auth, curl_http_proxy);
876 else {
877 struct strbuf url = STRBUF_INIT;
878 strbuf_addf(&url, "http://%s", curl_http_proxy);
879 credential_from_url(&proxy_auth, url.buf);
880 strbuf_release(&url);
881 }
882
ae51d911
SR
883 if (!proxy_auth.host)
884 die("Invalid proxy URL '%s'", curl_http_proxy);
885
372370f1 886 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
d445fda4
JX
887#if LIBCURL_VERSION_NUM >= 0x071304
888 var_override(&curl_no_proxy, getenv("NO_PROXY"));
889 var_override(&curl_no_proxy, getenv("no_proxy"));
890 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
891#endif
5841520b 892 }
ef976395 893 init_curl_proxy_auth(result);
9c5665aa 894
47ce1153 895 set_curl_keepalive(result);
a15d069a 896
11979b98
JH
897 return result;
898}
899
7059cd99
JH
900static void set_from_env(const char **var, const char *envname)
901{
902 const char *val = getenv(envname);
903 if (val)
904 *var = val;
905}
906
19113a26
BW
907static void protocol_http_header(void)
908{
909 if (get_protocol_version_config() > 0) {
910 struct strbuf protocol_header = STRBUF_INIT;
911
912 strbuf_addf(&protocol_header, GIT_PROTOCOL_HEADER ": version=%d",
913 get_protocol_version_config());
914
915
916 extra_http_headers = curl_slist_append(extra_http_headers,
917 protocol_header.buf);
918 strbuf_release(&protocol_header);
919 }
920}
921
a4ddbc33 922void http_init(struct remote *remote, const char *url, int proactive_auth)
29508e1e
NH
923{
924 char *low_speed_limit;
925 char *low_speed_time;
6a56993b
KM
926 char *normalized_url;
927 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
928
929 config.section = "http";
930 config.key = NULL;
931 config.collect_fn = http_options;
932 config.cascade_fn = git_default_config;
933 config.cb = NULL;
29508e1e 934
e9176745 935 http_is_verbose = 0;
6a56993b 936 normalized_url = url_normalize(url, &config.url);
e9176745 937
6a56993b
KM
938 git_config(urlmatch_config_entry, &config);
939 free(normalized_url);
7059cd99 940
faa3807c
BR
941 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
942 die("curl_global_init failed");
29508e1e 943
a4ddbc33
JK
944 http_proactive_auth = proactive_auth;
945
9fc6440d
MH
946 if (remote && remote->http_proxy)
947 curl_http_proxy = xstrdup(remote->http_proxy);
948
ef976395
KF
949 if (remote)
950 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
951
19113a26
BW
952 protocol_http_header();
953
8cb01e2f
JS
954 pragma_header = curl_slist_append(http_copy_default_headers(),
955 "Pragma: no-cache");
956 no_pragma_header = curl_slist_append(http_copy_default_headers(),
957 "Pragma:");
29508e1e
NH
958
959#ifdef USE_CURL_MULTI
960 {
961 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
962 if (http_max_requests != NULL)
963 max_requests = atoi(http_max_requests);
964 }
965
966 curlm = curl_multi_init();
8837eb47
JK
967 if (!curlm)
968 die("curl_multi_init failed");
29508e1e
NH
969#endif
970
971 if (getenv("GIT_SSL_NO_VERIFY"))
972 curl_ssl_verify = 0;
973
7059cd99 974 set_from_env(&ssl_cert, "GIT_SSL_CERT");
ef52aafa 975#if LIBCURL_VERSION_NUM >= 0x070903
7059cd99 976 set_from_env(&ssl_key, "GIT_SSL_KEY");
29508e1e
NH
977#endif
978#if LIBCURL_VERSION_NUM >= 0x070908
7059cd99 979 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
29508e1e 980#endif
7059cd99 981 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
29508e1e 982
b1d1058c
SO
983 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
984
29508e1e
NH
985 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
986 if (low_speed_limit != NULL)
987 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
988 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
989 if (low_speed_time != NULL)
990 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
991
29508e1e
NH
992 if (curl_ssl_verify == -1)
993 curl_ssl_verify = 1;
994
ad75ebe5 995 curl_session_count = 0;
29508e1e
NH
996#ifdef USE_CURL_MULTI
997 if (max_requests < 1)
998 max_requests = DEFAULT_MAX_REQUESTS;
999#endif
1000
3ea099d4
SK
1001 if (getenv("GIT_CURL_FTP_NO_EPSV"))
1002 curl_ftp_no_epsv = 1;
1003
deba4937 1004 if (url) {
148bb6a7 1005 credential_from_url(&http_auth, url);
754ae192
ML
1006 if (!ssl_cert_password_required &&
1007 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
59556548 1008 starts_with(url, "https://"))
30dd9163
ML
1009 ssl_cert_password_required = 1;
1010 }
c33976cb 1011
29508e1e
NH
1012#ifndef NO_CURL_EASY_DUPHANDLE
1013 curl_default = get_curl_handle();
1014#endif
1015}
1016
1017void http_cleanup(void)
1018{
1019 struct active_request_slot *slot = active_queue_head;
29508e1e
NH
1020
1021 while (slot != NULL) {
3278cd0a 1022 struct active_request_slot *next = slot->next;
f23d1f76 1023 if (slot->curl != NULL) {
d8b6b84d 1024 xmulti_remove_handle(slot);
29508e1e 1025 curl_easy_cleanup(slot->curl);
f23d1f76 1026 }
3278cd0a
SP
1027 free(slot);
1028 slot = next;
29508e1e 1029 }
3278cd0a 1030 active_queue_head = NULL;
29508e1e
NH
1031
1032#ifndef NO_CURL_EASY_DUPHANDLE
1033 curl_easy_cleanup(curl_default);
1034#endif
1035
1036#ifdef USE_CURL_MULTI
1037 curl_multi_cleanup(curlm);
1038#endif
1039 curl_global_cleanup();
b3ca4e4e 1040
8cb01e2f
JS
1041 curl_slist_free_all(extra_http_headers);
1042 extra_http_headers = NULL;
1043
b3ca4e4e 1044 curl_slist_free_all(pragma_header);
3278cd0a 1045 pragma_header = NULL;
9fc6440d 1046
e9176745
TRC
1047 curl_slist_free_all(no_pragma_header);
1048 no_pragma_header = NULL;
1049
9fc6440d 1050 if (curl_http_proxy) {
e4a80ecf 1051 free((void *)curl_http_proxy);
9fc6440d
MH
1052 curl_http_proxy = NULL;
1053 }
30dd9163 1054
372370f1
KF
1055 if (proxy_auth.password) {
1056 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
6a83d902 1057 FREE_AND_NULL(proxy_auth.password);
372370f1
KF
1058 }
1059
1060 free((void *)curl_proxyuserpwd);
1061 curl_proxyuserpwd = NULL;
1062
ef976395
KF
1063 free((void *)http_proxy_authmethod);
1064 http_proxy_authmethod = NULL;
1065
148bb6a7
JK
1066 if (cert_auth.password != NULL) {
1067 memset(cert_auth.password, 0, strlen(cert_auth.password));
6a83d902 1068 FREE_AND_NULL(cert_auth.password);
30dd9163
ML
1069 }
1070 ssl_cert_password_required = 0;
f18604bb 1071
6a83d902 1072 FREE_AND_NULL(cached_accept_language);
29508e1e
NH
1073}
1074
29508e1e
NH
1075struct active_request_slot *get_active_slot(void)
1076{
1077 struct active_request_slot *slot = active_queue_head;
1078 struct active_request_slot *newslot;
1079
1080#ifdef USE_CURL_MULTI
1081 int num_transfers;
1082
1083 /* Wait for a slot to open up if the queue is full */
1084 while (active_requests >= max_requests) {
1085 curl_multi_perform(curlm, &num_transfers);
4251ccbd 1086 if (num_transfers < active_requests)
29508e1e 1087 process_curl_messages();
29508e1e
NH
1088 }
1089#endif
1090
4251ccbd 1091 while (slot != NULL && slot->in_use)
29508e1e 1092 slot = slot->next;
4251ccbd 1093
29508e1e
NH
1094 if (slot == NULL) {
1095 newslot = xmalloc(sizeof(*newslot));
1096 newslot->curl = NULL;
1097 newslot->in_use = 0;
1098 newslot->next = NULL;
1099
1100 slot = active_queue_head;
1101 if (slot == NULL) {
1102 active_queue_head = newslot;
1103 } else {
4251ccbd 1104 while (slot->next != NULL)
29508e1e 1105 slot = slot->next;
29508e1e
NH
1106 slot->next = newslot;
1107 }
1108 slot = newslot;
1109 }
1110
1111 if (slot->curl == NULL) {
1112#ifdef NO_CURL_EASY_DUPHANDLE
1113 slot->curl = get_curl_handle();
1114#else
1115 slot->curl = curl_easy_duphandle(curl_default);
1116#endif
ad75ebe5 1117 curl_session_count++;
29508e1e
NH
1118 }
1119
1120 active_requests++;
1121 slot->in_use = 1;
c8568e13 1122 slot->results = NULL;
baa7b67d 1123 slot->finished = NULL;
29508e1e
NH
1124 slot->callback_data = NULL;
1125 slot->callback_func = NULL;
bcfb95dd 1126 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
912b2acf
DB
1127 if (curl_save_cookies)
1128 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
29508e1e 1129 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
29508e1e 1130 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
9094950d
NH
1131 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1132 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1133 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1e41827d 1134 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
9094950d
NH
1135 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1136 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
b793acf1 1137 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
835c4d36 1138 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
c915f11e 1139
50d34137
JK
1140 /*
1141 * Default following to off unless "ALWAYS" is configured; this gives
1142 * callers a sane starting point, and they can tweak for individual
1143 * HTTP_FOLLOW_* cases themselves.
1144 */
1145 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1146 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1147 else
1148 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1149
c915f11e
EW
1150#if LIBCURL_VERSION_NUM >= 0x070a08
1151 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1152#endif
4dbe6646 1153#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1154 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1155#endif
40a18fc7 1156 if (http_auth.password || curl_empty_auth_enabled())
dfa1725a 1157 init_curl_http_auth(slot->curl);
29508e1e
NH
1158
1159 return slot;
1160}
1161
1162int start_active_slot(struct active_request_slot *slot)
1163{
1164#ifdef USE_CURL_MULTI
1165 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
45c17412 1166 int num_transfers;
29508e1e
NH
1167
1168 if (curlm_result != CURLM_OK &&
1169 curlm_result != CURLM_CALL_MULTI_PERFORM) {
9f1b5884
EW
1170 warning("curl_multi_add_handle failed: %s",
1171 curl_multi_strerror(curlm_result));
29508e1e
NH
1172 active_requests--;
1173 slot->in_use = 0;
1174 return 0;
1175 }
45c17412
DB
1176
1177 /*
1178 * We know there must be something to do, since we just added
1179 * something.
1180 */
1181 curl_multi_perform(curlm, &num_transfers);
29508e1e
NH
1182#endif
1183 return 1;
1184}
1185
1186#ifdef USE_CURL_MULTI
fc57b6aa
DB
1187struct fill_chain {
1188 void *data;
1189 int (*fill)(void *);
1190 struct fill_chain *next;
1191};
1192
4251ccbd 1193static struct fill_chain *fill_cfg;
fc57b6aa
DB
1194
1195void add_fill_function(void *data, int (*fill)(void *))
1196{
e8eec71d 1197 struct fill_chain *new = xmalloc(sizeof(*new));
fc57b6aa
DB
1198 struct fill_chain **linkp = &fill_cfg;
1199 new->data = data;
1200 new->fill = fill;
1201 new->next = NULL;
1202 while (*linkp)
1203 linkp = &(*linkp)->next;
1204 *linkp = new;
1205}
1206
45c17412
DB
1207void fill_active_slots(void)
1208{
1209 struct active_request_slot *slot = active_queue_head;
1210
fc57b6aa
DB
1211 while (active_requests < max_requests) {
1212 struct fill_chain *fill;
1213 for (fill = fill_cfg; fill; fill = fill->next)
1214 if (fill->fill(fill->data))
1215 break;
1216
1217 if (!fill)
45c17412 1218 break;
fc57b6aa 1219 }
45c17412
DB
1220
1221 while (slot != NULL) {
ad75ebe5
TRC
1222 if (!slot->in_use && slot->curl != NULL
1223 && curl_session_count > min_curl_sessions) {
45c17412
DB
1224 curl_easy_cleanup(slot->curl);
1225 slot->curl = NULL;
ad75ebe5 1226 curl_session_count--;
45c17412
DB
1227 }
1228 slot = slot->next;
1229 }
1230}
1231
29508e1e
NH
1232void step_active_slots(void)
1233{
1234 int num_transfers;
1235 CURLMcode curlm_result;
1236
1237 do {
1238 curlm_result = curl_multi_perform(curlm, &num_transfers);
1239 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1240 if (num_transfers < active_requests) {
1241 process_curl_messages();
1242 fill_active_slots();
1243 }
1244}
1245#endif
1246
1247void run_active_slot(struct active_request_slot *slot)
1248{
1249#ifdef USE_CURL_MULTI
29508e1e
NH
1250 fd_set readfds;
1251 fd_set writefds;
1252 fd_set excfds;
1253 int max_fd;
1254 struct timeval select_timeout;
baa7b67d 1255 int finished = 0;
29508e1e 1256
baa7b67d
NH
1257 slot->finished = &finished;
1258 while (!finished) {
29508e1e
NH
1259 step_active_slots();
1260
df26c471 1261 if (slot->in_use) {
eb56c821
MF
1262#if LIBCURL_VERSION_NUM >= 0x070f04
1263 long curl_timeout;
1264 curl_multi_timeout(curlm, &curl_timeout);
1265 if (curl_timeout == 0) {
1266 continue;
1267 } else if (curl_timeout == -1) {
1268 select_timeout.tv_sec = 0;
1269 select_timeout.tv_usec = 50000;
1270 } else {
1271 select_timeout.tv_sec = curl_timeout / 1000;
1272 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1273 }
1274#else
1275 select_timeout.tv_sec = 0;
1276 select_timeout.tv_usec = 50000;
1277#endif
29508e1e 1278
6f9dd67f 1279 max_fd = -1;
29508e1e
NH
1280 FD_ZERO(&readfds);
1281 FD_ZERO(&writefds);
1282 FD_ZERO(&excfds);
6f9dd67f 1283 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
eb56c821 1284
7202b81f
SZ
1285 /*
1286 * It can happen that curl_multi_timeout returns a pathologically
1287 * long timeout when curl_multi_fdset returns no file descriptors
1288 * to read. See commit message for more details.
1289 */
1290 if (max_fd < 0 &&
1291 (select_timeout.tv_sec > 0 ||
1292 select_timeout.tv_usec > 50000)) {
1293 select_timeout.tv_sec = 0;
1294 select_timeout.tv_usec = 50000;
1295 }
1296
6f9dd67f 1297 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
29508e1e
NH
1298 }
1299 }
1300#else
1301 while (slot->in_use) {
1302 slot->curl_result = curl_easy_perform(slot->curl);
1303 finish_active_slot(slot);
1304 }
1305#endif
1306}
1307
83e41e2e 1308static void release_active_slot(struct active_request_slot *slot)
53f31389
MW
1309{
1310 closedown_active_slot(slot);
2abc848d 1311 if (slot->curl) {
d8b6b84d 1312 xmulti_remove_handle(slot);
2abc848d
EW
1313 if (curl_session_count > min_curl_sessions) {
1314 curl_easy_cleanup(slot->curl);
1315 slot->curl = NULL;
1316 curl_session_count--;
1317 }
53f31389 1318 }
b3ca4e4e 1319#ifdef USE_CURL_MULTI
53f31389 1320 fill_active_slots();
b3ca4e4e 1321#endif
53f31389
MW
1322}
1323
29508e1e
NH
1324void finish_all_active_slots(void)
1325{
1326 struct active_request_slot *slot = active_queue_head;
1327
1328 while (slot != NULL)
1329 if (slot->in_use) {
1330 run_active_slot(slot);
1331 slot = active_queue_head;
1332 } else {
1333 slot = slot->next;
1334 }
1335}
d7e92806 1336
5ace994f 1337/* Helpers for modifying and creating URLs */
d7e92806
MH
1338static inline int needs_quote(int ch)
1339{
1340 if (((ch >= 'A') && (ch <= 'Z'))
1341 || ((ch >= 'a') && (ch <= 'z'))
1342 || ((ch >= '0') && (ch <= '9'))
1343 || (ch == '/')
1344 || (ch == '-')
1345 || (ch == '.'))
1346 return 0;
1347 return 1;
1348}
1349
d7e92806
MH
1350static char *quote_ref_url(const char *base, const char *ref)
1351{
113106e0 1352 struct strbuf buf = STRBUF_INIT;
d7e92806 1353 const char *cp;
113106e0 1354 int ch;
d7e92806 1355
5ace994f 1356 end_url_with_slash(&buf, base);
113106e0
TRC
1357
1358 for (cp = ref; (ch = *cp) != 0; cp++)
d7e92806 1359 if (needs_quote(ch))
113106e0 1360 strbuf_addf(&buf, "%%%02x", ch);
d7e92806 1361 else
113106e0 1362 strbuf_addch(&buf, *cp);
d7e92806 1363
113106e0 1364 return strbuf_detach(&buf, NULL);
d7e92806
MH
1365}
1366
5424bc55
TRC
1367void append_remote_object_url(struct strbuf *buf, const char *url,
1368 const char *hex,
1369 int only_two_digit_prefix)
1370{
800324c3
TRC
1371 end_url_with_slash(buf, url);
1372
1373 strbuf_addf(buf, "objects/%.*s/", 2, hex);
5424bc55 1374 if (!only_two_digit_prefix)
bc57b9c0 1375 strbuf_addstr(buf, hex + 2);
5424bc55
TRC
1376}
1377
1378char *get_remote_object_url(const char *url, const char *hex,
1379 int only_two_digit_prefix)
1380{
1381 struct strbuf buf = STRBUF_INIT;
1382 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1383 return strbuf_detach(&buf, NULL);
1384}
1385
b90a3d7b 1386static int handle_curl_result(struct slot_results *results)
88097030 1387{
6d052d78
JK
1388 /*
1389 * If we see a failing http code with CURLE_OK, we have turned off
1390 * FAILONERROR (to keep the server's custom error response), and should
1391 * translate the code into failure here.
50d34137
JK
1392 *
1393 * Likewise, if we see a redirect (30x code), that means we turned off
1394 * redirect-following, and we should treat the result as an error.
6d052d78
JK
1395 */
1396 if (results->curl_result == CURLE_OK &&
50d34137 1397 results->http_code >= 300) {
6d052d78
JK
1398 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1399 /*
1400 * Normally curl will already have put the "reason phrase"
1401 * from the server into curl_errorstr; unfortunately without
1402 * FAILONERROR it is lost, so we can give only the numeric
1403 * status code.
1404 */
1a168e5c
JK
1405 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1406 "The requested URL returned error: %ld",
1407 results->http_code);
6d052d78
JK
1408 }
1409
88097030
JK
1410 if (results->curl_result == CURLE_OK) {
1411 credential_approve(&http_auth);
372370f1
KF
1412 if (proxy_auth.password)
1413 credential_approve(&proxy_auth);
88097030
JK
1414 return HTTP_OK;
1415 } else if (missing_target(results))
1416 return HTTP_MISSING_TARGET;
1417 else if (results->http_code == 401) {
1418 if (http_auth.username && http_auth.password) {
1419 credential_reject(&http_auth);
1420 return HTTP_NOAUTH;
1421 } else {
4dbe6646 1422#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1423 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
40a18fc7 1424 if (results->auth_avail) {
840398fe 1425 http_auth_methods &= results->auth_avail;
40a18fc7
JK
1426 http_auth_methods_restricted = 1;
1427 }
4dbe6646 1428#endif
88097030
JK
1429 return HTTP_REAUTH;
1430 }
1431 } else {
372370f1
KF
1432 if (results->http_connectcode == 407)
1433 credential_reject(&proxy_auth);
3503e9ab 1434#if LIBCURL_VERSION_NUM >= 0x070c00
88097030
JK
1435 if (!curl_errorstr[0])
1436 strlcpy(curl_errorstr,
1437 curl_easy_strerror(results->curl_result),
1438 sizeof(curl_errorstr));
3503e9ab 1439#endif
88097030
JK
1440 return HTTP_ERROR;
1441 }
1442}
1443
beed336c
JK
1444int run_one_slot(struct active_request_slot *slot,
1445 struct slot_results *results)
1446{
1447 slot->results = results;
1448 if (!start_active_slot(slot)) {
1a168e5c
JK
1449 xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1450 "failed to start HTTP request");
beed336c
JK
1451 return HTTP_START_FAILED;
1452 }
1453
1454 run_active_slot(slot);
1455 return handle_curl_result(results);
1456}
1457
8cb01e2f
JS
1458struct curl_slist *http_copy_default_headers(void)
1459{
1460 struct curl_slist *headers = NULL, *h;
1461
1462 for (h = extra_http_headers; h; h = h->next)
1463 headers = curl_slist_append(headers, h->data);
1464
1465 return headers;
1466}
1467
132b70a2
JK
1468static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1469{
1470 char *ptr;
1471 CURLcode ret;
1472
1473 strbuf_reset(buf);
1474 ret = curl_easy_getinfo(curl, info, &ptr);
1475 if (!ret && ptr)
1476 strbuf_addstr(buf, ptr);
1477 return ret;
1478}
1479
e3131626
JK
1480/*
1481 * Check for and extract a content-type parameter. "raw"
1482 * should be positioned at the start of the potential
1483 * parameter, with any whitespace already removed.
1484 *
1485 * "name" is the name of the parameter. The value is appended
1486 * to "out".
1487 */
1488static int extract_param(const char *raw, const char *name,
1489 struct strbuf *out)
1490{
1491 size_t len = strlen(name);
1492
1493 if (strncasecmp(raw, name, len))
1494 return -1;
1495 raw += len;
1496
1497 if (*raw != '=')
1498 return -1;
1499 raw++;
1500
f34a655d 1501 while (*raw && !isspace(*raw) && *raw != ';')
e3131626
JK
1502 strbuf_addch(out, *raw++);
1503 return 0;
1504}
1505
bf197fd7
JK
1506/*
1507 * Extract a normalized version of the content type, with any
1508 * spaces suppressed, all letters lowercased, and no trailing ";"
1509 * or parameters.
1510 *
1511 * Note that we will silently remove even invalid whitespace. For
1512 * example, "text / plain" is specifically forbidden by RFC 2616,
1513 * but "text/plain" is the only reasonable output, and this keeps
1514 * our code simple.
1515 *
e3131626
JK
1516 * If the "charset" argument is not NULL, store the value of any
1517 * charset parameter there.
1518 *
bf197fd7 1519 * Example:
e3131626 1520 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
bf197fd7
JK
1521 * "text / plain" -> "text/plain"
1522 */
e3131626
JK
1523static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1524 struct strbuf *charset)
bf197fd7
JK
1525{
1526 const char *p;
1527
1528 strbuf_reset(type);
1529 strbuf_grow(type, raw->len);
1530 for (p = raw->buf; *p; p++) {
1531 if (isspace(*p))
1532 continue;
e3131626
JK
1533 if (*p == ';') {
1534 p++;
bf197fd7 1535 break;
e3131626 1536 }
bf197fd7
JK
1537 strbuf_addch(type, tolower(*p));
1538 }
e3131626
JK
1539
1540 if (!charset)
1541 return;
1542
1543 strbuf_reset(charset);
1544 while (*p) {
f34a655d 1545 while (isspace(*p) || *p == ';')
e3131626
JK
1546 p++;
1547 if (!extract_param(p, "charset", charset))
1548 return;
1549 while (*p && !isspace(*p))
1550 p++;
1551 }
c553fd1c
JK
1552
1553 if (!charset->len && starts_with(type->buf, "text/"))
1554 strbuf_addstr(charset, "ISO-8859-1");
bf197fd7
JK
1555}
1556
f18604bb
YE
1557static void write_accept_language(struct strbuf *buf)
1558{
1559 /*
1560 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1561 * that, q-value will be smaller than 0.001, the minimum q-value the
1562 * HTTP specification allows. See
1563 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1564 */
1565 const int MAX_DECIMAL_PLACES = 3;
1566 const int MAX_LANGUAGE_TAGS = 1000;
1567 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1568 char **language_tags = NULL;
1569 int num_langs = 0;
1570 const char *s = get_preferred_languages();
1571 int i;
1572 struct strbuf tag = STRBUF_INIT;
1573
1574 /* Don't add Accept-Language header if no language is preferred. */
1575 if (!s)
1576 return;
1577
1578 /*
1579 * Split the colon-separated string of preferred languages into
1580 * language_tags array.
1581 */
1582 do {
1583 /* collect language tag */
1584 for (; *s && (isalnum(*s) || *s == '_'); s++)
1585 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1586
1587 /* skip .codeset, @modifier and any other unnecessary parts */
1588 while (*s && *s != ':')
1589 s++;
1590
1591 if (tag.len) {
1592 num_langs++;
1593 REALLOC_ARRAY(language_tags, num_langs);
1594 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1595 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1596 break;
1597 }
1598 } while (*s++);
1599
1600 /* write Accept-Language header into buf */
1601 if (num_langs) {
1602 int last_buf_len = 0;
1603 int max_q;
1604 int decimal_places;
1605 char q_format[32];
1606
1607 /* add '*' */
1608 REALLOC_ARRAY(language_tags, num_langs + 1);
1609 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1610
1611 /* compute decimal_places */
1612 for (max_q = 1, decimal_places = 0;
1613 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1614 decimal_places++, max_q *= 10)
1615 ;
1616
5096d490 1617 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
f18604bb
YE
1618
1619 strbuf_addstr(buf, "Accept-Language: ");
1620
1621 for (i = 0; i < num_langs; i++) {
1622 if (i > 0)
1623 strbuf_addstr(buf, ", ");
1624
1625 strbuf_addstr(buf, language_tags[i]);
1626
1627 if (i > 0)
1628 strbuf_addf(buf, q_format, max_q - i);
1629
1630 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1631 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1632 break;
1633 }
1634
1635 last_buf_len = buf->len;
1636 }
1637 }
1638
1639 /* free language tags -- last one is a static '*' */
1640 for (i = 0; i < num_langs - 1; i++)
1641 free(language_tags[i]);
1642 free(language_tags);
1643}
1644
1645/*
1646 * Get an Accept-Language header which indicates user's preferred languages.
1647 *
1648 * Examples:
1649 * LANGUAGE= -> ""
1650 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1651 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1652 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1653 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1654 * LANGUAGE= LANG=C -> ""
1655 */
1656static const char *get_accept_language(void)
1657{
1658 if (!cached_accept_language) {
1659 struct strbuf buf = STRBUF_INIT;
1660 write_accept_language(&buf);
1661 if (buf.len > 0)
1662 cached_accept_language = strbuf_detach(&buf, NULL);
1663 }
1664
1665 return cached_accept_language;
1666}
1667
835c4d36
DT
1668static void http_opt_request_remainder(CURL *curl, off_t pos)
1669{
1670 char buf[128];
1671 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1672 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1673}
1674
e929cd20
MH
1675/* http_request() targets */
1676#define HTTP_REQUEST_STRBUF 0
1677#define HTTP_REQUEST_FILE 1
1678
1bbcc224
JK
1679static int http_request(const char *url,
1680 void *result, int target,
1681 const struct http_get_options *options)
e929cd20
MH
1682{
1683 struct active_request_slot *slot;
1684 struct slot_results results;
8cb01e2f 1685 struct curl_slist *headers = http_copy_default_headers();
e929cd20 1686 struct strbuf buf = STRBUF_INIT;
f18604bb 1687 const char *accept_language;
e929cd20
MH
1688 int ret;
1689
1690 slot = get_active_slot();
e929cd20
MH
1691 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1692
1693 if (result == NULL) {
1694 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1695 } else {
1696 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1697 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1698
1699 if (target == HTTP_REQUEST_FILE) {
f8117f55 1700 off_t posn = ftello(result);
e929cd20
MH
1701 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1702 fwrite);
835c4d36
DT
1703 if (posn > 0)
1704 http_opt_request_remainder(slot->curl, posn);
e929cd20
MH
1705 } else
1706 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1707 fwrite_buffer);
1708 }
1709
f18604bb
YE
1710 accept_language = get_accept_language();
1711
1712 if (accept_language)
1713 headers = curl_slist_append(headers, accept_language);
1714
e929cd20 1715 strbuf_addstr(&buf, "Pragma:");
1bbcc224 1716 if (options && options->no_cache)
e929cd20 1717 strbuf_addstr(&buf, " no-cache");
1bbcc224 1718 if (options && options->keep_error)
6d052d78 1719 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
50d34137
JK
1720 if (options && options->initial_request &&
1721 http_follow_config == HTTP_FOLLOW_INITIAL)
1722 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
e929cd20
MH
1723
1724 headers = curl_slist_append(headers, buf.buf);
1725
1726 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1727 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
aa90b969 1728 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
e929cd20 1729
beed336c 1730 ret = run_one_slot(slot, &results);
e929cd20 1731
bf197fd7
JK
1732 if (options && options->content_type) {
1733 struct strbuf raw = STRBUF_INIT;
1734 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
e3131626
JK
1735 extract_content_type(&raw, options->content_type,
1736 options->charset);
bf197fd7
JK
1737 strbuf_release(&raw);
1738 }
4656bf47 1739
78868962
JK
1740 if (options && options->effective_url)
1741 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1742 options->effective_url);
4656bf47 1743
e929cd20
MH
1744 curl_slist_free_all(headers);
1745 strbuf_release(&buf);
1746
1747 return ret;
1748}
1749
c93c92f3
JK
1750/*
1751 * Update the "base" url to a more appropriate value, as deduced by
1752 * redirects seen when requesting a URL starting with "url".
1753 *
1754 * The "asked" parameter is a URL that we asked curl to access, and must begin
1755 * with "base".
1756 *
1757 * The "got" parameter is the URL that curl reported to us as where we ended
1758 * up.
1759 *
1760 * Returns 1 if we updated the base url, 0 otherwise.
1761 *
1762 * Our basic strategy is to compare "base" and "asked" to find the bits
1763 * specific to our request. We then strip those bits off of "got" to yield the
1764 * new base. So for example, if our base is "http://example.com/foo.git",
1765 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1766 * with "https://other.example.com/foo.git/info/refs". We would want the
1767 * new URL to become "https://other.example.com/foo.git".
1768 *
1769 * Note that this assumes a sane redirect scheme. It's entirely possible
1770 * in the example above to end up at a URL that does not even end in
6628eb41
JK
1771 * "info/refs". In such a case we die. There's not much we can do, such a
1772 * scheme is unlikely to represent a real git repository, and failing to
1773 * rewrite the base opens options for malicious redirects to do funny things.
c93c92f3
JK
1774 */
1775static int update_url_from_redirect(struct strbuf *base,
1776 const char *asked,
1777 const struct strbuf *got)
1778{
1779 const char *tail;
986d7f4d 1780 size_t new_len;
c93c92f3
JK
1781
1782 if (!strcmp(asked, got->buf))
1783 return 0;
1784
de8118e1 1785 if (!skip_prefix(asked, base->buf, &tail))
c93c92f3
JK
1786 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1787 asked, base->buf);
1788
986d7f4d
JK
1789 new_len = got->len;
1790 if (!strip_suffix_mem(got->buf, &new_len, tail))
6628eb41
JK
1791 die(_("unable to update url base from redirection:\n"
1792 " asked for: %s\n"
1793 " redirect: %s"),
1794 asked, got->buf);
c93c92f3
JK
1795
1796 strbuf_reset(base);
986d7f4d 1797 strbuf_add(base, got->buf, new_len);
6628eb41 1798
c93c92f3
JK
1799 return 1;
1800}
1801
4656bf47 1802static int http_request_reauth(const char *url,
4656bf47 1803 void *result, int target,
1bbcc224 1804 struct http_get_options *options)
8d677edc 1805{
1bbcc224 1806 int ret = http_request(url, result, target, options);
c93c92f3 1807
8e27391a
JT
1808 if (ret != HTTP_OK && ret != HTTP_REAUTH)
1809 return ret;
1810
c93c92f3
JK
1811 if (options && options->effective_url && options->base_url) {
1812 if (update_url_from_redirect(options->base_url,
1813 url, options->effective_url)) {
1814 credential_from_url(&http_auth, options->base_url->buf);
1815 url = options->effective_url->buf;
1816 }
1817 }
1818
8d677edc
JK
1819 if (ret != HTTP_REAUTH)
1820 return ret;
6d052d78
JK
1821
1822 /*
1823 * If we are using KEEP_ERROR, the previous request may have
1824 * put cruft into our output stream; we should clear it out before
1825 * making our next request. We only know how to do this for
1826 * the strbuf case, but that is enough to satisfy current callers.
1827 */
1bbcc224 1828 if (options && options->keep_error) {
6d052d78
JK
1829 switch (target) {
1830 case HTTP_REQUEST_STRBUF:
1831 strbuf_reset(result);
1832 break;
1833 default:
1834 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1835 }
1836 }
2501aff8
JK
1837
1838 credential_fill(&http_auth);
1839
1bbcc224 1840 return http_request(url, result, target, options);
8d677edc
JK
1841}
1842
4656bf47 1843int http_get_strbuf(const char *url,
1bbcc224
JK
1844 struct strbuf *result,
1845 struct http_get_options *options)
e929cd20 1846{
1bbcc224 1847 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
e929cd20
MH
1848}
1849
83e41e2e 1850/*
a7793a74 1851 * Downloads a URL and stores the result in the given file.
83e41e2e
JH
1852 *
1853 * If a previous interrupted download is detected (i.e. a previous temporary
1854 * file is still around) the download is resumed.
1855 */
1bbcc224
JK
1856static int http_get_file(const char *url, const char *filename,
1857 struct http_get_options *options)
e929cd20
MH
1858{
1859 int ret;
1860 struct strbuf tmpfile = STRBUF_INIT;
1861 FILE *result;
1862
1863 strbuf_addf(&tmpfile, "%s.temp", filename);
1864 result = fopen(tmpfile.buf, "a");
3d1fb769 1865 if (!result) {
e929cd20
MH
1866 error("Unable to open local file %s", tmpfile.buf);
1867 ret = HTTP_ERROR;
1868 goto cleanup;
1869 }
1870
1bbcc224 1871 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
e929cd20
MH
1872 fclose(result);
1873
cb5add58 1874 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
e929cd20
MH
1875 ret = HTTP_ERROR;
1876cleanup:
1877 strbuf_release(&tmpfile);
1878 return ret;
1879}
1880
c13b2633 1881int http_fetch_ref(const char *base, struct ref *ref)
d7e92806 1882{
1bbcc224 1883 struct http_get_options options = {0};
d7e92806
MH
1884 char *url;
1885 struct strbuf buffer = STRBUF_INIT;
0d5896e1 1886 int ret = -1;
d7e92806 1887
1bbcc224
JK
1888 options.no_cache = 1;
1889
c13b2633 1890 url = quote_ref_url(base, ref->name);
1bbcc224 1891 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
0d5896e1
MH
1892 strbuf_rtrim(&buffer);
1893 if (buffer.len == 40)
f4e54d02 1894 ret = get_oid_hex(buffer.buf, &ref->old_oid);
59556548 1895 else if (starts_with(buffer.buf, "ref: ")) {
0d5896e1
MH
1896 ref->symref = xstrdup(buffer.buf + 5);
1897 ret = 0;
d7e92806 1898 }
d7e92806
MH
1899 }
1900
1901 strbuf_release(&buffer);
1902 free(url);
1903 return ret;
1904}
b8caac2b
TRC
1905
1906/* Helpers for fetching packs */
750ef425 1907static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
b8caac2b 1908{
750ef425 1909 char *url, *tmp;
b8caac2b 1910 struct strbuf buf = STRBUF_INIT;
b8caac2b 1911
b8caac2b 1912 if (http_is_verbose)
162eb5f8 1913 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
b8caac2b
TRC
1914
1915 end_url_with_slash(&buf, base_url);
162eb5f8 1916 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
b8caac2b
TRC
1917 url = strbuf_detach(&buf, NULL);
1918
750ef425
SP
1919 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1920 tmp = strbuf_detach(&buf, NULL);
1921
70900eda 1922 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
82247e9b 1923 error("Unable to get pack index %s", url);
6a83d902 1924 FREE_AND_NULL(tmp);
750ef425 1925 }
b8caac2b 1926
b8caac2b 1927 free(url);
750ef425 1928 return tmp;
b8caac2b
TRC
1929}
1930
1931static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1932 unsigned char *sha1, const char *base_url)
1933{
1934 struct packed_git *new_pack;
750ef425
SP
1935 char *tmp_idx = NULL;
1936 int ret;
b8caac2b 1937
750ef425 1938 if (has_pack_index(sha1)) {
8b9c2dd4 1939 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
750ef425
SP
1940 if (!new_pack)
1941 return -1; /* parse_pack_index() already issued error message */
1942 goto add_pack;
1943 }
1944
1945 tmp_idx = fetch_pack_index(sha1, base_url);
1946 if (!tmp_idx)
b8caac2b
TRC
1947 return -1;
1948
750ef425
SP
1949 new_pack = parse_pack_index(sha1, tmp_idx);
1950 if (!new_pack) {
1951 unlink(tmp_idx);
1952 free(tmp_idx);
1953
b8caac2b 1954 return -1; /* parse_pack_index() already issued error message */
750ef425
SP
1955 }
1956
1957 ret = verify_pack_index(new_pack);
1958 if (!ret) {
1959 close_pack_index(new_pack);
cb5add58 1960 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
750ef425
SP
1961 }
1962 free(tmp_idx);
1963 if (ret)
1964 return -1;
1965
1966add_pack:
b8caac2b
TRC
1967 new_pack->next = *packs_head;
1968 *packs_head = new_pack;
1969 return 0;
1970}
1971
1972int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1973{
1bbcc224 1974 struct http_get_options options = {0};
b8caac2b
TRC
1975 int ret = 0, i = 0;
1976 char *url, *data;
1977 struct strbuf buf = STRBUF_INIT;
1978 unsigned char sha1[20];
1979
1980 end_url_with_slash(&buf, base_url);
1981 strbuf_addstr(&buf, "objects/info/packs");
1982 url = strbuf_detach(&buf, NULL);
1983
1bbcc224
JK
1984 options.no_cache = 1;
1985 ret = http_get_strbuf(url, &buf, &options);
b8caac2b
TRC
1986 if (ret != HTTP_OK)
1987 goto cleanup;
1988
1989 data = buf.buf;
1990 while (i < buf.len) {
1991 switch (data[i]) {
1992 case 'P':
1993 i++;
1994 if (i + 52 <= buf.len &&
59556548
CC
1995 starts_with(data + i, " pack-") &&
1996 starts_with(data + i + 46, ".pack\n")) {
b8caac2b
TRC
1997 get_sha1_hex(data + i + 6, sha1);
1998 fetch_and_setup_pack_index(packs_head, sha1,
1999 base_url);
2000 i += 51;
2001 break;
2002 }
2003 default:
2004 while (i < buf.len && data[i] != '\n')
2005 i++;
2006 }
2007 i++;
2008 }
2009
2010cleanup:
2011 free(url);
2012 return ret;
2013}
2264dfa5
TRC
2014
2015void release_http_pack_request(struct http_pack_request *preq)
2016{
2017 if (preq->packfile != NULL) {
2018 fclose(preq->packfile);
2019 preq->packfile = NULL;
2264dfa5 2020 }
2264dfa5
TRC
2021 preq->slot = NULL;
2022 free(preq->url);
826aed50 2023 free(preq);
2264dfa5
TRC
2024}
2025
2026int finish_http_pack_request(struct http_pack_request *preq)
2027{
2264dfa5 2028 struct packed_git **lst;
021ab6f0 2029 struct packed_git *p = preq->target;
fe72d420 2030 char *tmp_idx;
9ae97018 2031 size_t len;
d3180279 2032 struct child_process ip = CHILD_PROCESS_INIT;
2264dfa5 2033
fe72d420 2034 close_pack_index(p);
2264dfa5 2035
3065274c
SP
2036 fclose(preq->packfile);
2037 preq->packfile = NULL;
2264dfa5
TRC
2038
2039 lst = preq->lst;
021ab6f0 2040 while (*lst != p)
2264dfa5
TRC
2041 lst = &((*lst)->next);
2042 *lst = (*lst)->next;
2043
9ae97018
JK
2044 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2045 die("BUG: pack tmpfile does not end in .pack.temp?");
2046 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
fe72d420 2047
c7191fa5
RS
2048 argv_array_push(&ip.args, "index-pack");
2049 argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2050 argv_array_push(&ip.args, preq->tmpfile);
fe72d420
SP
2051 ip.git_cmd = 1;
2052 ip.no_stdin = 1;
2053 ip.no_stdout = 1;
2054
2055 if (run_command(&ip)) {
2056 unlink(preq->tmpfile);
2057 unlink(tmp_idx);
2058 free(tmp_idx);
2264dfa5 2059 return -1;
fe72d420
SP
2060 }
2061
2062 unlink(sha1_pack_index_name(p->sha1));
2264dfa5 2063
cb5add58
JH
2064 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2065 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
fe72d420 2066 free(tmp_idx);
2264dfa5 2067 return -1;
fe72d420 2068 }
2264dfa5 2069
fe72d420
SP
2070 install_packed_git(p);
2071 free(tmp_idx);
2264dfa5
TRC
2072 return 0;
2073}
2074
2075struct http_pack_request *new_http_pack_request(
2076 struct packed_git *target, const char *base_url)
2077{
f8117f55 2078 off_t prev_posn = 0;
2264dfa5
TRC
2079 struct strbuf buf = STRBUF_INIT;
2080 struct http_pack_request *preq;
2081
ec99c9a8 2082 preq = xcalloc(1, sizeof(*preq));
2264dfa5 2083 preq->target = target;
2264dfa5
TRC
2084
2085 end_url_with_slash(&buf, base_url);
2086 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2087 sha1_to_hex(target->sha1));
bb99190e 2088 preq->url = strbuf_detach(&buf, NULL);
2264dfa5 2089
90d05713
TRC
2090 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2091 sha1_pack_name(target->sha1));
2264dfa5
TRC
2092 preq->packfile = fopen(preq->tmpfile, "a");
2093 if (!preq->packfile) {
2094 error("Unable to open local file %s for pack",
2095 preq->tmpfile);
2096 goto abort;
2097 }
2098
2099 preq->slot = get_active_slot();
2264dfa5
TRC
2100 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2101 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
bb99190e 2102 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2264dfa5
TRC
2103 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2104 no_pragma_header);
2105
2106 /*
2107 * If there is data present from a previous transfer attempt,
2108 * resume where it left off
2109 */
f8117f55 2110 prev_posn = ftello(preq->packfile);
2264dfa5
TRC
2111 if (prev_posn>0) {
2112 if (http_is_verbose)
2113 fprintf(stderr,
838ecf0b
RJ
2114 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2115 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
835c4d36 2116 http_opt_request_remainder(preq->slot->curl, prev_posn);
2264dfa5
TRC
2117 }
2118
2119 return preq;
2120
2121abort:
bb99190e 2122 free(preq->url);
5ae9ebfd 2123 free(preq);
2264dfa5
TRC
2124 return NULL;
2125}
5424bc55
TRC
2126
2127/* Helpers for fetching objects (loose) */
a04ff3ec 2128static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
5424bc55
TRC
2129 void *data)
2130{
2131 unsigned char expn[4096];
2132 size_t size = eltsize * nmemb;
2133 int posn = 0;
17966c0a
EW
2134 struct http_object_request *freq = data;
2135 struct active_request_slot *slot = freq->slot;
2136
2137 if (slot) {
2138 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2139 &slot->http_code);
2140 if (c != CURLE_OK)
2141 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2142 curl_easy_strerror(c));
3680f16f 2143 if (slot->http_code >= 300)
17966c0a
EW
2144 return size;
2145 }
2146
5424bc55
TRC
2147 do {
2148 ssize_t retval = xwrite(freq->localfile,
2149 (char *) ptr + posn, size - posn);
2150 if (retval < 0)
2151 return posn;
2152 posn += retval;
2153 } while (posn < size);
2154
2155 freq->stream.avail_in = size;
a04ff3ec 2156 freq->stream.next_in = (void *)ptr;
5424bc55
TRC
2157 do {
2158 freq->stream.next_out = expn;
2159 freq->stream.avail_out = sizeof(expn);
2160 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2161 git_SHA1_Update(&freq->c, expn,
2162 sizeof(expn) - freq->stream.avail_out);
2163 } while (freq->stream.avail_in && freq->zret == Z_OK);
5424bc55
TRC
2164 return size;
2165}
2166
2167struct http_object_request *new_http_object_request(const char *base_url,
2168 unsigned char *sha1)
2169{
2170 char *hex = sha1_to_hex(sha1);
30d6c6ea 2171 const char *filename;
5424bc55 2172 char prevfile[PATH_MAX];
5424bc55 2173 int prevlocal;
a04ff3ec 2174 char prev_buf[PREV_BUF_SIZE];
5424bc55 2175 ssize_t prev_read = 0;
f8117f55 2176 off_t prev_posn = 0;
5424bc55
TRC
2177 struct http_object_request *freq;
2178
ec99c9a8 2179 freq = xcalloc(1, sizeof(*freq));
5424bc55
TRC
2180 hashcpy(freq->sha1, sha1);
2181 freq->localfile = -1;
2182
2183 filename = sha1_file_name(sha1);
5424bc55
TRC
2184 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2185 "%s.temp", filename);
2186
2187 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
2188 unlink_or_warn(prevfile);
2189 rename(freq->tmpfile, prevfile);
2190 unlink_or_warn(freq->tmpfile);
2191
2192 if (freq->localfile != -1)
2193 error("fd leakage in start: %d", freq->localfile);
2194 freq->localfile = open(freq->tmpfile,
2195 O_WRONLY | O_CREAT | O_EXCL, 0666);
2196 /*
2197 * This could have failed due to the "lazy directory creation";
2198 * try to mkdir the last path component.
2199 */
2200 if (freq->localfile < 0 && errno == ENOENT) {
2201 char *dir = strrchr(freq->tmpfile, '/');
2202 if (dir) {
2203 *dir = 0;
2204 mkdir(freq->tmpfile, 0777);
2205 *dir = '/';
2206 }
2207 freq->localfile = open(freq->tmpfile,
2208 O_WRONLY | O_CREAT | O_EXCL, 0666);
2209 }
2210
2211 if (freq->localfile < 0) {
d2e255ee 2212 error_errno("Couldn't create temporary file %s", freq->tmpfile);
5424bc55
TRC
2213 goto abort;
2214 }
2215
5424bc55
TRC
2216 git_inflate_init(&freq->stream);
2217
2218 git_SHA1_Init(&freq->c);
2219
bb99190e 2220 freq->url = get_remote_object_url(base_url, hex, 0);
5424bc55
TRC
2221
2222 /*
2223 * If a previous temp file is present, process what was already
2224 * fetched.
2225 */
2226 prevlocal = open(prevfile, O_RDONLY);
2227 if (prevlocal != -1) {
2228 do {
2229 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2230 if (prev_read>0) {
2231 if (fwrite_sha1_file(prev_buf,
2232 1,
2233 prev_read,
2234 freq) == prev_read) {
2235 prev_posn += prev_read;
2236 } else {
2237 prev_read = -1;
2238 }
2239 }
2240 } while (prev_read > 0);
2241 close(prevlocal);
2242 }
2243 unlink_or_warn(prevfile);
2244
2245 /*
2246 * Reset inflate/SHA1 if there was an error reading the previous temp
2247 * file; also rewind to the beginning of the local file.
2248 */
2249 if (prev_read == -1) {
2250 memset(&freq->stream, 0, sizeof(freq->stream));
2251 git_inflate_init(&freq->stream);
2252 git_SHA1_Init(&freq->c);
2253 if (prev_posn>0) {
2254 prev_posn = 0;
2255 lseek(freq->localfile, 0, SEEK_SET);
0c4f21e4 2256 if (ftruncate(freq->localfile, 0) < 0) {
d2e255ee
NTND
2257 error_errno("Couldn't truncate temporary file %s",
2258 freq->tmpfile);
0c4f21e4
JL
2259 goto abort;
2260 }
5424bc55
TRC
2261 }
2262 }
2263
2264 freq->slot = get_active_slot();
2265
2266 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
17966c0a 2267 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
5424bc55
TRC
2268 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2269 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
bb99190e 2270 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
5424bc55
TRC
2271 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2272
2273 /*
2274 * If we have successfully processed data from a previous fetch
2275 * attempt, only fetch the data we don't already have.
2276 */
2277 if (prev_posn>0) {
2278 if (http_is_verbose)
2279 fprintf(stderr,
838ecf0b
RJ
2280 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2281 hex, (uintmax_t)prev_posn);
835c4d36 2282 http_opt_request_remainder(freq->slot->curl, prev_posn);
5424bc55
TRC
2283 }
2284
2285 return freq;
2286
5424bc55 2287abort:
bb99190e 2288 free(freq->url);
5424bc55
TRC
2289 free(freq);
2290 return NULL;
2291}
2292
2293void process_http_object_request(struct http_object_request *freq)
2294{
2295 if (freq->slot == NULL)
2296 return;
2297 freq->curl_result = freq->slot->curl_result;
2298 freq->http_code = freq->slot->http_code;
2299 freq->slot = NULL;
2300}
2301
2302int finish_http_object_request(struct http_object_request *freq)
2303{
2304 struct stat st;
2305
2306 close(freq->localfile);
2307 freq->localfile = -1;
2308
2309 process_http_object_request(freq);
2310
2311 if (freq->http_code == 416) {
bd757c18 2312 warning("requested range invalid; we may already have all the data.");
5424bc55
TRC
2313 } else if (freq->curl_result != CURLE_OK) {
2314 if (stat(freq->tmpfile, &st) == 0)
2315 if (st.st_size == 0)
2316 unlink_or_warn(freq->tmpfile);
2317 return -1;
2318 }
2319
2320 git_inflate_end(&freq->stream);
2321 git_SHA1_Final(freq->real_sha1, &freq->c);
2322 if (freq->zret != Z_STREAM_END) {
2323 unlink_or_warn(freq->tmpfile);
2324 return -1;
2325 }
2326 if (hashcmp(freq->sha1, freq->real_sha1)) {
2327 unlink_or_warn(freq->tmpfile);
2328 return -1;
2329 }
2330 freq->rename =
cb5add58 2331 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
5424bc55
TRC
2332
2333 return freq->rename;
2334}
2335
2336void abort_http_object_request(struct http_object_request *freq)
2337{
2338 unlink_or_warn(freq->tmpfile);
2339
2340 release_http_object_request(freq);
2341}
2342
2343void release_http_object_request(struct http_object_request *freq)
2344{
2345 if (freq->localfile != -1) {
2346 close(freq->localfile);
2347 freq->localfile = -1;
2348 }
2349 if (freq->url != NULL) {
6a83d902 2350 FREE_AND_NULL(freq->url);
5424bc55 2351 }
4b9fa0e3
TRC
2352 if (freq->slot != NULL) {
2353 freq->slot->callback_func = NULL;
2354 freq->slot->callback_data = NULL;
2355 release_active_slot(freq->slot);
2356 freq->slot = NULL;
2357 }
5424bc55 2358}