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