main.c 36.5 KB
Newer Older
Sampo Saaristo's avatar
Sampo Saaristo committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*****************************************************************************
 *   main.c - the body for CRUDE
 *
 *   Copyright (C) 1999 Juha Laine and Sampo Saaristo
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 *   Authors:      Juha Laine     <james@cs.tut.fi>
 *                 Sampo Saaristo <sambo@cc.tut.fi>
Olav Kvittem's avatar
Olav Kvittem committed
22 23 24 25
 *   2015-07-02    Olav Kvittem   <oak@uninett.no>
 *      added reading pcap to disk, using kernel timestamp, forking write process to disk
 *      bug: reading AF_PACKET does not receive any packets
 *      caveats: only implemented for rec_to_file()
Sampo Saaristo's avatar
Sampo Saaristo committed
26 27 28 29
 *
 *****************************************************************************/
#include <config.h>
#include <rude.h>
Arne Øslebø's avatar
Arne Øslebø committed
30
#include <mcast.h>
Sampo Saaristo's avatar
Sampo Saaristo committed
31 32 33 34

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
Olav Kvittem's avatar
Olav Kvittem committed
35
#include <linux/fcntl.h>
Sampo Saaristo's avatar
Sampo Saaristo committed
36 37 38 39 40 41 42 43 44 45 46
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sched.h>
#include <sys/mman.h>
#include <arpa/inet.h>
#include <netinet/in.h>
Olav Kvittem's avatar
Olav Kvittem committed
47 48
#include <netinet/ip.h>
#include <netinet/udp.h>
Sampo Saaristo's avatar
Sampo Saaristo committed
49
#include <limits.h>
Olav Kvittem's avatar
Olav Kvittem committed
50 51 52 53 54 55 56 57
//#include <pcap.h> 
#include <pcap/pcap.h>
#include <netpacket/packet.h>
#include <net/ethernet.h> /* the L2 protocols */
//#include <linux/if_packet.h>  // provided by netpacket/packet.h

#define OBUFFERS 10000  // number of  records in ouput buffer 
#define OCHUNKS 100     // number of records for each write chunk
Sampo Saaristo's avatar
Sampo Saaristo committed
58 59 60
/*
 * Private struct for each flow of runtime statistics
 */
Arne Øslebø's avatar
Arne Øslebø committed
61 62
struct flow_stat
{
yorn's avatar
yorn committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
	unsigned long flowid;
	unsigned long seqmin, seq;  /* Seq number of the first and current packets */
	unsigned long rec;          /* Number of received packets */
	unsigned long oos;          /* Number of packets out of sequence */
	long long js_sec;           /* Jitter sum of seconds */
	long long js_usec;          /* Jitter sum of microsseconds */
	long long ds_sec;           /* Delay sum of seconds */
	long long ds_usec;          /* Delay sum of microsseconds */
	long last_tx_sec;
	long last_tx_usec;
	long last_rx_sec;
	long last_rx_usec;
	long last_delay_sec;
	long last_delay_usec;
	long first_rx_sec;
	long first_rx_usec;
	long max_jitter_sec;
	long max_jitter_usec;
	unsigned long long s_size;  /* Sum of all packet sizes */
Sampo Saaristo's avatar
Sampo Saaristo committed
82 83 84 85 86 87 88
};


/*
 * Function prototypes
 */
static void usage(char *);
Arne Øslebø's avatar
Arne Øslebø committed
89
static int  make_conn(unsigned short, char *,int,unsigned int);
Sampo Saaristo's avatar
Sampo Saaristo committed
90 91 92 93 94 95
static int  decode_file(void);
static int  runtime_stats(unsigned short, unsigned long);
void        print_stats(void);
static int  rec_to_file(unsigned short,unsigned long);
static int  rec_n_print(unsigned short,unsigned long);
void        crude_handler(int);
Arne Øslebø's avatar
Arne Øslebø committed
96
static void get_str_addr(struct sockaddr_storage,char[]);
Olav Kvittem's avatar
Olav Kvittem committed
97 98
static int output_data(int, int);
static int fork_write();
Sampo Saaristo's avatar
Sampo Saaristo committed
99 100 101 102 103 104

/*
 * Global variables
 */
int main_socket         = 0;     /* The socket to listen to                  */
int main_file           = 0;     /* File to read from/to write to            */
Olav Kvittem's avatar
Olav Kvittem committed
105
int main_output         = 0;     /* file to write output (is main_file if not fork) */
Sampo Saaristo's avatar
Sampo Saaristo committed
106 107 108
unsigned long pkt_count = 0;     /* Counter for received/processed packets   */
struct flow_stat *flows = NULL;  /* List of flows for runtime statistics  */
int nflows              = 0;
Arne Øslebø's avatar
Arne Øslebø committed
109
char preffix[] = "::ffff:";
Olav Kvittem's avatar
Olav Kvittem committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
short opt_af_packet=0, opt_pcap=0;
short opt_ktime=0; // kernel packet time by ioctl
short opt_fork=0; // fork for write in separate process with noblock for improving packet loss
char pcap_dev[100]="";
pcap_t *main_pcap;

// data structure for ouput ring buffer 
int  osize;
int  obufsize;
int  ochunksize;
int  ofree = 0; // next free pos
int  odata = 0; // next data pos
char *obuffer=NULL;
int pipefd[2]; // a pipe for writing to file in a subprocess


Sampo Saaristo's avatar
Sampo Saaristo committed
126 127

