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