Debian Codegraph @

lemonldap-ng-common/eg/llng-pubsub-server

raw
1 #!/usr/bin/perl
2
3 use strict;
4 use Getopt::Long;
5 use IO::Select;
6 use JSON;
7 use POSIX qw(strftime setsid setuid setgid);
8 use Protocol::WebSocket::Handshake::Server;
9 use Protocol::WebSocket::Frame;
10 use Regexp::Common qw(net);
11 use Socket
12 qw(AF_INET AF_INET6 inet_ntop unpack_sockaddr_in unpack_sockaddr_in6);
13 use URI;
14
15 # 1. Parse options
16
17 my (
18 $accessLog, $addr, $cert, $daemon,
19 $_debug, $group, $help, $key,
20 $maxRequestSize, $maxRequestTime, $maxRestarts, $maxWaitingConn,
21 $quiet, $pidFile, $port, $restartWindow,
22 $token, $user,
23 );
24
25 # HTTP header separator
26 use constant HS => qr/(?:\r?\n){2}/;
27
28 my @CMDLINE = @ARGV;
29
30 GetOptions(
31 'access-log=s' => \$accessLog,
32 'addr|a=s@' => \$addr,
33 'cert=s' => \$cert,
34 'daemon' => \$daemon,
35 'debug|d' => \$_debug,
36 'group|g=s' => \$group,
37 'help|h' => \$help,
38 'key=s' => \$key,
39 'max-request-size=s' => \$maxRequestSize,
40 'max-request-time=s' => \$maxRequestTime,
41 'max-restarts=s' => \$maxRestarts,
42 'max-waiting-conn=s' => \$maxWaitingConn,
43 'quiet|q' => \$quiet,
44 'pid-file=s' => \$pidFile,
45 'port|p=s' => \$port,
46 'restart-window' => \$restartWindow,
47 'token=s' => \$token,
48 'user|u=s' => \$user,
49 );
50
51 $accessLog ||= $ENV{PUBSUB_ACCESS_LOG};
52 $addr ||= [ split( /\s+/, $ENV{PUBSUB_ADDR} ) ];
53 $cert ||= $ENV{PUBSUB_CERT};
54 $daemon ||= $ENV{PUBSUB_DAEMON};
55 $_debug ||= $ENV{PUBSUB_DEBUG};
56 $group ||= $ENV{PUBSUB_GROUP};
57 $key ||= $ENV{PUBSUB_KEY};
58 $maxRequestSize ||= $ENV{PUBSUB_MAX_REQUEST_SIZE} || 8192;
59 $maxRequestTime ||= $ENV{PUBSUB_MAX_REQUEST_TIME} || 5;
60 $maxRestarts ||= $ENV{PUBSUB_MAX_RESTARTS} || 5;
61 $maxWaitingConn ||= $ENV{PUBSUB_MAX_WAITING_CONN} || 10;
62 $pidFile ||= $ENV{PUBSUB_PID_FILE};
63 $quiet ||= $ENV{PUBSUB_QUIET};
64 $restartWindow ||= $ENV{PUBSUB_RESTART_WINDOW} || 60;
65 $token ||= $ENV{PUBSUB_TOKEN};
66 $user ||= $ENV{PUBSUB_USER};
67
68 if ($help) {
69 require Pod::Usage;
70 Pod::Usage::pod2usage( -exitcode => 0, -verbose => 2 );
71 }
72
73 &daemonize if $daemon;
74
75 sub debug {
76 print STDERR map { "$_\n" } @_ if $_debug;
77 }
78
79 sub warning {
80 print STDERR map { "$_\n" } @_ unless $quiet;
81 }
82
83 sub error {
84 print STDERR map { "$_\n" } @_;
85 }
86
87 sub printWebLog {
88 return if $quiet and !$accessLog;
89 my ( $msg, $ip ) = @_;
90 my $date = strftime( "[%d/%b/%Y:%H:%M:%S %z]", localtime );
91 my $log = "$ip - - $date $msg -\n";
92 if ( $accessLog eq 'STDERR' ) {
93 print STDERR $log;
94 }
95 else {
96 print $log;
97 }
98 debug "Request: $msg";
99 }
100
101 if ( $accessLog and $accessLog ne '-' and $accessLog ne 'STDERR' ) {
102 debug "Access logs will be written into $accessLog\n";
103 open STDOUT, '>>', $accessLog or die "Unable to write logs: $!";
104 if ($daemon) {
105 open STDERR, '>&', fileno(STDOUT) or die "Can't dup STDERR: $!";
106 STDERR->autoflush(1);
107 }
108 }
109
110 if ( $cert xor $key ) {
111 die '--cert and --key must be used together';
112 }
113
114 unless ($token) {
115 warning "No token given, this means that anybody can use this server"
116 unless $quiet;
117 }
118
119 # 2. Create server
120
121 my @servers;
122 my $selector = IO::Select->new;
123 $addr = [0] unless @$addr;
124
125 foreach my $a (@$addr) {
126 my $server;
127 my $p;
128
129 # IPv6 addresses with port
130 if ( $a =~ s/^\s*\[($RE{net}{IPv6})\]:(\d+)\s*$/$1/ ) {
131 $p = $2;
132 }
133 elsif ( $a =~ s/^\s*($RE{net}{IPv4}):(\d+)\s*$/$1/ ) {
134 $p = $2;
135 }
136 elsif ( $a and $a !~ s/^\s*\[?($RE{net}{IPv4}|$RE{net}{IPv6})\]?\s*/$1/ ) {
137 die qq'Malformed IP address "$a"';
138 }
139 else {
140 $p = $port || ( $ENV{PUBSUB_PORT} || ( $cert ? 8443 : 8080 ) );
141 }
142
143 my %args = (
144 ( $a ? ( LocalAddr => $a ) : () ),
145 LocalPort => $p,
146 Listen => $maxWaitingConn,
147 ReuseAddr => 1,
148 ReusePort => 1,
149 );
150 if ($cert) {
151 require IO::Socket::SSL;
152 $server = IO::Socket::SSL->new(
153 %args,
154 SSL_cert_file => $cert,
155 SSL_key_file => $key,
156 SSL_server => 1,
157 );
158 }
159 else {
160 require IO::Socket::IP;
161 $server = IO::Socket::IP->new( %args, Proto => 'tcp', );
162 }
163
164 die "Cannot create socket ("
165 . ( $a ? "address: $a, " : '' )
166 . "port: $p): $!"
167 unless $server;
168
169 debug 'Listening on ' . ( $a ? "$a:" : 'port ' ) . $p;
170 $selector->add($server);
171 push @servers, $server;
172 }
173
174 if ($group) {
175 my $grp = getgrnam($group) or die "Can't change gid to $group";
176 setgid($grp) or die "setgid: $!";
177 }
178
179 if ($user) {
180 my $uid = getpwnam($user) or die "Can't change uid to $user";
181 setuid($uid) or die "setuid: $!";
182 }
183
184 my $json = JSON->new->utf8;
185
186 # 3. Manage requests
187
188 my %clients;
189
190 while (1) {
191 for my $sock ( $selector->can_read(0.1) ) {
192 my ($server) = grep { $sock eq $_ } @servers;
193 if ($server) {
194 my $client = $server->accept or next;
195 $client->autoflush(1);
196 $selector->add($client);
197 }
198 else {
199 my $fileno = fileno($sock);
200 my $buf = '';
201 my $n = sysread( $sock, $buf, 4096 );
202 if ( !defined $n || $n == 0 ) {
203 cleanupClient($sock);
204 next;
205 }
206
207 # Known clients are subscribers, we can discard
208 if ( exists $clients{$fileno} ) {
209 my $frame = $clients{$fileno}->{frame};
210 $frame->append($buf);
211 while ( my $msg = $frame->next ) {
212
213 # read-only client; we discard messages
214 }
215 }
216
217 else {
218 my $req = $buf;
219 my $start = time;
220 while ( $req !~ HS ) {
221 last if length($req) > $maxRequestSize;
222 last if ( time - $start ) > $maxRequestTime;
223 my $tmp;
224 my $r = sysread( $sock, $tmp, 4096 );
225 $req .= $tmp if $r;
226 }
227
228 # Get headers
229 my ( $headers, $body ) = split( HS, $req, 2 );
230 my @lines = split /\r?\n/, $headers;
231 my $request = shift @lines;
232 my %hdr;
233 for (@lines) {
234 if (/^([^:]+):\s*(.+)$/) {
235 $hdr{ lc $1 } = $2;
236 }
237 }
238
239 # Auth check
240 if ( $token and $hdr{authorization} ne "Bearer $token" ) {
241 sendHttp( $sock, 401, "Unauthorized", "Bad token",
242 $request );
243 next;
244 }
245
246 # WebSocket GET
247 if ( $request =~ m{^GET\s+(/subscribe\S*)\s+HTTP/1.[01]$} ) {
248 my %params = eval { URI->new($1)->query_form };
249 warning "URI parse error: $@" if $@;
250 my @channels = split /,/, ( $params{channels} // '' );
251
252 unless (@channels) {
253 warning "Missing channel(s)";
254 sendHttp( $sock, 400, "Bad Request",
255 "Missing channel(s)", $request );
256 }
257
258 my $hs = Protocol::WebSocket::Handshake::Server->new;
259 $hs->parse($req);
260
261 if ( $hs->is_done ) {
262 my $ip = getIp($sock);
263 my $res = $hs->to_string;
264 my $len = length($res);
265 print $sock $res;
266 $clients{$fileno} = {
267 socket => $sock,
268 frame => Protocol::WebSocket::Frame->new,
269 channels => { map { $_ => 1 } @channels },
270 };
271 $request =~ s/[\r\n]//g;
272 printWebLog( qq("$request" 200 $len), $ip );
273 }
274 else {
275 warning "ERROR: " . $hs->error;
276 sendHttp( $sock, 400, "Bad Request",
277 "WebSocket handshake failed", $request );
278 }
279 }
280
281 # Publish API
282 elsif ( $request =~ m{^POST\s+/publish\s+HTTP/1.[01]$} ) {
283 my $len = $hdr{'content-length'} // length($body);
284 my $remaining = $len - length($body);
285 while ( $remaining > 0 ) {
286 last if length($req) > $maxRequestSize;
287 last if ( time - $start ) > $maxRequestTime;
288 my $tmp;
289 my $r = sysread( $sock, $tmp, $remaining );
290 last unless $r;
291 $req .= $tmp;
292 $body .= $tmp;
293 $remaining -= $r;
294 }
295
296 if ($remaining) {
297 sendHttp( $sock, 408, 'Request timeout', $request );
298 next;
299 }
300
301 my $data = eval { $json->decode($body) };
302 if ( $@ || !defined $data ) {
303 sendHttp( $sock, 400, "Bad Request",
304 "Missing or invalid JSON", $request );
305 next;
306 }
307
308 debug "Message to publish: $body";
309
310 my $channel = $data->{channel};
311 unless ($channel) {
312 sendHttp( $sock, 400, "Bad Request",
313 "Missing channel", $request );
314 next;
315 }
316
317 my $msg = $body;
318 my $frame = Protocol::WebSocket::Frame->new;
319 $frame->append($msg);
320 my $bytes = $frame->to_bytes;
321
322 for my $c ( values %clients ) {
323 next unless $c->{channels}->{$channel};
324 my $ws_sock = $c->{socket};
325 print $ws_sock $bytes;
326 }
327
328 sendHttp( $sock, 200, "OK", "Message sent", $request );
329 }
330
331 else {
332 sendHttp( $sock, 404, "Not Found", "Unknown endpoint",
333 $request );
334 }
335 }
336 }
337 }
338 }
339
340 sub sendHttp {
341 my ( $sock, $code, $status, $body, $request ) = @_;
342 my $ip = getIp($sock);
343 my $len = length($body);
344 my $resp =
345 "HTTP/1.1 $code $status\r\n"
346 . "Content-Type: text/plain\r\n"
347 . "Content-Length: $len\r\n"
348 . "Connection: close\r\n\r\n"
349 . $body;
350 print $sock $resp;
351 cleanupClient($sock);
352 $request =~ s/[\r\n]//g;
353 $len = length($resp);
354 printWebLog( qq("$request" $code $len), $ip );
355 }
356
357 sub cleanupClient {
358 my ($sock) = @_;
359 $selector->remove($sock);
360 my $fileno = fileno($sock);
361 delete $clients{$fileno};
362 close $sock;
363 }
364
365 sub getIp {
366 my ($sock) = @_;
367 my $peer = getpeername($sock);
368 my ($family) = unpack( 'S', $peer );
369 if ( $family == AF_INET ) {
370 my ( $port, $addr ) = unpack_sockaddr_in($peer);
371 return inet_ntop( AF_INET, $addr );
372 }
373 else {
374 my ( $port, $addr ) = unpack_sockaddr_in6($peer);
375 return inet_ntop( AF_INET6, $addr );
376 }
377 }
378
379 sub daemonize {
380 open STDIN, '<', '/dev/null' or die "Can't read /dev/null: $!";
381 unless ( $accessLog eq '-' ) {
382 open STDOUT, '>', '/dev/null' or die "Can't write to /dev/null: $!";
383 }
384 unless ( $accessLog eq 'STDERR' ) {
385 open STDERR, '>', '/dev/null' or die "Can't write to /dev/null: $!";
386 }
387
388 defined( my $pid = fork ) or die "Can't fork: $!";
389 exit if $pid;
390
391 setsid() or die "Can't start a new session: $!";
392
393 defined( $pid = fork ) or die "Can't fork again: $!";
394 exit if $pid;
395
396 umask 0;
397
398 if ($pidFile) {
399 open my $fh, '>', $pidFile or die "Can't write $pidFile: $!";
400 print $fh "$$\n";
401 close $fh;
402 debug "Master pid written ($$)";
403 }
404 else {
405 debug "Master pid is $$";
406 }
407 $0 = join ' ', $0, @CMDLINE;
408
409 my $cpid;
410
411 # Master process code (relaunch webserver in case of failure)
412 if ( $cpid = fork ) {
413 $| = 1;
414 my @restartTimes;
415 my $term;
416 $SIG{CHLD} = 'DEFAULT';
417 $SIG{TERM} = sub {
418 kill 'TERM', $cpid;
419 waitpid( $cpid, 0 );
420 exit 0;
421 };
422 while (1) {
423 my $endedPid = waitpid( $cpid, 0 );
424 my $exitStatus = $? >> 8;
425 print STDERR "Server $endedPid ended with status $exitStatus\n";
426 @restartTimes = grep { time() - $_ < $restartWindow } @restartTimes;
427 print STDERR "@restartTimes >= $maxRestarts\n";
428 if ( @restartTimes >= $maxRestarts ) {
429 print STDERR "Too many failures in $restartWindow, aborting\n";
430 exit 1;
431 }
432 sleep 1;
433 last unless $cpid = fork;
434 push @restartTimes, time;
435 }
436 }
437 die $! unless defined $cpid;
438
439 # Don't propagate 'TERM' signal to master
440 setpgrp( 0, 0 );
441 }
442
443 __END__
444
445 =encoding UTF-8
446
447 =head1 NAME
448
449 llng-pubsub-server - Pub/Sub server based on websockets
450
451 =head1 SYNOPSIS
452
453 llng-pubsub-server <option>
454
455 Simple client using L<wscat|https://github.com/websockets/wscat>
456
457 wscat --connect ws://localhost:8080/subscribe?channels=chan1,chan2
458
459 Simple publisher
460
461 curl -XPOST -d '{"foo":"bar","bar":"baz","baz":"foo","channel":"chan1"}' http://localhost:8080/publish
462
463 Note that "channel" is required.
464
465 =head1 DESCRIPTION
466
467 B<llng-pubsub-server> is a web-based pub/sub server designed for L<LemonLDAP::NG|https://lemonldap-ng.org>.
468
469 =head2 Options
470
471 All options except B<--help> can have default value overriden by an
472 environment variable.
473
474 =head3 HTTP options
475
476 =over
477
478 =item * B<--token E<lt>valueE<gt>>
479
480 Optional token required to communicate with this server. When enabled, all
481 requests must contains an "Authorization" header:
482
483 Authorization: Bearer token-value
484
485 Environment variable: B<PUBSUB_TOKEN>
486
487 =item * B<--port E<lt>valueE<gt>> I<(default: 8080, or 8443 when B<--cert> is set)>
488
489 Port to listen to.
490
491 See L</"IPv4-IPv6 SUPPORT">.
492
493 Environment variable: B<PUBSUB_PORT>
494
495 =item * B<--addr E<lt>valueE<gt>> I<(default: all IPv4 interfaces)>
496
497 Adresse(s) to listen to, can be multi-valued and accept an optional port.
498 See L</"IPv4-IPv6 SUPPORT">.
499
500 Environment variable: B<PUBSUB_ADDR> I<(space-separated list)>
501
502 =item * B<--cert E<lt>valueE<gt>>
503
504 Optional server TLS certificate.
505
506 Environment variable: B<PUBSUB_CERT>
507
508 =item * B<--key E<lt>valueE<gt>>
509
510 Optional server TLS key.
511
512 Environment variable: B<PUBSUB_KEY>
513
514 =item * B<--max-request-size E<lt>valueE<gt>> I<(default: 8192)>
515
516 Maximum authorized size for a request.
517
518 Environment variable: B<PUBSUB_MAX_REQUEST_SIZE>
519
520 =item * B<--max-request-time E<lt>valueE<gt>> I<(default: 5)>
521
522 Maximum allowed delay for a request I<(in seconds)>.
523
524 Environment variable: B<PUBSUB_MAX_REQUEST_TIME>
525
526 =back
527
528 =head3 Server options
529
530 =over
531
532 =item * B<--daemon>
533
534 Daemonize the server.
535
536 Environment variable: B<PUBSUB_DAEMON>
537
538 =item * B<--pid-file E<lt>valueE<gt>>
539
540 When B<--daemon> is set, write the processus number into the given file.
541
542 Environment variable: B<PUBSUB_PID_FILE>
543
544 =item * B<--user> E<lt>valueE<gt>>
545
546 Change uid to the given value after opening socket.
547
548 Environment variable: B<PUBSUB_USER>
549
550 =item * B<--group> E<lt>valueE<gt>>
551
552 Change gid to the given value after opening socket.
553
554 Environment variable: B<PUBSUB_GROUP>
555
556 =item * B<--max-restarts> E<lt>valueE<gt>> I<(default: 5)>
557
558 Max failure accepted in the B<--restart-window> delay.
559
560 Environment variable: B<PUBSUB_MAX_RESTARTS>
561
562 =item * B<--max-waiting-conn> E<lt>valueE<gt>> I<(default: 10)>
563
564 Max client waiting for a response.
565
566 Environment variable: B<PUBSUB_MAX_WAITING_CONN>
567
568 =item * B<restart-window> E<lt>valueE<gt>> I<(default: 60)>
569
570 Delay for B<--max-restarts>
571
572 Environment variable: B<PUBSUB_RESTART_WINDOW>
573
574 =back
575
576 =head3 Logging options
577
578 =over
579
580 =item * B<--quiet>
581
582 Don't display warnings and access logs unless an explicit B<--access-log> is set.
583
584 Environment variable: B<PUBSUB_QUIET>
585
586 =item * B<--debug>
587
588 Display additional information.
589
590 Environment variable: B<PUBSUB_DEBUG>
591
592 =item * B<--access-log E<lt>valueE<gt>>
593
594 Files to store access logs. "B<->" means standard output. Useful to have access
595 logs on STDOUT when B<--quiet> is set.
596
597 Environment variable: B<PUBSUG_ACCESS_LOG>
598
599 =back
600
601 =head3 Other
602
603 =over
604
605 =item * B<--help>
606
607 Display this.
608
609 =back
610
611 =head2 API
612
613 =head3 Publisher
614
615 =over
616
617 =item * URL: C</publish>
618
619 =item * Method: POST
620
621 =item * Headers:
622
623 =over
624
625 =item * B<Authorization> I<(optional)>
626
627 If a token is required, set it here in the form:
628
629 Authorization: Bearer <value>
630
631 =back
632
633 =item * Request body:
634
635 JSON content with at least a "B<channel>" key
636 I<(the channel where the message will be published)>
637
638 =back
639
640 =head3 Reader I<(websockets)>
641
642 =over
643
644 =item * URL: C</subscribe> I<(this opens the websocket)>
645
646 =item * Method: GET
647
648 =item * Query I<(GET parameters)>
649
650 =over
651
652 =item * B<channels> I<(required)>
653
654 Comma separated list of channels to subscribe to.
655
656 =back
657
658 =back
659
660 =head1 IPv4-IPv6 SUPPORT
661
662 By default this server listen to all IPv4 addresses. To listen in the same time
663 to all IPv4/IPv6 addresses, use
664
665 --addr :: --addr 0.0.0.0
666
667 The B<--addr> option accepts also a port value. If port is not set, the
668 B<--port> will be used. Examples:
669
670 =over
671
672 =item * B<IPv4 address>: C<--addr 1.2.3.4>
673
674 =item * B<IPv4 address with port 7654>: C<--addr 1.2.3.4:7654>
675
676 =item * B<All IPv4 addresses>: C<--addr 0.0.0.0>
677
678 =item * B<All IPv4 addresses with port 8080>: C<--addr 0.0.0.0:8080>
679
680 =item * B<IPv6 address>: C<--addr fe80::1>
681
682 =item * B<IPv6 address with port 8080>: C<--addr '[::1]:8080'>
683
684 =item * B<All IPv6 addresses>: C<--addr ::>
685
686 =item * B<All IPv6 addresses with port 7654>: C<--addr '[::]:7654'>
687
688 =item * B<All IPv6 addresses with port 7654 and one IPv4 address with default port set to 8081>:
689 C<--addr '[::]:7654' --addr 1.2.3.4 --port 8081>
690
691 =back
692
693 =head1 SEE ALSO
694
695 =over
696
697 =item * L<Lemonldap::NG event management|https://lemonldap-ng.org/documentation/latest/eventsmanagement.html>
698
699 =item * L<http://lemonldap-ng.org/>
700
701 =back
702
703 =head1 BUG REPORT
704
705 Use OW2 system to report bug or ask for features:
706 L<https://gitlab.ow2.org/lemonldap-ng/lemonldap-ng/issues>
707
708
709 =head1 AUTHORS
710
711 =over
712
713 =item Xavier Guimard, E<lt>[email protected]<gt>
714
715 =back
716
717 =head1 COPYRIGHT AND LICENSE
718
719 See COPYING file for details.
720
721 This library is free software; you can redistribute it and/or modify
722 it under the terms of the GNU General Public License as published by
723 the Free Software Foundation; either version 2, or (at your option)
724 any later version.
725
726 This program is distributed in the hope that it will be useful,
727 but WITHOUT ANY WARRANTY; without even the implied warranty of
728 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
729 GNU General Public License for more details.
730
731 You should have received a copy of the GNU General Public License
732 along with this program. If not, see L<http://www.gnu.org/licenses/>.
733
734 =cut