f1c1ae448b3fd6566822904e58ab0911feee0191
[srvgit] / C4 / SIP / SIPServer.pm
1 #!/usr/bin/perl
2
3 package C4::SIP::SIPServer;
4
5 use strict;
6 use warnings;
7 use FindBin qw($Bin);
8 use lib "$Bin";
9 use Net::Server::PreFork;
10 use IO::Socket::INET;
11 use Socket qw(:DEFAULT :crlf);
12 use Scalar::Util qw(blessed);
13 require UNIVERSAL::require;
14
15 use C4::Context;
16 use C4::SIP::Sip qw(siplog);
17 use C4::SIP::Sip::Constants qw(:all);
18 use C4::SIP::Sip::Configuration;
19 use C4::SIP::Sip::Checksum qw(checksum verify_cksum);
20 use C4::SIP::Sip::MsgType qw( handle login_core );
21 use C4::SIP::Logger qw(set_logger);
22
23 use Koha::Caches;
24
25 use Koha::Logger;
26 use C4::SIP::Trapper;
27 tie *STDERR, "C4::SIP::Trapper";
28
29 use base qw(Net::Server::PreFork);
30
31 use constant LOG_SIP => "local6"; # Local alias for the logging facility
32
33 #
34 # Main  # not really, since package SIPServer
35 #
36 # FIXME: Is this a module or a script?  
37 # A script with no MAIN namespace?
38 # A module that takes command line args?
39
40 # Set interface to 'sip'
41 C4::Context->interface('sip');
42
43 my %transports = (
44     RAW    => \&raw_transport,
45     telnet => \&telnet_transport,
46 );
47
48 #
49 # Read configuration
50 #
51 my $config = C4::SIP::Sip::Configuration->new( $ARGV[0] );
52 my @parms;
53
54 #
55 # Ports to bind
56 #
57 foreach my $svc (keys %{$config->{listeners}}) {
58     push @parms, "port=" . $svc;
59 }
60
61 #
62 # Logging
63 #
64 # Log lines look like this:
65 # Jun 16 21:21:31 server08 steve_sip[19305]: ILS::Transaction::Checkout performing checkout...
66 # [  TIMESTAMP  ] [ HOST ] [ IDENT ]  PID  : Message...
67 #
68 # The IDENT is determined by config file 'server-params' arguments
69
70
71 #
72 # Server Management: set parameters for the Net::Server::PreFork
73 # module.  The module silently ignores parameters that it doesn't
74 # recognize, and complains about invalid values for parameters
75 # that it does.
76 #
77 if (defined($config->{'server-params'})) {
78     while (my ($key, $val) = each %{$config->{'server-params'}}) {
79         push @parms, $key . '=' . $val;
80     }
81 }
82
83
84 #
85 # This is the main event.
86 __PACKAGE__ ->run(@parms);
87
88 #
89 # Child
90 #
91
92 # process_request is the callback used by Net::Server to handle
93 # an incoming connection request.
94
95 sub process_request {
96     my $self = shift;
97     my $service;
98     my ($sockaddr, $port, $proto);
99     my $transport;
100
101     $self->{config} = $config;
102
103     # Flushing L1 to make sure the request will be processed using the correct data
104     Koha::Caches->flush_L1_caches();
105
106     $self->{account} = undef;  # Clear out the account from the last request, it may be different
107     $self->{logger} = set_logger( Koha::Logger->get( { interface => 'sip' } ) );
108
109     my $sockname = getsockname(STDIN);
110
111     # Check if socket connection is IPv6 before resolving address
112     my $family = Socket::sockaddr_family($sockname);
113     if ($family == AF_INET6) {
114       ($port, $sockaddr) = sockaddr_in6($sockname);
115       $sockaddr = Socket::inet_ntop(AF_INET6, $sockaddr);
116     } else {
117       ($port, $sockaddr) = sockaddr_in($sockname);
118       $sockaddr = inet_ntoa($sockaddr);
119     }
120     $proto = $self->{server}->{client}->NS_proto();
121
122     $self->{service} = $config->find_service($sockaddr, $port, $proto);
123
124     if (!defined($self->{service})) {
125         siplog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
126         die "process_request: Bad server connection";
127     }
128
129     $transport = $transports{$self->{service}->{transport}};
130
131     if (!defined($transport)) {
132         siplog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
133         return;
134     } else {
135         &$transport($self);
136     }
137     return;
138 }
139
140 #
141 # Transports
142 #
143
144 sub raw_transport {
145     my $self = shift;
146     my $input;
147     my $service = $self->{service};
148     # If using Net::Server::PreFork you may already have account set from a previous session
149     # Ensure you dont
150     if ($self->{account}) {
151         delete $self->{account};
152     }
153
154     # Timeout the while loop if we get stuck in it
155     # In practice it should only iterate once but be prepared
156     local $SIG{ALRM} = sub { die 'raw transport Timed Out!' };
157     my $timeout = $self->get_timeout({ transport => 1 });
158     siplog('LOG_DEBUG', "raw_transport: timeout is $timeout");
159     alarm $timeout;
160     while (!$self->{account}) {
161         $input = read_request();
162         if (!$input) {
163             # EOF on the socket
164             siplog("LOG_INFO", "raw_transport: shutting down: EOF during login");
165             return;
166         }
167         $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s)
168         my $reg = qr/^${\(LOGIN)}/;
169         last if $input !~ $reg ||
170             C4::SIP::Sip::MsgType::handle($input, $self, LOGIN);
171     }
172     alarm 0;
173
174     $self->{logger} = set_logger(
175         Koha::Logger->get(
176             {
177                 interface => 'sip',
178                 category  => $self->{account}->{id}, # Add id to namespace
179             }
180         )
181     );
182
183     siplog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
184         $self->{account}->{id},
185         $self->{account}->{institution});
186     if (! $self->{account}->{id}) {
187         siplog("LOG_ERR","Login failed shutting down");
188         return;
189     }
190
191     $self->sip_protocol_loop();
192     siplog("LOG_INFO", "raw_transport: shutting down");
193     return;
194 }
195
196 sub get_clean_string {
197     my $string = shift;
198     if (defined $string) {
199         siplog("LOG_DEBUG", "get_clean_string  pre-clean(length %s): %s", length($string), $string);
200         chomp($string);
201         $string =~ s/^[^A-z0-9]+//;
202         $string =~ s/[^A-z0-9]+$//;
203         siplog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
204     } else {
205         siplog("LOG_INFO", "get_clean_string called on undefined");
206     }
207     return $string;
208 }
209
210 sub get_clean_input {
211     local $/ = "\012";
212     my $in = <STDIN>;
213     $in = get_clean_string($in);
214     while (my $extra = <STDIN>){
215         siplog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
216     }
217     return $in;
218 }
219
220 sub telnet_transport {
221     my $self = shift;
222     my ($uid, $pwd);
223     my $strikes = 3;
224     my $account = undef;
225     my $input;
226     my $config  = $self->{config};
227     my $timeout = $self->get_timeout({ transport => 1 });
228     siplog("LOG_DEBUG", "telnet_transport: timeout is $timeout");
229
230     eval {
231     local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
232     local $| = 1;           # Unbuffered output
233     $/ = "\015";        # Internet Record Separator (lax version)
234     # Until the terminal has logged in, we don't trust it
235     # so use a timeout to protect ourselves from hanging.
236
237     while ($strikes--) {
238         print "login: ";
239         alarm $timeout;
240         # $uid = &get_clean_input;
241         $uid = <STDIN>;
242         print "password: ";
243         # $pwd = &get_clean_input || '';
244         $pwd = <STDIN>;
245         alarm 0;
246
247         siplog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
248         $uid = get_clean_string ($uid);
249         $pwd = get_clean_string ($pwd);
250         siplog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
251
252         if (exists ($config->{accounts}->{$uid})
253         && ($pwd eq $config->{accounts}->{$uid}->{password})) {
254             $account = $config->{accounts}->{$uid};
255             if ( C4::SIP::Sip::MsgType::login_core($self,$uid,$pwd) ) {
256                 last;
257             }
258         }
259         siplog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
260         print("Invalid login$CRLF");
261     }
262     }; # End of eval
263
264     if ($@) {
265         siplog("LOG_ERR", "telnet_transport: Login timed out");
266         die "Telnet Login Timed out";
267     } elsif (!defined($account)) {
268         siplog("LOG_ERR", "telnet_transport: Login Failed");
269         die "Login Failure";
270     } else {
271         print "Login OK.  Initiating SIP$CRLF";
272     }
273
274     $self->{account} = $account;
275     siplog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
276     $self->sip_protocol_loop();
277     siplog("LOG_INFO", "telnet_transport: shutting down");
278     return;
279 }
280
281 #
282 # The terminal has logged in, using either the SIP login process
283 # over a raw socket, or via the pseudo-unix login provided by the
284 # telnet transport.  From that point on, both the raw and the telnet
285 # processes are the same:
286 sub sip_protocol_loop {
287     my $self = shift;
288     my $service = $self->{service};
289     my $config  = $self->{config};
290     my $timeout = $self->get_timeout({ client => 1 });
291
292     # The spec says the first message will be:
293     #     SIP v1: SC_STATUS
294     #     SIP v2: LOGIN (or SC_STATUS via telnet?)
295     # But it might be SC_REQUEST_RESEND.  As long as we get
296     # SC_REQUEST_RESEND, we keep waiting.
297
298     # Comprise reports that no other ILS actually enforces this
299     # constraint, so we'll relax about it too.
300     # Using the SIP "raw" login process, rather than telnet,
301     # requires the LOGIN message and forces SIP 2.00.  In that
302     # case, the LOGIN message has already been processed (above).
303
304     # In short, we'll take any valid message here.
305     eval {
306         local $SIG{ALRM} = sub {
307             siplog( 'LOG_DEBUG', 'Inactive: timed out' );
308             die "Timed Out!\n";
309         };
310         my $previous_alarm = alarm($timeout);
311
312         while ( my $inputbuf = read_request() ) {
313             if ( !defined $inputbuf ) {
314                 return;    #EOF
315             }
316             alarm($timeout);
317
318             unless ($inputbuf) {
319                 siplog( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
320                 print("96$CR");
321                 next;
322             }
323
324             my $status = C4::SIP::Sip::MsgType::handle( $inputbuf, $self, q{} );
325             if ( !$status ) {
326                 siplog(
327                     "LOG_ERR",
328                     "sip_protocol_loop: failed to handle %s",
329                     substr( $inputbuf, 0, 2 )
330                 );
331             }
332             next if $status eq REQUEST_ACS_RESEND;
333         }
334         alarm($previous_alarm);
335         return;
336     };
337     if ( $@ =~ m/timed out/i ) {
338         return;
339     }
340     return;
341 }
342
343 sub read_request {
344       my $raw_length;
345       local $/ = "\015";
346
347     # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
348       my $buffer = <STDIN>;
349       if ( defined $buffer ) {
350           STDIN->flush();    # clear an extra linefeed
351           chomp $buffer;
352           $raw_length = length $buffer;
353           $buffer =~ s/^\s*[^A-z0-9]+//s;
354 # Every line must start with a "real" character.  Not whitespace, control chars, etc.
355           $buffer =~ s/[^A-z0-9]+$//s;
356
357 # Same for the end.  Note this catches the problem some clients have sending empty fields at the end, like |||
358           $buffer =~ s/\015?\012//g;    # Extra line breaks must die
359           $buffer =~ s/\015?\012//s;    # Extra line breaks must die
360           $buffer =~ s/\015*\012*$//s;
361
362     # treat as one line to include the extra linebreaks we are trying to remove!
363       }
364       else {
365           siplog( 'LOG_DEBUG', 'EOF returned on read' );
366           return;
367       }
368       my $len = length $buffer;
369       if ( $len != $raw_length ) {
370           my $trim = $raw_length - $len;
371           siplog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " );
372       }
373
374       siplog( 'LOG_INFO', "INPUT MSG: '$buffer'" );
375       return $buffer;
376 }
377
378 # $server->get_timeout({ $type => 1, fallback => $fallback });
379 #     where $type is transport | client | policy
380 #
381 # Centralizes all timeout logic.
382 # Transport refers to login process, client to active connections.
383 # Policy timeout is transaction timeout (used in ACS status message).
384 #
385 # Fallback is optional. If you do not pass transport, client or policy,
386 # you will get fallback or hardcoded default.
387
388 sub get_timeout {
389     my ( $server, $params ) = @_;
390     my $fallback = $params->{fallback} || 30;
391     my $service = $server->{service} // {};
392     my $config = $server->{config} // {};
393
394     if( $params->{transport} ||
395         ( $params->{client} && !exists $service->{client_timeout} )) {
396         # We do not allow zero values here.
397         # Note: config/timeout seems to be deprecated.
398         return $service->{timeout} || $config->{timeout} || $fallback;
399
400     } elsif( $params->{client} ) {
401         # We know that client_timeout exists now.
402         # We do allow zero values here to indicate no timeout.
403         return 0 if $service->{client_timeout} =~ /^0+$|\D/;
404         return $service->{client_timeout};
405
406     } elsif( $params->{policy} ) {
407         my $policy = $server->{policy} // {};
408         my $rv = sprintf( "%03d", $policy->{timeout} // 0 );
409         if( length($rv) != 3 ) {
410             siplog( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv );
411             return '000';
412         }
413         return $rv;
414
415     } else {
416         return $fallback;
417     }
418 }
419
420 1;
421
422 __END__