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