]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/POP3.pm
No ext_urls
[public-inbox.git] / lib / PublicInbox / POP3.pm
1 # Copyright (C) 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 a POP3 client connected to
5 # public-inbox-{netd,pop3d}.  Much of this was taken from IMAP.pm and NNTP.pm
6 #
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
10 # clients)
11 #
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.
16 #
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)
20 #
21 # fields:
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;
34 use v5.12;
35 use parent qw(PublicInbox::DS);
36 use PublicInbox::GitAsyncCat;
37 use PublicInbox::DS qw(now);
38 use Errno qw(EAGAIN);
39 use Digest::MD5 qw(md5);
40 use PublicInbox::IMAP; # for UID slice stuff
41
42 use constant {
43         LINE_MAX => 512, # XXX unsure
44 };
45
46 # XXX FIXME: duplicated stuff from NNTP.pm and IMAP.pm
47
48 sub out ($$;@) {
49         my ($self, $fmt, @args) = @_;
50         printf { $self->{pop3d}->{out} } $fmt."\n", @args;
51 }
52
53 sub do_greet {
54         my ($self) = @_;
55         my $s = $self->{salt} = sprintf('%x.%x', int(rand(0x7fffffff)), time);
56         $self->write("+OK POP3 server ready <$s\@public-inbox>\r\n");
57 }
58
59 sub new {
60         my ($cls, $sock, $pop3d) = @_;
61         (bless { pop3d => $pop3d }, $cls)->greet($sock)
62 }
63
64 # POP user is $UUID1@$NEWSGROUP.$SLICE
65 sub cmd_user ($$) {
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";
70         my $user = $1;
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";
73         my $slice;
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;
78         if (defined $slice) {
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"
82                         if $slice > $max;
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;
88                 $self->{slice} = -1;
89         }
90         $self->{ibx} = $ibx;
91         $self->{uuid} = pack('H*', $user); # deleted by _login_ok
92         $slice //= '(latest)';
93         \"+OK $ibx->{newsgroup} slice=$slice selected\r\n";
94 }
95
96 sub _login_ok ($) {
97         my ($self) = @_;
98         if ($self->{pop3d}->lock_mailbox($self)) {
99                 $self->{uid_max} = $self->{ibx}->over(1)->max;
100                 \"+OK logged in\r\n";
101         } else {
102                 \"-ERR [IN-USE] unable to lock maildrop\r\n";
103         }
104 }
105
106 sub cmd_apop {
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
112                                 pack('H*', $hex);
113         $self->{salt} = $s;
114         \"-ERR APOP password mismatch\r\n";
115 }
116
117 sub cmd_pass {
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';
122         $self->{salt} = $s;
123         \"-ERR password is not `anonymous'\r\n";
124 }
125
126 sub cmd_stls {
127         my ($self) = @_;
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);
135         undef;
136 }
137
138 sub need_txn ($) {
139         exists($_[0]->{salt}) ? \"-ERR not in TRANSACTION\r\n" : undef;
140 }
141
142 sub _stat_cache ($) {
143         my ($self) = @_;
144         my ($beg, $end) = (($self->{uid_dele} // -1) + 1, $self->{uid_max});
145         PublicInbox::IMAP::uid_clamp($self, \$beg, \$end);
146         my (@cache, $m);
147         my $sth = $self->{ibx}->over(1)->dbh->prepare_cached(<<'', undef, 1);
148 SELECT num,ddd FROM over WHERE num >= ? AND num <= ?
149 ORDER BY num ASC
150
151         $sth->execute($beg, $end);
152         my $tot = 0;
153         while (defined($m = $sth->fetchall_arrayref({}, 1000))) {
154                 for my $x (@$m) {
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
158                         $tot += $cache[-2];
159                 }
160         }
161         $self->{total_bytes} = $tot;
162         $self->{cache} = \@cache;
163 }
164
165 sub cmd_stat {
166         my ($self) = @_;
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";
171 }
172
173 # for LIST and UIDL
174 sub _list {
175         my ($desc, $idx, $self, $msn) = @_;
176         my $err; $err = need_txn($self) and return $err;
177         my $cache = $self->{cache} // _stat_cache($self);
178         if (defined $msn) {
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";
185                 my $msn = 0;
186                 for (my $i = 0; $i < scalar(@$cache); $i += 3) {
187                         ++$msn;
188                         defined($cache->[$i]) and
189                                 $res .= "$msn $cache->[$i + $idx]\r\n";
190                 }
191                 $res .= ".\r\n";
192         }
193 }
194
195 sub cmd_list { _list('scan', 1, @_) }
196 sub cmd_uidl { _list('unique-id', 2, @_) }
197
198 sub mark_dele ($$) {
199         my ($self, $off) = @_;
200         my $base_off = $off * 3;
201         my $cache = $self->{cache};
202         my $uid = $cache->[$base_off] // return; # already deleted
203
204         my $old = $self->{txn_max_uid} //= $uid;
205         $self->{txn_max_uid} = $uid if $uid > $old;
206
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
211         ++$self->{nr_dele};
212 }
213
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) {
226                 $self->close;
227                 die "BUG: $hex != $oid";
228         }
229         PublicInbox::IMAP::to_crlf_full($bref);
230         if (defined $top_nr) {
231                 my ($hdr, $bdy) = split(/\r\n\r\n/, $$bref, 2);
232                 $bref = \$hdr;
233                 $hdr .= "\r\n\r\n";
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);
238         }
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");
242         $self->write($bref);
243         $self->requeue;
244 }
245
246 sub cmd_retr {
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);
252         my $off = $msn - 1;
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 ])};
256 }
257
258 sub cmd_noop { $_[0]->write(\"+OK\r\n") }
259
260 sub cmd_rset {
261         my ($self) = @_;
262         my $err; $err = need_txn($self) and return $err;
263         delete $self->{cache};
264         delete $self->{txn_max_uid};
265         \"+OK\r\n";
266 }
267
268 sub cmd_dele {
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";
274 }
275
276 # RFC 2449
277 sub cmd_capa {
278         my ($self) = @_;
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
282         <<EOM;
283 +OK Capability list follows\r
284 TOP\r
285 USER\r
286 PIPELINING\r
287 UIDL\r
288 EXPIRE 0\r
289 RESP-CODES\r$STLS
290 .\r
291 EOM
292 }
293
294 sub close {
295         my ($self) = @_;
296         $self->{pop3d}->unlock_mailbox($self);
297         $self->SUPER::close;
298 }
299
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
306
307         my $sth = $self->{pop3d}->{-state_dbh}->prepare_cached(<<'', undef, 1);
308 SELECT COUNT(*) FROM deletes WHERE user_id = ?
309
310         $sth->execute($user_id);
311         my $nr = $sth->fetchrow_array;
312         if ($nr == 0) {
313                 $sth = $self->{pop3d}->{-state_dbh}->prepare_cached(<<'');
314 DELETE FROM users WHERE user_id = ?
315
316                 $sth->execute($user_id);
317         }
318         $nr;
319 }
320
321 sub cmd_quit {
322         my ($self) = @_;
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);
327                 }
328                 my $keep = 1;
329                 my $dbh = $self->{pop3d}->{-state_dbh};
330                 my $lk = $self->{pop3d}->lock_for_scope;
331                 $dbh->begin_work;
332
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 < ?
336
337                 } else {
338                         $keep = $self->__cleanup_state($txn_id);
339                 }
340                 $dbh->prepare_cached(<<'')->execute(time, $user_id) if $keep;
341 UPDATE users SET last_seen = ? WHERE user_id = ?
342
343                 $dbh->commit;
344                 # we MUST do txn_id F_UNLCK here inside ->lock_for_scope:
345                 $self->{did_quit} = 1;
346                 $self->{pop3d}->unlock_mailbox($self);
347         }
348         $self->write(\"+OK public-inbox POP3 server signing off\r\n");
349         $self->close;
350         undef;
351 }
352
353 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
354 sub process_line ($$) {
355         my ($self, $l) = @_;
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";
361         my $err = $@;
362         if ($err && $self->{sock}) {
363                 $l =~ s/\r?\n//s;
364                 warn("error from: $l ($err)\n");
365                 $res = \"-ERR program fault - command not performed\r\n";
366         }
367         defined($res) ? $self->write($res) : 0;
368 }
369
370 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
371 sub event_step {
372         my ($self) = @_;
373         local $SIG{__WARN__} = $self->{pop3d}->{warn_cb};
374         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
375
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");
380         while ($line < 0) {
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");
384         }
385         $line = substr($$rbuf, 0, $line + 1, '');
386         $line =~ s/\r?\n\z//s;
387         return $self->close if $line =~ /[[:cntrl:]]/s;
388         my $t0 = now();
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);
395
396         # maybe there's more pipelined data, or we'll have
397         # to register it for socket-readiness notifications
398         $self->requeue unless $pending;
399 }
400
401 no warnings 'once';
402 *cmd_top = \&cmd_retr;
403
404 1;