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 set_logger( Koha::Logger->get( { interface => 'sip' } ) );
37 # Main # not really, since package SIPServer
39 # FIXME: Is this a module or a script?
40 # A script with no MAIN namespace?
41 # A module that takes command line args?
43 # Set interface to 'sip'
44 C4::Context->interface('sip');
47 RAW => \&raw_transport,
48 telnet => \&telnet_transport,
54 my $config = C4::SIP::Sip::Configuration->new( $ARGV[0] );
60 foreach my $svc (keys %{$config->{listeners}}) {
61 push @parms, "port=" . $svc;
67 # Log lines look like this:
68 # Jun 16 21:21:31 server08 steve_sip[19305]: ILS::Transaction::Checkout performing checkout...
69 # [ TIMESTAMP ] [ HOST ] [ IDENT ] PID : Message...
71 # The IDENT is determined by config file 'server-params' arguments
75 # Server Management: set parameters for the Net::Server::PreFork
76 # module. The module silently ignores parameters that it doesn't
77 # recognize, and complains about invalid values for parameters
80 if (defined($config->{'server-params'})) {
81 while (my ($key, $val) = each %{$config->{'server-params'}}) {
82 push @parms, $key . '=' . $val;
85 # Add user and group to prevent warn from Net::Server.
86 push @parms, 'user=' . $>;
87 push @parms, 'group=' . $>;
90 # This is the main event.
91 __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 # Flushing L1 to make sure the request will be processed using the correct data
109 Koha::Caches->flush_L1_caches();
111 $self->{account} = undef; # Clear out the account from the last request, it may be different
112 $self->{logger} = set_logger( Koha::Logger->get( { interface => 'sip' } ) );
114 # Flush previous MDCs to prevent accidentally leaking incorrect MDC-entries
115 Koha::Logger->clear_mdc();
117 my $sockname = getsockname(STDIN);
119 # Check if socket connection is IPv6 before resolving address
120 my $family = Socket::sockaddr_family($sockname);
121 if ($family == AF_INET6) {
122 ($port, $sockaddr) = sockaddr_in6($sockname);
123 $sockaddr = Socket::inet_ntop(AF_INET6, $sockaddr);
125 ($port, $sockaddr) = sockaddr_in($sockname);
126 $sockaddr = inet_ntoa($sockaddr);
128 $proto = $self->{server}->{client}->NS_proto();
130 $self->{service} = $config->find_service($sockaddr, $port, $proto);
132 if (!defined($self->{service})) {
133 siplog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
134 die "process_request: Bad server connection";
137 $transport = $transports{$self->{service}->{transport}};
139 if (!defined($transport)) {
140 siplog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
155 my $service = $self->{service};
156 # If using Net::Server::PreFork you may already have account set from a previous session
158 if ($self->{account}) {
159 delete $self->{account};
162 # Timeout the while loop if we get stuck in it
163 # In practice it should only iterate once but be prepared
164 local $SIG{ALRM} = sub { die 'raw transport Timed Out!' };
165 my $timeout = $self->get_timeout({ transport => 1 });
166 siplog('LOG_DEBUG', "raw_transport: timeout is $timeout");
168 while (!$self->{account}) {
169 $input = read_request();
172 siplog("LOG_INFO", "raw_transport: shutting down: EOF during login");
175 $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s)
176 my $reg = qr/^${\(LOGIN)}/;
177 last if $input !~ $reg ||
178 C4::SIP::Sip::MsgType::handle($input, $self, LOGIN);
182 $self->{logger} = set_logger(
186 category => $self->{account}->{id}, # Add id to namespace
191 # Set MDCs after properly authenticating
192 Koha::Logger->put_mdc( "accountid", $self->{account}->{id} );
193 Koha::Logger->put_mdc( "peeraddr", $self->{server}->{peeraddr} );
195 siplog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
196 $self->{account}->{id},
197 $self->{account}->{institution});
198 if (! $self->{account}->{id}) {
199 siplog("LOG_ERR","Login failed shutting down");
203 $self->sip_protocol_loop();
204 siplog("LOG_INFO", "raw_transport: shutting down");
208 sub get_clean_string {
210 if (defined $string) {
211 siplog("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string);
213 $string =~ s/^[^A-z0-9]+//;
214 $string =~ s/[^A-z0-9]+$//;
215 siplog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
217 siplog("LOG_INFO", "get_clean_string called on undefined");
222 sub get_clean_input {
225 $in = get_clean_string($in);
226 while (my $extra = <STDIN>){
227 siplog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
232 sub telnet_transport {
238 my $config = $self->{config};
239 my $timeout = $self->get_timeout({ transport => 1 });
240 siplog("LOG_DEBUG", "telnet_transport: timeout is $timeout");
243 local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
244 local $| = 1; # Unbuffered output
245 $/ = "\015"; # Internet Record Separator (lax version)
246 # Until the terminal has logged in, we don't trust it
247 # so use a timeout to protect ourselves from hanging.
252 # $uid = &get_clean_input;
255 # $pwd = &get_clean_input || '';
259 siplog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
260 $uid = get_clean_string ($uid);
261 $pwd = get_clean_string ($pwd);
262 siplog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
264 if (exists ($config->{accounts}->{$uid})
265 && ($pwd eq $config->{accounts}->{$uid}->{password})) {
266 $account = $config->{accounts}->{$uid};
267 if ( C4::SIP::Sip::MsgType::login_core($self,$uid,$pwd) ) {
271 siplog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
272 print("Invalid login$CRLF");
277 siplog("LOG_ERR", "telnet_transport: Login timed out");
278 die "Telnet Login Timed out";
279 } elsif (!defined($account)) {
280 siplog("LOG_ERR", "telnet_transport: Login Failed");
283 print "Login OK. Initiating SIP$CRLF";
286 $self->{account} = $account;
287 siplog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
288 $self->sip_protocol_loop();
289 siplog("LOG_INFO", "telnet_transport: shutting down");
294 # The terminal has logged in, using either the SIP login process
295 # over a raw socket, or via the pseudo-unix login provided by the
296 # telnet transport. From that point on, both the raw and the telnet
297 # processes are the same:
298 sub sip_protocol_loop {
300 my $service = $self->{service};
301 my $config = $self->{config};
302 my $timeout = $self->get_timeout({ client => 1 });
304 # The spec says the first message will be:
306 # SIP v2: LOGIN (or SC_STATUS via telnet?)
307 # But it might be SC_REQUEST_RESEND. As long as we get
308 # SC_REQUEST_RESEND, we keep waiting.
310 # Comprise reports that no other ILS actually enforces this
311 # constraint, so we'll relax about it too.
312 # Using the SIP "raw" login process, rather than telnet,
313 # requires the LOGIN message and forces SIP 2.00. In that
314 # case, the LOGIN message has already been processed (above).
316 # In short, we'll take any valid message here.
318 local $SIG{ALRM} = sub {
319 siplog( 'LOG_DEBUG', 'Inactive: timed out' );
322 my $previous_alarm = alarm($timeout);
324 while ( my $inputbuf = read_request() ) {
325 if ( !defined $inputbuf ) {
331 siplog( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
336 my $status = C4::SIP::Sip::MsgType::handle( $inputbuf, $self, q{} );
340 "sip_protocol_loop: failed to handle %s",
341 substr( $inputbuf, 0, 2 )
344 next if $status eq REQUEST_ACS_RESEND;
346 alarm($previous_alarm);
349 if ( $@ =~ m/timed out/i ) {
359 # SIP connections might be active for weeks, clear L1 cache on every request
360 Koha::Caches->flush_L1_caches();
362 # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
363 my $buffer = <STDIN>;
364 if ( defined $buffer ) {
365 STDIN->flush(); # clear an extra linefeed
367 $raw_length = length $buffer;
368 $buffer =~ s/^\s*[^A-z0-9]+//s;
369 # Every line must start with a "real" character. Not whitespace, control chars, etc.
370 $buffer =~ s/[^A-z0-9]+$//s;
372 # Same for the end. Note this catches the problem some clients have sending empty fields at the end, like |||
373 $buffer =~ s/\015?\012//g; # Extra line breaks must die
374 $buffer =~ s/\015?\012//s; # Extra line breaks must die
375 $buffer =~ s/\015*\012*$//s;
377 # treat as one line to include the extra linebreaks we are trying to remove!
380 siplog( 'LOG_DEBUG', 'EOF returned on read' );
383 my $len = length $buffer;
384 if ( $len != $raw_length ) {
385 my $trim = $raw_length - $len;
386 siplog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " );
389 siplog( 'LOG_INFO', "INPUT MSG: '$buffer'" );
393 # $server->get_timeout({ $type => 1, fallback => $fallback });
394 # where $type is transport | client | policy
396 # Centralizes all timeout logic.
397 # Transport refers to login process, client to active connections.
398 # Policy timeout is transaction timeout (used in ACS status message).
400 # Fallback is optional. If you do not pass transport, client or policy,
401 # you will get fallback or hardcoded default.
404 my ( $server, $params ) = @_;
405 my $fallback = $params->{fallback} || 30;
406 my $service = $server->{service} // {};
407 my $config = $server->{config} // {};
409 if( $params->{transport} ||
410 ( $params->{client} && !exists $service->{client_timeout} )) {
411 # We do not allow zero values here.
412 # Note: config/timeout seems to be deprecated.
413 return $service->{timeout} || $config->{timeout} || $fallback;
415 } elsif( $params->{client} ) {
416 # We know that client_timeout exists now.
417 # We do allow zero values here to indicate no timeout.
418 return 0 if $service->{client_timeout} =~ /^0+$|\D/;
419 return $service->{client_timeout};
421 } elsif( $params->{policy} ) {
422 my $policy = $server->{policy} // {};
423 my $rv = sprintf( "%03d", $policy->{timeout} // 0 );
424 if( length($rv) != 3 ) {
425 siplog( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv );