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