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