]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
No ext_urls
[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 ECHILD EINTR);
34 use Carp qw(carp croak);
35 our @EXPORT_OK = qw(now msg_more awaitpid add_timer add_uniq_timer);
36
37 my %Stack;
38 my $nextq; # queue for next_tick
39 my $AWAIT_PIDS; # pid => [ $callback, @args ]
40 my $reap_armed;
41 my $ToClose; # sockets to close when event loop is done
42 our (
43      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
44      $Epoll,                     # Global epoll fd (or DSKQXS ref)
45      $ep_io,                     # IO::Handle for Epoll
46
47      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
48
49      $LoopTimeout,               # timeout of event loop in milliseconds
50      @Timers,                    # timers
51      %UniqTimer,
52      $in_loop,
53      );
54
55 Reset();
56
57 #####################################################################
58 ### C L A S S   M E T H O D S
59 #####################################################################
60
61 =head2 C<< CLASS->Reset() >>
62
63 Reset all state
64
65 =cut
66 sub Reset {
67         do {
68                 $in_loop = undef; # first in case DESTROY callbacks use this
69                 %DescriptorMap = ();
70                 @Timers = ();
71                 %UniqTimer = ();
72                 $PostLoopCallback = undef;
73
74                 # we may be iterating inside one of these on our stack
75                 my @q = delete @Stack{keys %Stack};
76                 for my $q (@q) { @$q = () }
77                 $AWAIT_PIDS = $nextq = $ToClose = undef;
78                 $ep_io = undef; # closes real $Epoll FD
79                 $Epoll = undef; # may call DSKQXS::DESTROY
80         } while (@Timers || keys(%Stack) || $nextq || $AWAIT_PIDS ||
81                 $ToClose || keys(%DescriptorMap) ||
82                 $PostLoopCallback || keys(%UniqTimer));
83
84         $reap_armed = undef;
85         $LoopTimeout = -1;  # no timeout by default
86 }
87
88 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
89
90 Set the loop timeout for the event loop to some value in milliseconds.
91
92 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
93 immediately.
94
95 =cut
96 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
97
98 sub _add_named_timer {
99         my ($name, $secs, $coderef, @args) = @_;
100         my $fire_time = now() + $secs;
101         my $timer = [$fire_time, $name, $coderef, @args];
102
103         if (!@Timers || $fire_time >= $Timers[-1][0]) {
104                 push @Timers, $timer;
105                 return $timer;
106         }
107
108         # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
109         # but it was compared against calendar queues, heaps, naive push/sort,
110         # and a bunch of other versions, and found to be fastest with a large
111         # variety of datasets.)
112         for (my $i = 0; $i < @Timers; $i++) {
113                 if ($Timers[$i][0] > $fire_time) {
114                         splice(@Timers, $i, 0, $timer);
115                         return $timer;
116                 }
117         }
118         die "Shouldn't get here.";
119 }
120
121 sub add_timer { _add_named_timer(undef, @_) }
122
123 sub add_uniq_timer { # ($name, $secs, $coderef, @args) = @_;
124         $UniqTimer{$_[0]} //= _add_named_timer(@_);
125 }
126
127 # caller sets return value to $Epoll
128 sub _InitPoller () {
129         if (defined $PublicInbox::Syscall::SYS_epoll_create)  {
130                 my $fd = epoll_create();
131                 die "epoll_create: $!" if $fd < 0;
132                 open($ep_io, '+<&=', $fd) or return;
133                 fcntl($ep_io, F_SETFD, FD_CLOEXEC);
134                 $fd;
135         } else {
136                 my $cls;
137                 for (qw(DSKQXS DSPoll)) {
138                         $cls = "PublicInbox::$_";
139                         last if eval "require $cls";
140                 }
141                 $cls->import(qw(epoll_ctl epoll_wait));
142                 $cls->new;
143         }
144 }
145
146 sub now () { clock_gettime(CLOCK_MONOTONIC) }
147
148 sub next_tick () {
149         my $q = $nextq or return;
150         $nextq = undef;
151         $Stack{cur_runq} = $q;
152         for my $obj (@$q) {
153                 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
154                 # https://rt.perl.org/Public/Bug/Display.html?id=114340
155                 if (blessed($obj)) {
156                         $obj->event_step;
157                 } else {
158                         $obj->();
159                 }
160         }
161         delete $Stack{cur_runq};
162 }
163
164 # runs timers and returns milliseconds for next one, or next event loop
165 sub RunTimers {
166         next_tick();
167
168         return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
169
170         my $now = now();
171
172         # Run expired timers
173         while (@Timers && $Timers[0][0] <= $now) {
174                 my $to_run = shift(@Timers);
175                 delete $UniqTimer{$to_run->[1] // ''};
176                 $to_run->[2]->(@$to_run[3..$#$to_run]);
177         }
178
179         # timers may enqueue into nextq:
180         return 0 if ($nextq || $ToClose);
181
182         return $LoopTimeout unless @Timers;
183
184         # convert time to an even number of milliseconds, adding 1
185         # extra, otherwise floating point fun can occur and we'll
186         # call RunTimers like 20-30 times, each returning a timeout
187         # of 0.0000212 seconds
188         my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
189
190         # -1 is an infinite timeout, so prefer a real timeout
191         ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout
192 }
193
194 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
195
196 sub block_signals () {
197         my $oldset = POSIX::SigSet->new;
198         my $newset = POSIX::SigSet->new;
199         $newset->fillset or die "fillset: $!";
200         sig_setmask($newset, $oldset);
201         $oldset;
202 }
203
204 sub await_cb ($;@) {
205         my ($pid, @cb_args) = @_;
206         my $cb = shift @cb_args or return;
207         eval { $cb->($pid, @cb_args) };
208         warn "E: awaitpid($pid): $@" if $@;
209 }
210
211 # This relies on our Perl process is single-threaded, or at least
212 # no threads are spawning and waiting on processes (``, system(), etc...)
213 # Threads are officially discouraged by the Perl5 team, and I expect
214 # that to remain the case.
215 sub reap_pids {
216         $reap_armed = undef;
217         my $oldset = block_signals();
218         while (1) {
219                 my $pid = waitpid(-1, WNOHANG) // last;
220                 last if $pid <= 0;
221                 if (defined(my $cb_args = delete $AWAIT_PIDS->{$pid})) {
222                         await_cb($pid, @$cb_args) if $cb_args;
223                 } else {
224                         warn "W: reaped unknown PID=$pid: \$?=$?\n";
225                 }
226         }
227         sig_setmask($oldset);
228 }
229
230 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
231 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
232
233 sub in_loop () { $in_loop }
234
235 # Internal function: run the post-event callback, send read events
236 # for pushed-back data, and close pending connections.  returns 1
237 # if event loop should continue, or 0 to shut it all down.
238 sub PostEventLoop () {
239         # now we can close sockets that wanted to close during our event
240         # processing.  (we didn't want to close them during the loop, as we
241         # didn't want fd numbers being reused and confused during the event
242         # loop)
243         if (my $close_now = $ToClose) {
244                 $ToClose = undef; # will be autovivified on push
245                 @$close_now = map { fileno($_) } @$close_now;
246
247                 # ->DESTROY methods may populate ToClose
248                 delete @DescriptorMap{@$close_now};
249         }
250
251         # by default we keep running, unless a postloop callback cancels it
252         $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
253 }
254
255 # Start processing IO events. In most daemon programs this never exits. See
256 # C<PostLoopCallback> for how to exit the loop.
257 sub event_loop (;$$) {
258         my ($sig, $oldset) = @_;
259         $Epoll //= _InitPoller();
260         require PublicInbox::Sigfd if $sig;
261         my $sigfd = PublicInbox::Sigfd->new($sig, 1) if $sig;
262         local @SIG{keys %$sig} = values(%$sig) if $sig && !$sigfd;
263         local $SIG{PIPE} = 'IGNORE';
264         if (!$sigfd && $sig) {
265                 # wake up every second to accept signals if we don't
266                 # have signalfd or IO::KQueue:
267                 sig_setmask($oldset);
268                 PublicInbox::DS->SetLoopTimeout(1000);
269         }
270         $_[0] = $sigfd = $sig = undef; # $_[0] == sig
271         local $in_loop = 1;
272         my @events;
273         do {
274                 my $timeout = RunTimers();
275
276                 # get up to 1000 events
277                 epoll_wait($Epoll, 1000, $timeout, \@events);
278                 for my $fd (@events) {
279                         # it's possible epoll_wait returned many events,
280                         # including some at the end that ones in the front
281                         # triggered unregister-interest actions.  if we can't
282                         # find the %sock entry, it's because we're no longer
283                         # interested in that event.
284
285                         # guard stack-not-refcounted w/ Carp + @DB::args
286                         my $obj = $DescriptorMap{$fd};
287                         $obj->event_step;
288                 }
289         } while (PostEventLoop());
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<event_loop>.
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 # for IMAP, NNTP, and POP3 which greet clients upon connect
347 sub greet {
348         my ($self, $sock) = @_;
349         my $ev = EPOLLIN;
350         my $wbuf;
351         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
352                 return CORE::close($sock) if $! != EAGAIN;
353                 $ev = PublicInbox::TLS::epollbit() or return CORE::close($sock);
354                 $wbuf = [ \&accept_tls_step, $self->can('do_greet')];
355         }
356         new($self, $sock, $ev | EPOLLONESHOT);
357         if ($wbuf) {
358                 $self->{wbuf} = $wbuf;
359         } else {
360                 $self->do_greet;
361         }
362         $self;
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 sub tmpio ($$$) {
506         my ($self, $bref, $off) = @_;
507         my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
508                 return drop($self, "tmpfile $!");
509         $fh->autoflush(1);
510         my $len = length($$bref) - $off;
511         my $n = syswrite($fh, $$bref, $len, $off) //
512                 return drop($self, "write ($len): $!");
513         $n == $len or return drop($self, "wrote $n < $len bytes");
514         [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
515 }
516
517 =head2 C<< $obj->write( $data ) >>
518
519 Write the specified data to the underlying handle.  I<data> may be scalar,
520 scalar ref, code ref (to run when there).
521 Returns 1 if writes all went through, or 0 if there are writes in queue. If
522 it returns 1, caller should stop waiting for 'writable' events)
523
524 =cut
525 sub write {
526     my ($self, $data) = @_;
527
528     # nobody should be writing to closed sockets, but caller code can
529     # do two writes within an event, have the first fail and
530     # disconnect the other side (whose destructor then closes the
531     # calling object, but it's still in a method), and then the
532     # now-dead object does its second write.  that is this case.  we
533     # just lie and say it worked.  it'll be dead soon and won't be
534     # hurt by this lie.
535     my $sock = $self->{sock} or return 1;
536     my $ref = ref $data;
537     my $bref = $ref ? $data : \$data;
538     my $wbuf = $self->{wbuf};
539     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
540         if ($ref eq 'CODE') {
541             push @$wbuf, $bref;
542         } else {
543             my $tmpio = $wbuf->[-1];
544             if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
545                 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
546             } else {
547                 my $tmpio = tmpio($self, $bref, 0) or return 0;
548                 push @$wbuf, $tmpio;
549             }
550         }
551         return 0;
552     } elsif ($ref eq 'CODE') {
553         $bref->($self);
554         return 1;
555     } else {
556         my $to_write = length($$bref);
557         my $written = syswrite($sock, $$bref, $to_write);
558
559         if (defined $written) {
560             return 1 if $written == $to_write;
561             requeue($self); # runs: event_step -> flush_write
562         } elsif ($! == EAGAIN) {
563             my $ev = epbit($sock, EPOLLOUT) or return $self->close;
564             epwait($sock, $ev | EPOLLONESHOT);
565             $written = 0;
566         } else {
567             return $self->close;
568         }
569
570         # deal with EAGAIN or partial write:
571         my $tmpio = tmpio($self, $bref, $written) or return 0;
572
573         # wbuf may be an empty array if we're being called inside
574         # ->flush_write via CODE bref:
575         push @{$self->{wbuf}}, $tmpio; # autovivifies
576         return 0;
577     }
578 }
579
580 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
581
582 sub msg_more ($$) {
583     my $self = $_[0];
584     my $sock = $self->{sock} or return 1;
585     my $wbuf = $self->{wbuf};
586
587     if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
588                 !$sock->can('stop_SSL')) {
589         my $n = send($sock, $_[1], MSG_MORE);
590         if (defined $n) {
591             my $nlen = length($_[1]) - $n;
592             return 1 if $nlen == 0; # all done!
593             # queue up the unwritten substring:
594             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
595             push @{$self->{wbuf}}, $tmpio; # autovivifies
596             epwait($sock, EPOLLOUT|EPOLLONESHOT);
597             return 0;
598         }
599     }
600
601     # don't redispatch into NNTPdeflate::write
602     PublicInbox::DS::write($self, \($_[1]));
603 }
604
605 sub epwait ($$) {
606     my ($sock, $ev) = @_;
607     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
608         croak("EPOLL_CTL_MOD($sock): $!");
609 }
610
611 # return true if complete, false if incomplete (or failure)
612 sub accept_tls_step ($) {
613     my ($self) = @_;
614     my $sock = $self->{sock} or return;
615     return 1 if $sock->accept_SSL;
616     return $self->close if $! != EAGAIN;
617     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
618     epwait($sock, $ev | EPOLLONESHOT);
619     unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
620     0;
621 }
622
623 # return true if complete, false if incomplete (or failure)
624 sub shutdn_tls_step ($) {
625     my ($self) = @_;
626     my $sock = $self->{sock} or return;
627     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
628     return $self->close if $! != EAGAIN;
629     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
630     epwait($sock, $ev | EPOLLONESHOT);
631     unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
632     0;
633 }
634
635 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
636 # or fork w/o exec, so no inadvertent socket sharing
637 sub shutdn ($) {
638     my ($self) = @_;
639     my $sock = $self->{sock} or return;
640     if ($sock->can('stop_SSL')) {
641         shutdn_tls_step($self);
642     } else {
643         $self->close;
644     }
645 }
646
647 sub dflush {} # overridden by DSdeflate
648 sub compressed {} # overridden by DSdeflate
649 sub long_response_done {} # overridden by Net::NNTP
650
651 sub long_step {
652         my ($self) = @_;
653         # wbuf is unset or empty, here; {long} may add to it
654         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
655         my $more = eval { $cb->($self, @args) };
656         if ($@ || !$self->{sock}) { # something bad happened...
657                 delete $self->{long_cb};
658                 my $elapsed = now() - $t0;
659                 $@ and warn("$@ during long response[$fd] - ",
660                                 sprintf('%0.6f', $elapsed),"\n");
661                 $self->out(" deferred[$fd] aborted - %0.6f", $elapsed);
662                 $self->close;
663         } elsif ($more) { # $self->{wbuf}:
664                 # control passed to ibx_async_cat if $more == \undef
665                 requeue_once($self) if !ref($more);
666         } else { # all done!
667                 delete $self->{long_cb};
668                 $self->long_response_done;
669                 my $elapsed = now() - $t0;
670                 my $fd = fileno($self->{sock});
671                 $self->out(" deferred[$fd] done - %0.6f", $elapsed);
672                 my $wbuf = $self->{wbuf}; # do NOT autovivify
673                 requeue($self) unless $wbuf && @$wbuf;
674         }
675 }
676
677 sub requeue_once {
678         my ($self) = @_;
679         # COMPRESS users all share the same DEFLATE context.
680         # Flush it here to ensure clients don't see each other's data
681         $self->dflush;
682
683         # no recursion, schedule another call ASAP,
684         # but only after all pending writes are done.
685         # autovivify wbuf.  wbuf may be populated by $cb,
686         # no need to rearm if so: (push returns new size of array)
687         $self->requeue if push(@{$self->{wbuf}}, \&long_step) == 1;
688 }
689
690 sub long_response ($$;@) {
691         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
692         my $sock = $self->{sock} or return;
693         # make sure we disable reading during a long response,
694         # clients should not be sending us stuff and making us do more
695         # work while we are stream a response to them
696         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
697         long_step($self); # kick off!
698         undef;
699 }
700
701 sub awaitpid {
702         my ($pid, @cb_args) = @_; # @cb_args = ($cb, @args), $cb may be undef
703         $AWAIT_PIDS->{$pid} = \@cb_args if @cb_args;
704         # provide synchronous API
705         if (defined(wantarray) || (!$in_loop && !@cb_args)) {
706                 my $ret;
707 again:
708                 $ret = waitpid($pid, 0) // -2;
709                 if ($ret == $pid) {
710                         my $cb_args = delete $AWAIT_PIDS->{$pid};
711                         @cb_args = @$cb_args if !@cb_args && $cb_args;
712                         await_cb($pid, @cb_args);
713                 } else {
714                         goto again if $! == EINTR;
715                         carp "waitpid($pid): $!";
716                         delete $AWAIT_PIDS->{$pid};
717                 }
718                 return $ret;
719         } elsif ($in_loop) { # We could've just missed our SIGCHLD, cover it, here:
720                 enqueue_reap();
721         }
722 }
723
724 1;
725
726 =head1 AUTHORS (Danga::Socket)
727
728 Brad Fitzpatrick <brad@danga.com> - author
729
730 Michael Granger <ged@danga.com> - docs, testing
731
732 Mark Smith <junior@danga.com> - contributor, heavy user, testing
733
734 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits