1 # Copyright (C) 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 a POP3 client connected to
5 # public-inbox-{netd,pop3d}. Much of this was taken from IMAP.pm and NNTP.pm
7 # POP3 is one mailbox per-user, so the "USER" command is like the
8 # format of -imapd and is mapped to $NEWSGROUP.$SLICE (large inboxes
9 # are sliced into 50K mailboxes in both POP3 and IMAP to avoid overloading
12 # Unlike IMAP, the "$NEWSGROUP" mailbox (without $SLICE) is a rolling
13 # window of the latest messages. We can do this for POP3 since the
14 # typical POP3 session is short-lived while long-lived IMAP sessions
15 # would cause slices to grow on the server side without bounds.
17 # Like IMAP, POP3 also has per-session message sequence numbers (MSN),
18 # which require mapping to UIDs. The offset of an entry into our
19 # per-client cache is: (MSN-1)
22 # - uuid - 16-byte (binary) UUID representation (before successful login)
23 # - cache - one-dimentional arrayref of (UID, bytesize, oidhex)
24 # - nr_dele - number of deleted messages
25 # - expire - string of packed unsigned short offsets
26 # - user_id - user-ID mapped to UUID (on successful login + lock)
27 # - txn_max_uid - for storing max deleted UID persistently
28 # - ibx - PublicInbox::Inbox object
29 # - slice - unsigned integer slice number (0..Inf), -1 => latest
30 # - salt - pre-auth for APOP
31 # - uid_dele - maximum deleted from previous session at login (NNTP ARTICLE)
32 # - uid_base - base UID for mailbox slice (0-based) (same as IMAP)
33 package PublicInbox::POP3;
35 use parent qw(PublicInbox::DS);
36 use PublicInbox::GitAsyncCat;
37 use PublicInbox::DS qw(now);
39 use Digest::MD5 qw(md5);
40 use PublicInbox::IMAP; # for UID slice stuff
43 LINE_MAX => 512, # XXX unsure
46 # XXX FIXME: duplicated stuff from NNTP.pm and IMAP.pm
49 my ($self, $fmt, @args) = @_;
50 printf { $self->{pop3d}->{err} } $fmt."\n", @args;
54 my ($self, $fmt, @args) = @_;
55 printf { $self->{pop3d}->{out} } $fmt."\n", @args;
60 sub requeue_once ($) {
62 # COMPRESS users all share the same DEFLATE context.
63 # Flush it here to ensure clients don't see
67 # no recursion, schedule another call ASAP,
68 # but only after all pending writes are done.
70 my $new_size = push(@{$self->{wbuf}}, \&long_step);
72 # wbuf may be populated by $cb, no need to rearm if so:
73 $self->requeue if $new_size == 1;
78 # wbuf is unset or empty, here; {long} may add to it
79 my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
80 my $more = eval { $cb->($self, @args) };
81 if ($@ || !$self->{sock}) { # something bad happened...
82 delete $self->{long_cb};
83 my $elapsed = now() - $t0;
86 "%s during long response[$fd] - %0.6f",
89 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
91 } elsif ($more) { # $self->{wbuf}:
92 # control passed to ibx_async_cat if $more == \undef
93 requeue_once($self) if !ref($more);
95 delete $self->{long_cb};
96 my $elapsed = now() - $t0;
97 my $fd = fileno($self->{sock});
98 out($self, " deferred[$fd] done - %0.6f", $elapsed);
99 my $wbuf = $self->{wbuf}; # do NOT autovivify
100 $self->requeue unless $wbuf && @$wbuf;
104 sub long_response ($$;@) {
105 my ($self, $cb, @args) = @_; # cb returns true if more, false if done
106 my $sock = $self->{sock} or return;
107 # make sure we disable reading during a long response,
108 # clients should not be sending us stuff and making us do more
109 # work while we are stream a response to them
110 $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
111 long_step($self); # kick off!
117 my $s = $self->{salt} = sprintf('%x.%x', int(rand(0x7fffffff)), time);
118 $self->write("+OK POP3 server ready <$s\@public-inbox>\r\n");
122 my ($cls, $sock, $pop3d) = @_;
123 (bless { pop3d => $pop3d }, $cls)->greet($sock)
126 # POP user is $UUID1@$NEWSGROUP.$SLICE
128 my ($self, $mailbox) = @_;
129 $self->{salt} // return \"-ERR already authed\r\n";
130 $mailbox =~ s/\A([a-f0-9\-]+)\@//i or
131 return \"-ERR no UUID@ in mailbox name\r\n";
133 $user =~ tr/-//d; # most have dashes, some (dbus-uuidgen) don't
134 $user =~ m!\A[a-f0-9]{32}\z!i or return \"-ERR user has no UUID\r\n";
136 $mailbox =~ s/\.([0-9]+)\z// and $slice = $1 + 0;
137 my $ibx = $self->{pop3d}->{pi_cfg}->lookup_newsgroup($mailbox) //
138 return \"-ERR $mailbox does not exist\r\n";
139 my $uidmax = $ibx->mm(1)->num_highwater // 0;
140 if (defined $slice) {
141 my $max = int($uidmax / PublicInbox::IMAP::UID_SLICE);
142 my $tip = "$mailbox.$max";
143 return \"-ERR $mailbox.$slice does not exist ($tip does)\r\n"
145 $self->{uid_base} = $slice * PublicInbox::IMAP::UID_SLICE;
146 $self->{slice} = $slice;
147 } else { # latest 50K messages
148 my $base = $uidmax - PublicInbox::IMAP::UID_SLICE;
149 $self->{uid_base} = $base < 0 ? 0 : $base;
153 $self->{uuid} = pack('H*', $user); # deleted by _login_ok
154 $slice //= '(latest)';
155 \"+OK $ibx->{newsgroup} slice=$slice selected\r\n";
160 if ($self->{pop3d}->lock_mailbox($self)) {
161 $self->{uid_max} = $self->{ibx}->over(1)->max;
162 \"+OK logged in\r\n";
164 \"-ERR [IN-USE] unable to lock maildrop\r\n";
169 my ($self, $mailbox, $hex) = @_;
170 my $res = cmd_user($self, $mailbox); # sets {uuid}
171 return $res if substr($$res, 0, 1) eq '-';
172 my $s = delete($self->{salt}) // die 'BUG: salt missing';
173 return _login_ok($self) if md5("<$s\@public-inbox>anonymous") eq
176 \"-ERR APOP password mismatch\r\n";
180 my ($self, $pass) = @_;
181 $self->{ibx} // return \"-ERR mailbox unspecified\r\n";
182 my $s = delete($self->{salt}) // return \"-ERR already authed\r\n";
183 return _login_ok($self) if $pass eq 'anonymous';
185 \"-ERR password is not `anonymous'\r\n";
190 my $sock = $self->{sock} or return;
191 return \"-ERR TLS already enabled\r\n" if $sock->can('stop_SSL');
192 my $opt = $self->{pop3d}->{accept_tls} or
193 return \"-ERR can't start TLS negotiation\r\n";
194 $self->write(\"+OK begin TLS negotiation now\r\n");
195 $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
196 $self->requeue if PublicInbox::DS::accept_tls_step($self);
201 exists($_[0]->{salt}) ? \"-ERR not in TRANSACTION\r\n" : undef;
204 sub _stat_cache ($) {
206 my ($beg, $end) = (($self->{uid_dele} // -1) + 1, $self->{uid_max});
207 PublicInbox::IMAP::uid_clamp($self, \$beg, \$end);
208 my $opt = { limit => PublicInbox::IMAP::UID_SLICE };
209 my $m = $self->{ibx}->over(1)->do_get(<<'', $opt, $beg, $end);
210 SELECT num,ddd FROM over WHERE num >= ? AND num <= ?
213 [ map { ($_->{num}, $_->{bytes} + 0, $_->{blob}) } @$m ];
218 my $err; $err = need_txn($self) and return $err;
219 my $cache = $self->{cache} //= _stat_cache($self);
221 for (my $i = 1; $i < scalar(@$cache); $i += 3) { $tot += $cache->[$i] }
222 my $nr = @$cache / 3 - ($self->{nr_dele} // 0);
228 my ($desc, $idx, $self, $msn) = @_;
229 my $err; $err = need_txn($self) and return $err;
230 my $cache = $self->{cache} //= _stat_cache($self);
232 my $base_off = ($msn - 1) * 3;
233 my $val = $cache->[$base_off + $idx] //
234 return \"-ERR no such message\r\n";
235 "+OK $desc listing follows\r\n$msn $val\r\n.\r\n";
236 } else { # always +OK, even if no messages
237 my $res = "+OK $desc listing follows\r\n";
239 for (my $i = 0; $i < scalar(@$cache); $i += 3) {
241 defined($cache->[$i]) and
242 $res .= "$msn $cache->[$i + $idx]\r\n";
248 sub cmd_list { _list('scan', 1, @_) }
249 sub cmd_uidl { _list('unique-id', 2, @_) }
252 my ($self, $off) = @_;
253 my $base_off = $off * 3;
254 my $cache = $self->{cache};
255 my $uid = $cache->[$base_off] // return; # already deleted
257 my $old = $self->{txn_max_uid} //= $uid;
258 $self->{txn_max_uid} = $uid if $uid > $old;
260 $cache->[$base_off] = undef; # clobber UID
261 $cache->[$base_off + 1] = 0; # zero bytes (simplifies cmd_stat)
262 $cache->[$base_off + 2] = undef; # clobber oidhex
266 sub retr_cb { # called by git->cat_async via ibx_async_cat
267 my ($bref, $oid, $type, $size, $args) = @_;
268 my ($self, $off, $top_nr) = @$args;
269 my $hex = $self->{cache}->[$off * 3 + 2] //
270 die "BUG: no hex (oid=$oid)";
271 if (!defined($oid)) {
272 # it's possible to have TOCTOU if an admin runs
273 # public-inbox-(edit|purge), just move onto the next message
274 warn "E: $hex missing in $self->{ibx}->{inboxdir}\n";
275 $self->write(\"-ERR no such message\r\n");
276 return $self->requeue;
277 } elsif ($hex ne $oid) {
279 die "BUG: $hex != $oid";
281 PublicInbox::IMAP::to_crlf_full($bref);
282 if (defined $top_nr) {
283 my ($hdr, $bdy) = split(/\r\n\r\n/, $$bref, 2);
286 my @tmp = split(/^/m, $bdy);
287 $hdr .= join('', splice(@tmp, 0, $top_nr));
288 } elsif (exists $self->{expire}) {
289 $self->{expire} .= pack('S', $off + 1);
291 $$bref =~ s/^\./../gms;
292 $$bref .= substr($$bref, -2, 2) eq "\r\n" ? ".\r\n" : "\r\n.\r\n";
293 $self->msg_more("+OK message follows\r\n");
299 my ($self, $msn, $top_nr) = @_;
300 return \"-ERR lines must be a non-negative number\r\n" if
301 (defined($top_nr) && $top_nr !~ /\A[0-9]+\z/);
302 my $err; $err = need_txn($self) and return $err;
303 my $cache = $self->{cache} //= _stat_cache($self);
305 my $hex = $cache->[$off * 3 + 2] // return \"-ERR no such message\r\n";
306 ${ibx_async_cat($self->{ibx}, $hex, \&retr_cb,
307 [ $self, $off, $top_nr ])};
310 sub cmd_noop { $_[0]->write(\"+OK\r\n") }
314 my $err; $err = need_txn($self) and return $err;
315 delete $self->{cache};
316 delete $self->{txn_max_uid};
321 my ($self, $msn) = @_;
322 my $err; $err = need_txn($self) and return $err;
323 $self->{cache} //= _stat_cache($self);
324 $msn =~ /\A[1-9][0-9]*\z/ or return \"-ERR no such message\r\n";
325 mark_dele($self, $msn - 1) ? \"+OK\r\n" : \"-ERR no such message\r\n";
331 my $STLS = !$self->{ibx} && !$self->{sock}->can('stop_SSL') &&
332 $self->{pop3d}->{accept_tls} ? "\nSTLS\r" : '';
333 $self->{expire} = ''; # "EXPIRE 0" allows clients to avoid DELE commands
335 +OK Capability list follows\r
348 $self->{pop3d}->unlock_mailbox($self);
354 if (defined(my $txn_id = $self->{txn_id})) {
355 my $user_id = $self->{user_id} // die 'BUG: no {user_id}';
356 if (my $exp = delete $self->{expire}) {
357 mark_dele($self, $_) for unpack('S*', $exp);
359 my $dbh = $self->{pop3d}->{-state_dbh};
360 my $lk = $self->{pop3d}->lock_for_scope;
364 if (defined $self->{txn_max_uid}) {
365 $sth = $dbh->prepare_cached(<<'');
366 UPDATE deletes SET uid_dele = ? WHERE txn_id = ? AND uid_dele < ?
368 $sth->execute($self->{txn_max_uid}, $txn_id,
369 $self->{txn_max_uid});
371 $sth = $dbh->prepare_cached(<<'');
372 UPDATE users SET last_seen = ? WHERE user_id = ?
374 $sth->execute(time, $user_id);
377 $self->write(\"+OK public-inbox POP3 server signing off\r\n");
382 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
383 sub process_line ($$) {
385 my ($req, @args) = split(/[ \t]+/, $l);
386 return 1 unless defined($req); # skip blank line
387 $req = $self->can('cmd_'.lc($req));
388 my $res = $req ? eval { $req->($self, @args) } :
389 \"-ERR command not recognized\r\n";
391 if ($err && $self->{sock}) {
393 err($self, 'error from: %s (%s)', $l, $err);
394 $res = \"-ERR program fault - command not performed\r\n";
396 defined($res) ? $self->write($res) : 0;
399 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
402 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
404 # only read more requests if we've drained the write buffer,
405 # otherwise we can be buffering infinitely w/o backpressure
406 my $rbuf = $self->{rbuf} // \(my $x = '');
407 my $line = index($$rbuf, "\n");
409 return $self->close if length($$rbuf) >= LINE_MAX;
410 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
411 $line = index($$rbuf, "\n");
413 $line = substr($$rbuf, 0, $line + 1, '');
414 $line =~ s/\r?\n\z//s;
415 return $self->close if $line =~ /[[:cntrl:]]/s;
417 my $fd = fileno($self->{sock}); # may become invalid after process_line
418 my $r = eval { process_line($self, $line) };
419 my $pending = $self->{wbuf} ? ' pending' : '';
420 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
421 return $self->close if $r < 0;
422 $self->rbuf_idle($rbuf);
424 # maybe there's more pipelined data, or we'll have
425 # to register it for socket-readiness notifications
426 $self->requeue unless $pending;
430 *cmd_top = \&cmd_retr;