remove superfluous retrieval of $ENV{'REMOTE_USER'}
[koha.git] / C4 / SIP / SIPServer.pm
1 package SIPServer;
2
3 use strict;
4 use warnings;
5 # use Exporter;
6 use Sys::Syslog qw(syslog);
7 use Net::Server::PreFork;
8 use IO::Socket::INET;
9 use Socket qw(:DEFAULT :crlf);
10 use Data::Dumper;               # For debugging
11 require UNIVERSAL::require;
12
13 #use Sip qw(readline);
14 use Sip::Constants qw(:all);
15 use Sip::Configuration;
16 use Sip::Checksum qw(checksum verify_cksum);
17 use Sip::MsgType;
18
19 use constant LOG_SIP => "local6"; # Local alias for the logging facility
20
21 use vars qw(@ISA $VERSION);
22
23 BEGIN {
24         $VERSION = 1.01;
25         @ISA = qw(Net::Server::PreFork);
26 }
27
28 #
29 # Main  # not really, since package SIPServer
30 #
31 # FIXME: Is this a module or a script?  
32 # A script with no MAIN namespace?
33 # A module that takes command line args?
34
35 my %transports = (
36     RAW    => \&raw_transport,
37     telnet => \&telnet_transport,
38     # http   => \&http_transport,       # for http just use the OPAC
39 );
40
41 #
42 # Read configuration
43 #
44 my $config = new Sip::Configuration $ARGV[0];
45 print STDERR "SIPServer config: \n" . Dumper($config) . "\nEND SIPServer config.\n";
46 my @parms;
47
48 #
49 # Ports to bind
50 #
51 foreach my $svc (keys %{$config->{listeners}}) {
52     push @parms, "port=" . $svc;
53 }
54
55 #
56 # Logging
57 #
58 push @parms, "log_file=Sys::Syslog", "syslog_ident=acs-server",
59   "syslog_facility=" . LOG_SIP;
60
61 #
62 # Server Management: set parameters for the Net::Server::PreFork
63 # module.  The module silently ignores parameters that it doesn't
64 # recognize, and complains about invalid values for parameters
65 # that it does.
66 #
67 if (defined($config->{'server-params'})) {
68     while (my ($key, $val) = each %{$config->{'server-params'}}) {
69                 push @parms, $key . '=' . $val;
70     }
71 }
72
73 print "Params for Net::Server::PreFork : \n" . Dumper(\@parms);
74
75 #
76 # This is the main event.
77 __PACKAGE__ ->run(@parms);
78
79 #
80 # Child
81 #
82
83 # process_request is the callback used by Net::Server to handle
84 # an incoming connection request.
85
86 sub process_request {
87     my $self = shift;
88     my $service;
89     my ($sockaddr, $port, $proto);
90     my $transport;
91
92     $self->{config} = $config;
93
94     my $sockname = getsockname(STDIN);
95     ($port, $sockaddr) = sockaddr_in($sockname);
96     $sockaddr = inet_ntoa($sockaddr);
97     $proto = $self->{server}->{client}->NS_proto();
98
99     $self->{service} = $config->find_service($sockaddr, $port, $proto);
100
101     if (!defined($self->{service})) {
102                 syslog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
103                 die "process_request: Bad server connection";
104     }
105
106     $transport = $transports{$self->{service}->{transport}};
107
108     if (!defined($transport)) {
109                 syslog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
110                 return;
111     } else {
112                 &$transport($self);
113     }
114 }
115
116 #
117 # Transports
118 #
119
120 sub raw_transport {
121     my $self = shift;
122     my ($input);
123     my $service = $self->{service};
124     my $strikes = 3;
125
126     eval {
127                 local $SIG{ALRM} = sub { die "raw_transport Timed Out!\n"; };
128                 syslog("LOG_DEBUG", "raw_transport: timeout is %d", $service->{timeout});
129                 while ($strikes--) {
130                     alarm $service->{timeout};
131                     $input = Sip::read_SIP_packet(*STDIN);
132                     alarm 0;
133                         if (!$input) {
134                                 # EOF on the socket
135                                 syslog("LOG_INFO", "raw_transport: shutting down: EOF during login");
136                                 return;
137                     }
138                     $input =~ s/[\r\n]+$//sm;   # Strip off trailing line terminator(s)
139                     last if Sip::MsgType::handle($input, $self, LOGIN);
140                 }
141         };
142
143     if (length $@) {
144                 syslog("LOG_ERR", "raw_transport: LOGIN ERROR: '$@'");
145                 die "raw_transport: login error (timeout? $@), exiting";
146     } elsif (!$self->{account}) {
147                 syslog("LOG_ERR", "raw_transport: LOGIN FAILED");
148                 die "raw_transport: Login failed (no account), exiting";
149     }
150
151     syslog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
152            $self->{account}->{id},
153            $self->{account}->{institution});
154
155     $self->sip_protocol_loop();
156     syslog("LOG_INFO", "raw_transport: shutting down");
157 }
158
159 sub get_clean_string ($) {
160         my $string = shift;
161         if (defined $string) {
162                 syslog("LOG_DEBUG", "get_clean_string  pre-clean(length %s): %s", length($string), $string);
163                 chomp($string);
164                 $string =~ s/^[^A-z0-9]+//;
165                 $string =~ s/[^A-z0-9]+$//;
166                 syslog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string);
167         } else {
168                 syslog("LOG_INFO", "get_clean_string called on undefined");
169         }
170         return $string;
171 }
172
173 sub get_clean_input {
174         local $/ = "\012";
175         my $in = <STDIN>;
176         $in = get_clean_string($in);
177         while (my $extra = <STDIN>){
178                 syslog("LOG_ERR", "get_clean_input got extra lines: %s", $extra);
179         }
180         return $in;
181 }
182
183 sub telnet_transport {
184     my $self = shift;
185     my ($uid, $pwd);
186     my $strikes = 3;
187     my $account = undef;
188     my $input;
189     my $config  = $self->{config};
190         my $timeout = $self->{service}->{timeout} || $config->{timeout} || 30;
191         syslog("LOG_DEBUG", "telnet_transport: timeout is %s", $timeout);
192
193     eval {
194         local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; };
195         local $| = 1;                   # Unbuffered output
196         $/ = "\015";            # Internet Record Separator (lax version)
197     # Until the terminal has logged in, we don't trust it
198     # so use a timeout to protect ourselves from hanging.
199
200         while ($strikes--) {
201             print "login: ";
202                 alarm $timeout;
203                 # $uid = &get_clean_input;
204                 $uid = <STDIN>;
205             print "password: ";
206             # $pwd = &get_clean_input || '';
207                 $pwd = <STDIN>;
208                 alarm 0;
209
210                 syslog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd));
211                 $uid = get_clean_string ($uid);
212                 $pwd = get_clean_string ($pwd);
213                 syslog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd));
214                 # $uid =~ s/^\s+//;                     # 
215                 # $pwd =~ s/^\s+//;                     # 
216             # $uid =~ s/[\r\n]+$//gms;  # 
217             # $pwd =~ s/[\r\n]+$//gms;  # 
218             # $uid =~ s/[[:cntrl:]]//g; # 
219             # $pwd =~ s/[[:cntrl:]]//g; # 
220                 # syslog("LOG_DEBUG", "telnet_transport 3: uid length %s, pwd length %s", length($uid), length($pwd));
221
222             if (exists ($config->{accounts}->{$uid})
223                 && ($pwd eq $config->{accounts}->{$uid}->password())) {
224                         $account = $config->{accounts}->{$uid};
225                         Sip::MsgType::login_core($self,$uid,$pwd) and last;
226             }
227                 syslog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||''));
228                 print("Invalid login$CRLF");
229         }
230     }; # End of eval
231
232     if ($@) {
233                 syslog("LOG_ERR", "telnet_transport: Login timed out");
234                 die "Telnet Login Timed out";
235     } elsif (!defined($account)) {
236                 syslog("LOG_ERR", "telnet_transport: Login Failed");
237                 die "Login Failure";
238     } else {
239                 print "Login OK.  Initiating SIP$CRLF";
240     }
241
242     $self->{account} = $account;
243     syslog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
244     $self->sip_protocol_loop();
245     syslog("LOG_INFO", "telnet_transport: shutting down");
246 }
247
248 #
249 # The terminal has logged in, using either the SIP login process
250 # over a raw socket, or via the pseudo-unix login provided by the
251 # telnet transport.  From that point on, both the raw and the telnet
252 # processes are the same:
253 sub sip_protocol_loop {
254         my $self = shift;
255         my $service = $self->{service};
256         my $config  = $self->{config};
257         my $input;
258
259     # The spec says the first message will be:
260         #       SIP v1: SC_STATUS
261         #       SIP v2: LOGIN (or SC_STATUS via telnet?)
262     # But it might be SC_REQUEST_RESEND.  As long as we get
263     # SC_REQUEST_RESEND, we keep waiting.
264
265     # Comprise reports that no other ILS actually enforces this
266     # constraint, so we'll relax about it too.
267     # Using the SIP "raw" login process, rather than telnet,
268     # requires the LOGIN message and forces SIP 2.00.  In that
269         # case, the LOGIN message has already been processed (above).
270         # 
271         # In short, we'll take any valid message here.
272         #my $expect = SC_STATUS;
273     my $expect = '';
274     my $strikes = 3;
275     while ($input = Sip::read_SIP_packet(*STDIN)) {
276                 # begin input hacks ...  a cheap stand in for better Telnet layer
277                 $input =~ s/^[^A-z0-9]+//s;     # Kill leading bad characters... like Telnet handshakers
278                 $input =~ s/[^A-z0-9]+$//s;     # Same on the end, should get DOSsy ^M line-endings too.
279                 while (chomp($input)) {warn "Extra line ending on input";}
280                 unless ($input) {
281                         if ($strikes--) {
282                                 syslog("LOG_ERR", "sip_protocol_loop: empty input skipped");
283                                 next;
284                         } else {
285                                 syslog("LOG_ERR", "sip_protocol_loop: quitting after too many errors");
286                                 die "sip_protocol_loop: quitting after too many errors";
287                         }
288                 }
289                 # end cheap input hacks
290                 my $status = Sip::MsgType::handle($input, $self, $expect);
291                 if (!$status) {
292                         syslog("LOG_ERR", "sip_protocol_loop: failed to handle %s",substr($input,0,2));
293                         die "sip_protocol_loop: failed Sip::MsgType::handle('$input', $self, '$expect')";
294                 }
295                 next if $status eq REQUEST_ACS_RESEND;
296                 if ($expect && ($status ne $expect)) {
297                         # We received a non-"RESEND" that wasn't what we were expecting.
298                     syslog("LOG_ERR", "sip_protocol_loop: expected %s, received %s, exiting", $expect, $input);
299                         die "sip_protocol_loop: exiting: expected '$expect', received '$status'";
300                 }
301                 # We successfully received and processed what we were expecting
302                 $expect = '';
303         }
304 }
305
306 1;
307 __END__