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