]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
3c922ccdf851b01a9e99ed0f9785282b133cb57c
[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 package PublicInbox::DS;
17 use strict;
18 use bytes;
19 use POSIX qw(WNOHANG);
20 use IO::Handle qw();
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);
25 use warnings;
26 use 5.010_001;
27 use Scalar::Util qw(blessed);
28
29 use PublicInbox::Syscall qw(:epoll);
30 use PublicInbox::Tmpfile;
31
32 use fields ('sock',              # underlying socket
33             'rbuf',              # scalarref, usually undef
34             'wbuf', # arrayref of coderefs or GLOB refs (autovivified)
35             'wbuf_off',  # offset into first element of wbuf to start writing at
36             );
37
38 use Errno qw(EAGAIN EINVAL);
39 use Carp qw(confess carp);
40
41 my $nextq; # queue for next_tick
42 my $wait_pids; # list of [ pid, callback, callback_arg ]
43 my $later_queue; # callbacks
44 my $EXPMAP; # fd -> [ idle_time, $self ]
45 our $EXPTIME = 180; # 3 minutes
46 my ($later_timer, $reap_timer, $exp_timer);
47 my $ToClose; # sockets to close when event loop is done
48 our (
49      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
50      $Epoll,                     # Global epoll fd (or DSKQXS ref)
51      $_io,                       # IO::Handle for Epoll
52
53      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
54
55      $LoopTimeout,               # timeout of event loop in milliseconds
56      $DoneInit,                  # if we've done the one-time module init yet
57      @Timers,                    # timers
58      $in_loop,
59      );
60
61 Reset();
62
63 #####################################################################
64 ### C L A S S   M E T H O D S
65 #####################################################################
66
67 =head2 C<< CLASS->Reset() >>
68
69 Reset all state
70
71 =cut
72 sub Reset {
73     %DescriptorMap = ();
74     $wait_pids = undef;
75     $later_queue = [];
76     $EXPMAP = {};
77     $nextq = $ToClose = $reap_timer = $later_timer = $exp_timer = undef;
78     $LoopTimeout = -1;  # no timeout by default
79     @Timers = ();
80
81     $PostLoopCallback = undef;
82     $DoneInit = 0;
83
84     $_io = undef; # closes real $Epoll FD
85     $Epoll = undef; # may call DSKQXS::DESTROY
86
87     *EventLoop = *FirstTimeEventLoop;
88 }
89
90 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
91
92 Set the loop timeout for the event loop to some value in milliseconds.
93
94 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
95 immediately.
96
97 =cut
98 sub SetLoopTimeout {
99     return $LoopTimeout = $_[1] + 0;
100 }
101
102 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef ) >>
103
104 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
105 are not guaranteed to fire at the exact time you ask for.
106
107 =cut
108 sub add_timer ($$) {
109     my ($secs, $coderef) = @_;
110
111     my $fire_time = now() + $secs;
112
113     my $timer = [$fire_time, $coderef];
114
115     if (!@Timers || $fire_time >= $Timers[-1][0]) {
116         push @Timers, $timer;
117         return $timer;
118     }
119
120     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
121     # but it was compared against calendar queues, heaps, naive push/sort,
122     # and a bunch of other versions, and found to be fastest with a large
123     # variety of datasets.)
124     for (my $i = 0; $i < @Timers; $i++) {
125         if ($Timers[$i][0] > $fire_time) {
126             splice(@Timers, $i, 0, $timer);
127             return $timer;
128         }
129     }
130
131     die "Shouldn't get here.";
132 }
133
134 # keeping this around in case we support other FD types for now,
135 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
136 sub set_cloexec ($) {
137     my ($fd) = @_;
138
139     $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
140     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
141     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
142 }
143
144 sub _InitPoller
145 {
146     return if $DoneInit;
147     $DoneInit = 1;
148
149     if (PublicInbox::Syscall::epoll_defined())  {
150         $Epoll = epoll_create();
151         set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
152     } else {
153         my $cls;
154         for (qw(DSKQXS DSPoll)) {
155             $cls = "PublicInbox::$_";
156             last if eval "require $cls";
157         }
158         $cls->import(qw(epoll_ctl epoll_wait));
159         $Epoll = $cls->new;
160     }
161     *EventLoop = *EpollEventLoop;
162 }
163
164 =head2 C<< CLASS->EventLoop() >>
165
166 Start processing IO events. In most daemon programs this never exits. See
167 C<PostLoopCallback> below for how to exit the loop.
168
169 =cut
170 sub FirstTimeEventLoop {
171     my $class = shift;
172
173     _InitPoller();
174
175     EventLoop($class);
176 }
177
178 sub now () { clock_gettime(CLOCK_MONOTONIC) }
179
180 sub next_tick () {
181     my $q = $nextq or return;
182     $nextq = undef;
183     for (@$q) {
184         # we avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
185         # https://rt.perl.org/Public/Bug/Display.html?id=114340
186         if (blessed($_)) {
187             $_->event_step;
188         } else {
189             $_->();
190         }
191     }
192 }
193
194 # runs timers and returns milliseconds for next one, or next event loop
195 sub RunTimers {
196     next_tick();
197
198     return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
199
200     my $now = now();
201
202     # Run expired timers
203     while (@Timers && $Timers[0][0] <= $now) {
204         my $to_run = shift(@Timers);
205         $to_run->[1]->($now) if $to_run->[1];
206     }
207
208     # timers may enqueue into nextq:
209     return 0 if ($nextq || $ToClose);
210
211     return $LoopTimeout unless @Timers;
212
213     # convert time to an even number of milliseconds, adding 1
214     # extra, otherwise floating point fun can occur and we'll
215     # call RunTimers like 20-30 times, each returning a timeout
216     # of 0.0000212 seconds
217     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
218
219     # -1 is an infinite timeout, so prefer a real timeout
220     return $timeout     if $LoopTimeout == -1;
221
222     # otherwise pick the lower of our regular timeout and time until
223     # the next timer
224     return $LoopTimeout if $LoopTimeout < $timeout;
225     return $timeout;
226 }
227
228 # We can't use waitpid(-1) safely here since it can hit ``, system(),
229 # and other things.  So we scan the $wait_pids list, which is hopefully
230 # not too big.  We keep $wait_pids small by not calling dwaitpid()
231 # until we've hit EOF when reading the stdout of the child.
232 sub reap_pids {
233     my $tmp = $wait_pids or return;
234     $wait_pids = $reap_timer = undef;
235     foreach my $ary (@$tmp) {
236         my ($pid, $cb, $arg) = @$ary;
237         my $ret = waitpid($pid, WNOHANG);
238         if ($ret == 0) {
239             push @$wait_pids, $ary; # autovivifies @$wait_pids
240         } elsif ($cb) {
241             eval { $cb->($arg, $pid) };
242         }
243     }
244     # we may not be done, yet, and could've missed/masked a SIGCHLD:
245     $reap_timer = add_timer(1, \&reap_pids) if $wait_pids;
246 }
247
248 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
249 sub enqueue_reap ($) { push @$nextq, \&reap_pids }; # autovivifies
250
251 sub in_loop () { $in_loop }
252
253 # Internal function: run the post-event callback, send read events
254 # for pushed-back data, and close pending connections.  returns 1
255 # if event loop should continue, or 0 to shut it all down.
256 sub PostEventLoop () {
257         # now we can close sockets that wanted to close during our event
258         # processing.  (we didn't want to close them during the loop, as we
259         # didn't want fd numbers being reused and confused during the event
260         # loop)
261         if (my $close_now = $ToClose) {
262                 $ToClose = undef; # will be autovivified on push
263                 # ->DESTROY methods may populate ToClose
264                 delete($DescriptorMap{fileno($_)}) for @$close_now;
265                 # let refcounting drop everything in $close_now at once
266         }
267
268         # by default we keep running, unless a postloop callback cancels it
269         $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
270 }
271
272 sub EpollEventLoop {
273     local $in_loop = 1;
274     do {
275         my @events;
276         my $i;
277         my $timeout = RunTimers();
278
279         # get up to 1000 events
280         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
281         for ($i=0; $i<$evcount; $i++) {
282             # it's possible epoll_wait returned many events, including some at the end
283             # that ones in the front triggered unregister-interest actions.  if we
284             # can't find the %sock entry, it's because we're no longer interested
285             # in that event.
286             $DescriptorMap{$events[$i]->[0]}->event_step;
287         }
288     } while (PostEventLoop());
289     _run_later();
290 }
291
292 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
293
294 Sets post loop callback function.  Pass a subref and it will be
295 called every time the event loop finishes.
296
297 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
298 and it will exit.
299
300 The callback function will be passed two parameters: \%DescriptorMap
301
302 =cut
303 sub SetPostLoopCallback {
304     my ($class, $ref) = @_;
305
306     # global callback
307     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
308 }
309
310 #####################################################################
311 ### PublicInbox::DS-the-object code
312 #####################################################################
313
314 =head2 OBJECT METHODS
315
316 =head2 C<< CLASS->new( $socket ) >>
317
318 Create a new PublicInbox::DS subclass object for the given I<socket> which will
319 react to events on it during the C<EventLoop>.
320
321 This is normally (always?) called from your subclass via:
322
323   $class->SUPER::new($socket);
324
325 =cut
326 sub new {
327     my ($self, $sock, $ev) = @_;
328     $self = fields::new($self) unless ref $self;
329
330     $self->{sock} = $sock;
331     my $fd = fileno($sock);
332
333     _InitPoller();
334
335     if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
336         if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
337             $ev &= ~EPOLLEXCLUSIVE;
338             goto retry;
339         }
340         die "couldn't add epoll watch for $fd: $!\n";
341     }
342     confess("DescriptorMap{$fd} defined ($DescriptorMap{$fd})")
343         if defined($DescriptorMap{$fd});
344
345     $DescriptorMap{$fd} = $self;
346 }
347
348
349 #####################################################################
350 ### I N S T A N C E   M E T H O D S
351 #####################################################################
352
353 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
354
355 =head2 C<< $obj->close >>
356
357 Close the socket.
358
359 =cut
360 sub close {
361     my ($self) = @_;
362     my $sock = delete $self->{sock} or return;
363
364     # we need to flush our write buffer, as there may
365     # be self-referential closures (sub { $client->close })
366     # preventing the object from being destroyed
367     delete $self->{wbuf};
368
369     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
370     # notifications about it
371     my $fd = fileno($sock);
372     epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
373         confess("EPOLL_CTL_DEL: $!");
374
375     # we explicitly don't delete from DescriptorMap here until we
376     # actually close the socket, as we might be in the middle of
377     # processing an epoll_wait/etc that returned hundreds of fds, one
378     # of which is not yet processed and is what we're closing.  if we
379     # keep it in DescriptorMap, then the event harnesses can just
380     # looked at $pob->{sock} == undef and ignore it.  but if it's an
381     # un-accounted for fd, then it (understandably) freak out a bit
382     # and emit warnings, thinking their state got off.
383
384     # defer closing the actual socket until the event loop is done
385     # processing this round of events.  (otherwise we might reuse fds)
386     push @$ToClose, $sock; # autovivifies $ToClose
387
388     return 0;
389 }
390
391 # portable, non-thread-safe sendfile emulation (no pread, yet)
392 sub psendfile ($$$) {
393     my ($sock, $fh, $off) = @_;
394
395     seek($fh, $$off, SEEK_SET) or return;
396     defined(my $to_write = read($fh, my $buf, 16384)) or return;
397     my $written = 0;
398     while ($to_write > 0) {
399         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
400             $written += $w;
401             $to_write -= $w;
402         } else {
403             return if $written == 0;
404             last;
405         }
406     }
407     $$off += $written;
408     $written;
409 }
410
411 sub epbit ($$) { # (sock, default)
412     ref($_[0]) eq 'IO::Socket::SSL' ? PublicInbox::TLS::epollbit() : $_[1];
413 }
414
415 # returns 1 if done, 0 if incomplete
416 sub flush_write ($) {
417     my ($self) = @_;
418     my $wbuf = $self->{wbuf} or return 1;
419     my $sock = $self->{sock};
420
421 next_buf:
422     while (my $bref = $wbuf->[0]) {
423         if (ref($bref) ne 'CODE') {
424             my $off = delete($self->{wbuf_off}) // 0;
425             while ($sock) {
426                 my $w = psendfile($sock, $bref, \$off);
427                 if (defined $w) {
428                     if ($w == 0) {
429                         shift @$wbuf;
430                         goto next_buf;
431                     }
432                 } elsif ($! == EAGAIN) {
433                     epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
434                     $self->{wbuf_off} = $off;
435                     return 0;
436                 } else {
437                     return $self->close;
438                 }
439             }
440         } else { #($ref eq 'CODE') {
441             shift @$wbuf;
442             my $before = scalar(@$wbuf);
443             $bref->($self);
444
445             # bref may be enqueueing more CODE to call (see accept_tls_step)
446             return 0 if (scalar(@$wbuf) > $before);
447         }
448     } # while @$wbuf
449
450     delete $self->{wbuf};
451     1; # all done
452 }
453
454 sub rbuf_idle ($$) {
455     my ($self, $rbuf) = @_;
456     if ($$rbuf eq '') { # who knows how long till we can read again
457         delete $self->{rbuf};
458     } else {
459         $self->{rbuf} = $rbuf;
460     }
461 }
462
463 sub do_read ($$$;$) {
464     my ($self, $rbuf, $len, $off) = @_;
465     my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
466     return ($r == 0 ? $self->close : $r) if defined $r;
467     # common for clients to break connections without warning,
468     # would be too noisy to log here:
469     if ($! == EAGAIN) {
470         epwait($sock, epbit($sock, EPOLLIN) | EPOLLONESHOT);
471         rbuf_idle($self, $rbuf);
472         0;
473     } else {
474         $self->close;
475     }
476 }
477
478 # drop the socket if we hit unrecoverable errors on our system which
479 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
480 sub drop {
481     my $self = shift;
482     carp(@_);
483     $self->close;
484 }
485
486 # n.b.: use ->write/->read for this buffer to allow compatibility with
487 # PerlIO::mmap or PerlIO::scalar if needed
488 sub tmpio ($$$) {
489     my ($self, $bref, $off) = @_;
490     my $fh = tmpfile('wbuf', $self->{sock}, 1) or
491         return drop($self, "tmpfile $!");
492     $fh->autoflush(1);
493     my $len = bytes::length($$bref) - $off;
494     $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
495     $fh
496 }
497
498 =head2 C<< $obj->write( $data ) >>
499
500 Write the specified data to the underlying handle.  I<data> may be scalar,
501 scalar ref, code ref (to run when there).
502 Returns 1 if writes all went through, or 0 if there are writes in queue. If
503 it returns 1, caller should stop waiting for 'writable' events)
504
505 =cut
506 sub write {
507     my ($self, $data) = @_;
508
509     # nobody should be writing to closed sockets, but caller code can
510     # do two writes within an event, have the first fail and
511     # disconnect the other side (whose destructor then closes the
512     # calling object, but it's still in a method), and then the
513     # now-dead object does its second write.  that is this case.  we
514     # just lie and say it worked.  it'll be dead soon and won't be
515     # hurt by this lie.
516     my $sock = $self->{sock} or return 1;
517     my $ref = ref $data;
518     my $bref = $ref ? $data : \$data;
519     my $wbuf = $self->{wbuf};
520     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
521         if ($ref eq 'CODE') {
522             push @$wbuf, $bref;
523         } else {
524             my $last = $wbuf->[-1];
525             if (ref($last) eq 'GLOB') { # append to tmp file buffer
526                 $last->print($$bref) or return drop($self, "print: $!");
527             } else {
528                 my $tmpio = tmpio($self, $bref, 0) or return 0;
529                 push @$wbuf, $tmpio;
530             }
531         }
532         return 0;
533     } elsif ($ref eq 'CODE') {
534         $bref->($self);
535         return 1;
536     } else {
537         my $to_write = bytes::length($$bref);
538         my $written = syswrite($sock, $$bref, $to_write);
539
540         if (defined $written) {
541             return 1 if $written == $to_write;
542             requeue($self); # runs: event_step -> flush_write
543         } elsif ($! == EAGAIN) {
544             epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
545             $written = 0;
546         } else {
547             return $self->close;
548         }
549
550         # deal with EAGAIN or partial write:
551         my $tmpio = tmpio($self, $bref, $written) or return 0;
552
553         # wbuf may be an empty array if we're being called inside
554         # ->flush_write via CODE bref:
555         push @{$self->{wbuf}}, $tmpio; # autovivifies
556         return 0;
557     }
558 }
559
560 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
561
562 sub msg_more ($$) {
563     my $self = $_[0];
564     my $sock = $self->{sock} or return 1;
565     my $wbuf = $self->{wbuf};
566
567     if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
568                 ref($sock) ne 'IO::Socket::SSL') {
569         my $n = send($sock, $_[1], MSG_MORE);
570         if (defined $n) {
571             my $nlen = bytes::length($_[1]) - $n;
572             return 1 if $nlen == 0; # all done!
573             # queue up the unwritten substring:
574             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
575             push @{$self->{wbuf}}, $tmpio; # autovivifies
576             epwait($sock, EPOLLOUT|EPOLLONESHOT);
577             return 0;
578         }
579     }
580
581     # don't redispatch into NNTPdeflate::write
582     PublicInbox::DS::write($self, \($_[1]));
583 }
584
585 sub epwait ($$) {
586     my ($sock, $ev) = @_;
587     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
588         confess("EPOLL_CTL_MOD $!");
589 }
590
591 # return true if complete, false if incomplete (or failure)
592 sub accept_tls_step ($) {
593     my ($self) = @_;
594     my $sock = $self->{sock} or return;
595     return 1 if $sock->accept_SSL;
596     return $self->close if $! != EAGAIN;
597     epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
598     unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
599     0;
600 }
601
602 # return true if complete, false if incomplete (or failure)
603 sub shutdn_tls_step ($) {
604     my ($self) = @_;
605     my $sock = $self->{sock} or return;
606     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
607     return $self->close if $! != EAGAIN;
608     epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
609     unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
610     0;
611 }
612
613 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
614 # or fork w/o exec, so no inadvertant socket sharing
615 sub shutdn ($) {
616     my ($self) = @_;
617     my $sock = $self->{sock} or return;
618     if (ref($sock) eq 'IO::Socket::SSL') {
619         shutdn_tls_step($self);
620     } else {
621         $self->close;
622     }
623 }
624
625 # must be called with eval, PublicInbox::DS may not be loaded (see t/qspawn.t)
626 sub dwaitpid ($$$) {
627         die "Not in EventLoop\n" unless $in_loop;
628         push @$wait_pids, [ @_ ]; # [ $pid, $cb, $arg ]
629
630         # We could've just missed our SIGCHLD, cover it, here:
631         requeue(\&reap_pids);
632 }
633
634 sub _run_later () {
635     my $run = $later_queue;
636     $later_timer = undef;
637     $later_queue = [];
638     $_->() for @$run;
639 }
640
641 sub later ($) {
642     my ($cb) = @_;
643     push @$later_queue, $cb;
644     $later_timer //= add_timer(60, \&_run_later);
645 }
646
647 sub expire_old () {
648     my $now = now();
649     my $exp = $EXPTIME;
650     my $old = $now - $exp;
651     my %new;
652     while (my ($fd, $v) = each %$EXPMAP) {
653         my ($idle_time, $ds_obj) = @$v;
654         if ($idle_time < $old) {
655             if (!$ds_obj->shutdn) {
656                 $new{$fd} = $v;
657             }
658         } else {
659             $new{$fd} = $v;
660         }
661     }
662     $EXPMAP = \%new;
663     $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
664 }
665
666 sub update_idle_time {
667     my ($self) = @_;
668     my $sock = $self->{sock} or return;
669     $EXPMAP->{fileno($sock)} = [ now(), $self ];
670     $exp_timer //= later(\&expire_old);
671 }
672
673 sub not_idle_long {
674     my ($self, $now) = @_;
675     my $sock = $self->{sock} or return;
676     my $ary = $EXPMAP->{fileno($sock)} or return;
677     my $exp_at = $ary->[0] + $EXPTIME;
678     $exp_at > $now;
679 }
680
681 1;
682
683 =head1 AUTHORS (Danga::Socket)
684
685 Brad Fitzpatrick <brad@danga.com> - author
686
687 Michael Granger <ged@danga.com> - docs, testing
688
689 Mark Smith <junior@danga.com> - contributor, heavy user, testing
690
691 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits