1 package C4::SIP::SIPServer;
7 use Net::Server::PreFork;
9 use Socket qw(:DEFAULT :crlf);
10 use Scalar::Util qw(blessed);
11 require UNIVERSAL::require;
14 use C4::SIP::Sip qw(siplog);
15 use C4::SIP::Sip::Constants qw(:all);
16 use C4::SIP::Sip::Configuration;
17 use C4::SIP::Sip::Checksum qw(checksum verify_cksum);
18 use C4::SIP::Sip::MsgType qw( handle login_core );
19 use C4::SIP::Logger qw(set_logger);
25 tie *STDERR, "C4::SIP::Trapper";
27 use base qw(Net::Server::PreFork);
29 use constant LOG_SIP => "local6"; # Local alias for the logging facility
32 # Main # not really, since package SIPServer
34 # FIXME: Is this a module or a script?
35 # A script with no MAIN namespace?
36 # A module that takes command line args?
38 # Set interface to 'sip'
39 C4::Context->interface('sip');
42 RAW => \&raw_transport,
43 telnet => \&telnet_transport,
49 my $config = C4::SIP::Sip::Configuration->new( $ARGV[0] );
55 foreach my $svc (keys %{$config->{listeners}}) {
56 push @parms, "port=" . $svc;
62 # Log lines look like this:
63 # Jun 16 21:21:31 server08 steve_sip[19305]: ILS::Transaction::Checkout performing checkout...
64 # [ TIMESTAMP ] [ HOST ] [ IDENT ] PID : Message...
66 # The IDENT is determined by config file 'server-params' arguments
70 # Server Management: set parameters for the Net::Server::PreFork
71 # module. The module silently ignores parameters that it doesn't
72 # recognize, and complains about invalid values for parameters
75 if (defined($config->{'server-params'})) {
76 while (my ($key, $val) = each %{$config->{'server-params'}}) {
77 push @parms, $key . '=' . $val;
83 # This is the main event.
84 __PACKAGE__ ->run(@parms);
90 # process_request is the callback used by Net::Server to handle
91 # an incoming connection request.
96 my ($sockaddr, $port, $proto);
99 $self->{config} = $config;
101 # Flushing L1 to make sure the request will be processed using the correct data
102 Koha::Caches->flush_L1_caches();
104 $self->{account} = undef; # Clear out the account from the last request, it may be different
105 $self->{logger} = set_logger( Koha::Logger->get( { interface => 'sip' } ) );
107 my $sockname = getsockname(STDIN);
109 # Check if socket connection is IPv6 before resolving address
110 my $family = Socket::sockaddr_family($sockname);
111 if ($family == AF_INET6) {
112 ($port, $sockaddr) = sockaddr_in6($sockname);
113 $sockaddr = Socket::inet_ntop(AF_INET6, $sockaddr);
115 ($port, $sockaddr) = sockaddr_in($sockname);
116 $sockaddr = inet_ntoa($sockaddr);
118 $proto = $self->{server}->{client}->NS_proto();
120 $self->{service} = $config->find_service($sockaddr, $port, $proto);
122 if (!defined($self->{service})) {
123 siplog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
124 die "process_request: Bad server connection";
127 $transport = $transports{$self->{service}->{transport}};
129 if (!defined($transport)) {
130 siplog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
145 my $service = $self->{service};
146 # If using Net::Server::PreFork you may already have account set from a previous session
148 if ($self->{account}) {
149 delete $self->{account};
152 # Timeout the while loop if we get stuck in it
153 # In practice it should only iterate once but be prepared
154 local $SIG{ALRM} = sub { die 'raw transport Timed Out!' };
155 my $timeout = $self->get_timeout({ transport => 1 });
156 siplog('LOG_DEBUG', "raw_transport: timeout is $timeout");
158 while (!$self->{account}) {
159 $input = read_request();
162 siplog("LOG_INFO", "raw_transport: shutting down: EOF during login");
165 $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s)
166 my $reg = qr/^${\(LOGIN)}/;
167 last if $input !~ $reg ||
168 C4::SIP::Sip::MsgType::handle($input, $self, LOGIN);
172 $self->{logger} = set_logger(
176 category => $self->{account}->{id}, # Add id to namespace
181 siplog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
182 $self->{account}->{id},
183 $self->{account}->{institution});
184 if (! $self->{account}->{id}) {
185 siplog("LOG_ERR","Login failed shutting down");
189 $self->sip_protocol_loop();
190 siplog("LOG_INFO", "raw_transport: shutting down");
194 sub get_clean_string {
196 if (defined $string) {
197 siplog("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string);
199 $string =~ s/^[^A-z0-9]+//;
200 $string =~ s/[^A-z0-9]+$//;
201 siplog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
203 siplog("LOG_INFO", "get_clean_string called on undefined");
208 sub get_clean_input {
211 $in = get_clean_string($in);
212 while (my $extra = <STDIN>){
213 siplog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
218 sub telnet_transport {
224 my $config = $self->{config};
225 my $timeout = $self->get_timeout({ transport => 1 });
226 siplog("LOG_DEBUG", "telnet_transport: timeout is $timeout");
229 local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
230 local $| = 1; # Unbuffered output
231 $/ = "\015"; # Internet Record Separator (lax version)
232 # Until the terminal has logged in, we don't trust it
233 # so use a timeout to protect ourselves from hanging.
238 # $uid = &get_clean_input;
241 # $pwd = &get_clean_input || '';
245 siplog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
246 $uid = get_clean_string ($uid);
247 $pwd = get_clean_string ($pwd);
248 siplog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
250 if (exists ($config->{accounts}->{$uid})
251 && ($pwd eq $config->{accounts}->{$uid}->{password})) {
252 $account = $config->{accounts}->{$uid};
253 if ( C4::SIP::Sip::MsgType::login_core($self,$uid,$pwd) ) {
257 siplog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
258 print("Invalid login$CRLF");
263 siplog("LOG_ERR", "telnet_transport: Login timed out");
264 die "Telnet Login Timed out";
265 } elsif (!defined($account)) {
266 siplog("LOG_ERR", "telnet_transport: Login Failed");
269 print "Login OK. Initiating SIP$CRLF";
272 $self->{account} = $account;
273 siplog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
274 $self->sip_protocol_loop();
275 siplog("LOG_INFO", "telnet_transport: shutting down");
280 # The terminal has logged in, using either the SIP login process
281 # over a raw socket, or via the pseudo-unix login provided by the
282 # telnet transport. From that point on, both the raw and the telnet
283 # processes are the same:
284 sub sip_protocol_loop {
286 my $service = $self->{service};
287 my $config = $self->{config};
288 my $timeout = $self->get_timeout({ client => 1 });
290 # The spec says the first message will be:
292 # SIP v2: LOGIN (or SC_STATUS via telnet?)
293 # But it might be SC_REQUEST_RESEND. As long as we get
294 # SC_REQUEST_RESEND, we keep waiting.
296 # Comprise reports that no other ILS actually enforces this
297 # constraint, so we'll relax about it too.
298 # Using the SIP "raw" login process, rather than telnet,
299 # requires the LOGIN message and forces SIP 2.00. In that
300 # case, the LOGIN message has already been processed (above).
302 # In short, we'll take any valid message here.
304 local $SIG{ALRM} = sub {
305 siplog( 'LOG_DEBUG', 'Inactive: timed out' );
308 my $previous_alarm = alarm($timeout);
310 while ( my $inputbuf = read_request() ) {
311 if ( !defined $inputbuf ) {
317 siplog( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
322 my $status = C4::SIP::Sip::MsgType::handle( $inputbuf, $self, q{} );
326 "sip_protocol_loop: failed to handle %s",
327 substr( $inputbuf, 0, 2 )
330 next if $status eq REQUEST_ACS_RESEND;
332 alarm($previous_alarm);
335 if ( $@ =~ m/timed out/i ) {
345 # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
346 my $buffer = <STDIN>;
347 if ( defined $buffer ) {
348 STDIN->flush(); # clear an extra linefeed
350 $raw_length = length $buffer;
351 $buffer =~ s/^\s*[^A-z0-9]+//s;
352 # Every line must start with a "real" character. Not whitespace, control chars, etc.
353 $buffer =~ s/[^A-z0-9]+$//s;
355 # Same for the end. Note this catches the problem some clients have sending empty fields at the end, like |||
356 $buffer =~ s/\015?\012//g; # Extra line breaks must die
357 $buffer =~ s/\015?\012//s; # Extra line breaks must die
358 $buffer =~ s/\015*\012*$//s;
360 # treat as one line to include the extra linebreaks we are trying to remove!
363 siplog( 'LOG_DEBUG', 'EOF returned on read' );
366 my $len = length $buffer;
367 if ( $len != $raw_length ) {
368 my $trim = $raw_length - $len;
369 siplog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " );
372 siplog( 'LOG_INFO', "INPUT MSG: '$buffer'" );
376 # $server->get_timeout({ $type => 1, fallback => $fallback });
377 # where $type is transport | client | policy
379 # Centralizes all timeout logic.
380 # Transport refers to login process, client to active connections.
381 # Policy timeout is transaction timeout (used in ACS status message).
383 # Fallback is optional. If you do not pass transport, client or policy,
384 # you will get fallback or hardcoded default.
387 my ( $server, $params ) = @_;
388 my $fallback = $params->{fallback} || 30;
389 my $service = $server->{service} // {};
390 my $config = $server->{config} // {};
392 if( $params->{transport} ||
393 ( $params->{client} && !exists $service->{client_timeout} )) {
394 # We do not allow zero values here.
395 # Note: config/timeout seems to be deprecated.
396 return $service->{timeout} || $config->{timeout} || $fallback;
398 } elsif( $params->{client} ) {
399 # We know that client_timeout exists now.
400 # We do allow zero values here to indicate no timeout.
401 return 0 if $service->{client_timeout} =~ /^0+$|\D/;
402 return $service->{client_timeout};
404 } elsif( $params->{policy} ) {
405 my $policy = $server->{policy} // {};
406 my $rv = sprintf( "%03d", $policy->{timeout} // 0 );
407 if( length($rv) != 3 ) {
408 siplog( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv );