]> git.evergreen-ils.org Git - working/SIPServer.git/blob - Sip.pm
Avoid undef warning, provide lanuage failover to 000 (unknown/default)
[working/SIPServer.git] / Sip.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 # Sip.pm: General Sip utility functions
21 #
22
23 package Sip;
24
25 use strict;
26 use warnings;
27 use English;
28 use Exporter;
29 use Encode;
30
31 use Sys::Syslog qw(syslog);
32 use POSIX qw(strftime);
33 use Socket qw(:crlf);
34
35 use Sip::Constants qw(SIP_DATETIME);
36 use Sip::Checksum qw(checksum);
37
38 our @ISA = qw(Exporter);
39
40 our @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count
41                     denied sipbool boolspace write_msg read_SIP_packet
42                     $error_detection $protocol_version $field_delimiter
43                     $last_response);
44
45 our %EXPORT_TAGS = (
46                     all => [qw(y_or_n timestamp add_field maybe_add
47                                add_count denied sipbool boolspace write_msg
48                                read_SIP_packet
49                                $error_detection $protocol_version
50                                $field_delimiter $last_response)]);
51
52
53 our $error_detection = 0;
54 our $protocol_version = 1;
55 our $field_delimiter = '|';     # Protocol Default
56
57 # We need to keep a copy of the last message we sent to the SC,
58 # in case there's a transmission error and the SC sends us a
59 # REQUEST_ACS_RESEND.  If we receive a REQUEST_ACS_RESEND before
60 # we've ever sent anything, then we are to respond with a
61 # REQUEST_SC_RESEND (p.16)
62
63 our $last_response = '';
64
65 sub timestamp {
66     my $time = $_[0] || time();
67
68     return strftime(SIP_DATETIME, localtime($time));
69 }
70
71 #
72 # add_field(field_id, value)
73 #    return constructed field value
74 #
75 sub add_field {
76     my ($field_id, $value) = @_;
77     my ($i, $ent);
78
79     if (!defined($value)) {
80         syslog("LOG_DEBUG", "add_field: Undefined value being added to '%s'",
81                $field_id);
82         $value = '';
83     }
84
85     # Replace any occurences of the field delimiter in the
86     # field value with the HTML character entity
87     $ent = sprintf("&#%d;", ord($field_delimiter));
88
89     while (($i = index($value, $field_delimiter)) != ($[-1)) {
90         substr($value, $i, 1) = $ent;
91     }
92
93     return $field_id . $value . $field_delimiter;
94 }
95 #
96 # maybe_add(field_id, value):
97 #    If value is defined and non-empty, then return the
98 #    constructed field value, otherwise return the empty string
99 #
100 sub maybe_add {
101     my ($fid, $value) = @_;
102
103     return (defined($value) && $value) ? add_field($fid, $value) : '';
104 }
105
106 #
107 # add_count()  produce fixed four-character count field,
108 # or a string of four spaces if the count is invalid for some
109 # reason
110 #
111 sub add_count {
112     my ($label, $count) = @_;
113
114     # If the field is unsupported, it will be undef, return blanks
115     # as per the spec.
116     if (!defined($count)) {
117         return ' ' x 4;
118     }
119
120     $count = sprintf("%04d", $count);
121     if (length($count) != 4) {
122         syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
123                $label, $count);
124         $count = ' ' x 4;
125     }
126     return $count;
127 }
128
129 #
130 # denied($bool)
131 # if $bool is false, return true.  This is because SIP statuses
132 # are inverted:  we report that something has been denied, not that
133 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
134 # that the user's not permitted to renew.  I assume that the ILS has
135 # real positive tests.
136 #
137 sub denied {
138     my $bool = shift;
139
140     return boolspace(!$bool);
141 }
142
143 sub sipbool {
144     my $bool = shift;
145
146     return $bool ? 'Y' : 'N';
147 }
148
149 #
150 # boolspace: ' ' is false, 'Y' is true. (don't ask)
151 #
152 sub boolspace {
153     my $bool = shift;
154
155     return $bool ? 'Y' : ' ';
156 }
157
158
159 # read_SIP_packet($file)
160 #
161 # Read a packet from $file, using the correct record separator
162 #
163 sub read_SIP_packet {
164     my $record;
165     my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
166     my $len1 = 999;
167
168     # local $/ = "\r";      # don't need any of these here.  use whatever the prevailing $/ is.
169     # local $/ = "\012";    # Internet Record Separator (lax version)
170     {    # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
171         for ( my $tries = 1 ; $tries <= 3 ; $tries++ ) {
172             undef $!;
173             $record = readline($fh);
174             if ( defined($record) ) {
175                 while ( chomp($record) ) { 1; }
176                 $len1 = length($record);
177                 syslog( "LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'" );
178                 $record =~ s/^\s*[^A-z0-9]+//s; # Every line must start with a "real" character.  Not whitespace, control chars, etc. 
179                 $record =~ s/[^A-z0-9]+$//s;    # Same for the end.  Note this catches the problem some clients have sending empty fields at the end, like |||
180                 $record =~ s/\015?\012//g;      # Extra line breaks must die
181                 $record =~ s/\015?\012//s;      # Extra line breaks must die
182                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
183                 while ( chomp($record) ) { 1; }
184
185                 $record and last;    # success
186             } else {
187                 if ($!) {
188                     syslog( "LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $! $@" );
189                     # die "read_SIP_packet ERROR: $!";
190                     warn "read_SIP_packet ERROR: $! $@";
191                 }
192             }
193         }
194     }
195     if ($record) {
196         my $len2 = length($record);
197         syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
198         ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
199     } else {
200         syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record) ? "empty ($record)" : 'undefined'));
201     }
202     #
203     # Cen-Tec self-check terminals transmit '\r\n' line terminators.
204     # This is actually very hard to deal with in perl in a reasonable
205     # since every OTHER piece of hardware out there gets the protocol
206     # right.
207     # 
208     # The incorrect line terminator presents as a \r at the end of the
209     # first record, and then a \n at the BEGINNING of the next record.
210     # So, the simplest thing to do is just throw away a leading newline
211     # on the input.
212     #  
213     # This is now handled by the vigorous cleansing above.
214     syslog("LOG_INFO", encode_utf8("INPUT MSG: '$record'")) if $record;
215     return $record;
216 }
217
218 #
219 # write_msg($msg, $file)
220 #
221 # Send $msg to the SC.  If error detection is active, then
222 # add the sequence number (if $seqno is non-zero) and checksum
223 # to the message, and save the whole thing as $last_response
224 #
225 # If $file is set, then it's a file handle: write to it, otherwise
226 # just write to the default destination.
227 #
228
229 sub write_msg {
230     my ($self, $msg, $file) = @_;
231     my $cksum;
232
233     $msg = encode_utf8($msg);
234     if ($error_detection) {
235         if (defined($self->{seqno})) {
236             $msg .= 'AY' . $self->{seqno};
237         }
238         $msg .= 'AZ';
239         $cksum = checksum($msg);
240         $msg .= sprintf('%04.4X', $cksum);
241     }
242
243
244     if ($file) {
245         print $file "$msg$CRLF";
246     } else {
247         print "$msg$CRLF";
248         syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
249     }
250
251     $last_response = $msg;
252 }
253
254 1;