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