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