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