1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18#include "qemu-common.h"
19#include "net/checksum.h"
20
21#define PROTO_TCP 6
22#define PROTO_UDP 17
23
24uint32_t net_checksum_add_cont(int len, uint8_t *buf, int seq)
25{
26 uint32_t sum = 0;
27 int i;
28
29 for (i = seq; i < seq + len; i++) {
30 if (i & 1) {
31 sum += (uint32_t)buf[i - seq];
32 } else {
33 sum += (uint32_t)buf[i - seq] << 8;
34 }
35 }
36 return sum;
37}
38
39uint16_t net_checksum_finish(uint32_t sum)
40{
41 while (sum>>16)
42 sum = (sum & 0xFFFF)+(sum >> 16);
43 return ~sum;
44}
45
46uint16_t net_checksum_tcpudp(uint16_t length, uint16_t proto,
47 uint8_t *addrs, uint8_t *buf)
48{
49 uint32_t sum = 0;
50
51 sum += net_checksum_add(length, buf);
52 sum += net_checksum_add(8, addrs);
53 sum += proto + length;
54 return net_checksum_finish(sum);
55}
56
57void net_checksum_calculate(uint8_t *data, int length)
58{
59 int hlen, plen, proto, csum_offset;
60 uint16_t csum;
61
62
63 if (length < 14 + 20) {
64 return;
65 }
66
67 if ((data[14] & 0xf0) != 0x40)
68 return;
69 hlen = (data[14] & 0x0f) * 4;
70 plen = (data[16] << 8 | data[17]) - hlen;
71 proto = data[23];
72
73 switch (proto) {
74 case PROTO_TCP:
75 csum_offset = 16;
76 break;
77 case PROTO_UDP:
78 csum_offset = 6;
79 break;
80 default:
81 return;
82 }
83
84 if (plen < csum_offset + 2 || 14 + hlen + plen > length) {
85 return;
86 }
87
88 data[14+hlen+csum_offset] = 0;
89 data[14+hlen+csum_offset+1] = 0;
90 csum = net_checksum_tcpudp(plen, proto, data+14+12, data+14+hlen);
91 data[14+hlen+csum_offset] = csum >> 8;
92 data[14+hlen+csum_offset+1] = csum & 0xff;
93}
94
95uint32_t
96net_checksum_add_iov(const struct iovec *iov, const unsigned int iov_cnt,
97 uint32_t iov_off, uint32_t size)
98{
99 size_t iovec_off, buf_off;
100 unsigned int i;
101 uint32_t res = 0;
102 uint32_t seq = 0;
103
104 iovec_off = 0;
105 buf_off = 0;
106 for (i = 0; i < iov_cnt && size; i++) {
107 if (iov_off < (iovec_off + iov[i].iov_len)) {
108 size_t len = MIN((iovec_off + iov[i].iov_len) - iov_off , size);
109 void *chunk_buf = iov[i].iov_base + (iov_off - iovec_off);
110
111 res += net_checksum_add_cont(len, chunk_buf, seq);
112 seq += len;
113
114 buf_off += len;
115 iov_off += len;
116 size -= len;
117 }
118 iovec_off += iov[i].iov_len;
119 }
120 return res;
121}
122