adding openncip / opensip SIP2 service
[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;
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 our @ISA = qw(Net::Server::PreFork);
22 #
23 # Main
24 #
25
26 my %transports = (
27     RAW    => \&raw_transport,
28     telnet => \&telnet_transport,
29     http   => \&http_transport,
30 );
31
32 # Read configuration
33
34 my $config = new Sip::Configuration $ARGV[0];
35
36 my @parms;
37
38 #
39 # Ports to bind
40 #
41 foreach my $svc (keys %{$config->{listeners}}) {
42     push @parms, "port=" . $svc;
43 }
44
45 #
46 # Logging
47 #
48 push @parms, "log_file=Sys::Syslog", "syslog_ident=acs-server",
49   "syslog_facility=" . LOG_SIP;
50
51 #
52 # Server Management: set parameters for the Net::Server::PreFork
53 # module.  The module silently ignores parameters that it doesn't
54 # recognize, and complains about invalid values for parameters
55 # that it does.
56 #
57 if (defined($config->{'server-params'})) {
58     while (my ($key, $val) = each %{$config->{'server-params'}}) {
59         push @parms, $key . '=' . $val;
60     }
61 }
62
63 print Dumper(@parms);
64
65 #
66 # This is the main event.
67 SIPServer->run(@parms);
68
69 #
70 # Child
71 #
72
73 # process_request is the callback used by Net::Server to handle
74 # an incoming connection request.
75
76 sub process_request {
77     my $self = shift;
78     my $service;
79     my $sockname;
80     my ($sockaddr, $port, $proto);
81     my $transport;
82
83     $self->{config} = $config;
84
85     $sockname = getsockname(STDIN);
86     ($port, $sockaddr) = sockaddr_in($sockname);
87     $sockaddr = inet_ntoa($sockaddr);
88     $proto = $self->{server}->{client}->NS_proto();
89
90     $self->{service} = $config->find_service($sockaddr, $port, $proto);
91
92     if (!defined($self->{service})) {
93         syslog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto);
94         die "process_request: Bad server connection";
95     }
96
97     $transport = $transports{$self->{service}->{transport}};
98
99     if (!defined($transport)) {
100         syslog("LOG_WARN", "Unknown transport '%s', dropping", $service->{transport});
101         return;
102     } else {
103         &$transport($self);
104     }
105 }
106
107 #
108 # Transports
109 #
110
111 sub raw_transport {
112     my $self = shift;
113     my ($uid, $pwd);
114     my $input;
115     my $service = $self->{service};
116     my $strikes = 3;
117     my $expect;
118     my $inst;
119
120     eval {
121         local $SIG{ALRM} = sub { die "alarm\n"; };
122         syslog("LOG_DEBUG", "raw_transport: timeout is %d",
123                $service->{timeout});
124         while ($strikes--) {
125             alarm $service->{timeout};
126             $input = Sip::read_SIP_packet(*STDIN);
127             alarm 0;
128
129             if (!$input) {
130                 # EOF on the socket
131                 syslog("LOG_INFO", "raw_transport: shutting down: EOF during login");
132                 return;
133             }
134
135             $input =~ s/[\r\n]+$//sm;   # Strip off trailing line terminator
136
137             last if Sip::MsgType::handle($input, $self, LOGIN);
138         }
139     };
140
141     if ($@) {
142         syslog("LOG_ERR", "raw_transport: LOGIN ERROR: '$@'");
143         die "raw_transport: login error, exiting";
144     } elsif (!$self->{account}) {
145         syslog("LOG_ERR", "raw_transport: LOGIN FAILED");
146         die "raw_transport: Login failed, exiting";
147     }
148
149     syslog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
150            $self->{account}->{id},
151            $self->{account}->{institution});
152
153     $self->sip_protocol_loop();
154
155     syslog("LOG_INFO", "raw_transport: shutting down");
156 }
157
158 sub telnet_transport {
159     my $self = shift;
160     my ($uid, $pwd);
161     my $strikes = 3;
162     my $account = undef;
163     my $input;
164     my $config = $self->{config};
165
166     # Until the terminal has logged in, we don't trust it
167     # so use a timeout to protect ourselves from hanging.
168     eval {
169         local $SIG{ALRM} = sub { die "alarm\n"; };
170         local $|;
171         my $timeout = 0;
172
173         $| = 1;                 # Unbuffered output
174         $timeout = $config->{timeout} if (exists($config->{timeout}));
175
176         while ($strikes--) {
177             print "login: ";
178             alarm $timeout;
179             $uid = <STDIN>;
180             alarm 0;
181
182             print "password: ";
183             alarm $timeout;
184             $pwd = <STDIN>;
185             alarm 0;
186
187             $uid =~ s/[\r\n]+$//;
188             $pwd =~ s/[\r\n]+$//;
189
190             if (exists($config->{accounts}->{$uid})
191                 && ($pwd eq $config->{accounts}->{$uid}->password())) {
192                 $account = $config->{accounts}->{$uid};
193                 last;
194             } else {
195                 syslog("LOG_WARNING", "Invalid login attempt: '%s'", $uid);
196                 print("Invalid login\n");
197             }
198         }
199     }; # End of eval
200
201     if ($@) {
202         syslog("LOG_ERR", "telnet_transport: Login timed out");
203         die "Telnet Login Timed out";
204     } elsif (!defined($account)) {
205         syslog("LOG_ERR", "telnet_transport: Login Failed");
206         die "Login Failure";
207     } else {
208         print "Login OK.  Initiating SIP\n";
209     }
210
211     $self->{account} = $account;
212
213     $self->sip_protocol_loop();
214     syslog("LOG_INFO", "telnet_transport: shutting down");
215 }
216
217
218 sub http_transport {
219 }
220
221 #
222 # The terminal has logged in, using either the SIP login process
223 # over a raw socket, or via the pseudo-unix login provided by the
224 # telnet transport.  From that point on, both the raw and the telnet
225 # processes are the same:
226 sub sip_protocol_loop {
227     my $self = shift;
228     my $expect;
229     my $service = $self->{service};
230     my $config = $self->{config};
231     my $input;
232
233     # Now that the terminal has logged in, the first message
234     # we recieve must be an SC_STATUS message.  But it might be
235     # an SC_REQUEST_RESEND.  So, as long as we keep receiving
236     # SC_REQUEST_RESEND, we keep waiting for an SC_STATUS
237
238     # Comprise reports that no other ILS actually enforces this
239     # constraint, so we'll relax about it too.  As long as everybody
240     # uses the SIP "raw" login process, rather than telnet, this
241     # will be fine, becaues the LOGIN protocol exchange will force
242     # us into SIP 2.00 anyway.  Machines that want to log in using
243     # telnet MUST send an SC Status message first, even though we're
244     # not enforcing it.
245     # 
246     #$expect = SC_STATUS;
247     $expect = '';
248
249     while ($input = Sip::read_SIP_packet(*STDIN)) {
250         my $status;
251
252         $input =~ s/[\r\n]+$//sm;       # Strip off any trailing line ends
253
254         $status = Sip::MsgType::handle($input, $self, $expect);
255         next if $status eq REQUEST_ACS_RESEND;
256
257         if (!$status) {
258             syslog("LOG_ERR", "raw_transport: failed to handle %s",
259                    substr($input, 0, 2));
260             die "raw_transport: dying";
261         } elsif ($expect && ($status ne $expect)) {
262             # We received a non-"RESEND" that wasn't what we were
263             # expecting.
264             syslog("LOG_ERR",
265                    "raw_transport: expected %s, received %s, exiting",
266                    $expect, $input);
267             die "raw_transport: exiting: expected '$expect', received '$status'";
268         }
269         # We successfully received and processed what we were expecting
270         # to receive
271         $expect = '';
272     }
273 }