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