]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
imap: further speed up HEADER.FIELDS FETCH requests
[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 =~ s/(?<!\r)\n/\r\n/sg;
796         $str .= "\r\n";
797 }
798
799 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
800 sub partial_hdr_get {
801         my ($eml, $section_idx, $hdrs_re) = @_;
802         if (defined $section_idx) {
803                 $eml = eml_body_idx($eml, $section_idx) or return;
804         }
805         my $str = $eml->header_obj->as_string;
806         $str = join('', ($str =~ m/($hdrs_re)/g));
807         $str =~ s/(?<!\r)\n/\r\n/sg;
808         $str .= "\r\n";
809 }
810
811 sub partial_prepare ($$$$) {
812         my ($need, $partial, $want, $att) = @_;
813
814         # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
815         # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
816         return unless $att =~ /\ABODY\[/s;
817         until (rindex($att, ']') >= 0) {
818                 my $next = shift @$want or return;
819                 $att .= ' ' . uc($next);
820         }
821         if ($att =~ /\ABODY\[([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
822                         (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
823                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
824                 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
825                 $$need |= CRLF_BREF|EML_HDR|EML_BDY;
826         } elsif ($att =~ /\ABODY\[(?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
827                                 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
828                                 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
829                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
830                 my $tmp = $partial->{$att} = [ $2 ? \&partial_hdr_not
831                                                 : \&partial_hdr_get,
832                                                 $1, undef, $4, $5 ];
833                 $tmp->[2] = hdrs_regexp($3);
834
835                 # don't emit CRLF_HDR instruction, here, partial_hdr_*
836                 # will do CRLF conversion with only the extracted result
837                 # and not waste time converting lines we don't care about.
838                 $$need |= EML_HDR;
839         } else {
840                 undef;
841         }
842 }
843
844 sub partial_emit ($$$) {
845         my ($self, $partial, $eml) = @_;
846         for (@$partial) {
847                 my ($k, $cb, @args) = @$_;
848                 my ($offset, $len) = splice(@args, -2);
849                 # $cb is partial_body|partial_hdr_get|partial_hdr_not
850                 my $str = $cb->($eml, @args) // '';
851                 if (defined $offset) {
852                         if (defined $len) {
853                                 $str = substr($str, $offset, $len);
854                                 $k =~ s/\.$len>\z/>/ or warn
855 "BUG: unable to remove `.$len>' from `$k'";
856                         } else {
857                                 $str = substr($str, $offset);
858                                 $len = length($str);
859                         }
860                 } else {
861                         $len = length($str);
862                 }
863                 $self->msg_more(" $k {$len}\r\n");
864                 $self->msg_more($str);
865         }
866 }
867
868 sub fetch_compile ($) {
869         my ($want) = @_;
870         if ($want->[0] =~ s/\A\(//s) {
871                 $want->[-1] =~ s/\)\z//s or return 'BAD no rparen';
872         }
873         my (%partial, %seen, @op);
874         my $need = 0;
875         while (defined(my $att = shift @$want)) {
876                 $att = uc($att);
877                 next if $att eq 'UID'; # always returned
878                 $att =~ s/\ABODY\.PEEK\[/BODY\[/; # we're read-only
879                 my $x = $FETCH_ATT{$att};
880                 if ($x) {
881                         while (my ($k, $fl_cb) = each %$x) {
882                                 next if $seen{$k}++;
883                                 $need |= $fl_cb->[0];
884                                 push @op, [ @$fl_cb, $k ];
885                         }
886                 } elsif (!partial_prepare(\$need, \%partial, $want, $att)) {
887                         return "BAD param: $att";
888                 }
889         }
890         my @r;
891
892         # stabilize partial order for consistency and ease-of-debugging:
893         if (scalar keys %partial) {
894                 $need |= NEED_BLOB;
895                 $r[2] = [ map { [ $_, @{$partial{$_}} ] } sort keys %partial ];
896         }
897
898         push @op, $OP_EML_NEW if ($need & (EML_HDR|EML_BDY));
899
900         # do we need CRLF conversion?
901         if ($need & CRLF_BREF) {
902                 push @op, $OP_CRLF_BREF;
903         } elsif (my $crlf = ($need & (CRLF_HDR|CRLF_BDY))) {
904                 if ($crlf == (CRLF_HDR|CRLF_BDY)) {
905                         push @op, $OP_CRLF_BREF;
906                 } elsif ($need & CRLF_HDR) {
907                         push @op, $OP_CRLF_HDR;
908                 } else {
909                         push @op, $OP_CRLF_BDY;
910                 }
911         }
912
913         $r[0] = $need & NEED_BLOB ? \&fetch_blob :
914                 ($need & NEED_SMSG ? \&fetch_smsg : \&fetch_uid);
915
916         # r[1] = [ $key1, $cb1, $key2, $cb2, ... ]
917         use sort 'stable'; # makes output more consistent
918         $r[1] = [ map { ($_->[2], $_->[1]) } sort { $a->[0] <=> $b->[0] } @op ];
919         @r;
920 }
921
922 sub cmd_uid_fetch ($$$$;@) {
923         my ($self, $tag, $range_csv, @want) = @_;
924         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
925         my ($cb, $ops, $partial) = fetch_compile(\@want);
926         return "$tag $cb\r\n" unless $ops;
927
928         $range_csv = 'bad' if $range_csv !~ $valid_range;
929         my $range_info = range_step($self, \$range_csv);
930         return "$tag $range_info\r\n" if !ref($range_info);
931         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
932 }
933
934 sub msn_to_uid_range ($$) {
935         my $uid_base = $_[0]->{uid_base};
936         $_[1] =~ s/([0-9]+)/$uid_base + $1/sge;
937 }
938
939 sub cmd_fetch ($$$$;@) {
940         my ($self, $tag, $range_csv, @want) = @_;
941         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
942         my ($cb, $ops, $partial) = fetch_compile(\@want);
943         return "$tag $cb\r\n" unless $ops;
944
945         # cb is one of fetch_blob, fetch_smsg, fetch_uid
946         $range_csv = 'bad' if $range_csv !~ $valid_range;
947         msn_to_uid_range($self, $range_csv);
948         my $range_info = range_step($self, \$range_csv);
949         return "$tag $range_info\r\n" if !ref($range_info);
950         long_response($self, $cb, $tag, [], $range_info, $ops, $partial);
951 }
952
953 sub parse_date ($) { # 02-Oct-1993
954         my ($date_text) = @_;
955         my ($dd, $mon, $yyyy) = split(/-/, $_[0], 3);
956         defined($yyyy) or return;
957         my $mm = $MoY{$mon} // return;
958         $dd =~ /\A[0123]?[0-9]\z/ or return;
959         $yyyy =~ /\A[0-9]{4,}\z/ or return; # Y10K-compatible!
960         timegm(0, 0, 0, $dd, $mm, $yyyy);
961 }
962
963 sub uid_search_uid_range { # long_response
964         my ($self, $tag, $beg, $end, $sql) = @_;
965         my $uids = $self->{ibx}->over->uid_range($$beg, $end, $sql);
966         if (@$uids) {
967                 $$beg = $uids->[-1] + 1;
968                 $self->msg_more(join(' ', '', @$uids));
969         } else {
970                 $self->write(\"\r\n$tag OK Search done\r\n");
971                 undef;
972         }
973 }
974
975 sub date_search {
976         my ($q, $k, $d) = @_;
977         my $sql = $q->{sql};
978
979         # Date: header
980         if ($k eq 'SENTON') {
981                 my $end = $d + 86399; # no leap day...
982                 my $da = strftime('%Y%m%d%H%M%S', gmtime($d));
983                 my $db = strftime('%Y%m%d%H%M%S', gmtime($end));
984                 $q->{xap} .= " dt:$da..$db";
985                 $$sql .= " AND ds >= $d AND ds <= $end" if defined($sql);
986         } elsif ($k eq 'SENTBEFORE') {
987                 $q->{xap} .= ' d:..'.strftime('%Y%m%d', gmtime($d));
988                 $$sql .= " AND ds <= $d" if defined($sql);
989         } elsif ($k eq 'SENTSINCE') {
990                 $q->{xap} .= ' d:'.strftime('%Y%m%d', gmtime($d)).'..';
991                 $$sql .= " AND ds >= $d" if defined($sql);
992
993         # INTERNALDATE (Received)
994         } elsif ($k eq 'ON') {
995                 my $end = $d + 86399; # no leap day...
996                 $q->{xap} .= " ts:$d..$end";
997                 $$sql .= " AND ts >= $d AND ts <= $end" if defined($sql);
998         } elsif ($k eq 'BEFORE') {
999                 $q->{xap} .= " ts:..$d";
1000                 $$sql .= " AND ts <= $d" if defined($sql);
1001         } elsif ($k eq 'SINCE') {
1002                 $q->{xap} .= " ts:$d..";
1003                 $$sql .= " AND ts >= $d" if defined($sql);
1004         } else {
1005                 die "BUG: $k not recognized";
1006         }
1007 }
1008
1009 # IMAP to Xapian search key mapping
1010 my %I2X = (
1011         SUBJECT => 's:',
1012         BODY => 'b:',
1013         FROM => 'f:',
1014         TEXT => '', # n.b. does not include all headers
1015         TO => 't:',
1016         CC => 'c:',
1017         # BCC => 'bcc:', # TODO
1018         # KEYWORD # TODO ? dfpre,dfpost,...
1019 );
1020
1021 sub parse_query {
1022         my ($self, $rest) = @_;
1023         if (uc($rest->[0]) eq 'CHARSET') {
1024                 shift @$rest;
1025                 defined(my $c = shift @$rest) or return 'BAD missing charset';
1026                 $c =~ /\A(?:UTF-8|US-ASCII)\z/ or return 'NO [BADCHARSET]';
1027         }
1028
1029         my $sql = ''; # date conditions, {sql} deleted if Xapian is needed
1030         my $q = { xap => '', sql => \$sql };
1031         while (@$rest) {
1032                 my $k = uc(shift @$rest);
1033                 # default criteria
1034                 next if $k =~ /\A(?:ALL|RECENT|UNSEEN|NEW)\z/;
1035                 next if $k eq 'AND'; # the default, until we support OR
1036                 if ($k =~ $valid_range) { # convert sequence numbers to UIDs
1037                         msn_to_uid_range($self, $k);
1038                         push @{$q->{uid}}, $k;
1039                 } elsif ($k eq 'UID') {
1040                         $k = shift(@$rest) // '';
1041                         $k =~ $valid_range or return 'BAD UID range';
1042                         push @{$q->{uid}}, $k;
1043                 } elsif ($k =~ /\A(?:SENT)?(?:SINCE|ON|BEFORE)\z/) {
1044                         my $d = parse_date(shift(@$rest) // '');
1045                         defined $d or return "BAD $k date format";
1046                         date_search($q, $k, $d);
1047                 } elsif ($k =~ /\A(?:SMALLER|LARGER)\z/) {
1048                         delete $q->{sql}; # can't use over.sqlite3
1049                         my $bytes = shift(@$rest) // '';
1050                         $bytes =~ /\A[0-9]+\z/ or return "BAD $k not a number";
1051                         $q->{xap} .= ' bytes:' . ($k eq 'SMALLER' ?
1052                                                         '..'.(--$bytes) :
1053                                                         (++$bytes).'..');
1054                 } elsif (defined(my $xk = $I2X{$k})) {
1055                         delete $q->{sql}; # can't use over.sqlite3
1056                         my $arg = shift @$rest;
1057                         defined($arg) or return "BAD $k no arg";
1058
1059                         # Xapian can't handle [*"] in probabilistic terms
1060                         $arg =~ tr/*"//d;
1061                         $q->{xap} .= qq[ $xk:"$arg"];
1062                 } else {
1063                         # TODO: parentheses, OR, NOT ...
1064                         return "BAD $k not supported (yet?)";
1065                 }
1066         }
1067
1068         # favor using over.sqlite3 if possible, since Xapian is optional
1069         if (exists $q->{sql}) {
1070                 delete($q->{xap});
1071                 delete($q->{sql}) if $sql eq '';
1072         } elsif (!$self->{ibx}->search) {
1073                 return 'BAD Xapian not configured for mailbox';
1074         }
1075
1076         if (my $uid = $q->{uid}) {
1077                 ((@$uid > 1) || $uid->[0] =~ /,/) and
1078                         return 'BAD multiple ranges not supported, yet';
1079                 ($q->{sql} // $q->{xap}) and
1080                         return 'BAD ranges and queries do not mix, yet';
1081                 $q->{uid} = join(',', @$uid); # TODO: multiple ranges
1082         }
1083         $q;
1084 }
1085
1086 sub cmd_uid_search ($$$;) {
1087         my ($self, $tag) = splice(@_, 0, 2);
1088         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
1089         my $q = parse_query($self, \@_);
1090         return "$tag $q\r\n" if !ref($q);
1091         my $sql = delete $q->{sql};
1092
1093         if (!scalar(keys %$q)) {
1094                 $self->msg_more('* SEARCH');
1095                 my $beg = 1;
1096                 my $end = $ibx->mm->max // 0;
1097                 uid_clamp($self, \$beg, \$end);
1098                 long_response($self, \&uid_search_uid_range,
1099                                 $tag, \$beg, $end, $sql);
1100         } elsif (my $uid = $q->{uid}) {
1101                 if ($uid =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
1102                         my ($beg, $end) = ($1, $2);
1103                         $end = $ibx->mm->max if $end eq '*';
1104                         uid_clamp($self, \$beg, \$end);
1105                         $self->msg_more('* SEARCH');
1106                         long_response($self, \&uid_search_uid_range,
1107                                         $tag, \$beg, $end, $sql);
1108                 } elsif ($uid =~ /\A[0-9]+\z/s) {
1109                         $uid = $ibx->over->get_art($uid) ? " $uid" : '';
1110                         "* SEARCH$uid\r\n$tag OK Search done\r\n";
1111                 } else {
1112                         "$tag BAD Error\r\n";
1113                 }
1114         } else {
1115                 "$tag BAD Error\r\n";
1116         }
1117 }
1118
1119 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
1120         my ($cb, $argc) = @_;
1121         my $tot = prototype $cb;
1122         my ($nreq, undef) = split(';', $tot);
1123         $nreq = ($nreq =~ tr/$//) - 1;
1124         $tot = ($tot =~ tr/$//) - 1;
1125         ($argc <= $tot && $argc >= $nreq);
1126 }
1127
1128 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
1129 sub process_line ($$) {
1130         my ($self, $l) = @_;
1131         my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
1132         pop(@args) if (@args && !defined($args[-1]));
1133         if (@args && uc($req) eq 'UID') {
1134                 $req .= "_".(shift @args);
1135         }
1136         my $res = eval {
1137                 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
1138                         defined($self->{-idle_tag}) ?
1139                                 "$self->{-idle_tag} BAD expected DONE\r\n" :
1140                                 $cmd->($self, $tag, @args);
1141                 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
1142                         cmd_done($self, $tag);
1143                 } else { # this is weird
1144                         auth_challenge_ok($self) //
1145                                         ($tag // '*') .
1146                                         ' BAD Error in IMAP command '.
1147                                         ($req // '(???)').
1148                                         ": Unknown command\r\n";
1149                 }
1150         };
1151         my $err = $@;
1152         if ($err && $self->{sock}) {
1153                 $l =~ s/\r?\n//s;
1154                 err($self, 'error from: %s (%s)', $l, $err);
1155                 $tag //= '*';
1156                 $res = "$tag BAD program fault - command not performed\r\n";
1157         }
1158         return 0 unless defined $res;
1159         $self->write($res);
1160 }
1161
1162 sub long_step {
1163         my ($self) = @_;
1164         # wbuf is unset or empty, here; {long} may add to it
1165         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
1166         my $more = eval { $cb->($self, @args) };
1167         if ($@ || !$self->{sock}) { # something bad happened...
1168                 delete $self->{long_cb};
1169                 my $elapsed = now() - $t0;
1170                 if ($@) {
1171                         err($self,
1172                             "%s during long response[$fd] - %0.6f",
1173                             $@, $elapsed);
1174                 }
1175                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
1176                 $self->close;
1177         } elsif ($more) { # $self->{wbuf}:
1178                 $self->update_idle_time;
1179
1180                 # control passed to $more may be a GitAsyncCat object
1181                 requeue_once($self) if !ref($more);
1182         } else { # all done!
1183                 delete $self->{long_cb};
1184                 my $elapsed = now() - $t0;
1185                 my $fd = fileno($self->{sock});
1186                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
1187                 my $wbuf = $self->{wbuf}; # do NOT autovivify
1188
1189                 $self->requeue unless $wbuf && @$wbuf;
1190         }
1191 }
1192
1193 sub err ($$;@) {
1194         my ($self, $fmt, @args) = @_;
1195         printf { $self->{imapd}->{err} } $fmt."\n", @args;
1196 }
1197
1198 sub out ($$;@) {
1199         my ($self, $fmt, @args) = @_;
1200         printf { $self->{imapd}->{out} } $fmt."\n", @args;
1201 }
1202
1203 sub long_response ($$;@) {
1204         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
1205
1206         my $sock = $self->{sock} or return;
1207         # make sure we disable reading during a long response,
1208         # clients should not be sending us stuff and making us do more
1209         # work while we are stream a response to them
1210         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
1211         long_step($self); # kick off!
1212         undef;
1213 }
1214
1215 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
1216 sub event_step {
1217         my ($self) = @_;
1218
1219         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
1220
1221         $self->update_idle_time;
1222         # only read more requests if we've drained the write buffer,
1223         # otherwise we can be buffering infinitely w/o backpressure
1224
1225         my $rbuf = $self->{rbuf} // \(my $x = '');
1226         my $line = index($$rbuf, "\n");
1227         while ($line < 0) {
1228                 if (length($$rbuf) >= LINE_MAX) {
1229                         $self->write(\"\* BAD request too long\r\n");
1230                         return $self->close;
1231                 }
1232                 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
1233                 $line = index($$rbuf, "\n");
1234         }
1235         $line = substr($$rbuf, 0, $line + 1, '');
1236         $line =~ s/\r?\n\z//s;
1237         return $self->close if $line =~ /[[:cntrl:]]/s;
1238         my $t0 = now();
1239         my $fd = fileno($self->{sock});
1240         my $r = eval { process_line($self, $line) };
1241         my $pending = $self->{wbuf} ? ' pending' : '';
1242         out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
1243
1244         return $self->close if $r < 0;
1245         $self->rbuf_idle($rbuf);
1246         $self->update_idle_time;
1247
1248         # maybe there's more pipelined data, or we'll have
1249         # to register it for socket-readiness notifications
1250         $self->requeue unless $pending;
1251 }
1252
1253 sub compressed { undef }
1254
1255 sub zflush {} # overridden by IMAPdeflate
1256
1257 # RFC 4978
1258 sub cmd_compress ($$$) {
1259         my ($self, $tag, $alg) = @_;
1260         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
1261         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
1262
1263         # CRIME made TLS compression obsolete
1264         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
1265
1266         PublicInbox::IMAPdeflate->enable($self, $tag);
1267         $self->requeue;
1268         undef
1269 }
1270
1271 sub cmd_starttls ($$) {
1272         my ($self, $tag) = @_;
1273         my $sock = $self->{sock} or return;
1274         if ($sock->can('stop_SSL') || $self->compressed) {
1275                 return "$tag BAD TLS or compression already enabled\r\n";
1276         }
1277         my $opt = $self->{imapd}->{accept_tls} or
1278                 return "$tag BAD can not initiate TLS negotiation\r\n";
1279         $self->write(\"$tag OK begin TLS negotiation now\r\n");
1280         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
1281         $self->requeue if PublicInbox::DS::accept_tls_step($self);
1282         undef;
1283 }
1284
1285 # for graceful shutdown in PublicInbox::Daemon:
1286 sub busy {
1287         my ($self, $now) = @_;
1288         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
1289 }
1290
1291 sub close {
1292         my ($self) = @_;
1293         if (my $ibx = delete $self->{ibx}) {
1294                 stop_idle($self, $ibx);
1295         }
1296         $self->SUPER::close; # PublicInbox::DS::close
1297 }
1298
1299 # we're read-only, so SELECT and EXAMINE do the same thing
1300 no warnings 'once';
1301 *cmd_select = \&cmd_examine;
1302
1303 package PublicInbox::IMAP_preauth;
1304 our @ISA = qw(PublicInbox::IMAP);
1305
1306 sub logged_in { 0 }
1307
1308 1;