6 #include <netinet/in.h>
7 #include <netinet/ip.h>
8 #include <netinet/ip6.h>
12 static inline unsigned short csum(unsigned short *buf
, int nwords
)
16 for (sum
= 0; nwords
> 0; nwords
--)
18 sum
= (sum
>> 16) + (sum
& 0xffff);
24 static inline uint16_t calc_csum(void *addr
, size_t len
)
26 return csum(addr
, len
>> 1);
29 static inline uint16_t csum_expected(uint16_t sum
, uint16_t computed_sum
)
34 shouldbe
+= ntohs(computed_sum
);
35 shouldbe
= (shouldbe
& 0xFFFF) + (shouldbe
>> 16);
36 shouldbe
= (shouldbe
& 0xFFFF) + (shouldbe
>> 16);
41 /* Taken and modified from tcpdump, Copyright belongs to them! */
49 do { if ((x) > 65535) \
56 sum = l_util.s[0] + l_util.s[1]; \
60 static inline uint16_t __in_cksum(const struct cksum_vec
*vec
, int veclen
)
63 int sum
= 0, mlen
= 0;
74 for (; veclen
!= 0; vec
++, veclen
--) {
78 w
= (const uint16_t *) (const void *) vec
->ptr
;
81 s_util
.c
[1] = *(const uint8_t *) w
;
83 w
= (const uint16_t *) (const void *) ((const uint8_t *) w
+ 1);
88 if ((1 & (unsigned long) w
) && (mlen
> 0)) {
91 s_util
.c
[0] = *(const uint8_t *) w
;
92 w
= (const uint16_t *) (const void *) ((const uint8_t *) w
+ 1);
97 while ((mlen
-= 32) >= 0) {
98 sum
+= w
[0]; sum
+= w
[1]; sum
+= w
[2]; sum
+= w
[3];
99 sum
+= w
[4]; sum
+= w
[5]; sum
+= w
[6]; sum
+= w
[7];
100 sum
+= w
[8]; sum
+= w
[9]; sum
+= w
[10]; sum
+= w
[11];
101 sum
+= w
[12]; sum
+= w
[13]; sum
+= w
[14]; sum
+= w
[15];
107 while ((mlen
-= 8) >= 0) {
108 sum
+= w
[0]; sum
+= w
[1]; sum
+= w
[2]; sum
+= w
[3];
114 if (mlen
== 0 && byte_swapped
== 0)
119 while ((mlen
-= 2) >= 0) {
129 s_util
.c
[1] = *(const uint8_t *) w
;
134 } else if (mlen
== -1)
135 s_util
.c
[0] = *(const uint8_t *) w
;
145 return (~sum
& 0xffff);
148 static inline uint16_t p4_csum(const struct ip
*ip
, const uint8_t *data
,
149 uint16_t len
, uint8_t next_proto
)
151 struct cksum_vec vec
[2];
160 ph
.src
= ip
->ip_src
.s_addr
;
161 ph
.dst
= ip
->ip_dst
.s_addr
;
163 ph
.proto
= next_proto
;
166 vec
[0].ptr
= (const uint8_t *) (void *) &ph
;
167 vec
[0].len
= sizeof(ph
);
172 return __in_cksum(vec
, 2);
175 static inline uint16_t p6_csum(const struct ip6_hdr
*ip6
, const uint8_t *data
,
176 uint32_t len
, uint8_t next_proto
)
178 struct cksum_vec vec
[2];
187 memcpy(&ph
.src
, ip6
->ip6_src
.s6_addr
, sizeof(ph
.src
));
188 memcpy(&ph
.dst
, ip6
->ip6_dst
.s6_addr
, sizeof(ph
.dst
));
190 memset(&ph
.mbz
, 0, sizeof(ph
.mbz
));
191 ph
.proto
= next_proto
;
193 vec
[0].ptr
= (const uint8_t *) (void *) &ph
;
194 vec
[0].len
= sizeof(ph
);
199 return __in_cksum(vec
, 2);