1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # common option and torsocks(1) wrapping for curl(1)
5 # Eventually, we may support using libcurl via Inline::C and/or
6 # WWW::Curl; but curl(1) is most prevalent and widely-installed.
7 # n.b. curl may support a daemon/client model like lei someday:
8 # https://github.com/curl/curl/wiki/curl-tool-master-client
9 package PublicInbox::LeiCurl;
12 use PublicInbox::Spawn qw(which);
13 use PublicInbox::Config;
15 # Ensures empty strings are quoted, we don't need more
16 # sophisticated quoting than for empty strings: curl -d ''
17 use overload '""' => sub {
18 join(' ', map { $_ eq '' ? "''" : $_ } @{$_[0]});
22 'curl-config=s@' => 'config|K=s@',
25 # prepares a common command for curl(1) based on $lei command
27 my ($cls, $lei, $curl) = @_;
28 $curl //= which('curl') // return $lei->fail('curl not found');
29 my $opt = $lei->{opt};
30 my @cmd = ($curl, qw(-Sf));
31 $cmd[-1] .= 's' if $opt->{quiet}; # already the default for "lei q"
32 $cmd[-1] .= 'v' if $opt->{verbose}; # we use ourselves, too
33 for my $o ($lei->curl_opt) {
34 if (my $lei_spec = $lei2curl{$o}) {
37 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
38 if ($o =~ s/=[is]@\z//) {
39 my $ary = $opt->{$o} or next;
40 push @cmd, map { ("--$o", $_) } @$ary;
41 } elsif ($o =~ s/=[is]\z//) {
42 my $val = $opt->{$o} // next;
43 push @cmd, "--$o", $val;
44 } elsif ($opt->{$o}) {
48 push @cmd, '-v' if $opt->{verbose}; # lei uses this itself
52 sub torsocks { # useful for "git clone" and "git fetch", too
53 my ($self, $lei, $uri)= @_;
54 my $opt = $lei->{opt};
55 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
56 my $torsocks = $opt->{torsocks} //= 'auto';
57 if ($torsocks eq 'auto' && substr($uri->host, -6) eq '.onion' &&
58 ($PublicInbox::Config::LD_PRELOAD//'') !~ m!/libtorsocks\b!) {
59 # "auto" continues anyways if torsocks is missing;
60 # a proxy may be specified via CLI, curlrc,
61 # environment variable, or even firewall rule
62 [ ($lei->{torsocks} //= which('torsocks')) // () ]
63 } elsif (PublicInbox::Config::git_bool($torsocks)) {
64 my $x = $lei->{torsocks} //= which('torsocks');
65 $x or return $lei->fail(<<EOM);
66 --torsocks=yes specified but torsocks not found in PATH=$ENV{PATH}
69 } else { # the common case for current Internet :<
74 # completes the result of cmd() for $uri
76 my ($self, $lei, $uri, @opt) = @_;
77 my $pfx = torsocks($self, $lei, $uri) or return; # error
78 if ($uri->scheme =~ /\Ahttps?\z/i) {
79 my $cfg = $lei->_lei_cfg;
80 my $p = $cfg ? $cfg->urlmatch('http.Proxy', $$uri) : undef;
81 push(@opt, "--proxy=$p") if defined($p);
83 bless [ @$pfx, @$self, @opt, $uri->as_string ], ref($self);