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