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 package PublicInbox::DS;
16 my $opt_bsd_resource = eval "use BSD::Resource; 1;";
18 use vars qw{$VERSION};
22 no warnings qw(deprecated);
24 use PublicInbox::Syscall qw(:epoll);
26 use fields ('sock', # underlying socket
27 'fd', # numeric file descriptor
28 'write_buf', # arrayref of scalars, scalarrefs, or coderefs to write
29 'write_buf_offset', # offset into first array of write_buf to start writing at
30 'write_buf_size', # total length of data in all write_buf items
31 'write_set_watch', # bool: true if we internally set watch_write rather than by a subclass
32 'read_push_back', # arrayref of "pushed-back" read data the application didn't want
33 'closed', # bool: socket is closed
34 'corked', # bool: socket is corked
35 'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
36 'peer_v6', # bool: cached; if peer is an IPv6 address
37 'peer_ip', # cached stringified IP address of $sock
38 'peer_port', # cached port number of $sock
39 'local_ip', # cached stringified IP address of local end of $sock
40 'local_port', # cached port number of local end of $sock
41 'writer_func', # subref which does writing. must return bytes written (or undef) and set $! on errors
44 use Errno qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
45 EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
46 use Socket qw(IPPROTO_TCP);
47 use Carp qw(croak confess);
49 use constant TCP_CORK => ($^O eq "linux" ? 3 : 0); # FIXME: not hard-coded (Linux-specific too)
50 use constant DebugLevel => 0;
52 use constant POLLIN => 1;
53 use constant POLLOUT => 4;
54 use constant POLLERR => 8;
55 use constant POLLHUP => 16;
56 use constant POLLNVAL => 32;
58 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
61 $HaveEpoll, # Flag -- is epoll available? initially undefined.
63 %DescriptorMap, # fd (num) -> PublicInbox::DS object
64 %PushBackSet, # fd (num) -> PublicInbox::DS (fds with pushed back read data)
65 $Epoll, # Global epoll fd (for epoll mode only)
66 $KQueue, # Global kqueue fd (for kqueue mode only)
67 @ToClose, # sockets to close when event loop is done
68 %OtherFds, # A hash of "other" (non-PublicInbox::DS) file
69 # descriptors for the event loop to track.
71 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
72 %PLCMap, # fd (num) -> PostLoopCallback (per-object)
74 $LoopTimeout, # timeout of event loop in milliseconds
75 $DoProfile, # if on, enable profiling
76 %Profiling, # what => [ utime, stime, calls ]
77 $DoneInit, # if we've done the one-time module init yet
81 # this may be set to zero with old kernels
82 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
85 #####################################################################
86 ### C L A S S M E T H O D S
87 #####################################################################
89 =head2 C<< CLASS->Reset() >>
99 $LoopTimeout = -1; # no timeout by default
104 $PostLoopCallback = undef;
108 POSIX::close($Epoll) if defined $Epoll && $Epoll >= 0;
109 POSIX::close($KQueue) if defined $KQueue && $KQueue >= 0;
111 *EventLoop = *FirstTimeEventLoop;
114 =head2 C<< CLASS->HaveEpoll() >>
116 Returns a true value if this class will use IO::Epoll for async IO.
124 =head2 C<< CLASS->WatchedSockets() >>
126 Returns the number of file descriptors which are registered with the global
131 return scalar keys %DescriptorMap;
133 *watched_sockets = *WatchedSockets;
135 =head2 C<< CLASS->EnableProfiling() >>
137 Turns profiling on, clearing current profiling data.
140 sub EnableProfiling {
141 if ($opt_bsd_resource) {
149 =head2 C<< CLASS->DisableProfiling() >>
151 Turns off profiling, but retains data up to this point
154 sub DisableProfiling {
158 =head2 C<< CLASS->ProfilingData() >>
160 Returns reference to a hash of data in format:
162 ITEM => [ utime, stime, #calls ]
169 =head2 C<< CLASS->ToClose() >>
171 Return the list of sockets that are awaiting close() at the end of the
175 sub ToClose { return @ToClose; }
177 =head2 C<< CLASS->OtherFds( [%fdmap] ) >>
179 Get/set the hash of file descriptors that need processing in parallel with
180 the registered PublicInbox::DS objects.
185 if ( @_ ) { %OtherFds = @_ }
186 return wantarray ? %OtherFds : \%OtherFds;
189 =head2 C<< CLASS->AddOtherFds( [%fdmap] ) >>
191 Add fds to the OtherFds hash for processing.
196 %OtherFds = ( %OtherFds, @_ ); # FIXME investigate what happens on dupe fds
197 return wantarray ? %OtherFds : \%OtherFds;
200 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
202 Set the loop timeout for the event loop to some value in milliseconds.
204 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
209 return $LoopTimeout = $_[1] + 0;
212 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
214 Print the debugging message specified by the C<sprintf>-style I<format> and
219 my ( $class, $fmt, @args ) = @_;
221 printf STDERR ">>> $fmt\n", @args;
224 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
226 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
227 are not guaranteed to fire at the exact time you ask for.
229 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
234 my ($secs, $coderef) = @_;
236 my $fire_time = Time::HiRes::time() + $secs;
238 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
240 if (!@Timers || $fire_time >= $Timers[-1][0]) {
241 push @Timers, $timer;
245 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
246 # but it was compared against calendar queues, heaps, naive push/sort,
247 # and a bunch of other versions, and found to be fastest with a large
248 # variety of datasets.)
249 for (my $i = 0; $i < @Timers; $i++) {
250 if ($Timers[$i][0] > $fire_time) {
251 splice(@Timers, $i, 0, $timer);
256 die "Shouldn't get here.";
259 =head2 C<< CLASS->DescriptorMap() >>
261 Get the hash of PublicInbox::DS objects keyed by the file descriptor (fileno) they
264 Returns a hash in list context or a hashref in scalar context.
268 return wantarray ? %DescriptorMap : \%DescriptorMap;
270 *descriptor_map = *DescriptorMap;
271 *get_sock_ref = *DescriptorMap;
279 $KQueue = IO::KQueue->new();
280 $HaveKQueue = $KQueue >= 0;
282 *EventLoop = *KQueueEventLoop;
285 elsif (PublicInbox::Syscall::epoll_defined()) {
286 $Epoll = eval { epoll_create(1024); };
287 $HaveEpoll = defined $Epoll && $Epoll >= 0;
289 *EventLoop = *EpollEventLoop;
293 if (!$HaveEpoll && !$HaveKQueue) {
295 *EventLoop = *PollEventLoop;
299 =head2 C<< CLASS->EventLoop() >>
301 Start processing IO events. In most daemon programs this never exits. See
302 C<PostLoopCallback> below for how to exit the loop.
305 sub FirstTimeEventLoop {
311 EpollEventLoop($class);
312 } elsif ($HaveKQueue) {
313 KQueueEventLoop($class);
315 PollEventLoop($class);
319 ## profiling-related data/functions
320 our ($Prof_utime0, $Prof_stime0);
322 ($Prof_utime0, $Prof_stime0) = getrusage();
326 # get post information
327 my ($autime, $astime) = getrusage();
329 # calculate differences
330 my $utime = $autime - $Prof_utime0;
331 my $stime = $astime - $Prof_stime0;
334 $Profiling{$k} ||= [ 0.0, 0.0, 0 ];
335 $Profiling{$k}->[0] += $utime;
336 $Profiling{$k}->[1] += $stime;
337 $Profiling{$k}->[2]++;
341 # runs timers and returns milliseconds for next one, or next event loop
343 return $LoopTimeout unless @Timers;
345 my $now = Time::HiRes::time();
348 while (@Timers && $Timers[0][0] <= $now) {
349 my $to_run = shift(@Timers);
350 $to_run->[1]->($now) if $to_run->[1];
353 return $LoopTimeout unless @Timers;
355 # convert time to an even number of milliseconds, adding 1
356 # extra, otherwise floating point fun can occur and we'll
357 # call RunTimers like 20-30 times, each returning a timeout
358 # of 0.0000212 seconds
359 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
361 # -1 is an infinite timeout, so prefer a real timeout
362 return $timeout if $LoopTimeout == -1;
364 # otherwise pick the lower of our regular timeout and time until
366 return $LoopTimeout if $LoopTimeout < $timeout;
370 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
375 foreach my $fd ( keys %OtherFds ) {
376 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, EPOLLIN) == -1) {
377 warn "epoll_ctl(): failure adding fd=$fd; $! (", $!+0, ")\n";
384 my $timeout = RunTimers();
386 # get up to 1000 events
387 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
389 for ($i=0; $i<$evcount; $i++) {
390 my $ev = $events[$i];
392 # it's possible epoll_wait returned many events, including some at the end
393 # that ones in the front triggered unregister-interest actions. if we
394 # can't find the %sock entry, it's because we're no longer interested
396 my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
398 my $state = $ev->[1];
400 # if we didn't find a Perlbal::Socket subclass for that fd, try other
401 # pseudo-registered (above) fds.
403 if (my $code = $OtherFds{$ev->[0]}) {
407 warn "epoll() returned fd $fd w/ state $state for which we have no mapping. removing.\n";
409 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
414 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
415 $ev->[0], ref($pob), $ev->[1], time);
418 my $class = ref $pob;
420 # call profiling action on things that need to be done
421 if ($state & EPOLLIN && ! $pob->{closed}) {
424 _post_profile("$class-read");
427 if ($state & EPOLLOUT && ! $pob->{closed}) {
430 _post_profile("$class-write");
433 if ($state & (EPOLLERR|EPOLLHUP)) {
434 if ($state & EPOLLERR && ! $pob->{closed}) {
437 _post_profile("$class-err");
439 if ($state & EPOLLHUP && ! $pob->{closed}) {
442 _post_profile("$class-hup");
449 # standard non-profiling codepat
450 $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
451 $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
452 if ($state & (EPOLLERR|EPOLLHUP)) {
453 $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
454 $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
457 return unless PostEventLoop();
462 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
463 ### IO::Epoll fails to load.
467 my PublicInbox::DS $pob;
470 my $timeout = RunTimers();
472 # the following sets up @poll as a series of ($poll,$event_mask)
473 # items, then uses IO::Poll::_poll, implemented in XS, which
474 # modifies the array in place with the even elements being
475 # replaced with the event masks that occured.
477 foreach my $fd ( keys %OtherFds ) {
478 push @poll, $fd, POLLIN;
480 while ( my ($fd, $sock) = each %DescriptorMap ) {
481 push @poll, $fd, $sock->{event_watch};
484 # if nothing to poll, either end immediately (if no timeout)
485 # or just keep calling the callback
487 select undef, undef, undef, ($timeout / 1000);
488 return unless PostEventLoop();
492 my $count = IO::Poll::_poll($timeout, @poll);
494 return unless PostEventLoop();
498 # Fetch handles with read events
500 my ($fd, $state) = splice(@poll, 0, 2);
503 $pob = $DescriptorMap{$fd};
506 if (my $code = $OtherFds{$fd}) {
512 $pob->event_read if $state & POLLIN && ! $pob->{closed};
513 $pob->event_write if $state & POLLOUT && ! $pob->{closed};
514 $pob->event_err if $state & POLLERR && ! $pob->{closed};
515 $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
518 return unless PostEventLoop();
524 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
526 sub KQueueEventLoop {
529 foreach my $fd (keys %OtherFds) {
530 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(), IO::KQueue::EV_ADD());
534 my $timeout = RunTimers();
535 my @ret = $KQueue->kevent($timeout);
537 foreach my $kev (@ret) {
538 my ($fd, $filter, $flags, $fflags) = @$kev;
539 my PublicInbox::DS $pob = $DescriptorMap{$fd};
541 if (my $code = $OtherFds{$fd}) {
544 warn "kevent() returned fd $fd for which we have no mapping. removing.\n";
545 POSIX::close($fd); # close deletes the kevent entry
550 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
551 $fd, ref($pob), $flags, time);
553 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
554 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
555 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
563 return unless PostEventLoop();
569 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
571 Sets post loop callback function. Pass a subref and it will be
572 called every time the event loop finishes.
574 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
577 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
580 sub SetPostLoopCallback {
581 my ($class, $ref) = @_;
584 # per-object callback
585 my PublicInbox::DS $self = $class;
586 if (defined $ref && ref $ref eq 'CODE') {
587 $PLCMap{$self->{fd}} = $ref;
589 delete $PLCMap{$self->{fd}};
593 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
597 # Internal function: run the post-event callback, send read events
598 # for pushed-back data, and close pending connections. returns 1
599 # if event loop should continue, or 0 to shut it all down.
601 # fire read events for objects with pushed-back read data
605 foreach my $fd (keys %PushBackSet) {
606 my PublicInbox::DS $pob = $PushBackSet{$fd};
608 # a previous event_read invocation could've closed a
609 # connection that we already evaluated in "keys
610 # %PushBackSet", so skip ones that seem to have
611 # disappeared. this is expected.
614 die "ASSERT: the $pob socket has no read_push_back" unless @{$pob->{read_push_back}};
615 next unless (! $pob->{closed} &&
616 $pob->{event_watch} & POLLIN);
622 # now we can close sockets that wanted to close during our event processing.
623 # (we didn't want to close them during the loop, as we didn't want fd numbers
624 # being reused and confused during the event loop)
625 while (my $sock = shift @ToClose) {
626 my $fd = fileno($sock);
628 # close the socket. (not a PublicInbox::DS close)
631 # and now we can finally remove the fd from the map. see
632 # comment above in _cleanup.
633 delete $DescriptorMap{$fd};
637 # by default we keep running, unless a postloop callback (either per-object
638 # or global) cancels it
639 my $keep_running = 1;
641 # per-object post-loop-callbacks
642 for my $plc (values %PLCMap) {
643 $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
646 # now we're at the very end, call callback if defined
647 if (defined $PostLoopCallback) {
648 $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
651 return $keep_running;
654 #####################################################################
655 ### PublicInbox::DS-the-object code
656 #####################################################################
658 =head2 OBJECT METHODS
660 =head2 C<< CLASS->new( $socket ) >>
662 Create a new PublicInbox::DS subclass object for the given I<socket> which will
663 react to events on it during the C<EventLoop>.
665 This is normally (always?) called from your subclass via:
667 $class->SUPER::new($socket);
671 my ($self, $sock, $exclusive) = @_;
672 $self = fields::new($self) unless ref $self;
674 $self->{sock} = $sock;
675 my $fd = fileno($sock);
677 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
681 $self->{write_buf} = [];
682 $self->{write_buf_offset} = 0;
683 $self->{write_buf_size} = 0;
686 $self->{read_push_back} = [];
688 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
694 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
697 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
698 if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
699 $EPOLLEXCLUSIVE = 0; # old kernel
700 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
703 die "couldn't add epoll watch for $fd: $!\n";
706 elsif ($HaveKQueue) {
707 # Add them to the queue but disabled for now
708 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
709 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
710 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
711 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
714 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
715 if $DescriptorMap{$fd};
717 $DescriptorMap{$fd} = $self;
722 #####################################################################
723 ### I N S T A N C E M E T H O D S
724 #####################################################################
726 =head2 C<< $obj->tcp_cork( $boolean ) >>
728 Turn TCP_CORK on or off depending on the value of I<boolean>.
732 my PublicInbox::DS $self = $_[0];
735 # make sure we have a socket
736 return unless $self->{sock};
737 return if $val == $self->{corked};
741 $rv = setsockopt($self->{sock}, IPPROTO_TCP, TCP_CORK,
742 pack("l", $val ? 1 : 0));
744 # FIXME: implement freebsd *PUSH sockopts
748 # if we failed, close (if we're not already) and warn about the error
750 $self->{corked} = $val;
752 if ($! == EBADF || $! == ENOTSOCK) {
753 # internal state is probably corrupted; warn and then close if
754 # we're not closed already
755 warn "setsockopt: $!";
756 $self->close('tcp_cork_failed');
757 } elsif ($! == ENOPROTOOPT || $!{ENOTSOCK} || $!{EOPNOTSUPP}) {
758 # TCP implementation doesn't support corking, so just ignore it
759 # or we're trying to tcp-cork a non-socket (like a socketpair pipe
760 # which is acting like a socket, which Perlbal does for child
761 # processes acting like inetd-like web servers)
763 # some other error; we should never hit here, but if we do, die
764 die "setsockopt: $!";
769 =head2 C<< $obj->steal_socket() >>
771 Basically returns our socket and makes it so that we don't try to close it,
772 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
773 thing as calling close, except it gives you the socket to use.
777 my PublicInbox::DS $self = $_[0];
778 return if $self->{closed};
780 # cleanup does most of the work of closing this socket
783 # now undef our internal sock and fd structures so we don't use them
784 my $sock = $self->{sock};
785 $self->{sock} = undef;
789 =head2 C<< $obj->close( [$reason] ) >>
791 Close the socket. The I<reason> argument will be used in debugging messages.
795 my PublicInbox::DS $self = $_[0];
796 return if $self->{closed};
798 # print out debugging info for this close
800 my ($pkg, $filename, $line) = caller;
801 my $reason = $_[1] || "";
802 warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
805 # this does most of the work of closing us
808 # defer closing the actual socket until the event loop is done
809 # processing this round of events. (otherwise we might reuse fds)
811 push @ToClose, $self->{sock};
812 $self->{sock} = undef;
818 ### METHOD: _cleanup()
819 ### Called by our closers so we can clean internal data structures.
821 my PublicInbox::DS $self = $_[0];
823 # we're effectively closed; we have no fd and sock when we leave here
826 # we need to flush our write buffer, as there may
827 # be self-referential closures (sub { $client->close })
828 # preventing the object from being destroyed
829 $self->{write_buf} = [];
831 # uncork so any final data gets sent. only matters if the person closing
832 # us forgot to do it, but we do it to be safe.
835 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
836 # notifications about it
837 if ($HaveEpoll && $self->{fd}) {
838 if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
839 # dump_error prints a backtrace so we can try to figure out why this happened
840 $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
844 # now delete from mappings. this fd no longer belongs to us, so we don't want
845 # to get alerts for it if it becomes writable/readable/etc.
846 delete $PushBackSet{$self->{fd}};
847 delete $PLCMap{$self->{fd}};
849 # we explicitly don't delete from DescriptorMap here until we
850 # actually close the socket, as we might be in the middle of
851 # processing an epoll_wait/etc that returned hundreds of fds, one
852 # of which is not yet processed and is what we're closing. if we
853 # keep it in DescriptorMap, then the event harnesses can just
854 # looked at $pob->{closed} and ignore it. but if it's an
855 # un-accounted for fd, then it (understandably) freak out a bit
856 # and emit warnings, thinking their state got off.
858 # and finally get rid of our fd so we can't use it anywhere else
862 =head2 C<< $obj->sock() >>
864 Returns the underlying IO::Handle for the object.
868 my PublicInbox::DS $self = shift;
869 return $self->{sock};
872 =head2 C<< $obj->set_writer_func( CODEREF ) >>
874 Sets a function to use instead of C<syswrite()> when writing data to the socket.
877 sub set_writer_func {
878 my PublicInbox::DS $self = shift;
880 Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
881 $self->{writer_func} = $wtr;
884 =head2 C<< $obj->write( $data ) >>
886 Write the specified data to the underlying handle. I<data> may be scalar,
887 scalar ref, code ref (to run when there), or undef just to kick-start.
888 Returns 1 if writes all went through, or 0 if there are writes in queue. If
889 it returns 1, caller should stop waiting for 'writable' events)
893 my PublicInbox::DS $self;
897 # nobody should be writing to closed sockets, but caller code can
898 # do two writes within an event, have the first fail and
899 # disconnect the other side (whose destructor then closes the
900 # calling object, but it's still in a method), and then the
901 # now-dead object does its second write. that is this case. we
902 # just lie and say it worked. it'll be dead soon and won't be
904 return 1 if $self->{closed};
908 # just queue data if there's already a wait
912 $bref = ref $data ? $data : \$data;
913 if ($self->{write_buf_size}) {
914 push @{$self->{write_buf}}, $bref;
915 $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
919 # this flag says we're bypassing the queue system, knowing we're the
920 # only outstanding write, and hoping we don't ever need to use it.
921 # if so later, though, we'll need to queue
927 return 1 unless $bref ||= $self->{write_buf}[0];
931 $len = length($$bref); # this will die if $bref is a code ref, caught below
934 if (UNIVERSAL::isa($bref, "CODE")) {
935 unless ($need_queue) {
936 $self->{write_buf_size}--; # code refs are worth 1
937 shift @{$self->{write_buf}};
941 # code refs are just run and never get reenqueued
942 # (they're one-shot), so turn off the flag indicating the
943 # outstanding data needs queueing.
949 die "Write error: $@ <$bref>";
952 my $to_write = $len - $self->{write_buf_offset};
954 if (my $wtr = $self->{writer_func}) {
955 $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
957 $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
960 if (! defined $written) {
962 return $self->close("EPIPE");
963 } elsif ($! == EAGAIN) {
964 # since connection has stuff to write, it should now be
965 # interested in pending writes:
967 push @{$self->{write_buf}}, $bref;
968 $self->{write_buf_size} += $len;
970 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
971 $self->watch_write(1);
973 } elsif ($! == ECONNRESET) {
974 return $self->close("ECONNRESET");
977 DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
979 return $self->close("write_error");
980 } elsif ($written != $to_write) {
981 DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
982 $written, $self->{fd});
984 push @{$self->{write_buf}}, $bref;
985 $self->{write_buf_size} += $len;
987 # since connection has stuff to write, it should now be
988 # interested in pending writes:
989 $self->{write_buf_offset} += $written;
990 $self->{write_buf_size} -= $written;
991 $self->on_incomplete_write;
993 } elsif ($written == $to_write) {
994 DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
995 $written, $self->{fd}, $need_queue);
996 $self->{write_buf_offset} = 0;
998 if ($self->{write_set_watch}) {
999 $self->watch_write(0);
1000 $self->{write_set_watch} = 0;
1003 # this was our only write, so we can return immediately
1004 # since we avoided incrementing the buffer size or
1005 # putting it in the buffer. we also know there
1006 # can't be anything else to write.
1007 return 1 if $need_queue;
1009 $self->{write_buf_size} -= $written;
1010 shift @{$self->{write_buf}};
1017 sub on_incomplete_write {
1018 my PublicInbox::DS $self = shift;
1019 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
1020 $self->watch_write(1);
1023 =head2 C<< $obj->push_back_read( $buf ) >>
1025 Push back I<buf> (a scalar or scalarref) into the read stream. Useful if you read
1026 more than you need to and want to return this data on the next "read".
1029 sub push_back_read {
1030 my PublicInbox::DS $self = shift;
1032 push @{$self->{read_push_back}}, ref $buf ? $buf : \$buf;
1033 $PushBackSet{$self->{fd}} = $self;
1036 =head2 C<< $obj->read( $bytecount ) >>
1038 Read at most I<bytecount> bytes from the underlying handle; returns scalar
1039 ref on read, or undef on connection closed.
1043 my PublicInbox::DS $self = shift;
1044 return if $self->{closed};
1047 my $sock = $self->{sock};
1049 if (@{$self->{read_push_back}}) {
1050 $buf = shift @{$self->{read_push_back}};
1051 my $len = length($$buf);
1053 if ($len <= $bytes) {
1054 delete $PushBackSet{$self->{fd}} unless @{$self->{read_push_back}};
1057 # if the pushed back read is too big, we have to split it
1058 my $overflow = substr($$buf, $bytes);
1059 $buf = substr($$buf, 0, $bytes);
1060 unshift @{$self->{read_push_back}}, \$overflow;
1065 # if this is too high, perl quits(!!). reports on mailing lists
1066 # don't seem to point to a universal answer. 5MB worked for some,
1067 # crashed for others. 1MB works for more people. let's go with 1MB
1069 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
1071 my $res = sysread($sock, $buf, $req_bytes, 0);
1072 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
1074 if (! $res && $! != EWOULDBLOCK) {
1075 # catches 0=conn closed or undef=error
1076 DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
1083 =head2 (VIRTUAL) C<< $obj->event_read() >>
1085 Readable event handler. Concrete deriviatives of PublicInbox::DS should
1086 provide an implementation of this. The default implementation will die if
1090 sub event_read { die "Base class event_read called for $_[0]\n"; }
1092 =head2 (VIRTUAL) C<< $obj->event_err() >>
1094 Error event handler. Concrete deriviatives of PublicInbox::DS should
1095 provide an implementation of this. The default implementation will die if
1099 sub event_err { die "Base class event_err called for $_[0]\n"; }
1101 =head2 (VIRTUAL) C<< $obj->event_hup() >>
1103 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
1104 provide an implementation of this. The default implementation will die if
1108 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
1110 =head2 C<< $obj->event_write() >>
1112 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
1113 provide an implementation of this. The default implementation calls
1114 C<write()> with an C<undef>.
1119 $self->write(undef);
1122 =head2 C<< $obj->watch_read( $boolean ) >>
1124 Turn 'readable' event notification on or off.
1128 my PublicInbox::DS $self = shift;
1129 return if $self->{closed} || !$self->{sock};
1132 my $event = $self->{event_watch};
1134 $event &= ~POLLIN if ! $val;
1135 $event |= POLLIN if $val;
1137 # If it changed, set it
1138 if ($event != $self->{event_watch}) {
1140 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
1141 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1143 elsif ($HaveEpoll) {
1144 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1145 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1146 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1148 $self->{event_watch} = $event;
1152 =head2 C<< $obj->watch_write( $boolean ) >>
1154 Turn 'writable' event notification on or off.
1158 my PublicInbox::DS $self = shift;
1159 return if $self->{closed} || !$self->{sock};
1162 my $event = $self->{event_watch};
1164 $event &= ~POLLOUT if ! $val;
1165 $event |= POLLOUT if $val;
1167 if ($val && caller ne __PACKAGE__) {
1168 # A subclass registered interest, it's now responsible for this.
1169 $self->{write_set_watch} = 0;
1172 # If it changed, set it
1173 if ($event != $self->{event_watch}) {
1175 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
1176 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1178 elsif ($HaveEpoll) {
1179 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1180 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1181 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1183 $self->{event_watch} = $event;
1187 =head2 C<< $obj->dump_error( $message ) >>
1189 Prints to STDERR a backtrace with information about this socket and what lead
1190 up to the dump_error call.
1196 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
1197 push @list, "\t$file:$line called $sub\n";
1200 warn "ERROR: $_[1]\n" .
1201 "\t$_[0] = " . $_[0]->as_string . "\n" .
1205 =head2 C<< $obj->debugmsg( $format, @args ) >>
1207 Print the debugging message specified by the C<sprintf>-style I<format> and
1212 my ( $self, $fmt, @args ) = @_;
1213 confess "Not an object" unless ref $self;
1216 printf STDERR ">>> $fmt\n", @args;
1220 =head2 C<< $obj->peer_ip_string() >>
1222 Returns the string describing the peer's IP
1225 sub peer_ip_string {
1226 my PublicInbox::DS $self = shift;
1227 return _undef("peer_ip_string undef: no sock") unless $self->{sock};
1228 return $self->{peer_ip} if defined $self->{peer_ip};
1230 my $pn = getpeername($self->{sock});
1231 return _undef("peer_ip_string undef: getpeername") unless $pn;
1233 my ($port, $iaddr) = eval {
1234 if (length($pn) >= 28) {
1235 return Socket6::unpack_sockaddr_in6($pn);
1237 return Socket::sockaddr_in($pn);
1242 $self->{peer_port} = "[Unknown peerport '$@']";
1243 return "[Unknown peername '$@']";
1246 $self->{peer_port} = $port;
1248 if (length($iaddr) == 4) {
1249 return $self->{peer_ip} = Socket::inet_ntoa($iaddr);
1251 $self->{peer_v6} = 1;
1252 return $self->{peer_ip} = Socket6::inet_ntop(Socket6::AF_INET6(),
1257 =head2 C<< $obj->peer_addr_string() >>
1259 Returns the string describing the peer for the socket which underlies this
1260 object in form "ip:port"
1263 sub peer_addr_string {
1264 my PublicInbox::DS $self = shift;
1265 my $ip = $self->peer_ip_string
1267 return $self->{peer_v6} ?
1268 "[$ip]:$self->{peer_port}" :
1269 "$ip:$self->{peer_port}";
1272 =head2 C<< $obj->local_ip_string() >>
1274 Returns the string describing the local IP
1277 sub local_ip_string {
1278 my PublicInbox::DS $self = shift;
1279 return _undef("local_ip_string undef: no sock") unless $self->{sock};
1280 return $self->{local_ip} if defined $self->{local_ip};
1282 my $pn = getsockname($self->{sock});
1283 return _undef("local_ip_string undef: getsockname") unless $pn;
1285 my ($port, $iaddr) = Socket::sockaddr_in($pn);
1286 $self->{local_port} = $port;
1288 return $self->{local_ip} = Socket::inet_ntoa($iaddr);
1291 =head2 C<< $obj->local_addr_string() >>
1293 Returns the string describing the local end of the socket which underlies this
1294 object in form "ip:port"
1297 sub local_addr_string {
1298 my PublicInbox::DS $self = shift;
1299 my $ip = $self->local_ip_string;
1300 return $ip ? "$ip:$self->{local_port}" : undef;
1304 =head2 C<< $obj->as_string() >>
1306 Returns a string describing this socket.
1310 my PublicInbox::DS $self = shift;
1311 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1312 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1313 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1314 my $peer = $self->peer_addr_string;
1316 $ret .= " to " . $self->peer_addr_string;
1322 return undef unless $ENV{DS_DEBUG};
1323 my $msg = shift || "";
1324 warn "PublicInbox::DS: $msg\n";
1328 package PublicInbox::DS::Timer;
1329 # [$abs_float_firetime, $coderef];
1336 =head1 AUTHORS (Danga::Socket)
1338 Brad Fitzpatrick <brad@danga.com> - author
1340 Michael Granger <ged@danga.com> - docs, testing
1342 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1344 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits