blob: 68f4dcb83a538c69e51f6cde9398b0eb099ba955 [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * Copyright (c) 2014 Chris Anderson
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24#include "minip-internal.h"
25
26/* XXX alternate implementation, merge */
27uint16_t ones_sum16(uint32_t sum, const void *_buf, int len)
28{
29 const uint16_t *buf = _buf;
30
31 while (len >= 2) {
32 sum += *buf++;
33 if(sum & 0x80000000)
34 sum = (sum & 0xffff) + (sum >> 16);
35 len -= 2;
36 }
37
38 if (len) {
39 uint16_t temp = htons((*(uint8_t *)buf) << 8);
40 sum += temp;
41 }
42
43 while (sum >> 16)
44 sum = (sum & 0xffff) + (sum >> 16);
45
46 return sum;
47}
48
49uint16_t rfc1701_chksum(const uint8_t *buf, size_t len)
50{
51 uint32_t total = 0;
52 uint16_t chksum = 0;
53 const uint16_t *p = (const uint16_t *) buf;
54
55 // Length is in bytes
56 for (size_t i = 0; i < len / 2; i++ ) {
57 total += p[i];
58 }
59
60 chksum = (total & 0xFFFF) + (total >> 16);
61 chksum = ~chksum;
62
63 return chksum;
64}
65
66#if MINIP_USE_UDP_CHECKSUM
67uint16_t rfc768_chksum(struct ipv4_hdr *ipv4, struct udp_hdr *udp)
68{
69 uint32_t total = 0;
70 uint16_t chksum = 0;
71 size_t len = ntohs(udp->len);
72 uint16_t *p;
73
74 p = (uint16_t *)ipv4->src_addr;
75 total += htons(p[0]);
76 total += htons(p[1]);
77
78 p = (uint16_t *)ipv4->dst_addr;
79 total += htons(p[0]);
80 total += htons(p[1]);
81
82 p = (const uint16_t *)udp->data;
83 for (size_t i = 0; i < len / 2; i++ ) {
84 total += p[i];
85 }
86
87 total += IP_PROTO_UDP;
88 total += udp->len;
89 total += udp->src_port;
90 total += udp->dst_port;
91 total += ipv4->len;
92
93 chksum = (total & 0xFFFF) + (total >> 16);
94 chksum = ~chksum;
95
96 return chksum;
97}
98#endif
99
100// vim: set ts=4 sw=4 expandtab: