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