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 # import a single file handle of $name
68 # Subclass must define ->input_eml_cb and ->input_mbox_cb
70 my ($self, $ifmt, $fh, $name, @args) = @_;
72 my $buf = do { local $/; <$fh> } //
73 return $self->{lei}->child_error(0, <<"");
74 error reading $name: $!
76 # mutt pipes single RFC822 messages with a "From " line,
77 # but no Content-Length or "From " escaping.
78 # "git format-patch" also generates such files by default.
79 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
81 # a user may feed just a body: git diff | lei rediff -U9
82 if ($self->{-force_eml}) {
83 my $eml = PublicInbox::Eml->new($buf);
84 substr($buf, 0, 0) = "\n\n" if !$eml->{bdy};
86 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
88 # prepare_inputs already validated $ifmt
89 my $cb = PublicInbox::MboxReader->reads($ifmt) //
90 die "BUG: bad fmt=$ifmt";
91 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
95 # handles mboxrd endpoints described in Documentation/design_notes.txt
96 sub handle_http_input ($$@) {
97 my ($self, $url, @args) = @_;
98 my $lei = $self->{lei} or die 'BUG: {lei} missing';
99 my $curl_opt = delete $self->{"-curl-$url"} or
100 die("BUG: $url curl options not prepared");
101 my $uri = pop @$curl_opt;
102 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
103 push @$curl, '-s', @$curl_opt;
104 my $cmd = $curl->for_uri($lei, $uri);
105 $lei->qerr("# $cmd");
106 my ($fh, $pid) = popen_rd($cmd, undef, { 2 => $lei->{2} });
107 my $ar = PublicInbox::AutoReap->new($pid);
108 grep(/\A--compressed\z/, @$curl) or
109 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
110 eval { $self->input_fh('mboxrd', $fh, $url, @args) };
114 $lei->child_error($?, "@$cmd failed".$err ? " $err" : '');
118 my ($self, $input, @args) = @_;
119 my $lei = $self->{lei};
120 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
122 if ($input =~ m!\Aimaps?://!i) {
123 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
126 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
127 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
130 } elsif ($input =~ m!\Ahttps?://!i) {
131 handle_http_input($self, $input, @args);
137 if ($input =~ s!\A([a-z0-9]+):!!i) {
140 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
142 } elsif (-f $input && $input =~ m{\A(?:.+)/(?:new|cur)/([^/]+)\z}) {
144 my $fl = PublicInbox::MdirReader::maildir_basename_flags($bn);
145 return if index($fl, 'T') >= 0;
146 return $self->pmdir_cb($input, $fl) if $self->can('pmdir_cb');
147 my $eml = eml_from_path($input) or return
148 $lei->qerr("# $input not readable");
149 my $kw = PublicInbox::MdirReader::flags2kw($fl);
150 $self->can('input_maildir_cb')->($input, $kw, $eml, $self);
153 my $devfd = $lei->path_to_fd($input) // return;
155 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
156 } elsif (-f $input && $ifmt eq 'eml') {
157 open my $fh, '<', $input or
158 return $lei->fail("open($input): $!");
159 $self->input_fh($ifmt, $fh, $input, @args);
161 my $m = $lei->{opt}->{'lock'} //
162 PublicInbox::MboxLock->defaults;
163 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
164 my $zsfx = PublicInbox::MboxReader::zsfx($input);
166 my $in = delete $mbl->{fh};
168 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
170 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
171 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
172 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
173 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
174 $input appears to be a maildir, not $ifmt
176 my $mdr = PublicInbox::MdirReader->new;
177 if (my $pmd = $self->{pmd}) {
178 $mdr->maildir_each_file($input,
179 $pmd->can('each_mdir_fn'),
182 $mdr->maildir_each_eml($input,
183 $self->can('input_maildir_cb'),
186 } elsif ($self->{missing_ok} && !-e $input) { # don't ->fail
187 $self->folder_missing("$ifmt:$input");
189 $lei->fail("$ifmt_pfx$input unsupported (TODO)");
193 # subclasses should overrride this (see LeiRefreshMailSync)
194 sub folder_missing { die "BUG: ->folder_missing undefined for $_[0]" }
196 sub bad_http ($$;$) {
197 my ($lei, $url, $alt) = @_;
198 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
199 $lei->fail("E: <$url> not recognized, $x");
202 sub prepare_http_input ($$$) {
203 my ($self, $lei, $url) = @_;
205 require PublicInbox::MboxReader;
206 require PublicInbox::LeiCurl;
207 require IO::Uncompress::Gunzip;
208 $self->{curl} //= which('curl') or
209 return $lei->fail("curl missing for <$url>");
210 my $uri = URI->new($url);
211 my $path = $uri->path;
212 my %qf = $uri->query_form;
214 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
216 } elsif ($path =~ m!/raw\z!) {
217 push @curl_opt, '--compressed';
218 # convert search query to mboxrd request since they require POST
219 # this is only intended for PublicInbox::WWW, and will false-positive
220 # on many other search engines... oh well
221 } elsif (defined $qf{'q'}) {
223 $uri->query_form(\%qf);
224 push @curl_opt, '-d', '';
225 $$uri ne $url and $lei->qerr(<<"");
226 # <$url> rewritten to <$$uri> with HTTP POST
228 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
229 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
230 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
231 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
233 return bad_http($lei, $url, $$uri);
235 return bad_http($lei, $url);
237 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
240 sub prepare_inputs { # returns undef on error
241 my ($self, $lei, $inputs) = @_;
242 my $in_fmt = $lei->{opt}->{'in-format'};
243 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
244 my $may_sync = $sync || $self->{-mail_sync};
245 if ($lei->{opt}->{stdin}) {
247 $lei->fail("--stdin and @$inputs do not mix");
248 check_input_format($lei) or return;
249 push @$inputs, '/dev/stdin';
250 push @{$sync->{no}}, '/dev/stdin' if $sync;
252 my $net = $lei->{net}; # NetWriter may be created by l2m
254 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
255 for my $input (@$inputs) {
256 my $input_path = $input;
257 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
258 require PublicInbox::NetReader;
259 $net //= PublicInbox::NetReader->new;
260 $net->add_url($input, $self->{-ls_ok});
261 push @{$sync->{ok}}, $input if $sync;
262 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
263 # TODO: how would we detect r/w JMAP?
264 push @{$sync->{no}}, $input if $sync;
265 prepare_http_input($self, $lei, $input_path) or return;
266 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
268 if (($in_fmt // $ifmt) ne $ifmt) {
269 return $lei->fail(<<"");
270 --in-format=$in_fmt and `$ifmt:' conflict
273 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
274 push @{$sync->{ok}}, $input if $sync;
276 push @{$sync->{no}}, $input if $sync;
278 my $devfd = $lei->path_to_fd($input_path) // return;
279 if ($devfd >= 0 || (-f $input_path || -p _)) {
280 require PublicInbox::MboxLock;
281 require PublicInbox::MboxReader;
282 PublicInbox::MboxReader->reads($ifmt) or return
283 $lei->fail("$ifmt not supported");
284 } elsif (-d $input_path) {
285 $ifmt eq 'maildir' or return
286 $lei->fail("$ifmt not supported");
287 $may_sync and $input = 'maildir:'.
288 $lei->abs_path($input_path);
290 } elsif ($self->{missing_ok} && !-e _) {
291 # for "lei rm-watch" on missing Maildir
292 $may_sync and $input = 'maildir:'.
293 $lei->abs_path($input_path);
295 my $m = "Unable to handle $input";
296 $input =~ /\A(?:L|kw):/ and
297 $m .= ", did you mean +$input?";
298 return $lei->fail($m);
300 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
301 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
302 $input is `eml', not --in-format=$in_fmt
304 push @{$sync->{no}}, $input if $sync;
305 } elsif (-f $input && $input =~ m{\A(.+)/(new|cur)/([^/]+)\z}) {
306 # single file in a Maildir
307 my ($mdir, $nc, $bn) = ($1, $2, $3);
308 my $other = $mdir . ($nc eq 'new' ? '/cur' : '/new');
309 return $lei->fail(<<EOM) if !-d $other;
310 No `$other' directory for `$input'
312 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
313 $input is `eml', not --in-format=$in_fmt
316 $input = $lei->abs_path($mdir) . "/$nc/$bn";
317 push @{$sync->{ok}}, $input if $sync;
319 require PublicInbox::MdirReader;
321 my $devfd = $lei->path_to_fd($input) // return;
322 if ($devfd >= 0 || -f $input || -p _) {
323 push @{$sync->{no}}, $input if $sync;
325 } elsif (-d "$input/new" && -d "$input/cur") {
328 $lei->abs_path($input);
329 push @{$sync->{ok}}, $input if $sync;
332 } elsif ($self->{missing_ok} && !-e $input) {
334 $may_sync and $input = 'maildir:'.
335 $lei->abs_path($input);
337 return $lei->fail("Unable to handle $input")
341 if (@f) { check_input_format($lei, \@f) or return }
342 if ($sync && $sync->{no}) {
343 return $lei->fail(<<"") if !$sync->{ok};
344 --mail-sync specified but no inputs support it
346 # non-fatal if some inputs support support sync
347 warn("# --mail-sync will only be used for @{$sync->{ok}}\n");
348 warn("# --mail-sync is not supported for: @{$sync->{no}}\n");
351 $net->{-can_die} = 1;
352 if (my $err = $net->errors($lei)) {
353 return $lei->fail($err);
355 $net->{quiet} = $lei->{opt}->{quiet};
356 require PublicInbox::LeiAuth;
357 $lei->{auth} //= PublicInbox::LeiAuth->new;
358 $lei->{net} //= $net;
361 require PublicInbox::MdirReader;
362 if ($self->can('pmdir_cb')) {
363 require PublicInbox::LeiPmdir;
364 $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
367 # start watching Maildirs ASAP
368 if ($may_sync && $lei->{sto}) {
369 grep(!m!\Amaildir:/!i, @md) and die "BUG: @md (no pfx)";
370 $lei->lms(1)->lms_write_prepare->add_folders(@md);
371 $lei->refresh_watches;
374 $self->{inputs} = $inputs;
380 for my $input (@{$self->{inputs}}) {
381 eval { $self->input_path_url($input) };
386 # always commit first, even on error partial work is acceptable for
387 # lei <import|tag|convert>
388 my $wait = $self->{lei}->{sto}->wq_do('done') if $self->{lei}->{sto};
389 $self->{lei}->fail($err) if $err;
392 sub input_only_atfork_child {
394 my $lei = $self->{lei};
395 $lei->_lei_atfork_child;
396 PublicInbox::IPC::ipc_atfork_child($self);
397 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
401 # alias this as "net_merge_all_done" to use as an LeiAuth callback
402 sub input_only_net_merge_all_done {
404 $self->wq_io_do('process_inputs');
408 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
409 # for update_xvmd -> update_vmd
410 # returns something like { "+L" => [ @Labels ], ... }
411 sub vmd_mod_extract {
416 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
417 my ($op, $pfx, $val) = ($1, $2, $3);
418 if (my $err = $ERR{$pfx}->($val)) {
419 push @{$vmd_mod->{err}}, $err;
420 } else { # set "+kw", "+L", "-L", "-kw"
421 push @{$vmd_mod->{$op.$pfx}}, $val;