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