1 /* $OpenBSD: checksum.c,v 1.1 2021/02/26 16:16:37 florian Exp $ */
2
3 /* Packet assembly code, originally contributed by Archie Cobbs. */
4
5 /*
6 * Copyright (c) 1995, 1996, 1999 The Internet Software Consortium.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of The Internet Software Consortium nor the names
19 * of its contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
23 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
24 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
27 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
30 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * This software has been written for the Internet Software Consortium
37 * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
38 * Enterprises. To learn more about the Internet Software Consortium,
39 * see ``http://www.vix.com/isc''. To learn more about Vixie
40 * Enterprises, see ``http://www.vix.com''.
41 */
42
43 #include <arpa/inet.h>
44
45 #include <stdint.h>
46
47 #include "checksum.h"
48
49 uint32_t
checksum(uint8_t * buf,uint32_t nbytes,uint32_t sum)50 checksum(uint8_t *buf, uint32_t nbytes, uint32_t sum)
51 {
52 unsigned int i;
53
54 /* Checksum all the pairs of bytes first. */
55 for (i = 0; i < (nbytes & ~1U); i += 2) {
56 sum += (uint16_t)ntohs(*((uint16_t *)(buf + i)));
57 if (sum > 0xFFFF)
58 sum -= 0xFFFF;
59 }
60
61 /*
62 * If there's a single byte left over, checksum it, too.
63 * Network byte order is big-endian, so the remaining byte is
64 * the high byte.
65 */
66 if (i < nbytes) {
67 sum += buf[i] << 8;
68 if (sum > 0xFFFF)
69 sum -= 0xFFFF;
70 }
71
72 return sum;
73 }
74
75 uint32_t
wrapsum(uint32_t sum)76 wrapsum(uint32_t sum)
77 {
78 sum = ~sum & 0xFFFF;
79 return htons(sum);
80 }
81