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(siplog);
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 );
20 use C4
::SIP
::Logger
qw(set_logger);
26 tie
*STDERR
, "C4::SIP::Trapper";
28 use base
qw(Net::Server::PreFork);
30 use constant LOG_SIP
=> "local6"; # Local alias for the logging facility
33 # Main # not really, since package SIPServer
35 # FIXME: Is this a module or a script?
36 # A script with no MAIN namespace?
37 # A module that takes command line args?
39 # Set interface to 'sip'
40 C4
::Context
->interface('sip');
43 RAW
=> \
&raw_transport
,
44 telnet
=> \
&telnet_transport
,
50 my $config = C4
::SIP
::Sip
::Configuration
->new( $ARGV[0] );
56 foreach my $svc (keys %{$config->{listeners
}}) {
57 push @parms, "port=" . $svc;
63 # Log lines look like this:
64 # Jun 16 21:21:31 server08 steve_sip[19305]: ILS::Transaction::Checkout performing checkout...
65 # [ TIMESTAMP ] [ HOST ] [ IDENT ] PID : Message...
67 # The IDENT is determined by config file 'server-params' arguments
71 # Server Management: set parameters for the Net::Server::PreFork
72 # module. The module silently ignores parameters that it doesn't
73 # recognize, and complains about invalid values for parameters
76 if (defined($config->{'server-params'})) {
77 while (my ($key, $val) = each %{$config->{'server-params'}}) {
78 push @parms, $key . '=' . $val;
84 # This is the main event.
85 __PACKAGE__
->run(@parms);
91 # process_request is the callback used by Net::Server to handle
92 # an incoming connection request.
97 my ($sockaddr, $port, $proto);
100 $self->{config
} = $config;
102 # Flushing L1 to make sure the request will be processed using the correct data
103 Koha
::Caches
->flush_L1_caches();
105 $self->{account
} = undef; # Clear out the account from the last request, it may be different
106 $self->{logger
} = set_logger
( Koha
::Logger
->get( { interface
=> 'sip' } ) );
108 my $sockname = getsockname(STDIN
);
110 # Check if socket connection is IPv6 before resolving address
111 my $family = Socket
::sockaddr_family
($sockname);
112 if ($family == AF_INET6
) {
113 ($port, $sockaddr) = sockaddr_in6
($sockname);
114 $sockaddr = Socket
::inet_ntop
(AF_INET6
, $sockaddr);
116 ($port, $sockaddr) = sockaddr_in
($sockname);
117 $sockaddr = inet_ntoa
($sockaddr);
119 $proto = $self->{server
}->{client
}->NS_proto();
121 $self->{service
} = $config->find_service($sockaddr, $port, $proto);
123 if (!defined($self->{service
})) {
124 siplog
("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
125 die "process_request: Bad server connection";
128 $transport = $transports{$self->{service
}->{transport
}};
130 if (!defined($transport)) {
131 siplog
("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport
});
146 my $service = $self->{service
};
147 # If using Net::Server::PreFork you may already have account set from a previous session
149 if ($self->{account
}) {
150 delete $self->{account
};
153 # Timeout the while loop if we get stuck in it
154 # In practice it should only iterate once but be prepared
155 local $SIG{ALRM
} = sub { die 'raw transport Timed Out!' };
156 my $timeout = $self->get_timeout({ transport
=> 1 });
157 siplog
('LOG_DEBUG', "raw_transport: timeout is $timeout");
159 while (!$self->{account
}) {
160 $input = read_request
();
163 siplog
("LOG_INFO", "raw_transport: shutting down: EOF during login");
166 $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s)
167 my $reg = qr/^${\(LOGIN)}/;
168 last if $input !~ $reg ||
169 C4
::SIP
::Sip
::MsgType
::handle
($input, $self, LOGIN
);
173 $self->{logger
} = set_logger
(
177 category
=> $self->{account
}->{id
}, # Add id to namespace
182 siplog
("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
183 $self->{account
}->{id
},
184 $self->{account
}->{institution
});
185 if (! $self->{account
}->{id
}) {
186 siplog
("LOG_ERR","Login failed shutting down");
190 $self->sip_protocol_loop();
191 siplog
("LOG_INFO", "raw_transport: shutting down");
195 sub get_clean_string
{
197 if (defined $string) {
198 siplog
("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string);
200 $string =~ s/^[^A-z0-9]+//;
201 $string =~ s/[^A-z0-9]+$//;
202 siplog
("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
204 siplog
("LOG_INFO", "get_clean_string called on undefined");
209 sub get_clean_input
{
212 $in = get_clean_string
($in);
213 while (my $extra = <STDIN
>){
214 siplog
("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
219 sub telnet_transport
{
225 my $config = $self->{config
};
226 my $timeout = $self->get_timeout({ transport
=> 1 });
227 siplog
("LOG_DEBUG", "telnet_transport: timeout is $timeout");
230 local $SIG{ALRM
} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
231 local $| = 1; # Unbuffered output
232 $/ = "\015"; # Internet Record Separator (lax version)
233 # Until the terminal has logged in, we don't trust it
234 # so use a timeout to protect ourselves from hanging.
239 # $uid = &get_clean_input;
242 # $pwd = &get_clean_input || '';
246 siplog
("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
247 $uid = get_clean_string
($uid);
248 $pwd = get_clean_string
($pwd);
249 siplog
("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
251 if (exists ($config->{accounts
}->{$uid})
252 && ($pwd eq $config->{accounts
}->{$uid}->{password
})) {
253 $account = $config->{accounts
}->{$uid};
254 if ( C4
::SIP
::Sip
::MsgType
::login_core
($self,$uid,$pwd) ) {
258 siplog
("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
259 print("Invalid login$CRLF");
264 siplog
("LOG_ERR", "telnet_transport: Login timed out");
265 die "Telnet Login Timed out";
266 } elsif (!defined($account)) {
267 siplog
("LOG_ERR", "telnet_transport: Login Failed");
270 print "Login OK. Initiating SIP$CRLF";
273 $self->{account
} = $account;
274 siplog
("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id
}, $account->{institution
});
275 $self->sip_protocol_loop();
276 siplog
("LOG_INFO", "telnet_transport: shutting down");
281 # The terminal has logged in, using either the SIP login process
282 # over a raw socket, or via the pseudo-unix login provided by the
283 # telnet transport. From that point on, both the raw and the telnet
284 # processes are the same:
285 sub sip_protocol_loop
{
287 my $service = $self->{service
};
288 my $config = $self->{config
};
289 my $timeout = $self->get_timeout({ client
=> 1 });
291 # The spec says the first message will be:
293 # SIP v2: LOGIN (or SC_STATUS via telnet?)
294 # But it might be SC_REQUEST_RESEND. As long as we get
295 # SC_REQUEST_RESEND, we keep waiting.
297 # Comprise reports that no other ILS actually enforces this
298 # constraint, so we'll relax about it too.
299 # Using the SIP "raw" login process, rather than telnet,
300 # requires the LOGIN message and forces SIP 2.00. In that
301 # case, the LOGIN message has already been processed (above).
303 # In short, we'll take any valid message here.
305 local $SIG{ALRM
} = sub {
306 siplog
( 'LOG_DEBUG', 'Inactive: timed out' );
309 my $previous_alarm = alarm($timeout);
311 while ( my $inputbuf = read_request
() ) {
312 if ( !defined $inputbuf ) {
318 siplog
( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
323 my $status = C4
::SIP
::Sip
::MsgType
::handle
( $inputbuf, $self, q{} );
327 "sip_protocol_loop: failed to handle %s",
328 substr( $inputbuf, 0, 2 )
331 next if $status eq REQUEST_ACS_RESEND
;
333 alarm($previous_alarm);
336 if ( $@
=~ m/timed out/i ) {
346 # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
347 my $buffer = <STDIN
>;
348 if ( defined $buffer ) {
349 STDIN
->flush(); # clear an extra linefeed
351 $raw_length = length $buffer;
352 $buffer =~ s/^\s*[^A-z0-9]+//s;
353 # Every line must start with a "real" character. Not whitespace, control chars, etc.
354 $buffer =~ s/[^A-z0-9]+$//s;
356 # Same for the end. Note this catches the problem some clients have sending empty fields at the end, like |||
357 $buffer =~ s/\015?\012//g; # Extra line breaks must die
358 $buffer =~ s/\015?\012//s; # Extra line breaks must die
359 $buffer =~ s/\015*\012*$//s;
361 # treat as one line to include the extra linebreaks we are trying to remove!
364 siplog
( 'LOG_DEBUG', 'EOF returned on read' );
367 my $len = length $buffer;
368 if ( $len != $raw_length ) {
369 my $trim = $raw_length - $len;
370 siplog
( 'LOG_DEBUG', "read_request trimmed $trim character(s) " );
373 siplog
( 'LOG_INFO', "INPUT MSG: '$buffer'" );
377 # $server->get_timeout({ $type => 1, fallback => $fallback });
378 # where $type is transport | client | policy
380 # Centralizes all timeout logic.
381 # Transport refers to login process, client to active connections.
382 # Policy timeout is transaction timeout (used in ACS status message).
384 # Fallback is optional. If you do not pass transport, client or policy,
385 # you will get fallback or hardcoded default.
388 my ( $server, $params ) = @_;
389 my $fallback = $params->{fallback
} || 30;
390 my $service = $server->{service
} // {};
391 my $config = $server->{config
} // {};
393 if( $params->{transport
} ||
394 ( $params->{client
} && !exists $service->{client_timeout
} )) {
395 # We do not allow zero values here.
396 # Note: config/timeout seems to be deprecated.
397 return $service->{timeout
} || $config->{timeout
} || $fallback;
399 } elsif( $params->{client
} ) {
400 # We know that client_timeout exists now.
401 # We do allow zero values here to indicate no timeout.
402 return 0 if $service->{client_timeout
} =~ /^0+$|\D/;
403 return $service->{client_timeout
};
405 } elsif( $params->{policy
} ) {
406 my $policy = $server->{policy
} // {};
407 my $rv = sprintf( "%03d", $policy->{timeout
} // 0 );
408 if( length($rv) != 3 ) {
409 siplog
( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv );