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