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