File: misc.cc

package info (click to toggle)
xprobe 0.3-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 2,588 kB
  • sloc: cpp: 12,317; sh: 2,858; makefile: 692; ansic: 7
file content (98 lines) | stat: -rwxr-xr-x 2,040 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "usi++/usi++"
#include "usi++/usi-structs.h"
#include <cstdlib>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>


namespace usipp {

typedef u_int16_t u_short;
bool exceptions = false;

// ripped code, slightly modified
// to pad odd length automagically (UDP,TCP)
unsigned short
in_cksum (unsigned short *ptr, int nbytes, bool may_pad)
{

  register long sum;		/* assumes long == 32 bits */
  u_short oddbyte;
  register u_short answer;	/* assumes u_short == 16 bits */


  /* For psuedo-headers: odd len's require
   * padding. We assume that UDP,TCP always
   * gives enough room for computation */
  if (nbytes % 2 && may_pad)
	++nbytes;
  /*
   * Our algorithm is simple, using a 32-bit accumulator (sum),
   * we add sequential 16-bit words to it, and at the end, fold back
   * all the carry bits from the top 16 bits into the lower 16 bits.
   */

  sum = 0;
  while (nbytes > 1)
    {
      sum += *ptr++;
      nbytes -= 2;
    }

  /* mop up an odd byte, if necessary */
  if (nbytes == 1)
    {
      oddbyte = 0;		/* make sure top half is zero */
      *((unsigned char *) & oddbyte) = *(unsigned char *) ptr;	/* one byte only */
      sum += oddbyte;
    }

  /*
   * Add back carry outs from top 16 bits to low 16 bits.
   */

  sum = (sum >> 16) + (sum & 0xffff);	/* add high-16 to low-16 */
  sum += (sum >> 16);		/* add carry */
  answer = ~sum;		/* ones-complement, then truncate to 16 bits */
  return (answer);
}

/*! Turn throwing of exceptions on or off.
 */
int useException(bool how)
{
	exceptions = how;
	return 0;
}

void die(const char *message, errorFuncs what, int error)
{
	if (exceptions) {
		throw usifault(message);
	}

	/* Not reached, if 'exceptions' was true */
	switch (what) {
	case PERROR:
		perror(message);
    		break;
	case STDERR:
		fprintf(stderr, "%s", message);
		break;
	case HERROR:
		(void)herror(message);
		break;
	case PCAP:
		fprintf(stderr, "%s", pcap_strerror(error));
		break;
	default:
		break;
	}
	exit(error);
}

} // namespace usipp