]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: simplify signalfd use
[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 unmaintained Danga::Socket (1.61) with
7 # significant changes.  See Documentation/technical/ds.txt in our
8 # source for details.
9 #
10 # Do not expect this to be a stable API like Danga::Socket,
11 # but it will evolve to suite our needs and to take advantage of
12 # newer Linux and *BSD features.
13 # Bugs encountered were reported to bug-Danga-Socket@rt.cpan.org,
14 # fixed in Danga::Socket 1.62 and visible at:
15 # https://rt.cpan.org/Public/Dist/Display.html?Name=Danga-Socket
16 #
17 # fields:
18 # sock: underlying socket
19 # rbuf: scalarref, usually undef
20 # wbuf: arrayref of coderefs or tmpio (autovivified))
21 #        (tmpio = [ GLOB, offset, [ length ] ])
22 package PublicInbox::DS;
23 use strict;
24 use v5.10.1;
25 use parent qw(Exporter);
26 use bytes qw(length substr); # FIXME(?): needed for PublicInbox::NNTP
27 use POSIX qw(WNOHANG sigprocmask SIG_SETMASK);
28 use Fcntl qw(SEEK_SET :DEFAULT O_APPEND);
29 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
30 use Scalar::Util qw(blessed);
31 use PublicInbox::Syscall qw(:epoll);
32 use PublicInbox::Tmpfile;
33 use Errno qw(EAGAIN EINVAL);
34 use Carp qw(carp croak);
35 our @EXPORT_OK = qw(now msg_more dwaitpid add_timer add_uniq_timer);
36
37 my %Stack;
38 my $nextq; # queue for next_tick
39 my $wait_pids; # list of [ pid, callback, callback_arg ]
40 my $EXPMAP; # fd -> idle_time
41 our $EXPTIME = 180; # 3 minutes
42 my ($reap_armed);
43 my $ToClose; # sockets to close when event loop is done
44 our (
45      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
46      $Epoll,                     # Global epoll fd (or DSKQXS ref)
47      $_io,                       # IO::Handle for Epoll
48
49      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
50
51      $LoopTimeout,               # timeout of event loop in milliseconds
52      @Timers,                    # timers
53      %UniqTimer,
54      $in_loop,
55      );
56
57 Reset();
58
59 #####################################################################
60 ### C L A S S   M E T H O D S
61 #####################################################################
62
63 =head2 C<< CLASS->Reset() >>
64
65 Reset all state
66
67 =cut
68 sub Reset {
69         do {
70                 $in_loop = undef; # first in case DESTROY callbacks use this
71                 %DescriptorMap = ();
72                 @Timers = ();
73                 %UniqTimer = ();
74                 $PostLoopCallback = undef;
75
76                 # we may be iterating inside one of these on our stack
77                 my @q = delete @Stack{keys %Stack};
78                 for my $q (@q) { @$q = () }
79                 $EXPMAP = undef;
80                 $wait_pids = $nextq = $ToClose = undef;
81                 $_io = undef; # closes real $Epoll FD
82                 $Epoll = undef; # may call DSKQXS::DESTROY
83         } while (@Timers || keys(%Stack) || $nextq || $wait_pids ||
84                 $ToClose || keys(%DescriptorMap) ||
85                 $PostLoopCallback || keys(%UniqTimer));
86
87         $reap_armed = undef;
88         $LoopTimeout = -1;  # no timeout by default
89 }
90
91 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
92
93 Set the loop timeout for the event loop to some value in milliseconds.
94
95 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
96 immediately.
97
98 =cut
99 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
100
101 sub _add_named_timer {
102         my ($name, $secs, $coderef, @args) = @_;
103         my $fire_time = now() + $secs;
104         my $timer = [$fire_time, $name, $coderef, @args];
105
106         if (!@Timers || $fire_time >= $Timers[-1][0]) {
107                 push @Timers, $timer;
108                 return $timer;
109         }
110
111         # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
112         # but it was compared against calendar queues, heaps, naive push/sort,
113         # and a bunch of other versions, and found to be fastest with a large
114         # variety of datasets.)
115         for (my $i = 0; $i < @Timers; $i++) {
116                 if ($Timers[$i][0] > $fire_time) {
117                         splice(@Timers, $i, 0, $timer);
118                         return $timer;
119                 }
120         }
121         die "Shouldn't get here.";
122 }
123
124 sub add_timer { _add_named_timer(undef, @_) }
125
126 sub add_uniq_timer { # ($name, $secs, $coderef, @args) = @_;
127         $UniqTimer{$_[0]} //= _add_named_timer(@_);
128 }
129
130 # keeping this around in case we support other FD types for now,
131 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
132 sub set_cloexec ($) {
133     my ($fd) = @_;
134
135     open($_io, '+<&=', $fd) or return;
136     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
137     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
138 }
139
140 # caller sets return value to $Epoll
141 sub _InitPoller
142 {
143     if (PublicInbox::Syscall::epoll_defined())  {
144         my $fd = epoll_create();
145         set_cloexec($fd) if (defined($fd) && $fd >= 0);
146         $fd;
147     } else {
148         my $cls;
149         for (qw(DSKQXS DSPoll)) {
150             $cls = "PublicInbox::$_";
151             last if eval "require $cls";
152         }
153         $cls->import(qw(epoll_ctl epoll_wait));
154         $cls->new;
155     }
156 }
157
158 sub now () { clock_gettime(CLOCK_MONOTONIC) }
159
160 sub next_tick () {
161         my $q = $nextq or return;
162         $nextq = undef;
163         $Stack{cur_runq} = $q;
164         for my $obj (@$q) {
165                 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
166                 # https://rt.perl.org/Public/Bug/Display.html?id=114340
167                 if (blessed($obj)) {
168                         $obj->event_step;
169                 } else {
170                         $obj->();
171                 }
172         }
173         delete $Stack{cur_runq};
174 }
175
176 # runs timers and returns milliseconds for next one, or next event loop
177 sub RunTimers {
178         next_tick();
179
180         return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
181
182         my $now = now();
183
184         # Run expired timers
185         while (@Timers && $Timers[0][0] <= $now) {
186                 my $to_run = shift(@Timers);
187                 delete $UniqTimer{$to_run->[1] // ''};
188                 $to_run->[2]->(@$to_run[3..$#$to_run]);
189         }
190
191         # timers may enqueue into nextq:
192         return 0 if ($nextq || $ToClose);
193
194         return $LoopTimeout unless @Timers;
195
196         # convert time to an even number of milliseconds, adding 1
197         # extra, otherwise floating point fun can occur and we'll
198         # call RunTimers like 20-30 times, each returning a timeout
199         # of 0.0000212 seconds
200         my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
201
202         # -1 is an infinite timeout, so prefer a real timeout
203         ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout
204 }
205
206 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
207
208 sub block_signals () {
209         my $oldset = POSIX::SigSet->new;
210         my $newset = POSIX::SigSet->new;
211         $newset->fillset or die "fillset: $!";
212         sig_setmask($newset, $oldset);
213         $oldset;
214 }
215
216 # We can't use waitpid(-1) safely here since it can hit ``, system(),
217 # and other things.  So we scan the $wait_pids list, which is hopefully
218 # not too big.  We keep $wait_pids small by not calling dwaitpid()
219 # until we've hit EOF when reading the stdout of the child.
220
221 sub reap_pids {
222         $reap_armed = undef;
223         my $tmp = $wait_pids or return;
224         $wait_pids = undef;
225         $Stack{reap_runq} = $tmp;
226         my $oldset = block_signals();
227         foreach my $ary (@$tmp) {
228                 my ($pid, $cb, $arg) = @$ary;
229                 my $ret = waitpid($pid, WNOHANG);
230                 if ($ret == 0) {
231                         push @$wait_pids, $ary; # autovivifies @$wait_pids
232                 } elsif ($ret == $pid) {
233                         if ($cb) {
234                                 eval { $cb->($arg, $pid) };
235                                 warn "E: dwaitpid($pid) in_loop: $@" if $@;
236                         }
237                 } else {
238                         warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
239                 }
240         }
241         sig_setmask($oldset);
242         delete $Stack{reap_runq};
243 }
244
245 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
246 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
247
248 sub in_loop () { $in_loop }
249
250 # Internal function: run the post-event callback, send read events
251 # for pushed-back data, and close pending connections.  returns 1
252 # if event loop should continue, or 0 to shut it all down.
253 sub PostEventLoop () {
254         # now we can close sockets that wanted to close during our event
255         # processing.  (we didn't want to close them during the loop, as we
256         # didn't want fd numbers being reused and confused during the event
257         # loop)
258         if (my $close_now = $ToClose) {
259                 $ToClose = undef; # will be autovivified on push
260                 @$close_now = map { fileno($_) } @$close_now;
261
262                 # order matters, destroy expiry times, first:
263                 delete @$EXPMAP{@$close_now};
264
265                 # ->DESTROY methods may populate ToClose
266                 delete @DescriptorMap{@$close_now};
267         }
268
269         # by default we keep running, unless a postloop callback cancels it
270         $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
271 }
272
273 # Start processing IO events. In most daemon programs this never exits. See
274 # C<PostLoopCallback> for how to exit the loop.
275 sub event_loop (;$$) {
276         my ($sig, $oldset) = @_;
277         $Epoll //= _InitPoller();
278         require PublicInbox::Sigfd if $sig;
279         my $sigfd = PublicInbox::Sigfd->new($sig, 1) if $sig;
280         local @SIG{keys %$sig} = values(%$sig) if $sig && !$sigfd;
281         local $SIG{PIPE} = 'IGNORE';
282         if (!$sigfd && $sig) {
283                 # wake up every second to accept signals if we don't
284                 # have signalfd or IO::KQueue:
285                 sig_setmask($oldset);
286                 PublicInbox::DS->SetLoopTimeout(1000);
287         }
288         $_[0] = $sigfd = $sig = undef; # $_[0] == sig
289         local $in_loop = 1;
290         my @events;
291         do {
292                 my $timeout = RunTimers();
293
294                 # get up to 1000 events
295                 epoll_wait($Epoll, 1000, $timeout, \@events);
296                 for my $fd (@events) {
297                         # it's possible epoll_wait returned many events,
298                         # including some at the end that ones in the front
299                         # triggered unregister-interest actions.  if we can't
300                         # find the %sock entry, it's because we're no longer
301                         # interested in that event.
302
303                         # guard stack-not-refcounted w/ Carp + @DB::args
304                         my $obj = $DescriptorMap{$fd};
305                         $obj->event_step;
306                 }
307         } while (PostEventLoop());
308 }
309
310 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
311
312 Sets post loop callback function.  Pass a subref and it will be
313 called every time the event loop finishes.
314
315 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
316 and it will exit.
317
318 The callback function will be passed two parameters: \%DescriptorMap
319
320 =cut
321 sub SetPostLoopCallback {
322     my ($class, $ref) = @_;
323
324     # global callback
325     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
326 }
327
328 #####################################################################
329 ### PublicInbox::DS-the-object code
330 #####################################################################
331
332 =head2 OBJECT METHODS
333
334 =head2 C<< CLASS->new( $socket ) >>
335
336 Create a new PublicInbox::DS subclass object for the given I<socket> which will
337 react to events on it during the C<event_loop>.
338
339 This is normally (always?) called from your subclass via:
340
341   $class->SUPER::new($socket);
342
343 =cut
344 sub new {
345     my ($self, $sock, $ev) = @_;
346     $self->{sock} = $sock;
347     my $fd = fileno($sock);
348
349     $Epoll //= _InitPoller();
350 retry:
351     if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
352         if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
353             $ev &= ~EPOLLEXCLUSIVE;
354             goto retry;
355         }
356         die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
357     }
358     croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
359         if defined($DescriptorMap{$fd});
360
361     $DescriptorMap{$fd} = $self;
362 }
363
364
365 #####################################################################
366 ### I N S T A N C E   M E T H O D S
367 #####################################################################
368
369 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
370
371 =head2 C<< $obj->close >>
372
373 Close the socket.
374
375 =cut
376 sub close {
377     my ($self) = @_;
378     my $sock = delete $self->{sock} or return;
379
380     # we need to flush our write buffer, as there may
381     # be self-referential closures (sub { $client->close })
382     # preventing the object from being destroyed
383     delete $self->{wbuf};
384
385     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
386     # notifications about it
387     my $fd = fileno($sock);
388     epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
389         croak("EPOLL_CTL_DEL($self/$sock): $!");
390
391     # we explicitly don't delete from DescriptorMap here until we
392     # actually close the socket, as we might be in the middle of
393     # processing an epoll_wait/etc that returned hundreds of fds, one
394     # of which is not yet processed and is what we're closing.  if we
395     # keep it in DescriptorMap, then the event harnesses can just
396     # looked at $pob->{sock} == undef and ignore it.  but if it's an
397     # un-accounted for fd, then it (understandably) freak out a bit
398     # and emit warnings, thinking their state got off.
399
400     # defer closing the actual socket until the event loop is done
401     # processing this round of events.  (otherwise we might reuse fds)
402     push @$ToClose, $sock; # autovivifies $ToClose
403
404     return 0;
405 }
406
407 # portable, non-thread-safe sendfile emulation (no pread, yet)
408 sub send_tmpio ($$) {
409     my ($sock, $tmpio) = @_;
410
411     sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
412     my $n = $tmpio->[2] // 65536;
413     $n = 65536 if $n > 65536;
414     defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
415     my $written = 0;
416     while ($to_write > 0) {
417         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
418             $written += $w;
419             $to_write -= $w;
420         } else {
421             return if $written == 0;
422             last;
423         }
424     }
425     $tmpio->[1] += $written; # offset
426     $tmpio->[2] -= $written if defined($tmpio->[2]); # length
427     $written;
428 }
429
430 sub epbit ($$) { # (sock, default)
431         $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
432 }
433
434 # returns 1 if done, 0 if incomplete
435 sub flush_write ($) {
436     my ($self) = @_;
437     my $sock = $self->{sock} or return;
438     my $wbuf = $self->{wbuf} or return 1;
439
440 next_buf:
441     while (my $bref = $wbuf->[0]) {
442         if (ref($bref) ne 'CODE') {
443             while ($sock) {
444                 my $w = send_tmpio($sock, $bref); # bref is tmpio
445                 if (defined $w) {
446                     if ($w == 0) {
447                         shift @$wbuf;
448                         goto next_buf;
449                     }
450                 } elsif ($! == EAGAIN) {
451                     my $ev = epbit($sock, EPOLLOUT) or return $self->close;
452                     epwait($sock, $ev | EPOLLONESHOT);
453                     return 0;
454                 } else {
455                     return $self->close;
456                 }
457             }
458         } else { #(ref($bref) eq 'CODE') {
459             shift @$wbuf;
460             my $before = scalar(@$wbuf);
461             $bref->($self);
462
463             # bref may be enqueueing more CODE to call (see accept_tls_step)
464             return 0 if (scalar(@$wbuf) > $before);
465         }
466     } # while @$wbuf
467
468     delete $self->{wbuf};
469     1; # all done
470 }
471
472 sub rbuf_idle ($$) {
473     my ($self, $rbuf) = @_;
474     if ($$rbuf eq '') { # who knows how long till we can read again
475         delete $self->{rbuf};
476     } else {
477         $self->{rbuf} = $rbuf;
478     }
479 }
480
481 sub do_read ($$$;$) {
482     my ($self, $rbuf, $len, $off) = @_;
483     my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
484     return ($r == 0 ? $self->close : $r) if defined $r;
485     # common for clients to break connections without warning,
486     # would be too noisy to log here:
487     if ($! == EAGAIN) {
488         my $ev = epbit($sock, EPOLLIN) or return $self->close;
489         epwait($sock, $ev | EPOLLONESHOT);
490         rbuf_idle($self, $rbuf);
491         0;
492     } else {
493         $self->close;
494     }
495 }
496
497 # drop the socket if we hit unrecoverable errors on our system which
498 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
499 sub drop {
500     my $self = shift;
501     carp(@_);
502     $self->close;
503 }
504
505 # n.b.: use ->write/->read for this buffer to allow compatibility with
506 # PerlIO::mmap or PerlIO::scalar if needed
507 sub tmpio ($$$) {
508         my ($self, $bref, $off) = @_;
509         my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
510                 return drop($self, "tmpfile $!");
511         $fh->autoflush(1);
512         my $len = length($$bref) - $off;
513         print $fh substr($$bref, $off, $len) or
514                 return drop($self, "write ($len): $!");
515         [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
516 }
517
518 =head2 C<< $obj->write( $data ) >>
519
520 Write the specified data to the underlying handle.  I<data> may be scalar,
521 scalar ref, code ref (to run when there).
522 Returns 1 if writes all went through, or 0 if there are writes in queue. If
523 it returns 1, caller should stop waiting for 'writable' events)
524
525 =cut
526 sub write {
527     my ($self, $data) = @_;
528
529     # nobody should be writing to closed sockets, but caller code can
530     # do two writes within an event, have the first fail and
531     # disconnect the other side (whose destructor then closes the
532     # calling object, but it's still in a method), and then the
533     # now-dead object does its second write.  that is this case.  we
534     # just lie and say it worked.  it'll be dead soon and won't be
535     # hurt by this lie.
536     my $sock = $self->{sock} or return 1;
537     my $ref = ref $data;
538     my $bref = $ref ? $data : \$data;
539     my $wbuf = $self->{wbuf};
540     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
541         if ($ref eq 'CODE') {
542             push @$wbuf, $bref;
543         } else {
544             my $tmpio = $wbuf->[-1];
545             if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
546                 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
547             } else {
548                 my $tmpio = tmpio($self, $bref, 0) or return 0;
549                 push @$wbuf, $tmpio;
550             }
551         }
552         return 0;
553     } elsif ($ref eq 'CODE') {
554         $bref->($self);
555         return 1;
556     } else {
557         my $to_write = length($$bref);
558         my $written = syswrite($sock, $$bref, $to_write);
559
560         if (defined $written) {
561             return 1 if $written == $to_write;
562             requeue($self); # runs: event_step -> flush_write
563         } elsif ($! == EAGAIN) {
564             my $ev = epbit($sock, EPOLLOUT) or return $self->close;
565             epwait($sock, $ev | EPOLLONESHOT);
566             $written = 0;
567         } else {
568             return $self->close;
569         }
570
571         # deal with EAGAIN or partial write:
572         my $tmpio = tmpio($self, $bref, $written) or return 0;
573
574         # wbuf may be an empty array if we're being called inside
575         # ->flush_write via CODE bref:
576         push @{$self->{wbuf}}, $tmpio; # autovivifies
577         return 0;
578     }
579 }
580
581 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
582
583 sub msg_more ($$) {
584     my $self = $_[0];
585     my $sock = $self->{sock} or return 1;
586     my $wbuf = $self->{wbuf};
587
588     if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
589                 !$sock->can('stop_SSL')) {
590         my $n = send($sock, $_[1], MSG_MORE);
591         if (defined $n) {
592             my $nlen = length($_[1]) - $n;
593             return 1 if $nlen == 0; # all done!
594             # queue up the unwritten substring:
595             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
596             push @{$self->{wbuf}}, $tmpio; # autovivifies
597             epwait($sock, EPOLLOUT|EPOLLONESHOT);
598             return 0;
599         }
600     }
601
602     # don't redispatch into NNTPdeflate::write
603     PublicInbox::DS::write($self, \($_[1]));
604 }
605
606 sub epwait ($$) {
607     my ($sock, $ev) = @_;
608     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
609         croak("EPOLL_CTL_MOD($sock): $!");
610 }
611
612 # return true if complete, false if incomplete (or failure)
613 sub accept_tls_step ($) {
614     my ($self) = @_;
615     my $sock = $self->{sock} or return;
616     return 1 if $sock->accept_SSL;
617     return $self->close if $! != EAGAIN;
618     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
619     epwait($sock, $ev | EPOLLONESHOT);
620     unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
621     0;
622 }
623
624 # return true if complete, false if incomplete (or failure)
625 sub shutdn_tls_step ($) {
626     my ($self) = @_;
627     my $sock = $self->{sock} or return;
628     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
629     return $self->close if $! != EAGAIN;
630     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
631     epwait($sock, $ev | EPOLLONESHOT);
632     unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
633     0;
634 }
635
636 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
637 # or fork w/o exec, so no inadvertent socket sharing
638 sub shutdn ($) {
639     my ($self) = @_;
640     my $sock = $self->{sock} or return;
641     if ($sock->can('stop_SSL')) {
642         shutdn_tls_step($self);
643     } else {
644         $self->close;
645     }
646 }
647
648 sub dwaitpid ($;$$) {
649         my ($pid, $cb, $arg) = @_;
650         if ($in_loop) {
651                 push @$wait_pids, [ $pid, $cb, $arg ];
652                 # We could've just missed our SIGCHLD, cover it, here:
653                 enqueue_reap();
654         } else {
655                 my $ret = waitpid($pid, 0);
656                 if ($ret == $pid) {
657                         if ($cb) {
658                                 eval { $cb->($arg, $pid) };
659                                 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
660                         }
661                 } else {
662                         carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
663                 }
664         }
665 }
666
667 sub expire_old () {
668         my $cur = $EXPMAP or return;
669         $EXPMAP = undef;
670         my $old = now() - $EXPTIME;
671         while (my ($fd, $idle_at) = each %$cur) {
672                 if ($idle_at < $old) {
673                         my $ds_obj = $DescriptorMap{$fd};
674                         $EXPMAP->{$fd} = $idle_at if !$ds_obj->shutdn;
675                 } else {
676                         $EXPMAP->{$fd} = $idle_at;
677                 }
678         }
679         add_uniq_timer('expire', 60, \&expire_old) if $EXPMAP;
680 }
681
682 sub update_idle_time {
683         my ($self) = @_;
684         my $sock = $self->{sock} or return;
685         $EXPMAP->{fileno($sock)} = now();
686         add_uniq_timer('expire', 60, \&expire_old);
687 }
688
689 sub not_idle_long {
690         my ($self, $now) = @_;
691         my $sock = $self->{sock} or return;
692         my $idle_at = $EXPMAP->{fileno($sock)} or return;
693         ($idle_at + $EXPTIME) > $now;
694 }
695
696 1;
697
698 =head1 AUTHORS (Danga::Socket)
699
700 Brad Fitzpatrick <brad@danga.com> - author
701
702 Michael Granger <ged@danga.com> - docs, testing
703
704 Mark Smith <junior@danga.com> - contributor, heavy user, testing
705
706 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits