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