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 $ep_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 $ep_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 # caller sets return value to $Epoll
132 if (PublicInbox::Syscall::epoll_defined()) {
133 my $fd = epoll_create();
134 die "epoll_create: $!" if $fd < 0;
135 open($ep_io, '+<&=', $fd) or return;
136 my $fl = fcntl($ep_io, F_GETFD, 0);
137 fcntl($ep_io, F_SETFD, $fl | FD_CLOEXEC);
141 for (qw(DSKQXS DSPoll)) {
142 $cls = "PublicInbox::$_";
143 last if eval "require $cls";
145 $cls->import(qw(epoll_ctl epoll_wait));
150 sub now () { clock_gettime(CLOCK_MONOTONIC) }
153 my $q = $nextq or return;
155 $Stack{cur_runq} = $q;
157 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
158 # https://rt.perl.org/Public/Bug/Display.html?id=114340
165 delete $Stack{cur_runq};
168 # runs timers and returns milliseconds for next one, or next event loop
172 return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
177 while (@Timers && $Timers[0][0] <= $now) {
178 my $to_run = shift(@Timers);
179 delete $UniqTimer{$to_run->[1] // ''};
180 $to_run->[2]->(@$to_run[3..$#$to_run]);
183 # timers may enqueue into nextq:
184 return 0 if ($nextq || $ToClose);
186 return $LoopTimeout unless @Timers;
188 # convert time to an even number of milliseconds, adding 1
189 # extra, otherwise floating point fun can occur and we'll
190 # call RunTimers like 20-30 times, each returning a timeout
191 # of 0.0000212 seconds
192 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
194 # -1 is an infinite timeout, so prefer a real timeout
195 ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout
198 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
200 sub block_signals () {
201 my $oldset = POSIX::SigSet->new;
202 my $newset = POSIX::SigSet->new;
203 $newset->fillset or die "fillset: $!";
204 sig_setmask($newset, $oldset);
208 # We can't use waitpid(-1) safely here since it can hit ``, system(),
209 # and other things. So we scan the $wait_pids list, which is hopefully
210 # not too big. We keep $wait_pids small by not calling dwaitpid()
211 # until we've hit EOF when reading the stdout of the child.
215 my $tmp = $wait_pids or return;
217 $Stack{reap_runq} = $tmp;
218 my $oldset = block_signals();
219 foreach my $ary (@$tmp) {
220 my ($pid, $cb, $arg) = @$ary;
221 my $ret = waitpid($pid, WNOHANG);
223 push @$wait_pids, $ary; # autovivifies @$wait_pids
224 } elsif ($ret == $pid) {
226 eval { $cb->($arg, $pid) };
227 warn "E: dwaitpid($pid) in_loop: $@" if $@;
230 warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
233 sig_setmask($oldset);
234 delete $Stack{reap_runq};
237 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
238 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
240 sub in_loop () { $in_loop }
242 # Internal function: run the post-event callback, send read events
243 # for pushed-back data, and close pending connections. returns 1
244 # if event loop should continue, or 0 to shut it all down.
245 sub PostEventLoop () {
246 # now we can close sockets that wanted to close during our event
247 # processing. (we didn't want to close them during the loop, as we
248 # didn't want fd numbers being reused and confused during the event
250 if (my $close_now = $ToClose) {
251 $ToClose = undef; # will be autovivified on push
252 @$close_now = map { fileno($_) } @$close_now;
254 # order matters, destroy expiry times, first:
255 delete @$EXPMAP{@$close_now};
257 # ->DESTROY methods may populate ToClose
258 delete @DescriptorMap{@$close_now};
261 # by default we keep running, unless a postloop callback cancels it
262 $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
265 # Start processing IO events. In most daemon programs this never exits. See
266 # C<PostLoopCallback> for how to exit the loop.
267 sub event_loop (;$$) {
268 my ($sig, $oldset) = @_;
269 $Epoll //= _InitPoller();
270 require PublicInbox::Sigfd if $sig;
271 my $sigfd = PublicInbox::Sigfd->new($sig, 1) if $sig;
272 local @SIG{keys %$sig} = values(%$sig) if $sig && !$sigfd;
273 local $SIG{PIPE} = 'IGNORE';
274 if (!$sigfd && $sig) {
275 # wake up every second to accept signals if we don't
276 # have signalfd or IO::KQueue:
277 sig_setmask($oldset);
278 PublicInbox::DS->SetLoopTimeout(1000);
280 $_[0] = $sigfd = $sig = undef; # $_[0] == sig
284 my $timeout = RunTimers();
286 # get up to 1000 events
287 epoll_wait($Epoll, 1000, $timeout, \@events);
288 for my $fd (@events) {
289 # it's possible epoll_wait returned many events,
290 # including some at the end that ones in the front
291 # triggered unregister-interest actions. if we can't
292 # find the %sock entry, it's because we're no longer
293 # interested in that event.
295 # guard stack-not-refcounted w/ Carp + @DB::args
296 my $obj = $DescriptorMap{$fd};
299 } while (PostEventLoop());
302 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
304 Sets post loop callback function. Pass a subref and it will be
305 called every time the event loop finishes.
307 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
310 The callback function will be passed two parameters: \%DescriptorMap
313 sub SetPostLoopCallback {
314 my ($class, $ref) = @_;
317 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
320 #####################################################################
321 ### PublicInbox::DS-the-object code
322 #####################################################################
324 =head2 OBJECT METHODS
326 =head2 C<< CLASS->new( $socket ) >>
328 Create a new PublicInbox::DS subclass object for the given I<socket> which will
329 react to events on it during the C<event_loop>.
331 This is normally (always?) called from your subclass via:
333 $class->SUPER::new($socket);
337 my ($self, $sock, $ev) = @_;
338 $self->{sock} = $sock;
339 my $fd = fileno($sock);
341 $Epoll //= _InitPoller();
343 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
344 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
345 $ev &= ~EPOLLEXCLUSIVE;
348 die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
350 croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
351 if defined($DescriptorMap{$fd});
353 $DescriptorMap{$fd} = $self;
357 #####################################################################
358 ### I N S T A N C E M E T H O D S
359 #####################################################################
361 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
363 =head2 C<< $obj->close >>
370 my $sock = delete $self->{sock} or return;
372 # we need to flush our write buffer, as there may
373 # be self-referential closures (sub { $client->close })
374 # preventing the object from being destroyed
375 delete $self->{wbuf};
377 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
378 # notifications about it
379 my $fd = fileno($sock);
380 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
381 croak("EPOLL_CTL_DEL($self/$sock): $!");
383 # we explicitly don't delete from DescriptorMap here until we
384 # actually close the socket, as we might be in the middle of
385 # processing an epoll_wait/etc that returned hundreds of fds, one
386 # of which is not yet processed and is what we're closing. if we
387 # keep it in DescriptorMap, then the event harnesses can just
388 # looked at $pob->{sock} == undef and ignore it. but if it's an
389 # un-accounted for fd, then it (understandably) freak out a bit
390 # and emit warnings, thinking their state got off.
392 # defer closing the actual socket until the event loop is done
393 # processing this round of events. (otherwise we might reuse fds)
394 push @$ToClose, $sock; # autovivifies $ToClose
399 # portable, non-thread-safe sendfile emulation (no pread, yet)
400 sub send_tmpio ($$) {
401 my ($sock, $tmpio) = @_;
403 sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
404 my $n = $tmpio->[2] // 65536;
405 $n = 65536 if $n > 65536;
406 defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
408 while ($to_write > 0) {
409 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
413 return if $written == 0;
417 $tmpio->[1] += $written; # offset
418 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
422 sub epbit ($$) { # (sock, default)
423 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
426 # returns 1 if done, 0 if incomplete
427 sub flush_write ($) {
429 my $sock = $self->{sock} or return;
430 my $wbuf = $self->{wbuf} or return 1;
433 while (my $bref = $wbuf->[0]) {
434 if (ref($bref) ne 'CODE') {
436 my $w = send_tmpio($sock, $bref); # bref is tmpio
442 } elsif ($! == EAGAIN) {
443 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
444 epwait($sock, $ev | EPOLLONESHOT);
450 } else { #(ref($bref) eq 'CODE') {
452 my $before = scalar(@$wbuf);
455 # bref may be enqueueing more CODE to call (see accept_tls_step)
456 return 0 if (scalar(@$wbuf) > $before);
460 delete $self->{wbuf};
465 my ($self, $rbuf) = @_;
466 if ($$rbuf eq '') { # who knows how long till we can read again
467 delete $self->{rbuf};
469 $self->{rbuf} = $rbuf;
473 sub do_read ($$$;$) {
474 my ($self, $rbuf, $len, $off) = @_;
475 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
476 return ($r == 0 ? $self->close : $r) if defined $r;
477 # common for clients to break connections without warning,
478 # would be too noisy to log here:
480 my $ev = epbit($sock, EPOLLIN) or return $self->close;
481 epwait($sock, $ev | EPOLLONESHOT);
482 rbuf_idle($self, $rbuf);
489 # drop the socket if we hit unrecoverable errors on our system which
490 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
497 # n.b.: use ->write/->read for this buffer to allow compatibility with
498 # PerlIO::mmap or PerlIO::scalar if needed
500 my ($self, $bref, $off) = @_;
501 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
502 return drop($self, "tmpfile $!");
504 my $len = length($$bref) - $off;
505 print $fh substr($$bref, $off, $len) or
506 return drop($self, "write ($len): $!");
507 [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
510 =head2 C<< $obj->write( $data ) >>
512 Write the specified data to the underlying handle. I<data> may be scalar,
513 scalar ref, code ref (to run when there).
514 Returns 1 if writes all went through, or 0 if there are writes in queue. If
515 it returns 1, caller should stop waiting for 'writable' events)
519 my ($self, $data) = @_;
521 # nobody should be writing to closed sockets, but caller code can
522 # do two writes within an event, have the first fail and
523 # disconnect the other side (whose destructor then closes the
524 # calling object, but it's still in a method), and then the
525 # now-dead object does its second write. that is this case. we
526 # just lie and say it worked. it'll be dead soon and won't be
528 my $sock = $self->{sock} or return 1;
530 my $bref = $ref ? $data : \$data;
531 my $wbuf = $self->{wbuf};
532 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
533 if ($ref eq 'CODE') {
536 my $tmpio = $wbuf->[-1];
537 if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
538 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
540 my $tmpio = tmpio($self, $bref, 0) or return 0;
545 } elsif ($ref eq 'CODE') {
549 my $to_write = length($$bref);
550 my $written = syswrite($sock, $$bref, $to_write);
552 if (defined $written) {
553 return 1 if $written == $to_write;
554 requeue($self); # runs: event_step -> flush_write
555 } elsif ($! == EAGAIN) {
556 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
557 epwait($sock, $ev | EPOLLONESHOT);
563 # deal with EAGAIN or partial write:
564 my $tmpio = tmpio($self, $bref, $written) or return 0;
566 # wbuf may be an empty array if we're being called inside
567 # ->flush_write via CODE bref:
568 push @{$self->{wbuf}}, $tmpio; # autovivifies
573 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
577 my $sock = $self->{sock} or return 1;
578 my $wbuf = $self->{wbuf};
580 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
581 !$sock->can('stop_SSL')) {
582 my $n = send($sock, $_[1], MSG_MORE);
584 my $nlen = length($_[1]) - $n;
585 return 1 if $nlen == 0; # all done!
586 # queue up the unwritten substring:
587 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
588 push @{$self->{wbuf}}, $tmpio; # autovivifies
589 epwait($sock, EPOLLOUT|EPOLLONESHOT);
594 # don't redispatch into NNTPdeflate::write
595 PublicInbox::DS::write($self, \($_[1]));
599 my ($sock, $ev) = @_;
600 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
601 croak("EPOLL_CTL_MOD($sock): $!");
604 # return true if complete, false if incomplete (or failure)
605 sub accept_tls_step ($) {
607 my $sock = $self->{sock} or return;
608 return 1 if $sock->accept_SSL;
609 return $self->close if $! != EAGAIN;
610 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
611 epwait($sock, $ev | EPOLLONESHOT);
612 unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
616 # return true if complete, false if incomplete (or failure)
617 sub shutdn_tls_step ($) {
619 my $sock = $self->{sock} or return;
620 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
621 return $self->close if $! != EAGAIN;
622 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
623 epwait($sock, $ev | EPOLLONESHOT);
624 unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
628 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
629 # or fork w/o exec, so no inadvertent socket sharing
632 my $sock = $self->{sock} or return;
633 if ($sock->can('stop_SSL')) {
634 shutdn_tls_step($self);
640 sub dwaitpid ($;$$) {
641 my ($pid, $cb, $arg) = @_;
643 push @$wait_pids, [ $pid, $cb, $arg ];
644 # We could've just missed our SIGCHLD, cover it, here:
647 my $ret = waitpid($pid, 0);
650 eval { $cb->($arg, $pid) };
651 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
654 carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
660 my $cur = $EXPMAP or return;
662 my $old = now() - $EXPTIME;
663 while (my ($fd, $idle_at) = each %$cur) {
664 if ($idle_at < $old) {
665 my $ds_obj = $DescriptorMap{$fd};
666 $EXPMAP->{$fd} = $idle_at if !$ds_obj->shutdn;
668 $EXPMAP->{$fd} = $idle_at;
671 add_uniq_timer('expire', 60, \&expire_old) if $EXPMAP;
674 sub update_idle_time {
676 my $sock = $self->{sock} or return;
677 $EXPMAP->{fileno($sock)} = now();
678 add_uniq_timer('expire', 60, \&expire_old);
682 my ($self, $now) = @_;
683 my $sock = $self->{sock} or return;
684 my $idle_at = $EXPMAP->{fileno($sock)} or return;
685 ($idle_at + $EXPTIME) > $now;
690 =head1 AUTHORS (Danga::Socket)
692 Brad Fitzpatrick <brad@danga.com> - author
694 Michael Granger <ged@danga.com> - docs, testing
696 Mark Smith <junior@danga.com> - contributor, heavy user, testing
698 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits