]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
imap: refill_xap: remove needless loop
[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{qw(uid_base uo2m)};
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         defined(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         delete $self->{uo2m};
419
420         # XXX: do we need this? RFC 5162/7162
421         my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
422         $self->{ibx} = $ibx;
423         $ret .= <<EOF;
424 * $exists EXISTS\r
425 * $exists RECENT\r
426 * FLAGS (\\Seen)\r
427 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
428 * OK [UNSEEN $exists]\r
429 * OK [UIDNEXT $uidnext]\r
430 * OK [UIDVALIDITY $ibx->{uidvalidity}]\r
431 $tag OK [READ-ONLY] EXAMINE/SELECT done\r
432 EOF
433 }
434
435 sub _esc ($) {
436         my ($v) = @_;
437         if (!defined($v)) {
438                 'NIL';
439         } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
440                 '{' . length($v) . "}\r\n" . $v;
441         } else { # quoted string
442                 qq{"$v"}
443         }
444 }
445
446 sub addr_envelope ($$;$) {
447         my ($eml, $x, $y) = @_;
448         my $v = $eml->header_raw($x) //
449                 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
450
451         my @x = $Address->parse($v) or return 'NIL';
452         '(' . join('',
453                 map { '(' . join(' ',
454                                 _esc($_->name), 'NIL',
455                                 _esc($_->user), _esc($_->host)
456                         ) . ')'
457                 } @x) .
458         ')';
459 }
460
461 sub eml_envelope ($) {
462         my ($eml) = @_;
463         '(' . join(' ',
464                 _esc($eml->header_raw('Date')),
465                 _esc($eml->header_raw('Subject')),
466                 addr_envelope($eml, 'From'),
467                 addr_envelope($eml, 'Sender', 'From'),
468                 addr_envelope($eml, 'Reply-To', 'From'),
469                 addr_envelope($eml, 'To'),
470                 addr_envelope($eml, 'Cc'),
471                 addr_envelope($eml, 'Bcc'),
472                 _esc($eml->header_raw('In-Reply-To')),
473                 _esc($eml->header_raw('Message-ID')),
474         ) . ')';
475 }
476
477 sub _esc_hash ($) {
478         my ($hash) = @_;
479         if ($hash && scalar keys %$hash) {
480                 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
481                 '(' . join(' ', map { _esc($_) } @$hash) . ')';
482         } else {
483                 'NIL';
484         }
485 }
486
487 sub body_disposition ($) {
488         my ($eml) = @_;
489         my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
490         $cd = parse_content_disposition($cd);
491         my $buf = '('._esc($cd->{type});
492         $buf .= ' ' . _esc_hash(delete $cd->{attributes});
493         $buf .= ')';
494 }
495
496 sub body_leaf ($$;$) {
497         my ($eml, $structure, $hold) = @_;
498         my $buf = '';
499         $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
500                 $buf .= eml_envelope($eml). ' ';
501         my $ct = $eml->ct;
502         $buf .= '('._esc($ct->{type}).' ';
503         $buf .= _esc($ct->{subtype});
504         $buf .= ' ' . _esc_hash(delete $ct->{attributes});
505         $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
506         $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
507         my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
508         $buf .= ' ' . _esc($cte);
509         $buf .= ' ' . $eml->{imap_body_len};
510         $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
511
512         # for message/(rfc822|global|news), $hold[0] should have envelope
513         $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
514
515         if ($structure) {
516                 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
517                 $buf .= ' '. body_disposition($eml);
518                 $buf .= ' '._esc($eml->header_raw('Content-Language'));
519                 $buf .= ' '._esc($eml->header_raw('Content-Location'));
520         }
521         $buf .= ')';
522 }
523
524 sub body_parent ($$$) {
525         my ($eml, $structure, $hold) = @_;
526         my $ct = $eml->ct;
527         my $type = lc($ct->{type});
528         if ($type eq 'multipart') {
529                 my $buf = '(';
530                 $buf .= @$hold ? join('', @$hold) : 'NIL';
531                 $buf .= ' '._esc($ct->{subtype});
532                 if ($structure) {
533                         $buf .= ' '._esc_hash(delete $ct->{attributes});
534                         $buf .= ' '.body_disposition($eml);
535                         $buf .= ' '._esc($eml->header_raw('Content-Language'));
536                         $buf .= ' '._esc($eml->header_raw('Content-Location'));
537                 }
538                 $buf .= ')';
539                 @$hold = ($buf);
540         } else { # message/(rfc822|global|news)
541                 @$hold = (body_leaf($eml, $structure, $hold));
542         }
543 }
544
545 # this is gross, but we need to process the parent part AFTER
546 # the child parts are done
547 sub bodystructure_prep {
548         my ($p, $q) = @_;
549         my ($eml, $depth) = @$p; # ignore idx
550         # set length here, as $eml->{bdy} gets deleted for message/rfc822
551         $eml->{imap_body_len} = length($eml->body_raw);
552         push @$q, $eml, $depth;
553 }
554
555 # for FETCH BODY and FETCH BODYSTRUCTURE
556 sub fetch_body ($;$) {
557         my ($eml, $structure) = @_;
558         my @q;
559         $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
560         my $cur_depth = 0;
561         my @hold;
562         do {
563                 my ($part, $depth) = splice(@q, -2);
564                 my $is_mp_parent = $depth == ($cur_depth - 1);
565                 $cur_depth = $depth;
566
567                 if ($is_mp_parent) {
568                         body_parent($part, $structure, \@hold);
569                 } else {
570                         unshift @hold, body_leaf($part, $structure);
571                 }
572         } while (@q);
573         join('', @hold);
574 }
575
576 sub requeue_once ($) {
577         my ($self) = @_;
578         # COMPRESS users all share the same DEFLATE context.
579         # Flush it here to ensure clients don't see
580         # each other's data
581         $self->zflush;
582
583         # no recursion, schedule another call ASAP,
584         # but only after all pending writes are done.
585         # autovivify wbuf:
586         my $new_size = push(@{$self->{wbuf}}, \&long_step);
587
588         # wbuf may be populated by $cb, no need to rearm if so:
589         $self->requeue if $new_size == 1;
590 }
591
592 sub fetch_run_ops {
593         my ($self, $smsg, $bref, $ops, $partial) = @_;
594         my $uid = $smsg->{num};
595         $self->msg_more('* '.uid2msn($self, $uid)." FETCH (UID $uid");
596         my ($eml, $k);
597         for (my $i = 0; $i < @$ops;) {
598                 $k = $ops->[$i++];
599                 $ops->[$i++]->($self, $k, $smsg, $bref, $eml);
600         }
601         partial_emit($self, $partial, $eml) if $partial;
602         $self->msg_more(")\r\n");
603 }
604
605 sub fetch_blob_cb { # called by git->cat_async via git_async_cat
606         my ($bref, $oid, $type, $size, $fetch_arg) = @_;
607         my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
608         my $smsg = shift @$msgs or die 'BUG: no smsg';
609         if (!defined($oid)) {
610                 # it's possible to have TOCTOU if an admin runs
611                 # public-inbox-(edit|purge), just move onto the next message
612                 return requeue_once($self);
613         } else {
614                 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
615         }
616         fetch_run_ops($self, $smsg, $bref, $ops, $partial);
617         requeue_once($self);
618 }
619
620 sub emit_rfc822 {
621         my ($self, $k, undef, $bref) = @_;
622         $self->msg_more(" $k {" . length($$bref)."}\r\n");
623         $self->msg_more($$bref);
624 }
625
626 # Mail::IMAPClient::message_string cares about this by default,
627 # (->Ignoresizeerrors attribute).  Admins are encouraged to
628 # --reindex for IMAP support, anyways.
629 sub emit_rfc822_size {
630         my ($self, $k, $smsg) = @_;
631         $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
632 }
633
634 sub emit_internaldate {
635         my ($self, undef, $smsg) = @_;
636         $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
637 }
638
639 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
640
641 sub emit_envelope {
642         my ($self, undef, undef, undef, $eml) = @_;
643         $self->msg_more(' ENVELOPE '.eml_envelope($eml));
644 }
645
646 sub emit_rfc822_header {
647         my ($self, $k, undef, undef, $eml) = @_;
648         $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
649         $self->msg_more(${$eml->{hdr}});
650 }
651
652 # n.b. this is sorted to be after any emit_eml_new ops
653 sub emit_rfc822_text {
654         my ($self, $k, undef, $bref) = @_;
655         $self->msg_more(" $k {".length($$bref)."}\r\n");
656         $self->msg_more($$bref);
657 }
658
659 sub emit_bodystructure {
660         my ($self, undef, undef, undef, $eml) = @_;
661         $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
662 }
663
664 sub emit_body {
665         my ($self, undef, undef, undef, $eml) = @_;
666         $self->msg_more(' BODY '.fetch_body($eml));
667 }
668
669 # set $eml once ($_[4] == $eml, $_[3] == $bref)
670 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
671
672 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
673 sub to_crlf_full {
674         ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
675         ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
676 }
677
678 sub op_crlf_bref { to_crlf_full($_[3]) }
679
680 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
681
682 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
683
684 sub uid_clamp ($$$) {
685         my ($self, $beg, $end) = @_;
686         my $uid_min = $self->{uid_base} + 1;
687         my $uid_end = $uid_min + UID_SLICE - 1;
688         $$beg = $uid_min if $$beg < $uid_min;
689         $$end = $uid_end if $$end > $uid_end;
690 }
691
692 sub range_step ($$) {
693         my ($self, $range_csv) = @_;
694         my ($beg, $end, $range);
695         if ($$range_csv =~ s/\A([^,]+),//) {
696                 $range = $1;
697         } else {
698                 $range = $$range_csv;
699                 $$range_csv = undef;
700         }
701         my $uid_base = $self->{uid_base};
702         my $uid_end = $uid_base + UID_SLICE;
703         if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
704                 ($beg, $end) = ($1 + 0, $2 + 0);
705                 uid_clamp($self, \$beg, \$end);
706         } elsif ($range =~ /\A([0-9]+):\*\z/) {
707                 $beg = $1 + 0;
708                 $end = $self->{ibx}->over->max;
709                 $end = $uid_end if $end > $uid_end;
710                 $beg = $end if $beg > $end;
711                 uid_clamp($self, \$beg, \$end);
712         } elsif ($range =~ /\A[0-9]+\z/) {
713                 $beg = $end = $range + 0;
714                 # just let the caller do an out-of-range query if a single
715                 # UID is out-of-range
716                 ++$beg if ($beg <= $uid_base || $end > $uid_end);
717         } else {
718                 return 'BAD fetch range';
719         }
720         [ $beg, $end, $$range_csv ];
721 }
722
723 sub refill_range ($$$) {
724         my ($self, $msgs, $range_info) = @_;
725         my ($beg, $end, $range_csv) = @$range_info;
726         if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
727                 $range_info->[0] = $msgs->[-1]->{num} + 1;
728                 return;
729         }
730         return 'OK Fetch done' if !$range_csv;
731         my $next_range = range_step($self, \$range_csv);
732         return $next_range if !ref($next_range); # error
733         @$range_info = @$next_range;
734         undef; # keep looping
735 }
736
737 sub fetch_blob { # long_response
738         my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
739         while (!@$msgs) { # rare
740                 if (my $end = refill_range($self, $msgs, $range_info)) {
741                         $self->write(\"$tag $end\r\n");
742                         return;
743                 }
744         }
745         uo2m_extend($self, $msgs->[-1]->{num});
746         git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
747                         \&fetch_blob_cb, \@_);
748 }
749
750 sub fetch_smsg { # long_response
751         my ($self, $tag, $msgs, $range_info, $ops) = @_;
752         while (!@$msgs) { # rare
753                 if (my $end = refill_range($self, $msgs, $range_info)) {
754                         $self->write(\"$tag $end\r\n");
755                         return;
756                 }
757         }
758         uo2m_extend($self, $msgs->[-1]->{num});
759         fetch_run_ops($self, $_, undef, $ops) for @$msgs;
760         @$msgs = ();
761         1; # more
762 }
763
764 sub refill_uids ($$$;$) {
765         my ($self, $uids, $range_info, $sql) = @_;
766         my ($beg, $end, $range_csv) = @$range_info;
767         my $over = $self->{ibx}->over;
768         while (1) {
769                 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
770                         $range_info->[0] = $uids->[-1] + 1; # update $beg
771                         return;
772                 } elsif (!$range_csv) {
773                         return 0;
774                 } else {
775                         my $next_range = range_step($self, \$range_csv);
776                         return $next_range if !ref($next_range); # error
777                         ($beg, $end, $range_csv) = @$range_info = @$next_range;
778                         # continue looping
779                 }
780         }
781 }
782
783 sub fetch_uid { # long_response
784         my ($self, $tag, $uids, $range_info, $ops) = @_;
785         if (defined(my $err = refill_uids($self, $uids, $range_info))) {
786                 $err ||= 'OK Fetch done';
787                 $self->write("$tag $err\r\n");
788                 return;
789         }
790         my $adj = $self->{uid_base} + 1;
791         my $uo2m = uo2m_extend($self, $uids->[-1]);
792         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
793         my ($i, $k);
794         for (@$uids) {
795                 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
796                 for ($i = 0; $i < @$ops;) {
797                         $k = $ops->[$i++];
798                         $ops->[$i++]->($self, $k);
799                 }
800                 $self->msg_more(")\r\n");
801         }
802         @$uids = ();
803         1; # more
804 }
805
806 sub cmd_status ($$$;@) {
807         my ($self, $tag, $mailbox, @items) = @_;
808         return "$tag BAD no items\r\n" if !scalar(@items);
809         ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
810                 return "$tag BAD invalid args\r\n";
811         my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
812         return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
813         my @it;
814         for my $it (@items) {
815                 $it = uc($it);
816                 push @it, $it;
817                 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
818                         push @it, $exists;
819                 } elsif ($it eq 'UIDNEXT') {
820                         push @it, $uidnext;
821                 } elsif ($it eq 'UIDVALIDITY') {
822                         push @it, $ibx->{uidvalidity};
823                 } else {
824                         return "$tag BAD invalid item\r\n";
825                 }
826         }
827         return "$tag BAD no items\r\n" if !@it;
828         "* STATUS $mailbox (".join(' ', @it).")\r\n" .
829         "$tag OK Status done\r\n";
830 }
831
832 my %patmap = ('*' => '.*', '%' => '[^\.]*');
833 sub cmd_list ($$$$) {
834         my ($self, $tag, $refname, $wildcard) = @_;
835         my $l = $self->{imapd}->{inboxlist};
836         if ($refname eq '' && $wildcard eq '') {
837                 # request for hierarchy delimiter
838                 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
839         } elsif ($refname ne '' || $wildcard ne '*') {
840                 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
841                 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
842         }
843         \(join('', @$l, "$tag OK List done\r\n"));
844 }
845
846 sub cmd_lsub ($$$$) {
847         my (undef, $tag) = @_; # same args as cmd_list
848         "$tag OK Lsub done\r\n";
849 }
850
851 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
852         my ($p, $all) = @_;
853         my ($eml, undef, $idx) = @$p;
854         if ($idx && lc($eml->ct->{type}) eq 'multipart') {
855                 $eml->{imap_bdy} = $eml->{bdy} // \'';
856         }
857         $all->{$idx} = $eml; # $idx => Eml
858 }
859
860 # prepares an index for BODY[$SECTION_IDX] fetches
861 sub eml_body_idx ($$) {
862         my ($eml, $section_idx) = @_;
863         my $idx = $eml->{imap_all_parts} //= do {
864                 my $all = {};
865                 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
866                 # top-level of multipart, BODY[0] not allowed (nz-number)
867                 delete $all->{0};
868                 $all;
869         };
870         $idx->{$section_idx};
871 }
872
873 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
874 sub partial_body {
875         my ($eml, $section_idx, $section_name) = @_;
876         if (defined $section_idx) {
877                 $eml = eml_body_idx($eml, $section_idx) or return;
878         }
879         if (defined $section_name) {
880                 if ($section_name eq 'MIME') {
881                         # RFC 3501 6.4.5 states:
882                         #       The MIME part specifier MUST be prefixed
883                         #       by one or more numeric part specifiers
884                         return unless defined $section_idx;
885                         return $eml->header_obj->as_string . "\r\n";
886                 }
887                 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
888                 $eml = PublicInbox::Eml->new($$bdy);
889                 if ($section_name eq 'TEXT') {
890                         return $eml->body_raw;
891                 } elsif ($section_name eq 'HEADER') {
892                         return $eml->header_obj->as_string . "\r\n";
893                 } else {
894                         die "BUG: bad section_name=$section_name";
895                 }
896         }
897         ${$eml->{bdy} // $eml->{imap_bdy} // \''};
898 }
899
900 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
901 # to avoid OOM with malicious users
902 sub hdrs_regexp ($) {
903         my ($hdrs) = @_;
904         my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
905         qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
906                 # continuation lines:
907                 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
908                 /ismx;
909 }
910
911 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
912 sub partial_hdr_not {
913         my ($eml, $section_idx, $hdrs_re) = @_;
914         if (defined $section_idx) {
915                 $eml = eml_body_idx($eml, $section_idx) or return;
916         }
917         my $str = $eml->header_obj->as_string;
918         $str =~ s/$hdrs_re//g;
919         $str =~ s/(?<!\r)\n/\r\n/sg;
920         $str .= "\r\n";
921 }
922
923 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
924 sub partial_hdr_get {
925         my ($eml, $section_idx, $hdrs_re) = @_;
926         if (defined $section_idx) {
927                 $eml = eml_body_idx($eml, $section_idx) or return;
928         }
929         my $str = $eml->header_obj->as_string;
930         $str = join('', ($str =~ m/($hdrs_re)/g));
931         $str =~ s/(?<!\r)\n/\r\n/sg;
932         $str .= "\r\n";
933 }
934
935 sub partial_prepare ($$$$) {
936         my ($need, $partial, $want, $att) = @_;
937
938         # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
939         # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
940         return unless $att =~ /\ABODY\[/s;
941         until (rindex($att, ']') >= 0) {
942                 my $next = shift @$want or return;
943                 $att .= ' ' . uc($next);
944         }
945         if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
946                         (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
947                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
948                 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
949                 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
950         } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
951                                 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
952                                 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
953                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
954                 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
955                                                 : \&partial_hdr_get,
956                                                 $1, undef, $4, $5 ];
957                 $tmp->[2] = hdrs_regexp($3);
958
959                 # don't emit CRLF_HDR instruction, here, partial_hdr_*
960                 # will do CRLF conversion with only the extracted result
961                 # and not waste time converting lines we don't care about.
962                 $$need |= EML_HDR;
963         } else {
964                 undef;
965         }
966 }
967
968 sub partial_emit ($$$) {
969         my ($self, $partial, $eml) = @_;
970         for (@$partial) {
971                 my ($k, $cb, @args) = @$_;
972                 my ($offset, $len) = splice(@args, -2);
973                 # $cb is partial_body|partial_hdr_get|partial_hdr_not
974                 my $str = $cb->($eml, @args) // '';
975                 if (defined $offset) {
976                         if (defined $len) {
977                                 $str = substr($str, $offset, $len);
978                                 $k =~ s/\.$len>\z/>/ or warn
979 "BUG: unable to remove `.$len>' from `$k'";
980                         } else {
981                                 $str = substr($str, $offset);
982                                 $len = length($str);
983                         }
984                 } else {
985                         $len = length($str);
986                 }
987                 $self->msg_more(" $k {$len}\r\n");
988                 $self->msg_more($str);
989         }
990 }
991
992 sub fetch_compile ($) {
993         my ($want) = @_;
994         if ($want->[0] =~ s/\A\(//s) {
995                 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
996         }
997         my (%partial, %seen, @op);
998         my $need = 0;
999         while (defined(my $att = shift @$want)) {
1000                 $att = uc($att);
1001                 next if $att eq 'UID'; # always returned
1002                 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1003                 my $x = $FETCH_ATT{$att};
1004                 if ($x) {
1005                         while (my ($k, $fl_cb) = each %$x) {
1006                                 next if $seen{$k}++;
1007                                 $need |= $fl_cb->[0];
1008                                 push @op, [ @$fl_cb, $k ];
1009                         }
1010                 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1011                         return "BAD param: $att";
1012                 }
1013         }
1014         my @r;
1015
1016         # stabilize partial order for consistency and ease-of-debugging:
1017         if (scalar keys %partial) {
1018                 $need |= NEED_BLOB;
1019                 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1020         }
1021
1022         push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1023
1024         # do we need CRLF conversion?
1025         if ($need & CRLF_BREF) {
1026                 push @op, $OP_CRLF_BREF;
1027         } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1028                 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1029                         push @op, $OP_CRLF_BREF;
1030                 } elsif ($need & CRLF_HDR) {
1031                         push @op, $OP_CRLF_HDR;
1032                 } else {
1033                         push @op, $OP_CRLF_BDY;
1034                 }
1035         }
1036
1037         $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1038                 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1039
1040         # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1041         use sort 'stable'; # makes output more consistent
1042         $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1043         @r;
1044 }
1045
1046 sub cmd_uid_fetch ($$$$;@) {
1047         my ($self, $tag, $range_csv, @want) = @_;
1048         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1049         my ($cb, $ops, $partial) = fetch_compile(\@want);
1050         return "$tag $cb\r\n" unless $ops;
1051
1052         # cb is one of fetch_blob, fetch_smsg, fetch_uid
1053         $range_csv = 'bad' if $range_csv !~ $valid_range;
1054         my $range_info = range_step($self, \$range_csv);
1055         return "$tag $range_info\r\n" if !ref($range_info);
1056         uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1057         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1058 }
1059
1060 sub cmd_fetch ($$$$;@) {
1061         my ($self, $tag, $range_csv, @want) = @_;
1062         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1063         my ($cb, $ops, $partial) = fetch_compile(\@want);
1064         return "$tag $cb\r\n" unless $ops;
1065
1066         # cb is one of fetch_blob, fetch_smsg, fetch_uid
1067         $range_csv = 'bad' if $range_csv !~ $valid_range;
1068         msn_to_uid_range(msn2uid($self), $range_csv);
1069         my $range_info = range_step($self, \$range_csv);
1070         return "$tag $range_info\r\n" if !ref($range_info);
1071         uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1072         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1073 }
1074
1075 sub msn_convert ($$) {
1076         my ($self, $uids) = @_;
1077         my $adj = $self->{uid_base} + 1;
1078         my $uo2m = uo2m_extend($self, $uids->[-1]);
1079         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1080         $_ = $uo2m->[$_ - $adj] for @$uids;
1081 }
1082
1083 sub search_uid_range { # long_response
1084         my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1085         my $uids = [];
1086         if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1087                 $err ||= 'OK Search done';
1088                 $self->write("\r\n$tag $err\r\n");
1089                 return;
1090         }
1091         msn_convert($self, $uids) if $want_msn;
1092         $self->msg_more(join(' ', '', @$uids));
1093         1; # more
1094 }
1095
1096 sub date_search {
1097         my ($q, $k, $d) = @_;
1098         my $sql = $q->{sql};
1099
1100         # Date: header
1101         if ($k eq 'SENTON') {
1102                 my $end = $d + 86399; # no leap day...
1103                 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1104                 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1105                 $q->{xap} .= " dt:$da..$db";
1106                 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1107         } elsif ($k eq 'SENTBEFORE') {
1108                 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1109                 $$sql .= " AND ds <= $d" if defined($sql);
1110         } elsif ($k eq 'SENTSINCE') {
1111                 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1112                 $$sql .= " AND ds >= $d" if defined($sql);
1113
1114         # INTERNALDATE (Received)
1115         } elsif ($k eq 'ON') {
1116                 my $end = $d + 86399; # no leap day...
1117                 $q->{xap} .= " ts:$d..$end";
1118                 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1119         } elsif ($k eq 'BEFORE') {
1120                 $q->{xap} .= " ts:..$d";
1121                 $$sql .= " AND ts <= $d" if defined($sql);
1122         } elsif ($k eq 'SINCE') {
1123                 $q->{xap} .= " ts:$d..";
1124                 $$sql .= " AND ts >= $d" if defined($sql);
1125         } else {
1126                 die "BUG: $k not recognized";
1127         }
1128 }
1129
1130 # IMAP to Xapian search key mapping
1131 my %I2X = (
1132         SUBJECT => 's:',
1133         BODY => 'b:',
1134         FROM => 'f:',
1135         TEXT => '', # n.b. does not include all headers
1136         TO => 't:',
1137         CC => 'c:',
1138         # BCC => 'bcc:', # TODO
1139         # KEYWORD # TODO ? dfpre,dfpost,...
1140 );
1141
1142 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1143 # which gets silly expensive.  We only allow the headers we already index.
1144 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1145
1146 sub xap_append ($$$$) {
1147         my ($q, $rest, $k, $xk) = @_;
1148         delete $q->{sql}; # can't use over.sqlite3
1149         defined(my $arg = shift @$rest) or return "BAD $k no arg";
1150
1151         # AFAIK Xapian can't handle [*"] in probabilistic terms
1152         $arg =~ tr/*"//d;
1153         ${$q->{xap}} .= qq[ $xk"$arg"];
1154         undef;
1155 }
1156
1157 sub parse_query ($$) {
1158         my ($self, $query) = @_;
1159         my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1160         if (ref($q)) {
1161                 my $max = $self->{ibx}->over->max;
1162                 my $beg = 1;
1163                 uid_clamp($self, \$beg, \$max);
1164                 $q->{range_info} = [ $beg, $max ];
1165         }
1166         $q;
1167 }
1168
1169 sub refill_xap ($$$$) {
1170         my ($self, $uids, $range_info, $q) = @_;
1171         my ($beg, $end) = @$range_info;
1172         my $srch = $self->{ibx}->search;
1173         my $opt = { mset => 2, limit => 1000 };
1174         my $nshard = $srch->{nshard} // 1;
1175         my $mset = $srch->query("$q uid:$beg..$end", $opt);
1176         @$uids = map { mdocid($nshard, $_) } $mset->items;
1177         if (@$uids) {
1178                 $range_info->[0] = $uids->[-1] + 1; # update $beg
1179                 return; # possibly more
1180         }
1181         0; # all done
1182 }
1183
1184 sub search_xap_range { # long_response
1185         my ($self, $tag, $q, $range_info, $want_msn) = @_;
1186         my $uids = [];
1187         if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1188                 $err ||= 'OK Search done';
1189                 $self->write("\r\n$tag $err\r\n");
1190                 return;
1191         }
1192         msn_convert($self, $uids) if $want_msn;
1193         $self->msg_more(join(' ', '', @$uids));
1194         1; # more
1195 }
1196
1197 sub search_common {
1198         my ($self, $tag, $query, $want_msn) = @_;
1199         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1200         my $q = parse_query($self, $query);
1201         return "$tag $q\r\n" if !ref($q);
1202         my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1203         if (!scalar(keys %$q)) { # overview.sqlite3
1204                 $self->msg_more('* SEARCH');
1205                 long_response($self, \&search_uid_range,
1206                                 $tag, $sql, $range_info, $want_msn);
1207         } elsif ($q = $q->{xap}) {
1208                 $self->{ibx}->search or
1209                         return "$tag BAD search not available for mailbox\r\n";
1210                 $self->msg_more('* SEARCH');
1211                 long_response($self, \&search_xap_range,
1212                                 $tag, $q, $range_info, $want_msn);
1213         } else {
1214                 "$tag BAD Error\r\n";
1215         }
1216 }
1217
1218 sub cmd_uid_search ($$$) {
1219         my ($self, $tag, $query) = @_;
1220         search_common($self, $tag, $query);
1221 }
1222
1223 sub cmd_search ($$$;) {
1224         my ($self, $tag, $query) = @_;
1225         search_common($self, $tag, $query, 1);
1226 }
1227
1228 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1229         my ($cb, $argc) = @_;
1230         my $tot = prototype $cb;
1231         my ($nreq, undef) = split(';', $tot);
1232         $nreq = ($nreq =~ tr/$//) - 1;
1233         $tot = ($tot =~ tr/$//) - 1;
1234         ($argc <= $tot && $argc >= $nreq);
1235 }
1236
1237 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1238 sub process_line ($$) {
1239         my ($self, $l) = @_;
1240
1241         # TODO: IMAP allows literals for big requests to upload messages
1242         # (which we don't support) but maybe some big search queries use it.
1243         # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1244         my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1245         pop(@args) if (@args && !defined($args[-1]));
1246         if (@args && uc($req) eq 'UID') {
1247                 $req .= "_".(shift @args);
1248         }
1249         my $res = eval {
1250                 if (defined(my $idle_tag = $self->{-idle_tag})) {
1251                         (uc($tag // '') eq 'DONE' && !defined($req)) ?
1252                                 idle_done($self, $tag) :
1253                                 "$idle_tag BAD expected DONE\r\n";
1254                 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1255                         if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1256                                 # preserve user-supplied quotes for search
1257                                 (undef, @args) = split(/ search /i, $l, 2);
1258                         }
1259                         $cmd->($self, $tag, @args);
1260                 } else { # this is weird
1261                         auth_challenge_ok($self) //
1262                                         ($tag // '*') .
1263                                         ' BAD Error in IMAP command '.
1264                                         ($req // '(???)').
1265                                         ": Unknown command\r\n";
1266                 }
1267         };
1268         my $err = $@;
1269         if ($err && $self->{sock}) {
1270                 $l =~ s/\r?\n//s;
1271                 err($self, 'error from: %s (%s)', $l, $err);
1272                 $tag //= '*';
1273                 $res = "$tag BAD program fault - command not performed\r\n";
1274         }
1275         return 0 unless defined $res;
1276         $self->write($res);
1277 }
1278
1279 sub long_step {
1280         my ($self) = @_;
1281         # wbuf is unset or empty, here; {long} may add to it
1282         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1283         my $more = eval { $cb->($self, @args) };
1284         if ($@ || !$self->{sock}) { # something bad happened...
1285                 delete $self->{long_cb};
1286                 my $elapsed = now() - $t0;
1287                 if ($@) {
1288                         err($self,
1289                             "%s during long response[$fd] - %0.6f",
1290                             $@, $elapsed);
1291                 }
1292                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1293                 $self->close;
1294         } elsif ($more) { # $self->{wbuf}:
1295                 $self->update_idle_time;
1296
1297                 # control passed to $more may be a GitAsyncCat object
1298                 requeue_once($self) if !ref($more);
1299         } else { # all done!
1300                 delete $self->{long_cb};
1301                 my $elapsed = now() - $t0;
1302                 my $fd = fileno($self->{sock});
1303                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1304                 my $wbuf = $self->{wbuf}; # do NOT autovivify
1305
1306                 $self->requeue unless $wbuf && @$wbuf;
1307         }
1308 }
1309
1310 sub err ($$;@) {
1311         my ($self, $fmt, @args) = @_;
1312         printf { $self->{imapd}->{err} } $fmt."\n", @args;
1313 }
1314
1315 sub out ($$;@) {
1316         my ($self, $fmt, @args) = @_;
1317         printf { $self->{imapd}->{out} } $fmt."\n", @args;
1318 }
1319
1320 sub long_response ($$;@) {
1321         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1322
1323         my $sock = $self->{sock} or return;
1324         # make sure we disable reading during a long response,
1325         # clients should not be sending us stuff and making us do more
1326         # work while we are stream a response to them
1327         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1328         long_step($self); # kick off!
1329         undef;
1330 }
1331
1332 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1333 sub event_step {
1334         my ($self) = @_;
1335
1336         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1337
1338         $self->update_idle_time;
1339         # only read more requests if we've drained the write buffer,
1340         # otherwise we can be buffering infinitely w/o backpressure
1341
1342         my $rbuf = $self->{rbuf} // \(my $x = '');
1343         my $line = index($$rbuf, "\n");
1344         while ($line < 0) {
1345                 if (length($$rbuf) >= LINE_MAX) {
1346                         $self->write(\"\* BAD request too long\r\n");
1347                         return $self->close;
1348                 }
1349                 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1350                                 return uo2m_hibernate($self);
1351                 $line = index($$rbuf, "\n");
1352         }
1353         $line = substr($$rbuf, 0, $line + 1, '');
1354         $line =~ s/\r?\n\z//s;
1355         return $self->close if $line =~ /[[:cntrl:]]/s;
1356         my $t0 = now();
1357         my $fd = fileno($self->{sock});
1358         my $r = eval { process_line($self, $line) };
1359         my $pending = $self->{wbuf} ? ' pending' : '';
1360         out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1361
1362         return $self->close if $r < 0;
1363         $self->rbuf_idle($rbuf);
1364         $self->update_idle_time;
1365
1366         # maybe there's more pipelined data, or we'll have
1367         # to register it for socket-readiness notifications
1368         $self->requeue unless $pending;
1369 }
1370
1371 sub compressed { undef }
1372
1373 sub zflush {} # overridden by IMAPdeflate
1374
1375 # RFC 4978
1376 sub cmd_compress ($$$) {
1377         my ($self, $tag, $alg) = @_;
1378         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1379         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1380
1381         # CRIME made TLS compression obsolete
1382         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1383
1384         PublicInbox::IMAPdeflate->enable($self, $tag);
1385         $self->requeue;
1386         undef
1387 }
1388
1389 sub cmd_starttls ($$) {
1390         my ($self, $tag) = @_;
1391         my $sock = $self->{sock} or return;
1392         if ($sock->can('stop_SSL') || $self->compressed) {
1393                 return "$tag BAD TLS or compression already enabled\r\n";
1394         }
1395         my $opt = $self->{imapd}->{accept_tls} or
1396                 return "$tag BAD can not initiate TLS negotiation\r\n";
1397         $self->write(\"$tag OK begin TLS negotiation now\r\n");
1398         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1399         $self->requeue if PublicInbox::DS::accept_tls_step($self);
1400         undef;
1401 }
1402
1403 # for graceful shutdown in PublicInbox::Daemon:
1404 sub busy {
1405         my ($self, $now) = @_;
1406         if (defined($self->{-idle_tag})) {
1407                 $self->write(\"* BYE server shutting down\r\n");
1408                 return; # not busy anymore
1409         }
1410         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1411 }
1412
1413 sub close {
1414         my ($self) = @_;
1415         if (my $ibx = delete $self->{ibx}) {
1416                 stop_idle($self, $ibx);
1417         }
1418         $self->SUPER::close; # PublicInbox::DS::close
1419 }
1420
1421 # we're read-only, so SELECT and EXAMINE do the same thing
1422 no warnings 'once';
1423 *cmd_select = \&cmd_examine;
1424
1425 package PublicInbox::IMAP_preauth;
1426 our @ISA = qw(PublicInbox::IMAP);
1427
1428 sub logged_in { 0 }
1429
1430 1;