4 #include <netinet/in.h>
5 #include <netinet/ip.h>
6 #include <netinet/ip6.h>
10 static inline unsigned short csum(unsigned short *buf
, int nwords
)
14 for (sum
= 0; nwords
> 0; nwords
--)
16 sum
= (sum
>> 16) + (sum
& 0xffff);
22 static inline uint16_t calc_csum(void *addr
, size_t len
)
24 return csum(addr
, len
>> 1);
27 static inline uint16_t csum_expected(uint16_t sum
, uint16_t computed_sum
)
32 shouldbe
+= ntohs(computed_sum
);
33 shouldbe
= (shouldbe
& 0xFFFF) + (shouldbe
>> 16);
34 shouldbe
= (shouldbe
& 0xFFFF) + (shouldbe
>> 16);
39 /* Taken and modified from tcpdump, Copyright belongs to them! */
47 do { if ((x) > 65535) \
54 sum = l_util.s[0] + l_util.s[1]; \
58 static inline uint16_t __in_cksum(const struct cksum_vec
*vec
, int veclen
)
61 int sum
= 0, mlen
= 0;
72 for (; veclen
!= 0; vec
++, veclen
--) {
76 w
= (const uint16_t *) (const void *) vec
->ptr
;
79 s_util
.c
[1] = *(const uint8_t *) w
;
81 w
= (const uint16_t *) (const void *) ((const uint8_t *) w
+ 1);
86 if ((1 & (unsigned long) w
) && (mlen
> 0)) {
89 s_util
.c
[0] = *(const uint8_t *) w
;
90 w
= (const uint16_t *) (const void *) ((const uint8_t *) w
+ 1);
95 while ((mlen
-= 32) >= 0) {
96 sum
+= w
[0]; sum
+= w
[1]; sum
+= w
[2]; sum
+= w
[3];
97 sum
+= w
[4]; sum
+= w
[5]; sum
+= w
[6]; sum
+= w
[7];
98 sum
+= w
[8]; sum
+= w
[9]; sum
+= w
[10]; sum
+= w
[11];
99 sum
+= w
[12]; sum
+= w
[13]; sum
+= w
[14]; sum
+= w
[15];
105 while ((mlen
-= 8) >= 0) {
106 sum
+= w
[0]; sum
+= w
[1]; sum
+= w
[2]; sum
+= w
[3];
112 if (mlen
== 0 && byte_swapped
== 0)
117 while ((mlen
-= 2) >= 0) {
127 s_util
.c
[1] = *(const uint8_t *) w
;
132 } else if (mlen
== -1)
133 s_util
.c
[0] = *(const uint8_t *) w
;
143 return (~sum
& 0xffff);
146 static inline uint16_t p4_csum(const struct ip
*ip
, const uint8_t *data
,
147 uint16_t len
, uint8_t next_proto
)
149 struct cksum_vec vec
[2];
158 ph
.src
= ip
->ip_src
.s_addr
;
159 ph
.dst
= ip
->ip_dst
.s_addr
;
161 ph
.proto
= next_proto
;
164 vec
[0].ptr
= (const uint8_t *) (void *) &ph
;
165 vec
[0].len
= sizeof(ph
);
170 return __in_cksum(vec
, 2);
173 static inline uint16_t p6_csum(const struct ip6_hdr
*ip6
, const uint8_t *data
,
174 uint32_t len
, uint8_t next_proto
)
176 struct cksum_vec vec
[2];
185 memcpy(&ph
.src
, ip6
->ip6_src
.s6_addr
, sizeof(ph
.src
));
186 memcpy(&ph
.dst
, ip6
->ip6_dst
.s6_addr
, sizeof(ph
.dst
));
188 memset(&ph
.mbz
, 0, sizeof(ph
.mbz
));
189 ph
.proto
= next_proto
;
191 vec
[0].ptr
= (const uint8_t *) (void *) &ph
;
192 vec
[0].len
= sizeof(ph
);
197 return __in_cksum(vec
, 2);