1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # parent class for LeiImport, LeiConvert, LeiIndex
5 package PublicInbox::LeiInput;
9 use PublicInbox::Spawn qw(which popen_rd);
10 use PublicInbox::InboxWritable qw(eml_from_path);
11 use PublicInbox::AutoReap;
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
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')
26 # RFC 8621, sec 2 (Mailboxes) a "label" for us is a JMAP Mailbox "name"
27 # "Servers MAY reject names that violate server policy"
31 length($label) >= $L_MAX and
32 return "`$label' too long (must be <= $L_MAX)";
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";
40 $KW{$kw} ? undef : <<EOM;
41 `$kw' is not one of: `seen', `flagged', `answered', `draft'
42 `junk', `notjunk', `phishing' or `forwarded'
47 sub check_input_format ($;$) {
48 my ($lei, $files) = @_;
49 my $opt_key = 'in-format';
50 my $fmt = $lei->{opt}->{$opt_key};
52 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
53 return $lei->fail("--$opt_key unset for $err");
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");
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);
69 sub input_maildir_cb {
70 my ($fn, $kw, $eml, $self) = @_;
71 $self->input_eml_cb($eml);
74 sub input_net_cb { # imap_each, nntp_each cb
75 my ($url, $uid, $kw, $eml, $self) = @_;
76 $self->input_eml_cb($eml);
79 # import a single file handle of $name
80 # Subclass must define ->input_eml_cb and ->input_mbox_cb
82 my ($self, $ifmt, $fh, $name, @args) = @_;
84 my $buf = do { local $/; <$fh> } //
85 return $self->{lei}->child_error(0, <<"");
86 error reading $name: $!
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;
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};
98 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
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);
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 = ($@ ? $@ : ());
125 push(@err, "\$?=$?") if $?;
126 $lei->child_error($?, "@$cmd failed: @err") if @err;
130 my ($self, $input, @args) = @_;
131 my $lei = $self->{lei};
132 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
134 if ($input =~ m!\Aimaps?://!i) {
135 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
138 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
139 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
142 } elsif ($input =~ m!\Ahttps?://!i) {
143 handle_http_input($self, $input, @args);
149 if ($input =~ s!\A([a-z0-9]+):!!i) {
152 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
154 } elsif (-f $input && $input =~ m{\A(?:.+)/(?:new|cur)/([^/]+)\z}) {
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);
165 my $devfd = $lei->path_to_fd($input) // return;
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);
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);
178 my $in = delete $mbl->{fh};
180 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
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
188 my $mdr = PublicInbox::MdirReader->new;
189 if (my $pmd = $self->{pmd}) {
190 $mdr->maildir_each_file($input,
191 $pmd->can('each_mdir_fn'),
194 $mdr->maildir_each_eml($input,
195 $self->can('input_maildir_cb'),
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;
208 $self->folder_missing("$ifmt:$input");
211 $lei->fail("$ifmt_pfx$input unsupported (TODO)");
215 # subclasses should overrride this (see LeiRefreshMailSync)
216 sub folder_missing { die "BUG: ->folder_missing undefined for $_[0]" }
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");
224 sub prepare_http_input ($$$) {
225 my ($self, $lei, $url) = @_;
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;
236 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
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'}) {
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
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!) {
255 return bad_http($lei, $url, $$uri);
257 return bad_http($lei, $url);
259 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
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}) {
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;
274 my $net = $lei->{net}; # NetWriter may be created by l2m
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) {
290 if (($in_fmt // $ifmt) ne $ifmt) {
291 return $lei->fail(<<"");
292 --in-format=$in_fmt and `$ifmt:' conflict
295 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
296 push @{$sync->{ok}}, $input if $sync;
298 push @{$sync->{no}}, $input if $sync;
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);
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);
317 my $m = "Unable to handle $input";
318 $input =~ /\A(?:L|kw):/ and
319 $m .= ", did you mean +$input?";
320 return $lei->fail($m);
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
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'
334 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
335 $input is `eml', not --in-format=$in_fmt
338 $input = $lei->abs_path($mdir) . "/$nc/$bn";
339 push @{$sync->{ok}}, $input if $sync;
341 require PublicInbox::MdirReader;
343 my $devfd = $lei->path_to_fd($input) // return;
344 if ($devfd >= 0 || -f $input || -p _) {
345 push @{$sync->{no}}, $input if $sync;
347 } elsif (-d "$input/new" && -d "$input/cur") {
350 $lei->abs_path($input);
351 push @{$sync->{ok}}, $input if $sync;
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
359 $lei->abs_path($input);
362 return $lei->fail("Unable to handle $input")
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
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");
376 $net->{-can_die} = 1;
377 if (my $err = $net->errors($lei)) {
378 return $lei->fail($err);
380 $net->{quiet} = $lei->{opt}->{quiet};
381 require PublicInbox::LeiAuth;
382 $lei->{auth} //= PublicInbox::LeiAuth->new;
383 $lei->{net} //= $net;
386 require PublicInbox::MdirReader;
387 if ($self->can('pmdir_cb')) {
388 require PublicInbox::LeiPmdir;
389 $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
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;
399 $self->{inputs} = $inputs;
405 for my $input (@{$self->{inputs}}) {
406 eval { $self->input_path_url($input) };
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;
417 sub input_only_atfork_child {
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};
426 # alias this as "net_merge_all_done" to use as an LeiAuth callback
427 sub input_only_net_merge_all_done {
429 $self->wq_io_do('process_inputs');
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 {
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;