]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiInput.pm
46eea1118394abb2af004f13870a5f67d450a05c
[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
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 { $self->input_fh('mboxrd', $fh, $url, @args) };
97         my $err = $@;
98         waitpid($pid, 0);
99         $? || $err and
100                 $lei->child_error($? || 1, "@$cmd failed".$err ? " $err" : '');
101 }
102
103 sub input_path_url {
104         my ($self, $input, @args) = @_;
105         my $lei = $self->{lei};
106         my $ifmt = lc($lei->{opt}->{'in-format'} // '');
107         # TODO auto-detect?
108         if ($input =~ m!\Aimaps?://!i) {
109                 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
110                                                 $self, @args);
111                 return;
112         } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
113                 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
114                                                 $self, @args);
115                 return;
116         } elsif ($input =~ m!\Ahttps?://!i) {
117                 handle_http_input($self, $input, @args);
118                 return;
119         }
120         if ($input =~ s!\A([a-z0-9]+):!!i) {
121                 $ifmt = lc($1);
122         } elsif ($input =~ /\.(?:patch|eml)\z/i) {
123                 $ifmt = 'eml';
124         }
125         my $devfd = $lei->path_to_fd($input) // return;
126         if ($devfd >= 0) {
127                 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
128         } elsif (-f $input && $ifmt eq 'eml') {
129                 open my $fh, '<', $input or
130                                         return $lei->fail("open($input): $!");
131                 $self->input_fh($ifmt, $fh, $input, @args);
132         } elsif (-f _) {
133                 my $m = $lei->{opt}->{'lock'} //
134                         PublicInbox::MboxLock->defaults;
135                 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
136                 my $zsfx = PublicInbox::MboxReader::zsfx($input);
137                 if ($zsfx) {
138                         my $in = delete $mbl->{fh};
139                         $mbl->{fh} =
140                              PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
141                 }
142                 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
143                 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
144         } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
145                 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
146 $input appears to a be a maildir, not $ifmt
147 EOM
148                 PublicInbox::MdirReader->new->maildir_each_eml($input,
149                                         $self->can('input_maildir_cb'),
150                                         $self, @args);
151         } else {
152                 $lei->fail("$input unsupported (TODO)");
153         }
154 }
155
156 sub bad_http ($$;$) {
157         my ($lei, $url, $alt) = @_;
158         my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
159         $lei->fail("E: <$url> not recognized, $x");
160 }
161
162 sub prepare_http_input ($$$) {
163         my ($self, $lei, $url) = @_;
164         require URI;
165         require PublicInbox::MboxReader;
166         require PublicInbox::LeiCurl;
167         require IO::Uncompress::Gunzip;
168         $self->{curl} //= which('curl') or
169                                 return $lei->fail("curl missing for <$url>");
170         my $uri = URI->new($url);
171         my $path = $uri->path;
172         my %qf = $uri->query_form;
173         my @curl_opt;
174         if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
175                 # OK
176         } elsif ($path =~ m!/raw\z!) {
177                 push @curl_opt, '--compressed';
178         # convert search query to mboxrd request since they require POST
179         # this is only intended for PublicInbox::WWW, and will false-positive
180         # on many other search engines... oh well
181         } elsif (defined $qf{'q'}) {
182                 $qf{x} = 'm';
183                 $uri->query_form(\%qf);
184                 push @curl_opt, '-d', '';
185                 $$uri ne $url and $lei->qerr(<<"");
186 # <$url> rewritten to <$$uri> with HTTP POST
187
188         # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
189         } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
190                         $path =~ s!/t\.atom\z!/t.mbox.gz! ||
191                         $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
192                 $uri->path($path);
193                 return bad_http($lei, $url, $$uri);
194         } else {
195                 return bad_http($lei, $url);
196         }
197         $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
198 }
199
200 sub prepare_inputs { # returns undef on error
201         my ($self, $lei, $inputs) = @_;
202         my $in_fmt = $lei->{opt}->{'in-format'};
203         my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
204         if ($lei->{opt}->{stdin}) {
205                 @$inputs and return
206                         $lei->fail("--stdin and @$inputs do not mix");
207                 check_input_format($lei) or return;
208                 push @$inputs, '/dev/stdin';
209                 push @{$sync->{no}}, '/dev/stdin' if $sync;
210         }
211         my $net = $lei->{net}; # NetWriter may be created by l2m
212         my (@f, @d);
213         # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
214         for my $input (@$inputs) {
215                 my $input_path = $input;
216                 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
217                         require PublicInbox::NetReader;
218                         $net //= PublicInbox::NetReader->new;
219                         $net->add_url($input);
220                         push @{$sync->{ok}}, $input if $sync;
221                 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
222                         # TODO: how would we detect r/w JMAP?
223                         push @{$sync->{no}}, $input if $sync;
224                         prepare_http_input($self, $lei, $input_path) or return;
225                 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
226                         my $ifmt = lc $1;
227                         if (($in_fmt // $ifmt) ne $ifmt) {
228                                 return $lei->fail(<<"");
229 --in-format=$in_fmt and `$ifmt:' conflict
230
231                         }
232                         if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
233                                 push @{$sync->{ok}}, $input if $sync;
234                         } else {
235                                 push @{$sync->{no}}, $input if $sync;
236                         }
237                         my $devfd = $lei->path_to_fd($input_path) // return;
238                         if ($devfd >= 0 || (-f $input_path || -p _)) {
239                                 require PublicInbox::MboxLock;
240                                 require PublicInbox::MboxReader;
241                                 PublicInbox::MboxReader->reads($ifmt) or return
242                                         $lei->fail("$ifmt not supported");
243                         } elsif (-d $input_path) {
244                                 require PublicInbox::MdirReader;
245                                 $ifmt eq 'maildir' or return
246                                         $lei->fail("$ifmt not supported");
247                                 $input = $lei->abs_path($input) if $sync;
248                         } else {
249                                 return $lei->fail("Unable to handle $input");
250                         }
251                 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
252                         lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
253 $input is `eml', not --in-format=$in_fmt
254
255                         require PublicInbox::Eml;
256                         push @{$sync->{no}}, $input if $sync;
257                 } else {
258                         my $devfd = $lei->path_to_fd($input) // return;
259                         if ($devfd >= 0 || -f $input || -p _) {
260                                 push @{$sync->{no}}, $input if $sync;
261                                 push @f, $input;
262                         } elsif (-d $input) {
263                                 if ($sync) {
264                                         $input = $lei->abs_path($input);
265                                         push @{$sync->{ok}}, $input;
266                                 }
267                                 push @d, $input;
268                         } else {
269                                 return $lei->fail("Unable to handle $input")
270                         }
271                 }
272         }
273         if (@f) { check_input_format($lei, \@f) or return }
274         if (@d) { # TODO: check for MH vs Maildir, here
275                 require PublicInbox::MdirReader;
276         }
277         if ($sync && $sync->{no}) {
278                 return $lei->fail(<<"") if !$sync->{ok};
279 --mail-sync specified but no inputs support it
280
281                 # non-fatal if some inputs support support sync
282                 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
283                 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
284         }
285         if ($net) {
286                 $net->{-can_die} = 1;
287                 if (my $err = $net->errors($lei)) {
288                         return $lei->fail($err);
289                 }
290                 $net->{quiet} = $lei->{opt}->{quiet};
291                 require PublicInbox::LeiAuth;
292                 $lei->{auth} //= PublicInbox::LeiAuth->new;
293                 $lei->{net} //= $net;
294         }
295         $self->{inputs} = $inputs;
296 }
297
298 sub process_inputs {
299         my ($self) = @_;
300         my $err;
301         for my $input (@{$self->{inputs}}) {
302                 eval { $self->input_path_url($input) };
303                 next unless $@;
304                 $err = "$input: $@";
305                 last;
306         }
307         # always commit first, even on error partial work is acceptable for
308         # lei <import|tag|convert>
309         my $wait = $self->{lei}->{sto}->ipc_do('done') if $self->{lei}->{sto};
310         $self->{lei}->fail($err) if $err;
311 }
312
313 sub input_only_atfork_child {
314         my ($self) = @_;
315         my $lei = $self->{lei};
316         $lei->_lei_atfork_child;
317         PublicInbox::IPC::ipc_atfork_child($self);
318         $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
319         undef;
320 }
321
322 # alias this as "net_merge_all_done" to use as an LeiAuth callback
323 sub input_only_net_merge_all_done {
324         my ($self) = @_;
325         $self->wq_io_do('process_inputs');
326         $self->wq_close(1);
327 }
328
329 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
330 # for update_xvmd -> update_vmd
331 sub vmd_mod_extract {
332         my $argv = $_[-1];
333         my $vmd_mod = {};
334         my @new_argv;
335         for my $x (@$argv) {
336                 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
337                         my ($op, $pfx, $val) = ($1, $2, $3);
338                         if (my $err = $ERR{$pfx}->($val)) {
339                                 push @{$vmd_mod->{err}}, $err;
340                         } else { # set "+kw", "+L", "-L", "-kw"
341                                 push @{$vmd_mod->{$op.$pfx}}, $val;
342                         }
343                 } else {
344                         push @new_argv, $x;
345                 }
346         }
347         @$argv = @new_argv;
348         $vmd_mod;
349 }
350
351 1;