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