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