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