]> git.evergreen-ils.org Git - working/SIPServer.git/blob - Sip.pm
LP#1613326 change UNIVERSAL::can import, style
[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 modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19 # Sip.pm: General Sip utility functions
20 #
21
22 package Sip;
23
24 use strict;
25 use warnings;
26 use English;
27 use Exporter;
28 use Encode;
29
30 use Sys::Syslog qw(syslog);
31 use POSIX qw(strftime);
32 use Socket qw(:crlf);
33
34 use Sip::Constants qw(SIP_DATETIME);
35 use Sip::Checksum qw(checksum);
36
37 our $VERSION = 0.02;
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     # SIP2 Protocol document specifies that variable fields are from 0
93     # to 255 characters in length.  We'll do a check of the field
94     # length and truncate if necessary.
95     if (length($value) > 255) {
96         $value = substr($value, 0, 255);
97     }
98
99     return $field_id . $value . $field_delimiter;
100 }
101 #
102 # maybe_add(field_id, value):
103 #    If value is defined and non-empty, then return the
104 #    constructed field value, otherwise return the empty string.
105 #    NOTE: if zero is a valid value for your field, don't use maybe_add!
106 #
107 sub maybe_add {
108     my ($fid, $value) = @_;
109     return (defined($value) && $value) ? add_field($fid, $value) : '';
110 }
111
112 #
113 # add_count()  produce fixed four-character count field,
114 # or a string of four spaces if the count is invalid for some
115 # reason
116 #
117 sub add_count {
118     my ($label, $count) = @_;
119
120     # If the field is unsupported, it will be undef, return blanks
121     # as per the spec.
122     if (!defined($count)) {
123         return ' ' x 4;
124     }
125
126     $count = sprintf("%04d", $count);
127     if (length($count) != 4) {
128         syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
129                $label, $count);
130         $count = ' ' x 4;
131     }
132     return $count;
133 }
134
135 #
136 # denied($bool)
137 # if $bool is false, return true.  This is because SIP statuses
138 # are inverted:  we report that something has been denied, not that
139 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
140 # that the user's not permitted to renew.  I assume that the ILS has
141 # real positive tests.
142 #
143 sub denied {
144     my $bool = shift;
145     return boolspace(!$bool);
146 }
147
148 sub sipbool {
149     my $bool = shift;
150     return $bool ? 'Y' : 'N';
151 }
152
153 #
154 # boolspace: ' ' is false, 'Y' is true. (don't ask)
155 #
156 sub boolspace {
157     my $bool = shift;
158     return $bool ? 'Y' : ' ';
159 }
160
161
162 # read_SIP_packet($file)
163 #
164 # Read a packet from $file, using the correct record separator
165 #
166 sub read_SIP_packet {
167     my $record;
168     my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
169     my $len1 = 999;
170
171     # local $/ = "\r";      # don't need any of these here.  use whatever the prevailing $/ is.
172     local $/ = "\015";    # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
173     {    # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
174         for ( my $tries = 1 ; $tries <= 3 ; $tries++ ) {
175             undef $!;
176             $record = decode_utf8(readline($fh));
177             if ( defined($record) ) {
178                 while ( chomp($record) ) { 1; }
179                 $len1 = length($record);
180                 syslog( "LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'" );
181                 $record =~ s/^\s*[^A-z0-9]+//s; # Every line must start with a "real" character.  Not whitespace, control chars, etc. 
182                 $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 |||
183                 $record =~ s/\015?\012//g;      # Extra line breaks must die
184                 $record =~ s/\015?\012//s;      # Extra line breaks must die
185                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
186                 while ( chomp($record) ) { 1; }
187
188                 $record and last;    # success
189             } else {
190                 if ($!) {
191                     syslog( "LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $! $@" );
192                     # die "read_SIP_packet ERROR: $!";
193                     warn "read_SIP_packet ERROR: $! $@";
194                 }
195             }
196         }
197     }
198     if ($record) {
199         my $len2 = length($record);
200         syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
201         ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
202     } else {
203         syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record) ? "empty ($record)" : 'undefined'));
204     }
205     #
206     # Cen-Tec self-check terminals transmit '\r\n' line terminators.
207     # This is actually very hard to deal with in perl in a reasonable
208     # since every OTHER piece of hardware out there gets the protocol
209     # right.
210     # 
211     # The incorrect line terminator presents as a \r at the end of the
212     # first record, and then a \n at the BEGINNING of the next record.
213     # So, the simplest thing to do is just throw away a leading newline
214     # on the input.
215     #  
216     # This is now handled by the vigorous cleansing above.
217     syslog("LOG_INFO", encode_utf8("INPUT MSG: '$record'")) if $record;
218     return encode_utf8($record);
219 }
220
221 #
222 # write_msg($msg, $file)
223 #
224 # Send $msg to the SC.  If error detection is active, then
225 # add the sequence number (if $seqno is non-zero) and checksum
226 # to the message, and save the whole thing as $last_response
227 #
228 # If $file is set, then it's a file handle: write to it, otherwise
229 # just write to the default destination.
230 #
231
232 sub write_msg {
233     my ($self, $msg, $file) = @_;
234
235     if ($error_detection) {
236         if (defined($self->{seqno})) {
237             $msg .= 'AY' . $self->{seqno};
238         }
239         $msg .= 'AZ';
240         $msg .= checksum($msg);
241     }
242
243     my $outmsg = "$msg\r";
244
245     if ($file) {
246         print $file $outmsg;
247     } else {
248         my $rv = POSIX::write(fileno(STDOUT), $outmsg, length($outmsg));
249         syslog("LOG_ERR", "Error writing to STDOUT $!") unless $rv;
250     }
251
252     syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
253     $last_response = $msg;
254 }
255
256 1;