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