]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiInput.pm
lei ls-mail-source: list IMAP folders and NNTP groups
[public-inbox.git] / lib / PublicInbox / LeiInput.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # parent class for LeiImport, LeiConvert, LeiIndex
5 package PublicInbox::LeiInput;
6 use strict;
7 use v5.10.1;
8 use PublicInbox::DS;
9 use PublicInbox::Spawn qw(which popen_rd);
10
11 # JMAP RFC 8621 4.1.1
12 # https://www.iana.org/assignments/imap-jmap-keywords/imap-jmap-keywords.xhtml
13 our @KW = (qw(seen answered flagged draft), # widely-compatible
14         qw(forwarded), # IMAP + Maildir
15         qw(phishing junk notjunk)); # rarely supported
16
17 # note: RFC 8621 states "Users may add arbitrary keywords to an Email",
18 # but is it good idea?  Stick to the system and reserved ones, for now.
19 # The widely-compatible ones map to IMAP system flags, Maildir flags
20 # and mbox Status/X-Status headers.
21 my %KW = map { $_ => 1 } @KW;
22 my $L_MAX = 244; # Xapian term limit - length('L')
23
24 # RFC 8621, sec 2 (Mailboxes) a "label" for us is a JMAP Mailbox "name"
25 # "Servers MAY reject names that violate server policy"
26 my %ERR = (
27         L => sub {
28                 my ($label) = @_;
29                 length($label) >= $L_MAX and
30                         return "`$label' too long (must be <= $L_MAX)";
31                 $label =~ m{\A[a-z0-9_](?:[a-z0-9_\-\./\@,]*[a-z0-9])?\z}i ?
32                         undef : "`$label' is invalid";
33         },
34         kw => sub {
35                 my ($kw) = @_;
36                 $KW{$kw} ? undef : <<EOM;
37 `$kw' is not one of: `seen', `flagged', `answered', `draft'
38 `junk', `notjunk', `phishing' or `forwarded'
39 EOM
40         }
41 );
42
43 sub check_input_format ($;$) {
44         my ($lei, $files) = @_;
45         my $opt_key = 'in-format';
46         my $fmt = $lei->{opt}->{$opt_key};
47         if (!$fmt) {
48                 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
49                 return $lei->fail("--$opt_key unset for $err");
50         }
51         return 1 if $fmt eq 'eml';
52         require PublicInbox::MboxLock if $files;
53         require PublicInbox::MboxReader;
54         PublicInbox::MboxReader->reads($fmt) or
55                 return $lei->fail("--$opt_key=$fmt unrecognized");
56         1;
57 }
58
59 # import a single file handle of $name
60 # Subclass must define ->input_eml_cb and ->input_mbox_cb
61 sub input_fh {
62         my ($self, $ifmt, $fh, $name, @args) = @_;
63         if ($ifmt eq 'eml') {
64                 my $buf = do { local $/; <$fh> } //
65                         return $self->{lei}->child_error(1 << 8, <<"");
66 error reading $name: $!
67
68                 # mutt pipes single RFC822 messages with a "From " line,
69                 # but no Content-Length or "From " escaping.
70                 # "git format-patch" also generates such files by default.
71                 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
72
73                 # a user may feed just a body: git diff | lei rediff -U9
74                 if ($self->{-force_eml}) {
75                         my $eml = PublicInbox::Eml->new($buf);
76                         substr($buf, 0, 0) = "\n\n" if !$eml->{bdy};
77                 }
78                 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
79         } else {
80                 # prepare_inputs already validated $ifmt
81                 my $cb = PublicInbox::MboxReader->reads($ifmt) //
82                                 die "BUG: bad fmt=$ifmt";
83                 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
84         }
85 }
86
87 # handles mboxrd endpoints described in Documentation/design_notes.txt
88 sub handle_http_input ($$@) {
89         my ($self, $url, @args) = @_;
90         my $lei = $self->{lei} or die 'BUG: {lei} missing';
91         my $curl_opt = delete $self->{"-curl-$url"} or
92                                 die("BUG: $url curl options not prepared");
93         my $uri = pop @$curl_opt;
94         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
95         push @$curl, '-s', @$curl_opt;
96         my $cmd = $curl->for_uri($lei, $uri);
97         $lei->qerr("# $cmd");
98         my $rdr = { 2 => $lei->{2}, pgid => 0 };
99         my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
100         grep(/\A--compressed\z/, @$curl) or
101                 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
102         eval { $self->input_fh('mboxrd', $fh, $url, @args) };
103         my $err = $@;
104         waitpid($pid, 0);
105         $? || $err and
106                 $lei->child_error($? || 1, "@$cmd failed".$err ? " $err" : '');
107 }
108
109 sub input_path_url {
110         my ($self, $input, @args) = @_;
111         my $lei = $self->{lei};
112         my $ifmt = lc($lei->{opt}->{'in-format'} // '');
113         # TODO auto-detect?
114         if ($input =~ m!\Aimaps?://!i) {
115                 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
116                                                 $self, @args);
117                 return;
118         } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
119                 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
120                                                 $self, @args);
121                 return;
122         } elsif ($input =~ m!\Ahttps?://!i) {
123                 handle_http_input($self, $input, @args);
124                 return;
125         }
126         if ($input =~ s!\A([a-z0-9]+):!!i) {
127                 $ifmt = lc($1);
128         } elsif ($input =~ /\.(?:patch|eml)\z/i) {
129                 $ifmt = 'eml';
130         }
131         my $devfd = $lei->path_to_fd($input) // return;
132         if ($devfd >= 0) {
133                 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
134         } elsif (-f $input && $ifmt eq 'eml') {
135                 open my $fh, '<', $input or
136                                         return $lei->fail("open($input): $!");
137                 $self->input_fh($ifmt, $fh, $input, @args);
138         } elsif (-f _) {
139                 my $m = $lei->{opt}->{'lock'} //
140                         PublicInbox::MboxLock->defaults;
141                 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
142                 my $zsfx = PublicInbox::MboxReader::zsfx($input);
143                 if ($zsfx) {
144                         my $in = delete $mbl->{fh};
145                         $mbl->{fh} =
146                              PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
147                 }
148                 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
149                 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
150         } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
151                 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
152 $input appears to be a maildir, not $ifmt
153 EOM
154                 my $mdr = PublicInbox::MdirReader->new;
155                 if (my $pmd = $self->{pmd}) {
156                         $mdr->maildir_each_file($input,
157                                                 $pmd->can('each_mdir_fn'),
158                                                 $pmd, @args);
159                 } else {
160                         $mdr->maildir_each_eml($input,
161                                                 $self->can('input_maildir_cb'),
162                                                 $self, @args);
163                 }
164         } else {
165                 $lei->fail("$input unsupported (TODO)");
166         }
167 }
168
169 sub bad_http ($$;$) {
170         my ($lei, $url, $alt) = @_;
171         my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
172         $lei->fail("E: <$url> not recognized, $x");
173 }
174
175 sub prepare_http_input ($$$) {
176         my ($self, $lei, $url) = @_;
177         require URI;
178         require PublicInbox::MboxReader;
179         require PublicInbox::LeiCurl;
180         require IO::Uncompress::Gunzip;
181         $self->{curl} //= which('curl') or
182                                 return $lei->fail("curl missing for <$url>");
183         my $uri = URI->new($url);
184         my $path = $uri->path;
185         my %qf = $uri->query_form;
186         my @curl_opt;
187         if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
188                 # OK
189         } elsif ($path =~ m!/raw\z!) {
190                 push @curl_opt, '--compressed';
191         # convert search query to mboxrd request since they require POST
192         # this is only intended for PublicInbox::WWW, and will false-positive
193         # on many other search engines... oh well
194         } elsif (defined $qf{'q'}) {
195                 $qf{x} = 'm';
196                 $uri->query_form(\%qf);
197                 push @curl_opt, '-d', '';
198                 $$uri ne $url and $lei->qerr(<<"");
199 # <$url> rewritten to <$$uri> with HTTP POST
200
201         # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
202         } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
203                         $path =~ s!/t\.atom\z!/t.mbox.gz! ||
204                         $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
205                 $uri->path($path);
206                 return bad_http($lei, $url, $$uri);
207         } else {
208                 return bad_http($lei, $url);
209         }
210         $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
211 }
212
213 sub prepare_inputs { # returns undef on error
214         my ($self, $lei, $inputs) = @_;
215         my $in_fmt = $lei->{opt}->{'in-format'};
216         my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
217         if ($lei->{opt}->{stdin}) {
218                 @$inputs and return
219                         $lei->fail("--stdin and @$inputs do not mix");
220                 check_input_format($lei) or return;
221                 push @$inputs, '/dev/stdin';
222                 push @{$sync->{no}}, '/dev/stdin' if $sync;
223         }
224         my $net = $lei->{net}; # NetWriter may be created by l2m
225         my (@f, @md);
226         # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
227         for my $input (@$inputs) {
228                 my $input_path = $input;
229                 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
230                         require PublicInbox::NetReader;
231                         $net //= PublicInbox::NetReader->new;
232                         $net->add_url($input, $self->{-ls_ok});
233                         push @{$sync->{ok}}, $input if $sync;
234                 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
235                         # TODO: how would we detect r/w JMAP?
236                         push @{$sync->{no}}, $input if $sync;
237                         prepare_http_input($self, $lei, $input_path) or return;
238                 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
239                         my $ifmt = lc $1;
240                         if (($in_fmt // $ifmt) ne $ifmt) {
241                                 return $lei->fail(<<"");
242 --in-format=$in_fmt and `$ifmt:' conflict
243
244                         }
245                         if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
246                                 push @{$sync->{ok}}, $input if $sync;
247                         } else {
248                                 push @{$sync->{no}}, $input if $sync;
249                         }
250                         my $devfd = $lei->path_to_fd($input_path) // return;
251                         if ($devfd >= 0 || (-f $input_path || -p _)) {
252                                 require PublicInbox::MboxLock;
253                                 require PublicInbox::MboxReader;
254                                 PublicInbox::MboxReader->reads($ifmt) or return
255                                         $lei->fail("$ifmt not supported");
256                         } elsif (-d $input_path) {
257                                 $ifmt eq 'maildir' or return
258                                         $lei->fail("$ifmt not supported");
259                                 $sync and $input = 'maildir:'.
260                                                 $lei->abs_path($input_path);
261                                 push @md, $input;
262                         } else {
263                                 return $lei->fail("Unable to handle $input");
264                         }
265                 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
266                         lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
267 $input is `eml', not --in-format=$in_fmt
268
269                         require PublicInbox::Eml;
270                         push @{$sync->{no}}, $input if $sync;
271                 } else {
272                         my $devfd = $lei->path_to_fd($input) // return;
273                         if ($devfd >= 0 || -f $input || -p _) {
274                                 push @{$sync->{no}}, $input if $sync;
275                                 push @f, $input;
276                         } elsif (-d "$input/new" && -d "$input/cur") {
277                                 if ($sync) {
278                                         $input = $lei->abs_path($input);
279                                         push @{$sync->{ok}}, $input;
280                                 }
281                                 push @md, $input;
282                         } else {
283                                 return $lei->fail("Unable to handle $input")
284                         }
285                 }
286         }
287         if (@f) { check_input_format($lei, \@f) or return }
288         if ($sync && $sync->{no}) {
289                 return $lei->fail(<<"") if !$sync->{ok};
290 --mail-sync specified but no inputs support it
291
292                 # non-fatal if some inputs support support sync
293                 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
294                 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
295         }
296         if ($net) {
297                 $net->{-can_die} = 1;
298                 if (my $err = $net->errors($lei)) {
299                         return $lei->fail($err);
300                 }
301                 $net->{quiet} = $lei->{opt}->{quiet};
302                 require PublicInbox::LeiAuth;
303                 $lei->{auth} //= PublicInbox::LeiAuth->new;
304                 $lei->{net} //= $net;
305         }
306         if (scalar(@md)) {
307                 require PublicInbox::MdirReader;
308                 if ($self->can('pmdir_cb')) {
309                         require PublicInbox::LeiPmdir;
310                         $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
311                 }
312         }
313         $self->{inputs} = $inputs;
314 }
315
316 sub process_inputs {
317         my ($self) = @_;
318         my $err;
319         for my $input (@{$self->{inputs}}) {
320                 eval { $self->input_path_url($input) };
321                 next unless $@;
322                 $err = "$input: $@";
323                 last;
324         }
325         # always commit first, even on error partial work is acceptable for
326         # lei <import|tag|convert>
327         my $wait = $self->{lei}->{sto}->ipc_do('done') if $self->{lei}->{sto};
328         $self->{lei}->fail($err) if $err;
329 }
330
331 sub input_only_atfork_child {
332         my ($self) = @_;
333         my $lei = $self->{lei};
334         $lei->_lei_atfork_child;
335         PublicInbox::IPC::ipc_atfork_child($self);
336         $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
337         undef;
338 }
339
340 # alias this as "net_merge_all_done" to use as an LeiAuth callback
341 sub input_only_net_merge_all_done {
342         my ($self) = @_;
343         $self->wq_io_do('process_inputs');
344         $self->wq_close(1);
345 }
346
347 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
348 # for update_xvmd -> update_vmd
349 sub vmd_mod_extract {
350         my $argv = $_[-1];
351         my $vmd_mod = {};
352         my @new_argv;
353         for my $x (@$argv) {
354                 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
355                         my ($op, $pfx, $val) = ($1, $2, $3);
356                         if (my $err = $ERR{$pfx}->($val)) {
357                                 push @{$vmd_mod->{err}}, $err;
358                         } else { # set "+kw", "+L", "-L", "-kw"
359                                 push @{$vmd_mod->{$op.$pfx}}, $val;
360                         }
361                 } else {
362                         push @new_argv, $x;
363                 }
364         }
365         @$argv = @new_argv;
366         $vmd_mod;
367 }
368
369 1;