]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
listener: use EPOLLEXCLUSIVE for listen sockets
[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 my $opt_bsd_resource = eval "use BSD::Resource; 1;";
17
18 use vars qw{$VERSION};
19 $VERSION = "1.61";
20
21 use warnings;
22 no  warnings qw(deprecated);
23
24 use PublicInbox::Syscall qw(:epoll);
25
26 use fields ('sock',              # underlying socket
27             'fd',                # numeric file descriptor
28             'write_buf',         # arrayref of scalars, scalarrefs, or coderefs to write
29             'write_buf_offset',  # offset into first array of write_buf to start writing at
30             'write_buf_size',    # total length of data in all write_buf items
31             'write_set_watch',   # bool: true if we internally set watch_write rather than by a subclass
32             'read_push_back',    # arrayref of "pushed-back" read data the application didn't want
33             'closed',            # bool: socket is closed
34             'corked',            # bool: socket is corked
35             'event_watch',       # bitmask of events the client is interested in (POLLIN,OUT,etc.)
36             'peer_v6',           # bool: cached; if peer is an IPv6 address
37             'peer_ip',           # cached stringified IP address of $sock
38             'peer_port',         # cached port number of $sock
39             'local_ip',          # cached stringified IP address of local end of $sock
40             'local_port',        # cached port number of local end of $sock
41             'writer_func',       # subref which does writing.  must return bytes written (or undef) and set $! on errors
42             );
43
44 use Errno  qw(EINPROGRESS EWOULDBLOCK EISCONN ENOTSOCK
45               EPIPE EAGAIN EBADF ECONNRESET ENOPROTOOPT);
46 use Socket qw(IPPROTO_TCP);
47 use Carp   qw(croak confess);
48
49 use constant TCP_CORK => ($^O eq "linux" ? 3 : 0); # FIXME: not hard-coded (Linux-specific too)
50 use constant DebugLevel => 0;
51
52 use constant POLLIN        => 1;
53 use constant POLLOUT       => 4;
54 use constant POLLERR       => 8;
55 use constant POLLHUP       => 16;
56 use constant POLLNVAL      => 32;
57
58 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
59
60 our (
61      $HaveEpoll,                 # Flag -- is epoll available?  initially undefined.
62      $HaveKQueue,
63      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
64      %PushBackSet,               # fd (num) -> PublicInbox::DS (fds with pushed back read data)
65      $Epoll,                     # Global epoll fd (for epoll mode only)
66      $KQueue,                    # Global kqueue fd (for kqueue mode only)
67      @ToClose,                   # sockets to close when event loop is done
68      %OtherFds,                  # A hash of "other" (non-PublicInbox::DS) file
69                                  # descriptors for the event loop to track.
70
71      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
72      %PLCMap,                    # fd (num) -> PostLoopCallback (per-object)
73
74      $LoopTimeout,               # timeout of event loop in milliseconds
75      $DoProfile,                 # if on, enable profiling
76      %Profiling,                 # what => [ utime, stime, calls ]
77      $DoneInit,                  # if we've done the one-time module init yet
78      @Timers,                    # timers
79      );
80
81 # this may be set to zero with old kernels
82 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
83 Reset();
84
85 #####################################################################
86 ### C L A S S   M E T H O D S
87 #####################################################################
88
89 =head2 C<< CLASS->Reset() >>
90
91 Reset all state
92
93 =cut
94 sub Reset {
95     %DescriptorMap = ();
96     %PushBackSet = ();
97     @ToClose = ();
98     %OtherFds = ();
99     $LoopTimeout = -1;  # no timeout by default
100     $DoProfile = 0;
101     %Profiling = ();
102     @Timers = ();
103
104     $PostLoopCallback = undef;
105     %PLCMap = ();
106     $DoneInit = 0;
107
108     POSIX::close($Epoll)  if defined $Epoll  && $Epoll  >= 0;
109     POSIX::close($KQueue) if defined $KQueue && $KQueue >= 0;
110
111     *EventLoop = *FirstTimeEventLoop;
112 }
113
114 =head2 C<< CLASS->HaveEpoll() >>
115
116 Returns a true value if this class will use IO::Epoll for async IO.
117
118 =cut
119 sub HaveEpoll {
120     _InitPoller();
121     return $HaveEpoll;
122 }
123
124 =head2 C<< CLASS->WatchedSockets() >>
125
126 Returns the number of file descriptors which are registered with the global
127 poll object.
128
129 =cut
130 sub WatchedSockets {
131     return scalar keys %DescriptorMap;
132 }
133 *watched_sockets = *WatchedSockets;
134
135 =head2 C<< CLASS->EnableProfiling() >>
136
137 Turns profiling on, clearing current profiling data.
138
139 =cut
140 sub EnableProfiling {
141     if ($opt_bsd_resource) {
142         %Profiling = ();
143         $DoProfile = 1;
144         return 1;
145     }
146     return 0;
147 }
148
149 =head2 C<< CLASS->DisableProfiling() >>
150
151 Turns off profiling, but retains data up to this point
152
153 =cut
154 sub DisableProfiling {
155     $DoProfile = 0;
156 }
157
158 =head2 C<< CLASS->ProfilingData() >>
159
160 Returns reference to a hash of data in format:
161
162   ITEM => [ utime, stime, #calls ]
163
164 =cut
165 sub ProfilingData {
166     return \%Profiling;
167 }
168
169 =head2 C<< CLASS->ToClose() >>
170
171 Return the list of sockets that are awaiting close() at the end of the
172 current event loop.
173
174 =cut
175 sub ToClose { return @ToClose; }
176
177 =head2 C<< CLASS->OtherFds( [%fdmap] ) >>
178
179 Get/set the hash of file descriptors that need processing in parallel with
180 the registered PublicInbox::DS objects.
181
182 =cut
183 sub OtherFds {
184     my $class = shift;
185     if ( @_ ) { %OtherFds = @_ }
186     return wantarray ? %OtherFds : \%OtherFds;
187 }
188
189 =head2 C<< CLASS->AddOtherFds( [%fdmap] ) >>
190
191 Add fds to the OtherFds hash for processing.
192
193 =cut
194 sub AddOtherFds {
195     my $class = shift;
196     %OtherFds = ( %OtherFds, @_ ); # FIXME investigate what happens on dupe fds
197     return wantarray ? %OtherFds : \%OtherFds;
198 }
199
200 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
201
202 Set the loop timeout for the event loop to some value in milliseconds.
203
204 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
205 immediately.
206
207 =cut
208 sub SetLoopTimeout {
209     return $LoopTimeout = $_[1] + 0;
210 }
211
212 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
213
214 Print the debugging message specified by the C<sprintf>-style I<format> and
215 I<args>
216
217 =cut
218 sub DebugMsg {
219     my ( $class, $fmt, @args ) = @_;
220     chomp $fmt;
221     printf STDERR ">>> $fmt\n", @args;
222 }
223
224 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
225
226 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
227 are not guaranteed to fire at the exact time you ask for.
228
229 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
230
231 =cut
232 sub AddTimer {
233     my $class = shift;
234     my ($secs, $coderef) = @_;
235
236     my $fire_time = Time::HiRes::time() + $secs;
237
238     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
239
240     if (!@Timers || $fire_time >= $Timers[-1][0]) {
241         push @Timers, $timer;
242         return $timer;
243     }
244
245     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
246     # but it was compared against calendar queues, heaps, naive push/sort,
247     # and a bunch of other versions, and found to be fastest with a large
248     # variety of datasets.)
249     for (my $i = 0; $i < @Timers; $i++) {
250         if ($Timers[$i][0] > $fire_time) {
251             splice(@Timers, $i, 0, $timer);
252             return $timer;
253         }
254     }
255
256     die "Shouldn't get here.";
257 }
258
259 =head2 C<< CLASS->DescriptorMap() >>
260
261 Get the hash of PublicInbox::DS objects keyed by the file descriptor (fileno) they
262 are wrapping.
263
264 Returns a hash in list context or a hashref in scalar context.
265
266 =cut
267 sub DescriptorMap {
268     return wantarray ? %DescriptorMap : \%DescriptorMap;
269 }
270 *descriptor_map = *DescriptorMap;
271 *get_sock_ref = *DescriptorMap;
272
273 sub _InitPoller
274 {
275     return if $DoneInit;
276     $DoneInit = 1;
277
278     if ($HAVE_KQUEUE) {
279         $KQueue = IO::KQueue->new();
280         $HaveKQueue = $KQueue >= 0;
281         if ($HaveKQueue) {
282             *EventLoop = *KQueueEventLoop;
283         }
284     }
285     elsif (PublicInbox::Syscall::epoll_defined()) {
286         $Epoll = eval { epoll_create(1024); };
287         $HaveEpoll = defined $Epoll && $Epoll >= 0;
288         if ($HaveEpoll) {
289             *EventLoop = *EpollEventLoop;
290         }
291     }
292
293     if (!$HaveEpoll && !$HaveKQueue) {
294         require IO::Poll;
295         *EventLoop = *PollEventLoop;
296     }
297 }
298
299 =head2 C<< CLASS->EventLoop() >>
300
301 Start processing IO events. In most daemon programs this never exits. See
302 C<PostLoopCallback> below for how to exit the loop.
303
304 =cut
305 sub FirstTimeEventLoop {
306     my $class = shift;
307
308     _InitPoller();
309
310     if ($HaveEpoll) {
311         EpollEventLoop($class);
312     } elsif ($HaveKQueue) {
313         KQueueEventLoop($class);
314     } else {
315         PollEventLoop($class);
316     }
317 }
318
319 ## profiling-related data/functions
320 our ($Prof_utime0, $Prof_stime0);
321 sub _pre_profile {
322     ($Prof_utime0, $Prof_stime0) = getrusage();
323 }
324
325 sub _post_profile {
326     # get post information
327     my ($autime, $astime) = getrusage();
328
329     # calculate differences
330     my $utime = $autime - $Prof_utime0;
331     my $stime = $astime - $Prof_stime0;
332
333     foreach my $k (@_) {
334         $Profiling{$k} ||= [ 0.0, 0.0, 0 ];
335         $Profiling{$k}->[0] += $utime;
336         $Profiling{$k}->[1] += $stime;
337         $Profiling{$k}->[2]++;
338     }
339 }
340
341 # runs timers and returns milliseconds for next one, or next event loop
342 sub RunTimers {
343     return $LoopTimeout unless @Timers;
344
345     my $now = Time::HiRes::time();
346
347     # Run expired timers
348     while (@Timers && $Timers[0][0] <= $now) {
349         my $to_run = shift(@Timers);
350         $to_run->[1]->($now) if $to_run->[1];
351     }
352
353     return $LoopTimeout unless @Timers;
354
355     # convert time to an even number of milliseconds, adding 1
356     # extra, otherwise floating point fun can occur and we'll
357     # call RunTimers like 20-30 times, each returning a timeout
358     # of 0.0000212 seconds
359     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
360
361     # -1 is an infinite timeout, so prefer a real timeout
362     return $timeout     if $LoopTimeout == -1;
363
364     # otherwise pick the lower of our regular timeout and time until
365     # the next timer
366     return $LoopTimeout if $LoopTimeout < $timeout;
367     return $timeout;
368 }
369
370 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
371 ### okay.
372 sub EpollEventLoop {
373     my $class = shift;
374
375     foreach my $fd ( keys %OtherFds ) {
376         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, EPOLLIN) == -1) {
377             warn "epoll_ctl(): failure adding fd=$fd; $! (", $!+0, ")\n";
378         }
379     }
380
381     while (1) {
382         my @events;
383         my $i;
384         my $timeout = RunTimers();
385
386         # get up to 1000 events
387         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
388       EVENT:
389         for ($i=0; $i<$evcount; $i++) {
390             my $ev = $events[$i];
391
392             # it's possible epoll_wait returned many events, including some at the end
393             # that ones in the front triggered unregister-interest actions.  if we
394             # can't find the %sock entry, it's because we're no longer interested
395             # in that event.
396             my PublicInbox::DS $pob = $DescriptorMap{$ev->[0]};
397             my $code;
398             my $state = $ev->[1];
399
400             # if we didn't find a Perlbal::Socket subclass for that fd, try other
401             # pseudo-registered (above) fds.
402             if (! $pob) {
403                 if (my $code = $OtherFds{$ev->[0]}) {
404                     $code->($state);
405                 } else {
406                     my $fd = $ev->[0];
407                     warn "epoll() returned fd $fd w/ state $state for which we have no mapping.  removing.\n";
408                     POSIX::close($fd);
409                     epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0);
410                 }
411                 next;
412             }
413
414             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), state=%d \@ %s\n",
415                                                 $ev->[0], ref($pob), $ev->[1], time);
416
417             if ($DoProfile) {
418                 my $class = ref $pob;
419
420                 # call profiling action on things that need to be done
421                 if ($state & EPOLLIN && ! $pob->{closed}) {
422                     _pre_profile();
423                     $pob->event_read;
424                     _post_profile("$class-read");
425                 }
426
427                 if ($state & EPOLLOUT && ! $pob->{closed}) {
428                     _pre_profile();
429                     $pob->event_write;
430                     _post_profile("$class-write");
431                 }
432
433                 if ($state & (EPOLLERR|EPOLLHUP)) {
434                     if ($state & EPOLLERR && ! $pob->{closed}) {
435                         _pre_profile();
436                         $pob->event_err;
437                         _post_profile("$class-err");
438                     }
439                     if ($state & EPOLLHUP && ! $pob->{closed}) {
440                         _pre_profile();
441                         $pob->event_hup;
442                         _post_profile("$class-hup");
443                     }
444                 }
445
446                 next;
447             }
448
449             # standard non-profiling codepat
450             $pob->event_read   if $state & EPOLLIN && ! $pob->{closed};
451             $pob->event_write  if $state & EPOLLOUT && ! $pob->{closed};
452             if ($state & (EPOLLERR|EPOLLHUP)) {
453                 $pob->event_err    if $state & EPOLLERR && ! $pob->{closed};
454                 $pob->event_hup    if $state & EPOLLHUP && ! $pob->{closed};
455             }
456         }
457         return unless PostEventLoop();
458     }
459     exit 0;
460 }
461
462 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
463 ### IO::Epoll fails to load.
464 sub PollEventLoop {
465     my $class = shift;
466
467     my PublicInbox::DS $pob;
468
469     while (1) {
470         my $timeout = RunTimers();
471
472         # the following sets up @poll as a series of ($poll,$event_mask)
473         # items, then uses IO::Poll::_poll, implemented in XS, which
474         # modifies the array in place with the even elements being
475         # replaced with the event masks that occured.
476         my @poll;
477         foreach my $fd ( keys %OtherFds ) {
478             push @poll, $fd, POLLIN;
479         }
480         while ( my ($fd, $sock) = each %DescriptorMap ) {
481             push @poll, $fd, $sock->{event_watch};
482         }
483
484         # if nothing to poll, either end immediately (if no timeout)
485         # or just keep calling the callback
486         unless (@poll) {
487             select undef, undef, undef, ($timeout / 1000);
488             return unless PostEventLoop();
489             next;
490         }
491
492         my $count = IO::Poll::_poll($timeout, @poll);
493         unless ($count) {
494             return unless PostEventLoop();
495             next;
496         }
497
498         # Fetch handles with read events
499         while (@poll) {
500             my ($fd, $state) = splice(@poll, 0, 2);
501             next unless $state;
502
503             $pob = $DescriptorMap{$fd};
504
505             if (!$pob) {
506                 if (my $code = $OtherFds{$fd}) {
507                     $code->($state);
508                 }
509                 next;
510             }
511
512             $pob->event_read   if $state & POLLIN && ! $pob->{closed};
513             $pob->event_write  if $state & POLLOUT && ! $pob->{closed};
514             $pob->event_err    if $state & POLLERR && ! $pob->{closed};
515             $pob->event_hup    if $state & POLLHUP && ! $pob->{closed};
516         }
517
518         return unless PostEventLoop();
519     }
520
521     exit 0;
522 }
523
524 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
525 ### okay.
526 sub KQueueEventLoop {
527     my $class = shift;
528
529     foreach my $fd (keys %OtherFds) {
530         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(), IO::KQueue::EV_ADD());
531     }
532
533     while (1) {
534         my $timeout = RunTimers();
535         my @ret = $KQueue->kevent($timeout);
536
537         foreach my $kev (@ret) {
538             my ($fd, $filter, $flags, $fflags) = @$kev;
539             my PublicInbox::DS $pob = $DescriptorMap{$fd};
540             if (!$pob) {
541                 if (my $code = $OtherFds{$fd}) {
542                     $code->($filter);
543                 }  else {
544                     warn "kevent() returned fd $fd for which we have no mapping.  removing.\n";
545                     POSIX::close($fd); # close deletes the kevent entry
546                 }
547                 next;
548             }
549
550             DebugLevel >= 1 && $class->DebugMsg("Event: fd=%d (%s), flags=%d \@ %s\n",
551                                                         $fd, ref($pob), $flags, time);
552
553             $pob->event_read  if $filter == IO::KQueue::EVFILT_READ()  && !$pob->{closed};
554             $pob->event_write if $filter == IO::KQueue::EVFILT_WRITE() && !$pob->{closed};
555             if ($flags ==  IO::KQueue::EV_EOF() && !$pob->{closed}) {
556                 if ($fflags) {
557                     $pob->event_err;
558                 } else {
559                     $pob->event_hup;
560                 }
561             }
562         }
563         return unless PostEventLoop();
564     }
565
566     exit(0);
567 }
568
569 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
570
571 Sets post loop callback function.  Pass a subref and it will be
572 called every time the event loop finishes.
573
574 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
575 and it will exit.
576
577 The callback function will be passed two parameters: \%DescriptorMap, \%OtherFds.
578
579 =cut
580 sub SetPostLoopCallback {
581     my ($class, $ref) = @_;
582
583     if (ref $class) {
584         # per-object callback
585         my PublicInbox::DS $self = $class;
586         if (defined $ref && ref $ref eq 'CODE') {
587             $PLCMap{$self->{fd}} = $ref;
588         } else {
589             delete $PLCMap{$self->{fd}};
590         }
591     } else {
592         # global callback
593         $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
594     }
595 }
596
597 # Internal function: run the post-event callback, send read events
598 # for pushed-back data, and close pending connections.  returns 1
599 # if event loop should continue, or 0 to shut it all down.
600 sub PostEventLoop {
601     # fire read events for objects with pushed-back read data
602     my $loop = 1;
603     while ($loop) {
604         $loop = 0;
605         foreach my $fd (keys %PushBackSet) {
606             my PublicInbox::DS $pob = $PushBackSet{$fd};
607
608             # a previous event_read invocation could've closed a
609             # connection that we already evaluated in "keys
610             # %PushBackSet", so skip ones that seem to have
611             # disappeared.  this is expected.
612             next unless $pob;
613
614             die "ASSERT: the $pob socket has no read_push_back" unless @{$pob->{read_push_back}};
615             next unless (! $pob->{closed} &&
616                          $pob->{event_watch} & POLLIN);
617             $loop = 1;
618             $pob->event_read;
619         }
620     }
621
622     # now we can close sockets that wanted to close during our event processing.
623     # (we didn't want to close them during the loop, as we didn't want fd numbers
624     #  being reused and confused during the event loop)
625     while (my $sock = shift @ToClose) {
626         my $fd = fileno($sock);
627
628         # close the socket.  (not a PublicInbox::DS close)
629         $sock->close;
630
631         # and now we can finally remove the fd from the map.  see
632         # comment above in _cleanup.
633         delete $DescriptorMap{$fd};
634     }
635
636
637     # by default we keep running, unless a postloop callback (either per-object
638     # or global) cancels it
639     my $keep_running = 1;
640
641     # per-object post-loop-callbacks
642     for my $plc (values %PLCMap) {
643         $keep_running &&= $plc->(\%DescriptorMap, \%OtherFds);
644     }
645
646     # now we're at the very end, call callback if defined
647     if (defined $PostLoopCallback) {
648         $keep_running &&= $PostLoopCallback->(\%DescriptorMap, \%OtherFds);
649     }
650
651     return $keep_running;
652 }
653
654 #####################################################################
655 ### PublicInbox::DS-the-object code
656 #####################################################################
657
658 =head2 OBJECT METHODS
659
660 =head2 C<< CLASS->new( $socket ) >>
661
662 Create a new PublicInbox::DS subclass object for the given I<socket> which will
663 react to events on it during the C<EventLoop>.
664
665 This is normally (always?) called from your subclass via:
666
667   $class->SUPER::new($socket);
668
669 =cut
670 sub new {
671     my ($self, $sock, $exclusive) = @_;
672     $self = fields::new($self) unless ref $self;
673
674     $self->{sock}        = $sock;
675     my $fd = fileno($sock);
676
677     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
678         unless $sock && $fd;
679
680     $self->{fd}          = $fd;
681     $self->{write_buf}      = [];
682     $self->{write_buf_offset} = 0;
683     $self->{write_buf_size} = 0;
684     $self->{closed} = 0;
685     $self->{corked} = 0;
686     $self->{read_push_back} = [];
687
688     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
689
690     _InitPoller();
691
692     if ($HaveEpoll) {
693         if ($exclusive) {
694             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
695         }
696 retry:
697         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
698             if ($!{EINVAL} && ($ev & $EPOLLEXCLUSIVE)) {
699                 $EPOLLEXCLUSIVE = 0; # old kernel
700                 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
701                 goto retry;
702             }
703             die "couldn't add epoll watch for $fd: $!\n";
704         }
705     }
706     elsif ($HaveKQueue) {
707         # Add them to the queue but disabled for now
708         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
709                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
710         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
711                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
712     }
713
714     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
715         if $DescriptorMap{$fd};
716
717     $DescriptorMap{$fd} = $self;
718     return $self;
719 }
720
721
722 #####################################################################
723 ### I N S T A N C E   M E T H O D S
724 #####################################################################
725
726 =head2 C<< $obj->tcp_cork( $boolean ) >>
727
728 Turn TCP_CORK on or off depending on the value of I<boolean>.
729
730 =cut
731 sub tcp_cork {
732     my PublicInbox::DS $self = $_[0];
733     my $val = $_[1];
734
735     # make sure we have a socket
736     return unless $self->{sock};
737     return if $val == $self->{corked};
738
739     my $rv;
740     if (TCP_CORK) {
741         $rv = setsockopt($self->{sock}, IPPROTO_TCP, TCP_CORK,
742                          pack("l", $val ? 1 : 0));
743     } else {
744         # FIXME: implement freebsd *PUSH sockopts
745         $rv = 1;
746     }
747
748     # if we failed, close (if we're not already) and warn about the error
749     if ($rv) {
750         $self->{corked} = $val;
751     } else {
752         if ($! == EBADF || $! == ENOTSOCK) {
753             # internal state is probably corrupted; warn and then close if
754             # we're not closed already
755             warn "setsockopt: $!";
756             $self->close('tcp_cork_failed');
757         } elsif ($! == ENOPROTOOPT || $!{ENOTSOCK} || $!{EOPNOTSUPP}) {
758             # TCP implementation doesn't support corking, so just ignore it
759             # or we're trying to tcp-cork a non-socket (like a socketpair pipe
760             # which is acting like a socket, which Perlbal does for child
761             # processes acting like inetd-like web servers)
762         } else {
763             # some other error; we should never hit here, but if we do, die
764             die "setsockopt: $!";
765         }
766     }
767 }
768
769 =head2 C<< $obj->steal_socket() >>
770
771 Basically returns our socket and makes it so that we don't try to close it,
772 but we do remove it from epoll handlers.  THIS CLOSES $self.  It is the same
773 thing as calling close, except it gives you the socket to use.
774
775 =cut
776 sub steal_socket {
777     my PublicInbox::DS $self = $_[0];
778     return if $self->{closed};
779
780     # cleanup does most of the work of closing this socket
781     $self->_cleanup();
782
783     # now undef our internal sock and fd structures so we don't use them
784     my $sock = $self->{sock};
785     $self->{sock} = undef;
786     return $sock;
787 }
788
789 =head2 C<< $obj->close( [$reason] ) >>
790
791 Close the socket. The I<reason> argument will be used in debugging messages.
792
793 =cut
794 sub close {
795     my PublicInbox::DS $self = $_[0];
796     return if $self->{closed};
797
798     # print out debugging info for this close
799     if (DebugLevel) {
800         my ($pkg, $filename, $line) = caller;
801         my $reason = $_[1] || "";
802         warn "Closing \#$self->{fd} due to $pkg/$filename/$line ($reason)\n";
803     }
804
805     # this does most of the work of closing us
806     $self->_cleanup();
807
808     # defer closing the actual socket until the event loop is done
809     # processing this round of events.  (otherwise we might reuse fds)
810     if ($self->{sock}) {
811         push @ToClose, $self->{sock};
812         $self->{sock} = undef;
813     }
814
815     return 0;
816 }
817
818 ### METHOD: _cleanup()
819 ### Called by our closers so we can clean internal data structures.
820 sub _cleanup {
821     my PublicInbox::DS $self = $_[0];
822
823     # we're effectively closed; we have no fd and sock when we leave here
824     $self->{closed} = 1;
825
826     # we need to flush our write buffer, as there may
827     # be self-referential closures (sub { $client->close })
828     # preventing the object from being destroyed
829     $self->{write_buf} = [];
830
831     # uncork so any final data gets sent.  only matters if the person closing
832     # us forgot to do it, but we do it to be safe.
833     $self->tcp_cork(0);
834
835     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
836     # notifications about it
837     if ($HaveEpoll && $self->{fd}) {
838         if (epoll_ctl($Epoll, EPOLL_CTL_DEL, $self->{fd}, $self->{event_watch}) != 0) {
839             # dump_error prints a backtrace so we can try to figure out why this happened
840             $self->dump_error("epoll_ctl(): failure deleting fd=$self->{fd} during _cleanup(); $! (" . ($!+0) . ")");
841         }
842     }
843
844     # now delete from mappings.  this fd no longer belongs to us, so we don't want
845     # to get alerts for it if it becomes writable/readable/etc.
846     delete $PushBackSet{$self->{fd}};
847     delete $PLCMap{$self->{fd}};
848
849     # we explicitly don't delete from DescriptorMap here until we
850     # actually close the socket, as we might be in the middle of
851     # processing an epoll_wait/etc that returned hundreds of fds, one
852     # of which is not yet processed and is what we're closing.  if we
853     # keep it in DescriptorMap, then the event harnesses can just
854     # looked at $pob->{closed} and ignore it.  but if it's an
855     # un-accounted for fd, then it (understandably) freak out a bit
856     # and emit warnings, thinking their state got off.
857
858     # and finally get rid of our fd so we can't use it anywhere else
859     $self->{fd} = undef;
860 }
861
862 =head2 C<< $obj->sock() >>
863
864 Returns the underlying IO::Handle for the object.
865
866 =cut
867 sub sock {
868     my PublicInbox::DS $self = shift;
869     return $self->{sock};
870 }
871
872 =head2 C<< $obj->set_writer_func( CODEREF ) >>
873
874 Sets a function to use instead of C<syswrite()> when writing data to the socket.
875
876 =cut
877 sub set_writer_func {
878    my PublicInbox::DS $self = shift;
879    my $wtr = shift;
880    Carp::croak("Not a subref") unless !defined $wtr || UNIVERSAL::isa($wtr, "CODE");
881    $self->{writer_func} = $wtr;
882 }
883
884 =head2 C<< $obj->write( $data ) >>
885
886 Write the specified data to the underlying handle.  I<data> may be scalar,
887 scalar ref, code ref (to run when there), or undef just to kick-start.
888 Returns 1 if writes all went through, or 0 if there are writes in queue. If
889 it returns 1, caller should stop waiting for 'writable' events)
890
891 =cut
892 sub write {
893     my PublicInbox::DS $self;
894     my $data;
895     ($self, $data) = @_;
896
897     # nobody should be writing to closed sockets, but caller code can
898     # do two writes within an event, have the first fail and
899     # disconnect the other side (whose destructor then closes the
900     # calling object, but it's still in a method), and then the
901     # now-dead object does its second write.  that is this case.  we
902     # just lie and say it worked.  it'll be dead soon and won't be
903     # hurt by this lie.
904     return 1 if $self->{closed};
905
906     my $bref;
907
908     # just queue data if there's already a wait
909     my $need_queue;
910
911     if (defined $data) {
912         $bref = ref $data ? $data : \$data;
913         if ($self->{write_buf_size}) {
914             push @{$self->{write_buf}}, $bref;
915             $self->{write_buf_size} += ref $bref eq "SCALAR" ? length($$bref) : 1;
916             return 0;
917         }
918
919         # this flag says we're bypassing the queue system, knowing we're the
920         # only outstanding write, and hoping we don't ever need to use it.
921         # if so later, though, we'll need to queue
922         $need_queue = 1;
923     }
924
925   WRITE:
926     while (1) {
927         return 1 unless $bref ||= $self->{write_buf}[0];
928
929         my $len;
930         eval {
931             $len = length($$bref); # this will die if $bref is a code ref, caught below
932         };
933         if ($@) {
934             if (UNIVERSAL::isa($bref, "CODE")) {
935                 unless ($need_queue) {
936                     $self->{write_buf_size}--; # code refs are worth 1
937                     shift @{$self->{write_buf}};
938                 }
939                 $bref->();
940
941                 # code refs are just run and never get reenqueued
942                 # (they're one-shot), so turn off the flag indicating the
943                 # outstanding data needs queueing.
944                 $need_queue = 0;
945
946                 undef $bref;
947                 next WRITE;
948             }
949             die "Write error: $@ <$bref>";
950         }
951
952         my $to_write = $len - $self->{write_buf_offset};
953         my $written;
954         if (my $wtr = $self->{writer_func}) {
955             $written = $wtr->($bref, $to_write, $self->{write_buf_offset});
956         } else {
957             $written = syswrite($self->{sock}, $$bref, $to_write, $self->{write_buf_offset});
958         }
959
960         if (! defined $written) {
961             if ($! == EPIPE) {
962                 return $self->close("EPIPE");
963             } elsif ($! == EAGAIN) {
964                 # since connection has stuff to write, it should now be
965                 # interested in pending writes:
966                 if ($need_queue) {
967                     push @{$self->{write_buf}}, $bref;
968                     $self->{write_buf_size} += $len;
969                 }
970                 $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
971                 $self->watch_write(1);
972                 return 0;
973             } elsif ($! == ECONNRESET) {
974                 return $self->close("ECONNRESET");
975             }
976
977             DebugLevel >= 1 && $self->debugmsg("Closing connection ($self) due to write error: $!\n");
978
979             return $self->close("write_error");
980         } elsif ($written != $to_write) {
981             DebugLevel >= 2 && $self->debugmsg("Wrote PARTIAL %d bytes to %d",
982                                                $written, $self->{fd});
983             if ($need_queue) {
984                 push @{$self->{write_buf}}, $bref;
985                 $self->{write_buf_size} += $len;
986             }
987             # since connection has stuff to write, it should now be
988             # interested in pending writes:
989             $self->{write_buf_offset} += $written;
990             $self->{write_buf_size} -= $written;
991             $self->on_incomplete_write;
992             return 0;
993         } elsif ($written == $to_write) {
994             DebugLevel >= 2 && $self->debugmsg("Wrote ALL %d bytes to %d (nq=%d)",
995                                                $written, $self->{fd}, $need_queue);
996             $self->{write_buf_offset} = 0;
997
998             if ($self->{write_set_watch}) {
999                 $self->watch_write(0);
1000                 $self->{write_set_watch} = 0;
1001             }
1002
1003             # this was our only write, so we can return immediately
1004             # since we avoided incrementing the buffer size or
1005             # putting it in the buffer.  we also know there
1006             # can't be anything else to write.
1007             return 1 if $need_queue;
1008
1009             $self->{write_buf_size} -= $written;
1010             shift @{$self->{write_buf}};
1011             undef $bref;
1012             next WRITE;
1013         }
1014     }
1015 }
1016
1017 sub on_incomplete_write {
1018     my PublicInbox::DS $self = shift;
1019     $self->{write_set_watch} = 1 unless $self->{event_watch} & POLLOUT;
1020     $self->watch_write(1);
1021 }
1022
1023 =head2 C<< $obj->push_back_read( $buf ) >>
1024
1025 Push back I<buf> (a scalar or scalarref) into the read stream. Useful if you read
1026 more than you need to and want to return this data on the next "read".
1027
1028 =cut
1029 sub push_back_read {
1030     my PublicInbox::DS $self = shift;
1031     my $buf = shift;
1032     push @{$self->{read_push_back}}, ref $buf ? $buf : \$buf;
1033     $PushBackSet{$self->{fd}} = $self;
1034 }
1035
1036 =head2 C<< $obj->read( $bytecount ) >>
1037
1038 Read at most I<bytecount> bytes from the underlying handle; returns scalar
1039 ref on read, or undef on connection closed.
1040
1041 =cut
1042 sub read {
1043     my PublicInbox::DS $self = shift;
1044     return if $self->{closed};
1045     my $bytes = shift;
1046     my $buf;
1047     my $sock = $self->{sock};
1048
1049     if (@{$self->{read_push_back}}) {
1050         $buf = shift @{$self->{read_push_back}};
1051         my $len = length($$buf);
1052
1053         if ($len <= $bytes) {
1054             delete $PushBackSet{$self->{fd}} unless @{$self->{read_push_back}};
1055             return $buf;
1056         } else {
1057             # if the pushed back read is too big, we have to split it
1058             my $overflow = substr($$buf, $bytes);
1059             $buf = substr($$buf, 0, $bytes);
1060             unshift @{$self->{read_push_back}}, \$overflow;
1061             return \$buf;
1062         }
1063     }
1064
1065     # if this is too high, perl quits(!!).  reports on mailing lists
1066     # don't seem to point to a universal answer.  5MB worked for some,
1067     # crashed for others.  1MB works for more people.  let's go with 1MB
1068     # for now.  :/
1069     my $req_bytes = $bytes > 1048576 ? 1048576 : $bytes;
1070
1071     my $res = sysread($sock, $buf, $req_bytes, 0);
1072     DebugLevel >= 2 && $self->debugmsg("sysread = %d; \$! = %d", $res, $!);
1073
1074     if (! $res && $! != EWOULDBLOCK) {
1075         # catches 0=conn closed or undef=error
1076         DebugLevel >= 2 && $self->debugmsg("Fd \#%d read hit the end of the road.", $self->{fd});
1077         return undef;
1078     }
1079
1080     return \$buf;
1081 }
1082
1083 =head2 (VIRTUAL) C<< $obj->event_read() >>
1084
1085 Readable event handler. Concrete deriviatives of PublicInbox::DS should
1086 provide an implementation of this. The default implementation will die if
1087 called.
1088
1089 =cut
1090 sub event_read  { die "Base class event_read called for $_[0]\n"; }
1091
1092 =head2 (VIRTUAL) C<< $obj->event_err() >>
1093
1094 Error event handler. Concrete deriviatives of PublicInbox::DS should
1095 provide an implementation of this. The default implementation will die if
1096 called.
1097
1098 =cut
1099 sub event_err   { die "Base class event_err called for $_[0]\n"; }
1100
1101 =head2 (VIRTUAL) C<< $obj->event_hup() >>
1102
1103 'Hangup' event handler. Concrete deriviatives of PublicInbox::DS should
1104 provide an implementation of this. The default implementation will die if
1105 called.
1106
1107 =cut
1108 sub event_hup   { die "Base class event_hup called for $_[0]\n"; }
1109
1110 =head2 C<< $obj->event_write() >>
1111
1112 Writable event handler. Concrete deriviatives of PublicInbox::DS may wish to
1113 provide an implementation of this. The default implementation calls
1114 C<write()> with an C<undef>.
1115
1116 =cut
1117 sub event_write {
1118     my $self = shift;
1119     $self->write(undef);
1120 }
1121
1122 =head2 C<< $obj->watch_read( $boolean ) >>
1123
1124 Turn 'readable' event notification on or off.
1125
1126 =cut
1127 sub watch_read {
1128     my PublicInbox::DS $self = shift;
1129     return if $self->{closed} || !$self->{sock};
1130
1131     my $val = shift;
1132     my $event = $self->{event_watch};
1133
1134     $event &= ~POLLIN if ! $val;
1135     $event |=  POLLIN if   $val;
1136
1137     # If it changed, set it
1138     if ($event != $self->{event_watch}) {
1139         if ($HaveKQueue) {
1140             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_READ(),
1141                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1142         }
1143         elsif ($HaveEpoll) {
1144             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1145                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1146                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1147         }
1148         $self->{event_watch} = $event;
1149     }
1150 }
1151
1152 =head2 C<< $obj->watch_write( $boolean ) >>
1153
1154 Turn 'writable' event notification on or off.
1155
1156 =cut
1157 sub watch_write {
1158     my PublicInbox::DS $self = shift;
1159     return if $self->{closed} || !$self->{sock};
1160
1161     my $val = shift;
1162     my $event = $self->{event_watch};
1163
1164     $event &= ~POLLOUT if ! $val;
1165     $event |=  POLLOUT if   $val;
1166
1167     if ($val && caller ne __PACKAGE__) {
1168         # A subclass registered interest, it's now responsible for this.
1169         $self->{write_set_watch} = 0;
1170     }
1171
1172     # If it changed, set it
1173     if ($event != $self->{event_watch}) {
1174         if ($HaveKQueue) {
1175             $KQueue->EV_SET($self->{fd}, IO::KQueue::EVFILT_WRITE(),
1176                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
1177         }
1178         elsif ($HaveEpoll) {
1179             epoll_ctl($Epoll, EPOLL_CTL_MOD, $self->{fd}, $event)
1180                 and $self->dump_error("couldn't modify epoll settings for $self->{fd} " .
1181                                       "from $self->{event_watch} -> $event: $! (" . ($!+0) . ")");
1182         }
1183         $self->{event_watch} = $event;
1184     }
1185 }
1186
1187 =head2 C<< $obj->dump_error( $message ) >>
1188
1189 Prints to STDERR a backtrace with information about this socket and what lead
1190 up to the dump_error call.
1191
1192 =cut
1193 sub dump_error {
1194     my $i = 0;
1195     my @list;
1196     while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
1197         push @list, "\t$file:$line called $sub\n";
1198     }
1199
1200     warn "ERROR: $_[1]\n" .
1201         "\t$_[0] = " . $_[0]->as_string . "\n" .
1202         join('', @list);
1203 }
1204
1205 =head2 C<< $obj->debugmsg( $format, @args ) >>
1206
1207 Print the debugging message specified by the C<sprintf>-style I<format> and
1208 I<args>.
1209
1210 =cut
1211 sub debugmsg {
1212     my ( $self, $fmt, @args ) = @_;
1213     confess "Not an object" unless ref $self;
1214
1215     chomp $fmt;
1216     printf STDERR ">>> $fmt\n", @args;
1217 }
1218
1219
1220 =head2 C<< $obj->peer_ip_string() >>
1221
1222 Returns the string describing the peer's IP
1223
1224 =cut
1225 sub peer_ip_string {
1226     my PublicInbox::DS $self = shift;
1227     return _undef("peer_ip_string undef: no sock") unless $self->{sock};
1228     return $self->{peer_ip} if defined $self->{peer_ip};
1229
1230     my $pn = getpeername($self->{sock});
1231     return _undef("peer_ip_string undef: getpeername") unless $pn;
1232
1233     my ($port, $iaddr) = eval {
1234         if (length($pn) >= 28) {
1235             return Socket6::unpack_sockaddr_in6($pn);
1236         } else {
1237             return Socket::sockaddr_in($pn);
1238         }
1239     };
1240
1241     if ($@) {
1242         $self->{peer_port} = "[Unknown peerport '$@']";
1243         return "[Unknown peername '$@']";
1244     }
1245
1246     $self->{peer_port} = $port;
1247
1248     if (length($iaddr) == 4) {
1249         return $self->{peer_ip} = Socket::inet_ntoa($iaddr);
1250     } else {
1251         $self->{peer_v6} = 1;
1252         return $self->{peer_ip} = Socket6::inet_ntop(Socket6::AF_INET6(),
1253                                                      $iaddr);
1254     }
1255 }
1256
1257 =head2 C<< $obj->peer_addr_string() >>
1258
1259 Returns the string describing the peer for the socket which underlies this
1260 object in form "ip:port"
1261
1262 =cut
1263 sub peer_addr_string {
1264     my PublicInbox::DS $self = shift;
1265     my $ip = $self->peer_ip_string
1266         or return undef;
1267     return $self->{peer_v6} ?
1268         "[$ip]:$self->{peer_port}" :
1269         "$ip:$self->{peer_port}";
1270 }
1271
1272 =head2 C<< $obj->local_ip_string() >>
1273
1274 Returns the string describing the local IP
1275
1276 =cut
1277 sub local_ip_string {
1278     my PublicInbox::DS $self = shift;
1279     return _undef("local_ip_string undef: no sock") unless $self->{sock};
1280     return $self->{local_ip} if defined $self->{local_ip};
1281
1282     my $pn = getsockname($self->{sock});
1283     return _undef("local_ip_string undef: getsockname") unless $pn;
1284
1285     my ($port, $iaddr) = Socket::sockaddr_in($pn);
1286     $self->{local_port} = $port;
1287
1288     return $self->{local_ip} = Socket::inet_ntoa($iaddr);
1289 }
1290
1291 =head2 C<< $obj->local_addr_string() >>
1292
1293 Returns the string describing the local end of the socket which underlies this
1294 object in form "ip:port"
1295
1296 =cut
1297 sub local_addr_string {
1298     my PublicInbox::DS $self = shift;
1299     my $ip = $self->local_ip_string;
1300     return $ip ? "$ip:$self->{local_port}" : undef;
1301 }
1302
1303
1304 =head2 C<< $obj->as_string() >>
1305
1306 Returns a string describing this socket.
1307
1308 =cut
1309 sub as_string {
1310     my PublicInbox::DS $self = shift;
1311     my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
1312                    ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
1313     my $ret = ref($self) . "$rw: " . ($self->{closed} ? "closed" : "open");
1314     my $peer = $self->peer_addr_string;
1315     if ($peer) {
1316         $ret .= " to " . $self->peer_addr_string;
1317     }
1318     return $ret;
1319 }
1320
1321 sub _undef {
1322     return undef unless $ENV{DS_DEBUG};
1323     my $msg = shift || "";
1324     warn "PublicInbox::DS: $msg\n";
1325     return undef;
1326 }
1327
1328 package PublicInbox::DS::Timer;
1329 # [$abs_float_firetime, $coderef];
1330 sub cancel {
1331     $_[0][1] = undef;
1332 }
1333
1334 1;
1335
1336 =head1 AUTHORS (Danga::Socket)
1337
1338 Brad Fitzpatrick <brad@danga.com> - author
1339
1340 Michael Granger <ged@danga.com> - docs, testing
1341
1342 Mark Smith <junior@danga.com> - contributor, heavy user, testing
1343
1344 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits