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