• 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 <string.h>		/* for strlen(), ... */
39 #include <stdlib.h>		/* for malloc(), free(), ... */
40 #include <stdarg.h>		/* for functions with variable number of arguments */
41 #include <errno.h>		/* for the errno variable */
42 #include "pcap-int.h"
43 #include "pcap-rpcap.h"
44 #include "sockutils.h"
45 
46 /*
47  * \file pcap-rpcap.c
48  *
49  * This file keeps all the new funtions that are needed for the RPCAP protocol.
50  * Almost all the pcap functions need to be modified in order to become compatible
51  * with the RPCAP protocol. However, you can find here only the ones that are completely new.
52  *
53  * This file keeps also the functions that are 'private', i.e. are needed by the RPCAP
54  * protocol but are not exported to the user.
55  *
56  * \warning All the RPCAP functions that are allowed to return a buffer containing
57  * the error description can return max PCAP_ERRBUF_SIZE characters.
58  * However there is no guarantees that the string will be zero-terminated.
59  * Best practice is to define the errbuf variable as a char of size 'PCAP_ERRBUF_SIZE+1'
60  * and to insert manually a NULL character at the end of the buffer. This will
61  * guarantee that no buffer overflows occur even if we use the printf() to show
62  * the error on the screen.
63  */
64 
65 #define PCAP_STATS_STANDARD	0	/* Used by pcap_stats_remote to see if we want standard or extended statistics */
66 #define PCAP_STATS_EX		1	/* Used by pcap_stats_remote to see if we want standard or extended statistics */
67 
68 /* Keeps a list of all the opened connections in the active mode. */
69 struct activehosts *activeHosts;
70 
71 /*
72  * Private data for capturing on WinPcap devices.
73  */
74 struct pcap_win {
75 	int nonblock;
76 	int rfmon_selfstart;		/* a flag tells whether the monitor mode is set by itself */
77 	int filtering_in_kernel;	/* using kernel filter */
78 
79 #ifdef HAVE_DAG_API
80 	int	dag_fcs_bits;		/* Number of checksum bits from link layer */
81 #endif
82 };
83 
84 /****************************************************
85  *                                                  *
86  * Locally defined functions                        *
87  *                                                  *
88  ****************************************************/
89 static int rpcap_checkver(SOCKET sock, struct rpcap_header *header, char *errbuf);
90 static struct pcap_stat *rpcap_stats_remote(pcap_t *p, struct pcap_stat *ps, int mode);
91 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog);
92 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog);
93 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog);
94 static int pcap_setfilter_remote(pcap_t *fp, struct bpf_program *prog);
95 static int pcap_setsampling_remote(pcap_t *p);
96 
97 
98 /****************************************************
99  *                                                  *
100  * Function bodies                                  *
101  *                                                  *
102  ****************************************************/
103 
104 /*
105  * \ingroup remote_pri_func
106  *
107  * \brief 	It traslates (i.e. de-serializes) a 'sockaddr_storage' structure from
108  * the network byte order to the host byte order.
109  *
110  * It accepts a 'sockaddr_storage' structure as it is received from the network and it
111  * converts it into the host byte order (by means of a set of ntoh() ).
112  * The function will allocate the 'sockaddrout' variable according to the address family
113  * in use. In case the address does not belong to the AF_INET nor AF_INET6 families,
114  * 'sockaddrout' is not allocated and a NULL pointer is returned.
115  * This usually happens because that address does not exist on the other host, so the
116  * RPCAP daemon sent a 'sockaddr_storage' structure containing all 'zero' values.
117  *
118  * \param sockaddrin: a 'sockaddr_storage' pointer to the variable that has to be
119  * de-serialized.
120  *
121  * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
122  * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
123  * This variable will be allocated automatically inside this function.
124  *
125  * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
126  * that will contain the error message (in case there is one).
127  *
128  * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
129  * can be only the fact that the malloc() failed to allocate memory.
130  * The error message is returned in the 'errbuf' variable, while the deserialized address
131  * is returned into the 'sockaddrout' variable.
132  *
133  * \warning This function supports only AF_INET and AF_INET6 address families.
134  *
135  * \warning The sockaddrout (if not NULL) must be deallocated by the user.
136  */
rpcap_deseraddr(struct sockaddr_storage * sockaddrin,struct sockaddr_storage ** sockaddrout,char * errbuf)137 int rpcap_deseraddr(struct sockaddr_storage *sockaddrin, struct sockaddr_storage **sockaddrout, char *errbuf)
138 {
139 	/* Warning: we support only AF_INET and AF_INET6 */
140 	if (ntohs(sockaddrin->ss_family) == AF_INET)
141 	{
142 		struct sockaddr_in *sockaddr;
143 
144 		sockaddr = (struct sockaddr_in *) sockaddrin;
145 		sockaddr->sin_family = ntohs(sockaddr->sin_family);
146 		sockaddr->sin_port = ntohs(sockaddr->sin_port);
147 
148 		(*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in));
149 		if ((*sockaddrout) == NULL)
150 		{
151 			pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
152 			return -1;
153 		}
154 		memcpy(*sockaddrout, sockaddr, sizeof(struct sockaddr_in));
155 		return 0;
156 	}
157 	if (ntohs(sockaddrin->ss_family) == AF_INET6)
158 	{
159 		struct sockaddr_in6 *sockaddr;
160 
161 		sockaddr = (struct sockaddr_in6 *) sockaddrin;
162 		sockaddr->sin6_family = ntohs(sockaddr->sin6_family);
163 		sockaddr->sin6_port = ntohs(sockaddr->sin6_port);
164 		sockaddr->sin6_flowinfo = ntohl(sockaddr->sin6_flowinfo);
165 		sockaddr->sin6_scope_id = ntohl(sockaddr->sin6_scope_id);
166 
167 		(*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in6));
168 		if ((*sockaddrout) == NULL)
169 		{
170 			pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
171 			return -1;
172 		}
173 		memcpy(*sockaddrout, sockaddr, sizeof(struct sockaddr_in6));
174 		return 0;
175 	}
176 
177 	/* It is neither AF_INET nor AF_INET6 */
178 	*sockaddrout = NULL;
179 	return 0;
180 }
181 
182 /* \ingroup remote_pri_func
183  *
184  * \brief It reads a packet from the network socket. This does not make use of
185  * callback (hence the "nocb" string into its name).
186  *
187  * This function is called by the several pcap_next_ex() when they detect that
188  * we have a remote capture and they are the client side. In that case, they need
189  * to read packets from the socket.
190  *
191  * Parameters and return values are exactly the same of the pcap_next_ex().
192  *
193  * \warning By choice, this function does not make use of semaphores. A smarter
194  * implementation should put a semaphore into the data thread, and a signal will
195  * be raised as soon as there is data into the socket buffer.
196  * However this is complicated and it does not bring any advantages when reading
197  * from the network, in which network delays can be much more important than
198  * these optimizations. Therefore, we chose the following approach:
199  * - the 'timeout' chosen by the user is split in two (half on the server side,
200  * with the usual meaning, and half on the client side)
201  * - this function checks for packets; if there are no packets, it waits for
202  * timeout/2 and then it checks again. If packets are still missing, it returns,
203  * otherwise it reads packets.
204  */
pcap_read_nocb_remote(pcap_t * p,struct pcap_pkthdr ** pkt_header,u_char ** pkt_data)205 static int pcap_read_nocb_remote(pcap_t *p, struct pcap_pkthdr **pkt_header, u_char **pkt_data)
206 {
207 	struct rpcap_header *header;		/* general header according to the RPCAP format */
208 	struct rpcap_pkthdr *net_pkt_header;	/* header of the packet */
209 	char netbuf[RPCAP_NETBUF_SIZE];		/* size of the network buffer in which the packet is copied, just for UDP */
210 	uint32 totread;				/* number of bytes (of payload) currently read from the network (referred to the current pkt) */
211 	int nread;
212 	int retval;				/* generic return value */
213 
214 	/* Structures needed for the select() call */
215 	fd_set rfds;				/* set of socket descriptors we have to check */
216 	struct timeval tv;			/* maximum time the select() can block waiting for data */
217 	struct pcap_md *md;			/* structure used when doing a remote live capture */
218 
219 	md = (struct pcap_md *) ((u_char*)p->priv + sizeof(struct pcap_win));
220 
221 	/*
222 	 * Define the read timeout, to be used in the select()
223 	 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
224 	 */
225 	tv.tv_sec = p->opt.timeout / 1000;
226 	tv.tv_usec = (p->opt.timeout - tv.tv_sec * 1000) * 1000;
227 
228 	/* Watch out sockdata to see if it has input */
229 	FD_ZERO(&rfds);
230 
231 	/*
232 	 * 'fp->rmt_sockdata' has always to be set before calling the select(),
233 	 * since it is cleared by the select()
234 	 */
235 	FD_SET(md->rmt_sockdata, &rfds);
236 
237 	retval = select((int) md->rmt_sockdata + 1, &rfds, NULL, NULL, &tv);
238 	if (retval == -1)
239 	{
240 		sock_geterror("select(): ", p->errbuf, PCAP_ERRBUF_SIZE);
241 		return -1;
242 	}
243 
244 	/* There is no data waiting, so return '0' */
245 	if (retval == 0)
246 		return 0;
247 
248 	/*
249 	 * data is here; so, let's copy it into the user buffer.
250 	 * I'm going to read a new packet; so I reset the number of bytes (payload only) read
251 	 */
252 	totread = 0;
253 
254 	/*
255 	 * We have to define 'header' as a pointer to a larger buffer,
256 	 * because in case of UDP we have to read all the message within a single call
257 	 */
258 	header = (struct rpcap_header *) netbuf;
259 	net_pkt_header = (struct rpcap_pkthdr *) (netbuf + sizeof(struct rpcap_header));
260 
261 	if (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
262 	{
263 		/* Read the entire message from the network */
264 		if (sock_recv(md->rmt_sockdata, netbuf, RPCAP_NETBUF_SIZE, SOCK_RECEIVEALL_NO, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
265 			return -1;
266 	}
267 	else
268 	{
269 		if (sock_recv(md->rmt_sockdata, netbuf, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
270 			return -1;
271 	}
272 
273 	/* Checks if the message is correct */
274 	retval = rpcap_checkmsg(p->errbuf, md->rmt_sockdata, header, RPCAP_MSG_PACKET, 0);
275 
276 	if (retval != RPCAP_MSG_PACKET)		/* the message is not the one expected */
277 	{
278 		switch (retval)
279 		{
280 		case -3:		/* Unrecoverable network error */
281 			return -1;	/* Do nothing; just exit from here; the error code is already into the errbuf */
282 
283 		case -2:		/* The other endpoint sent a message that is not allowed here */
284 		case -1:		/* The other endpoint has a version number that is not compatible with our */
285 			return 0;	/* Return 'no packets received' */
286 
287 		default:
288 			SOCK_ASSERT("Internal error", 1);
289 			return 0;	/* Return 'no packets received' */
290 		}
291 	}
292 
293 	/* In case of TCP, read the remaining of the packet from the socket */
294 	if (!(md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
295 	{
296 		/* Read the RPCAP packet header from the network */
297 		nread = sock_recv(md->rmt_sockdata, (char *)net_pkt_header,
298 		    sizeof(struct rpcap_pkthdr), SOCK_RECEIVEALL_YES,
299 		    p->errbuf, PCAP_ERRBUF_SIZE);
300 		if (nread == -1)
301 			return -1;
302 		totread += nread;
303 	}
304 
305 	if ((ntohl(net_pkt_header->caplen) + sizeof(struct pcap_pkthdr)) <= p->bufsize)
306 	{
307 		/* Initialize returned structures */
308 		*pkt_header = (struct pcap_pkthdr *) p->buffer;
309 		*pkt_data = (u_char*)p->buffer + sizeof(struct pcap_pkthdr);
310 
311 		(*pkt_header)->caplen = ntohl(net_pkt_header->caplen);
312 		(*pkt_header)->len = ntohl(net_pkt_header->len);
313 		(*pkt_header)->ts.tv_sec = ntohl(net_pkt_header->timestamp_sec);
314 		(*pkt_header)->ts.tv_usec = ntohl(net_pkt_header->timestamp_usec);
315 
316 		/*
317 		 * I don't update the counter of the packets dropped by the network since we're using TCP,
318 		 * therefore no packets are dropped. Just update the number of packets received correctly
319 		 */
320 		md->TotCapt++;
321 
322 		/* Copies the packet into the data buffer */
323 		if (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
324 		{
325 			unsigned int npkt;
326 
327 			/*
328 			 * In case of UDP the packet has already been read, we have to copy it into 'buffer'.
329 			 * Another option should be to declare 'netbuf' as 'static'. However this prevents
330 			 * using several pcap instances within the same process (because the static buffer is shared among
331 			 * all processes)
332 			 */
333 			memcpy(*pkt_data, netbuf + sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr), (*pkt_header)->caplen);
334 
335 			/* We're using UDP, so we need to update the counter of the packets dropped by the network */
336 			npkt = ntohl(net_pkt_header->npkt);
337 
338 			if (md->TotCapt != npkt)
339 			{
340 				md->TotNetDrops += (npkt - md->TotCapt);
341 				md->TotCapt = npkt;
342 			}
343 
344 		}
345 		else
346 		{
347 			/* In case of TCP, read the remaining of the packet from the socket */
348 			nread = sock_recv(md->rmt_sockdata, *pkt_data,
349 			    (*pkt_header)->caplen, SOCK_RECEIVEALL_YES,
350 			    p->errbuf, PCAP_ERRBUF_SIZE);
351 			if (nread == -1)
352 				return -1;
353 			totread += nread;
354 
355 			/* Checks if all the data has been read; if not, discard the data in excess */
356 			/* This check has to be done only on TCP connections */
357 			if (totread != ntohl(header->plen))
358 				sock_discard(md->rmt_sockdata, ntohl(header->plen) - totread, NULL, 0);
359 		}
360 
361 
362 		/* Packet read successfully */
363 		return 1;
364 	}
365 	else
366 	{
367 		pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Received a packet that is larger than the internal buffer size.");
368 		return -1;
369 	}
370 
371 }
372 
373 /* \ingroup remote_pri_func
374  *
375  * \brief It reads a packet from the network socket.
376  *
377  * This function is called by the several pcap_read() when they detect that
378  * we have a remote capture and they are the client side. In that case, they need
379  * to read packets from the socket.
380  *
381  * This function relies on the pcap_read_nocb_remote to deliver packets. The
382  * difference, here, is that as soon as a packet is read, it is delivered
383  * to the application by means of a callback function.
384  *
385  * Parameters and return values are exactly the same of the pcap_read().
386  */
pcap_read_remote(pcap_t * p,int cnt,pcap_handler callback,u_char * user)387 static int pcap_read_remote(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
388 {
389 	struct pcap_pkthdr *pkt_header;
390 	u_char *pkt_data;
391 	int n = 0;
392 
393 	while ((n < cnt) || (cnt < 0))
394 	{
395 		if (pcap_read_nocb_remote(p, &pkt_header, &pkt_data) == 1)
396 		{
397 			(*callback)(user, pkt_header, pkt_data);
398 			n++;
399 		}
400 		else
401 			return n;
402 	}
403 	return n;
404 }
405 
406 /* \ingroup remote_pri_func
407  *
408  * \brief It sends a CLOSE command to the capture server.
409  *
410  * This function is called when the user wants to close a pcap_t adapter.
411  * In case we're capturing from the network, it sends a command to the other
412  * peer that says 'ok, let's stop capturing'.
413  * This function is called automatically when the user calls the pcap_close().
414  *
415  * Parameters and return values are exactly the same of the pcap_close().
416  *
417  * \warning Since we're closing the connection, we do not check for errors.
418  */
pcap_cleanup_remote(pcap_t * fp)419 static void pcap_cleanup_remote(pcap_t *fp)
420 {
421 	struct rpcap_header header;		/* header of the RPCAP packet */
422 	struct activehosts *temp;		/* temp var needed to scan the host list chain, to detect if we're in active mode */
423 	int active = 0;					/* active mode or not? */
424 	struct pcap_md *md;				/* structure used when doing a remote live capture */
425 
426 	md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
427 
428 	/* detect if we're in active mode */
429 	temp = activeHosts;
430 	while (temp)
431 	{
432 		if (temp->sockctrl == md->rmt_sockctrl)
433 		{
434 			active = 1;
435 			break;
436 		}
437 		temp = temp->next;
438 	}
439 
440 	if (!active)
441 	{
442 		rpcap_createhdr(&header, RPCAP_MSG_CLOSE, 0, 0);
443 
444 		/* I don't check for errors, since I'm going to close everything */
445 		sock_send(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), NULL, 0);
446 	}
447 	else
448 	{
449 		rpcap_createhdr(&header, RPCAP_MSG_ENDCAP_REQ, 0, 0);
450 
451 		/* I don't check for errors, since I'm going to close everything */
452 		sock_send(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), NULL, 0);
453 
454 		/* wait for the answer */
455 		/* Don't check what we got, since the present libpcap does not uses this pcap_t anymore */
456 		sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, NULL, 0);
457 
458 		if (ntohl(header.plen) != 0)
459 			sock_discard(md->rmt_sockctrl, ntohl(header.plen), NULL, 0);
460 	}
461 
462 	if (md->rmt_sockdata)
463 	{
464 		sock_close(md->rmt_sockdata, NULL, 0);
465 		md->rmt_sockdata = 0;
466 	}
467 
468 	if ((!active) && (md->rmt_sockctrl))
469 		sock_close(md->rmt_sockctrl, NULL, 0);
470 
471 	md->rmt_sockctrl = 0;
472 
473 	if (md->currentfilter)
474 	{
475 		free(md->currentfilter);
476 		md->currentfilter = NULL;
477 	}
478 
479 	/* To avoid inconsistencies in the number of sock_init() */
480 	sock_cleanup();
481 }
482 
483 /* \ingroup remote_pri_func
484  *
485  * \brief It retrieves network statistics from the other peer.
486  *
487  * This function is just a void cointainer, since the work is done by the rpcap_stats_remote().
488  * See that funcion for more details.
489  *
490  * Parameters and return values are exactly the same of the pcap_stats().
491  */
pcap_stats_remote(pcap_t * p,struct pcap_stat * ps)492 static int pcap_stats_remote(pcap_t *p, struct pcap_stat *ps)
493 {
494 	struct pcap_stat *retval;
495 
496 	retval = rpcap_stats_remote(p, ps, PCAP_STATS_STANDARD);
497 
498 	if (retval)
499 		return 0;
500 	else
501 		return -1;
502 }
503 
504 #ifdef _WIN32
505 /* \ingroup remote_pri_func
506  *
507  * \brief It retrieves network statistics from the other peer.
508  *
509  * This function is just a void cointainer, since the work is done by the rpcap_stats_remote().
510  * See that funcion for more details.
511  *
512  * Parameters and return values are exactly the same of the pcap_stats_ex().
513  */
pcap_stats_ex_remote(pcap_t * p,int * pcap_stat_size)514 static struct pcap_stat *pcap_stats_ex_remote(pcap_t *p, int *pcap_stat_size)
515 {
516 	*pcap_stat_size = sizeof (p->stat);
517 
518 	/* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
519 	return (rpcap_stats_remote(p, &(p->stat), PCAP_STATS_EX));
520 }
521 #endif
522 
523 /* \ingroup remote_pri_func
524  *
525  * \brief It retrieves network statistics from the other peer.
526  *
527  * This function can be called in two modes:
528  * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e. the pcap_stats() )
529  * - PCAP_STATS_EX: if we want extended statistics (i.e. the pcap_stats_ex() )
530  *
531  * This 'mode' parameter is needed because in the standard pcap_stats() the variable that keeps the
532  * statistics is allocated by the user. Unfortunately, this structure has been extended in order
533  * to keep new stats. However, if the user has a smaller structure and it passes it to the pcap_stats,
534  * thid function will try to fill in more data than the size of the structure, so that the application
535  * goes in memory overflow.
536  * So, we need to know it we have to copy just the standard fields, or the extended fields as well.
537  *
538  * In case we want to copy the extended fields as well, the problem of memory overflow does no
539  * longer exist because the structure pcap_stat is no longer allocated by the program;
540  * it is allocated by the library instead.
541  *
542  * \param p: the pcap_t structure related to the current instance.
543  *
544  * \param ps: a 'pcap_stat' structure, needed for compatibility with pcap_stat(), in which
545  * the structure is allocated by the user. In case of pcap_stats_ex, this structure and the
546  * function return value point to the same variable.
547  *
548  * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
549  *
550  * \return The structure that keeps the statistics, or NULL in case of error.
551  * The error string is placed in the pcap_t structure.
552  */
rpcap_stats_remote(pcap_t * p,struct pcap_stat * ps,int mode)553 static struct pcap_stat *rpcap_stats_remote(pcap_t *p, struct pcap_stat *ps, int mode)
554 {
555 	struct rpcap_header header;		/* header of the RPCAP packet */
556 	struct rpcap_stats netstats;		/* statistics sent on the network */
557 	uint32 totread = 0;			/* number of bytes of the payload read from the socket */
558 	int nread;
559 	int retval;				/* temp variable which stores functions return value */
560 	struct pcap_md *md;			/* structure used when doing a remote live capture */
561 
562 	md = (struct pcap_md *) ((u_char*)p->priv + sizeof(struct pcap_win));
563 
564 	/*
565 	 * If the capture has still to start, we cannot ask statistics to the other peer,
566 	 * so we return a fake number
567 	 */
568 	if (!md->rmt_capstarted)
569 	{
570 		if (mode == PCAP_STATS_STANDARD)
571 		{
572 			ps->ps_drop = 0;
573 			ps->ps_ifdrop = 0;
574 			ps->ps_recv = 0;
575 		}
576 		else
577 		{
578 			ps->ps_capt = 0;
579 			ps->ps_drop = 0;
580 			ps->ps_ifdrop = 0;
581 			ps->ps_netdrop = 0;
582 			ps->ps_recv = 0;
583 			ps->ps_sent = 0;
584 		}
585 
586 		return ps;
587 	}
588 
589 	rpcap_createhdr(&header, RPCAP_MSG_STATS_REQ, 0, 0);
590 
591 	/* Send the PCAP_STATS command */
592 	if (sock_send(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), p->errbuf, PCAP_ERRBUF_SIZE))
593 		goto error;
594 
595 	/* Receive the RPCAP stats reply message */
596 	if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
597 		goto error;
598 
599 	/* Checks if the message is correct */
600 	retval = rpcap_checkmsg(p->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_STATS_REPLY, RPCAP_MSG_ERROR, 0);
601 
602 	if (retval != RPCAP_MSG_STATS_REPLY)		/* the message is not the one expected */
603 	{
604 		switch (retval)
605 		{
606 		case -3:		/* Unrecoverable network error */
607 		case -2:		/* The other endpoint send a message that is not allowed here */
608 		case -1:		/* The other endpoint has a version number that is not compatible with our */
609 			goto error;
610 
611 		case RPCAP_MSG_ERROR:		/* The other endpoint reported an error */
612 			/* Update totread, since the rpcap_checkmsg() already purged the buffer */
613 			totread = ntohl(header.plen);
614 
615 			/* Do nothing; just exit; the error code is already into the errbuf */
616 			goto error;
617 
618 		default:
619 			pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
620 			goto error;
621 		}
622 	}
623 
624 	nread = sock_recv(md->rmt_sockctrl, (char *)&netstats,
625 	    sizeof(struct rpcap_stats), SOCK_RECEIVEALL_YES,
626 	    p->errbuf, PCAP_ERRBUF_SIZE);
627 	if (nread == -1)
628 		goto error;
629 	totread += nread;
630 
631 	if (mode == PCAP_STATS_STANDARD)
632 	{
633 		ps->ps_drop = ntohl(netstats.krnldrop);
634 		ps->ps_ifdrop = ntohl(netstats.ifdrop);
635 		ps->ps_recv = ntohl(netstats.ifrecv);
636 	}
637 	else
638 	{
639 		ps->ps_capt = md->TotCapt;
640 		ps->ps_drop = ntohl(netstats.krnldrop);
641 		ps->ps_ifdrop = ntohl(netstats.ifdrop);
642 		ps->ps_netdrop = md->TotNetDrops;
643 		ps->ps_recv = ntohl(netstats.ifrecv);
644 		ps->ps_sent = ntohl(netstats.svrcapt);
645 	}
646 
647 	/* Checks if all the data has been read; if not, discard the data in excess */
648 	if (totread != ntohl(header.plen))
649 	{
650 		if (sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
651 			goto error;
652 	}
653 
654 	return ps;
655 
656 error:
657 	if (totread != ntohl(header.plen))
658 		sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0);
659 
660 	return NULL;
661 }
662 
663 /* \ingroup remote_pri_func
664  *
665  * \brief It opens a remote adapter by opening an RPCAP connection and so on.
666  *
667  * This function does basically the job of pcap_open_live() for a remote interface.
668  * In other words, we have a pcap_read for win32, which reads packets from NPF,
669  * another for LINUX, and so on. Now, we have a pcap_opensource_remote() as well.
670  * The difference, here, is the capture thread does not start until the
671  * pcap_startcapture_remote() is called.
672  *
673  * This is because, in remote capture, we cannot start capturing data as soon ad the
674  * 'open adapter' command is sent. Suppose the remote adapter is already overloaded;
675  * if we start a capture (which, by default, has a NULL filter) the new traffic can
676  * saturate the network.
677  *
678  * Instead, we want to "open" the adapter, then send a "start capture" command only
679  * when we're ready to start the capture.
680  * This funtion does this job: it sends a "open adapter" command (according to the
681  * RPCAP protocol), but it does not start the capture.
682  *
683  * Since the other libpcap functions do not share this way of life, we have to make
684  * some dirty things in order to make everyting working.
685  *
686  * \param fp: A pointer to a pcap_t structure that has been previously created with
687  * \ref pcap_create().
688  * \param source: see pcap_open().
689  * \param auth: see pcap_open().
690  *
691  * \return 0 in case of success, -1 otherwise. In case of success, the pcap_t pointer in fp can be
692  * used as a parameter to the following calls (pcap_compile() and so on). In case of
693  * problems, fp->errbuf contains a text explanation of error.
694  *
695  * \warning In case we call the pcap_compile() and the capture is not started, the filter
696  * will be saved into the pcap_t structure, and it will be sent to the other host later
697  * (when the pcap_startcapture_remote() is called).
698  */
pcap_opensource_remote(pcap_t * fp,struct pcap_rmtauth * auth)699 int pcap_opensource_remote(pcap_t *fp, struct pcap_rmtauth *auth)
700 {
701 	char host[PCAP_BUF_SIZE], ctrlport[PCAP_BUF_SIZE], iface[PCAP_BUF_SIZE];
702 
703 	char sendbuf[RPCAP_NETBUF_SIZE];	/* temporary buffer in which data to be sent is buffered */
704 	int sendbufidx = 0;			/* index which keeps the number of bytes currently buffered */
705 	uint32 totread = 0;			/* number of bytes of the payload read from the socket */
706 	int nread;
707 	int retval;				/* store the return value of the functions */
708 	int active = 0;				/* '1' if we're in active mode */
709 
710 	/* socket-related variables */
711 	struct addrinfo hints;			/* temp, needed to open a socket connection */
712 	struct addrinfo *addrinfo;		/* temp, needed to open a socket connection */
713 	SOCKET sockctrl = 0;			/* socket descriptor of the control connection */
714 
715 	/* RPCAP-related variables */
716 	struct rpcap_header header;		/* header of the RPCAP packet */
717 	struct rpcap_openreply openreply;	/* open reply message */
718 
719 	struct pcap_md *md;			/* structure used when doing a remote live capture */
720 
721 	md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
722 
723 
724 	/*
725 	 * determine the type of the source (NULL, file, local, remote)
726 	 * You must have a valid source string even if we're in active mode, because otherwise
727 	 * the call to the following function will fail.
728 	 */
729 	if (pcap_parsesrcstr(fp->opt.device, &retval, host, ctrlport, iface, fp->errbuf) == -1)
730 		return -1;
731 
732 	if (retval != PCAP_SRC_IFREMOTE)
733 	{
734 		pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "This function is able to open only remote interfaces");
735 		return -1;
736 	}
737 
738 	addrinfo = NULL;
739 
740 	/*
741 	 * Warning: this call can be the first one called by the user.
742 	 * For this reason, we have to initialize the WinSock support.
743 	 */
744 	if (sock_init(fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
745 		return -1;
746 
747 	sockctrl = rpcap_remoteact_getsock(host, &active, fp->errbuf);
748 	if (sockctrl == INVALID_SOCKET)
749 		return -1;
750 
751 	if (!active)
752 	{
753 		/*
754 		 * We're not in active mode; let's try to open a new
755 		 * control connection.
756 		 */
757 		memset(&hints, 0, sizeof(struct addrinfo));
758 		hints.ai_family = PF_UNSPEC;
759 		hints.ai_socktype = SOCK_STREAM;
760 
761 		if ((ctrlport == NULL) || (ctrlport[0] == 0))
762 		{
763 			/* the user chose not to specify the port */
764 			if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
765 				return -1;
766 		}
767 		else
768 		{
769 			/* the user chose not to specify the port */
770 			if (sock_initaddress(host, ctrlport, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
771 				return -1;
772 		}
773 
774 		if ((sockctrl = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
775 			goto error;
776 
777 		freeaddrinfo(addrinfo);
778 		addrinfo = NULL;
779 
780 		if (rpcap_sendauth(sockctrl, auth, fp->errbuf) == -1)
781 			goto error;
782 	}
783 
784 	/*
785 	 * Now it's time to start playing with the RPCAP protocol
786 	 * RPCAP open command: create the request message
787 	 */
788 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
789 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
790 		goto error;
791 
792 	rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_OPEN_REQ, 0, (uint32) strlen(iface));
793 
794 	if (sock_bufferize(iface, (int) strlen(iface), sendbuf, &sendbufidx,
795 		RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, fp->errbuf, PCAP_ERRBUF_SIZE))
796 		goto error;
797 
798 	if (sock_send(sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
799 		goto error;
800 
801 	/* Receive the RPCAP open reply message */
802 	if (sock_recv(sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
803 		goto error;
804 
805 	/* Checks if the message is correct */
806 	retval = rpcap_checkmsg(fp->errbuf, sockctrl, &header, RPCAP_MSG_OPEN_REPLY, RPCAP_MSG_ERROR, 0);
807 
808 	if (retval != RPCAP_MSG_OPEN_REPLY)		/* the message is not the one expected */
809 	{
810 		switch (retval)
811 		{
812 		case -3:		/* Unrecoverable network error */
813 		case -2:		/* The other endpoint send a message that is not allowed here */
814 		case -1:		/* The other endpoint has a version number that is not compatible with our */
815 			goto error;
816 
817 		case RPCAP_MSG_ERROR:		/* The other endpoint reported an error */
818 			/* Update totread, since the rpcap_checkmsg() already purged the buffer */
819 			totread = ntohl(header.plen);
820 			/* Do nothing; just exit; the error code is already into the errbuf */
821 			goto error;
822 
823 		default:
824 			pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
825 			goto error;
826 		}
827 	}
828 
829 	nread = sock_recv(sockctrl, (char *)&openreply,
830 	    sizeof(struct rpcap_openreply), SOCK_RECEIVEALL_YES,
831 	    fp->errbuf, PCAP_ERRBUF_SIZE);
832 	if (nread == -1)
833 		goto error;
834 	totread += nread;
835 
836 	/* Set proper fields into the pcap_t struct */
837 	fp->linktype = ntohl(openreply.linktype);
838 	fp->tzoff = ntohl(openreply.tzoff);
839 	md->rmt_sockctrl = sockctrl;
840 	md->rmt_clientside = 1;
841 
842 
843 	/* This code is duplicated from the end of this function */
844 	fp->read_op = pcap_read_remote;
845 	fp->setfilter_op = pcap_setfilter_remote;
846 	fp->getnonblock_op = NULL;	/* This is not implemented in remote capture */
847 	fp->setnonblock_op = NULL;	/* This is not implemented in remote capture */
848 	fp->stats_op = pcap_stats_remote;
849 #ifdef _WIN32
850 	fp->stats_ex_op = pcap_stats_ex_remote;
851 #endif
852 	fp->cleanup_op = pcap_cleanup_remote;
853 
854 	/* Checks if all the data has been read; if not, discard the data in excess */
855 	if (totread != ntohl(header.plen))
856 	{
857 		if (sock_discard(sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
858 			goto error;
859 	}
860 	return 0;
861 
862 error:
863 	/*
864 	 * When the connection has been established, we have to close it. So, at the
865 	 * beginning of this function, if an error occur we return immediately with
866 	 * a return NULL; when the connection is established, we have to come here
867 	 * ('goto error;') in order to close everything properly.
868 	 *
869 	 * Checks if all the data has been read; if not, discard the data in excess
870 	 */
871 	if (totread != ntohl(header.plen))
872 		sock_discard(sockctrl, ntohl(header.plen) - totread, NULL, 0);
873 
874 	if (addrinfo)
875 		freeaddrinfo(addrinfo);
876 
877 	if (!active)
878 		sock_close(sockctrl, NULL, 0);
879 
880 	return -1;
881 }
882 
883 /* \ingroup remote_pri_func
884  *
885  * \brief It starts a remote capture.
886  *
887  * This function is requires since the RPCAP protocol decouples the 'open' from the
888  * 'start capture' functions.
889  * This function takes all the parameters needed (which have been stored into the pcap_t structure)
890  * and sends them to the server.
891  * If everything is fine, it creates a new child thread that reads data from the network
892  * and puts data it into the user buffer.
893  * The pcap_read() will read data from the user buffer, as usual.
894  *
895  * The remote capture acts like a new "kernel", which puts packets directly into
896  * the buffer pointed by pcap_t.
897  * In fact, this function does not rely on a kernel that reads packets and put them
898  * into the user buffer; it has to do that on its own.
899  *
900  * \param fp: the pcap_t descriptor of the device currently open.
901  *
902  * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
903  * is returned into the 'errbuf' field of the pcap_t structure.
904  */
pcap_startcapture_remote(pcap_t * fp)905 int pcap_startcapture_remote(pcap_t *fp)
906 {
907 	char sendbuf[RPCAP_NETBUF_SIZE];	/* temporary buffer in which data to be sent is buffered */
908 	int sendbufidx = 0;			/* index which keeps the number of bytes currently buffered */
909 	char portdata[PCAP_BUF_SIZE];		/* temp variable needed to keep the network port for the the data connection */
910 	uint32 totread = 0;			/* number of bytes of the payload read from the socket */
911 	int nread;
912 	int retval;				/* store the return value of the functions */
913 	int active = 0;				/* '1' if we're in active mode */
914 	struct activehosts *temp;		/* temp var needed to scan the host list chain, to detect if we're in active mode */
915 	char host[INET6_ADDRSTRLEN + 1];	/* numeric name of the other host */
916 
917 	/* socket-related variables*/
918 	struct addrinfo hints;			/* temp, needed to open a socket connection */
919 	struct addrinfo *addrinfo;		/* temp, needed to open a socket connection */
920 	SOCKET sockdata = 0;			/* socket descriptor of the data connection */
921 	struct sockaddr_storage saddr;		/* temp, needed to retrieve the network data port chosen on the local machine */
922 	socklen_t saddrlen;			/* temp, needed to retrieve the network data port chosen on the local machine */
923 	int ai_family;				/* temp, keeps the address family used by the control connection */
924 
925 	/* RPCAP-related variables*/
926 	struct rpcap_header header;			/* header of the RPCAP packet */
927 	struct rpcap_startcapreq *startcapreq;		/* start capture request message */
928 	struct rpcap_startcapreply startcapreply;	/* start capture reply message */
929 
930 	/* Variables related to the buffer setting */
931 	int res, itemp;
932 	int sockbufsize = 0;
933 
934 	struct pcap_md *md;			/* structure used when doing a remote live capture */
935 
936 	md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
937 
938 	/*
939 	 * Let's check if sampling has been required.
940 	 * If so, let's set it first
941 	 */
942 	if (pcap_setsampling_remote(fp) != 0)
943 		return -1;
944 
945 
946 	/* detect if we're in active mode */
947 	temp = activeHosts;
948 	while (temp)
949 	{
950 		if (temp->sockctrl == md->rmt_sockctrl)
951 		{
952 			active = 1;
953 			break;
954 		}
955 		temp = temp->next;
956 	}
957 
958 	addrinfo = NULL;
959 
960 	/*
961 	 * Gets the complete sockaddr structure used in the ctrl connection
962 	 * This is needed to get the address family of the control socket
963 	 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
964 	 * since the ctrl socket can already be open in case of active mode;
965 	 * so I would have to call getpeername() anyway
966 	 */
967 	saddrlen = sizeof(struct sockaddr_storage);
968 	if (getpeername(md->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
969 	{
970 		sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
971 		goto error;
972 	}
973 	ai_family = ((struct sockaddr_storage *) &saddr)->ss_family;
974 
975 	/* Get the numeric address of the remote host we are connected to */
976 	if (getnameinfo((struct sockaddr *) &saddr, saddrlen, host,
977 		sizeof(host), NULL, 0, NI_NUMERICHOST))
978 	{
979 		sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
980 		goto error;
981 	}
982 
983 	/*
984 	 * Data connection is opened by the server toward the client if:
985 	 * - we're using TCP, and the user wants us to be in active mode
986 	 * - we're using UDP
987 	 */
988 	if ((active) || (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
989 	{
990 		/*
991 		 * We have to create a new socket to receive packets
992 		 * We have to do that immediately, since we have to tell the other
993 		 * end which network port we picked up
994 		 */
995 		memset(&hints, 0, sizeof(struct addrinfo));
996 		/* TEMP addrinfo is NULL in case of active */
997 		hints.ai_family = ai_family;	/* Use the same address family of the control socket */
998 		hints.ai_socktype = (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
999 		hints.ai_flags = AI_PASSIVE;	/* Data connection is opened by the server toward the client */
1000 
1001 		/* Let's the server pick up a free network port for us */
1002 		if (sock_initaddress(NULL, "0", &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1003 			goto error;
1004 
1005 		if ((sockdata = sock_open(addrinfo, SOCKOPEN_SERVER,
1006 			1 /* max 1 connection in queue */, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1007 			goto error;
1008 
1009 		/* addrinfo is no longer used */
1010 		freeaddrinfo(addrinfo);
1011 		addrinfo = NULL;
1012 
1013 		/* get the complete sockaddr structure used in the data connection */
1014 		saddrlen = sizeof(struct sockaddr_storage);
1015 		if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1016 		{
1017 			sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1018 			goto error;
1019 		}
1020 
1021 		/* Get the local port the system picked up */
1022 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
1023 			0, portdata, sizeof(portdata), NI_NUMERICSERV))
1024 		{
1025 			sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1026 			goto error;
1027 		}
1028 	}
1029 
1030 	/*
1031 	 * Now it's time to start playing with the RPCAP protocol
1032 	 * RPCAP start capture command: create the request message
1033 	 */
1034 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1035 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1036 		goto error;
1037 
1038 	rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_STARTCAP_REQ, 0,
1039 		sizeof(struct rpcap_startcapreq) + sizeof(struct rpcap_filter) + fp->fcode.bf_len * sizeof(struct rpcap_filterbpf_insn));
1040 
1041 	/* Fill the structure needed to open an adapter remotely */
1042 	startcapreq = (struct rpcap_startcapreq *) &sendbuf[sendbufidx];
1043 
1044 	if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreq), NULL,
1045 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1046 		goto error;
1047 
1048 	memset(startcapreq, 0, sizeof(struct rpcap_startcapreq));
1049 
1050 	/* By default, apply half the timeout on one side, half of the other */
1051 	fp->opt.timeout = fp->opt.timeout / 2;
1052 	startcapreq->read_timeout = htonl(fp->opt.timeout);
1053 
1054 	/* portdata on the openreq is meaningful only if we're in active mode */
1055 	if ((active) || (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1056 	{
1057 		sscanf(portdata, "%d", (int *)&(startcapreq->portdata));	/* cast to avoid a compiler warning */
1058 		startcapreq->portdata = htons(startcapreq->portdata);
1059 	}
1060 
1061 	startcapreq->snaplen = htonl(fp->snapshot);
1062 	startcapreq->flags = 0;
1063 
1064 	if (md->rmt_flags & PCAP_OPENFLAG_PROMISCUOUS)
1065 		startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_PROMISC;
1066 	if (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
1067 		startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_DGRAM;
1068 	if (active)
1069 		startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN;
1070 
1071 	startcapreq->flags = htons(startcapreq->flags);
1072 
1073 	/* Pack the capture filter */
1074 	if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, &fp->fcode))
1075 		goto error;
1076 
1077 	if (sock_send(md->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
1078 		goto error;
1079 
1080 
1081 	/* Receive the RPCAP start capture reply message */
1082 	if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1083 		goto error;
1084 
1085 	/* Checks if the message is correct */
1086 	retval = rpcap_checkmsg(fp->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_STARTCAP_REPLY, RPCAP_MSG_ERROR, 0);
1087 
1088 	if (retval != RPCAP_MSG_STARTCAP_REPLY)		/* the message is not the one expected */
1089 	{
1090 		switch (retval)
1091 		{
1092 		case -3:		/* Unrecoverable network error */
1093 		case -2:		/* The other endpoint send a message that is not allowed here */
1094 		case -1:		/* The other endpoint has a version number that is not compatible with our */
1095 			goto error;
1096 
1097 		case RPCAP_MSG_ERROR:		/* The other endpoint reported an error */
1098 			/* Update totread, since the rpcap_checkmsg() already purged the buffer */
1099 			totread = ntohl(header.plen);
1100 			/* Do nothing; just exit; the error code is already into the errbuf */
1101 			goto error;
1102 
1103 		default:
1104 			pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
1105 			goto error;
1106 		}
1107 	}
1108 
1109 	nread = sock_recv(md->rmt_sockctrl, (char *)&startcapreply,
1110 	    sizeof(struct rpcap_startcapreply), SOCK_RECEIVEALL_YES,
1111 	    fp->errbuf, PCAP_ERRBUF_SIZE);
1112 	if (nread == -1)
1113 		goto error;
1114 	totread += nread;
1115 
1116 	/*
1117 	 * In case of UDP data stream, the connection is always opened by the daemon
1118 	 * So, this case is already covered by the code above.
1119 	 * Now, we have still to handle TCP connections, because:
1120 	 * - if we're in active mode, we have to wait for a remote connection
1121 	 * - if we're in passive more, we have to start a connection
1122 	 *
1123 	 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1124 	 * to tell the port we're using to the remote side; in case we're accepting a TCP
1125 	 * connection, we have to wait this info from the remote side.
1126 	 */
1127 
1128 	if (!(md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1129 	{
1130 		if (!active)
1131 		{
1132 			memset(&hints, 0, sizeof(struct addrinfo));
1133 			hints.ai_family = ai_family;		/* Use the same address family of the control socket */
1134 			hints.ai_socktype = (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1135 			pcap_snprintf(portdata, PCAP_BUF_SIZE, "%d", ntohs(startcapreply.portdata));
1136 
1137 			/* Let's the server pick up a free network port for us */
1138 			if (sock_initaddress(host, portdata, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1139 				goto error;
1140 
1141 			if ((sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1142 				goto error;
1143 
1144 			/* addrinfo is no longer used */
1145 			freeaddrinfo(addrinfo);
1146 			addrinfo = NULL;
1147 		}
1148 		else
1149 		{
1150 			SOCKET socktemp;	/* We need another socket, since we're going to accept() a connection */
1151 
1152 			/* Connection creation */
1153 			saddrlen = sizeof(struct sockaddr_storage);
1154 
1155 			socktemp = accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
1156 
1157 			if (socktemp == -1)
1158 			{
1159 				sock_geterror("accept(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1160 				goto error;
1161 			}
1162 
1163 			/* Now that I accepted the connection, the server socket is no longer needed */
1164 			sock_close(sockdata, fp->errbuf, PCAP_ERRBUF_SIZE);
1165 			sockdata = socktemp;
1166 		}
1167 	}
1168 
1169 	/* Let's save the socket of the data connection */
1170 	md->rmt_sockdata = sockdata;
1171 
1172 	/* Allocates WinPcap/libpcap user buffer, which is a socket buffer in case of a remote capture */
1173 	/* It has the same size of the one used on the other side of the connection */
1174 	fp->bufsize = ntohl(startcapreply.bufsize);
1175 
1176 	/* Let's get the actual size of the socket buffer */
1177 	itemp = sizeof(sockbufsize);
1178 
1179 	res = getsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &itemp);
1180 	if (res == -1)
1181 	{
1182 		sock_geterror("pcap_startcapture_remote()", fp->errbuf, PCAP_ERRBUF_SIZE);
1183 		SOCK_ASSERT(fp->errbuf, 1);
1184 	}
1185 
1186 	/*
1187 	 * Warning: on some kernels (e.g. Linux), the size of the user buffer does not take
1188 	 * into account the pcap_header and such, and it is set equal to the snaplen.
1189 	 * In my view, this is wrong (the meaning of the bufsize became a bit strange).
1190 	 * So, here bufsize is the whole size of the user buffer.
1191 	 * In case the bufsize returned is too small, let's adjust it accordingly.
1192 	 */
1193 	if (fp->bufsize <= (u_int) fp->snapshot)
1194 		fp->bufsize += sizeof(struct pcap_pkthdr);
1195 
1196 	/* if the current socket buffer is smaller than the desired one */
1197 	if ((u_int) sockbufsize < fp->bufsize)
1198 	{
1199 		/* Loop until the buffer size is OK or the original socket buffer size is larger than this one */
1200 		while (1)
1201 		{
1202 			res = setsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&(fp->bufsize), sizeof(fp->bufsize));
1203 
1204 			if (res == 0)
1205 				break;
1206 
1207 			/*
1208 			 * If something goes wrong, half the buffer size (checking that it does not become smaller than
1209 			 * the current one)
1210 			 */
1211 			fp->bufsize /= 2;
1212 
1213 			if ((u_int) sockbufsize >= fp->bufsize)
1214 			{
1215 				fp->bufsize = sockbufsize;
1216 				break;
1217 			}
1218 		}
1219 	}
1220 
1221 	/*
1222 	 * Let's allocate the packet; this is required in order to put the packet somewhere when
1223 	 * extracting data from the socket
1224 	 * Since buffering has already been done in the socket buffer, here we need just a buffer,
1225 	 * whose size is equal to the pcap header plus the snapshot length
1226 	 */
1227 	fp->bufsize = fp->snapshot + sizeof(struct pcap_pkthdr);
1228 
1229 	fp->buffer = (u_char *)malloc(fp->bufsize);
1230 	if (fp->buffer == NULL)
1231 	{
1232 		pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
1233 		goto error;
1234 	}
1235 
1236 
1237 	/* Checks if all the data has been read; if not, discard the data in excess */
1238 	if (totread != ntohl(header.plen))
1239 	{
1240 		if (sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
1241 			goto error;
1242 	}
1243 
1244 	/*
1245 	 * In case the user does not want to capture RPCAP packets, let's update the filter
1246 	 * We have to update it here (instead of sending it into the 'StartCapture' message
1247 	 * because when we generate the 'start capture' we do not know (yet) all the ports
1248 	 * we're currently using.
1249 	 */
1250 	if (md->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1251 	{
1252 		struct bpf_program fcode;
1253 
1254 		if (pcap_createfilter_norpcappkt(fp, &fcode) == -1)
1255 			goto error;
1256 
1257 		/* We cannot use 'pcap_setfilter_remote' because formally the capture has not been started yet */
1258 		/* (the 'fp->rmt_capstarted' variable will be updated some lines below) */
1259 		if (pcap_updatefilter_remote(fp, &fcode) == -1)
1260 			goto error;
1261 
1262 		pcap_freecode(&fcode);
1263 	}
1264 
1265 	md->rmt_capstarted = 1;
1266 	return 0;
1267 
1268 error:
1269 	/*
1270 	 * When the connection has been established, we have to close it. So, at the
1271 	 * beginning of this function, if an error occur we return immediately with
1272 	 * a return NULL; when the connection is established, we have to come here
1273 	 * ('goto error;') in order to close everything properly.
1274 	 *
1275 	 * Checks if all the data has been read; if not, discard the data in excess
1276 	 */
1277 	if (totread != ntohl(header.plen))
1278 		sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0);
1279 
1280 	if ((sockdata) && (sockdata != -1))		/* we can be here because sockdata said 'error' */
1281 		sock_close(sockdata, NULL, 0);
1282 
1283 	if (!active)
1284 		sock_close(md->rmt_sockctrl, NULL, 0);
1285 
1286 	/*
1287 	 * We do not have to call pcap_close() here, because this function is always called
1288 	 * by the user in case something bad happens
1289 	 */
1290 	// 	if (fp)
1291 	// 	{
1292 	// 		pcap_close(fp);
1293 	// 		fp= NULL;
1294 	// 	}
1295 
1296 	return -1;
1297 }
1298 
1299 /*
1300  * \brief Takes a bpf program and sends it to the other host.
1301  *
1302  * This function can be called in two cases:
1303  * - the pcap_startcapture() is called (we have to send the filter along with
1304  * the 'start capture' command)
1305  * - we want to udpate the filter during a capture (i.e. the pcap_setfilter()
1306  * is called when the capture is still on)
1307  *
1308  * This function serializes the filter into the sending buffer ('sendbuf', passed
1309  * as a parameter) and return back. It does not send anything on the network.
1310  *
1311  * \param fp: the pcap_t descriptor of the device currently opened.
1312  *
1313  * \param sendbuf: the buffer on which the serialized data has to copied.
1314  *
1315  * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1316  *
1317  * \param prog: the bpf program we have to copy.
1318  *
1319  * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1320  * is returned into the 'errbuf' field of the pcap_t structure.
1321  */
pcap_pack_bpffilter(pcap_t * fp,char * sendbuf,int * sendbufidx,struct bpf_program * prog)1322 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog)
1323 {
1324 	struct rpcap_filter *filter;
1325 	struct rpcap_filterbpf_insn *insn;
1326 	struct bpf_insn *bf_insn;
1327 	struct bpf_program fake_prog;		/* To be used just in case the user forgot to set a filter */
1328 	unsigned int i;
1329 
1330 
1331 	if (prog->bf_len == 0)	/* No filters have been specified; so, let's apply a "fake" filter */
1332 	{
1333 		if (pcap_compile(fp, &fake_prog, NULL /* buffer */, 1, 0) == -1)
1334 			return -1;
1335 
1336 		prog = &fake_prog;
1337 	}
1338 
1339 	filter = (struct rpcap_filter *) sendbuf;
1340 
1341 	if (sock_bufferize(NULL, sizeof(struct rpcap_filter), NULL, sendbufidx,
1342 		RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1343 		return -1;
1344 
1345 	filter->filtertype = htons(RPCAP_UPDATEFILTER_BPF);
1346 	filter->nitems = htonl((int32)prog->bf_len);
1347 
1348 	if (sock_bufferize(NULL, prog->bf_len * sizeof(struct rpcap_filterbpf_insn),
1349 		NULL, sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1350 		return -1;
1351 
1352 	insn = (struct rpcap_filterbpf_insn *) (filter + 1);
1353 	bf_insn = prog->bf_insns;
1354 
1355 	for (i = 0; i < prog->bf_len; i++)
1356 	{
1357 		insn->code = htons(bf_insn->code);
1358 		insn->jf = bf_insn->jf;
1359 		insn->jt = bf_insn->jt;
1360 		insn->k = htonl(bf_insn->k);
1361 
1362 		insn++;
1363 		bf_insn++;
1364 	}
1365 
1366 	return 0;
1367 }
1368 
1369 /* \ingroup remote_pri_func
1370  *
1371  * \brief Update a filter on a remote host.
1372  *
1373  * This function is called when the user wants to update a filter.
1374  * In case we're capturing from the network, it sends the filter to the other peer.
1375  * This function is *not* called automatically when the user calls the pcap_setfilter().
1376  * There will be two cases:
1377  * - the capture is already on: in this case, pcap_setfilter() calls pcap_updatefilter_remote()
1378  * - the capture has not started yet: in this case, pcap_setfilter() stores the filter into
1379  * the pcap_t structure, and then the filter is sent with the pcap_startcap().
1380  *
1381  * Parameters and return values are exactly the same of the pcap_setfilter().
1382  *
1383  * \warning This function *does not* clear the packet currently into the buffers. Therefore,
1384  * the user has to expect to receive some packets that are related to the previous filter.
1385  * If you want to discard all the packets before applying a new filter, you have to close
1386  * the current capture session and start a new one.
1387  */
pcap_updatefilter_remote(pcap_t * fp,struct bpf_program * prog)1388 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog)
1389 {
1390 	int retval;						/* general variable used to keep the return value of other functions */
1391 	char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
1392 	int sendbufidx = 0;				/* index which keeps the number of bytes currently buffered */
1393 	struct rpcap_header header;		/* To keep the reply message */
1394 	struct pcap_md *md;				/* structure used when doing a remote live capture */
1395 
1396 	md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
1397 
1398 
1399 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1400 		RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1401 		return -1;
1402 
1403 	rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_UPDATEFILTER_REQ, 0,
1404 		sizeof(struct rpcap_filter) + prog->bf_len * sizeof(struct rpcap_filterbpf_insn));
1405 
1406 	if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, prog))
1407 		return -1;
1408 
1409 	if (sock_send(md->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
1410 		return -1;
1411 
1412 	/* Waits for the answer */
1413 	if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1414 		return -1;
1415 
1416 	/* Checks if the message is correct */
1417 	retval = rpcap_checkmsg(fp->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_UPDATEFILTER_REPLY, 0);
1418 
1419 	if (retval != RPCAP_MSG_UPDATEFILTER_REPLY)		/* the message is not the one expected */
1420 	{
1421 		switch (retval)
1422 		{
1423 		case -3:		/* Unrecoverable network error */
1424 		case -2:		/* The other endpoint sent a message that is not allowed here */
1425 		case -1:		/* The other endpoint has a version number that is not compatible with our */
1426 			/* Do nothing; just exit from here; the error code is already into the errbuf */
1427 			return -1;
1428 
1429 		default:
1430 			SOCK_ASSERT("Internal error", 0);
1431 			return -1;
1432 		}
1433 	}
1434 
1435 	if (ntohl(header.plen) != 0)	/* the message has an unexpected size */
1436 	{
1437 		if (sock_discard(md->rmt_sockctrl, ntohl(header.plen), fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1438 			return -1;
1439 	}
1440 
1441 	return 0;
1442 }
1443 
1444 /*
1445  * \ingroup remote_pri_func
1446  *
1447  * \brief Send a filter to a remote host.
1448  *
1449  * This function is called when the user wants to set a filter.
1450  * In case we're capturing from the network, it sends the filter to the other peer.
1451  * This function is called automatically when the user calls the pcap_setfilter().
1452  *
1453  * Parameters and return values are exactly the same of the pcap_setfilter().
1454  */
pcap_setfilter_remote(pcap_t * fp,struct bpf_program * prog)1455 static int pcap_setfilter_remote(pcap_t *fp, struct bpf_program *prog)
1456 {
1457 	struct pcap_md *md;				/* structure used when doing a remote live capture */
1458 
1459 	md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
1460 
1461 	if (!md->rmt_capstarted)
1462 	{
1463 		/* copy filter into the pcap_t structure */
1464 		if (install_bpf_program(fp, prog) == -1)
1465 			return -1;
1466 		return 0;
1467 	}
1468 
1469 	/* we have to update a filter during run-time */
1470 	if (pcap_updatefilter_remote(fp, prog))
1471 		return -1;
1472 
1473 	return 0;
1474 }
1475 
1476 /*
1477  * \ingroup remote_pri_func
1478  *
1479  * \brief Update the current filter in order not to capture rpcap packets.
1480  *
1481  * This function is called *only* when the user wants exclude RPCAP packets
1482  * related to the current session from the captured packets.
1483  *
1484  * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1485  * is returned into the 'errbuf' field of the pcap_t structure.
1486  */
pcap_createfilter_norpcappkt(pcap_t * fp,struct bpf_program * prog)1487 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog)
1488 {
1489 	int RetVal = 0;
1490 	struct pcap_md *md;				/* structure used when doing a remote live capture */
1491 
1492 	md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
1493 
1494 	/* We do not want to capture our RPCAP traffic. So, let's update the filter */
1495 	if (md->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1496 	{
1497 		struct sockaddr_storage saddr;		/* temp, needed to retrieve the network data port chosen on the local machine */
1498 		socklen_t saddrlen;					/* temp, needed to retrieve the network data port chosen on the local machine */
1499 		char myaddress[128];
1500 		char myctrlport[128];
1501 		char mydataport[128];
1502 		char peeraddress[128];
1503 		char peerctrlport[128];
1504 		char *newfilter;
1505 		const int newstringsize = 1024;
1506 		size_t currentfiltersize;
1507 
1508 		/* Get the name/port of the other peer */
1509 		saddrlen = sizeof(struct sockaddr_storage);
1510 		if (getpeername(md->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1511 		{
1512 			sock_geterror("getpeername(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1513 			return -1;
1514 		}
1515 
1516 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peeraddress,
1517 			sizeof(peeraddress), peerctrlport, sizeof(peerctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1518 		{
1519 			sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1520 			return -1;
1521 		}
1522 
1523 		/* We cannot check the data port, because this is available only in case of TCP sockets */
1524 		/* Get the name/port of the current host */
1525 		if (getsockname(md->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1526 		{
1527 			sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1528 			return -1;
1529 		}
1530 
1531 		/* Get the local port the system picked up */
1532 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, myaddress,
1533 			sizeof(myaddress), myctrlport, sizeof(myctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1534 		{
1535 			sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1536 			return -1;
1537 		}
1538 
1539 		/* Let's now check the data port */
1540 		if (getsockname(md->rmt_sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1541 		{
1542 			sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1543 			return -1;
1544 		}
1545 
1546 		/* Get the local port the system picked up */
1547 		if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL, 0, mydataport, sizeof(mydataport), NI_NUMERICSERV))
1548 		{
1549 			sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1550 			return -1;
1551 		}
1552 
1553 		currentfiltersize = strlen(md->currentfilter);
1554 
1555 		newfilter = (char *)malloc(currentfiltersize + newstringsize + 1);
1556 
1557 		if (currentfiltersize)
1558 		{
1559 			pcap_snprintf(newfilter, currentfiltersize + newstringsize,
1560 				"(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1561 				md->currentfilter, myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
1562 		}
1563 		else
1564 		{
1565 			pcap_snprintf(newfilter, currentfiltersize + newstringsize,
1566 				"not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1567 				myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
1568 		}
1569 
1570 		newfilter[currentfiltersize + newstringsize] = 0;
1571 
1572 		/* This is only an hack to make the pcap_compile() working properly */
1573 		md->rmt_clientside = 0;
1574 
1575 		if (pcap_compile(fp, prog, newfilter, 1, 0) == -1)
1576 			RetVal = -1;
1577 
1578 		/* This is only an hack to make the pcap_compile() working properly */
1579 		md->rmt_clientside = 1;
1580 
1581 		free(newfilter);
1582 	}
1583 
1584 	return RetVal;
1585 }
1586 
1587 /*
1588  * \ingroup remote_pri_func
1589  *
1590  * \brief Set sampling parameters in the remote host.
1591  *
1592  * This function is called when the user wants to set activate sampling on the remote host.
1593  *
1594  * Sampling parameters are defined into the 'pcap_t' structure.
1595  *
1596  * \param p: the pcap_t descriptor of the device currently opened.
1597  *
1598  * \return '0' if everything is OK, '-1' is something goes wrong. The error message is returned
1599  * in the 'errbuf' member of the pcap_t structure.
1600  */
pcap_setsampling_remote(pcap_t * p)1601 static int pcap_setsampling_remote(pcap_t *p)
1602 {
1603 	int retval;						/* general variable used to keep the return value of other functions */
1604 	char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
1605 	int sendbufidx = 0;				/* index which keeps the number of bytes currently buffered */
1606 	struct rpcap_header header;		/* To keep the reply message */
1607 	struct rpcap_sampling *sampling_pars;	/* Structure that is needed to send sampling parameters to the remote host */
1608 	struct pcap_md *md;				/* structure used when doing a remote live capture */
1609 
1610 	md = (struct pcap_md *) ((u_char*)p->priv + sizeof(struct pcap_win));
1611 
1612 	/* If no samping is requested, return 'ok' */
1613 	if (md->rmt_samp.method == PCAP_SAMP_NOSAMP)
1614 		return 0;
1615 
1616 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1617 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, p->errbuf, PCAP_ERRBUF_SIZE))
1618 		return -1;
1619 
1620 	rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_SETSAMPLING_REQ, 0, sizeof(struct rpcap_sampling));
1621 
1622 	/* Fill the structure needed to open an adapter remotely */
1623 	sampling_pars = (struct rpcap_sampling *) &sendbuf[sendbufidx];
1624 
1625 	if (sock_bufferize(NULL, sizeof(struct rpcap_sampling), NULL,
1626 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, p->errbuf, PCAP_ERRBUF_SIZE))
1627 		return -1;
1628 
1629 	memset(sampling_pars, 0, sizeof(struct rpcap_sampling));
1630 
1631 	sampling_pars->method = md->rmt_samp.method;
1632 	sampling_pars->value = htonl(md->rmt_samp.value);
1633 
1634 	if (sock_send(md->rmt_sockctrl, sendbuf, sendbufidx, p->errbuf, PCAP_ERRBUF_SIZE))
1635 		return -1;
1636 
1637 	/* Waits for the answer */
1638 	if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
1639 		return -1;
1640 
1641 	/* Checks if the message is correct */
1642 	retval = rpcap_checkmsg(p->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_SETSAMPLING_REPLY, 0);
1643 
1644 	if (retval != RPCAP_MSG_SETSAMPLING_REPLY)		/* the message is not the one expected */
1645 	{
1646 		switch (retval)
1647 		{
1648 		case -3:		/* Unrecoverable network error */
1649 		case -2:		/* The other endpoint sent a message that is not allowed here */
1650 		case -1:		/* The other endpoint has a version number that is not compatible with our */
1651 		case RPCAP_MSG_ERROR:
1652 			/* Do nothing; just exit from here; the error code is already into the errbuf */
1653 			return -1;
1654 
1655 		default:
1656 			SOCK_ASSERT("Internal error", 0);
1657 			return -1;
1658 		}
1659 	}
1660 
1661 	if (ntohl(header.plen) != 0)	/* the message has an unexpected size */
1662 	{
1663 		if (sock_discard(md->rmt_sockctrl, ntohl(header.plen), p->errbuf, PCAP_ERRBUF_SIZE) == -1)
1664 			return -1;
1665 	}
1666 
1667 	return 0;
1668 
1669 }
1670 
1671 /*********************************************************
1672  *                                                       *
1673  * Miscellaneous functions                               *
1674  *                                                       *
1675  *********************************************************/
1676 
1677 
1678 /* \ingroup remote_pri_func
1679  * \brief It sends a RPCAP error to the other peer.
1680  *
1681  * This function has to be called when the main program detects an error. This function
1682  * will send on the other peer the 'buffer' specified by the user.
1683  * This function *does not* request a RPCAP CLOSE connection. A CLOSE command must be sent
1684  * explicitly by the program, since we do not know it the error can be recovered in some
1685  * way or it is a non-recoverable one.
1686  *
1687  * \param sock: the socket we are currently using.
1688  *
1689  * \param error: an user-allocated (and '0' terminated) buffer that contains the error
1690  * description that has to be transmitted on the other peer. The error message cannot
1691  * be longer than PCAP_ERRBUF_SIZE.
1692  *
1693  * \param errcode: a integer which tells the other party the type of error we had;
1694  * currently is is not too much used.
1695  *
1696  * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
1697  * that will contain the error message (in case there is one). It could be network problem.
1698  *
1699  * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
1700  * in the 'errbuf' variable.
1701  */
rpcap_senderror(SOCKET sock,char * error,unsigned short errcode,char * errbuf)1702 int rpcap_senderror(SOCKET sock, char *error, unsigned short errcode, char *errbuf)
1703 {
1704 	char sendbuf[RPCAP_NETBUF_SIZE];			/* temporary buffer in which data to be sent is buffered */
1705 	int sendbufidx = 0;							/* index which keeps the number of bytes currently buffered */
1706 	uint16 length;
1707 
1708 	length = (uint16)strlen(error);
1709 
1710 	if (length > PCAP_ERRBUF_SIZE)
1711 		length = PCAP_ERRBUF_SIZE;
1712 
1713 	rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_ERROR, errcode, length);
1714 
1715 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1716 		RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1717 		return -1;
1718 
1719 	if (sock_bufferize(error, length, sendbuf, &sendbufidx,
1720 		RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1721 		return -1;
1722 
1723 	if (sock_send(sock, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE))
1724 		return -1;
1725 
1726 	return 0;
1727 }
1728 
1729 /* \ingroup remote_pri_func
1730  * \brief Sends the authentication message.
1731  *
1732  * It sends the authentication parameters on the control socket.
1733  * This function is required in order to open the connection with the other end party.
1734  *
1735  * \param sock: the socket we are currently using.
1736  *
1737  * \param auth: authentication parameters that have to be sent.
1738  *
1739  * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
1740  * that will contain the error message (in case there is one). It could be network problem
1741  * of the fact that the authorization failed.
1742  *
1743  * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
1744  * in the 'errbuf' variable.
1745  * The error message could be also 'the authentication failed'.
1746  */
rpcap_sendauth(SOCKET sock,struct pcap_rmtauth * auth,char * errbuf)1747 int rpcap_sendauth(SOCKET sock, struct pcap_rmtauth *auth, char *errbuf)
1748 {
1749 	char sendbuf[RPCAP_NETBUF_SIZE];	/* temporary buffer in which data that has to be sent is buffered */
1750 	int sendbufidx = 0;					/* index which keeps the number of bytes currently buffered */
1751 	uint16 length;						/* length of the payload of this message */
1752 	struct rpcap_auth *rpauth;
1753 	uint16 auth_type;
1754 	struct rpcap_header header;
1755 	int retval;							/* temp variable which stores functions return value */
1756 
1757 	if (auth)
1758 	{
1759 		auth_type = auth->type;
1760 
1761 		switch (auth->type)
1762 		{
1763 		case RPCAP_RMTAUTH_NULL:
1764 			length = sizeof(struct rpcap_auth);
1765 			break;
1766 
1767 		case RPCAP_RMTAUTH_PWD:
1768 			length = sizeof(struct rpcap_auth);
1769 			if (auth->username) length += (uint16) strlen(auth->username);
1770 			if (auth->password) length += (uint16) strlen(auth->password);
1771 			break;
1772 
1773 		default:
1774 			pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized.");
1775 			return -1;
1776 		}
1777 	}
1778 	else
1779 	{
1780 		auth_type = RPCAP_RMTAUTH_NULL;
1781 		length = sizeof(struct rpcap_auth);
1782 	}
1783 
1784 
1785 	if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1786 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1787 		return -1;
1788 
1789 	rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_AUTH_REQ, 0, length);
1790 
1791 	rpauth = (struct rpcap_auth *) &sendbuf[sendbufidx];
1792 
1793 	if (sock_bufferize(NULL, sizeof(struct rpcap_auth), NULL,
1794 		&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1795 		return -1;
1796 
1797 	memset(rpauth, 0, sizeof(struct rpcap_auth));
1798 
1799 	rpauth->type = htons(auth_type);
1800 
1801 	if (auth_type == RPCAP_RMTAUTH_PWD)
1802 	{
1803 
1804 		if (auth->username)
1805 			rpauth->slen1 = (uint16) strlen(auth->username);
1806 		else
1807 			rpauth->slen1 = 0;
1808 
1809 		if (sock_bufferize(auth->username, rpauth->slen1, sendbuf,
1810 			&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1811 			return -1;
1812 
1813 		if (auth->password)
1814 			rpauth->slen2 = (uint16) strlen(auth->password);
1815 		else
1816 			rpauth->slen2 = 0;
1817 
1818 		if (sock_bufferize(auth->password, rpauth->slen2, sendbuf,
1819 			&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1820 			return -1;
1821 
1822 		rpauth->slen1 = htons(rpauth->slen1);
1823 		rpauth->slen2 = htons(rpauth->slen2);
1824 	}
1825 
1826 	if (sock_send(sock, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE))
1827 		return -1;
1828 
1829 	if (sock_recv(sock, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1)
1830 		return -1;
1831 
1832 	retval = rpcap_checkmsg(errbuf, sock, &header, RPCAP_MSG_AUTH_REPLY, RPCAP_MSG_ERROR, 0);
1833 
1834 	if (retval != RPCAP_MSG_AUTH_REPLY)		/* the message is not the one expected */
1835 	{
1836 		switch (retval)
1837 		{
1838 		case -3:		/* Unrecoverable network error */
1839 		case -2:		/* The other endpoint sent a message that is not allowed here */
1840 		case -1:		/* The other endpoint has a version number that is not compatible with our */
1841 			/* Do nothing; just exit from here; the error code is already into the errbuf */
1842 			return -1;
1843 
1844 		case RPCAP_MSG_ERROR:
1845 			return -1;
1846 
1847 		default:
1848 			SOCK_ASSERT("Internal error", 0);
1849 			return -1;
1850 		}
1851 	}
1852 
1853 	if (ntohl(header.plen))
1854 	{
1855 		if (sock_discard(sock, ntohl(header.plen), errbuf, PCAP_ERRBUF_SIZE))
1856 			return -1;
1857 	}
1858 
1859 	return 0;
1860 }
1861 
1862 /* \ingroup remote_pri_func
1863  * \brief Creates a structure of type rpcap_header.
1864  *
1865  * This function is provided just because the creation of an rpcap header is quite a common
1866  * task. It accepts all the values that appears into an rpcap_header, and it puts them in
1867  * place using the proper hton() calls.
1868  *
1869  * \param header: a pointer to a user-allocated buffer which will contain the serialized
1870  * header, ready to be sent on the network.
1871  *
1872  * \param type: a value (in the host by order) which will be placed into the header.type
1873  * field and that represents the type of the current message.
1874  *
1875  * \param value: a value (in the host by order) which will be placed into the header.value
1876  * field and that has a message-dependent meaning.
1877  *
1878  * \param length: a value (in the host by order) which will be placed into the header.length
1879  * field and that represents the payload length of the message.
1880  *
1881  * \return Nothing. The serialized header is returned into the 'header' variable.
1882  */
rpcap_createhdr(struct rpcap_header * header,uint8 type,uint16 value,uint32 length)1883 void rpcap_createhdr(struct rpcap_header *header, uint8 type, uint16 value, uint32 length)
1884 {
1885 	memset(header, 0, sizeof(struct rpcap_header));
1886 
1887 	header->ver = RPCAP_VERSION;
1888 	header->type = type;
1889 	header->value = htons(value);
1890 	header->plen = htonl(length);
1891 }
1892 
1893 /* ingroup remote_pri_func
1894  * \brief Checks if the header of the received message is correct.
1895  *
1896  * This function is a way to easily check if the message received, in a certain
1897  * state of the RPCAP protocol Finite State Machine, is valid. This function accepts,
1898  * as a parameter, the list of message types that are allowed in a certain situation,
1899  * and it returns the one which occurs.
1900  *
1901  * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
1902  * that will contain the error message (in case there is one). It could be either problem
1903  * occurred inside this function (e.g. a network problem in case it tries to send an
1904  * error on the other peer and the send() call fails), an error message which has been
1905  * sent to us from the other party, or a version error (the message receive has a version
1906  * number that is incompatible with our).
1907  *
1908  * \param sock: the socket that has to be used to receive data. This function can
1909  * read data from socket in case the version contained into the message is not compatible
1910  * with our. In that case, all the message is purged from the socket, so that the following
1911  * recv() calls will return a new message.
1912  *
1913  * \param header: a pointer to and 'rpcap_header' structure that keeps the data received from
1914  * the network (still in network byte order) and that has to be checked.
1915  *
1916  * \param first: this function has a variable number of parameters. From this point on,
1917  * all the messages that are valid in this context must be passed as parameters.
1918  * The message type list must be terminated with a '0' value, the null message type,
1919  * which means 'no more types to check'. The RPCAP protocol does not define anything with
1920  * message type equal to zero, so there is no ambiguity in using this value as a list terminator.
1921  *
1922  * \return The message type of the message that has been detected. In case of errors (e.g. the
1923  * header contains a type that is not listed among the allowed types), this function will
1924  * return the following codes:
1925  * - (-1) if the version is incompatible.
1926  * - (-2) if the code is not among the one listed into the parameters list
1927  * - (-3) if a network error (connection reset, ...)
1928  * - RPCAP_MSG_ERROR if the message is an error message (it follow that the RPCAP_MSG_ERROR
1929  * could not be present in the allowed message-types list, because this function checks
1930  * for errors anyway)
1931  *
1932  * In case either the version is incompatible or nothing matches (i.e. it returns '-1' or '-2'),
1933  * it discards the message body (i.e. it reads the remaining part of the message from the
1934  * network and it discards it) so that the application is ready to receive a new message.
1935  */
rpcap_checkmsg(char * errbuf,SOCKET sock,struct rpcap_header * header,uint8 first,...)1936 int rpcap_checkmsg(char *errbuf, SOCKET sock, struct rpcap_header *header, uint8 first, ...)
1937 {
1938 	va_list ap;
1939 	uint8 type;
1940 	int32 len;
1941 
1942 	va_start(ap, first);
1943 
1944 	/* Check if the present version of the protocol can handle this message */
1945 	if (rpcap_checkver(sock, header, errbuf))
1946 	{
1947 		SOCK_ASSERT(errbuf, 1);
1948 
1949 		va_end(ap);
1950 		return -1;
1951 	}
1952 
1953 	type = first;
1954 
1955 	while (type != 0)
1956 	{
1957 		/*
1958 		 * The message matches with one of the types listed
1959 		 * There is no need of conversions since both values are uint8
1960 		 *
1961 		 * Check if the other side reported an error.
1962 		 * If yes, it retrieves it and it returns it back to the caller
1963 		 */
1964 		if (header->type == RPCAP_MSG_ERROR)
1965 		{
1966 			len = ntohl(header->plen);
1967 
1968 			if (len >= PCAP_ERRBUF_SIZE)
1969 			{
1970 				if (sock_recv(sock, errbuf, PCAP_ERRBUF_SIZE - 1, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE))
1971 					return -3;
1972 
1973 				sock_discard(sock, len - (PCAP_ERRBUF_SIZE - 1), NULL, 0);
1974 
1975 				/* Put '\0' at the end of the string */
1976 				errbuf[PCAP_ERRBUF_SIZE - 1] = 0;
1977 			}
1978 			else
1979 			{
1980 				if (sock_recv(sock, errbuf, len, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1)
1981 					return -3;
1982 
1983 				/* Put '\0' at the end of the string */
1984 				errbuf[len] = 0;
1985 			}
1986 
1987 
1988 			va_end(ap);
1989 			return header->type;
1990 		}
1991 
1992 		if (header->type == type)
1993 		{
1994 			va_end(ap);
1995 			return header->type;
1996 		}
1997 
1998 		/* get next argument */
1999 		type = va_arg(ap, int);
2000 	}
2001 
2002 	/* we already have an error, so please discard this one */
2003 	sock_discard(sock, ntohl(header->plen), NULL, 0);
2004 
2005 	pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The other endpoint sent a message that is not allowed here.");
2006 	SOCK_ASSERT(errbuf, 1);
2007 
2008 	va_end(ap);
2009 	return -2;
2010 }
2011 
2012 /* \ingroup remote_pri_func
2013  * \brief Checks if the version contained into the message is compatible with
2014  * the one handled by this implementation.
2015  *
2016  * Right now, this function does not have any sophisticated task: if the versions
2017  * are different, it returns -1 and it discards the message.
2018  * It is expected that in the future this message will become more complex.
2019  *
2020  * \param sock: the socket that has to be used to receive data. This function can
2021  * read data from socket in case the version contained into the message is not compatible
2022  * with our. In that case, all the message is purged from the socket, so that the following
2023  * recv() calls will return a new (clean) message.
2024  *
2025  * \param header: a pointer to and 'rpcap_header' structure that keeps the data received from
2026  * the network (still in network byte order) and that has to be checked.
2027  *
2028  * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
2029  * that will contain the error message (in case there is one). The error message is
2030  * "incompatible version".
2031  *
2032  * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
2033  * in the 'errbuf' variable.
2034  */
rpcap_checkver(SOCKET sock,struct rpcap_header * header,char * errbuf)2035 static int rpcap_checkver(SOCKET sock, struct rpcap_header *header, char *errbuf)
2036 {
2037 	/*
2038 	 * This is a sample function.
2039 	 *
2040 	 * In the real world, you have to check at the type code,
2041 	 * and decide accordingly.
2042 	 */
2043 
2044 	if (header->ver != RPCAP_VERSION)
2045 	{
2046 		pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Incompatible version number: message discarded.");
2047 
2048 		/* we already have an error, so please discard this one */
2049 		sock_discard(sock, ntohl(header->plen), NULL, 0);
2050 		return -1;
2051 	}
2052 
2053 	return 0;
2054 }
2055 
2056 /* \ingroup remote_pri_func
2057  *
2058  * \brief It returns the socket currently used for this active connection
2059  * (active mode only) and provides an indication of whether this connection
2060  * is in active mode or not.
2061  *
2062  * This function is just for internal use; it returns the socket ID of the
2063  * active connection currently opened.
2064  *
2065  * \param host: a string that keeps the host name of the host for which we
2066  * want to get the socket ID for that active connection.
2067  *
2068  * \param isactive: a pointer to an int that is set to 1 if there's an
2069  * active connection to that host and 0 otherwise.
2070  *
2071  * \param errbuf: a pointer to a user-allocated buffer (of size
2072  * PCAP_ERRBUF_SIZE) that will contain the error message (in case
2073  * there is one).
2074  *
2075  * \return the socket identifier if everything is fine, '0' if this host
2076  * is not in the active host list. An indication of whether this host
2077  * is in the active host list is returned into the isactive variable.
2078  * It returns 'INVALID_SOCKET' in case of error. The error message is
2079  * returned into the errbuf variable.
2080  */
rpcap_remoteact_getsock(const char * host,int * isactive,char * errbuf)2081 SOCKET rpcap_remoteact_getsock(const char *host, int *isactive, char *errbuf)
2082 {
2083 	struct activehosts *temp;					/* temp var needed to scan the host list chain */
2084 	struct addrinfo hints, *addrinfo, *ai_next;	/* temp var needed to translate between hostname to its address */
2085 	int retval;
2086 
2087 	/* retrieve the network address corresponding to 'host' */
2088 	addrinfo = NULL;
2089 	memset(&hints, 0, sizeof(struct addrinfo));
2090 	hints.ai_family = PF_UNSPEC;
2091 	hints.ai_socktype = SOCK_STREAM;
2092 
2093 	retval = getaddrinfo(host, "0", &hints, &addrinfo);
2094 	if (retval != 0)
2095 	{
2096 		pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "getaddrinfo() %s", gai_strerror(retval));
2097 		*isactive = 0;
2098 		return INVALID_SOCKET;
2099 	}
2100 
2101 	temp = activeHosts;
2102 
2103 	while (temp)
2104 	{
2105 		ai_next = addrinfo;
2106 		while (ai_next)
2107 		{
2108 			if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0) {
2109 				*isactive = 1;
2110 				return (temp->sockctrl);
2111 			}
2112 
2113 			ai_next = ai_next->ai_next;
2114 		}
2115 		temp = temp->next;
2116 	}
2117 
2118 	if (addrinfo)
2119 		freeaddrinfo(addrinfo);
2120 
2121 	/*
2122 	 * The host for which you want to get the socket ID does not have an
2123 	 * active connection.
2124 	 */
2125 	*isactive = 0;
2126 	return 0;
2127 }
2128