1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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
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.
15 package PublicInbox::IMAP;
17 use base qw(PublicInbox::DS);
18 use fields qw(imapd logged_in ibx long_cb -login_tag
21 use PublicInbox::DS qw(now);
22 use PublicInbox::Syscall qw(EPOLLIN EPOLLONESHOT);
25 for my $mod (qw(Email::Address::XS Mail::Address)) {
26 eval "require $mod" or next;
27 $Address = $mod and last;
29 die "neither Email::Address::XS nor Mail::Address loaded: $@" if !$Address;
31 sub LINE_MAX () { 512 } # does RFC 3501 have a limit like RFC 977?
33 my %FETCH_NEED_BLOB = ( # for future optimization
34 'BODY.PEEK[HEADER]' => 1,
35 'BODY.PEEK[TEXT]' => 1,
41 'RFC822.SIZE' => 1, # needs CRLF conversion :<
51 my %FETCH_ATT = map { $_ => [ $_ ] } keys %FETCH_NEED_BLOB;
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' ];
58 for my $att (keys %FETCH_ATT) {
59 my %h = map { $_ => 1 } @{$FETCH_ATT{$att}};
60 $FETCH_ATT{$att} = \%h;
65 my $capa = capa($self);
66 $self->write(\"* OK [$capa] public-inbox-imapd ready\r\n");
70 my ($class, $sock, $imapd) = @_;
71 my $self = fields::new($class);
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 ];
79 $self->SUPER::new($sock, $ev | EPOLLONESHOT);
80 $self->{imapd} = $imapd;
82 $self->{wbuf} = $wbuf;
86 $self->update_idle_time;
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';
99 if (!($self->{sock} // $self)->can('accept_SSL') &&
100 $self->{imapd}->{accept_tls}) {
101 $capa .= ' STARTTLS';
103 $capa .= ' AUTH=ANONYMOUS';
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";
114 sub auth_challenge_ok ($) {
116 my $tag = delete($self->{-login_tag}) or return;
117 login_success($self, $tag);
120 sub cmd_login ($$$$) {
121 my ($self, $tag) = @_; # ignore ($user, $password) = ($_[2], $_[3])
122 login_success($self, $tag);
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
133 sub cmd_authenticate ($$$) {
134 my ($self, $tag) = @_; # $method = $_[2], should be "ANONYMOUS"
135 $self->{-login_tag} = $tag;
139 sub cmd_capability ($$) {
140 my ($self, $tag) = @_;
141 '* '.capa($self)."\r\n$tag OK\r\n";
144 sub cmd_noop ($$) { "$_[1] OK NOOP completed\r\n" }
146 # called by PublicInbox::InboxIdle
147 sub on_inbox_unlock {
148 my ($self, $ibx) = @_;
149 my $new = $ibx->mm->max;
150 defined(my $old = $self->{-idle_max}) or die 'BUG: -idle_max unset';
152 $self->{-idle_max} = $new;
153 $self->msg_more("* $_ EXISTS\r\n") for (($old + 1)..($new - 1));
154 $self->write(\"* $new EXISTS\r\n");
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->{imapd}->idler_start;
164 $self->{-idle_tag} = $tag;
165 $self->{-idle_max} = $ibx->mm->max // 0;
170 my ($self, $tag) = @_; # $tag is "DONE" (case-insensitive)
171 defined(my $idle_tag = delete $self->{-idle_tag}) or
172 return "$tag BAD not idle\r\n";
173 my $ibx = $self->{ibx} or do {
174 warn "BUG: idle_tag set w/o inbox";
175 return "$tag BAD internal bug\r\n";
177 $ibx->unsubscribe_unlock(fileno($self->{sock}));
178 "$idle_tag OK Idle completed\r\n";
181 sub cmd_examine ($$$) {
182 my ($self, $tag, $mailbox) = @_;
183 my $ibx = $self->{imapd}->{groups}->{$mailbox} or
184 return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
186 my $max = $mm->max // 0;
187 # RFC 3501 2.3.1.1 - "A good UIDVALIDITY value to use in
188 # this case is a 32-bit representation of the creation
189 # date/time of the mailbox"
190 my $uidvalidity = $mm->created_at or return "$tag BAD UIDVALIDITY\r\n";
191 my $uidnext = $max + 1;
193 # XXX: do we need this? RFC 5162/7162
194 my $ret = $self->{ibx} ? "* OK [CLOSED] previous closed\r\n" : '';
200 * OK [PERMANENTFLAGS ()] Read-only mailbox\r
202 $ret .= "* OK [UNSEEN $max]\r\n" if $max;
203 $ret .= "* OK [UIDNEXT $uidnext]\r\n" if defined $uidnext;
204 $ret .= "* OK [UIDVALIDITY $uidvalidity]\r\n" if defined $uidvalidity;
205 $ret .= "$tag OK [READ-ONLY] EXAMINE/SELECT complete\r\n";
212 } elsif ($v =~ /[{"\r\n%*\\\[]/) { # literal string
213 '{' . length($v) . "}\r\n" . $v;
214 } else { # quoted string
219 sub addr_envelope ($$;$) {
220 my ($eml, $x, $y) = @_;
221 my $v = $eml->header_raw($x) //
222 ($y ? $eml->header_raw($y) : undef) // return 'NIL';
224 my @x = $Address->parse($v) or return 'NIL';
226 map { '(' . join(' ',
227 _esc($_->name), 'NIL',
228 _esc($_->user), _esc($_->host)
234 sub eml_envelope ($) {
237 _esc($eml->header_raw('Date')),
238 _esc($eml->header_raw('Subject')),
239 addr_envelope($eml, 'From'),
240 addr_envelope($eml, 'Sender', 'From'),
241 addr_envelope($eml, 'Reply-To', 'From'),
242 addr_envelope($eml, 'To'),
243 addr_envelope($eml, 'Cc'),
244 addr_envelope($eml, 'Bcc'),
245 _esc($eml->header_raw('In-Reply-To')),
246 _esc($eml->header_raw('Message-ID')),
250 sub uid_fetch_cb { # called by git->cat_async
251 my ($bref, $oid, $type, $size, $fetch_m_arg) = @_;
252 my ($self, undef, $ibx, undef, undef, $msgs, $want) = @$fetch_m_arg;
253 my $smsg = shift @$msgs or die 'BUG: no smsg';
254 $smsg->{blob} eq $oid or die "BUG: $smsg->{blob} != $oid";
255 $$bref =~ s/(?<!\r)\n/\r\n/sg; # make strict clients happy
257 # fixup old bug from import (pre-a0c07cba0e5d8b6a)
258 $$bref =~ s/\A[\r\n]*From [^\r\n]*\r\n//s;
260 $self->msg_more("* $smsg->{num} FETCH (UID $smsg->{num}");
262 $want->{'RFC822.SIZE'} and
263 $self->msg_more(' RFC822.SIZE '.length($$bref));
264 $want->{INTERNALDATE} and
265 $self->msg_more(' INTERNALDATE "'.$smsg->internaldate.'"');
266 $want->{FLAGS} and $self->msg_more(' FLAGS ()');
267 for ('RFC822', 'BODY[]', 'BODY.PEEK[]') {
268 next unless $want->{$_};
269 $self->msg_more(" $_ {".length($$bref)."}\r\n");
270 $self->msg_more($$bref);
273 my $eml = PublicInbox::Eml->new($bref);
275 $want->{ENVELOPE} and
276 $self->msg_more(' ENVELOPE '.eml_envelope($eml));
278 for my $f ('RFC822.HEADER', 'BODY[HEADER]', 'BODY.PEEK[HEADER]') {
279 next unless $want->{$f};
280 $self->msg_more(" $f {".length(${$eml->{hdr}})."}\r\n");
281 $self->msg_more(${$eml->{hdr}});
283 for my $f ('RFC822.TEXT', 'BODY[TEXT]') {
284 next unless $want->{$f};
285 $self->msg_more(" $f {".length($$bref)."}\r\n");
286 $self->msg_more($$bref);
288 # TODO BODY/BODYSTRUCTURE, specific headers
289 $self->msg_more(")\r\n");
292 sub uid_fetch_m { # long_response
293 my ($self, $tag, $ibx, $beg, $end, $msgs, $want) = @_;
294 if (!@$msgs) { # refill
295 @$msgs = @{$ibx->over->query_xover($$beg, $end)};
297 $self->write(\"$tag OK Fetch done\r\n");
300 $$beg = $msgs->[-1]->{num} + 1;
303 $git->cat_async_begin; # TODO: actually make async
304 $git->cat_async($msgs->[0]->{blob}, \&uid_fetch_cb, \@_);
305 $git->cat_async_wait;
309 sub cmd_status ($$$;@) {
310 my ($self, $tag, $mailbox, @items) = @_;
311 my $ibx = $self->{imapd}->{groups}->{$mailbox} or
312 return "$tag NO Mailbox doesn't exist: $mailbox\r\n";
313 return "$tag BAD no items\r\n" if !scalar(@items);
314 ($items[0] !~ s/\A\(//s || $items[-1] !~ s/\)\z//s) and
315 return "$tag BAD invalid args\r\n";
319 for my $it (@items) {
322 if ($it =~ /\A(?:MESSAGES|UNSEEN|RECENT)\z/) {
323 push(@it, ($max //= $mm->max // 0));
324 } elsif ($it eq 'UIDNEXT') {
325 push(@it, ($max //= $mm->max // 0) + 1);
326 } elsif ($it eq 'UIDVALIDITY') {
327 push(@it, $mm->created_at //
328 return("$tag BAD UIDVALIDITY\r\n"));
330 return "$tag BAD invalid item\r\n";
333 return "$tag BAD no items\r\n" if !@it;
334 "* STATUS $mailbox (".join(' ', @it).")\r\n" .
335 "$tag OK Status complete\r\n";
338 sub cmd_uid_fetch ($$$;@) {
339 my ($self, $tag, $range, @want) = @_;
340 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
341 if ($want[0] =~ s/\A\(//s) {
342 $want[-1] =~ s/\)\z//s or return "$tag BAD no rparen\r\n";
345 my $x = $FETCH_ATT{uc($_)} or return "$tag BAD param: $_\r\n";
350 if ($range =~ /\A([0-9]+):([0-9]+)\z/s) {
351 ($beg, $end) = ($1, $2);
352 } elsif ($range =~ /\A([0-9]+):\*\z/s) {
353 ($beg, $end) = ($1, $ibx->mm->max // 0);
354 } elsif ($range =~ /\A[0-9]+\z/) {
355 my $smsg = $ibx->over->get_art($range) or return "$tag OK\r\n";
357 ($beg, $end) = ($range, 0);
359 return "$tag BAD\r\n";
361 long_response($self, \&uid_fetch_m, $tag, $ibx,
362 \$beg, $end, $msgs, \%want);
365 sub uid_search_all { # long_response
366 my ($self, $tag, $ibx, $num) = @_;
367 my $uids = $ibx->mm->ids_after($num);
368 if (scalar(@$uids)) {
369 $self->msg_more(join(' ', '', @$uids));
371 $self->write(\"\r\n$tag OK\r\n");
376 sub uid_search_uid_range { # long_response
377 my ($self, $tag, $ibx, $beg, $end) = @_;
378 my $uids = $ibx->mm->msg_range($beg, $end, 'num');
380 $self->msg_more(join('', map { " $_->[0]" } @$uids));
382 $self->write(\"\r\n$tag OK\r\n");
387 sub cmd_uid_search ($$$;) {
388 my ($self, $tag, $arg, @rest) = @_;
389 my $ibx = $self->{ibx} or return "$tag BAD No mailbox selected\r\n";
391 if ($arg eq 'ALL' && !@rest) {
392 $self->msg_more('* SEARCH');
394 long_response($self, \&uid_search_all, $tag, $ibx, \$num);
395 } elsif ($arg eq 'UID' && scalar(@rest) == 1) {
396 if ($rest[0] =~ /\A([0-9]+):([0-9]+|\*)\z/s) {
397 my ($beg, $end) = ($1, $2);
398 $end = $ibx->mm->max if $end eq '*';
399 $self->msg_more('* SEARCH');
400 long_response($self, \&uid_search_uid_range,
401 $tag, $ibx, \$beg, $end);
402 } elsif ($rest[0] =~ /\A[0-9]+\z/s) {
404 $uid = $ibx->over->get_art($uid) ? " $uid" : '';
405 "* SEARCH$uid\r\n$tag OK\r\n";
414 sub args_ok ($$) { # duplicated from PublicInbox::NNTP
415 my ($cb, $argc) = @_;
416 my $tot = prototype $cb;
417 my ($nreq, undef) = split(';', $tot);
418 $nreq = ($nreq =~ tr/$//) - 1;
419 $tot = ($tot =~ tr/$//) - 1;
420 ($argc <= $tot && $argc >= $nreq);
423 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
424 sub process_line ($$) {
426 my ($tag, $req, @args) = split(/[ \t]+/, $l);
427 if (@args && uc($req) eq 'UID') {
428 $req .= "_".(shift @args);
431 if (my $cmd = $self->can('cmd_'.lc($req // ''))) {
432 defined($self->{-idle_tag}) ?
433 "$self->{-idle_tag} BAD expected DONE\r\n" :
434 $cmd->($self, $tag, @args);
435 } elsif (uc($tag // '') eq 'DONE' && !defined($req)) {
436 cmd_done($self, $tag);
437 } else { # this is weird
438 auth_challenge_ok($self) //
439 "$tag BAD Error in IMAP command $req: ".
440 "Unknown command\r\n";
444 if ($err && $self->{sock}) {
446 err($self, 'error from: %s (%s)', $l, $err);
447 $res = "$tag BAD program fault - command not performed\r\n";
449 return 0 unless defined $res;
455 # wbuf is unset or empty, here; {long} may add to it
456 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
457 my $more = eval { $cb->($self, @args) };
458 if ($@ || !$self->{sock}) { # something bad happened...
459 delete $self->{long_cb};
460 my $elapsed = now() - $t0;
463 "%s during long response[$fd] - %0.6f",
466 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
468 } elsif ($more) { # $self->{wbuf}:
469 $self->update_idle_time;
471 # COMPRESS users all share the same DEFLATE context.
472 # Flush it here to ensure clients don't see
476 # no recursion, schedule another call ASAP, but only after
477 # all pending writes are done. autovivify wbuf:
478 my $new_size = push(@{$self->{wbuf}}, \&long_step);
480 # wbuf may be populated by $cb, no need to rearm if so:
481 $self->requeue if $new_size == 1;
483 delete $self->{long_cb};
484 my $elapsed = now() - $t0;
485 my $fd = fileno($self->{sock});
486 out($self, " deferred[$fd] done - %0.6f", $elapsed);
487 my $wbuf = $self->{wbuf}; # do NOT autovivify
489 $self->requeue unless $wbuf && @$wbuf;
494 my ($self, $fmt, @args) = @_;
495 printf { $self->{imapd}->{err} } $fmt."\n", @args;
499 my ($self, $fmt, @args) = @_;
500 printf { $self->{imapd}->{out} } $fmt."\n", @args;
503 sub long_response ($$;@) {
504 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
506 my $sock = $self->{sock} or return;
507 # make sure we disable reading during a long response,
508 # clients should not be sending us stuff and making us do more
509 # work while we are stream a response to them
510 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
511 long_step($self); # kick off!
515 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
519 return unless $self->flush_write && $self->{sock};
521 $self->update_idle_time;
522 # only read more requests if we've drained the write buffer,
523 # otherwise we can be buffering infinitely w/o backpressure
525 my $rbuf = $self->{rbuf} // (\(my $x = ''));
528 if (index($$rbuf, "\n") < 0) {
529 my $off = length($$rbuf);
530 $r = $self->do_read($rbuf, LINE_MAX, $off) or return;
532 while ($r > 0 && $$rbuf =~ s/\A[ \t]*([^\n]*?)\r?\n//) {
534 return $self->close if $line =~ /[[:cntrl:]]/s;
536 my $fd = fileno($self->{sock});
537 $r = eval { process_line($self, $line) };
538 my $pending = $self->{wbuf} ? ' pending' : '';
539 out($self, "[$fd] %s - %0.6f$pending", $line, now() - $t0);
542 return $self->close if $r < 0;
543 my $len = length($$rbuf);
544 return $self->close if ($len >= LINE_MAX);
545 $self->rbuf_idle($rbuf);
546 $self->update_idle_time;
548 # maybe there's more pipelined data, or we'll have
549 # to register it for socket-readiness notifications
550 $self->requeue unless $self->{wbuf};
553 sub compressed { undef }
555 sub zflush {} # overridden by IMAPdeflate
558 sub cmd_compress ($$$) {
559 my ($self, $tag, $alg) = @_;
560 return "$tag BAD DEFLATE only\r\n" if uc($alg) ne "DEFLATE";
561 return "$tag BAD COMPRESS active\r\n" if $self->compressed;
563 # CRIME made TLS compression obsolete
564 # return "$tag NO [COMPRESSIONACTIVE]\r\n" if $self->tls_compressed;
566 PublicInbox::IMAPdeflate->enable($self, $tag);
571 sub cmd_starttls ($$) {
572 my ($self, $tag) = @_;
573 my $sock = $self->{sock} or return;
574 if ($sock->can('stop_SSL') || $self->compressed) {
575 return "$tag BAD TLS or compression already enabled\r\n";
577 my $opt = $self->{imapd}->{accept_tls} or
578 return "$tag BAD can not initiate TLS negotiation\r\n";
579 $self->write(\"$tag OK begin TLS negotiation now\r\n");
580 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
581 $self->requeue if PublicInbox::DS::accept_tls_step($self);
585 # for graceful shutdown in PublicInbox::Daemon:
587 my ($self, $now) = @_;
588 ($self->{rbuf} || $self->{wbuf} || $self->not_idle_long($now));
593 if (my $ibx = delete $self->{ibx}) {
594 if (my $sock = $self->{sock}) {;
595 $ibx->unsubscribe_unlock(fileno($sock));
598 $self->SUPER::close; # PublicInbox::DS::close
601 # we're read-only, so SELECT and EXAMINE do the same thing
603 *cmd_select = \&cmd_examine;