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