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