]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/POP3.pm
c368615d6f94143af05be534ae782cdea4b6faad
[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 zflush {} # noop
59
60 sub requeue_once ($) {
61         my ($self) = @_;
62         # COMPRESS users all share the same DEFLATE context.
63         # Flush it here to ensure clients don't see
64         # each other's data
65         $self->zflush;
66
67         # no recursion, schedule another call ASAP,
68         # but only after all pending writes are done.
69         # autovivify wbuf:
70         my $new_size = push(@{$self->{wbuf}}, \&long_step);
71
72         # wbuf may be populated by $cb, no need to rearm if so:
73         $self->requeue if $new_size == 1;
74 }
75
76 sub long_step {
77         my ($self) = @_;
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;
84                 if ($@) {
85                         err($self,
86                             "%s during long response[$fd] - %0.6f",
87                             $@, $elapsed);
88                 }
89                 out($self, " deferred[$fd] aborted - %0.6f", $elapsed);
90                 $self->close;
91         } elsif ($more) { # $self->{wbuf}:
92                 # control passed to ibx_async_cat if $more == \undef
93                 requeue_once($self) if !ref($more);
94         } else { # all done!
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;
101         }
102 }
103
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!
112         undef;
113 }
114
115 sub do_greet {
116         my ($self) = @_;
117         my $s = $self->{salt} = sprintf('%x.%x', int(rand(0x7fffffff)), time);
118         $self->write("+OK POP3 server ready <$s\@public-inbox>\r\n");
119 }
120
121 sub new {
122         my ($cls, $sock, $pop3d) = @_;
123         (bless { pop3d => $pop3d }, $cls)->greet($sock)
124 }
125
126 # POP user is $UUID1@$NEWSGROUP.$SLICE
127 sub cmd_user ($$) {
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";
132         my $user = $1;
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";
135         my $slice;
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"
144                         if $slice > $max;
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;
150                 $self->{slice} = -1;
151         }
152         $self->{ibx} = $ibx;
153         $self->{uuid} = pack('H*', $user); # deleted by _login_ok
154         $slice //= '(latest)';
155         \"+OK $ibx->{newsgroup} slice=$slice selected\r\n";
156 }
157
158 sub _login_ok ($) {
159         my ($self) = @_;
160         if ($self->{pop3d}->lock_mailbox($self)) {
161                 $self->{uid_max} = $self->{ibx}->over(1)->max;
162                 \"+OK logged in\r\n";
163         } else {
164                 \"-ERR [IN-USE] unable to lock maildrop\r\n";
165         }
166 }
167
168 sub cmd_apop {
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
174                                 pack('H*', $hex);
175         $self->{salt} = $s;
176         \"-ERR APOP password mismatch\r\n";
177 }
178
179 sub cmd_pass {
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';
184         $self->{salt} = $s;
185         \"-ERR password is not `anonymous'\r\n";
186 }
187
188 sub cmd_stls {
189         my ($self) = @_;
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);
197         undef;
198 }
199
200 sub need_txn ($) {
201         exists($_[0]->{salt}) ? \"-ERR not in TRANSACTION\r\n" : undef;
202 }
203
204 sub _stat_cache ($) {
205         my ($self) = @_;
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 <= ?
211 ORDER BY num ASC
212
213         [ map { ($_->{num}, $_->{bytes} + 0, $_->{blob}) } @$m ];
214 }
215
216 sub cmd_stat {
217         my ($self) = @_;
218         my $err; $err = need_txn($self) and return $err;
219         my $cache = $self->{cache} //= _stat_cache($self);
220         my $tot = 0;
221         for (my $i = 1; $i < scalar(@$cache); $i += 3) { $tot += $cache->[$i] }
222         my $nr = @$cache / 3 - ($self->{nr_dele} // 0);
223         "+OK $nr $tot\r\n";
224 }
225
226 # for LIST and UIDL
227 sub _list {
228         my ($desc, $idx, $self, $msn) = @_;
229         my $err; $err = need_txn($self) and return $err;
230         my $cache = $self->{cache} //= _stat_cache($self);
231         if (defined $msn) {
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";
238                 my $msn = 0;
239                 for (my $i = 0; $i < scalar(@$cache); $i += 3) {
240                         ++$msn;
241                         defined($cache->[$i]) and
242                                 $res .= "$msn $cache->[$i + $idx]\r\n";
243                 }
244                 $res .= ".\r\n";
245         }
246 }
247
248 sub cmd_list { _list('scan', 1, @_) }
249 sub cmd_uidl { _list('unique-id', 2, @_) }
250
251 sub mark_dele ($$) {
252         my ($self, $off) = @_;
253         my $base_off = $off * 3;
254         my $cache = $self->{cache};
255         my $uid = $cache->[$base_off] // return; # already deleted
256
257         my $old = $self->{txn_max_uid} //= $uid;
258         $self->{txn_max_uid} = $uid if $uid > $old;
259
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
263         ++$self->{nr_dele};
264 }
265
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) {
278                 $self->close;
279                 die "BUG: $hex != $oid";
280         }
281         PublicInbox::IMAP::to_crlf_full($bref);
282         if (defined $top_nr) {
283                 my ($hdr, $bdy) = split(/\r\n\r\n/, $$bref, 2);
284                 $bref = \$hdr;
285                 $hdr .= "\r\n\r\n";
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);
290         }
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");
294         $self->write($bref);
295         $self->requeue;
296 }
297
298 sub cmd_retr {
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);
304         my $off = $msn - 1;
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 ])};
308 }
309
310 sub cmd_noop { $_[0]->write(\"+OK\r\n") }
311
312 sub cmd_rset {
313         my ($self) = @_;
314         my $err; $err = need_txn($self) and return $err;
315         delete $self->{cache};
316         delete $self->{txn_max_uid};
317         \"+OK\r\n";
318 }
319
320 sub cmd_dele {
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";
326 }
327
328 # RFC 2449
329 sub cmd_capa {
330         my ($self) = @_;
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
334         <<EOM;
335 +OK Capability list follows\r
336 TOP\r
337 USER\r
338 PIPELINING\r
339 UIDL\r
340 EXPIRE 0\r
341 RESP-CODES\r$STLS
342 .\r
343 EOM
344 }
345
346 sub close {
347         my ($self) = @_;
348         $self->{pop3d}->unlock_mailbox($self);
349         $self->SUPER::close;
350 }
351
352 sub cmd_quit {
353         my ($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);
358                 }
359                 my $dbh = $self->{pop3d}->{-state_dbh};
360                 my $lk = $self->{pop3d}->lock_for_scope;
361                 my $sth;
362                 $dbh->begin_work;
363
364                 if (defined $self->{txn_max_uid}) {
365                         $sth = $dbh->prepare_cached(<<'');
366 UPDATE deletes SET uid_dele = ? WHERE txn_id = ? AND uid_dele < ?
367
368                         $sth->execute($self->{txn_max_uid}, $txn_id,
369                                         $self->{txn_max_uid});
370                 }
371                 $sth = $dbh->prepare_cached(<<'');
372 UPDATE users SET last_seen = ? WHERE user_id = ?
373
374                 $sth->execute(time, $user_id);
375                 $dbh->commit;
376         }
377         $self->write(\"+OK public-inbox POP3 server signing off\r\n");
378         $self->close;
379         undef;
380 }
381
382 # returns 1 if we can continue, 0 if not due to buffered writes or disconnect
383 sub process_line ($$) {
384         my ($self, $l) = @_;
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";
390         my $err = $@;
391         if ($err && $self->{sock}) {
392                 chomp($l);
393                 err($self, 'error from: %s (%s)', $l, $err);
394                 $res = \"-ERR program fault - command not performed\r\n";
395         }
396         defined($res) ? $self->write($res) : 0;
397 }
398
399 # callback used by PublicInbox::DS for any (e)poll (in/out/hup/err)
400 sub event_step {
401         my ($self) = @_;
402         return unless $self->flush_write && $self->{sock} && !$self->{long_cb};
403
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");
408         while ($line < 0) {
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");
412         }
413         $line = substr($$rbuf, 0, $line + 1, '');
414         $line =~ s/\r?\n\z//s;
415         return $self->close if $line =~ /[[:cntrl:]]/s;
416         my $t0 = now();
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);
423
424         # maybe there's more pipelined data, or we'll have
425         # to register it for socket-readiness notifications
426         $self->requeue unless $pending;
427 }
428
429 no warnings 'once';
430 *cmd_top = \&cmd_retr;
431
432 1;