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 package PublicInbox::LeiCurl;
8 use PublicInbox::Spawn qw(which);
9 use PublicInbox::Config;
11 # Ensures empty strings are quoted, we don't need more
12 # sophisticated quoting than for empty strings: curl -d ''
13 use overload '""' => sub {
14 join(' ', map { $_ eq '' ? "''" : $_ } @{$_[0]});
18 'curl-config=s@' => 'config|K=s@',
21 # prepares a common command for curl(1) based on $lei command
23 my ($cls, $lei, $curl) = @_;
24 $curl //= which('curl') // return $lei->fail('curl not found');
25 my $opt = $lei->{opt};
26 my @cmd = ($curl, qw(-Sf));
27 $cmd[-1] .= 's' if $opt->{quiet}; # already the default for "lei q"
28 $cmd[-1] .= 'v' if $opt->{verbose}; # we use ourselves, too
29 for my $o ($lei->curl_opt) {
30 if (my $lei_spec = $lei2curl{$o}) {
33 $o =~ s/\|[a-z0-9]\b//i; # remove single char short option
34 if ($o =~ s/=[is]@\z//) {
35 my $ary = $opt->{$o} or next;
36 push @cmd, map { ("--$o", $_) } @$ary;
37 } elsif ($o =~ s/=[is]\z//) {
38 my $val = $opt->{$o} // next;
39 push @cmd, "--$o", $val;
40 } elsif ($opt->{$o}) {
44 push @cmd, '-v' if $opt->{verbose}; # lei uses this itself
48 sub torsocks { # useful for "git clone" and "git fetch", too
49 my ($self, $lei, $uri)= @_;
50 my $opt = $lei->{opt};
51 $opt->{torsocks} = 'false' if $opt->{'no-torsocks'};
52 my $torsocks = $opt->{torsocks} //= 'auto';
53 if ($torsocks eq 'auto' && substr($uri->host, -6) eq '.onion' &&
54 (($lei->{env}->{LD_PRELOAD}//'') !~ /torsocks/)) {
55 # "auto" continues anyways if torsocks is missing;
56 # a proxy may be specified via CLI, curlrc,
57 # environment variable, or even firewall rule
58 [ ($lei->{torsocks} //= which('torsocks')) // () ]
59 } elsif (PublicInbox::Config::git_bool($torsocks)) {
60 my $x = $lei->{torsocks} //= which('torsocks');
61 $x or return $lei->fail(<<EOM);
62 --torsocks=yes specified but torsocks not found in PATH=$ENV{PATH}
65 } else { # the common case for current Internet :<
70 # completes the result of cmd() for $uri
72 my ($self, $lei, $uri, @opt) = @_;
73 my $pfx = torsocks($self, $lei, $uri) or return; # error
74 bless [ @$pfx, @$self, @opt, $uri->as_string ], ref($self);