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