2 package C4::SIP::SIPServer;
8 use Net::Server::PreFork;
10 use Socket qw(:DEFAULT :crlf);
11 use Scalar::Util qw(blessed);
12 require UNIVERSAL::require;
15 use C4::SIP::Sip qw(syslog);
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 );
24 tie *STDERR, "C4::SIP::Trapper";
26 use base qw(Net::Server::PreFork);
28 use constant LOG_SIP => "local6"; # Local alias for the logging facility
31 # Main # not really, since package SIPServer
33 # FIXME: Is this a module or a script?
34 # A script with no MAIN namespace?
35 # A module that takes command line args?
37 # Set interface to 'sip'
38 C4::Context->interface('sip');
41 RAW => \&raw_transport,
42 telnet => \&telnet_transport,
48 my $config = C4::SIP::Sip::Configuration->new( $ARGV[0] );
54 foreach my $svc (keys %{$config->{listeners}}) {
55 push @parms, "port=" . $svc;
61 # Log lines look like this:
62 # Jun 16 21:21:31 server08 steve_sip[19305]: ILS::Transaction::Checkout performing checkout...
63 # [ TIMESTAMP ] [ HOST ] [ IDENT ] PID : Message...
65 # The IDENT is determined by config file 'server-params' arguments
69 # Server Management: set parameters for the Net::Server::PreFork
70 # module. The module silently ignores parameters that it doesn't
71 # recognize, and complains about invalid values for parameters
74 if (defined($config->{'server-params'})) {
75 while (my ($key, $val) = each %{$config->{'server-params'}}) {
76 push @parms, $key . '=' . $val;
82 # This is the main event.
83 __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 # Flush previous MDCs to prevent accidentally leaking incorrect MDC-entries
110 Log::Log4perl::MDC->put( "accountid", undef );
111 Log::Log4perl::MDC->put( "peeraddr", undef );
113 my $sockname = getsockname(STDIN);
115 # Check if socket connection is IPv6 before resolving address
116 my $family = Socket::sockaddr_family($sockname);
117 if ($family == AF_INET6) {
118 ($port, $sockaddr) = sockaddr_in6($sockname);
119 $sockaddr = Socket::inet_ntop(AF_INET6, $sockaddr);
121 ($port, $sockaddr) = sockaddr_in($sockname);
122 $sockaddr = inet_ntoa($sockaddr);
124 $proto = $self->{server}->{client}->NS_proto();
126 $self->{service} = $config->find_service($sockaddr, $port, $proto);
128 if (!defined($self->{service})) {
129 syslog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
130 die "process_request: Bad server connection";
133 $transport = $transports{$self->{service}->{transport}};
135 if (!defined($transport)) {
136 syslog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
151 my $service = $self->{service};
152 # If using Net::Server::PreFork you may already have account set from a previous session
154 if ($self->{account}) {
155 delete $self->{account};
158 # Timeout the while loop if we get stuck in it
159 # In practice it should only iterate once but be prepared
160 local $SIG{ALRM} = sub { die 'raw transport Timed Out!' };
161 my $timeout = $self->get_timeout({ transport => 1 });
162 syslog('LOG_DEBUG', "raw_transport: timeout is $timeout");
164 while (!$self->{account}) {
165 $input = read_request();
168 syslog("LOG_INFO", "raw_transport: shutting down: EOF during login");
171 $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s)
172 my $reg = qr/^${\(LOGIN)}/;
173 last if $input !~ $reg ||
174 C4::SIP::Sip::MsgType::handle($input, $self, LOGIN);
178 $self->{logger} = _set_logger(
182 category => $self->{account}->{id}, # Add id to namespace
187 # Set MDCs after properly authenticating
188 Log::Log4perl::MDC->put( "accountid", $self->{account}->{id} );
189 Log::Log4perl::MDC->put( "peeraddr", $self->{server}->{peeraddr} );
191 syslog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
192 $self->{account}->{id},
193 $self->{account}->{institution});
194 if (! $self->{account}->{id}) {
195 syslog("LOG_ERR","Login failed shutting down");
199 $self->sip_protocol_loop();
200 syslog("LOG_INFO", "raw_transport: shutting down");
204 sub get_clean_string {
206 if (defined $string) {
207 syslog("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string);
209 $string =~ s/^[^A-z0-9]+//;
210 $string =~ s/[^A-z0-9]+$//;
211 syslog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
213 syslog("LOG_INFO", "get_clean_string called on undefined");
218 sub get_clean_input {
221 $in = get_clean_string($in);
222 while (my $extra = <STDIN>){
223 syslog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
228 sub telnet_transport {
234 my $config = $self->{config};
235 my $timeout = $self->get_timeout({ transport => 1 });
236 syslog("LOG_DEBUG", "telnet_transport: timeout is $timeout");
239 local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
240 local $| = 1; # Unbuffered output
241 $/ = "\015"; # Internet Record Separator (lax version)
242 # Until the terminal has logged in, we don't trust it
243 # so use a timeout to protect ourselves from hanging.
248 # $uid = &get_clean_input;
251 # $pwd = &get_clean_input || '';
255 syslog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
256 $uid = get_clean_string ($uid);
257 $pwd = get_clean_string ($pwd);
258 syslog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
260 if (exists ($config->{accounts}->{$uid})
261 && ($pwd eq $config->{accounts}->{$uid}->{password})) {
262 $account = $config->{accounts}->{$uid};
263 if ( C4::SIP::Sip::MsgType::login_core($self,$uid,$pwd) ) {
267 syslog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
268 print("Invalid login$CRLF");
273 syslog("LOG_ERR", "telnet_transport: Login timed out");
274 die "Telnet Login Timed out";
275 } elsif (!defined($account)) {
276 syslog("LOG_ERR", "telnet_transport: Login Failed");
279 print "Login OK. Initiating SIP$CRLF";
282 $self->{account} = $account;
283 syslog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
284 $self->sip_protocol_loop();
285 syslog("LOG_INFO", "telnet_transport: shutting down");
290 # The terminal has logged in, using either the SIP login process
291 # over a raw socket, or via the pseudo-unix login provided by the
292 # telnet transport. From that point on, both the raw and the telnet
293 # processes are the same:
294 sub sip_protocol_loop {
296 my $service = $self->{service};
297 my $config = $self->{config};
298 my $timeout = $self->get_timeout({ client => 1 });
300 # The spec says the first message will be:
302 # SIP v2: LOGIN (or SC_STATUS via telnet?)
303 # But it might be SC_REQUEST_RESEND. As long as we get
304 # SC_REQUEST_RESEND, we keep waiting.
306 # Comprise reports that no other ILS actually enforces this
307 # constraint, so we'll relax about it too.
308 # Using the SIP "raw" login process, rather than telnet,
309 # requires the LOGIN message and forces SIP 2.00. In that
310 # case, the LOGIN message has already been processed (above).
312 # In short, we'll take any valid message here.
314 local $SIG{ALRM} = sub {
315 syslog( 'LOG_DEBUG', 'Inactive: timed out' );
318 my $previous_alarm = alarm($timeout);
320 while ( my $inputbuf = read_request() ) {
321 if ( !defined $inputbuf ) {
327 syslog( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
332 my $status = C4::SIP::Sip::MsgType::handle( $inputbuf, $self, q{} );
336 "sip_protocol_loop: failed to handle %s",
337 substr( $inputbuf, 0, 2 )
340 next if $status eq REQUEST_ACS_RESEND;
342 alarm($previous_alarm);
345 if ( $@ =~ m/timed out/i ) {
355 # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
356 my $buffer = <STDIN>;
357 if ( defined $buffer ) {
358 STDIN->flush(); # clear an extra linefeed
360 $raw_length = length $buffer;
361 $buffer =~ s/^\s*[^A-z0-9]+//s;
362 # Every line must start with a "real" character. Not whitespace, control chars, etc.
363 $buffer =~ s/[^A-z0-9]+$//s;
365 # Same for the end. Note this catches the problem some clients have sending empty fields at the end, like |||
366 $buffer =~ s/\015?\012//g; # Extra line breaks must die
367 $buffer =~ s/\015?\012//s; # Extra line breaks must die
368 $buffer =~ s/\015*\012*$//s;
370 # treat as one line to include the extra linebreaks we are trying to remove!
373 syslog( 'LOG_DEBUG', 'EOF returned on read' );
376 my $len = length $buffer;
377 if ( $len != $raw_length ) {
378 my $trim = $raw_length - $len;
379 syslog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " );
382 syslog( 'LOG_INFO', "INPUT MSG: '$buffer'" );
386 # $server->get_timeout({ $type => 1, fallback => $fallback });
387 # where $type is transport | client | policy
389 # Centralizes all timeout logic.
390 # Transport refers to login process, client to active connections.
391 # Policy timeout is transaction timeout (used in ACS status message).
393 # Fallback is optional. If you do not pass transport, client or policy,
394 # you will get fallback or hardcoded default.
397 my ( $server, $params ) = @_;
398 my $fallback = $params->{fallback} || 30;
399 my $service = $server->{service} // {};
400 my $config = $server->{config} // {};
402 if( $params->{transport} ||
403 ( $params->{client} && !exists $service->{client_timeout} )) {
404 # We do not allow zero values here.
405 # Note: config/timeout seems to be deprecated.
406 return $service->{timeout} || $config->{timeout} || $fallback;
408 } elsif( $params->{client} ) {
409 # We know that client_timeout exists now.
410 # We do allow zero values here to indicate no timeout.
411 return 0 if $service->{client_timeout} =~ /^0+$|\D/;
412 return $service->{client_timeout};
414 } elsif( $params->{policy} ) {
415 my $policy = $server->{policy} // {};
416 my $rv = sprintf( "%03d", $policy->{timeout} // 0 );
417 if( length($rv) != 3 ) {
418 syslog( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv );
430 my $sipServer = C4::SIP::SIPServer::get_SIPServer()
432 @RETURNS C4::SIP::SIPServer, the current server's child-process used to handle this SIP-transaction
437 unless($activeSIPServer) {
439 die "$cc[3]() asks for \$activeSIPServer, but he is not defined yet";
441 return $activeSIPServer;
445 my ($sipServer) = @_;
446 unless (blessed($sipServer) && $sipServer->isa('C4::SIP::SIPServer')) {
448 die "$cc[3]():> \$sipServer '$sipServer' is not a C4::SIP::SIPServer-object";
450 $activeSIPServer = $sipServer;
451 return $activeSIPServer;
456 my $logger = C4::SIP::SIPServer::get_logger()
458 @RETURNS Koha::Logger, the logger used to log this SIP-transaction
463 unless($activeLogger) {
465 die "$cc[3]() asks for \$activeLogger, but he is not defined yet";
467 return $activeLogger;
472 unless (blessed($logger) && $logger->isa('Koha::Logger')) {
474 die "$cc[3]():> \$logger '$logger' is not a Koha::Logger-object";
476 $activeLogger = $logger;
477 return $activeLogger;