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 'wbuf', # arrayref of scalars, scalarrefs, or coderefs to write
30 'wbuf_off', # offset into first element of wbuf to start writing at
31 'closed', # bool: socket is closed
32 'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
35 use Errno qw(EAGAIN EINVAL);
36 use Carp qw(croak confess);
38 use constant DebugLevel => 0;
40 use constant POLLIN => 1;
41 use constant POLLOUT => 4;
42 use constant POLLERR => 8;
43 use constant POLLHUP => 16;
44 use constant POLLNVAL => 32;
46 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
49 $HaveEpoll, # Flag -- is epoll available? initially undefined.
51 %DescriptorMap, # fd (num) -> PublicInbox::DS object
52 $Epoll, # Global epoll fd (for epoll mode only)
53 $KQueue, # Global kqueue fd ref (for kqueue mode only)
54 $_io, # IO::Handle for Epoll
55 @ToClose, # sockets to close when event loop is done
57 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
59 $LoopTimeout, # timeout of event loop in milliseconds
60 $DoneInit, # if we've done the one-time module init yet
64 # this may be set to zero with old kernels
65 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
68 #####################################################################
69 ### C L A S S M E T H O D S
70 #####################################################################
72 =head2 C<< CLASS->Reset() >>
80 $LoopTimeout = -1; # no timeout by default
83 $PostLoopCallback = undef;
86 # NOTE kqueue is close-on-fork, and we don't account for it, yet
87 # OTOH, we (public-inbox) don't need this sub outside of tests...
88 POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
91 $_io = undef; # close $Epoll
94 *EventLoop = *FirstTimeEventLoop;
97 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
99 Set the loop timeout for the event loop to some value in milliseconds.
101 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
106 return $LoopTimeout = $_[1] + 0;
109 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
111 Print the debugging message specified by the C<sprintf>-style I<format> and
116 my ( $class, $fmt, @args ) = @_;
118 printf STDERR ">>> $fmt\n", @args;
121 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
123 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
124 are not guaranteed to fire at the exact time you ask for.
126 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
131 my ($secs, $coderef) = @_;
133 my $fire_time = Time::HiRes::time() + $secs;
135 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
137 if (!@Timers || $fire_time >= $Timers[-1][0]) {
138 push @Timers, $timer;
142 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
143 # but it was compared against calendar queues, heaps, naive push/sort,
144 # and a bunch of other versions, and found to be fastest with a large
145 # variety of datasets.)
146 for (my $i = 0; $i < @Timers; $i++) {
147 if ($Timers[$i][0] > $fire_time) {
148 splice(@Timers, $i, 0, $timer);
153 die "Shouldn't get here.";
156 # keeping this around in case we support other FD types for now,
157 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
158 sub set_cloexec ($) {
161 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
162 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
163 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
172 $KQueue = IO::KQueue->new();
173 $HaveKQueue = defined $KQueue;
175 *EventLoop = *KQueueEventLoop;
178 elsif (PublicInbox::Syscall::epoll_defined()) {
179 $Epoll = eval { epoll_create(1024); };
180 $HaveEpoll = defined $Epoll && $Epoll >= 0;
183 *EventLoop = *EpollEventLoop;
187 if (!$HaveEpoll && !$HaveKQueue) {
189 *EventLoop = *PollEventLoop;
193 =head2 C<< CLASS->EventLoop() >>
195 Start processing IO events. In most daemon programs this never exits. See
196 C<PostLoopCallback> below for how to exit the loop.
199 sub FirstTimeEventLoop {
205 EpollEventLoop($class);
206 } elsif ($HaveKQueue) {
207 KQueueEventLoop($class);
209 PollEventLoop($class);
213 # runs timers and returns milliseconds for next one, or next event loop
215 return $LoopTimeout unless @Timers;
217 my $now = Time::HiRes::time();
220 while (@Timers && $Timers[0][0] <= $now) {
221 my $to_run = shift(@Timers);
222 $to_run->[1]->($now) if $to_run->[1];
225 return $LoopTimeout unless @Timers;
227 # convert time to an even number of milliseconds, adding 1
228 # extra, otherwise floating point fun can occur and we'll
229 # call RunTimers like 20-30 times, each returning a timeout
230 # of 0.0000212 seconds
231 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
233 # -1 is an infinite timeout, so prefer a real timeout
234 return $timeout if $LoopTimeout == -1;
236 # otherwise pick the lower of our regular timeout and time until
238 return $LoopTimeout if $LoopTimeout < $timeout;
242 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
250 my $timeout = RunTimers();
252 # get up to 1000 events
253 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
254 for ($i=0; $i<$evcount; $i++) {
255 my $ev = $events[$i];
257 # it's possible epoll_wait returned many events, including some at the end
258 # that ones in the front triggered unregister-interest actions. if we
259 # can't find the %sock entry, it's because we're no longer interested
261 my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
263 my $state = $ev->[1];
265 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
266 $ev->[0], ref($pob), $ev->[1], time);
268 # standard non-profiling codepat
269 $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
270 $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
271 if ($state & (EPOLLERR|EPOLLHUP)) {
272 $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
273 $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
276 return unless PostEventLoop();
281 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
282 ### IO::Epoll fails to load.
286 my PublicInbox::DS $pob;
289 my $timeout = RunTimers();
291 # the following sets up @poll as a series of ($poll,$event_mask)
292 # items, then uses IO::Poll::_poll, implemented in XS, which
293 # modifies the array in place with the even elements being
294 # replaced with the event masks that occured.
296 while ( my ($fd, $sock) = each %DescriptorMap ) {
297 push @poll, $fd, $sock->{event_watch};
300 # if nothing to poll, either end immediately (if no timeout)
301 # or just keep calling the callback
303 select undef, undef, undef, ($timeout / 1000);
304 return unless PostEventLoop();
308 my $count = IO::Poll::_poll($timeout, @poll);
309 unless ($count >= 0) {
310 return unless PostEventLoop();
314 # Fetch handles with read events
316 my ($fd, $state) = splice(@poll, 0, 2);
319 $pob = $DescriptorMap{$fd};
321 $pob->event_read if $state & POLLIN && ! $pob->{closed};
322 $pob->event_write if $state & POLLOUT && ! $pob->{closed};
323 $pob->event_err if $state & POLLERR && ! $pob->{closed};
324 $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
327 return unless PostEventLoop();
333 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
335 sub KQueueEventLoop {
339 my $timeout = RunTimers();
340 my @ret = eval { $KQueue->kevent($timeout) };
342 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
343 if ($err =~ /Interrupted system call/) {
350 foreach my $kev (@ret) {
351 my ($fd, $filter, $flags, $fflags) = @$kev;
352 my PublicInbox::DS $pob = $DescriptorMap{$fd};
354 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
355 $fd, ref($pob), $flags, time);
357 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
358 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
359 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
367 return unless PostEventLoop();
373 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
375 Sets post loop callback function. Pass a subref and it will be
376 called every time the event loop finishes.
378 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
381 The callback function will be passed two parameters: \%DescriptorMap
384 sub SetPostLoopCallback {
385 my ($class, $ref) = @_;
388 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
391 # Internal function: run the post-event callback, send read events
392 # for pushed-back data, and close pending connections. returns 1
393 # if event loop should continue, or 0 to shut it all down.
395 # now we can close sockets that wanted to close during our event processing.
396 # (we didn't want to close them during the loop, as we didn't want fd numbers
397 # being reused and confused during the event loop)
398 while (my $sock = shift @ToClose) {
399 my $fd = fileno($sock);
401 # close the socket. (not a PublicInbox::DS close)
404 # and now we can finally remove the fd from the map. see
405 # comment above in _cleanup.
406 delete $DescriptorMap{$fd};
410 # by default we keep running, unless a postloop callback (either per-object
411 # or global) cancels it
412 my $keep_running = 1;
414 # now we're at the very end, call callback if defined
415 if (defined $PostLoopCallback) {
416 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
419 return $keep_running;
422 #####################################################################
423 ### PublicInbox::DS-the-object code
424 #####################################################################
426 =head2 OBJECT METHODS
428 =head2 C<< CLASS->new( $socket ) >>
430 Create a new PublicInbox::DS subclass object for the given I<socket> which will
431 react to events on it during the C<EventLoop>.
433 This is normally (always?) called from your subclass via:
435 $class->SUPER::new($socket);
439 my ($self, $sock, $exclusive) = @_;
440 $self = fields::new($self) unless ref $self;
442 $self->{sock} = $sock;
443 my $fd = fileno($sock);
445 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
449 $self->{wbuf_off} = 0;
452 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
458 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
461 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
462 if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
463 $EPOLLEXCLUSIVE = 0; # old kernel
464 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
467 die "couldn't add epoll watch for $fd: $!\n";
470 elsif ($HaveKQueue) {
471 # Add them to the queue but disabled for now
472 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
473 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
474 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
475 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
478 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
479 if $DescriptorMap{$fd};
481 $DescriptorMap{$fd} = $self;
486 #####################################################################
487 ### I N S T A N C E M E T H O D S
488 #####################################################################
490 =head2 C<< $obj->steal_socket() >>
492 Basically returns our socket and makes it so that we don't try to close it,
493 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
494 thing as calling close, except it gives you the socket to use.
498 my PublicInbox::DS $self = $_[0];
499 return if $self->{closed};
501 # cleanup does most of the work of closing this socket
504 # now undef our internal sock and fd structures so we don't use them
505 my $sock = $self->{sock};
506 $self->{sock} = undef;
510 =head2 C<< $obj->close >>
516 my PublicInbox::DS $self = $_[0];
517 return if $self->{closed};
519 # this does most of the work of closing us
522 # defer closing the actual socket until the event loop is done
523 # processing this round of events. (otherwise we might reuse fds)
524 if (my $sock = delete $self->{sock}) {
525 push @ToClose, $sock;
531 ### METHOD: _cleanup()
532 ### Called by our closers so we can clean internal data structures.
534 my PublicInbox::DS $self = $_[0];
536 # we're effectively closed; we have no fd and sock when we leave here
539 # we need to flush our write buffer, as there may
540 # be self-referential closures (sub { $client->close })
541 # preventing the object from being destroyed
542 @{$self->{wbuf}} = ();
544 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
545 # notifications about it
546 if ($HaveEpoll && $self->{sock}) {
547 my $fd = fileno($self->{sock});
548 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
549 confess("EPOLL_CTL_DEL: $!");
552 # we explicitly don't delete from DescriptorMap here until we
553 # actually close the socket, as we might be in the middle of
554 # processing an epoll_wait/etc that returned hundreds of fds, one
555 # of which is not yet processed and is what we're closing. if we
556 # keep it in DescriptorMap, then the event harnesses can just
557 # looked at $pob->{closed} and ignore it. but if it's an
558 # un-accounted for fd, then it (understandably) freak out a bit
559 # and emit warnings, thinking their state got off.
562 =head2 C<< $obj->sock() >>
564 Returns the underlying IO::Handle for the object.
568 my PublicInbox::DS $self = shift;
569 return $self->{sock};
572 =head2 C<< $obj->write( $data ) >>
574 Write the specified data to the underlying handle. I<data> may be scalar,
575 scalar ref, code ref (to run when there), or undef just to kick-start.
576 Returns 1 if writes all went through, or 0 if there are writes in queue. If
577 it returns 1, caller should stop waiting for 'writable' events)
581 my PublicInbox::DS $self;
585 # nobody should be writing to closed sockets, but caller code can
586 # do two writes within an event, have the first fail and
587 # disconnect the other side (whose destructor then closes the
588 # calling object, but it's still in a method), and then the
589 # now-dead object does its second write. that is this case. we
590 # just lie and say it worked. it'll be dead soon and won't be
592 return 1 if $self->{closed};
596 # just queue data if there's already a wait
598 my $wbuf = $self->{wbuf};
601 $bref = ref $data ? $data : \$data;
607 # this flag says we're bypassing the queue system, knowing we're the
608 # only outstanding write, and hoping we don't ever need to use it.
609 # if so later, though, we'll need to queue
615 return 1 unless $bref ||= $wbuf->[0];
619 $len = length($$bref); # this will die if $bref is a code ref, caught below
622 if (UNIVERSAL::isa($bref, "CODE")) {
623 unless ($need_queue) {
628 # code refs are just run and never get reenqueued
629 # (they're one-shot), so turn off the flag indicating the
630 # outstanding data needs queueing.
636 die "Write error: $@ <$bref>";
639 my $to_write = $len - $self->{wbuf_off};
640 my $written = syswrite($self->{sock}, $$bref, $to_write,
643 if (! defined $written) {
645 # since connection has stuff to write, it should now be
646 # interested in pending writes:
650 $self->watch_write(1);
655 } elsif ($written != $to_write) {
659 # since connection has stuff to write, it should now be
660 # interested in pending writes:
661 $self->{wbuf_off} += $written;
662 $self->on_incomplete_write;
664 } elsif ($written == $to_write) {
665 $self->{wbuf_off} = 0;
666 $self->watch_write(0);
668 # this was our only write, so we can return immediately
669 # since we avoided incrementing the buffer size or
670 # putting it in the buffer. we also know there
671 # can't be anything else to write.
672 return 1 if $need_queue;
681 sub on_incomplete_write {
682 my PublicInbox::DS $self = shift;
683 $self->watch_write(1);
686 =head2 C<< $obj->read( $bytecount ) >>
688 Read at most I<bytecount> bytes from the underlying handle; returns scalar
689 ref on read, or undef on connection closed.
693 my PublicInbox::DS $self = shift;
694 return if $self->{closed};
697 my $sock = $self->{sock};
699 # if this is too high, perl quits(!!). reports on mailing lists
700 # don't seem to point to a universal answer. 5MB worked for some,
701 # crashed for others. 1MB works for more people. let's go with 1MB
703 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
705 my $res = sysread($sock, $buf, $req_bytes, 0);
706 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
708 if (! $res && $! != EAGAIN) {
709 # catches 0=conn closed or undef=error
716 =head2 (VIRTUAL) C<< $obj->event_read() >>
718 Readable event handler. Concrete deriviatives of PublicInbox::DS should
719 provide an implementation of this. The default implementation will die if
723 sub event_read { die "Base class event_read called for $_[0]\n"; }
725 =head2 (VIRTUAL) C<< $obj->event_err() >>
727 Error event handler. Concrete deriviatives of PublicInbox::DS should
728 provide an implementation of this. The default implementation will die if
732 sub event_err { die "Base class event_err called for $_[0]\n"; }
734 =head2 (VIRTUAL) C<< $obj->event_hup() >>
736 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
737 provide an implementation of this. The default implementation will die if
741 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
743 =head2 C<< $obj->event_write() >>
745 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
746 provide an implementation of this. The default implementation calls
747 C<write()> with an C<undef>.
755 =head2 C<< $obj->watch_read( $boolean ) >>
757 Turn 'readable' event notification on or off.
761 my PublicInbox::DS $self = shift;
762 return if $self->{closed} || !$self->{sock};
765 my $event = $self->{event_watch};
767 $event &= ~POLLIN if ! $val;
768 $event |= POLLIN if $val;
770 my $fd = fileno($self->{sock});
771 # If it changed, set it
772 if ($event != $self->{event_watch}) {
774 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
775 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
778 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
779 confess("EPOLL_CTL_MOD: $!");
781 $self->{event_watch} = $event;
785 =head2 C<< $obj->watch_write( $boolean ) >>
787 Turn 'writable' event notification on or off.
791 my PublicInbox::DS $self = shift;
792 return if $self->{closed} || !$self->{sock};
795 my $event = $self->{event_watch};
797 $event &= ~POLLOUT if ! $val;
798 $event |= POLLOUT if $val;
799 my $fd = fileno($self->{sock});
801 # If it changed, set it
802 if ($event != $self->{event_watch}) {
804 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
805 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
808 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
809 confess "EPOLL_CTL_MOD: $!";
811 $self->{event_watch} = $event;
815 =head2 C<< $obj->dump_error( $message ) >>
817 Prints to STDERR a backtrace with information about this socket and what lead
818 up to the dump_error call.
824 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
825 push @list, "\t$file:$line called $sub\n";
828 warn "ERROR: $_[1]\n" .
829 "\t$_[0] = " . $_[0]->as_string . "\n" .
833 =head2 C<< $obj->debugmsg( $format, @args ) >>
835 Print the debugging message specified by the C<sprintf>-style I<format> and
840 my ( $self, $fmt, @args ) = @_;
841 confess "Not an object" unless ref $self;
844 printf STDERR ">>> $fmt\n", @args;
847 =head2 C<< $obj->as_string() >>
849 Returns a string describing this socket.
853 my PublicInbox::DS $self = shift;
854 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
855 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
856 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
860 package PublicInbox::DS::Timer;
861 # [$abs_float_firetime, $coderef];
868 =head1 AUTHORS (Danga::Socket)
870 Brad Fitzpatrick <brad@danga.com> - author
872 Michael Granger <ged@danga.com> - docs, testing
874 Mark Smith <junior@danga.com> - contributor, heavy user, testing
876 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits