]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: drop ::later support
[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 =head2 C<< CLASS->EventLoop() >>
159
160 Start processing IO events. In most daemon programs this never exits. See
161 C<PostLoopCallback> below for how to exit the loop.
162
163 =cut
164
165 sub now () { clock_gettime(CLOCK_MONOTONIC) }
166
167 sub next_tick () {
168         my $q = $nextq or return;
169         $nextq = undef;
170         $Stack{cur_runq} = $q;
171         for my $obj (@$q) {
172                 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
173                 # https://rt.perl.org/Public/Bug/Display.html?id=114340
174                 if (blessed($obj)) {
175                         $obj->event_step;
176                 } else {
177                         $obj->();
178                 }
179         }
180         delete $Stack{cur_runq};
181 }
182
183 # runs timers and returns milliseconds for next one, or next event loop
184 sub RunTimers {
185         next_tick();
186
187         return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
188
189         my $now = now();
190
191         # Run expired timers
192         while (@Timers && $Timers[0][0] <= $now) {
193                 my $to_run = shift(@Timers);
194                 delete $UniqTimer{$to_run->[1] // ''};
195                 $to_run->[2]->(@$to_run[3..$#$to_run]);
196         }
197
198         # timers may enqueue into nextq:
199         return 0 if ($nextq || $ToClose);
200
201         return $LoopTimeout unless @Timers;
202
203         # convert time to an even number of milliseconds, adding 1
204         # extra, otherwise floating point fun can occur and we'll
205         # call RunTimers like 20-30 times, each returning a timeout
206         # of 0.0000212 seconds
207         my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
208
209         # -1 is an infinite timeout, so prefer a real timeout
210         ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout
211 }
212
213 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
214
215 sub block_signals () {
216         my $oldset = POSIX::SigSet->new;
217         my $newset = POSIX::SigSet->new;
218         $newset->fillset or die "fillset: $!";
219         sig_setmask($newset, $oldset);
220         $oldset;
221 }
222
223 # We can't use waitpid(-1) safely here since it can hit ``, system(),
224 # and other things.  So we scan the $wait_pids list, which is hopefully
225 # not too big.  We keep $wait_pids small by not calling dwaitpid()
226 # until we've hit EOF when reading the stdout of the child.
227
228 sub reap_pids {
229         $reap_armed = undef;
230         my $tmp = $wait_pids or return;
231         $wait_pids = undef;
232         $Stack{reap_runq} = $tmp;
233         my $oldset = block_signals();
234         foreach my $ary (@$tmp) {
235                 my ($pid, $cb, $arg) = @$ary;
236                 my $ret = waitpid($pid, WNOHANG);
237                 if ($ret == 0) {
238                         push @$wait_pids, $ary; # autovivifies @$wait_pids
239                 } elsif ($ret == $pid) {
240                         if ($cb) {
241                                 eval { $cb->($arg, $pid) };
242                                 warn "E: dwaitpid($pid) in_loop: $@" if $@;
243                         }
244                 } else {
245                         warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
246                 }
247         }
248         sig_setmask($oldset);
249         delete $Stack{reap_runq};
250 }
251
252 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
253 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
254
255 sub in_loop () { $in_loop }
256
257 # Internal function: run the post-event callback, send read events
258 # for pushed-back data, and close pending connections.  returns 1
259 # if event loop should continue, or 0 to shut it all down.
260 sub PostEventLoop () {
261         # now we can close sockets that wanted to close during our event
262         # processing.  (we didn't want to close them during the loop, as we
263         # didn't want fd numbers being reused and confused during the event
264         # loop)
265         if (my $close_now = $ToClose) {
266                 $ToClose = undef; # will be autovivified on push
267                 @$close_now = map { fileno($_) } @$close_now;
268
269                 # order matters, destroy expiry times, first:
270                 delete @$EXPMAP{@$close_now};
271
272                 # ->DESTROY methods may populate ToClose
273                 delete @DescriptorMap{@$close_now};
274         }
275
276         # by default we keep running, unless a postloop callback cancels it
277         $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
278 }
279
280 sub EventLoop {
281     $Epoll //= _InitPoller();
282     local $in_loop = 1;
283     my @events;
284     do {
285         my $timeout = RunTimers();
286
287         # get up to 1000 events
288         epoll_wait($Epoll, 1000, $timeout, \@events);
289         for my $fd (@events) {
290             # it's possible epoll_wait returned many events, including some at the end
291             # that ones in the front triggered unregister-interest actions.  if we
292             # can't find the %sock entry, it's because we're no longer interested
293             # 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<EventLoop>.
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 # n.b.: use ->write/->read for this buffer to allow compatibility with
498 # PerlIO::mmap or PerlIO::scalar if needed
499 sub tmpio ($$$) {
500         my ($self, $bref, $off) = @_;
501         my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
502                 return drop($self, "tmpfile $!");
503         $fh->autoflush(1);
504         my $len = length($$bref) - $off;
505         print $fh substr($$bref, $off, $len) or
506                 return drop($self, "write ($len): $!");
507         [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
508 }
509
510 =head2 C<< $obj->write( $data ) >>
511
512 Write the specified data to the underlying handle.  I<data> may be scalar,
513 scalar ref, code ref (to run when there).
514 Returns 1 if writes all went through, or 0 if there are writes in queue. If
515 it returns 1, caller should stop waiting for 'writable' events)
516
517 =cut
518 sub write {
519     my ($self, $data) = @_;
520
521     # nobody should be writing to closed sockets, but caller code can
522     # do two writes within an event, have the first fail and
523     # disconnect the other side (whose destructor then closes the
524     # calling object, but it's still in a method), and then the
525     # now-dead object does its second write.  that is this case.  we
526     # just lie and say it worked.  it'll be dead soon and won't be
527     # hurt by this lie.
528     my $sock = $self->{sock} or return 1;
529     my $ref = ref $data;
530     my $bref = $ref ? $data : \$data;
531     my $wbuf = $self->{wbuf};
532     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
533         if ($ref eq 'CODE') {
534             push @$wbuf, $bref;
535         } else {
536             my $tmpio = $wbuf->[-1];
537             if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
538                 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
539             } else {
540                 my $tmpio = tmpio($self, $bref, 0) or return 0;
541                 push @$wbuf, $tmpio;
542             }
543         }
544         return 0;
545     } elsif ($ref eq 'CODE') {
546         $bref->($self);
547         return 1;
548     } else {
549         my $to_write = length($$bref);
550         my $written = syswrite($sock, $$bref, $to_write);
551
552         if (defined $written) {
553             return 1 if $written == $to_write;
554             requeue($self); # runs: event_step -> flush_write
555         } elsif ($! == EAGAIN) {
556             my $ev = epbit($sock, EPOLLOUT) or return $self->close;
557             epwait($sock, $ev | EPOLLONESHOT);
558             $written = 0;
559         } else {
560             return $self->close;
561         }
562
563         # deal with EAGAIN or partial write:
564         my $tmpio = tmpio($self, $bref, $written) or return 0;
565
566         # wbuf may be an empty array if we're being called inside
567         # ->flush_write via CODE bref:
568         push @{$self->{wbuf}}, $tmpio; # autovivifies
569         return 0;
570     }
571 }
572
573 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
574
575 sub msg_more ($$) {
576     my $self = $_[0];
577     my $sock = $self->{sock} or return 1;
578     my $wbuf = $self->{wbuf};
579
580     if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
581                 !$sock->can('stop_SSL')) {
582         my $n = send($sock, $_[1], MSG_MORE);
583         if (defined $n) {
584             my $nlen = length($_[1]) - $n;
585             return 1 if $nlen == 0; # all done!
586             # queue up the unwritten substring:
587             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
588             push @{$self->{wbuf}}, $tmpio; # autovivifies
589             epwait($sock, EPOLLOUT|EPOLLONESHOT);
590             return 0;
591         }
592     }
593
594     # don't redispatch into NNTPdeflate::write
595     PublicInbox::DS::write($self, \($_[1]));
596 }
597
598 sub epwait ($$) {
599     my ($sock, $ev) = @_;
600     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
601         croak("EPOLL_CTL_MOD($sock): $!");
602 }
603
604 # return true if complete, false if incomplete (or failure)
605 sub accept_tls_step ($) {
606     my ($self) = @_;
607     my $sock = $self->{sock} or return;
608     return 1 if $sock->accept_SSL;
609     return $self->close if $! != EAGAIN;
610     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
611     epwait($sock, $ev | EPOLLONESHOT);
612     unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
613     0;
614 }
615
616 # return true if complete, false if incomplete (or failure)
617 sub shutdn_tls_step ($) {
618     my ($self) = @_;
619     my $sock = $self->{sock} or return;
620     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
621     return $self->close if $! != EAGAIN;
622     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
623     epwait($sock, $ev | EPOLLONESHOT);
624     unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
625     0;
626 }
627
628 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
629 # or fork w/o exec, so no inadvertent socket sharing
630 sub shutdn ($) {
631     my ($self) = @_;
632     my $sock = $self->{sock} or return;
633     if ($sock->can('stop_SSL')) {
634         shutdn_tls_step($self);
635     } else {
636         $self->close;
637     }
638 }
639
640 sub dwaitpid ($;$$) {
641         my ($pid, $cb, $arg) = @_;
642         if ($in_loop) {
643                 push @$wait_pids, [ $pid, $cb, $arg ];
644                 # We could've just missed our SIGCHLD, cover it, here:
645                 enqueue_reap();
646         } else {
647                 my $ret = waitpid($pid, 0);
648                 if ($ret == $pid) {
649                         if ($cb) {
650                                 eval { $cb->($arg, $pid) };
651                                 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
652                         }
653                 } else {
654                         carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
655                 }
656         }
657 }
658
659 sub expire_old () {
660         my $cur = $EXPMAP or return;
661         $EXPMAP = undef;
662         my $old = now() - $EXPTIME;
663         while (my ($fd, $idle_at) = each %$cur) {
664                 if ($idle_at < $old) {
665                         my $ds_obj = $DescriptorMap{$fd};
666                         $EXPMAP->{$fd} = $idle_at if !$ds_obj->shutdn;
667                 } else {
668                         $EXPMAP->{$fd} = $idle_at;
669                 }
670         }
671         add_uniq_timer('expire', 60, \&expire_old) if $EXPMAP;
672 }
673
674 sub update_idle_time {
675         my ($self) = @_;
676         my $sock = $self->{sock} or return;
677         $EXPMAP->{fileno($sock)} = now();
678         add_uniq_timer('expire', 60, \&expire_old);
679 }
680
681 sub not_idle_long {
682         my ($self, $now) = @_;
683         my $sock = $self->{sock} or return;
684         my $idle_at = $EXPMAP->{fileno($sock)} or return;
685         ($idle_at + $EXPTIME) > $now;
686 }
687
688 1;
689
690 =head1 AUTHORS (Danga::Socket)
691
692 Brad Fitzpatrick <brad@danga.com> - author
693
694 Michael Granger <ged@danga.com> - docs, testing
695
696 Mark Smith <junior@danga.com> - contributor, heavy user, testing
697
698 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits