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