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 sub input_mbox_cb { # base MboxReader callback
61 my ($eml, $self) = @_;
62 $eml->header_set($_) for (qw(Status X-Status));
63 $self->input_eml_cb($eml);
66 # import a single file handle of $name
67 # Subclass must define ->input_eml_cb and ->input_mbox_cb
69 my ($self, $ifmt, $fh, $name, @args) = @_;
71 my $buf = do { local $/; <$fh> } //
72 return $self->{lei}->child_error(0, <<"");
73 error reading $name: $!
75 # mutt pipes single RFC822 messages with a "From " line,
76 # but no Content-Length or "From " escaping.
77 # "git format-patch" also generates such files by default.
78 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
80 # a user may feed just a body: git diff | lei rediff -U9
81 if ($self->{-force_eml}) {
82 my $eml = PublicInbox::Eml->new($buf);
83 substr($buf, 0, 0) = "\n\n" if !$eml->{bdy};
85 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
87 # prepare_inputs already validated $ifmt
88 my $cb = PublicInbox::MboxReader->reads($ifmt) //
89 die "BUG: bad fmt=$ifmt";
90 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
94 # handles mboxrd endpoints described in Documentation/design_notes.txt
95 sub handle_http_input ($$@) {
96 my ($self, $url, @args) = @_;
97 my $lei = $self->{lei} or die 'BUG: {lei} missing';
98 my $curl_opt = delete $self->{"-curl-$url"} or
99 die("BUG: $url curl options not prepared");
100 my $uri = pop @$curl_opt;
101 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
102 push @$curl, '-s', @$curl_opt;
103 my $cmd = $curl->for_uri($lei, $uri);
104 $lei->qerr("# $cmd");
105 my $rdr = { 2 => $lei->{2}, pgid => 0 };
106 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
107 grep(/\A--compressed\z/, @$curl) or
108 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
109 eval { $self->input_fh('mboxrd', $fh, $url, @args) };
113 $lei->child_error($?, "@$cmd failed".$err ? " $err" : '');
117 my ($self, $input, @args) = @_;
118 my $lei = $self->{lei};
119 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
121 if ($input =~ m!\Aimaps?://!i) {
122 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
125 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
126 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
129 } elsif ($input =~ m!\Ahttps?://!i) {
130 handle_http_input($self, $input, @args);
136 if ($input =~ s!\A([a-z0-9]+):!!i) {
139 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
141 } elsif (-f $input && $input =~ m{\A(?:.+)/(?:new|cur)/([^/]+)\z}) {
143 my $fl = PublicInbox::MdirReader::maildir_basename_flags($bn);
144 return if index($fl, 'T') >= 0;
145 return $self->pmdir_cb($input, $fl) if $self->can('pmdir_cb');
146 my $eml = eml_from_path($input) or return
147 $lei->qerr("# $input not readable");
148 my $kw = PublicInbox::MdirReader::flags2kw($fl);
149 $self->can('input_maildir_cb')->($input, $kw, $eml, $self);
152 my $devfd = $lei->path_to_fd($input) // return;
154 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
155 } elsif (-f $input && $ifmt eq 'eml') {
156 open my $fh, '<', $input or
157 return $lei->fail("open($input): $!");
158 $self->input_fh($ifmt, $fh, $input, @args);
160 my $m = $lei->{opt}->{'lock'} //
161 PublicInbox::MboxLock->defaults;
162 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
163 my $zsfx = PublicInbox::MboxReader::zsfx($input);
165 my $in = delete $mbl->{fh};
167 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
169 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
170 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
171 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
172 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
173 $input appears to be a maildir, not $ifmt
175 my $mdr = PublicInbox::MdirReader->new;
176 if (my $pmd = $self->{pmd}) {
177 $mdr->maildir_each_file($input,
178 $pmd->can('each_mdir_fn'),
181 $mdr->maildir_each_eml($input,
182 $self->can('input_maildir_cb'),
185 } elsif ($self->{missing_ok} && !-e $input) { # don't ->fail
186 $self->folder_missing("$ifmt:$input");
188 $lei->fail("$ifmt_pfx$input unsupported (TODO)");
192 # subclasses should overrride this (see LeiRefreshMailSync)
193 sub folder_missing { die "BUG: ->folder_missing undefined for $_[0]" }
195 sub bad_http ($$;$) {
196 my ($lei, $url, $alt) = @_;
197 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
198 $lei->fail("E: <$url> not recognized, $x");
201 sub prepare_http_input ($$$) {
202 my ($self, $lei, $url) = @_;
204 require PublicInbox::MboxReader;
205 require PublicInbox::LeiCurl;
206 require IO::Uncompress::Gunzip;
207 $self->{curl} //= which('curl') or
208 return $lei->fail("curl missing for <$url>");
209 my $uri = URI->new($url);
210 my $path = $uri->path;
211 my %qf = $uri->query_form;
213 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
215 } elsif ($path =~ m!/raw\z!) {
216 push @curl_opt, '--compressed';
217 # convert search query to mboxrd request since they require POST
218 # this is only intended for PublicInbox::WWW, and will false-positive
219 # on many other search engines... oh well
220 } elsif (defined $qf{'q'}) {
222 $uri->query_form(\%qf);
223 push @curl_opt, '-d', '';
224 $$uri ne $url and $lei->qerr(<<"");
225 # <$url> rewritten to <$$uri> with HTTP POST
227 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
228 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
229 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
230 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
232 return bad_http($lei, $url, $$uri);
234 return bad_http($lei, $url);
236 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
239 sub prepare_inputs { # returns undef on error
240 my ($self, $lei, $inputs) = @_;
241 my $in_fmt = $lei->{opt}->{'in-format'};
242 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
243 my $may_sync = $sync || $self->{-mail_sync};
244 if ($lei->{opt}->{stdin}) {
246 $lei->fail("--stdin and @$inputs do not mix");
247 check_input_format($lei) or return;
248 push @$inputs, '/dev/stdin';
249 push @{$sync->{no}}, '/dev/stdin' if $sync;
251 my $net = $lei->{net}; # NetWriter may be created by l2m
253 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
254 for my $input (@$inputs) {
255 my $input_path = $input;
256 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
257 require PublicInbox::NetReader;
258 $net //= PublicInbox::NetReader->new;
259 $net->add_url($input, $self->{-ls_ok});
260 push @{$sync->{ok}}, $input if $sync;
261 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
262 # TODO: how would we detect r/w JMAP?
263 push @{$sync->{no}}, $input if $sync;
264 prepare_http_input($self, $lei, $input_path) or return;
265 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
267 if (($in_fmt // $ifmt) ne $ifmt) {
268 return $lei->fail(<<"");
269 --in-format=$in_fmt and `$ifmt:' conflict
272 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
273 push @{$sync->{ok}}, $input if $sync;
275 push @{$sync->{no}}, $input if $sync;
277 my $devfd = $lei->path_to_fd($input_path) // return;
278 if ($devfd >= 0 || (-f $input_path || -p _)) {
279 require PublicInbox::MboxLock;
280 require PublicInbox::MboxReader;
281 PublicInbox::MboxReader->reads($ifmt) or return
282 $lei->fail("$ifmt not supported");
283 } elsif (-d $input_path) {
284 $ifmt eq 'maildir' or return
285 $lei->fail("$ifmt not supported");
286 $may_sync and $input = 'maildir:'.
287 $lei->abs_path($input_path);
289 } elsif ($self->{missing_ok} && !-e _) {
290 # for "lei rm-watch" on missing Maildir
291 $may_sync and $input = 'maildir:'.
292 $lei->abs_path($input_path);
294 my $m = "Unable to handle $input";
295 $input =~ /\A(?:L|kw):/ and
296 $m .= ", did you mean +$input?";
297 return $lei->fail($m);
299 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
300 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
301 $input is `eml', not --in-format=$in_fmt
303 push @{$sync->{no}}, $input if $sync;
304 } elsif (-f $input && $input =~ m{\A(.+)/(new|cur)/([^/]+)\z}) {
305 # single file in a Maildir
306 my ($mdir, $nc, $bn) = ($1, $2, $3);
307 my $other = $mdir . ($nc eq 'new' ? '/cur' : '/new');
308 return $lei->fail(<<EOM) if !-d $other;
309 No `$other' directory for `$input'
311 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
312 $input is `eml', not --in-format=$in_fmt
315 $input = $lei->abs_path($mdir) . "/$nc/$bn";
316 push @{$sync->{ok}}, $input if $sync;
318 require PublicInbox::MdirReader;
320 my $devfd = $lei->path_to_fd($input) // return;
321 if ($devfd >= 0 || -f $input || -p _) {
322 push @{$sync->{no}}, $input if $sync;
324 } elsif (-d "$input/new" && -d "$input/cur") {
327 $lei->abs_path($input);
328 push @{$sync->{ok}}, $input if $sync;
331 } elsif ($self->{missing_ok} && !-e $input) {
333 $may_sync and $input = 'maildir:'.
334 $lei->abs_path($input);
336 return $lei->fail("Unable to handle $input")
340 if (@f) { check_input_format($lei, \@f) or return }
341 if ($sync && $sync->{no}) {
342 return $lei->fail(<<"") if !$sync->{ok};
343 --mail-sync specified but no inputs support it
345 # non-fatal if some inputs support support sync
346 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
347 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
350 $net->{-can_die} = 1;
351 if (my $err = $net->errors($lei)) {
352 return $lei->fail($err);
354 $net->{quiet} = $lei->{opt}->{quiet};
355 require PublicInbox::LeiAuth;
356 $lei->{auth} //= PublicInbox::LeiAuth->new;
357 $lei->{net} //= $net;
360 require PublicInbox::MdirReader;
361 if ($self->can('pmdir_cb')) {
362 require PublicInbox::LeiPmdir;
363 $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
366 # start watching Maildirs ASAP
367 if ($may_sync && $lei->{sto}) {
368 grep(!m!\Amaildir:/!i, @md) and die "BUG: @md (no pfx)";
369 $lei->lms(1)->lms_write_prepare->add_folders(@md);
370 $lei->refresh_watches;
373 $self->{inputs} = $inputs;
379 for my $input (@{$self->{inputs}}) {
380 eval { $self->input_path_url($input) };
385 # always commit first, even on error partial work is acceptable for
386 # lei <import|tag|convert>
387 my $wait = $self->{lei}->{sto}->wq_do('done') if $self->{lei}->{sto};
388 $self->{lei}->fail($err) if $err;
391 sub input_only_atfork_child {
393 my $lei = $self->{lei};
394 $lei->_lei_atfork_child;
395 PublicInbox::IPC::ipc_atfork_child($self);
396 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
400 # alias this as "net_merge_all_done" to use as an LeiAuth callback
401 sub input_only_net_merge_all_done {
403 $self->wq_io_do('process_inputs');
407 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
408 # for update_xvmd -> update_vmd
409 # returns something like { "+L" => [ @Labels ], ... }
410 sub vmd_mod_extract {
415 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
416 my ($op, $pfx, $val) = ($1, $2, $3);
417 if (my $err = $ERR{$pfx}->($val)) {
418 push @{$vmd_mod->{err}}, $err;
419 } else { # set "+kw", "+L", "-L", "-kw"
420 push @{$vmd_mod->{$op.$pfx}}, $val;