1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
4 # This license differs from the rest of public-inbox
6 # This is a fork of the unmaintained Danga::Socket (1.61) with
7 # significant changes. See Documentation/technical/ds.txt in our
10 # Do not expect this to be a stable API like Danga::Socket,
11 # but it will evolve to suite our needs and to take advantage of
12 # newer Linux and *BSD features.
13 # Bugs encountered were reported to bug-Danga-Socket@rt.cpan.org,
14 # fixed in Danga::Socket 1.62 and visible at:
15 # https://rt.cpan.org/Public/Dist/Display.html?Name=Danga-Socket
18 # sock: underlying socket
19 # rbuf: scalarref, usually undef
20 # wbuf: arrayref of coderefs or tmpio (autovivified))
21 # (tmpio = [ GLOB, offset, [ length ] ])
22 package PublicInbox::DS;
25 use parent qw(Exporter);
27 use POSIX qw(WNOHANG sigprocmask SIG_SETMASK);
28 use Fcntl qw(SEEK_SET :DEFAULT O_APPEND);
29 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
30 use Scalar::Util qw(blessed);
31 use PublicInbox::Syscall qw(:epoll);
32 use PublicInbox::Tmpfile;
33 use Errno qw(EAGAIN EINVAL);
34 use Carp qw(carp croak);
35 our @EXPORT_OK = qw(now msg_more dwaitpid add_timer);
38 my $nextq; # queue for next_tick
39 my $wait_pids; # list of [ pid, callback, callback_arg ]
40 my $later_q; # list of callbacks to run at some later interval
41 my $EXPMAP; # fd -> idle_time
42 our $EXPTIME = 180; # 3 minutes
43 my ($later_timer, $reap_armed, $exp_timer);
44 my $ToClose; # sockets to close when event loop is done
46 %DescriptorMap, # fd (num) -> PublicInbox::DS object
47 $Epoll, # Global epoll fd (or DSKQXS ref)
48 $_io, # IO::Handle for Epoll
50 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
52 $LoopTimeout, # timeout of event loop in milliseconds
59 #####################################################################
60 ### C L A S S M E T H O D S
61 #####################################################################
63 =head2 C<< CLASS->Reset() >>
70 $in_loop = undef; # first in case DESTROY callbacks use this
73 $PostLoopCallback = undef;
75 # we may be iterating inside one of these on our stack
76 my @q = delete @Stack{keys %Stack};
77 for my $q (@q) { @$q = () }
79 $wait_pids = $later_q = $nextq = $ToClose = undef;
80 $_io = undef; # closes real $Epoll FD
81 $Epoll = undef; # may call DSKQXS::DESTROY
82 } while (@Timers || keys(%Stack) || $nextq || $wait_pids ||
83 $later_q || $ToClose || keys(%DescriptorMap) ||
86 $reap_armed = $later_timer = $exp_timer = undef;
87 $LoopTimeout = -1; # no timeout by default
90 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
92 Set the loop timeout for the event loop to some value in milliseconds.
94 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
98 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
100 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef, $arg) >>
102 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
103 are not guaranteed to fire at the exact time you ask for.
106 sub add_timer ($$;@) {
107 my ($secs, $coderef, @args) = @_;
109 my $fire_time = now() + $secs;
111 my $timer = [$fire_time, $coderef, @args];
113 if (!@Timers || $fire_time >= $Timers[-1][0]) {
114 push @Timers, $timer;
118 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
119 # but it was compared against calendar queues, heaps, naive push/sort,
120 # and a bunch of other versions, and found to be fastest with a large
121 # variety of datasets.)
122 for (my $i = 0; $i < @Timers; $i++) {
123 if ($Timers[$i][0] > $fire_time) {
124 splice(@Timers, $i, 0, $timer);
129 die "Shouldn't get here.";
132 # keeping this around in case we support other FD types for now,
133 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
134 sub set_cloexec ($) {
137 open($_io, '+<&=', $fd) or return;
138 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
139 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
142 # caller sets return value to $Epoll
145 if (PublicInbox::Syscall::epoll_defined()) {
146 my $fd = epoll_create();
147 set_cloexec($fd) if (defined($fd) && $fd >= 0);
151 for (qw(DSKQXS DSPoll)) {
152 $cls = "PublicInbox::$_";
153 last if eval "require $cls";
155 $cls->import(qw(epoll_ctl epoll_wait));
160 =head2 C<< CLASS->EventLoop() >>
162 Start processing IO events. In most daemon programs this never exits. See
163 C<PostLoopCallback> below for how to exit the loop.
167 sub now () { clock_gettime(CLOCK_MONOTONIC) }
170 my $q = $nextq or return;
172 $Stack{cur_runq} = $q;
174 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
175 # https://rt.perl.org/Public/Bug/Display.html?id=114340
182 delete $Stack{cur_runq};
185 # runs timers and returns milliseconds for next one, or next event loop
189 return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
194 while (@Timers && $Timers[0][0] <= $now) {
195 my $to_run = shift(@Timers);
196 $to_run->[1]->(@$to_run[2..$#$to_run]);
199 # timers may enqueue into nextq:
200 return 0 if ($nextq || $ToClose);
202 return $LoopTimeout unless @Timers;
204 # convert time to an even number of milliseconds, adding 1
205 # extra, otherwise floating point fun can occur and we'll
206 # call RunTimers like 20-30 times, each returning a timeout
207 # of 0.0000212 seconds
208 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
210 # -1 is an infinite timeout, so prefer a real timeout
211 ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout;
214 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
216 sub block_signals () {
217 my $oldset = POSIX::SigSet->new;
218 my $newset = POSIX::SigSet->new;
219 $newset->fillset or die "fillset: $!";
220 sig_setmask($newset, $oldset);
224 # We can't use waitpid(-1) safely here since it can hit ``, system(),
225 # and other things. So we scan the $wait_pids list, which is hopefully
226 # not too big. We keep $wait_pids small by not calling dwaitpid()
227 # until we've hit EOF when reading the stdout of the child.
231 my $tmp = $wait_pids or return;
233 $Stack{reap_runq} = $tmp;
234 my $oldset = block_signals();
235 foreach my $ary (@$tmp) {
236 my ($pid, $cb, $arg) = @$ary;
237 my $ret = waitpid($pid, WNOHANG);
239 push @$wait_pids, $ary; # autovivifies @$wait_pids
240 } elsif ($ret == $pid) {
242 eval { $cb->($arg, $pid) };
243 warn "E: dwaitpid($pid) in_loop: $@" if $@;
246 warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
249 sig_setmask($oldset);
250 delete $Stack{reap_runq};
253 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
254 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
256 sub in_loop () { $in_loop }
258 # Internal function: run the post-event callback, send read events
259 # for pushed-back data, and close pending connections. returns 1
260 # if event loop should continue, or 0 to shut it all down.
261 sub PostEventLoop () {
262 # now we can close sockets that wanted to close during our event
263 # processing. (we didn't want to close them during the loop, as we
264 # didn't want fd numbers being reused and confused during the event
266 if (my $close_now = $ToClose) {
267 $ToClose = undef; # will be autovivified on push
268 @$close_now = map { fileno($_) } @$close_now;
270 # order matters, destroy expiry times, first:
271 delete @$EXPMAP{@$close_now};
273 # ->DESTROY methods may populate ToClose
274 delete @DescriptorMap{@$close_now};
277 # by default we keep running, unless a postloop callback cancels it
278 $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
282 $Epoll //= _InitPoller();
286 my $timeout = RunTimers();
288 # get up to 1000 events
289 epoll_wait($Epoll, 1000, $timeout, \@events);
290 for my $fd (@events) {
291 # it's possible epoll_wait returned many events, including some at the end
292 # that ones in the front triggered unregister-interest actions. if we
293 # can't find the %sock entry, it's because we're no longer interested
296 # guard stack-not-refcounted w/ Carp + @DB::args
297 my $obj = $DescriptorMap{$fd};
300 } while (PostEventLoop());
304 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
306 Sets post loop callback function. Pass a subref and it will be
307 called every time the event loop finishes.
309 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
312 The callback function will be passed two parameters: \%DescriptorMap
315 sub SetPostLoopCallback {
316 my ($class, $ref) = @_;
319 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
322 #####################################################################
323 ### PublicInbox::DS-the-object code
324 #####################################################################
326 =head2 OBJECT METHODS
328 =head2 C<< CLASS->new( $socket ) >>
330 Create a new PublicInbox::DS subclass object for the given I<socket> which will
331 react to events on it during the C<EventLoop>.
333 This is normally (always?) called from your subclass via:
335 $class->SUPER::new($socket);
339 my ($self, $sock, $ev) = @_;
340 $self->{sock} = $sock;
341 my $fd = fileno($sock);
343 $Epoll //= _InitPoller();
345 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
346 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
347 $ev &= ~EPOLLEXCLUSIVE;
350 die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
352 croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
353 if defined($DescriptorMap{$fd});
355 $DescriptorMap{$fd} = $self;
359 #####################################################################
360 ### I N S T A N C E M E T H O D S
361 #####################################################################
363 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
365 =head2 C<< $obj->close >>
372 my $sock = delete $self->{sock} or return;
374 # we need to flush our write buffer, as there may
375 # be self-referential closures (sub { $client->close })
376 # preventing the object from being destroyed
377 delete $self->{wbuf};
379 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
380 # notifications about it
381 my $fd = fileno($sock);
382 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
383 croak("EPOLL_CTL_DEL($self/$sock): $!");
385 # we explicitly don't delete from DescriptorMap here until we
386 # actually close the socket, as we might be in the middle of
387 # processing an epoll_wait/etc that returned hundreds of fds, one
388 # of which is not yet processed and is what we're closing. if we
389 # keep it in DescriptorMap, then the event harnesses can just
390 # looked at $pob->{sock} == undef and ignore it. but if it's an
391 # un-accounted for fd, then it (understandably) freak out a bit
392 # and emit warnings, thinking their state got off.
394 # defer closing the actual socket until the event loop is done
395 # processing this round of events. (otherwise we might reuse fds)
396 push @$ToClose, $sock; # autovivifies $ToClose
401 # portable, non-thread-safe sendfile emulation (no pread, yet)
402 sub send_tmpio ($$) {
403 my ($sock, $tmpio) = @_;
405 sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
406 my $n = $tmpio->[2] // 65536;
407 $n = 65536 if $n > 65536;
408 defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
410 while ($to_write > 0) {
411 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
415 return if $written == 0;
419 $tmpio->[1] += $written; # offset
420 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
424 sub epbit ($$) { # (sock, default)
425 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
428 # returns 1 if done, 0 if incomplete
429 sub flush_write ($) {
431 my $sock = $self->{sock} or return;
432 my $wbuf = $self->{wbuf} or return 1;
435 while (my $bref = $wbuf->[0]) {
436 if (ref($bref) ne 'CODE') {
438 my $w = send_tmpio($sock, $bref); # bref is tmpio
444 } elsif ($! == EAGAIN) {
445 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
446 epwait($sock, $ev | EPOLLONESHOT);
452 } else { #(ref($bref) eq 'CODE') {
454 my $before = scalar(@$wbuf);
457 # bref may be enqueueing more CODE to call (see accept_tls_step)
458 return 0 if (scalar(@$wbuf) > $before);
462 delete $self->{wbuf};
467 my ($self, $rbuf) = @_;
468 if ($$rbuf eq '') { # who knows how long till we can read again
469 delete $self->{rbuf};
471 $self->{rbuf} = $rbuf;
475 sub do_read ($$$;$) {
476 my ($self, $rbuf, $len, $off) = @_;
477 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
478 return ($r == 0 ? $self->close : $r) if defined $r;
479 # common for clients to break connections without warning,
480 # would be too noisy to log here:
482 my $ev = epbit($sock, EPOLLIN) or return $self->close;
483 epwait($sock, $ev | EPOLLONESHOT);
484 rbuf_idle($self, $rbuf);
491 # drop the socket if we hit unrecoverable errors on our system which
492 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
499 # n.b.: use ->write/->read for this buffer to allow compatibility with
500 # PerlIO::mmap or PerlIO::scalar if needed
502 my ($self, $bref, $off) = @_;
503 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
504 return drop($self, "tmpfile $!");
506 my $len = bytes::length($$bref) - $off;
507 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
508 [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
511 =head2 C<< $obj->write( $data ) >>
513 Write the specified data to the underlying handle. I<data> may be scalar,
514 scalar ref, code ref (to run when there).
515 Returns 1 if writes all went through, or 0 if there are writes in queue. If
516 it returns 1, caller should stop waiting for 'writable' events)
520 my ($self, $data) = @_;
522 # nobody should be writing to closed sockets, but caller code can
523 # do two writes within an event, have the first fail and
524 # disconnect the other side (whose destructor then closes the
525 # calling object, but it's still in a method), and then the
526 # now-dead object does its second write. that is this case. we
527 # just lie and say it worked. it'll be dead soon and won't be
529 my $sock = $self->{sock} or return 1;
531 my $bref = $ref ? $data : \$data;
532 my $wbuf = $self->{wbuf};
533 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
534 if ($ref eq 'CODE') {
537 my $tmpio = $wbuf->[-1];
538 if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
539 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
541 my $tmpio = tmpio($self, $bref, 0) or return 0;
546 } elsif ($ref eq 'CODE') {
550 my $to_write = bytes::length($$bref);
551 my $written = syswrite($sock, $$bref, $to_write);
553 if (defined $written) {
554 return 1 if $written == $to_write;
555 requeue($self); # runs: event_step -> flush_write
556 } elsif ($! == EAGAIN) {
557 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
558 epwait($sock, $ev | EPOLLONESHOT);
564 # deal with EAGAIN or partial write:
565 my $tmpio = tmpio($self, $bref, $written) or return 0;
567 # wbuf may be an empty array if we're being called inside
568 # ->flush_write via CODE bref:
569 push @{$self->{wbuf}}, $tmpio; # autovivifies
574 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
578 my $sock = $self->{sock} or return 1;
579 my $wbuf = $self->{wbuf};
581 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
582 !$sock->can('stop_SSL')) {
583 my $n = send($sock, $_[1], MSG_MORE);
585 my $nlen = bytes::length($_[1]) - $n;
586 return 1 if $nlen == 0; # all done!
587 # queue up the unwritten substring:
588 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
589 push @{$self->{wbuf}}, $tmpio; # autovivifies
590 epwait($sock, EPOLLOUT|EPOLLONESHOT);
595 # don't redispatch into NNTPdeflate::write
596 PublicInbox::DS::write($self, \($_[1]));
600 my ($sock, $ev) = @_;
601 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
602 croak("EPOLL_CTL_MOD($sock): $!");
605 # return true if complete, false if incomplete (or failure)
606 sub accept_tls_step ($) {
608 my $sock = $self->{sock} or return;
609 return 1 if $sock->accept_SSL;
610 return $self->close if $! != EAGAIN;
611 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
612 epwait($sock, $ev | EPOLLONESHOT);
613 unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
617 # return true if complete, false if incomplete (or failure)
618 sub shutdn_tls_step ($) {
620 my $sock = $self->{sock} or return;
621 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
622 return $self->close if $! != EAGAIN;
623 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
624 epwait($sock, $ev | EPOLLONESHOT);
625 unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
629 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
630 # or fork w/o exec, so no inadvertent socket sharing
633 my $sock = $self->{sock} or return;
634 if ($sock->can('stop_SSL')) {
635 shutdn_tls_step($self);
641 sub dwaitpid ($;$$) {
642 my ($pid, $cb, $arg) = @_;
644 push @$wait_pids, [ $pid, $cb, $arg ];
645 # We could've just missed our SIGCHLD, cover it, here:
648 my $ret = waitpid($pid, 0);
651 eval { $cb->($arg, $pid) };
652 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
655 carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
661 my $q = $later_q or return;
662 $later_timer = $later_q = undef;
663 $Stack{later_q} = $q;
665 delete $Stack{later_q};
669 push @$later_q, $_[0]; # autovivifies @$later_q
670 $later_timer //= add_timer(60, \&_run_later);
676 my $old = $now - $exp;
678 while (my ($fd, $idle_at) = each %$EXPMAP) {
679 if ($idle_at < $old) {
680 my $ds_obj = $DescriptorMap{$fd};
681 $new{$fd} = $idle_at if !$ds_obj->shutdn;
683 $new{$fd} = $idle_at;
687 $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
690 sub update_idle_time {
692 my $sock = $self->{sock} or return;
693 $EXPMAP->{fileno($sock)} = now();
694 $exp_timer //= later(\&expire_old);
698 my ($self, $now) = @_;
699 my $sock = $self->{sock} or return;
700 my $idle_at = $EXPMAP->{fileno($sock)} or return;
701 ($idle_at + $EXPTIME) > $now;
706 =head1 AUTHORS (Danga::Socket)
708 Brad Fitzpatrick <brad@danga.com> - author
710 Michael Granger <ged@danga.com> - docs, testing
712 Mark Smith <junior@danga.com> - contributor, heavy user, testing
714 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits