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