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} ?
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_maildir_cb {
68 my ($fn, $kw, $eml, $self) = @_;
69 $self->input_eml_cb($eml);
72 sub input_net_cb { # imap_each, nntp_each cb
73 my ($url, $uid, $kw, $eml, $self) = @_;
74 $self->input_eml_cb($eml);
77 # import a single file handle of $name
78 # Subclass must define ->input_eml_cb and ->input_mbox_cb
80 my ($self, $ifmt, $fh, $name, @args) = @_;
82 my $buf = do { local $/; <$fh> } //
83 return $self->{lei}->child_error(0, <<"");
84 error reading $name: $!
86 # mutt pipes single RFC822 messages with a "From " line,
87 # but no Content-Length or "From " escaping.
88 # "git format-patch" also generates such files by default.
89 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
91 # a user may feed just a body: git diff | lei rediff -U9
92 if ($self->{-force_eml}) {
93 my $eml = PublicInbox::Eml->new($buf);
94 substr($buf, 0, 0) = "\n\n" if !$eml->{bdy};
96 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
98 # prepare_inputs already validated $ifmt
99 my $cb = PublicInbox::MboxReader->reads($ifmt) //
100 die "BUG: bad fmt=$ifmt";
101 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
105 # handles mboxrd endpoints described in Documentation/design_notes.txt
106 sub handle_http_input ($$@) {
107 my ($self, $url, @args) = @_;
108 my $lei = $self->{lei} or die 'BUG: {lei} missing';
109 my $curl_opt = delete $self->{"-curl-$url"} or
110 die("BUG: $url curl options not prepared");
111 my $uri = pop @$curl_opt;
112 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
113 push @$curl, '-s', @$curl_opt;
114 my $cmd = $curl->for_uri($lei, $uri);
115 $lei->qerr("# $cmd");
116 my ($fh, $pid) = popen_rd($cmd, undef, { 2 => $lei->{2} });
117 my $ar = PublicInbox::AutoReap->new($pid);
118 grep(/\A--compressed\z/, @$curl) or
119 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
120 eval { $self->input_fh('mboxrd', $fh, $url, @args) };
121 my @err = ($@ ? $@ : ());
123 push(@err, "\$?=$?") if $?;
124 $lei->child_error($?, "@$cmd failed: @err") if @err;
128 my ($self, $input, @args) = @_;
129 my $lei = $self->{lei};
130 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
132 if ($input =~ m!\Aimaps?://!i) {
133 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
136 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
137 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
140 } elsif ($input =~ m!\Ahttps?://!i) {
141 handle_http_input($self, $input, @args);
147 if ($input =~ s!\A([a-z0-9]+):!!i) {
150 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
152 } elsif (-f $input && $input =~ m{\A(?:.+)/(?:new|cur)/([^/]+)\z}) {
154 my $fl = PublicInbox::MdirReader::maildir_basename_flags($bn);
155 return if index($fl, 'T') >= 0;
156 return $self->pmdir_cb($input, $fl) if $self->can('pmdir_cb');
157 my $eml = eml_from_path($input) or return
158 $lei->qerr("# $input not readable");
159 my $kw = PublicInbox::MdirReader::flags2kw($fl);
160 $self->can('input_maildir_cb')->($input, $kw, $eml, $self);
163 my $devfd = $lei->path_to_fd($input) // return;
165 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
166 } elsif (-f $input && $ifmt eq 'eml') {
167 open my $fh, '<', $input or
168 return $lei->fail("open($input): $!");
169 $self->input_fh($ifmt, $fh, $input, @args);
171 my $m = $lei->{opt}->{'lock'} //
172 PublicInbox::MboxLock->defaults;
173 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
174 my $zsfx = PublicInbox::MboxReader::zsfx($input);
176 my $in = delete $mbl->{fh};
178 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
180 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
181 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
182 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
183 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
184 $input appears to be a maildir, not $ifmt
186 my $mdr = PublicInbox::MdirReader->new;
187 if (my $pmd = $self->{pmd}) {
188 $mdr->maildir_each_file($input,
189 $pmd->can('each_mdir_fn'),
192 $mdr->maildir_each_eml($input,
193 $self->can('input_maildir_cb'),
196 } elsif ($self->{missing_ok} && !-e $input) { # don't ->fail
197 if ($lei->{cmd} eq 'p2q') {
198 my $fp = [ qw(git format-patch --stdout -1), $input ];
199 my $rdr = { 2 => $lei->{2} };
200 my $fh = popen_rd($fp, undef, $rdr);
201 eval { $self->input_fh('eml', $fh, $input, @args) };
202 my @err = ($@ ? $@ : ());
203 close($fh) or push @err, "\$?=$?";
204 $lei->child_error($?, "@$fp failed: @err") if @err;
206 $self->folder_missing("$ifmt:$input");
209 $lei->fail("$ifmt_pfx$input unsupported (TODO)");
213 # subclasses should overrride this (see LeiRefreshMailSync)
214 sub folder_missing { die "BUG: ->folder_missing undefined for $_[0]" }
216 sub bad_http ($$;$) {
217 my ($lei, $url, $alt) = @_;
218 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
219 $lei->fail("E: <$url> not recognized, $x");
222 sub prepare_http_input ($$$) {
223 my ($self, $lei, $url) = @_;
225 require PublicInbox::MboxReader;
226 require PublicInbox::LeiCurl;
227 require IO::Uncompress::Gunzip;
228 $self->{curl} //= which('curl') or
229 return $lei->fail("curl missing for <$url>");
230 my $uri = URI->new($url);
231 my $path = $uri->path;
232 my %qf = $uri->query_form;
234 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
236 } elsif ($path =~ m!/raw\z!) {
237 push @curl_opt, '--compressed';
238 # convert search query to mboxrd request since they require POST
239 # this is only intended for PublicInbox::WWW, and will false-positive
240 # on many other search engines... oh well
241 } elsif (defined $qf{'q'}) {
243 $uri->query_form(\%qf);
244 push @curl_opt, '-d', '';
245 $$uri ne $url and $lei->qerr(<<"");
246 # <$url> rewritten to <$$uri> with HTTP POST
248 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
249 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
250 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
251 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
253 return bad_http($lei, $url, $$uri);
255 return bad_http($lei, $url);
257 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
260 sub prepare_inputs { # returns undef on error
261 my ($self, $lei, $inputs) = @_;
262 my $in_fmt = $lei->{opt}->{'in-format'};
263 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
264 my $may_sync = $sync || $self->{-mail_sync};
265 if ($lei->{opt}->{stdin}) {
267 $lei->fail("--stdin and @$inputs do not mix");
268 check_input_format($lei) or return;
269 push @$inputs, '/dev/stdin';
270 push @{$sync->{no}}, '/dev/stdin' if $sync;
272 my $net = $lei->{net}; # NetWriter may be created by l2m
274 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
275 for my $input (@$inputs) {
276 my $input_path = $input;
277 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
278 require PublicInbox::NetReader;
279 $net //= PublicInbox::NetReader->new;
280 $net->add_url($input, $self->{-ls_ok});
281 push @{$sync->{ok}}, $input if $sync;
282 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
283 # TODO: how would we detect r/w JMAP?
284 push @{$sync->{no}}, $input if $sync;
285 prepare_http_input($self, $lei, $input_path) or return;
286 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
288 if (($in_fmt // $ifmt) ne $ifmt) {
289 return $lei->fail(<<"");
290 --in-format=$in_fmt and `$ifmt:' conflict
293 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
294 push @{$sync->{ok}}, $input if $sync;
296 push @{$sync->{no}}, $input if $sync;
298 my $devfd = $lei->path_to_fd($input_path) // return;
299 if ($devfd >= 0 || (-f $input_path || -p _)) {
300 require PublicInbox::MboxLock;
301 require PublicInbox::MboxReader;
302 PublicInbox::MboxReader->reads($ifmt) or return
303 $lei->fail("$ifmt not supported");
304 } elsif (-d $input_path) {
305 $ifmt eq 'maildir' or return
306 $lei->fail("$ifmt not supported");
307 $may_sync and $input = 'maildir:'.
308 $lei->abs_path($input_path);
310 } elsif ($self->{missing_ok} && !-e _) {
311 # for "lei rm-watch" on missing Maildir
312 $may_sync and $input = 'maildir:'.
313 $lei->abs_path($input_path);
315 my $m = "Unable to handle $input";
316 $input =~ /\A(?:L|kw):/ and
317 $m .= ", did you mean +$input?";
318 return $lei->fail($m);
320 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
321 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
322 $input is `eml', not --in-format=$in_fmt
324 push @{$sync->{no}}, $input if $sync;
325 } elsif (-f $input && $input =~ m{\A(.+)/(new|cur)/([^/]+)\z}) {
326 # single file in a Maildir
327 my ($mdir, $nc, $bn) = ($1, $2, $3);
328 my $other = $mdir . ($nc eq 'new' ? '/cur' : '/new');
329 return $lei->fail(<<EOM) if !-d $other;
330 No `$other' directory for `$input'
332 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
333 $input is `eml', not --in-format=$in_fmt
336 $input = $lei->abs_path($mdir) . "/$nc/$bn";
337 push @{$sync->{ok}}, $input if $sync;
339 require PublicInbox::MdirReader;
341 my $devfd = $lei->path_to_fd($input) // return;
342 if ($devfd >= 0 || -f $input || -p _) {
343 push @{$sync->{no}}, $input if $sync;
345 } elsif (-d "$input/new" && -d "$input/cur") {
348 $lei->abs_path($input);
349 push @{$sync->{ok}}, $input if $sync;
352 } elsif ($self->{missing_ok} && !-e $input) {
353 if ($lei->{cmd} eq 'p2q') {
354 # will run "git format-patch"
355 } elsif ($may_sync) { # for lei rm-watch
357 $lei->abs_path($input);
360 return $lei->fail("Unable to handle $input")
364 if (@f) { check_input_format($lei, \@f) or return }
365 if ($sync && $sync->{no}) {
366 return $lei->fail(<<"") if !$sync->{ok};
367 --mail-sync specified but no inputs support it
369 # non-fatal if some inputs support support sync
370 warn("# --mail-sync will only be used for @{$sync->{ok}}\n");
371 warn("# --mail-sync is not supported for: @{$sync->{no}}\n");
374 $net->{-can_die} = 1;
375 if (my $err = $net->errors($lei)) {
376 return $lei->fail($err);
378 $net->{quiet} = $lei->{opt}->{quiet};
379 require PublicInbox::LeiAuth;
380 $lei->{auth} //= PublicInbox::LeiAuth->new;
381 $lei->{net} //= $net;
384 require PublicInbox::MdirReader;
385 if ($self->can('pmdir_cb')) {
386 require PublicInbox::LeiPmdir;
387 $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
390 # start watching Maildirs ASAP
391 if ($may_sync && $lei->{sto}) {
392 grep(!m!\Amaildir:/!i, @md) and die "BUG: @md (no pfx)";
393 $lei->lms(1)->lms_write_prepare->add_folders(@md);
394 $lei->refresh_watches;
397 $self->{inputs} = $inputs;
403 for my $input (@{$self->{inputs}}) {
404 eval { $self->input_path_url($input) };
409 # always commit first, even on error partial work is acceptable for
410 # lei <import|tag|convert>
411 my $wait = $self->{lei}->{sto}->wq_do('done') if $self->{lei}->{sto};
412 $self->{lei}->fail($err) if $err;
415 sub input_only_atfork_child {
417 my $lei = $self->{lei};
418 $lei->_lei_atfork_child;
419 PublicInbox::IPC::ipc_atfork_child($self);
420 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
424 # alias this as "net_merge_all_done" to use as an LeiAuth callback
425 sub input_only_net_merge_all_done {
427 $self->wq_io_do('process_inputs');
431 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
432 # for update_xvmd -> update_vmd
433 # returns something like { "+L" => [ @Labels ], ... }
434 sub vmd_mod_extract {
439 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
440 my ($op, $pfx, $val) = ($1, $2, $3);
441 if (my $err = $ERR{$pfx}->($val)) {
442 push @{$vmd_mod->{err}}, $err;
443 } else { # set "+kw", "+L", "-L", "-kw"
444 push @{$vmd_mod->{$op.$pfx}}, $val;