]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiInput.pm
85caac35aa24d8ab1f7d7d0e173377ca2c83ab40
[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
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
11 # JMAP RFC 8621 4.1.1
12 # https://www.iana.org/assignments/imap-jmap-keywords/imap-jmap-keywords.xhtml
13 our @KW = (qw(seen answered flagged draft), # widely-compatible
14         qw(forwarded), # IMAP + Maildir
15         qw(phishing junk notjunk)); # rarely supported
16
17 # note: RFC 8621 states "Users may add arbitrary keywords to an Email",
18 # but is it good idea?  Stick to the system and reserved ones, for now.
19 # The widely-compatible ones map to IMAP system flags, Maildir flags
20 # and mbox Status/X-Status headers.
21 my %KW = map { $_ => 1 } @KW;
22 my $L_MAX = 244; # Xapian term limit - length('L')
23
24 # RFC 8621, sec 2 (Mailboxes) a "label" for us is a JMAP Mailbox "name"
25 # "Servers MAY reject names that violate server policy"
26 my %ERR = (
27         L => sub {
28                 my ($label) = @_;
29                 length($label) >= $L_MAX and
30                         return "`$label' too long (must be <= $L_MAX)";
31                 $label =~ m{\A[a-z0-9_](?:[a-z0-9_\-\./\@,]*[a-z0-9])?\z}i ?
32                         undef : "`$label' is invalid";
33         },
34         kw => sub {
35                 my ($kw) = @_;
36                 $KW{$kw} ? undef : <<EOM;
37 `$kw' is not one of: `seen', `flagged', `answered', `draft'
38 `junk', `notjunk', `phishing' or `forwarded'
39 EOM
40         }
41 );
42
43 sub check_input_format ($;$) {
44         my ($lei, $files) = @_;
45         my $opt_key = 'in-format';
46         my $fmt = $lei->{opt}->{$opt_key};
47         if (!$fmt) {
48                 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
49                 return $lei->fail("--$opt_key unset for $err");
50         }
51         return 1 if $fmt eq 'eml';
52         require PublicInbox::MboxLock if $files;
53         require PublicInbox::MboxReader;
54         PublicInbox::MboxReader->reads($fmt) or
55                 return $lei->fail("--$opt_key=$fmt unrecognized");
56         1;
57 }
58
59 # import a single file handle of $name
60 # Subclass must define ->input_eml_cb and ->input_mbox_cb
61 sub input_fh {
62         my ($self, $ifmt, $fh, $name, @args) = @_;
63         if ($ifmt eq 'eml') {
64                 my $buf = do { local $/; <$fh> } //
65                         return $self->{lei}->child_error(1 << 8, <<"");
66 error reading $name: $!
67
68                 # mutt pipes single RFC822 messages with a "From " line,
69                 # but no Content-Length or "From " escaping.
70                 # "git format-patch" also generates such files by default.
71                 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
72                 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
73         } else {
74                 # prepare_inputs already validated $ifmt
75                 my $cb = PublicInbox::MboxReader->reads($ifmt) //
76                                 die "BUG: bad fmt=$ifmt";
77                 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
78         }
79 }
80
81 # handles mboxrd endpoints described in Documentation/design_notes.txt
82 sub handle_http_input ($$@) {
83         my ($self, $url, @args) = @_;
84         my $lei = $self->{lei} or die 'BUG: {lei} missing';
85         my $curl_opt = delete $self->{"-curl-$url"} or
86                                 die("BUG: $url curl options not prepared");
87         my $uri = pop @$curl_opt;
88         my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
89         push @$curl, '-s', @$curl_opt;
90         my $cmd = $curl->for_uri($lei, $uri);
91         $lei->qerr("# $cmd");
92         my $rdr = { 2 => $lei->{2}, pgid => 0 };
93         my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
94         grep(/\A--compressed\z/, @$curl) or
95                 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
96         eval {
97                 PublicInbox::MboxReader->mboxrd($fh,
98                                                 $self->can('input_mbox_cb'),
99                                                 $self, @args);
100         };
101         my $err = $@;
102         waitpid($pid, 0);
103         $? || $err and
104                 $lei->child_error($? || 1, "@$cmd failed".$err ? " $err" : '');
105 }
106
107 sub input_path_url {
108         my ($self, $input, @args) = @_;
109         my $lei = $self->{lei};
110         my $ifmt = lc($lei->{opt}->{'in-format'} // '');
111         # TODO auto-detect?
112         if ($input =~ m!\Aimaps?://!i) {
113                 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
114                                                 $self, @args);
115                 return;
116         } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
117                 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
118                                                 $self, @args);
119                 return;
120         } elsif ($input =~ m!\Ahttps?://!i) {
121                 handle_http_input($self, $input, @args);
122                 return;
123         }
124         if ($input =~ s!\A([a-z0-9]+):!!i) {
125                 $ifmt = lc($1);
126         } elsif ($input =~ /\.(?:patch|eml)\z/i) {
127                 $ifmt = 'eml';
128         }
129         my $devfd = $lei->path_to_fd($input) // return;
130         if ($devfd >= 0) {
131                 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
132         } elsif (-f $input && $ifmt eq 'eml') {
133                 open my $fh, '<', $input or
134                                         return $lei->fail("open($input): $!");
135                 $self->input_fh($ifmt, $fh, $input, @args);
136         } elsif (-f _) {
137                 my $m = $lei->{opt}->{'lock'} //
138                         PublicInbox::MboxLock->defaults;
139                 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
140                 my $zsfx = PublicInbox::MboxReader::zsfx($input);
141                 if ($zsfx) {
142                         my $in = delete $mbl->{fh};
143                         $mbl->{fh} =
144                              PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
145                 }
146                 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
147                 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
148         } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
149                 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
150 $input appears to a be a maildir, not $ifmt
151 EOM
152                 PublicInbox::MdirReader->new->maildir_each_eml($input,
153                                         $self->can('input_maildir_cb'),
154                                         $self, @args);
155         } else {
156                 $lei->fail("$input unsupported (TODO)");
157         }
158 }
159
160 sub bad_http ($$;$) {
161         my ($lei, $url, $alt) = @_;
162         my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
163         $lei->fail("E: <$url> not recognized, $x");
164 }
165
166 sub prepare_http_input ($$$) {
167         my ($self, $lei, $url) = @_;
168         require URI;
169         require PublicInbox::MboxReader;
170         require PublicInbox::LeiCurl;
171         require IO::Uncompress::Gunzip;
172         $self->{curl} //= which('curl') or
173                                 return $lei->fail("curl missing for <$url>");
174         my $uri = URI->new($url);
175         my $path = $uri->path;
176         my %qf = $uri->query_form;
177         my @curl_opt;
178         if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
179                 # OK
180         } elsif ($path =~ m!/raw\z!) {
181                 push @curl_opt, '--compressed';
182         # convert search query to mboxrd request since they require POST
183         # this is only intended for PublicInbox::WWW, and will false-positive
184         # on many other search engines... oh well
185         } elsif (defined $qf{'q'}) {
186                 $qf{x} = 'm';
187                 $uri->query_form(\%qf);
188                 push @curl_opt, '-d', '';
189                 $$uri ne $url and $lei->qerr(<<"");
190 # <$url> rewritten to <$$uri> with HTTP POST
191
192         # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
193         } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
194                         $path =~ s!/t\.atom\z!/t.mbox.gz! ||
195                         $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
196                 $uri->path($path);
197                 return bad_http($lei, $url, $$uri);
198         } else {
199                 return bad_http($lei, $url);
200         }
201         $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
202 }
203
204 sub prepare_inputs { # returns undef on error
205         my ($self, $lei, $inputs) = @_;
206         my $in_fmt = $lei->{opt}->{'in-format'};
207         my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
208         if ($lei->{opt}->{stdin}) {
209                 @$inputs and return
210                         $lei->fail("--stdin and @$inputs do not mix");
211                 check_input_format($lei) or return;
212                 push @$inputs, '/dev/stdin';
213                 push @{$sync->{no}}, '/dev/stdin' if $sync;
214         }
215         my $net = $lei->{net}; # NetWriter may be created by l2m
216         my (@f, @d);
217         # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
218         for my $input (@$inputs) {
219                 my $input_path = $input;
220                 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
221                         require PublicInbox::NetReader;
222                         $net //= PublicInbox::NetReader->new;
223                         $net->add_url($input);
224                         if ($sync) {
225                                 if ($input =~ m!\Aimaps?://!) {
226                                         push @{$sync->{ok}}, $input;
227                                 } else {
228                                         push @{$sync->{no}}, $input;
229                                 }
230                         }
231                 } elsif ($input_path =~ m!\Ahttps?://!i) {
232                         # TODO: how would we detect r/w JMAP?
233                         push @{$sync->{no}}, $input if $sync;
234                         prepare_http_input($self, $lei, $input_path) or return;
235                 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
236                         my $ifmt = lc $1;
237                         if (($in_fmt // $ifmt) ne $ifmt) {
238                                 return $lei->fail(<<"");
239 --in-format=$in_fmt and `$ifmt:' conflict
240
241                         }
242                         if ($sync) {
243                                 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
244                                         push @{$sync->{ok}}, $input;
245                                 } else {
246                                         push @{$sync->{no}}, $input;
247                                 }
248                         }
249                         my $devfd = $lei->path_to_fd($input_path) // return;
250                         if ($devfd >= 0 || (-f $input_path || -p _)) {
251                                 require PublicInbox::MboxLock;
252                                 require PublicInbox::MboxReader;
253                                 PublicInbox::MboxReader->reads($ifmt) or return
254                                         $lei->fail("$ifmt not supported");
255                         } elsif (-d $input_path) {
256                                 require PublicInbox::MdirReader;
257                                 $ifmt eq 'maildir' or return
258                                         $lei->fail("$ifmt not supported");
259                                 $input = $lei->abs_path($input) if $sync;
260                         } else {
261                                 return $lei->fail("Unable to handle $input");
262                         }
263                 } elsif ($input =~ /\.(eml|patch)\z/i && -f $input) {
264                         lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
265 $input is `eml', not --in-format=$in_fmt
266
267                         require PublicInbox::Eml;
268                         push @{$sync->{no}}, $input if $sync;
269                 } else {
270                         my $devfd = $lei->path_to_fd($input) // return;
271                         if ($devfd >= 0 || -f $input || -p _) {
272                                 push @{$sync->{no}}, $input if $sync;
273                                 push @f, $input;
274                         } elsif (-d $input) {
275                                 if ($sync) {
276                                         $input = $lei->abs_path($input);
277                                         push @{$sync->{ok}}, $input;
278                                 }
279                                 push @d, $input;
280                         } else {
281                                 return $lei->fail("Unable to handle $input")
282                         }
283                 }
284         }
285         if (@f) { check_input_format($lei, \@f) or return }
286         if (@d) { # TODO: check for MH vs Maildir, here
287                 require PublicInbox::MdirReader;
288         }
289         if ($sync && $sync->{no}) {
290                 return $lei->fail(<<"") if !$sync->{ok};
291 --mail-sync specified but no inputs support it
292
293                 # non-fatal if some inputs support support sync
294                 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
295                 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
296         }
297         if ($net) {
298                 $net->{-can_die} = 1;
299                 if (my $err = $net->errors($lei)) {
300                         return $lei->fail($err);
301                 }
302                 $net->{quiet} = $lei->{opt}->{quiet};
303                 require PublicInbox::LeiAuth;
304                 $lei->{auth} //= PublicInbox::LeiAuth->new;
305                 $lei->{net} //= $net;
306         }
307         $self->{inputs} = $inputs;
308 }
309
310 sub process_inputs {
311         my ($self) = @_;
312         my $err;
313         for my $input (@{$self->{inputs}}) {
314                 eval { $self->input_path_url($input) };
315                 next unless $@;
316                 $err = "$input: $@";
317                 last;
318         }
319         # always commit first, even on error partial work is acceptable for
320         # lei <import|tag|convert>
321         my $wait = $self->{lei}->{sto}->ipc_do('done') if $self->{lei}->{sto};
322         $self->{lei}->fail($err) if $err;
323 }
324
325 sub input_only_atfork_child {
326         my ($self) = @_;
327         my $lei = $self->{lei};
328         $lei->_lei_atfork_child;
329         PublicInbox::IPC::ipc_atfork_child($self);
330         $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
331         undef;
332 }
333
334 # alias this as "net_merge_all_done" to use as an LeiAuth callback
335 sub input_only_net_merge_all_done {
336         my ($self) = @_;
337         $self->wq_io_do('process_inputs');
338         $self->wq_close(1);
339 }
340
341 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
342 # for update_xvmd -> update_vmd
343 sub vmd_mod_extract {
344         my $argv = $_[-1];
345         my $vmd_mod = {};
346         my @new_argv;
347         for my $x (@$argv) {
348                 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
349                         my ($op, $pfx, $val) = ($1, $2, $3);
350                         if (my $err = $ERR{$pfx}->($val)) {
351                                 push @{$vmd_mod->{err}}, $err;
352                         } else { # set "+kw", "+L", "-L", "-kw"
353                                 push @{$vmd_mod->{$op.$pfx}}, $val;
354                         }
355                 } else {
356                         push @new_argv, $x;
357                 }
358         }
359         @$argv = @new_argv;
360         $vmd_mod;
361 }
362
363 1;