]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
daemon: don't bother checking for existing FD flags
[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 $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                 $wait_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 || $wait_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 # We can't use waitpid(-1) safely here since it can hit ``, system(),
205 # and other things.  So we scan the $wait_pids list, which is hopefully
206 # not too big.  We keep $wait_pids small by not calling dwaitpid()
207 # until we've hit EOF when reading the stdout of the child.
208
209 sub reap_pids {
210         $reap_armed = undef;
211         my $tmp = $wait_pids or return;
212         $wait_pids = undef;
213         $Stack{reap_runq} = $tmp;
214         my $oldset = block_signals();
215         foreach my $ary (@$tmp) {
216                 my ($pid, $cb, $arg) = @$ary;
217                 my $ret = waitpid($pid, WNOHANG);
218                 if ($ret == 0) {
219                         push @$wait_pids, $ary; # autovivifies @$wait_pids
220                 } elsif ($ret == $pid) {
221                         if ($cb) {
222                                 eval { $cb->($arg, $pid) };
223                                 warn "E: dwaitpid($pid) in_loop: $@" if $@;
224                         }
225                 } else {
226                         warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
227                 }
228         }
229         sig_setmask($oldset);
230         delete $Stack{reap_runq};
231 }
232
233 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
234 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
235
236 sub in_loop () { $in_loop }
237
238 # Internal function: run the post-event callback, send read events
239 # for pushed-back data, and close pending connections.  returns 1
240 # if event loop should continue, or 0 to shut it all down.
241 sub PostEventLoop () {
242         # now we can close sockets that wanted to close during our event
243         # processing.  (we didn't want to close them during the loop, as we
244         # didn't want fd numbers being reused and confused during the event
245         # loop)
246         if (my $close_now = $ToClose) {
247                 $ToClose = undef; # will be autovivified on push
248                 @$close_now = map { fileno($_) } @$close_now;
249
250                 # ->DESTROY methods may populate ToClose
251                 delete @DescriptorMap{@$close_now};
252         }
253
254         # by default we keep running, unless a postloop callback cancels it
255         $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
256 }
257
258 # Start processing IO events. In most daemon programs this never exits. See
259 # C<PostLoopCallback> for how to exit the loop.
260 sub event_loop (;$$) {
261         my ($sig, $oldset) = @_;
262         $Epoll //= _InitPoller();
263         require PublicInbox::Sigfd if $sig;
264         my $sigfd = PublicInbox::Sigfd->new($sig, 1) if $sig;
265         local @SIG{keys %$sig} = values(%$sig) if $sig && !$sigfd;
266         local $SIG{PIPE} = 'IGNORE';
267         if (!$sigfd && $sig) {
268                 # wake up every second to accept signals if we don't
269                 # have signalfd or IO::KQueue:
270                 sig_setmask($oldset);
271                 PublicInbox::DS->SetLoopTimeout(1000);
272         }
273         $_[0] = $sigfd = $sig = undef; # $_[0] == sig
274         local $in_loop = 1;
275         my @events;
276         do {
277                 my $timeout = RunTimers();
278
279                 # get up to 1000 events
280                 epoll_wait($Epoll, 1000, $timeout, \@events);
281                 for my $fd (@events) {
282                         # it's possible epoll_wait returned many events,
283                         # including some at the end that ones in the front
284                         # triggered unregister-interest actions.  if we can't
285                         # find the %sock entry, it's because we're no longer
286                         # interested in that event.
287
288                         # guard stack-not-refcounted w/ Carp + @DB::args
289                         my $obj = $DescriptorMap{$fd};
290                         $obj->event_step;
291                 }
292         } while (PostEventLoop());
293 }
294
295 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
296
297 Sets post loop callback function.  Pass a subref and it will be
298 called every time the event loop finishes.
299
300 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
301 and it will exit.
302
303 The callback function will be passed two parameters: \%DescriptorMap
304
305 =cut
306 sub SetPostLoopCallback {
307     my ($class, $ref) = @_;
308
309     # global callback
310     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
311 }
312
313 #####################################################################
314 ### PublicInbox::DS-the-object code
315 #####################################################################
316
317 =head2 OBJECT METHODS
318
319 =head2 C<< CLASS->new( $socket ) >>
320
321 Create a new PublicInbox::DS subclass object for the given I<socket> which will
322 react to events on it during the C<event_loop>.
323
324 This is normally (always?) called from your subclass via:
325
326   $class->SUPER::new($socket);
327
328 =cut
329 sub new {
330     my ($self, $sock, $ev) = @_;
331     $self->{sock} = $sock;
332     my $fd = fileno($sock);
333
334     $Epoll //= _InitPoller();
335 retry:
336     if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
337         if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
338             $ev &= ~EPOLLEXCLUSIVE;
339             goto retry;
340         }
341         die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
342     }
343     croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
344         if defined($DescriptorMap{$fd});
345
346     $DescriptorMap{$fd} = $self;
347 }
348
349 # for IMAP, NNTP, and POP3 which greet clients upon connect
350 sub greet {
351         my ($self, $sock) = @_;
352         my $ev = EPOLLIN;
353         my $wbuf;
354         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
355                 return CORE::close($sock) if $! != EAGAIN;
356                 $ev = PublicInbox::TLS::epollbit() or return CORE::close($sock);
357                 $wbuf = [ \&accept_tls_step, $self->can('do_greet')];
358         }
359         new($self, $sock, $ev | EPOLLONESHOT);
360         if ($wbuf) {
361                 $self->{wbuf} = $wbuf;
362         } else {
363                 $self->do_greet;
364         }
365         $self;
366 }
367
368 #####################################################################
369 ### I N S T A N C E   M E T H O D S
370 #####################################################################
371
372 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
373
374 =head2 C<< $obj->close >>
375
376 Close the socket.
377
378 =cut
379 sub close {
380     my ($self) = @_;
381     my $sock = delete $self->{sock} or return;
382
383     # we need to flush our write buffer, as there may
384     # be self-referential closures (sub { $client->close })
385     # preventing the object from being destroyed
386     delete $self->{wbuf};
387
388     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
389     # notifications about it
390     my $fd = fileno($sock);
391     epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
392         croak("EPOLL_CTL_DEL($self/$sock): $!");
393
394     # we explicitly don't delete from DescriptorMap here until we
395     # actually close the socket, as we might be in the middle of
396     # processing an epoll_wait/etc that returned hundreds of fds, one
397     # of which is not yet processed and is what we're closing.  if we
398     # keep it in DescriptorMap, then the event harnesses can just
399     # looked at $pob->{sock} == undef and ignore it.  but if it's an
400     # un-accounted for fd, then it (understandably) freak out a bit
401     # and emit warnings, thinking their state got off.
402
403     # defer closing the actual socket until the event loop is done
404     # processing this round of events.  (otherwise we might reuse fds)
405     push @$ToClose, $sock; # autovivifies $ToClose
406
407     return 0;
408 }
409
410 # portable, non-thread-safe sendfile emulation (no pread, yet)
411 sub send_tmpio ($$) {
412     my ($sock, $tmpio) = @_;
413
414     sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
415     my $n = $tmpio->[2] // 65536;
416     $n = 65536 if $n > 65536;
417     defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
418     my $written = 0;
419     while ($to_write > 0) {
420         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
421             $written += $w;
422             $to_write -= $w;
423         } else {
424             return if $written == 0;
425             last;
426         }
427     }
428     $tmpio->[1] += $written; # offset
429     $tmpio->[2] -= $written if defined($tmpio->[2]); # length
430     $written;
431 }
432
433 sub epbit ($$) { # (sock, default)
434         $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
435 }
436
437 # returns 1 if done, 0 if incomplete
438 sub flush_write ($) {
439     my ($self) = @_;
440     my $sock = $self->{sock} or return;
441     my $wbuf = $self->{wbuf} or return 1;
442
443 next_buf:
444     while (my $bref = $wbuf->[0]) {
445         if (ref($bref) ne 'CODE') {
446             while ($sock) {
447                 my $w = send_tmpio($sock, $bref); # bref is tmpio
448                 if (defined $w) {
449                     if ($w == 0) {
450                         shift @$wbuf;
451                         goto next_buf;
452                     }
453                 } elsif ($! == EAGAIN) {
454                     my $ev = epbit($sock, EPOLLOUT) or return $self->close;
455                     epwait($sock, $ev | EPOLLONESHOT);
456                     return 0;
457                 } else {
458                     return $self->close;
459                 }
460             }
461         } else { #(ref($bref) eq 'CODE') {
462             shift @$wbuf;
463             my $before = scalar(@$wbuf);
464             $bref->($self);
465
466             # bref may be enqueueing more CODE to call (see accept_tls_step)
467             return 0 if (scalar(@$wbuf) > $before);
468         }
469     } # while @$wbuf
470
471     delete $self->{wbuf};
472     1; # all done
473 }
474
475 sub rbuf_idle ($$) {
476     my ($self, $rbuf) = @_;
477     if ($$rbuf eq '') { # who knows how long till we can read again
478         delete $self->{rbuf};
479     } else {
480         $self->{rbuf} = $rbuf;
481     }
482 }
483
484 sub do_read ($$$;$) {
485     my ($self, $rbuf, $len, $off) = @_;
486     my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
487     return ($r == 0 ? $self->close : $r) if defined $r;
488     # common for clients to break connections without warning,
489     # would be too noisy to log here:
490     if ($! == EAGAIN) {
491         my $ev = epbit($sock, EPOLLIN) or return $self->close;
492         epwait($sock, $ev | EPOLLONESHOT);
493         rbuf_idle($self, $rbuf);
494         0;
495     } else {
496         $self->close;
497     }
498 }
499
500 # drop the socket if we hit unrecoverable errors on our system which
501 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
502 sub drop {
503     my $self = shift;
504     carp(@_);
505     $self->close;
506 }
507
508 sub tmpio ($$$) {
509         my ($self, $bref, $off) = @_;
510         my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
511                 return drop($self, "tmpfile $!");
512         $fh->autoflush(1);
513         my $len = length($$bref) - $off;
514         my $n = syswrite($fh, $$bref, $len, $off) //
515                 return drop($self, "write ($len): $!");
516         $n == $len or return drop($self, "wrote $n < $len bytes");
517         [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
518 }
519
520 =head2 C<< $obj->write( $data ) >>
521
522 Write the specified data to the underlying handle.  I<data> may be scalar,
523 scalar ref, code ref (to run when there).
524 Returns 1 if writes all went through, or 0 if there are writes in queue. If
525 it returns 1, caller should stop waiting for 'writable' events)
526
527 =cut
528 sub write {
529     my ($self, $data) = @_;
530
531     # nobody should be writing to closed sockets, but caller code can
532     # do two writes within an event, have the first fail and
533     # disconnect the other side (whose destructor then closes the
534     # calling object, but it's still in a method), and then the
535     # now-dead object does its second write.  that is this case.  we
536     # just lie and say it worked.  it'll be dead soon and won't be
537     # hurt by this lie.
538     my $sock = $self->{sock} or return 1;
539     my $ref = ref $data;
540     my $bref = $ref ? $data : \$data;
541     my $wbuf = $self->{wbuf};
542     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
543         if ($ref eq 'CODE') {
544             push @$wbuf, $bref;
545         } else {
546             my $tmpio = $wbuf->[-1];
547             if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
548                 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
549             } else {
550                 my $tmpio = tmpio($self, $bref, 0) or return 0;
551                 push @$wbuf, $tmpio;
552             }
553         }
554         return 0;
555     } elsif ($ref eq 'CODE') {
556         $bref->($self);
557         return 1;
558     } else {
559         my $to_write = length($$bref);
560         my $written = syswrite($sock, $$bref, $to_write);
561
562         if (defined $written) {
563             return 1 if $written == $to_write;
564             requeue($self); # runs: event_step -> flush_write
565         } elsif ($! == EAGAIN) {
566             my $ev = epbit($sock, EPOLLOUT) or return $self->close;
567             epwait($sock, $ev | EPOLLONESHOT);
568             $written = 0;
569         } else {
570             return $self->close;
571         }
572
573         # deal with EAGAIN or partial write:
574         my $tmpio = tmpio($self, $bref, $written) or return 0;
575
576         # wbuf may be an empty array if we're being called inside
577         # ->flush_write via CODE bref:
578         push @{$self->{wbuf}}, $tmpio; # autovivifies
579         return 0;
580     }
581 }
582
583 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
584
585 sub msg_more ($$) {
586     my $self = $_[0];
587     my $sock = $self->{sock} or return 1;
588     my $wbuf = $self->{wbuf};
589
590     if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
591                 !$sock->can('stop_SSL')) {
592         my $n = send($sock, $_[1], MSG_MORE);
593         if (defined $n) {
594             my $nlen = length($_[1]) - $n;
595             return 1 if $nlen == 0; # all done!
596             # queue up the unwritten substring:
597             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
598             push @{$self->{wbuf}}, $tmpio; # autovivifies
599             epwait($sock, EPOLLOUT|EPOLLONESHOT);
600             return 0;
601         }
602     }
603
604     # don't redispatch into NNTPdeflate::write
605     PublicInbox::DS::write($self, \($_[1]));
606 }
607
608 sub epwait ($$) {
609     my ($sock, $ev) = @_;
610     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
611         croak("EPOLL_CTL_MOD($sock): $!");
612 }
613
614 # return true if complete, false if incomplete (or failure)
615 sub accept_tls_step ($) {
616     my ($self) = @_;
617     my $sock = $self->{sock} or return;
618     return 1 if $sock->accept_SSL;
619     return $self->close if $! != EAGAIN;
620     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
621     epwait($sock, $ev | EPOLLONESHOT);
622     unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
623     0;
624 }
625
626 # return true if complete, false if incomplete (or failure)
627 sub shutdn_tls_step ($) {
628     my ($self) = @_;
629     my $sock = $self->{sock} or return;
630     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
631     return $self->close if $! != EAGAIN;
632     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
633     epwait($sock, $ev | EPOLLONESHOT);
634     unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
635     0;
636 }
637
638 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
639 # or fork w/o exec, so no inadvertent socket sharing
640 sub shutdn ($) {
641     my ($self) = @_;
642     my $sock = $self->{sock} or return;
643     if ($sock->can('stop_SSL')) {
644         shutdn_tls_step($self);
645     } else {
646         $self->close;
647     }
648 }
649
650 sub dflush {} # overridden by DSdeflate
651 sub compressed {} # overridden by DSdeflate
652 sub long_response_done {} # overridden by Net::NNTP
653
654 sub long_step {
655         my ($self) = @_;
656         # wbuf is unset or empty, here; {long} may add to it
657         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
658         my $more = eval { $cb->($self, @args) };
659         if ($@ || !$self->{sock}) { # something bad happened...
660                 delete $self->{long_cb};
661                 my $elapsed = now() - $t0;
662                 $@ and warn("$@ during long response[$fd] - ",
663                                 sprintf('%0.6f', $elapsed),"\n");
664                 $self->out(" deferred[$fd] aborted - %0.6f", $elapsed);
665                 $self->close;
666         } elsif ($more) { # $self->{wbuf}:
667                 # control passed to ibx_async_cat if $more == \undef
668                 requeue_once($self) if !ref($more);
669         } else { # all done!
670                 delete $self->{long_cb};
671                 $self->long_response_done;
672                 my $elapsed = now() - $t0;
673                 my $fd = fileno($self->{sock});
674                 $self->out(" deferred[$fd] done - %0.6f", $elapsed);
675                 my $wbuf = $self->{wbuf}; # do NOT autovivify
676                 requeue($self) unless $wbuf && @$wbuf;
677         }
678 }
679
680 sub requeue_once {
681         my ($self) = @_;
682         # COMPRESS users all share the same DEFLATE context.
683         # Flush it here to ensure clients don't see each other's data
684         $self->dflush;
685
686         # no recursion, schedule another call ASAP,
687         # but only after all pending writes are done.
688         # autovivify wbuf.  wbuf may be populated by $cb,
689         # no need to rearm if so: (push returns new size of array)
690         $self->requeue if push(@{$self->{wbuf}}, \&long_step) == 1;
691 }
692
693 sub long_response ($$;@) {
694         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
695         my $sock = $self->{sock} or return;
696         # make sure we disable reading during a long response,
697         # clients should not be sending us stuff and making us do more
698         # work while we are stream a response to them
699         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
700         long_step($self); # kick off!
701         undef;
702 }
703
704 sub dwaitpid ($;$$) {
705         my ($pid, $cb, $arg) = @_;
706         if ($in_loop) {
707                 push @$wait_pids, [ $pid, $cb, $arg ];
708                 # We could've just missed our SIGCHLD, cover it, here:
709                 enqueue_reap();
710         } else {
711                 my $ret = waitpid($pid, 0);
712                 if ($ret == $pid) {
713                         if ($cb) {
714                                 eval { $cb->($arg, $pid) };
715                                 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
716                         }
717                 } else {
718                         carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
719                 }
720         }
721 }
722
723 1;
724
725 =head1 AUTHORS (Danga::Socket)
726
727 Brad Fitzpatrick <brad@danga.com> - author
728
729 Michael Granger <ged@danga.com> - docs, testing
730
731 Mark Smith <junior@danga.com> - contributor, heavy user, testing
732
733 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits