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 (for now) unmaintained Danga::Socket 1.61.
7 # Unused features will be removed, and updates will be made to take
8 # advantage of newer kernels.
10 # API changes to diverge from Danga::Socket will happen to better
11 # accomodate new features and improve scalability. Do not expect
12 # this to be a stable API like Danga::Socket.
13 # Bugs encountered (and likely fixed) are reported to
14 # bug-Danga-Socket@rt.cpan.org and visible at:
15 # https://rt.cpan.org/Public/Dist/Display.html?Name=Danga-Socket
16 package PublicInbox::DS;
21 use Fcntl qw(SEEK_SET :DEFAULT);
22 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
23 use parent qw(Exporter);
24 our @EXPORT_OK = qw(now msg_more);
28 use PublicInbox::Syscall qw(:epoll);
30 use fields ('sock', # underlying socket
31 'rbuf', # scalarref, usually undef
32 'wbuf', # arrayref of coderefs or GLOB refs
33 'wbuf_off', # offset into first element of wbuf to start writing at
36 use Errno qw(EAGAIN EINVAL EEXIST);
37 use Carp qw(croak confess carp);
41 %DescriptorMap, # fd (num) -> PublicInbox::DS object
42 $Epoll, # Global epoll fd (or DSKQXS ref)
43 $_io, # IO::Handle for Epoll
44 @ToClose, # sockets to close when event loop is done
46 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
48 $LoopTimeout, # timeout of event loop in milliseconds
49 $DoneInit, # if we've done the one-time module init yet
55 #####################################################################
56 ### C L A S S M E T H O D S
57 #####################################################################
59 =head2 C<< CLASS->Reset() >>
67 $LoopTimeout = -1; # no timeout by default
70 $PostLoopCallback = undef;
73 $_io = undef; # closes real $Epoll FD
74 $Epoll = undef; # may call DSKQXS::DESTROY
76 *EventLoop = *FirstTimeEventLoop;
79 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
81 Set the loop timeout for the event loop to some value in milliseconds.
83 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
88 return $LoopTimeout = $_[1] + 0;
91 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
93 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
94 are not guaranteed to fire at the exact time you ask for.
96 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
100 my ($class, $secs, $coderef) = @_;
103 my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
104 unshift(@Timers, $timer);
108 my $fire_time = now() + $secs;
110 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
112 if (!@Timers || $fire_time >= $Timers[-1][0]) {
113 push @Timers, $timer;
117 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
118 # but it was compared against calendar queues, heaps, naive push/sort,
119 # and a bunch of other versions, and found to be fastest with a large
120 # variety of datasets.)
121 for (my $i = 0; $i < @Timers; $i++) {
122 if ($Timers[$i][0] > $fire_time) {
123 splice(@Timers, $i, 0, $timer);
128 die "Shouldn't get here.";
131 # keeping this around in case we support other FD types for now,
132 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
133 sub set_cloexec ($) {
136 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
137 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
138 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
146 if (PublicInbox::Syscall::epoll_defined()) {
147 $Epoll = epoll_create();
148 set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
151 for (qw(DSKQXS DSPoll)) {
152 $cls = "PublicInbox::$_";
153 last if eval "require $cls";
155 $cls->import(qw(epoll_ctl epoll_wait));
158 *EventLoop = *EpollEventLoop;
161 =head2 C<< CLASS->EventLoop() >>
163 Start processing IO events. In most daemon programs this never exits. See
164 C<PostLoopCallback> below for how to exit the loop.
167 sub FirstTimeEventLoop {
175 sub now () { clock_gettime(CLOCK_MONOTONIC) }
177 # runs timers and returns milliseconds for next one, or next event loop
179 return $LoopTimeout unless @Timers;
184 while (@Timers && $Timers[0][0] <= $now) {
185 my $to_run = shift(@Timers);
186 $to_run->[1]->($now) if $to_run->[1];
189 return $LoopTimeout unless @Timers;
191 # convert time to an even number of milliseconds, adding 1
192 # extra, otherwise floating point fun can occur and we'll
193 # call RunTimers like 20-30 times, each returning a timeout
194 # of 0.0000212 seconds
195 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
197 # -1 is an infinite timeout, so prefer a real timeout
198 return $timeout if $LoopTimeout == -1;
200 # otherwise pick the lower of our regular timeout and time until
202 return $LoopTimeout if $LoopTimeout < $timeout;
210 my $timeout = RunTimers();
212 # get up to 1000 events
213 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
214 for ($i=0; $i<$evcount; $i++) {
215 # it's possible epoll_wait returned many events, including some at the end
216 # that ones in the front triggered unregister-interest actions. if we
217 # can't find the %sock entry, it's because we're no longer interested
219 $DescriptorMap{$events[$i]->[0]}->event_step;
221 return unless PostEventLoop();
225 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
227 Sets post loop callback function. Pass a subref and it will be
228 called every time the event loop finishes.
230 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
233 The callback function will be passed two parameters: \%DescriptorMap
236 sub SetPostLoopCallback {
237 my ($class, $ref) = @_;
240 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
243 # Internal function: run the post-event callback, send read events
244 # for pushed-back data, and close pending connections. returns 1
245 # if event loop should continue, or 0 to shut it all down.
247 # now we can close sockets that wanted to close during our event processing.
248 # (we didn't want to close them during the loop, as we didn't want fd numbers
249 # being reused and confused during the event loop)
250 while (my $sock = shift @ToClose) {
251 my $fd = fileno($sock);
253 # close the socket. (not a PublicInbox::DS close)
256 # and now we can finally remove the fd from the map. see
257 # comment above in ->close.
258 delete $DescriptorMap{$fd};
262 # by default we keep running, unless a postloop callback (either per-object
263 # or global) cancels it
264 my $keep_running = 1;
266 # now we're at the very end, call callback if defined
267 if (defined $PostLoopCallback) {
268 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
271 return $keep_running;
274 #####################################################################
275 ### PublicInbox::DS-the-object code
276 #####################################################################
278 =head2 OBJECT METHODS
280 =head2 C<< CLASS->new( $socket ) >>
282 Create a new PublicInbox::DS subclass object for the given I<socket> which will
283 react to events on it during the C<EventLoop>.
285 This is normally (always?) called from your subclass via:
287 $class->SUPER::new($socket);
291 my ($self, $sock, $ev) = @_;
292 $self = fields::new($self) unless ref $self;
294 $self->{sock} = $sock;
295 my $fd = fileno($sock);
297 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
302 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
303 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
304 $ev &= ~EPOLLEXCLUSIVE;
307 die "couldn't add epoll watch for $fd: $!\n";
309 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
310 if $DescriptorMap{$fd};
312 $DescriptorMap{$fd} = $self;
317 #####################################################################
318 ### I N S T A N C E M E T H O D S
319 #####################################################################
321 =head2 C<< $obj->close >>
328 my $sock = delete $self->{sock} or return;
330 # we need to flush our write buffer, as there may
331 # be self-referential closures (sub { $client->close })
332 # preventing the object from being destroyed
333 delete $self->{wbuf};
335 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
336 # notifications about it
337 my $fd = fileno($sock);
338 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
339 confess("EPOLL_CTL_DEL: $!");
341 # we explicitly don't delete from DescriptorMap here until we
342 # actually close the socket, as we might be in the middle of
343 # processing an epoll_wait/etc that returned hundreds of fds, one
344 # of which is not yet processed and is what we're closing. if we
345 # keep it in DescriptorMap, then the event harnesses can just
346 # looked at $pob->{sock} == undef and ignore it. but if it's an
347 # un-accounted for fd, then it (understandably) freak out a bit
348 # and emit warnings, thinking their state got off.
350 # defer closing the actual socket until the event loop is done
351 # processing this round of events. (otherwise we might reuse fds)
352 push @ToClose, $sock;
357 # portable, non-thread-safe sendfile emulation (no pread, yet)
358 sub psendfile ($$$) {
359 my ($sock, $fh, $off) = @_;
361 seek($fh, $$off, SEEK_SET) or return;
362 defined(my $to_write = read($fh, my $buf, 16384)) or return;
364 while ($to_write > 0) {
365 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
369 return if $written == 0;
377 # returns 1 if done, 0 if incomplete
378 sub flush_write ($) {
380 my $wbuf = $self->{wbuf} or return 1;
381 my $sock = $self->{sock};
384 while (my $bref = $wbuf->[0]) {
385 if (ref($bref) ne 'CODE') {
386 my $off = delete($self->{wbuf_off}) // 0;
388 my $w = psendfile($sock, $bref, \$off);
394 } elsif ($! == EAGAIN) {
395 $self->{wbuf_off} = $off;
396 watch($self, EPOLLOUT|EPOLLONESHOT);
402 } else { #($ref eq 'CODE') {
404 my $before = scalar(@$wbuf);
407 # bref may be enqueueing more CODE to call (see accept_tls_step)
408 return 0 if (scalar(@$wbuf) > $before);
412 delete $self->{wbuf};
417 my ($self, $rbuf) = @_;
418 if ($$rbuf eq '') { # who knows how long till we can read again
419 delete $self->{rbuf};
421 $self->{rbuf} = $rbuf;
425 sub do_read ($$$;$) {
426 my ($self, $rbuf, $len, $off) = @_;
427 my $r = sysread($self->{sock}, $$rbuf, $len, $off // 0);
428 return ($r == 0 ? $self->close : $r) if defined $r;
429 # common for clients to break connections without warning,
430 # would be too noisy to log here:
431 if (ref($self) eq 'IO::Socket::SSL') {
432 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
433 rbuf_idle($self, $rbuf);
434 watch($self, $ev | EPOLLONESHOT);
435 } elsif ($! == EAGAIN) {
436 rbuf_idle($self, $rbuf);
437 watch($self, EPOLLIN | EPOLLONESHOT);
443 # drop the socket if we hit unrecoverable errors on our system which
444 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
451 # n.b.: use ->write/->read for this buffer to allow compatibility with
452 # PerlIO::mmap or PerlIO::scalar if needed
454 my ($self, $bref, $off) = @_;
455 my $fh; # open(my $fh, '+>>', undef) doesn't set O_APPEND
457 my $fn = File::Spec->tmpdir . '/wbuf-' . rand;
458 if (sysopen($fh, $fn, O_RDWR|O_CREAT|O_EXCL|O_APPEND, 0600)) { # likely
459 unlink($fn) or return drop($self, "unlink($fn) $!");
460 } elsif ($! != EEXIST) { # EMFILE/ENFILE/ENOSPC/ENOMEM
461 return drop($self, "open: $!");
463 } until (defined $fh);
465 my $len = bytes::length($$bref) - $off;
466 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
470 =head2 C<< $obj->write( $data ) >>
472 Write the specified data to the underlying handle. I<data> may be scalar,
473 scalar ref, code ref (to run when there).
474 Returns 1 if writes all went through, or 0 if there are writes in queue. If
475 it returns 1, caller should stop waiting for 'writable' events)
479 my ($self, $data) = @_;
481 # nobody should be writing to closed sockets, but caller code can
482 # do two writes within an event, have the first fail and
483 # disconnect the other side (whose destructor then closes the
484 # calling object, but it's still in a method), and then the
485 # now-dead object does its second write. that is this case. we
486 # just lie and say it worked. it'll be dead soon and won't be
488 my $sock = $self->{sock} or return 1;
490 my $bref = $ref ? $data : \$data;
491 my $wbuf = $self->{wbuf};
492 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
493 if ($ref eq 'CODE') {
496 my $last = $wbuf->[-1];
497 if (ref($last) eq 'GLOB') { # append to tmp file buffer
498 $last->print($$bref) or return drop($self, "print: $!");
500 my $tmpio = tmpio($self, $bref, 0) or return 0;
505 } elsif ($ref eq 'CODE') {
509 my $to_write = bytes::length($$bref);
510 my $written = syswrite($sock, $$bref, $to_write);
512 if (defined $written) {
513 return 1 if $written == $to_write;
514 } elsif ($! == EAGAIN) {
519 my $tmpio = tmpio($self, $bref, $written) or return 0;
521 # wbuf may be an empty array if we're being called inside
522 # ->flush_write via CODE bref:
523 push @{$self->{wbuf} ||= []}, $tmpio;
524 watch($self, EPOLLOUT|EPOLLONESHOT);
529 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
533 my $sock = $self->{sock} or return 1;
535 if (MSG_MORE && !$self->{wbuf} && ref($sock) ne 'IO::Socket::SSL') {
536 my $n = send($sock, $_[1], MSG_MORE);
538 my $nlen = bytes::length($_[1]) - $n;
539 return 1 if $nlen == 0; # all done!
540 # queue up the unwritten substring:
541 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
542 $self->{wbuf} = [ $tmpio ];
543 watch($self, EPOLLOUT|EPOLLONESHOT);
547 $self->write(\($_[1]));
551 my ($self, $ev) = @_;
552 my $sock = $self->{sock} or return;
553 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
554 confess("EPOLL_CTL_MOD $!");
558 sub watch_in1 ($) { watch($_[0], EPOLLIN | EPOLLONESHOT) }
560 # return true if complete, false if incomplete (or failure)
561 sub accept_tls_step ($) {
563 my $sock = $self->{sock} or return;
564 return 1 if $sock->accept_SSL;
565 return $self->close if $! != EAGAIN;
566 if (my $ev = PublicInbox::TLS::epollbit()) {
567 unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
568 return watch($self, $ev | EPOLLONESHOT);
570 drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
573 sub shutdn_tls_step ($) {
575 my $sock = $self->{sock} or return;
576 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
577 return $self->close if $! != EAGAIN;
578 if (my $ev = PublicInbox::TLS::epollbit()) {
579 unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
580 return watch($self, $ev | EPOLLONESHOT);
582 drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
585 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
586 # or fork w/o exec, so no inadvertant socket sharing
589 my $sock = $self->{sock} or return;
590 if (ref($sock) eq 'IO::Socket::SSL') {
591 shutdn_tls_step($self);
597 package PublicInbox::DS::Timer;
598 # [$abs_float_firetime, $coderef];
605 =head1 AUTHORS (Danga::Socket)
607 Brad Fitzpatrick <brad@danga.com> - author
609 Michael Granger <ged@danga.com> - docs, testing
611 Mark Smith <junior@danga.com> - contributor, heavy user, testing
613 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits