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