]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/IMAP.pm
imap: support IDLE
[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::DS qw(now);
22 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
23 use Errno qw(EAGAIN);
24 my $Address;
25 for my $mod (qw(Email::Address::XS Mail::Address)) {
26         eval "require $mod" or next;
27         $Address = $mod and last;
28 }
29 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
30
31 sub LINE_MAX () { 512 } # does RFC 3501 have a limit like RFC 977?
32
33 my %FETCH_NEED_BLOB = ( # for future optimization
34         'BODY.PEEK[HEADER]' => 1,
35         'BODY.PEEK[TEXT]' => 1,
36         'BODY.PEEK[]' => 1,
37         'BODY[HEADER]' => 1,
38         'BODY[TEXT]' => 1,
39         'BODY[]' => 1,
40         'RFC822.HEADER' => 1,
41         'RFC822.SIZE' => 1, # needs CRLF conversion :<
42         'RFC822.TEXT' => 1,
43         BODY => 1,
44         BODYSTRUCTURE => 1,
45         ENVELOPE => 1,
46         FLAGS => 0,
47         INTERNALDATE => 0,
48         RFC822 => 1,
49         UID => 0,
50 );
51 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED_BLOB;
52
53 # aliases (RFC 3501 section 6.4.5)
54 $FETCH_ATT{FAST} = [ qw(FLAGS INTERNALDATE RFC822.SIZE) ];
55 $FETCH_ATT{ALL} = [ @{$FETCH_ATT{FAST}}, 'ENVELOPE' ];
56 $FETCH_ATT{FULL} = [ @{$FETCH_ATT{ALL}}, 'BODY' ];
57
58 for my $att (keys %FETCH_ATT) {
59         my %h = map { $_ => 1 } @{$FETCH_ATT{$att}};
60         $FETCH_ATT{$att} = \%h;
61 }
62
63 sub greet ($) {
64         my ($self) = @_;
65         my $capa = capa($self);
66         $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
67 }
68
69 sub new ($$$) {
70         my ($class, $sock, $imapd) = @_;
71         my $self = fields::new($class);
72         my $ev = EPOLLIN;
73         my $wbuf;
74         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
75                 return CORE::close($sock) if $! != EAGAIN;
76                 $ev = PublicInbox::TLS::epollbit();
77                 $wbuf = [ \&PublicInbox::DS::accept_tls_step, \&greet ];
78         }
79         $self->SUPER::new($sock, $ev | EPOLLONESHOT);
80         $self->{imapd} = $imapd;
81         if ($wbuf) {
82                 $self->{wbuf} = $wbuf;
83         } else {
84                 greet($self);
85         }
86         $self->update_idle_time;
87         $self;
88 }
89
90 sub capa ($) {
91         my ($self) = @_;
92
93         # dovecot advertises IDLE pre-login; perhaps because some clients
94         # depend on it, so we'll do the same
95         my $capa = 'CAPABILITY IMAP4rev1 IDLE';
96         if ($self->{logged_in}) {
97                 $capa .= ' COMPRESS=DEFLATE';
98         } else {
99                 if (!($self->{sock} // $self)->can('accept_SSL') &&
100                         $self->{imapd}->{accept_tls}) {
101                         $capa .= ' STARTTLS';
102                 }
103                 $capa .= ' AUTH=ANONYMOUS';
104         }
105 }
106
107 sub login_success ($$) {
108         my ($self, $tag) = @_;
109         $self->{logged_in} = 1;
110         my $capa = capa($self);
111         "$tag OK [$capa] Logged in\r\n";
112 }
113
114 sub auth_challenge_ok ($) {
115         my ($self) = @_;
116         my $tag = delete($self->{-login_tag}) or return;
117         login_success($self, $tag);
118 }
119
120 sub cmd_login ($$$$) {
121         my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
122         login_success($self, $tag);
123 }
124
125 sub cmd_logout ($$) {
126         my ($self, $tag) = @_;
127         delete $self->{logged_in};
128         $self->write(\"* BYE logging out\r\n$tag OK logout completed\r\n");
129         $self->shutdn; # PublicInbox::DS::shutdn
130         undef;
131 }
132
133 sub cmd_authenticate ($$$) {
134         my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
135         $self->{-login_tag} = $tag;
136         "+\r\n"; # challenge
137 }
138
139 sub cmd_capability ($$) {
140         my ($self, $tag) = @_;
141         '* '.capa($self)."\r\n$tag OK\r\n";
142 }
143
144 sub cmd_noop ($$) { "$_[1] OK NOOP completed\r\n" }
145
146 # called by PublicInbox::InboxIdle
147 sub on_inbox_unlock {
148         my ($self, $ibx) = @_;
149         my $new = ($ibx->mm->minmax)[1];
150         defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
151         if ($new > $old) {
152                 $self->{-idle_max} = $new;
153                 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
154                 $self->write(\"* $new EXISTS\r\n");
155         }
156 }
157
158 sub cmd_idle ($$) {
159         my ($self, $tag) = @_;
160         # IDLE seems allowed by dovecot w/o a mailbox selected *shrug*
161         my $ibx = $self->{ibx} or return "$tag BAD no mailbox selected\r\n";
162         $ibx->subscribe_unlock(fileno($self->{sock}), $self);
163         $self->{-idle_tag} = $tag;
164         $self->{-idle_max} = ($ibx->mm->minmax)[1] // 0;
165         "+ idling\r\n"
166 }
167
168 sub cmd_done ($$) {
169         my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
170         defined(my $idle_tag = delete $self->{-idle_tag}) or
171                 return "$tag BAD not idle\r\n";
172         my $ibx = $self->{ibx} or do {
173                 warn "BUG: idle_tag set w/o inbox";
174                 return "$tag BAD internal bug\r\n";
175         };
176         $ibx->unsubscribe_unlock(fileno($self->{sock}));
177         "$idle_tag OK Idle completed\r\n";
178 }
179
180 sub cmd_examine ($$$) {
181         my ($self, $tag, $mailbox) = @_;
182         my $ibx = $self->{imapd}->{groups}->{$mailbox} or
183                 return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
184         my $mm = $ibx->mm;
185         my $max = $mm->num_highwater // 0;
186         # RFC 3501 2.3.1.1 -  "A good UIDVALIDITY value to use in
187         # this case is a 32-bit representation of the creation
188         # date/time of the mailbox"
189         my $uidvalidity = $mm->created_at or return "$tag BAD UIDVALIDITY\r\n";
190         my $uidnext = $max + 1;
191
192         # XXX: do we need this? RFC 5162/7162
193         my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
194         $self->{ibx} = $ibx;
195         $ret .= <<EOF;
196 * $max EXISTS\r
197 * $max RECENT\r
198 * FLAGS (\\Seen)\r
199 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
200 EOF
201         $ret .= "* OK [UNSEEN $max]\r\n" if $max;
202         $ret .= "* OK [UIDNEXT $uidnext]\r\n" if defined $uidnext;
203         $ret .= "* OK [UIDVALIDITY $uidvalidity]\r\n" if defined $uidvalidity;
204         $ret .= "$tag OK [READ-ONLY] EXAMINE/SELECT complete\r\n";
205 }
206
207 sub _esc ($) {
208         my ($v) = @_;
209         if (!defined($v)) {
210                 'NIL';
211         } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
212                 '{' . length($v) . "}\r\n" . $v;
213         } else { # quoted string
214                 qq{"$v"}
215         }
216 }
217
218 sub addr_envelope ($$;$) {
219         my ($eml, $x, $y) = @_;
220         my $v = $eml->header_raw($x) //
221                 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
222
223         my @x = $Address->parse($v) or return 'NIL';
224         '(' . join('',
225                 map { '(' . join(' ',
226                                 _esc($_->name), 'NIL',
227                                 _esc($_->user), _esc($_->host)
228                         ) . ')'
229                 } @x) .
230         ')';
231 }
232
233 sub eml_envelope ($) {
234         my ($eml) = @_;
235         '(' . join(' ',
236                 _esc($eml->header_raw('Date')),
237                 _esc($eml->header_raw('Subject')),
238                 addr_envelope($eml, 'From'),
239                 addr_envelope($eml, 'Sender', 'From'),
240                 addr_envelope($eml, 'Reply-To', 'From'),
241                 addr_envelope($eml, 'To'),
242                 addr_envelope($eml, 'Cc'),
243                 addr_envelope($eml, 'Bcc'),
244                 _esc($eml->header_raw('In-Reply-To')),
245                 _esc($eml->header_raw('Message-ID')),
246         ) . ')';
247 }
248
249 sub uid_fetch_cb { # called by git->cat_async
250         my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
251         my ($self, undef, $ibx, undef, undef, $msgs, $want) = @$fetch_m_arg;
252         my $smsg = shift @$msgs or die 'BUG: no smsg';
253         $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
254         $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
255
256         # fixup old bug from import (pre-a0c07cba0e5d8b6a)
257         $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
258
259         $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
260
261         $want->{'RFC822.SIZE'} and
262                 $self->msg_more(' RFC822.SIZE '.length($$bref));
263         $want->{INTERNALDATE} and
264                 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
265         $want->{FLAGS} and $self->msg_more(' FLAGS ()');
266         for ('RFC822', 'BODY[]', 'BODY.PEEK[]') {
267                 next unless $want->{$_};
268                 $self->msg_more(" $_ {".length($$bref)."}\r\n");
269                 $self->msg_more($$bref);
270         }
271
272         my $eml = PublicInbox::Eml->new($bref);
273
274         $want->{ENVELOPE} and
275                 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
276
277         for my $f ('RFC822.HEADER', 'BODY[HEADER]', 'BODY.PEEK[HEADER]') {
278                 next unless $want->{$f};
279                 $self->msg_more(" $f {".length(${$eml->{hdr}})."}\r\n");
280                 $self->msg_more(${$eml->{hdr}});
281         }
282         for my $f ('RFC822.TEXT', 'BODY[TEXT]') {
283                 next unless $want->{$f};
284                 $self->msg_more(" $f {".length($$bref)."}\r\n");
285                 $self->msg_more($$bref);
286         }
287         # TODO BODY/BODYSTRUCTURE, specific headers
288         $self->msg_more(")\r\n");
289 }
290
291 sub uid_fetch_m { # long_response
292         my ($self, $tag, $ibx, $beg, $end, $msgs, $want) = @_;
293         if (!@$msgs) { # refill
294                 @$msgs = @{$ibx->over->query_xover($$beg, $end)};
295                 if (!@$msgs) {
296                         $self->write(\"$tag OK Fetch done\r\n");
297                         return;
298                 }
299                 $$beg = $msgs->[-1]->{num} + 1;
300         }
301         my $git = $ibx->git;
302         $git->cat_async_begin; # TODO: actually make async
303         $git->cat_async($msgs->[0]->{blob}, \&uid_fetch_cb, \@_);
304         $git->cat_async_wait;
305         1;
306 }
307
308 sub cmd_uid_fetch ($$$;@) {
309         my ($self, $tag, $range, @want) = @_;
310         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
311         if ($want[0] =~ s/\A\(//s) {
312                 $want[-1] =~ s/\)\z//s or return "$tag BAD no rparen\r\n";
313         }
314         my %want = map {;
315                 my $x = $FETCH_ATT{uc($_)} or return "$tag BAD param: $_\r\n";
316                 %$x;
317         } @want;
318         my ($beg, $end);
319         my $msgs = [];
320         if ($range =~ /\A([0-9]+):([0-9]+)\z/s) {
321                 ($beg, $end) = ($1, $2);
322         } elsif ($range =~ /\A([0-9]+):\*\z/s) {
323                 ($beg, $end) =  ($1, $ibx->mm->num_highwater // 0);
324         } elsif ($range =~ /\A[0-9]+\z/) {
325                 my $smsg = $ibx->over->get_art($range) or return "$tag OK\r\n";
326                 push @$msgs, $smsg;
327                 ($beg, $end) = ($range, 0);
328         } else {
329                 return "$tag BAD\r\n";
330         }
331         long_response($self, \&uid_fetch_m, $tag, $ibx,
332                                 \$beg, $end, $msgs, \%want);
333 }
334
335 sub uid_search_all { # long_response
336         my ($self, $tag, $ibx, $num) = @_;
337         my $uids = $ibx->mm->ids_after($num);
338         if (scalar(@$uids)) {
339                 $self->msg_more(join(' ', '', @$uids));
340         } else {
341                 $self->write(\"\r\n$tag OK\r\n");
342                 undef;
343         }
344 }
345
346 sub uid_search_uid_range { # long_response
347         my ($self, $tag, $ibx, $beg, $end) = @_;
348         my $uids = $ibx->mm->msg_range($beg, $end, 'num');
349         if (@$uids) {
350                 $self->msg_more(join('', map { " $_->[0]" } @$uids));
351         } else {
352                 $self->write(\"\r\n$tag OK\r\n");
353                 undef;
354         }
355 }
356
357 sub cmd_uid_search ($$$;) {
358         my ($self, $tag, $arg, @rest) = @_;
359         my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
360         $arg = uc($arg);
361         if ($arg eq 'ALL' && !@rest) {
362                 $self->msg_more('* SEARCH');
363                 my $num = 0;
364                 long_response($self, \&uid_search_all, $tag, $ibx, \$num);
365         } elsif ($arg eq 'UID' && scalar(@rest) == 1) {
366                 if ($rest[0] =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
367                         my ($beg, $end) = ($1, $2);
368                         $end = ($ibx->mm->minmax)[1] if $end eq '*';
369                         $self->msg_more('* SEARCH');
370                         long_response($self, \&uid_search_uid_range,
371                                         $tag, $ibx, \$beg, $end);
372                 } elsif ($rest[0] =~ /\A[0-9]+\z/s) {
373                         my $uid = $rest[0];
374                         $uid = $ibx->over->get_art($uid) ? " $uid" : '';
375                         "* SEARCH$uid\r\n$tag OK\r\n";
376                 } else {
377                         "$tag BAD\r\n";
378                 }
379         } else {
380                 "$tag BAD\r\n";
381         }
382 }
383
384 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
385         my ($cb, $argc) = @_;
386         my $tot = prototype $cb;
387         my ($nreq, undef) = split(';', $tot);
388         $nreq = ($nreq =~ tr/$//) - 1;
389         $tot = ($tot =~ tr/$//) - 1;
390         ($argc <= $tot && $argc >= $nreq);
391 }
392
393 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
394 sub process_line ($$) {
395         my ($self, $l) = @_;
396         my ($tag, $req, @args) = split(/[ \t]+/, $l);
397         if (@args && uc($req) eq 'UID') {
398                 $req .= "_".(shift @args);
399         }
400         my $res = eval {
401                 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
402                         defined($self->{-idle_tag}) ?
403                                 "$self->{-idle_tag} BAD expected DONE\r\n" :
404                                 $cmd->($self, $tag, @args);
405                 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
406                         cmd_done($self, $tag);
407                 } else { # this is weird
408                         auth_challenge_ok($self) //
409                                 "$tag BAD Error in IMAP command $req: ".
410                                 "Unknown command\r\n";
411                 }
412         };
413         my $err = $@;
414         if ($err && $self->{sock}) {
415                 $l =~ s/\r?\n//s;
416                 err($self, 'error from: %s (%s)', $l, $err);
417                 $res = "$tag BAD program fault - command not performed\r\n";
418         }
419         return 0 unless defined $res;
420         $self->write($res);
421 }
422
423 sub long_step {
424         my ($self) = @_;
425         # wbuf is unset or empty, here; {long} may add to it
426         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
427         my $more = eval { $cb->($self, @args) };
428         if ($@ || !$self->{sock}) { # something bad happened...
429                 delete $self->{long_cb};
430                 my $elapsed = now() - $t0;
431                 if ($@) {
432                         err($self,
433                             "%s during long response[$fd] - %0.6f",
434                             $@, $elapsed);
435                 }
436                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
437                 $self->close;
438         } elsif ($more) { # $self->{wbuf}:
439                 $self->update_idle_time;
440
441                 # COMPRESS users all share the same DEFLATE context.
442                 # Flush it here to ensure clients don't see
443                 # each other's data
444                 $self->zflush;
445
446                 # no recursion, schedule another call ASAP, but only after
447                 # all pending writes are done.  autovivify wbuf:
448                 my $new_size = push(@{$self->{wbuf}}, \&long_step);
449
450                 # wbuf may be populated by $cb, no need to rearm if so:
451                 $self->requeue if $new_size == 1;
452         } else { # all done!
453                 delete $self->{long_cb};
454                 my $elapsed = now() - $t0;
455                 my $fd = fileno($self->{sock});
456                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
457                 my $wbuf = $self->{wbuf}; # do NOT autovivify
458
459                 $self->requeue unless $wbuf && @$wbuf;
460         }
461 }
462
463 sub err ($$;@) {
464         my ($self, $fmt, @args) = @_;
465         printf { $self->{imapd}->{err} } $fmt."\n", @args;
466 }
467
468 sub out ($$;@) {
469         my ($self, $fmt, @args) = @_;
470         printf { $self->{imapd}->{out} } $fmt."\n", @args;
471 }
472
473 sub long_response ($$;@) {
474         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
475
476         my $sock = $self->{sock} or return;
477         # make sure we disable reading during a long response,
478         # clients should not be sending us stuff and making us do more
479         # work while we are stream a response to them
480         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
481         long_step($self); # kick off!
482         undef;
483 }
484
485 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
486 sub event_step {
487         my ($self) = @_;
488
489         return unless $self->flush_write && $self->{sock};
490
491         $self->update_idle_time;
492         # only read more requests if we've drained the write buffer,
493         # otherwise we can be buffering infinitely w/o backpressure
494
495         my $rbuf = $self->{rbuf} // (\(my $x = ''));
496         my $r = 1;
497
498         if (index($$rbuf, "\n") < 0) {
499                 my $off = length($$rbuf);
500                 $r = $self->do_read($rbuf, LINE_MAX, $off) or return;
501         }
502         while ($r > 0 && $$rbuf =~ s/\A[ \t]*([^\n]*?)\r?\n//) {
503                 my $line = $1;
504                 return $self->close if $line =~ /[[:cntrl:]]/s;
505                 my $t0 = now();
506                 my $fd = fileno($self->{sock});
507                 $r = eval { process_line($self, $line) };
508                 my $pending = $self->{wbuf} ? ' pending' : '';
509                 out($self, "[$fd] %s - %0.6f$pending", $line, now() - $t0);
510         }
511
512         return $self->close if $r < 0;
513         my $len = length($$rbuf);
514         return $self->close if ($len >= LINE_MAX);
515         $self->rbuf_idle($rbuf);
516         $self->update_idle_time;
517
518         # maybe there's more pipelined data, or we'll have
519         # to register it for socket-readiness notifications
520         $self->requeue unless $self->{wbuf};
521 }
522
523 sub compressed { undef }
524
525 sub zflush {} # overridden by IMAPdeflate
526
527 # RFC 4978
528 sub cmd_compress ($$$) {
529         my ($self, $tag, $alg) = @_;
530         return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
531         return "$tag BAD COMPRESS active\r\n" if $self->compressed;
532
533         # CRIME made TLS compression obsolete
534         # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
535
536         PublicInbox::IMAPdeflate->enable($self, $tag);
537         $self->requeue;
538         undef
539 }
540
541 sub cmd_starttls ($$) {
542         my ($self, $tag) = @_;
543         my $sock = $self->{sock} or return;
544         if ($sock->can('stop_SSL') || $self->compressed) {
545                 return "$tag BAD TLS or compression already enabled\r\n";
546         }
547         my $opt = $self->{imapd}->{accept_tls} or
548                 return "$tag BAD can not initiate TLS negotiation\r\n";
549         $self->write(\"$tag OK begin TLS negotiation now\r\n");
550         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
551         $self->requeue if PublicInbox::DS::accept_tls_step($self);
552         undef;
553 }
554
555 # for graceful shutdown in PublicInbox::Daemon:
556 sub busy {
557         my ($self, $now) = @_;
558         ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
559 }
560
561 sub close {
562         my ($self) = @_;
563         if (my $ibx = delete $self->{ibx}) {
564                 if (my $sock = $self->{sock}) {;
565                         $ibx->unsubscribe_unlock(fileno($sock));
566                 }
567         }
568         $self->SUPER::close; # PublicInbox::DS::close
569 }
570
571 # we're read-only, so SELECT and EXAMINE do the same thing
572 no warnings 'once';
573 *cmd_select = \&cmd_examine;
574
575 1;