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()) {
147 require PublicInbox::DSKQXS;
148 PublicInbox::DSKQXS->import;
149 PublicInbox::DSKQXS->new;
152 $Epoll = epoll_create();
153 set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
155 *EventLoop = *EpollEventLoop;
158 =head2 C<< CLASS->EventLoop() >>
160 Start processing IO events. In most daemon programs this never exits. See
161 C<PostLoopCallback> below for how to exit the loop.
164 sub FirstTimeEventLoop {
172 sub now () { clock_gettime(CLOCK_MONOTONIC) }
174 # runs timers and returns milliseconds for next one, or next event loop
176 return $LoopTimeout unless @Timers;
181 while (@Timers && $Timers[0][0] <= $now) {
182 my $to_run = shift(@Timers);
183 $to_run->[1]->($now) if $to_run->[1];
186 return $LoopTimeout unless @Timers;
188 # convert time to an even number of milliseconds, adding 1
189 # extra, otherwise floating point fun can occur and we'll
190 # call RunTimers like 20-30 times, each returning a timeout
191 # of 0.0000212 seconds
192 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
194 # -1 is an infinite timeout, so prefer a real timeout
195 return $timeout if $LoopTimeout == -1;
197 # otherwise pick the lower of our regular timeout and time until
199 return $LoopTimeout if $LoopTimeout < $timeout;
207 my $timeout = RunTimers();
209 # get up to 1000 events
210 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
211 for ($i=0; $i<$evcount; $i++) {
212 # it's possible epoll_wait returned many events, including some at the end
213 # that ones in the front triggered unregister-interest actions. if we
214 # can't find the %sock entry, it's because we're no longer interested
216 $DescriptorMap{$events[$i]->[0]}->event_step;
218 return unless PostEventLoop();
222 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
224 Sets post loop callback function. Pass a subref and it will be
225 called every time the event loop finishes.
227 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
230 The callback function will be passed two parameters: \%DescriptorMap
233 sub SetPostLoopCallback {
234 my ($class, $ref) = @_;
237 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
240 # Internal function: run the post-event callback, send read events
241 # for pushed-back data, and close pending connections. returns 1
242 # if event loop should continue, or 0 to shut it all down.
244 # now we can close sockets that wanted to close during our event processing.
245 # (we didn't want to close them during the loop, as we didn't want fd numbers
246 # being reused and confused during the event loop)
247 while (my $sock = shift @ToClose) {
248 my $fd = fileno($sock);
250 # close the socket. (not a PublicInbox::DS close)
253 # and now we can finally remove the fd from the map. see
254 # comment above in ->close.
255 delete $DescriptorMap{$fd};
259 # by default we keep running, unless a postloop callback (either per-object
260 # or global) cancels it
261 my $keep_running = 1;
263 # now we're at the very end, call callback if defined
264 if (defined $PostLoopCallback) {
265 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
268 return $keep_running;
271 #####################################################################
272 ### PublicInbox::DS-the-object code
273 #####################################################################
275 =head2 OBJECT METHODS
277 =head2 C<< CLASS->new( $socket ) >>
279 Create a new PublicInbox::DS subclass object for the given I<socket> which will
280 react to events on it during the C<EventLoop>.
282 This is normally (always?) called from your subclass via:
284 $class->SUPER::new($socket);
288 my ($self, $sock, $ev) = @_;
289 $self = fields::new($self) unless ref $self;
291 $self->{sock} = $sock;
292 my $fd = fileno($sock);
294 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
299 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
300 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
301 $ev &= ~EPOLLEXCLUSIVE;
304 die "couldn't add epoll watch for $fd: $!\n";
306 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
307 if $DescriptorMap{$fd};
309 $DescriptorMap{$fd} = $self;
314 #####################################################################
315 ### I N S T A N C E M E T H O D S
316 #####################################################################
318 =head2 C<< $obj->close >>
325 my $sock = delete $self->{sock} or return;
327 # we need to flush our write buffer, as there may
328 # be self-referential closures (sub { $client->close })
329 # preventing the object from being destroyed
330 delete $self->{wbuf};
332 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
333 # notifications about it
334 my $fd = fileno($sock);
335 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
336 confess("EPOLL_CTL_DEL: $!");
338 # we explicitly don't delete from DescriptorMap here until we
339 # actually close the socket, as we might be in the middle of
340 # processing an epoll_wait/etc that returned hundreds of fds, one
341 # of which is not yet processed and is what we're closing. if we
342 # keep it in DescriptorMap, then the event harnesses can just
343 # looked at $pob->{sock} == undef and ignore it. but if it's an
344 # un-accounted for fd, then it (understandably) freak out a bit
345 # and emit warnings, thinking their state got off.
347 # defer closing the actual socket until the event loop is done
348 # processing this round of events. (otherwise we might reuse fds)
349 push @ToClose, $sock;
354 # portable, non-thread-safe sendfile emulation (no pread, yet)
355 sub psendfile ($$$) {
356 my ($sock, $fh, $off) = @_;
358 seek($fh, $$off, SEEK_SET) or return;
359 defined(my $to_write = read($fh, my $buf, 16384)) or return;
361 while ($to_write > 0) {
362 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
366 return if $written == 0;
374 # returns 1 if done, 0 if incomplete
375 sub flush_write ($) {
377 my $wbuf = $self->{wbuf} or return 1;
378 my $sock = $self->{sock};
381 while (my $bref = $wbuf->[0]) {
382 if (ref($bref) ne 'CODE') {
383 my $off = delete($self->{wbuf_off}) // 0;
385 my $w = psendfile($sock, $bref, \$off);
391 } elsif ($! == EAGAIN) {
392 $self->{wbuf_off} = $off;
393 watch($self, EPOLLOUT|EPOLLONESHOT);
399 } else { #($ref eq 'CODE') {
401 my $before = scalar(@$wbuf);
404 # bref may be enqueueing more CODE to call (see accept_tls_step)
405 return 0 if (scalar(@$wbuf) > $before);
409 delete $self->{wbuf};
414 my ($self, $rbuf, $len, $off) = @_;
415 my $r = sysread($self->{sock}, $$rbuf, $len, $off);
416 return ($r == 0 ? $self->close : $r) if defined $r;
417 # common for clients to break connections without warning,
418 # would be too noisy to log here:
419 if (ref($self) eq 'IO::Socket::SSL') {
420 my $ev = PublicInbox::TLS::epollbit() or return $self->close;
421 watch($self, $ev | EPOLLONESHOT);
422 } elsif ($! == EAGAIN) {
423 watch($self, EPOLLIN | EPOLLONESHOT);
429 # drop the socket if we hit unrecoverable errors on our system which
430 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
437 # n.b.: use ->write/->read for this buffer to allow compatibility with
438 # PerlIO::mmap or PerlIO::scalar if needed
440 my ($self, $bref, $off) = @_;
441 # open(my $fh, '+>>', undef) doesn't set O_APPEND
442 my ($fh, $path) = eval { tempfile('wbuf-XXXXXXX', TMPDIR => 1) };
443 $fh or return drop($self, "tempfile: $@");
444 open($fh, '+>>', $path) or return drop($self, "open: $!");
446 unlink($path) or return drop($self, "unlink: $!");
447 my $len = bytes::length($$bref) - $off;
448 $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
452 =head2 C<< $obj->write( $data ) >>
454 Write the specified data to the underlying handle. I<data> may be scalar,
455 scalar ref, code ref (to run when there).
456 Returns 1 if writes all went through, or 0 if there are writes in queue. If
457 it returns 1, caller should stop waiting for 'writable' events)
461 my ($self, $data) = @_;
463 # nobody should be writing to closed sockets, but caller code can
464 # do two writes within an event, have the first fail and
465 # disconnect the other side (whose destructor then closes the
466 # calling object, but it's still in a method), and then the
467 # now-dead object does its second write. that is this case. we
468 # just lie and say it worked. it'll be dead soon and won't be
470 my $sock = $self->{sock} or return 1;
472 my $bref = $ref ? $data : \$data;
473 my $wbuf = $self->{wbuf};
474 if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
475 if ($ref eq 'CODE') {
478 my $last = $wbuf->[-1];
479 if (ref($last) eq 'GLOB') { # append to tmp file buffer
480 $last->print($$bref) or return drop($self, "print: $!");
482 my $tmpio = tmpio($self, $bref, 0) or return 0;
487 } elsif ($ref eq 'CODE') {
491 my $to_write = bytes::length($$bref);
492 my $written = syswrite($sock, $$bref, $to_write);
494 if (defined $written) {
495 return 1 if $written == $to_write;
496 } elsif ($! == EAGAIN) {
501 my $tmpio = tmpio($self, $bref, $written) or return 0;
502 $self->{wbuf} = [ $tmpio ];
503 watch($self, EPOLLOUT|EPOLLONESHOT);
508 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
512 my $sock = $self->{sock} or return 1;
514 if (MSG_MORE && !$self->{wbuf} && ref($sock) ne 'IO::Socket::SSL') {
515 my $n = send($sock, $_[1], MSG_MORE);
517 my $nlen = bytes::length($_[1]) - $n;
518 return 1 if $nlen == 0; # all done!
519 # queue up the unwritten substring:
520 my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
521 $self->{wbuf} = [ $tmpio ];
522 watch($self, EPOLLOUT|EPOLLONESHOT);
526 $self->write(\($_[1]));
530 my ($self, $ev) = @_;
531 my $sock = $self->{sock} or return;
532 epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
533 confess("EPOLL_CTL_MOD $!");
537 sub watch_in1 ($) { watch($_[0], EPOLLIN | EPOLLONESHOT) }
539 # return true if complete, false if incomplete (or failure)
540 sub accept_tls_step ($) {
542 my $sock = $self->{sock} or return;
543 return 1 if $sock->accept_SSL;
544 return $self->close if $! != EAGAIN;
545 if (my $ev = PublicInbox::TLS::epollbit()) {
546 unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
547 return watch($self, $ev | EPOLLONESHOT);
549 drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
552 sub shutdn_tls_step ($) {
554 my $sock = $self->{sock} or return;
555 return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
556 return $self->close if $! != EAGAIN;
557 if (my $ev = PublicInbox::TLS::epollbit()) {
558 unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
559 return watch($self, $ev | EPOLLONESHOT);
561 drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
564 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
565 # or fork w/o exec, so no inadvertant socket sharing
568 my $sock = $self->{sock} or return;
569 if (ref($sock) eq 'IO::Socket::SSL') {
570 shutdn_tls_step($self);
576 package PublicInbox::DS::Timer;
577 # [$abs_float_firetime, $coderef];
584 =head1 AUTHORS (Danga::Socket)
586 Brad Fitzpatrick <brad@danga.com> - author
588 Michael Granger <ged@danga.com> - docs, testing
590 Mark Smith <junior@danga.com> - contributor, heavy user, testing
592 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits