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