int main(int argc, char **argv)
Arne Øslebø's avatar
Arne Øslebø committed
128
{
yorn's avatar
yorn committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
	extern char *optarg;
	extern int  optind, opterr, optopt, errno;

	char *ifipadd       = NULL;    /* pointer to interface IP address */
	unsigned short port = 10001;   /* default UDP port number         */
	long w_num          = 0;       /* # pkts to capture. 0=unlimited  */
	int priority        = 0;
	uid_t user_id       = getuid();
	int  cmd_char       = 0;
	int  retval         = 0;
	long temp1          = 0;
	int ps_flag         = 0;
	struct sigaction action;
	struct sched_param p;
	char *sptr, *eptr;
	struct flow_stat *newflows;
	int use_ip6=0;
	int ifindex = -1;

	printf("crude version %s, Copyright (C) 1999 Juha Laine and Sampo Saaristo\n"
	       "crude comes with ABSOLUTELY NO WARRANTY!\n"
	       "This is free software, and you are welcome to redistribute it\n"
	       "under GNU GENERAL PUBLIC LICENSE Version 2.\n",VERSION);

	struct sockaddr_storage test;
Olav Kvittem's avatar
Olav Kvittem committed
154
	printf("Size of sockaddr_storage: %lu ss_len:%lu \n",sizeof(test),sizeof(test.ss_family));
yorn's avatar
yorn committed
155 156

	while((retval >= 0) &&
Olav Kvittem's avatar
Olav Kvittem committed
157
				((cmd_char = getopt(argc,argv,"Ahvd:p:C:fi:kl:P:n:s:6D:")) != EOF))
yorn's avatar
yorn committed
158 159 160
	{
		switch(cmd_char)
		{
Olav Kvittem's avatar
Olav Kvittem committed
161 162 163
		case 'A': 
		  opt_af_packet=1;
		  break;
yorn's avatar
yorn committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
		case 'v':
			if((optind == 2) && (argc == 2))
			{
				printf("crude version is %s\n",VERSION);
				retval = -1;
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

		case 'h':
			if((optind == 2) && (argc == 2))
			{
				usage(argv[0]);
				retval = -1;
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

		case 'd':
			if((optind == 3) && (argc == 3) && (optarg != NULL))
			{
				if((main_file = open(optarg, O_RDONLY, 0)) < 0)
				{
					RUDEBUG1("crude: couldn't open file %s: %s\n",optarg,strerror(errno));
					retval = -3;
				}
				else
				{
					retval = 1;
				}
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

Olav Kvittem's avatar
Olav Kvittem committed
210 211 212
		case 'f':  // fork output write
		  opt_fork=1;
		  break;
yorn's avatar
yorn committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
		case 'p':
			if(optarg != NULL)
			{
				errno = 0;
				temp1 = strtol((const char *)optarg,NULL,0);
				if(errno != 0)
				{
					RUDEBUG1("crude: '-p' number format error: %s\n",strerror(errno));
					retval = -4;
				}
				else if((temp1 < 1025) || (temp1 > 65535))
				{
					RUDEBUG1("crude: port must be  between 1025-65535!\n");
					retval = -4;
				}
				else
				{
					port = temp1;
					retval += 2;
				}
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

Olav Kvittem's avatar
Olav Kvittem committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
		case 'k': // use kernel time
		  opt_ktime=1;
		  // retval=1;
		  break;

		case 'C': // pcap capture
			if(optarg != NULL)
			{
				errno=0;
				opt_pcap=1;
				strncpy(pcap_dev, optarg, 10);
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

yorn's avatar
yorn committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
		case 'i':
			if(optarg != NULL)
			{
				ifipadd = argv[(optind-1)];
				retval += 4;
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

		case 'l':
			if(optarg != NULL)
			{
				if((main_file = open(optarg, O_WRONLY|O_CREAT|O_TRUNC, 0644)) < 0)
				{
					RUDEBUG1("crude: couldn't open file %s: %s\n",optarg,strerror(errno));
					retval = -5;
				}
				else
				{
					retval += 8;
				}
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

		case 'P':
			if(optarg != NULL)
			{
				priority = atoi(optarg);
				if((priority < 1) || (priority > 90))
				{
					fprintf(stderr,"crude: priority must be between 1 to 90\n");
					retval = -2;
				}
				if(user_id != 0)
				{
					fprintf(stderr,"crude: must be root to set the priority level\n");
					retval = -2;
				}
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

		case 'n':
			if(optarg != NULL)
			{
				errno = 0;
				w_num = strtol((const char *)optarg,NULL,0);
				if(errno != 0)
				{
					RUDEBUG1("crude: '-w' number format error: %s\n",strerror(errno));
					retval = -6;
				}
				else if(w_num <= 0)
				{
					RUDEBUG1("crude: # of logged packets must be > 0!\n");
					retval = -6;
				}
				else
				{
					retval += 16;
				}
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

		case 's':
			if(optarg != NULL)
			{
				sptr = optarg;
				do
				{
					newflows = realloc(flows, (nflows + 1) * sizeof(struct flow_stat));
					if (newflows == NULL)
					{
						RUDEBUG1("crude: failed to allocate memory for statistics!\n");
						retval = -6;
						break;
					}
					flows = newflows;
					flows[nflows].flowid = strtoul(sptr, &eptr, 10);
					if (eptr == sptr || flows[nflows].flowid == ULONG_MAX)
					{
						RUDEBUG1("crude: error reading flow IDs!\n");
						retval = -6;
						break;
					}
					if (*eptr && *eptr != ',')
					{
						RUDEBUG1("crude: flow IDs must be separated by a comma!\n");
						retval = -6;
						break;
					}
					sptr = eptr + 1;
					flows[nflows].rec = 0;
					flows[nflows].oos = 0;
					flows[nflows].seq = ULONG_MAX;
					flows[nflows].seqmin = ULONG_MAX;
					flows[nflows].js_sec = 0;
					flows[nflows].js_usec = 0;
					flows[nflows].ds_sec = 0;
					flows[nflows].ds_usec = 0;
					flows[nflows].s_size = 0;
					flows[nflows].last_delay_sec = 0;
					flows[nflows].last_delay_usec = 0;
					flows[nflows].max_jitter_sec = 0;
					flows[nflows].max_jitter_usec = 0;
					/* The other fields are initialized when the first packet arrives */
					nflows++;
				}
				while (*eptr);
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;

		case '6':
		use_ip6 = 1;
		break;

		case 'D':
			if(optarg != NULL){
			RUDEBUG7("crude: using specified interface for multicast, name: %s\n",optarg);
			if(0==(ifindex = if_nametoindex(optarg))){
Arne Øslebø's avatar
Arne Øslebø committed
403 404
			RUDEBUG1("crude: specified interface does not exist\n");
			retval = -10;
yorn's avatar
yorn committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
			}
			}
			else
			{
				RUDEBUG1("crude: invalid commandline arguments!\n");
				retval = -2;
			}
			break;


		default:
			usage(argv[0]);
			retval = -1;
			break;
		}
	}

	/* (if retval < 0 -> ERROR or/and EXIT IMMEDIATELY) */
	if(retval < 0){ goto crude_exit; }

	/*
	 * If this process is owned by root we can do some tricks to
	 * improve the performance... (the -P option)
	 */
	if((user_id == 0) && (priority > 0))
	{
		/* Try to lock the memory to avoid paging delays */
		if(mlockall(MCL_CURRENT | MCL_FUTURE) < 0)
		{
			RUDEBUG1("crude: memory lock failed: %s\n", strerror(errno));
		}

		/* Switch to Round-Robin-Real-Time Scheduling */
		p.sched_priority = priority;
		if(sched_setscheduler(0, SCHED_RR, &p) < 0)
		{
			RUDEBUG1("crude: sched_setscheduler() failed: %s\n",strerror(errno));
			retval = -1;
			goto crude_exit;
		}
		RUDEBUG7("crude: program priority set to %d\n", p.sched_priority);
	}

	/* Activate the signal handler(s) */
	memset(&action, 0, sizeof(struct sigaction));
	action.sa_handler = crude_handler;
	if(sigaction(SIGINT,&action,NULL))
	{
		RUDEBUG1("crude: signal SIGINT handler failure!\n");
		retval = -7;
		goto crude_exit;
	}

	if(retval == 1)
	{
		retval = decode_file();
	}
	else
	{
		if((main_socket=make_conn(port,ifipadd,use_ip6,ifindex)) < 0)
		{
			RUDEBUG1("crude: couldn't create socket!\n");
			retval = -8;
		}
		else
		{
			if (nflows > 0){ retval = runtime_stats(port,w_num); }
			else if(main_file > 0){ retval = rec_to_file(port,w_num); }
			else { retval = rec_n_print(port,w_num); }
		}
	}
Sampo Saaristo's avatar
Sampo Saaristo committed
476

Arne Øslebø's avatar
Arne Øslebø committed
477
crude_exit:
yorn's avatar
yorn committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
	if (retval >= 0 && nflows > 0) { ps_flag = 1; }
	/*
	 * Restore the tweaked settings...
	 */
	if((user_id == 0) && (priority > 0))
	{
		/* Restore the program priority */
		p.sched_priority = 0;
		if(sched_setscheduler(0, SCHED_OTHER, &p) < 0)
		{
			RUDEBUG1("crude: program priority restoring failed: %s\n",
			          strerror(errno));
			retval = -1;
		}
		else
		{
			RUDEBUG7("crude: program priority restored\n");
		}

		/* Release the locked memory */
		munlockall();
	}

	if(ps_flag){ print_stats(); }
	if(main_file > 0){ close(main_file); }
	if(main_socket > 0){ close(main_socket); }
	if(flows){free(flows); }
	exit(retval);
Sampo Saaristo's avatar
Sampo Saaristo committed
506 507 508 509 510 511 512 513
}


/*
 * usage() - print help and usage information
 */
static void usage(char *name)
{
yorn's avatar
yorn committed
514 515 516 517 518 519 520 521 522 523 524 525 526 527
	printf("\nusage: %s -h | -v | -d file | "
	       "[-p port] [-i addr] [-l file] [-n #]\n\n"
	       "\t-h           = print (this) short help and usage information\n"
	       "\t-v           = print the version number and exit\n"
	       "\t-d file      = decode the file to stdout\n"
	       "\t-p port      = port to listen to\n"
	       "\t-i addr      = numeric IP addres for the interface to listen to\n"
	       "\t-6           = use ipv6\n"
	       "\t-D if_name   = interface name(e.g. eth0) to be used-use only with multicast and -i option\n"
	       "\t-l file      = direct undecoded output to file (fastest method!)\n"
	       "\t               default is to decode the output to stdout\n"
	       "\t-P priority  = process realtime priority {1-90}\n\n"
	       "\t-s #[,# ...] = don't record: get runtime stats for specified flows\n"
	       "\t-n #         = exit automatically after # packets has been logged.\n"
Olav Kvittem's avatar
Olav Kvittem committed
528 529 530 531
	       "\t-k           = use kernel time stamps(ioctl).\n"
	       "\t-A           = use Linux AF_PACKET capture\n"
	       "\t-f           = fork a write process to avoid write blocks\n"
	       "\t-C interface = use pcap packet capture\n"
yorn's avatar
yorn committed
532
	       "\t               use CTRL+C to exit the program otherwise\n\n", name);
Sampo Saaristo's avatar
Sampo Saaristo committed
533 534 535 536 537 538 539 540
}


/*
 * crude_handler() - simple signal handler function
 */
void crude_handler(int value)
{
yorn's avatar
yorn committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
	struct sched_param pri;
	RUDEBUG7("\ncrude: SIGNAL caught - exiting...\n");

	/* Check & restore process priority */
	if((getuid() == 0) && (sched_getscheduler(0) != SCHED_OTHER))
	{
		pri.sched_priority = 0;
		if(sched_setscheduler(0, SCHED_OTHER, &pri) < 0)
		{
			RUDEBUG1("crude_handler: crude priority failure: %s\n",strerror(errno));
		}
		else
		{
			RUDEBUG7("crude_handler: crude priority restored\n");
		}
	}

	if(nflows > 0){ print_stats(); }
Olav Kvittem's avatar
Olav Kvittem committed
559 560 561 562 563 564
	if(main_file > 0){
	  output_data(main_output, 1);
	  close(main_file); 
	  if ( main_file != main_output) // forking
	    close(main_output); // will hopefully close the pipe so that the child dies
	}
yorn's avatar
yorn committed
565 566 567
	if(main_socket > 0){ close(main_socket); }
	RUDEBUG1("\ncrude: captured/processed %lu packets\n", pkt_count);
	exit(0);
Sampo Saaristo's avatar
Sampo Saaristo committed
568 569 570 571 572 573
}


/*
 * make_conn()   - make the required connection(s)
 */
Arne Øslebø's avatar
Arne Øslebø committed
574
static int make_conn(unsigned short port, char *ifaddr,int use_ip6,unsigned int ifindex)
Sampo Saaristo's avatar
Sampo Saaristo committed
575
{
yorn's avatar
yorn committed
576 577 578 579
	struct sockaddr_storage our_addr;
	struct in6_addr our_ip6;
	struct in_addr our_ip4;
	int our_sock;
Arne Øslebø's avatar
Arne Øslebø committed
580

yorn's avatar
yorn committed
581 582
	memset(&our_addr, 0, sizeof(struct sockaddr_storage));
	((struct sockaddr_in6*)&our_addr)->sin6_port = htons(port);
Arne Øslebø's avatar
Arne Øslebø committed
583 584


yorn's avatar
yorn committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	if((ifaddr == NULL) || (strlen(ifaddr) == 0))
	{
		if(use_ip6){
				((struct sockaddr_in6*)&our_addr)->sin6_addr = in6addr_any;
				((struct sockaddr_in6*)&our_addr)->sin6_family = AF_INET6;
				RUDEBUG7("crude: using an ipv6 wildcard interface \n");
		}
		else
		{
			((struct sockaddr_in*)&our_addr)->sin_addr.s_addr = INADDR_ANY;
				((struct sockaddr_in*)&our_addr)->sin_family = AF_INET;
				RUDEBUG7("crude: using an ipv4 wildcard interface \n");
		}
	}
	else if((inet_pton(AF_INET6, ifaddr, &our_ip6)) > 0)
	{
		((struct sockaddr_in6*)&our_addr)->sin6_addr = our_ip6;
		((struct sockaddr_in6*)&our_addr)->sin6_family = AF_INET6;
		RUDEBUG7("crude: using an ipv6 interface \n");
	}
	else if((inet_pton(AF_INET, ifaddr, &our_ip4)) > 0)
	{
		((struct sockaddr_in*)&our_addr)->sin_addr = our_ip4;
		((struct sockaddr_in*)&our_addr)->sin_family = AF_INET;
		RUDEBUG7("crude: using an ipv4 interface \n");
Arne Øslebø's avatar
Arne Øslebø committed
610 611 612
	}
	else
	{
yorn's avatar
yorn committed
613 614 615 616
		RUDEBUG1("crude: invalid interface address %s !\n",ifaddr);
		return -1;
	}

Olav Kvittem's avatar
Olav Kvittem committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
	
	if ( opt_af_packet) { // ip packet interface
	  if ( (our_sock=socket( AF_PACKET ,SOCK_DGRAM, htons(ETH_P_IP|ETH_P_IPV6) ) ) < 0 ) {
	    RUDEBUG1("crude: socket(AF_PACKET,) failed : %s\n", strerror(errno));
	  }
	  struct sockaddr_ll link;
	  memset(&link, 0, sizeof(struct sockaddr_ll));
	  link.sll_family = AF_PACKET;
	  link.sll_ifindex = if_nametoindex("eth0");
	  //	  link.sll_protocol = ETH_P_IP; 
	  
	  if(bind(our_sock, (struct sockaddr *)&link, sizeof(struct sockaddr_ll)) < 0)
	    {
	      RUDEBUG1("crude: bind(AF_packet) failed: %s\n", strerror(errno));
	      close(our_sock);
	      return -3;
	      } 
	} else if (opt_pcap) {
	  struct bpf_program fp;		/* The compiled filter */
	  char filter[100];
	  char errbuf[PCAP_ERRBUF_SIZE];

	  sprintf( filter, "udp and port %d", port);

	  if ( ( main_pcap=pcap_open_live("eth0", BUFSIZ, 1, 1000, errbuf) ) == NULL){
	    RUDEBUG1("crude: pcap open_live failed : %s\n", strerror(errno));
	    return(-1);
	  } 
	  if ( pcap_compile(main_pcap, &fp, filter, 0, PCAP_NETMASK_UNKNOWN) == -1) {
	    RUDEBUG1("Couldn't parse filter %s: %s\n", filter, pcap_geterr(main_pcap));
	    return(-1);
	  }
	if ( pcap_setfilter(main_pcap, &fp) == -1) {
	    RUDEBUG1("Couldn't install filter %s: %s\n", filter, pcap_geterr(main_pcap));
	    return(-1);
	  }
	  
	} else {

	  if( (our_sock=socket(our_addr.ss_family ,SOCK_DGRAM,0) ) < 0)
	    {
yorn's avatar
yorn committed
658 659
		RUDEBUG1("crude: socket() failed: %s\n", strerror(errno));
		return -2;
Olav Kvittem's avatar
Olav Kvittem committed
660 661 662 663 664 665 666 667
	    }

	  if(bind(our_sock, (struct sockaddr *)&our_addr, sizeof(struct sockaddr_storage)) < 0)
	    {
	      RUDEBUG1("crude: bind() failed: %s\n", strerror(errno));
	      close(our_sock);
	      return -3;
	    }
Arne Øslebø's avatar
Arne Øslebø committed
668
	}
yorn's avatar
yorn committed
669 670 671

	if(isMulticastAddr(&our_addr)>0)
	{
Olav Kvittem's avatar
Olav Kvittem committed
672
		RUDEBUG7("crude: make_conn(): address is a multicast one : port %d if %s\n",port,ifaddr);
yorn's avatar
yorn committed
673 674 675 676
		if(joinGroup(our_sock, 0, 200, &our_addr,ifindex) < 0){
			RUDEBUG1("crude: make_conn() failed to join group\n");
		close(our_sock);
		return -4;
Arne Øslebø's avatar
Arne Øslebø committed
677
	}
yorn's avatar
yorn committed
678 679
		else
			RUDEBUG7("crude: make_conn() group joined\n");
Arne Øslebø's avatar
Arne Øslebø committed
680

yorn's avatar
yorn committed
681
	}
Sampo Saaristo's avatar
Sampo Saaristo committed
682

yorn's avatar
yorn committed
683
	return our_sock;
Sampo Saaristo's avatar
Sampo Saaristo committed
684 685 686 687 688 689 690 691 692
}


/*
 * decode_file() - read the file and print the statistics to stdout in
 *                 human readable form
 */
static int decode_file(void)
{
yorn's avatar
yorn committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
	struct udp_data *ptr1   = NULL;
	struct crude_struct *ptr2 = NULL;
	char *buffer            = NULL;
	int buf_len             = 0;
	struct sockaddr_storage s_add,d_add;
	char str1[INET6_ADDRSTRLEN],str2[INET6_ADDRSTRLEN];

	/* Allocate memory for the small buffer */
	buf_len = (sizeof(struct udp_data) + sizeof(struct crude_struct));
	if((buffer=(char *)malloc(buf_len)) == NULL)
	{
		RUDEBUG1("crude: couldn't allocate memory: %s\n", strerror(errno));
		return -10;
	}

	memset(str1,0,INET6_ADDRSTRLEN);
	memset(str2,0,INET6_ADDRSTRLEN);

	while(read(main_file,buffer,buf_len) > 0)
	{
		pkt_count++;
		ptr1 = (struct udp_data*)buffer;
		ptr2 = (struct crude_struct*)(buffer + sizeof(struct udp_data));
		s_add = ptr2->src;
		d_add = ptr1->dest_addr;
		char srcport[10];

		get_str_addr(s_add,str1);
		get_str_addr(d_add,str2);

		printf("ID=%lu SEQ=%lu SRC=%s:%hu DST=%s:%hu "
		       "Tx=%ld.%06ld Rx=%ld.%06ld SIZE=%ld\n",
		       (unsigned long)ntohl(ptr1->flow_id),
		       (unsigned long)ntohl(ptr1->sequence_number),
		       str1, ntohs(((struct sockaddr_in *)&s_add)->sin_port),
		       str2, ntohs(ptr2->dest_port),
		       (unsigned long)ntohl(ptr1->tx_time_seconds),
		       (unsigned long)ntohl(ptr1->tx_time_useconds),
		       (unsigned long)ntohl(ptr2->rx_time_seconds),
		       (unsigned long)ntohl(ptr2->rx_time_useconds),
		       (long)ntohl(ptr2->pkt_size));
	}

	if(errno){ RUDEBUG1("crude: read failed: %s\n", strerror(errno)); }
	free(buffer);
	RUDEBUG1("crude: captured/processed %lu packets\n", pkt_count);
	return 0;
Sampo Saaristo's avatar
Sampo Saaristo committed
740 741 742 743 744
}


/*
 * runtime_stats() - don't record: gather statistics at runtime...
yorn's avatar
yorn committed
745
 * This routine
Sampo Saaristo's avatar
Sampo Saaristo committed
746 747 748
 */
static int runtime_stats(unsigned short port, unsigned long limit)
{
yorn's avatar
yorn committed
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
	long               rec_bytes = 0;     /* Bytes read            */
	int                wri_bytes = 0;     /* Bytes written         */
	int                src_len = sizeof(struct sockaddr_in6);
	struct sockaddr_in6 src_addr;
	struct timeval     time1;
	char buffer[PMAXSIZE];
	struct udp_data *data = (struct udp_data *) buffer;
	int i;
	struct flow_stat *fsp;
	unsigned long seq;
	long tx_s;
	long tx_us;
	unsigned long flowid;
	long delay_s;
	long delay_us;
	long jitter_s;
	long jitter_us;

	/* Initialize some variables */
	memset(buffer,0,PMAXSIZE);
Arne Øslebø's avatar
Arne Øslebø committed
769
//TODO: mozna misto sockaddr_in6 by se melo pouzit sockaddr_storage
yorn's avatar
yorn committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
	while(1)
	{
		rec_bytes = recvfrom(main_socket, buffer, PMAXSIZE, 0,
		                     (struct sockaddr *)&src_addr, (socklen_t *)&src_len);
		if(rec_bytes <= 0)
		{
			RUDEBUG1("crude: error when receiving packet: %s\n",strerror(errno));
		}
		else
		{
			gettimeofday(&time1, NULL);
			flowid = ntohl(data->flow_id);
			for (i = 0; i < nflows; i++)
			{
				if (flows[i].flowid == flowid)
					break;
			}
			if (i == nflows)
			{
				continue;
			}
			fsp = &(flows[i]);
			/* BUG: the remaining code in the loop should really be atomic, but
			 * how do we guaratee that?
			 * Anyway, if you stop your sources before hitting CTRL-C this should
			 * be OK. */
			seq = ntohl(data->sequence_number);
			fsp->rec++;
			tx_s = ntohl(data->tx_time_seconds);
			tx_us = ntohl(data->tx_time_useconds);
			delay_s = time1.tv_sec - tx_s;
			delay_us = time1.tv_usec - tx_us;
			if (seq <= fsp->seq)
			{
				fsp->oos++;
				if (seq < fsp->seqmin)
				{
					/* Should only occur in case of reordering of the first packets */
					fsp->seqmin = seq;
					if (fsp->rec == 1)
					{
						/* First packet: do the initialization.
						 * Here we use a trick to move the initialization conditional out
						 * of the normal execution path: we initialized seqmin with
						 * ULONG_MAX so that when we receive the first packet it's sequence
						 * number is always less than that.  :-)  */
						fsp->oos--; /* The first packet obviously isn't out of sequence */
						fsp->first_rx_sec = time1.tv_sec;
						fsp->first_rx_usec = time1.tv_usec;
						fsp->seq = seq;
						goto update_last;
					}
				}
			}
			else
			{
				fsp->seq = seq;
			}
			fsp->ds_sec += delay_s;
			fsp->ds_usec += delay_us;
			jitter_s = delay_s - fsp->last_delay_sec;
			jitter_us = delay_us - fsp->last_delay_usec;
			/* We need the absolute value, so: */
			if (jitter_s < 0)
			{
				jitter_s = -jitter_s;
				jitter_us = -jitter_us;
			}  /* At this point, jitter_s >= 0 */
			if (jitter_us < 0)
			{
				if (jitter_s == 0)
				{
					jitter_us = -jitter_us;
				}
				else
				{
					jitter_us += 1000000;
					jitter_s--;
				}
			}  /* Now both jitter components are positive */
			fsp->js_sec += jitter_s;
			fsp->js_usec += jitter_us;
			if (jitter_s > fsp->max_jitter_sec ||
					jitter_s == fsp->max_jitter_sec && jitter_us > fsp->max_jitter_usec)
			{
				fsp->max_jitter_sec = jitter_s;
				fsp->max_jitter_usec = jitter_us;
			}
		update_last:
			fsp->last_tx_sec = tx_s;
			fsp->last_tx_usec = tx_us;
			fsp->last_rx_sec = time1.tv_sec;
			fsp->last_rx_usec = time1.tv_usec;
			fsp->last_delay_sec = delay_s;
			fsp->last_delay_usec = delay_us;
			fsp->s_size += rec_bytes;
		}

		pkt_count++;
		/* Note that we only count packets from the flows we are gathering
		 * statistics for: the others don't matter in this case. */
		if((limit != 0) && (pkt_count >= limit)){ break; }
	} /* end of while */

	RUDEBUG1("\ncrude: captured/processed %lu packets\n", pkt_count);
	return 0;
Sampo Saaristo's avatar
Sampo Saaristo committed
876 877 878 879 880 881 882 883 884
}


/*
 * print_stats() - print the statistics at the end of a runtime statistics
 *                 gathering session
 */
void print_stats(void)
{
yorn's avatar
yorn committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
	int i;
	struct flow_stat *fsp;
	long long sec, usec;
	double interval;

	printf("\n"
	       "Runtime statistics results: \n"
	       "--------------------------- \n");
	for (i = 0; i < nflows; i++)
	{
		fsp = &flows[i];
		printf("\nFlow_ID=%lu \n", fsp->flowid);
		printf("Packets: received=%lu   out-of-seq=%lu   "
		       "lost(est)=%lu \n", fsp->rec, fsp->oos,
		       fsp->rec > 0 ? (fsp->seq - fsp->seqmin + 1 - fsp->rec) : 0);
		printf("Total bytes received=%llu \n", fsp->s_size);
		if (fsp->rec > 0)
		{
			printf("Sequence numbers: first=%lu   last=%lu \n",
			       fsp->seqmin, fsp->seq);
		}
		if (fsp->rec < 2)
		{
			printf("Can't calculate statistics: not enough packets received. \n");
			continue;
		}
		sec = fsp->ds_sec / fsp->rec;
		usec = (fsp->ds_usec + 1000000 * (fsp->ds_sec % fsp->rec)) / fsp->rec;
		sec += usec / 1000000;
		usec %= 1000000;

		// printf( "Raw data:       sec = %lld    usec = %lld\n", sec, usec );

		/* Possible with dessynchronized clocks */
		/* sec and usec must have same sign for output */
		if ( (sec > 0 ) && (usec < 0) )
		{
			sec--;
			usec = 1000000 + usec;
		}
		else if ( (sec < 0 ) && (usec > 0) )
		{
			sec++;
			usec = -1000000 + usec;
		}

		// printf( "Corrected data: sec = %lld    usec = %lld\n", sec, usec );

		/* print average delay as sign and absolute value */
		if ( (sec < 0) || (usec < 0) )
		{
			sec  = llabs( sec );
			usec = llabs( usec );
			printf("Delay: average = -%lld.%06llu   ", sec, usec);
		}
		else
		{
			printf("Delay: average = %lld.%06llu   ", sec, usec);
		}

		/* Both components of all jitter values are positive, thus the sum of
		 * them is also positive */
		sec = fsp->js_sec / (fsp->rec - 1);
		usec = (fsp->js_usec + 1000000 * (fsp->js_sec % (fsp->rec - 1))) /
		       (fsp->rec - 1);
		sec += usec / 1000000;
		usec %= 1000000;
		printf("jitter=%llu.%06llu   seconds \n", sec, usec);
		printf("Absolute maximum jitter=%ld.%06ld   seconds \n",
		       fsp->max_jitter_sec, fsp->max_jitter_usec);
		sec = (long) fsp->last_rx_sec - (long) fsp->first_rx_sec;
		usec = (long) fsp->last_rx_usec - (long) fsp->first_rx_usec;
		interval = (double) sec + (double) usec / 1000000.0;
		printf("Throughput=%g   Bps  (from first to last packet received) \n",
		       (double) fsp->s_size / interval);
	}
	printf("\n");
Sampo Saaristo's avatar
Sampo Saaristo committed
962 963
}

Olav Kvittem's avatar
Olav Kvittem committed
964 965 966 967 968 969 970
static int check_response( struct timeval tw1,  char *msg){
	struct timeval tw2;
	gettimeofday(&tw2, NULL);
	int tdiff_us=(tw2.tv_sec-tw1.tv_sec)*10^6 + (tw2.tv_usec-tw1.tv_usec);
	if (tdiff_us > 500)
		fprintf(  stderr, "used time us: %d - task %s\n", tdiff_us, msg );
}
Sampo Saaristo's avatar
Sampo Saaristo committed
971 972 973 974 975 976

/*
 * rec_to_file() - record packets to file in binary format...
 */
static int rec_to_file(unsigned short port, unsigned long limit)
{
yorn's avatar
yorn committed
977 978 979 980
	long               rec_bytes = 0;     /* Bytes read            */
	int                wri_bytes = 0;     /* Bytes written         */
	int                src_len = sizeof(struct sockaddr_storage);
	struct sockaddr_storage src_addr;
Olav Kvittem's avatar
Olav Kvittem committed
981
	struct timeval     time1, tw1;
yorn's avatar
yorn committed
982 983
	struct crude_struct  other_info;
	char buffer[PMAXSIZE];
Olav Kvittem's avatar
Olav Kvittem committed
984 985
	struct udp_data *rude_data= (struct udp_data *)&buffer;
	int rude_seq=0;
yorn's avatar
yorn committed
986 987 988 989 990

	/* Initialize some variables */
	memset(buffer,0,PMAXSIZE);
	other_info.dest_port = htons(port);

Olav Kvittem's avatar
Olav Kvittem committed
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
	// establish output file ring buffer
	osize = sizeof(struct udp_data) + sizeof(struct crude_struct);
	obufsize=OBUFFERS * osize;
	ochunksize = osize * OCHUNKS;
	obuffer=malloc(obufsize);

	if ( opt_fork)
	  main_output=fork_write();
	else
	  main_output=main_file;


	  struct pcap_pkthdr *header;
	  const u_char *packet;
	  int result;

	  while(1)
	    {
	      if ( opt_pcap){
		if ( (  result= pcap_next_ex(main_pcap, &header, &packet)) < 1 ){
		  if ( result == 0 ) continue;  // just timeout waiting for data
		  fprintf( stderr, "crude: error when receiving pcap packet: result %d , error %s \n", 
			   result, pcap_geterr(main_pcap));
		  rec_bytes=0;
		};
		rec_bytes = header->caplen;
	      } else {
yorn's avatar
yorn committed
1018 1019
		rec_bytes = recvfrom(main_socket, buffer, PMAXSIZE, 0,
		                     (struct sockaddr *)&src_addr, (socklen_t *)&src_len);
Olav Kvittem's avatar
Olav Kvittem committed
1020 1021
	      }
	      if(rec_bytes <= 0)
yorn's avatar
yorn committed
1022
		{
Olav Kvittem's avatar
Olav Kvittem committed
1023
		  RUDEBUG1("crude: error when receiving packet: %s\n",strerror(errno));
yorn's avatar
yorn committed
1024
		}
Olav Kvittem's avatar
Olav Kvittem committed
1025
	      else
yorn's avatar
yorn committed
1026
		{
Olav Kvittem's avatar
Olav Kvittem committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
		  if ( opt_pcap || opt_af_packet){ 
		    if ( opt_pcap) { // ether header
		      rude_data= (struct udp_data*) (packet + 14) ; // feil : sizeof(struct ether_header);
		      memcpy(&time1, &header->ts, sizeof(struct timeval));
		    } 
		      
		    unsigned short iphdrlen;
		    struct iphdr *iph = (struct iphdr*)rude_data;

		    if ( iph->protocol == 17){ // udp
		      iphdrlen = iph->ihl*4;
		      struct udphdr *udph = (struct udphdr*)((char*)rude_data + iphdrlen);
		      if ( ntohs(udph->dest) != port)
			continue;

		      struct sockaddr_in* v4=(struct sockaddr_in *)&(src_addr);
		      v4->sin_family=AF_INET;
		      v4->sin_addr=*(struct in_addr*)&iph->saddr;
		      /* turn around elsewhere
			 uint32_t v4adr=ntohl(iph->saddr);
			 memcpy( &(v4->sin_addr), &v4adr, sizeof(uint32_t)); */
		      v4->sin_port = port;
		    } else {
		      continue;
		    }
		    rude_data=(struct udp_data*)((char*)rude_data + iphdrlen + sizeof(struct udphdr));
		  } 

		  if ( opt_ktime)
		      ioctl(main_socket, SIOCGSTAMP, &time1);
		  else if ( time1.tv_sec == 0)
		      gettimeofday(&time1, NULL);
		   
		  int newseq=ntohl(rude_data->sequence_number);
		  if ( rude_seq > 0 && newseq != (rude_seq+1) ){
		    fprintf( stderr, "Lost seq : %d - %d\n", rude_seq, newseq-rude_seq-1);
		  }
		  rude_seq=newseq;
		 
		  
yorn's avatar
yorn committed
1067 1068 1069 1070 1071
			pkt_count++;
			other_info.rx_time_seconds  = htonl(time1.tv_sec);
			other_info.rx_time_useconds = htonl(time1.tv_usec);
			other_info.pkt_size         = htonl(rec_bytes);

Olav Kvittem's avatar
Olav Kvittem committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
			other_info.src = src_addr; /* don't use network order here
			struct sockaddr_in *sin_ref=(struct sockaddr_in*)&other_info.src;
			struct sockaddr_in *src_ref=(struct sockaddr_in*)&src_addr;
			sin_ref->sin_family=htons(AF_INET);
			sin_ref->sin_port = htons(((struct sockaddr_in*)&src_addr)->sin_port);
			uint32_t* h_a_r = (uint32_t*)&(src_ref->sin_addr);
			uint32_t n_a = htonl(*h_a_r);
			memcpy(&(sin_ref->sin_addr), &n_a, sizeof(struct in_addr));*/

			// fill up buffer
			int newfree=ofree + osize;
		        if ( ( newfree > odata && newfree <= obufsize ) ||
			     ( newfree < odata ) ){
			  memcpy( obuffer + ofree, rude_data, sizeof(struct udp_data));
			  memcpy( obuffer + ofree + sizeof(struct udp_data), &other_info,
				  sizeof(struct crude_struct));

			  ofree = newfree % obufsize;
			} else {
			  perror ("Internal output buffer overflow\n");
			}
			// output data until empty or bad return
			output_data(main_output, 0);
			// RUDEBUG7("crude: pkt %lu (%lubytes) status: %s\n",
			//         pkt_count, rec_bytes, strerror(errno));
yorn's avatar
yorn committed
1097
		}
Sampo Saaristo's avatar
Sampo Saaristo committed
1098

yorn's avatar
yorn committed
1099
		if((limit != 0) && (pkt_count >= limit)){ break; }
Olav Kvittem's avatar
Olav Kvittem committed
1100 1101
	    } /* end of while */

Sampo Saaristo's avatar
Sampo Saaristo committed
1102

yorn's avatar
yorn committed
1103 1104
	RUDEBUG1("\ncrude: captured/processed %lu packets \n", pkt_count);
	return 0;
Sampo Saaristo's avatar
Sampo Saaristo committed
1105 1106
}

Olav Kvittem's avatar
Olav Kvittem committed
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
static int fork_write( ){
	// fork a process to write to disk to avoid hangups
	pid_t child = 0;
	int recsz= sizeof(struct udp_data) + sizeof(struct crude_struct);
	char *filebuffer=malloc(recsz);

	if (pipe(pipefd) == -1 ) // Create new pipe
        {
                fprintf(stderr, "Failed to create pipe\n");
                exit(1);
        }
	fcntl(pipefd[1], F_SETPIPE_SZ, 1001001);
	fprintf( stderr, "pipe size is : %d\n", fcntl(pipefd[1], F_GETPIPE_SZ) );
	child = fork();   

	if ( child){ // mother process
	  // set noblocking write to avoid buffer emptying wait.
	  if ( fcntl(pipefd[1], F_SETFL, fcntl(pipefd[1], F_GETFL, 0) | O_NONBLOCK) != 0 )
	    fprintf( stderr, "fcntl nonblock failed : %d\n", errno );
	  else  RUDEBUG1( "fcntl nonblock OK flag : %d\n", fcntl(pipefd[1], F_GETFL, 0) & O_NONBLOCK );
	  return(pipefd[1]);

	} else { // in child - read and write to disk
	  close(pipefd[1]); // Child is read only
	  signal(SIGINT, SIG_IGN); // ignore signal - just wait for eof 
	  int bytes;

	  while( (bytes=read(pipefd[0], filebuffer, ochunksize)) > 0){
	    write( main_file, filebuffer, bytes);
	    RUDEBUG7("crude: writing to disk %u \n", bytes) ;
	  }
	  exit(0);
	}
}

// output data until empty or bad return
static int output_data(int fd, int flush){
	ssize_t result;
	int written=0;
	struct timeval tw1, tw2;

	while (ofree != odata){
		int ochunk=ofree-odata;
		if ( ochunk < 0 ) ochunk = obufsize-odata;
		if (flush || ochunk >= ochunksize ){ // delay writes until chunksize
		  // return(0);// just to see that write is not the problem  #######################
			if ( ochunk > ochunksize ) ochunk=ochunksize ;
			gettimeofday(&tw1, NULL);
			if ( (result=write(fd, obuffer+odata, ochunk )) > 0 ){ // IO buffer overflow 
				check_response(tw1, "write");
				odata= (odata + result) % obufsize;
				written += result;
				RUDEBUG1("odata %lu ofree %d chunk %d result %d\n", odata, ofree, ochunk, (int)result);
			} else {  // I'll be back
				check_response(tw1, "error");
				if ( result == EAGAIN || result == EWOULDBLOCK){
				  RUDEBUG1( "Write failed wouldblock: reason %d\n", (int)result);
					break; // probably hit full ouput buffer
				} else {
				  fprintf( stderr, "Write failed : return %d : cause %s\n", (int)result, strerror(errno));
				}
			}
		} else {
			break;
		}
	}
	return(written);
}


/* not used */

static void handle_interrupt(int signum){
  output_data(pipefd[1], 1);
  close(main_file);
  fprintf(stderr, "Cancelled by signal : %d", signum);
  fflush(stderr);
  exit(1);
}
Sampo Saaristo's avatar
Sampo Saaristo committed
1186

Arne Øslebø's avatar
Arne Øslebø committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
/*
* get_str_addr - prints address in readable format into buffer
*/
static void get_str_addr(struct sockaddr_storage src_addr,char buffer[]){
	char straddr[INET6_ADDRSTRLEN];
	switch (src_addr.ss_family) {
		case AF_INET:{
			struct sockaddr_in* dstin = (struct sockaddr_in *)&(src_addr);
			strncpy(buffer,inet_ntop(AF_INET, &(dstin->sin_addr), straddr, sizeof(straddr)),INET6_ADDRSTRLEN-1);

			}
			return;
		case AF_INET6:{
			struct sockaddr_in6* dstin = (struct sockaddr_in6 *)&(src_addr);
			strncpy(buffer,inet_ntop(AF_INET6, &(dstin->sin6_addr), straddr, sizeof(straddr)),INET6_ADDRSTRLEN-1);
			//if address starts with ::ffff: cut this part from string
			if(strncmp(buffer,preffix,strlen(preffix)) == 0){
				strncpy(buffer,straddr+strlen(preffix),INET6_ADDRSTRLEN-1);
				}
			return;
			}
yorn's avatar
yorn committed
1208
	}
Arne Øslebø's avatar
Arne Øslebø committed
1209 1210
}

Sampo Saaristo's avatar
Sampo Saaristo committed
1211 1212 1213 1214 1215
/*
 * rec_n_print() - print information of received packets to stdout
 */
static int rec_n_print(unsigned short port, unsigned long limit)
{
yorn's avatar
yorn committed
1216
	ssize_t            rec_bytes = 0;     /* Bytes read            */
yorn's avatar
yorn committed
1217
	int                src_len   = sizeof(struct sockaddr_storage);
yorn's avatar
yorn committed
1218
	int                ttl = 64;
yorn's avatar
yorn committed
1219
	int                hoplimit = 64;
yorn's avatar
yorn committed
1220
	int                received_ttl;
yorn's avatar
yorn committed
1221
	struct sockaddr_storage src_addr;
yorn's avatar
yorn committed
1222 1223
	struct msghdr msgh;
	struct iovec iov;
yorn's avatar
yorn committed
1224 1225 1226
	struct timeval     time1;
	struct udp_data    *udp_ptr;
	struct sockaddr_storage  d_add;
yorn's avatar
yorn committed
1227 1228
	struct cmsghdr *cmptr = NULL;
	#define CONTROLLEN (sizeof(struct cmsghdr) + sizeof(int))
yorn's avatar
yorn committed
1229 1230 1231 1232 1233 1234
	char buffer[PMAXSIZE], str1[INET6_ADDRSTRLEN], str2[INET6_ADDRSTRLEN];

	/* Initialize some variables */
	memset(buffer,0,PMAXSIZE);
	memset(str1,0,INET6_ADDRSTRLEN);
	memset(str2,0,INET6_ADDRSTRLEN);
yorn's avatar
yorn committed
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
	cmptr = malloc(CONTROLLEN);

	iov.iov_base       = &buffer;
	iov.iov_len        = sizeof(buffer);
	memset(&msgh, 0, sizeof(msgh));
	msgh.msg_name       = &src_addr;
	msgh.msg_namelen    = sizeof(src_addr);
	msgh.msg_iov        = &iov;
	msgh.msg_iovlen     = 1;
	msgh.msg_control    = (caddr_t) cmptr;
	msgh.msg_controllen = CONTROLLEN;

	if(setsockopt(main_socket, IPPROTO_IP, IP_RECVTTL, &ttl,sizeof(ttl))>0) 
yorn's avatar
yorn committed
1248
	{
yorn's avatar
yorn committed
1249 1250 1251 1252 1253
		RUDEBUG1("crude: unable to receive TTL values for IPv4: %s\n",strerror(errno));
	}
	if(setsockopt(main_socket, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &hoplimit,sizeof(hoplimit))>0)
	{
		RUDEBUG1("crude: unable to receive HOPLIMIT values for IPv6: %s\n",strerror(errno));
yorn's avatar
yorn committed
1254 1255 1256
	}
	for( ; ; )
	{
Olav Kvittem's avatar
Olav Kvittem committed
1257 1258
	  rec_bytes = recvmsg(main_socket, &msgh, MSG_WAITALL);

yorn's avatar
yorn committed
1259 1260 1261 1262 1263 1264
		if(rec_bytes <= 0)
		{
			RUDEBUG1("crude: error when receiving packet: %s\n",strerror(errno));
		}
		else
		{
yorn's avatar
yorn committed
1265 1266 1267 1268 1269
			struct cmsghdr *cmsg;
			int *ttlptr;
			received_ttl = -1;
			for (cmsg = CMSG_FIRSTHDR(&msgh); cmsg != NULL;
					cmsg = CMSG_NXTHDR(&msgh,cmsg)) {
yorn's avatar
yorn committed
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
				if ((
						( (cmsg->cmsg_level == IPPROTO_IP) &&
							(cmsg->cmsg_type == IP_TTL)
						) || (
							(cmsg->cmsg_level == SOL_IPV6) &&
							(cmsg->cmsg_type == IPV6_HOPLIMIT))
						) &&
							(cmsg->cmsg_len) ){
					ttlptr = (int *) CMSG_DATA(cmsg);
					received_ttl = *ttlptr;
					break;
				}
				if ((cmsg->cmsg_level == SOL_IPV6) &&
						(cmsg->cmsg_type == IPV6_HOPLIMIT) &&
yorn's avatar
yorn committed
1284 1285 1286 1287 1288 1289 1290
						(cmsg->cmsg_len) ){
					ttlptr = (int *) CMSG_DATA(cmsg);
					received_ttl = *ttlptr;
					break;
				}
			}
 			gettimeofday(&time1, NULL);
yorn's avatar
yorn committed
1291 1292 1293 1294 1295 1296 1297 1298
			pkt_count++;
			udp_ptr = (struct udp_data*)buffer;
			d_add = udp_ptr->dest_addr;

			get_str_addr(src_addr,str1);
			get_str_addr(d_add,str2);

			printf("ID=%lu SEQ=%lu SRC=%s:%hu DST=%s:%hu "
yorn's avatar
yorn committed
1299
			       "Tx=%lu.%06lu Rx=%ld.%06ld HOPLIMIT=%d SIZE=%ld\n",
yorn's avatar
yorn committed
1300 1301 1302 1303 1304
			       (unsigned long)ntohl(udp_ptr->flow_id),
			       (unsigned long)ntohl(udp_ptr->sequence_number),
			       str1, ntohs(((struct sockaddr_in *)&src_addr)->sin_port), str2, port,
			       (unsigned long)ntohl(udp_ptr->tx_time_seconds),
			       (unsigned long)ntohl(udp_ptr->tx_time_useconds),
yorn's avatar
yorn committed
1305
			       time1.tv_sec, time1.tv_usec, received_ttl, rec_bytes);
yorn's avatar
yorn committed
1306 1307
			fflush(stdout);
		}
Arne Øslebø's avatar
Arne Øslebø committed
1308

yorn's avatar
yorn committed
1309 1310 1311 1312 1313
		if((limit != 0) && (pkt_count >= limit)){ break; }
	} /* end of while */

	RUDEBUG1("\ncrude: captured/processed %lu packets\n", pkt_count);
	return 0;
Sampo Saaristo's avatar
Sampo Saaristo committed
1314
}