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