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, $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() >>
70 $in_loop = $wait_pids = $later_queue = $reap_armed = undef;
72 $nextq = $ToClose = $later_timer = $exp_timer = undef;
73 $LoopTimeout = -1; # no timeout by default
76 $PostLoopCallback = undef;
78 $_io = undef; # closes real $Epoll FD
79 $Epoll = undef; # may call DSKQXS::DESTROY
82 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
84 Set the loop timeout for the event loop to some value in milliseconds.
86 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
91 return $LoopTimeout = $_[1] + 0;
94 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef, $arg) >>
96 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
97 are not guaranteed to fire at the exact time you ask for.
100 sub add_timer ($$;$) {
101 my ($secs, $coderef, $arg) = @_;
103 my $fire_time = now() + $secs;
105 my $timer = [$fire_time, $coderef, $arg];
107 if (!@Timers || $fire_time >= $Timers[-1][0]) {
108 push @Timers, $timer;
112 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
113 # but it was compared against calendar queues, heaps, naive push/sort,
114 # and a bunch of other versions, and found to be fastest with a large
115 # variety of datasets.)
116 for (my $i = 0; $i < @Timers; $i++) {
117 if ($Timers[$i][0] > $fire_time) {
118 splice(@Timers, $i, 0, $timer);
123 die "Shouldn't get here.";
126 # keeping this around in case we support other FD types for now,
127 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
128 sub set_cloexec ($) {
131 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
132 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
133 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
136 # caller sets return value to $Epoll
139 if (PublicInbox::Syscall::epoll_defined()) {
140 my $fd = epoll_create();
141 set_cloexec($fd) if (defined($fd) && $fd >= 0);
145 for (qw(DSKQXS DSPoll)) {
146 $cls = "PublicInbox::$_";
147 last if eval "require $cls";
149 $cls->import(qw(epoll_ctl epoll_wait));
154 =head2 C<< CLASS->EventLoop() >>
156 Start processing IO events. In most daemon programs this never exits. See
157 C<PostLoopCallback> below for how to exit the loop.
161 sub now () { clock_gettime(CLOCK_MONOTONIC) }
164 my $q = $nextq or return;
167 # we avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
168 # https://rt.perl.org/Public/Bug/Display.html?id=114340
177 # runs timers and returns milliseconds for next one, or next event loop
181 return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
186 while (@Timers && $Timers[0][0] <= $now) {
187 my $to_run = shift(@Timers);
188 $to_run->[1]->($to_run->[2]);
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 return $timeout if $LoopTimeout == -1;
205 # otherwise pick the lower of our regular timeout and time until
207 return $LoopTimeout if $LoopTimeout < $timeout;
211 # We can't use waitpid(-1) safely here since it can hit ``, system(),
212 # and other things. So we scan the $wait_pids list, which is hopefully
213 # not too big. We keep $wait_pids small by not calling dwaitpid()
214 # until we've hit EOF when reading the stdout of the child.
218 my $tmp = $wait_pids or return;
220 foreach my $ary (@$tmp) {
221 my ($pid, $cb, $arg) = @$ary;
222 my $ret = waitpid($pid, WNOHANG);
224 push @$wait_pids, $ary; # autovivifies @$wait_pids
226 eval { $cb->($arg, $pid) };
229 # we may not be done, yet, and could've missed/masked a SIGCHLD:
230 $reap_armed //= requeue(\&reap_pids) if $wait_pids;
233 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
234 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
236 sub in_loop () { $in_loop }
238 # Internal function: run the post-event callback, send read events
239 # for pushed-back data, and close pending connections. returns 1
240 # if event loop should continue, or 0 to shut it all down.
241 sub PostEventLoop () {
242 # now we can close sockets that wanted to close during our event
243 # processing. (we didn't want to close them during the loop, as we
244 # didn't want fd numbers being reused and confused during the event
246 if (my $close_now = $ToClose) {
247 $ToClose = undef; # will be autovivified on push
248 @$close_now = map { fileno($_) } @$close_now;
250 # order matters, destroy expiry times, first:
251 delete @$EXPMAP{@$close_now};
253 # ->DESTROY methods may populate ToClose
254 delete @DescriptorMap{@$close_now};
257 # by default we keep running, unless a postloop callback cancels it
258 $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
262 $Epoll //= _InitPoller();
267 my $timeout = RunTimers();
269 # get up to 1000 events
270 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
271 for ($i=0; $i<$evcount; $i++) {
272 # it's possible epoll_wait returned many events, including some at the end
273 # that ones in the front triggered unregister-interest actions. if we
274 # can't find the %sock entry, it's because we're no longer interested
276 $DescriptorMap{$events[$i]->[0]}->event_step;
278 } while (PostEventLoop());
282 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
284 Sets post loop callback function. Pass a subref and it will be
285 called every time the event loop finishes.
287 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
290 The callback function will be passed two parameters: \%DescriptorMap
293 sub SetPostLoopCallback {
294 my ($class, $ref) = @_;
297 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
300 #####################################################################
301 ### PublicInbox::DS-the-object code
302 #####################################################################
304 =head2 OBJECT METHODS
306 =head2 C<< CLASS->new( $socket ) >>
308 Create a new PublicInbox::DS subclass object for the given I<socket> which will
309 react to events on it during the C<EventLoop>.
311 This is normally (always?) called from your subclass via:
313 $class->SUPER::new($socket);
317 my ($self, $sock, $ev) = @_;
318 $self->{sock} = $sock;
319 my $fd = fileno($sock);
321 $Epoll //= _InitPoller();
323 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
324 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
325 $ev &= ~EPOLLEXCLUSIVE;
328 die "couldn't add epoll watch for $fd: $!\n";
330 confess("DescriptorMap{$fd} defined ($DescriptorMap{$fd})")
331 if defined($DescriptorMap{$fd});
333 $DescriptorMap{$fd} = $self;
337 #####################################################################
338 ### I N S T A N C E M E T H O D S
339 #####################################################################
341 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
343 =head2 C<< $obj->close >>
350 my $sock = delete $self->{sock} or return;
352 # we need to flush our write buffer, as there may
353 # be self-referential closures (sub { $client->close })
354 # preventing the object from being destroyed
355 delete $self->{wbuf};
357 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
358 # notifications about it
359 my $fd = fileno($sock);
360 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
361 confess("EPOLL_CTL_DEL: $!");
363 # we explicitly don't delete from DescriptorMap here until we
364 # actually close the socket, as we might be in the middle of
365 # processing an epoll_wait/etc that returned hundreds of fds, one
366 # of which is not yet processed and is what we're closing. if we
367 # keep it in DescriptorMap, then the event harnesses can just
368 # looked at $pob->{sock} == undef and ignore it. but if it's an
369 # un-accounted for fd, then it (understandably) freak out a bit
370 # and emit warnings, thinking their state got off.
372 # defer closing the actual socket until the event loop is done
373 # processing this round of events. (otherwise we might reuse fds)
374 push @$ToClose, $sock; # autovivifies $ToClose
379 # portable, non-thread-safe sendfile emulation (no pread, yet)
380 sub send_tmpio ($$) {
381 my ($sock, $tmpio) = @_;
383 sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
384 my $n = $tmpio->[2] // 65536;
385 $n = 65536 if $n > 65536;
386 defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
388 while ($to_write > 0) {
389 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
393 return if $written == 0;
397 $tmpio->[1] += $written; # offset
398 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
402 sub epbit ($$) { # (sock, default)
403 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
406 # returns 1 if done, 0 if incomplete
407 sub flush_write ($) {
409 my $sock = $self->{sock} or return;
410 my $wbuf = $self->{wbuf} or return 1;
413 while (my $bref = $wbuf->[0]) {
414 if (ref($bref) ne 'CODE') {
416 my $w = send_tmpio($sock, $bref); # bref is tmpio
422 } elsif ($! == EAGAIN) {
423 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
424 epwait($sock, $ev | EPOLLONESHOT);
430 } else { #(ref($bref) eq 'CODE') {
432 my $before = scalar(@$wbuf);
435 # bref may be enqueueing more CODE to call (see accept_tls_step)
436 return 0 if (scalar(@$wbuf) > $before);
440 delete $self->{wbuf};
445 my ($self, $rbuf) = @_;
446 if ($$rbuf eq '') { # who knows how long till we can read again
447 delete $self->{rbuf};
449 $self->{rbuf} = $rbuf;
453 sub do_read ($$$;$) {
454 my ($self, $rbuf, $len, $off) = @_;
455 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
456 return ($r == 0 ? $self->close : $r) if defined $r;
457 # common for clients to break connections without warning,
458 # would be too noisy to log here:
460 my $ev = epbit($sock, EPOLLIN) or return $self->close;
461 epwait($sock, $ev | EPOLLONESHOT);
462 rbuf_idle($self, $rbuf);
469 # drop the socket if we hit unrecoverable errors on our system which
470 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
477 # n.b.: use ->write/->read for this buffer to allow compatibility with
478 # PerlIO::mmap or PerlIO::scalar if needed
480 my ($self, $bref, $off) = @_;
481 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
482 return drop($self, "tmpfile $!");
484 my $len = bytes::length($$bref) - $off;
485 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
486 [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
489 =head2 C<< $obj->write( $data ) >>
491 Write the specified data to the underlying handle. I<data> may be scalar,
492 scalar ref, code ref (to run when there).
493 Returns 1 if writes all went through, or 0 if there are writes in queue. If
494 it returns 1, caller should stop waiting for 'writable' events)
498 my ($self, $data) = @_;
500 # nobody should be writing to closed sockets, but caller code can
501 # do two writes within an event, have the first fail and
502 # disconnect the other side (whose destructor then closes the
503 # calling object, but it's still in a method), and then the
504 # now-dead object does its second write. that is this case. we
505 # just lie and say it worked. it'll be dead soon and won't be
507 my $sock = $self->{sock} or return 1;
509 my $bref = $ref ? $data : \$data;
510 my $wbuf = $self->{wbuf};
511 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
512 if ($ref eq 'CODE') {
515 my $tmpio = $wbuf->[-1];
516 if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
517 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
519 my $tmpio = tmpio($self, $bref, 0) or return 0;
524 } elsif ($ref eq 'CODE') {
528 my $to_write = bytes::length($$bref);
529 my $written = syswrite($sock, $$bref, $to_write);
531 if (defined $written) {
532 return 1 if $written == $to_write;
533 requeue($self); # runs: event_step -> flush_write
534 } elsif ($! == EAGAIN) {
535 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
536 epwait($sock, $ev | EPOLLONESHOT);
542 # deal with EAGAIN or partial write:
543 my $tmpio = tmpio($self, $bref, $written) or return 0;
545 # wbuf may be an empty array if we're being called inside
546 # ->flush_write via CODE bref:
547 push @{$self->{wbuf}}, $tmpio; # autovivifies
552 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
556 my $sock = $self->{sock} or return 1;
557 my $wbuf = $self->{wbuf};
559 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
560 !$sock->can('stop_SSL')) {
561 my $n = send($sock, $_[1], MSG_MORE);
563 my $nlen = bytes::length($_[1]) - $n;
564 return 1 if $nlen == 0; # all done!
565 # queue up the unwritten substring:
566 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
567 push @{$self->{wbuf}}, $tmpio; # autovivifies
568 epwait($sock, EPOLLOUT|EPOLLONESHOT);
573 # don't redispatch into NNTPdeflate::write
574 PublicInbox::DS::write($self, \($_[1]));
578 my ($sock, $ev) = @_;
579 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
580 confess("EPOLL_CTL_MOD $!");
583 # return true if complete, false if incomplete (or failure)
584 sub accept_tls_step ($) {
586 my $sock = $self->{sock} or return;
587 return 1 if $sock->accept_SSL;
588 return $self->close if $! != EAGAIN;
589 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
590 epwait($sock, $ev | EPOLLONESHOT);
591 unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
595 # return true if complete, false if incomplete (or failure)
596 sub shutdn_tls_step ($) {
598 my $sock = $self->{sock} or return;
599 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
600 return $self->close if $! != EAGAIN;
601 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
602 epwait($sock, $ev | EPOLLONESHOT);
603 unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
607 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
608 # or fork w/o exec, so no inadvertent socket sharing
611 my $sock = $self->{sock} or return;
612 if ($sock->can('stop_SSL')) {
613 shutdn_tls_step($self);
619 # must be called with eval, PublicInbox::DS may not be loaded (see t/qspawn.t)
621 die "Not in EventLoop\n" unless $in_loop;
622 push @$wait_pids, [ @_ ]; # [ $pid, $cb, $arg ]
624 # We could've just missed our SIGCHLD, cover it, here:
629 my $run = $later_queue or return;
630 $later_timer = $later_queue = undef;
635 push @$later_queue, $_[0]; # autovivifies @$later_queue
636 $later_timer //= add_timer(60, \&_run_later);
642 my $old = $now - $exp;
644 while (my ($fd, $idle_at) = each %$EXPMAP) {
645 if ($idle_at < $old) {
646 my $ds_obj = $DescriptorMap{$fd};
647 $new{$fd} = $idle_at if !$ds_obj->shutdn;
649 $new{$fd} = $idle_at;
653 $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
656 sub update_idle_time {
658 my $sock = $self->{sock} or return;
659 $EXPMAP->{fileno($sock)} = now();
660 $exp_timer //= later(\&expire_old);
664 my ($self, $now) = @_;
665 my $sock = $self->{sock} or return;
666 my $idle_at = $EXPMAP->{fileno($sock)} or return;
667 ($idle_at + $EXPTIME) > $now;
672 =head1 AUTHORS (Danga::Socket)
674 Brad Fitzpatrick <brad@danga.com> - author
676 Michael Granger <ged@danga.com> - docs, testing
678 Mark Smith <junior@danga.com> - contributor, heavy user, testing
680 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits