3 package C4::SIP::SIPServer;
9 use Net::Server::PreFork;
11 use Socket qw(:DEFAULT :crlf);
12 use Scalar::Util qw(blessed);
13 require UNIVERSAL::require;
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);
27 tie *STDERR, "C4::SIP::Trapper";
29 use base qw(Net::Server::PreFork);
31 use constant LOG_SIP => "local6"; # Local alias for the logging facility
34 # Main # not really, since package SIPServer
36 # FIXME: Is this a module or a script?
37 # A script with no MAIN namespace?
38 # A module that takes command line args?
40 # Set interface to 'sip'
41 C4::Context->interface('sip');
44 RAW => \&raw_transport,
45 telnet => \&telnet_transport,
51 my $config = C4::SIP::Sip::Configuration->new( $ARGV[0] );
57 foreach my $svc (keys %{$config->{listeners}}) {
58 push @parms, "port=" . $svc;
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...
68 # The IDENT is determined by config file 'server-params' arguments
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
77 if (defined($config->{'server-params'})) {
78 while (my ($key, $val) = each %{$config->{'server-params'}}) {
79 push @parms, $key . '=' . $val;
85 # This is the main event.
86 __PACKAGE__ ->run(@parms);
92 # process_request is the callback used by Net::Server to handle
93 # an incoming connection request.
98 my ($sockaddr, $port, $proto);
101 $self->{config} = $config;
103 # Flushing L1 to make sure the request will be processed using the correct data
104 Koha::Caches->flush_L1_caches();
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' } ) );
109 my $sockname = getsockname(STDIN);
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);
117 ($port, $sockaddr) = sockaddr_in($sockname);
118 $sockaddr = inet_ntoa($sockaddr);
120 $proto = $self->{server}->{client}->NS_proto();
122 $self->{service} = $config->find_service($sockaddr, $port, $proto);
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";
129 $transport = $transports{$self->{service}->{transport}};
131 if (!defined($transport)) {
132 siplog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
147 my $service = $self->{service};
148 # If using Net::Server::PreFork you may already have account set from a previous session
150 if ($self->{account}) {
151 delete $self->{account};
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");
160 while (!$self->{account}) {
161 $input = read_request();
164 siplog("LOG_INFO", "raw_transport: shutting down: EOF during login");
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);
174 $self->{logger} = set_logger(
178 category => $self->{account}->{id}, # Add id to namespace
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");
191 $self->sip_protocol_loop();
192 siplog("LOG_INFO", "raw_transport: shutting down");
196 sub get_clean_string {
198 if (defined $string) {
199 siplog("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $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);
205 siplog("LOG_INFO", "get_clean_string called on undefined");
210 sub get_clean_input {
213 $in = get_clean_string($in);
214 while (my $extra = <STDIN>){
215 siplog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
220 sub telnet_transport {
226 my $config = $self->{config};
227 my $timeout = $self->get_timeout({ transport => 1 });
228 siplog("LOG_DEBUG", "telnet_transport: timeout is $timeout");
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.
240 # $uid = &get_clean_input;
243 # $pwd = &get_clean_input || '';
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));
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) ) {
259 siplog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
260 print("Invalid login$CRLF");
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");
271 print "Login OK. Initiating SIP$CRLF";
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");
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 {
288 my $service = $self->{service};
289 my $config = $self->{config};
290 my $timeout = $self->get_timeout({ client => 1 });
292 # The spec says the first message will be:
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.
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).
304 # In short, we'll take any valid message here.
306 local $SIG{ALRM} = sub {
307 siplog( 'LOG_DEBUG', 'Inactive: timed out' );
310 my $previous_alarm = alarm($timeout);
312 while ( my $inputbuf = read_request() ) {
313 if ( !defined $inputbuf ) {
319 siplog( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
324 my $status = C4::SIP::Sip::MsgType::handle( $inputbuf, $self, q{} );
328 "sip_protocol_loop: failed to handle %s",
329 substr( $inputbuf, 0, 2 )
332 next if $status eq REQUEST_ACS_RESEND;
334 alarm($previous_alarm);
337 if ( $@ =~ m/timed out/i ) {
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
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;
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;
362 # treat as one line to include the extra linebreaks we are trying to remove!
365 siplog( 'LOG_DEBUG', 'EOF returned on read' );
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) " );
374 siplog( 'LOG_INFO', "INPUT MSG: '$buffer'" );
378 # $server->get_timeout({ $type => 1, fallback => $fallback });
379 # where $type is transport | client | policy
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).
385 # Fallback is optional. If you do not pass transport, client or policy,
386 # you will get fallback or hardcoded default.
389 my ( $server, $params ) = @_;
390 my $fallback = $params->{fallback} || 30;
391 my $service = $server->{service} // {};
392 my $config = $server->{config} // {};
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;
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};
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 );