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)";
33 $label =~ m{\A[a-z0-9_](?:[a-z0-9_\-\./\@,]*[a-z0-9])?\z}i ?
34 undef : "`$label' is invalid";
38 $KW{$kw} ? undef : <<EOM;
39 `$kw' is not one of: `seen', `flagged', `answered', `draft'
40 `junk', `notjunk', `phishing' or `forwarded'
45 sub check_input_format ($;$) {
46 my ($lei, $files) = @_;
47 my $opt_key = 'in-format';
48 my $fmt = $lei->{opt}->{$opt_key};
50 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
51 return $lei->fail("--$opt_key unset for $err");
53 return 1 if $fmt eq 'eml';
54 require PublicInbox::MboxLock if $files;
55 require PublicInbox::MboxReader;
56 PublicInbox::MboxReader->reads($fmt) or
57 return $lei->fail("--$opt_key=$fmt unrecognized");
61 sub input_mbox_cb { # base MboxReader callback
62 my ($eml, $self) = @_;
63 $eml->header_set($_) for (qw(Status X-Status));
64 $self->input_eml_cb($eml);
67 sub input_net_cb { # imap_each, nntp_each cb
68 my ($url, $uid, $kw, $eml, $self) = @_;
69 $self->input_eml_cb($eml);
72 # import a single file handle of $name
73 # Subclass must define ->input_eml_cb and ->input_mbox_cb
75 my ($self, $ifmt, $fh, $name, @args) = @_;
77 my $buf = do { local $/; <$fh> } //
78 return $self->{lei}->child_error(0, <<"");
79 error reading $name: $!
81 # mutt pipes single RFC822 messages with a "From " line,
82 # but no Content-Length or "From " escaping.
83 # "git format-patch" also generates such files by default.
84 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
86 # a user may feed just a body: git diff | lei rediff -U9
87 if ($self->{-force_eml}) {
88 my $eml = PublicInbox::Eml->new($buf);
89 substr($buf, 0, 0) = "\n\n" if !$eml->{bdy};
91 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
93 # prepare_inputs already validated $ifmt
94 my $cb = PublicInbox::MboxReader->reads($ifmt) //
95 die "BUG: bad fmt=$ifmt";
96 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
100 # handles mboxrd endpoints described in Documentation/design_notes.txt
101 sub handle_http_input ($$@) {
102 my ($self, $url, @args) = @_;
103 my $lei = $self->{lei} or die 'BUG: {lei} missing';
104 my $curl_opt = delete $self->{"-curl-$url"} or
105 die("BUG: $url curl options not prepared");
106 my $uri = pop @$curl_opt;
107 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
108 push @$curl, '-s', @$curl_opt;
109 my $cmd = $curl->for_uri($lei, $uri);
110 $lei->qerr("# $cmd");
111 my ($fh, $pid) = popen_rd($cmd, undef, { 2 => $lei->{2} });
112 my $ar = PublicInbox::AutoReap->new($pid);
113 grep(/\A--compressed\z/, @$curl) or
114 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
115 eval { $self->input_fh('mboxrd', $fh, $url, @args) };
116 my @err = ($@ ? $@ : ());
118 push(@err, "\$?=$?") if $?;
119 $lei->child_error($?, "@$cmd failed: @err") if @err;
123 my ($self, $input, @args) = @_;
124 my $lei = $self->{lei};
125 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
127 if ($input =~ m!\Aimaps?://!i) {
128 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
131 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
132 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
135 } elsif ($input =~ m!\Ahttps?://!i) {
136 handle_http_input($self, $input, @args);
142 if ($input =~ s!\A([a-z0-9]+):!!i) {
145 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
147 } elsif (-f $input && $input =~ m{\A(?:.+)/(?:new|cur)/([^/]+)\z}) {
149 my $fl = PublicInbox::MdirReader::maildir_basename_flags($bn);
150 return if index($fl, 'T') >= 0;
151 return $self->pmdir_cb($input, $fl) if $self->can('pmdir_cb');
152 my $eml = eml_from_path($input) or return
153 $lei->qerr("# $input not readable");
154 my $kw = PublicInbox::MdirReader::flags2kw($fl);
155 $self->can('input_maildir_cb')->($input, $kw, $eml, $self);
158 my $devfd = $lei->path_to_fd($input) // return;
160 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
161 } elsif (-f $input && $ifmt eq 'eml') {
162 open my $fh, '<', $input or
163 return $lei->fail("open($input): $!");
164 $self->input_fh($ifmt, $fh, $input, @args);
166 my $m = $lei->{opt}->{'lock'} //
167 PublicInbox::MboxLock->defaults;
168 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
169 my $zsfx = PublicInbox::MboxReader::zsfx($input);
171 my $in = delete $mbl->{fh};
173 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
175 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
176 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
177 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
178 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
179 $input appears to be a maildir, not $ifmt
181 my $mdr = PublicInbox::MdirReader->new;
182 if (my $pmd = $self->{pmd}) {
183 $mdr->maildir_each_file($input,
184 $pmd->can('each_mdir_fn'),
187 $mdr->maildir_each_eml($input,
188 $self->can('input_maildir_cb'),
191 } elsif ($self->{missing_ok} && !-e $input) { # don't ->fail
192 if ($lei->{cmd} eq 'p2q') {
193 my $fp = [ qw(git format-patch --stdout -1), $input ];
194 my $rdr = { 2 => $lei->{2} };
195 my $fh = popen_rd($fp, undef, $rdr);
196 eval { $self->input_fh('eml', $fh, $input, @args) };
197 my @err = ($@ ? $@ : ());
198 close($fh) or push @err, "\$?=$?";
199 $lei->child_error($?, "@$fp failed: @err") if @err;
201 $self->folder_missing("$ifmt:$input");
204 $lei->fail("$ifmt_pfx$input unsupported (TODO)");
208 # subclasses should overrride this (see LeiRefreshMailSync)
209 sub folder_missing { die "BUG: ->folder_missing undefined for $_[0]" }
211 sub bad_http ($$;$) {
212 my ($lei, $url, $alt) = @_;
213 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
214 $lei->fail("E: <$url> not recognized, $x");
217 sub prepare_http_input ($$$) {
218 my ($self, $lei, $url) = @_;
220 require PublicInbox::MboxReader;
221 require PublicInbox::LeiCurl;
222 require IO::Uncompress::Gunzip;
223 $self->{curl} //= which('curl') or
224 return $lei->fail("curl missing for <$url>");
225 my $uri = URI->new($url);
226 my $path = $uri->path;
227 my %qf = $uri->query_form;
229 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
231 } elsif ($path =~ m!/raw\z!) {
232 push @curl_opt, '--compressed';
233 # convert search query to mboxrd request since they require POST
234 # this is only intended for PublicInbox::WWW, and will false-positive
235 # on many other search engines... oh well
236 } elsif (defined $qf{'q'}) {
238 $uri->query_form(\%qf);
239 push @curl_opt, '-d', '';
240 $$uri ne $url and $lei->qerr(<<"");
241 # <$url> rewritten to <$$uri> with HTTP POST
243 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
244 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
245 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
246 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
248 return bad_http($lei, $url, $$uri);
250 return bad_http($lei, $url);
252 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
255 sub prepare_inputs { # returns undef on error
256 my ($self, $lei, $inputs) = @_;
257 my $in_fmt = $lei->{opt}->{'in-format'};
258 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
259 my $may_sync = $sync || $self->{-mail_sync};
260 if ($lei->{opt}->{stdin}) {
262 $lei->fail("--stdin and @$inputs do not mix");
263 check_input_format($lei) or return;
264 push @$inputs, '/dev/stdin';
265 push @{$sync->{no}}, '/dev/stdin' if $sync;
267 my $net = $lei->{net}; # NetWriter may be created by l2m
269 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
270 for my $input (@$inputs) {
271 my $input_path = $input;
272 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
273 require PublicInbox::NetReader;
274 $net //= PublicInbox::NetReader->new;
275 $net->add_url($input, $self->{-ls_ok});
276 push @{$sync->{ok}}, $input if $sync;
277 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
278 # TODO: how would we detect r/w JMAP?
279 push @{$sync->{no}}, $input if $sync;
280 prepare_http_input($self, $lei, $input_path) or return;
281 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
283 if (($in_fmt // $ifmt) ne $ifmt) {
284 return $lei->fail(<<"");
285 --in-format=$in_fmt and `$ifmt:' conflict
288 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
289 push @{$sync->{ok}}, $input if $sync;
291 push @{$sync->{no}}, $input if $sync;
293 my $devfd = $lei->path_to_fd($input_path) // return;
294 if ($devfd >= 0 || (-f $input_path || -p _)) {
295 require PublicInbox::MboxLock;
296 require PublicInbox::MboxReader;
297 PublicInbox::MboxReader->reads($ifmt) or return
298 $lei->fail("$ifmt not supported");
299 } elsif (-d $input_path) {
300 $ifmt eq 'maildir' or return
301 $lei->fail("$ifmt not supported");
302 $may_sync and $input = 'maildir:'.
303 $lei->abs_path($input_path);
305 } elsif ($self->{missing_ok} && !-e _) {
306 # for "lei rm-watch" on missing Maildir
307 $may_sync and $input = 'maildir:'.
308 $lei->abs_path($input_path);
310 my $m = "Unable to handle $input";
311 $input =~ /\A(?:L|kw):/ and
312 $m .= ", did you mean +$input?";
313 return $lei->fail($m);
315 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
316 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
317 $input is `eml', not --in-format=$in_fmt
319 push @{$sync->{no}}, $input if $sync;
320 } elsif (-f $input && $input =~ m{\A(.+)/(new|cur)/([^/]+)\z}) {
321 # single file in a Maildir
322 my ($mdir, $nc, $bn) = ($1, $2, $3);
323 my $other = $mdir . ($nc eq 'new' ? '/cur' : '/new');
324 return $lei->fail(<<EOM) if !-d $other;
325 No `$other' directory for `$input'
327 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
328 $input is `eml', not --in-format=$in_fmt
331 $input = $lei->abs_path($mdir) . "/$nc/$bn";
332 push @{$sync->{ok}}, $input if $sync;
334 require PublicInbox::MdirReader;
336 my $devfd = $lei->path_to_fd($input) // return;
337 if ($devfd >= 0 || -f $input || -p _) {
338 push @{$sync->{no}}, $input if $sync;
340 } elsif (-d "$input/new" && -d "$input/cur") {
343 $lei->abs_path($input);
344 push @{$sync->{ok}}, $input if $sync;
347 } elsif ($self->{missing_ok} && !-e $input) {
348 if ($lei->{cmd} eq 'p2q') {
349 # will run "git format-patch"
350 } elsif ($may_sync) { # for lei rm-watch
352 $lei->abs_path($input);
355 return $lei->fail("Unable to handle $input")
359 if (@f) { check_input_format($lei, \@f) or return }
360 if ($sync && $sync->{no}) {
361 return $lei->fail(<<"") if !$sync->{ok};
362 --mail-sync specified but no inputs support it
364 # non-fatal if some inputs support support sync
365 warn("# --mail-sync will only be used for @{$sync->{ok}}\n");
366 warn("# --mail-sync is not supported for: @{$sync->{no}}\n");
369 $net->{-can_die} = 1;
370 if (my $err = $net->errors($lei)) {
371 return $lei->fail($err);
373 $net->{quiet} = $lei->{opt}->{quiet};
374 require PublicInbox::LeiAuth;
375 $lei->{auth} //= PublicInbox::LeiAuth->new;
376 $lei->{net} //= $net;
379 require PublicInbox::MdirReader;
380 if ($self->can('pmdir_cb')) {
381 require PublicInbox::LeiPmdir;
382 $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
385 # start watching Maildirs ASAP
386 if ($may_sync && $lei->{sto}) {
387 grep(!m!\Amaildir:/!i, @md) and die "BUG: @md (no pfx)";
388 $lei->lms(1)->lms_write_prepare->add_folders(@md);
389 $lei->refresh_watches;
392 $self->{inputs} = $inputs;
398 for my $input (@{$self->{inputs}}) {
399 eval { $self->input_path_url($input) };
404 # always commit first, even on error partial work is acceptable for
405 # lei <import|tag|convert>
406 my $wait = $self->{lei}->{sto}->wq_do('done') if $self->{lei}->{sto};
407 $self->{lei}->fail($err) if $err;
410 sub input_only_atfork_child {
412 my $lei = $self->{lei};
413 $lei->_lei_atfork_child;
414 PublicInbox::IPC::ipc_atfork_child($self);
415 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
419 # alias this as "net_merge_all_done" to use as an LeiAuth callback
420 sub input_only_net_merge_all_done {
422 $self->wq_io_do('process_inputs');
426 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
427 # for update_xvmd -> update_vmd
428 # returns something like { "+L" => [ @Labels ], ... }
429 sub vmd_mod_extract {
434 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
435 my ($op, $pfx, $val) = ($1, $2, $3);
436 if (my $err = $ERR{$pfx}->($val)) {
437 push @{$vmd_mod->{err}}, $err;
438 } else { # set "+kw", "+L", "-L", "-kw"
439 push @{$vmd_mod->{$op.$pfx}}, $val;