]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: introduce awaitpid, switch ProcessPipe users
[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 awaitpid 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 $AWAIT_PIDS; # pid => [ $callback, @args ]
41 my $reap_armed;
42 my $ToClose; # sockets to close when event loop is done
43 our (
44      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
45      $Epoll,                     # Global epoll fd (or DSKQXS ref)
46      $ep_io,                     # IO::Handle for Epoll
47
48      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
49
50      $LoopTimeout,               # timeout of event loop in milliseconds
51      @Timers,                    # timers
52      %UniqTimer,
53      $in_loop,
54      );
55
56 Reset();
57
58 #####################################################################
59 ### C L A S S   M E T H O D S
60 #####################################################################
61
62 =head2 C<< CLASS->Reset() >>
63
64 Reset all state
65
66 =cut
67 sub Reset {
68         do {
69                 $in_loop = undef; # first in case DESTROY callbacks use this
70                 %DescriptorMap = ();
71                 @Timers = ();
72                 %UniqTimer = ();
73                 $PostLoopCallback = undef;
74
75                 # we may be iterating inside one of these on our stack
76                 my @q = delete @Stack{keys %Stack};
77                 for my $q (@q) { @$q = () }
78                 $AWAIT_PIDS = $wait_pids = $nextq = $ToClose = undef;
79                 $ep_io = undef; # closes real $Epoll FD
80                 $Epoll = undef; # may call DSKQXS::DESTROY
81         } while (@Timers || keys(%Stack) || $nextq || $wait_pids ||
82                 $ToClose || keys(%DescriptorMap) || $AWAIT_PIDS ||
83                 $PostLoopCallback || keys(%UniqTimer));
84
85         $reap_armed = undef;
86         $LoopTimeout = -1;  # no timeout by default
87 }
88
89 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
90
91 Set the loop timeout for the event loop to some value in milliseconds.
92
93 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
94 immediately.
95
96 =cut
97 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
98
99 sub _add_named_timer {
100         my ($name, $secs, $coderef, @args) = @_;
101         my $fire_time = now() + $secs;
102         my $timer = [$fire_time, $name, $coderef, @args];
103
104         if (!@Timers || $fire_time >= $Timers[-1][0]) {
105                 push @Timers, $timer;
106                 return $timer;
107         }
108
109         # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
110         # but it was compared against calendar queues, heaps, naive push/sort,
111         # and a bunch of other versions, and found to be fastest with a large
112         # variety of datasets.)
113         for (my $i = 0; $i < @Timers; $i++) {
114                 if ($Timers[$i][0] > $fire_time) {
115                         splice(@Timers, $i, 0, $timer);
116                         return $timer;
117                 }
118         }
119         die "Shouldn't get here.";
120 }
121
122 sub add_timer { _add_named_timer(undef, @_) }
123
124 sub add_uniq_timer { # ($name, $secs, $coderef, @args) = @_;
125         $UniqTimer{$_[0]} //= _add_named_timer(@_);
126 }
127
128 # caller sets return value to $Epoll
129 sub _InitPoller () {
130         if (defined $PublicInbox::Syscall::SYS_epoll_create)  {
131                 my $fd = epoll_create();
132                 die "epoll_create: $!" if $fd < 0;
133                 open($ep_io, '+<&=', $fd) or return;
134                 fcntl($ep_io, F_SETFD, FD_CLOEXEC);
135                 $fd;
136         } else {
137                 my $cls;
138                 for (qw(DSKQXS DSPoll)) {
139                         $cls = "PublicInbox::$_";
140                         last if eval "require $cls";
141                 }
142                 $cls->import(qw(epoll_ctl epoll_wait));
143                 $cls->new;
144         }
145 }
146
147 sub now () { clock_gettime(CLOCK_MONOTONIC) }
148
149 sub next_tick () {
150         my $q = $nextq or return;
151         $nextq = undef;
152         $Stack{cur_runq} = $q;
153         for my $obj (@$q) {
154                 # avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
155                 # https://rt.perl.org/Public/Bug/Display.html?id=114340
156                 if (blessed($obj)) {
157                         $obj->event_step;
158                 } else {
159                         $obj->();
160                 }
161         }
162         delete $Stack{cur_runq};
163 }
164
165 # runs timers and returns milliseconds for next one, or next event loop
166 sub RunTimers {
167         next_tick();
168
169         return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
170
171         my $now = now();
172
173         # Run expired timers
174         while (@Timers && $Timers[0][0] <= $now) {
175                 my $to_run = shift(@Timers);
176                 delete $UniqTimer{$to_run->[1] // ''};
177                 $to_run->[2]->(@$to_run[3..$#$to_run]);
178         }
179
180         # timers may enqueue into nextq:
181         return 0 if ($nextq || $ToClose);
182
183         return $LoopTimeout unless @Timers;
184
185         # convert time to an even number of milliseconds, adding 1
186         # extra, otherwise floating point fun can occur and we'll
187         # call RunTimers like 20-30 times, each returning a timeout
188         # of 0.0000212 seconds
189         my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
190
191         # -1 is an infinite timeout, so prefer a real timeout
192         ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout
193 }
194
195 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
196
197 sub block_signals () {
198         my $oldset = POSIX::SigSet->new;
199         my $newset = POSIX::SigSet->new;
200         $newset->fillset or die "fillset: $!";
201         sig_setmask($newset, $oldset);
202         $oldset;
203 }
204
205 sub await_cb ($;@) {
206         my ($pid, @cb_args) = @_;
207         my $cb = shift @cb_args or return;
208         eval { $cb->($pid, @cb_args) };
209         warn "E: awaitpid($pid): $@" if $@;
210 }
211
212 # We can't use waitpid(-1) safely here since it can hit ``, system(),
213 # and other things.  So we scan the $wait_pids list, which is hopefully
214 # not too big.  We keep $wait_pids small by not calling dwaitpid()
215 # until we've hit EOF when reading the stdout of the child.
216
217 sub reap_pids {
218         $reap_armed = undef;
219         my $tmp = $wait_pids // [];
220         $wait_pids = undef;
221         $Stack{reap_runq} = $tmp;
222         my $oldset = block_signals();
223
224         # old API
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
240         # new API TODO: convert to waitpid(-1) in the future as long
241         # as we don't use threads
242         for my $pid (keys %$AWAIT_PIDS) {
243                 my $wpid = waitpid($pid, WNOHANG) // next;
244                 my $cb_args = delete $AWAIT_PIDS->{$wpid} or next;
245                 await_cb($pid, @$cb_args);
246         }
247         sig_setmask($oldset);
248         delete $Stack{reap_runq};
249 }
250
251 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
252 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
253
254 sub in_loop () { $in_loop }
255
256 # Internal function: run the post-event callback, send read events
257 # for pushed-back data, and close pending connections.  returns 1
258 # if event loop should continue, or 0 to shut it all down.
259 sub PostEventLoop () {
260         # now we can close sockets that wanted to close during our event
261         # processing.  (we didn't want to close them during the loop, as we
262         # didn't want fd numbers being reused and confused during the event
263         # loop)
264         if (my $close_now = $ToClose) {
265                 $ToClose = undef; # will be autovivified on push
266                 @$close_now = map { fileno($_) } @$close_now;
267
268                 # ->DESTROY methods may populate ToClose
269                 delete @DescriptorMap{@$close_now};
270         }
271
272         # by default we keep running, unless a postloop callback cancels it
273         $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
274 }
275
276 # Start processing IO events. In most daemon programs this never exits. See
277 # C<PostLoopCallback> for how to exit the loop.
278 sub event_loop (;$$) {
279         my ($sig, $oldset) = @_;
280         $Epoll //= _InitPoller();
281         require PublicInbox::Sigfd if $sig;
282         my $sigfd = PublicInbox::Sigfd->new($sig, 1) if $sig;
283         local @SIG{keys %$sig} = values(%$sig) if $sig && !$sigfd;
284         local $SIG{PIPE} = 'IGNORE';
285         if (!$sigfd && $sig) {
286                 # wake up every second to accept signals if we don't
287                 # have signalfd or IO::KQueue:
288                 sig_setmask($oldset);
289                 PublicInbox::DS->SetLoopTimeout(1000);
290         }
291         $_[0] = $sigfd = $sig = undef; # $_[0] == sig
292         local $in_loop = 1;
293         my @events;
294         do {
295                 my $timeout = RunTimers();
296
297                 # get up to 1000 events
298                 epoll_wait($Epoll, 1000, $timeout, \@events);
299                 for my $fd (@events) {
300                         # it's possible epoll_wait returned many events,
301                         # including some at the end that ones in the front
302                         # triggered unregister-interest actions.  if we can't
303                         # find the %sock entry, it's because we're no longer
304                         # interested in that event.
305
306                         # guard stack-not-refcounted w/ Carp + @DB::args
307                         my $obj = $DescriptorMap{$fd};
308                         $obj->event_step;
309                 }
310         } while (PostEventLoop());
311 }
312
313 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
314
315 Sets post loop callback function.  Pass a subref and it will be
316 called every time the event loop finishes.
317
318 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
319 and it will exit.
320
321 The callback function will be passed two parameters: \%DescriptorMap
322
323 =cut
324 sub SetPostLoopCallback {
325     my ($class, $ref) = @_;
326
327     # global callback
328     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
329 }
330
331 #####################################################################
332 ### PublicInbox::DS-the-object code
333 #####################################################################
334
335 =head2 OBJECT METHODS
336
337 =head2 C<< CLASS->new( $socket ) >>
338
339 Create a new PublicInbox::DS subclass object for the given I<socket> which will
340 react to events on it during the C<event_loop>.
341
342 This is normally (always?) called from your subclass via:
343
344   $class->SUPER::new($socket);
345
346 =cut
347 sub new {
348     my ($self, $sock, $ev) = @_;
349     $self->{sock} = $sock;
350     my $fd = fileno($sock);
351
352     $Epoll //= _InitPoller();
353 retry:
354     if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
355         if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
356             $ev &= ~EPOLLEXCLUSIVE;
357             goto retry;
358         }
359         die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
360     }
361     croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
362         if defined($DescriptorMap{$fd});
363
364     $DescriptorMap{$fd} = $self;
365 }
366
367 # for IMAP, NNTP, and POP3 which greet clients upon connect
368 sub greet {
369         my ($self, $sock) = @_;
370         my $ev = EPOLLIN;
371         my $wbuf;
372         if ($sock->can('accept_SSL') && !$sock->accept_SSL) {
373                 return CORE::close($sock) if $! != EAGAIN;
374                 $ev = PublicInbox::TLS::epollbit() or return CORE::close($sock);
375                 $wbuf = [ \&accept_tls_step, $self->can('do_greet')];
376         }
377         new($self, $sock, $ev | EPOLLONESHOT);
378         if ($wbuf) {
379                 $self->{wbuf} = $wbuf;
380         } else {
381                 $self->do_greet;
382         }
383         $self;
384 }
385
386 #####################################################################
387 ### I N S T A N C E   M E T H O D S
388 #####################################################################
389
390 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
391
392 =head2 C<< $obj->close >>
393
394 Close the socket.
395
396 =cut
397 sub close {
398     my ($self) = @_;
399     my $sock = delete $self->{sock} or return;
400
401     # we need to flush our write buffer, as there may
402     # be self-referential closures (sub { $client->close })
403     # preventing the object from being destroyed
404     delete $self->{wbuf};
405
406     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
407     # notifications about it
408     my $fd = fileno($sock);
409     epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
410         croak("EPOLL_CTL_DEL($self/$sock): $!");
411
412     # we explicitly don't delete from DescriptorMap here until we
413     # actually close the socket, as we might be in the middle of
414     # processing an epoll_wait/etc that returned hundreds of fds, one
415     # of which is not yet processed and is what we're closing.  if we
416     # keep it in DescriptorMap, then the event harnesses can just
417     # looked at $pob->{sock} == undef and ignore it.  but if it's an
418     # un-accounted for fd, then it (understandably) freak out a bit
419     # and emit warnings, thinking their state got off.
420
421     # defer closing the actual socket until the event loop is done
422     # processing this round of events.  (otherwise we might reuse fds)
423     push @$ToClose, $sock; # autovivifies $ToClose
424
425     return 0;
426 }
427
428 # portable, non-thread-safe sendfile emulation (no pread, yet)
429 sub send_tmpio ($$) {
430     my ($sock, $tmpio) = @_;
431
432     sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
433     my $n = $tmpio->[2] // 65536;
434     $n = 65536 if $n > 65536;
435     defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
436     my $written = 0;
437     while ($to_write > 0) {
438         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
439             $written += $w;
440             $to_write -= $w;
441         } else {
442             return if $written == 0;
443             last;
444         }
445     }
446     $tmpio->[1] += $written; # offset
447     $tmpio->[2] -= $written if defined($tmpio->[2]); # length
448     $written;
449 }
450
451 sub epbit ($$) { # (sock, default)
452         $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
453 }
454
455 # returns 1 if done, 0 if incomplete
456 sub flush_write ($) {
457     my ($self) = @_;
458     my $sock = $self->{sock} or return;
459     my $wbuf = $self->{wbuf} or return 1;
460
461 next_buf:
462     while (my $bref = $wbuf->[0]) {
463         if (ref($bref) ne 'CODE') {
464             while ($sock) {
465                 my $w = send_tmpio($sock, $bref); # bref is tmpio
466                 if (defined $w) {
467                     if ($w == 0) {
468                         shift @$wbuf;
469                         goto next_buf;
470                     }
471                 } elsif ($! == EAGAIN) {
472                     my $ev = epbit($sock, EPOLLOUT) or return $self->close;
473                     epwait($sock, $ev | EPOLLONESHOT);
474                     return 0;
475                 } else {
476                     return $self->close;
477                 }
478             }
479         } else { #(ref($bref) eq 'CODE') {
480             shift @$wbuf;
481             my $before = scalar(@$wbuf);
482             $bref->($self);
483
484             # bref may be enqueueing more CODE to call (see accept_tls_step)
485             return 0 if (scalar(@$wbuf) > $before);
486         }
487     } # while @$wbuf
488
489     delete $self->{wbuf};
490     1; # all done
491 }
492
493 sub rbuf_idle ($$) {
494     my ($self, $rbuf) = @_;
495     if ($$rbuf eq '') { # who knows how long till we can read again
496         delete $self->{rbuf};
497     } else {
498         $self->{rbuf} = $rbuf;
499     }
500 }
501
502 sub do_read ($$$;$) {
503     my ($self, $rbuf, $len, $off) = @_;
504     my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
505     return ($r == 0 ? $self->close : $r) if defined $r;
506     # common for clients to break connections without warning,
507     # would be too noisy to log here:
508     if ($! == EAGAIN) {
509         my $ev = epbit($sock, EPOLLIN) or return $self->close;
510         epwait($sock, $ev | EPOLLONESHOT);
511         rbuf_idle($self, $rbuf);
512         0;
513     } else {
514         $self->close;
515     }
516 }
517
518 # drop the socket if we hit unrecoverable errors on our system which
519 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
520 sub drop {
521     my $self = shift;
522     carp(@_);
523     $self->close;
524 }
525
526 sub tmpio ($$$) {
527         my ($self, $bref, $off) = @_;
528         my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
529                 return drop($self, "tmpfile $!");
530         $fh->autoflush(1);
531         my $len = length($$bref) - $off;
532         my $n = syswrite($fh, $$bref, $len, $off) //
533                 return drop($self, "write ($len): $!");
534         $n == $len or return drop($self, "wrote $n < $len bytes");
535         [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
536 }
537
538 =head2 C<< $obj->write( $data ) >>
539
540 Write the specified data to the underlying handle.  I<data> may be scalar,
541 scalar ref, code ref (to run when there).
542 Returns 1 if writes all went through, or 0 if there are writes in queue. If
543 it returns 1, caller should stop waiting for 'writable' events)
544
545 =cut
546 sub write {
547     my ($self, $data) = @_;
548
549     # nobody should be writing to closed sockets, but caller code can
550     # do two writes within an event, have the first fail and
551     # disconnect the other side (whose destructor then closes the
552     # calling object, but it's still in a method), and then the
553     # now-dead object does its second write.  that is this case.  we
554     # just lie and say it worked.  it'll be dead soon and won't be
555     # hurt by this lie.
556     my $sock = $self->{sock} or return 1;
557     my $ref = ref $data;
558     my $bref = $ref ? $data : \$data;
559     my $wbuf = $self->{wbuf};
560     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
561         if ($ref eq 'CODE') {
562             push @$wbuf, $bref;
563         } else {
564             my $tmpio = $wbuf->[-1];
565             if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
566                 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
567             } else {
568                 my $tmpio = tmpio($self, $bref, 0) or return 0;
569                 push @$wbuf, $tmpio;
570             }
571         }
572         return 0;
573     } elsif ($ref eq 'CODE') {
574         $bref->($self);
575         return 1;
576     } else {
577         my $to_write = length($$bref);
578         my $written = syswrite($sock, $$bref, $to_write);
579
580         if (defined $written) {
581             return 1 if $written == $to_write;
582             requeue($self); # runs: event_step -> flush_write
583         } elsif ($! == EAGAIN) {
584             my $ev = epbit($sock, EPOLLOUT) or return $self->close;
585             epwait($sock, $ev | EPOLLONESHOT);
586             $written = 0;
587         } else {
588             return $self->close;
589         }
590
591         # deal with EAGAIN or partial write:
592         my $tmpio = tmpio($self, $bref, $written) or return 0;
593
594         # wbuf may be an empty array if we're being called inside
595         # ->flush_write via CODE bref:
596         push @{$self->{wbuf}}, $tmpio; # autovivifies
597         return 0;
598     }
599 }
600
601 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
602
603 sub msg_more ($$) {
604     my $self = $_[0];
605     my $sock = $self->{sock} or return 1;
606     my $wbuf = $self->{wbuf};
607
608     if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
609                 !$sock->can('stop_SSL')) {
610         my $n = send($sock, $_[1], MSG_MORE);
611         if (defined $n) {
612             my $nlen = length($_[1]) - $n;
613             return 1 if $nlen == 0; # all done!
614             # queue up the unwritten substring:
615             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
616             push @{$self->{wbuf}}, $tmpio; # autovivifies
617             epwait($sock, EPOLLOUT|EPOLLONESHOT);
618             return 0;
619         }
620     }
621
622     # don't redispatch into NNTPdeflate::write
623     PublicInbox::DS::write($self, \($_[1]));
624 }
625
626 sub epwait ($$) {
627     my ($sock, $ev) = @_;
628     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
629         croak("EPOLL_CTL_MOD($sock): $!");
630 }
631
632 # return true if complete, false if incomplete (or failure)
633 sub accept_tls_step ($) {
634     my ($self) = @_;
635     my $sock = $self->{sock} or return;
636     return 1 if $sock->accept_SSL;
637     return $self->close if $! != EAGAIN;
638     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
639     epwait($sock, $ev | EPOLLONESHOT);
640     unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
641     0;
642 }
643
644 # return true if complete, false if incomplete (or failure)
645 sub shutdn_tls_step ($) {
646     my ($self) = @_;
647     my $sock = $self->{sock} or return;
648     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
649     return $self->close if $! != EAGAIN;
650     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
651     epwait($sock, $ev | EPOLLONESHOT);
652     unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
653     0;
654 }
655
656 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
657 # or fork w/o exec, so no inadvertent socket sharing
658 sub shutdn ($) {
659     my ($self) = @_;
660     my $sock = $self->{sock} or return;
661     if ($sock->can('stop_SSL')) {
662         shutdn_tls_step($self);
663     } else {
664         $self->close;
665     }
666 }
667
668 sub dflush {} # overridden by DSdeflate
669 sub compressed {} # overridden by DSdeflate
670 sub long_response_done {} # overridden by Net::NNTP
671
672 sub long_step {
673         my ($self) = @_;
674         # wbuf is unset or empty, here; {long} may add to it
675         my ($fd, $cb, $t0, @args) = @{$self->{long_cb}};
676         my $more = eval { $cb->($self, @args) };
677         if ($@ || !$self->{sock}) { # something bad happened...
678                 delete $self->{long_cb};
679                 my $elapsed = now() - $t0;
680                 $@ and warn("$@ during long response[$fd] - ",
681                                 sprintf('%0.6f', $elapsed),"\n");
682                 $self->out(" deferred[$fd] aborted - %0.6f", $elapsed);
683                 $self->close;
684         } elsif ($more) { # $self->{wbuf}:
685                 # control passed to ibx_async_cat if $more == \undef
686                 requeue_once($self) if !ref($more);
687         } else { # all done!
688                 delete $self->{long_cb};
689                 $self->long_response_done;
690                 my $elapsed = now() - $t0;
691                 my $fd = fileno($self->{sock});
692                 $self->out(" deferred[$fd] done - %0.6f", $elapsed);
693                 my $wbuf = $self->{wbuf}; # do NOT autovivify
694                 requeue($self) unless $wbuf && @$wbuf;
695         }
696 }
697
698 sub requeue_once {
699         my ($self) = @_;
700         # COMPRESS users all share the same DEFLATE context.
701         # Flush it here to ensure clients don't see each other's data
702         $self->dflush;
703
704         # no recursion, schedule another call ASAP,
705         # but only after all pending writes are done.
706         # autovivify wbuf.  wbuf may be populated by $cb,
707         # no need to rearm if so: (push returns new size of array)
708         $self->requeue if push(@{$self->{wbuf}}, \&long_step) == 1;
709 }
710
711 sub long_response ($$;@) {
712         my ($self, $cb, @args) = @_; # cb returns true if more, false if done
713         my $sock = $self->{sock} or return;
714         # make sure we disable reading during a long response,
715         # clients should not be sending us stuff and making us do more
716         # work while we are stream a response to them
717         $self->{long_cb} = [ fileno($sock), $cb, now(), @args ];
718         long_step($self); # kick off!
719         undef;
720 }
721
722 sub dwaitpid ($;$$) {
723         my ($pid, $cb, $arg) = @_;
724         if ($in_loop) {
725                 push @$wait_pids, [ $pid, $cb, $arg ];
726                 # We could've just missed our SIGCHLD, cover it, here:
727                 enqueue_reap();
728         } else {
729                 my $ret = waitpid($pid, 0);
730                 if ($ret == $pid) {
731                         if ($cb) {
732                                 eval { $cb->($arg, $pid) };
733                                 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
734                         }
735                 } else {
736                         carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
737                 }
738         }
739 }
740
741 sub awaitpid {
742         my ($pid, @cb_args) = @_;
743         $AWAIT_PIDS->{$pid} //= @cb_args ? \@cb_args : 0;
744         # provide synchronous API
745         if (defined(wantarray) || (!$in_loop && !@cb_args)) {
746                 my $ret = waitpid($pid, 0) // -2;
747                 if ($ret == $pid) {
748                         my $cb_args = delete $AWAIT_PIDS->{$pid};
749                         @cb_args = @$cb_args if !@cb_args && $cb_args;
750                         await_cb($pid, @cb_args);
751                         return $ret;
752                 }
753         }
754         # We could've just missed our SIGCHLD, cover it, here:
755         enqueue_reap() if $in_loop;
756 }
757
758 1;
759
760 =head1 AUTHORS (Danga::Socket)
761
762 Brad Fitzpatrick <brad@danga.com> - author
763
764 Michael Granger <ged@danga.com> - docs, testing
765
766 Mark Smith <junior@danga.com> - contributor, heavy user, testing
767
768 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits