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;
22 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
26 use PublicInbox::Syscall qw(:epoll);
28 use fields ('sock', # underlying socket
29 'fd', # numeric file descriptor
30 'wbuf', # arrayref of scalars, scalarrefs, or coderefs to write
31 'wbuf_off', # offset into first element of wbuf to start writing at
32 'closed', # bool: socket is closed
33 'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
36 use Errno qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
37 EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
38 use Carp qw(croak confess);
40 use constant DebugLevel => 0;
42 use constant POLLIN => 1;
43 use constant POLLOUT => 4;
44 use constant POLLERR => 8;
45 use constant POLLHUP => 16;
46 use constant POLLNVAL => 32;
48 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
51 $HaveEpoll, # Flag -- is epoll available? initially undefined.
53 %DescriptorMap, # fd (num) -> PublicInbox::DS object
54 $Epoll, # Global epoll fd (for epoll mode only)
55 $KQueue, # Global kqueue fd ref (for kqueue mode only)
56 $_io, # IO::Handle for Epoll
57 @ToClose, # sockets to close when event loop is done
59 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
61 $LoopTimeout, # timeout of event loop in milliseconds
62 $DoneInit, # if we've done the one-time module init yet
66 # this may be set to zero with old kernels
67 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
70 #####################################################################
71 ### C L A S S M E T H O D S
72 #####################################################################
74 =head2 C<< CLASS->Reset() >>
82 $LoopTimeout = -1; # no timeout by default
85 $PostLoopCallback = undef;
88 # NOTE kqueue is close-on-fork, and we don't account for it, yet
89 # OTOH, we (public-inbox) don't need this sub outside of tests...
90 POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
93 $_io = undef; # close $Epoll
96 *EventLoop = *FirstTimeEventLoop;
99 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
101 Set the loop timeout for the event loop to some value in milliseconds.
103 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
108 return $LoopTimeout = $_[1] + 0;
111 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
113 Print the debugging message specified by the C<sprintf>-style I<format> and
118 my ( $class, $fmt, @args ) = @_;
120 printf STDERR ">>> $fmt\n", @args;
123 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
125 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
126 are not guaranteed to fire at the exact time you ask for.
128 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
133 my ($secs, $coderef) = @_;
135 my $fire_time = Time::HiRes::time() + $secs;
137 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
139 if (!@Timers || $fire_time >= $Timers[-1][0]) {
140 push @Timers, $timer;
144 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
145 # but it was compared against calendar queues, heaps, naive push/sort,
146 # and a bunch of other versions, and found to be fastest with a large
147 # variety of datasets.)
148 for (my $i = 0; $i < @Timers; $i++) {
149 if ($Timers[$i][0] > $fire_time) {
150 splice(@Timers, $i, 0, $timer);
155 die "Shouldn't get here.";
158 # keeping this around in case we support other FD types for now,
159 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
160 sub set_cloexec ($) {
163 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
164 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
165 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
174 $KQueue = IO::KQueue->new();
175 $HaveKQueue = defined $KQueue;
177 *EventLoop = *KQueueEventLoop;
180 elsif (PublicInbox::Syscall::epoll_defined()) {
181 $Epoll = eval { epoll_create(1024); };
182 $HaveEpoll = defined $Epoll && $Epoll >= 0;
185 *EventLoop = *EpollEventLoop;
189 if (!$HaveEpoll && !$HaveKQueue) {
191 *EventLoop = *PollEventLoop;
195 =head2 C<< CLASS->EventLoop() >>
197 Start processing IO events. In most daemon programs this never exits. See
198 C<PostLoopCallback> below for how to exit the loop.
201 sub FirstTimeEventLoop {
207 EpollEventLoop($class);
208 } elsif ($HaveKQueue) {
209 KQueueEventLoop($class);
211 PollEventLoop($class);
215 # runs timers and returns milliseconds for next one, or next event loop
217 return $LoopTimeout unless @Timers;
219 my $now = Time::HiRes::time();
222 while (@Timers && $Timers[0][0] <= $now) {
223 my $to_run = shift(@Timers);
224 $to_run->[1]->($now) if $to_run->[1];
227 return $LoopTimeout unless @Timers;
229 # convert time to an even number of milliseconds, adding 1
230 # extra, otherwise floating point fun can occur and we'll
231 # call RunTimers like 20-30 times, each returning a timeout
232 # of 0.0000212 seconds
233 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
235 # -1 is an infinite timeout, so prefer a real timeout
236 return $timeout if $LoopTimeout == -1;
238 # otherwise pick the lower of our regular timeout and time until
240 return $LoopTimeout if $LoopTimeout < $timeout;
244 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
252 my $timeout = RunTimers();
254 # get up to 1000 events
255 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
256 for ($i=0; $i<$evcount; $i++) {
257 my $ev = $events[$i];
259 # it's possible epoll_wait returned many events, including some at the end
260 # that ones in the front triggered unregister-interest actions. if we
261 # can't find the %sock entry, it's because we're no longer interested
263 my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
265 my $state = $ev->[1];
267 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
268 $ev->[0], ref($pob), $ev->[1], time);
270 # standard non-profiling codepat
271 $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
272 $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
273 if ($state & (EPOLLERR|EPOLLHUP)) {
274 $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
275 $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
278 return unless PostEventLoop();
283 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
284 ### IO::Epoll fails to load.
288 my PublicInbox::DS $pob;
291 my $timeout = RunTimers();
293 # the following sets up @poll as a series of ($poll,$event_mask)
294 # items, then uses IO::Poll::_poll, implemented in XS, which
295 # modifies the array in place with the even elements being
296 # replaced with the event masks that occured.
298 while ( my ($fd, $sock) = each %DescriptorMap ) {
299 push @poll, $fd, $sock->{event_watch};
302 # if nothing to poll, either end immediately (if no timeout)
303 # or just keep calling the callback
305 select undef, undef, undef, ($timeout / 1000);
306 return unless PostEventLoop();
310 my $count = IO::Poll::_poll($timeout, @poll);
311 unless ($count >= 0) {
312 return unless PostEventLoop();
316 # Fetch handles with read events
318 my ($fd, $state) = splice(@poll, 0, 2);
321 $pob = $DescriptorMap{$fd};
323 $pob->event_read if $state & POLLIN && ! $pob->{closed};
324 $pob->event_write if $state & POLLOUT && ! $pob->{closed};
325 $pob->event_err if $state & POLLERR && ! $pob->{closed};
326 $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
329 return unless PostEventLoop();
335 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
337 sub KQueueEventLoop {
341 my $timeout = RunTimers();
342 my @ret = eval { $KQueue->kevent($timeout) };
344 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
345 if ($err =~ /Interrupted system call/) {
352 foreach my $kev (@ret) {
353 my ($fd, $filter, $flags, $fflags) = @$kev;
354 my PublicInbox::DS $pob = $DescriptorMap{$fd};
356 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
357 $fd, ref($pob), $flags, time);
359 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
360 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
361 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
369 return unless PostEventLoop();
375 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
377 Sets post loop callback function. Pass a subref and it will be
378 called every time the event loop finishes.
380 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
383 The callback function will be passed two parameters: \%DescriptorMap
386 sub SetPostLoopCallback {
387 my ($class, $ref) = @_;
390 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
393 # Internal function: run the post-event callback, send read events
394 # for pushed-back data, and close pending connections. returns 1
395 # if event loop should continue, or 0 to shut it all down.
397 # now we can close sockets that wanted to close during our event processing.
398 # (we didn't want to close them during the loop, as we didn't want fd numbers
399 # being reused and confused during the event loop)
400 while (my $sock = shift @ToClose) {
401 my $fd = fileno($sock);
403 # close the socket. (not a PublicInbox::DS close)
406 # and now we can finally remove the fd from the map. see
407 # comment above in _cleanup.
408 delete $DescriptorMap{$fd};
412 # by default we keep running, unless a postloop callback (either per-object
413 # or global) cancels it
414 my $keep_running = 1;
416 # now we're at the very end, call callback if defined
417 if (defined $PostLoopCallback) {
418 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
421 return $keep_running;
424 #####################################################################
425 ### PublicInbox::DS-the-object code
426 #####################################################################
428 =head2 OBJECT METHODS
430 =head2 C<< CLASS->new( $socket ) >>
432 Create a new PublicInbox::DS subclass object for the given I<socket> which will
433 react to events on it during the C<EventLoop>.
435 This is normally (always?) called from your subclass via:
437 $class->SUPER::new($socket);
441 my ($self, $sock, $exclusive) = @_;
442 $self = fields::new($self) unless ref $self;
444 $self->{sock} = $sock;
445 my $fd = fileno($sock);
447 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
452 $self->{wbuf_off} = 0;
455 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
461 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
464 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
465 if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
466 $EPOLLEXCLUSIVE = 0; # old kernel
467 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
470 die "couldn't add epoll watch for $fd: $!\n";
473 elsif ($HaveKQueue) {
474 # Add them to the queue but disabled for now
475 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
476 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
477 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
478 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
481 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
482 if $DescriptorMap{$fd};
484 $DescriptorMap{$fd} = $self;
489 #####################################################################
490 ### I N S T A N C E M E T H O D S
491 #####################################################################
493 =head2 C<< $obj->steal_socket() >>
495 Basically returns our socket and makes it so that we don't try to close it,
496 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
497 thing as calling close, except it gives you the socket to use.
501 my PublicInbox::DS $self = $_[0];
502 return if $self->{closed};
504 # cleanup does most of the work of closing this socket
507 # now undef our internal sock and fd structures so we don't use them
508 my $sock = $self->{sock};
509 $self->{sock} = undef;
513 =head2 C<< $obj->close( [$reason] ) >>
515 Close the socket. The I<reason> argument will be used in debugging messages.
519 my PublicInbox::DS $self = $_[0];
520 return if $self->{closed};
522 # print out debugging info for this close
524 my ($pkg, $filename, $line) = caller;
525 my $reason = $_[1] || "";
526 warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
529 # this does most of the work of closing us
532 # defer closing the actual socket until the event loop is done
533 # processing this round of events. (otherwise we might reuse fds)
535 push @ToClose, $self->{sock};
536 $self->{sock} = undef;
542 ### METHOD: _cleanup()
543 ### Called by our closers so we can clean internal data structures.
545 my PublicInbox::DS $self = $_[0];
547 # we're effectively closed; we have no fd and sock when we leave here
550 # we need to flush our write buffer, as there may
551 # be self-referential closures (sub { $client->close })
552 # preventing the object from being destroyed
553 @{$self->{wbuf}} = ();
555 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
556 # notifications about it
557 if ($HaveEpoll && $self->{fd}) {
558 if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
559 # dump_error prints a backtrace so we can try to figure out why this happened
560 $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
564 # we explicitly don't delete from DescriptorMap here until we
565 # actually close the socket, as we might be in the middle of
566 # processing an epoll_wait/etc that returned hundreds of fds, one
567 # of which is not yet processed and is what we're closing. if we
568 # keep it in DescriptorMap, then the event harnesses can just
569 # looked at $pob->{closed} and ignore it. but if it's an
570 # un-accounted for fd, then it (understandably) freak out a bit
571 # and emit warnings, thinking their state got off.
573 # and finally get rid of our fd so we can't use it anywhere else
577 =head2 C<< $obj->sock() >>
579 Returns the underlying IO::Handle for the object.
583 my PublicInbox::DS $self = shift;
584 return $self->{sock};
587 =head2 C<< $obj->write( $data ) >>
589 Write the specified data to the underlying handle. I<data> may be scalar,
590 scalar ref, code ref (to run when there), or undef just to kick-start.
591 Returns 1 if writes all went through, or 0 if there are writes in queue. If
592 it returns 1, caller should stop waiting for 'writable' events)
596 my PublicInbox::DS $self;
600 # nobody should be writing to closed sockets, but caller code can
601 # do two writes within an event, have the first fail and
602 # disconnect the other side (whose destructor then closes the
603 # calling object, but it's still in a method), and then the
604 # now-dead object does its second write. that is this case. we
605 # just lie and say it worked. it'll be dead soon and won't be
607 return 1 if $self->{closed};
611 # just queue data if there's already a wait
613 my $wbuf = $self->{wbuf};
616 $bref = ref $data ? $data : \$data;
622 # this flag says we're bypassing the queue system, knowing we're the
623 # only outstanding write, and hoping we don't ever need to use it.
624 # if so later, though, we'll need to queue
630 return 1 unless $bref ||= $wbuf->[0];
634 $len = length($$bref); # this will die if $bref is a code ref, caught below
637 if (UNIVERSAL::isa($bref, "CODE")) {
638 unless ($need_queue) {
643 # code refs are just run and never get reenqueued
644 # (they're one-shot), so turn off the flag indicating the
645 # outstanding data needs queueing.
651 die "Write error: $@ <$bref>";
654 my $to_write = $len - $self->{wbuf_off};
655 my $written = syswrite($self->{sock}, $$bref, $to_write,
658 if (! defined $written) {
660 return $self->close("EPIPE");
661 } elsif ($! == EAGAIN) {
662 # since connection has stuff to write, it should now be
663 # interested in pending writes:
667 $self->watch_write(1);
669 } elsif ($! == ECONNRESET) {
670 return $self->close("ECONNRESET");
673 DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
675 return $self->close("write_error");
676 } elsif ($written != $to_write) {
677 DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
678 $written, $self->{fd});
682 # since connection has stuff to write, it should now be
683 # interested in pending writes:
684 $self->{wbuf_off} += $written;
685 $self->on_incomplete_write;
687 } elsif ($written == $to_write) {
688 DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
689 $written, $self->{fd}, $need_queue);
690 $self->{wbuf_off} = 0;
691 $self->watch_write(0);
693 # this was our only write, so we can return immediately
694 # since we avoided incrementing the buffer size or
695 # putting it in the buffer. we also know there
696 # can't be anything else to write.
697 return 1 if $need_queue;
706 sub on_incomplete_write {
707 my PublicInbox::DS $self = shift;
708 $self->watch_write(1);
711 =head2 C<< $obj->read( $bytecount ) >>
713 Read at most I<bytecount> bytes from the underlying handle; returns scalar
714 ref on read, or undef on connection closed.
718 my PublicInbox::DS $self = shift;
719 return if $self->{closed};
722 my $sock = $self->{sock};
724 # if this is too high, perl quits(!!). reports on mailing lists
725 # don't seem to point to a universal answer. 5MB worked for some,
726 # crashed for others. 1MB works for more people. let's go with 1MB
728 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
730 my $res = sysread($sock, $buf, $req_bytes, 0);
731 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
733 if (! $res && $! != EWOULDBLOCK) {
734 # catches 0=conn closed or undef=error
735 DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
742 =head2 (VIRTUAL) C<< $obj->event_read() >>
744 Readable event handler. Concrete deriviatives of PublicInbox::DS should
745 provide an implementation of this. The default implementation will die if
749 sub event_read { die "Base class event_read called for $_[0]\n"; }
751 =head2 (VIRTUAL) C<< $obj->event_err() >>
753 Error event handler. Concrete deriviatives of PublicInbox::DS should
754 provide an implementation of this. The default implementation will die if
758 sub event_err { die "Base class event_err called for $_[0]\n"; }
760 =head2 (VIRTUAL) C<< $obj->event_hup() >>
762 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
763 provide an implementation of this. The default implementation will die if
767 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
769 =head2 C<< $obj->event_write() >>
771 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
772 provide an implementation of this. The default implementation calls
773 C<write()> with an C<undef>.
781 =head2 C<< $obj->watch_read( $boolean ) >>
783 Turn 'readable' event notification on or off.
787 my PublicInbox::DS $self = shift;
788 return if $self->{closed} || !$self->{sock};
791 my $event = $self->{event_watch};
793 $event &= ~POLLIN if ! $val;
794 $event |= POLLIN if $val;
796 # If it changed, set it
797 if ($event != $self->{event_watch}) {
799 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
800 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
803 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
804 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
805 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
807 $self->{event_watch} = $event;
811 =head2 C<< $obj->watch_write( $boolean ) >>
813 Turn 'writable' event notification on or off.
817 my PublicInbox::DS $self = shift;
818 return if $self->{closed} || !$self->{sock};
821 my $event = $self->{event_watch};
823 $event &= ~POLLOUT if ! $val;
824 $event |= POLLOUT if $val;
826 # If it changed, set it
827 if ($event != $self->{event_watch}) {
829 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
830 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
833 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
834 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
835 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
837 $self->{event_watch} = $event;
841 =head2 C<< $obj->dump_error( $message ) >>
843 Prints to STDERR a backtrace with information about this socket and what lead
844 up to the dump_error call.
850 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
851 push @list, "\t$file:$line called $sub\n";
854 warn "ERROR: $_[1]\n" .
855 "\t$_[0] = " . $_[0]->as_string . "\n" .
859 =head2 C<< $obj->debugmsg( $format, @args ) >>
861 Print the debugging message specified by the C<sprintf>-style I<format> and
866 my ( $self, $fmt, @args ) = @_;
867 confess "Not an object" unless ref $self;
870 printf STDERR ">>> $fmt\n", @args;
873 =head2 C<< $obj->as_string() >>
875 Returns a string describing this socket.
879 my PublicInbox::DS $self = shift;
880 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
881 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
882 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
886 package PublicInbox::DS::Timer;
887 # [$abs_float_firetime, $coderef];
894 =head1 AUTHORS (Danga::Socket)
896 Brad Fitzpatrick <brad@danga.com> - author
898 Michael Granger <ged@danga.com> - docs, testing
900 Mark Smith <junior@danga.com> - contributor, heavy user, testing
902 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits