Bug 28606: Remove $DEBUG and $ENV{DEBUG}
[srvgit] / C4 / SIP / Sip / Checksum.pm
1 package C4::SIP::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
10 sub checksum {
11     my $pkt = shift;
12     return (-unpack('%16C*', $pkt) & 0xFFFF);
13 }
14
15 sub verify_cksum {
16     my $pkt = shift;
17     my $cksum;
18     my $shortsum;
19
20     unless ($pkt =~ /AZ(....)$/) {
21                 warn "verify_cksum: no sum detected";
22                 return 0; # No checksum at end
23         }
24     # return 0 if (substr($pkt, -6, 2) ne "AZ");
25
26     # Convert the checksum back to hex and calculate the sum of the
27     # pack without the checksum.
28     $cksum = hex($1);
29     $shortsum = unpack("%16C*", substr($pkt, 0, -4));
30
31     # The checksum is valid if the hex sum, plus the checksum of the 
32     # base packet short when truncated to 16 bits.
33     return (($cksum + $shortsum) & 0xFFFF) == 0;
34 }
35
36 1;
37 __END__
38
39 #
40 # Some simple test data
41 #
42 sub test {
43     my $testpkt = shift;
44     my $cksum = checksum($testpkt);
45     my $fullpkt = sprintf("%s%4X", $testpkt, $cksum);
46
47     print $fullpkt, "\n";
48 }
49
50 while (<>) {
51     chomp;
52     test($_);
53 }
54
55 1;