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