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