Bug 2653 Protect against sending End of Message in Text
[koha-ffzg.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     return strftime(SIP_DATETIME, localtime($time));
53 }
54
55 #
56 # add_field(field_id, value)
57 #    return constructed field value
58 #
59 sub add_field {
60     my ($field_id, $value) = @_;
61     my ($i, $ent);
62
63     if (!defined($value)) {
64         syslog("LOG_DEBUG", "add_field: Undefined value being added to '%s'",
65                $field_id);
66                 $value = '';
67     }
68     $value=~s/\r/ /g; # CR terminates a sip message
69                       # Protect against them in sip text fields
70
71     # Replace any occurences of the field delimiter in the
72     # field value with the HTML character entity
73     $ent = sprintf("&#%d;", ord($field_delimiter));
74
75     while (($i = index($value, $field_delimiter)) != ($[-1)) {
76                 substr($value, $i, 1) = $ent;
77     }
78
79     return $field_id . $value . $field_delimiter;
80 }
81 #
82 # maybe_add(field_id, value):
83 #    If value is defined and non-empty, then return the
84 #    constructed field value, otherwise return the empty string
85 #
86 sub maybe_add {
87     my ($fid, $value) = @_;
88     return (defined($value) && $value) ? add_field($fid, $value) : '';
89 }
90
91 #
92 # add_count()  produce fixed four-character count field,
93 # or a string of four spaces if the count is invalid for some
94 # reason
95 #
96 sub add_count {
97     my ($label, $count) = @_;
98
99     # If the field is unsupported, it will be undef, return blanks
100     # as per the spec.
101     if (!defined($count)) {
102                 return ' ' x 4;
103     }
104
105     $count = sprintf("%04d", $count);
106     if (length($count) != 4) {
107                 syslog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'",
108                $label, $count);
109                 $count = ' ' x 4;
110     }
111     return $count;
112 }
113
114 #
115 # denied($bool)
116 # if $bool is false, return true.  This is because SIP statuses
117 # are inverted:  we report that something has been denied, not that
118 # it's permitted.  For example, 'renewal priv. denied' of 'Y' means
119 # that the user's not permitted to renew.  I assume that the ILS has
120 # real positive tests.
121 #
122 sub denied {
123     my $bool = shift;
124     return boolspace(!$bool);
125 }
126
127 sub sipbool {
128     my $bool = shift;
129     return $bool ? 'Y' : 'N';
130 }
131
132 #
133 # boolspace: ' ' is false, 'Y' is true. (don't ask)
134 #
135 sub boolspace {
136     my $bool = shift;
137     return $bool ? 'Y' : ' ';
138 }
139
140
141 # Read a packet from $file, using the correct record separator
142 #
143 sub read_SIP_packet {
144     my $record;
145         my $fh = shift or syslog("LOG_ERR", "read_SIP_packet: no filehandle argument!");
146         my $len1 = 999;
147         # local $/ = "\012";    # Internet Record Separator (lax version)
148         {               # adapted from http://perldoc.perl.org/5.8.8/functions/readline.html
149                 for (my $tries=1; $tries<=3; $tries++) {
150                         undef $!;
151                         $record = readline($fh);
152                         if (defined($record)) {
153                                 while(chomp($record)){1;}
154                                 $len1 = length($record);
155                                 syslog("LOG_DEBUG", "read_SIP_packet, INPUT MSG: '$record'");
156                                 $record =~ s/^\s*[^A-z0-9]+//s;
157                                 $record =~ s/[^A-z0-9]+$//s;
158                                 $record =~ s/\015?\012//g;
159                                 $record =~ s/\015?\012//s;
160                                 $record =~ s/\015*\012*$//s;    # treat as one line to include the extra linebreaks we are trying to remove!
161                                 while(chomp($record)){1;}
162                                 if ($record) {
163                                         last;   # success
164                                 }
165                         } else {
166                                 if ($!) {
167                                 syslog("LOG_DEBUG", "read_SIP_packet (try #$tries) ERROR: $!");
168                                         # die "read_SIP_packet ERROR: $!";
169                                         warn "read_SIP_packet ERROR: $!";
170                                 }
171                         }
172                 }
173         }
174         if ($record) {
175                 my $len2 = length($record);
176                 syslog("LOG_INFO", "read_SIP_packet, INPUT MSG: '$record'") if $record;
177                 ($len1 != $len2) and syslog("LOG_DEBUG", "read_SIP_packet, trimmed %s character(s) (after chomps).", $len1-$len2);
178         } else {
179                 syslog("LOG_WARNING", "read_SIP_packet input %s, end of input.", (defined($record)? "empty ($record)" : 'undefined')); 
180         }
181     return $record;
182 }
183
184 #
185 # write_msg($msg, $file)
186 #
187 # Send $msg to the SC.  If error detection is active, then
188 # add the sequence number (if $seqno is non-zero) and checksum
189 # to the message, and save the whole thing as $last_response
190 #
191 # If $file is set, then it's a file handle: write to it, otherwise
192 # just write to the default destination.
193 #
194
195 sub write_msg {
196     my ($self, $msg, $file) = @_;
197     my $cksum;
198
199     if ($error_detection) {
200                 if (defined($self->{seqno})) {
201                     $msg .= 'AY' . $self->{seqno};
202                 }
203                 $msg .= 'AZ';
204                 $cksum = checksum($msg);
205                 $msg .= sprintf('%04.4X', $cksum);
206     }
207
208     if ($file) {
209                 print $file "$msg$CRLF";
210                 syslog("LOG_DEBUG", "write_msg outputting to $file");
211     } else {
212                 print "$msg$CRLF";
213     }
214         syslog("LOG_INFO", "OUTPUT MSG: '$msg'");
215
216     $last_response = $msg;
217 }
218
219 1;