]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
imap: fix multi-message partial header fetches
[public-inbox.git] / lib / PublicInbox / IMAP.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Each instance of this represents an IMAP client connected to
5 # public-inbox-imapd.  Much of this was taken from NNTP, but
6 # further refined while experimenting on future ideas to handle
7 # slow storage.
8 #
9 # data notes:
10 # * NNTP article numbers are UIDs and message sequence numbers (MSNs)
11 # * Message sequence numbers (MSNs) can be stable since we're read-only.
12 #   Most IMAP clients use UIDs (I hope), and we can return a dummy
13 #   message if a client requests a non-existent MSN.
14
15 package PublicInbox::IMAP;
16 use strict;
17 use base qw(PublicInbox::DS);
18 use fields qw(imapd logged_in ibx long_cb -login_tag
19         -idle_tag -idle_max);
20 use PublicInbox::Eml;
21 use PublicInbox::EmlContentFoo qw(parse_content_disposition);
22 use PublicInbox::DS qw(now);
23 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
24 use Text::ParseWords qw(parse_line);
25 use Errno qw(EAGAIN);
26 my $Address;
27 for my $mod (qw(Email::Address::XS Mail::Address)) {
28         eval "require $mod" or next;
29         $Address = $mod and last;
30 }
31 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
32
33 sub LINE_MAX () { 512 } # does RFC 3501 have a limit like RFC 977?
34
35 my %FETCH_NEED_BLOB = ( # for future optimization
36         'BODY.PEEK[HEADER]' => 1,
37         'BODY.PEEK[TEXT]' => 1,
38         'BODY.PEEK[]' => 1,
39         'BODY[HEADER]' => 1,
40         'BODY[TEXT]' => 1,
41         'BODY[]' => 1,
42         'RFC822.HEADER' => 1,
43         'RFC822.SIZE' => 1, # needs CRLF conversion :<
44         'RFC822.TEXT' => 1,
45         BODY => 1,
46         BODYSTRUCTURE => 1,
47         ENVELOPE => 1,
48         FLAGS => 0,
49         INTERNALDATE => 0,
50         RFC822 => 1,
51         UID => 0,
52 );
53 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED_BLOB;
54
55 # aliases (RFC 3501 section 6.4.5)
56 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
57 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
58 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
59
60 for my $att (keys %FETCH_ATT) {
61         my %h = map { $_ => 1 } @{$FETCH_ATT{$att}};
62         $FETCH_ATT{$att} = \%h;
63 }
64
65 sub greet ($) {
66         my ($self) = @_;
67         my $capa = capa($self);
68         $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
69 }
70
71 sub new ($$$) {
72         my ($class, $sock, $imapd) = @_;
73         my $self = fields::new($class);
74         my $ev = EPOLLIN;
75         my $wbuf;
76         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
77                 return CORE::close($sock) if $! != EAGAIN;
78                 $ev = PublicInbox::TLS::epollbit();
79                 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
80         }
81         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
82         $self->{imapd} = $imapd;
83         if ($wbuf) {
84                 $self->{wbuf} = $wbuf;
85         } else {
86                 greet($self);
87         }
88         $self->update_idle_time;
89         $self;
90 }
91
92 sub capa ($) {
93         my ($self) = @_;
94
95         # dovecot advertises IDLE pre-login; perhaps because some clients
96         # depend on it, so we'll do the same
97         my $capa = 'CAPABILITY IMAP4rev1 IDLE';
98         if ($self->{logged_in}) {
99                 $capa .= ' COMPRESS=DEFLATE';
100         } else {
101                 if (!($self->{sock} // $self)->can('accept_SSL') &&
102                         $self->{imapd}->{accept_tls}) {
103                         $capa .= ' STARTTLS';
104                 }
105                 $capa .= ' AUTH=ANONYMOUS';
106         }
107 }
108
109 sub login_success ($$) {
110         my ($self, $tag) = @_;
111         $self->{logged_in} = 1;
112         my $capa = capa($self);
113         "$tag OK [$capa] Logged in\r\n";
114 }
115
116 sub auth_challenge_ok ($) {
117         my ($self) = @_;
118         my $tag = delete($self->{-login_tag}) or return;
119         login_success($self, $tag);
120 }
121
122 sub cmd_login ($$$$) {
123         my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
124         login_success($self, $tag);
125 }
126
127 sub cmd_logout ($$) {
128         my ($self, $tag) = @_;
129         delete $self->{logged_in};
130         $self->write(\"* BYE logging out\r\n$tag OK Logout done\r\n");
131         $self->shutdn; # PublicInbox::DS::shutdn
132         undef;
133 }
134
135 sub cmd_authenticate ($$$) {
136         my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
137         $self->{-login_tag} = $tag;
138         "+\r\n"; # challenge
139 }
140
141 sub cmd_capability ($$) {
142         my ($self, $tag) = @_;
143         '* '.capa($self)."\r\n$tag OK Capability done\r\n";
144 }
145
146 sub cmd_noop ($$) { "$_[1] OK Noop done\r\n" }
147
148 # called by PublicInbox::InboxIdle
149 sub on_inbox_unlock {
150         my ($self, $ibx) = @_;
151         my $new = $ibx->mm->max;
152         defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
153         if ($new > $old) {
154                 $self->{-idle_max} = $new;
155                 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
156                 $self->write(\"* $new EXISTS\r\n");
157         }
158 }
159
160 sub cmd_idle ($$) {
161         my ($self, $tag) = @_;
162         # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
163         my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
164         $ibx->subscribe_unlock(fileno($self->{sock}), $self);
165         $self->{imapd}->idler_start;
166         $self->{-idle_tag} = $tag;
167         $self->{-idle_max} = $ibx->mm->max // 0;
168         "+ idling\r\n"
169 }
170
171 sub cmd_done ($$) {
172         my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
173         defined(my $idle_tag = delete $self->{-idle_tag}) or
174                 return "$tag BAD not idle\r\n";
175         my $ibx = $self->{ibx} or do {
176                 warn "BUG: idle_tag set w/o inbox";
177                 return "$tag BAD internal bug\r\n";
178         };
179         $ibx->unsubscribe_unlock(fileno($self->{sock}));
180         "$idle_tag OK Idle done\r\n";
181 }
182
183 sub cmd_examine ($$$) {
184         my ($self, $tag, $mailbox) = @_;
185         my $ibx = $self->{imapd}->{groups}->{$mailbox} or
186                 return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
187         my $mm = $ibx->mm;
188         my $max = $mm->max // 0;
189         # RFC 3501 2.3.1.1 -  "A good UIDVALIDITY value to use in
190         # this case is a 32-bit representation of the creation
191         # date/time of the mailbox"
192         my $uidvalidity = $mm->created_at or return "$tag BAD UIDVALIDITY\r\n";
193         my $uidnext = $max + 1;
194
195         # XXX: do we need this? RFC 5162/7162
196         my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
197         $self->{ibx} = $ibx;
198         $ret .= <<EOF;
199 * $max EXISTS\r
200 * $max RECENT\r
201 * FLAGS (\\Seen)\r
202 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
203 EOF
204         $ret .= "* OK [UNSEEN $max]\r\n" if $max;
205         $ret .= "* OK [UIDNEXT $uidnext]\r\n" if defined $uidnext;
206         $ret .= "* OK [UIDVALIDITY $uidvalidity]\r\n" if defined $uidvalidity;
207         $ret .= "$tag OK [READ-ONLY] EXAMINE/SELECT done\r\n";
208 }
209
210 sub _esc ($) {
211         my ($v) = @_;
212         if (!defined($v)) {
213                 'NIL';
214         } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
215                 '{' . length($v) . "}\r\n" . $v;
216         } else { # quoted string
217                 qq{"$v"}
218         }
219 }
220
221 sub addr_envelope ($$;$) {
222         my ($eml, $x, $y) = @_;
223         my $v = $eml->header_raw($x) //
224                 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
225
226         my @x = $Address->parse($v) or return 'NIL';
227         '(' . join('',
228                 map { '(' . join(' ',
229                                 _esc($_->name), 'NIL',
230                                 _esc($_->user), _esc($_->host)
231                         ) . ')'
232                 } @x) .
233         ')';
234 }
235
236 sub eml_envelope ($) {
237         my ($eml) = @_;
238         '(' . join(' ',
239                 _esc($eml->header_raw('Date')),
240                 _esc($eml->header_raw('Subject')),
241                 addr_envelope($eml, 'From'),
242                 addr_envelope($eml, 'Sender', 'From'),
243                 addr_envelope($eml, 'Reply-To', 'From'),
244                 addr_envelope($eml, 'To'),
245                 addr_envelope($eml, 'Cc'),
246                 addr_envelope($eml, 'Bcc'),
247                 _esc($eml->header_raw('In-Reply-To')),
248                 _esc($eml->header_raw('Message-ID')),
249         ) . ')';
250 }
251
252 sub _esc_hash ($) {
253         my ($hash) = @_;
254         if ($hash && scalar keys %$hash) {
255                 $hash = [ %$hash ]; # flatten hash into 1-dimensional array
256                 '(' . join(' ', map { _esc($_) } @$hash) . ')';
257         } else {
258                 'NIL';
259         }
260 }
261
262 sub body_disposition ($) {
263         my ($eml) = @_;
264         my $cd = $eml->header_raw('Content-Disposition') or return 'NIL';
265         $cd = parse_content_disposition($cd);
266         my $buf = '('._esc($cd->{type});
267         $buf .= ' ' . _esc_hash(delete $cd->{attributes});
268         $buf .= ')';
269 }
270
271 sub body_leaf ($$;$) {
272         my ($eml, $structure, $hold) = @_;
273         my $buf = '';
274         $eml->{is_submsg} and # parent was a message/(rfc822|news|global)
275                 $buf .= eml_envelope($eml). ' ';
276         my $ct = $eml->ct;
277         $buf .= '('._esc($ct->{type}).' ';
278         $buf .= _esc($ct->{subtype});
279         $buf .= ' ' . _esc_hash(delete $ct->{attributes});
280         $buf .= ' ' . _esc($eml->header_raw('Content-ID'));
281         $buf .= ' ' . _esc($eml->header_raw('Content-Description'));
282         my $cte = $eml->header_raw('Content-Transfer-Encoding') // '7bit';
283         $buf .= ' ' . _esc($cte);
284         $buf .= ' ' . $eml->{imap_body_len};
285         $buf .= ' '.($eml->body_raw =~ tr/\n/\n/) if lc($ct->{type}) eq 'text';
286
287         # for message/(rfc822|global|news), $hold[0] should have envelope
288         $buf .= ' ' . (@$hold ? join('', @$hold) : 'NIL') if $hold;
289
290         if ($structure) {
291                 $buf .= ' '._esc($eml->header_raw('Content-MD5'));
292                 $buf .= ' '. body_disposition($eml);
293                 $buf .= ' '._esc($eml->header_raw('Content-Language'));
294                 $buf .= ' '._esc($eml->header_raw('Content-Location'));
295         }
296         $buf .= ')';
297 }
298
299 sub body_parent ($$$) {
300         my ($eml, $structure, $hold) = @_;
301         my $ct = $eml->ct;
302         my $type = lc($ct->{type});
303         if ($type eq 'multipart') {
304                 my $buf = '(';
305                 $buf .= @$hold ? join('', @$hold) : 'NIL';
306                 $buf .= ' '._esc($ct->{subtype});
307                 if ($structure) {
308                         $buf .= ' '._esc_hash(delete $ct->{attributes});
309                         $buf .= ' '.body_disposition($eml);
310                         $buf .= ' '._esc($eml->header_raw('Content-Language'));
311                         $buf .= ' '._esc($eml->header_raw('Content-Location'));
312                 }
313                 $buf .= ')';
314                 @$hold = ($buf);
315         } else { # message/(rfc822|global|news)
316                 @$hold = (body_leaf($eml, $structure, $hold));
317         }
318 }
319
320 # this is gross, but we need to process the parent part AFTER
321 # the child parts are done
322 sub bodystructure_prep {
323         my ($p, $q) = @_;
324         my ($eml, $depth) = @$p; # ignore idx
325         # set length here, as $eml->{bdy} gets deleted for message/rfc822
326         $eml->{imap_body_len} = length($eml->body_raw);
327         push @$q, $eml, $depth;
328 }
329
330 # for FETCH BODY and FETCH BODYSTRUCTURE
331 sub fetch_body ($;$) {
332         my ($eml, $structure) = @_;
333         my @q;
334         $eml->each_part(\&bodystructure_prep, \@q, 0, 1);
335         my $cur_depth = 0;
336         my @hold;
337         do {
338                 my ($part, $depth) = splice(@q, -2);
339                 my $is_mp_parent = $depth == ($cur_depth - 1);
340                 $cur_depth = $depth;
341
342                 if ($is_mp_parent) {
343                         body_parent($part, $structure, \@hold);
344                 } else {
345                         unshift @hold, body_leaf($part, $structure);
346                 }
347         } while (@q);
348         join('', @hold);
349 }
350
351 sub uid_fetch_cb { # called by git->cat_async
352         my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
353         my ($self, undef, $ibx, undef, undef, $msgs, $want) = @$fetch_m_arg;
354         my $smsg = shift @$msgs or die 'BUG: no smsg';
355         $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
356         $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
357
358         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
359         $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
360
361         $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
362
363         $want->{'RFC822.SIZE'} and
364                 $self->msg_more(' RFC822.SIZE '.length($$bref));
365         $want->{INTERNALDATE} and
366                 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
367         $want->{FLAGS} and $self->msg_more(' FLAGS ()');
368         for ('RFC822', 'BODY[]', 'BODY.PEEK[]') {
369                 next unless $want->{$_};
370                 $self->msg_more(" $_ {".length($$bref)."}\r\n");
371                 $self->msg_more($$bref);
372         }
373
374         my $eml = PublicInbox::Eml->new($bref);
375
376         $want->{ENVELOPE} and
377                 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
378
379         for my $f ('RFC822.HEADER', 'BODY[HEADER]', 'BODY.PEEK[HEADER]') {
380                 next unless $want->{$f};
381                 $self->msg_more(" $f {".length(${$eml->{hdr}})."}\r\n");
382                 $self->msg_more(${$eml->{hdr}});
383         }
384         for my $f ('RFC822.TEXT', 'BODY[TEXT]') {
385                 next unless $want->{$f};
386                 $self->msg_more(" $f {".length($$bref)."}\r\n");
387                 $self->msg_more($$bref);
388         }
389         $want->{BODYSTRUCTURE} and
390                 $self->msg_more(' BODYSTRUCTURE '.fetch_body($eml, 1));
391         $want->{BODY} and
392                 $self->msg_more(' BODY '.fetch_body($eml));
393         if (my $partial = $want->{-partial}) {
394                 partial_emit($self, $partial, $eml);
395         }
396         $self->msg_more(")\r\n");
397 }
398
399 sub uid_fetch_m { # long_response
400         my ($self, $tag, $ibx, $beg, $end, $msgs, $want) = @_;
401         if (!@$msgs) { # refill
402                 @$msgs = @{$ibx->over->query_xover($$beg, $end)};
403                 if (!@$msgs) {
404                         $self->write(\"$tag OK Fetch done\r\n");
405                         return;
406                 }
407                 $$beg = $msgs->[-1]->{num} + 1;
408         }
409         my $git = $ibx->git;
410         $git->cat_async_begin; # TODO: actually make async
411         $git->cat_async($msgs->[0]->{blob}, \&uid_fetch_cb, \@_);
412         $git->cat_async_wait;
413         1;
414 }
415
416 sub cmd_status ($$$;@) {
417         my ($self, $tag, $mailbox, @items) = @_;
418         my $ibx = $self->{imapd}->{groups}->{$mailbox} or
419                 return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
420         return "$tag BAD no items\r\n" if !scalar(@items);
421         ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
422                 return "$tag BAD invalid args\r\n";
423
424         my $mm = $ibx->mm;
425         my ($max, @it);
426         for my $it (@items) {
427                 $it = uc($it);
428                 push @it, $it;
429                 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
430                         push(@it, ($max //= $mm->max // 0));
431                 } elsif ($it eq 'UIDNEXT') {
432                         push(@it, ($max //= $mm->max // 0) + 1);
433                 } elsif ($it eq 'UIDVALIDITY') {
434                         push(@it, $mm->created_at //
435                                 return("$tag BAD UIDVALIDITY\r\n"));
436                 } else {
437                         return "$tag BAD invalid item\r\n";
438                 }
439         }
440         return "$tag BAD no items\r\n" if !@it;
441         "* STATUS $mailbox (".join(' ', @it).")\r\n" .
442         "$tag OK Status done\r\n";
443 }
444
445 my %patmap = ('*' => '.*', '%' => '[^\.]*');
446 sub cmd_list ($$$$) {
447         my ($self, $tag, $refname, $wildcard) = @_;
448         my $l = $self->{imapd}->{inboxlist};
449         if ($refname eq '' && $wildcard eq '') {
450                 # request for hierarchy delimiter
451                 $l = [ qq[* LIST (\\Noselect) "." ""\r\n] ];
452         } elsif ($refname ne '' || $wildcard ne '*') {
453                 $wildcard =~ s!([^a-z0-9_])!$patmap{$1} // "\Q$1"!eig;
454                 $l = [ grep(/ \Q$refname\E$wildcard\r\n\z/s, @$l) ];
455         }
456         \(join('', @$l, "$tag OK List done\r\n"));
457 }
458
459 sub eml_index_offs_i { # PublicInbox::Eml::each_part callback
460         my ($p, $all) = @_;
461         my ($eml, undef, $idx) = @$p;
462         if ($idx && lc($eml->ct->{type}) eq 'multipart') {
463                 $eml->{imap_bdy} = $eml->{bdy} // \'';
464         }
465         $all->{$idx} = $eml; # $idx => Eml
466 }
467
468 # prepares an index for BODY[$SECTION_IDX] fetches
469 sub eml_body_idx ($$) {
470         my ($eml, $section_idx) = @_;
471         my $idx = $eml->{imap_all_parts} //= do {
472                 my $all = {};
473                 $eml->each_part(\&eml_index_offs_i, $all, 0, 1);
474                 # top-level of multipart, BODY[0] not allowed (nz-number)
475                 delete $all->{0};
476                 $all;
477         };
478         $idx->{$section_idx};
479 }
480
481 # BODY[($SECTION_IDX)?(.$SECTION_NAME)?]<$offset.$bytes>
482 sub partial_body {
483         my ($eml, $section_idx, $section_name) = @_;
484         if (defined $section_idx) {
485                 $eml = eml_body_idx($eml, $section_idx) or return;
486         }
487         if (defined $section_name) {
488                 if ($section_name eq 'MIME') {
489                         # RFC 3501 6.4.5 states:
490                         #       The MIME part specifier MUST be prefixed
491                         #       by one or more numeric part specifiers
492                         return unless defined $section_idx;
493                         return $eml->header_obj->as_string . "\r\n";
494                 }
495                 my $bdy = $eml->{bdy} // $eml->{imap_bdy} // \'';
496                 $eml = PublicInbox::Eml->new($$bdy);
497                 if ($section_name eq 'TEXT') {
498                         return $eml->body_raw;
499                 } elsif ($section_name eq 'HEADER') {
500                         return $eml->header_obj->as_string . "\r\n";
501                 } else {
502                         die "BUG: bad section_name=$section_name";
503                 }
504         }
505         ${$eml->{bdy} // $eml->{imap_bdy} // \''};
506 }
507
508 # similar to what's in PublicInbox::Eml::re_memo, but doesn't memoize
509 # to avoid OOM with malicious users
510 sub hdrs_regexp ($) {
511         my ($hdrs) = @_;
512         my $names = join('|', map { "\Q$_" } split(/[ \t]+/, $hdrs));
513         qr/^(?:$names):[ \t]*[^\n]*\r?\n # 1st line
514                 # continuation lines:
515                 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*
516                 /ismx;
517 }
518
519 # BODY[($SECTION_IDX.)?HEADER.FIELDS.NOT ($HDRS)]<$offset.$bytes>
520 sub partial_hdr_not {
521         my ($eml, $section_idx, $hdrs) = @_;
522         if (defined $section_idx) {
523                 $eml = eml_body_idx($eml, $section_idx) or return;
524         }
525         my $str = $eml->header_obj->as_string;
526         my $re = hdrs_regexp($hdrs);
527         $str =~ s/$re//g;
528         $str .= "\r\n";
529 }
530
531 # BODY[($SECTION_IDX.)?HEADER.FIELDS ($HDRS)]<$offset.$bytes>
532 sub partial_hdr_get {
533         my ($eml, $section_idx, $hdrs) = @_;
534         if (defined $section_idx) {
535                 $eml = eml_body_idx($eml, $section_idx) or return;
536         }
537         my $str = $eml->header_obj->as_string;
538         my $re = hdrs_regexp($hdrs);
539         join('', ($str =~ m/($re)/g), "\r\n");
540 }
541
542 sub partial_prepare ($$$) {
543         my ($partial, $want, $att) = @_;
544
545         # recombine [ "BODY[1.HEADER.FIELDS", "(foo", "bar)]" ]
546         # back to: "BODY[1.HEADER.FIELDS (foo bar)]"
547         return unless $att =~ /\ABODY(?:\.PEEK)?\[/s;
548         until (rindex($att, ']') >= 0) {
549                 my $next = shift @$want or return;
550                 $att .= ' ' . uc($next);
551         }
552         if ($att =~ /\ABODY(?:\.PEEK)?\[
553                                 ([0-9]+(?:\.[0-9]+)*)? # 1 - section_idx
554                                 (?:\.(HEADER|MIME|TEXT))? # 2 - section_name
555                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 3, 4
556                 $partial->{$att} = [ \&partial_body, $1, $2, $3, $4 ];
557         } elsif ($att =~ /\ABODY(?:\.PEEK)?\[
558                                 (?:([0-9]+(?:\.[0-9]+)*)\.)? # 1 - section_idx
559                                 (?:HEADER\.FIELDS(\.NOT)?)\x20 # 2
560                                 \(([A-Z0-9\-\x20]+)\) # 3 - hdrs
561                         \](?:<([0-9]+)(?:\.([0-9]+))?>)?\z/sx) { # 4 5
562                 $partial->{$att} = [ $2 ? \&partial_hdr_not
563                                         : \&partial_hdr_get,
564                                         $1, $3, $4, $5 ];
565         } else {
566                 undef;
567         }
568 }
569
570 sub partial_emit ($$$) {
571         my ($self, $partial, $eml) = @_;
572         for my $k (sort keys %$partial) {
573                 my ($cb, @args) = @{$partial->{$k}};
574                 my ($offset, $len) = splice(@args, -2);
575                 # $cb is partial_body|partial_hdr_get|partial_hdr_not
576                 my $str = $cb->($eml, @args) // '';
577                 if (defined $offset) {
578                         if (defined $len) {
579                                 $str = substr($str, $offset, $len);
580                                 $k =~ s/\.$len>\z/>/ or warn
581 "BUG: unable to remove `.$len>' from `$k'";
582                         } else {
583                                 $str = substr($str, $offset);
584                                 $len = length($str);
585                         }
586                 } else {
587                         $len = length($str);
588                 }
589                 $self->msg_more(" $k {$len}\r\n");
590                 $self->msg_more($str);
591         }
592 }
593
594 sub cmd_uid_fetch ($$$;@) {
595         my ($self, $tag, $range, @want) = @_;
596         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
597         if ($want[0] =~ s/\A\(//s) {
598                 $want[-1] =~ s/\)\z//s or return "$tag BAD no rparen\r\n";
599         }
600         my (%partial, %want);
601         while (defined(my $att = shift @want)) {
602                 $att = uc($att);
603                 my $x = $FETCH_ATT{$att};
604                 if ($x) {
605                         %want = (%want, %$x);
606                 } elsif (!partial_prepare(\%partial, \@want, $att)) {
607                         return "$tag BAD param: $att\r\n";
608                 }
609         }
610         $want{-partial} = \%partial if scalar keys %partial;
611         my ($beg, $end);
612         my $msgs = [];
613         if ($range =~ /\A([0-9]+):([0-9]+)\z/s) {
614                 ($beg, $end) = ($1, $2);
615         } elsif ($range =~ /\A([0-9]+):\*\z/s) {
616                 ($beg, $end) =  ($1, $ibx->mm->max // 0);
617         } elsif ($range =~ /\A[0-9]+\z/) {
618                 my $smsg = $ibx->over->get_art($range) or
619                         return "$tag OK Fetch done\r\n"; # really OK(!)
620                 push @$msgs, $smsg;
621                 ($beg, $end) = ($range, 0);
622         } else {
623                 return "$tag BAD fetch range\r\n";
624         }
625         long_response($self, \&uid_fetch_m, $tag, $ibx,
626                                 \$beg, $end, $msgs, \%want);
627 }
628
629 sub uid_search_all { # long_response
630         my ($self, $tag, $ibx, $num) = @_;
631         my $uids = $ibx->mm->ids_after($num);
632         if (scalar(@$uids)) {
633                 $self->msg_more(join(' ', '', @$uids));
634         } else {
635                 $self->write(\"\r\n$tag OK Search done\r\n");
636                 undef;
637         }
638 }
639
640 sub uid_search_uid_range { # long_response
641         my ($self, $tag, $ibx, $beg, $end) = @_;
642         my $uids = $ibx->mm->msg_range($beg, $end, 'num');
643         if (@$uids) {
644                 $self->msg_more(join('', map { " $_->[0]" } @$uids));
645         } else {
646                 $self->write(\"\r\n$tag OK Search done\r\n");
647                 undef;
648         }
649 }
650
651 sub cmd_uid_search ($$$;) {
652         my ($self, $tag, $arg, @rest) = @_;
653         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
654         $arg = uc($arg);
655         if ($arg eq 'ALL' && !@rest) {
656                 $self->msg_more('* SEARCH');
657                 my $num = 0;
658                 long_response($self, \&uid_search_all, $tag, $ibx, \$num);
659         } elsif ($arg eq 'UID' && scalar(@rest) == 1) {
660                 if ($rest[0] =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
661                         my ($beg, $end) = ($1, $2);
662                         $end = $ibx->mm->max if $end eq '*';
663                         $self->msg_more('* SEARCH');
664                         long_response($self, \&uid_search_uid_range,
665                                         $tag, $ibx, \$beg, $end);
666                 } elsif ($rest[0] =~ /\A[0-9]+\z/s) {
667                         my $uid = $rest[0];
668                         $uid = $ibx->over->get_art($uid) ? " $uid" : '';
669                         "* SEARCH$uid\r\n$tag OK Search done\r\n";
670                 } else {
671                         "$tag BAD Error\r\n";
672                 }
673         } else {
674                 "$tag BAD Error\r\n";
675         }
676 }
677
678 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
679         my ($cb, $argc) = @_;
680         my $tot = prototype $cb;
681         my ($nreq, undef) = split(';', $tot);
682         $nreq = ($nreq =~ tr/$//) - 1;
683         $tot = ($tot =~ tr/$//) - 1;
684         ($argc <= $tot && $argc >= $nreq);
685 }
686
687 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
688 sub process_line ($$) {
689         my ($self, $l) = @_;
690         my ($tag, $req, @args) = parse_line('[ \t]+', 0, $l);
691         pop(@args) if (@args && !defined($args[-1]));
692         if (@args && uc($req) eq 'UID') {
693                 $req .= "_".(shift @args);
694         }
695         my $res = eval {
696                 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
697                         defined($self->{-idle_tag}) ?
698                                 "$self->{-idle_tag} BAD expected DONE\r\n" :
699                                 $cmd->($self, $tag, @args);
700                 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
701                         cmd_done($self, $tag);
702                 } else { # this is weird
703                         auth_challenge_ok($self) //
704                                 "$tag BAD Error in IMAP command $req: ".
705                                 "Unknown command\r\n";
706                 }
707         };
708         my $err = $@;
709         if ($err && $self->{sock}) {
710                 $l =~ s/\r?\n//s;
711                 err($self, 'error from: %s (%s)', $l, $err);
712                 $res = "$tag BAD program fault - command not performed\r\n";
713         }
714         return 0 unless defined $res;
715         $self->write($res);
716 }
717
718 sub long_step {
719         my ($self) = @_;
720         # wbuf is unset or empty, here; {long} may add to it
721         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
722         my $more = eval { $cb->($self, @args) };
723         if ($@ || !$self->{sock}) { # something bad happened...
724                 delete $self->{long_cb};
725                 my $elapsed = now() - $t0;
726                 if ($@) {
727                         err($self,
728                             "%s during long response[$fd] - %0.6f",
729                             $@, $elapsed);
730                 }
731                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
732                 $self->close;
733         } elsif ($more) { # $self->{wbuf}:
734                 $self->update_idle_time;
735
736                 # COMPRESS users all share the same DEFLATE context.
737                 # Flush it here to ensure clients don't see
738                 # each other's data
739                 $self->zflush;
740
741                 # no recursion, schedule another call ASAP, but only after
742                 # all pending writes are done.  autovivify wbuf:
743                 my $new_size = push(@{$self->{wbuf}}, \&long_step);
744
745                 # wbuf may be populated by $cb, no need to rearm if so:
746                 $self->requeue if $new_size == 1;
747         } else { # all done!
748                 delete $self->{long_cb};
749                 my $elapsed = now() - $t0;
750                 my $fd = fileno($self->{sock});
751                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
752                 my $wbuf = $self->{wbuf}; # do NOT autovivify
753
754                 $self->requeue unless $wbuf && @$wbuf;
755         }
756 }
757
758 sub err ($$;@) {
759         my ($self, $fmt, @args) = @_;
760         printf { $self->{imapd}->{err} } $fmt."\n", @args;
761 }
762
763 sub out ($$;@) {
764         my ($self, $fmt, @args) = @_;
765         printf { $self->{imapd}->{out} } $fmt."\n", @args;
766 }
767
768 sub long_response ($$;@) {
769         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
770
771         my $sock = $self->{sock} or return;
772         # make sure we disable reading during a long response,
773         # clients should not be sending us stuff and making us do more
774         # work while we are stream a response to them
775         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
776         long_step($self); # kick off!
777         undef;
778 }
779
780 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
781 sub event_step {
782         my ($self) = @_;
783
784         return unless $self->flush_write && $self->{sock};
785
786         $self->update_idle_time;
787         # only read more requests if we've drained the write buffer,
788         # otherwise we can be buffering infinitely w/o backpressure
789
790         my $rbuf = $self->{rbuf} // (\(my $x = ''));
791         my $r = 1;
792
793         if (index($$rbuf, "\n") < 0) {
794                 my $off = length($$rbuf);
795                 $r = $self->do_read($rbuf, LINE_MAX, $off) or return;
796         }
797         while ($r > 0 && $$rbuf =~ s/\A[ \t]*([^\n]*?)\r?\n//) {
798                 my $line = $1;
799                 return $self->close if $line =~ /[[:cntrl:]]/s;
800                 my $t0 = now();
801                 my $fd = fileno($self->{sock});
802                 $r = eval { process_line($self, $line) };
803                 my $pending = $self->{wbuf} ? ' pending' : '';
804                 out($self, "[$fd] %s - %0.6f$pending", $line, now() - $t0);
805         }
806
807         return $self->close if $r < 0;
808         my $len = length($$rbuf);
809         return $self->close if ($len >= LINE_MAX);
810         $self->rbuf_idle($rbuf);
811         $self->update_idle_time;
812
813         # maybe there's more pipelined data, or we'll have
814         # to register it for socket-readiness notifications
815         $self->requeue unless $self->{wbuf};
816 }
817
818 sub compressed { undef }
819
820 sub zflush {} # overridden by IMAPdeflate
821
822 # RFC 4978
823 sub cmd_compress ($$$) {
824         my ($self, $tag, $alg) = @_;
825         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
826         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
827
828         # CRIME made TLS compression obsolete
829         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
830
831         PublicInbox::IMAPdeflate->enable($self, $tag);
832         $self->requeue;
833         undef
834 }
835
836 sub cmd_starttls ($$) {
837         my ($self, $tag) = @_;
838         my $sock = $self->{sock} or return;
839         if ($sock->can('stop_SSL') || $self->compressed) {
840                 return "$tag BAD TLS or compression already enabled\r\n";
841         }
842         my $opt = $self->{imapd}->{accept_tls} or
843                 return "$tag BAD can not initiate TLS negotiation\r\n";
844         $self->write(\"$tag OK begin TLS negotiation now\r\n");
845         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
846         $self->requeue if PublicInbox::DS::accept_tls_step($self);
847         undef;
848 }
849
850 # for graceful shutdown in PublicInbox::Daemon:
851 sub busy {
852         my ($self, $now) = @_;
853         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
854 }
855
856 sub close {
857         my ($self) = @_;
858         if (my $ibx = delete $self->{ibx}) {
859                 if (my $sock = $self->{sock}) {;
860                         $ibx->unsubscribe_unlock(fileno($sock));
861                 }
862         }
863         $self->SUPER::close; # PublicInbox::DS::close
864 }
865
866 # we're read-only, so SELECT and EXAMINE do the same thing
867 no warnings 'once';
868 *cmd_select = \&cmd_examine;
869
870 1;