Merge remote branch 'kc/new/bug_4912' into kcmaster
[koha.git] / C4 / SIP / Sip.pm
1 #
2 # Sip.pm: General Sip utility functions
3 #
4
5 package Sip;
6
7 use strict;
8 use warnings;
9 use English;
10 use Exporter;
11
12 use Sys::Syslog qw(syslog);
13 use POSIX qw(strftime);
14 use Socket qw(:crlf);
15
16 use Sip::Constants qw(SIP_DATETIME);
17 use Sip::Checksum qw(checksum);
18
19 use vars qw($VERSION @ISA @EXPORT_OK %EXPORT_TAGS);
20
21 BEGIN {
22         $VERSION = 1.00;
23         @ISA = qw(Exporter);
24
25         @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count
26                     denied sipbool boolspace write_msg read_SIP_packet
27                     $error_detection $protocol_version $field_delimiter
28                     $last_response);
29
30         %EXPORT_TAGS = (
31                     all => [qw(y_or_n timestamp add_field maybe_add
32                                add_count denied sipbool boolspace write_msg
33                                read_SIP_packet
34                                $error_detection $protocol_version
35                                $field_delimiter $last_response)]);
36 }
37
38 our $error_detection = 0;
39 our $protocol_version = 1;
40 our $field_delimiter = '|';     # Protocol Default
41
42 # We need to keep a copy of the last message we sent to the SC,
43 # in case there's a transmission error and the SC sends us a
44 # REQUEST_ACS_RESEND.  If we receive a REQUEST_ACS_RESEND before
45 # we've ever sent anything, then we are to respond with a
46 # REQUEST_SC_RESEND (p.16)
47
48 our $last_response = '';
49
50 sub timestamp {
51     my $time = $_[0] || time();
52     if ($time=~m/^(\d{4})\-(\d{2})\-(\d{2})/) {
53         # passing a db returned date as is + bogus time
54         return sprintf( '%04d%02d%02d    235900', $1, $2, $3);
55     }
56     return strftime(SIP_DATETIME, localtime($time));
57 }
58
59 #
60 # add_field(field_id, value)
61 #    return constructed field value
62 #
63 sub add_field {
64     my ($field_id, $value) = @_;
65     my ($i, $ent);
66
67     if (!defined($value)) {
68         syslog("LOG_DEBUG", "add_field: Undefined value being added to '%s'",
69                $field_id);
70                 $value = '';
71     }
72     $value=~s/\r/ /g; # CR terminates a sip message
73                       # Protect against them in sip text fields
74
75     # Replace any occurences of the field delimiter in the
76     # field value with the HTML character entity
77     $ent = sprintf("&#%d;", ord($field_delimiter));
78
79     while (($i = index($value, $field_delimiter)) != ($[-1)) {
80                 substr($value, $i, 1) = $ent;
81     }
82
83     return $field_id . $value . $field_delimiter;
84 }
85 #
86 # maybe_add(field_id, value):
87 #    If value is defined and non-empty, then return the
88 #    constructed field value, otherwise return the empty string.
89 #    NOTE: if zero is a valid value for your field, don't use maybe_add!
90 #
91 sub maybe_add {
92     my ($fid, $value) = @_;
93     return (defined($value) && $value) ? add_field($fid, $value) : '';
94 }
95
96 #
97 # add_count()  produce fixed four-character count field,
98 # or a string of four spaces if the count is invalid for some
99 # reason
100 #
101 sub add_count {
102     my ($label, $count) = @_;
103
104     # If the field is unsupported, it will be undef, return blanks
105     # as per the spec.
106     if (!defined($count)) {
107                 return ' ' x 4;
108     }
109
110     $count = sprintf("%04d", $count);
111     if (length($count) != 4) {
112                 syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
113                $label, $count);
114                 $count = ' ' x 4;
115     }
116     return $count;
117 }
118
119 #
120 # denied($bool)
121 # if $bool is false, return true.  This is because SIP statuses
122 # are inverted:  we report that something has been denied, not that
123 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
124 # that the user's not permitted to renew.  I assume that the ILS has
125 # real positive tests.
126 #
127 sub denied {
128     my $bool = shift;
129     return boolspace(!$bool);
130 }
131
132 sub sipbool {
133     my $bool = shift;
134     return $bool ? 'Y' : 'N';
135 }
136
137 #
138 # boolspace: ' ' is false, 'Y' is true. (don't ask)
139 #
140 sub boolspace {
141     my $bool = shift;
142     return $bool ? 'Y' : ' ';
143 }
144
145
146 # read_SIP_packet($file)
147 #
148 # Read a packet from $file, using the correct record separator
149 #
150 sub read_SIP_packet {
151     my $record;
152     my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
153     my $len1 = 999;
154
155     # local $/ = "\r";      # don't need any of these here.  use whatever the prevailing $/ is.
156     local $/ = "\015";    # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return
157     {    # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
158         for ( my $tries = 1 ; $tries <= 3 ; $tries++ ) {
159             undef $!;
160             $record = readline($fh);
161             if ( defined($record) ) {
162                 while ( chomp($record) ) { 1; }
163                 $len1 = length($record);
164                 syslog( "LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'" );
165                 $record =~ s/^\s*[^A-z0-9]+//s; # Every line must start with a "real" character.  Not whitespace, control chars, etc. 
166                 $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 |||
167                 $record =~ s/\015?\012//g;      # Extra line breaks must die
168                 $record =~ s/\015?\012//s;      # Extra line breaks must die
169                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
170                 while ( chomp($record) ) { 1; }
171
172                 $record and last;    # success
173             } else {
174                 if ($!) {
175                     syslog( "LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $! $@" );
176                     # die "read_SIP_packet ERROR: $!";
177                     warn "read_SIP_packet ERROR: $! $@";
178                 }
179             }
180         }
181     }
182     if ($record) {
183         my $len2 = length($record);
184         syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
185         ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
186     } else {
187         syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record) ? "empty ($record)" : 'undefined'));
188     }
189     #
190     # Cen-Tec self-check terminals transmit '\r\n' line terminators.
191     # This is actually very hard to deal with in perl in a reasonable
192     # since every OTHER piece of hardware out there gets the protocol
193     # right.
194     # 
195     # The incorrect line terminator presents as a \r at the end of the
196     # first record, and then a \n at the BEGINNING of the next record.
197     # So, the simplest thing to do is just throw away a leading newline
198     # on the input.
199     #  
200     # This is now handled by the vigorous cleansing above.
201     # syslog("LOG_INFO", encode_utf8("INPUT MSG: '$record'")) if $record;
202     syslog("LOG_INFO", "INPUT MSG: '$record'") if $record;
203     return $record;
204 }
205
206 #
207 # write_msg($msg, $file)
208 #
209 # Send $msg to the SC.  If error detection is active, then
210 # add the sequence number (if $seqno is non-zero) and checksum
211 # to the message, and save the whole thing as $last_response
212 #
213 # If $file is set, then it's a file handle: write to it, otherwise
214 # just write to the default destination.
215 #
216
217 sub write_msg {
218     my ($self, $msg, $file) = @_;
219     my $cksum;
220
221     # $msg = encode_utf8($msg);
222     if ($error_detection) {
223         if (defined($self->{seqno})) {
224             $msg .= 'AY' . $self->{seqno};
225         }
226         $msg .= 'AZ';
227         $cksum = checksum($msg);
228         $msg .= sprintf('%04.4X', $cksum);
229     }
230
231
232     if ($file) {
233         print $file "$msg\r";
234     } else {
235         print "$msg\r";
236         syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
237     }
238
239     $last_response = $msg;
240 }
241
242 1;