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