1 /* -*- mode: c; c-file-style: "openbsd" -*- */
2 /*
3  * Copyright (c) 2009 Vincent Bernat <bernat@luffy.cx>
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include "lldpd.h"
19 
20 /**
21  * Compute the checksum as 16-bit word.
22  */
23 u_int16_t
frame_checksum(const u_char * cp,int len,int cisco)24 frame_checksum(const u_char *cp, int len, int cisco)
25 {
26 	unsigned int sum = 0, v = 0;
27 	int oddbyte = 0;
28 
29 	while ((len -= 2) >= 0) {
30 		sum += *cp++ << 8;
31 		sum += *cp++;
32 	}
33 	if ((oddbyte = len & 1) != 0)
34 		v = *cp;
35 
36 	/* The remaining byte seems to be handled oddly by Cisco. From function
37 	 * dissect_cdp() in wireshark. 2014/6/14,zhengy@yealink.com:
38 	 *
39 	 * CDP doesn't adhere to RFC 1071 section 2. (B). It incorrectly assumes
40 	 * checksums are calculated on a big endian platform, therefore i.s.o.
41 	 * padding odd sized data with a zero byte _at the end_ it sets the last
42 	 * big endian _word_ to contain the last network _octet_. This byteswap
43 	 * has to be done on the last octet of network data before feeding it to
44 	 * the Internet checksum routine.
45 	 * CDP checksumming code has a bug in the addition of this last _word_
46 	 * as a signed number into the long word intermediate checksum. When
47 	 * reducing this long to word size checksum an off-by-one error can be
48 	 * made. This off-by-one error is compensated for in the last _word_ of
49 	 * the network data.
50 	 */
51 	if (oddbyte) {
52 		if (cisco) {
53 			if (v & 0x80) {
54 				sum += 0xff << 8;
55 				sum += v - 1;
56 			} else {
57 				sum += v;
58 			}
59 		} else {
60 			sum += v << 8;
61 		}
62 	}
63 
64       	sum = (sum >> 16) + (sum & 0xffff);
65       	sum += sum >> 16;
66       	return (0xffff & ~sum);
67 }
68