]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/POP3.pm
nntp: inline CRLF in all response lines
[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 err ($$;@) {
49         my ($self, $fmt, @args) = @_;
50         printf { $self->{pop3d}->{err} } $fmt."\n", @args;
51 }
52
53 sub out ($$;@) {
54         my ($self, $fmt, @args) = @_;
55         printf { $self->{pop3d}->{out} } $fmt."\n", @args;
56 }
57
58 sub long_step {
59         my ($self) = @_;
60         # wbuf is unset or empty, here; {long} may add to it
61         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
62         my $more = eval { $cb->($self, @args) };
63         if ($@ || !$self->{sock}) { # something bad happened...
64                 delete $self->{long_cb};
65                 my $elapsed = now() - $t0;
66                 if ($@) {
67                         err($self,
68                             "%s during long response[$fd] - %0.6f",
69                             $@, $elapsed);
70                 }
71                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
72                 $self->close;
73         } elsif ($more) { # $self->{wbuf}:
74                 # control passed to ibx_async_cat if $more == \undef
75                 requeue_once($self) if !ref($more);
76         } else { # all done!
77                 delete $self->{long_cb};
78                 my $elapsed = now() - $t0;
79                 my $fd = fileno($self->{sock});
80                 out($self, " deferred[$fd] done - %0.6f", $elapsed);
81                 my $wbuf = $self->{wbuf}; # do NOT autovivify
82                 $self->requeue unless $wbuf && @$wbuf;
83         }
84 }
85
86 sub long_response ($$;@) {
87         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
88         my $sock = $self->{sock} or return;
89         # make sure we disable reading during a long response,
90         # clients should not be sending us stuff and making us do more
91         # work while we are stream a response to them
92         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
93         long_step($self); # kick off!
94         undef;
95 }
96
97 sub do_greet {
98         my ($self) = @_;
99         my $s = $self->{salt} = sprintf('%x.%x', int(rand(0x7fffffff)), time);
100         $self->write("+OK POP3 server ready <$s\@public-inbox>\r\n");
101 }
102
103 sub new {
104         my ($cls, $sock, $pop3d) = @_;
105         (bless { pop3d => $pop3d }, $cls)->greet($sock)
106 }
107
108 # POP user is $UUID1@$NEWSGROUP.$SLICE
109 sub cmd_user ($$) {
110         my ($self, $mailbox) = @_;
111         $self->{salt} // return \"-ERR already authed\r\n";
112         $mailbox =~ s/\A([a-f0-9\-]+)\@//i or
113                 return \"-ERR no UUID@ in mailbox name\r\n";
114         my $user = $1;
115         $user =~ tr/-//d; # most have dashes, some (dbus-uuidgen) don't
116         $user =~ m!\A[a-f0-9]{32}\z!i or return \"-ERR user has no UUID\r\n";
117         my $slice;
118         $mailbox =~ s/\.([0-9]+)\z// and $slice = $1 + 0;
119         my $ibx = $self->{pop3d}->{pi_cfg}->lookup_newsgroup($mailbox) //
120                 return \"-ERR $mailbox does not exist\r\n";
121         my $uidmax = $ibx->mm(1)->num_highwater // 0;
122         if (defined $slice) {
123                 my $max = int($uidmax / PublicInbox::IMAP::UID_SLICE);
124                 my $tip = "$mailbox.$max";
125                 return \"-ERR $mailbox.$slice does not exist ($tip does)\r\n"
126                         if $slice > $max;
127                 $self->{uid_base} = $slice * PublicInbox::IMAP::UID_SLICE;
128                 $self->{slice} = $slice;
129         } else { # latest 50K messages
130                 my $base = $uidmax - PublicInbox::IMAP::UID_SLICE;
131                 $self->{uid_base} = $base < 0 ? 0 : $base;
132                 $self->{slice} = -1;
133         }
134         $self->{ibx} = $ibx;
135         $self->{uuid} = pack('H*', $user); # deleted by _login_ok
136         $slice //= '(latest)';
137         \"+OK $ibx->{newsgroup} slice=$slice selected\r\n";
138 }
139
140 sub _login_ok ($) {
141         my ($self) = @_;
142         if ($self->{pop3d}->lock_mailbox($self)) {
143                 $self->{uid_max} = $self->{ibx}->over(1)->max;
144                 \"+OK logged in\r\n";
145         } else {
146                 \"-ERR [IN-USE] unable to lock maildrop\r\n";
147         }
148 }
149
150 sub cmd_apop {
151         my ($self, $mailbox, $hex) = @_;
152         my $res = cmd_user($self, $mailbox); # sets {uuid}
153         return $res if substr($$res, 0, 1) eq '-';
154         my $s = delete($self->{salt}) // die 'BUG: salt missing';
155         return _login_ok($self) if md5("<$s\@public-inbox>anonymous") eq
156                                 pack('H*', $hex);
157         $self->{salt} = $s;
158         \"-ERR APOP password mismatch\r\n";
159 }
160
161 sub cmd_pass {
162         my ($self, $pass) = @_;
163         $self->{ibx} // return \"-ERR mailbox unspecified\r\n";
164         my $s = delete($self->{salt}) // return \"-ERR already authed\r\n";
165         return _login_ok($self) if $pass eq 'anonymous';
166         $self->{salt} = $s;
167         \"-ERR password is not `anonymous'\r\n";
168 }
169
170 sub cmd_stls {
171         my ($self) = @_;
172         my $sock = $self->{sock} or return;
173         return \"-ERR TLS already enabled\r\n" if $sock->can('stop_SSL');
174         my $opt = $self->{pop3d}->{accept_tls} or
175                 return \"-ERR can't start TLS negotiation\r\n";
176         $self->write(\"+OK begin TLS negotiation now\r\n");
177         $self->{sock} = IO::Socket::SSL->start_SSL($sock, %$opt);
178         $self->requeue if PublicInbox::DS::accept_tls_step($self);
179         undef;
180 }
181
182 sub need_txn ($) {
183         exists($_[0]->{salt}) ? \"-ERR not in TRANSACTION\r\n" : undef;
184 }
185
186 sub _stat_cache ($) {
187         my ($self) = @_;
188         my ($beg, $end) = (($self->{uid_dele} // -1) + 1, $self->{uid_max});
189         PublicInbox::IMAP::uid_clamp($self, \$beg, \$end);
190         my $opt = { limit => PublicInbox::IMAP::UID_SLICE };
191         my $m = $self->{ibx}->over(1)->do_get(<<'', $opt, $beg, $end);
192 SELECT num,ddd FROM over WHERE num >= ? AND num <= ?
193 ORDER BY num ASC
194
195         [ map { ($_->{num}, $_->{bytes} + 0, $_->{blob}) } @$m ];
196 }
197
198 sub cmd_stat {
199         my ($self) = @_;
200         my $err; $err = need_txn($self) and return $err;
201         my $cache = $self->{cache} //= _stat_cache($self);
202         my $tot = 0;
203         for (my $i = 1; $i < scalar(@$cache); $i += 3) { $tot += $cache->[$i] }
204         my $nr = @$cache / 3 - ($self->{nr_dele} // 0);
205         "+OK $nr $tot\r\n";
206 }
207
208 # for LIST and UIDL
209 sub _list {
210         my ($desc, $idx, $self, $msn) = @_;
211         my $err; $err = need_txn($self) and return $err;
212         my $cache = $self->{cache} //= _stat_cache($self);
213         if (defined $msn) {
214                 my $base_off = ($msn - 1) * 3;
215                 my $val = $cache->[$base_off + $idx] //
216                                 return \"-ERR no such message\r\n";
217                 "+OK $desc listing follows\r\n$msn $val\r\n.\r\n";
218         } else { # always +OK, even if no messages
219                 my $res = "+OK $desc listing follows\r\n";
220                 my $msn = 0;
221                 for (my $i = 0; $i < scalar(@$cache); $i += 3) {
222                         ++$msn;
223                         defined($cache->[$i]) and
224                                 $res .= "$msn $cache->[$i + $idx]\r\n";
225                 }
226                 $res .= ".\r\n";
227         }
228 }
229
230 sub cmd_list { _list('scan', 1, @_) }
231 sub cmd_uidl { _list('unique-id', 2, @_) }
232
233 sub mark_dele ($$) {
234         my ($self, $off) = @_;
235         my $base_off = $off * 3;
236         my $cache = $self->{cache};
237         my $uid = $cache->[$base_off] // return; # already deleted
238
239         my $old = $self->{txn_max_uid} //= $uid;
240         $self->{txn_max_uid} = $uid if $uid > $old;
241
242         $cache->[$base_off] = undef; # clobber UID
243         $cache->[$base_off + 1] = 0; # zero bytes (simplifies cmd_stat)
244         $cache->[$base_off + 2] = undef; # clobber oidhex
245         ++$self->{nr_dele};
246 }
247
248 sub retr_cb { # called by git->cat_async via ibx_async_cat
249         my ($bref, $oid, $type, $size, $args) = @_;
250         my ($self, $off, $top_nr) = @$args;
251         my $hex = $self->{cache}->[$off * 3 + 2] //
252                 die "BUG: no hex (oid=$oid)";
253         if (!defined($oid)) {
254                 # it's possible to have TOCTOU if an admin runs
255                 # public-inbox-(edit|purge), just move onto the next message
256                 warn "E: $hex missing in $self->{ibx}->{inboxdir}\n";
257                 $self->write(\"-ERR no such message\r\n");
258                 return $self->requeue;
259         } elsif ($hex ne $oid) {
260                 $self->close;
261                 die "BUG: $hex != $oid";
262         }
263         PublicInbox::IMAP::to_crlf_full($bref);
264         if (defined $top_nr) {
265                 my ($hdr, $bdy) = split(/\r\n\r\n/, $$bref, 2);
266                 $bref = \$hdr;
267                 $hdr .= "\r\n\r\n";
268                 my @tmp = split(/^/m, $bdy);
269                 $hdr .= join('', splice(@tmp, 0, $top_nr));
270         } elsif (exists $self->{expire}) {
271                 $self->{expire} .= pack('S', $off + 1);
272         }
273         $$bref =~ s/^\./../gms;
274         $$bref .= substr($$bref, -2, 2) eq "\r\n" ? ".\r\n" : "\r\n.\r\n";
275         $self->msg_more("+OK message follows\r\n");
276         $self->write($bref);
277         $self->requeue;
278 }
279
280 sub cmd_retr {
281         my ($self, $msn, $top_nr) = @_;
282         return \"-ERR lines must be a non-negative number\r\n" if
283                         (defined($top_nr) && $top_nr !~ /\A[0-9]+\z/);
284         my $err; $err = need_txn($self) and return $err;
285         my $cache = $self->{cache} //= _stat_cache($self);
286         my $off = $msn - 1;
287         my $hex = $cache->[$off * 3 + 2] // return \"-ERR no such message\r\n";
288         ${ibx_async_cat($self->{ibx}, $hex, \&retr_cb,
289                         [ $self, $off, $top_nr ])};
290 }
291
292 sub cmd_noop { $_[0]->write(\"+OK\r\n") }
293
294 sub cmd_rset {
295         my ($self) = @_;
296         my $err; $err = need_txn($self) and return $err;
297         delete $self->{cache};
298         delete $self->{txn_max_uid};
299         \"+OK\r\n";
300 }
301
302 sub cmd_dele {
303         my ($self, $msn) = @_;
304         my $err; $err = need_txn($self) and return $err;
305         $self->{cache} //= _stat_cache($self);
306         $msn =~ /\A[1-9][0-9]*\z/ or return \"-ERR no such message\r\n";
307         mark_dele($self, $msn - 1) ? \"+OK\r\n" : \"-ERR no such message\r\n";
308 }
309
310 # RFC 2449
311 sub cmd_capa {
312         my ($self) = @_;
313         my $STLS = !$self->{ibx} && !$self->{sock}->can('stop_SSL') &&
314                         $self->{pop3d}->{accept_tls} ? "\nSTLS\r" : '';
315         $self->{expire} = ''; # "EXPIRE 0" allows clients to avoid DELE commands
316         <<EOM;
317 +OK Capability list follows\r
318 TOP\r
319 USER\r
320 PIPELINING\r
321 UIDL\r
322 EXPIRE 0\r
323 RESP-CODES\r$STLS
324 .\r
325 EOM
326 }
327
328 sub close {
329         my ($self) = @_;
330         $self->{pop3d}->unlock_mailbox($self);
331         $self->SUPER::close;
332 }
333
334 sub cmd_quit {
335         my ($self) = @_;
336         if (defined(my $txn_id = $self->{txn_id})) {
337                 my $user_id = $self->{user_id} // die 'BUG: no {user_id}';
338                 if (my $exp = delete $self->{expire}) {
339                         mark_dele($self, $_) for unpack('S*', $exp);
340                 }
341                 my $dbh = $self->{pop3d}->{-state_dbh};
342                 my $lk = $self->{pop3d}->lock_for_scope;
343                 my $sth;
344                 $dbh->begin_work;
345
346                 if (defined $self->{txn_max_uid}) {
347                         $sth = $dbh->prepare_cached(<<'');
348 UPDATE deletes SET uid_dele = ? WHERE txn_id = ? AND uid_dele < ?
349
350                         $sth->execute($self->{txn_max_uid}, $txn_id,
351                                         $self->{txn_max_uid});
352                 }
353                 $sth = $dbh->prepare_cached(<<'');
354 UPDATE users SET last_seen = ? WHERE user_id = ?
355
356                 $sth->execute(time, $user_id);
357                 $dbh->commit;
358         }
359         $self->write(\"+OK public-inbox POP3 server signing off\r\n");
360         $self->close;
361         undef;
362 }
363
364 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
365 sub process_line ($$) {
366         my ($self, $l) = @_;
367         my ($req, @args) = split(/[ \t]+/, $l);
368         return 1 unless defined($req); # skip blank line
369         $req = $self->can('cmd_'.lc($req));
370         my $res = $req ? eval { $req->($self, @args) } :
371                 \"-ERR command not recognized\r\n";
372         my $err = $@;
373         if ($err && $self->{sock}) {
374                 chomp($l);
375                 err($self, 'error from: %s (%s)', $l, $err);
376                 $res = \"-ERR program fault - command not performed\r\n";
377         }
378         defined($res) ? $self->write($res) : 0;
379 }
380
381 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
382 sub event_step {
383         my ($self) = @_;
384         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
385
386         # only read more requests if we've drained the write buffer,
387         # otherwise we can be buffering infinitely w/o backpressure
388         my $rbuf = $self->{rbuf} // \(my $x = '');
389         my $line = index($$rbuf, "\n");
390         while ($line < 0) {
391                 return $self->close if length($$rbuf) >= LINE_MAX;
392                 $self->do_read($rbuf, LINE_MAX, length($$rbuf)) or return;
393                 $line = index($$rbuf, "\n");
394         }
395         $line = substr($$rbuf, 0, $line + 1, '');
396         $line =~ s/\r?\n\z//s;
397         return $self->close if $line =~ /[[:cntrl:]]/s;
398         my $t0 = now();
399         my $fd = fileno($self->{sock}); # may become invalid after process_line
400         my $r = eval { process_line($self, $line) };
401         my $pending = $self->{wbuf} ? ' pending' : '';
402         out($self, "[$fd] %s - %0.6f$pending - $r", $line, now() - $t0);
403         return $self->close if $r < 0;
404         $self->rbuf_idle($rbuf);
405
406         # maybe there's more pipelined data, or we'll have
407         # to register it for socket-readiness notifications
408         $self->requeue unless $pending;
409 }
410
411 no warnings 'once';
412 *cmd_top = \&cmd_retr;
413
414 1;