Debug output capability
[sitka/SIPServer.git] / Sip / Checksum.pm
CommitLineData
d19d5be0 1#
2# Copyright (C) 2006-2008 Georgia Public Library Service
3#
4# Author: David J. Fiander
5#
6# This program is free software; you can redistribute it and/or
7# modify it under the terms of version 2 of the GNU General Public
8# License as published by the Free Software Foundation.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public
16# License along with this program; if not, write to the Free
17# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
18# MA 02111-1307 USA
19
20package Sip::Checksum;
21
22use Exporter;
23use strict;
24use warnings;
25
26our @ISA = qw(Exporter);
27our @EXPORT_OK = qw(checksum verify_cksum);
28
29sub checksum {
30 my $pkt = shift;
d19d5be0 31 return (-unpack('%16C*', $pkt) & 0xFFFF);
32}
33
34sub verify_cksum {
35 my $pkt = shift;
36 my $cksum;
37 my $shortsum;
38
39 return 0 if (substr($pkt, -6, 2) ne "AZ"); # No checksum at end
40
41 # Convert the checksum back to hex and calculate the sum of the
42 # pack without the checksum.
43 $cksum = hex(substr($pkt, -4));
44 $shortsum = unpack("%16C*", substr($pkt, 0, -4));
45
46 # The checksum is valid if the hex sum, plus the checksum of the
47 # base packet short when truncated to 16 bits.
48 return (($cksum + $shortsum) & 0xFFFF) == 0;
49}
50
29ae5acf
JA
511;
52
d19d5be0 53__END__
54
55#
56# Some simple test data
57#
58sub test {
59 my $testpkt = shift;
60 my $cksum = checksum($testpkt);
61 my $fullpkt = sprintf("%s%4X", $testpkt, $cksum);
62
63 print $fullpkt, "\n";
64}
65
66while (<>) {
67 chomp;
68 test($_);
69}