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 (for now) unmaintained Danga::Socket 1.61.
7 # Unused features will be removed, and updates will be made to take
8 # advantage of newer kernels.
10 # API changes to diverge from Danga::Socket will happen to better
11 # accomodate new features and improve scalability. Do not expect
12 # this to be a stable API like Danga::Socket.
13 # Bugs encountered (and likely fixed) are reported to
14 # bug-Danga-Socket@rt.cpan.org 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);
28 use PublicInbox::Syscall qw(:epoll);
29 use PublicInbox::Tmpfile;
31 use fields ('sock', # underlying socket
32 'rbuf', # scalarref, usually undef
33 'wbuf', # arrayref of coderefs or GLOB refs
34 'wbuf_off', # offset into first element of wbuf to start writing at
37 use Errno qw(EAGAIN EINVAL);
38 use Carp qw(croak confess carp);
41 my $nextq = []; # queue for next_tick
42 my $WaitPids = []; # list of [ pid, callback, callback_arg ]
45 %DescriptorMap, # fd (num) -> PublicInbox::DS object
46 $Epoll, # Global epoll fd (or DSKQXS ref)
47 $_io, # IO::Handle for Epoll
48 @ToClose, # sockets to close when event loop is done
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
59 #####################################################################
60 ### C L A S S M E T H O D S
61 #####################################################################
63 =head2 C<< CLASS->Reset() >>
73 $LoopTimeout = -1; # no timeout by default
76 $PostLoopCallback = undef;
79 $_io = undef; # closes real $Epoll FD
80 $Epoll = undef; # may call DSKQXS::DESTROY
82 *EventLoop = *FirstTimeEventLoop;
85 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
87 Set the loop timeout for the event loop to some value in milliseconds.
89 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
94 return $LoopTimeout = $_[1] + 0;
97 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
99 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
100 are not guaranteed to fire at the exact time you ask for.
102 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
106 my ($class, $secs, $coderef) = @_;
108 my $fire_time = now() + $secs;
110 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
112 if (!@Timers || $fire_time >= $Timers[-1][0]) {
113 push @Timers, $timer;
117 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
118 # but it was compared against calendar queues, heaps, naive push/sort,
119 # and a bunch of other versions, and found to be fastest with a large
120 # variety of datasets.)
121 for (my $i = 0; $i < @Timers; $i++) {
122 if ($Timers[$i][0] > $fire_time) {
123 splice(@Timers, $i, 0, $timer);
128 die "Shouldn't get here.";
131 # keeping this around in case we support other FD types for now,
132 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
133 sub set_cloexec ($) {
136 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
137 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
138 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
146 if (PublicInbox::Syscall::epoll_defined()) {
147 $Epoll = epoll_create();
148 set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
151 for (qw(DSKQXS DSPoll)) {
152 $cls = "PublicInbox::$_";
153 last if eval "require $cls";
155 $cls->import(qw(epoll_ctl epoll_wait));
158 *EventLoop = *EpollEventLoop;
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.
167 sub FirstTimeEventLoop {
175 sub now () { clock_gettime(CLOCK_MONOTONIC) }
181 if (ref($_) eq 'CODE') {
189 # runs timers and returns milliseconds for next one, or next event loop
193 return ((@$nextq || @ToClose) ? 0 : $LoopTimeout) unless @Timers;
198 while (@Timers && $Timers[0][0] <= $now) {
199 my $to_run = shift(@Timers);
200 $to_run->[1]->($now) if $to_run->[1];
203 # timers may enqueue into nextq:
204 return 0 if (@$nextq || @ToClose);
206 return $LoopTimeout unless @Timers;
208 # convert time to an even number of milliseconds, adding 1
209 # extra, otherwise floating point fun can occur and we'll
210 # call RunTimers like 20-30 times, each returning a timeout
211 # of 0.0000212 seconds
212 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
214 # -1 is an infinite timeout, so prefer a real timeout
215 return $timeout if $LoopTimeout == -1;
217 # otherwise pick the lower of our regular timeout and time until
219 return $LoopTimeout if $LoopTimeout < $timeout;
223 # We can't use waitpid(-1) safely here since it can hit ``, system(),
224 # and other things. So we scan the $WaitPids list, which is hopefully
230 foreach my $ary (@$tmp) {
231 my ($pid, $cb, $arg) = @$ary;
232 my $ret = waitpid($pid, WNOHANG);
234 push @$WaitPids, $ary;
236 eval { $cb->($arg, $pid) };
240 # we may not be donea, and we may miss our
241 $reap_timer = AddTimer(undef, 1, \&reap_pids);
245 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
246 sub enqueue_reap ($) { push @$nextq, \&reap_pids };
249 local $SIG{CHLD} = \&enqueue_reap;
253 my $timeout = RunTimers();
255 # get up to 1000 events
256 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
257 for ($i=0; $i<$evcount; $i++) {
258 # it's possible epoll_wait returned many events, including some at the end
259 # that ones in the front triggered unregister-interest actions. if we
260 # can't find the %sock entry, it's because we're no longer interested
262 $DescriptorMap{$events[$i]->[0]}->event_step;
264 return unless PostEventLoop();
268 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
270 Sets post loop callback function. Pass a subref and it will be
271 called every time the event loop finishes.
273 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
276 The callback function will be passed two parameters: \%DescriptorMap
279 sub SetPostLoopCallback {
280 my ($class, $ref) = @_;
283 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
286 # Internal function: run the post-event callback, send read events
287 # for pushed-back data, and close pending connections. returns 1
288 # if event loop should continue, or 0 to shut it all down.
290 # now we can close sockets that wanted to close during our event processing.
291 # (we didn't want to close them during the loop, as we didn't want fd numbers
292 # being reused and confused during the event loop)
293 delete($DescriptorMap{fileno($_)}) for @ToClose;
294 @ToClose = (); # let refcounting drop everything all at once
296 # by default we keep running, unless a postloop callback (either per-object
297 # or global) cancels it
298 my $keep_running = 1;
300 # now we're at the very end, call callback if defined
301 if (defined $PostLoopCallback) {
302 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
305 return $keep_running;
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 = fields::new($self) unless ref $self;
328 $self->{sock} = $sock;
329 my $fd = fileno($sock);
331 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
336 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
337 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
338 $ev &= ~EPOLLEXCLUSIVE;
341 die "couldn't add epoll watch for $fd: $!\n";
343 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
344 if $DescriptorMap{$fd};
346 $DescriptorMap{$fd} = $self;
351 #####################################################################
352 ### I N S T A N C E M E T H O D S
353 #####################################################################
355 sub requeue ($) { push @$nextq, $_[0] }
357 =head2 C<< $obj->close >>
364 my $sock = delete $self->{sock} or return;
366 # we need to flush our write buffer, as there may
367 # be self-referential closures (sub { $client->close })
368 # preventing the object from being destroyed
369 delete $self->{wbuf};
371 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
372 # notifications about it
373 my $fd = fileno($sock);
374 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
375 confess("EPOLL_CTL_DEL: $!");
377 # we explicitly don't delete from DescriptorMap here until we
378 # actually close the socket, as we might be in the middle of
379 # processing an epoll_wait/etc that returned hundreds of fds, one
380 # of which is not yet processed and is what we're closing. if we
381 # keep it in DescriptorMap, then the event harnesses can just
382 # looked at $pob->{sock} == undef and ignore it. but if it's an
383 # un-accounted for fd, then it (understandably) freak out a bit
384 # and emit warnings, thinking their state got off.
386 # defer closing the actual socket until the event loop is done
387 # processing this round of events. (otherwise we might reuse fds)
388 push @ToClose, $sock;
393 # portable, non-thread-safe sendfile emulation (no pread, yet)
394 sub psendfile ($$$) {
395 my ($sock, $fh, $off) = @_;
397 seek($fh, $$off, SEEK_SET) or return;
398 defined(my $to_write = read($fh, my $buf, 16384)) or return;
400 while ($to_write > 0) {
401 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
405 return if $written == 0;
413 sub epbit ($$) { # (sock, default)
414 ref($_[0]) eq 'IO::Socket::SSL' ? PublicInbox::TLS::epollbit() : $_[1];
417 # returns 1 if done, 0 if incomplete
418 sub flush_write ($) {
420 my $wbuf = $self->{wbuf} or return 1;
421 my $sock = $self->{sock};
424 while (my $bref = $wbuf->[0]) {
425 if (ref($bref) ne 'CODE') {
426 my $off = delete($self->{wbuf_off}) // 0;
428 my $w = psendfile($sock, $bref, \$off);
434 } elsif ($! == EAGAIN) {
435 epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
436 $self->{wbuf_off} = $off;
442 } else { #($ref eq 'CODE') {
444 my $before = scalar(@$wbuf);
447 # bref may be enqueueing more CODE to call (see accept_tls_step)
448 return 0 if (scalar(@$wbuf) > $before);
452 delete $self->{wbuf};
457 my ($self, $rbuf) = @_;
458 if ($$rbuf eq '') { # who knows how long till we can read again
459 delete $self->{rbuf};
461 $self->{rbuf} = $rbuf;
465 sub do_read ($$$;$) {
466 my ($self, $rbuf, $len, $off) = @_;
467 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
468 return ($r == 0 ? $self->close : $r) if defined $r;
469 # common for clients to break connections without warning,
470 # would be too noisy to log here:
472 epwait($sock, epbit($sock, EPOLLIN) | EPOLLONESHOT);
473 rbuf_idle($self, $rbuf);
480 # drop the socket if we hit unrecoverable errors on our system which
481 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
488 # n.b.: use ->write/->read for this buffer to allow compatibility with
489 # PerlIO::mmap or PerlIO::scalar if needed
491 my ($self, $bref, $off) = @_;
492 my $fh = tmpfile('wbuf', $self->{sock}, 1) or
493 return drop($self, "tmpfile $!");
495 my $len = bytes::length($$bref) - $off;
496 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
500 =head2 C<< $obj->write( $data ) >>
502 Write the specified data to the underlying handle. I<data> may be scalar,
503 scalar ref, code ref (to run when there).
504 Returns 1 if writes all went through, or 0 if there are writes in queue. If
505 it returns 1, caller should stop waiting for 'writable' events)
509 my ($self, $data) = @_;
511 # nobody should be writing to closed sockets, but caller code can
512 # do two writes within an event, have the first fail and
513 # disconnect the other side (whose destructor then closes the
514 # calling object, but it's still in a method), and then the
515 # now-dead object does its second write. that is this case. we
516 # just lie and say it worked. it'll be dead soon and won't be
518 my $sock = $self->{sock} or return 1;
520 my $bref = $ref ? $data : \$data;
521 my $wbuf = $self->{wbuf};
522 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
523 if ($ref eq 'CODE') {
526 my $last = $wbuf->[-1];
527 if (ref($last) eq 'GLOB') { # append to tmp file buffer
528 $last->print($$bref) or return drop($self, "print: $!");
530 my $tmpio = tmpio($self, $bref, 0) or return 0;
535 } elsif ($ref eq 'CODE') {
539 my $to_write = bytes::length($$bref);
540 my $written = syswrite($sock, $$bref, $to_write);
542 if (defined $written) {
543 return 1 if $written == $to_write;
544 requeue($self); # runs: event_step -> flush_write
545 } elsif ($! == EAGAIN) {
546 epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
552 # deal with EAGAIN or partial write:
553 my $tmpio = tmpio($self, $bref, $written) or return 0;
555 # wbuf may be an empty array if we're being called inside
556 # ->flush_write via CODE bref:
557 push @{$self->{wbuf} ||= []}, $tmpio;
562 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
566 my $sock = $self->{sock} or return 1;
568 if (MSG_MORE && !$self->{wbuf} && ref($sock) ne 'IO::Socket::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 $self->{wbuf} = [ $tmpio ];
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 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
598 unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
602 # return true if complete, false if incomplete (or failure)
603 sub shutdn_tls_step ($) {
605 my $sock = $self->{sock} or return;
606 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
607 return $self->close if $! != EAGAIN;
608 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
609 unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
613 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
614 # or fork w/o exec, so no inadvertant socket sharing
617 my $sock = $self->{sock} or return;
618 if (ref($sock) eq 'IO::Socket::SSL') {
619 shutdn_tls_step($self);
625 # must be called with eval, PublicInbox::DS may not be loaded (see t/qspawn.t)
627 my ($pid, $cb, $arg) = @_;
628 my $chld = $SIG{CHLD};
629 if (defined($chld) && $chld eq \&enqueue_reap) {
630 push @$WaitPids, [ $pid, $cb, $arg ];
632 # We could've just missed our SIGCHLD, cover it, here:
633 requeue(\&reap_pids);
635 die "Not in EventLoop\n";
639 package PublicInbox::DS::Timer;
640 # [$abs_float_firetime, $coderef];
647 =head1 AUTHORS (Danga::Socket)
649 Brad Fitzpatrick <brad@danga.com> - author
651 Michael Granger <ged@danga.com> - docs, testing
653 Mark Smith <junior@danga.com> - contributor, heavy user, testing
655 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits