File Coverage

File:C4/SIP/Sip.pm
Coverage:32.6%

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