]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
imap: *SEARCH: use Parse::RecDescent
[public-inbox.git] / lib / PublicInbox / IMAP.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Each instance of this represents an IMAP client connected to
5 # public-inbox-imapd.  Much of this was taken from NNTP, but
6 # further refined while experimenting on future ideas to handle
7 # slow storage.
8 #
9 # data notes:
10 #
11 # * NNTP article numbers are UIDs, mm->created_at is UIDVALIDITY
12 #
13 # * public-inboxes are sliced into mailboxes of 50K messages
14 #   to not overload MUAs: $NEWSGROUP_NAME.$SLICE_INDEX
15 #   Slices are similar in concept to v2 "epochs".  Epochs
16 #   are for the limitations of git clients, while slices are
17 #   for the limitations of IMAP clients.
18 #
19 # * We also take advantage of slices being only 50K to store
20 #   "UID offset" to message sequence number (MSN) mapping
21 #   as a 50K uint16_t array (via pack("S*", ...)).  "UID offset"
22 #   is the offset from {uid_base} which determines the start of
23 #   the mailbox slice.
24
25 package PublicInbox::IMAP;
26 use strict;
27 use base qw(PublicInbox::DS);
28 use fields qw(imapd ibx long_cb -login_tag
29         uid_base -idle_tag uo2m);
30 use PublicInbox::Eml;
31 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
32 use PublicInbox::DS qw(now);
33 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
34 use PublicInbox::GitAsyncCat;
35 use Text::ParseWords qw(parse_line);
36 use Errno qw(EAGAIN);
37 use Hash::Util qw(unlock_hash); # dependency of fields for perl 5.10+, anyways
38 use PublicInbox::Search;
39 use PublicInbox::IMAPsearchqp;
40 *mdocid = \&PublicInbox::Search::mdocid;
41
42 my $Address;
43 for my $mod (qw(Email::Address::XS Mail::Address)) {
44         eval "require $mod" or next;
45         $Address = $mod and last;
46 }
47 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
48
49 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
50
51 # Changing UID_SLICE will cause grief for clients which cache.
52 # This also needs to be <64K: we pack it into a uint16_t
53 # for long_response UID (offset) => MSN mappings
54 sub UID_SLICE () { 50_000 }
55
56 # these values area also used for sorting
57 sub NEED_SMSG () { 1 }
58 sub NEED_BLOB () { NEED_SMSG|2 }
59 sub CRLF_BREF () { 4 }
60 sub EML_HDR () { 8 }
61 sub CRLF_HDR () { 16 }
62 sub EML_BDY () { 32 }
63 sub CRLF_BDY () { 64 }
64 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
65 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
66 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
67 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
68
69 my %FETCH_NEED = (
70         'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
71         'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
72         'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
73         'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
74         'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
75         'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
76         RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
77         BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
78         BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
79         ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
80         FLAGS => [ 0, \&emit_flags ],
81         INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
82 );
83 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
84
85 # aliases (RFC 3501 section 6.4.5)
86 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
87 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
88 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
89
90 for my $att (keys %FETCH_ATT) {
91         my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
92         $FETCH_ATT{$att} = \%h;
93 }
94 undef %FETCH_NEED;
95
96 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
97 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
98
99 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
100 $PublicInbox::DS::EXPTIME = 60 * 30;
101
102 sub greet ($) {
103         my ($self) = @_;
104         my $capa = capa($self);
105         $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
106 }
107
108 sub new ($$$) {
109         my ($class, $sock, $imapd) = @_;
110         my $self = fields::new('PublicInbox::IMAP_preauth');
111         unlock_hash(%$self);
112         my $ev = EPOLLIN;
113         my $wbuf;
114         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
115                 return CORE::close($sock) if $! != EAGAIN;
116                 $ev = PublicInbox::TLS::epollbit();
117                 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
118         }
119         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
120         $self->{imapd} = $imapd;
121         if ($wbuf) {
122                 $self->{wbuf} = $wbuf;
123         } else {
124                 greet($self);
125         }
126         $self->update_idle_time;
127         $self;
128 }
129
130 sub logged_in { 1 }
131
132 sub capa ($) {
133         my ($self) = @_;
134
135         # dovecot advertises IDLE pre-login; perhaps because some clients
136         # depend on it, so we'll do the same
137         my $capa = 'CAPABILITY IMAP4rev1 IDLE';
138         if ($self->logged_in) {
139                 $capa .= ' COMPRESS=DEFLATE';
140         } else {
141                 if (!($self->{sock} // $self)->can('accept_SSL') &&
142                         $self->{imapd}->{accept_tls}) {
143                         $capa .= ' STARTTLS';
144                 }
145                 $capa .= ' AUTH=ANONYMOUS';
146         }
147 }
148
149 sub login_success ($$) {
150         my ($self, $tag) = @_;
151         bless $self, 'PublicInbox::IMAP';
152         my $capa = capa($self);
153         "$tag OK [$capa] Logged in\r\n";
154 }
155
156 sub auth_challenge_ok ($) {
157         my ($self) = @_;
158         my $tag = delete($self->{-login_tag}) or return;
159         login_success($self, $tag);
160 }
161
162 sub cmd_login ($$$$) {
163         my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
164         login_success($self, $tag);
165 }
166
167 sub cmd_close ($$) {
168         my ($self, $tag) = @_;
169         delete $self->{uid_base};
170         delete $self->{ibx} ? "$tag OK Close done\r\n"
171                                 : "$tag BAD No mailbox\r\n";
172 }
173
174 sub cmd_logout ($$) {
175         my ($self, $tag) = @_;
176         delete $self->{-idle_tag};
177         $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
178         $self->shutdn; # PublicInbox::DS::shutdn
179         undef;
180 }
181
182 sub cmd_authenticate ($$$) {
183         my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
184         $self->{-login_tag} = $tag;
185         "+\r\n"; # challenge
186 }
187
188 sub cmd_capability ($$) {
189         my ($self, $tag) = @_;
190         '* '.capa($self)."\r\n$tag OK Capability done\r\n";
191 }
192
193 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
194
195 # uo2m: UID Offset to MSN, this is an arrayref by default,
196 # but uo2m_hibernate can compact and deduplicate it
197 sub uo2m_ary_new ($) {
198         my ($self) = @_;
199         my $base = $self->{uid_base};
200         my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
201
202         # convert UIDs to offsets from {base}
203         my @tmp; # [$UID_OFFSET] => $MSN
204         my $msn = 0;
205         ++$base;
206         $tmp[$_ - $base] = ++$msn for @$uids;
207         \@tmp;
208 }
209
210 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
211 # uint16_t uo2m[UID_SLICE].
212 # May be swapped out for idle clients if THP is disabled.
213 sub uo2m_hibernate ($) {
214         my ($self) = @_;
215         ref(my $uo2m = $self->{uo2m}) or return;
216         my %dedupe = ( uo2m_pack($uo2m) => undef );
217         $self->{uo2m} = (keys(%dedupe))[0];
218         undef;
219 }
220
221 sub uo2m_last_uid ($) {
222         my ($self) = @_;
223         my $uo2m = $self->{uo2m} or die 'BUG: uo2m_last_uid w/o {uo2m}';
224         (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
225 }
226
227 sub uo2m_pack ($) {
228         # $_[0] is an arrayref of MSNs, it may have undef gaps if there
229         # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
230         no warnings 'uninitialized';
231         pack('S*', @{$_[0]});
232 }
233
234 # extend {uo2m} to account for new messages which arrived since
235 # {uo2m} was created.
236 sub uo2m_extend ($$) {
237         my ($self, $new_uid_max) = @_;
238         defined(my $uo2m = $self->{uo2m}) or
239                 return($self->{uo2m} = uo2m_ary_new($self));
240         my $beg = uo2m_last_uid($self); # last UID we've learned
241         return $uo2m if $beg >= $new_uid_max; # fast path
242
243         # need to extend the current range:
244         my $base = $self->{uid_base};
245         ++$beg;
246         my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
247         my @tmp; # [$UID_OFFSET] => $MSN
248         if (ref($uo2m)) {
249                 my $msn = $uo2m->[-1];
250                 $tmp[$_ - $beg] = ++$msn for @$uids;
251                 push @$uo2m, @tmp;
252                 $uo2m;
253         } else {
254                 my $msn = unpack('S', substr($uo2m, -2, 2));
255                 $tmp[$_ - $beg] = ++$msn for @$uids;
256                 $uo2m .= uo2m_pack(\@tmp);
257                 my %dedupe = ($uo2m => undef);
258                 $self->{uo2m} = (keys %dedupe)[0];
259         }
260 }
261
262 # the flexible version which works on scalars and array refs.
263 # Must call uo2m_extend before this
264 sub uid2msn ($$) {
265         my ($self, $uid) = @_;
266         my $uo2m = $self->{uo2m};
267         my $off = $uid - $self->{uid_base} - 1;
268         ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
269 }
270
271 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
272 # $msn2uid->[$MSN-1] => $UID.  The result of this is always ephemeral
273 # and does not live beyond the event loop.
274 sub msn2uid ($) {
275         my ($self) = @_;
276         my $base = $self->{uid_base};
277         my $uo2m = uo2m_extend($self, $base + UID_SLICE);
278         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
279
280         my $uo = 0;
281         my @msn2uid;
282         for my $msn (@$uo2m) {
283                 ++$uo;
284                 $msn2uid[$msn - 1] = $uo + $base if $msn;
285         }
286         \@msn2uid;
287 }
288
289 # converts a set of message sequence numbers in requests to UIDs:
290 sub msn_to_uid_range ($$) {
291         my $msn2uid = $_[0];
292         $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
293 }
294
295 # called by PublicInbox::InboxIdle
296 sub on_inbox_unlock {
297         my ($self, $ibx) = @_;
298         my $old = uo2m_last_uid($self);
299         my $uid_end = $self->{uid_base} + UID_SLICE;
300         uo2m_extend($self, $uid_end);
301         my $new = uo2m_last_uid($self);
302         if ($new > $old) {
303                 my $msn = uid2msn($self, $new);
304                 $self->write(\"* $msn EXISTS\r\n");
305         } elsif ($new == $uid_end) { # max exceeded $uid_end
306                 # continue idling w/o inotify
307                 my $sock = $self->{sock} or return;
308                 $ibx->unsubscribe_unlock(fileno($sock));
309         }
310 }
311
312 # called every X minute(s) or so by PublicInbox::DS::later
313 my $IDLERS = {};
314 my $idle_timer;
315 sub idle_tick_all {
316         my $old = $IDLERS;
317         $IDLERS = {};
318         for my $i (values %$old) {
319                 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
320                 $i->update_idle_time or next;
321                 $IDLERS->{fileno($i->{sock})} = $i;
322                 $i->write(\"* OK Still here\r\n");
323         }
324         $idle_timer = scalar keys %$IDLERS ?
325                         PublicInbox::DS::later(\&idle_tick_all) : undef;
326 }
327
328 sub cmd_idle ($$) {
329         my ($self, $tag) = @_;
330         # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
331         my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
332         $self->{-idle_tag} = $tag;
333         my $max = $ibx->over->max;
334         my $uid_end = $self->{uid_base} + UID_SLICE;
335         my $sock = $self->{sock} or return;
336         my $fd = fileno($sock);
337         # only do inotify on most recent slice
338         if ($max < $uid_end) {
339                 uo2m_extend($self, $uid_end);
340                 $ibx->subscribe_unlock($fd, $self);
341                 $self->{imapd}->idler_start;
342         }
343         $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
344         $IDLERS->{$fd} = $self;
345         \"+ idling\r\n"
346 }
347
348 sub stop_idle ($$) {
349         my ($self, $ibx) = @_;
350         my $sock = $self->{sock} or return;
351         my $fd = fileno($sock);
352         delete $IDLERS->{$fd};
353         $ibx->unsubscribe_unlock($fd);
354 }
355
356 sub idle_done ($$) {
357         my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
358         defined(my $idle_tag = delete $self->{-idle_tag}) or
359                 return "$tag BAD not idle\r\n";
360         my $ibx = $self->{ibx} or do {
361                 warn "BUG: idle_tag set w/o inbox";
362                 return "$tag BAD internal bug\r\n";
363         };
364         stop_idle($self, $ibx);
365         "$idle_tag OK Idle done\r\n";
366 }
367
368 sub ensure_slices_exist ($$$) {
369         my ($imapd, $ibx, $max) = @_;
370         defined(my $mb_top = $ibx->{newsgroup}) or return;
371         my $mailboxes = $imapd->{mailboxes};
372         my @created;
373         for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
374                 my $sub_mailbox = "$mb_top.$i";
375                 last if exists $mailboxes->{$sub_mailbox};
376                 $mailboxes->{$sub_mailbox} = $ibx;
377                 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
378                 push @created, $sub_mailbox;
379         }
380         return unless @created;
381         my $l = $imapd->{inboxlist} or return;
382         push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
383 }
384
385 sub inbox_lookup ($$) {
386         my ($self, $mailbox) = @_;
387         my ($ibx, $exists, $uidnext, $uid_base);
388         if ($mailbox =~ /\A(.+)\.([0-9]+)\z/) {
389                 # old mail: inbox.comp.foo.$SLICE_IDX
390                 my $mb_top = $1;
391                 $uid_base = $2 * UID_SLICE;
392                 $ibx = $self->{imapd}->{mailboxes}->{lc $mailbox} or return;
393                 my $max;
394                 ($exists, $uidnext, $max) = $ibx->over->imap_status($uid_base,
395                                                         $uid_base + UID_SLICE);
396                 ensure_slices_exist($self->{imapd}, $ibx, $max);
397         } else { # check for dummy inboxes
398                 $mailbox = lc $mailbox;
399                 $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
400
401                 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
402                 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
403                 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
404                         ensure_slices_exist($self->{imapd}, $z, $z->over->max);
405                 }
406
407                 $uid_base = $exists = 0;
408                 $uidnext = 1;
409         }
410         ($ibx, $exists, $uidnext, $uid_base);
411 }
412
413 sub cmd_examine ($$$) {
414         my ($self, $tag, $mailbox) = @_;
415         my ($ibx, $exists, $uidnext, $base) = inbox_lookup($self, $mailbox);
416         return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
417         $self->{uid_base} = $base;
418
419         # XXX: do we need this? RFC 5162/7162
420         my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
421         $self->{ibx} = $ibx;
422         $ret .= <<EOF;
423 * $exists EXISTS\r
424 * $exists RECENT\r
425 * FLAGS (\\Seen)\r
426 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
427 * OK [UNSEEN $exists]\r
428 * OK [UIDNEXT $uidnext]\r
429 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
430 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
431 EOF
432 }
433
434 sub _esc ($) {
435         my ($v) = @_;
436         if (!defined($v)) {
437                 'NIL';
438         } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
439                 '{' . length($v) . "}\r\n" . $v;
440         } else { # quoted string
441                 qq{"$v"}
442         }
443 }
444
445 sub addr_envelope ($$;$) {
446         my ($eml, $x, $y) = @_;
447         my $v = $eml->header_raw($x) //
448                 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
449
450         my @x = $Address->parse($v) or return 'NIL';
451         '(' . join('',
452                 map { '(' . join(' ',
453                                 _esc($_->name), 'NIL',
454                                 _esc($_->user), _esc($_->host)
455                         ) . ')'
456                 } @x) .
457         ')';
458 }
459
460 sub eml_envelope ($) {
461         my ($eml) = @_;
462         '(' . join(' ',
463                 _esc($eml->header_raw('Date')),
464                 _esc($eml->header_raw('Subject')),
465                 addr_envelope($eml, 'From'),
466                 addr_envelope($eml, 'Sender', 'From'),
467                 addr_envelope($eml, 'Reply-To', 'From'),
468                 addr_envelope($eml, 'To'),
469                 addr_envelope($eml, 'Cc'),
470                 addr_envelope($eml, 'Bcc'),
471                 _esc($eml->header_raw('In-Reply-To')),
472                 _esc($eml->header_raw('Message-ID')),
473         ) . ')';
474 }
475
476 sub _esc_hash ($) {
477         my ($hash) = @_;
478         if ($hash && scalar keys %$hash) {
479                 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
480                 '(' . join(' ', map { _esc($_) } @$hash) . ')';
481         } else {
482                 'NIL';
483         }
484 }
485
486 sub body_disposition ($) {
487         my ($eml) = @_;
488         my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
489         $cd = parse_content_disposition($cd);
490         my $buf = '('._esc($cd->{type});
491         $buf .= ' ' . _esc_hash(delete $cd->{attributes});
492         $buf .= ')';
493 }
494
495 sub body_leaf ($$;$) {
496         my ($eml, $structure, $hold) = @_;
497         my $buf = '';
498         $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
499                 $buf .= eml_envelope($eml). ' ';
500         my $ct = $eml->ct;
501         $buf .= '('._esc($ct->{type}).' ';
502         $buf .= _esc($ct->{subtype});
503         $buf .= ' ' . _esc_hash(delete $ct->{attributes});
504         $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
505         $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
506         my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
507         $buf .= ' ' . _esc($cte);
508         $buf .= ' ' . $eml->{imap_body_len};
509         $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
510
511         # for message/(rfc822|global|news), $hold[0] should have envelope
512         $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
513
514         if ($structure) {
515                 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
516                 $buf .= ' '. body_disposition($eml);
517                 $buf .= ' '._esc($eml->header_raw('Content-Language'));
518                 $buf .= ' '._esc($eml->header_raw('Content-Location'));
519         }
520         $buf .= ')';
521 }
522
523 sub body_parent ($$$) {
524         my ($eml, $structure, $hold) = @_;
525         my $ct = $eml->ct;
526         my $type = lc($ct->{type});
527         if ($type eq 'multipart') {
528                 my $buf = '(';
529                 $buf .= @$hold ? join('', @$hold) : 'NIL';
530                 $buf .= ' '._esc($ct->{subtype});
531                 if ($structure) {
532                         $buf .= ' '._esc_hash(delete $ct->{attributes});
533                         $buf .= ' '.body_disposition($eml);
534                         $buf .= ' '._esc($eml->header_raw('Content-Language'));
535                         $buf .= ' '._esc($eml->header_raw('Content-Location'));
536                 }
537                 $buf .= ')';
538                 @$hold = ($buf);
539         } else { # message/(rfc822|global|news)
540                 @$hold = (body_leaf($eml, $structure, $hold));
541         }
542 }
543
544 # this is gross, but we need to process the parent part AFTER
545 # the child parts are done
546 sub bodystructure_prep {
547         my ($p, $q) = @_;
548         my ($eml, $depth) = @$p; # ignore idx
549         # set length here, as $eml->{bdy} gets deleted for message/rfc822
550         $eml->{imap_body_len} = length($eml->body_raw);
551         push @$q, $eml, $depth;
552 }
553
554 # for FETCH BODY and FETCH BODYSTRUCTURE
555 sub fetch_body ($;$) {
556         my ($eml, $structure) = @_;
557         my @q;
558         $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
559         my $cur_depth = 0;
560         my @hold;
561         do {
562                 my ($part, $depth) = splice(@q, -2);
563                 my $is_mp_parent = $depth == ($cur_depth - 1);
564                 $cur_depth = $depth;
565
566                 if ($is_mp_parent) {
567                         body_parent($part, $structure, \@hold);
568                 } else {
569                         unshift @hold, body_leaf($part, $structure);
570                 }
571         } while (@q);
572         join('', @hold);
573 }
574
575 sub requeue_once ($) {
576         my ($self) = @_;
577         # COMPRESS users all share the same DEFLATE context.
578         # Flush it here to ensure clients don't see
579         # each other's data
580         $self->zflush;
581
582         # no recursion, schedule another call ASAP,
583         # but only after all pending writes are done.
584         # autovivify wbuf:
585         my $new_size = push(@{$self->{wbuf}}, \&long_step);
586
587         # wbuf may be populated by $cb, no need to rearm if so:
588         $self->requeue if $new_size == 1;
589 }
590
591 sub fetch_run_ops {
592         my ($self, $smsg, $bref, $ops, $partial) = @_;
593         my $uid = $smsg->{num};
594         $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
595         my ($eml, $k);
596         for (my $i = 0; $i < @$ops;) {
597                 $k = $ops->[$i++];
598                 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
599         }
600         partial_emit($self, $partial, $eml) if $partial;
601         $self->msg_more(")\r\n");
602 }
603
604 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
605         my ($bref, $oid, $type, $size, $fetch_arg) = @_;
606         my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
607         my $smsg = shift @$msgs or die 'BUG: no smsg';
608         if (!defined($oid)) {
609                 # it's possible to have TOCTOU if an admin runs
610                 # public-inbox-(edit|purge), just move onto the next message
611                 return requeue_once($self);
612         } else {
613                 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
614         }
615         fetch_run_ops($self, $smsg, $bref, $ops, $partial);
616         requeue_once($self);
617 }
618
619 sub emit_rfc822 {
620         my ($self, $k, undef, $bref) = @_;
621         $self->msg_more(" $k {" . length($$bref)."}\r\n");
622         $self->msg_more($$bref);
623 }
624
625 # Mail::IMAPClient::message_string cares about this by default,
626 # (->Ignoresizeerrors attribute).  Admins are encouraged to
627 # --reindex for IMAP support, anyways.
628 sub emit_rfc822_size {
629         my ($self, $k, $smsg) = @_;
630         $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
631 }
632
633 sub emit_internaldate {
634         my ($self, undef, $smsg) = @_;
635         $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
636 }
637
638 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
639
640 sub emit_envelope {
641         my ($self, undef, undef, undef, $eml) = @_;
642         $self->msg_more(' ENVELOPE '.eml_envelope($eml));
643 }
644
645 sub emit_rfc822_header {
646         my ($self, $k, undef, undef, $eml) = @_;
647         $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
648         $self->msg_more(${$eml->{hdr}});
649 }
650
651 # n.b. this is sorted to be after any emit_eml_new ops
652 sub emit_rfc822_text {
653         my ($self, $k, undef, $bref) = @_;
654         $self->msg_more(" $k {".length($$bref)."}\r\n");
655         $self->msg_more($$bref);
656 }
657
658 sub emit_bodystructure {
659         my ($self, undef, undef, undef, $eml) = @_;
660         $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
661 }
662
663 sub emit_body {
664         my ($self, undef, undef, undef, $eml) = @_;
665         $self->msg_more(' BODY '.fetch_body($eml));
666 }
667
668 # set $eml once ($_[4] == $eml, $_[3] == $bref)
669 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
670
671 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
672 sub to_crlf_full {
673         ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
674         ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
675 }
676
677 sub op_crlf_bref { to_crlf_full($_[3]) }
678
679 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
680
681 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
682
683 sub uid_clamp ($$$) {
684         my ($self, $beg, $end) = @_;
685         my $uid_min = $self->{uid_base} + 1;
686         my $uid_end = $uid_min + UID_SLICE - 1;
687         $$beg = $uid_min if $$beg < $uid_min;
688         $$end = $uid_end if $$end > $uid_end;
689 }
690
691 sub range_step ($$) {
692         my ($self, $range_csv) = @_;
693         my ($beg, $end, $range);
694         if ($$range_csv =~ s/\A([^,]+),//) {
695                 $range = $1;
696         } else {
697                 $range = $$range_csv;
698                 $$range_csv = undef;
699         }
700         my $uid_base = $self->{uid_base};
701         my $uid_end = $uid_base + UID_SLICE;
702         if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
703                 ($beg, $end) = ($1 + 0, $2 + 0);
704                 uid_clamp($self, \$beg, \$end);
705         } elsif ($range =~ /\A([0-9]+):\*\z/) {
706                 $beg = $1 + 0;
707                 $end = $self->{ibx}->over->max;
708                 $end = $uid_end if $end > $uid_end;
709                 $beg = $end if $beg > $end;
710                 uid_clamp($self, \$beg, \$end);
711         } elsif ($range =~ /\A[0-9]+\z/) {
712                 $beg = $end = $range + 0;
713                 # just let the caller do an out-of-range query if a single
714                 # UID is out-of-range
715                 ++$beg if ($beg <= $uid_base || $end > $uid_end);
716         } else {
717                 return 'BAD fetch range';
718         }
719         [ $beg, $end, $$range_csv ];
720 }
721
722 sub refill_range ($$$) {
723         my ($self, $msgs, $range_info) = @_;
724         my ($beg, $end, $range_csv) = @$range_info;
725         if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
726                 $range_info->[0] = $msgs->[-1]->{num} + 1;
727                 return;
728         }
729         return 'OK Fetch done' if !$range_csv;
730         my $next_range = range_step($self, \$range_csv);
731         return $next_range if !ref($next_range); # error
732         @$range_info = @$next_range;
733         undef; # keep looping
734 }
735
736 sub fetch_blob { # long_response
737         my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
738         while (!@$msgs) { # rare
739                 if (my $end = refill_range($self, $msgs, $range_info)) {
740                         $self->write(\"$tag $end\r\n");
741                         return;
742                 }
743         }
744         uo2m_extend($self, $msgs->[-1]->{num});
745         git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
746                         \&fetch_blob_cb, \@_);
747 }
748
749 sub fetch_smsg { # long_response
750         my ($self, $tag, $msgs, $range_info, $ops) = @_;
751         while (!@$msgs) { # rare
752                 if (my $end = refill_range($self, $msgs, $range_info)) {
753                         $self->write(\"$tag $end\r\n");
754                         return;
755                 }
756         }
757         uo2m_extend($self, $msgs->[-1]->{num});
758         fetch_run_ops($self, $_, undef, $ops) for @$msgs;
759         @$msgs = ();
760         1; # more
761 }
762
763 sub refill_uids ($$$;$) {
764         my ($self, $uids, $range_info, $sql) = @_;
765         my ($beg, $end, $range_csv) = @$range_info;
766         my $over = $self->{ibx}->over;
767         while (1) {
768                 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
769                         $range_info->[0] = $uids->[-1] + 1; # update $beg
770                         return;
771                 } elsif (!$range_csv) {
772                         return 0;
773                 } else {
774                         my $next_range = range_step($self, \$range_csv);
775                         return $next_range if !ref($next_range); # error
776                         ($beg, $end, $range_csv) = @$range_info = @$next_range;
777                         # continue looping
778                 }
779         }
780 }
781
782 sub fetch_uid { # long_response
783         my ($self, $tag, $uids, $range_info, $ops) = @_;
784         if (defined(my $err = refill_uids($self, $uids, $range_info))) {
785                 $err ||= 'OK Fetch done';
786                 $self->write("$tag $err\r\n");
787                 return;
788         }
789         my $adj = $self->{uid_base} + 1;
790         my $uo2m = uo2m_extend($self, $uids->[-1]);
791         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
792         my ($i, $k);
793         for (@$uids) {
794                 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
795                 for ($i = 0; $i < @$ops;) {
796                         $k = $ops->[$i++];
797                         $ops->[$i++]->($self, $k);
798                 }
799                 $self->msg_more(")\r\n");
800         }
801         @$uids = ();
802         1; # more
803 }
804
805 sub cmd_status ($$$;@) {
806         my ($self, $tag, $mailbox, @items) = @_;
807         return "$tag BAD no items\r\n" if !scalar(@items);
808         ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
809                 return "$tag BAD invalid args\r\n";
810         my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
811         return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
812         my @it;
813         for my $it (@items) {
814                 $it = uc($it);
815                 push @it, $it;
816                 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
817                         push @it, $exists;
818                 } elsif ($it eq 'UIDNEXT') {
819                         push @it, $uidnext;
820                 } elsif ($it eq 'UIDVALIDITY') {
821                         push @it, $ibx->{uidvalidity};
822                 } else {
823                         return "$tag BAD invalid item\r\n";
824                 }
825         }
826         return "$tag BAD no items\r\n" if !@it;
827         "* STATUS $mailbox (".join(' ', @it).")\r\n" .
828         "$tag OK Status done\r\n";
829 }
830
831 my %patmap = ('*' => '.*', '%' => '[^\.]*');
832 sub cmd_list ($$$$) {
833         my ($self, $tag, $refname, $wildcard) = @_;
834         my $l = $self->{imapd}->{inboxlist};
835         if ($refname eq '' && $wildcard eq '') {
836                 # request for hierarchy delimiter
837                 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
838         } elsif ($refname ne '' || $wildcard ne '*') {
839                 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
840                 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
841         }
842         \(join('', @$l, "$tag OK List done\r\n"));
843 }
844
845 sub cmd_lsub ($$$$) {
846         my (undef, $tag) = @_; # same args as cmd_list
847         "$tag OK Lsub done\r\n";
848 }
849
850 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
851         my ($p, $all) = @_;
852         my ($eml, undef, $idx) = @$p;
853         if ($idx && lc($eml->ct->{type}) eq 'multipart') {
854                 $eml->{imap_bdy} = $eml->{bdy} // \'';
855         }
856         $all->{$idx} = $eml; # $idx => Eml
857 }
858
859 # prepares an index for BODY[$SECTION_IDX] fetches
860 sub eml_body_idx ($$) {
861         my ($eml, $section_idx) = @_;
862         my $idx = $eml->{imap_all_parts} //= do {
863                 my $all = {};
864                 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
865                 # top-level of multipart, BODY[0] not allowed (nz-number)
866                 delete $all->{0};
867                 $all;
868         };
869         $idx->{$section_idx};
870 }
871
872 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
873 sub partial_body {
874         my ($eml, $section_idx, $section_name) = @_;
875         if (defined $section_idx) {
876                 $eml = eml_body_idx($eml, $section_idx) or return;
877         }
878         if (defined $section_name) {
879                 if ($section_name eq 'MIME') {
880                         # RFC 3501 6.4.5 states:
881                         #       The MIME part specifier MUST be prefixed
882                         #       by one or more numeric part specifiers
883                         return unless defined $section_idx;
884                         return $eml->header_obj->as_string . "\r\n";
885                 }
886                 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
887                 $eml = PublicInbox::Eml->new($$bdy);
888                 if ($section_name eq 'TEXT') {
889                         return $eml->body_raw;
890                 } elsif ($section_name eq 'HEADER') {
891                         return $eml->header_obj->as_string . "\r\n";
892                 } else {
893                         die "BUG: bad section_name=$section_name";
894                 }
895         }
896         ${$eml->{bdy} // $eml->{imap_bdy} // \''};
897 }
898
899 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
900 # to avoid OOM with malicious users
901 sub hdrs_regexp ($) {
902         my ($hdrs) = @_;
903         my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
904         qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
905                 # continuation lines:
906                 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
907                 /ismx;
908 }
909
910 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
911 sub partial_hdr_not {
912         my ($eml, $section_idx, $hdrs_re) = @_;
913         if (defined $section_idx) {
914                 $eml = eml_body_idx($eml, $section_idx) or return;
915         }
916         my $str = $eml->header_obj->as_string;
917         $str =~ s/$hdrs_re//g;
918         $str =~ s/(?<!\r)\n/\r\n/sg;
919         $str .= "\r\n";
920 }
921
922 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
923 sub partial_hdr_get {
924         my ($eml, $section_idx, $hdrs_re) = @_;
925         if (defined $section_idx) {
926                 $eml = eml_body_idx($eml, $section_idx) or return;
927         }
928         my $str = $eml->header_obj->as_string;
929         $str = join('', ($str =~ m/($hdrs_re)/g));
930         $str =~ s/(?<!\r)\n/\r\n/sg;
931         $str .= "\r\n";
932 }
933
934 sub partial_prepare ($$$$) {
935         my ($need, $partial, $want, $att) = @_;
936
937         # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
938         # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
939         return unless $att =~ /\ABODY\[/s;
940         until (rindex($att, ']') >= 0) {
941                 my $next = shift @$want or return;
942                 $att .= ' ' . uc($next);
943         }
944         if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
945                         (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
946                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
947                 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
948                 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
949         } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
950                                 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
951                                 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
952                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
953                 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
954                                                 : \&partial_hdr_get,
955                                                 $1, undef, $4, $5 ];
956                 $tmp->[2] = hdrs_regexp($3);
957
958                 # don't emit CRLF_HDR instruction, here, partial_hdr_*
959                 # will do CRLF conversion with only the extracted result
960                 # and not waste time converting lines we don't care about.
961                 $$need |= EML_HDR;
962         } else {
963                 undef;
964         }
965 }
966
967 sub partial_emit ($$$) {
968         my ($self, $partial, $eml) = @_;
969         for (@$partial) {
970                 my ($k, $cb, @args) = @$_;
971                 my ($offset, $len) = splice(@args, -2);
972                 # $cb is partial_body|partial_hdr_get|partial_hdr_not
973                 my $str = $cb->($eml, @args) // '';
974                 if (defined $offset) {
975                         if (defined $len) {
976                                 $str = substr($str, $offset, $len);
977                                 $k =~ s/\.$len>\z/>/ or warn
978 "BUG: unable to remove `.$len>' from `$k'";
979                         } else {
980                                 $str = substr($str, $offset);
981                                 $len = length($str);
982                         }
983                 } else {
984                         $len = length($str);
985                 }
986                 $self->msg_more(" $k {$len}\r\n");
987                 $self->msg_more($str);
988         }
989 }
990
991 sub fetch_compile ($) {
992         my ($want) = @_;
993         if ($want->[0] =~ s/\A\(//s) {
994                 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
995         }
996         my (%partial, %seen, @op);
997         my $need = 0;
998         while (defined(my $att = shift @$want)) {
999                 $att = uc($att);
1000                 next if $att eq 'UID'; # always returned
1001                 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1002                 my $x = $FETCH_ATT{$att};
1003                 if ($x) {
1004                         while (my ($k, $fl_cb) = each %$x) {
1005                                 next if $seen{$k}++;
1006                                 $need |= $fl_cb->[0];
1007                                 push @op, [ @$fl_cb, $k ];
1008                         }
1009                 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1010                         return "BAD param: $att";
1011                 }
1012         }
1013         my @r;
1014
1015         # stabilize partial order for consistency and ease-of-debugging:
1016         if (scalar keys %partial) {
1017                 $need |= NEED_BLOB;
1018                 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1019         }
1020
1021         push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1022
1023         # do we need CRLF conversion?
1024         if ($need & CRLF_BREF) {
1025                 push @op, $OP_CRLF_BREF;
1026         } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1027                 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1028                         push @op, $OP_CRLF_BREF;
1029                 } elsif ($need & CRLF_HDR) {
1030                         push @op, $OP_CRLF_HDR;
1031                 } else {
1032                         push @op, $OP_CRLF_BDY;
1033                 }
1034         }
1035
1036         $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1037                 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1038
1039         # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1040         use sort 'stable'; # makes output more consistent
1041         $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1042         @r;
1043 }
1044
1045 sub cmd_uid_fetch ($$$$;@) {
1046         my ($self, $tag, $range_csv, @want) = @_;
1047         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1048         my ($cb, $ops, $partial) = fetch_compile(\@want);
1049         return "$tag $cb\r\n" unless $ops;
1050
1051         # cb is one of fetch_blob, fetch_smsg, fetch_uid
1052         $range_csv = 'bad' if $range_csv !~ $valid_range;
1053         my $range_info = range_step($self, \$range_csv);
1054         return "$tag $range_info\r\n" if !ref($range_info);
1055         uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1056         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1057 }
1058
1059 sub cmd_fetch ($$$$;@) {
1060         my ($self, $tag, $range_csv, @want) = @_;
1061         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1062         my ($cb, $ops, $partial) = fetch_compile(\@want);
1063         return "$tag $cb\r\n" unless $ops;
1064
1065         # cb is one of fetch_blob, fetch_smsg, fetch_uid
1066         $range_csv = 'bad' if $range_csv !~ $valid_range;
1067         msn_to_uid_range(msn2uid($self), $range_csv);
1068         my $range_info = range_step($self, \$range_csv);
1069         return "$tag $range_info\r\n" if !ref($range_info);
1070         uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1071         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1072 }
1073
1074 sub msn_convert ($$) {
1075         my ($self, $uids) = @_;
1076         my $adj = $self->{uid_base} + 1;
1077         my $uo2m = uo2m_extend($self, $uids->[-1]);
1078         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1079         $_ = $uo2m->[$_ - $adj] for @$uids;
1080 }
1081
1082 sub search_uid_range { # long_response
1083         my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1084         my $uids = [];
1085         if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1086                 $err ||= 'OK Search done';
1087                 $self->write("\r\n$tag $err\r\n");
1088                 return;
1089         }
1090         msn_convert($self, $uids) if $want_msn;
1091         $self->msg_more(join(' ', '', @$uids));
1092         1; # more
1093 }
1094
1095 sub date_search {
1096         my ($q, $k, $d) = @_;
1097         my $sql = $q->{sql};
1098
1099         # Date: header
1100         if ($k eq 'SENTON') {
1101                 my $end = $d + 86399; # no leap day...
1102                 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1103                 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1104                 $q->{xap} .= " dt:$da..$db";
1105                 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1106         } elsif ($k eq 'SENTBEFORE') {
1107                 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1108                 $$sql .= " AND ds <= $d" if defined($sql);
1109         } elsif ($k eq 'SENTSINCE') {
1110                 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1111                 $$sql .= " AND ds >= $d" if defined($sql);
1112
1113         # INTERNALDATE (Received)
1114         } elsif ($k eq 'ON') {
1115                 my $end = $d + 86399; # no leap day...
1116                 $q->{xap} .= " ts:$d..$end";
1117                 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1118         } elsif ($k eq 'BEFORE') {
1119                 $q->{xap} .= " ts:..$d";
1120                 $$sql .= " AND ts <= $d" if defined($sql);
1121         } elsif ($k eq 'SINCE') {
1122                 $q->{xap} .= " ts:$d..";
1123                 $$sql .= " AND ts >= $d" if defined($sql);
1124         } else {
1125                 die "BUG: $k not recognized";
1126         }
1127 }
1128
1129 # IMAP to Xapian search key mapping
1130 my %I2X = (
1131         SUBJECT => 's:',
1132         BODY => 'b:',
1133         FROM => 'f:',
1134         TEXT => '', # n.b. does not include all headers
1135         TO => 't:',
1136         CC => 'c:',
1137         # BCC => 'bcc:', # TODO
1138         # KEYWORD # TODO ? dfpre,dfpost,...
1139 );
1140
1141 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1142 # which gets silly expensive.  We only allow the headers we already index.
1143 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1144
1145 sub xap_append ($$$$) {
1146         my ($q, $rest, $k, $xk) = @_;
1147         delete $q->{sql}; # can't use over.sqlite3
1148         defined(my $arg = shift @$rest) or return "BAD $k no arg";
1149
1150         # AFAIK Xapian can't handle [*"] in probabilistic terms
1151         $arg =~ tr/*"//d;
1152         ${$q->{xap}} .= qq[ $xk"$arg"];
1153         undef;
1154 }
1155
1156 sub parse_query ($$) {
1157         my ($self, $rest) = @_;
1158         if (uc($rest->[0]) eq 'CHARSET') {
1159                 shift @$rest;
1160                 defined(my $c = shift @$rest) or return 'BAD missing charset';
1161                 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
1162         }
1163         my $q = PublicInbox::IMAPsearchqp::parse($self, join(' ', @$rest));
1164         if (ref($q)) {
1165                 my $max = $self->{ibx}->over->max;
1166                 my $beg = 1;
1167                 uid_clamp($self, \$beg, \$max);
1168                 $q->{range_info} = [ $beg, $max ];
1169         }
1170         $q;
1171 }
1172
1173 sub refill_xap ($$$$) {
1174         my ($self, $uids, $range_info, $q) = @_;
1175         my ($beg, $end) = @$range_info;
1176         my $srch = $self->{ibx}->search;
1177         my $opt = { mset => 2, limit => 1000 };
1178         my $nshard = $srch->{nshard} // 1;
1179         while (1) {
1180                 my $mset = $srch->query("$q uid:$beg..$end", $opt);
1181                 @$uids = map { mdocid($nshard, $_) } $mset->items;
1182                 if (@$uids) {
1183                         $range_info->[0] = $uids->[-1] + 1; # update $beg
1184                         return;
1185                 } else { # all done
1186                         return 0;
1187                 }
1188         }
1189 }
1190
1191 sub search_xap_range { # long_response
1192         my ($self, $tag, $q, $range_info, $want_msn) = @_;
1193         my $uids = [];
1194         if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1195                 $err ||= 'OK Search done';
1196                 $self->write("\r\n$tag $err\r\n");
1197                 return;
1198         }
1199         msn_convert($self, $uids) if $want_msn;
1200         $self->msg_more(join(' ', '', @$uids));
1201         1; # more
1202 }
1203
1204 sub search_common {
1205         my ($self, $tag, $rest, $want_msn) = @_;
1206         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1207         my $q = parse_query($self, $rest);
1208         return "$tag $q\r\n" if !ref($q);
1209         my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1210         if (!scalar(keys %$q)) { # overview.sqlite3
1211                 $self->msg_more('* SEARCH');
1212                 long_response($self, \&search_uid_range,
1213                                 $tag, $sql, $range_info, $want_msn);
1214         } elsif ($q = $q->{xap}) {
1215                 $self->{ibx}->search or
1216                         return "$tag BAD search not available for mailbox\r\n";
1217                 $self->msg_more('* SEARCH');
1218                 long_response($self, \&search_xap_range,
1219                                 $tag, $q, $range_info, $want_msn);
1220         } else {
1221                 "$tag BAD Error\r\n";
1222         }
1223 }
1224
1225 sub cmd_uid_search ($$$;) {
1226         my ($self, $tag) = splice(@_, 0, 2);
1227         search_common($self, $tag, \@_);
1228 }
1229
1230 sub cmd_search ($$$;) {
1231         my ($self, $tag) = splice(@_, 0, 2);
1232         search_common($self, $tag, \@_, 1);
1233 }
1234
1235 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1236         my ($cb, $argc) = @_;
1237         my $tot = prototype $cb;
1238         my ($nreq, undef) = split(';', $tot);
1239         $nreq = ($nreq =~ tr/$//) - 1;
1240         $tot = ($tot =~ tr/$//) - 1;
1241         ($argc <= $tot && $argc >= $nreq);
1242 }
1243
1244 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1245 sub process_line ($$) {
1246         my ($self, $l) = @_;
1247
1248         # TODO: IMAP allows literals for big requests to upload messages
1249         # (which we don't support) but maybe some big search queries use it.
1250         # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1251         my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1252         pop(@args) if (@args && !defined($args[-1]));
1253         if (@args && uc($req) eq 'UID') {
1254                 $req .= "_".(shift @args);
1255         }
1256         my $res = eval {
1257                 if (defined(my $idle_tag = $self->{-idle_tag})) {
1258                         (uc($tag // '') eq 'DONE' && !defined($req)) ?
1259                                 idle_done($self, $tag) :
1260                                 "$idle_tag BAD expected DONE\r\n";
1261                 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1262                         if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1263                                 # preserve user-supplied quotes for search
1264                                 (undef, @args) = split(/ search /i, $l, 2);
1265                         }
1266                         $cmd->($self, $tag, @args);
1267                 } else { # this is weird
1268                         auth_challenge_ok($self) //
1269                                         ($tag // '*') .
1270                                         ' BAD Error in IMAP command '.
1271                                         ($req // '(???)').
1272                                         ": Unknown command\r\n";
1273                 }
1274         };
1275         my $err = $@;
1276         if ($err && $self->{sock}) {
1277                 $l =~ s/\r?\n//s;
1278                 err($self, 'error from: %s (%s)', $l, $err);
1279                 $tag //= '*';
1280                 $res = "$tag BAD program fault - command not performed\r\n";
1281         }
1282         return 0 unless defined $res;
1283         $self->write($res);
1284 }
1285
1286 sub long_step {
1287         my ($self) = @_;
1288         # wbuf is unset or empty, here; {long} may add to it
1289         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1290         my $more = eval { $cb->($self, @args) };
1291         if ($@ || !$self->{sock}) { # something bad happened...
1292                 delete $self->{long_cb};
1293                 my $elapsed = now() - $t0;
1294                 if ($@) {
1295                         err($self,
1296                             "%s during long response[$fd] - %0.6f",
1297                             $@, $elapsed);
1298                 }
1299                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1300                 $self->close;
1301         } elsif ($more) { # $self->{wbuf}:
1302                 $self->update_idle_time;
1303
1304                 # control passed to $more may be a GitAsyncCat object
1305                 requeue_once($self) if !ref($more);
1306         } else { # all done!
1307                 delete $self->{long_cb};
1308                 my $elapsed = now() - $t0;
1309                 my $fd = fileno($self->{sock});
1310                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1311                 my $wbuf = $self->{wbuf}; # do NOT autovivify
1312
1313                 $self->requeue unless $wbuf && @$wbuf;
1314         }
1315 }
1316
1317 sub err ($$;@) {
1318         my ($self, $fmt, @args) = @_;
1319         printf { $self->{imapd}->{err} } $fmt."\n", @args;
1320 }
1321
1322 sub out ($$;@) {
1323         my ($self, $fmt, @args) = @_;
1324         printf { $self->{imapd}->{out} } $fmt."\n", @args;
1325 }
1326
1327 sub long_response ($$;@) {
1328         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1329
1330         my $sock = $self->{sock} or return;
1331         # make sure we disable reading during a long response,
1332         # clients should not be sending us stuff and making us do more
1333         # work while we are stream a response to them
1334         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1335         long_step($self); # kick off!
1336         undef;
1337 }
1338
1339 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1340 sub event_step {
1341         my ($self) = @_;
1342
1343         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1344
1345         $self->update_idle_time;
1346         # only read more requests if we've drained the write buffer,
1347         # otherwise we can be buffering infinitely w/o backpressure
1348
1349         my $rbuf = $self->{rbuf} // \(my $x = '');
1350         my $line = index($$rbuf, "\n");
1351         while ($line < 0) {
1352                 if (length($$rbuf) >= LINE_MAX) {
1353                         $self->write(\"\* BAD request too long\r\n");
1354                         return $self->close;
1355                 }
1356                 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1357                                 return uo2m_hibernate($self);
1358                 $line = index($$rbuf, "\n");
1359         }
1360         $line = substr($$rbuf, 0, $line + 1, '');
1361         $line =~ s/\r?\n\z//s;
1362         return $self->close if $line =~ /[[:cntrl:]]/s;
1363         my $t0 = now();
1364         my $fd = fileno($self->{sock});
1365         my $r = eval { process_line($self, $line) };
1366         my $pending = $self->{wbuf} ? ' pending' : '';
1367         out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1368
1369         return $self->close if $r < 0;
1370         $self->rbuf_idle($rbuf);
1371         $self->update_idle_time;
1372
1373         # maybe there's more pipelined data, or we'll have
1374         # to register it for socket-readiness notifications
1375         $self->requeue unless $pending;
1376 }
1377
1378 sub compressed { undef }
1379
1380 sub zflush {} # overridden by IMAPdeflate
1381
1382 # RFC 4978
1383 sub cmd_compress ($$$) {
1384         my ($self, $tag, $alg) = @_;
1385         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1386         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1387
1388         # CRIME made TLS compression obsolete
1389         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1390
1391         PublicInbox::IMAPdeflate->enable($self, $tag);
1392         $self->requeue;
1393         undef
1394 }
1395
1396 sub cmd_starttls ($$) {
1397         my ($self, $tag) = @_;
1398         my $sock = $self->{sock} or return;
1399         if ($sock->can('stop_SSL') || $self->compressed) {
1400                 return "$tag BAD TLS or compression already enabled\r\n";
1401         }
1402         my $opt = $self->{imapd}->{accept_tls} or
1403                 return "$tag BAD can not initiate TLS negotiation\r\n";
1404         $self->write(\"$tag OK begin TLS negotiation now\r\n");
1405         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1406         $self->requeue if PublicInbox::DS::accept_tls_step($self);
1407         undef;
1408 }
1409
1410 # for graceful shutdown in PublicInbox::Daemon:
1411 sub busy {
1412         my ($self, $now) = @_;
1413         if (defined($self->{-idle_tag})) {
1414                 $self->write(\"* BYE server shutting down\r\n");
1415                 return; # not busy anymore
1416         }
1417         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1418 }
1419
1420 sub close {
1421         my ($self) = @_;
1422         if (my $ibx = delete $self->{ibx}) {
1423                 stop_idle($self, $ibx);
1424         }
1425         $self->SUPER::close; # PublicInbox::DS::close
1426 }
1427
1428 # we're read-only, so SELECT and EXAMINE do the same thing
1429 no warnings 'once';
1430 *cmd_select = \&cmd_examine;
1431
1432 package PublicInbox::IMAP_preauth;
1433 our @ISA = qw(PublicInbox::IMAP);
1434
1435 sub logged_in { 0 }
1436
1437 1;