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 );
23 tie *STDERR, "C4::SIP::Trapper";
25 use base qw(Net::Server::PreFork);
27 use constant LOG_SIP => "local6"; # Local alias for the logging facility
30 # Main # not really, since package SIPServer
32 # FIXME: Is this a module or a script?
33 # A script with no MAIN namespace?
34 # A module that takes command line args?
42 # Set interface to 'sip'
43 C4::Context->interface('sip');
46 RAW => \&raw_transport,
47 telnet => \&telnet_transport,
53 my $config = C4::SIP::Sip::Configuration->new( $ARGV[0] );
59 foreach my $svc (keys %{$config->{listeners}}) {
60 push @parms, "port=" . $svc;
66 # Log lines look like this:
67 # Jun 16 21:21:31 server08 steve_sip[19305]: ILS::Transaction::Checkout performing checkout...
68 # [ TIMESTAMP ] [ HOST ] [ IDENT ] PID : Message...
70 # The IDENT is determined by config file 'server-params' arguments
74 # Server Management: set parameters for the Net::Server::PreFork
75 # module. The module silently ignores parameters that it doesn't
76 # recognize, and complains about invalid values for parameters
79 if (defined($config->{'server-params'})) {
80 while (my ($key, $val) = each %{$config->{'server-params'}}) {
81 push @parms, $key . '=' . $val;
87 # This is the main event.
88 __PACKAGE__ ->run(@parms);
97 # process_request is the callback used by Net::Server to handle
98 # an incoming connection request.
100 sub process_request {
103 my ($sockaddr, $port, $proto);
106 $self->{config} = $config;
108 $self->{account} = undef; # Clear out the account from the last request, it may be different
109 $self->{logger} = _set_logger( Koha::Logger->get( { interface => 'sip' } ) );
111 # Flush previous MDCs to prevent accidentally leaking incorrect MDC-entries
112 Log::Log4perl::MDC->put( "accountid", undef );
113 Log::Log4perl::MDC->put( "peeraddr", undef );
115 my $sockname = getsockname(STDIN);
117 # Check if socket connection is IPv6 before resolving address
118 my $family = Socket::sockaddr_family($sockname);
119 if ($family == AF_INET6) {
120 ($port, $sockaddr) = sockaddr_in6($sockname);
121 $sockaddr = Socket::inet_ntop(AF_INET6, $sockaddr);
123 ($port, $sockaddr) = sockaddr_in($sockname);
124 $sockaddr = inet_ntoa($sockaddr);
126 $proto = $self->{server}->{client}->NS_proto();
128 $self->{service} = $config->find_service($sockaddr, $port, $proto);
130 if (!defined($self->{service})) {
131 syslog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
132 die "process_request: Bad server connection";
135 $transport = $transports{$self->{service}->{transport}};
137 if (!defined($transport)) {
138 syslog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
153 my $service = $self->{service};
154 # If using Net::Server::PreFork you may already have account set from a previous session
156 if ($self->{account}) {
157 delete $self->{account};
160 # Timeout the while loop if we get stuck in it
161 # In practice it should only iterate once but be prepared
162 local $SIG{ALRM} = sub { die 'raw transport Timed Out!' };
163 my $timeout = $self->get_timeout({ transport => 1 });
164 syslog('LOG_DEBUG', "raw_transport: timeout is $timeout");
166 while (!$self->{account}) {
167 $input = read_request();
170 syslog("LOG_INFO", "raw_transport: shutting down: EOF during login");
173 $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s)
174 my $reg = qr/^${\(LOGIN)}/;
175 last if $input !~ $reg ||
176 C4::SIP::Sip::MsgType::handle($input, $self, LOGIN);
180 $self->{logger} = _set_logger(
184 category => $self->{account}->{id}, # Add id to namespace
189 # Set MDCs after properly authenticating
190 Log::Log4perl::MDC->put( "accountid", $self->{account}->{id} );
191 Log::Log4perl::MDC->put( "peeraddr", $self->{server}->{peeraddr} );
193 syslog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
194 $self->{account}->{id},
195 $self->{account}->{institution});
196 if (! $self->{account}->{id}) {
197 syslog("LOG_ERR","Login failed shutting down");
201 $self->sip_protocol_loop();
202 syslog("LOG_INFO", "raw_transport: shutting down");
206 sub get_clean_string {
208 if (defined $string) {
209 syslog("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string);
211 $string =~ s/^[^A-z0-9]+//;
212 $string =~ s/[^A-z0-9]+$//;
213 syslog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
215 syslog("LOG_INFO", "get_clean_string called on undefined");
220 sub get_clean_input {
223 $in = get_clean_string($in);
224 while (my $extra = <STDIN>){
225 syslog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
230 sub telnet_transport {
236 my $config = $self->{config};
237 my $timeout = $self->get_timeout({ transport => 1 });
238 syslog("LOG_DEBUG", "telnet_transport: timeout is $timeout");
241 local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
242 local $| = 1; # Unbuffered output
243 $/ = "\015"; # Internet Record Separator (lax version)
244 # Until the terminal has logged in, we don't trust it
245 # so use a timeout to protect ourselves from hanging.
250 # $uid = &get_clean_input;
253 # $pwd = &get_clean_input || '';
257 syslog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
258 $uid = get_clean_string ($uid);
259 $pwd = get_clean_string ($pwd);
260 syslog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
262 if (exists ($config->{accounts}->{$uid})
263 && ($pwd eq $config->{accounts}->{$uid}->{password})) {
264 $account = $config->{accounts}->{$uid};
265 if ( C4::SIP::Sip::MsgType::login_core($self,$uid,$pwd) ) {
269 syslog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
270 print("Invalid login$CRLF");
275 syslog("LOG_ERR", "telnet_transport: Login timed out");
276 die "Telnet Login Timed out";
277 } elsif (!defined($account)) {
278 syslog("LOG_ERR", "telnet_transport: Login Failed");
281 print "Login OK. Initiating SIP$CRLF";
284 $self->{account} = $account;
285 syslog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
286 $self->sip_protocol_loop();
287 syslog("LOG_INFO", "telnet_transport: shutting down");
292 # The terminal has logged in, using either the SIP login process
293 # over a raw socket, or via the pseudo-unix login provided by the
294 # telnet transport. From that point on, both the raw and the telnet
295 # processes are the same:
296 sub sip_protocol_loop {
298 my $service = $self->{service};
299 my $config = $self->{config};
300 my $timeout = $self->get_timeout({ client => 1 });
302 # The spec says the first message will be:
304 # SIP v2: LOGIN (or SC_STATUS via telnet?)
305 # But it might be SC_REQUEST_RESEND. As long as we get
306 # SC_REQUEST_RESEND, we keep waiting.
308 # Comprise reports that no other ILS actually enforces this
309 # constraint, so we'll relax about it too.
310 # Using the SIP "raw" login process, rather than telnet,
311 # requires the LOGIN message and forces SIP 2.00. In that
312 # case, the LOGIN message has already been processed (above).
314 # In short, we'll take any valid message here.
316 local $SIG{ALRM} = sub {
317 syslog( 'LOG_DEBUG', 'Inactive: timed out' );
320 my $previous_alarm = alarm($timeout);
322 while ( my $inputbuf = read_request() ) {
323 if ( !defined $inputbuf ) {
329 syslog( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
334 my $status = C4::SIP::Sip::MsgType::handle( $inputbuf, $self, q{} );
338 "sip_protocol_loop: failed to handle %s",
339 substr( $inputbuf, 0, 2 )
342 next if $status eq REQUEST_ACS_RESEND;
344 alarm($previous_alarm);
347 if ( $@ =~ m/timed out/i ) {
357 # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
358 my $buffer = <STDIN>;
359 if ( defined $buffer ) {
360 STDIN->flush(); # clear an extra linefeed
362 $raw_length = length $buffer;
363 $buffer =~ s/^\s*[^A-z0-9]+//s;
364 # Every line must start with a "real" character. Not whitespace, control chars, etc.
365 $buffer =~ s/[^A-z0-9]+$//s;
367 # Same for the end. Note this catches the problem some clients have sending empty fields at the end, like |||
368 $buffer =~ s/\015?\012//g; # Extra line breaks must die
369 $buffer =~ s/\015?\012//s; # Extra line breaks must die
370 $buffer =~ s/\015*\012*$//s;
372 # treat as one line to include the extra linebreaks we are trying to remove!
375 syslog( 'LOG_DEBUG', 'EOF returned on read' );
378 my $len = length $buffer;
379 if ( $len != $raw_length ) {
380 my $trim = $raw_length - $len;
381 syslog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " );
384 syslog( 'LOG_INFO', "INPUT MSG: '$buffer'" );
388 # $server->get_timeout({ $type => 1, fallback => $fallback });
389 # where $type is transport | client | policy
391 # Centralizes all timeout logic.
392 # Transport refers to login process, client to active connections.
393 # Policy timeout is transaction timeout (used in ACS status message).
395 # Fallback is optional. If you do not pass transport, client or policy,
396 # you will get fallback or hardcoded default.
399 my ( $server, $params ) = @_;
400 my $fallback = $params->{fallback} || 30;
401 my $service = $server->{service} // {};
402 my $config = $server->{config} // {};
404 if( $params->{transport} ||
405 ( $params->{client} && !exists $service->{client_timeout} )) {
406 # We do not allow zero values here.
407 # Note: config/timeout seems to be deprecated.
408 return $service->{timeout} || $config->{timeout} || $fallback;
410 } elsif( $params->{client} ) {
411 # We know that client_timeout exists now.
412 # We do allow zero values here to indicate no timeout.
413 return 0 if $service->{client_timeout} =~ /^0+$|\D/;
414 return $service->{client_timeout};
416 } elsif( $params->{policy} ) {
417 my $policy = $server->{policy} // {};
418 my $rv = sprintf( "%03d", $policy->{timeout} // 0 );
419 if( length($rv) != 3 ) {
420 syslog( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv );
432 my $sipServer = C4::SIP::SIPServer::get_SIPServer()
434 @RETURNS C4::SIP::SIPServer, the current server's child-process used to handle this SIP-transaction
439 unless($activeSIPServer) {
441 die "$cc[3]() asks for \$activeSIPServer, but it is not defined yet";
443 return $activeSIPServer;
447 my ($sipServer) = @_;
448 unless (blessed($sipServer) && $sipServer->isa('C4::SIP::SIPServer')) {
450 die "$cc[3]():> \$sipServer '$sipServer' is not a C4::SIP::SIPServer-object";
452 $activeSIPServer = $sipServer;
453 return $activeSIPServer;
458 my $logger = C4::SIP::SIPServer::get_logger()
460 @RETURNS Koha::Logger, the logger used to log this SIP-transaction
465 unless($activeLogger) {
467 die "$cc[3]() asks for \$activeLogger, but it is not defined yet";
469 return $activeLogger;
474 unless (blessed($logger) && $logger->isa('Koha::Logger')) {
476 die "$cc[3]():> \$logger '$logger' is not a Koha::Logger-object";
478 $activeLogger = $logger;
479 return $activeLogger;