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