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
16 package PublicInbox::DS;
19 use POSIX qw(WNOHANG);
21 use Fcntl qw(SEEK_SET :DEFAULT);
22 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
23 use parent qw(Exporter);
24 our @EXPORT_OK = qw(now msg_more);
27 use Scalar::Util qw(blessed);
29 use PublicInbox::Syscall qw(:epoll);
30 use PublicInbox::Tmpfile;
32 use fields ('sock', # underlying socket
33 'rbuf', # scalarref, usually undef
34 'wbuf', # arrayref of coderefs or GLOB refs
35 'wbuf_off', # offset into first element of wbuf to start writing at
38 use Errno qw(EAGAIN EINVAL);
39 use Carp qw(confess carp);
41 my $nextq; # queue for next_tick
42 my $WaitPids; # list of [ pid, callback, callback_arg ]
43 my $later_queue; # callbacks
44 my $EXPMAP; # fd -> [ idle_time, $self ]
45 our $EXPTIME = 180; # 3 minutes
46 my ($later_timer, $reap_timer, $exp_timer);
48 %DescriptorMap, # fd (num) -> PublicInbox::DS object
49 $Epoll, # Global epoll fd (or DSKQXS ref)
50 $_io, # IO::Handle for Epoll
51 @ToClose, # sockets to close when event loop is done
53 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
55 $LoopTimeout, # timeout of event loop in milliseconds
56 $DoneInit, # if we've done the one-time module init yet
63 #####################################################################
64 ### C L A S S M E T H O D S
65 #####################################################################
67 =head2 C<< CLASS->Reset() >>
78 $reap_timer = $later_timer = $exp_timer = undef;
80 $LoopTimeout = -1; # no timeout by default
83 $PostLoopCallback = undef;
86 $_io = undef; # closes real $Epoll FD
87 $Epoll = undef; # may call DSKQXS::DESTROY
89 *EventLoop = *FirstTimeEventLoop;
92 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
94 Set the loop timeout for the event loop to some value in milliseconds.
96 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
101 return $LoopTimeout = $_[1] + 0;
104 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef ) >>
106 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
107 are not guaranteed to fire at the exact time you ask for.
109 Returns a timer object which you can call C<< $timer->cancel >> on if you need
114 my ($secs, $coderef) = @_;
116 my $fire_time = now() + $secs;
118 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
120 if (!@Timers || $fire_time >= $Timers[-1][0]) {
121 push @Timers, $timer;
125 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
126 # but it was compared against calendar queues, heaps, naive push/sort,
127 # and a bunch of other versions, and found to be fastest with a large
128 # variety of datasets.)
129 for (my $i = 0; $i < @Timers; $i++) {
130 if ($Timers[$i][0] > $fire_time) {
131 splice(@Timers, $i, 0, $timer);
136 die "Shouldn't get here.";
139 # keeping this around in case we support other FD types for now,
140 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
141 sub set_cloexec ($) {
144 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
145 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
146 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
154 if (PublicInbox::Syscall::epoll_defined()) {
155 $Epoll = epoll_create();
156 set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
159 for (qw(DSKQXS DSPoll)) {
160 $cls = "PublicInbox::$_";
161 last if eval "require $cls";
163 $cls->import(qw(epoll_ctl epoll_wait));
166 *EventLoop = *EpollEventLoop;
169 =head2 C<< CLASS->EventLoop() >>
171 Start processing IO events. In most daemon programs this never exits. See
172 C<PostLoopCallback> below for how to exit the loop.
175 sub FirstTimeEventLoop {
183 sub now () { clock_gettime(CLOCK_MONOTONIC) }
189 # we avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
190 # https://rt.perl.org/Public/Bug/Display.html?id=114340
199 # runs timers and returns milliseconds for next one, or next event loop
203 return ((@$nextq || @ToClose) ? 0 : $LoopTimeout) unless @Timers;
208 while (@Timers && $Timers[0][0] <= $now) {
209 my $to_run = shift(@Timers);
210 $to_run->[1]->($now) if $to_run->[1];
213 # timers may enqueue into nextq:
214 return 0 if (@$nextq || @ToClose);
216 return $LoopTimeout unless @Timers;
218 # convert time to an even number of milliseconds, adding 1
219 # extra, otherwise floating point fun can occur and we'll
220 # call RunTimers like 20-30 times, each returning a timeout
221 # of 0.0000212 seconds
222 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
224 # -1 is an infinite timeout, so prefer a real timeout
225 return $timeout if $LoopTimeout == -1;
227 # otherwise pick the lower of our regular timeout and time until
229 return $LoopTimeout if $LoopTimeout < $timeout;
233 # We can't use waitpid(-1) safely here since it can hit ``, system(),
234 # and other things. So we scan the $WaitPids list, which is hopefully
240 foreach my $ary (@$tmp) {
241 my ($pid, $cb, $arg) = @$ary;
242 my $ret = waitpid($pid, WNOHANG);
244 push @$WaitPids, $ary;
246 eval { $cb->($arg, $pid) };
250 # we may not be donea, and we may miss our
251 $reap_timer = add_timer(1, \&reap_pids);
255 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
256 sub enqueue_reap ($) { push @$nextq, \&reap_pids };
263 my $timeout = RunTimers();
265 # get up to 1000 events
266 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
267 for ($i=0; $i<$evcount; $i++) {
268 # it's possible epoll_wait returned many events, including some at the end
269 # that ones in the front triggered unregister-interest actions. if we
270 # can't find the %sock entry, it's because we're no longer interested
272 $DescriptorMap{$events[$i]->[0]}->event_step;
274 } while (PostEventLoop());
278 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
280 Sets post loop callback function. Pass a subref and it will be
281 called every time the event loop finishes.
283 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
286 The callback function will be passed two parameters: \%DescriptorMap
289 sub SetPostLoopCallback {
290 my ($class, $ref) = @_;
293 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
296 # Internal function: run the post-event callback, send read events
297 # for pushed-back data, and close pending connections. returns 1
298 # if event loop should continue, or 0 to shut it all down.
300 # now we can close sockets that wanted to close during our event processing.
301 # (we didn't want to close them during the loop, as we didn't want fd numbers
302 # being reused and confused during the event loop)
303 delete($DescriptorMap{fileno($_)}) for @ToClose;
304 @ToClose = (); # let refcounting drop everything all at once
306 # by default we keep running, unless a postloop callback (either per-object
307 # or global) cancels it
308 my $keep_running = 1;
310 # now we're at the very end, call callback if defined
311 if (defined $PostLoopCallback) {
312 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
315 return $keep_running;
318 #####################################################################
319 ### PublicInbox::DS-the-object code
320 #####################################################################
322 =head2 OBJECT METHODS
324 =head2 C<< CLASS->new( $socket ) >>
326 Create a new PublicInbox::DS subclass object for the given I<socket> which will
327 react to events on it during the C<EventLoop>.
329 This is normally (always?) called from your subclass via:
331 $class->SUPER::new($socket);
335 my ($self, $sock, $ev) = @_;
336 $self = fields::new($self) unless ref $self;
338 $self->{sock} = $sock;
339 my $fd = fileno($sock);
343 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
344 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
345 $ev &= ~EPOLLEXCLUSIVE;
348 die "couldn't add epoll watch for $fd: $!\n";
350 confess("DescriptorMap{$fd} defined ($DescriptorMap{$fd})")
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] }
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 confess("EPOLL_CTL_DEL: $!");
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;
399 # portable, non-thread-safe sendfile emulation (no pread, yet)
400 sub psendfile ($$$) {
401 my ($sock, $fh, $off) = @_;
403 seek($fh, $$off, SEEK_SET) or return;
404 defined(my $to_write = read($fh, my $buf, 16384)) or return;
406 while ($to_write > 0) {
407 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
411 return if $written == 0;
419 sub epbit ($$) { # (sock, default)
420 ref($_[0]) eq 'IO::Socket::SSL' ? PublicInbox::TLS::epollbit() : $_[1];
423 # returns 1 if done, 0 if incomplete
424 sub flush_write ($) {
426 my $wbuf = $self->{wbuf} or return 1;
427 my $sock = $self->{sock};
430 while (my $bref = $wbuf->[0]) {
431 if (ref($bref) ne 'CODE') {
432 my $off = delete($self->{wbuf_off}) // 0;
434 my $w = psendfile($sock, $bref, \$off);
440 } elsif ($! == EAGAIN) {
441 epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
442 $self->{wbuf_off} = $off;
448 } else { #($ref 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}, 1) 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): $!");
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 $last = $wbuf->[-1];
533 if (ref($last) eq 'GLOB') { # append to tmp file buffer
534 $last->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;
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 ref($sock) ne 'IO::Socket::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 $self->{wbuf} //= $wbuf //= [];
585 epwait($sock, EPOLLOUT|EPOLLONESHOT);
590 # don't redispatch into NNTPdeflate::write
591 PublicInbox::DS::write($self, \($_[1]));
595 my ($sock, $ev) = @_;
596 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
597 confess("EPOLL_CTL_MOD $!");
600 # return true if complete, false if incomplete (or failure)
601 sub accept_tls_step ($) {
603 my $sock = $self->{sock} or return;
604 return 1 if $sock->accept_SSL;
605 return $self->close if $! != EAGAIN;
606 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
607 unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
611 # return true if complete, false if incomplete (or failure)
612 sub shutdn_tls_step ($) {
614 my $sock = $self->{sock} or return;
615 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
616 return $self->close if $! != EAGAIN;
617 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
618 unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
622 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
623 # or fork w/o exec, so no inadvertant socket sharing
626 my $sock = $self->{sock} or return;
627 if (ref($sock) eq 'IO::Socket::SSL') {
628 shutdn_tls_step($self);
634 # must be called with eval, PublicInbox::DS may not be loaded (see t/qspawn.t)
636 my ($pid, $cb, $arg) = @_;
638 push @$WaitPids, [ $pid, $cb, $arg ];
640 # We could've just missed our SIGCHLD, cover it, here:
641 requeue(\&reap_pids);
643 die "Not in EventLoop\n";
648 my $run = $later_queue;
649 $later_timer = undef;
656 push @$later_queue, $cb;
657 $later_timer //= add_timer(60, \&_run_later);
663 my $old = $now - $exp;
665 while (my ($fd, $v) = each %$EXPMAP) {
666 my ($idle_time, $ds_obj) = @$v;
667 if ($idle_time < $old) {
668 if (!$ds_obj->shutdn) {
676 $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
679 sub update_idle_time {
681 my $sock = $self->{sock} or return;
682 $EXPMAP->{fileno($sock)} = [ now(), $self ];
683 $exp_timer //= later(\&expire_old);
687 my ($self, $now) = @_;
688 my $sock = $self->{sock} or return;
689 my $ary = $EXPMAP->{fileno($sock)} or return;
690 my $exp_at = $ary->[0] + $EXPTIME;
694 package PublicInbox::DS::Timer;
695 # [$abs_float_firetime, $coderef];
702 =head1 AUTHORS (Danga::Socket)
704 Brad Fitzpatrick <brad@danga.com> - author
706 Michael Granger <ged@danga.com> - docs, testing
708 Mark Smith <junior@danga.com> - contributor, heavy user, testing
710 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits