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