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);
26 use bytes qw(length substr); # FIXME(?): needed for PublicInbox::NNTP
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 add_uniq_timer);
38 my $nextq; # queue for next_tick
39 my $wait_pids; # list of [ pid, callback, callback_arg ]
40 my $EXPMAP; # fd -> idle_time
41 our $EXPTIME = 180; # 3 minutes
43 my $ToClose; # sockets to close when event loop is done
45 %DescriptorMap, # fd (num) -> PublicInbox::DS object
46 $Epoll, # Global epoll fd (or DSKQXS ref)
47 $_io, # IO::Handle for Epoll
49 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
51 $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
74 $PostLoopCallback = undef;
76 # we may be iterating inside one of these on our stack
77 my @q = delete @Stack{keys %Stack};
78 for my $q (@q) { @$q = () }
80 $wait_pids = $nextq = $ToClose = undef;
81 $_io = undef; # closes real $Epoll FD
82 $Epoll = undef; # may call DSKQXS::DESTROY
83 } while (@Timers || keys(%Stack) || $nextq || $wait_pids ||
84 $ToClose || keys(%DescriptorMap) ||
85 $PostLoopCallback || keys(%UniqTimer));
88 $LoopTimeout = -1; # no timeout by default
91 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
93 Set the loop timeout for the event loop to some value in milliseconds.
95 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
99 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
101 sub _add_named_timer {
102 my ($name, $secs, $coderef, @args) = @_;
103 my $fire_time = now() + $secs;
104 my $timer = [$fire_time, $name, $coderef, @args];
106 if (!@Timers || $fire_time >= $Timers[-1][0]) {
107 push @Timers, $timer;
111 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
112 # but it was compared against calendar queues, heaps, naive push/sort,
113 # and a bunch of other versions, and found to be fastest with a large
114 # variety of datasets.)
115 for (my $i = 0; $i < @Timers; $i++) {
116 if ($Timers[$i][0] > $fire_time) {
117 splice(@Timers, $i, 0, $timer);
121 die "Shouldn't get here.";
124 sub add_timer { _add_named_timer(undef, @_) }
126 sub add_uniq_timer { # ($name, $secs, $coderef, @args) = @_;
127 $UniqTimer{$_[0]} //= _add_named_timer(@_);
130 # keeping this around in case we support other FD types for now,
131 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
132 sub set_cloexec ($) {
135 open($_io, '+<&=', $fd) or return;
136 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
137 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
140 # caller sets return value to $Epoll
143 if (PublicInbox::Syscall::epoll_defined()) {
144 my $fd = epoll_create();
145 set_cloexec($fd) if (defined($fd) && $fd >= 0);
149 for (qw(DSKQXS DSPoll)) {
150 $cls = "PublicInbox::$_";
151 last if eval "require $cls";
153 $cls->import(qw(epoll_ctl epoll_wait));
158 sub now () { clock_gettime(CLOCK_MONOTONIC) }
161 my $q = $nextq or return;
163 $Stack{cur_runq} = $q;
165 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
166 # https://rt.perl.org/Public/Bug/Display.html?id=114340
173 delete $Stack{cur_runq};
176 # runs timers and returns milliseconds for next one, or next event loop
180 return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
185 while (@Timers && $Timers[0][0] <= $now) {
186 my $to_run = shift(@Timers);
187 delete $UniqTimer{$to_run->[1] // ''};
188 $to_run->[2]->(@$to_run[3..$#$to_run]);
191 # timers may enqueue into nextq:
192 return 0 if ($nextq || $ToClose);
194 return $LoopTimeout unless @Timers;
196 # convert time to an even number of milliseconds, adding 1
197 # extra, otherwise floating point fun can occur and we'll
198 # call RunTimers like 20-30 times, each returning a timeout
199 # of 0.0000212 seconds
200 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
202 # -1 is an infinite timeout, so prefer a real timeout
203 ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout
206 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
208 sub block_signals () {
209 my $oldset = POSIX::SigSet->new;
210 my $newset = POSIX::SigSet->new;
211 $newset->fillset or die "fillset: $!";
212 sig_setmask($newset, $oldset);
216 # We can't use waitpid(-1) safely here since it can hit ``, system(),
217 # and other things. So we scan the $wait_pids list, which is hopefully
218 # not too big. We keep $wait_pids small by not calling dwaitpid()
219 # until we've hit EOF when reading the stdout of the child.
223 my $tmp = $wait_pids or return;
225 $Stack{reap_runq} = $tmp;
226 my $oldset = block_signals();
227 foreach my $ary (@$tmp) {
228 my ($pid, $cb, $arg) = @$ary;
229 my $ret = waitpid($pid, WNOHANG);
231 push @$wait_pids, $ary; # autovivifies @$wait_pids
232 } elsif ($ret == $pid) {
234 eval { $cb->($arg, $pid) };
235 warn "E: dwaitpid($pid) in_loop: $@" if $@;
238 warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
241 sig_setmask($oldset);
242 delete $Stack{reap_runq};
245 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
246 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
248 sub in_loop () { $in_loop }
250 # Internal function: run the post-event callback, send read events
251 # for pushed-back data, and close pending connections. returns 1
252 # if event loop should continue, or 0 to shut it all down.
253 sub PostEventLoop () {
254 # now we can close sockets that wanted to close during our event
255 # processing. (we didn't want to close them during the loop, as we
256 # didn't want fd numbers being reused and confused during the event
258 if (my $close_now = $ToClose) {
259 $ToClose = undef; # will be autovivified on push
260 @$close_now = map { fileno($_) } @$close_now;
262 # order matters, destroy expiry times, first:
263 delete @$EXPMAP{@$close_now};
265 # ->DESTROY methods may populate ToClose
266 delete @DescriptorMap{@$close_now};
269 # by default we keep running, unless a postloop callback cancels it
270 $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
273 # Start processing IO events. In most daemon programs this never exits. See
274 # C<PostLoopCallback> for how to exit the loop.
275 sub event_loop (;$$) {
276 my ($sig, $oldset) = @_;
277 $Epoll //= _InitPoller();
278 require PublicInbox::Sigfd if $sig;
279 my $sigfd = PublicInbox::Sigfd->new($sig, 1) if $sig;
280 local @SIG{keys %$sig} = values(%$sig) if $sig && !$sigfd;
281 local $SIG{PIPE} = 'IGNORE';
282 if (!$sigfd && $sig) {
283 # wake up every second to accept signals if we don't
284 # have signalfd or IO::KQueue:
285 sig_setmask($oldset);
286 PublicInbox::DS->SetLoopTimeout(1000);
288 $_[0] = $sigfd = $sig = undef; # $_[0] == sig
292 my $timeout = RunTimers();
294 # get up to 1000 events
295 epoll_wait($Epoll, 1000, $timeout, \@events);
296 for my $fd (@events) {
297 # it's possible epoll_wait returned many events,
298 # including some at the end that ones in the front
299 # triggered unregister-interest actions. if we can't
300 # find the %sock entry, it's because we're no longer
301 # interested in that event.
303 # guard stack-not-refcounted w/ Carp + @DB::args
304 my $obj = $DescriptorMap{$fd};
307 } while (PostEventLoop());
310 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
312 Sets post loop callback function. Pass a subref and it will be
313 called every time the event loop finishes.
315 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
318 The callback function will be passed two parameters: \%DescriptorMap
321 sub SetPostLoopCallback {
322 my ($class, $ref) = @_;
325 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
328 #####################################################################
329 ### PublicInbox::DS-the-object code
330 #####################################################################
332 =head2 OBJECT METHODS
334 =head2 C<< CLASS->new( $socket ) >>
336 Create a new PublicInbox::DS subclass object for the given I<socket> which will
337 react to events on it during the C<event_loop>.
339 This is normally (always?) called from your subclass via:
341 $class->SUPER::new($socket);
345 my ($self, $sock, $ev) = @_;
346 $self->{sock} = $sock;
347 my $fd = fileno($sock);
349 $Epoll //= _InitPoller();
351 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
352 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
353 $ev &= ~EPOLLEXCLUSIVE;
356 die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
358 croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
359 if defined($DescriptorMap{$fd});
361 $DescriptorMap{$fd} = $self;
365 #####################################################################
366 ### I N S T A N C E M E T H O D S
367 #####################################################################
369 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
371 =head2 C<< $obj->close >>
378 my $sock = delete $self->{sock} or return;
380 # we need to flush our write buffer, as there may
381 # be self-referential closures (sub { $client->close })
382 # preventing the object from being destroyed
383 delete $self->{wbuf};
385 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
386 # notifications about it
387 my $fd = fileno($sock);
388 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
389 croak("EPOLL_CTL_DEL($self/$sock): $!");
391 # we explicitly don't delete from DescriptorMap here until we
392 # actually close the socket, as we might be in the middle of
393 # processing an epoll_wait/etc that returned hundreds of fds, one
394 # of which is not yet processed and is what we're closing. if we
395 # keep it in DescriptorMap, then the event harnesses can just
396 # looked at $pob->{sock} == undef and ignore it. but if it's an
397 # un-accounted for fd, then it (understandably) freak out a bit
398 # and emit warnings, thinking their state got off.
400 # defer closing the actual socket until the event loop is done
401 # processing this round of events. (otherwise we might reuse fds)
402 push @$ToClose, $sock; # autovivifies $ToClose
407 # portable, non-thread-safe sendfile emulation (no pread, yet)
408 sub send_tmpio ($$) {
409 my ($sock, $tmpio) = @_;
411 sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
412 my $n = $tmpio->[2] // 65536;
413 $n = 65536 if $n > 65536;
414 defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
416 while ($to_write > 0) {
417 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
421 return if $written == 0;
425 $tmpio->[1] += $written; # offset
426 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
430 sub epbit ($$) { # (sock, default)
431 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
434 # returns 1 if done, 0 if incomplete
435 sub flush_write ($) {
437 my $sock = $self->{sock} or return;
438 my $wbuf = $self->{wbuf} or return 1;
441 while (my $bref = $wbuf->[0]) {
442 if (ref($bref) ne 'CODE') {
444 my $w = send_tmpio($sock, $bref); # bref is tmpio
450 } elsif ($! == EAGAIN) {
451 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
452 epwait($sock, $ev | EPOLLONESHOT);
458 } else { #(ref($bref) eq 'CODE') {
460 my $before = scalar(@$wbuf);
463 # bref may be enqueueing more CODE to call (see accept_tls_step)
464 return 0 if (scalar(@$wbuf) > $before);
468 delete $self->{wbuf};
473 my ($self, $rbuf) = @_;
474 if ($$rbuf eq '') { # who knows how long till we can read again
475 delete $self->{rbuf};
477 $self->{rbuf} = $rbuf;
481 sub do_read ($$$;$) {
482 my ($self, $rbuf, $len, $off) = @_;
483 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
484 return ($r == 0 ? $self->close : $r) if defined $r;
485 # common for clients to break connections without warning,
486 # would be too noisy to log here:
488 my $ev = epbit($sock, EPOLLIN) or return $self->close;
489 epwait($sock, $ev | EPOLLONESHOT);
490 rbuf_idle($self, $rbuf);
497 # drop the socket if we hit unrecoverable errors on our system which
498 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
505 # n.b.: use ->write/->read for this buffer to allow compatibility with
506 # PerlIO::mmap or PerlIO::scalar if needed
508 my ($self, $bref, $off) = @_;
509 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
510 return drop($self, "tmpfile $!");
512 my $len = length($$bref) - $off;
513 print $fh substr($$bref, $off, $len) or
514 return drop($self, "write ($len): $!");
515 [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
518 =head2 C<< $obj->write( $data ) >>
520 Write the specified data to the underlying handle. I<data> may be scalar,
521 scalar ref, code ref (to run when there).
522 Returns 1 if writes all went through, or 0 if there are writes in queue. If
523 it returns 1, caller should stop waiting for 'writable' events)
527 my ($self, $data) = @_;
529 # nobody should be writing to closed sockets, but caller code can
530 # do two writes within an event, have the first fail and
531 # disconnect the other side (whose destructor then closes the
532 # calling object, but it's still in a method), and then the
533 # now-dead object does its second write. that is this case. we
534 # just lie and say it worked. it'll be dead soon and won't be
536 my $sock = $self->{sock} or return 1;
538 my $bref = $ref ? $data : \$data;
539 my $wbuf = $self->{wbuf};
540 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
541 if ($ref eq 'CODE') {
544 my $tmpio = $wbuf->[-1];
545 if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
546 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
548 my $tmpio = tmpio($self, $bref, 0) or return 0;
553 } elsif ($ref eq 'CODE') {
557 my $to_write = length($$bref);
558 my $written = syswrite($sock, $$bref, $to_write);
560 if (defined $written) {
561 return 1 if $written == $to_write;
562 requeue($self); # runs: event_step -> flush_write
563 } elsif ($! == EAGAIN) {
564 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
565 epwait($sock, $ev | EPOLLONESHOT);
571 # deal with EAGAIN or partial write:
572 my $tmpio = tmpio($self, $bref, $written) or return 0;
574 # wbuf may be an empty array if we're being called inside
575 # ->flush_write via CODE bref:
576 push @{$self->{wbuf}}, $tmpio; # autovivifies
581 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
585 my $sock = $self->{sock} or return 1;
586 my $wbuf = $self->{wbuf};
588 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
589 !$sock->can('stop_SSL')) {
590 my $n = send($sock, $_[1], MSG_MORE);
592 my $nlen = length($_[1]) - $n;
593 return 1 if $nlen == 0; # all done!
594 # queue up the unwritten substring:
595 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
596 push @{$self->{wbuf}}, $tmpio; # autovivifies
597 epwait($sock, EPOLLOUT|EPOLLONESHOT);
602 # don't redispatch into NNTPdeflate::write
603 PublicInbox::DS::write($self, \($_[1]));
607 my ($sock, $ev) = @_;
608 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
609 croak("EPOLL_CTL_MOD($sock): $!");
612 # return true if complete, false if incomplete (or failure)
613 sub accept_tls_step ($) {
615 my $sock = $self->{sock} or return;
616 return 1 if $sock->accept_SSL;
617 return $self->close if $! != EAGAIN;
618 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
619 epwait($sock, $ev | EPOLLONESHOT);
620 unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
624 # return true if complete, false if incomplete (or failure)
625 sub shutdn_tls_step ($) {
627 my $sock = $self->{sock} or return;
628 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
629 return $self->close if $! != EAGAIN;
630 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
631 epwait($sock, $ev | EPOLLONESHOT);
632 unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
636 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
637 # or fork w/o exec, so no inadvertent socket sharing
640 my $sock = $self->{sock} or return;
641 if ($sock->can('stop_SSL')) {
642 shutdn_tls_step($self);
648 sub dwaitpid ($;$$) {
649 my ($pid, $cb, $arg) = @_;
651 push @$wait_pids, [ $pid, $cb, $arg ];
652 # We could've just missed our SIGCHLD, cover it, here:
655 my $ret = waitpid($pid, 0);
658 eval { $cb->($arg, $pid) };
659 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
662 carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
668 my $cur = $EXPMAP or return;
670 my $old = now() - $EXPTIME;
671 while (my ($fd, $idle_at) = each %$cur) {
672 if ($idle_at < $old) {
673 my $ds_obj = $DescriptorMap{$fd};
674 $EXPMAP->{$fd} = $idle_at if !$ds_obj->shutdn;
676 $EXPMAP->{$fd} = $idle_at;
679 add_uniq_timer('expire', 60, \&expire_old) if $EXPMAP;
682 sub update_idle_time {
684 my $sock = $self->{sock} or return;
685 $EXPMAP->{fileno($sock)} = now();
686 add_uniq_timer('expire', 60, \&expire_old);
690 my ($self, $now) = @_;
691 my $sock = $self->{sock} or return;
692 my $idle_at = $EXPMAP->{fileno($sock)} or return;
693 ($idle_at + $EXPTIME) > $now;
698 =head1 AUTHORS (Danga::Socket)
700 Brad Fitzpatrick <brad@danga.com> - author
702 Michael Granger <ged@danga.com> - docs, testing
704 Mark Smith <junior@danga.com> - contributor, heavy user, testing
706 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits