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);
13 # https://www.iana.org/assignments/imap-jmap-keywords/imap-jmap-keywords.xhtml
14 our @KW = (qw(seen answered flagged draft), # widely-compatible
15 qw(forwarded), # IMAP + Maildir
16 qw(phishing junk notjunk)); # rarely supported
18 # note: RFC 8621 states "Users may add arbitrary keywords to an Email",
19 # but is it good idea? Stick to the system and reserved ones, for now.
20 # The widely-compatible ones map to IMAP system flags, Maildir flags
21 # and mbox Status/X-Status headers.
22 my %KW = map { $_ => 1 } @KW;
23 my $L_MAX = 244; # Xapian term limit - length('L')
25 # RFC 8621, sec 2 (Mailboxes) a "label" for us is a JMAP Mailbox "name"
26 # "Servers MAY reject names that violate server policy"
30 length($label) >= $L_MAX and
31 return "`$label' too long (must be <= $L_MAX)";
32 $label =~ m{\A[a-z0-9_](?:[a-z0-9_\-\./\@,]*[a-z0-9])?\z}i ?
33 undef : "`$label' is invalid";
37 $KW{$kw} ? undef : <<EOM;
38 `$kw' is not one of: `seen', `flagged', `answered', `draft'
39 `junk', `notjunk', `phishing' or `forwarded'
44 sub check_input_format ($;$) {
45 my ($lei, $files) = @_;
46 my $opt_key = 'in-format';
47 my $fmt = $lei->{opt}->{$opt_key};
49 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
50 return $lei->fail("--$opt_key unset for $err");
52 return 1 if $fmt eq 'eml';
53 require PublicInbox::MboxLock if $files;
54 require PublicInbox::MboxReader;
55 PublicInbox::MboxReader->reads($fmt) or
56 return $lei->fail("--$opt_key=$fmt unrecognized");
60 # import a single file handle of $name
61 # Subclass must define ->input_eml_cb and ->input_mbox_cb
63 my ($self, $ifmt, $fh, $name, @args) = @_;
65 my $buf = do { local $/; <$fh> } //
66 return $self->{lei}->child_error(0, <<"");
67 error reading $name: $!
69 # mutt pipes single RFC822 messages with a "From " line,
70 # but no Content-Length or "From " escaping.
71 # "git format-patch" also generates such files by default.
72 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
74 # a user may feed just a body: git diff | lei rediff -U9
75 if ($self->{-force_eml}) {
76 my $eml = PublicInbox::Eml->new($buf);
77 substr($buf, 0, 0) = "\n\n" if !$eml->{bdy};
79 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
81 # prepare_inputs already validated $ifmt
82 my $cb = PublicInbox::MboxReader->reads($ifmt) //
83 die "BUG: bad fmt=$ifmt";
84 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
88 # handles mboxrd endpoints described in Documentation/design_notes.txt
89 sub handle_http_input ($$@) {
90 my ($self, $url, @args) = @_;
91 my $lei = $self->{lei} or die 'BUG: {lei} missing';
92 my $curl_opt = delete $self->{"-curl-$url"} or
93 die("BUG: $url curl options not prepared");
94 my $uri = pop @$curl_opt;
95 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
96 push @$curl, '-s', @$curl_opt;
97 my $cmd = $curl->for_uri($lei, $uri);
99 my $rdr = { 2 => $lei->{2}, pgid => 0 };
100 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
101 grep(/\A--compressed\z/, @$curl) or
102 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
103 eval { $self->input_fh('mboxrd', $fh, $url, @args) };
107 $lei->child_error($?, "@$cmd failed".$err ? " $err" : '');
111 my ($self, $input, @args) = @_;
112 my $lei = $self->{lei};
113 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
115 if ($input =~ m!\Aimaps?://!i) {
116 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
119 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
120 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
123 } elsif ($input =~ m!\Ahttps?://!i) {
124 handle_http_input($self, $input, @args);
130 if ($input =~ s!\A([a-z0-9]+):!!i) {
133 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
135 } elsif (-f $input && $input =~ m{\A(?:.+)/(?:new|cur)/([^/]+)\z}) {
137 my $fl = PublicInbox::MdirReader::maildir_basename_flags($bn);
138 return if index($fl, 'T') >= 0;
139 return $self->pmdir_cb($input, $fl) if $self->can('pmdir_cb');
140 my $eml = eml_from_path($input) or return
141 $lei->qerr("# $input not readable");
142 my $kw = PublicInbox::MdirReader::flags2kw($fl);
143 $self->can('input_maildir_cb')->($input, $kw, $eml, $self);
146 my $devfd = $lei->path_to_fd($input) // return;
148 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
149 } elsif (-f $input && $ifmt eq 'eml') {
150 open my $fh, '<', $input or
151 return $lei->fail("open($input): $!");
152 $self->input_fh($ifmt, $fh, $input, @args);
154 my $m = $lei->{opt}->{'lock'} //
155 PublicInbox::MboxLock->defaults;
156 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
157 my $zsfx = PublicInbox::MboxReader::zsfx($input);
159 my $in = delete $mbl->{fh};
161 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
163 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
164 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
165 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
166 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
167 $input appears to be a maildir, not $ifmt
169 my $mdr = PublicInbox::MdirReader->new;
170 if (my $pmd = $self->{pmd}) {
171 $mdr->maildir_each_file($input,
172 $pmd->can('each_mdir_fn'),
175 $mdr->maildir_each_eml($input,
176 $self->can('input_maildir_cb'),
179 } elsif ($self->{missing_ok} && !-e $input) { # don't ->fail
180 $self->folder_missing("$ifmt:$input");
182 $lei->fail("$ifmt_pfx$input unsupported (TODO)");
186 # subclasses should overrride this (see LeiRefreshMailSync)
187 sub folder_missing { die "BUG: ->folder_missing undefined for $_[0]" }
189 sub bad_http ($$;$) {
190 my ($lei, $url, $alt) = @_;
191 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
192 $lei->fail("E: <$url> not recognized, $x");
195 sub prepare_http_input ($$$) {
196 my ($self, $lei, $url) = @_;
198 require PublicInbox::MboxReader;
199 require PublicInbox::LeiCurl;
200 require IO::Uncompress::Gunzip;
201 $self->{curl} //= which('curl') or
202 return $lei->fail("curl missing for <$url>");
203 my $uri = URI->new($url);
204 my $path = $uri->path;
205 my %qf = $uri->query_form;
207 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
209 } elsif ($path =~ m!/raw\z!) {
210 push @curl_opt, '--compressed';
211 # convert search query to mboxrd request since they require POST
212 # this is only intended for PublicInbox::WWW, and will false-positive
213 # on many other search engines... oh well
214 } elsif (defined $qf{'q'}) {
216 $uri->query_form(\%qf);
217 push @curl_opt, '-d', '';
218 $$uri ne $url and $lei->qerr(<<"");
219 # <$url> rewritten to <$$uri> with HTTP POST
221 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
222 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
223 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
224 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
226 return bad_http($lei, $url, $$uri);
228 return bad_http($lei, $url);
230 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
233 sub prepare_inputs { # returns undef on error
234 my ($self, $lei, $inputs) = @_;
235 my $in_fmt = $lei->{opt}->{'in-format'};
236 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
237 my $may_sync = $sync || $self->{-mail_sync};
238 if ($lei->{opt}->{stdin}) {
240 $lei->fail("--stdin and @$inputs do not mix");
241 check_input_format($lei) or return;
242 push @$inputs, '/dev/stdin';
243 push @{$sync->{no}}, '/dev/stdin' if $sync;
245 my $net = $lei->{net}; # NetWriter may be created by l2m
247 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
248 for my $input (@$inputs) {
249 my $input_path = $input;
250 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
251 require PublicInbox::NetReader;
252 $net //= PublicInbox::NetReader->new;
253 $net->add_url($input, $self->{-ls_ok});
254 push @{$sync->{ok}}, $input if $sync;
255 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
256 # TODO: how would we detect r/w JMAP?
257 push @{$sync->{no}}, $input if $sync;
258 prepare_http_input($self, $lei, $input_path) or return;
259 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
261 if (($in_fmt // $ifmt) ne $ifmt) {
262 return $lei->fail(<<"");
263 --in-format=$in_fmt and `$ifmt:' conflict
266 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
267 push @{$sync->{ok}}, $input if $sync;
269 push @{$sync->{no}}, $input if $sync;
271 my $devfd = $lei->path_to_fd($input_path) // return;
272 if ($devfd >= 0 || (-f $input_path || -p _)) {
273 require PublicInbox::MboxLock;
274 require PublicInbox::MboxReader;
275 PublicInbox::MboxReader->reads($ifmt) or return
276 $lei->fail("$ifmt not supported");
277 } elsif (-d $input_path) {
278 $ifmt eq 'maildir' or return
279 $lei->fail("$ifmt not supported");
280 $may_sync and $input = 'maildir:'.
281 $lei->abs_path($input_path);
283 } elsif ($self->{missing_ok} && !-e _) {
284 # for "lei rm-watch" on missing Maildir
285 $may_sync and $input = 'maildir:'.
286 $lei->abs_path($input_path);
288 my $m = "Unable to handle $input";
289 $input =~ /\A(?:L|kw):/ and
290 $m .= ", did you mean +$input?";
291 return $lei->fail($m);
293 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
294 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
295 $input is `eml', not --in-format=$in_fmt
297 push @{$sync->{no}}, $input if $sync;
298 } elsif (-f $input && $input =~ m{\A(.+)/(new|cur)/([^/]+)\z}) {
299 # single file in a Maildir
300 my ($mdir, $nc, $bn) = ($1, $2, $3);
301 my $other = $mdir . ($nc eq 'new' ? '/cur' : '/new');
302 return $lei->fail(<<EOM) if !-d $other;
303 No `$other' directory for `$input'
305 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
306 $input is `eml', not --in-format=$in_fmt
309 $input = $lei->abs_path($mdir) . "/$nc/$bn";
310 push @{$sync->{ok}}, $input if $sync;
312 require PublicInbox::MdirReader;
314 my $devfd = $lei->path_to_fd($input) // return;
315 if ($devfd >= 0 || -f $input || -p _) {
316 push @{$sync->{no}}, $input if $sync;
318 } elsif (-d "$input/new" && -d "$input/cur") {
321 $lei->abs_path($input);
322 push @{$sync->{ok}}, $input if $sync;
325 } elsif ($self->{missing_ok} && !-e $input) {
327 $may_sync and $input = 'maildir:'.
328 $lei->abs_path($input);
330 return $lei->fail("Unable to handle $input")
334 if (@f) { check_input_format($lei, \@f) or return }
335 if ($sync && $sync->{no}) {
336 return $lei->fail(<<"") if !$sync->{ok};
337 --mail-sync specified but no inputs support it
339 # non-fatal if some inputs support support sync
340 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
341 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
344 $net->{-can_die} = 1;
345 if (my $err = $net->errors($lei)) {
346 return $lei->fail($err);
348 $net->{quiet} = $lei->{opt}->{quiet};
349 require PublicInbox::LeiAuth;
350 $lei->{auth} //= PublicInbox::LeiAuth->new;
351 $lei->{net} //= $net;
354 require PublicInbox::MdirReader;
355 if ($self->can('pmdir_cb')) {
356 require PublicInbox::LeiPmdir;
357 $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
360 # start watching Maildirs ASAP
361 if ($may_sync && $lei->{sto}) {
362 grep(!m!\Amaildir:/!i, @md) and die "BUG: @md (no pfx)";
363 $lei->lms(1)->lms_write_prepare->add_folders(@md);
364 $lei->refresh_watches;
367 $self->{inputs} = $inputs;
373 for my $input (@{$self->{inputs}}) {
374 eval { $self->input_path_url($input) };
379 # always commit first, even on error partial work is acceptable for
380 # lei <import|tag|convert>
381 my $wait = $self->{lei}->{sto}->wq_do('done') if $self->{lei}->{sto};
382 $self->{lei}->fail($err) if $err;
385 sub input_only_atfork_child {
387 my $lei = $self->{lei};
388 $lei->_lei_atfork_child;
389 PublicInbox::IPC::ipc_atfork_child($self);
390 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
394 # alias this as "net_merge_all_done" to use as an LeiAuth callback
395 sub input_only_net_merge_all_done {
397 $self->wq_io_do('process_inputs');
401 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
402 # for update_xvmd -> update_vmd
403 # returns something like { "+L" => [ @Labels ], ... }
404 sub vmd_mod_extract {
409 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
410 my ($op, $pfx, $val) = ($1, $2, $3);
411 if (my $err = $ERR{$pfx}->($val)) {
412 push @{$vmd_mod->{err}}, $err;
413 } else { # set "+kw", "+L", "-L", "-kw"
414 push @{$vmd_mod->{$op.$pfx}}, $val;