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