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