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