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(1 << 8, <<"");
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($? || 1, "@$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);
127 if ($input =~ s!\A([a-z0-9]+):!!i) {
129 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
131 } elsif (-f $input && $input =~ m{\A(?:.+)/(?:new|cur)/([^/]+)\z}) {
133 my $fl = PublicInbox::MdirReader::maildir_basename_flags($bn);
134 return if index($fl, 'T') >= 0;
135 return $self->pmdir_cb($input, $fl) if $self->can('pmdir_cb');
136 my $eml = eml_from_path($input) or return
137 $lei->qerr("# $input not readable");
138 my $kw = PublicInbox::MdirReader::flags2kw($fl);
139 $self->can('input_maildir_cb')->($input, $kw, $eml, $self);
142 my $devfd = $lei->path_to_fd($input) // return;
144 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
145 } elsif (-f $input && $ifmt eq 'eml') {
146 open my $fh, '<', $input or
147 return $lei->fail("open($input): $!");
148 $self->input_fh($ifmt, $fh, $input, @args);
150 my $m = $lei->{opt}->{'lock'} //
151 PublicInbox::MboxLock->defaults;
152 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
153 my $zsfx = PublicInbox::MboxReader::zsfx($input);
155 my $in = delete $mbl->{fh};
157 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
159 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
160 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
161 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
162 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
163 $input appears to be a maildir, not $ifmt
165 my $mdr = PublicInbox::MdirReader->new;
166 if (my $pmd = $self->{pmd}) {
167 $mdr->maildir_each_file($input,
168 $pmd->can('each_mdir_fn'),
171 $mdr->maildir_each_eml($input,
172 $self->can('input_maildir_cb'),
176 $lei->fail("$input unsupported (TODO)");
180 sub bad_http ($$;$) {
181 my ($lei, $url, $alt) = @_;
182 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
183 $lei->fail("E: <$url> not recognized, $x");
186 sub prepare_http_input ($$$) {
187 my ($self, $lei, $url) = @_;
189 require PublicInbox::MboxReader;
190 require PublicInbox::LeiCurl;
191 require IO::Uncompress::Gunzip;
192 $self->{curl} //= which('curl') or
193 return $lei->fail("curl missing for <$url>");
194 my $uri = URI->new($url);
195 my $path = $uri->path;
196 my %qf = $uri->query_form;
198 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
200 } elsif ($path =~ m!/raw\z!) {
201 push @curl_opt, '--compressed';
202 # convert search query to mboxrd request since they require POST
203 # this is only intended for PublicInbox::WWW, and will false-positive
204 # on many other search engines... oh well
205 } elsif (defined $qf{'q'}) {
207 $uri->query_form(\%qf);
208 push @curl_opt, '-d', '';
209 $$uri ne $url and $lei->qerr(<<"");
210 # <$url> rewritten to <$$uri> with HTTP POST
212 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
213 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
214 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
215 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
217 return bad_http($lei, $url, $$uri);
219 return bad_http($lei, $url);
221 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
224 sub prepare_inputs { # returns undef on error
225 my ($self, $lei, $inputs) = @_;
226 my $in_fmt = $lei->{opt}->{'in-format'};
227 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
228 if ($lei->{opt}->{stdin}) {
230 $lei->fail("--stdin and @$inputs do not mix");
231 check_input_format($lei) or return;
232 push @$inputs, '/dev/stdin';
233 push @{$sync->{no}}, '/dev/stdin' if $sync;
235 my $net = $lei->{net}; # NetWriter may be created by l2m
237 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
238 for my $input (@$inputs) {
239 my $input_path = $input;
240 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
241 require PublicInbox::NetReader;
242 $net //= PublicInbox::NetReader->new;
243 $net->add_url($input, $self->{-ls_ok});
244 push @{$sync->{ok}}, $input if $sync;
245 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
246 # TODO: how would we detect r/w JMAP?
247 push @{$sync->{no}}, $input if $sync;
248 prepare_http_input($self, $lei, $input_path) or return;
249 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
251 if (($in_fmt // $ifmt) ne $ifmt) {
252 return $lei->fail(<<"");
253 --in-format=$in_fmt and `$ifmt:' conflict
256 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
257 push @{$sync->{ok}}, $input if $sync;
259 push @{$sync->{no}}, $input if $sync;
261 my $devfd = $lei->path_to_fd($input_path) // return;
262 if ($devfd >= 0 || (-f $input_path || -p _)) {
263 require PublicInbox::MboxLock;
264 require PublicInbox::MboxReader;
265 PublicInbox::MboxReader->reads($ifmt) or return
266 $lei->fail("$ifmt not supported");
267 } elsif (-d $input_path) {
268 $ifmt eq 'maildir' or return
269 $lei->fail("$ifmt not supported");
270 $sync and $input = 'maildir:'.
271 $lei->abs_path($input_path);
274 return $lei->fail("Unable to handle $input");
276 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
277 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
278 $input is `eml', not --in-format=$in_fmt
280 push @{$sync->{no}}, $input if $sync;
281 } elsif (-f $input && $input =~ m{\A(.+)/(new|cur)/([^/]+)\z}) {
282 # single file in a Maildir
283 my ($mdir, $nc, $bn) = ($1, $2, $3);
284 my $other = $mdir . ($nc eq 'new' ? '/cur' : '/new');
285 return $lei->fail(<<EOM) if !-d $other;
286 No `$other' directory for `$input'
288 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
289 $input is `eml', not --in-format=$in_fmt
292 $input = $lei->abs_path($mdir) . "/$nc/$bn";
293 push @{$sync->{ok}}, $input;
295 require PublicInbox::MdirReader;
297 my $devfd = $lei->path_to_fd($input) // return;
298 if ($devfd >= 0 || -f $input || -p _) {
299 push @{$sync->{no}}, $input if $sync;
301 } elsif (-d "$input/new" && -d "$input/cur") {
304 $lei->abs_path($input);
305 push @{$sync->{ok}}, $input;
309 return $lei->fail("Unable to handle $input")
313 if (@f) { check_input_format($lei, \@f) or return }
314 if ($sync && $sync->{no}) {
315 return $lei->fail(<<"") if !$sync->{ok};
316 --mail-sync specified but no inputs support it
318 # non-fatal if some inputs support support sync
319 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
320 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
323 $net->{-can_die} = 1;
324 if (my $err = $net->errors($lei)) {
325 return $lei->fail($err);
327 $net->{quiet} = $lei->{opt}->{quiet};
328 require PublicInbox::LeiAuth;
329 $lei->{auth} //= PublicInbox::LeiAuth->new;
330 $lei->{net} //= $net;
333 require PublicInbox::MdirReader;
334 if ($self->can('pmdir_cb')) {
335 require PublicInbox::LeiPmdir;
336 $self->{pmd} = PublicInbox::LeiPmdir->new($lei, $self);
339 $self->{inputs} = $inputs;
345 for my $input (@{$self->{inputs}}) {
346 eval { $self->input_path_url($input) };
351 # always commit first, even on error partial work is acceptable for
352 # lei <import|tag|convert>
353 my $wait = $self->{lei}->{sto}->ipc_do('done') if $self->{lei}->{sto};
354 $self->{lei}->fail($err) if $err;
357 sub input_only_atfork_child {
359 my $lei = $self->{lei};
360 $lei->_lei_atfork_child;
361 PublicInbox::IPC::ipc_atfork_child($self);
362 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
366 # alias this as "net_merge_all_done" to use as an LeiAuth callback
367 sub input_only_net_merge_all_done {
369 $self->wq_io_do('process_inputs');
373 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
374 # for update_xvmd -> update_vmd
375 sub vmd_mod_extract {
380 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
381 my ($op, $pfx, $val) = ($1, $2, $3);
382 if (my $err = $ERR{$pfx}->($val)) {
383 push @{$vmd_mod->{err}}, $err;
384 } else { # set "+kw", "+L", "-L", "-kw"
385 push @{$vmd_mod->{$op.$pfx}}, $val;