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