xref: /xnu-11215.41.3/tests/in_cksum.c (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 2000-2018 Apple Inc. All rights reserved.
3  *
4  * @APPLE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. Please obtain a copy of the License at
10  * http://www.opensource.apple.com/apsl/ and read it before using this
11  * file.
12  *
13  * The Original Code and all software distributed under the License are
14  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18  * Please see the License for the specific language governing rights and
19  * limitations under the License.
20  *
21  * @APPLE_LICENSE_HEADER_END@
22  */
23 
24 /*
25  * Copyright (c) 1988, 1992, 1993
26  *	The Regents of the University of California.  All rights reserved.
27  *
28  *	@(#)in_cksum.c	8.1 (Berkeley) 6/10/93
29  */
30 
31 #include <sys/param.h>
32 #include "in_cksum.h"
33 
34 typedef union {
35 	char        c[2];
36 	u_short     s;
37 } short_union_t;
38 
39 typedef union {
40 	u_short     s[2];
41 	long        l;
42 } long_union_t;
43 
44 static __inline__ void
reduce(int * sum)45 reduce(int * sum)
46 {
47 	long_union_t l_util;
48 
49 	l_util.l = *sum;
50 	*sum = l_util.s[0] + l_util.s[1];
51 	if (*sum > 65535) {
52 		*sum -= 65535;
53 	}
54 	return;
55 }
56 
57 
58 #include <stdio.h>
59 
60 unsigned short
in_cksum(void * pkt,int len)61 in_cksum(void * pkt, int len)
62 {
63 	u_short * w;
64 	int sum = 0;
65 
66 	w = (u_short *)pkt;
67 	while ((len -= 32) >= 0) {
68 		sum += w[0]; sum += w[1];
69 		sum += w[2]; sum += w[3];
70 		sum += w[4]; sum += w[5];
71 		sum += w[6]; sum += w[7];
72 		sum += w[8]; sum += w[9];
73 		sum += w[10]; sum += w[11];
74 		sum += w[12]; sum += w[13];
75 		sum += w[14]; sum += w[15];
76 		w += 16;
77 	}
78 	len += 32;
79 	while ((len -= 8) >= 0) {
80 		sum += w[0]; sum += w[1];
81 		sum += w[2]; sum += w[3];
82 		w += 4;
83 	}
84 	len += 8;
85 	if (len) {
86 		reduce(&sum);
87 		while ((len -= 2) >= 0) {
88 			sum += *w++;
89 		}
90 	}
91 	if (len == -1) { /* odd-length packet */
92 		short_union_t s_util;
93 
94 		s_util.s = 0;
95 		s_util.c[0] = *((char *)w);
96 		s_util.c[1] = 0;
97 		sum += s_util.s;
98 	}
99 	reduce(&sum);
100 	return ~sum & 0xffff;
101 }
102