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