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