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