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