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(confess carp);
36 our @EXPORT_OK = qw(now msg_more dwaitpid);
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, $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() >>
69 $in_loop = undef; # first in case DESTROY callbacks use this
71 $wait_pids = $later_queue = $reap_armed = undef;
73 $nextq = $ToClose = $later_timer = $exp_timer = undef;
74 $LoopTimeout = -1; # no timeout by default
77 $PostLoopCallback = undef;
79 $_io = undef; # closes real $Epoll FD
80 $Epoll = undef; # may call DSKQXS::DESTROY
83 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
85 Set the loop timeout for the event loop to some value in milliseconds.
87 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
91 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
93 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef, $arg) >>
95 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
96 are not guaranteed to fire at the exact time you ask for.
99 sub add_timer ($$;$) {
100 my ($secs, $coderef, $arg) = @_;
102 my $fire_time = now() + $secs;
104 my $timer = [$fire_time, $coderef, $arg];
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);
122 die "Shouldn't get here.";
125 # keeping this around in case we support other FD types for now,
126 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
127 sub set_cloexec ($) {
130 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
131 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
132 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
135 # caller sets return value to $Epoll
138 if (PublicInbox::Syscall::epoll_defined()) {
139 my $fd = epoll_create();
140 set_cloexec($fd) if (defined($fd) && $fd >= 0);
144 for (qw(DSKQXS DSPoll)) {
145 $cls = "PublicInbox::$_";
146 last if eval "require $cls";
148 $cls->import(qw(epoll_ctl epoll_wait));
153 =head2 C<< CLASS->EventLoop() >>
155 Start processing IO events. In most daemon programs this never exits. See
156 C<PostLoopCallback> below for how to exit the loop.
160 sub now () { clock_gettime(CLOCK_MONOTONIC) }
163 my $q = $nextq or return;
166 # we avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
167 # https://rt.perl.org/Public/Bug/Display.html?id=114340
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 $to_run->[1]->($to_run->[2]);
190 # timers may enqueue into nextq:
191 return 0 if ($nextq || $ToClose);
193 return $LoopTimeout unless @Timers;
195 # convert time to an even number of milliseconds, adding 1
196 # extra, otherwise floating point fun can occur and we'll
197 # call RunTimers like 20-30 times, each returning a timeout
198 # of 0.0000212 seconds
199 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
201 # -1 is an infinite timeout, so prefer a real timeout
202 ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout;
205 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
207 sub block_signals () {
208 my $oldset = POSIX::SigSet->new;
209 my $newset = POSIX::SigSet->new;
210 $newset->fillset or die "fillset: $!";
211 sig_setmask($newset, $oldset);
215 # We can't use waitpid(-1) safely here since it can hit ``, system(),
216 # and other things. So we scan the $wait_pids list, which is hopefully
217 # not too big. We keep $wait_pids small by not calling dwaitpid()
218 # until we've hit EOF when reading the stdout of the child.
222 my $tmp = $wait_pids or return;
224 my $oldset = block_signals();
225 foreach my $ary (@$tmp) {
226 my ($pid, $cb, $arg) = @$ary;
227 my $ret = waitpid($pid, WNOHANG);
229 push @$wait_pids, $ary; # autovivifies @$wait_pids
230 } elsif ($ret == $pid) {
232 eval { $cb->($arg, $pid) };
233 warn "E: dwaitpid($pid) in_loop: $@" if $@;
236 warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
239 sig_setmask($oldset);
242 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
243 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
245 sub in_loop () { $in_loop }
247 # Internal function: run the post-event callback, send read events
248 # for pushed-back data, and close pending connections. returns 1
249 # if event loop should continue, or 0 to shut it all down.
250 sub PostEventLoop () {
251 # now we can close sockets that wanted to close during our event
252 # processing. (we didn't want to close them during the loop, as we
253 # didn't want fd numbers being reused and confused during the event
255 if (my $close_now = $ToClose) {
256 $ToClose = undef; # will be autovivified on push
257 @$close_now = map { fileno($_) } @$close_now;
259 # order matters, destroy expiry times, first:
260 delete @$EXPMAP{@$close_now};
262 # ->DESTROY methods may populate ToClose
263 delete @DescriptorMap{@$close_now};
266 # by default we keep running, unless a postloop callback cancels it
267 $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
271 $Epoll //= _InitPoller();
275 my $timeout = RunTimers();
277 # get up to 1000 events
278 epoll_wait($Epoll, 1000, $timeout, \@events);
279 for my $fd (@events) {
280 # it's possible epoll_wait returned many events, including some at the end
281 # that ones in the front triggered unregister-interest actions. if we
282 # can't find the %sock entry, it's because we're no longer interested
284 $DescriptorMap{$fd}->event_step;
286 } while (PostEventLoop());
290 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
292 Sets post loop callback function. Pass a subref and it will be
293 called every time the event loop finishes.
295 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
298 The callback function will be passed two parameters: \%DescriptorMap
301 sub SetPostLoopCallback {
302 my ($class, $ref) = @_;
305 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
308 #####################################################################
309 ### PublicInbox::DS-the-object code
310 #####################################################################
312 =head2 OBJECT METHODS
314 =head2 C<< CLASS->new( $socket ) >>
316 Create a new PublicInbox::DS subclass object for the given I<socket> which will
317 react to events on it during the C<EventLoop>.
319 This is normally (always?) called from your subclass via:
321 $class->SUPER::new($socket);
325 my ($self, $sock, $ev) = @_;
326 $self->{sock} = $sock;
327 my $fd = fileno($sock);
329 $Epoll //= _InitPoller();
331 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
332 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
333 $ev &= ~EPOLLEXCLUSIVE;
336 die "couldn't add epoll watch for $fd: $!\n";
338 confess("DescriptorMap{$fd} defined ($DescriptorMap{$fd})")
339 if defined($DescriptorMap{$fd});
341 $DescriptorMap{$fd} = $self;
345 #####################################################################
346 ### I N S T A N C E M E T H O D S
347 #####################################################################
349 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
351 =head2 C<< $obj->close >>
358 my $sock = delete $self->{sock} or return;
360 # we need to flush our write buffer, as there may
361 # be self-referential closures (sub { $client->close })
362 # preventing the object from being destroyed
363 delete $self->{wbuf};
365 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
366 # notifications about it
367 my $fd = fileno($sock);
368 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
369 confess("EPOLL_CTL_DEL: $!");
371 # we explicitly don't delete from DescriptorMap here until we
372 # actually close the socket, as we might be in the middle of
373 # processing an epoll_wait/etc that returned hundreds of fds, one
374 # of which is not yet processed and is what we're closing. if we
375 # keep it in DescriptorMap, then the event harnesses can just
376 # looked at $pob->{sock} == undef and ignore it. but if it's an
377 # un-accounted for fd, then it (understandably) freak out a bit
378 # and emit warnings, thinking their state got off.
380 # defer closing the actual socket until the event loop is done
381 # processing this round of events. (otherwise we might reuse fds)
382 push @$ToClose, $sock; # autovivifies $ToClose
387 # portable, non-thread-safe sendfile emulation (no pread, yet)
388 sub send_tmpio ($$) {
389 my ($sock, $tmpio) = @_;
391 sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
392 my $n = $tmpio->[2] // 65536;
393 $n = 65536 if $n > 65536;
394 defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
396 while ($to_write > 0) {
397 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
401 return if $written == 0;
405 $tmpio->[1] += $written; # offset
406 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
410 sub epbit ($$) { # (sock, default)
411 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
414 # returns 1 if done, 0 if incomplete
415 sub flush_write ($) {
417 my $sock = $self->{sock} or return;
418 my $wbuf = $self->{wbuf} or return 1;
421 while (my $bref = $wbuf->[0]) {
422 if (ref($bref) ne 'CODE') {
424 my $w = send_tmpio($sock, $bref); # bref is tmpio
430 } elsif ($! == EAGAIN) {
431 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
432 epwait($sock, $ev | EPOLLONESHOT);
438 } else { #(ref($bref) eq 'CODE') {
440 my $before = scalar(@$wbuf);
443 # bref may be enqueueing more CODE to call (see accept_tls_step)
444 return 0 if (scalar(@$wbuf) > $before);
448 delete $self->{wbuf};
453 my ($self, $rbuf) = @_;
454 if ($$rbuf eq '') { # who knows how long till we can read again
455 delete $self->{rbuf};
457 $self->{rbuf} = $rbuf;
461 sub do_read ($$$;$) {
462 my ($self, $rbuf, $len, $off) = @_;
463 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
464 return ($r == 0 ? $self->close : $r) if defined $r;
465 # common for clients to break connections without warning,
466 # would be too noisy to log here:
468 my $ev = epbit($sock, EPOLLIN) or return $self->close;
469 epwait($sock, $ev | EPOLLONESHOT);
470 rbuf_idle($self, $rbuf);
477 # drop the socket if we hit unrecoverable errors on our system which
478 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
485 # n.b.: use ->write/->read for this buffer to allow compatibility with
486 # PerlIO::mmap or PerlIO::scalar if needed
488 my ($self, $bref, $off) = @_;
489 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
490 return drop($self, "tmpfile $!");
492 my $len = bytes::length($$bref) - $off;
493 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
494 [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
497 =head2 C<< $obj->write( $data ) >>
499 Write the specified data to the underlying handle. I<data> may be scalar,
500 scalar ref, code ref (to run when there).
501 Returns 1 if writes all went through, or 0 if there are writes in queue. If
502 it returns 1, caller should stop waiting for 'writable' events)
506 my ($self, $data) = @_;
508 # nobody should be writing to closed sockets, but caller code can
509 # do two writes within an event, have the first fail and
510 # disconnect the other side (whose destructor then closes the
511 # calling object, but it's still in a method), and then the
512 # now-dead object does its second write. that is this case. we
513 # just lie and say it worked. it'll be dead soon and won't be
515 my $sock = $self->{sock} or return 1;
517 my $bref = $ref ? $data : \$data;
518 my $wbuf = $self->{wbuf};
519 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
520 if ($ref eq 'CODE') {
523 my $tmpio = $wbuf->[-1];
524 if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
525 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
527 my $tmpio = tmpio($self, $bref, 0) or return 0;
532 } elsif ($ref eq 'CODE') {
536 my $to_write = bytes::length($$bref);
537 my $written = syswrite($sock, $$bref, $to_write);
539 if (defined $written) {
540 return 1 if $written == $to_write;
541 requeue($self); # runs: event_step -> flush_write
542 } elsif ($! == EAGAIN) {
543 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
544 epwait($sock, $ev | EPOLLONESHOT);
550 # deal with EAGAIN or partial write:
551 my $tmpio = tmpio($self, $bref, $written) or return 0;
553 # wbuf may be an empty array if we're being called inside
554 # ->flush_write via CODE bref:
555 push @{$self->{wbuf}}, $tmpio; # autovivifies
560 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
564 my $sock = $self->{sock} or return 1;
565 my $wbuf = $self->{wbuf};
567 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
568 !$sock->can('stop_SSL')) {
569 my $n = send($sock, $_[1], MSG_MORE);
571 my $nlen = bytes::length($_[1]) - $n;
572 return 1 if $nlen == 0; # all done!
573 # queue up the unwritten substring:
574 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
575 push @{$self->{wbuf}}, $tmpio; # autovivifies
576 epwait($sock, EPOLLOUT|EPOLLONESHOT);
581 # don't redispatch into NNTPdeflate::write
582 PublicInbox::DS::write($self, \($_[1]));
586 my ($sock, $ev) = @_;
587 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
588 confess("EPOLL_CTL_MOD $!");
591 # return true if complete, false if incomplete (or failure)
592 sub accept_tls_step ($) {
594 my $sock = $self->{sock} or return;
595 return 1 if $sock->accept_SSL;
596 return $self->close if $! != EAGAIN;
597 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
598 epwait($sock, $ev | EPOLLONESHOT);
599 unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
603 # return true if complete, false if incomplete (or failure)
604 sub shutdn_tls_step ($) {
606 my $sock = $self->{sock} or return;
607 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
608 return $self->close if $! != EAGAIN;
609 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
610 epwait($sock, $ev | EPOLLONESHOT);
611 unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
615 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
616 # or fork w/o exec, so no inadvertent socket sharing
619 my $sock = $self->{sock} or return;
620 if ($sock->can('stop_SSL')) {
621 shutdn_tls_step($self);
627 sub dwaitpid ($;$$) {
628 my ($pid, $cb, $arg) = @_;
630 push @$wait_pids, [ $pid, $cb, $arg ];
631 # We could've just missed our SIGCHLD, cover it, here:
634 my $ret = waitpid($pid, 0);
637 eval { $cb->($arg, $pid) };
638 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
641 carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
647 my $run = $later_queue or return;
648 $later_timer = $later_queue = undef;
653 push @$later_queue, $_[0]; # autovivifies @$later_queue
654 $later_timer //= add_timer(60, \&_run_later);
660 my $old = $now - $exp;
662 while (my ($fd, $idle_at) = each %$EXPMAP) {
663 if ($idle_at < $old) {
664 my $ds_obj = $DescriptorMap{$fd};
665 $new{$fd} = $idle_at if !$ds_obj->shutdn;
667 $new{$fd} = $idle_at;
671 $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
674 sub update_idle_time {
676 my $sock = $self->{sock} or return;
677 $EXPMAP->{fileno($sock)} = now();
678 $exp_timer //= later(\&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