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