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