Home | History | Annotate | Line # | Download | only in dist
pcap-sita.c revision 1.1.1.2
      1 /*	$NetBSD: pcap-sita.c,v 1.1.1.2 2013/04/06 15:57:49 christos Exp $	*/
      2 
      3 /*
      4  *  pcap-sita.c: Packet capture interface additions for SITA ACN devices
      5  *
      6  *  Copyright (c) 2007 Fulko Hew, SITA INC Canada, Inc <fulko.hew (at) sita.aero>
      7  *
      8  *  License: BSD
      9  *
     10  *  Redistribution and use in source and binary forms, with or without
     11  *  modification, are permitted provided that the following conditions
     12  *  are met:
     13  *
     14  *  1. Redistributions of source code must retain the above copyright
     15  *     notice, this list of conditions and the following disclaimer.
     16  *  2. Redistributions in binary form must reproduce the above copyright
     17  *     notice, this list of conditions and the following disclaimer in
     18  *     the documentation and/or other materials provided with the
     19  *     distribution.
     20  *  3. The names of the authors may not be used to endorse or promote
     21  *     products derived from this software without specific prior
     22  *     written permission.
     23  *
     24  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
     25  *  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
     26  *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
     27  */
     28 
     29  /* $Id: pcap-sita.c */
     30 
     31 #ifdef HAVE_CONFIG_H
     32 #include "config.h"
     33 #endif
     34 
     35 #include <stdio.h>
     36 #include <string.h>
     37 #include <stdlib.h>
     38 #include <unistd.h>
     39 #include <fcntl.h>
     40 #include <errno.h>
     41 #include <sys/time.h>
     42 #include <sys/socket.h>
     43 #include <netinet/in.h>
     44 #include <arpa/inet.h>
     45 #include "pcap-int.h"
     46 
     47 #include "pcap-sita.h"
     48 
     49 	/* non-configureable manifests follow */
     50 
     51 #define IOP_SNIFFER_PORT	49152			/* TCP port on the IOP used for 'distributed pcap' usage */
     52 #define MAX_LINE_SIZE		255				/* max size of a buffer/line in /etc/hosts we allow */
     53 #define MAX_CHASSIS			8				/* number of chassis in an ACN site */
     54 #define MAX_GEOSLOT			8				/* max number of access units in an ACN site */
     55 
     56 #define FIND			0
     57 #define LIVE			1
     58 
     59 typedef struct iface {
     60 	struct iface	*next;					/* a pointer to the next interface */
     61 	char			*name;					/* this interface's name on Wireshark */
     62 	char			*IOPname;				/* this interface's name on an IOP */
     63 	uint32_t		iftype;					/* the type of interface (DLT values) */
     64 } iface_t;
     65 
     66 typedef struct unit {
     67 	char				*ip;				/* this unit's IP address (as extracted from /etc/hosts) */
     68 	int					fd;					/* the connection to this unit (if it exists) */
     69 	int					find_fd;			/* a big kludge to avoid my programming limitations since I could have this unit open for findalldevs purposes */
     70 	int					first_time;			/* 0 = just opened via acn_open_live(),  ie. the first time, NZ = nth time */
     71 	struct sockaddr_in	*serv_addr;			/* the address control block for comms to this unit */
     72 	int					chassis;
     73 	int					geoslot;
     74 	iface_t				*iface;				/* a pointer to a linked list of interface structures */
     75 	char				*imsg;				/* a pointer to an inbound message */
     76 	int					len;				/* the current size of the inbound message */
     77 } unit_t;
     78 
     79 static char			*errorString;
     80 static unit_t		units[MAX_CHASSIS+1][MAX_GEOSLOT+1];	/* we use indexes of 1 through 8, but we reserve/waste index 0 */
     81 static fd_set		readfds;								/* a place to store the file descriptors for the connections to the IOPs */
     82 static fd_set		working_set;
     83 static int			max_fs;
     84 static char			static_buf[32];
     85 
     86 pcap_if_t			*acn_if_list;							/* pcap's list of available interfaces */
     87 
     88 static void dump_interface_list(void) {
     89 	pcap_if_t		*iff;
     90 	pcap_addr_t		*addr;
     91 	int				longest_name_len = 0;
     92 	char			*n, *d, *f;
     93 	int				if_number = 0;
     94 
     95 	iff = acn_if_list;
     96 	while (iff) {
     97 		if (iff->name && (strlen(iff->name) > longest_name_len)) longest_name_len = strlen(iff->name);
     98 		iff = iff->next;
     99 	}
    100 	iff = acn_if_list;
    101 	printf("Interface List:\n");
    102 	while (iff) {
    103 		n = (iff->name)							? iff->name			: "";
    104 		d = (iff->description)					? iff->description	: "";
    105 		f = (iff->flags == PCAP_IF_LOOPBACK)	? "L"				: "";
    106 		printf("%3d: %*s %s '%s'\n", if_number++, longest_name_len, n, f, d);
    107 		addr = iff->addresses;
    108 		while (addr) {
    109 			printf("%*s ", (5 + longest_name_len), "");		/* add some indentation */
    110 			printf("%15s  ", (addr->addr)		? inet_ntoa(((struct sockaddr_in *)addr->addr)->sin_addr)		: "");
    111 			printf("%15s  ", (addr->netmask)	? inet_ntoa(((struct sockaddr_in *)addr->netmask)->sin_addr)	: "");
    112 			printf("%15s  ", (addr->broadaddr)	? inet_ntoa(((struct sockaddr_in *)addr->broadaddr)->sin_addr)	: "");
    113 			printf("%15s  ", (addr->dstaddr)	? inet_ntoa(((struct sockaddr_in *)addr->dstaddr)->sin_addr)	: "");
    114 			printf("\n");
    115 			addr = addr->next;
    116 		}
    117 		iff = iff->next;
    118 	}
    119 }
    120 
    121 static void dump(unsigned char *ptr, int i, int indent) {
    122 	fprintf(stderr, "%*s", indent, " ");
    123 	for (; i > 0; i--) {
    124 		fprintf(stderr, "%2.2x ", *ptr++);
    125 	}
    126 	fprintf(stderr, "\n");
    127 }
    128 
    129 static void dump_interface_list_p(void) {
    130 	pcap_if_t		*iff;
    131 	pcap_addr_t		*addr;
    132 	int				if_number = 0;
    133 
    134 	iff = acn_if_list;
    135 	printf("Interface Pointer @ %p is %p:\n", &acn_if_list, iff);
    136 	while (iff) {
    137 		printf("%3d: %p %p next: %p\n", if_number++, iff->name, iff->description, iff->next);
    138 		dump((unsigned char *)iff, sizeof(pcap_if_t), 5);
    139 		addr = iff->addresses;
    140 		while (addr) {
    141 			printf("          %p %p %p %p, next: %p\n", addr->addr, addr->netmask, addr->broadaddr, addr->dstaddr, addr->next);
    142 			dump((unsigned char *)addr, sizeof(pcap_addr_t), 10);
    143 			addr = addr->next;
    144 		}
    145 		iff = iff->next;
    146 	}
    147 }
    148 
    149 static void dump_unit_table(void) {
    150 	int		chassis, geoslot;
    151 	iface_t	*p;
    152 
    153 	printf("%c:%c %s %s\n", 'C', 'S', "fd", "IP Address");
    154 	for (chassis = 0; chassis <= MAX_CHASSIS; chassis++) {
    155 		for (geoslot = 0; geoslot <= MAX_GEOSLOT; geoslot++) {
    156 			if (units[chassis][geoslot].ip != NULL)
    157 				printf("%d:%d %2d %s\n", chassis, geoslot, units[chassis][geoslot].fd, units[chassis][geoslot].ip);
    158 			p = units[chassis][geoslot].iface;
    159 			while (p) {
    160 				char *n = (p->name)			? p->name			: "";
    161 				char *i = (p->IOPname)		? p->IOPname		: "";
    162 				p = p->next;
    163 				printf("   %12s    -> %12s\n", i, n);
    164 			}
    165 		}
    166 	}
    167 }
    168 
    169 static int find_unit_by_fd(int fd, int *chassis, int *geoslot, unit_t **unit_ptr) {
    170 	int		c, s;
    171 
    172 	for (c = 0; c <= MAX_CHASSIS; c++) {
    173 		for (s = 0; s <= MAX_GEOSLOT; s++) {
    174 			if (units[c][s].fd == fd || units[c][s].find_fd == fd) {
    175 				if (chassis)	*chassis = c;
    176 				if (geoslot)	*geoslot = s;
    177 				if (unit_ptr)	*unit_ptr = &units[c][s];
    178 				return 1;
    179 			}
    180 		}
    181 	}
    182 	return 0;
    183 }
    184 
    185 static int read_client_nbytes(int fd, int count, unsigned char *buf) {
    186 	unit_t			*u;
    187 	int				chassis, geoslot;
    188 	int				len;
    189 
    190 	find_unit_by_fd(fd, &chassis, &geoslot, &u);
    191 	while (count) {
    192 		if ((len = recv(fd, buf, count, 0)) <= 0)	return -1;	/* read in whatever data was sent to us */
    193 		count -= len;
    194 		buf += len;
    195 	}															/* till we have everything we are looking for */
    196 	return 0;
    197 }
    198 
    199 static void empty_unit_iface(unit_t *u) {
    200 	iface_t	*p, *cur;
    201 
    202 	cur = u->iface;
    203 	while (cur) {											/* loop over all the interface entries */
    204 		if (cur->name)			free(cur->name);			/* throwing away the contents if they exist */
    205 		if (cur->IOPname)		free(cur->IOPname);
    206 		p = cur->next;
    207 		free(cur);											/* then throw away the structure itself */
    208 		cur = p;
    209 	}
    210 	u->iface = 0;											/* and finally remember that there are no remaining structure */
    211 }
    212 
    213 static void empty_unit(int chassis, int geoslot) {
    214 	unit_t	*u = &units[chassis][geoslot];
    215 
    216 	empty_unit_iface(u);
    217 	if (u->imsg) {											/* then if an inbound message buffer exists */
    218 		u->imsg = (char *)realloc(u->imsg, 1);				/* and re-allocate the old large buffer into a new small one */
    219 	}
    220 }
    221 
    222 static void empty_unit_table(void) {
    223 	int		chassis, geoslot;
    224 
    225 	for (chassis = 0; chassis <= MAX_CHASSIS; chassis++) {
    226 		for (geoslot = 0; geoslot <= MAX_GEOSLOT; geoslot++) {
    227 			if (units[chassis][geoslot].ip != NULL) {
    228 				free(units[chassis][geoslot].ip);			/* get rid of the malloc'ed space that holds the IP address */
    229 				units[chassis][geoslot].ip = 0;				/* then set the pointer to NULL */
    230 			}
    231 			empty_unit(chassis, geoslot);
    232 		}
    233 	}
    234 }
    235 
    236 static char *find_nth_interface_name(int n) {
    237 	int		chassis, geoslot;
    238 	iface_t	*p;
    239 	char	*last_name = 0;
    240 
    241 	if (n < 0) n = 0;												/* ensure we are working with a valid number */
    242 	for (chassis = 0; chassis <= MAX_CHASSIS; chassis++) {			/* scan the table... */
    243 		for (geoslot = 0; geoslot <= MAX_GEOSLOT; geoslot++) {
    244 			if (units[chassis][geoslot].ip != NULL) {
    245 				p = units[chassis][geoslot].iface;
    246 				while (p) {											/* and all interfaces... */
    247 					if (p->IOPname) last_name = p->name;			/* remembering the last name found */
    248 					if (n-- == 0) return last_name;					/* and if we hit the instance requested */
    249 					p = p->next;
    250 				}
    251 			}
    252 		}
    253 	}
    254 											/* if we couldn't fine the selected entry */
    255 	if (last_name)	return last_name;		/* ... but we did have at least one entry... return the last entry found */
    256 	return "";								/* ... but if there wasn't any entry... return an empty string instead */
    257 }
    258 
    259 int acn_parse_hosts_file(char *errbuf) {				/* returns: -1 = error, 0 = OK */
    260 	FILE	*fp;
    261 	char	buf[MAX_LINE_SIZE];
    262 	char	*ptr, *ptr2;
    263 	int		pos;
    264 	int		chassis, geoslot;
    265 	unit_t	*u;
    266 
    267 	empty_unit_table();
    268 	if ((fp = fopen("/etc/hosts", "r")) == NULL) {										/* try to open the hosts file and if it fails */
    269 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot open '/etc/hosts' for reading.");	/* return the nohostsfile error response */
    270 		return -1;
    271 	}
    272 	while (fgets(buf, MAX_LINE_SIZE-1, fp)) {			/* while looping over the file */
    273 
    274 		pos = strcspn(buf, "#\n\r");					/* find the first comment character or EOL */
    275 		*(buf + pos) = '\0';							/* and clobber it and anything that follows it */
    276 
    277 		pos = strspn(buf, " \t");						/* then find the first non-white space */
    278 		if (pos == strlen(buf))							/* if there is nothing but white space on the line */
    279 			continue;									/* ignore that empty line */
    280 		ptr = buf + pos;								/* and skip over any of that leading whitespace */
    281 
    282 		if ((ptr2 = strstr(ptr, "_I_")) == NULL)		/* skip any lines that don't have names that look like they belong to IOPs */
    283 			continue;
    284 		if (*(ptr2 + 4) != '_')							/* and skip other lines that have names that don't look like ACN components */
    285 			continue;
    286 		*(ptr + strcspn(ptr, " \t")) = '\0';			/* null terminate the IP address so its a standalone string */
    287 
    288 		chassis = *(ptr2 + 3) - '0';					/* extract the chassis number */
    289 		geoslot = *(ptr2 + 5) - '0';					/* and geo-slot number */
    290 		if (chassis < 1 || chassis > MAX_CHASSIS ||
    291 			geoslot < 1 || geoslot > MAX_GEOSLOT) {		/* if the chassis and/or slot numbers appear to be bad... */
    292 			snprintf(errbuf, PCAP_ERRBUF_SIZE, "Invalid ACN name in '/etc/hosts'.");	/* warn the user */
    293 			continue;																	/* and ignore the entry */
    294 		}
    295 		if ((ptr2 = (char *)malloc(strlen(ptr) + 1)) == NULL) {
    296 			snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    297 			continue;
    298 		}
    299 		strcpy(ptr2, ptr);								/* copy the IP address into our malloc'ed memory */
    300 		u = &units[chassis][geoslot];
    301 		u->ip = ptr2;									/* and remember the whole shebang */
    302 		u->chassis = chassis;
    303 		u->geoslot = geoslot;
    304 	}
    305 	fclose(fp);
    306 	if (*errbuf)	return -1;
    307 	else			return 0;
    308 }
    309 
    310 static int open_with_IOP(unit_t  *u, int flag) {
    311 	int					sockfd;
    312 	char				*ip;
    313 
    314 	if (u->serv_addr == NULL) {
    315 		u->serv_addr = malloc(sizeof(struct sockaddr_in));
    316 	}
    317 	ip = u->ip;
    318 	bzero((char *)u->serv_addr, sizeof(struct sockaddr_in));
    319 	u->serv_addr->sin_family		= AF_INET;
    320 	u->serv_addr->sin_addr.s_addr	= inet_addr(ip);
    321 	u->serv_addr->sin_port			= htons(IOP_SNIFFER_PORT);
    322 
    323 	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    324 		fprintf(stderr, "pcap can't open a socket for connecting to IOP at %s\n", ip);
    325 		return 0;
    326 	}
    327 	if (connect(sockfd, (struct sockaddr *)u->serv_addr, sizeof(struct sockaddr_in)) < 0) {
    328 		fprintf(stderr, "pcap can't connect to IOP at %s\n", ip);
    329 		return 0;
    330 	}
    331 	if (flag == LIVE)	u->fd = sockfd;
    332 	else				u->find_fd = sockfd;
    333 	u->first_time = 0;
    334 	return sockfd;			/* return the non-zero file descriptor as a 'success' indicator */
    335 }
    336 
    337 static void close_with_IOP(int chassis, int geoslot, int flag) {
    338 	int		*id;
    339 
    340 	if (flag == LIVE)	id = &units[chassis][geoslot].fd;
    341 	else				id = &units[chassis][geoslot].find_fd;
    342 
    343 	if (*id) {										/* this was the last time, so... if we are connected... */
    344 		close(*id);									/* disconnect us */
    345 		*id = 0;									/* and forget that the descriptor exists because we are not open */
    346 	}
    347 }
    348 
    349 static void pcap_cleanup_acn(pcap_t *handle) {
    350 	int		chassis, geoslot;
    351 	unit_t	*u;
    352 
    353 	if (find_unit_by_fd(handle->fd, &chassis, &geoslot, &u) == 0)
    354 		return;
    355 	close_with_IOP(chassis, geoslot, LIVE);
    356 	if (u)
    357 		u->first_time = 0;
    358 	pcap_cleanup_live_common(handle);
    359 }
    360 
    361 static void send_to_fd(int fd, int len, unsigned char *str) {
    362 	int		nwritten;
    363 	int		chassis, geoslot;
    364 
    365 	while (len > 0) {
    366 		if ((nwritten = write(fd, str, len)) <= 0) {
    367 			find_unit_by_fd(fd, &chassis, &geoslot, NULL);
    368 			if (units[chassis][geoslot].fd == fd)			close_with_IOP(chassis, geoslot, LIVE);
    369 			else if (units[chassis][geoslot].find_fd == fd)	close_with_IOP(chassis, geoslot, FIND);
    370 			empty_unit(chassis, geoslot);
    371 			return;
    372 		}
    373 		len -= nwritten;
    374 		str += nwritten;
    375 	}
    376 }
    377 
    378 static void acn_freealldevs(void) {
    379 
    380 	pcap_if_t	*iff, *next_iff;
    381 	pcap_addr_t	*addr, *next_addr;
    382 
    383 	for (iff = acn_if_list; iff != NULL; iff = next_iff) {
    384 		next_iff = iff->next;
    385 		for (addr = iff->addresses; addr != NULL; addr = next_addr) {
    386 			next_addr = addr->next;
    387 			if (addr->addr)			free(addr->addr);
    388 			if (addr->netmask)		free(addr->netmask);
    389 			if (addr->broadaddr)	free(addr->broadaddr);
    390 			if (addr->dstaddr)		free(addr->dstaddr);
    391 			free(addr);
    392 		}
    393 		if (iff->name)			free(iff->name);
    394 		if (iff->description)	free(iff->description);
    395 		free(iff);
    396 	}
    397 }
    398 
    399 static char *nonUnified_port_num(unit_t *u, int IOPportnum) {
    400 
    401 	sprintf(static_buf, "%d_%d", u->chassis, u->geoslot);
    402 	return static_buf;
    403 }
    404 
    405 static char *unified_port_num(unit_t *u, int IOPportnum) {
    406 	int			portnum;
    407 
    408 	portnum = ((u->chassis - 1) * 64) + ((u->geoslot - 1) * 8) + IOPportnum + 1;
    409 	sprintf(static_buf, "%d", portnum);
    410 	return static_buf;
    411 }
    412 
    413 static char *translate_IOP_to_pcap_name(unit_t *u, char *IOPname, bpf_u_int32 iftype) {
    414 	iface_t		*iface_ptr, *iface;
    415 	char		*name;
    416 	char		buf[32];
    417 	char		*proto;
    418 	char		*port;
    419 	int			IOPportnum = 0;
    420 
    421 	iface = malloc(sizeof(iface_t));		/* get memory for a structure */
    422 	bzero((char *)iface, sizeof(iface_t));
    423 
    424 	iface->iftype = iftype;					/* remember the interface type of this interface */
    425 
    426 	name = malloc(strlen(IOPname) + 1);		/* get memory for the IOP's name */
    427 	strcpy(name, IOPname);					/* and copy it in */
    428 	iface->IOPname = name;					/* and stick it into the structure */
    429 
    430 	if (strncmp(IOPname, "lo", 2) == 0) {
    431 		IOPportnum = atoi(&IOPname[2]);
    432 		switch (iftype) {
    433 			case DLT_EN10MB:	proto = "lo";		port = nonUnified_port_num(u, IOPportnum);	break;
    434 			default:			proto = "???";		port = unified_port_num(u, IOPportnum);		break;
    435 		}
    436 	} else if (strncmp(IOPname, "eth", 3) == 0) {
    437 		IOPportnum = atoi(&IOPname[3]);
    438 		switch (iftype) {
    439 			case DLT_EN10MB:	proto = "eth";		port = nonUnified_port_num(u, IOPportnum);	break;
    440 			default:			proto = "???";		port = unified_port_num(u, IOPportnum);		break;
    441 		}
    442 	} else if (strncmp(IOPname, "wan", 3) == 0) {
    443 		IOPportnum = atoi(&IOPname[3]);
    444 		switch (iftype) {
    445 			case DLT_SITA:		proto = "wan";		port = unified_port_num(u, IOPportnum);		break;
    446 			default:			proto = "???";		port = unified_port_num(u, IOPportnum);		break;
    447 		}
    448 	}
    449 
    450 	sprintf(buf, "%s_%s", proto, port);		/* compose the user's name for that IOP port name */
    451 	name = malloc(strlen(buf) + 1);			/* get memory for that name */
    452 	strcpy(name, buf);						/* and copy it in */
    453 	iface->name = name;						/* and stick it into the structure */
    454 
    455 	if (u->iface == 0) {					/* if this is the first name */
    456 		u->iface = iface;					/* stick this entry at the head of the list */
    457 	} else {
    458 		iface_ptr = u->iface;
    459 		while (iface_ptr->next) {			/* othewise scan the list */
    460 			iface_ptr = iface_ptr->next;	/* till we're at the last entry */
    461 		}
    462 		iface_ptr->next = iface;			/* then tack this entry on the end of the list */
    463 	}
    464 	return iface->name;
    465 }
    466 
    467 static int if_sort(char *s1, char *s2) {
    468 	char	*s1_p2, *s2_p2;
    469 	char	str1[MAX_LINE_SIZE], str2[MAX_LINE_SIZE];
    470 	int		s1_p1_len, s2_p1_len;
    471 	int		retval;
    472 
    473 	if ((s1_p2 = strchr(s1, '_'))) {	/* if an underscore is found... */
    474 		s1_p1_len = s1_p2 - s1;			/* the prefix length is the difference in pointers */
    475 		s1_p2++;						/* the suffix actually starts _after_ the underscore */
    476 	} else {							/* otherwise... */
    477 		s1_p1_len = strlen(s1);			/* the prefix length is the length of the string itself */
    478 		s1_p2 = 0;						/* and there is no suffix */
    479 	}
    480 	if ((s2_p2 = strchr(s2, '_'))) {	/* now do the same for the second string */
    481 		s2_p1_len = s2_p2 - s2;
    482 		s2_p2++;
    483 	} else {
    484 		s2_p1_len = strlen(s2);
    485 		s2_p2 = 0;
    486 	}
    487 	strncpy(str1, s1, (s1_p1_len > sizeof(str1)) ? s1_p1_len : sizeof(str1));   *(str1 + s1_p1_len) = 0;
    488 	strncpy(str2, s2, (s2_p1_len > sizeof(str2)) ? s2_p1_len : sizeof(str2));   *(str2 + s2_p1_len) = 0;
    489 	retval = strcmp(str1, str2);
    490 	if (retval != 0) return retval;		/* if they are not identical, then we can quit now and return the indication */
    491 	return strcmp(s1_p2, s2_p2);		/* otherwise we return the result of comparing the 2nd half of the string */
    492 }
    493 
    494 static void sort_if_table(void) {
    495 	pcap_if_t	*p1, *p2, *prev, *temp;
    496 	int			has_swapped;
    497 
    498 	if (!acn_if_list) return;				/* nothing to do if the list is empty */
    499 
    500 	while (1) {
    501 		p1 = acn_if_list;					/* start at the head of the list */
    502 		prev = 0;
    503 		has_swapped = 0;
    504 		while ((p2 = p1->next)) {
    505 			if (if_sort(p1->name, p2->name) > 0) {
    506 				if (prev) {					/* we are swapping things that are _not_ at the head of the list */
    507 					temp = p2->next;
    508 					prev->next = p2;
    509 					p2->next = p1;
    510 					p1->next = temp;
    511 				} else {					/* special treatment if we are swapping with the head of the list */
    512 					temp = p2->next;
    513 					acn_if_list= p2;
    514 					p2->next = p1;
    515 					p1->next = temp;
    516 				}
    517 				p1 = p2;
    518 				prev = p1;
    519 				has_swapped = 1;
    520 			}
    521 			prev = p1;
    522 			p1 = p1->next;
    523 		}
    524 		if (has_swapped == 0)
    525 			return;
    526 	}
    527 	return;
    528 }
    529 
    530 static int process_client_data (char *errbuf) {								/* returns: -1 = error, 0 = OK */
    531 	int					chassis, geoslot;
    532 	unit_t				*u;
    533 	pcap_if_t			*iff, *prev_iff;
    534 	pcap_addr_t			*addr, *prev_addr;
    535 	char				*ptr;
    536 	int					address_count;
    537 	struct sockaddr_in	*s;
    538 	char				*newname;
    539 	bpf_u_int32				interfaceType;
    540 	unsigned char		flags;
    541 
    542 	prev_iff = 0;
    543 	for (chassis = 0; chassis <= MAX_CHASSIS; chassis++) {
    544 		for (geoslot = 0; geoslot <= MAX_GEOSLOT; geoslot++) {				/* now loop over all the devices */
    545 			u = &units[chassis][geoslot];
    546 			empty_unit_iface(u);
    547 			ptr = u->imsg;													/* point to the start of the msg for this IOP */
    548 			while (ptr < (u->imsg + u->len)) {
    549 				if ((iff = malloc(sizeof(pcap_if_t))) == NULL) {
    550 					snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    551 					return -1;
    552 				}
    553 				bzero((char *)iff, sizeof(pcap_if_t));
    554 				if (acn_if_list == 0)	acn_if_list = iff;					/* remember the head of the list */
    555 				if (prev_iff)			prev_iff->next = iff;				/* insert a forward link */
    556 
    557 				if (*ptr) {													/* if there is a count for the name */
    558 					if ((iff->name = malloc(*ptr + 1)) == NULL) {			/* get that amount of space */
    559 						snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    560 						return -1;
    561 					}
    562 					memcpy(iff->name, (ptr + 1), *ptr);						/* copy the name into the malloc'ed space */
    563 					*(iff->name + *ptr) = 0;								/* and null terminate the string */
    564 					ptr += *ptr;											/* now move the pointer forwards by the length of the count plus the length of the string */
    565 				}
    566 				ptr++;
    567 
    568 				if (*ptr) {													/* if there is a count for the description */
    569 					if ((iff->description = malloc(*ptr + 1)) == NULL) {	/* get that amount of space */
    570 						snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    571 						return -1;
    572 					}
    573 					memcpy(iff->description, (ptr + 1), *ptr);				/* copy the name into the malloc'ed space */
    574 					*(iff->description + *ptr) = 0;							/* and null terminate the string */
    575 					ptr += *ptr;											/* now move the pointer forwards by the length of the count plus the length of the string */
    576 				}
    577 				ptr++;
    578 
    579 				interfaceType = ntohl(*(bpf_u_int32 *)ptr);
    580 				ptr += 4;													/* skip over the interface type */
    581 
    582 				flags = *ptr++;
    583 				if (flags) iff->flags = PCAP_IF_LOOPBACK;					/* if this is a loopback style interface, lets mark it as such */
    584 
    585 				address_count = *ptr++;
    586 
    587 				prev_addr = 0;
    588 				while (address_count--) {
    589 					if ((addr = malloc(sizeof(pcap_addr_t))) == NULL) {
    590 						snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    591 						return -1;
    592 					}
    593 					bzero((char *)addr, sizeof(pcap_addr_t));
    594 					if (iff->addresses == 0) iff->addresses = addr;
    595 					if (prev_addr) prev_addr->next = addr;							/* insert a forward link */
    596 					if (*ptr) {														/* if there is a count for the address */
    597 						if ((s = malloc(sizeof(struct sockaddr_in))) == NULL) {		/* get that amount of space */
    598 							snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    599 							return -1;
    600 						}
    601 						bzero((char *)s, sizeof(struct sockaddr_in));
    602 						addr->addr = (struct sockaddr *)s;
    603 						s->sin_family		= AF_INET;
    604 						s->sin_addr.s_addr	= *(bpf_u_int32 *)(ptr + 1);			/* copy the address in */
    605 						ptr += *ptr;										/* now move the pointer forwards according to the specified length of the address */
    606 					}
    607 					ptr++;													/* then forwards one more for the 'length of the address' field */
    608 					if (*ptr) {												/* process any netmask */
    609 						if ((s = malloc(sizeof(struct sockaddr_in))) == NULL) {
    610 							snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    611 							return -1;
    612 						}
    613 						bzero((char *)s, sizeof(struct sockaddr_in));
    614 						addr->netmask = (struct sockaddr *)s;
    615 						s->sin_family		= AF_INET;
    616 						s->sin_addr.s_addr	= *(bpf_u_int32*)(ptr + 1);
    617 						ptr += *ptr;
    618 					}
    619 					ptr++;
    620 					if (*ptr) {												/* process any broadcast address */
    621 						if ((s = malloc(sizeof(struct sockaddr_in))) == NULL) {
    622 							snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    623 							return -1;
    624 						}
    625 						bzero((char *)s, sizeof(struct sockaddr_in));
    626 						addr->broadaddr = (struct sockaddr *)s;
    627 						s->sin_family		= AF_INET;
    628 						s->sin_addr.s_addr	= *(bpf_u_int32*)(ptr + 1);
    629 						ptr += *ptr;
    630 					}
    631 					ptr++;
    632 					if (*ptr) {												/* process any destination address */
    633 						if ((s = malloc(sizeof(struct sockaddr_in))) == NULL) {
    634 							snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
    635 							return -1;
    636 						}
    637 						bzero((char *)s, sizeof(struct sockaddr_in));
    638 						addr->dstaddr = (struct sockaddr *)s;
    639 						s->sin_family		= AF_INET;
    640 						s->sin_addr.s_addr	= *(bpf_u_int32*)(ptr + 1);
    641 						ptr += *ptr;
    642 					}
    643 					ptr++;
    644 					prev_addr = addr;
    645 				}
    646 				prev_iff = iff;
    647 
    648 				newname = translate_IOP_to_pcap_name(u, iff->name, interfaceType);		/* add a translation entry and get a point to the mangled name */
    649 				if ((iff->name = realloc(iff->name, strlen(newname) + 1)) == NULL) {	/* we now re-write the name stored in the interface list */
    650 					snprintf(errbuf, PCAP_ERRBUF_SIZE, "realloc: %s", pcap_strerror(errno));
    651 					return -1;
    652 				}
    653 				strcpy(iff->name, newname);												/* to this new name */
    654 			}
    655 		}
    656 	}
    657 	return 0;
    658 }
    659 
    660 static int read_client_data (int fd) {
    661 	unsigned char	buf[256];
    662 	int				chassis, geoslot;
    663 	unit_t			*u;
    664 	int				len;
    665 
    666 	find_unit_by_fd(fd, &chassis, &geoslot, &u);
    667 
    668 	if ((len = recv(fd, buf, sizeof(buf), 0)) <= 0)	return 0;	/* read in whatever data was sent to us */
    669 
    670 	if ((u->imsg = realloc(u->imsg, (u->len + len))) == NULL)	/* extend the buffer for the new data */
    671 		return 0;
    672 	memcpy((u->imsg + u->len), buf, len);						/* append the new data */
    673 	u->len += len;
    674 	return 1;
    675 }
    676 
    677 static void wait_for_all_answers(void) {
    678 	int		retval;
    679 	struct	timeval tv;
    680 	int		fd;
    681 	int		chassis, geoslot;
    682 
    683 	tv.tv_sec = 2;
    684 	tv.tv_usec = 0;
    685 
    686 	while (1) {
    687 		int flag = 0;
    688 		for (fd = 0; fd <= max_fs; fd++) {								/* scan the list of descriptors we may be listening to */
    689 			if (FD_ISSET(fd, &readfds)) flag = 1;						/* and see if there are any still set */
    690 		}
    691 		if (flag == 0) return;											/* we are done, when they are all gone */
    692 
    693 		memcpy(&working_set, &readfds, sizeof(readfds));				/* otherwise, we still have to listen for more stuff, till we timeout */
    694 		retval = select(max_fs + 1, &working_set, NULL, NULL, &tv);
    695 		if (retval == -1) {												/* an error occured !!!!! */
    696 			return;
    697 		} else if (retval == 0) {										/* timeout occured, so process what we've got sofar and return */
    698 			printf("timeout\n");
    699 			return;
    700 		} else {
    701 			for (fd = 0; fd <= max_fs; fd++) {							/* scan the list of things to do, and do them */
    702 				if (FD_ISSET(fd, &working_set)) {
    703 					if (read_client_data(fd) == 0) {					/* if the socket has closed */
    704 						FD_CLR(fd, &readfds);							/* and descriptors we listen to for errors */
    705 						find_unit_by_fd(fd, &chassis, &geoslot, NULL);
    706 						close_with_IOP(chassis, geoslot, FIND);			/* and close out connection to him */
    707 					}
    708 				}
    709 			}
    710 		}
    711 	}
    712 }
    713 
    714 static char *get_error_response(int fd, char *errbuf) {		/* return a pointer on error, NULL on no error */
    715 	char	byte;
    716 	int		len = 0;
    717 
    718 	while (1) {
    719 		recv(fd, &byte, 1, 0);							/* read another byte in */
    720 		if (errbuf && (len++ < PCAP_ERRBUF_SIZE)) {		/* and if there is still room in the buffer */
    721 			*errbuf++ = byte;							/* stick it in */
    722 			*errbuf = '\0';								/* ensure the string is null terminated just in case we might exceed the buffer's size */
    723 		}
    724 		if (byte == '\0') {
    725 			if (len > 1)	{ return errbuf;	}
    726 			else			{ return NULL;		}
    727 		}
    728 	}
    729 }
    730 
    731 int acn_findalldevs(char *errbuf) {								/* returns: -1 = error, 0 = OK */
    732 	int		chassis, geoslot;
    733 	unit_t	*u;
    734 
    735 	FD_ZERO(&readfds);
    736 	max_fs = 0;
    737 	for (chassis = 0; chassis <= MAX_CHASSIS; chassis++) {
    738 		for (geoslot = 0; geoslot <= MAX_GEOSLOT; geoslot++) {
    739 			u = &units[chassis][geoslot];
    740 			if (u->ip && (open_with_IOP(u, FIND))) {			/* connect to the remote IOP */
    741 				send_to_fd(u->find_fd, 1, (unsigned char *)"\0");
    742 				if (get_error_response(u->find_fd, errbuf))
    743 					close_with_IOP(chassis, geoslot, FIND);
    744 				else {
    745 					if (u->find_fd > max_fs)
    746 						max_fs = u->find_fd;								/* remember the highest number currently in use */
    747 					FD_SET(u->find_fd, &readfds);						/* we are going to want to read this guy's response to */
    748 					u->len = 0;
    749 					send_to_fd(u->find_fd, 1, (unsigned char *)"Q");		/* this interface query request */
    750 				}
    751 			}
    752 		}
    753 	}
    754 	wait_for_all_answers();
    755 	if (process_client_data(errbuf))
    756 		return -1;
    757 	sort_if_table();
    758 	return 0;
    759 }
    760 
    761 static int pcap_stats_acn(pcap_t *handle, struct pcap_stat *ps) {
    762 	unsigned char	buf[12];
    763 
    764 	send_to_fd(handle->fd, 1, (unsigned char *)"S");						/* send the get_stats command to the IOP */
    765 
    766 	if (read_client_nbytes(handle->fd, sizeof(buf), buf) == -1) return -1;	/* try reading the required bytes */
    767 
    768 	ps->ps_recv		= ntohl(*(uint32_t *)&buf[0]);							/* break the buffer into its three 32 bit components */
    769 	ps->ps_drop		= ntohl(*(uint32_t *)&buf[4]);
    770 	ps->ps_ifdrop	= ntohl(*(uint32_t *)&buf[8]);
    771 
    772 	return 0;
    773 }
    774 
    775 static int acn_open_live(const char *name, char *errbuf, int *linktype) {		/* returns 0 on error, else returns the file descriptor */
    776 	int			chassis, geoslot;
    777 	unit_t		*u;
    778 	iface_t		*p;
    779 	pcap_if_t	*alldevsp;
    780 
    781 	pcap_findalldevs(&alldevsp, errbuf);
    782 	for (chassis = 0; chassis <= MAX_CHASSIS; chassis++) {										/* scan the table... */
    783 		for (geoslot = 0; geoslot <= MAX_GEOSLOT; geoslot++) {
    784 			u = &units[chassis][geoslot];
    785 			if (u->ip != NULL) {
    786 				p = u->iface;
    787 				while (p) {																		/* and all interfaces... */
    788 					if (p->IOPname && p->name && (strcmp(p->name, name) == 0)) {				/* and if we found the interface we want... */
    789 						*linktype = p->iftype;
    790 						open_with_IOP(u, LIVE);													/* start a connection with that IOP */
    791 						send_to_fd(u->fd, strlen(p->IOPname)+1, (unsigned char *)p->IOPname);	/* send the IOP's interface name, and a terminating null */
    792 						if (get_error_response(u->fd, errbuf)) {
    793 							return -1;
    794 						}
    795 						return u->fd;															/* and return that open descriptor */
    796 					}
    797 					p = p->next;
    798 				}
    799 			}
    800 		}
    801 	}
    802 	return -1;																				/* if the interface wasn't found, return an error */
    803 }
    804 
    805 static void acn_start_monitor(int fd, int snaplen, int timeout, int promiscuous, int direction) {
    806 	unsigned char	buf[8];
    807 	unit_t			*u;
    808 
    809 	//printf("acn_start_monitor()\n");				// fulko
    810 	find_unit_by_fd(fd, NULL, NULL, &u);
    811 	if (u->first_time == 0) {
    812 		buf[0]					= 'M';
    813 		*(uint32_t *)&buf[1]	= htonl(snaplen);
    814 		buf[5]					= timeout;
    815 		buf[6]					= promiscuous;
    816 		buf[7]					= direction;
    817 	//printf("acn_start_monitor() first time\n");				// fulko
    818 		send_to_fd(fd, 8, buf);								/* send the start monitor command with its parameters to the IOP */
    819 		u->first_time = 1;
    820 	}
    821 	//printf("acn_start_monitor() complete\n");				// fulko
    822 }
    823 
    824 static int pcap_inject_acn(pcap_t *p, const void *buf _U_, size_t size _U_) {
    825 	strlcpy(p->errbuf, "Sending packets isn't supported on ACN adapters",
    826 	    PCAP_ERRBUF_SIZE);
    827 	return (-1);
    828 }
    829 
    830 static int pcap_setfilter_acn(pcap_t *handle, struct bpf_program *bpf) {
    831 	int				fd = handle->fd;
    832 	int				count;
    833 	struct bpf_insn	*p;
    834 	uint16_t		shortInt;
    835 	uint32_t		longInt;
    836 
    837 	send_to_fd(fd, 1, (unsigned char *)"F");			/* BPF filter follows command */
    838 	count = bpf->bf_len;
    839 	longInt = htonl(count);
    840 	send_to_fd(fd, 4, (unsigned char *)&longInt);		/* send the instruction sequence count */
    841 	p = bpf->bf_insns;
    842 	while (count--) {									/* followed by the list of instructions */
    843 		shortInt = htons(p->code);
    844 		longInt = htonl(p->k);
    845 		send_to_fd(fd, 2, (unsigned char *)&shortInt);
    846 		send_to_fd(fd, 1, (unsigned char *)&p->jt);
    847 		send_to_fd(fd, 1, (unsigned char *)&p->jf);
    848 		send_to_fd(fd, 4, (unsigned char *)&longInt);
    849 		p++;
    850 	}
    851 	if (get_error_response(fd, NULL))
    852 		return -1;
    853 	return 0;
    854 }
    855 
    856 static int pcap_setdirection_acn(pcap_t *handle, pcap_direction_t d) {
    857 	snprintf(handle->errbuf, sizeof(handle->errbuf),
    858 	    "Setting direction is not supported on ACN adapters");
    859 	return -1;
    860 }
    861 
    862 static int acn_read_n_bytes_with_timeout(pcap_t *handle, int count) {
    863 	struct		timeval tv;
    864 	int			retval, fd;
    865 	fd_set		r_fds;
    866 	fd_set		w_fds;
    867 	u_char		*bp;
    868 	int			len = 0;
    869 	int			offset = 0;
    870 
    871 	tv.tv_sec = 5;
    872 	tv.tv_usec = 0;
    873 
    874 	fd = handle->fd;
    875 	FD_ZERO(&r_fds);
    876 	FD_SET(fd, &r_fds);
    877 	memcpy(&w_fds, &r_fds, sizeof(r_fds));
    878 	bp = handle->bp;
    879 	while (count) {
    880 		retval = select(fd + 1, &w_fds, NULL, NULL, &tv);
    881 		if (retval == -1) {											/* an error occured !!!!! */
    882 //			fprintf(stderr, "error during packet data read\n");
    883 			return -1;												/* but we need to return a good indication to prevent unneccessary popups */
    884 		} else if (retval == 0) {									/* timeout occured, so process what we've got sofar and return */
    885 //			fprintf(stderr, "timeout during packet data read\n");
    886 			return -1;
    887 		} else {
    888 			if ((len = recv(fd, (bp + offset), count, 0)) <= 0) {
    889 //				fprintf(stderr, "premature exit during packet data rx\n");
    890 				return -1;
    891 			}
    892 			count -= len;
    893 			offset += len;
    894 		}
    895 	}
    896 	return 0;
    897 }
    898 
    899 static int pcap_read_acn(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user) {
    900 	#define HEADER_SIZE (4 * 4)
    901 	unsigned char		packet_header[HEADER_SIZE];
    902 	struct pcap_pkthdr	pcap_header;
    903 
    904 	//printf("pcap_read_acn()\n");			// fulko
    905 	acn_start_monitor(handle->fd, handle->snapshot, handle->md.timeout, handle->md.clear_promisc, handle->direction);	/* maybe tell him to start monitoring */
    906 	//printf("pcap_read_acn() after start monitor\n");			// fulko
    907 
    908 	handle->bp = packet_header;
    909 	if (acn_read_n_bytes_with_timeout(handle, HEADER_SIZE) == -1) return 0;			/* try to read a packet header in so we can get the sizeof the packet data */
    910 
    911 	pcap_header.ts.tv_sec	= ntohl(*(uint32_t *)&packet_header[0]);				/* tv_sec */
    912 	pcap_header.ts.tv_usec	= ntohl(*(uint32_t *)&packet_header[4]);				/* tv_usec */
    913 	pcap_header.caplen		= ntohl(*(uint32_t *)&packet_header[8]);				/* caplen */
    914 	pcap_header.len			= ntohl(*(uint32_t *)&packet_header[12]);				/* len */
    915 
    916 	handle->bp = handle->buffer + handle->offset;									/* start off the receive pointer at the right spot */
    917 	if (acn_read_n_bytes_with_timeout(handle, pcap_header.caplen) == -1) return 0;	/* then try to read in the rest of the data */
    918 
    919 	callback(user, &pcap_header, handle->bp);										/* call the user supplied callback function */
    920 	return 1;
    921 }
    922 
    923 static int pcap_activate_sita(pcap_t *handle) {
    924 	int		fd;
    925 
    926 	if (handle->opt.rfmon) {
    927 		/*
    928 		 * No monitor mode on SITA devices (they're not Wi-Fi
    929 		 * devices).
    930 		 */
    931 		return PCAP_ERROR_RFMON_NOTSUP;
    932 	}
    933 
    934 	/* Initialize some components of the pcap structure. */
    935 
    936 	handle->inject_op = pcap_inject_acn;
    937 	handle->setfilter_op = pcap_setfilter_acn;
    938 	handle->setdirection_op = pcap_setdirection_acn;
    939 	handle->set_datalink_op = NULL;	/* can't change data link type */
    940 	handle->getnonblock_op = pcap_getnonblock_fd;
    941 	handle->setnonblock_op = pcap_setnonblock_fd;
    942 	handle->cleanup_op = pcap_cleanup_acn;
    943 	handle->read_op = pcap_read_acn;
    944 	handle->stats_op = pcap_stats_acn;
    945 
    946 	fd = acn_open_live(handle->opt.source, handle->errbuf,
    947 	    &handle->linktype);
    948 	if (fd == -1)
    949 		return PCAP_ERROR;
    950 	handle->md.clear_promisc = handle->md.promisc;
    951 	handle->fd = fd;
    952 	handle->bufsize = handle->snapshot;
    953 
    954 	/* Allocate the buffer */
    955 
    956 	handle->buffer	 = malloc(handle->bufsize + handle->offset);
    957 	if (!handle->buffer) {
    958 	        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
    959 			 "malloc: %s", pcap_strerror(errno));
    960 		pcap_cleanup_acn(handle);
    961 		return PCAP_ERROR;
    962 	}
    963 
    964 	/*
    965 	 * "handle->fd" is a socket, so "select()" and "poll()"
    966 	 * should work on it.
    967 	 */
    968 	handle->selectable_fd = handle->fd;
    969 
    970 	return 0;
    971 }
    972 
    973 pcap_t *pcap_create(const char *device, char *ebuf) {
    974 	pcap_t *p;
    975 
    976 	p = pcap_create_common(device, ebuf);
    977 	if (p == NULL)
    978 		return (NULL);
    979 
    980 	p->activate_op = pcap_activate_sita;
    981 	return (p);
    982 }
    983