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 POSIX qw(WNOHANG);
27 use Fcntl qw(SEEK_SET :DEFAULT O_APPEND);
28 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
29 use parent qw(Exporter);
30 our @EXPORT_OK = qw(now msg_more);
32 use Scalar::Util qw(blessed);
33 use PublicInbox::Syscall qw(:epoll);
34 use PublicInbox::Tmpfile;
35 use Errno qw(EAGAIN EINVAL);
36 use Carp qw(confess carp);
38 my $nextq; # queue for next_tick
39 my $wait_pids; # list of [ pid, callback, callback_arg ]
40 my $later_queue; # 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, $reap_timer, $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
53 $DoneInit, # if we've done the one-time module init yet
60 #####################################################################
61 ### C L A S S M E T H O D S
62 #####################################################################
64 =head2 C<< CLASS->Reset() >>
71 $in_loop = $wait_pids = $later_queue = $reap_armed = undef;
73 $nextq = $ToClose = $reap_timer = $later_timer = $exp_timer = undef;
74 $LoopTimeout = -1; # no timeout by default
77 $PostLoopCallback = undef;
80 $_io = undef; # closes real $Epoll FD
81 $Epoll = undef; # may call DSKQXS::DESTROY
83 *EventLoop = *FirstTimeEventLoop;
86 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
88 Set the loop timeout for the event loop to some value in milliseconds.
90 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
95 return $LoopTimeout = $_[1] + 0;
98 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef, $arg) >>
100 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
101 are not guaranteed to fire at the exact time you ask for.
104 sub add_timer ($$;$) {
105 my ($secs, $coderef, $arg) = @_;
107 my $fire_time = now() + $secs;
109 my $timer = [$fire_time, $coderef, $arg];
111 if (!@Timers || $fire_time >= $Timers[-1][0]) {
112 push @Timers, $timer;
116 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
117 # but it was compared against calendar queues, heaps, naive push/sort,
118 # and a bunch of other versions, and found to be fastest with a large
119 # variety of datasets.)
120 for (my $i = 0; $i < @Timers; $i++) {
121 if ($Timers[$i][0] > $fire_time) {
122 splice(@Timers, $i, 0, $timer);
127 die "Shouldn't get here.";
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 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
136 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
137 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
145 if (PublicInbox::Syscall::epoll_defined()) {
146 $Epoll = epoll_create();
147 set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
150 for (qw(DSKQXS DSPoll)) {
151 $cls = "PublicInbox::$_";
152 last if eval "require $cls";
154 $cls->import(qw(epoll_ctl epoll_wait));
157 *EventLoop = *EpollEventLoop;
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.
166 sub FirstTimeEventLoop {
174 sub now () { clock_gettime(CLOCK_MONOTONIC) }
177 my $q = $nextq or return;
180 # we avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
181 # https://rt.perl.org/Public/Bug/Display.html?id=114340
190 # runs timers and returns milliseconds for next one, or next event loop
194 return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
199 while (@Timers && $Timers[0][0] <= $now) {
200 my $to_run = shift(@Timers);
201 $to_run->[1]->($to_run->[2]);
204 # timers may enqueue into nextq:
205 return 0 if ($nextq || $ToClose);
207 return $LoopTimeout unless @Timers;
209 # convert time to an even number of milliseconds, adding 1
210 # extra, otherwise floating point fun can occur and we'll
211 # call RunTimers like 20-30 times, each returning a timeout
212 # of 0.0000212 seconds
213 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
215 # -1 is an infinite timeout, so prefer a real timeout
216 return $timeout if $LoopTimeout == -1;
218 # otherwise pick the lower of our regular timeout and time until
220 return $LoopTimeout if $LoopTimeout < $timeout;
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 foreach my $ary (@$tmp) {
234 my ($pid, $cb, $arg) = @$ary;
235 my $ret = waitpid($pid, WNOHANG);
237 push @$wait_pids, $ary; # autovivifies @$wait_pids
239 eval { $cb->($arg, $pid) };
242 # we may not be done, yet, and could've missed/masked a SIGCHLD:
243 if ($wait_pids && !$reap_armed) {
244 $reap_timer //= add_timer(1, \&reap_pids_timed);
248 sub reap_pids_timed {
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;
286 my $timeout = RunTimers();
288 # get up to 1000 events
289 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
290 for ($i=0; $i<$evcount; $i++) {
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
295 $DescriptorMap{$events[$i]->[0]}->event_step;
297 } while (PostEventLoop());
301 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
303 Sets post loop callback function. Pass a subref and it will be
304 called every time the event loop finishes.
306 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
309 The callback function will be passed two parameters: \%DescriptorMap
312 sub SetPostLoopCallback {
313 my ($class, $ref) = @_;
316 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
319 #####################################################################
320 ### PublicInbox::DS-the-object code
321 #####################################################################
323 =head2 OBJECT METHODS
325 =head2 C<< CLASS->new( $socket ) >>
327 Create a new PublicInbox::DS subclass object for the given I<socket> which will
328 react to events on it during the C<EventLoop>.
330 This is normally (always?) called from your subclass via:
332 $class->SUPER::new($socket);
336 my ($self, $sock, $ev) = @_;
337 $self->{sock} = $sock;
338 my $fd = fileno($sock);
342 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
343 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
344 $ev &= ~EPOLLEXCLUSIVE;
347 die "couldn't add epoll watch for $fd: $!\n";
349 confess("DescriptorMap{$fd} defined ($DescriptorMap{$fd})")
350 if defined($DescriptorMap{$fd});
352 $DescriptorMap{$fd} = $self;
356 #####################################################################
357 ### I N S T A N C E M E T H O D S
358 #####################################################################
360 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
362 =head2 C<< $obj->close >>
369 my $sock = delete $self->{sock} or return;
371 # we need to flush our write buffer, as there may
372 # be self-referential closures (sub { $client->close })
373 # preventing the object from being destroyed
374 delete $self->{wbuf};
376 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
377 # notifications about it
378 my $fd = fileno($sock);
379 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
380 confess("EPOLL_CTL_DEL: $!");
382 # we explicitly don't delete from DescriptorMap here until we
383 # actually close the socket, as we might be in the middle of
384 # processing an epoll_wait/etc that returned hundreds of fds, one
385 # of which is not yet processed and is what we're closing. if we
386 # keep it in DescriptorMap, then the event harnesses can just
387 # looked at $pob->{sock} == undef and ignore it. but if it's an
388 # un-accounted for fd, then it (understandably) freak out a bit
389 # and emit warnings, thinking their state got off.
391 # defer closing the actual socket until the event loop is done
392 # processing this round of events. (otherwise we might reuse fds)
393 push @$ToClose, $sock; # autovivifies $ToClose
398 # portable, non-thread-safe sendfile emulation (no pread, yet)
399 sub send_tmpio ($$) {
400 my ($sock, $tmpio) = @_;
402 sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
403 my $n = $tmpio->[2] // 65536;
404 $n = 65536 if $n > 65536;
405 defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
407 while ($to_write > 0) {
408 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
412 return if $written == 0;
416 $tmpio->[1] += $written; # offset
417 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
421 sub epbit ($$) { # (sock, default)
422 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
425 # returns 1 if done, 0 if incomplete
426 sub flush_write ($) {
428 my $sock = $self->{sock} or return;
429 my $wbuf = $self->{wbuf} or return 1;
432 while (my $bref = $wbuf->[0]) {
433 if (ref($bref) ne 'CODE') {
435 my $w = send_tmpio($sock, $bref); # bref is tmpio
441 } elsif ($! == EAGAIN) {
442 epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
448 } else { #(ref($bref) eq 'CODE') {
450 my $before = scalar(@$wbuf);
453 # bref may be enqueueing more CODE to call (see accept_tls_step)
454 return 0 if (scalar(@$wbuf) > $before);
458 delete $self->{wbuf};
463 my ($self, $rbuf) = @_;
464 if ($$rbuf eq '') { # who knows how long till we can read again
465 delete $self->{rbuf};
467 $self->{rbuf} = $rbuf;
471 sub do_read ($$$;$) {
472 my ($self, $rbuf, $len, $off) = @_;
473 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
474 return ($r == 0 ? $self->close : $r) if defined $r;
475 # common for clients to break connections without warning,
476 # would be too noisy to log here:
478 epwait($sock, epbit($sock, EPOLLIN) | EPOLLONESHOT);
479 rbuf_idle($self, $rbuf);
486 # drop the socket if we hit unrecoverable errors on our system which
487 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
494 # n.b.: use ->write/->read for this buffer to allow compatibility with
495 # PerlIO::mmap or PerlIO::scalar if needed
497 my ($self, $bref, $off) = @_;
498 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
499 return drop($self, "tmpfile $!");
501 my $len = bytes::length($$bref) - $off;
502 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
503 [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
506 =head2 C<< $obj->write( $data ) >>
508 Write the specified data to the underlying handle. I<data> may be scalar,
509 scalar ref, code ref (to run when there).
510 Returns 1 if writes all went through, or 0 if there are writes in queue. If
511 it returns 1, caller should stop waiting for 'writable' events)
515 my ($self, $data) = @_;
517 # nobody should be writing to closed sockets, but caller code can
518 # do two writes within an event, have the first fail and
519 # disconnect the other side (whose destructor then closes the
520 # calling object, but it's still in a method), and then the
521 # now-dead object does its second write. that is this case. we
522 # just lie and say it worked. it'll be dead soon and won't be
524 my $sock = $self->{sock} or return 1;
526 my $bref = $ref ? $data : \$data;
527 my $wbuf = $self->{wbuf};
528 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
529 if ($ref eq 'CODE') {
532 my $tmpio = $wbuf->[-1];
533 if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
534 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
536 my $tmpio = tmpio($self, $bref, 0) or return 0;
541 } elsif ($ref eq 'CODE') {
545 my $to_write = bytes::length($$bref);
546 my $written = syswrite($sock, $$bref, $to_write);
548 if (defined $written) {
549 return 1 if $written == $to_write;
550 requeue($self); # runs: event_step -> flush_write
551 } elsif ($! == EAGAIN) {
552 epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
558 # deal with EAGAIN or partial write:
559 my $tmpio = tmpio($self, $bref, $written) or return 0;
561 # wbuf may be an empty array if we're being called inside
562 # ->flush_write via CODE bref:
563 push @{$self->{wbuf}}, $tmpio; # autovivifies
568 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
572 my $sock = $self->{sock} or return 1;
573 my $wbuf = $self->{wbuf};
575 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
576 !$sock->can('stop_SSL')) {
577 my $n = send($sock, $_[1], MSG_MORE);
579 my $nlen = bytes::length($_[1]) - $n;
580 return 1 if $nlen == 0; # all done!
581 # queue up the unwritten substring:
582 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
583 push @{$self->{wbuf}}, $tmpio; # autovivifies
584 epwait($sock, EPOLLOUT|EPOLLONESHOT);
589 # don't redispatch into NNTPdeflate::write
590 PublicInbox::DS::write($self, \($_[1]));
594 my ($sock, $ev) = @_;
595 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
596 confess("EPOLL_CTL_MOD $!");
599 # return true if complete, false if incomplete (or failure)
600 sub accept_tls_step ($) {
602 my $sock = $self->{sock} or return;
603 return 1 if $sock->accept_SSL;
604 return $self->close if $! != EAGAIN;
605 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
606 unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
610 # return true if complete, false if incomplete (or failure)
611 sub shutdn_tls_step ($) {
613 my $sock = $self->{sock} or return;
614 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
615 return $self->close if $! != EAGAIN;
616 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
617 unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
621 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
622 # or fork w/o exec, so no inadvertent socket sharing
625 my $sock = $self->{sock} or return;
626 if ($sock->can('stop_SSL')) {
627 shutdn_tls_step($self);
633 # must be called with eval, PublicInbox::DS may not be loaded (see t/qspawn.t)
635 die "Not in EventLoop\n" unless $in_loop;
636 push @$wait_pids, [ @_ ]; # [ $pid, $cb, $arg ]
638 # We could've just missed our SIGCHLD, cover it, here:
639 goto &enqueue_reap; # tail recursion
643 my $run = $later_queue or return;
644 $later_timer = $later_queue = undef;
649 push @$later_queue, $_[0]; # autovivifies @$later_queue
650 $later_timer //= add_timer(60, \&_run_later);
656 my $old = $now - $exp;
658 while (my ($fd, $idle_at) = each %$EXPMAP) {
659 if ($idle_at < $old) {
660 my $ds_obj = $DescriptorMap{$fd};
661 $new{$fd} = $idle_at if !$ds_obj->shutdn;
663 $new{$fd} = $idle_at;
667 $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
670 sub update_idle_time {
672 my $sock = $self->{sock} or return;
673 $EXPMAP->{fileno($sock)} = now();
674 $exp_timer //= later(\&expire_old);
678 my ($self, $now) = @_;
679 my $sock = $self->{sock} or return;
680 my $idle_at = $EXPMAP->{fileno($sock)} or return;
681 ($idle_at + $EXPTIME) > $now;
686 =head1 AUTHORS (Danga::Socket)
688 Brad Fitzpatrick <brad@danga.com> - author
690 Michael Granger <ged@danga.com> - docs, testing
692 Mark Smith <junior@danga.com> - contributor, heavy user, testing
694 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits