xref: /openbmc/qemu/net/checksum.c (revision 1529ae1b)
1 /*
2  *  IP checksumming functions.
3  *  (c) 2008 Gerd Hoffmann <kraxel@redhat.com>
4  *
5  *  This program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; under version 2 of the License.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
16  *
17  *  Contributions after 2012-01-13 are licensed under the terms of the
18  *  GNU GPL, version 2 or (at your option) any later version.
19  */
20 
21 #include "net/checksum.h"
22 
23 #define PROTO_TCP  6
24 #define PROTO_UDP 17
25 
26 uint32_t net_checksum_add(int len, uint8_t *buf)
27 {
28     uint32_t sum = 0;
29     int i;
30 
31     for (i = 0; i < len; i++) {
32 	if (i & 1)
33 	    sum += (uint32_t)buf[i];
34 	else
35 	    sum += (uint32_t)buf[i] << 8;
36     }
37     return sum;
38 }
39 
40 uint16_t net_checksum_finish(uint32_t sum)
41 {
42     while (sum>>16)
43 	sum = (sum & 0xFFFF)+(sum >> 16);
44     return ~sum;
45 }
46 
47 uint16_t net_checksum_tcpudp(uint16_t length, uint16_t proto,
48                              uint8_t *addrs, uint8_t *buf)
49 {
50     uint32_t sum = 0;
51 
52     sum += net_checksum_add(length, buf);         // payload
53     sum += net_checksum_add(8, addrs);            // src + dst address
54     sum += proto + length;                        // protocol & length
55     return net_checksum_finish(sum);
56 }
57 
58 void net_checksum_calculate(uint8_t *data, int length)
59 {
60     int hlen, plen, proto, csum_offset;
61     uint16_t csum;
62 
63     if ((data[14] & 0xf0) != 0x40)
64 	return; /* not IPv4 */
65     hlen  = (data[14] & 0x0f) * 4;
66     plen  = (data[16] << 8 | data[17]) - hlen;
67     proto = data[23];
68 
69     switch (proto) {
70     case PROTO_TCP:
71 	csum_offset = 16;
72 	break;
73     case PROTO_UDP:
74 	csum_offset = 6;
75 	break;
76     default:
77 	return;
78     }
79 
80     if (plen < csum_offset+2)
81 	return;
82 
83     data[14+hlen+csum_offset]   = 0;
84     data[14+hlen+csum_offset+1] = 0;
85     csum = net_checksum_tcpudp(plen, proto, data+14+12, data+14+hlen);
86     data[14+hlen+csum_offset]   = csum >> 8;
87     data[14+hlen+csum_offset+1] = csum & 0xff;
88 }
89