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;
72 $self->input_eml_cb(PublicInbox::Eml->new(\$buf), @args);
74 # prepare_inputs already validated $ifmt
75 my $cb = PublicInbox::MboxReader->reads($ifmt) //
76 die "BUG: bad fmt=$ifmt";
77 $cb->(undef, $fh, $self->can('input_mbox_cb'), $self, @args);
81 # handles mboxrd endpoints described in Documentation/design_notes.txt
82 sub handle_http_input ($$@) {
83 my ($self, $url, @args) = @_;
84 my $lei = $self->{lei} or die 'BUG: {lei} missing';
85 my $curl_opt = delete $self->{"-curl-$url"} or
86 die("BUG: $url curl options not prepared");
87 my $uri = pop @$curl_opt;
88 my $curl = PublicInbox::LeiCurl->new($lei, $self->{curl}) or return;
89 push @$curl, '-s', @$curl_opt;
90 my $cmd = $curl->for_uri($lei, $uri);
92 my $rdr = { 2 => $lei->{2}, pgid => 0 };
93 my ($fh, $pid) = popen_rd($cmd, undef, $rdr);
94 grep(/\A--compressed\z/, @$curl) or
95 $fh = IO::Uncompress::Gunzip->new($fh, MultiStream => 1);
96 eval { $self->input_fh('mboxrd', $fh, $url, @args) };
100 $lei->child_error($? || 1, "@$cmd failed".$err ? " $err" : '');
104 my ($self, $input, @args) = @_;
105 my $lei = $self->{lei};
106 my $ifmt = lc($lei->{opt}->{'in-format'} // '');
108 if ($input =~ m!\Aimaps?://!i) {
109 $lei->{net}->imap_each($input, $self->can('input_net_cb'),
112 } elsif ($input =~ m!\A(?:nntps?|s?news)://!i) {
113 $lei->{net}->nntp_each($input, $self->can('input_net_cb'),
116 } elsif ($input =~ m!\Ahttps?://!i) {
117 handle_http_input($self, $input, @args);
120 if ($input =~ s!\A([a-z0-9]+):!!i) {
122 } elsif ($input =~ /\.(?:patch|eml)\z/i) {
125 my $devfd = $lei->path_to_fd($input) // return;
127 $self->input_fh($ifmt, $lei->{$devfd}, $input, @args);
128 } elsif (-f $input && $ifmt eq 'eml') {
129 open my $fh, '<', $input or
130 return $lei->fail("open($input): $!");
131 $self->input_fh($ifmt, $fh, $input, @args);
133 my $m = $lei->{opt}->{'lock'} //
134 PublicInbox::MboxLock->defaults;
135 my $mbl = PublicInbox::MboxLock->acq($input, 0, $m);
136 my $zsfx = PublicInbox::MboxReader::zsfx($input);
138 my $in = delete $mbl->{fh};
140 PublicInbox::MboxReader::zsfxcat($in, $zsfx, $lei);
142 local $PublicInbox::DS::in_loop = 0 if $zsfx; # dwaitpid
143 $self->input_fh($ifmt, $mbl->{fh}, $input, @args);
144 } elsif (-d _ && (-d "$input/cur" || -d "$input/new")) {
145 return $lei->fail(<<EOM) if $ifmt && $ifmt ne 'maildir';
146 $input appears to a be a maildir, not $ifmt
148 PublicInbox::MdirReader->new->maildir_each_eml($input,
149 $self->can('input_maildir_cb'),
152 $lei->fail("$input unsupported (TODO)");
156 sub bad_http ($$;$) {
157 my ($lei, $url, $alt) = @_;
158 my $x = $alt ? "did you mean <$alt>?" : 'download and import manually';
159 $lei->fail("E: <$url> not recognized, $x");
162 sub prepare_http_input ($$$) {
163 my ($self, $lei, $url) = @_;
165 require PublicInbox::MboxReader;
166 require PublicInbox::LeiCurl;
167 require IO::Uncompress::Gunzip;
168 $self->{curl} //= which('curl') or
169 return $lei->fail("curl missing for <$url>");
170 my $uri = URI->new($url);
171 my $path = $uri->path;
172 my %qf = $uri->query_form;
174 if ($path =~ m!/(?:t\.mbox\.gz|all\.mbox\.gz)\z!) {
176 } elsif ($path =~ m!/raw\z!) {
177 push @curl_opt, '--compressed';
178 # convert search query to mboxrd request since they require POST
179 # this is only intended for PublicInbox::WWW, and will false-positive
180 # on many other search engines... oh well
181 } elsif (defined $qf{'q'}) {
183 $uri->query_form(\%qf);
184 push @curl_opt, '-d', '';
185 $$uri ne $url and $lei->qerr(<<"");
186 # <$url> rewritten to <$$uri> with HTTP POST
188 # try to provide hints for /$INBOX/$MSGID/T/ and /$INBOX/
189 } elsif ($path =~ s!/[tT]/\z!/t.mbox.gz! ||
190 $path =~ s!/t\.atom\z!/t.mbox.gz! ||
191 $path =~ s!/([^/]+\@[^/]+)/\z!/$1/raw!) {
193 return bad_http($lei, $url, $$uri);
195 return bad_http($lei, $url);
197 $self->{"-curl-$url"} = [ @curl_opt, $uri ]; # for handle_http_input
200 sub prepare_inputs { # returns undef on error
201 my ($self, $lei, $inputs) = @_;
202 my $in_fmt = $lei->{opt}->{'in-format'};
203 my $sync = $lei->{opt}->{'mail-sync'} ? {} : undef; # using LeiMailSync
204 if ($lei->{opt}->{stdin}) {
206 $lei->fail("--stdin and @$inputs do not mix");
207 check_input_format($lei) or return;
208 push @$inputs, '/dev/stdin';
209 push @{$sync->{no}}, '/dev/stdin' if $sync;
211 my $net = $lei->{net}; # NetWriter may be created by l2m
213 # e.g. Maildir:/home/user/Mail/ or imaps://example.com/INBOX
214 for my $input (@$inputs) {
215 my $input_path = $input;
216 if ($input =~ m!\A(?:imaps?|nntps?|s?news)://!i) {
217 require PublicInbox::NetReader;
218 $net //= PublicInbox::NetReader->new;
219 $net->add_url($input);
220 push @{$sync->{ok}}, $input if $sync;
221 } elsif ($input_path =~ m!\Ahttps?://!i) { # mboxrd.gz
222 # TODO: how would we detect r/w JMAP?
223 push @{$sync->{no}}, $input if $sync;
224 prepare_http_input($self, $lei, $input_path) or return;
225 } elsif ($input_path =~ s/\A([a-z0-9]+)://is) {
227 if (($in_fmt // $ifmt) ne $ifmt) {
228 return $lei->fail(<<"");
229 --in-format=$in_fmt and `$ifmt:' conflict
232 if ($ifmt =~ /\A(?:maildir|mh)\z/i) {
233 push @{$sync->{ok}}, $input if $sync;
235 push @{$sync->{no}}, $input if $sync;
237 my $devfd = $lei->path_to_fd($input_path) // return;
238 if ($devfd >= 0 || (-f $input_path || -p _)) {
239 require PublicInbox::MboxLock;
240 require PublicInbox::MboxReader;
241 PublicInbox::MboxReader->reads($ifmt) or return
242 $lei->fail("$ifmt not supported");
243 } elsif (-d $input_path) {
244 require PublicInbox::MdirReader;
245 $ifmt eq 'maildir' or return
246 $lei->fail("$ifmt not supported");
247 $input = $lei->abs_path($input) if $sync;
249 return $lei->fail("Unable to handle $input");
251 } elsif ($input =~ /\.(?:eml|patch)\z/i && -f $input) {
252 lc($in_fmt//'eml') eq 'eml' or return $lei->fail(<<"");
253 $input is `eml', not --in-format=$in_fmt
255 require PublicInbox::Eml;
256 push @{$sync->{no}}, $input if $sync;
258 my $devfd = $lei->path_to_fd($input) // return;
259 if ($devfd >= 0 || -f $input || -p _) {
260 push @{$sync->{no}}, $input if $sync;
262 } elsif (-d $input) {
264 $input = $lei->abs_path($input);
265 push @{$sync->{ok}}, $input;
269 return $lei->fail("Unable to handle $input")
273 if (@f) { check_input_format($lei, \@f) or return }
274 if (@d) { # TODO: check for MH vs Maildir, here
275 require PublicInbox::MdirReader;
277 if ($sync && $sync->{no}) {
278 return $lei->fail(<<"") if !$sync->{ok};
279 --mail-sync specified but no inputs support it
281 # non-fatal if some inputs support support sync
282 $lei->err("# --mail-sync will only be used for @{$sync->{ok}}");
283 $lei->err("# --mail-sync is not supported for: @{$sync->{no}}");
286 $net->{-can_die} = 1;
287 if (my $err = $net->errors($lei)) {
288 return $lei->fail($err);
290 $net->{quiet} = $lei->{opt}->{quiet};
291 require PublicInbox::LeiAuth;
292 $lei->{auth} //= PublicInbox::LeiAuth->new;
293 $lei->{net} //= $net;
295 $self->{inputs} = $inputs;
301 for my $input (@{$self->{inputs}}) {
302 eval { $self->input_path_url($input) };
307 # always commit first, even on error partial work is acceptable for
308 # lei <import|tag|convert>
309 my $wait = $self->{lei}->{sto}->ipc_do('done') if $self->{lei}->{sto};
310 $self->{lei}->fail($err) if $err;
313 sub input_only_atfork_child {
315 my $lei = $self->{lei};
316 $lei->_lei_atfork_child;
317 PublicInbox::IPC::ipc_atfork_child($self);
318 $lei->{auth}->do_auth_atfork($self) if $lei->{auth};
322 # alias this as "net_merge_all_done" to use as an LeiAuth callback
323 sub input_only_net_merge_all_done {
325 $self->wq_io_do('process_inputs');
329 # like Getopt::Long, but for +kw:FOO and -kw:FOO to prepare
330 # for update_xvmd -> update_vmd
331 sub vmd_mod_extract {
336 if ($x =~ /\A(\+|\-)(kw|L):(.+)\z/) {
337 my ($op, $pfx, $val) = ($1, $2, $3);
338 if (my $err = $ERR{$pfx}->($val)) {
339 push @{$vmd_mod->{err}}, $err;
340 } else { # set "+kw", "+L", "-L", "-kw"
341 push @{$vmd_mod->{$op.$pfx}}, $val;