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
83 #####################################################################
84 ### C L A S S M E T H O D S
85 #####################################################################
87 =head2 C<< CLASS->Reset() >>
97 $LoopTimeout = -1; # no timeout by default
102 $PostLoopCallback = undef;
106 POSIX::close($Epoll) if defined $Epoll && $Epoll >= 0;
107 POSIX::close($KQueue) if defined $KQueue && $KQueue >= 0;
109 *EventLoop = *FirstTimeEventLoop;
112 =head2 C<< CLASS->HaveEpoll() >>
114 Returns a true value if this class will use IO::Epoll for async IO.
122 =head2 C<< CLASS->WatchedSockets() >>
124 Returns the number of file descriptors which are registered with the global
129 return scalar keys %DescriptorMap;
131 *watched_sockets = *WatchedSockets;
133 =head2 C<< CLASS->EnableProfiling() >>
135 Turns profiling on, clearing current profiling data.
138 sub EnableProfiling {
139 if ($opt_bsd_resource) {
147 =head2 C<< CLASS->DisableProfiling() >>
149 Turns off profiling, but retains data up to this point
152 sub DisableProfiling {
156 =head2 C<< CLASS->ProfilingData() >>
158 Returns reference to a hash of data in format:
160 ITEM => [ utime, stime, #calls ]
167 =head2 C<< CLASS->ToClose() >>
169 Return the list of sockets that are awaiting close() at the end of the
173 sub ToClose { return @ToClose; }
175 =head2 C<< CLASS->OtherFds( [%fdmap] ) >>
177 Get/set the hash of file descriptors that need processing in parallel with
178 the registered PublicInbox::DS objects.
183 if ( @_ ) { %OtherFds = @_ }
184 return wantarray ? %OtherFds : \%OtherFds;
187 =head2 C<< CLASS->AddOtherFds( [%fdmap] ) >>
189 Add fds to the OtherFds hash for processing.
194 %OtherFds = ( %OtherFds, @_ ); # FIXME investigate what happens on dupe fds
195 return wantarray ? %OtherFds : \%OtherFds;
198 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
200 Set the loop timeout for the event loop to some value in milliseconds.
202 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
207 return $LoopTimeout = $_[1] + 0;
210 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
212 Print the debugging message specified by the C<sprintf>-style I<format> and
217 my ( $class, $fmt, @args ) = @_;
219 printf STDERR ">>> $fmt\n", @args;
222 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
224 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
225 are not guaranteed to fire at the exact time you ask for.
227 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
232 my ($secs, $coderef) = @_;
234 my $fire_time = Time::HiRes::time() + $secs;
236 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
238 if (!@Timers || $fire_time >= $Timers[-1][0]) {
239 push @Timers, $timer;
243 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
244 # but it was compared against calendar queues, heaps, naive push/sort,
245 # and a bunch of other versions, and found to be fastest with a large
246 # variety of datasets.)
247 for (my $i = 0; $i < @Timers; $i++) {
248 if ($Timers[$i][0] > $fire_time) {
249 splice(@Timers, $i, 0, $timer);
254 die "Shouldn't get here.";
257 =head2 C<< CLASS->DescriptorMap() >>
259 Get the hash of PublicInbox::DS objects keyed by the file descriptor (fileno) they
262 Returns a hash in list context or a hashref in scalar context.
266 return wantarray ? %DescriptorMap : \%DescriptorMap;
268 *descriptor_map = *DescriptorMap;
269 *get_sock_ref = *DescriptorMap;
277 $KQueue = IO::KQueue->new();
278 $HaveKQueue = $KQueue >= 0;
280 *EventLoop = *KQueueEventLoop;
283 elsif (PublicInbox::Syscall::epoll_defined()) {
284 $Epoll = eval { epoll_create(1024); };
285 $HaveEpoll = defined $Epoll && $Epoll >= 0;
287 *EventLoop = *EpollEventLoop;
291 if (!$HaveEpoll && !$HaveKQueue) {
293 *EventLoop = *PollEventLoop;
297 =head2 C<< CLASS->EventLoop() >>
299 Start processing IO events. In most daemon programs this never exits. See
300 C<PostLoopCallback> below for how to exit the loop.
303 sub FirstTimeEventLoop {
309 EpollEventLoop($class);
310 } elsif ($HaveKQueue) {
311 KQueueEventLoop($class);
313 PollEventLoop($class);
317 ## profiling-related data/functions
318 our ($Prof_utime0, $Prof_stime0);
320 ($Prof_utime0, $Prof_stime0) = getrusage();
324 # get post information
325 my ($autime, $astime) = getrusage();
327 # calculate differences
328 my $utime = $autime - $Prof_utime0;
329 my $stime = $astime - $Prof_stime0;
332 $Profiling{$k} ||= [ 0.0, 0.0, 0 ];
333 $Profiling{$k}->[0] += $utime;
334 $Profiling{$k}->[1] += $stime;
335 $Profiling{$k}->[2]++;
339 # runs timers and returns milliseconds for next one, or next event loop
341 return $LoopTimeout unless @Timers;
343 my $now = Time::HiRes::time();
346 while (@Timers && $Timers[0][0] <= $now) {
347 my $to_run = shift(@Timers);
348 $to_run->[1]->($now) if $to_run->[1];
351 return $LoopTimeout unless @Timers;
353 # convert time to an even number of milliseconds, adding 1
354 # extra, otherwise floating point fun can occur and we'll
355 # call RunTimers like 20-30 times, each returning a timeout
356 # of 0.0000212 seconds
357 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
359 # -1 is an infinite timeout, so prefer a real timeout
360 return $timeout if $LoopTimeout == -1;
362 # otherwise pick the lower of our regular timeout and time until
364 return $LoopTimeout if $LoopTimeout < $timeout;
368 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
373 foreach my $fd ( keys %OtherFds ) {
374 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, EPOLLIN) == -1) {
375 warn "epoll_ctl(): failure adding fd=$fd; $! (", $!+0, ")\n";
382 my $timeout = RunTimers();
384 # get up to 1000 events
385 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
387 for ($i=0; $i<$evcount; $i++) {
388 my $ev = $events[$i];
390 # it's possible epoll_wait returned many events, including some at the end
391 # that ones in the front triggered unregister-interest actions. if we
392 # can't find the %sock entry, it's because we're no longer interested
394 my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
396 my $state = $ev->[1];
398 # if we didn't find a Perlbal::Socket subclass for that fd, try other
399 # pseudo-registered (above) fds.
401 if (my $code = $OtherFds{$ev->[0]}) {
405 warn "epoll() returned fd $fd w/ state $state for which we have no mapping. removing.\n";
407 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
412 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
413 $ev->[0], ref($pob), $ev->[1], time);
416 my $class = ref $pob;
418 # call profiling action on things that need to be done
419 if ($state & EPOLLIN && ! $pob->{closed}) {
422 _post_profile("$class-read");
425 if ($state & EPOLLOUT && ! $pob->{closed}) {
428 _post_profile("$class-write");
431 if ($state & (EPOLLERR|EPOLLHUP)) {
432 if ($state & EPOLLERR && ! $pob->{closed}) {
435 _post_profile("$class-err");
437 if ($state & EPOLLHUP && ! $pob->{closed}) {
440 _post_profile("$class-hup");
447 # standard non-profiling codepat
448 $pob->event_read if $state & EPOLLIN && ! $pob->{closed};
449 $pob->event_write if $state & EPOLLOUT && ! $pob->{closed};
450 if ($state & (EPOLLERR|EPOLLHUP)) {
451 $pob->event_err if $state & EPOLLERR && ! $pob->{closed};
452 $pob->event_hup if $state & EPOLLHUP && ! $pob->{closed};
455 return unless PostEventLoop();
460 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
461 ### IO::Epoll fails to load.
465 my PublicInbox::DS $pob;
468 my $timeout = RunTimers();
470 # the following sets up @poll as a series of ($poll,$event_mask)
471 # items, then uses IO::Poll::_poll, implemented in XS, which
472 # modifies the array in place with the even elements being
473 # replaced with the event masks that occured.
475 foreach my $fd ( keys %OtherFds ) {
476 push @poll, $fd, POLLIN;
478 while ( my ($fd, $sock) = each %DescriptorMap ) {
479 push @poll, $fd, $sock->{event_watch};
482 # if nothing to poll, either end immediately (if no timeout)
483 # or just keep calling the callback
485 select undef, undef, undef, ($timeout / 1000);
486 return unless PostEventLoop();
490 my $count = IO::Poll::_poll($timeout, @poll);
492 return unless PostEventLoop();
496 # Fetch handles with read events
498 my ($fd, $state) = splice(@poll, 0, 2);
501 $pob = $DescriptorMap{$fd};
504 if (my $code = $OtherFds{$fd}) {
510 $pob->event_read if $state & POLLIN && ! $pob->{closed};
511 $pob->event_write if $state & POLLOUT && ! $pob->{closed};
512 $pob->event_err if $state & POLLERR && ! $pob->{closed};
513 $pob->event_hup if $state & POLLHUP && ! $pob->{closed};
516 return unless PostEventLoop();
522 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
524 sub KQueueEventLoop {
527 foreach my $fd (keys %OtherFds) {
528 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(), IO::KQueue::EV_ADD());
532 my $timeout = RunTimers();
533 my @ret = $KQueue->kevent($timeout);
535 foreach my $kev (@ret) {
536 my ($fd, $filter, $flags, $fflags) = @$kev;
537 my PublicInbox::DS $pob = $DescriptorMap{$fd};
539 if (my $code = $OtherFds{$fd}) {
542 warn "kevent() returned fd $fd for which we have no mapping. removing.\n";
543 POSIX::close($fd); # close deletes the kevent entry
548 DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
549 $fd, ref($pob), $flags, time);
551 $pob->event_read if $filter == IO::KQueue::EVFILT_READ() && !$pob->{closed};
552 $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
553 if ($flags == IO::KQueue::EV_EOF() && !$pob->{closed}) {
561 return unless PostEventLoop();
567 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
569 Sets post loop callback function. Pass a subref and it will be
570 called every time the event loop finishes.
572 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
575 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
578 sub SetPostLoopCallback {
579 my ($class, $ref) = @_;
582 # per-object callback
583 my PublicInbox::DS $self = $class;
584 if (defined $ref && ref $ref eq 'CODE') {
585 $PLCMap{$self->{fd}} = $ref;
587 delete $PLCMap{$self->{fd}};
591 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
595 # Internal function: run the post-event callback, send read events
596 # for pushed-back data, and close pending connections. returns 1
597 # if event loop should continue, or 0 to shut it all down.
599 # fire read events for objects with pushed-back read data
603 foreach my $fd (keys %PushBackSet) {
604 my PublicInbox::DS $pob = $PushBackSet{$fd};
606 # a previous event_read invocation could've closed a
607 # connection that we already evaluated in "keys
608 # %PushBackSet", so skip ones that seem to have
609 # disappeared. this is expected.
612 die "ASSERT: the $pob socket has no read_push_back" unless @{$pob->{read_push_back}};
613 next unless (! $pob->{closed} &&
614 $pob->{event_watch} & POLLIN);
620 # now we can close sockets that wanted to close during our event processing.
621 # (we didn't want to close them during the loop, as we didn't want fd numbers
622 # being reused and confused during the event loop)
623 while (my $sock = shift @ToClose) {
624 my $fd = fileno($sock);
626 # close the socket. (not a PublicInbox::DS close)
629 # and now we can finally remove the fd from the map. see
630 # comment above in _cleanup.
631 delete $DescriptorMap{$fd};
635 # by default we keep running, unless a postloop callback (either per-object
636 # or global) cancels it
637 my $keep_running = 1;
639 # per-object post-loop-callbacks
640 for my $plc (values %PLCMap) {
641 $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
644 # now we're at the very end, call callback if defined
645 if (defined $PostLoopCallback) {
646 $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
649 return $keep_running;
652 #####################################################################
653 ### PublicInbox::DS-the-object code
654 #####################################################################
656 =head2 OBJECT METHODS
658 =head2 C<< CLASS->new( $socket ) >>
660 Create a new PublicInbox::DS subclass object for the given I<socket> which will
661 react to events on it during the C<EventLoop>.
663 This is normally (always?) called from your subclass via:
665 $class->SUPER::new($socket);
669 my PublicInbox::DS $self = shift;
670 $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 $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
693 epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $self->{event_watch})
694 and die "couldn't add epoll watch for $fd\n";
696 elsif ($HaveKQueue) {
697 # Add them to the queue but disabled for now
698 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
699 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
700 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
701 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
704 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
705 if $DescriptorMap{$fd};
707 $DescriptorMap{$fd} = $self;
712 #####################################################################
713 ### I N S T A N C E M E T H O D S
714 #####################################################################
716 =head2 C<< $obj->tcp_cork( $boolean ) >>
718 Turn TCP_CORK on or off depending on the value of I<boolean>.
722 my PublicInbox::DS $self = $_[0];
725 # make sure we have a socket
726 return unless $self->{sock};
727 return if $val == $self->{corked};
731 $rv = setsockopt($self->{sock}, IPPROTO_TCP, TCP_CORK,
732 pack("l", $val ? 1 : 0));
734 # FIXME: implement freebsd *PUSH sockopts
738 # if we failed, close (if we're not already) and warn about the error
740 $self->{corked} = $val;
742 if ($! == EBADF || $! == ENOTSOCK) {
743 # internal state is probably corrupted; warn and then close if
744 # we're not closed already
745 warn "setsockopt: $!";
746 $self->close('tcp_cork_failed');
747 } elsif ($! == ENOPROTOOPT || $!{ENOTSOCK} || $!{EOPNOTSUPP}) {
748 # TCP implementation doesn't support corking, so just ignore it
749 # or we're trying to tcp-cork a non-socket (like a socketpair pipe
750 # which is acting like a socket, which Perlbal does for child
751 # processes acting like inetd-like web servers)
753 # some other error; we should never hit here, but if we do, die
754 die "setsockopt: $!";
759 =head2 C<< $obj->steal_socket() >>
761 Basically returns our socket and makes it so that we don't try to close it,
762 but we do remove it from epoll handlers. THIS CLOSES $self. It is the same
763 thing as calling close, except it gives you the socket to use.
767 my PublicInbox::DS $self = $_[0];
768 return if $self->{closed};
770 # cleanup does most of the work of closing this socket
773 # now undef our internal sock and fd structures so we don't use them
774 my $sock = $self->{sock};
775 $self->{sock} = undef;
779 =head2 C<< $obj->close( [$reason] ) >>
781 Close the socket. The I<reason> argument will be used in debugging messages.
785 my PublicInbox::DS $self = $_[0];
786 return if $self->{closed};
788 # print out debugging info for this close
790 my ($pkg, $filename, $line) = caller;
791 my $reason = $_[1] || "";
792 warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
795 # this does most of the work of closing us
798 # defer closing the actual socket until the event loop is done
799 # processing this round of events. (otherwise we might reuse fds)
801 push @ToClose, $self->{sock};
802 $self->{sock} = undef;
808 ### METHOD: _cleanup()
809 ### Called by our closers so we can clean internal data structures.
811 my PublicInbox::DS $self = $_[0];
813 # we're effectively closed; we have no fd and sock when we leave here
816 # we need to flush our write buffer, as there may
817 # be self-referential closures (sub { $client->close })
818 # preventing the object from being destroyed
819 $self->{write_buf} = [];
821 # uncork so any final data gets sent. only matters if the person closing
822 # us forgot to do it, but we do it to be safe.
825 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
826 # notifications about it
827 if ($HaveEpoll && $self->{fd}) {
828 if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
829 # dump_error prints a backtrace so we can try to figure out why this happened
830 $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
834 # now delete from mappings. this fd no longer belongs to us, so we don't want
835 # to get alerts for it if it becomes writable/readable/etc.
836 delete $PushBackSet{$self->{fd}};
837 delete $PLCMap{$self->{fd}};
839 # we explicitly don't delete from DescriptorMap here until we
840 # actually close the socket, as we might be in the middle of
841 # processing an epoll_wait/etc that returned hundreds of fds, one
842 # of which is not yet processed and is what we're closing. if we
843 # keep it in DescriptorMap, then the event harnesses can just
844 # looked at $pob->{closed} and ignore it. but if it's an
845 # un-accounted for fd, then it (understandably) freak out a bit
846 # and emit warnings, thinking their state got off.
848 # and finally get rid of our fd so we can't use it anywhere else
852 =head2 C<< $obj->sock() >>
854 Returns the underlying IO::Handle for the object.
858 my PublicInbox::DS $self = shift;
859 return $self->{sock};
862 =head2 C<< $obj->set_writer_func( CODEREF ) >>
864 Sets a function to use instead of C<syswrite()> when writing data to the socket.
867 sub set_writer_func {
868 my PublicInbox::DS $self = shift;
870 Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
871 $self->{writer_func} = $wtr;
874 =head2 C<< $obj->write( $data ) >>
876 Write the specified data to the underlying handle. I<data> may be scalar,
877 scalar ref, code ref (to run when there), or undef just to kick-start.
878 Returns 1 if writes all went through, or 0 if there are writes in queue. If
879 it returns 1, caller should stop waiting for 'writable' events)
883 my PublicInbox::DS $self;
887 # nobody should be writing to closed sockets, but caller code can
888 # do two writes within an event, have the first fail and
889 # disconnect the other side (whose destructor then closes the
890 # calling object, but it's still in a method), and then the
891 # now-dead object does its second write. that is this case. we
892 # just lie and say it worked. it'll be dead soon and won't be
894 return 1 if $self->{closed};
898 # just queue data if there's already a wait
902 $bref = ref $data ? $data : \$data;
903 if ($self->{write_buf_size}) {
904 push @{$self->{write_buf}}, $bref;
905 $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
909 # this flag says we're bypassing the queue system, knowing we're the
910 # only outstanding write, and hoping we don't ever need to use it.
911 # if so later, though, we'll need to queue
917 return 1 unless $bref ||= $self->{write_buf}[0];
921 $len = length($$bref); # this will die if $bref is a code ref, caught below
924 if (UNIVERSAL::isa($bref, "CODE")) {
925 unless ($need_queue) {
926 $self->{write_buf_size}--; # code refs are worth 1
927 shift @{$self->{write_buf}};
931 # code refs are just run and never get reenqueued
932 # (they're one-shot), so turn off the flag indicating the
933 # outstanding data needs queueing.
939 die "Write error: $@ <$bref>";
942 my $to_write = $len - $self->{write_buf_offset};
944 if (my $wtr = $self->{writer_func}) {
945 $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
947 $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
950 if (! defined $written) {
952 return $self->close("EPIPE");
953 } elsif ($! == EAGAIN) {
954 # since connection has stuff to write, it should now be
955 # interested in pending writes:
957 push @{$self->{write_buf}}, $bref;
958 $self->{write_buf_size} += $len;
960 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
961 $self->watch_write(1);
963 } elsif ($! == ECONNRESET) {
964 return $self->close("ECONNRESET");
967 DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
969 return $self->close("write_error");
970 } elsif ($written != $to_write) {
971 DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
972 $written, $self->{fd});
974 push @{$self->{write_buf}}, $bref;
975 $self->{write_buf_size} += $len;
977 # since connection has stuff to write, it should now be
978 # interested in pending writes:
979 $self->{write_buf_offset} += $written;
980 $self->{write_buf_size} -= $written;
981 $self->on_incomplete_write;
983 } elsif ($written == $to_write) {
984 DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
985 $written, $self->{fd}, $need_queue);
986 $self->{write_buf_offset} = 0;
988 if ($self->{write_set_watch}) {
989 $self->watch_write(0);
990 $self->{write_set_watch} = 0;
993 # this was our only write, so we can return immediately
994 # since we avoided incrementing the buffer size or
995 # putting it in the buffer. we also know there
996 # can't be anything else to write.
997 return 1 if $need_queue;
999 $self->{write_buf_size} -= $written;
1000 shift @{$self->{write_buf}};
1007 sub on_incomplete_write {
1008 my PublicInbox::DS $self = shift;
1009 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
1010 $self->watch_write(1);
1013 =head2 C<< $obj->push_back_read( $buf ) >>
1015 Push back I<buf> (a scalar or scalarref) into the read stream. Useful if you read
1016 more than you need to and want to return this data on the next "read".
1019 sub push_back_read {
1020 my PublicInbox::DS $self = shift;
1022 push @{$self->{read_push_back}}, ref $buf ? $buf : \$buf;
1023 $PushBackSet{$self->{fd}} = $self;
1026 =head2 C<< $obj->read( $bytecount ) >>
1028 Read at most I<bytecount> bytes from the underlying handle; returns scalar
1029 ref on read, or undef on connection closed.
1033 my PublicInbox::DS $self = shift;
1034 return if $self->{closed};
1037 my $sock = $self->{sock};
1039 if (@{$self->{read_push_back}}) {
1040 $buf = shift @{$self->{read_push_back}};
1041 my $len = length($$buf);
1043 if ($len <= $bytes) {
1044 delete $PushBackSet{$self->{fd}} unless @{$self->{read_push_back}};
1047 # if the pushed back read is too big, we have to split it
1048 my $overflow = substr($$buf, $bytes);
1049 $buf = substr($$buf, 0, $bytes);
1050 unshift @{$self->{read_push_back}}, \$overflow;
1055 # if this is too high, perl quits(!!). reports on mailing lists
1056 # don't seem to point to a universal answer. 5MB worked for some,
1057 # crashed for others. 1MB works for more people. let's go with 1MB
1059 my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
1061 my $res = sysread($sock, $buf, $req_bytes, 0);
1062 DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
1064 if (! $res && $! != EWOULDBLOCK) {
1065 # catches 0=conn closed or undef=error
1066 DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
1073 =head2 (VIRTUAL) C<< $obj->event_read() >>
1075 Readable event handler. Concrete deriviatives of PublicInbox::DS should
1076 provide an implementation of this. The default implementation will die if
1080 sub event_read { die "Base class event_read called for $_[0]\n"; }
1082 =head2 (VIRTUAL) C<< $obj->event_err() >>
1084 Error event handler. Concrete deriviatives of PublicInbox::DS should
1085 provide an implementation of this. The default implementation will die if
1089 sub event_err { die "Base class event_err called for $_[0]\n"; }
1091 =head2 (VIRTUAL) C<< $obj->event_hup() >>
1093 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
1094 provide an implementation of this. The default implementation will die if
1098 sub event_hup { die "Base class event_hup called for $_[0]\n"; }
1100 =head2 C<< $obj->event_write() >>
1102 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
1103 provide an implementation of this. The default implementation calls
1104 C<write()> with an C<undef>.
1109 $self->write(undef);
1112 =head2 C<< $obj->watch_read( $boolean ) >>
1114 Turn 'readable' event notification on or off.
1118 my PublicInbox::DS $self = shift;
1119 return if $self->{closed} || !$self->{sock};
1122 my $event = $self->{event_watch};
1124 $event &= ~POLLIN if ! $val;
1125 $event |= POLLIN if $val;
1127 # If it changed, set it
1128 if ($event != $self->{event_watch}) {
1130 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
1131 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1133 elsif ($HaveEpoll) {
1134 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1135 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1136 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1138 $self->{event_watch} = $event;
1142 =head2 C<< $obj->watch_write( $boolean ) >>
1144 Turn 'writable' event notification on or off.
1148 my PublicInbox::DS $self = shift;
1149 return if $self->{closed} || !$self->{sock};
1152 my $event = $self->{event_watch};
1154 $event &= ~POLLOUT if ! $val;
1155 $event |= POLLOUT if $val;
1157 if ($val && caller ne __PACKAGE__) {
1158 # A subclass registered interest, it's now responsible for this.
1159 $self->{write_set_watch} = 0;
1162 # If it changed, set it
1163 if ($event != $self->{event_watch}) {
1165 $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
1166 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1168 elsif ($HaveEpoll) {
1169 epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1170 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1171 "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1173 $self->{event_watch} = $event;
1177 =head2 C<< $obj->dump_error( $message ) >>
1179 Prints to STDERR a backtrace with information about this socket and what lead
1180 up to the dump_error call.
1186 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
1187 push @list, "\t$file:$line called $sub\n";
1190 warn "ERROR: $_[1]\n" .
1191 "\t$_[0] = " . $_[0]->as_string . "\n" .
1195 =head2 C<< $obj->debugmsg( $format, @args ) >>
1197 Print the debugging message specified by the C<sprintf>-style I<format> and
1202 my ( $self, $fmt, @args ) = @_;
1203 confess "Not an object" unless ref $self;
1206 printf STDERR ">>> $fmt\n", @args;
1210 =head2 C<< $obj->peer_ip_string() >>
1212 Returns the string describing the peer's IP
1215 sub peer_ip_string {
1216 my PublicInbox::DS $self = shift;
1217 return _undef("peer_ip_string undef: no sock") unless $self->{sock};
1218 return $self->{peer_ip} if defined $self->{peer_ip};
1220 my $pn = getpeername($self->{sock});
1221 return _undef("peer_ip_string undef: getpeername") unless $pn;
1223 my ($port, $iaddr) = eval {
1224 if (length($pn) >= 28) {
1225 return Socket6::unpack_sockaddr_in6($pn);
1227 return Socket::sockaddr_in($pn);
1232 $self->{peer_port} = "[Unknown peerport '$@']";
1233 return "[Unknown peername '$@']";
1236 $self->{peer_port} = $port;
1238 if (length($iaddr) == 4) {
1239 return $self->{peer_ip} = Socket::inet_ntoa($iaddr);
1241 $self->{peer_v6} = 1;
1242 return $self->{peer_ip} = Socket6::inet_ntop(Socket6::AF_INET6(),
1247 =head2 C<< $obj->peer_addr_string() >>
1249 Returns the string describing the peer for the socket which underlies this
1250 object in form "ip:port"
1253 sub peer_addr_string {
1254 my PublicInbox::DS $self = shift;
1255 my $ip = $self->peer_ip_string
1257 return $self->{peer_v6} ?
1258 "[$ip]:$self->{peer_port}" :
1259 "$ip:$self->{peer_port}";
1262 =head2 C<< $obj->local_ip_string() >>
1264 Returns the string describing the local IP
1267 sub local_ip_string {
1268 my PublicInbox::DS $self = shift;
1269 return _undef("local_ip_string undef: no sock") unless $self->{sock};
1270 return $self->{local_ip} if defined $self->{local_ip};
1272 my $pn = getsockname($self->{sock});
1273 return _undef("local_ip_string undef: getsockname") unless $pn;
1275 my ($port, $iaddr) = Socket::sockaddr_in($pn);
1276 $self->{local_port} = $port;
1278 return $self->{local_ip} = Socket::inet_ntoa($iaddr);
1281 =head2 C<< $obj->local_addr_string() >>
1283 Returns the string describing the local end of the socket which underlies this
1284 object in form "ip:port"
1287 sub local_addr_string {
1288 my PublicInbox::DS $self = shift;
1289 my $ip = $self->local_ip_string;
1290 return $ip ? "$ip:$self->{local_port}" : undef;
1294 =head2 C<< $obj->as_string() >>
1296 Returns a string describing this socket.
1300 my PublicInbox::DS $self = shift;
1301 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1302 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1303 my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1304 my $peer = $self->peer_addr_string;
1306 $ret .= " to " . $self->peer_addr_string;
1312 return undef unless $ENV{DS_DEBUG};
1313 my $msg = shift || "";
1314 warn "PublicInbox::DS: $msg\n";
1318 package PublicInbox::DS::Timer;
1319 # [$abs_float_firetime, $coderef];
1326 =head1 AUTHORS (Danga::Socket)
1328 Brad Fitzpatrick <brad@danga.com> - author
1330 Michael Granger <ged@danga.com> - docs, testing
1332 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1334 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits