2 # Copyright (C) 2006-2008 Georgia Public Library Service
4 # Author: David J. Fiander
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.
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.
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/>.
19 # Sip.pm: General Sip utility functions
29 use Unicode::Normalize;
31 use Sys::Syslog qw(syslog);
32 use POSIX qw(strftime);
35 use Sip::Constants qw(SIP_DATETIME);
36 use Sip::Checksum qw(checksum);
39 our @ISA = qw(Exporter);
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
47 all => [qw(y_or_n timestamp add_field maybe_add
48 add_count denied sipbool boolspace write_msg
50 $error_detection $protocol_version
51 $field_delimiter $last_response)]);
54 our $error_detection = 0;
55 our $protocol_version = 1;
56 our $field_delimiter = '|'; # Protocol Default
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)
64 our $last_response = '';
67 my $time = $_[0] || time();
68 return strftime(SIP_DATETIME, localtime($time));
72 # add_field(field_id, value)
73 # return constructed field value
76 my ($field_id, $value) = @_;
79 if (!defined($value)) {
80 syslog("LOG_DEBUG", "add_field: Undefined value being added to '%s'",
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));
89 while (($i = index($value, $field_delimiter)) != ($[-1)) {
90 substr($value, $i, 1) = $ent;
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);
100 return $field_id . $value . $field_delimiter;
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!
109 my ($fid, $value) = @_;
110 return (defined($value) && $value) ? add_field($fid, $value) : '';
114 # add_count() produce fixed four-character count field,
115 # or a string of four spaces if the count is invalid for some
119 my ($label, $count) = @_;
121 # If the field is unsupported, it will be undef, return blanks
123 if (!defined($count)) {
127 $count = sprintf("%04d", $count);
128 if (length($count) != 4) {
129 syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
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.
146 return boolspace(!$bool);
151 return $bool ? 'Y' : 'N';
155 # boolspace: ' ' is false, 'Y' is true. (don't ask)
159 return $bool ? 'Y' : ' ';
163 # read_SIP_packet($file)
165 # Read a packet from $file, using the correct record separator
167 sub read_SIP_packet {
169 my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
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++ ) {
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; }
189 $record and last; # success
192 syslog( "LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $! $@" );
193 # die "read_SIP_packet ERROR: $!";
194 warn "read_SIP_packet ERROR: $! $@";
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);
204 syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record) ? "empty ($record)" : 'undefined'));
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
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
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);
223 # write_msg($msg, $file, $encoding)
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
229 # If $file is set, then it's a file handle: write to it, otherwise
230 # just write to the default destination.
232 # If encoding is set, the message will be encoded to that encoding.
236 my ($self, $msg, $file, $encoding) = @_;
239 # Use nomalization form D, because some conversion blow up
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.
248 # Stripping the combining characters converts ""béè♁ts"
249 # into "bee?ts" instead of "b???ts" - better, eh?
252 $msg = encode($encoding, $msg);
254 # Send an UTF-8 string. This makes the length call, below
255 # succeed and fixes LP 1628995.
256 $msg = encode_utf8($msg);
259 if ($error_detection) {
260 if (defined($self->{seqno})) {
261 $msg .= 'AY' . $self->{seqno};
264 $msg .= checksum($msg);
267 my $outmsg = "$msg\r";
272 my $rv = POSIX::write(fileno(STDOUT), $outmsg, length($outmsg));
273 syslog("LOG_ERR", "Error writing to STDOUT $!") unless $rv;
276 syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
277 $last_response = $msg;