1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
4 # This license differs from the rest of public-inbox
6 # This is a fork of the unmaintained Danga::Socket (1.61) with
7 # significant changes. See Documentation/technical/ds.txt in our
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
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;
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);
38 my $nextq; # queue for next_tick
39 my $wait_pids; # list of [ pid, callback, callback_arg ]
41 my $ToClose; # sockets to close when event loop is done
43 %DescriptorMap, # fd (num) -> PublicInbox::DS object
44 $Epoll, # Global epoll fd (or DSKQXS ref)
45 $ep_io, # IO::Handle for Epoll
47 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
49 $LoopTimeout, # timeout of event loop in milliseconds
57 #####################################################################
58 ### C L A S S M E T H O D S
59 #####################################################################
61 =head2 C<< CLASS->Reset() >>
68 $in_loop = undef; # first in case DESTROY callbacks use this
72 $PostLoopCallback = undef;
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));
85 $LoopTimeout = -1; # no timeout by default
88 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
90 Set the loop timeout for the event loop to some value in milliseconds.
92 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
96 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
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];
103 if (!@Timers || $fire_time >= $Timers[-1][0]) {
104 push @Timers, $timer;
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);
118 die "Shouldn't get here.";
121 sub add_timer { _add_named_timer(undef, @_) }
123 sub add_uniq_timer { # ($name, $secs, $coderef, @args) = @_;
124 $UniqTimer{$_[0]} //= _add_named_timer(@_);
127 # caller sets return value to $Epoll
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);
137 for (qw(DSKQXS DSPoll)) {
138 $cls = "PublicInbox::$_";
139 last if eval "require $cls";
141 $cls->import(qw(epoll_ctl epoll_wait));
146 sub now () { clock_gettime(CLOCK_MONOTONIC) }
149 my $q = $nextq or return;
151 $Stack{cur_runq} = $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
161 delete $Stack{cur_runq};
164 # runs timers and returns milliseconds for next one, or next event loop
168 return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @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]);
179 # timers may enqueue into nextq:
180 return 0 if ($nextq || $ToClose);
182 return $LoopTimeout unless @Timers;
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;
190 # -1 is an infinite timeout, so prefer a real timeout
191 ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout
194 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
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);
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.
211 my $tmp = $wait_pids or return;
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);
219 push @$wait_pids, $ary; # autovivifies @$wait_pids
220 } elsif ($ret == $pid) {
222 eval { $cb->($arg, $pid) };
223 warn "E: dwaitpid($pid) in_loop: $@" if $@;
226 warn "waitpid($pid, WNOHANG) = $ret, \$!=$!, \$?=$?";
229 sig_setmask($oldset);
230 delete $Stack{reap_runq};
233 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
234 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
236 sub in_loop () { $in_loop }
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
246 if (my $close_now = $ToClose) {
247 $ToClose = undef; # will be autovivified on push
248 @$close_now = map { fileno($_) } @$close_now;
250 # ->DESTROY methods may populate ToClose
251 delete @DescriptorMap{@$close_now};
254 # by default we keep running, unless a postloop callback cancels it
255 $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
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);
273 $_[0] = $sigfd = $sig = undef; # $_[0] == sig
277 my $timeout = RunTimers();
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.
288 # guard stack-not-refcounted w/ Carp + @DB::args
289 my $obj = $DescriptorMap{$fd};
292 } while (PostEventLoop());
295 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
297 Sets post loop callback function. Pass a subref and it will be
298 called every time the event loop finishes.
300 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
303 The callback function will be passed two parameters: \%DescriptorMap
306 sub SetPostLoopCallback {
307 my ($class, $ref) = @_;
310 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
313 #####################################################################
314 ### PublicInbox::DS-the-object code
315 #####################################################################
317 =head2 OBJECT METHODS
319 =head2 C<< CLASS->new( $socket ) >>
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>.
324 This is normally (always?) called from your subclass via:
326 $class->SUPER::new($socket);
330 my ($self, $sock, $ev) = @_;
331 $self->{sock} = $sock;
332 my $fd = fileno($sock);
334 $Epoll //= _InitPoller();
336 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
337 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
338 $ev &= ~EPOLLEXCLUSIVE;
341 die "EPOLL_CTL_ADD $self/$sock/$fd: $!";
343 croak("FD:$fd in use by $DescriptorMap{$fd} (for $self/$sock)")
344 if defined($DescriptorMap{$fd});
346 $DescriptorMap{$fd} = $self;
349 # for IMAP, NNTP, and POP3 which greet clients upon connect
351 my ($self, $sock) = @_;
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')];
359 new($self, $sock, $ev | EPOLLONESHOT);
361 $self->{wbuf} = $wbuf;
368 #####################################################################
369 ### I N S T A N C E M E T H O D S
370 #####################################################################
372 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
374 =head2 C<< $obj->close >>
381 my $sock = delete $self->{sock} or return;
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};
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): $!");
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.
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
410 # portable, non-thread-safe sendfile emulation (no pread, yet)
411 sub send_tmpio ($$) {
412 my ($sock, $tmpio) = @_;
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;
419 while ($to_write > 0) {
420 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
424 return if $written == 0;
428 $tmpio->[1] += $written; # offset
429 $tmpio->[2] -= $written if defined($tmpio->[2]); # length
433 sub epbit ($$) { # (sock, default)
434 $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
437 # returns 1 if done, 0 if incomplete
438 sub flush_write ($) {
440 my $sock = $self->{sock} or return;
441 my $wbuf = $self->{wbuf} or return 1;
444 while (my $bref = $wbuf->[0]) {
445 if (ref($bref) ne 'CODE') {
447 my $w = send_tmpio($sock, $bref); # bref is tmpio
453 } elsif ($! == EAGAIN) {
454 my $ev = epbit($sock, EPOLLOUT) or return $self->close;
455 epwait($sock, $ev | EPOLLONESHOT);
461 } else { #(ref($bref) eq 'CODE') {
463 my $before = scalar(@$wbuf);
466 # bref may be enqueueing more CODE to call (see accept_tls_step)
467 return 0 if (scalar(@$wbuf) > $before);
471 delete $self->{wbuf};
476 my ($self, $rbuf) = @_;
477 if ($$rbuf eq '') { # who knows how long till we can read again
478 delete $self->{rbuf};
480 $self->{rbuf} = $rbuf;
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:
491 my $ev = epbit($sock, EPOLLIN) or return $self->close;
492 epwait($sock, $ev | EPOLLONESHOT);
493 rbuf_idle($self, $rbuf);
500 # drop the socket if we hit unrecoverable errors on our system which
501 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
509 my ($self, $bref, $off) = @_;
510 my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
511 return drop($self, "tmpfile $!");
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
520 =head2 C<< $obj->write( $data ) >>
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)
529 my ($self, $data) = @_;
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
538 my $sock = $self->{sock} or return 1;
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') {
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: $!");
550 my $tmpio = tmpio($self, $bref, 0) or return 0;
555 } elsif ($ref eq 'CODE') {
559 my $to_write = length($$bref);
560 my $written = syswrite($sock, $$bref, $to_write);
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);
573 # deal with EAGAIN or partial write:
574 my $tmpio = tmpio($self, $bref, $written) or return 0;
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
583 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
587 my $sock = $self->{sock} or return 1;
588 my $wbuf = $self->{wbuf};
590 if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
591 !$sock->can('stop_SSL')) {
592 my $n = send($sock, $_[1], MSG_MORE);
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);
604 # don't redispatch into NNTPdeflate::write
605 PublicInbox::DS::write($self, \($_[1]));
609 my ($sock, $ev) = @_;
610 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
611 croak("EPOLL_CTL_MOD($sock): $!");
614 # return true if complete, false if incomplete (or failure)
615 sub accept_tls_step ($) {
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
626 # return true if complete, false if incomplete (or failure)
627 sub shutdn_tls_step ($) {
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
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
642 my $sock = $self->{sock} or return;
643 if ($sock->can('stop_SSL')) {
644 shutdn_tls_step($self);
650 sub dflush {} # overridden by DSdeflate
651 sub compressed {} # overridden by DSdeflate
652 sub long_response_done {} # overridden by Net::NNTP
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);
666 } elsif ($more) { # $self->{wbuf}:
667 # control passed to ibx_async_cat if $more == \undef
668 requeue_once($self) if !ref($more);
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;
682 # COMPRESS users all share the same DEFLATE context.
683 # Flush it here to ensure clients don't see each other's data
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;
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!
704 sub dwaitpid ($;$$) {
705 my ($pid, $cb, $arg) = @_;
707 push @$wait_pids, [ $pid, $cb, $arg ];
708 # We could've just missed our SIGCHLD, cover it, here:
711 my $ret = waitpid($pid, 0);
714 eval { $cb->($arg, $pid) };
715 carp "E: dwaitpid($pid) !in_loop: $@" if $@;
718 carp "waitpid($pid, 0) = $ret, \$!=$!, \$?=$?";
725 =head1 AUTHORS (Danga::Socket)
727 Brad Fitzpatrick <brad@danga.com> - author
729 Michael Granger <ged@danga.com> - docs, testing
731 Mark Smith <junior@danga.com> - contributor, heavy user, testing
733 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits