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);
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(croak confess carp);
42 my $nextq = []; # queue for next_tick
43 my $WaitPids = []; # list of [ pid, callback, callback_arg ]
46 %DescriptorMap, # fd (num) -> PublicInbox::DS object
47 $Epoll, # Global epoll fd (or DSKQXS ref)
48 $_io, # IO::Handle for Epoll
49 @ToClose, # sockets to close when event loop is done
51 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
53 $LoopTimeout, # timeout of event loop in milliseconds
54 $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() >>
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<< CLASS->AddTimer( $seconds, $coderef ) >>
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.
103 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
107 my ($class, $secs, $coderef) = @_;
109 my $fire_time = now() + $secs;
111 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
113 if (!@Timers || $fire_time >= $Timers[-1][0]) {
114 push @Timers, $timer;
118 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
119 # but it was compared against calendar queues, heaps, naive push/sort,
120 # and a bunch of other versions, and found to be fastest with a large
121 # variety of datasets.)
122 for (my $i = 0; $i < @Timers; $i++) {
123 if ($Timers[$i][0] > $fire_time) {
124 splice(@Timers, $i, 0, $timer);
129 die "Shouldn't get here.";
132 # keeping this around in case we support other FD types for now,
133 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
134 sub set_cloexec ($) {
137 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
138 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
139 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
147 if (PublicInbox::Syscall::epoll_defined()) {
148 $Epoll = epoll_create();
149 set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
152 for (qw(DSKQXS DSPoll)) {
153 $cls = "PublicInbox::$_";
154 last if eval "require $cls";
156 $cls->import(qw(epoll_ctl epoll_wait));
159 *EventLoop = *EpollEventLoop;
162 =head2 C<< CLASS->EventLoop() >>
164 Start processing IO events. In most daemon programs this never exits. See
165 C<PostLoopCallback> below for how to exit the loop.
168 sub FirstTimeEventLoop {
176 sub now () { clock_gettime(CLOCK_MONOTONIC) }
182 # we avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
183 # https://rt.perl.org/Public/Bug/Display.html?id=114340
192 # runs timers and returns milliseconds for next one, or next event loop
196 return ((@$nextq || @ToClose) ? 0 : $LoopTimeout) unless @Timers;
201 while (@Timers && $Timers[0][0] <= $now) {
202 my $to_run = shift(@Timers);
203 $to_run->[1]->($now) if $to_run->[1];
206 # timers may enqueue into nextq:
207 return 0 if (@$nextq || @ToClose);
209 return $LoopTimeout unless @Timers;
211 # convert time to an even number of milliseconds, adding 1
212 # extra, otherwise floating point fun can occur and we'll
213 # call RunTimers like 20-30 times, each returning a timeout
214 # of 0.0000212 seconds
215 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
217 # -1 is an infinite timeout, so prefer a real timeout
218 return $timeout if $LoopTimeout == -1;
220 # otherwise pick the lower of our regular timeout and time until
222 return $LoopTimeout if $LoopTimeout < $timeout;
226 # We can't use waitpid(-1) safely here since it can hit ``, system(),
227 # and other things. So we scan the $WaitPids list, which is hopefully
233 foreach my $ary (@$tmp) {
234 my ($pid, $cb, $arg) = @$ary;
235 my $ret = waitpid($pid, WNOHANG);
237 push @$WaitPids, $ary;
239 eval { $cb->($arg, $pid) };
243 # we may not be donea, and we may miss our
244 $reap_timer = AddTimer(undef, 1, \&reap_pids);
248 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
249 sub enqueue_reap ($) { push @$nextq, \&reap_pids };
252 local $SIG{CHLD} = \&enqueue_reap;
256 my $timeout = RunTimers();
258 # get up to 1000 events
259 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
260 for ($i=0; $i<$evcount; $i++) {
261 # it's possible epoll_wait returned many events, including some at the end
262 # that ones in the front triggered unregister-interest actions. if we
263 # can't find the %sock entry, it's because we're no longer interested
265 $DescriptorMap{$events[$i]->[0]}->event_step;
267 return unless PostEventLoop();
271 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
273 Sets post loop callback function. Pass a subref and it will be
274 called every time the event loop finishes.
276 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
279 The callback function will be passed two parameters: \%DescriptorMap
282 sub SetPostLoopCallback {
283 my ($class, $ref) = @_;
286 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
289 # Internal function: run the post-event callback, send read events
290 # for pushed-back data, and close pending connections. returns 1
291 # if event loop should continue, or 0 to shut it all down.
293 # now we can close sockets that wanted to close during our event processing.
294 # (we didn't want to close them during the loop, as we didn't want fd numbers
295 # being reused and confused during the event loop)
296 delete($DescriptorMap{fileno($_)}) for @ToClose;
297 @ToClose = (); # let refcounting drop everything all at once
299 # by default we keep running, unless a postloop callback (either per-object
300 # or global) cancels it
301 my $keep_running = 1;
303 # now we're at the very end, call callback if defined
304 if (defined $PostLoopCallback) {
305 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
308 return $keep_running;
311 #####################################################################
312 ### PublicInbox::DS-the-object code
313 #####################################################################
315 =head2 OBJECT METHODS
317 =head2 C<< CLASS->new( $socket ) >>
319 Create a new PublicInbox::DS subclass object for the given I<socket> which will
320 react to events on it during the C<EventLoop>.
322 This is normally (always?) called from your subclass via:
324 $class->SUPER::new($socket);
328 my ($self, $sock, $ev) = @_;
329 $self = fields::new($self) unless ref $self;
331 $self->{sock} = $sock;
332 my $fd = fileno($sock);
334 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
339 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
340 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
341 $ev &= ~EPOLLEXCLUSIVE;
344 die "couldn't add epoll watch for $fd: $!\n";
346 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
347 if $DescriptorMap{$fd};
349 $DescriptorMap{$fd} = $self;
354 #####################################################################
355 ### I N S T A N C E M E T H O D S
356 #####################################################################
358 sub requeue ($) { push @$nextq, $_[0] }
360 =head2 C<< $obj->close >>
367 my $sock = delete $self->{sock} or return;
369 # we need to flush our write buffer, as there may
370 # be self-referential closures (sub { $client->close })
371 # preventing the object from being destroyed
372 delete $self->{wbuf};
374 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
375 # notifications about it
376 my $fd = fileno($sock);
377 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
378 confess("EPOLL_CTL_DEL: $!");
380 # we explicitly don't delete from DescriptorMap here until we
381 # actually close the socket, as we might be in the middle of
382 # processing an epoll_wait/etc that returned hundreds of fds, one
383 # of which is not yet processed and is what we're closing. if we
384 # keep it in DescriptorMap, then the event harnesses can just
385 # looked at $pob->{sock} == undef and ignore it. but if it's an
386 # un-accounted for fd, then it (understandably) freak out a bit
387 # and emit warnings, thinking their state got off.
389 # defer closing the actual socket until the event loop is done
390 # processing this round of events. (otherwise we might reuse fds)
391 push @ToClose, $sock;
396 # portable, non-thread-safe sendfile emulation (no pread, yet)
397 sub psendfile ($$$) {
398 my ($sock, $fh, $off) = @_;
400 seek($fh, $$off, SEEK_SET) or return;
401 defined(my $to_write = read($fh, my $buf, 16384)) or return;
403 while ($to_write > 0) {
404 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
408 return if $written == 0;
416 sub epbit ($$) { # (sock, default)
417 ref($_[0]) eq 'IO::Socket::SSL' ? PublicInbox::TLS::epollbit() : $_[1];
420 # returns 1 if done, 0 if incomplete
421 sub flush_write ($) {
423 my $wbuf = $self->{wbuf} or return 1;
424 my $sock = $self->{sock};
427 while (my $bref = $wbuf->[0]) {
428 if (ref($bref) ne 'CODE') {
429 my $off = delete($self->{wbuf_off}) // 0;
431 my $w = psendfile($sock, $bref, \$off);
437 } elsif ($! == EAGAIN) {
438 epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
439 $self->{wbuf_off} = $off;
445 } else { #($ref eq 'CODE') {
447 my $before = scalar(@$wbuf);
450 # bref may be enqueueing more CODE to call (see accept_tls_step)
451 return 0 if (scalar(@$wbuf) > $before);
455 delete $self->{wbuf};
460 my ($self, $rbuf) = @_;
461 if ($$rbuf eq '') { # who knows how long till we can read again
462 delete $self->{rbuf};
464 $self->{rbuf} = $rbuf;
468 sub do_read ($$$;$) {
469 my ($self, $rbuf, $len, $off) = @_;
470 my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
471 return ($r == 0 ? $self->close : $r) if defined $r;
472 # common for clients to break connections without warning,
473 # would be too noisy to log here:
475 epwait($sock, epbit($sock, EPOLLIN) | EPOLLONESHOT);
476 rbuf_idle($self, $rbuf);
483 # drop the socket if we hit unrecoverable errors on our system which
484 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
491 # n.b.: use ->write/->read for this buffer to allow compatibility with
492 # PerlIO::mmap or PerlIO::scalar if needed
494 my ($self, $bref, $off) = @_;
495 my $fh = tmpfile('wbuf', $self->{sock}, 1) or
496 return drop($self, "tmpfile $!");
498 my $len = bytes::length($$bref) - $off;
499 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
503 =head2 C<< $obj->write( $data ) >>
505 Write the specified data to the underlying handle. I<data> may be scalar,
506 scalar ref, code ref (to run when there).
507 Returns 1 if writes all went through, or 0 if there are writes in queue. If
508 it returns 1, caller should stop waiting for 'writable' events)
512 my ($self, $data) = @_;
514 # nobody should be writing to closed sockets, but caller code can
515 # do two writes within an event, have the first fail and
516 # disconnect the other side (whose destructor then closes the
517 # calling object, but it's still in a method), and then the
518 # now-dead object does its second write. that is this case. we
519 # just lie and say it worked. it'll be dead soon and won't be
521 my $sock = $self->{sock} or return 1;
523 my $bref = $ref ? $data : \$data;
524 my $wbuf = $self->{wbuf};
525 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
526 if ($ref eq 'CODE') {
529 my $last = $wbuf->[-1];
530 if (ref($last) eq 'GLOB') { # append to tmp file buffer
531 $last->print($$bref) or return drop($self, "print: $!");
533 my $tmpio = tmpio($self, $bref, 0) or return 0;
538 } elsif ($ref eq 'CODE') {
542 my $to_write = bytes::length($$bref);
543 my $written = syswrite($sock, $$bref, $to_write);
545 if (defined $written) {
546 return 1 if $written == $to_write;
547 requeue($self); # runs: event_step -> flush_write
548 } elsif ($! == EAGAIN) {
549 epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
555 # deal with EAGAIN or partial write:
556 my $tmpio = tmpio($self, $bref, $written) or return 0;
558 # wbuf may be an empty array if we're being called inside
559 # ->flush_write via CODE bref:
560 push @{$self->{wbuf} ||= []}, $tmpio;
565 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
569 my $sock = $self->{sock} or return 1;
571 if (MSG_MORE && !$self->{wbuf} && ref($sock) ne 'IO::Socket::SSL') {
572 my $n = send($sock, $_[1], MSG_MORE);
574 my $nlen = bytes::length($_[1]) - $n;
575 return 1 if $nlen == 0; # all done!
576 # queue up the unwritten substring:
577 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
578 $self->{wbuf} = [ $tmpio ];
579 epwait($sock, EPOLLOUT|EPOLLONESHOT);
584 # don't redispatch into NNTPdeflate::write
585 PublicInbox::DS::write($self, \($_[1]));
589 my ($sock, $ev) = @_;
590 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
591 confess("EPOLL_CTL_MOD $!");
594 # return true if complete, false if incomplete (or failure)
595 sub accept_tls_step ($) {
597 my $sock = $self->{sock} or return;
598 return 1 if $sock->accept_SSL;
599 return $self->close if $! != EAGAIN;
600 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
601 unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
605 # return true if complete, false if incomplete (or failure)
606 sub shutdn_tls_step ($) {
608 my $sock = $self->{sock} or return;
609 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
610 return $self->close if $! != EAGAIN;
611 epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
612 unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
616 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
617 # or fork w/o exec, so no inadvertant socket sharing
620 my $sock = $self->{sock} or return;
621 if (ref($sock) eq 'IO::Socket::SSL') {
622 shutdn_tls_step($self);
628 # must be called with eval, PublicInbox::DS may not be loaded (see t/qspawn.t)
630 my ($pid, $cb, $arg) = @_;
631 my $chld = $SIG{CHLD};
632 if (defined($chld) && $chld eq \&enqueue_reap) {
633 push @$WaitPids, [ $pid, $cb, $arg ];
635 # We could've just missed our SIGCHLD, cover it, here:
636 requeue(\&reap_pids);
638 die "Not in EventLoop\n";
642 package PublicInbox::DS::Timer;
643 # [$abs_float_firetime, $coderef];
650 =head1 AUTHORS (Danga::Socket)
652 Brad Fitzpatrick <brad@danga.com> - author
654 Michael Granger <ged@danga.com> - docs, testing
656 Mark Smith <junior@danga.com> - contributor, heavy user, testing
658 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits