1 /* 2 * IP checksumming functions. 3 * (c) 2008 Gerd Hoffmann <kraxel (at) 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 18 #include "hw/hw.h" 19 #include "net/net.h" 20 21 #define PROTO_TCP 6 22 #define PROTO_UDP 17 23 24 uint32_t net_checksum_add(int len, uint8_t *buf) 25 { 26 uint32_t sum = 0; 27 int i; 28 29 for (i = 0; i < len; i++) { 30 if (i & 1) 31 sum += (uint32_t)buf[i]; 32 else 33 sum += (uint32_t)buf[i] << 8; 34 } 35 return sum; 36 } 37 38 uint16_t net_checksum_finish(uint32_t sum) 39 { 40 while (sum>>16) 41 sum = (sum & 0xFFFF)+(sum >> 16); 42 return ~sum; 43 } 44 45 uint16_t net_checksum_tcpudp(uint16_t length, uint16_t proto, 46 uint8_t *addrs, uint8_t *buf) 47 { 48 uint32_t sum = 0; 49 50 sum += net_checksum_add(length, buf); // payload 51 sum += net_checksum_add(8, addrs); // src + dst address 52 sum += proto + length; // protocol & length 53 return net_checksum_finish(sum); 54 } 55 56 void net_checksum_calculate(uint8_t *data, int length) 57 { 58 int hlen, plen, proto, csum_offset; 59 uint16_t csum; 60 61 if ((data[14] & 0xf0) != 0x40) 62 return; /* not IPv4 */ 63 hlen = (data[14] & 0x0f) * 4; 64 plen = (data[16] << 8 | data[17]) - hlen; 65 proto = data[23]; 66 67 switch (proto) { 68 case PROTO_TCP: 69 csum_offset = 16; 70 break; 71 case PROTO_UDP: 72 csum_offset = 6; 73 break; 74 default: 75 return; 76 } 77 78 if (plen < csum_offset+2) 79 return; 80 81 data[14+hlen+csum_offset] = 0; 82 data[14+hlen+csum_offset+1] = 0; 83 csum = net_checksum_tcpudp(plen, proto, data+14+12, data+14+hlen); 84 data[14+hlen+csum_offset] = csum >> 8; 85 data[14+hlen+csum_offset+1] = csum & 0xff; 86 } 87