]> git.evergreen-ils.org Git - working/SIPServer.git/blob - Sip.pm
LP1528301: (follow-up) tweak whitespace
[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 use Unicode::Normalize;
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     # SIP2 Protocol document specifies that variable fields are from 0
94     # to 255 characters in length.  We'll do a check of the field
95     # length and truncate if necessary.
96     if (length($value) > 255) {
97         $value = substr($value, 0, 255);
98     }
99
100     return $field_id . $value . $field_delimiter;
101 }
102 #
103 # maybe_add(field_id, value):
104 #    If value is defined and non-empty, then return the
105 #    constructed field value, otherwise return the empty string.
106 #    NOTE: if zero is a valid value for your field, don't use maybe_add!
107 #
108 sub maybe_add {
109     my ($fid, $value) = @_;
110     return (defined($value) && $value) ? add_field($fid, $value) : '';
111 }
112
113 #
114 # add_count()  produce fixed four-character count field,
115 # or a string of four spaces if the count is invalid for some
116 # reason
117 #
118 sub add_count {
119     my ($label, $count) = @_;
120
121     # If the field is unsupported, it will be undef, return blanks
122     # as per the spec.
123     if (!defined($count)) {
124         return ' ' x 4;
125     }
126
127     $count = sprintf("%04d", $count);
128     if (length($count) != 4) {
129         syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
130                $label, $count);
131         $count = ' ' x 4;
132     }
133     return $count;
134 }
135
136 #
137 # denied($bool)
138 # if $bool is false, return true.  This is because SIP statuses
139 # are inverted:  we report that something has been denied, not that
140 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
141 # that the user's not permitted to renew.  I assume that the ILS has
142 # real positive tests.
143 #
144 sub denied {
145     my $bool = shift;
146     return boolspace(!$bool);
147 }
148
149 sub sipbool {
150     my $bool = shift;
151     return $bool ? 'Y' : 'N';
152 }
153
154 #
155 # boolspace: ' ' is false, 'Y' is true. (don't ask)
156 #
157 sub boolspace {
158     my $bool = shift;
159     return $bool ? 'Y' : ' ';
160 }
161
162
163 # read_SIP_packet($file)
164 #
165 # Read a packet from $file, using the correct record separator
166 #
167 sub read_SIP_packet {
168     my $record;
169     my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
170     my $len1 = 999;
171
172     # local $/ = "\r";      # don't need any of these here.  use whatever the prevailing $/ is.
173     local $/ = "\015";    # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
174     {    # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
175         for ( my $tries = 1 ; $tries <= 3 ; $tries++ ) {
176             undef $!;
177             $record = decode_utf8(readline($fh));
178             if ( defined($record) ) {
179                 while ( chomp($record) ) { 1; }
180                 $len1 = length($record);
181                 syslog( "LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'" );
182                 $record =~ s/^\s*[^A-z0-9]+//s; # Every line must start with a "real" character.  Not whitespace, control chars, etc. 
183                 $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 |||
184                 $record =~ s/\015?\012//g;      # Extra line breaks must die
185                 $record =~ s/\015?\012//s;      # Extra line breaks must die
186                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
187                 while ( chomp($record) ) { 1; }
188
189                 $record and last;    # success
190             } else {
191                 if ($!) {
192                     syslog( "LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $! $@" );
193                     # die "read_SIP_packet ERROR: $!";
194                     warn "read_SIP_packet ERROR: $! $@";
195                 }
196             }
197         }
198     }
199     if ($record) {
200         my $len2 = length($record);
201         syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
202         ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
203     } else {
204         syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record) ? "empty ($record)" : 'undefined'));
205     }
206     #
207     # Cen-Tec self-check terminals transmit '\r\n' line terminators.
208     # This is actually very hard to deal with in perl in a reasonable
209     # since every OTHER piece of hardware out there gets the protocol
210     # right.
211     # 
212     # The incorrect line terminator presents as a \r at the end of the
213     # first record, and then a \n at the BEGINNING of the next record.
214     # So, the simplest thing to do is just throw away a leading newline
215     # on the input.
216     #  
217     # This is now handled by the vigorous cleansing above.
218     syslog("LOG_INFO", encode_utf8("INPUT MSG: '$record'")) if $record;
219     return encode_utf8($record);
220 }
221
222 #
223 # write_msg($msg, $file, $encoding)
224 #
225 # Send $msg to the SC.  If error detection is active, then
226 # add the sequence number (if $seqno is non-zero) and checksum
227 # to the message, and save the whole thing as $last_response
228 #
229 # If $file is set, then it's a file handle: write to it, otherwise
230 # just write to the default destination.
231 #
232 # If encoding is set, the message will be encoded to that encoding.
233 #
234
235 sub write_msg {
236     my ($self, $msg, $file, $encoding) = @_;
237
238     if ($encoding) {
239         # Use nomalization form D, because some conversion blow up
240         # without it.
241         $msg = NFD($msg);
242         if ($encoding eq 'ascii') {
243             # Try to maintain a reasonable version of the content by
244             # stripping diacritics from the text, given that the SIP client
245             # wants just plain ASCII. This is the base requirement according
246             # to the SIP2 specification.
247
248             # Stripping the combining characters converts ""béè♁ts"
249             # into "bee?ts" instead of "b???ts" - better, eh?
250             $msg =~ s/\pM+//og;
251         }
252         $msg = encode($encoding, $msg);
253     } else {
254         # Send an UTF-8 string.  This makes the length call, below
255         # succeed and fixes LP 1628995.
256         $msg = encode_utf8($msg);
257     }
258
259     if ($error_detection) {
260         if (defined($self->{seqno})) {
261             $msg .= 'AY' . $self->{seqno};
262         }
263         $msg .= 'AZ';
264         $msg .= checksum($msg);
265     }
266
267     my $outmsg = "$msg\r";
268
269     if ($file) {
270         print $file $outmsg;
271     } else {
272         my $rv = POSIX::write(fileno(STDOUT), $outmsg, length($outmsg));
273         syslog("LOG_ERR", "Error writing to STDOUT $!") unless $rv;
274     }
275
276     syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
277     $last_response = $msg;
278 }
279
280 1;