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(FD_CLOEXEC F_SETFD F_GETFD SEEK_SET);
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 'wbuf', # arrayref of coderefs or GLOB refs
32 'wbuf_off', # offset into first element of wbuf to start writing at
35 use Errno qw(EAGAIN EINVAL);
36 use Carp qw(croak confess carp);
37 use File::Temp qw(tempfile);
40 %DescriptorMap, # fd (num) -> PublicInbox::DS object
41 $Epoll, # Global epoll fd (or DSKQXS ref)
42 $_io, # IO::Handle for Epoll
43 @ToClose, # sockets to close when event loop is done
45 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
47 $LoopTimeout, # timeout of event loop in milliseconds
48 $DoneInit, # if we've done the one-time module init yet
54 #####################################################################
55 ### C L A S S M E T H O D S
56 #####################################################################
58 =head2 C<< CLASS->Reset() >>
66 $LoopTimeout = -1; # no timeout by default
69 $PostLoopCallback = undef;
72 $_io = undef; # closes real $Epoll FD
73 $Epoll = undef; # may call DSKQXS::DESTROY
75 *EventLoop = *FirstTimeEventLoop;
78 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
80 Set the loop timeout for the event loop to some value in milliseconds.
82 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
87 return $LoopTimeout = $_[1] + 0;
90 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
92 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
93 are not guaranteed to fire at the exact time you ask for.
95 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
99 my ($class, $secs, $coderef) = @_;
102 my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
103 unshift(@Timers, $timer);
107 my $fire_time = now() + $secs;
109 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
111 if (!@Timers || $fire_time >= $Timers[-1][0]) {
112 push @Timers, $timer;
116 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
117 # but it was compared against calendar queues, heaps, naive push/sort,
118 # and a bunch of other versions, and found to be fastest with a large
119 # variety of datasets.)
120 for (my $i = 0; $i < @Timers; $i++) {
121 if ($Timers[$i][0] > $fire_time) {
122 splice(@Timers, $i, 0, $timer);
127 die "Shouldn't get here.";
130 # keeping this around in case we support other FD types for now,
131 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
132 sub set_cloexec ($) {
135 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
136 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
137 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
145 if (PublicInbox::Syscall::epoll_defined()) {
146 $Epoll = epoll_create();
147 set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
150 for (qw(DSKQXS DSPoll)) {
151 $cls = "PublicInbox::$_";
152 last if eval "require $cls";
157 *EventLoop = *EpollEventLoop;
160 =head2 C<< CLASS->EventLoop() >>
162 Start processing IO events. In most daemon programs this never exits. See
163 C<PostLoopCallback> below for how to exit the loop.
166 sub FirstTimeEventLoop {
174 sub now () { clock_gettime(CLOCK_MONOTONIC) }
176 # runs timers and returns milliseconds for next one, or next event loop
178 return $LoopTimeout unless @Timers;
183 while (@Timers && $Timers[0][0] <= $now) {
184 my $to_run = shift(@Timers);
185 $to_run->[1]->($now) if $to_run->[1];
188 return $LoopTimeout unless @Timers;
190 # convert time to an even number of milliseconds, adding 1
191 # extra, otherwise floating point fun can occur and we'll
192 # call RunTimers like 20-30 times, each returning a timeout
193 # of 0.0000212 seconds
194 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
196 # -1 is an infinite timeout, so prefer a real timeout
197 return $timeout if $LoopTimeout == -1;
199 # otherwise pick the lower of our regular timeout and time until
201 return $LoopTimeout if $LoopTimeout < $timeout;
209 my $timeout = RunTimers();
211 # get up to 1000 events
212 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
213 for ($i=0; $i<$evcount; $i++) {
214 # it's possible epoll_wait returned many events, including some at the end
215 # that ones in the front triggered unregister-interest actions. if we
216 # can't find the %sock entry, it's because we're no longer interested
218 $DescriptorMap{$events[$i]->[0]}->event_step;
220 return unless PostEventLoop();
224 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
226 Sets post loop callback function. Pass a subref and it will be
227 called every time the event loop finishes.
229 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
232 The callback function will be passed two parameters: \%DescriptorMap
235 sub SetPostLoopCallback {
236 my ($class, $ref) = @_;
239 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
242 # Internal function: run the post-event callback, send read events
243 # for pushed-back data, and close pending connections. returns 1
244 # if event loop should continue, or 0 to shut it all down.
246 # now we can close sockets that wanted to close during our event processing.
247 # (we didn't want to close them during the loop, as we didn't want fd numbers
248 # being reused and confused during the event loop)
249 while (my $sock = shift @ToClose) {
250 my $fd = fileno($sock);
252 # close the socket. (not a PublicInbox::DS close)
255 # and now we can finally remove the fd from the map. see
256 # comment above in ->close.
257 delete $DescriptorMap{$fd};
261 # by default we keep running, unless a postloop callback (either per-object
262 # or global) cancels it
263 my $keep_running = 1;
265 # now we're at the very end, call callback if defined
266 if (defined $PostLoopCallback) {
267 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
270 return $keep_running;
273 #####################################################################
274 ### PublicInbox::DS-the-object code
275 #####################################################################
277 =head2 OBJECT METHODS
279 =head2 C<< CLASS->new( $socket ) >>
281 Create a new PublicInbox::DS subclass object for the given I<socket> which will
282 react to events on it during the C<EventLoop>.
284 This is normally (always?) called from your subclass via:
286 $class->SUPER::new($socket);
290 my ($self, $sock, $ev) = @_;
291 $self = fields::new($self) unless ref $self;
293 $self->{sock} = $sock;
294 my $fd = fileno($sock);
296 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
301 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
302 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
303 $ev &= ~EPOLLEXCLUSIVE;
306 die "couldn't add epoll watch for $fd: $!\n";
308 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
309 if $DescriptorMap{$fd};
311 $DescriptorMap{$fd} = $self;
316 #####################################################################
317 ### I N S T A N C E M E T H O D S
318 #####################################################################
320 =head2 C<< $obj->close >>
327 my $sock = delete $self->{sock} or return;
329 # we need to flush our write buffer, as there may
330 # be self-referential closures (sub { $client->close })
331 # preventing the object from being destroyed
332 delete $self->{wbuf};
334 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
335 # notifications about it
336 my $fd = fileno($sock);
337 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
338 confess("EPOLL_CTL_DEL: $!");
340 # we explicitly don't delete from DescriptorMap here until we
341 # actually close the socket, as we might be in the middle of
342 # processing an epoll_wait/etc that returned hundreds of fds, one
343 # of which is not yet processed and is what we're closing. if we
344 # keep it in DescriptorMap, then the event harnesses can just
345 # looked at $pob->{sock} == undef and ignore it. but if it's an
346 # un-accounted for fd, then it (understandably) freak out a bit
347 # and emit warnings, thinking their state got off.
349 # defer closing the actual socket until the event loop is done
350 # processing this round of events. (otherwise we might reuse fds)
351 push @ToClose, $sock;
356 # portable, non-thread-safe sendfile emulation (no pread, yet)
357 sub psendfile ($$$) {
358 my ($sock, $fh, $off) = @_;
360 seek($fh, $$off, SEEK_SET) or return;
361 defined(my $to_write = read($fh, my $buf, 16384)) or return;
363 while ($to_write > 0) {
364 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
368 return if $written == 0;
376 # returns 1 if done, 0 if incomplete
377 sub flush_write ($) {
379 my $wbuf = $self->{wbuf} or return 1;
380 my $sock = $self->{sock};
383 while (my $bref = $wbuf->[0]) {
384 if (ref($bref) ne 'CODE') {
385 my $off = delete($self->{wbuf_off}) // 0;
387 my $w = psendfile($sock, $bref, \$off);
393 } elsif ($! == EAGAIN) {
394 $self->{wbuf_off} = $off;
395 watch($self, EPOLLOUT|EPOLLONESHOT);
401 } else { #($ref eq 'CODE') {
403 my $before = scalar(@$wbuf);
406 # bref may be enqueueing more CODE to call (see accept_tls_step)
407 return 0 if (scalar(@$wbuf) > $before);
411 delete $self->{wbuf};
416 my ($self, $rbuf, $len, $off) = @_;
417 my $r = sysread($self->{sock}, $$rbuf, $len, $off);
418 return ($r == 0 ? $self->close : $r) if defined $r;
419 # common for clients to break connections without warning,
420 # would be too noisy to log here:
421 if (ref($self) eq 'IO::Socket::SSL') {
422 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
423 watch($self, $ev | EPOLLONESHOT);
424 } elsif ($! == EAGAIN) {
425 watch($self, EPOLLIN | EPOLLONESHOT);
431 # drop the socket if we hit unrecoverable errors on our system which
432 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
439 # n.b.: use ->write/->read for this buffer to allow compatibility with
440 # PerlIO::mmap or PerlIO::scalar if needed
442 my ($self, $bref, $off) = @_;
443 # open(my $fh, '+>>', undef) doesn't set O_APPEND
444 my ($fh, $path) = eval { tempfile('wbuf-XXXXXXX', TMPDIR => 1) };
445 $fh or return drop($self, "tempfile: $@");
446 open($fh, '+>>', $path) or return drop($self, "open: $!");
448 unlink($path) or return drop($self, "unlink: $!");
449 my $len = bytes::length($$bref) - $off;
450 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
454 =head2 C<< $obj->write( $data ) >>
456 Write the specified data to the underlying handle. I<data> may be scalar,
457 scalar ref, code ref (to run when there).
458 Returns 1 if writes all went through, or 0 if there are writes in queue. If
459 it returns 1, caller should stop waiting for 'writable' events)
463 my ($self, $data) = @_;
465 # nobody should be writing to closed sockets, but caller code can
466 # do two writes within an event, have the first fail and
467 # disconnect the other side (whose destructor then closes the
468 # calling object, but it's still in a method), and then the
469 # now-dead object does its second write. that is this case. we
470 # just lie and say it worked. it'll be dead soon and won't be
472 my $sock = $self->{sock} or return 1;
474 my $bref = $ref ? $data : \$data;
475 my $wbuf = $self->{wbuf};
476 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
477 if ($ref eq 'CODE') {
480 my $last = $wbuf->[-1];
481 if (ref($last) eq 'GLOB') { # append to tmp file buffer
482 $last->print($$bref) or return drop($self, "print: $!");
484 my $tmpio = tmpio($self, $bref, 0) or return 0;
489 } elsif ($ref eq 'CODE') {
493 my $to_write = bytes::length($$bref);
494 my $written = syswrite($sock, $$bref, $to_write);
496 if (defined $written) {
497 return 1 if $written == $to_write;
498 } elsif ($! == EAGAIN) {
503 my $tmpio = tmpio($self, $bref, $written) or return 0;
504 $self->{wbuf} = [ $tmpio ];
505 watch($self, EPOLLOUT|EPOLLONESHOT);
510 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
514 my $sock = $self->{sock} or return 1;
516 if (MSG_MORE && !$self->{wbuf} && ref($sock) ne 'IO::Socket::SSL') {
517 my $n = send($sock, $_[1], MSG_MORE);
519 my $nlen = bytes::length($_[1]) - $n;
520 return 1 if $nlen == 0; # all done!
521 # queue up the unwritten substring:
522 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
523 $self->{wbuf} = [ $tmpio ];
524 watch($self, EPOLLOUT|EPOLLONESHOT);
528 $self->write(\($_[1]));
532 my ($self, $ev) = @_;
533 my $sock = $self->{sock} or return;
534 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
535 confess("EPOLL_CTL_MOD $!");
539 sub watch_in1 ($) { watch($_[0], EPOLLIN | EPOLLONESHOT) }
541 # return true if complete, false if incomplete (or failure)
542 sub accept_tls_step ($) {
544 my $sock = $self->{sock} or return;
545 return 1 if $sock->accept_SSL;
546 return $self->close if $! != EAGAIN;
547 if (my $ev = PublicInbox::TLS::epollbit()) {
548 unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
549 return watch($self, $ev | EPOLLONESHOT);
551 drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
554 sub shutdn_tls_step ($) {
556 my $sock = $self->{sock} or return;
557 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
558 return $self->close if $! != EAGAIN;
559 if (my $ev = PublicInbox::TLS::epollbit()) {
560 unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
561 return watch($self, $ev | EPOLLONESHOT);
563 drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
566 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
567 # or fork w/o exec, so no inadvertant socket sharing
570 my $sock = $self->{sock} or return;
571 if (ref($sock) eq 'IO::Socket::SSL') {
572 shutdn_tls_step($self);
578 package PublicInbox::DS::Timer;
579 # [$abs_float_firetime, $coderef];
586 =head1 AUTHORS (Danga::Socket)
588 Brad Fitzpatrick <brad@danga.com> - author
590 Michael Granger <ged@danga.com> - docs, testing
592 Mark Smith <junior@danga.com> - contributor, heavy user, testing
594 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits