Bug 8216: Allow SIP modules to pass critic tests
[koha.git] / C4 / SIP / Sip / Checksum.pm
1 package Sip::Checksum;
2
3 use Exporter;
4 use strict;
5 use warnings;
6
7 our @ISA = qw(Exporter);
8 our @EXPORT_OK = qw(checksum verify_cksum);
9 our $debug = 0;
10
11 sub checksum {
12     my $pkt = shift;
13     return (-unpack('%16C*', $pkt) & 0xFFFF);
14 }
15
16 sub verify_cksum {
17     my $pkt = shift;
18     my $cksum;
19     my $shortsum;
20
21         if ($pkt =~ /AZ(....)$/) {
22                 $debug and warn "verify_cksum: sum ($1) detected";
23         } else {
24                 warn "verify_cksum: no sum detected";
25                 return 0; # No checksum at end
26         }
27     # return 0 if (substr($pkt, -6, 2) ne "AZ");
28
29     # Convert the checksum back to hex and calculate the sum of the
30     # pack without the checksum.
31     $cksum = hex($1);
32     $shortsum = unpack("%16C*", substr($pkt, 0, -4));
33
34     # The checksum is valid if the hex sum, plus the checksum of the 
35     # base packet short when truncated to 16 bits.
36     return (($cksum + $shortsum) & 0xFFFF) == 0;
37 }
38
39 1;
40 __END__
41
42 #
43 # Some simple test data
44 #
45 sub test {
46     my $testpkt = shift;
47     my $cksum = checksum($testpkt);
48     my $fullpkt = sprintf("%s%4X", $testpkt, $cksum);
49
50     print $fullpkt, "\n";
51 }
52
53 while (<>) {
54     chomp;
55     test($_);
56 }
57
58 1;