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}->{out} } $fmt."\n", @args;
55 my $s = $self->{salt} = sprintf('%x.%x', int(rand(0x7fffffff)), time);
56 $self->write("+OK POP3 server ready <$s\@public-inbox>\r\n");
60 my ($cls, $sock, $pop3d) = @_;
61 (bless { pop3d => $pop3d }, $cls)->greet($sock)
64 # POP user is $UUID1@$NEWSGROUP.$SLICE
66 my ($self, $mailbox) = @_;
67 $self->{salt} // return \"-ERR already authed\r\n";
68 $mailbox =~ s/\A([a-f0-9\-]+)\@//i or
69 return \"-ERR no UUID@ in mailbox name\r\n";
71 $user =~ tr/-//d; # most have dashes, some (dbus-uuidgen) don't
72 $user =~ m!\A[a-f0-9]{32}\z!i or return \"-ERR user has no UUID\r\n";
74 $mailbox =~ s/\.([0-9]+)\z// and $slice = $1 + 0;
75 my $ibx = $self->{pop3d}->{pi_cfg}->lookup_newsgroup($mailbox) //
76 return \"-ERR $mailbox does not exist\r\n";
77 my $uidmax = $ibx->mm(1)->num_highwater // 0;
79 my $max = int($uidmax / PublicInbox::IMAP::UID_SLICE);
80 my $tip = "$mailbox.$max";
81 return \"-ERR $mailbox.$slice does not exist ($tip does)\r\n"
83 $self->{uid_base} = $slice * PublicInbox::IMAP::UID_SLICE;
84 $self->{slice} = $slice;
85 } else { # latest 50K messages
86 my $base = $uidmax - PublicInbox::IMAP::UID_SLICE;
87 $self->{uid_base} = $base < 0 ? 0 : $base;
91 $self->{uuid} = pack('H*', $user); # deleted by _login_ok
92 $slice //= '(latest)';
93 \"+OK $ibx->{newsgroup} slice=$slice selected\r\n";
98 if ($self->{pop3d}->lock_mailbox($self)) {
99 $self->{uid_max} = $self->{ibx}->over(1)->max;
100 \"+OK logged in\r\n";
102 \"-ERR [IN-USE] unable to lock maildrop\r\n";
107 my ($self, $mailbox, $hex) = @_;
108 my $res = cmd_user($self, $mailbox); # sets {uuid}
109 return $res if substr($$res, 0, 1) eq '-';
110 my $s = delete($self->{salt}) // die 'BUG: salt missing';
111 return _login_ok($self) if md5("<$s\@public-inbox>anonymous") eq
114 \"-ERR APOP password mismatch\r\n";
118 my ($self, $pass) = @_;
119 $self->{ibx} // return \"-ERR mailbox unspecified\r\n";
120 my $s = delete($self->{salt}) // return \"-ERR already authed\r\n";
121 return _login_ok($self) if $pass eq 'anonymous';
123 \"-ERR password is not `anonymous'\r\n";
128 ($self->{sock} // return)->can('stop_SSL') and
129 return \"-ERR TLS already enabled\r\n";
130 $self->{pop3d}->{ssl_ctx_opt} or
131 return \"-ERR can't start TLS negotiation\r\n";
132 $self->write(\"+OK begin TLS negotiation now\r\n");
133 PublicInbox::TLS::start($self->{sock}, $self->{pop3d});
134 $self->requeue if PublicInbox::DS::accept_tls_step($self);
139 exists($_[0]->{salt}) ? \"-ERR not in TRANSACTION\r\n" : undef;
142 sub _stat_cache ($) {
144 my ($beg, $end) = (($self->{uid_dele} // -1) + 1, $self->{uid_max});
145 PublicInbox::IMAP::uid_clamp($self, \$beg, \$end);
147 my $sth = $self->{ibx}->over(1)->dbh->prepare_cached(<<'', undef, 1);
148 SELECT num,ddd FROM over WHERE num >= ? AND num <= ?
151 $sth->execute($beg, $end);
153 while (defined($m = $sth->fetchall_arrayref({}, 1000))) {
155 PublicInbox::Over::load_from_row($x);
156 push(@cache, $x->{num}, $x->{bytes} + 0, $x->{blob});
157 undef $x; # saves ~1.5M memory w/ 50k messages
161 $self->{total_bytes} = $tot;
162 $self->{cache} = \@cache;
167 my $err; $err = need_txn($self) and return $err;
168 my $cache = $self->{cache} // _stat_cache($self);
169 my $nr = @$cache / 3 - ($self->{nr_dele} // 0);
170 "+OK $nr $self->{total_bytes}\r\n";
175 my ($desc, $idx, $self, $msn) = @_;
176 my $err; $err = need_txn($self) and return $err;
177 my $cache = $self->{cache} // _stat_cache($self);
179 my $base_off = ($msn - 1) * 3;
180 my $val = $cache->[$base_off + $idx] //
181 return \"-ERR no such message\r\n";
182 "+OK $desc listing follows\r\n$msn $val\r\n.\r\n";
183 } else { # always +OK, even if no messages
184 my $res = "+OK $desc listing follows\r\n";
186 for (my $i = 0; $i < scalar(@$cache); $i += 3) {
188 defined($cache->[$i]) and
189 $res .= "$msn $cache->[$i + $idx]\r\n";
195 sub cmd_list { _list('scan', 1, @_) }
196 sub cmd_uidl { _list('unique-id', 2, @_) }
199 my ($self, $off) = @_;
200 my $base_off = $off * 3;
201 my $cache = $self->{cache};
202 my $uid = $cache->[$base_off] // return; # already deleted
204 my $old = $self->{txn_max_uid} //= $uid;
205 $self->{txn_max_uid} = $uid if $uid > $old;
207 $self->{total_bytes} -= $cache->[$base_off + 1];
208 $cache->[$base_off] = undef; # clobber UID
209 $cache->[$base_off + 1] = undef; # clobber bytes
210 $cache->[$base_off + 2] = undef; # clobber oidhex
214 sub retr_cb { # called by git->cat_async via ibx_async_cat
215 my ($bref, $oid, $type, $size, $args) = @_;
216 my ($self, $off, $top_nr) = @$args;
217 my $hex = $self->{cache}->[$off * 3 + 2] //
218 die "BUG: no hex (oid=$oid)";
219 if (!defined($oid)) {
220 # it's possible to have TOCTOU if an admin runs
221 # public-inbox-(edit|purge), just move onto the next message
222 warn "E: $hex missing in $self->{ibx}->{inboxdir}\n";
223 $self->write(\"-ERR no such message\r\n");
224 return $self->requeue;
225 } elsif ($hex ne $oid) {
227 die "BUG: $hex != $oid";
229 PublicInbox::IMAP::to_crlf_full($bref);
230 if (defined $top_nr) {
231 my ($hdr, $bdy) = split(/\r\n\r\n/, $$bref, 2);
234 my @tmp = split(/^/m, $bdy);
235 $hdr .= join('', splice(@tmp, 0, $top_nr));
236 } elsif (exists $self->{expire}) {
237 $self->{expire} .= pack('S', $off);
239 $$bref =~ s/^\./../gms;
240 $$bref .= substr($$bref, -2, 2) eq "\r\n" ? ".\r\n" : "\r\n.\r\n";
241 $self->msg_more("+OK message follows\r\n");
247 my ($self, $msn, $top_nr) = @_;
248 return \"-ERR lines must be a non-negative number\r\n" if
249 (defined($top_nr) && $top_nr !~ /\A[0-9]+\z/);
250 my $err; $err = need_txn($self) and return $err;
251 my $cache = $self->{cache} // _stat_cache($self);
253 my $hex = $cache->[$off * 3 + 2] // return \"-ERR no such message\r\n";
254 ${ibx_async_cat($self->{ibx}, $hex, \&retr_cb,
255 [ $self, $off, $top_nr ])};
258 sub cmd_noop { $_[0]->write(\"+OK\r\n") }
262 my $err; $err = need_txn($self) and return $err;
263 delete $self->{cache};
264 delete $self->{txn_max_uid};
269 my ($self, $msn) = @_;
270 my $err; $err = need_txn($self) and return $err;
271 $self->{cache} // _stat_cache($self);
272 $msn =~ /\A[1-9][0-9]*\z/ or return \"-ERR no such message\r\n";
273 mark_dele($self, $msn - 1) ? \"+OK\r\n" : \"-ERR no such message\r\n";
279 my $STLS = !$self->{ibx} && !$self->{sock}->can('stop_SSL') &&
280 $self->{pop3d}->{ssl_ctx_opt} ? "\nSTLS\r" : '';
281 $self->{expire} = ''; # "EXPIRE 0" allows clients to avoid DELE commands
283 +OK Capability list follows\r
296 $self->{pop3d}->unlock_mailbox($self);
300 # must be called inside a state_dbh transaction with flock held
301 sub __cleanup_state {
302 my ($self, $txn_id) = @_;
303 my $user_id = $self->{user_id} // die 'BUG: no {user_id}';
304 $self->{pop3d}->{-state_dbh}->prepare_cached(<<'')->execute($txn_id);
305 DELETE FROM deletes WHERE txn_id = ? AND uid_dele = -1
307 my $sth = $self->{pop3d}->{-state_dbh}->prepare_cached(<<'', undef, 1);
308 SELECT COUNT(*) FROM deletes WHERE user_id = ?
310 $sth->execute($user_id);
311 my $nr = $sth->fetchrow_array;
313 $sth = $self->{pop3d}->{-state_dbh}->prepare_cached(<<'');
314 DELETE FROM users WHERE user_id = ?
316 $sth->execute($user_id);
323 if (defined(my $txn_id = $self->{txn_id})) {
324 my $user_id = $self->{user_id} // die 'BUG: no {user_id}';
325 if (my $exp = delete $self->{expire}) {
326 mark_dele($self, $_) for unpack('S*', $exp);
329 my $dbh = $self->{pop3d}->{-state_dbh};
330 my $lk = $self->{pop3d}->lock_for_scope;
333 if (defined(my $max = $self->{txn_max_uid})) {
334 $dbh->prepare_cached(<<'')->execute($max, $txn_id, $max)
335 UPDATE deletes SET uid_dele = ? WHERE txn_id = ? AND uid_dele < ?
338 $keep = $self->__cleanup_state($txn_id);
340 $dbh->prepare_cached(<<'')->execute(time, $user_id) if $keep;
341 UPDATE users SET last_seen = ? WHERE user_id = ?
344 # we MUST do txn_id F_UNLCK here inside ->lock_for_scope:
345 $self->{did_quit} = 1;
346 $self->{pop3d}->unlock_mailbox($self);
348 $self->write(\"+OK public-inbox POP3 server signing off\r\n");
353 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
354 sub process_line ($$) {
356 my ($req, @args) = split(/[ \t]+/, $l);
357 return 1 unless defined($req); # skip blank line
358 $req = $self->can('cmd_'.lc($req));
359 my $res = $req ? eval { $req->($self, @args) } :
360 \"-ERR command not recognized\r\n";
362 if ($err && $self->{sock}) {
364 warn("error from: $l ($err)\n");
365 $res = \"-ERR program fault - command not performed\r\n";
367 defined($res) ? $self->write($res) : 0;
370 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
373 local $SIG{__WARN__} = $self->{pop3d}->{warn_cb};
374 return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
376 # only read more requests if we've drained the write buffer,
377 # otherwise we can be buffering infinitely w/o backpressure
378 my $rbuf = $self->{rbuf} // \(my $x = '');
379 my $line = index($$rbuf, "\n");
381 return $self->close if length($$rbuf) >= LINE_MAX;
382 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
383 $line = index($$rbuf, "\n");
385 $line = substr($$rbuf, 0, $line + 1, '');
386 $line =~ s/\r?\n\z//s;
387 return $self->close if $line =~ /[[:cntrl:]]/s;
389 my $fd = fileno($self->{sock}); # may become invalid after process_line
390 my $r = eval { process_line($self, $line) };
391 my $pending = $self->{wbuf} ? ' pending' : '';
392 out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
393 return $self->close if $r < 0;
394 $self->rbuf_idle($rbuf);
396 # maybe there's more pipelined data, or we'll have
397 # to register it for socket-readiness notifications
398 $self->requeue unless $pending;
402 *cmd_top = \&cmd_retr;