]> git.evergreen-ils.org Git - working/SIPServer.git/blob - SIPServer.pm
Perltidy and cleanup.
[working/SIPServer.git] / SIPServer.pm
1 #
2 # Copyright (C) 2006-2008  Georgia Public Library Service
3
4 # Author: David J. Fiander
5
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of version 2 of the GNU General Public
8 # License as published by the Free Software Foundation.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public
16 # License along with this program; if not, write to the Free
17 # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
18 # MA 02111-1307 USA
19
20 package SIPServer;
21
22 use strict;
23 use warnings;
24 use Exporter;
25 use Sys::Syslog qw(syslog);
26 use Net::Server::PreFork;
27 use Net::Server::Proto;
28 use IO::Socket::INET;
29 use Socket qw(:crlf);
30 use Data::Dumper;               # For debugging
31 require UNIVERSAL::require;
32
33 #use Sip qw(readline);
34 use Sip::Constants qw(:all);
35 use Sip::Configuration;
36 use Sip::Checksum qw(checksum verify_cksum);
37 use Sip::MsgType;
38
39 use constant LOG_SIP => "local6"; # Local alias for the logging facility
40
41 our $VERSION = 0.02;
42 our @ISA = qw(Net::Server::PreFork);
43 #
44 # Main
45 #
46
47 my %transports = (
48     RAW    => \&raw_transport,
49     telnet => \&telnet_transport,
50     http   => \&http_transport,
51 );
52
53 # Read configuration
54
55 my $config = Sip::Configuration->new($ARGV[0]);
56
57 my @parms;
58
59 #
60 # Ports to bind
61 #
62 foreach my $svc (keys %{$config->{listeners}}) {
63     push @parms, "port=" . $svc;
64 }
65
66 #
67 # Logging
68 #
69 # Log lines look like this:
70 # Jun 16 21:21:31 server08 steve_sip: Sip::MsgType::_initialize('Login', ...)
71 # [  TIMESTAMP  ] [ HOST ] [ IDENT ]: Message...
72 #
73 # The IDENT is determined by $ENV{SIP_LOG_IDENT}, if present.
74 # Otherwise it is "_sip" appended to $USER, if present, or "acs-server" as a fallback.
75 #
76
77 my $syslog_ident = $ENV{SIP_LOG_IDENT} || ($ENV{USER} ? $ENV{USER} . "_sip" : 'acs-server');
78
79 push @parms,
80     "log_file=Sys::Syslog",
81     "syslog_ident=$syslog_ident",
82     "syslog_facility=" . LOG_SIP;
83
84 #
85 # Server Management: set parameters for the Net::Server::PreFork
86 # module.  The module silently ignores parameters that it doesn't
87 # recognize, and complains about invalid values for parameters
88 # that it does.
89 #
90 if (defined($config->{'server-params'})) {
91     while (my ($key, $val) = each %{$config->{'server-params'}}) {
92         push @parms, $key . '=' . $val;
93     }
94 }
95
96 print Dumper(@parms);
97
98 #
99 # This is the main event.
100 SIPServer->run(@parms);
101
102 #
103 # Child
104 #
105
106 # process_request is the callback used by Net::Server to handle
107 # an incoming connection request.
108
109 sub process_request {
110     my $self = shift;
111     my $service;
112     my $sockname;
113     my ($sockaddr, $port, $proto);
114     my $transport;
115
116     $self->{config} = $config;
117
118     $sockaddr = $self->{server}->{sockaddr};
119     $port     = $self->{server}->{sockport};
120     $proto    = $self->{server}->{client}->NS_proto();
121     syslog('LOG_INFO', "Inbound connection from $sockaddr on port $port and proto $proto");
122
123     $self->{service} = $config->find_service( $sockaddr, $port, $proto );
124
125     if (! defined($self->{service})) {
126         syslog( "LOG_ERR", "process_request: Unrecognized server connection: %s:%s/%s",
127             $sockaddr, $port, $proto );
128         die "process_request: Bad server connection";
129     }
130
131     $transport = $transports{ $self->{service}->{transport} };
132
133     if ( !defined($transport) ) {
134         syslog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport});
135         return;
136     } else {
137         &$transport($self);
138     }
139 }
140
141 #
142 # Transports
143 #
144
145 sub raw_transport {
146     my $self = shift;
147     my ($uid, $pwd);
148     my $input;
149     my $service = $self->{service};
150     my $strikes = 3;
151     my $expect;
152     my $inst;
153
154     eval {
155         local $SIG{ALRM} = sub { die "raw_transport Timed Out!\n"; };
156         syslog("LOG_DEBUG", "raw_transport: timeout is %d", $service->{timeout});
157
158     while ($strikes--) {
159         alarm $service->{timeout};
160         $input = Sip::read_SIP_packet(*STDIN);
161         alarm 0;
162
163         if (!$input) {
164             # EOF on the socket
165             syslog("LOG_INFO", "raw_transport: shutting down: EOF during login");
166             return;
167         }
168         $input =~ s/[\r\n]+$//sm;       # Strip off trailing line terminator
169         last if Sip::MsgType::handle($input, $self, LOGIN);
170     }
171     };
172
173     if ($@) {
174         syslog("LOG_ERR", "raw_transport: LOGIN ERROR: '$@'");
175         die "raw_transport: login error (timeout? $@), exiting";
176     } elsif (!$self->{account}) {
177         syslog("LOG_ERR", "raw_transport: LOGIN FAILED");
178         die "raw_transport: Login failed (no account), exiting";
179     }
180
181     syslog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'",
182         $self->{account}->{id},
183         $self->{account}->{institution});
184
185     $self->sip_protocol_loop();
186
187     syslog("LOG_INFO", "raw_transport: shutting down");
188 }
189
190 sub telnet_transport {
191     my $self = shift;
192     my ($uid, $pwd);
193     my $strikes = 3;
194     my $account = undef;
195     my $input;
196     my $config = $self->{config};
197     my $timeout = $self->{service}->{timeout} || $config->{timeout} || 0;
198     syslog("LOG_DEBUG", "telnet_transport: timeout is %s", $timeout);
199
200     # Until the terminal has logged in, we don't trust it
201     # so use a timeout to protect ourselves from hanging.
202     eval {
203     local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n";; };
204     local $| = 1;                       # Unbuffered output
205
206     while ($strikes--) {
207         print "login: ";
208         alarm $timeout;
209         $uid = <STDIN>;
210         alarm 0;
211
212         print "password: ";
213         alarm $timeout;
214         $pwd = <STDIN>;
215         alarm 0;
216
217         $uid =~ s/[\r\n]+$//;
218         $pwd =~ s/[\r\n]+$//;
219
220         if (exists($config->{accounts}->{$uid})
221         && ($pwd eq $config->{accounts}->{$uid}->password())) {
222             $account = $config->{accounts}->{$uid};
223             last;
224         } else {
225             syslog("LOG_WARNING", "Invalid login attempt: '%s'", $uid);
226             print("Invalid login$CRLF");
227         }
228     }
229     }; # End of eval
230
231     if ($@) {
232         syslog("LOG_ERR", "telnet_transport: Login timed out");
233         die "Telnet Login Timed out";
234     } elsif (!defined($account)) {
235         syslog("LOG_ERR", "telnet_transport: Login Failed");
236         die "Login Failure";
237     } else {
238         print "Login OK.  Initiating SIP$CRLF";
239     }
240
241     $self->{account} = $account;
242     syslog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution});
243     $self->sip_protocol_loop();
244     syslog("LOG_INFO", "telnet_transport: shutting down");
245 }
246
247
248 sub http_transport {
249 }
250
251 #
252 # The terminal has logged in, using either the SIP login process
253 # over a raw socket, or via the pseudo-unix login provided by the
254 # telnet transport.  From that point on, both the raw and the telnet
255 # processes are the same:
256 sub sip_protocol_loop {
257     my $self = shift;
258     my $expect;
259     my $service = $self->{service};
260     my $config  = $self->{config};
261     my $input;
262
263     # Now that the terminal has logged in, the first message
264     # we recieve must be an SC_STATUS message.  But it might be
265     # an SC_REQUEST_RESEND.  So, as long as we keep receiving
266     # SC_REQUEST_RESEND, we keep waiting for an SC_STATUS
267
268     # Comprise reports that no other ILS actually enforces this
269     # constraint, so we'll relax about it too.  As long as everybody
270     # uses the SIP "raw" login process, rather than telnet, this
271     # will be fine, becaues the LOGIN protocol exchange will force
272     # us into SIP 2.00 anyway.  Machines that want to log in using
273     # telnet MUST send an SC Status message first, even though we're
274     # not enforcing it.
275     # 
276     #$expect = SC_STATUS;
277     $expect = '';
278
279     while ( $input = Sip::read_SIP_packet(*STDIN) ) {
280         $input =~ s/[\r\n]+$//sm;    # Strip off any trailing line ends
281
282         my $status = Sip::MsgType::handle($input, $self, $expect);
283         next if $status eq REQUEST_ACS_RESEND;
284
285         if (!$status) {
286             syslog("LOG_ERR", "raw_transport: failed to handle %s", substr($input,0,2));
287             die "sip_protocol_loop: failed Sip::MsgType::handle('$input', $self, '$expect')";
288         }
289         elsif ($expect && ($status ne $expect)) {
290             # We received a non-"RESEND" that wasn't what we were expecting.
291             syslog("LOG_ERR", "raw_transport: expected %s, received %s, exiting", $expect, $input);
292             die "sip_protocol_loop: exiting: expected '$expect', received '$status'";
293         }
294
295         # We successfully received and processed what we were expecting
296         $expect = '';
297     }
298 }