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