Bug 19338: Fix sorting by dates in opac-account.tt
[koha.git] / C4 / SIP / SIPServer.pm
blob5e1e3a6ee38fac6c7e4ace1babcedf0e9d7f14d1
1 #!/usr/bin/perl
2 package C4::SIP::SIPServer;
4 use strict;
5 use warnings;
6 use FindBin qw($Bin);
7 use lib "$Bin";
8 use Sys::Syslog qw(syslog);
9 use Net::Server::PreFork;
10 use IO::Socket::INET;
11 use Socket qw(:DEFAULT :crlf);
12 require UNIVERSAL::require;
14 use C4::SIP::Sip::Constants qw(:all);
15 use C4::SIP::Sip::Configuration;
16 use C4::SIP::Sip::Checksum qw(checksum verify_cksum);
17 use C4::SIP::Sip::MsgType qw( handle login_core );
19 use base qw(Net::Server::PreFork);
21 use constant LOG_SIP => "local6"; # Local alias for the logging facility
24 # Main # not really, since package SIPServer
26 # FIXME: Is this a module or a script?
27 # A script with no MAIN namespace?
28 # A module that takes command line args?
30 my %transports = (
31 RAW => \&raw_transport,
32 telnet => \&telnet_transport,
36 # Read configuration
38 my $config = C4::SIP::Sip::Configuration->new( $ARGV[0] );
39 my @parms;
42 # Ports to bind
44 foreach my $svc (keys %{$config->{listeners}}) {
45 push @parms, "port=" . $svc;
49 # Logging
51 # Log lines look like this:
52 # Jun 16 21:21:31 server08 steve_sip[19305]: ILS::Transaction::Checkout performing checkout...
53 # [ TIMESTAMP ] [ HOST ] [ IDENT ] PID : Message...
55 # The IDENT is determined by config file 'server-params' arguments
59 # Server Management: set parameters for the Net::Server::PreFork
60 # module. The module silently ignores parameters that it doesn't
61 # recognize, and complains about invalid values for parameters
62 # that it does.
64 if (defined($config->{'server-params'})) {
65 while (my ($key, $val) = each %{$config->{'server-params'}}) {
66 push @parms, $key . '=' . $val;
72 # This is the main event.
73 __PACKAGE__ ->run(@parms);
76 # Child
79 # process_request is the callback used by Net::Server to handle
80 # an incoming connection request.
82 sub process_request {
83 my $self = shift;
84 my $service;
85 my ($sockaddr, $port, $proto);
86 my $transport;
88 $self->{config} = $config;
90 my $sockname = getsockname(STDIN);
92 # Check if socket connection is IPv6 before resolving address
93 my $family = Socket::sockaddr_family($sockname);
94 if ($family == AF_INET6) {
95 ($port, $sockaddr) = sockaddr_in6($sockname);
96 $sockaddr = Socket::inet_ntop(AF_INET6, $sockaddr);
97 } else {
98 ($port, $sockaddr) = sockaddr_in($sockname);
99 $sockaddr = inet_ntoa($sockaddr);
101 $proto = $self->{server}->{client}->NS_proto();
103 $self->{service} = $config->find_service($sockaddr, $port, $proto);
105 if (!defined($self->{service})) {
106 syslog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
107 die "process_request: Bad server connection";
110 $transport = $transports{$self->{service}->{transport}};
112 if (!defined($transport)) {
113 syslog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
114 return;
115 } else {
116 &$transport($self);
118 return;
122 # Transports
125 sub raw_transport {
126 my $self = shift;
127 my $input;
128 my $service = $self->{service};
129 # If using Net::Server::PreFork you may already have account set from a previous session
130 # Ensure you dont
131 if ($self->{account}) {
132 delete $self->{account};
135 # Timeout the while loop if we get stuck in it
136 # In practice it should only iterate once but be prepared
137 local $SIG{ALRM} = sub { die 'raw transport Timed Out!' };
138 my $timeout = $self->get_timeout({ transport => 1 });
139 syslog('LOG_DEBUG', "raw_transport: timeout is $timeout");
140 alarm $timeout;
141 while (!$self->{account}) {
142 $input = read_request();
143 if (!$input) {
144 # EOF on the socket
145 syslog("LOG_INFO", "raw_transport: shutting down: EOF during login");
146 return;
148 $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s)
149 my $reg = qr/^${\(LOGIN)}/;
150 last if $input !~ $reg ||
151 C4::SIP::Sip::MsgType::handle($input, $self, LOGIN);
153 alarm 0;
155 syslog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
156 $self->{account}->{id},
157 $self->{account}->{institution});
158 if (! $self->{account}->{id}) {
159 syslog("LOG_ERR","Login failed shutting down");
160 return;
163 $self->sip_protocol_loop();
164 syslog("LOG_INFO", "raw_transport: shutting down");
165 return;
168 sub get_clean_string {
169 my $string = shift;
170 if (defined $string) {
171 syslog("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string);
172 chomp($string);
173 $string =~ s/^[^A-z0-9]+//;
174 $string =~ s/[^A-z0-9]+$//;
175 syslog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
176 } else {
177 syslog("LOG_INFO", "get_clean_string called on undefined");
179 return $string;
182 sub get_clean_input {
183 local $/ = "\012";
184 my $in = <STDIN>;
185 $in = get_clean_string($in);
186 while (my $extra = <STDIN>){
187 syslog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
189 return $in;
192 sub telnet_transport {
193 my $self = shift;
194 my ($uid, $pwd);
195 my $strikes = 3;
196 my $account = undef;
197 my $input;
198 my $config = $self->{config};
199 my $timeout = $self->get_timeout({ transport => 1 });
200 syslog("LOG_DEBUG", "telnet_transport: timeout is $timeout");
202 eval {
203 local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
204 local $| = 1; # Unbuffered output
205 $/ = "\015"; # Internet Record Separator (lax version)
206 # Until the terminal has logged in, we don't trust it
207 # so use a timeout to protect ourselves from hanging.
209 while ($strikes--) {
210 print "login: ";
211 alarm $timeout;
212 # $uid = &get_clean_input;
213 $uid = <STDIN>;
214 print "password: ";
215 # $pwd = &get_clean_input || '';
216 $pwd = <STDIN>;
217 alarm 0;
219 syslog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
220 $uid = get_clean_string ($uid);
221 $pwd = get_clean_string ($pwd);
222 syslog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
224 if (exists ($config->{accounts}->{$uid})
225 && ($pwd eq $config->{accounts}->{$uid}->{password})) {
226 $account = $config->{accounts}->{$uid};
227 if ( C4::SIP::Sip::MsgType::login_core($self,$uid,$pwd) ) {
228 last;
231 syslog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
232 print("Invalid login$CRLF");
234 }; # End of eval
236 if ($@) {
237 syslog("LOG_ERR", "telnet_transport: Login timed out");
238 die "Telnet Login Timed out";
239 } elsif (!defined($account)) {
240 syslog("LOG_ERR", "telnet_transport: Login Failed");
241 die "Login Failure";
242 } else {
243 print "Login OK. Initiating SIP$CRLF";
246 $self->{account} = $account;
247 syslog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
248 $self->sip_protocol_loop();
249 syslog("LOG_INFO", "telnet_transport: shutting down");
250 return;
254 # The terminal has logged in, using either the SIP login process
255 # over a raw socket, or via the pseudo-unix login provided by the
256 # telnet transport. From that point on, both the raw and the telnet
257 # processes are the same:
258 sub sip_protocol_loop {
259 my $self = shift;
260 my $service = $self->{service};
261 my $config = $self->{config};
262 my $timeout = $self->get_timeout({ client => 1 });
264 # The spec says the first message will be:
265 # SIP v1: SC_STATUS
266 # SIP v2: LOGIN (or SC_STATUS via telnet?)
267 # But it might be SC_REQUEST_RESEND. As long as we get
268 # SC_REQUEST_RESEND, we keep waiting.
270 # Comprise reports that no other ILS actually enforces this
271 # constraint, so we'll relax about it too.
272 # Using the SIP "raw" login process, rather than telnet,
273 # requires the LOGIN message and forces SIP 2.00. In that
274 # case, the LOGIN message has already been processed (above).
276 # In short, we'll take any valid message here.
277 eval {
278 local $SIG{ALRM} = sub {
279 syslog( 'LOG_DEBUG', 'Inactive: timed out' );
280 die "Timed Out!\n";
282 my $previous_alarm = alarm($timeout);
284 while ( my $inputbuf = read_request() ) {
285 if ( !defined $inputbuf ) {
286 return; #EOF
288 alarm($timeout);
290 unless ($inputbuf) {
291 syslog( "LOG_ERR", "sip_protocol_loop: empty input skipped" );
292 print("96$CR");
293 next;
296 my $status = C4::SIP::Sip::MsgType::handle( $inputbuf, $self, q{} );
297 if ( !$status ) {
298 syslog(
299 "LOG_ERR",
300 "sip_protocol_loop: failed to handle %s",
301 substr( $inputbuf, 0, 2 )
304 next if $status eq REQUEST_ACS_RESEND;
306 alarm($previous_alarm);
307 return;
309 if ( $@ =~ m/timed out/i ) {
310 return;
312 return;
315 sub read_request {
316 my $raw_length;
317 local $/ = "\015";
319 # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
320 my $buffer = <STDIN>;
321 if ( defined $buffer ) {
322 STDIN->flush(); # clear an extra linefeed
323 chomp $buffer;
324 $raw_length = length $buffer;
325 $buffer =~ s/^\s*[^A-z0-9]+//s;
326 # Every line must start with a "real" character. Not whitespace, control chars, etc.
327 $buffer =~ s/[^A-z0-9]+$//s;
329 # Same for the end. Note this catches the problem some clients have sending empty fields at the end, like |||
330 $buffer =~ s/\015?\012//g; # Extra line breaks must die
331 $buffer =~ s/\015?\012//s; # Extra line breaks must die
332 $buffer =~ s/\015*\012*$//s;
334 # treat as one line to include the extra linebreaks we are trying to remove!
336 else {
337 syslog( 'LOG_DEBUG', 'EOF returned on read' );
338 return;
340 my $len = length $buffer;
341 if ( $len != $raw_length ) {
342 my $trim = $raw_length - $len;
343 syslog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " );
346 syslog( 'LOG_INFO', "INPUT MSG: '$buffer'" );
347 return $buffer;
350 # $server->get_timeout({ $type => 1, fallback => $fallback });
351 # where $type is transport | client | policy
353 # Centralizes all timeout logic.
354 # Transport refers to login process, client to active connections.
355 # Policy timeout is transaction timeout (used in ACS status message).
357 # Fallback is optional. If you do not pass transport, client or policy,
358 # you will get fallback or hardcoded default.
360 sub get_timeout {
361 my ( $server, $params ) = @_;
362 my $fallback = $params->{fallback} || 30;
363 my $service = $server->{service} // {};
364 my $config = $server->{config} // {};
366 if( $params->{transport} ||
367 ( $params->{client} && !exists $service->{client_timeout} )) {
368 # We do not allow zero values here.
369 # Note: config/timeout seems to be deprecated.
370 return $service->{timeout} || $config->{timeout} || $fallback;
372 } elsif( $params->{client} ) {
373 # We know that client_timeout exists now.
374 # We do allow zero values here to indicate no timeout.
375 return 0 if $service->{client_timeout} =~ /^0+$|\D/;
376 return $service->{client_timeout};
378 } elsif( $params->{policy} ) {
379 my $policy = $server->{policy} // {};
380 my $rv = sprintf( "%03d", $policy->{timeout} // 0 );
381 if( length($rv) != 3 ) {
382 syslog( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv );
383 return '000';
385 return $rv;
387 } else {
388 return $fallback;
394 __END__