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