1 /* 2 * Copyright (c) 1998-2006 The TCPDUMP project 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that: (1) source code 6 * distributions retain the above copyright notice and this paragraph 7 * in its entirety, and (2) distributions including binary code include 8 * the above copyright notice and this paragraph in its entirety in 9 * the documentation or other materials provided with the distribution. 10 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND 11 * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT 12 * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 13 * FOR A PARTICULAR PURPOSE. 14 * 15 * miscellaneous checksumming routines 16 * 17 * Original code by Hannes Gredler (hannes@juniper.net) 18 */ 19 20 #ifndef lint 21 static const char rcsid[] _U_ = 22 "@(#) $Header: /tcpdump/master/tcpdump/checksum.c,v 1.4 2006-09-25 09:23:32 hannes Exp $"; 23 #endif 24 25 #ifdef HAVE_CONFIG_H 26 #include "config.h" 27 #endif 28 29 #include <tcpdump-stdinc.h> 30 31 #include <stdio.h> 32 #include <stdlib.h> 33 #include <string.h> 34 35 #include "interface.h" 36 37 #define CRC10_POLYNOMIAL 0x633 38 static u_int16_t crc10_table[256]; 39 40 static void 41 init_crc10_table(void) 42 { 43 register int i, j; 44 register u_int16_t accum; 45 46 for ( i = 0; i < 256; i++ ) 47 { 48 accum = ((unsigned short) i << 2); 49 for ( j = 0; j < 8; j++ ) 50 { 51 if ((accum <<= 1) & 0x400) accum ^= CRC10_POLYNOMIAL; 52 } 53 crc10_table[i] = accum; 54 } 55 return; 56 } 57 58 u_int16_t 59 verify_crc10_cksum(u_int16_t accum, const u_char *p, int length) 60 { 61 register int i; 62 63 for ( i = 0; i < length; i++ ) 64 { 65 accum = ((accum << 8) & 0x3ff) 66 ^ crc10_table[( accum >> 2) & 0xff] 67 ^ *p++; 68 } 69 return accum; 70 } 71 72 /* precompute checksum tables */ 73 void 74 init_checksum(void) { 75 76 init_crc10_table(); 77 78 } 79 80 /* 81 * Creates the OSI Fletcher checksum. See 8473-1, Appendix C, section C.3. 82 * The checksum field of the passed PDU does not need to be reset to zero. 83 */ 84 u_int16_t 85 create_osi_cksum (const u_int8_t *pptr, int checksum_offset, int length) 86 { 87 88 int x; 89 int y; 90 u_int32_t mul; 91 u_int32_t c0; 92 u_int32_t c1; 93 u_int16_t checksum; 94 int index; 95 96 checksum = 0; 97 98 c0 = 0; 99 c1 = 0; 100 101 for (index = 0; index < length; index++) { 102 /* 103 * Ignore the contents of the checksum field. 104 */ 105 if (index == checksum_offset || 106 index == checksum_offset+1) { 107 c1 += c0; 108 pptr++; 109 } else { 110 c0 = c0 + *(pptr++); 111 c1 += c0; 112 } 113 } 114 115 c0 = c0 % 255; 116 c1 = c1 % 255; 117 118 mul = (length - checksum_offset)*(c0); 119 120 x = mul - c0 - c1; 121 y = c1 - mul - 1; 122 123 if ( y >= 0 ) y++; 124 if ( x < 0 ) x--; 125 126 x %= 255; 127 y %= 255; 128 129 130 if (x == 0) x = 255; 131 if (y == 0) y = 255; 132 133 y &= 0x00FF; 134 checksum = ((x << 8) | y); 135 136 return checksum; 137 } 138