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