]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: fix and test for FD leaks with kqueue on ->Reset
[public-inbox.git] / lib / PublicInbox / DS.pm
1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
3 #
4 # This license differs from the rest of public-inbox
5 #
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
9
10 package PublicInbox::DS;
11 use strict;
12 use bytes;
13 use POSIX ();
14 use Time::HiRes ();
15 use IO::Handle qw();
16 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
17
18 use warnings;
19
20 use PublicInbox::Syscall qw(:epoll);
21
22 use fields ('sock',              # underlying socket
23             'fd',                # numeric file descriptor
24             'write_buf',         # arrayref of scalars, scalarrefs, or coderefs to write
25             'write_buf_offset',  # offset into first array of write_buf to start writing at
26             'write_buf_size',    # total length of data in all write_buf items
27             'write_set_watch',   # bool: true if we internally set watch_write rather than by a subclass
28             'closed',            # bool: socket is closed
29             'event_watch',       # bitmask of events the client is interested in (POLLIN,OUT,etc.)
30             'writer_func',       # subref which does writing.  must return bytes written (or undef) and set $! on errors
31             );
32
33 use Errno  qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
34               EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
35 use Carp   qw(croak confess);
36
37 use constant DebugLevel => 0;
38
39 use constant POLLIN        => 1;
40 use constant POLLOUT       => 4;
41 use constant POLLERR       => 8;
42 use constant POLLHUP       => 16;
43 use constant POLLNVAL      => 32;
44
45 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
46
47 our (
48      $HaveEpoll,                 # Flag -- is epoll available?  initially undefined.
49      $HaveKQueue,
50      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
51      $Epoll,                     # Global epoll fd (for epoll mode only)
52      $KQueue,                    # Global kqueue fd ref (for kqueue mode only)
53      $_io,                       # IO::Handle for Epoll
54      @ToClose,                   # sockets to close when event loop is done
55
56      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
57      %PLCMap,                    # fd (num) -> PostLoopCallback (per-object)
58
59      $LoopTimeout,               # timeout of event loop in milliseconds
60      $DoneInit,                  # if we've done the one-time module init yet
61      @Timers,                    # timers
62      );
63
64 # this may be set to zero with old kernels
65 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
66 Reset();
67
68 #####################################################################
69 ### C L A S S   M E T H O D S
70 #####################################################################
71
72 =head2 C<< CLASS->Reset() >>
73
74 Reset all state
75
76 =cut
77 sub Reset {
78     %DescriptorMap = ();
79     @ToClose = ();
80     $LoopTimeout = -1;  # no timeout by default
81     @Timers = ();
82
83     $PostLoopCallback = undef;
84     %PLCMap = ();
85     $DoneInit = 0;
86
87     # NOTE kqueue is close-on-fork, and we don't account for it, yet
88     # OTOH, we (public-inbox) don't need this sub outside of tests...
89     POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
90     $KQueue = undef;
91
92     $_io = undef; # close $Epoll
93     $Epoll = undef;
94
95     *EventLoop = *FirstTimeEventLoop;
96 }
97
98 =head2 C<< CLASS->HaveEpoll() >>
99
100 Returns a true value if this class will use IO::Epoll for async IO.
101
102 =cut
103 sub HaveEpoll {
104     _InitPoller();
105     return $HaveEpoll;
106 }
107
108 =head2 C<< CLASS->ToClose() >>
109
110 Return the list of sockets that are awaiting close() at the end of the
111 current event loop.
112
113 =cut
114 sub ToClose { return @ToClose; }
115
116 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
117
118 Set the loop timeout for the event loop to some value in milliseconds.
119
120 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
121 immediately.
122
123 =cut
124 sub SetLoopTimeout {
125     return $LoopTimeout = $_[1] + 0;
126 }
127
128 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
129
130 Print the debugging message specified by the C<sprintf>-style I<format> and
131 I<args>
132
133 =cut
134 sub DebugMsg {
135     my ( $class, $fmt, @args ) = @_;
136     chomp $fmt;
137     printf STDERR ">>> $fmt\n", @args;
138 }
139
140 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
141
142 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
143 are not guaranteed to fire at the exact time you ask for.
144
145 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
146
147 =cut
148 sub AddTimer {
149     my $class = shift;
150     my ($secs, $coderef) = @_;
151
152     my $fire_time = Time::HiRes::time() + $secs;
153
154     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
155
156     if (!@Timers || $fire_time >= $Timers[-1][0]) {
157         push @Timers, $timer;
158         return $timer;
159     }
160
161     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
162     # but it was compared against calendar queues, heaps, naive push/sort,
163     # and a bunch of other versions, and found to be fastest with a large
164     # variety of datasets.)
165     for (my $i = 0; $i < @Timers; $i++) {
166         if ($Timers[$i][0] > $fire_time) {
167             splice(@Timers, $i, 0, $timer);
168             return $timer;
169         }
170     }
171
172     die "Shouldn't get here.";
173 }
174
175 # keeping this around in case we support other FD types for now,
176 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
177 sub set_cloexec ($) {
178     my ($fd) = @_;
179
180     $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
181     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
182     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
183 }
184
185 sub _InitPoller
186 {
187     return if $DoneInit;
188     $DoneInit = 1;
189
190     if ($HAVE_KQUEUE) {
191         $KQueue = IO::KQueue->new();
192         $HaveKQueue = defined $KQueue;
193         if ($HaveKQueue) {
194             *EventLoop = *KQueueEventLoop;
195         }
196     }
197     elsif (PublicInbox::Syscall::epoll_defined()) {
198         $Epoll = eval { epoll_create(1024); };
199         $HaveEpoll = defined $Epoll && $Epoll >= 0;
200         if ($HaveEpoll) {
201             set_cloexec($Epoll);
202             *EventLoop = *EpollEventLoop;
203         }
204     }
205
206     if (!$HaveEpoll && !$HaveKQueue) {
207         require IO::Poll;
208         *EventLoop = *PollEventLoop;
209     }
210 }
211
212 =head2 C<< CLASS->EventLoop() >>
213
214 Start processing IO events. In most daemon programs this never exits. See
215 C<PostLoopCallback> below for how to exit the loop.
216
217 =cut
218 sub FirstTimeEventLoop {
219     my $class = shift;
220
221     _InitPoller();
222
223     if ($HaveEpoll) {
224         EpollEventLoop($class);
225     } elsif ($HaveKQueue) {
226         KQueueEventLoop($class);
227     } else {
228         PollEventLoop($class);
229     }
230 }
231
232 # runs timers and returns milliseconds for next one, or next event loop
233 sub RunTimers {
234     return $LoopTimeout unless @Timers;
235
236     my $now = Time::HiRes::time();
237
238     # Run expired timers
239     while (@Timers && $Timers[0][0] <= $now) {
240         my $to_run = shift(@Timers);
241         $to_run->[1]->($now) if $to_run->[1];
242     }
243
244     return $LoopTimeout unless @Timers;
245
246     # convert time to an even number of milliseconds, adding 1
247     # extra, otherwise floating point fun can occur and we'll
248     # call RunTimers like 20-30 times, each returning a timeout
249     # of 0.0000212 seconds
250     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
251
252     # -1 is an infinite timeout, so prefer a real timeout
253     return $timeout     if $LoopTimeout == -1;
254
255     # otherwise pick the lower of our regular timeout and time until
256     # the next timer
257     return $LoopTimeout if $LoopTimeout < $timeout;
258     return $timeout;
259 }
260
261 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
262 ### okay.
263 sub EpollEventLoop {
264     my $class = shift;
265
266     while (1) {
267         my @events;
268         my $i;
269         my $timeout = RunTimers();
270
271         # get up to 1000 events
272         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
273       EVENT:
274         for ($i=0; $i<$evcount; $i++) {
275             my $ev = $events[$i];
276
277             # it's possible epoll_wait returned many events, including some at the end
278             # that ones in the front triggered unregister-interest actions.  if we
279             # can't find the %sock entry, it's because we're no longer interested
280             # in that event.
281             my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
282             my $code;
283             my $state = $ev->[1];
284
285             # if we didn't find a Perlbal::Socket subclass for that fd, try other
286             # pseudo-registered (above) fds.
287             if (! $pob) {
288                 my $fd = $ev->[0];
289                 warn "epoll() returned fd $fd w/ state $state for which we have no mapping.  removing.\n";
290                 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
291                 POSIX::close($fd);
292                 next;
293             }
294
295             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
296                                                 $ev->[0], ref($pob), $ev->[1], time);
297
298             # standard non-profiling codepat
299             $pob->event_read   if $state & EPOLLIN && ! $pob->{closed};
300             $pob->event_write  if $state & EPOLLOUT && ! $pob->{closed};
301             if ($state & (EPOLLERR|EPOLLHUP)) {
302                 $pob->event_err    if $state & EPOLLERR && ! $pob->{closed};
303                 $pob->event_hup    if $state & EPOLLHUP && ! $pob->{closed};
304             }
305         }
306         return unless PostEventLoop();
307     }
308     exit 0;
309 }
310
311 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
312 ### IO::Epoll fails to load.
313 sub PollEventLoop {
314     my $class = shift;
315
316     my PublicInbox::DS $pob;
317
318     while (1) {
319         my $timeout = RunTimers();
320
321         # the following sets up @poll as a series of ($poll,$event_mask)
322         # items, then uses IO::Poll::_poll, implemented in XS, which
323         # modifies the array in place with the even elements being
324         # replaced with the event masks that occured.
325         my @poll;
326         while ( my ($fd, $sock) = each %DescriptorMap ) {
327             push @poll, $fd, $sock->{event_watch};
328         }
329
330         # if nothing to poll, either end immediately (if no timeout)
331         # or just keep calling the callback
332         unless (@poll) {
333             select undef, undef, undef, ($timeout / 1000);
334             return unless PostEventLoop();
335             next;
336         }
337
338         my $count = IO::Poll::_poll($timeout, @poll);
339         unless ($count >= 0) {
340             return unless PostEventLoop();
341             next;
342         }
343
344         # Fetch handles with read events
345         while (@poll) {
346             my ($fd, $state) = splice(@poll, 0, 2);
347             next unless $state;
348
349             $pob = $DescriptorMap{$fd};
350
351             if (!$pob) {
352                 next;
353             }
354
355             $pob->event_read   if $state & POLLIN && ! $pob->{closed};
356             $pob->event_write  if $state & POLLOUT && ! $pob->{closed};
357             $pob->event_err    if $state & POLLERR && ! $pob->{closed};
358             $pob->event_hup    if $state & POLLHUP && ! $pob->{closed};
359         }
360
361         return unless PostEventLoop();
362     }
363
364     exit 0;
365 }
366
367 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
368 ### okay.
369 sub KQueueEventLoop {
370     my $class = shift;
371
372     while (1) {
373         my $timeout = RunTimers();
374         my @ret = eval { $KQueue->kevent($timeout) };
375         if (my $err = $@) {
376             # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
377             if ($err =~ /Interrupted system call/) {
378                 @ret = ();
379             } else {
380                 die $err;
381             }
382         }
383
384         foreach my $kev (@ret) {
385             my ($fd, $filter, $flags, $fflags) = @$kev;
386             my PublicInbox::DS $pob = $DescriptorMap{$fd};
387             if (!$pob) {
388                 warn "kevent() returned fd $fd for which we have no mapping.  removing.\n";
389                 POSIX::close($fd); # close deletes the kevent entry
390                 next;
391             }
392
393             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
394                                                         $fd, ref($pob), $flags, time);
395
396             $pob->event_read  if $filter == IO::KQueue::EVFILT_READ()  && !$pob->{closed};
397             $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
398             if ($flags ==  IO::KQueue::EV_EOF() && !$pob->{closed}) {
399                 if ($fflags) {
400                     $pob->event_err;
401                 } else {
402                     $pob->event_hup;
403                 }
404             }
405         }
406         return unless PostEventLoop();
407     }
408
409     exit(0);
410 }
411
412 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
413
414 Sets post loop callback function.  Pass a subref and it will be
415 called every time the event loop finishes.
416
417 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
418 and it will exit.
419
420 The callback function will be passed two parameters: \%DescriptorMap
421
422 =cut
423 sub SetPostLoopCallback {
424     my ($class, $ref) = @_;
425
426     if (ref $class) {
427         # per-object callback
428         my PublicInbox::DS $self = $class;
429         if (defined $ref && ref $ref eq 'CODE') {
430             $PLCMap{$self->{fd}} = $ref;
431         } else {
432             delete $PLCMap{$self->{fd}};
433         }
434     } else {
435         # global callback
436         $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
437     }
438 }
439
440 # Internal function: run the post-event callback, send read events
441 # for pushed-back data, and close pending connections.  returns 1
442 # if event loop should continue, or 0 to shut it all down.
443 sub PostEventLoop {
444     # now we can close sockets that wanted to close during our event processing.
445     # (we didn't want to close them during the loop, as we didn't want fd numbers
446     #  being reused and confused during the event loop)
447     while (my $sock = shift @ToClose) {
448         my $fd = fileno($sock);
449
450         # close the socket.  (not a PublicInbox::DS close)
451         $sock->close;
452
453         # and now we can finally remove the fd from the map.  see
454         # comment above in _cleanup.
455         delete $DescriptorMap{$fd};
456     }
457
458
459     # by default we keep running, unless a postloop callback (either per-object
460     # or global) cancels it
461     my $keep_running = 1;
462
463     # per-object post-loop-callbacks
464     for my $plc (values %PLCMap) {
465         $keep_running &&= $plc->(\%DescriptorMap);
466     }
467
468     # now we're at the very end, call callback if defined
469     if (defined $PostLoopCallback) {
470         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
471     }
472
473     return $keep_running;
474 }
475
476 #####################################################################
477 ### PublicInbox::DS-the-object code
478 #####################################################################
479
480 =head2 OBJECT METHODS
481
482 =head2 C<< CLASS->new( $socket ) >>
483
484 Create a new PublicInbox::DS subclass object for the given I<socket> which will
485 react to events on it during the C<EventLoop>.
486
487 This is normally (always?) called from your subclass via:
488
489   $class->SUPER::new($socket);
490
491 =cut
492 sub new {
493     my ($self, $sock, $exclusive) = @_;
494     $self = fields::new($self) unless ref $self;
495
496     $self->{sock}        = $sock;
497     my $fd = fileno($sock);
498
499     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
500         unless $sock && $fd;
501
502     $self->{fd}          = $fd;
503     $self->{write_buf}      = [];
504     $self->{write_buf_offset} = 0;
505     $self->{write_buf_size} = 0;
506     $self->{closed} = 0;
507
508     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
509
510     _InitPoller();
511
512     if ($HaveEpoll) {
513         if ($exclusive) {
514             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
515         }
516 retry:
517         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
518             if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
519                 $EPOLLEXCLUSIVE = 0; # old kernel
520                 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
521                 goto retry;
522             }
523             die "couldn't add epoll watch for $fd: $!\n";
524         }
525     }
526     elsif ($HaveKQueue) {
527         # Add them to the queue but disabled for now
528         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
529                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
530         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
531                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
532     }
533
534     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
535         if $DescriptorMap{$fd};
536
537     $DescriptorMap{$fd} = $self;
538     return $self;
539 }
540
541
542 #####################################################################
543 ### I N S T A N C E   M E T H O D S
544 #####################################################################
545
546 =head2 C<< $obj->steal_socket() >>
547
548 Basically returns our socket and makes it so that we don't try to close it,
549 but we do remove it from epoll handlers.  THIS CLOSES $self.  It is the same
550 thing as calling close, except it gives you the socket to use.
551
552 =cut
553 sub steal_socket {
554     my PublicInbox::DS $self = $_[0];
555     return if $self->{closed};
556
557     # cleanup does most of the work of closing this socket
558     $self->_cleanup();
559
560     # now undef our internal sock and fd structures so we don't use them
561     my $sock = $self->{sock};
562     $self->{sock} = undef;
563     return $sock;
564 }
565
566 =head2 C<< $obj->close( [$reason] ) >>
567
568 Close the socket. The I<reason> argument will be used in debugging messages.
569
570 =cut
571 sub close {
572     my PublicInbox::DS $self = $_[0];
573     return if $self->{closed};
574
575     # print out debugging info for this close
576     if (DebugLevel) {
577         my ($pkg, $filename, $line) = caller;
578         my $reason = $_[1] || "";
579         warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
580     }
581
582     # this does most of the work of closing us
583     $self->_cleanup();
584
585     # defer closing the actual socket until the event loop is done
586     # processing this round of events.  (otherwise we might reuse fds)
587     if ($self->{sock}) {
588         push @ToClose, $self->{sock};
589         $self->{sock} = undef;
590     }
591
592     return 0;
593 }
594
595 ### METHOD: _cleanup()
596 ### Called by our closers so we can clean internal data structures.
597 sub _cleanup {
598     my PublicInbox::DS $self = $_[0];
599
600     # we're effectively closed; we have no fd and sock when we leave here
601     $self->{closed} = 1;
602
603     # we need to flush our write buffer, as there may
604     # be self-referential closures (sub { $client->close })
605     # preventing the object from being destroyed
606     $self->{write_buf} = [];
607
608     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
609     # notifications about it
610     if ($HaveEpoll && $self->{fd}) {
611         if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
612             # dump_error prints a backtrace so we can try to figure out why this happened
613             $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
614         }
615     }
616
617     # now delete from mappings.  this fd no longer belongs to us, so we don't want
618     # to get alerts for it if it becomes writable/readable/etc.
619     delete $PLCMap{$self->{fd}};
620
621     # we explicitly don't delete from DescriptorMap here until we
622     # actually close the socket, as we might be in the middle of
623     # processing an epoll_wait/etc that returned hundreds of fds, one
624     # of which is not yet processed and is what we're closing.  if we
625     # keep it in DescriptorMap, then the event harnesses can just
626     # looked at $pob->{closed} and ignore it.  but if it's an
627     # un-accounted for fd, then it (understandably) freak out a bit
628     # and emit warnings, thinking their state got off.
629
630     # and finally get rid of our fd so we can't use it anywhere else
631     $self->{fd} = undef;
632 }
633
634 =head2 C<< $obj->sock() >>
635
636 Returns the underlying IO::Handle for the object.
637
638 =cut
639 sub sock {
640     my PublicInbox::DS $self = shift;
641     return $self->{sock};
642 }
643
644 =head2 C<< $obj->set_writer_func( CODEREF ) >>
645
646 Sets a function to use instead of C<syswrite()> when writing data to the socket.
647
648 =cut
649 sub set_writer_func {
650    my PublicInbox::DS $self = shift;
651    my $wtr = shift;
652    Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
653    $self->{writer_func} = $wtr;
654 }
655
656 =head2 C<< $obj->write( $data ) >>
657
658 Write the specified data to the underlying handle.  I<data> may be scalar,
659 scalar ref, code ref (to run when there), or undef just to kick-start.
660 Returns 1 if writes all went through, or 0 if there are writes in queue. If
661 it returns 1, caller should stop waiting for 'writable' events)
662
663 =cut
664 sub write {
665     my PublicInbox::DS $self;
666     my $data;
667     ($self, $data) = @_;
668
669     # nobody should be writing to closed sockets, but caller code can
670     # do two writes within an event, have the first fail and
671     # disconnect the other side (whose destructor then closes the
672     # calling object, but it's still in a method), and then the
673     # now-dead object does its second write.  that is this case.  we
674     # just lie and say it worked.  it'll be dead soon and won't be
675     # hurt by this lie.
676     return 1 if $self->{closed};
677
678     my $bref;
679
680     # just queue data if there's already a wait
681     my $need_queue;
682
683     if (defined $data) {
684         $bref = ref $data ? $data : \$data;
685         if ($self->{write_buf_size}) {
686             push @{$self->{write_buf}}, $bref;
687             $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
688             return 0;
689         }
690
691         # this flag says we're bypassing the queue system, knowing we're the
692         # only outstanding write, and hoping we don't ever need to use it.
693         # if so later, though, we'll need to queue
694         $need_queue = 1;
695     }
696
697   WRITE:
698     while (1) {
699         return 1 unless $bref ||= $self->{write_buf}[0];
700
701         my $len;
702         eval {
703             $len = length($$bref); # this will die if $bref is a code ref, caught below
704         };
705         if ($@) {
706             if (UNIVERSAL::isa($bref, "CODE")) {
707                 unless ($need_queue) {
708                     $self->{write_buf_size}--; # code refs are worth 1
709                     shift @{$self->{write_buf}};
710                 }
711                 $bref->();
712
713                 # code refs are just run and never get reenqueued
714                 # (they're one-shot), so turn off the flag indicating the
715                 # outstanding data needs queueing.
716                 $need_queue = 0;
717
718                 undef $bref;
719                 next WRITE;
720             }
721             die "Write error: $@ <$bref>";
722         }
723
724         my $to_write = $len - $self->{write_buf_offset};
725         my $written;
726         if (my $wtr = $self->{writer_func}) {
727             $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
728         } else {
729             $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
730         }
731
732         if (! defined $written) {
733             if ($! == EPIPE) {
734                 return $self->close("EPIPE");
735             } elsif ($! == EAGAIN) {
736                 # since connection has stuff to write, it should now be
737                 # interested in pending writes:
738                 if ($need_queue) {
739                     push @{$self->{write_buf}}, $bref;
740                     $self->{write_buf_size} += $len;
741                 }
742                 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
743                 $self->watch_write(1);
744                 return 0;
745             } elsif ($! == ECONNRESET) {
746                 return $self->close("ECONNRESET");
747             }
748
749             DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
750
751             return $self->close("write_error");
752         } elsif ($written != $to_write) {
753             DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
754                                                $written, $self->{fd});
755             if ($need_queue) {
756                 push @{$self->{write_buf}}, $bref;
757                 $self->{write_buf_size} += $len;
758             }
759             # since connection has stuff to write, it should now be
760             # interested in pending writes:
761             $self->{write_buf_offset} += $written;
762             $self->{write_buf_size} -= $written;
763             $self->on_incomplete_write;
764             return 0;
765         } elsif ($written == $to_write) {
766             DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
767                                                $written, $self->{fd}, $need_queue);
768             $self->{write_buf_offset} = 0;
769
770             if ($self->{write_set_watch}) {
771                 $self->watch_write(0);
772                 $self->{write_set_watch} = 0;
773             }
774
775             # this was our only write, so we can return immediately
776             # since we avoided incrementing the buffer size or
777             # putting it in the buffer.  we also know there
778             # can't be anything else to write.
779             return 1 if $need_queue;
780
781             $self->{write_buf_size} -= $written;
782             shift @{$self->{write_buf}};
783             undef $bref;
784             next WRITE;
785         }
786     }
787 }
788
789 sub on_incomplete_write {
790     my PublicInbox::DS $self = shift;
791     $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
792     $self->watch_write(1);
793 }
794
795 =head2 C<< $obj->read( $bytecount ) >>
796
797 Read at most I<bytecount> bytes from the underlying handle; returns scalar
798 ref on read, or undef on connection closed.
799
800 =cut
801 sub read {
802     my PublicInbox::DS $self = shift;
803     return if $self->{closed};
804     my $bytes = shift;
805     my $buf;
806     my $sock = $self->{sock};
807
808     # if this is too high, perl quits(!!).  reports on mailing lists
809     # don't seem to point to a universal answer.  5MB worked for some,
810     # crashed for others.  1MB works for more people.  let's go with 1MB
811     # for now.  :/
812     my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
813
814     my $res = sysread($sock, $buf, $req_bytes, 0);
815     DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
816
817     if (! $res && $! != EWOULDBLOCK) {
818         # catches 0=conn closed or undef=error
819         DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
820         return undef;
821     }
822
823     return \$buf;
824 }
825
826 =head2 (VIRTUAL) C<< $obj->event_read() >>
827
828 Readable event handler. Concrete deriviatives of PublicInbox::DS should
829 provide an implementation of this. The default implementation will die if
830 called.
831
832 =cut
833 sub event_read  { die "Base class event_read called for $_[0]\n"; }
834
835 =head2 (VIRTUAL) C<< $obj->event_err() >>
836
837 Error event handler. Concrete deriviatives of PublicInbox::DS should
838 provide an implementation of this. The default implementation will die if
839 called.
840
841 =cut
842 sub event_err   { die "Base class event_err called for $_[0]\n"; }
843
844 =head2 (VIRTUAL) C<< $obj->event_hup() >>
845
846 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
847 provide an implementation of this. The default implementation will die if
848 called.
849
850 =cut
851 sub event_hup   { die "Base class event_hup called for $_[0]\n"; }
852
853 =head2 C<< $obj->event_write() >>
854
855 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
856 provide an implementation of this. The default implementation calls
857 C<write()> with an C<undef>.
858
859 =cut
860 sub event_write {
861     my $self = shift;
862     $self->write(undef);
863 }
864
865 =head2 C<< $obj->watch_read( $boolean ) >>
866
867 Turn 'readable' event notification on or off.
868
869 =cut
870 sub watch_read {
871     my PublicInbox::DS $self = shift;
872     return if $self->{closed} || !$self->{sock};
873
874     my $val = shift;
875     my $event = $self->{event_watch};
876
877     $event &= ~POLLIN if ! $val;
878     $event |=  POLLIN if   $val;
879
880     # If it changed, set it
881     if ($event != $self->{event_watch}) {
882         if ($HaveKQueue) {
883             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
884                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
885         }
886         elsif ($HaveEpoll) {
887             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
888                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
889                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
890         }
891         $self->{event_watch} = $event;
892     }
893 }
894
895 =head2 C<< $obj->watch_write( $boolean ) >>
896
897 Turn 'writable' event notification on or off.
898
899 =cut
900 sub watch_write {
901     my PublicInbox::DS $self = shift;
902     return if $self->{closed} || !$self->{sock};
903
904     my $val = shift;
905     my $event = $self->{event_watch};
906
907     $event &= ~POLLOUT if ! $val;
908     $event |=  POLLOUT if   $val;
909
910     if ($val && caller ne __PACKAGE__) {
911         # A subclass registered interest, it's now responsible for this.
912         $self->{write_set_watch} = 0;
913     }
914
915     # If it changed, set it
916     if ($event != $self->{event_watch}) {
917         if ($HaveKQueue) {
918             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
919                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
920         }
921         elsif ($HaveEpoll) {
922             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
923                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
924                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
925         }
926         $self->{event_watch} = $event;
927     }
928 }
929
930 =head2 C<< $obj->dump_error( $message ) >>
931
932 Prints to STDERR a backtrace with information about this socket and what lead
933 up to the dump_error call.
934
935 =cut
936 sub dump_error {
937     my $i = 0;
938     my @list;
939     while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
940         push @list, "\t$file:$line called $sub\n";
941     }
942
943     warn "ERROR: $_[1]\n" .
944         "\t$_[0] = " . $_[0]->as_string . "\n" .
945         join('', @list);
946 }
947
948 =head2 C<< $obj->debugmsg( $format, @args ) >>
949
950 Print the debugging message specified by the C<sprintf>-style I<format> and
951 I<args>.
952
953 =cut
954 sub debugmsg {
955     my ( $self, $fmt, @args ) = @_;
956     confess "Not an object" unless ref $self;
957
958     chomp $fmt;
959     printf STDERR ">>> $fmt\n", @args;
960 }
961
962 =head2 C<< $obj->as_string() >>
963
964 Returns a string describing this socket.
965
966 =cut
967 sub as_string {
968     my PublicInbox::DS $self = shift;
969     my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
970                    ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
971     my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
972     return $ret;
973 }
974
975 package PublicInbox::DS::Timer;
976 # [$abs_float_firetime, $coderef];
977 sub cancel {
978     $_[0][1] = undef;
979 }
980
981 1;
982
983 =head1 AUTHORS (Danga::Socket)
984
985 Brad Fitzpatrick <brad@danga.com> - author
986
987 Michael Granger <ged@danga.com> - docs, testing
988
989 Mark Smith <junior@danga.com> - contributor, heavy user, testing
990
991 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits