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);
12 # https://www.iana.org/assignments/imap-jmap-keywords/imap-jmap-keywords.xhtml
13 our @KW = (qw(seen answered flagged draft), # widely-compatible
14 qw(forwarded), # IMAP + Maildir
15 qw(phishing junk notjunk)); # rarely supported
17 # note: RFC 8621 states "Users may add arbitrary keywords to an Email",
18 # but is it good idea? Stick to the system and reserved ones, for now.
19 # The widely-compatible ones map to IMAP system flags, Maildir flags
20 # and mbox Status/X-Status headers.
21 my %KW = map { $_ => 1 } @KW;
22 my $L_MAX = 244; # Xapian term limit - length('L')
24 # RFC 8621, sec 2 (Mailboxes) a "label" for us is a JMAP Mailbox "name"
25 # "Servers MAY reject names that violate server policy"
29 length($label) >= $L_MAX and
30 return "`$label' too long (must be <= $L_MAX)";
31 $label =~ m{\A[a-z0-9_](?:[a-z0-9_\-\./\@,]*[a-z0-9])?\z}i ?
32 undef : "`$label' is invalid";
36 $KW{$kw} ? undef : <<EOM;
37 `$kw' is not one of: `seen', `flagged', `answered', `draft'
38 `junk', `notjunk', `phishing' or `forwarded'
43 sub check_input_format ($;$) {
44 my ($lei, $files) = @_;
45 my $opt_key = 'in-format';
46 my $fmt = $lei->{opt}->{$opt_key};
48 my $err = $files ? "regular file(s):\n@$files" : '--stdin';
49 return $lei->fail("--$opt_key unset for $err");
51 return 1 if $fmt eq 'eml';
52 require PublicInbox::MboxLock if $files;
53 require PublicInbox::MboxReader;
54 PublicInbox::MboxReader->reads($fmt) or
55 return $lei->fail("--$opt_key=$fmt unrecognized");
59 # import a single file handle of $name
60 # Subclass must define ->input_eml_cb and ->input_mbox_cb
62 my ($self, $ifmt, $fh, $name, @args) = @_;
64 my $buf = do { local $/; <$fh> } //
65 return $self->{lei}->child_error(1 << 8, <<"");
66 error reading $name: $!
68 # mutt pipes single RFC822 messages with a "From " line,
69 # but no Content-Length or "From " escaping.
70 # "git format-patch" also generates such files by default.
71 $buf =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
73 # a user may feed just a body: git diff | lei rediff -U9
74 if ($self->{-force_eml}) {
75 my $eml = PublicInbox::Eml->new($buf);
76 substr($buf, 0, 0) = "\n\n" if !$eml->{bdy};
78 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
80 # prepare_inputs already validated $ifmt
81 my $cb = PublicInbox::MboxReader->reads($ifmt) //
82 die "BUG: bad fmt=$ifmt";
83 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
87 # handles mboxrd endpoints described in Documentation/design_notes.txt
88 sub handle_http_input ($$@) {
89 my ($self, $url, @args) = @_;
90 my $lei = $self->{lei} or die 'BUG: {lei} missing';
91 my $curl_opt = delete $self->{"-curl-$url"} or
92 die("BUG: $url curl options not prepared");
93 my $uri = pop @$curl_opt;
94 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
95 push @$curl, '-s', @$curl_opt;
96 my $cmd = $curl->for_uri($lei, $uri);
98 my $rdr = { 2 => $lei->{2}, pgid => 0 };
99 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
100 grep(/\A--compressed\z/, @$curl) or
101 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
102 eval { $self->input_fh('mboxrd', $fh, $url, @args) };
106 $lei->child_error($? || 1, "@$cmd failed".$err ? " $err" : '');
110 my ($self, $input, @args) = @_;
111 my $lei = $self->{lei};
112 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
114 if ($input =~ m!\Aimaps?://!i) {
115 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
118 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
119 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
122 } elsif ($input =~ m!\Ahttps?://!i) {
123 handle_http_input($self, $input, @args);
126 if ($input =~ s!\A([a-z0-9]+):!!i) {
128 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
131 my $devfd = $lei->path_to_fd($input) // return;
133 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
134 } elsif (-f $input && $ifmt eq 'eml') {
135 open my $fh, '<', $input or
136 return $lei->fail("open($input): $!");
137 $self->input_fh($ifmt, $fh, $input, @args);
139 my $m = $lei->{opt}->{'lock'} //
140 PublicInbox::MboxLock->defaults;
141 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
142 my $zsfx = PublicInbox::MboxReader::zsfx($input);
144 my $in = delete $mbl->{fh};
146 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
148 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
149 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
150 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
151 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
152 $input appears to be a maildir, not $ifmt
154 PublicInbox::MdirReader->new->maildir_each_eml($input,
155 $self->can('input_maildir_cb'),
158 $lei->fail("$input unsupported (TODO)");
162 sub bad_http ($$;$) {
163 my ($lei, $url, $alt) = @_;
164 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
165 $lei->fail("E: <$url> not recognized, $x");
168 sub prepare_http_input ($$$) {
169 my ($self, $lei, $url) = @_;
171 require PublicInbox::MboxReader;
172 require PublicInbox::LeiCurl;
173 require IO::Uncompress::Gunzip;
174 $self->{curl} //= which('curl') or
175 return $lei->fail("curl missing for <$url>");
176 my $uri = URI->new($url);
177 my $path = $uri->path;
178 my %qf = $uri->query_form;
180 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
182 } elsif ($path =~ m!/raw\z!) {
183 push @curl_opt, '--compressed';
184 # convert search query to mboxrd request since they require POST
185 # this is only intended for PublicInbox::WWW, and will false-positive
186 # on many other search engines... oh well
187 } elsif (defined $qf{'q'}) {
189 $uri->query_form(\%qf);
190 push @curl_opt, '-d', '';
191 $$uri ne $url and $lei->qerr(<<"");
192 # <$url> rewritten to <$$uri> with HTTP POST
194 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
195 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
196 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
197 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
199 return bad_http($lei, $url, $$uri);
201 return bad_http($lei, $url);
203 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
206 sub prepare_inputs { # returns undef on error
207 my ($self, $lei, $inputs) = @_;
208 my $in_fmt = $lei->{opt}->{'in-format'};
209 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
210 if ($lei->{opt}->{stdin}) {
212 $lei->fail("--stdin and @$inputs do not mix");
213 check_input_format($lei) or return;
214 push @$inputs, '/dev/stdin';
215 push @{$sync->{no}}, '/dev/stdin' if $sync;
217 my $net = $lei->{net}; # NetWriter may be created by l2m
219 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
220 for my $input (@$inputs) {
221 my $input_path = $input;
222 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
223 require PublicInbox::NetReader;
224 $net //= PublicInbox::NetReader->new;
225 $net->add_url($input);
226 push @{$sync->{ok}}, $input if $sync;
227 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
228 # TODO: how would we detect r/w JMAP?
229 push @{$sync->{no}}, $input if $sync;
230 prepare_http_input($self, $lei, $input_path) or return;
231 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
233 if (($in_fmt // $ifmt) ne $ifmt) {
234 return $lei->fail(<<"");
235 --in-format=$in_fmt and `$ifmt:' conflict
238 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
239 push @{$sync->{ok}}, $input if $sync;
241 push @{$sync->{no}}, $input if $sync;
243 my $devfd = $lei->path_to_fd($input_path) // return;
244 if ($devfd >= 0 || (-f $input_path || -p _)) {
245 require PublicInbox::MboxLock;
246 require PublicInbox::MboxReader;
247 PublicInbox::MboxReader->reads($ifmt) or return
248 $lei->fail("$ifmt not supported");
249 } elsif (-d $input_path) {
250 require PublicInbox::MdirReader;
251 $ifmt eq 'maildir' or return
252 $lei->fail("$ifmt not supported");
253 $sync and $input = 'maildir:'.
254 $lei->abs_path($input_path);
256 return $lei->fail("Unable to handle $input");
258 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
259 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
260 $input is `eml', not --in-format=$in_fmt
262 require PublicInbox::Eml;
263 push @{$sync->{no}}, $input if $sync;
265 my $devfd = $lei->path_to_fd($input) // return;
266 if ($devfd >= 0 || -f $input || -p _) {
267 push @{$sync->{no}}, $input if $sync;
269 } elsif (-d $input) {
271 $input = $lei->abs_path($input);
272 push @{$sync->{ok}}, $input;
276 return $lei->fail("Unable to handle $input")
280 if (@f) { check_input_format($lei, \@f) or return }
281 if (@d) { # TODO: check for MH vs Maildir, here
282 require PublicInbox::MdirReader;
284 if ($sync && $sync->{no}) {
285 return $lei->fail(<<"") if !$sync->{ok};
286 --mail-sync specified but no inputs support it
288 # non-fatal if some inputs support support sync
289 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
290 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
293 $net->{-can_die} = 1;
294 if (my $err = $net->errors($lei)) {
295 return $lei->fail($err);
297 $net->{quiet} = $lei->{opt}->{quiet};
298 require PublicInbox::LeiAuth;
299 $lei->{auth} //= PublicInbox::LeiAuth->new;
300 $lei->{net} //= $net;
302 $self->{inputs} = $inputs;
308 for my $input (@{$self->{inputs}}) {
309 eval { $self->input_path_url($input) };
314 # always commit first, even on error partial work is acceptable for
315 # lei <import|tag|convert>
316 my $wait = $self->{lei}->{sto}->ipc_do('done') if $self->{lei}->{sto};
317 $self->{lei}->fail($err) if $err;
320 sub input_only_atfork_child {
322 my $lei = $self->{lei};
323 $lei->_lei_atfork_child;
324 PublicInbox::IPC::ipc_atfork_child($self);
325 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
329 # alias this as "net_merge_all_done" to use as an LeiAuth callback
330 sub input_only_net_merge_all_done {
332 $self->wq_io_do('process_inputs');
336 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
337 # for update_xvmd -> update_vmd
338 sub vmd_mod_extract {
343 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
344 my ($op, $pfx, $val) = ($1, $2, $3);
345 if (my $err = $ERR{$pfx}->($val)) {
346 push @{$vmd_mod->{err}}, $err;
347 } else { # set "+kw", "+L", "-L", "-kw"
348 push @{$vmd_mod->{$op.$pfx}}, $val;