]> git.evergreen-ils.org Git - working/SIPServer.git/blob - Sip.pm
Return proper renewal OK field on checkout fail
[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 $VERSION = 0.02;
39 our @ISA = qw(Exporter);
40
41 our @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count
42                     denied sipbool boolspace write_msg read_SIP_packet
43                     $error_detection $protocol_version $field_delimiter
44                     $last_response);
45
46 our %EXPORT_TAGS = (
47                     all => [qw(y_or_n timestamp add_field maybe_add
48                                add_count denied sipbool boolspace write_msg
49                                read_SIP_packet
50                                $error_detection $protocol_version
51                                $field_delimiter $last_response)]);
52
53
54 our $error_detection = 0;
55 our $protocol_version = 1;
56 our $field_delimiter = '|';     # Protocol Default
57
58 # We need to keep a copy of the last message we sent to the SC,
59 # in case there's a transmission error and the SC sends us a
60 # REQUEST_ACS_RESEND.  If we receive a REQUEST_ACS_RESEND before
61 # we've ever sent anything, then we are to respond with a
62 # REQUEST_SC_RESEND (p.16)
63
64 our $last_response = '';
65
66 sub timestamp {
67     my $time = $_[0] || time();
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 #    NOTE: if zero is a valid value for your field, don't use maybe_add!
100 #
101 sub maybe_add {
102     my ($fid, $value) = @_;
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     return boolspace(!$bool);
140 }
141
142 sub sipbool {
143     my $bool = shift;
144     return $bool ? 'Y' : 'N';
145 }
146
147 #
148 # boolspace: ' ' is false, 'Y' is true. (don't ask)
149 #
150 sub boolspace {
151     my $bool = shift;
152     return $bool ? 'Y' : ' ';
153 }
154
155
156 # read_SIP_packet($file)
157 #
158 # Read a packet from $file, using the correct record separator
159 #
160 sub read_SIP_packet {
161     my $record;
162     my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
163     my $len1 = 999;
164
165     # local $/ = "\r";      # don't need any of these here.  use whatever the prevailing $/ is.
166     local $/ = "\015";    # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
167     {    # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
168         for ( my $tries = 1 ; $tries <= 3 ; $tries++ ) {
169             undef $!;
170             $record = decode_utf8(readline($fh));
171             if ( defined($record) ) {
172                 while ( chomp($record) ) { 1; }
173                 $len1 = length($record);
174                 syslog( "LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'" );
175                 $record =~ s/^\s*[^A-z0-9]+//s; # Every line must start with a "real" character.  Not whitespace, control chars, etc. 
176                 $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 |||
177                 $record =~ s/\015?\012//g;      # Extra line breaks must die
178                 $record =~ s/\015?\012//s;      # Extra line breaks must die
179                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
180                 while ( chomp($record) ) { 1; }
181
182                 $record and last;    # success
183             } else {
184                 if ($!) {
185                     syslog( "LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $! $@" );
186                     # die "read_SIP_packet ERROR: $!";
187                     warn "read_SIP_packet ERROR: $! $@";
188                 }
189             }
190         }
191     }
192     if ($record) {
193         my $len2 = length($record);
194         syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
195         ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
196     } else {
197         syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record) ? "empty ($record)" : 'undefined'));
198     }
199     #
200     # Cen-Tec self-check terminals transmit '\r\n' line terminators.
201     # This is actually very hard to deal with in perl in a reasonable
202     # since every OTHER piece of hardware out there gets the protocol
203     # right.
204     # 
205     # The incorrect line terminator presents as a \r at the end of the
206     # first record, and then a \n at the BEGINNING of the next record.
207     # So, the simplest thing to do is just throw away a leading newline
208     # on the input.
209     #  
210     # This is now handled by the vigorous cleansing above.
211     syslog("LOG_INFO", encode_utf8("INPUT MSG: '$record'")) if $record;
212     return encode_utf8($record);
213 }
214
215 #
216 # write_msg($msg, $file)
217 #
218 # Send $msg to the SC.  If error detection is active, then
219 # add the sequence number (if $seqno is non-zero) and checksum
220 # to the message, and save the whole thing as $last_response
221 #
222 # If $file is set, then it's a file handle: write to it, otherwise
223 # just write to the default destination.
224 #
225
226 sub write_msg {
227     my ($self, $msg, $file) = @_;
228
229     if ($error_detection) {
230         if (defined($self->{seqno})) {
231             $msg .= 'AY' . $self->{seqno};
232         }
233         $msg .= 'AZ';
234         $msg .= checksum($msg);
235     }
236
237
238     if ($file) {
239         print $file "$msg\r";
240     } else {
241         print "$msg\r";
242         syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
243     }
244
245     $last_response = $msg;
246 }
247
248 1;