]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
search: export mdocid subroutine
[public-inbox.git] / lib / PublicInbox / IMAP.pm
1 # Copyright (C) 2020 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::Search qw(mdocid);
44 use PublicInbox::IMAPsearchqp;
45
46 my $Address;
47 for my $mod (qw(Email::Address::XS Mail::Address)) {
48         eval "require $mod" or next;
49         $Address = $mod and last;
50 }
51 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
52
53 sub LINE_MAX () { 8000 } # RFC 2683 3.2.1.5
54
55 # Changing UID_SLICE will cause grief for clients which cache.
56 # This also needs to be <64K: we pack it into a uint16_t
57 # for long_response UID (offset) => MSN mappings
58 sub UID_SLICE () { 50_000 }
59
60 # these values area also used for sorting
61 sub NEED_SMSG () { 1 }
62 sub NEED_BLOB () { NEED_SMSG|2 }
63 sub CRLF_BREF () { 4 }
64 sub EML_HDR () { 8 }
65 sub CRLF_HDR () { 16 }
66 sub EML_BDY () { 32 }
67 sub CRLF_BDY () { 64 }
68 my $OP_EML_NEW = [ EML_HDR - 1, \&op_eml_new ];
69 my $OP_CRLF_BREF = [ CRLF_BREF, \&op_crlf_bref ];
70 my $OP_CRLF_HDR = [ CRLF_HDR, \&op_crlf_hdr ];
71 my $OP_CRLF_BDY = [ CRLF_BDY, \&op_crlf_bdy ];
72
73 my %FETCH_NEED = (
74         'BODY[HEADER]' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
75         'BODY[TEXT]' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
76         'BODY[]' => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
77         'RFC822.HEADER' => [ NEED_BLOB|EML_HDR|CRLF_HDR, \&emit_rfc822_header ],
78         'RFC822.TEXT' => [ NEED_BLOB|EML_BDY|CRLF_BDY, \&emit_rfc822_text ],
79         'RFC822.SIZE' => [ NEED_SMSG, \&emit_rfc822_size ],
80         RFC822 => [ NEED_BLOB|CRLF_BREF, \&emit_rfc822 ],
81         BODY => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_body ],
82         BODYSTRUCTURE => [ NEED_BLOB|EML_HDR|EML_BDY, \&emit_bodystructure ],
83         ENVELOPE => [ NEED_BLOB|EML_HDR, \&emit_envelope ],
84         FLAGS => [ 0, \&emit_flags ],
85         INTERNALDATE => [ NEED_SMSG, \&emit_internaldate ],
86 );
87 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED;
88
89 # aliases (RFC 3501 section 6.4.5)
90 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
91 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
92 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
93
94 for my $att (keys %FETCH_ATT) {
95         my %h = map { $_ => $FETCH_NEED{$_} } @{$FETCH_ATT{$att}};
96         $FETCH_ATT{$att} = \%h;
97 }
98 undef %FETCH_NEED;
99
100 my $valid_range = '[0-9]+|[0-9]+:[0-9]+|[0-9]+:\*';
101 $valid_range = qr/\A(?:$valid_range)(?:,(?:$valid_range))*\z/;
102
103 # RFC 3501 5.4. Autologout Timer needs to be >= 30min
104 $PublicInbox::DS::EXPTIME = 60 * 30;
105
106 sub greet ($) {
107         my ($self) = @_;
108         my $capa = capa($self);
109         $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
110 }
111
112 sub new ($$$) {
113         my ($class, $sock, $imapd) = @_;
114         my $self = bless { imapd => $imapd }, 'PublicInbox::IMAP_preauth';
115         my $ev = EPOLLIN;
116         my $wbuf;
117         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
118                 return CORE::close($sock) if $! != EAGAIN;
119                 $ev = PublicInbox::TLS::epollbit();
120                 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
121         }
122         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
123         if ($wbuf) {
124                 $self->{wbuf} = $wbuf;
125         } else {
126                 greet($self);
127         }
128         $self->update_idle_time;
129         $self;
130 }
131
132 sub logged_in { 1 }
133
134 sub capa ($) {
135         my ($self) = @_;
136
137         # dovecot advertises IDLE pre-login; perhaps because some clients
138         # depend on it, so we'll do the same
139         my $capa = 'CAPABILITY IMAP4rev1 IDLE';
140         if ($self->logged_in) {
141                 $capa .= ' COMPRESS=DEFLATE';
142         } else {
143                 if (!($self->{sock} // $self)->can('accept_SSL') &&
144                         $self->{imapd}->{accept_tls}) {
145                         $capa .= ' STARTTLS';
146                 }
147                 $capa .= ' AUTH=ANONYMOUS';
148         }
149 }
150
151 sub login_success ($$) {
152         my ($self, $tag) = @_;
153         bless $self, 'PublicInbox::IMAP';
154         my $capa = capa($self);
155         "$tag OK [$capa] Logged in\r\n";
156 }
157
158 sub auth_challenge_ok ($) {
159         my ($self) = @_;
160         my $tag = delete($self->{-login_tag}) or return;
161         login_success($self, $tag);
162 }
163
164 sub cmd_login ($$$$) {
165         my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
166         login_success($self, $tag);
167 }
168
169 sub cmd_close ($$) {
170         my ($self, $tag) = @_;
171         delete @$self{qw(uid_base uo2m)};
172         delete $self->{ibx} ? "$tag OK Close done\r\n"
173                                 : "$tag BAD No mailbox\r\n";
174 }
175
176 sub cmd_logout ($$) {
177         my ($self, $tag) = @_;
178         delete $self->{-idle_tag};
179         $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
180         $self->shutdn; # PublicInbox::DS::shutdn
181         undef;
182 }
183
184 sub cmd_authenticate ($$$) {
185         my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
186         $self->{-login_tag} = $tag;
187         "+\r\n"; # challenge
188 }
189
190 sub cmd_capability ($$) {
191         my ($self, $tag) = @_;
192         '* '.capa($self)."\r\n$tag OK Capability done\r\n";
193 }
194
195 # uo2m: UID Offset to MSN, this is an arrayref by default,
196 # but uo2m_hibernate can compact and deduplicate it
197 sub uo2m_ary_new ($;$) {
198         my ($self, $exists) = @_;
199         my $base = $self->{uid_base};
200         my $uids = $self->{ibx}->over->uid_range($base + 1, $base + UID_SLICE);
201
202         # convert UIDs to offsets from {base}
203         my @tmp; # [$UID_OFFSET] => $MSN
204         my $msn = 0;
205         ++$base;
206         $tmp[$_ - $base] = ++$msn for @$uids;
207         $$exists = $msn if $exists;
208         \@tmp;
209 }
210
211 # changes UID-offset-to-MSN mapping into a deduplicated scalar:
212 # uint16_t uo2m[UID_SLICE].
213 # May be swapped out for idle clients if THP is disabled.
214 sub uo2m_hibernate ($) {
215         my ($self) = @_;
216         ref(my $uo2m = $self->{uo2m}) or return;
217         my %dedupe = ( uo2m_pack($uo2m) => undef );
218         $self->{uo2m} = (keys(%dedupe))[0];
219         undef;
220 }
221
222 sub uo2m_last_uid ($) {
223         my ($self) = @_;
224         defined(my $uo2m = $self->{uo2m}) or die 'BUG: uo2m_last_uid w/o {uo2m}';
225         (ref($uo2m) ? @$uo2m : (length($uo2m) >> 1)) + $self->{uid_base};
226 }
227
228 sub uo2m_pack ($) {
229         # $_[0] is an arrayref of MSNs, it may have undef gaps if there
230         # are gaps in the corresponding UIDs: [ msn1, msn2, undef, msn3 ]
231         no warnings 'uninitialized';
232         pack('S*', @{$_[0]});
233 }
234
235 # extend {uo2m} to account for new messages which arrived since
236 # {uo2m} was created.
237 sub uo2m_extend ($$;$) {
238         my ($self, $new_uid_max) = @_;
239         defined(my $uo2m = $self->{uo2m}) or
240                 return($self->{uo2m} = uo2m_ary_new($self));
241         my $beg = uo2m_last_uid($self); # last UID we've learned
242         return $uo2m if $beg >= $new_uid_max; # fast path
243
244         # need to extend the current range:
245         my $base = $self->{uid_base};
246         ++$beg;
247         my $uids = $self->{ibx}->over->uid_range($beg, $base + UID_SLICE);
248         return $uo2m if !scalar(@$uids);
249         my @tmp; # [$UID_OFFSET] => $MSN
250         my $write_method = $_[2] // 'msg_more';
251         if (ref($uo2m)) {
252                 my $msn = $uo2m->[-1];
253                 $tmp[$_ - $beg] = ++$msn for @$uids;
254                 $self->$write_method("* $msn EXISTS\r\n");
255                 push @$uo2m, @tmp;
256                 $uo2m;
257         } else {
258                 my $msn = unpack('S', substr($uo2m, -2, 2));
259                 $tmp[$_ - $beg] = ++$msn for @$uids;
260                 $self->$write_method("* $msn EXISTS\r\n");
261                 $uo2m .= uo2m_pack(\@tmp);
262                 my %dedupe = ($uo2m => undef);
263                 $self->{uo2m} = (keys %dedupe)[0];
264         }
265 }
266
267 sub cmd_noop ($$) {
268         my ($self, $tag) = @_;
269         defined($self->{uid_base}) and
270                 uo2m_extend($self, $self->{uid_base} + UID_SLICE);
271         \"$tag OK Noop done\r\n";
272 }
273
274 # the flexible version which works on scalars and array refs.
275 # Must call uo2m_extend before this
276 sub uid2msn ($$) {
277         my ($self, $uid) = @_;
278         my $uo2m = $self->{uo2m};
279         my $off = $uid - $self->{uid_base} - 1;
280         ref($uo2m) ? $uo2m->[$off] : unpack('S', substr($uo2m, $off << 1, 2));
281 }
282
283 # returns an arrayref of UIDs, so MSNs can be translated to UIDs via:
284 # $msn2uid->[$MSN-1] => $UID.  The result of this is always ephemeral
285 # and does not live beyond the event loop.
286 sub msn2uid ($) {
287         my ($self) = @_;
288         my $base = $self->{uid_base};
289         my $uo2m = uo2m_extend($self, $base + UID_SLICE);
290         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
291
292         my $uo = 0;
293         my @msn2uid;
294         for my $msn (@$uo2m) {
295                 ++$uo;
296                 $msn2uid[$msn - 1] = $uo + $base if $msn;
297         }
298         \@msn2uid;
299 }
300
301 # converts a set of message sequence numbers in requests to UIDs:
302 sub msn_to_uid_range ($$) {
303         my $msn2uid = $_[0];
304         $_[1] =~ s!([0-9]+)!$msn2uid->[$1 - 1] // ($msn2uid->[-1] + 1)!sge;
305 }
306
307 # called by PublicInbox::InboxIdle
308 sub on_inbox_unlock {
309         my ($self, $ibx) = @_;
310         my $uid_end = $self->{uid_base} + UID_SLICE;
311         uo2m_extend($self, $uid_end, 'write');
312         my $new = uo2m_last_uid($self);
313         if ($new == $uid_end) { # max exceeded $uid_end
314                 # continue idling w/o inotify
315                 my $sock = $self->{sock} or return;
316                 $ibx->unsubscribe_unlock(fileno($sock));
317         }
318 }
319
320 # called every X minute(s) or so by PublicInbox::DS::later
321 my $IDLERS = {};
322 my $idle_timer;
323 sub idle_tick_all {
324         my $old = $IDLERS;
325         $IDLERS = {};
326         for my $i (values %$old) {
327                 next if ($i->{wbuf} || !exists($i->{-idle_tag}));
328                 $i->update_idle_time or next;
329                 $IDLERS->{fileno($i->{sock})} = $i;
330                 $i->write(\"* OK Still here\r\n");
331         }
332         $idle_timer = scalar keys %$IDLERS ?
333                         PublicInbox::DS::later(\&idle_tick_all) : undef;
334 }
335
336 sub cmd_idle ($$) {
337         my ($self, $tag) = @_;
338         # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
339         my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
340         my $uid_end = $self->{uid_base} + UID_SLICE;
341         uo2m_extend($self, $uid_end);
342         my $sock = $self->{sock} or return;
343         my $fd = fileno($sock);
344         $self->{-idle_tag} = $tag;
345         # only do inotify on most recent slice
346         if ($ibx->over->max < $uid_end) {
347                 $ibx->subscribe_unlock($fd, $self);
348                 $self->{imapd}->idler_start;
349         }
350         $idle_timer //= PublicInbox::DS::later(\&idle_tick_all);
351         $IDLERS->{$fd} = $self;
352         \"+ idling\r\n"
353 }
354
355 sub stop_idle ($$) {
356         my ($self, $ibx) = @_;
357         my $sock = $self->{sock} or return;
358         my $fd = fileno($sock);
359         delete $IDLERS->{$fd};
360         $ibx->unsubscribe_unlock($fd);
361 }
362
363 sub idle_done ($$) {
364         my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
365         defined(my $idle_tag = delete $self->{-idle_tag}) or
366                 return "$tag BAD not idle\r\n";
367         my $ibx = $self->{ibx} or do {
368                 warn "BUG: idle_tag set w/o inbox";
369                 return "$tag BAD internal bug\r\n";
370         };
371         stop_idle($self, $ibx);
372         "$idle_tag OK Idle done\r\n";
373 }
374
375 sub ensure_slices_exist ($$$) {
376         my ($imapd, $ibx, $max) = @_;
377         defined(my $mb_top = $ibx->{newsgroup}) or return;
378         my $mailboxes = $imapd->{mailboxes};
379         my @created;
380         for (my $i = int($max/UID_SLICE); $i >= 0; --$i) {
381                 my $sub_mailbox = "$mb_top.$i";
382                 last if exists $mailboxes->{$sub_mailbox};
383                 $mailboxes->{$sub_mailbox} = $ibx;
384                 $sub_mailbox =~ s/\Ainbox\./INBOX./i; # more familiar to users
385                 push @created, $sub_mailbox;
386         }
387         return unless @created;
388         my $l = $imapd->{inboxlist} or return;
389         push @$l, map { qq[* LIST (\\HasNoChildren) "." $_\r\n] } @created;
390 }
391
392 sub inbox_lookup ($$;$) {
393         my ($self, $mailbox, $examine) = @_;
394         my ($ibx, $exists, $uidmax, $uid_base) = (undef, 0, 0, 0);
395         $mailbox = lc $mailbox;
396         $ibx = $self->{imapd}->{mailboxes}->{$mailbox} or return;
397         my $over = $ibx->over;
398         if ($over != $ibx) { # not a dummy
399                 $mailbox =~ /\.([0-9]+)\z/ or
400                                 die "BUG: unexpected dummy mailbox: $mailbox\n";
401                 $uid_base = $1 * UID_SLICE;
402
403                 # ->num_highwater caches for writers, so use ->meta_accessor
404                 $uidmax = $ibx->mm->meta_accessor('num_highwater') // 0;
405                 if ($examine) {
406                         $self->{uid_base} = $uid_base;
407                         $self->{ibx} = $ibx;
408                         $self->{uo2m} = uo2m_ary_new($self, \$exists);
409                 } else {
410                         $exists = $over->imap_exists;
411                 }
412                 ensure_slices_exist($self->{imapd}, $ibx, $over->max);
413         } else {
414                 if ($examine) {
415                         $self->{uid_base} = $uid_base;
416                         $self->{ibx} = $ibx;
417                         delete $self->{uo2m};
418                 }
419                 # if "INBOX.foo.bar" is selected and "INBOX.foo.bar.0",
420                 # check for new UID ranges (e.g. "INBOX.foo.bar.1")
421                 if (my $z = $self->{imapd}->{mailboxes}->{"$mailbox.0"}) {
422                         ensure_slices_exist($self->{imapd}, $z, $z->over->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(delete $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(delete $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(delete $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 git_async_cat
617         my ($bref, $oid, $type, $size, $fetch_arg) = @_;
618         my ($self, undef, $msgs, $range_info, $ops, $partial) = @$fetch_arg;
619         my $smsg = shift @$msgs or die 'BUG: no smsg';
620         if (!defined($oid)) {
621                 # it's possible to have TOCTOU if an admin runs
622                 # public-inbox-(edit|purge), just move onto the next message
623                 warn "E: $smsg->{blob} missing in $self->{ibx}->{inboxdir}\n";
624                 return requeue_once($self);
625         } else {
626                 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
627         }
628         my $pre;
629         if (!$self->{wbuf} && (my $nxt = $msgs->[0])) {
630                 $pre = $self->{ibx}->git->async_prefetch($nxt->{blob},
631                                                 \&fetch_blob_cb, $fetch_arg);
632         }
633         fetch_run_ops($self, $smsg, $bref, $ops, $partial);
634         $pre ? $self->zflush : requeue_once($self);
635 }
636
637 sub emit_rfc822 {
638         my ($self, $k, undef, $bref) = @_;
639         $self->msg_more(" $k {" . length($$bref)."}\r\n");
640         $self->msg_more($$bref);
641 }
642
643 # Mail::IMAPClient::message_string cares about this by default,
644 # (->Ignoresizeerrors attribute).  Admins are encouraged to
645 # --reindex for IMAP support, anyways.
646 sub emit_rfc822_size {
647         my ($self, $k, $smsg) = @_;
648         $self->msg_more(' RFC822.SIZE ' . $smsg->{bytes});
649 }
650
651 sub emit_internaldate {
652         my ($self, undef, $smsg) = @_;
653         $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
654 }
655
656 sub emit_flags { $_[0]->msg_more(' FLAGS ()') }
657
658 sub emit_envelope {
659         my ($self, undef, undef, undef, $eml) = @_;
660         $self->msg_more(' ENVELOPE '.eml_envelope($eml));
661 }
662
663 sub emit_rfc822_header {
664         my ($self, $k, undef, undef, $eml) = @_;
665         $self->msg_more(" $k {".length(${$eml->{hdr}})."}\r\n");
666         $self->msg_more(${$eml->{hdr}});
667 }
668
669 # n.b. this is sorted to be after any emit_eml_new ops
670 sub emit_rfc822_text {
671         my ($self, $k, undef, $bref) = @_;
672         $self->msg_more(" $k {".length($$bref)."}\r\n");
673         $self->msg_more($$bref);
674 }
675
676 sub emit_bodystructure {
677         my ($self, undef, undef, undef, $eml) = @_;
678         $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
679 }
680
681 sub emit_body {
682         my ($self, undef, undef, undef, $eml) = @_;
683         $self->msg_more(' BODY '.fetch_body($eml));
684 }
685
686 # set $eml once ($_[4] == $eml, $_[3] == $bref)
687 sub op_eml_new { $_[4] = PublicInbox::Eml->new($_[3]) }
688
689 # s/From / fixes old bug from import (pre-a0c07cba0e5d8b6a)
690 sub to_crlf_full {
691         ${$_[0]} =~ s/(?<!\r)\n/\r\n/sg;
692         ${$_[0]} =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
693 }
694
695 sub op_crlf_bref { to_crlf_full($_[3]) }
696
697 sub op_crlf_hdr { to_crlf_full($_[4]->{hdr}) }
698
699 sub op_crlf_bdy { ${$_[4]->{bdy}} =~ s/(?<!\r)\n/\r\n/sg if $_[4]->{bdy} }
700
701 sub uid_clamp ($$$) {
702         my ($self, $beg, $end) = @_;
703         my $uid_min = $self->{uid_base} + 1;
704         my $uid_end = $uid_min + UID_SLICE - 1;
705         $$beg = $uid_min if $$beg < $uid_min;
706         $$end = $uid_end if $$end > $uid_end;
707 }
708
709 sub range_step ($$) {
710         my ($self, $range_csv) = @_;
711         my ($beg, $end, $range);
712         if ($$range_csv =~ s/\A([^,]+),//) {
713                 $range = $1;
714         } else {
715                 $range = $$range_csv;
716                 $$range_csv = undef;
717         }
718         my $uid_base = $self->{uid_base};
719         my $uid_end = $uid_base + UID_SLICE;
720         if ($range =~ /\A([0-9]+):([0-9]+)\z/) {
721                 ($beg, $end) = ($1 + 0, $2 + 0);
722                 uid_clamp($self, \$beg, \$end);
723         } elsif ($range =~ /\A([0-9]+):\*\z/) {
724                 $beg = $1 + 0;
725                 $end = $self->{ibx}->over->max;
726                 $end = $uid_end if $end > $uid_end;
727                 $beg = $end if $beg > $end;
728                 uid_clamp($self, \$beg, \$end);
729         } elsif ($range =~ /\A[0-9]+\z/) {
730                 $beg = $end = $range + 0;
731                 # just let the caller do an out-of-range query if a single
732                 # UID is out-of-range
733                 ++$beg if ($beg <= $uid_base || $end > $uid_end);
734         } else {
735                 return 'BAD fetch range';
736         }
737         [ $beg, $end, $$range_csv ];
738 }
739
740 sub refill_range ($$$) {
741         my ($self, $msgs, $range_info) = @_;
742         my ($beg, $end, $range_csv) = @$range_info;
743         if (scalar(@$msgs = @{$self->{ibx}->over->query_xover($beg, $end)})) {
744                 $range_info->[0] = $msgs->[-1]->{num} + 1;
745                 return;
746         }
747         return 'OK Fetch done' if !$range_csv;
748         my $next_range = range_step($self, \$range_csv);
749         return $next_range if !ref($next_range); # error
750         @$range_info = @$next_range;
751         undef; # keep looping
752 }
753
754 sub fetch_blob { # long_response
755         my ($self, $tag, $msgs, $range_info, $ops, $partial) = @_;
756         while (!@$msgs) { # rare
757                 if (my $end = refill_range($self, $msgs, $range_info)) {
758                         $self->write(\"$tag $end\r\n");
759                         return;
760                 }
761         }
762         uo2m_extend($self, $msgs->[-1]->{num});
763         git_async_cat($self->{ibx}->git, $msgs->[0]->{blob},
764                         \&fetch_blob_cb, \@_);
765 }
766
767 sub fetch_smsg { # long_response
768         my ($self, $tag, $msgs, $range_info, $ops) = @_;
769         while (!@$msgs) { # rare
770                 if (my $end = refill_range($self, $msgs, $range_info)) {
771                         $self->write(\"$tag $end\r\n");
772                         return;
773                 }
774         }
775         uo2m_extend($self, $msgs->[-1]->{num});
776         fetch_run_ops($self, $_, undef, $ops) for @$msgs;
777         @$msgs = ();
778         1; # more
779 }
780
781 sub refill_uids ($$$;$) {
782         my ($self, $uids, $range_info, $sql) = @_;
783         my ($beg, $end, $range_csv) = @$range_info;
784         my $over = $self->{ibx}->over;
785         while (1) {
786                 if (scalar(@$uids = @{$over->uid_range($beg, $end, $sql)})) {
787                         $range_info->[0] = $uids->[-1] + 1; # update $beg
788                         return;
789                 } elsif (!$range_csv) {
790                         return 0;
791                 } else {
792                         my $next_range = range_step($self, \$range_csv);
793                         return $next_range if !ref($next_range); # error
794                         ($beg, $end, $range_csv) = @$range_info = @$next_range;
795                         # continue looping
796                 }
797         }
798 }
799
800 sub fetch_uid { # long_response
801         my ($self, $tag, $uids, $range_info, $ops) = @_;
802         if (defined(my $err = refill_uids($self, $uids, $range_info))) {
803                 $err ||= 'OK Fetch done';
804                 $self->write("$tag $err\r\n");
805                 return;
806         }
807         my $adj = $self->{uid_base} + 1;
808         my $uo2m = uo2m_extend($self, $uids->[-1]);
809         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
810         my ($i, $k);
811         for (@$uids) {
812                 $self->msg_more("* $uo2m->[$_ - $adj] FETCH (UID $_");
813                 for ($i = 0; $i < @$ops;) {
814                         $k = $ops->[$i++];
815                         $ops->[$i++]->($self, $k);
816                 }
817                 $self->msg_more(")\r\n");
818         }
819         @$uids = ();
820         1; # more
821 }
822
823 sub cmd_status ($$$;@) {
824         my ($self, $tag, $mailbox, @items) = @_;
825         return "$tag BAD no items\r\n" if !scalar(@items);
826         ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
827                 return "$tag BAD invalid args\r\n";
828         my ($ibx, $exists, $uidnext) = inbox_lookup($self, $mailbox);
829         return "$tag NO Mailbox doesn't exist: $mailbox\r\n" if !$ibx;
830         my @it;
831         for my $it (@items) {
832                 $it = uc($it);
833                 push @it, $it;
834                 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
835                         push @it, $exists;
836                 } elsif ($it eq 'UIDNEXT') {
837                         push @it, $uidnext;
838                 } elsif ($it eq 'UIDVALIDITY') {
839                         push @it, $ibx->{uidvalidity};
840                 } else {
841                         return "$tag BAD invalid item\r\n";
842                 }
843         }
844         return "$tag BAD no items\r\n" if !@it;
845         "* STATUS $mailbox (".join(' ', @it).")\r\n" .
846         "$tag OK Status done\r\n";
847 }
848
849 my %patmap = ('*' => '.*', '%' => '[^\.]*');
850 sub cmd_list ($$$$) {
851         my ($self, $tag, $refname, $wildcard) = @_;
852         my $l = $self->{imapd}->{inboxlist};
853         if ($refname eq '' && $wildcard eq '') {
854                 # request for hierarchy delimiter
855                 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
856         } elsif ($refname ne '' || $wildcard ne '*') {
857                 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!egi;
858                 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/is, @$l) ];
859         }
860         \(join('', @$l, "$tag OK List done\r\n"));
861 }
862
863 sub cmd_lsub ($$$$) {
864         my (undef, $tag) = @_; # same args as cmd_list
865         "$tag OK Lsub done\r\n";
866 }
867
868 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
869         my ($p, $all) = @_;
870         my ($eml, undef, $idx) = @$p;
871         if ($idx && lc($eml->ct->{type}) eq 'multipart') {
872                 $eml->{imap_bdy} = $eml->{bdy} // \'';
873         }
874         $all->{$idx} = $eml; # $idx => Eml
875 }
876
877 # prepares an index for BODY[$SECTION_IDX] fetches
878 sub eml_body_idx ($$) {
879         my ($eml, $section_idx) = @_;
880         my $idx = $eml->{imap_all_parts} //= do {
881                 my $all = {};
882                 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
883                 # top-level of multipart, BODY[0] not allowed (nz-number)
884                 delete $all->{0};
885                 $all;
886         };
887         $idx->{$section_idx};
888 }
889
890 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
891 sub partial_body {
892         my ($eml, $section_idx, $section_name) = @_;
893         if (defined $section_idx) {
894                 $eml = eml_body_idx($eml, $section_idx) or return;
895         }
896         if (defined $section_name) {
897                 if ($section_name eq 'MIME') {
898                         # RFC 3501 6.4.5 states:
899                         #       The MIME part specifier MUST be prefixed
900                         #       by one or more numeric part specifiers
901                         return unless defined $section_idx;
902                         return $eml->header_obj->as_string . "\r\n";
903                 }
904                 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
905                 $eml = PublicInbox::Eml->new($$bdy);
906                 if ($section_name eq 'TEXT') {
907                         return $eml->body_raw;
908                 } elsif ($section_name eq 'HEADER') {
909                         return $eml->header_obj->as_string . "\r\n";
910                 } else {
911                         die "BUG: bad section_name=$section_name";
912                 }
913         }
914         ${$eml->{bdy} // $eml->{imap_bdy} // \''};
915 }
916
917 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
918 # to avoid OOM with malicious users
919 sub hdrs_regexp ($) {
920         my ($hdrs) = @_;
921         my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
922         qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
923                 # continuation lines:
924                 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
925                 /ismx;
926 }
927
928 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
929 sub partial_hdr_not {
930         my ($eml, $section_idx, $hdrs_re) = @_;
931         if (defined $section_idx) {
932                 $eml = eml_body_idx($eml, $section_idx) or return;
933         }
934         my $str = $eml->header_obj->as_string;
935         $str =~ s/$hdrs_re//g;
936         $str =~ s/(?<!\r)\n/\r\n/sg;
937         $str .= "\r\n";
938 }
939
940 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
941 sub partial_hdr_get {
942         my ($eml, $section_idx, $hdrs_re) = @_;
943         if (defined $section_idx) {
944                 $eml = eml_body_idx($eml, $section_idx) or return;
945         }
946         my $str = $eml->header_obj->as_string;
947         $str = join('', ($str =~ m/($hdrs_re)/g));
948         $str =~ s/(?<!\r)\n/\r\n/sg;
949         $str .= "\r\n";
950 }
951
952 sub partial_prepare ($$$$) {
953         my ($need, $partial, $want, $att) = @_;
954
955         # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
956         # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
957         return unless $att =~ /\ABODY\[/s;
958         until (rindex($att, ']') >= 0) {
959                 my $next = shift @$want or return;
960                 $att .= ' ' . uc($next);
961         }
962         if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
963                         (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
964                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
965                 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
966                 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
967         } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
968                                 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
969                                 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
970                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
971                 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
972                                                 : \&partial_hdr_get,
973                                                 $1, undef, $4, $5 ];
974                 $tmp->[2] = hdrs_regexp($3);
975
976                 # don't emit CRLF_HDR instruction, here, partial_hdr_*
977                 # will do CRLF conversion with only the extracted result
978                 # and not waste time converting lines we don't care about.
979                 $$need |= EML_HDR;
980         } else {
981                 undef;
982         }
983 }
984
985 sub partial_emit ($$$) {
986         my ($self, $partial, $eml) = @_;
987         for (@$partial) {
988                 my ($k, $cb, @args) = @$_;
989                 my ($offset, $len) = splice(@args, -2);
990                 # $cb is partial_body|partial_hdr_get|partial_hdr_not
991                 my $str = $cb->($eml, @args) // '';
992                 if (defined $offset) {
993                         if (defined $len) {
994                                 $str = substr($str, $offset, $len);
995                                 $k =~ s/\.$len>\z/>/ or warn
996 "BUG: unable to remove `.$len>' from `$k'";
997                         } else {
998                                 $str = substr($str, $offset);
999                                 $len = length($str);
1000                         }
1001                 } else {
1002                         $len = length($str);
1003                 }
1004                 $self->msg_more(" $k {$len}\r\n");
1005                 $self->msg_more($str);
1006         }
1007 }
1008
1009 sub fetch_compile ($) {
1010         my ($want) = @_;
1011         if ($want->[0] =~ s/\A\(//s) {
1012                 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
1013         }
1014         my (%partial, %seen, @op);
1015         my $need = 0;
1016         while (defined(my $att = shift @$want)) {
1017                 $att = uc($att);
1018                 next if $att eq 'UID'; # always returned
1019                 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
1020                 my $x = $FETCH_ATT{$att};
1021                 if ($x) {
1022                         while (my ($k, $fl_cb) = each %$x) {
1023                                 next if $seen{$k}++;
1024                                 $need |= $fl_cb->[0];
1025                                 push @op, [ @$fl_cb, $k ];
1026                         }
1027                 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
1028                         return "BAD param: $att";
1029                 }
1030         }
1031         my @r;
1032
1033         # stabilize partial order for consistency and ease-of-debugging:
1034         if (scalar keys %partial) {
1035                 $need |= NEED_BLOB;
1036                 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
1037         }
1038
1039         push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
1040
1041         # do we need CRLF conversion?
1042         if ($need & CRLF_BREF) {
1043                 push @op, $OP_CRLF_BREF;
1044         } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
1045                 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
1046                         push @op, $OP_CRLF_BREF;
1047                 } elsif ($need & CRLF_HDR) {
1048                         push @op, $OP_CRLF_HDR;
1049                 } else {
1050                         push @op, $OP_CRLF_BDY;
1051                 }
1052         }
1053
1054         $r[0] = $need & NEED_BLOB ? \&fetch_blob :
1055                 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
1056
1057         # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
1058         use sort 'stable'; # makes output more consistent
1059         $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
1060         @r;
1061 }
1062
1063 sub cmd_uid_fetch ($$$$;@) {
1064         my ($self, $tag, $range_csv, @want) = @_;
1065         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1066         my ($cb, $ops, $partial) = fetch_compile(\@want);
1067         return "$tag $cb\r\n" unless $ops;
1068
1069         # cb is one of fetch_blob, fetch_smsg, fetch_uid
1070         $range_csv = 'bad' if $range_csv !~ $valid_range;
1071         my $range_info = range_step($self, \$range_csv);
1072         return "$tag $range_info\r\n" if !ref($range_info);
1073         uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1074         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1075 }
1076
1077 sub cmd_fetch ($$$$;@) {
1078         my ($self, $tag, $range_csv, @want) = @_;
1079         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1080         my ($cb, $ops, $partial) = fetch_compile(\@want);
1081         return "$tag $cb\r\n" unless $ops;
1082
1083         # cb is one of fetch_blob, fetch_smsg, fetch_uid
1084         $range_csv = 'bad' if $range_csv !~ $valid_range;
1085         msn_to_uid_range(msn2uid($self), $range_csv);
1086         my $range_info = range_step($self, \$range_csv);
1087         return "$tag $range_info\r\n" if !ref($range_info);
1088         uo2m_hibernate($self) if $cb == \&fetch_blob; # slow, save RAM
1089         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
1090 }
1091
1092 sub msn_convert ($$) {
1093         my ($self, $uids) = @_;
1094         my $adj = $self->{uid_base} + 1;
1095         my $uo2m = uo2m_extend($self, $uids->[-1]);
1096         $uo2m = [ unpack('S*', $uo2m) ] if !ref($uo2m);
1097         $_ = $uo2m->[$_ - $adj] for @$uids;
1098 }
1099
1100 sub search_uid_range { # long_response
1101         my ($self, $tag, $sql, $range_info, $want_msn) = @_;
1102         my $uids = [];
1103         if (defined(my $err = refill_uids($self, $uids, $range_info, $sql))) {
1104                 $err ||= 'OK Search done';
1105                 $self->write("\r\n$tag $err\r\n");
1106                 return;
1107         }
1108         msn_convert($self, $uids) if $want_msn;
1109         $self->msg_more(join(' ', '', @$uids));
1110         1; # more
1111 }
1112
1113 sub date_search {
1114         my ($q, $k, $d) = @_;
1115         my $sql = $q->{sql};
1116
1117         # Date: header
1118         if ($k eq 'SENTON') {
1119                 my $end = $d + 86399; # no leap day...
1120                 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
1121                 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
1122                 $q->{xap} .= " dt:$da..$db";
1123                 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
1124         } elsif ($k eq 'SENTBEFORE') {
1125                 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
1126                 $$sql .= " AND ds <= $d" if defined($sql);
1127         } elsif ($k eq 'SENTSINCE') {
1128                 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
1129                 $$sql .= " AND ds >= $d" if defined($sql);
1130
1131         # INTERNALDATE (Received)
1132         } elsif ($k eq 'ON') {
1133                 my $end = $d + 86399; # no leap day...
1134                 $q->{xap} .= " ts:$d..$end";
1135                 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
1136         } elsif ($k eq 'BEFORE') {
1137                 $q->{xap} .= " ts:..$d";
1138                 $$sql .= " AND ts <= $d" if defined($sql);
1139         } elsif ($k eq 'SINCE') {
1140                 $q->{xap} .= " ts:$d..";
1141                 $$sql .= " AND ts >= $d" if defined($sql);
1142         } else {
1143                 die "BUG: $k not recognized";
1144         }
1145 }
1146
1147 # IMAP to Xapian search key mapping
1148 my %I2X = (
1149         SUBJECT => 's:',
1150         BODY => 'b:',
1151         FROM => 'f:',
1152         TEXT => '', # n.b. does not include all headers
1153         TO => 't:',
1154         CC => 'c:',
1155         # BCC => 'bcc:', # TODO
1156         # KEYWORD # TODO ? dfpre,dfpost,...
1157 );
1158
1159 # IMAP allows searching arbitrary headers via "HEADER $HDR_NAME $HDR_VAL"
1160 # which gets silly expensive.  We only allow the headers we already index.
1161 my %H2X = (%I2X, 'MESSAGE-ID' => 'm:', 'LIST-ID' => 'l:');
1162
1163 sub xap_append ($$$$) {
1164         my ($q, $rest, $k, $xk) = @_;
1165         delete $q->{sql}; # can't use over.sqlite3
1166         defined(my $arg = shift @$rest) or return "BAD $k no arg";
1167
1168         # AFAIK Xapian can't handle [*"] in probabilistic terms
1169         $arg =~ tr/*"//d;
1170         ${$q->{xap}} .= qq[ $xk"$arg"];
1171         undef;
1172 }
1173
1174 sub parse_query ($$) {
1175         my ($self, $query) = @_;
1176         my $q = PublicInbox::IMAPsearchqp::parse($self, $query);
1177         if (ref($q)) {
1178                 my $max = $self->{ibx}->over->max;
1179                 my $beg = 1;
1180                 uid_clamp($self, \$beg, \$max);
1181                 $q->{range_info} = [ $beg, $max ];
1182         }
1183         $q;
1184 }
1185
1186 sub refill_xap ($$$$) {
1187         my ($self, $uids, $range_info, $q) = @_;
1188         my ($beg, $end) = @$range_info;
1189         my $srch = $self->{ibx}->search;
1190         my $opt = { mset => 2, limit => 1000 };
1191         my $nshard = $srch->{nshard} // 1;
1192         my $mset = $srch->query("$q uid:$beg..$end", $opt);
1193         @$uids = map { mdocid($nshard, $_) } $mset->items;
1194         if (@$uids) {
1195                 $range_info->[0] = $uids->[-1] + 1; # update $beg
1196                 return; # possibly more
1197         }
1198         0; # all done
1199 }
1200
1201 sub search_xap_range { # long_response
1202         my ($self, $tag, $q, $range_info, $want_msn) = @_;
1203         my $uids = [];
1204         if (defined(my $err = refill_xap($self, $uids, $range_info, $q))) {
1205                 $err ||= 'OK Search done';
1206                 $self->write("\r\n$tag $err\r\n");
1207                 return;
1208         }
1209         msn_convert($self, $uids) if $want_msn;
1210         $self->msg_more(join(' ', '', @$uids));
1211         1; # more
1212 }
1213
1214 sub search_common {
1215         my ($self, $tag, $query, $want_msn) = @_;
1216         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1217         my $q = parse_query($self, $query);
1218         return "$tag $q\r\n" if !ref($q);
1219         my ($sql, $range_info) = delete @$q{qw(sql range_info)};
1220         if (!scalar(keys %$q)) { # overview.sqlite3
1221                 $self->msg_more('* SEARCH');
1222                 long_response($self, \&search_uid_range,
1223                                 $tag, $sql, $range_info, $want_msn);
1224         } elsif ($q = $q->{xap}) {
1225                 $self->{ibx}->search or
1226                         return "$tag BAD search not available for mailbox\r\n";
1227                 $self->msg_more('* SEARCH');
1228                 long_response($self, \&search_xap_range,
1229                                 $tag, $q, $range_info, $want_msn);
1230         } else {
1231                 "$tag BAD Error\r\n";
1232         }
1233 }
1234
1235 sub cmd_uid_search ($$$) {
1236         my ($self, $tag, $query) = @_;
1237         search_common($self, $tag, $query);
1238 }
1239
1240 sub cmd_search ($$$;) {
1241         my ($self, $tag, $query) = @_;
1242         search_common($self, $tag, $query, 1);
1243 }
1244
1245 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1246         my ($cb, $argc) = @_;
1247         my $tot = prototype $cb;
1248         my ($nreq, undef) = split(';', $tot);
1249         $nreq = ($nreq =~ tr/$//) - 1;
1250         $tot = ($tot =~ tr/$//) - 1;
1251         ($argc <= $tot && $argc >= $nreq);
1252 }
1253
1254 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1255 sub process_line ($$) {
1256         my ($self, $l) = @_;
1257
1258         # TODO: IMAP allows literals for big requests to upload messages
1259         # (which we don't support) but maybe some big search queries use it.
1260         # RFC 3501 9 (2) doesn't permit TAB or multiple SP
1261         my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1262         pop(@args) if (@args && !defined($args[-1]));
1263         if (@args && uc($req) eq 'UID') {
1264                 $req .= "_".(shift @args);
1265         }
1266         my $res = eval {
1267                 if (defined(my $idle_tag = $self->{-idle_tag})) {
1268                         (uc($tag // '') eq 'DONE' && !defined($req)) ?
1269                                 idle_done($self, $tag) :
1270                                 "$idle_tag BAD expected DONE\r\n";
1271                 } elsif (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1272                         if ($cmd == \&cmd_uid_search || $cmd == \&cmd_search) {
1273                                 # preserve user-supplied quotes for search
1274                                 (undef, @args) = split(/ search /i, $l, 2);
1275                         }
1276                         $cmd->($self, $tag, @args);
1277                 } else { # this is weird
1278                         auth_challenge_ok($self) //
1279                                         ($tag // '*') .
1280                                         ' BAD Error in IMAP command '.
1281                                         ($req // '(???)').
1282                                         ": Unknown command\r\n";
1283                 }
1284         };
1285         my $err = $@;
1286         if ($err && $self->{sock}) {
1287                 $l =~ s/\r?\n//s;
1288                 err($self, 'error from: %s (%s)', $l, $err);
1289                 $tag //= '*';
1290                 $res = "$tag BAD program fault - command not performed\r\n";
1291         }
1292         return 0 unless defined $res;
1293         $self->write($res);
1294 }
1295
1296 sub long_step {
1297         my ($self) = @_;
1298         # wbuf is unset or empty, here; {long} may add to it
1299         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1300         my $more = eval { $cb->($self, @args) };
1301         if ($@ || !$self->{sock}) { # something bad happened...
1302                 delete $self->{long_cb};
1303                 my $elapsed = now() - $t0;
1304                 if ($@) {
1305                         err($self,
1306                             "%s during long response[$fd] - %0.6f",
1307                             $@, $elapsed);
1308                 }
1309                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1310                 $self->close;
1311         } elsif ($more) { # $self->{wbuf}:
1312                 $self->update_idle_time;
1313
1314                 # control passed to git_async_cat if $more == \undef
1315                 requeue_once($self) if !ref($more);
1316         } else { # all done!
1317                 delete $self->{long_cb};
1318                 my $elapsed = now() - $t0;
1319                 my $fd = fileno($self->{sock});
1320                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1321                 my $wbuf = $self->{wbuf}; # do NOT autovivify
1322
1323                 $self->requeue unless $wbuf && @$wbuf;
1324         }
1325 }
1326
1327 sub err ($$;@) {
1328         my ($self, $fmt, @args) = @_;
1329         printf { $self->{imapd}->{err} } $fmt."\n", @args;
1330 }
1331
1332 sub out ($$;@) {
1333         my ($self, $fmt, @args) = @_;
1334         printf { $self->{imapd}->{out} } $fmt."\n", @args;
1335 }
1336
1337 sub long_response ($$;@) {
1338         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1339
1340         my $sock = $self->{sock} or return;
1341         # make sure we disable reading during a long response,
1342         # clients should not be sending us stuff and making us do more
1343         # work while we are stream a response to them
1344         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1345         long_step($self); # kick off!
1346         undef;
1347 }
1348
1349 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1350 sub event_step {
1351         my ($self) = @_;
1352
1353         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1354
1355         $self->update_idle_time;
1356         # only read more requests if we've drained the write buffer,
1357         # otherwise we can be buffering infinitely w/o backpressure
1358
1359         my $rbuf = $self->{rbuf} // \(my $x = '');
1360         my $line = index($$rbuf, "\n");
1361         while ($line < 0) {
1362                 if (length($$rbuf) >= LINE_MAX) {
1363                         $self->write(\"\* BAD request too long\r\n");
1364                         return $self->close;
1365                 }
1366                 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or
1367                                 return uo2m_hibernate($self);
1368                 $line = index($$rbuf, "\n");
1369         }
1370         $line = substr($$rbuf, 0, $line + 1, '');
1371         $line =~ s/\r?\n\z//s;
1372         return $self->close if $line =~ /[[:cntrl:]]/s;
1373         my $t0 = now();
1374         my $fd = fileno($self->{sock});
1375         my $r = eval { process_line($self, $line) };
1376         my $pending = $self->{wbuf} ? ' pending' : '';
1377         out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1378
1379         return $self->close if $r < 0;
1380         $self->rbuf_idle($rbuf);
1381         $self->update_idle_time;
1382
1383         # maybe there's more pipelined data, or we'll have
1384         # to register it for socket-readiness notifications
1385         $self->requeue unless $pending;
1386 }
1387
1388 sub compressed { undef }
1389
1390 sub zflush {} # overridden by IMAPdeflate
1391
1392 # RFC 4978
1393 sub cmd_compress ($$$) {
1394         my ($self, $tag, $alg) = @_;
1395         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1396         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1397
1398         # CRIME made TLS compression obsolete
1399         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1400
1401         PublicInbox::IMAPdeflate->enable($self, $tag);
1402         $self->requeue;
1403         undef
1404 }
1405
1406 sub cmd_starttls ($$) {
1407         my ($self, $tag) = @_;
1408         my $sock = $self->{sock} or return;
1409         if ($sock->can('stop_SSL') || $self->compressed) {
1410                 return "$tag BAD TLS or compression already enabled\r\n";
1411         }
1412         my $opt = $self->{imapd}->{accept_tls} or
1413                 return "$tag BAD can not initiate TLS negotiation\r\n";
1414         $self->write(\"$tag OK begin TLS negotiation now\r\n");
1415         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1416         $self->requeue if PublicInbox::DS::accept_tls_step($self);
1417         undef;
1418 }
1419
1420 # for graceful shutdown in PublicInbox::Daemon:
1421 sub busy {
1422         my ($self, $now) = @_;
1423         if (defined($self->{-idle_tag})) {
1424                 $self->write(\"* BYE server shutting down\r\n");
1425                 return; # not busy anymore
1426         }
1427         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1428 }
1429
1430 sub close {
1431         my ($self) = @_;
1432         if (my $ibx = delete $self->{ibx}) {
1433                 stop_idle($self, $ibx);
1434         }
1435         $self->SUPER::close; # PublicInbox::DS::close
1436 }
1437
1438 # we're read-only, so SELECT and EXAMINE do the same thing
1439 no warnings 'once';
1440 *cmd_select = \&cmd_examine;
1441
1442 package PublicInbox::IMAP_preauth;
1443 our @ISA = qw(PublicInbox::IMAP);
1444
1445 sub logged_in { 0 }
1446
1447 1;