xref: /freebsd/contrib/libpcap/pcap-rpcap.c (revision cab6a39d7b343596a5823e65c0f7b426551ec22d)
1 /*
2  * Copyright (c) 2002 - 2005 NetGroup, Politecnico di Torino (Italy)
3  * Copyright (c) 2005 - 2008 CACE Technologies, Davis (California)
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in the
14  * documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the Politecnico di Torino, CACE Technologies
16  * nor the names of its contributors may be used to endorse or promote
17  * products derived from this software without specific prior written
18  * permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37 
38 #include "ftmacros.h"
39 
40 #include <string.h>		/* for strlen(), ... */
41 #include <stdlib.h>		/* for malloc(), free(), ... */
42 #include <stdarg.h>		/* for functions with variable number of arguments */
43 #include <errno.h>		/* for the errno variable */
44 #include "sockutils.h"
45 #include "pcap-int.h"
46 #include "rpcap-protocol.h"
47 #include "pcap-rpcap.h"
48 
49 /*
50  * This file contains the pcap module for capturing from a remote machine's
51  * interfaces using the RPCAP protocol.
52  *
53  * WARNING: All the RPCAP functions that are allowed to return a buffer
54  * containing the error description can return max PCAP_ERRBUF_SIZE characters.
55  * However there is no guarantees that the string will be zero-terminated.
56  * Best practice is to define the errbuf variable as a char of size
57  * 'PCAP_ERRBUF_SIZE+1' and to insert manually a NULL character at the end
58  * of the buffer. This will guarantee that no buffer overflows occur even
59  * if we use the printf() to show the error on the screen.
60  *
61  * XXX - actually, null-terminating the error string is part of the
62  * contract for the pcap API; if there's any place in the pcap code
63  * that doesn't guarantee null-termination, even at the expense of
64  * cutting the message short, that's a bug and needs to be fixed.
65  */
66 
67 #define PCAP_STATS_STANDARD	0	/* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
68 #ifdef _WIN32
69 #define PCAP_STATS_EX		1	/* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
70 #endif
71 
72 /*
73  * \brief Keeps a list of all the opened connections in the active mode.
74  *
75  * This structure defines a linked list of items that are needed to keep the info required to
76  * manage the active mode.
77  * In other words, when a new connection in active mode starts, this structure is updated so that
78  * it reflects the list of active mode connections currently opened.
79  * This structure is required by findalldevs() and open_remote() to see if they have to open a new
80  * control connection toward the host, or they already have a control connection in place.
81  */
82 struct activehosts
83 {
84 	struct sockaddr_storage host;
85 	SOCKET sockctrl;
86 	uint8 protocol_version;
87 	struct activehosts *next;
88 };
89 
90 /* Keeps a list of all the opened connections in the active mode. */
91 static struct activehosts *activeHosts;
92 
93 /*
94  * Keeps the main socket identifier when we want to accept a new remote
95  * connection (active mode only).
96  * See the documentation of pcap_remoteact_accept() and
97  * pcap_remoteact_cleanup() for more details.
98  */
99 static SOCKET sockmain;
100 
101 /*
102  * Private data for capturing remotely using the rpcap protocol.
103  */
104 struct pcap_rpcap {
105 	/*
106 	 * This is '1' if we're the network client; it is needed by several
107 	 * functions (such as pcap_setfilter()) to know whether they have
108 	 * to use the socket or have to open the local adapter.
109 	 */
110 	int rmt_clientside;
111 
112 	SOCKET rmt_sockctrl;		/* socket ID of the socket used for the control connection */
113 	SOCKET rmt_sockdata;		/* socket ID of the socket used for the data connection */
114 	int rmt_flags;			/* we have to save flags, since they are passed by the pcap_open_live(), but they are used by the pcap_startcapture() */
115 	int rmt_capstarted;		/* 'true' if the capture is already started (needed to knoe if we have to call the pcap_startcapture() */
116 	char *currentfilter;		/* Pointer to a buffer (allocated at run-time) that stores the current filter. Needed when flag PCAP_OPENFLAG_NOCAPTURE_RPCAP is turned on. */
117 
118 	uint8 protocol_version;		/* negotiated protocol version */
119 
120 	unsigned int TotNetDrops;	/* keeps the number of packets that have been dropped by the network */
121 
122 	/*
123 	 * This keeps the number of packets that have been received by the
124 	 * application.
125 	 *
126 	 * Packets dropped by the kernel buffer are not counted in this
127 	 * variable. It is always equal to (TotAccepted - TotDrops),
128 	 * except for the case of remote capture, in which we have also
129 	 * packets in flight, i.e. that have been transmitted by the remote
130 	 * host, but that have not been received (yet) from the client.
131 	 * In this case, (TotAccepted - TotDrops - TotNetDrops) gives a
132 	 * wrong result, since this number does not corresponds always to
133 	 * the number of packet received by the application. For this reason,
134 	 * in the remote capture we need another variable that takes into
135 	 * account of the number of packets actually received by the
136 	 * application.
137 	 */
138 	unsigned int TotCapt;
139 
140 	struct pcap_stat stat;
141 	/* XXX */
142 	struct pcap *next;		/* list of open pcaps that need stuff cleared on close */
143 };
144 
145 /****************************************************
146  *                                                  *
147  * Locally defined functions                        *
148  *                                                  *
149  ****************************************************/
150 static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode);
151 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog);
152 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog);
153 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog);
154 static void pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter);
155 static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog);
156 static int pcap_setsampling_remote(pcap_t *fp);
157 static int pcap_startcapture_remote(pcap_t *fp);
158 static int rpcap_recv_msg_header(SOCKET sock, struct rpcap_header *header, char *errbuf);
159 static int rpcap_check_msg_ver(SOCKET sock, uint8 expected_ver, struct rpcap_header *header, char *errbuf);
160 static int rpcap_check_msg_type(SOCKET sock, uint8 request_type, struct rpcap_header *header, uint16 *errcode, char *errbuf);
161 static int rpcap_process_msg_header(SOCKET sock, uint8 ver, uint8 request_type, struct rpcap_header *header, char *errbuf);
162 static int rpcap_recv(SOCKET sock, void *buffer, size_t toread, uint32 *plen, char *errbuf);
163 static void rpcap_msg_err(SOCKET sockctrl, uint32 plen, char *remote_errbuf);
164 static int rpcap_discard(SOCKET sock, uint32 len, char *errbuf);
165 static int rpcap_read_packet_msg(SOCKET sock, pcap_t *p, size_t size);
166 
167 /****************************************************
168  *                                                  *
169  * Function bodies                                  *
170  *                                                  *
171  ****************************************************/
172 
173 /*
174  * This function translates (i.e. de-serializes) a 'rpcap_sockaddr'
175  * structure from the network byte order to a 'sockaddr_in" or
176  * 'sockaddr_in6' structure in the host byte order.
177  *
178  * It accepts an 'rpcap_sockaddr' structure as it is received from the
179  * network, and checks the address family field against various values
180  * to see whether it looks like an IPv4 address, an IPv6 address, or
181  * neither of those.  It checks for multiple values in order to try
182  * to handle older rpcap daemons that sent the native OS's 'sockaddr_in'
183  * or 'sockaddr_in6' structures over the wire with some members
184  * byte-swapped, and to handle the fact that AF_INET6 has different
185  * values on different OSes.
186  *
187  * For IPv4 addresses, it converts the address family to host byte
188  * order from network byte order and puts it into the structure,
189  * sets the length if a sockaddr structure has a length, converts the
190  * port number to host byte order from network byte order and puts
191  * it into the structure, copies over the IPv4 address, and zeroes
192  * out the zero padding.
193  *
194  * For IPv6 addresses, it converts the address family to host byte
195  * order from network byte order and puts it into the structure,
196  * sets the length if a sockaddr structure has a length, converts the
197  * port number and flow information to host byte order from network
198  * byte order and puts them into the structure, copies over the IPv6
199  * address, and converts the scope ID to host byte order from network
200  * byte order and puts it into the structure.
201  *
202  * The function will allocate the 'sockaddrout' variable according to the
203  * address family in use. In case the address does not belong to the
204  * AF_INET nor AF_INET6 families, 'sockaddrout' is not allocated and a
205  * NULL pointer is returned.  This usually happens because that address
206  * does not exist on the other host, or is of an address family other
207  * than AF_INET or AF_INET6, so the RPCAP daemon sent a 'sockaddr_storage'
208  * structure containing all 'zero' values.
209  *
210  * Older RPCAPDs sent the addresses over the wire in the OS's native
211  * structure format.  For most OSes, this looks like the over-the-wire
212  * format, but might have a different value for AF_INET6 than the value
213  * on the machine receiving the reply.  For OSes with the newer BSD-style
214  * sockaddr structures, this has, instead of a 2-byte address family,
215  * a 1-byte structure length followed by a 1-byte address family.  The
216  * RPCAPD code would put the address family in network byte order before
217  * sending it; that would set it to 0 on a little-endian machine, as
218  * htons() of any value between 1 and 255 would result in a value > 255,
219  * with its lower 8 bits zero, so putting that back into a 1-byte field
220  * would set it to 0.
221  *
222  * Therefore, for older RPCAPDs running on an OS with newer BSD-style
223  * sockaddr structures, the family field, if treated as a big-endian
224  * (network byte order) 16-bit field, would be:
225  *
226  *	(length << 8) | family if sent by a big-endian machine
227  *	(length << 8) if sent by a little-endian machine
228  *
229  * For current RPCAPDs, and for older RPCAPDs running on an OS with
230  * older BSD-style sockaddr structures, the family field, if treated
231  * as a big-endian 16-bit field, would just contain the family.
232  *
233  * \param sockaddrin: a 'rpcap_sockaddr' pointer to the variable that has
234  * to be de-serialized.
235  *
236  * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
237  * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
238  * This variable will be allocated automatically inside this function.
239  *
240  * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
241  * that will contain the error message (in case there is one).
242  *
243  * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
244  * can be only the fact that the malloc() failed to allocate memory.
245  * The error message is returned in the 'errbuf' variable, while the deserialized address
246  * is returned into the 'sockaddrout' variable.
247  *
248  * \warning This function supports only AF_INET and AF_INET6 address families.
249  *
250  * \warning The sockaddrout (if not NULL) must be deallocated by the user.
251  */
252 
253 /*
254  * Possible IPv4 family values other than the designated over-the-wire value,
255  * which is 2 (because everybody uses 2 for AF_INET4).
256  */
257 #define SOCKADDR_IN_LEN		16	/* length of struct sockaddr_in */
258 #define SOCKADDR_IN6_LEN	28	/* length of struct sockaddr_in6 */
259 #define NEW_BSD_AF_INET_BE	((SOCKADDR_IN_LEN << 8) | 2)
260 #define NEW_BSD_AF_INET_LE	(SOCKADDR_IN_LEN << 8)
261 
262 /*
263  * Possible IPv6 family values other than the designated over-the-wire value,
264  * which is 23 (because that's what Windows uses, and most RPCAP servers
265  * out there are probably running Windows, as WinPcap includes the server
266  * but few if any UN*Xes build and ship it).
267  *
268  * The new BSD sockaddr structure format was in place before 4.4-Lite, so
269  * all the free-software BSDs use it.
270  */
271 #define NEW_BSD_AF_INET6_BSD_BE		((SOCKADDR_IN6_LEN << 8) | 24)	/* NetBSD, OpenBSD, BSD/OS */
272 #define NEW_BSD_AF_INET6_FREEBSD_BE	((SOCKADDR_IN6_LEN << 8) | 28)	/* FreeBSD, DragonFly BSD */
273 #define NEW_BSD_AF_INET6_DARWIN_BE	((SOCKADDR_IN6_LEN << 8) | 30)	/* macOS, iOS, anything else Darwin-based */
274 #define NEW_BSD_AF_INET6_LE		(SOCKADDR_IN6_LEN << 8)
275 #define LINUX_AF_INET6			10
276 #define HPUX_AF_INET6			22
277 #define AIX_AF_INET6			24
278 #define SOLARIS_AF_INET6		26
279 
280 static int
281 rpcap_deseraddr(struct rpcap_sockaddr *sockaddrin, struct sockaddr_storage **sockaddrout, char *errbuf)
282 {
283 	/* Warning: we support only AF_INET and AF_INET6 */
284 	switch (ntohs(sockaddrin->family))
285 	{
286 	case RPCAP_AF_INET:
287 	case NEW_BSD_AF_INET_BE:
288 	case NEW_BSD_AF_INET_LE:
289 		{
290 		struct rpcap_sockaddr_in *sockaddrin_ipv4;
291 		struct sockaddr_in *sockaddrout_ipv4;
292 
293 		(*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in));
294 		if ((*sockaddrout) == NULL)
295 		{
296 			pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
297 			    errno, "malloc() failed");
298 			return -1;
299 		}
300 		sockaddrin_ipv4 = (struct rpcap_sockaddr_in *) sockaddrin;
301 		sockaddrout_ipv4 = (struct sockaddr_in *) (*sockaddrout);
302 		sockaddrout_ipv4->sin_family = AF_INET;
303 		sockaddrout_ipv4->sin_port = ntohs(sockaddrin_ipv4->port);
304 		memcpy(&sockaddrout_ipv4->sin_addr, &sockaddrin_ipv4->addr, sizeof(sockaddrout_ipv4->sin_addr));
305 		memset(sockaddrout_ipv4->sin_zero, 0, sizeof(sockaddrout_ipv4->sin_zero));
306 		break;
307 		}
308 
309 #ifdef AF_INET6
310 	case RPCAP_AF_INET6:
311 	case NEW_BSD_AF_INET6_BSD_BE:
312 	case NEW_BSD_AF_INET6_FREEBSD_BE:
313 	case NEW_BSD_AF_INET6_DARWIN_BE:
314 	case NEW_BSD_AF_INET6_LE:
315 	case LINUX_AF_INET6:
316 	case HPUX_AF_INET6:
317 	case AIX_AF_INET6:
318 	case SOLARIS_AF_INET6:
319 		{
320 		struct rpcap_sockaddr_in6 *sockaddrin_ipv6;
321 		struct sockaddr_in6 *sockaddrout_ipv6;
322 
323 		(*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in6));
324 		if ((*sockaddrout) == NULL)
325 		{
326 			pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
327 			    errno, "malloc() failed");
328 			return -1;
329 		}
330 		sockaddrin_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrin;
331 		sockaddrout_ipv6 = (struct sockaddr_in6 *) (*sockaddrout);
332 		sockaddrout_ipv6->sin6_family = AF_INET6;
333 		sockaddrout_ipv6->sin6_port = ntohs(sockaddrin_ipv6->port);
334 		sockaddrout_ipv6->sin6_flowinfo = ntohl(sockaddrin_ipv6->flowinfo);
335 		memcpy(&sockaddrout_ipv6->sin6_addr, &sockaddrin_ipv6->addr, sizeof(sockaddrout_ipv6->sin6_addr));
336 		sockaddrout_ipv6->sin6_scope_id = ntohl(sockaddrin_ipv6->scope_id);
337 		break;
338 		}
339 #endif
340 
341 	default:
342 		/*
343 		 * It is neither AF_INET nor AF_INET6 (or, if the OS doesn't
344 		 * support AF_INET6, it's not AF_INET).
345 		 */
346 		*sockaddrout = NULL;
347 		break;
348 	}
349 	return 0;
350 }
351 
352 /*
353  * This function reads a packet from the network socket.  It does not
354  * deliver the packet to a pcap_dispatch()/pcap_loop() callback (hence
355  * the "nocb" string into its name).
356  *
357  * This function is called by pcap_read_rpcap().
358  *
359  * WARNING: By choice, this function does not make use of semaphores. A smarter
360  * implementation should put a semaphore into the data thread, and a signal will
361  * be raised as soon as there is data into the socket buffer.
362  * However this is complicated and it does not bring any advantages when reading
363  * from the network, in which network delays can be much more important than
364  * these optimizations. Therefore, we chose the following approach:
365  * - the 'timeout' chosen by the user is split in two (half on the server side,
366  * with the usual meaning, and half on the client side)
367  * - this function checks for packets; if there are no packets, it waits for
368  * timeout/2 and then it checks again. If packets are still missing, it returns,
369  * otherwise it reads packets.
370  */
371 static int pcap_read_nocb_remote(pcap_t *p, struct pcap_pkthdr *pkt_header, u_char **pkt_data)
372 {
373 	struct pcap_rpcap *pr = p->priv;	/* structure used when doing a remote live capture */
374 	struct rpcap_header *header;		/* general header according to the RPCAP format */
375 	struct rpcap_pkthdr *net_pkt_header;	/* header of the packet, from the message */
376 	u_char *net_pkt_data;			/* packet data from the message */
377 	uint32 plen;
378 	int retval;				/* generic return value */
379 	int msglen;
380 
381 	/* Structures needed for the select() call */
382 	struct timeval tv;			/* maximum time the select() can block waiting for data */
383 	fd_set rfds;				/* set of socket descriptors we have to check */
384 
385 	/*
386 	 * Define the packet buffer timeout, to be used in the select()
387 	 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
388 	 */
389 	tv.tv_sec = p->opt.timeout / 1000;
390 	tv.tv_usec = (p->opt.timeout - tv.tv_sec * 1000) * 1000;
391 
392 	/* Watch out sockdata to see if it has input */
393 	FD_ZERO(&rfds);
394 
395 	/*
396 	 * 'fp->rmt_sockdata' has always to be set before calling the select(),
397 	 * since it is cleared by the select()
398 	 */
399 	FD_SET(pr->rmt_sockdata, &rfds);
400 
401 	retval = select((int) pr->rmt_sockdata + 1, &rfds, NULL, NULL, &tv);
402 	if (retval == -1)
403 	{
404 #ifndef _WIN32
405 		if (errno == EINTR)
406 		{
407 			/* Interrupted. */
408 			return 0;
409 		}
410 #endif
411 		sock_geterror("select()", p->errbuf, PCAP_ERRBUF_SIZE);
412 		return -1;
413 	}
414 
415 	/* There is no data waiting, so return '0' */
416 	if (retval == 0)
417 		return 0;
418 
419 	/*
420 	 * We have to define 'header' as a pointer to a larger buffer,
421 	 * because in case of UDP we have to read all the message within a single call
422 	 */
423 	header = (struct rpcap_header *) p->buffer;
424 	net_pkt_header = (struct rpcap_pkthdr *) ((char *)p->buffer + sizeof(struct rpcap_header));
425 	net_pkt_data = (u_char *)p->buffer + sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr);
426 
427 	if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
428 	{
429 		/* Read the entire message from the network */
430 		msglen = sock_recv_dgram(pr->rmt_sockdata, p->buffer,
431 		    p->bufsize, p->errbuf, PCAP_ERRBUF_SIZE);
432 		if (msglen == -1)
433 		{
434 			/* Network error. */
435 			return -1;
436 		}
437 		if (msglen == -3)
438 		{
439 			/* Interrupted receive. */
440 			return 0;
441 		}
442 		if ((size_t)msglen < sizeof(struct rpcap_header))
443 		{
444 			/*
445 			 * Message is shorter than an rpcap header.
446 			 */
447 			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
448 			    "UDP packet message is shorter than an rpcap header");
449 			return -1;
450 		}
451 		plen = ntohl(header->plen);
452 		if ((size_t)msglen < sizeof(struct rpcap_header) + plen)
453 		{
454 			/*
455 			 * Message is shorter than the header claims it
456 			 * is.
457 			 */
458 			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
459 			    "UDP packet message is shorter than its rpcap header claims");
460 			return -1;
461 		}
462 	}
463 	else
464 	{
465 		int status;
466 
467 		if ((size_t)p->cc < sizeof(struct rpcap_header))
468 		{
469 			/*
470 			 * We haven't read any of the packet header yet.
471 			 * The size we should get is the size of the
472 			 * packet header.
473 			 */
474 			status = rpcap_read_packet_msg(pr->rmt_sockdata, p,
475 			    sizeof(struct rpcap_header));
476 			if (status == -1)
477 			{
478 				/* Network error. */
479 				return -1;
480 			}
481 			if (status == -3)
482 			{
483 				/* Interrupted receive. */
484 				return 0;
485 			}
486 		}
487 
488 		/*
489 		 * We have the header, so we know how long the
490 		 * message payload is.  The size we should get
491 		 * is the size of the packet header plus the
492 		 * size of the payload.
493 		 */
494 		plen = ntohl(header->plen);
495 		if (plen > p->bufsize - sizeof(struct rpcap_header))
496 		{
497 			/*
498 			 * This is bigger than the largest
499 			 * record we'd expect.  (We do it by
500 			 * subtracting in order to avoid an
501 			 * overflow.)
502 			 */
503 			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
504 			    "Server sent us a message larger than the largest expected packet message");
505 			return -1;
506 		}
507 		status = rpcap_read_packet_msg(pr->rmt_sockdata, p,
508 		    sizeof(struct rpcap_header) + plen);
509 		if (status == -1)
510 		{
511 			/* Network error. */
512 			return -1;
513 		}
514 		if (status == -3)
515 		{
516 			/* Interrupted receive. */
517 			return 0;
518 		}
519 
520 		/*
521 		 * We have the entire message; reset the buffer pointer
522 		 * and count, as the next read should start a new
523 		 * message.
524 		 */
525 		p->bp = p->buffer;
526 		p->cc = 0;
527 	}
528 
529 	/*
530 	 * We have the entire message.
531 	 */
532 	header->plen = plen;
533 
534 	/*
535 	 * Did the server specify the version we negotiated?
536 	 */
537 	if (rpcap_check_msg_ver(pr->rmt_sockdata, pr->protocol_version,
538 	    header, p->errbuf) == -1)
539 	{
540 		return 0;	/* Return 'no packets received' */
541 	}
542 
543 	/*
544 	 * Is this a RPCAP_MSG_PACKET message?
545 	 */
546 	if (header->type != RPCAP_MSG_PACKET)
547 	{
548 		return 0;	/* Return 'no packets received' */
549 	}
550 
551 	if (ntohl(net_pkt_header->caplen) > plen)
552 	{
553 		pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
554 		    "Packet's captured data goes past the end of the received packet message.");
555 		return -1;
556 	}
557 
558 	/* Fill in packet header */
559 	pkt_header->caplen = ntohl(net_pkt_header->caplen);
560 	pkt_header->len = ntohl(net_pkt_header->len);
561 	pkt_header->ts.tv_sec = ntohl(net_pkt_header->timestamp_sec);
562 	pkt_header->ts.tv_usec = ntohl(net_pkt_header->timestamp_usec);
563 
564 	/* Supply a pointer to the beginning of the packet data */
565 	*pkt_data = net_pkt_data;
566 
567 	/*
568 	 * I don't update the counter of the packets dropped by the network since we're using TCP,
569 	 * therefore no packets are dropped. Just update the number of packets received correctly
570 	 */
571 	pr->TotCapt++;
572 
573 	if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
574 	{
575 		unsigned int npkt;
576 
577 		/* We're using UDP, so we need to update the counter of the packets dropped by the network */
578 		npkt = ntohl(net_pkt_header->npkt);
579 
580 		if (pr->TotCapt != npkt)
581 		{
582 			pr->TotNetDrops += (npkt - pr->TotCapt);
583 			pr->TotCapt = npkt;
584 		}
585 	}
586 
587 	/* Packet read successfully */
588 	return 1;
589 }
590 
591 /*
592  * This function reads a packet from the network socket.
593  *
594  * This function relies on the pcap_read_nocb_remote to deliver packets. The
595  * difference, here, is that as soon as a packet is read, it is delivered
596  * to the application by means of a callback function.
597  */
598 static int pcap_read_rpcap(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
599 {
600 	struct pcap_rpcap *pr = p->priv;	/* structure used when doing a remote live capture */
601 	struct pcap_pkthdr pkt_header;
602 	u_char *pkt_data;
603 	int n = 0;
604 	int ret;
605 
606 	/*
607 	 * If this is client-side, and we haven't already started
608 	 * the capture, start it now.
609 	 */
610 	if (pr->rmt_clientside)
611 	{
612 		/* We are on an remote capture */
613 		if (!pr->rmt_capstarted)
614 		{
615 			/*
616 			 * The capture isn't started yet, so try to
617 			 * start it.
618 			 */
619 			if (pcap_startcapture_remote(p))
620 				return -1;
621 		}
622 	}
623 
624 	while (n < cnt || PACKET_COUNT_IS_UNLIMITED(cnt))
625 	{
626 		/*
627 		 * Has "pcap_breakloop()" been called?
628 		 */
629 		if (p->break_loop) {
630 			/*
631 			 * Yes - clear the flag that indicates that it
632 			 * has, and return PCAP_ERROR_BREAK to indicate
633 			 * that we were told to break out of the loop.
634 			 */
635 			p->break_loop = 0;
636 			return (PCAP_ERROR_BREAK);
637 		}
638 
639 		/*
640 		 * Read some packets.
641 		 */
642 		ret = pcap_read_nocb_remote(p, &pkt_header, &pkt_data);
643 		if (ret == 1)
644 		{
645 			/*
646 			 * We got a packet.  Hand it to the callback
647 			 * and count it so we can return the count.
648 			 */
649 			(*callback)(user, &pkt_header, pkt_data);
650 			n++;
651 		}
652 		else if (ret == -1)
653 		{
654 			/* Error. */
655 			return ret;
656 		}
657 		else
658 		{
659 			/*
660 			 * No packet; this could mean that we timed
661 			 * out, or that we got interrupted, or that
662 			 * we got a bad packet.
663 			 *
664 			 * Were we told to break out of the loop?
665 			 */
666 			if (p->break_loop) {
667 				/*
668 				 * Yes.
669 				 */
670 				p->break_loop = 0;
671 				return (PCAP_ERROR_BREAK);
672 			}
673 			/* No - return the number of packets we've processed. */
674 			return n;
675 		}
676 	}
677 	return n;
678 }
679 
680 /*
681  * This function sends a CLOSE command to the capture server.
682  *
683  * It is called when the user calls pcap_close().  It sends a command
684  * to our peer that says 'ok, let's stop capturing'.
685  *
686  * WARNING: Since we're closing the connection, we do not check for errors.
687  */
688 static void pcap_cleanup_rpcap(pcap_t *fp)
689 {
690 	struct pcap_rpcap *pr = fp->priv;	/* structure used when doing a remote live capture */
691 	struct rpcap_header header;		/* header of the RPCAP packet */
692 	struct activehosts *temp;		/* temp var needed to scan the host list chain, to detect if we're in active mode */
693 	int active = 0;				/* active mode or not? */
694 
695 	/* detect if we're in active mode */
696 	temp = activeHosts;
697 	while (temp)
698 	{
699 		if (temp->sockctrl == pr->rmt_sockctrl)
700 		{
701 			active = 1;
702 			break;
703 		}
704 		temp = temp->next;
705 	}
706 
707 	if (!active)
708 	{
709 		rpcap_createhdr(&header, pr->protocol_version,
710 		    RPCAP_MSG_CLOSE, 0, 0);
711 
712 		/*
713 		 * Send the close request; don't report any errors, as
714 		 * we're closing this pcap_t, and have no place to report
715 		 * the error.  No reply is sent to this message.
716 		 */
717 		(void)sock_send(pr->rmt_sockctrl, (char *)&header,
718 		    sizeof(struct rpcap_header), NULL, 0);
719 	}
720 	else
721 	{
722 		rpcap_createhdr(&header, pr->protocol_version,
723 		    RPCAP_MSG_ENDCAP_REQ, 0, 0);
724 
725 		/*
726 		 * Send the end capture request; don't report any errors,
727 		 * as we're closing this pcap_t, and have no place to
728 		 * report the error.
729 		 */
730 		if (sock_send(pr->rmt_sockctrl, (char *)&header,
731 		    sizeof(struct rpcap_header), NULL, 0) == 0)
732 		{
733 			/*
734 			 * Wait for the answer; don't report any errors,
735 			 * as we're closing this pcap_t, and have no
736 			 * place to report the error.
737 			 */
738 			if (rpcap_process_msg_header(pr->rmt_sockctrl,
739 			    pr->protocol_version, RPCAP_MSG_ENDCAP_REQ,
740 			    &header, NULL) == 0)
741 			{
742 				(void)rpcap_discard(pr->rmt_sockctrl,
743 				    header.plen, NULL);
744 			}
745 		}
746 	}
747 
748 	if (pr->rmt_sockdata)
749 	{
750 		sock_close(pr->rmt_sockdata, NULL, 0);
751 		pr->rmt_sockdata = 0;
752 	}
753 
754 	if ((!active) && (pr->rmt_sockctrl))
755 		sock_close(pr->rmt_sockctrl, NULL, 0);
756 
757 	pr->rmt_sockctrl = 0;
758 
759 	if (pr->currentfilter)
760 	{
761 		free(pr->currentfilter);
762 		pr->currentfilter = NULL;
763 	}
764 
765 	pcap_cleanup_live_common(fp);
766 
767 	/* To avoid inconsistencies in the number of sock_init() */
768 	sock_cleanup();
769 }
770 
771 /*
772  * This function retrieves network statistics from our peer;
773  * it provides only the standard statistics.
774  */
775 static int pcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps)
776 {
777 	struct pcap_stat *retval;
778 
779 	retval = rpcap_stats_rpcap(p, ps, PCAP_STATS_STANDARD);
780 
781 	if (retval)
782 		return 0;
783 	else
784 		return -1;
785 }
786 
787 #ifdef _WIN32
788 /*
789  * This function retrieves network statistics from our peer;
790  * it provides the additional statistics supported by pcap_stats_ex().
791  */
792 static struct pcap_stat *pcap_stats_ex_rpcap(pcap_t *p, int *pcap_stat_size)
793 {
794 	*pcap_stat_size = sizeof (p->stat);
795 
796 	/* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
797 	return (rpcap_stats_rpcap(p, &(p->stat), PCAP_STATS_EX));
798 }
799 #endif
800 
801 /*
802  * This function retrieves network statistics from our peer.  It
803  * is used by the two previous functions.
804  *
805  * It can be called in two modes:
806  * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e.,
807  *   for pcap_stats())
808  * - PCAP_STATS_EX: if we want extended statistics (i.e., for
809  *   pcap_stats_ex())
810  *
811  * This 'mode' parameter is needed because in pcap_stats() the variable that
812  * keeps the statistics is allocated by the user. On Windows, this structure
813  * has been extended in order to keep new stats. However, if the user has a
814  * smaller structure and it passes it to pcap_stats(), this function will
815  * try to fill in more data than the size of the structure, so that memory
816  * after the structure will be overwritten.
817  *
818  * So, we need to know it we have to copy just the standard fields, or the
819  * extended fields as well.
820  *
821  * In case we want to copy the extended fields as well, the problem of
822  * memory overflow no longer exists because the structure that's filled
823  * in is part of the pcap_t, so that it can be guaranteed to be large
824  * enough for the additional statistics.
825  *
826  * \param p: the pcap_t structure related to the current instance.
827  *
828  * \param ps: a pointer to a 'pcap_stat' structure, needed for compatibility
829  * with pcap_stat(), where the structure is allocated by the user. In case
830  * of pcap_stats_ex(), this structure and the function return value point
831  * to the same variable.
832  *
833  * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
834  *
835  * \return The structure that keeps the statistics, or NULL in case of error.
836  * The error string is placed in the pcap_t structure.
837  */
838 static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode)
839 {
840 	struct pcap_rpcap *pr = p->priv;	/* structure used when doing a remote live capture */
841 	struct rpcap_header header;		/* header of the RPCAP packet */
842 	struct rpcap_stats netstats;		/* statistics sent on the network */
843 	uint32 plen;				/* data remaining in the message */
844 
845 #ifdef _WIN32
846 	if (mode != PCAP_STATS_STANDARD && mode != PCAP_STATS_EX)
847 #else
848 	if (mode != PCAP_STATS_STANDARD)
849 #endif
850 	{
851 		pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
852 		    "Invalid stats mode %d", mode);
853 		return NULL;
854 	}
855 
856 	/*
857 	 * If the capture has not yet started, we cannot request statistics
858 	 * for the capture from our peer, so we return 0 for all statistics,
859 	 * as nothing's been seen yet.
860 	 */
861 	if (!pr->rmt_capstarted)
862 	{
863 		ps->ps_drop = 0;
864 		ps->ps_ifdrop = 0;
865 		ps->ps_recv = 0;
866 #ifdef _WIN32
867 		if (mode == PCAP_STATS_EX)
868 		{
869 			ps->ps_capt = 0;
870 			ps->ps_sent = 0;
871 			ps->ps_netdrop = 0;
872 		}
873 #endif /* _WIN32 */
874 
875 		return ps;
876 	}
877 
878 	rpcap_createhdr(&header, pr->protocol_version,
879 	    RPCAP_MSG_STATS_REQ, 0, 0);
880 
881 	/* Send the PCAP_STATS command */
882 	if (sock_send(pr->rmt_sockctrl, (char *)&header,
883 	    sizeof(struct rpcap_header), p->errbuf, PCAP_ERRBUF_SIZE) < 0)
884 		return NULL;		/* Unrecoverable network error */
885 
886 	/* Receive and process the reply message header. */
887 	if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
888 	    RPCAP_MSG_STATS_REQ, &header, p->errbuf) == -1)
889 		return NULL;		/* Error */
890 
891 	plen = header.plen;
892 
893 	/* Read the reply body */
894 	if (rpcap_recv(pr->rmt_sockctrl, (char *)&netstats,
895 	    sizeof(struct rpcap_stats), &plen, p->errbuf) == -1)
896 		goto error;
897 
898 	ps->ps_drop = ntohl(netstats.krnldrop);
899 	ps->ps_ifdrop = ntohl(netstats.ifdrop);
900 	ps->ps_recv = ntohl(netstats.ifrecv);
901 #ifdef _WIN32
902 	if (mode == PCAP_STATS_EX)
903 	{
904 		ps->ps_capt = pr->TotCapt;
905 		ps->ps_netdrop = pr->TotNetDrops;
906 		ps->ps_sent = ntohl(netstats.svrcapt);
907 	}
908 #endif /* _WIN32 */
909 
910 	/* Discard the rest of the message. */
911 	if (rpcap_discard(pr->rmt_sockctrl, plen, p->errbuf) == -1)
912 		goto error_nodiscard;
913 
914 	return ps;
915 
916 error:
917 	/*
918 	 * Discard the rest of the message.
919 	 * We already reported an error; if this gets an error, just
920 	 * drive on.
921 	 */
922 	(void)rpcap_discard(pr->rmt_sockctrl, plen, NULL);
923 
924 error_nodiscard:
925 	return NULL;
926 }
927 
928 /*
929  * This function returns the entry in the list of active hosts for this
930  * active connection (active mode only), or NULL if there is no
931  * active connection or an error occurred.  It is just for internal
932  * use.
933  *
934  * \param host: a string that keeps the host name of the host for which we
935  * want to get the socket ID for that active connection.
936  *
937  * \param error: a pointer to an int that is set to 1 if an error occurred
938  * and 0 otherwise.
939  *
940  * \param errbuf: a pointer to a user-allocated buffer (of size
941  * PCAP_ERRBUF_SIZE) that will contain the error message (in case
942  * there is one).
943  *
944  * \return the entry for this host in the list of active connections
945  * if found, NULL if it's not found or there's an error.
946  */
947 static struct activehosts *
948 rpcap_remoteact_getsock(const char *host, int *error, char *errbuf)
949 {
950 	struct activehosts *temp;			/* temp var needed to scan the host list chain */
951 	struct addrinfo hints, *addrinfo, *ai_next;	/* temp var needed to translate between hostname to its address */
952 	int retval;
953 
954 	/* retrieve the network address corresponding to 'host' */
955 	addrinfo = NULL;
956 	memset(&hints, 0, sizeof(struct addrinfo));
957 	hints.ai_family = PF_UNSPEC;
958 	hints.ai_socktype = SOCK_STREAM;
959 
960 	retval = getaddrinfo(host, "0", &hints, &addrinfo);
961 	if (retval != 0)
962 	{
963 		pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "getaddrinfo() %s",
964 		    gai_strerror(retval));
965 		*error = 1;
966 		return NULL;
967 	}
968 
969 	temp = activeHosts;
970 
971 	while (temp)
972 	{
973 		ai_next = addrinfo;
974 		while (ai_next)
975 		{
976 			if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
977 			{
978 				*error = 0;
979 				freeaddrinfo(addrinfo);
980 				return temp;
981 			}
982 
983 			ai_next = ai_next->ai_next;
984 		}
985 		temp = temp->next;
986 	}
987 
988 	if (addrinfo)
989 		freeaddrinfo(addrinfo);
990 
991 	/*
992 	 * The host for which you want to get the socket ID does not have an
993 	 * active connection.
994 	 */
995 	*error = 0;
996 	return NULL;
997 }
998 
999 /*
1000  * This function starts a remote capture.
1001  *
1002  * This function is required since the RPCAP protocol decouples the 'open'
1003  * from the 'start capture' functions.
1004  * This function takes all the parameters needed (which have been stored
1005  * into the pcap_t structure) and sends them to the server.
1006  *
1007  * \param fp: the pcap_t descriptor of the device currently open.
1008  *
1009  * \return '0' if everything is fine, '-1' otherwise. The error message
1010  * (if one) is returned into the 'errbuf' field of the pcap_t structure.
1011  */
1012 static int pcap_startcapture_remote(pcap_t *fp)
1013 {
1014 	struct pcap_rpcap *pr = fp->priv;	/* structure used when doing a remote live capture */
1015 	char sendbuf[RPCAP_NETBUF_SIZE];	/* temporary buffer in which data to be sent is buffered */
1016 	int sendbufidx = 0;			/* index which keeps the number of bytes currently buffered */
1017 	char portdata[PCAP_BUF_SIZE];		/* temp variable needed to keep the network port for the data connection */
1018 	uint32 plen;
1019 	int active = 0;				/* '1' if we're in active mode */
1020 	struct activehosts *temp;		/* temp var needed to scan the host list chain, to detect if we're in active mode */
1021 	char host[INET6_ADDRSTRLEN + 1];	/* numeric name of the other host */
1022 
1023 	/* socket-related variables*/
1024 	struct addrinfo hints;			/* temp, needed to open a socket connection */
1025 	struct addrinfo *addrinfo;		/* temp, needed to open a socket connection */
1026 	SOCKET sockdata = 0;			/* socket descriptor of the data connection */
1027 	struct sockaddr_storage saddr;		/* temp, needed to retrieve the network data port chosen on the local machine */
1028 	socklen_t saddrlen;			/* temp, needed to retrieve the network data port chosen on the local machine */
1029 	int ai_family;				/* temp, keeps the address family used by the control connection */
1030 
1031 	/* RPCAP-related variables*/
1032 	struct rpcap_header header;			/* header of the RPCAP packet */
1033 	struct rpcap_startcapreq *startcapreq;		/* start capture request message */
1034 	struct rpcap_startcapreply startcapreply;	/* start capture reply message */
1035 
1036 	/* Variables related to the buffer setting */
1037 	int res;
1038 	socklen_t itemp;
1039 	int sockbufsize = 0;
1040 	uint32 server_sockbufsize;
1041 
1042 	/*
1043 	 * Let's check if sampling has been required.
1044 	 * If so, let's set it first
1045 	 */
1046 	if (pcap_setsampling_remote(fp) != 0)
1047 		return -1;
1048 
1049 	/* detect if we're in active mode */
1050 	temp = activeHosts;
1051 	while (temp)
1052 	{
1053 		if (temp->sockctrl == pr->rmt_sockctrl)
1054 		{
1055 			active = 1;
1056 			break;
1057 		}
1058 		temp = temp->next;
1059 	}
1060 
1061 	addrinfo = NULL;
1062 
1063 	/*
1064 	 * Gets the complete sockaddr structure used in the ctrl connection
1065 	 * This is needed to get the address family of the control socket
1066 	 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
1067 	 * since the ctrl socket can already be open in case of active mode;
1068 	 * so I would have to call getpeername() anyway
1069 	 */
1070 	saddrlen = sizeof(struct sockaddr_storage);
1071 	if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1072 	{
1073 		sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1074 		goto error_nodiscard;
1075 	}
1076 	ai_family = ((struct sockaddr_storage *) &saddr)->ss_family;
1077 
1078 	/* Get the numeric address of the remote host we are connected to */
1079 	if (getnameinfo((struct sockaddr *) &saddr, saddrlen, host,
1080 		sizeof(host), NULL, 0, NI_NUMERICHOST))
1081 	{
1082 		sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1083 		goto error_nodiscard;
1084 	}
1085 
1086 	/*
1087 	 * Data connection is opened by the server toward the client if:
1088 	 * - we're using TCP, and the user wants us to be in active mode
1089 	 * - we're using UDP
1090 	 */
1091 	if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1092 	{
1093 		/*
1094 		 * We have to create a new socket to receive packets
1095 		 * We have to do that immediately, since we have to tell the other
1096 		 * end which network port we picked up
1097 		 */
1098 		memset(&hints, 0, sizeof(struct addrinfo));
1099 		/* TEMP addrinfo is NULL in case of active */
1100 		hints.ai_family = ai_family;	/* Use the same address family of the control socket */
1101 		hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1102 		hints.ai_flags = AI_PASSIVE;	/* Data connection is opened by the server toward the client */
1103 
1104 		/* Let's the server pick up a free network port for us */
1105 		if (sock_initaddress(NULL, "0", &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1106 			goto error_nodiscard;
1107 
1108 		if ((sockdata = sock_open(addrinfo, SOCKOPEN_SERVER,
1109 			1 /* max 1 connection in queue */, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1110 			goto error_nodiscard;
1111 
1112 		/* addrinfo is no longer used */
1113 		freeaddrinfo(addrinfo);
1114 		addrinfo = NULL;
1115 
1116 		/* get the complete sockaddr structure used in the data connection */
1117 		saddrlen = sizeof(struct sockaddr_storage);
1118 		if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1119 		{
1120 			sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1121 			goto error_nodiscard;
1122 		}
1123 
1124 		/* Get the local port the system picked up */
1125 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
1126 			0, portdata, sizeof(portdata), NI_NUMERICSERV))
1127 		{
1128 			sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1129 			goto error_nodiscard;
1130 		}
1131 	}
1132 
1133 	/*
1134 	 * Now it's time to start playing with the RPCAP protocol
1135 	 * RPCAP start capture command: create the request message
1136 	 */
1137 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1138 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1139 		goto error_nodiscard;
1140 
1141 	rpcap_createhdr((struct rpcap_header *) sendbuf,
1142 	    pr->protocol_version, RPCAP_MSG_STARTCAP_REQ, 0,
1143 	    sizeof(struct rpcap_startcapreq) + sizeof(struct rpcap_filter) + fp->fcode.bf_len * sizeof(struct rpcap_filterbpf_insn));
1144 
1145 	/* Fill the structure needed to open an adapter remotely */
1146 	startcapreq = (struct rpcap_startcapreq *) &sendbuf[sendbufidx];
1147 
1148 	if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreq), NULL,
1149 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1150 		goto error_nodiscard;
1151 
1152 	memset(startcapreq, 0, sizeof(struct rpcap_startcapreq));
1153 
1154 	/* By default, apply half the timeout on one side, half of the other */
1155 	fp->opt.timeout = fp->opt.timeout / 2;
1156 	startcapreq->read_timeout = htonl(fp->opt.timeout);
1157 
1158 	/* portdata on the openreq is meaningful only if we're in active mode */
1159 	if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1160 	{
1161 		sscanf(portdata, "%d", (int *)&(startcapreq->portdata));	/* cast to avoid a compiler warning */
1162 		startcapreq->portdata = htons(startcapreq->portdata);
1163 	}
1164 
1165 	startcapreq->snaplen = htonl(fp->snapshot);
1166 	startcapreq->flags = 0;
1167 
1168 	if (pr->rmt_flags & PCAP_OPENFLAG_PROMISCUOUS)
1169 		startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_PROMISC;
1170 	if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
1171 		startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_DGRAM;
1172 	if (active)
1173 		startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN;
1174 
1175 	startcapreq->flags = htons(startcapreq->flags);
1176 
1177 	/* Pack the capture filter */
1178 	if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, &fp->fcode))
1179 		goto error_nodiscard;
1180 
1181 	if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf,
1182 	    PCAP_ERRBUF_SIZE) < 0)
1183 		goto error_nodiscard;
1184 
1185 	/* Receive and process the reply message header. */
1186 	if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
1187 	    RPCAP_MSG_STARTCAP_REQ, &header, fp->errbuf) == -1)
1188 		goto error_nodiscard;
1189 
1190 	plen = header.plen;
1191 
1192 	if (rpcap_recv(pr->rmt_sockctrl, (char *)&startcapreply,
1193 	    sizeof(struct rpcap_startcapreply), &plen, fp->errbuf) == -1)
1194 		goto error;
1195 
1196 	/*
1197 	 * In case of UDP data stream, the connection is always opened by the daemon
1198 	 * So, this case is already covered by the code above.
1199 	 * Now, we have still to handle TCP connections, because:
1200 	 * - if we're in active mode, we have to wait for a remote connection
1201 	 * - if we're in passive more, we have to start a connection
1202 	 *
1203 	 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1204 	 * to tell the port we're using to the remote side; in case we're accepting a TCP
1205 	 * connection, we have to wait this info from the remote side.
1206 	 */
1207 	if (!(pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1208 	{
1209 		if (!active)
1210 		{
1211 			memset(&hints, 0, sizeof(struct addrinfo));
1212 			hints.ai_family = ai_family;		/* Use the same address family of the control socket */
1213 			hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1214 			pcap_snprintf(portdata, PCAP_BUF_SIZE, "%d", ntohs(startcapreply.portdata));
1215 
1216 			/* Let's the server pick up a free network port for us */
1217 			if (sock_initaddress(host, portdata, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1218 				goto error;
1219 
1220 			if ((sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1221 				goto error;
1222 
1223 			/* addrinfo is no longer used */
1224 			freeaddrinfo(addrinfo);
1225 			addrinfo = NULL;
1226 		}
1227 		else
1228 		{
1229 			SOCKET socktemp;	/* We need another socket, since we're going to accept() a connection */
1230 
1231 			/* Connection creation */
1232 			saddrlen = sizeof(struct sockaddr_storage);
1233 
1234 			socktemp = accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
1235 
1236 			if (socktemp == INVALID_SOCKET)
1237 			{
1238 				sock_geterror("accept()", fp->errbuf, PCAP_ERRBUF_SIZE);
1239 				goto error;
1240 			}
1241 
1242 			/* Now that I accepted the connection, the server socket is no longer needed */
1243 			sock_close(sockdata, fp->errbuf, PCAP_ERRBUF_SIZE);
1244 			sockdata = socktemp;
1245 		}
1246 	}
1247 
1248 	/* Let's save the socket of the data connection */
1249 	pr->rmt_sockdata = sockdata;
1250 
1251 	/*
1252 	 * Set the size of the socket buffer for the data socket.
1253 	 * It has the same size as the local capture buffer used
1254 	 * on the other side of the connection.
1255 	 */
1256 	server_sockbufsize = ntohl(startcapreply.bufsize);
1257 
1258 	/* Let's get the actual size of the socket buffer */
1259 	itemp = sizeof(sockbufsize);
1260 
1261 	res = getsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &itemp);
1262 	if (res == -1)
1263 	{
1264 		sock_geterror("pcap_startcapture_remote(): getsockopt() failed", fp->errbuf, PCAP_ERRBUF_SIZE);
1265 		goto error;
1266 	}
1267 
1268 	/*
1269 	 * Warning: on some kernels (e.g. Linux), the size of the user
1270 	 * buffer does not take into account the pcap_header and such,
1271 	 * and it is set equal to the snaplen.
1272 	 *
1273 	 * In my view, this is wrong (the meaning of the bufsize became
1274 	 * a bit strange).  So, here bufsize is the whole size of the
1275 	 * user buffer.  In case the bufsize returned is too small,
1276 	 * let's adjust it accordingly.
1277 	 */
1278 	if (server_sockbufsize <= (u_int) fp->snapshot)
1279 		server_sockbufsize += sizeof(struct pcap_pkthdr);
1280 
1281 	/* if the current socket buffer is smaller than the desired one */
1282 	if ((u_int) sockbufsize < server_sockbufsize)
1283 	{
1284 		/*
1285 		 * Loop until the buffer size is OK or the original
1286 		 * socket buffer size is larger than this one.
1287 		 */
1288 		for (;;)
1289 		{
1290 			res = setsockopt(sockdata, SOL_SOCKET, SO_RCVBUF,
1291 			    (char *)&(server_sockbufsize),
1292 			    sizeof(server_sockbufsize));
1293 
1294 			if (res == 0)
1295 				break;
1296 
1297 			/*
1298 			 * If something goes wrong, halve the buffer size
1299 			 * (checking that it does not become smaller than
1300 			 * the current one).
1301 			 */
1302 			server_sockbufsize /= 2;
1303 
1304 			if ((u_int) sockbufsize >= server_sockbufsize)
1305 			{
1306 				server_sockbufsize = sockbufsize;
1307 				break;
1308 			}
1309 		}
1310 	}
1311 
1312 	/*
1313 	 * Let's allocate the packet; this is required in order to put
1314 	 * the packet somewhere when extracting data from the socket.
1315 	 * Since buffering has already been done in the socket buffer,
1316 	 * here we need just a buffer whose size is equal to the
1317 	 * largest possible packet message for the snapshot size,
1318 	 * namely the length of the message header plus the length
1319 	 * of the packet header plus the snapshot length.
1320 	 */
1321 	fp->bufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + fp->snapshot;
1322 
1323 	fp->buffer = (u_char *)malloc(fp->bufsize);
1324 	if (fp->buffer == NULL)
1325 	{
1326 		pcap_fmt_errmsg_for_errno(fp->errbuf, PCAP_ERRBUF_SIZE,
1327 		    errno, "malloc");
1328 		goto error;
1329 	}
1330 
1331 	/*
1332 	 * The buffer is currently empty.
1333 	 */
1334 	fp->bp = fp->buffer;
1335 	fp->cc = 0;
1336 
1337 	/* Discard the rest of the message. */
1338 	if (rpcap_discard(pr->rmt_sockctrl, plen, fp->errbuf) == -1)
1339 		goto error_nodiscard;
1340 
1341 	/*
1342 	 * In case the user does not want to capture RPCAP packets, let's update the filter
1343 	 * We have to update it here (instead of sending it into the 'StartCapture' message
1344 	 * because when we generate the 'start capture' we do not know (yet) all the ports
1345 	 * we're currently using.
1346 	 */
1347 	if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1348 	{
1349 		struct bpf_program fcode;
1350 
1351 		if (pcap_createfilter_norpcappkt(fp, &fcode) == -1)
1352 			goto error;
1353 
1354 		/* We cannot use 'pcap_setfilter_rpcap' because formally the capture has not been started yet */
1355 		/* (the 'pr->rmt_capstarted' variable will be updated some lines below) */
1356 		if (pcap_updatefilter_remote(fp, &fcode) == -1)
1357 			goto error;
1358 
1359 		pcap_freecode(&fcode);
1360 	}
1361 
1362 	pr->rmt_capstarted = 1;
1363 	return 0;
1364 
1365 error:
1366 	/*
1367 	 * When the connection has been established, we have to close it. So, at the
1368 	 * beginning of this function, if an error occur we return immediately with
1369 	 * a return NULL; when the connection is established, we have to come here
1370 	 * ('goto error;') in order to close everything properly.
1371 	 */
1372 
1373 	/*
1374 	 * Discard the rest of the message.
1375 	 * We already reported an error; if this gets an error, just
1376 	 * drive on.
1377 	 */
1378 	(void)rpcap_discard(pr->rmt_sockctrl, plen, NULL);
1379 
1380 error_nodiscard:
1381 	if ((sockdata) && (sockdata != -1))		/* we can be here because sockdata said 'error' */
1382 		sock_close(sockdata, NULL, 0);
1383 
1384 	if (!active)
1385 		sock_close(pr->rmt_sockctrl, NULL, 0);
1386 
1387 	if (addrinfo != NULL)
1388 		freeaddrinfo(addrinfo);
1389 
1390 	/*
1391 	 * We do not have to call pcap_close() here, because this function is always called
1392 	 * by the user in case something bad happens
1393 	 */
1394 #if 0
1395 	if (fp)
1396 	{
1397 		pcap_close(fp);
1398 		fp= NULL;
1399 	}
1400 #endif
1401 
1402 	return -1;
1403 }
1404 
1405 /*
1406  * This function takes a bpf program and sends it to the other host.
1407  *
1408  * This function can be called in two cases:
1409  * - pcap_startcapture_remote() is called (we have to send the filter
1410  *   along with the 'start capture' command)
1411  * - we want to udpate the filter during a capture (i.e. pcap_setfilter()
1412  *   after the capture has been started)
1413  *
1414  * This function serializes the filter into the sending buffer ('sendbuf',
1415  * passed as a parameter) and return back. It does not send anything on
1416  * the network.
1417  *
1418  * \param fp: the pcap_t descriptor of the device currently opened.
1419  *
1420  * \param sendbuf: the buffer on which the serialized data has to copied.
1421  *
1422  * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1423  *
1424  * \param prog: the bpf program we have to copy.
1425  *
1426  * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1427  * is returned into the 'errbuf' field of the pcap_t structure.
1428  */
1429 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog)
1430 {
1431 	struct rpcap_filter *filter;
1432 	struct rpcap_filterbpf_insn *insn;
1433 	struct bpf_insn *bf_insn;
1434 	struct bpf_program fake_prog;		/* To be used just in case the user forgot to set a filter */
1435 	unsigned int i;
1436 
1437 	if (prog->bf_len == 0)	/* No filters have been specified; so, let's apply a "fake" filter */
1438 	{
1439 		if (pcap_compile(fp, &fake_prog, NULL /* buffer */, 1, 0) == -1)
1440 			return -1;
1441 
1442 		prog = &fake_prog;
1443 	}
1444 
1445 	filter = (struct rpcap_filter *) sendbuf;
1446 
1447 	if (sock_bufferize(NULL, sizeof(struct rpcap_filter), NULL, sendbufidx,
1448 		RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1449 		return -1;
1450 
1451 	filter->filtertype = htons(RPCAP_UPDATEFILTER_BPF);
1452 	filter->nitems = htonl((int32)prog->bf_len);
1453 
1454 	if (sock_bufferize(NULL, prog->bf_len * sizeof(struct rpcap_filterbpf_insn),
1455 		NULL, sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1456 		return -1;
1457 
1458 	insn = (struct rpcap_filterbpf_insn *) (filter + 1);
1459 	bf_insn = prog->bf_insns;
1460 
1461 	for (i = 0; i < prog->bf_len; i++)
1462 	{
1463 		insn->code = htons(bf_insn->code);
1464 		insn->jf = bf_insn->jf;
1465 		insn->jt = bf_insn->jt;
1466 		insn->k = htonl(bf_insn->k);
1467 
1468 		insn++;
1469 		bf_insn++;
1470 	}
1471 
1472 	return 0;
1473 }
1474 
1475 /*
1476  * This function updates a filter on a remote host.
1477  *
1478  * It is called when the user wants to update a filter.
1479  * In case we're capturing from the network, it sends the filter to our
1480  * peer.
1481  * This function is *not* called automatically when the user calls
1482  * pcap_setfilter().
1483  * There will be two cases:
1484  * - the capture has been started: in this case, pcap_setfilter_rpcap()
1485  *   calls pcap_updatefilter_remote()
1486  * - the capture has not started yet: in this case, pcap_setfilter_rpcap()
1487  *   stores the filter into the pcap_t structure, and then the filter is
1488  *   sent with pcap_startcap().
1489  *
1490  * WARNING This function *does not* clear the packet currently into the
1491  * buffers. Therefore, the user has to expect to receive some packets
1492  * that are related to the previous filter.  If you want to discard all
1493  * the packets before applying a new filter, you have to close the
1494  * current capture session and start a new one.
1495  *
1496  * XXX - we really should have pcap_setfilter() always discard packets
1497  * received with the old filter, and have a separate pcap_setfilter_noflush()
1498  * function that doesn't discard any packets.
1499  */
1500 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog)
1501 {
1502 	struct pcap_rpcap *pr = fp->priv;	/* structure used when doing a remote live capture */
1503 	char sendbuf[RPCAP_NETBUF_SIZE];	/* temporary buffer in which data to be sent is buffered */
1504 	int sendbufidx = 0;			/* index which keeps the number of bytes currently buffered */
1505 	struct rpcap_header header;		/* To keep the reply message */
1506 
1507 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1508 		RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1509 		return -1;
1510 
1511 	rpcap_createhdr((struct rpcap_header *) sendbuf,
1512 	    pr->protocol_version, RPCAP_MSG_UPDATEFILTER_REQ, 0,
1513 	    sizeof(struct rpcap_filter) + prog->bf_len * sizeof(struct rpcap_filterbpf_insn));
1514 
1515 	if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, prog))
1516 		return -1;
1517 
1518 	if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf,
1519 	    PCAP_ERRBUF_SIZE) < 0)
1520 		return -1;
1521 
1522 	/* Receive and process the reply message header. */
1523 	if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
1524 	    RPCAP_MSG_UPDATEFILTER_REQ, &header, fp->errbuf) == -1)
1525 		return -1;
1526 
1527 	/*
1528 	 * It shouldn't have any contents; discard it if it does.
1529 	 */
1530 	if (rpcap_discard(pr->rmt_sockctrl, header.plen, fp->errbuf) == -1)
1531 		return -1;
1532 
1533 	return 0;
1534 }
1535 
1536 static void
1537 pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter)
1538 {
1539 	struct pcap_rpcap *pr = fp->priv;	/* structure used when doing a remote live capture */
1540 
1541 	/*
1542 	 * Check if:
1543 	 *  - We are on an remote capture
1544 	 *  - we do not want to capture RPCAP traffic
1545 	 *
1546 	 * If so, we have to save the current filter, because we have to
1547 	 * add some piece of stuff later
1548 	 */
1549 	if (pr->rmt_clientside &&
1550 	    (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP))
1551 	{
1552 		if (pr->currentfilter)
1553 			free(pr->currentfilter);
1554 
1555 		if (filter == NULL)
1556 			filter = "";
1557 
1558 		pr->currentfilter = strdup(filter);
1559 	}
1560 }
1561 
1562 /*
1563  * This function sends a filter to a remote host.
1564  *
1565  * This function is called when the user wants to set a filter.
1566  * It sends the filter to our peer.
1567  * This function is called automatically when the user calls pcap_setfilter().
1568  *
1569  * Parameters and return values are exactly the same of pcap_setfilter().
1570  */
1571 static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog)
1572 {
1573 	struct pcap_rpcap *pr = fp->priv;	/* structure used when doing a remote live capture */
1574 
1575 	if (!pr->rmt_capstarted)
1576 	{
1577 		/* copy filter into the pcap_t structure */
1578 		if (install_bpf_program(fp, prog) == -1)
1579 			return -1;
1580 		return 0;
1581 	}
1582 
1583 	/* we have to update a filter during run-time */
1584 	if (pcap_updatefilter_remote(fp, prog))
1585 		return -1;
1586 
1587 	return 0;
1588 }
1589 
1590 /*
1591  * This function updates the current filter in order not to capture rpcap
1592  * packets.
1593  *
1594  * This function is called *only* when the user wants exclude RPCAP packets
1595  * related to the current session from the captured packets.
1596  *
1597  * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1598  * is returned into the 'errbuf' field of the pcap_t structure.
1599  */
1600 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog)
1601 {
1602 	struct pcap_rpcap *pr = fp->priv;	/* structure used when doing a remote live capture */
1603 	int RetVal = 0;
1604 
1605 	/* We do not want to capture our RPCAP traffic. So, let's update the filter */
1606 	if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1607 	{
1608 		struct sockaddr_storage saddr;		/* temp, needed to retrieve the network data port chosen on the local machine */
1609 		socklen_t saddrlen;					/* temp, needed to retrieve the network data port chosen on the local machine */
1610 		char myaddress[128];
1611 		char myctrlport[128];
1612 		char mydataport[128];
1613 		char peeraddress[128];
1614 		char peerctrlport[128];
1615 		char *newfilter;
1616 
1617 		/* Get the name/port of our peer */
1618 		saddrlen = sizeof(struct sockaddr_storage);
1619 		if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1620 		{
1621 			sock_geterror("getpeername()", fp->errbuf, PCAP_ERRBUF_SIZE);
1622 			return -1;
1623 		}
1624 
1625 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peeraddress,
1626 			sizeof(peeraddress), peerctrlport, sizeof(peerctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1627 		{
1628 			sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1629 			return -1;
1630 		}
1631 
1632 		/* We cannot check the data port, because this is available only in case of TCP sockets */
1633 		/* Get the name/port of the current host */
1634 		if (getsockname(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1635 		{
1636 			sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1637 			return -1;
1638 		}
1639 
1640 		/* Get the local port the system picked up */
1641 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, myaddress,
1642 			sizeof(myaddress), myctrlport, sizeof(myctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1643 		{
1644 			sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1645 			return -1;
1646 		}
1647 
1648 		/* Let's now check the data port */
1649 		if (getsockname(pr->rmt_sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1650 		{
1651 			sock_geterror("getsockname()", fp->errbuf, PCAP_ERRBUF_SIZE);
1652 			return -1;
1653 		}
1654 
1655 		/* Get the local port the system picked up */
1656 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL, 0, mydataport, sizeof(mydataport), NI_NUMERICSERV))
1657 		{
1658 			sock_geterror("getnameinfo()", fp->errbuf, PCAP_ERRBUF_SIZE);
1659 			return -1;
1660 		}
1661 
1662 		if (pr->currentfilter && pr->currentfilter[0] != '\0')
1663 		{
1664 			/*
1665 			 * We have a current filter; add items to it to
1666 			 * filter out this rpcap session.
1667 			 */
1668 			if (pcap_asprintf(&newfilter,
1669 			    "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1670 			    pr->currentfilter, myaddress, peeraddress,
1671 			    myctrlport, peerctrlport, myaddress, peeraddress,
1672 			    mydataport) == -1)
1673 			{
1674 				/* Failed. */
1675 				pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1676 				    "Can't allocate memory for new filter");
1677 				return -1;
1678 			}
1679 		}
1680 		else
1681 		{
1682 			/*
1683 			 * We have no current filter; construct a filter to
1684 			 * filter out this rpcap session.
1685 			 */
1686 			if (pcap_asprintf(&newfilter,
1687 			    "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1688 			    myaddress, peeraddress, myctrlport, peerctrlport,
1689 			    myaddress, peeraddress, mydataport) == -1)
1690 			{
1691 				/* Failed. */
1692 				pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1693 				    "Can't allocate memory for new filter");
1694 				return -1;
1695 			}
1696 		}
1697 
1698 		/*
1699 		 * This is only an hack to prevent the save_current_filter
1700 		 * routine, which will be called when we call pcap_compile(),
1701 		 * from saving the modified filter.
1702 		 */
1703 		pr->rmt_clientside = 0;
1704 
1705 		if (pcap_compile(fp, prog, newfilter, 1, 0) == -1)
1706 			RetVal = -1;
1707 
1708 		/* Undo the hack. */
1709 		pr->rmt_clientside = 1;
1710 
1711 		free(newfilter);
1712 	}
1713 
1714 	return RetVal;
1715 }
1716 
1717 /*
1718  * This function sets sampling parameters in the remote host.
1719  *
1720  * It is called when the user wants to set activate sampling on the
1721  * remote host.
1722  *
1723  * Sampling parameters are defined into the 'pcap_t' structure.
1724  *
1725  * \param p: the pcap_t descriptor of the device currently opened.
1726  *
1727  * \return '0' if everything is OK, '-1' is something goes wrong. The
1728  * error message is returned in the 'errbuf' member of the pcap_t structure.
1729  */
1730 static int pcap_setsampling_remote(pcap_t *fp)
1731 {
1732 	struct pcap_rpcap *pr = fp->priv;	/* structure used when doing a remote live capture */
1733 	char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
1734 	int sendbufidx = 0;			/* index which keeps the number of bytes currently buffered */
1735 	struct rpcap_header header;		/* To keep the reply message */
1736 	struct rpcap_sampling *sampling_pars;	/* Structure that is needed to send sampling parameters to the remote host */
1737 
1738 	/* If no samping is requested, return 'ok' */
1739 	if (fp->rmt_samp.method == PCAP_SAMP_NOSAMP)
1740 		return 0;
1741 
1742 	/*
1743 	 * Check for sampling parameters that don't fit in a message.
1744 	 * We'll let the server complain about invalid parameters
1745 	 * that do fit into the message.
1746 	 */
1747 	if (fp->rmt_samp.method < 0 || fp->rmt_samp.method > 255) {
1748 		pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1749 		    "Invalid sampling method %d", fp->rmt_samp.method);
1750 		return -1;
1751 	}
1752 	if (fp->rmt_samp.value < 0 || fp->rmt_samp.value > 65535) {
1753 		pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
1754 		    "Invalid sampling value %d", fp->rmt_samp.value);
1755 		return -1;
1756 	}
1757 
1758 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1759 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1760 		return -1;
1761 
1762 	rpcap_createhdr((struct rpcap_header *) sendbuf,
1763 	    pr->protocol_version, RPCAP_MSG_SETSAMPLING_REQ, 0,
1764 	    sizeof(struct rpcap_sampling));
1765 
1766 	/* Fill the structure needed to open an adapter remotely */
1767 	sampling_pars = (struct rpcap_sampling *) &sendbuf[sendbufidx];
1768 
1769 	if (sock_bufferize(NULL, sizeof(struct rpcap_sampling), NULL,
1770 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1771 		return -1;
1772 
1773 	memset(sampling_pars, 0, sizeof(struct rpcap_sampling));
1774 
1775 	sampling_pars->method = (uint8)fp->rmt_samp.method;
1776 	sampling_pars->value = (uint16)htonl(fp->rmt_samp.value);
1777 
1778 	if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf,
1779 	    PCAP_ERRBUF_SIZE) < 0)
1780 		return -1;
1781 
1782 	/* Receive and process the reply message header. */
1783 	if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
1784 	    RPCAP_MSG_SETSAMPLING_REQ, &header, fp->errbuf) == -1)
1785 		return -1;
1786 
1787 	/*
1788 	 * It shouldn't have any contents; discard it if it does.
1789 	 */
1790 	if (rpcap_discard(pr->rmt_sockctrl, header.plen, fp->errbuf) == -1)
1791 		return -1;
1792 
1793 	return 0;
1794 }
1795 
1796 /*********************************************************
1797  *                                                       *
1798  * Miscellaneous functions                               *
1799  *                                                       *
1800  *********************************************************/
1801 
1802 /*
1803  * This function performs authentication and protocol version
1804  * negotiation.  It is required in order to open the connection
1805  * with the other end party.
1806  *
1807  * It sends authentication parameters on the control socket and
1808  * reads the reply.  If the reply is a success indication, it
1809  * checks whether the reply includes minimum and maximum supported
1810  * versions from the server; if not, it assumes both are 0, as
1811  * that means it's an older server that doesn't return supported
1812  * version numbers in authentication replies, so it only supports
1813  * version 0.  It then tries to determine the maximum version
1814  * supported both by us and by the server.  If it can find such a
1815  * version, it sets us up to use that version; otherwise, it fails,
1816  * indicating that there is no version supported by us and by the
1817  * server.
1818  *
1819  * \param sock: the socket we are currently using.
1820  *
1821  * \param ver: pointer to variable to which to set the protocol version
1822  * number we selected.
1823  *
1824  * \param auth: authentication parameters that have to be sent.
1825  *
1826  * \param errbuf: a pointer to a user-allocated buffer (of size
1827  * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1828  * is one). It could be a network problem or the fact that the authorization
1829  * failed.
1830  *
1831  * \return '0' if everything is fine, '-1' for an error.  For errors,
1832  * an error message string is returned in the 'errbuf' variable.
1833  */
1834 static int rpcap_doauth(SOCKET sockctrl, uint8 *ver, struct pcap_rmtauth *auth, char *errbuf)
1835 {
1836 	char sendbuf[RPCAP_NETBUF_SIZE];	/* temporary buffer in which data that has to be sent is buffered */
1837 	int sendbufidx = 0;			/* index which keeps the number of bytes currently buffered */
1838 	uint16 length;				/* length of the payload of this message */
1839 	struct rpcap_auth *rpauth;
1840 	uint16 auth_type;
1841 	struct rpcap_header header;
1842 	size_t str_length;
1843 	uint32 plen;
1844 	struct rpcap_authreply authreply;	/* authentication reply message */
1845 	uint8 ourvers;
1846 
1847 	if (auth)
1848 	{
1849 		switch (auth->type)
1850 		{
1851 		case RPCAP_RMTAUTH_NULL:
1852 			length = sizeof(struct rpcap_auth);
1853 			break;
1854 
1855 		case RPCAP_RMTAUTH_PWD:
1856 			length = sizeof(struct rpcap_auth);
1857 			if (auth->username)
1858 			{
1859 				str_length = strlen(auth->username);
1860 				if (str_length > 65535)
1861 				{
1862 					pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "User name is too long (> 65535 bytes)");
1863 					return -1;
1864 				}
1865 				length += (uint16)str_length;
1866 			}
1867 			if (auth->password)
1868 			{
1869 				str_length = strlen(auth->password);
1870 				if (str_length > 65535)
1871 				{
1872 					pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Password is too long (> 65535 bytes)");
1873 					return -1;
1874 				}
1875 				length += (uint16)str_length;
1876 			}
1877 			break;
1878 
1879 		default:
1880 			pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized.");
1881 			return -1;
1882 		}
1883 
1884 		auth_type = (uint16)auth->type;
1885 	}
1886 	else
1887 	{
1888 		auth_type = RPCAP_RMTAUTH_NULL;
1889 		length = sizeof(struct rpcap_auth);
1890 	}
1891 
1892 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1893 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1894 		return -1;
1895 
1896 	rpcap_createhdr((struct rpcap_header *) sendbuf, 0,
1897 	    RPCAP_MSG_AUTH_REQ, 0, length);
1898 
1899 	rpauth = (struct rpcap_auth *) &sendbuf[sendbufidx];
1900 
1901 	if (sock_bufferize(NULL, sizeof(struct rpcap_auth), NULL,
1902 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1903 		return -1;
1904 
1905 	memset(rpauth, 0, sizeof(struct rpcap_auth));
1906 
1907 	rpauth->type = htons(auth_type);
1908 
1909 	if (auth_type == RPCAP_RMTAUTH_PWD)
1910 	{
1911 		if (auth->username)
1912 			rpauth->slen1 = (uint16)strlen(auth->username);
1913 		else
1914 			rpauth->slen1 = 0;
1915 
1916 		if (sock_bufferize(auth->username, rpauth->slen1, sendbuf,
1917 			&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1918 			return -1;
1919 
1920 		if (auth->password)
1921 			rpauth->slen2 = (uint16)strlen(auth->password);
1922 		else
1923 			rpauth->slen2 = 0;
1924 
1925 		if (sock_bufferize(auth->password, rpauth->slen2, sendbuf,
1926 			&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1927 			return -1;
1928 
1929 		rpauth->slen1 = htons(rpauth->slen1);
1930 		rpauth->slen2 = htons(rpauth->slen2);
1931 	}
1932 
1933 	if (sock_send(sockctrl, sendbuf, sendbufidx, errbuf,
1934 	    PCAP_ERRBUF_SIZE) < 0)
1935 		return -1;
1936 
1937 	/* Receive and process the reply message header */
1938 	if (rpcap_process_msg_header(sockctrl, 0, RPCAP_MSG_AUTH_REQ,
1939 	    &header, errbuf) == -1)
1940 		return -1;
1941 
1942 	/*
1943 	 * OK, it's an authentication reply, so we're logged in.
1944 	 *
1945 	 * Did it send any additional information?
1946 	 */
1947 	plen = header.plen;
1948 	if (plen != 0)
1949 	{
1950 		/* Yes - is it big enough to be version information? */
1951 		if (plen < sizeof(struct rpcap_authreply))
1952 		{
1953 			/* No - discard it and fail. */
1954 			(void)rpcap_discard(sockctrl, plen, NULL);
1955 			return -1;
1956 		}
1957 
1958 		/* Read the reply body */
1959 		if (rpcap_recv(sockctrl, (char *)&authreply,
1960 		    sizeof(struct rpcap_authreply), &plen, errbuf) == -1)
1961 		{
1962 			(void)rpcap_discard(sockctrl, plen, NULL);
1963 			return -1;
1964 		}
1965 
1966 		/* Discard the rest of the message, if there is any. */
1967 		if (rpcap_discard(sockctrl, plen, errbuf) == -1)
1968 			return -1;
1969 
1970 		/*
1971 		 * Check the minimum and maximum versions for sanity;
1972 		 * the minimum must be <= the maximum.
1973 		 */
1974 		if (authreply.minvers > authreply.maxvers)
1975 		{
1976 			/*
1977 			 * Bogus - give up on this server.
1978 			 */
1979 			pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1980 			    "The server's minimum supported protocol version is greater than its maximum supported protocol version");
1981 			return -1;
1982 		}
1983 	}
1984 	else
1985 	{
1986 		/* No - it supports only version 0. */
1987 		authreply.minvers = 0;
1988 		authreply.maxvers = 0;
1989 	}
1990 
1991 	/*
1992 	 * OK, let's start with the maximum version the server supports.
1993 	 */
1994 	ourvers = authreply.maxvers;
1995 
1996 #if RPCAP_MIN_VERSION != 0
1997 	/*
1998 	 * If that's less than the minimum version we support, we
1999 	 * can't communicate.
2000 	 */
2001 	if (ourvers < RPCAP_MIN_VERSION)
2002 		goto novers;
2003 #endif
2004 
2005 	/*
2006 	 * If that's greater than the maximum version we support,
2007 	 * choose the maximum version we support.
2008 	 */
2009 	if (ourvers > RPCAP_MAX_VERSION)
2010 	{
2011 		ourvers = RPCAP_MAX_VERSION;
2012 
2013 		/*
2014 		 * If that's less than the minimum version they
2015 		 * support, we can't communicate.
2016 		 */
2017 		if (ourvers < authreply.minvers)
2018 			goto novers;
2019 	}
2020 
2021 	*ver = ourvers;
2022 	return 0;
2023 
2024 novers:
2025 	/*
2026 	 * There is no version we both support; that is a fatal error.
2027 	 */
2028 	pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
2029 	    "The server doesn't support any protocol version that we support");
2030 	return -1;
2031 }
2032 
2033 /* We don't currently support non-blocking mode. */
2034 static int
2035 pcap_getnonblock_rpcap(pcap_t *p)
2036 {
2037 	pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2038 	    "Non-blocking mode isn't supported for capturing remotely with rpcap");
2039 	return (-1);
2040 }
2041 
2042 static int
2043 pcap_setnonblock_rpcap(pcap_t *p, int nonblock _U_)
2044 {
2045 	pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2046 	    "Non-blocking mode isn't supported for capturing remotely with rpcap");
2047 	return (-1);
2048 }
2049 
2050 static int
2051 rpcap_setup_session(const char *source, struct pcap_rmtauth *auth,
2052     int *activep, SOCKET *sockctrlp, uint8 *protocol_versionp,
2053     char *host, char *port, char *iface, char *errbuf)
2054 {
2055 	int type;
2056 	struct activehosts *activeconn;		/* active connection, if there is one */
2057 	int error;				/* 1 if rpcap_remoteact_getsock got an error */
2058 
2059 	/*
2060 	 * Determine the type of the source (NULL, file, local, remote).
2061 	 * You must have a valid source string even if we're in active mode,
2062 	 * because otherwise the call to the following function will fail.
2063 	 */
2064 	if (pcap_parsesrcstr(source, &type, host, port, iface, errbuf) == -1)
2065 		return -1;
2066 
2067 	/*
2068 	 * It must be remote.
2069 	 */
2070 	if (type != PCAP_SRC_IFREMOTE)
2071 	{
2072 		pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
2073 		    "Non-remote interface passed to remote capture routine");
2074 		return -1;
2075 	}
2076 
2077 	/* Warning: this call can be the first one called by the user. */
2078 	/* For this reason, we have to initialize the WinSock support. */
2079 	if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
2080 		return -1;
2081 
2082 	/* Check for active mode */
2083 	activeconn = rpcap_remoteact_getsock(host, &error, errbuf);
2084 	if (activeconn != NULL)
2085 	{
2086 		*activep = 1;
2087 		*sockctrlp = activeconn->sockctrl;
2088 		*protocol_versionp = activeconn->protocol_version;
2089 	}
2090 	else
2091 	{
2092 		*activep = 0;
2093 		struct addrinfo hints;		/* temp variable needed to resolve hostnames into to socket representation */
2094 		struct addrinfo *addrinfo;	/* temp variable needed to resolve hostnames into to socket representation */
2095 
2096 		if (error)
2097 		{
2098 			/*
2099 			 * Call failed.
2100 			 */
2101 			return -1;
2102 		}
2103 
2104 		/*
2105 		 * We're not in active mode; let's try to open a new
2106 		 * control connection.
2107 		 */
2108 		memset(&hints, 0, sizeof(struct addrinfo));
2109 		hints.ai_family = PF_UNSPEC;
2110 		hints.ai_socktype = SOCK_STREAM;
2111 
2112 		if (port[0] == 0)
2113 		{
2114 			/* the user chose not to specify the port */
2115 			if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT,
2116 			    &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2117 				return -1;
2118 		}
2119 		else
2120 		{
2121 			if (sock_initaddress(host, port, &hints, &addrinfo,
2122 			    errbuf, PCAP_ERRBUF_SIZE) == -1)
2123 				return -1;
2124 		}
2125 
2126 		if ((*sockctrlp = sock_open(addrinfo, SOCKOPEN_CLIENT, 0,
2127 		    errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
2128 		{
2129 			freeaddrinfo(addrinfo);
2130 			return -1;
2131 		}
2132 
2133 		/* addrinfo is no longer used */
2134 		freeaddrinfo(addrinfo);
2135 		addrinfo = NULL;
2136 
2137 		if (rpcap_doauth(*sockctrlp, protocol_versionp, auth,
2138 		    errbuf) == -1)
2139 		{
2140 			sock_close(*sockctrlp, NULL, 0);
2141 			return -1;
2142 		}
2143 	}
2144 	return 0;
2145 }
2146 
2147 /*
2148  * This function opens a remote adapter by opening an RPCAP connection and
2149  * so on.
2150  *
2151  * It does the job of pcap_open_live() for a remote interface; it's called
2152  * by pcap_open() for remote interfaces.
2153  *
2154  * We do not start the capture until pcap_startcapture_remote() is called.
2155  *
2156  * This is because, when doing a remote capture, we cannot start capturing
2157  * data as soon as the 'open adapter' command is sent. Suppose the remote
2158  * adapter is already overloaded; if we start a capture (which, by default,
2159  * has a NULL filter) the new traffic can saturate the network.
2160  *
2161  * Instead, we want to "open" the adapter, then send a "start capture"
2162  * command only when we're ready to start the capture.
2163  * This function does this job: it sends an "open adapter" command
2164  * (according to the RPCAP protocol), but it does not start the capture.
2165  *
2166  * Since the other libpcap functions do not share this way of life, we
2167  * have to do some dirty things in order to make everything work.
2168  *
2169  * \param source: see pcap_open().
2170  * \param snaplen: see pcap_open().
2171  * \param flags: see pcap_open().
2172  * \param read_timeout: see pcap_open().
2173  * \param auth: see pcap_open().
2174  * \param errbuf: see pcap_open().
2175  *
2176  * \return a pcap_t pointer in case of success, NULL otherwise. In case of
2177  * success, the pcap_t pointer can be used as a parameter to the following
2178  * calls (pcap_compile() and so on). In case of problems, errbuf contains
2179  * a text explanation of error.
2180  *
2181  * WARNING: In case we call pcap_compile() and the capture has not yet
2182  * been started, the filter will be saved into the pcap_t structure,
2183  * and it will be sent to the other host later (when
2184  * pcap_startcapture_remote() is called).
2185  */
2186 pcap_t *pcap_open_rpcap(const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf)
2187 {
2188 	pcap_t *fp;
2189 	char *source_str;
2190 	struct pcap_rpcap *pr;		/* structure used when doing a remote live capture */
2191 	char host[PCAP_BUF_SIZE], ctrlport[PCAP_BUF_SIZE], iface[PCAP_BUF_SIZE];
2192 	SOCKET sockctrl;
2193 	uint8 protocol_version;			/* negotiated protocol version */
2194 	int active;
2195 	uint32 plen;
2196 	char sendbuf[RPCAP_NETBUF_SIZE];	/* temporary buffer in which data to be sent is buffered */
2197 	int sendbufidx = 0;			/* index which keeps the number of bytes currently buffered */
2198 
2199 	/* RPCAP-related variables */
2200 	struct rpcap_header header;		/* header of the RPCAP packet */
2201 	struct rpcap_openreply openreply;	/* open reply message */
2202 
2203 	fp = pcap_create_common(errbuf, sizeof (struct pcap_rpcap));
2204 	if (fp == NULL)
2205 	{
2206 		return NULL;
2207 	}
2208 	source_str = strdup(source);
2209 	if (source_str == NULL) {
2210 		pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2211 		    errno, "malloc");
2212 		return NULL;
2213 	}
2214 
2215 	/*
2216 	 * Turn a negative snapshot value (invalid), a snapshot value of
2217 	 * 0 (unspecified), or a value bigger than the normal maximum
2218 	 * value, into the maximum allowed value.
2219 	 *
2220 	 * If some application really *needs* a bigger snapshot
2221 	 * length, we should just increase MAXIMUM_SNAPLEN.
2222 	 *
2223 	 * XXX - should we leave this up to the remote server to
2224 	 * do?
2225 	 */
2226 	if (snaplen <= 0 || snaplen > MAXIMUM_SNAPLEN)
2227 		snaplen = MAXIMUM_SNAPLEN;
2228 
2229 	fp->opt.device = source_str;
2230 	fp->snapshot = snaplen;
2231 	fp->opt.timeout = read_timeout;
2232 	pr = fp->priv;
2233 	pr->rmt_flags = flags;
2234 
2235 	/*
2236 	 * Attempt to set up the session with the server.
2237 	 */
2238 	if (rpcap_setup_session(fp->opt.device, auth, &active, &sockctrl,
2239 	    &protocol_version, host, ctrlport, iface, errbuf) == -1)
2240 	{
2241 		/* Session setup failed. */
2242 		pcap_close(fp);
2243 		return NULL;
2244 	}
2245 
2246 	/*
2247 	 * Now it's time to start playing with the RPCAP protocol
2248 	 * RPCAP open command: create the request message
2249 	 */
2250 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2251 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
2252 		goto error_nodiscard;
2253 
2254 	rpcap_createhdr((struct rpcap_header *) sendbuf, protocol_version,
2255 	    RPCAP_MSG_OPEN_REQ, 0, (uint32) strlen(iface));
2256 
2257 	if (sock_bufferize(iface, (int) strlen(iface), sendbuf, &sendbufidx,
2258 		RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
2259 		goto error_nodiscard;
2260 
2261 	if (sock_send(sockctrl, sendbuf, sendbufidx, errbuf,
2262 	    PCAP_ERRBUF_SIZE) < 0)
2263 		goto error_nodiscard;
2264 
2265 	/* Receive and process the reply message header. */
2266 	if (rpcap_process_msg_header(sockctrl, protocol_version,
2267 	    RPCAP_MSG_OPEN_REQ, &header, errbuf) == -1)
2268 		goto error_nodiscard;
2269 	plen = header.plen;
2270 
2271 	/* Read the reply body */
2272 	if (rpcap_recv(sockctrl, (char *)&openreply,
2273 	    sizeof(struct rpcap_openreply), &plen, errbuf) == -1)
2274 		goto error;
2275 
2276 	/* Discard the rest of the message, if there is any. */
2277 	if (rpcap_discard(sockctrl, plen, errbuf) == -1)
2278 		goto error_nodiscard;
2279 
2280 	/* Set proper fields into the pcap_t struct */
2281 	fp->linktype = ntohl(openreply.linktype);
2282 	fp->tzoff = ntohl(openreply.tzoff);
2283 	pr->rmt_sockctrl = sockctrl;
2284 	pr->protocol_version = protocol_version;
2285 	pr->rmt_clientside = 1;
2286 
2287 	/* This code is duplicated from the end of this function */
2288 	fp->read_op = pcap_read_rpcap;
2289 	fp->save_current_filter_op = pcap_save_current_filter_rpcap;
2290 	fp->setfilter_op = pcap_setfilter_rpcap;
2291 	fp->getnonblock_op = pcap_getnonblock_rpcap;
2292 	fp->setnonblock_op = pcap_setnonblock_rpcap;
2293 	fp->stats_op = pcap_stats_rpcap;
2294 #ifdef _WIN32
2295 	fp->stats_ex_op = pcap_stats_ex_rpcap;
2296 #endif
2297 	fp->cleanup_op = pcap_cleanup_rpcap;
2298 
2299 	fp->activated = 1;
2300 	return fp;
2301 
2302 error:
2303 	/*
2304 	 * When the connection has been established, we have to close it. So, at the
2305 	 * beginning of this function, if an error occur we return immediately with
2306 	 * a return NULL; when the connection is established, we have to come here
2307 	 * ('goto error;') in order to close everything properly.
2308 	 */
2309 
2310 	/*
2311 	 * Discard the rest of the message.
2312 	 * We already reported an error; if this gets an error, just
2313 	 * drive on.
2314 	 */
2315 	(void)rpcap_discard(sockctrl, plen, NULL);
2316 
2317 error_nodiscard:
2318 	if (!active)
2319 		sock_close(sockctrl, NULL, 0);
2320 
2321 	pcap_close(fp);
2322 	return NULL;
2323 }
2324 
2325 /* String identifier to be used in the pcap_findalldevs_ex() */
2326 #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
2327 #define PCAP_TEXT_SOURCE_ADAPTER_LEN (sizeof PCAP_TEXT_SOURCE_ADAPTER - 1)
2328 /* String identifier to be used in the pcap_findalldevs_ex() */
2329 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST "on remote node"
2330 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST_LEN (sizeof PCAP_TEXT_SOURCE_ON_REMOTE_HOST - 1)
2331 
2332 static void
2333 freeaddr(struct pcap_addr *addr)
2334 {
2335 	free(addr->addr);
2336 	free(addr->netmask);
2337 	free(addr->broadaddr);
2338 	free(addr->dstaddr);
2339 	free(addr);
2340 }
2341 
2342 int
2343 pcap_findalldevs_ex_remote(const char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf)
2344 {
2345 	uint8 protocol_version;		/* protocol version */
2346 	SOCKET sockctrl;		/* socket descriptor of the control connection */
2347 	uint32 plen;
2348 	struct rpcap_header header;	/* structure that keeps the general header of the rpcap protocol */
2349 	int i, j;		/* temp variables */
2350 	int nif;		/* Number of interfaces listed */
2351 	int active;			/* 'true' if we the other end-party is in active mode */
2352 	char host[PCAP_BUF_SIZE], port[PCAP_BUF_SIZE];
2353 	char tmpstring[PCAP_BUF_SIZE + 1];		/* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2354 	pcap_if_t *lastdev;	/* Last device in the pcap_if_t list */
2355 	pcap_if_t *dev;		/* Device we're adding to the pcap_if_t list */
2356 
2357 	/* List starts out empty. */
2358 	(*alldevs) = NULL;
2359 	lastdev = NULL;
2360 
2361 	/*
2362 	 * Attempt to set up the session with the server.
2363 	 */
2364 	if (rpcap_setup_session(source, auth, &active, &sockctrl,
2365 	    &protocol_version, host, port, NULL, errbuf) == -1)
2366 	{
2367 		/* Session setup failed. */
2368 		return -1;
2369 	}
2370 
2371 	/* RPCAP findalldevs command */
2372 	rpcap_createhdr(&header, protocol_version, RPCAP_MSG_FINDALLIF_REQ,
2373 	    0, 0);
2374 
2375 	if (sock_send(sockctrl, (char *)&header, sizeof(struct rpcap_header),
2376 	    errbuf, PCAP_ERRBUF_SIZE) < 0)
2377 		goto error_nodiscard;
2378 
2379 	/* Receive and process the reply message header. */
2380 	if (rpcap_process_msg_header(sockctrl, protocol_version,
2381 	    RPCAP_MSG_FINDALLIF_REQ, &header, errbuf) == -1)
2382 		goto error_nodiscard;
2383 
2384 	plen = header.plen;
2385 
2386 	/* read the number of interfaces */
2387 	nif = ntohs(header.value);
2388 
2389 	/* loop until all interfaces have been received */
2390 	for (i = 0; i < nif; i++)
2391 	{
2392 		struct rpcap_findalldevs_if findalldevs_if;
2393 		char tmpstring2[PCAP_BUF_SIZE + 1];		/* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2394 		struct pcap_addr *addr, *prevaddr;
2395 
2396 		tmpstring2[PCAP_BUF_SIZE] = 0;
2397 
2398 		/* receive the findalldevs structure from remote host */
2399 		if (rpcap_recv(sockctrl, (char *)&findalldevs_if,
2400 		    sizeof(struct rpcap_findalldevs_if), &plen, errbuf) == -1)
2401 			goto error;
2402 
2403 		findalldevs_if.namelen = ntohs(findalldevs_if.namelen);
2404 		findalldevs_if.desclen = ntohs(findalldevs_if.desclen);
2405 		findalldevs_if.naddr = ntohs(findalldevs_if.naddr);
2406 
2407 		/* allocate the main structure */
2408 		dev = (pcap_if_t *)malloc(sizeof(pcap_if_t));
2409 		if (dev == NULL)
2410 		{
2411 			pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2412 			    errno, "malloc() failed");
2413 			goto error;
2414 		}
2415 
2416 		/* Initialize the structure to 'zero' */
2417 		memset(dev, 0, sizeof(pcap_if_t));
2418 
2419 		/* Append it to the list. */
2420 		if (lastdev == NULL)
2421 		{
2422 			/*
2423 			 * List is empty, so it's also the first device.
2424 			 */
2425 			*alldevs = dev;
2426 		}
2427 		else
2428 		{
2429 			/*
2430 			 * Append after the last device.
2431 			 */
2432 			lastdev->next = dev;
2433 		}
2434 		/* It's now the last device. */
2435 		lastdev = dev;
2436 
2437 		/* allocate mem for name and description */
2438 		if (findalldevs_if.namelen)
2439 		{
2440 
2441 			if (findalldevs_if.namelen >= sizeof(tmpstring))
2442 			{
2443 				pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface name too long");
2444 				goto error;
2445 			}
2446 
2447 			/* Retrieve adapter name */
2448 			if (rpcap_recv(sockctrl, tmpstring,
2449 			    findalldevs_if.namelen, &plen, errbuf) == -1)
2450 				goto error;
2451 
2452 			tmpstring[findalldevs_if.namelen] = 0;
2453 
2454 			/* Create the new device identifier */
2455 			if (pcap_createsrcstr(tmpstring2, PCAP_SRC_IFREMOTE,
2456 			    host, port, tmpstring, errbuf) == -1)
2457 				goto error;
2458 
2459 			dev->name = strdup(tmpstring2);
2460 			if (dev->name == NULL)
2461 			{
2462 				pcap_fmt_errmsg_for_errno(errbuf,
2463 				    PCAP_ERRBUF_SIZE, errno, "malloc() failed");
2464 				goto error;
2465 			}
2466 		}
2467 
2468 		if (findalldevs_if.desclen)
2469 		{
2470 			if (findalldevs_if.desclen >= sizeof(tmpstring))
2471 			{
2472 				pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface description too long");
2473 				goto error;
2474 			}
2475 
2476 			/* Retrieve adapter description */
2477 			if (rpcap_recv(sockctrl, tmpstring,
2478 			    findalldevs_if.desclen, &plen, errbuf) == -1)
2479 				goto error;
2480 
2481 			tmpstring[findalldevs_if.desclen] = 0;
2482 
2483 			if (pcap_asprintf(&dev->description,
2484 			    "%s '%s' %s %s", PCAP_TEXT_SOURCE_ADAPTER,
2485 			    tmpstring, PCAP_TEXT_SOURCE_ON_REMOTE_HOST, host) == -1)
2486 			{
2487 				pcap_fmt_errmsg_for_errno(errbuf,
2488 				    PCAP_ERRBUF_SIZE, errno, "malloc() failed");
2489 				goto error;
2490 			}
2491 		}
2492 
2493 		dev->flags = ntohl(findalldevs_if.flags);
2494 
2495 		prevaddr = NULL;
2496 		/* loop until all addresses have been received */
2497 		for (j = 0; j < findalldevs_if.naddr; j++)
2498 		{
2499 			struct rpcap_findalldevs_ifaddr ifaddr;
2500 
2501 			/* Retrieve the interface addresses */
2502 			if (rpcap_recv(sockctrl, (char *)&ifaddr,
2503 			    sizeof(struct rpcap_findalldevs_ifaddr),
2504 			    &plen, errbuf) == -1)
2505 				goto error;
2506 
2507 			/*
2508 			 * Deserialize all the address components.
2509 			 */
2510 			addr = (struct pcap_addr *) malloc(sizeof(struct pcap_addr));
2511 			if (addr == NULL)
2512 			{
2513 				pcap_fmt_errmsg_for_errno(errbuf,
2514 				    PCAP_ERRBUF_SIZE, errno, "malloc() failed");
2515 				goto error;
2516 			}
2517 			addr->next = NULL;
2518 			addr->addr = NULL;
2519 			addr->netmask = NULL;
2520 			addr->broadaddr = NULL;
2521 			addr->dstaddr = NULL;
2522 
2523 			if (rpcap_deseraddr(&ifaddr.addr,
2524 				(struct sockaddr_storage **) &addr->addr, errbuf) == -1)
2525 			{
2526 				freeaddr(addr);
2527 				goto error;
2528 			}
2529 			if (rpcap_deseraddr(&ifaddr.netmask,
2530 				(struct sockaddr_storage **) &addr->netmask, errbuf) == -1)
2531 			{
2532 				freeaddr(addr);
2533 				goto error;
2534 			}
2535 			if (rpcap_deseraddr(&ifaddr.broadaddr,
2536 				(struct sockaddr_storage **) &addr->broadaddr, errbuf) == -1)
2537 			{
2538 				freeaddr(addr);
2539 				goto error;
2540 			}
2541 			if (rpcap_deseraddr(&ifaddr.dstaddr,
2542 				(struct sockaddr_storage **) &addr->dstaddr, errbuf) == -1)
2543 			{
2544 				freeaddr(addr);
2545 				goto error;
2546 			}
2547 
2548 			if ((addr->addr == NULL) && (addr->netmask == NULL) &&
2549 				(addr->broadaddr == NULL) && (addr->dstaddr == NULL))
2550 			{
2551 				/*
2552 				 * None of the addresses are IPv4 or IPv6
2553 				 * addresses, so throw this entry away.
2554 				 */
2555 				free(addr);
2556 			}
2557 			else
2558 			{
2559 				/*
2560 				 * Add this entry to the list.
2561 				 */
2562 				if (prevaddr == NULL)
2563 				{
2564 					dev->addresses = addr;
2565 				}
2566 				else
2567 				{
2568 					prevaddr->next = addr;
2569 				}
2570 				prevaddr = addr;
2571 			}
2572 		}
2573 	}
2574 
2575 	/* Discard the rest of the message. */
2576 	if (rpcap_discard(sockctrl, plen, errbuf) == 1)
2577 		goto error_nodiscard;
2578 
2579 	/* Control connection has to be closed only in case the remote machine is in passive mode */
2580 	if (!active)
2581 	{
2582 		/* DO not send RPCAP_CLOSE, since we did not open a pcap_t; no need to free resources */
2583 		if (sock_close(sockctrl, errbuf, PCAP_ERRBUF_SIZE))
2584 			return -1;
2585 	}
2586 
2587 	/* To avoid inconsistencies in the number of sock_init() */
2588 	sock_cleanup();
2589 
2590 	return 0;
2591 
2592 error:
2593 	/*
2594 	 * In case there has been an error, I don't want to overwrite it with a new one
2595 	 * if the following call fails. I want to return always the original error.
2596 	 *
2597 	 * Take care: this connection can already be closed when we try to close it.
2598 	 * This happens because a previous error in the rpcapd, which requested to
2599 	 * closed the connection. In that case, we already recognized that into the
2600 	 * rpspck_isheaderok() and we already acknowledged the closing.
2601 	 * In that sense, this call is useless here (however it is needed in case
2602 	 * the client generates the error).
2603 	 *
2604 	 * Checks if all the data has been read; if not, discard the data in excess
2605 	 */
2606 	(void) rpcap_discard(sockctrl, plen, NULL);
2607 
2608 error_nodiscard:
2609 	/* Control connection has to be closed only in case the remote machine is in passive mode */
2610 	if (!active)
2611 		sock_close(sockctrl, NULL, 0);
2612 
2613 	/* To avoid inconsistencies in the number of sock_init() */
2614 	sock_cleanup();
2615 
2616 	/* Free whatever interfaces we've allocated. */
2617 	pcap_freealldevs(*alldevs);
2618 
2619 	return -1;
2620 }
2621 
2622 /*
2623  * Active mode routines.
2624  *
2625  * The old libpcap API is somewhat ugly, and makes active mode difficult
2626  * to implement; we provide some APIs for it that work only with rpcap.
2627  */
2628 
2629 SOCKET pcap_remoteact_accept(const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf)
2630 {
2631 	/* socket-related variables */
2632 	struct addrinfo hints;			/* temporary struct to keep settings needed to open the new socket */
2633 	struct addrinfo *addrinfo;		/* keeps the addrinfo chain; required to open a new socket */
2634 	struct sockaddr_storage from;	/* generic sockaddr_storage variable */
2635 	socklen_t fromlen;				/* keeps the length of the sockaddr_storage variable */
2636 	SOCKET sockctrl;				/* keeps the main socket identifier */
2637 	uint8 protocol_version;			/* negotiated protocol version */
2638 	struct activehosts *temp, *prev;	/* temp var needed to scan he host list chain */
2639 
2640 	*connectinghost = 0;		/* just in case */
2641 
2642 	/* Prepare to open a new server socket */
2643 	memset(&hints, 0, sizeof(struct addrinfo));
2644 	/* WARNING Currently it supports only ONE socket family among ipv4 and IPv6  */
2645 	hints.ai_family = AF_INET;		/* PF_UNSPEC to have both IPv4 and IPv6 server */
2646 	hints.ai_flags = AI_PASSIVE;	/* Ready to a bind() socket */
2647 	hints.ai_socktype = SOCK_STREAM;
2648 
2649 	/* Warning: this call can be the first one called by the user. */
2650 	/* For this reason, we have to initialize the WinSock support. */
2651 	if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
2652 		return (SOCKET)-1;
2653 
2654 	/* Do the work */
2655 	if ((port == NULL) || (port[0] == 0))
2656 	{
2657 		if (sock_initaddress(address, RPCAP_DEFAULT_NETPORT_ACTIVE, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2658 		{
2659 			return (SOCKET)-2;
2660 		}
2661 	}
2662 	else
2663 	{
2664 		if (sock_initaddress(address, port, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2665 		{
2666 			return (SOCKET)-2;
2667 		}
2668 	}
2669 
2670 
2671 	if ((sockmain = sock_open(addrinfo, SOCKOPEN_SERVER, 1, errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
2672 	{
2673 		freeaddrinfo(addrinfo);
2674 		return (SOCKET)-2;
2675 	}
2676 	freeaddrinfo(addrinfo);
2677 
2678 	/* Connection creation */
2679 	fromlen = sizeof(struct sockaddr_storage);
2680 
2681 	sockctrl = accept(sockmain, (struct sockaddr *) &from, &fromlen);
2682 
2683 	/* We're not using sock_close, since we do not want to send a shutdown */
2684 	/* (which is not allowed on a non-connected socket) */
2685 	closesocket(sockmain);
2686 	sockmain = 0;
2687 
2688 	if (sockctrl == INVALID_SOCKET)
2689 	{
2690 		sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE);
2691 		return (SOCKET)-2;
2692 	}
2693 
2694 	/* Get the numeric for of the name of the connecting host */
2695 	if (getnameinfo((struct sockaddr *) &from, fromlen, connectinghost, RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST))
2696 	{
2697 		sock_geterror("getnameinfo()", errbuf, PCAP_ERRBUF_SIZE);
2698 		rpcap_senderror(sockctrl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2699 		sock_close(sockctrl, NULL, 0);
2700 		return (SOCKET)-1;
2701 	}
2702 
2703 	/* checks if the connecting host is among the ones allowed */
2704 	if (sock_check_hostlist((char *)hostlist, RPCAP_HOSTLIST_SEP, &from, errbuf, PCAP_ERRBUF_SIZE) < 0)
2705 	{
2706 		rpcap_senderror(sockctrl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2707 		sock_close(sockctrl, NULL, 0);
2708 		return (SOCKET)-1;
2709 	}
2710 
2711 	/*
2712 	 * Send authentication to the remote machine.
2713 	 */
2714 	if (rpcap_doauth(sockctrl, &protocol_version, auth, errbuf) == -1)
2715 	{
2716 		/* Unrecoverable error. */
2717 		rpcap_senderror(sockctrl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2718 		sock_close(sockctrl, NULL, 0);
2719 		return (SOCKET)-3;
2720 	}
2721 
2722 	/* Checks that this host does not already have a cntrl connection in place */
2723 
2724 	/* Initialize pointers */
2725 	temp = activeHosts;
2726 	prev = NULL;
2727 
2728 	while (temp)
2729 	{
2730 		/* This host already has an active connection in place, so I don't have to update the host list */
2731 		if (sock_cmpaddr(&temp->host, &from) == 0)
2732 			return sockctrl;
2733 
2734 		prev = temp;
2735 		temp = temp->next;
2736 	}
2737 
2738 	/* The host does not exist in the list; so I have to update the list */
2739 	if (prev)
2740 	{
2741 		prev->next = (struct activehosts *) malloc(sizeof(struct activehosts));
2742 		temp = prev->next;
2743 	}
2744 	else
2745 	{
2746 		activeHosts = (struct activehosts *) malloc(sizeof(struct activehosts));
2747 		temp = activeHosts;
2748 	}
2749 
2750 	if (temp == NULL)
2751 	{
2752 		pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2753 		    errno, "malloc() failed");
2754 		rpcap_senderror(sockctrl, protocol_version, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
2755 		sock_close(sockctrl, NULL, 0);
2756 		return (SOCKET)-1;
2757 	}
2758 
2759 	memcpy(&temp->host, &from, fromlen);
2760 	temp->sockctrl = sockctrl;
2761 	temp->protocol_version = protocol_version;
2762 	temp->next = NULL;
2763 
2764 	return sockctrl;
2765 }
2766 
2767 int pcap_remoteact_close(const char *host, char *errbuf)
2768 {
2769 	struct activehosts *temp, *prev;	/* temp var needed to scan the host list chain */
2770 	struct addrinfo hints, *addrinfo, *ai_next;	/* temp var needed to translate between hostname to its address */
2771 	int retval;
2772 
2773 	temp = activeHosts;
2774 	prev = NULL;
2775 
2776 	/* retrieve the network address corresponding to 'host' */
2777 	addrinfo = NULL;
2778 	memset(&hints, 0, sizeof(struct addrinfo));
2779 	hints.ai_family = PF_UNSPEC;
2780 	hints.ai_socktype = SOCK_STREAM;
2781 
2782 	retval = getaddrinfo(host, "0", &hints, &addrinfo);
2783 	if (retval != 0)
2784 	{
2785 		pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "getaddrinfo() %s", gai_strerror(retval));
2786 		return -1;
2787 	}
2788 
2789 	while (temp)
2790 	{
2791 		ai_next = addrinfo;
2792 		while (ai_next)
2793 		{
2794 			if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
2795 			{
2796 				struct rpcap_header header;
2797 				int status = 0;
2798 
2799 				/* Close this connection */
2800 				rpcap_createhdr(&header, temp->protocol_version,
2801 				    RPCAP_MSG_CLOSE, 0, 0);
2802 
2803 				/*
2804 				 * Don't check for errors, since we're
2805 				 * just cleaning up.
2806 				 */
2807 				if (sock_send(temp->sockctrl,
2808 				    (char *)&header,
2809 				    sizeof(struct rpcap_header), errbuf,
2810 				    PCAP_ERRBUF_SIZE) < 0)
2811 				{
2812 					/*
2813 					 * Let that error be the one we
2814 					 * report.
2815 					 */
2816 					(void)sock_close(temp->sockctrl, NULL,
2817 					   0);
2818 					status = -1;
2819 				}
2820 				else
2821 				{
2822 					if (sock_close(temp->sockctrl, errbuf,
2823 					   PCAP_ERRBUF_SIZE) == -1)
2824 						status = -1;
2825 				}
2826 
2827 				/*
2828 				 * Remove the host from the list of active
2829 				 * hosts.
2830 				 */
2831 				if (prev)
2832 					prev->next = temp->next;
2833 				else
2834 					activeHosts = temp->next;
2835 
2836 				freeaddrinfo(addrinfo);
2837 
2838 				free(temp);
2839 
2840 				/* To avoid inconsistencies in the number of sock_init() */
2841 				sock_cleanup();
2842 
2843 				return status;
2844 			}
2845 
2846 			ai_next = ai_next->ai_next;
2847 		}
2848 		prev = temp;
2849 		temp = temp->next;
2850 	}
2851 
2852 	if (addrinfo)
2853 		freeaddrinfo(addrinfo);
2854 
2855 	/* To avoid inconsistencies in the number of sock_init() */
2856 	sock_cleanup();
2857 
2858 	pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The host you want to close the active connection is not known");
2859 	return -1;
2860 }
2861 
2862 void pcap_remoteact_cleanup(void)
2863 {
2864 	/* Very dirty, but it works */
2865 	if (sockmain)
2866 	{
2867 		closesocket(sockmain);
2868 
2869 		/* To avoid inconsistencies in the number of sock_init() */
2870 		sock_cleanup();
2871 	}
2872 
2873 }
2874 
2875 int pcap_remoteact_list(char *hostlist, char sep, int size, char *errbuf)
2876 {
2877 	struct activehosts *temp;	/* temp var needed to scan the host list chain */
2878 	size_t len;
2879 	char hoststr[RPCAP_HOSTLIST_SIZE + 1];
2880 
2881 	temp = activeHosts;
2882 
2883 	len = 0;
2884 	*hostlist = 0;
2885 
2886 	while (temp)
2887 	{
2888 		/*int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen) */
2889 
2890 		/* Get the numeric form of the name of the connecting host */
2891 		if (sock_getascii_addrport((struct sockaddr_storage *) &temp->host, hoststr,
2892 			RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST, errbuf, PCAP_ERRBUF_SIZE) != -1)
2893 			/*	if (getnameinfo( (struct sockaddr *) &temp->host, sizeof (struct sockaddr_storage), hoststr, */
2894 			/*		RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST) ) */
2895 		{
2896 			/*	sock_geterror("getnameinfo()", errbuf, PCAP_ERRBUF_SIZE); */
2897 			return -1;
2898 		}
2899 
2900 		len = len + strlen(hoststr) + 1 /* the separator */;
2901 
2902 		if ((size < 0) || (len >= (size_t)size))
2903 		{
2904 			pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The string you provided is not able to keep "
2905 				"the hostnames for all the active connections");
2906 			return -1;
2907 		}
2908 
2909 		pcap_strlcat(hostlist, hoststr, PCAP_ERRBUF_SIZE);
2910 		hostlist[len - 1] = sep;
2911 		hostlist[len] = 0;
2912 
2913 		temp = temp->next;
2914 	}
2915 
2916 	return 0;
2917 }
2918 
2919 /*
2920  * Receive the header of a message.
2921  */
2922 static int rpcap_recv_msg_header(SOCKET sock, struct rpcap_header *header, char *errbuf)
2923 {
2924 	int nrecv;
2925 
2926 	nrecv = sock_recv(sock, (char *) header, sizeof(struct rpcap_header),
2927 	    SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
2928 	    PCAP_ERRBUF_SIZE);
2929 	if (nrecv == -1)
2930 	{
2931 		/* Network error. */
2932 		return -1;
2933 	}
2934 	header->plen = ntohl(header->plen);
2935 	return 0;
2936 }
2937 
2938 /*
2939  * Make sure the protocol version of a received message is what we were
2940  * expecting.
2941  */
2942 static int rpcap_check_msg_ver(SOCKET sock, uint8 expected_ver, struct rpcap_header *header, char *errbuf)
2943 {
2944 	/*
2945 	 * Did the server specify the version we negotiated?
2946 	 */
2947 	if (header->ver != expected_ver)
2948 	{
2949 		/*
2950 		 * Discard the rest of the message.
2951 		 */
2952 		if (rpcap_discard(sock, header->plen, errbuf) == -1)
2953 			return -1;
2954 
2955 		/*
2956 		 * Tell our caller that it's not the negotiated version.
2957 		 */
2958 		if (errbuf != NULL)
2959 		{
2960 			pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
2961 			    "Server sent us a message with version %u when we were expecting %u",
2962 			    header->ver, expected_ver);
2963 		}
2964 		return -1;
2965 	}
2966 	return 0;
2967 }
2968 
2969 /*
2970  * Check the message type of a received message, which should either be
2971  * the expected message type or RPCAP_MSG_ERROR.
2972  */
2973 static int rpcap_check_msg_type(SOCKET sock, uint8 request_type, struct rpcap_header *header, uint16 *errcode, char *errbuf)
2974 {
2975 	const char *request_type_string;
2976 	const char *msg_type_string;
2977 
2978 	/*
2979 	 * What type of message is it?
2980 	 */
2981 	if (header->type == RPCAP_MSG_ERROR)
2982 	{
2983 		/*
2984 		 * The server reported an error.
2985 		 * Hand that error back to our caller.
2986 		 */
2987 		*errcode = ntohs(header->value);
2988 		rpcap_msg_err(sock, header->plen, errbuf);
2989 		return -1;
2990 	}
2991 
2992 	*errcode = 0;
2993 
2994 	/*
2995 	 * For a given request type value, the expected reply type value
2996 	 * is the request type value with ORed with RPCAP_MSG_IS_REPLY.
2997 	 */
2998 	if (header->type != (request_type | RPCAP_MSG_IS_REPLY))
2999 	{
3000 		/*
3001 		 * This isn't a reply to the request we sent.
3002 		 */
3003 
3004 		/*
3005 		 * Discard the rest of the message.
3006 		 */
3007 		if (rpcap_discard(sock, header->plen, errbuf) == -1)
3008 			return -1;
3009 
3010 		/*
3011 		 * Tell our caller about it.
3012 		 */
3013 		request_type_string = rpcap_msg_type_string(request_type);
3014 		msg_type_string = rpcap_msg_type_string(header->type);
3015 		if (errbuf != NULL)
3016 		{
3017 			if (request_type_string == NULL)
3018 			{
3019 				/* This should not happen. */
3020 				pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
3021 				    "rpcap_check_msg_type called for request message with type %u",
3022 				    request_type);
3023 				return -1;
3024 			}
3025 			if (msg_type_string != NULL)
3026 				pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
3027 				    "%s message received in response to a %s message",
3028 				    msg_type_string, request_type_string);
3029 			else
3030 				pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
3031 				    "Message of unknown type %u message received in response to a %s request",
3032 				    header->type, request_type_string);
3033 		}
3034 		return -1;
3035 	}
3036 
3037 	return 0;
3038 }
3039 
3040 /*
3041  * Receive and process the header of a message.
3042  */
3043 static int rpcap_process_msg_header(SOCKET sock, uint8 expected_ver, uint8 request_type, struct rpcap_header *header, char *errbuf)
3044 {
3045 	uint16 errcode;
3046 
3047 	if (rpcap_recv_msg_header(sock, header, errbuf) == -1)
3048 	{
3049 		/* Network error. */
3050 		return -1;
3051 	}
3052 
3053 	/*
3054 	 * Did the server specify the version we negotiated?
3055 	 */
3056 	if (rpcap_check_msg_ver(sock, expected_ver, header, errbuf) == -1)
3057 		return -1;
3058 
3059 	/*
3060 	 * Check the message type.
3061 	 */
3062 	return rpcap_check_msg_type(sock, request_type, header,
3063 	    &errcode, errbuf);
3064 }
3065 
3066 /*
3067  * Read data from a message.
3068  * If we're trying to read more data that remains, puts an error
3069  * message into errmsgbuf and returns -2.  Otherwise, tries to read
3070  * the data and, if that succeeds, subtracts the amount read from
3071  * the number of bytes of data that remains.
3072  * Returns 0 on success, logs a message and returns -1 on a network
3073  * error.
3074  */
3075 static int rpcap_recv(SOCKET sock, void *buffer, size_t toread, uint32 *plen, char *errbuf)
3076 {
3077 	int nread;
3078 
3079 	if (toread > *plen)
3080 	{
3081 		/* The server sent us a bad message */
3082 		pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
3083 		return -1;
3084 	}
3085 	nread = sock_recv(sock, buffer, toread,
3086 	    SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
3087 	if (nread == -1)
3088 	{
3089 		return -1;
3090 	}
3091 	*plen -= nread;
3092 	return 0;
3093 }
3094 
3095 /*
3096  * This handles the RPCAP_MSG_ERROR message.
3097  */
3098 static void rpcap_msg_err(SOCKET sockctrl, uint32 plen, char *remote_errbuf)
3099 {
3100 	char errbuf[PCAP_ERRBUF_SIZE];
3101 
3102 	if (plen >= PCAP_ERRBUF_SIZE)
3103 	{
3104 		/*
3105 		 * Message is too long; just read as much of it as we
3106 		 * can into the buffer provided, and discard the rest.
3107 		 */
3108 		if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
3109 		    SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
3110 		    PCAP_ERRBUF_SIZE) == -1)
3111 		{
3112 			// Network error.
3113 			pcap_snprintf(remote_errbuf, PCAP_ERRBUF_SIZE, "Read of error message from client failed: %s", errbuf);
3114 			return;
3115 		}
3116 
3117 		/*
3118 		 * Null-terminate it.
3119 		 */
3120 		remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
3121 
3122 		/*
3123 		 * Throw away the rest.
3124 		 */
3125 		(void)rpcap_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1), remote_errbuf);
3126 	}
3127 	else if (plen == 0)
3128 	{
3129 		/* Empty error string. */
3130 		remote_errbuf[0] = '\0';
3131 	}
3132 	else
3133 	{
3134 		if (sock_recv(sockctrl, remote_errbuf, plen,
3135 		    SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
3136 		    PCAP_ERRBUF_SIZE) == -1)
3137 		{
3138 			// Network error.
3139 			pcap_snprintf(remote_errbuf, PCAP_ERRBUF_SIZE, "Read of error message from client failed: %s", errbuf);
3140 			return;
3141 		}
3142 
3143 		/*
3144 		 * Null-terminate it.
3145 		 */
3146 		remote_errbuf[plen] = '\0';
3147 	}
3148 }
3149 
3150 /*
3151  * Discard data from a connection.
3152  * Mostly used to discard wrong-sized messages.
3153  * Returns 0 on success, logs a message and returns -1 on a network
3154  * error.
3155  */
3156 static int rpcap_discard(SOCKET sock, uint32 len, char *errbuf)
3157 {
3158 	if (len != 0)
3159 	{
3160 		if (sock_discard(sock, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
3161 		{
3162 			// Network error.
3163 			return -1;
3164 		}
3165 	}
3166 	return 0;
3167 }
3168 
3169 /*
3170  * Read bytes into the pcap_t's buffer until we have the specified
3171  * number of bytes read or we get an error or interrupt indication.
3172  */
3173 static int rpcap_read_packet_msg(SOCKET sock, pcap_t *p, size_t size)
3174 {
3175 	u_char *bp;
3176 	int cc;
3177 	int bytes_read;
3178 
3179 	bp = p->bp;
3180 	cc = p->cc;
3181 
3182 	/*
3183 	 * Loop until we have the amount of data requested or we get
3184 	 * an error or interrupt.
3185 	 */
3186 	while ((size_t)cc < size)
3187 	{
3188 		/*
3189 		 * We haven't read all of the packet header yet.
3190 		 * Read what remains, which could be all of it.
3191 		 */
3192 		bytes_read = sock_recv(sock, bp, size - cc,
3193 		    SOCK_RECEIVEALL_NO|SOCK_EOF_IS_ERROR, p->errbuf,
3194 		    PCAP_ERRBUF_SIZE);
3195 		if (bytes_read == -1)
3196 		{
3197 			/*
3198 			 * Network error.  Update the read pointer and
3199 			 * byte count, and return an error indication.
3200 			 */
3201 			p->bp = bp;
3202 			p->cc = cc;
3203 			return -1;
3204 		}
3205 		if (bytes_read == -3)
3206 		{
3207 			/*
3208 			 * Interrupted receive.  Update the read
3209 			 * pointer and byte count, and return
3210 			 * an interrupted indication.
3211 			 */
3212 			p->bp = bp;
3213 			p->cc = cc;
3214 			return -3;
3215 		}
3216 		if (bytes_read == 0)
3217 		{
3218 			/*
3219 			 * EOF - server terminated the connection.
3220 			 * Update the read pointer and byte count, and
3221 			 * return an error indication.
3222 			 */
3223 			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
3224 			    "The server terminated the connection.");
3225 			return -1;
3226 		}
3227 		bp += bytes_read;
3228 		cc += bytes_read;
3229 	}
3230 	p->bp = bp;
3231 	p->cc = cc;
3232 	return 0;
3233 }
3234