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);
29 use Fcntl qw(SEEK_SET :DEFAULT O_APPEND);
30 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
31 use Scalar::Util qw(blessed);
32 use PublicInbox::Syscall qw(:epoll);
33 use PublicInbox::Tmpfile;
34 use Errno qw(EAGAIN EINVAL);
35 use Carp qw(carp croak);
36 our @EXPORT_OK = qw(now msg_more dwaitpid add_timer);
39 my $nextq; # queue for next_tick
40 my $wait_pids; # list of [ pid, callback, callback_arg ]
41 my $later_q; # list of callbacks to run at some later interval
42 my $EXPMAP; # fd -> idle_time
43 our $EXPTIME = 180; # 3 minutes
44 my ($later_timer, $reap_armed, $exp_timer);
45 my $ToClose; # sockets to close when event loop is done
47 %DescriptorMap, # fd (num) -> PublicInbox::DS object
48 $Epoll, # Global epoll fd (or DSKQXS ref)
49 $_io, # IO::Handle for Epoll
51 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
53 $LoopTimeout, # timeout of event loop in milliseconds
60 #####################################################################
61 ### C L A S S M E T H O D S
62 #####################################################################
64 =head2 C<< CLASS->Reset() >>
71 $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 = $later_q = $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 $later_q || $ToClose || keys(%DescriptorMap) ||
87 $reap_armed = $later_timer = $exp_timer = undef;
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 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef, $arg) >>
103 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
104 are not guaranteed to fire at the exact time you ask for.
107 sub add_timer ($$;@) {
108 my ($secs, $coderef, @args) = @_;
110 my $fire_time = now() + $secs;
112 my $timer = [$fire_time, $coderef, @args];
114 if (!@Timers || $fire_time >= $Timers[-1][0]) {
115 push @Timers, $timer;
119 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
120 # but it was compared against calendar queues, heaps, naive push/sort,
121 # and a bunch of other versions, and found to be fastest with a large
122 # variety of datasets.)
123 for (my $i = 0; $i < @Timers; $i++) {
124 if ($Timers[$i][0] > $fire_time) {
125 splice(@Timers, $i, 0, $timer);
130 die "Shouldn't get here.";
133 # keeping this around in case we support other FD types for now,
134 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
135 sub set_cloexec ($) {
138 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
139 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
140 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
143 # caller sets return value to $Epoll
146 if (PublicInbox::Syscall::epoll_defined()) {
147 my $fd = epoll_create();
148 set_cloexec($fd) if (defined($fd) && $fd >= 0);
152 for (qw(DSKQXS DSPoll)) {
153 $cls = "PublicInbox::$_";
154 last if eval "require $cls";
156 $cls->import(qw(epoll_ctl epoll_wait));
161 =head2 C<< CLASS->EventLoop() >>
163 Start processing IO events. In most daemon programs this never exits. See
164 C<PostLoopCallback> below for how to exit the loop.
168 sub now () { clock_gettime(CLOCK_MONOTONIC) }
171 my $q = $nextq or return;
173 $Stack{cur_runq} = $q;
175 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
176 # https://rt.perl.org/Public/Bug/Display.html?id=114340
183 delete $Stack{cur_runq};
186 # runs timers and returns milliseconds for next one, or next event loop
190 return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
195 while (@Timers && $Timers[0][0] <= $now) {
196 my $to_run = shift(@Timers);
197 $to_run->[1]->(@$to_run[2..$#$to_run]);
200 # timers may enqueue into nextq:
201 return 0 if ($nextq || $ToClose);
203 return $LoopTimeout unless @Timers;
205 # convert time to an even number of milliseconds, adding 1
206 # extra, otherwise floating point fun can occur and we'll
207 # call RunTimers like 20-30 times, each returning a timeout
208 # of 0.0000212 seconds
209 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
211 # -1 is an infinite timeout, so prefer a real timeout
212 ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout;
215 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
217 sub block_signals () {
218 my $oldset = POSIX::SigSet->new;
219 my $newset = POSIX::SigSet->new;
220 $newset->fillset or die "fillset: $!";
221 sig_setmask($newset, $oldset);
225 # We can't use waitpid(-1) safely here since it can hit ``, system(),
226 # and other things. So we scan the $wait_pids list, which is hopefully
227 # not too big. We keep $wait_pids small by not calling dwaitpid()
228 # until we've hit EOF when reading the stdout of the child.
232 my $tmp = $wait_pids or return;
234 $Stack{reap_runq} = $tmp;
235 my $oldset = block_signals();
236 foreach my $ary (@$tmp) {
237 my ($pid, $cb, $arg) = @$ary;
238 my $ret = waitpid($pid, WNOHANG);
240 push @$wait_pids, $ary; # autovivifies @$wait_pids
241 } elsif ($ret == $pid) {
243 eval { $cb->($arg, $pid) };
244 warn "E: dwaitpid($pid) in_loop: $@" if $@;
247 warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
250 sig_setmask($oldset);
251 delete $Stack{reap_runq};
254 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
255 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
257 sub in_loop () { $in_loop }
259 # Internal function: run the post-event callback, send read events
260 # for pushed-back data, and close pending connections. returns 1
261 # if event loop should continue, or 0 to shut it all down.
262 sub PostEventLoop () {
263 # now we can close sockets that wanted to close during our event
264 # processing. (we didn't want to close them during the loop, as we
265 # didn't want fd numbers being reused and confused during the event
267 if (my $close_now = $ToClose) {
268 $ToClose = undef; # will be autovivified on push
269 @$close_now = map { fileno($_) } @$close_now;
271 # order matters, destroy expiry times, first:
272 delete @$EXPMAP{@$close_now};
274 # ->DESTROY methods may populate ToClose
275 delete @DescriptorMap{@$close_now};
278 # by default we keep running, unless a postloop callback cancels it
279 $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
283 $Epoll //= _InitPoller();
287 my $timeout = RunTimers();
289 # get up to 1000 events
290 epoll_wait($Epoll, 1000, $timeout, \@events);
291 for my $fd (@events) {
292 # it's possible epoll_wait returned many events, including some at the end
293 # that ones in the front triggered unregister-interest actions. if we
294 # can't find the %sock entry, it's because we're no longer interested
297 # guard stack-not-refcounted w/ Carp + @DB::args
298 my $obj = $DescriptorMap{$fd};
301 } while (PostEventLoop());
305 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
307 Sets post loop callback function. Pass a subref and it will be
308 called every time the event loop finishes.
310 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
313 The callback function will be passed two parameters: \%DescriptorMap
316 sub SetPostLoopCallback {
317 my ($class, $ref) = @_;
320 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
323 #####################################################################
324 ### PublicInbox::DS-the-object code
325 #####################################################################
327 =head2 OBJECT METHODS
329 =head2 C<< CLASS->new( $socket ) >>
331 Create a new PublicInbox::DS subclass object for the given I<socket> which will
332 react to events on it during the C<EventLoop>.
334 This is normally (always?) called from your subclass via:
336 $class->SUPER::new($socket);
340 my ($self, $sock, $ev) = @_;
341 $self->{sock} = $sock;
342 my $fd = fileno($sock);
344 $Epoll //= _InitPoller();
346 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
347 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
348 $ev &= ~EPOLLEXCLUSIVE;
351 die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
353 croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
354 if defined($DescriptorMap{$fd});
356 $DescriptorMap{$fd} = $self;
360 #####################################################################
361 ### I N S T A N C E M E T H O D S
362 #####################################################################
364 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
366 =head2 C<< $obj->close >>
373 my $sock = delete $self->{sock} or return;
375 # we need to flush our write buffer, as there may
376 # be self-referential closures (sub { $client->close })
377 # preventing the object from being destroyed
378 delete $self->{wbuf};
380 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
381 # notifications about it
382 my $fd = fileno($sock);
383 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
384 croak("EPOLL_CTL_DEL($self/$sock): $!");
386 # we explicitly don't delete from DescriptorMap here until we
387 # actually close the socket, as we might be in the middle of
388 # processing an epoll_wait/etc that returned hundreds of fds, one
389 # of which is not yet processed and is what we're closing. if we
390 # keep it in DescriptorMap, then the event harnesses can just
391 # looked at $pob->{sock} == undef and ignore it. but if it's an
392 # un-accounted for fd, then it (understandably) freak out a bit
393 # and emit warnings, thinking their state got off.
395 # defer closing the actual socket until the event loop is done
396 # processing this round of events. (otherwise we might reuse fds)
397 push @$ToClose, $sock; # autovivifies $ToClose
402 # portable, non-thread-safe sendfile emulation (no pread, yet)
403 sub send_tmpio ($$) {
404 my ($sock, $tmpio) = @_;
406 sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
407 my $n = $tmpio->[2] // 65536;
408 $n = 65536 if $n > 65536;
409 defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
411 while ($to_write > 0) {
412 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
416 return if $written == 0;
420 $tmpio->[1] += $written; # offset
421 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
425 sub epbit ($$) { # (sock, default)
426 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
429 # returns 1 if done, 0 if incomplete
430 sub flush_write ($) {
432 my $sock = $self->{sock} or return;
433 my $wbuf = $self->{wbuf} or return 1;
436 while (my $bref = $wbuf->[0]) {
437 if (ref($bref) ne 'CODE') {
439 my $w = send_tmpio($sock, $bref); # bref is tmpio
445 } elsif ($! == EAGAIN) {
446 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
447 epwait($sock, $ev | EPOLLONESHOT);
453 } else { #(ref($bref) eq 'CODE') {
455 my $before = scalar(@$wbuf);
458 # bref may be enqueueing more CODE to call (see accept_tls_step)
459 return 0 if (scalar(@$wbuf) > $before);
463 delete $self->{wbuf};
468 my ($self, $rbuf) = @_;
469 if ($$rbuf eq '') { # who knows how long till we can read again
470 delete $self->{rbuf};
472 $self->{rbuf} = $rbuf;
476 sub do_read ($$$;$) {
477 my ($self, $rbuf, $len, $off) = @_;
478 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
479 return ($r == 0 ? $self->close : $r) if defined $r;
480 # common for clients to break connections without warning,
481 # would be too noisy to log here:
483 my $ev = epbit($sock, EPOLLIN) or return $self->close;
484 epwait($sock, $ev | EPOLLONESHOT);
485 rbuf_idle($self, $rbuf);
492 # drop the socket if we hit unrecoverable errors on our system which
493 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
500 # n.b.: use ->write/->read for this buffer to allow compatibility with
501 # PerlIO::mmap or PerlIO::scalar if needed
503 my ($self, $bref, $off) = @_;
504 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
505 return drop($self, "tmpfile $!");
507 my $len = bytes::length($$bref) - $off;
508 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
509 [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
512 =head2 C<< $obj->write( $data ) >>
514 Write the specified data to the underlying handle. I<data> may be scalar,
515 scalar ref, code ref (to run when there).
516 Returns 1 if writes all went through, or 0 if there are writes in queue. If
517 it returns 1, caller should stop waiting for 'writable' events)
521 my ($self, $data) = @_;
523 # nobody should be writing to closed sockets, but caller code can
524 # do two writes within an event, have the first fail and
525 # disconnect the other side (whose destructor then closes the
526 # calling object, but it's still in a method), and then the
527 # now-dead object does its second write. that is this case. we
528 # just lie and say it worked. it'll be dead soon and won't be
530 my $sock = $self->{sock} or return 1;
532 my $bref = $ref ? $data : \$data;
533 my $wbuf = $self->{wbuf};
534 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
535 if ($ref eq 'CODE') {
538 my $tmpio = $wbuf->[-1];
539 if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
540 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
542 my $tmpio = tmpio($self, $bref, 0) or return 0;
547 } elsif ($ref eq 'CODE') {
551 my $to_write = bytes::length($$bref);
552 my $written = syswrite($sock, $$bref, $to_write);
554 if (defined $written) {
555 return 1 if $written == $to_write;
556 requeue($self); # runs: event_step -> flush_write
557 } elsif ($! == EAGAIN) {
558 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
559 epwait($sock, $ev | EPOLLONESHOT);
565 # deal with EAGAIN or partial write:
566 my $tmpio = tmpio($self, $bref, $written) or return 0;
568 # wbuf may be an empty array if we're being called inside
569 # ->flush_write via CODE bref:
570 push @{$self->{wbuf}}, $tmpio; # autovivifies
575 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
579 my $sock = $self->{sock} or return 1;
580 my $wbuf = $self->{wbuf};
582 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
583 !$sock->can('stop_SSL')) {
584 my $n = send($sock, $_[1], MSG_MORE);
586 my $nlen = bytes::length($_[1]) - $n;
587 return 1 if $nlen == 0; # all done!
588 # queue up the unwritten substring:
589 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
590 push @{$self->{wbuf}}, $tmpio; # autovivifies
591 epwait($sock, EPOLLOUT|EPOLLONESHOT);
596 # don't redispatch into NNTPdeflate::write
597 PublicInbox::DS::write($self, \($_[1]));
601 my ($sock, $ev) = @_;
602 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
603 croak("EPOLL_CTL_MOD($sock): $!");
606 # return true if complete, false if incomplete (or failure)
607 sub accept_tls_step ($) {
609 my $sock = $self->{sock} or return;
610 return 1 if $sock->accept_SSL;
611 return $self->close if $! != EAGAIN;
612 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
613 epwait($sock, $ev | EPOLLONESHOT);
614 unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
618 # return true if complete, false if incomplete (or failure)
619 sub shutdn_tls_step ($) {
621 my $sock = $self->{sock} or return;
622 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
623 return $self->close if $! != EAGAIN;
624 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
625 epwait($sock, $ev | EPOLLONESHOT);
626 unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
630 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
631 # or fork w/o exec, so no inadvertent socket sharing
634 my $sock = $self->{sock} or return;
635 if ($sock->can('stop_SSL')) {
636 shutdn_tls_step($self);
642 sub dwaitpid ($;$$) {
643 my ($pid, $cb, $arg) = @_;
645 push @$wait_pids, [ $pid, $cb, $arg ];
646 # We could've just missed our SIGCHLD, cover it, here:
649 my $ret = waitpid($pid, 0);
652 eval { $cb->($arg, $pid) };
653 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
656 carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
662 my $q = $later_q or return;
663 $later_timer = $later_q = undef;
664 $Stack{later_q} = $q;
666 delete $Stack{later_q};
670 push @$later_q, $_[0]; # autovivifies @$later_q
671 $later_timer //= add_timer(60, \&_run_later);
677 my $old = $now - $exp;
679 while (my ($fd, $idle_at) = each %$EXPMAP) {
680 if ($idle_at < $old) {
681 my $ds_obj = $DescriptorMap{$fd};
682 $new{$fd} = $idle_at if !$ds_obj->shutdn;
684 $new{$fd} = $idle_at;
688 $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
691 sub update_idle_time {
693 my $sock = $self->{sock} or return;
694 $EXPMAP->{fileno($sock)} = now();
695 $exp_timer //= later(\&expire_old);
699 my ($self, $now) = @_;
700 my $sock = $self->{sock} or return;
701 my $idle_at = $EXPMAP->{fileno($sock)} or return;
702 ($idle_at + $EXPTIME) > $now;
707 =head1 AUTHORS (Danga::Socket)
709 Brad Fitzpatrick <brad@danga.com> - author
711 Michael Granger <ged@danga.com> - docs, testing
713 Mark Smith <junior@danga.com> - contributor, heavy user, testing
715 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits