]> The Tcpdump Group git mirrors - libpcap/blob - pcap-rpcap.c
Move rpcap-protocol.h to the top-level directory.
[libpcap] / pcap-rpcap.c
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 "sockutils.h"
44 #include "rpcap-protocol.h"
45 #include "pcap-rpcap-int.h"
46
47 /*
48 * \file pcap-rpcap.c
49 *
50 * This file keeps all the new functions that are needed for the RPCAP protocol.
51 * Almost all the pcap functions need to be modified in order to become compatible
52 * with the RPCAP protocol. However, you can find here only the ones that are completely new.
53 *
54 * This file keeps also the functions that are 'private', i.e. are needed by the RPCAP
55 * protocol but are not exported to the user.
56 *
57 * \warning All the RPCAP functions that are allowed to return a buffer containing
58 * the error description can return max PCAP_ERRBUF_SIZE characters.
59 * However there is no guarantees that the string will be zero-terminated.
60 * Best practice is to define the errbuf variable as a char of size 'PCAP_ERRBUF_SIZE+1'
61 * and to insert manually a NULL character at the end of the buffer. This will
62 * guarantee that no buffer overflows occur even if we use the printf() to show
63 * the error on the screen.
64 */
65
66 #define PCAP_STATS_STANDARD 0 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
67 #ifdef _WIN32
68 #define PCAP_STATS_EX 1 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
69 #endif
70
71 /* Keeps a list of all the opened connections in the active mode. */
72 struct activehosts *activeHosts;
73
74 /*
75 * Private data for capturing remotely using the rpcap protocol.
76 */
77 struct pcap_rpcap {
78 /*
79 * This is '1' if we're the network client; it is needed by several
80 * functions (such as pcap_setfilter()) to know whether they have
81 * to use the socket or have to open the local adapter.
82 */
83 int rmt_clientside;
84
85 SOCKET rmt_sockctrl; /* socket ID of the socket used for the control connection */
86 SOCKET rmt_sockdata; /* socket ID of the socket used for the data connection */
87 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() */
88 int rmt_capstarted; /* 'true' if the capture is already started (needed to knoe if we have to call the pcap_startcapture() */
89 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. */
90
91 unsigned int TotNetDrops; /* keeps the number of packets that have been dropped by the network */
92
93 /*
94 * This keeps the number of packets that have been received by the
95 * application.
96 *
97 * Packets dropped by the kernel buffer are not counted in this
98 * variable. It is always equal to (TotAccepted - TotDrops),
99 * except for the case of remote capture, in which we have also
100 * packets in flight, i.e. that have been transmitted by the remote
101 * host, but that have not been received (yet) from the client.
102 * In this case, (TotAccepted - TotDrops - TotNetDrops) gives a
103 * wrong result, since this number does not corresponds always to
104 * the number of packet received by the application. For this reason,
105 * in the remote capture we need another variable that takes into
106 * account of the number of packets actually received by the
107 * application.
108 */
109 unsigned int TotCapt;
110
111 struct pcap_stat stat;
112 /* XXX */
113 struct pcap *next; /* list of open pcaps that need stuff cleared on close */
114 };
115
116 /****************************************************
117 * *
118 * Locally defined functions *
119 * *
120 ****************************************************/
121 static int rpcap_checkver(SOCKET sock, struct rpcap_header *header, char *errbuf);
122 static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode);
123 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog);
124 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog);
125 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog);
126 static void pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter);
127 static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog);
128 static int pcap_setsampling_remote(pcap_t *p);
129
130 /****************************************************
131 * *
132 * Function bodies *
133 * *
134 ****************************************************/
135
136 /*
137 * \ingroup remote_pri_func
138 *
139 * \brief It traslates (i.e. de-serializes) a 'rpcap_sockaddr'
140 * structure from the network byte order to a 'sockaddr_in" or
141 * 'sockaddr_in6' structure in the host byte order.
142 *
143 * It accepts an 'rpcap_sockaddr' structure as it is received from the
144 * network, and checks the address family field against various values
145 * to see whether it looks like an IPv4 address, an IPv6 address, or
146 * neither of those. It checks for multiple values in order to try
147 * to handle older rpcap daemons that sent the native OS's 'sockaddr_in'
148 * or 'sockaddr_in6' structures over the wire with some members
149 * byte-swapped, and to handle the fact that AF_INET6 has different
150 * values on different OSes.
151 *
152 * For IPv4 addresses, it converts the address family to host byte
153 * order from network byte order and puts it into the structure,
154 * sets the length if a sockaddr structure has a length, converts the
155 * port number to host byte order from network byte order and puts
156 * it into the structure, copies over the IPv4 address, and zeroes
157 * out the zero padding.
158 *
159 * For IPv6 addresses, it converts the address family to host byte
160 * order from network byte order and puts it into the structure,
161 * sets the length if a sockaddr structure has a length, converts the
162 * port number and flow information to host byte order from network
163 * byte order and puts them into the structure, copies over the IPv6
164 * address, and converts the scope ID to host byte order from network
165 * byte order and puts it into the structure.
166 *
167 * The function will allocate the 'sockaddrout' variable according to the
168 * address family in use. In case the address does not belong to the
169 * AF_INET nor AF_INET6 families, 'sockaddrout' is not allocated and a
170 * NULL pointer is returned. This usually happens because that address
171 * does not exist on the other host, or is of an address family other
172 * than AF_INET or AF_INET6, so the RPCAP daemon sent a 'sockaddr_storage'
173 * structure containing all 'zero' values.
174 *
175 * Older RPCAPDs sent the addresses over the wire in the OS's native
176 * structure format. For most OSes, this looks like the over-the-wire
177 * format, but might have a different value for AF_INET6 than the value
178 * on the machine receiving the reply. For OSes with the newer BSD-style
179 * sockaddr structures, this has, instead of a 2-byte address family,
180 * a 1-byte structure length followed by a 1-byte address family. The
181 * RPCAPD code would put the address family in network byte order before
182 * sending it; that would set it to 0 on a little-endian machine, as
183 * htons() of any value between 1 and 255 would result in a value > 255,
184 * with its lower 8 bits zero, so putting that back into a 1-byte field
185 * would set it to 0.
186 *
187 * Therefore, for older RPCAPDs running on an OS with newer BSD-style
188 * sockaddr structures, the family field, if treated as a big-endian
189 * (network byte order) 16-bit field, would be:
190 *
191 * (length << 8) | family if sent by a big-endian machine
192 * (length << 8) if sent by a little-endian machine
193 *
194 * For current RPCAPDs, and for older RPCAPDs running on an OS with
195 * older BSD-style sockaddr structures, the family field, if treated
196 * as a big-endian 16-bit field, would just contain the family.
197 *
198 * \param sockaddrin: a 'rpcap_sockaddr' pointer to the variable that has
199 * to be de-serialized.
200 *
201 * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
202 * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
203 * This variable will be allocated automatically inside this function.
204 *
205 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
206 * that will contain the error message (in case there is one).
207 *
208 * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
209 * can be only the fact that the malloc() failed to allocate memory.
210 * The error message is returned in the 'errbuf' variable, while the deserialized address
211 * is returned into the 'sockaddrout' variable.
212 *
213 * \warning This function supports only AF_INET and AF_INET6 address families.
214 *
215 * \warning The sockaddrout (if not NULL) must be deallocated by the user.
216 */
217
218 /*
219 * Possible IPv4 family values other than the designated over-the-wire value,
220 * which is 2 (because everybody uses 2 for AF_INET4).
221 */
222 #define SOCKADDR_IN_LEN 16 /* length of struct sockaddr_in */
223 #define SOCKADDR_IN6_LEN 28 /* length of struct sockaddr_in6 */
224 #define NEW_BSD_AF_INET_BE ((SOCKADDR_IN_LEN << 8) | 2)
225 #define NEW_BSD_AF_INET_LE (SOCKADDR_IN_LEN << 8)
226
227 /*
228 * Possible IPv6 family values other than the designated over-the-wire value,
229 * which is 23 (because that's what Windows uses, and most RPCAP servers
230 * out there are probably running Windows, as WinPcap includes the server
231 * but few if any UN*Xes build and ship it).
232 *
233 * The new BSD sockaddr structure format was in place before 4.4-Lite, so
234 * all the free-software BSDs use it.
235 */
236 #define NEW_BSD_AF_INET6_BSD_BE ((SOCKADDR_IN6_LEN << 8) | 24) /* NetBSD, OpenBSD, BSD/OS */
237 #define NEW_BSD_AF_INET6_FREEBSD_BE ((SOCKADDR_IN6_LEN << 8) | 28) /* FreeBSD, DragonFly BSD */
238 #define NEW_BSD_AF_INET6_DARWIN_BE ((SOCKADDR_IN6_LEN << 8) | 30) /* macOS, iOS, anything else Darwin-based */
239 #define NEW_BSD_AF_INET6_LE (SOCKADDR_IN6_LEN << 8)
240 #define LINUX_AF_INET6 10
241 #define HPUX_AF_INET6 22
242 #define AIX_AF_INET6 24
243 #define SOLARIS_AF_INET6 26
244
245 int rpcap_deseraddr(struct rpcap_sockaddr *sockaddrin, struct sockaddr_storage **sockaddrout, char *errbuf)
246 {
247 /* Warning: we support only AF_INET and AF_INET6 */
248 switch (ntohs(sockaddrin->family))
249 {
250 case RPCAP_AF_INET:
251 case NEW_BSD_AF_INET_BE:
252 case NEW_BSD_AF_INET_LE:
253 {
254 struct rpcap_sockaddr_in *sockaddrin_ipv4;
255 struct sockaddr_in *sockaddrout_ipv4;
256
257 (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in));
258 if ((*sockaddrout) == NULL)
259 {
260 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
261 return -1;
262 }
263 sockaddrin_ipv4 = (struct rpcap_sockaddr_in *) sockaddrin;
264 sockaddrout_ipv4 = (struct sockaddr_in *) (*sockaddrout);
265 sockaddrout_ipv4->sin_family = AF_INET;
266 sockaddrout_ipv4->sin_port = ntohs(sockaddrin_ipv4->port);
267 memcpy(&sockaddrout_ipv4->sin_addr, &sockaddrin_ipv4->addr, sizeof(sockaddrout_ipv4->sin_addr));
268 memset(sockaddrout_ipv4->sin_zero, 0, sizeof(sockaddrout_ipv4->sin_zero));
269 break;
270 }
271
272 #ifdef AF_INET6
273 case RPCAP_AF_INET6:
274 case NEW_BSD_AF_INET6_BSD_BE:
275 case NEW_BSD_AF_INET6_FREEBSD_BE:
276 case NEW_BSD_AF_INET6_DARWIN_BE:
277 case NEW_BSD_AF_INET6_LE:
278 case LINUX_AF_INET6:
279 case HPUX_AF_INET6:
280 case AIX_AF_INET6:
281 case SOLARIS_AF_INET6:
282 {
283 struct rpcap_sockaddr_in6 *sockaddrin_ipv6;
284 struct sockaddr_in6 *sockaddrout_ipv6;
285
286 (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in6));
287 if ((*sockaddrout) == NULL)
288 {
289 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
290 return -1;
291 }
292 sockaddrin_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrin;
293 sockaddrout_ipv6 = (struct sockaddr_in6 *) (*sockaddrout);
294 sockaddrout_ipv6->sin6_family = AF_INET6;
295 sockaddrout_ipv6->sin6_port = ntohs(sockaddrin_ipv6->port);
296 sockaddrout_ipv6->sin6_flowinfo = ntohl(sockaddrin_ipv6->flowinfo);
297 memcpy(&sockaddrout_ipv6->sin6_addr, &sockaddrin_ipv6->addr, sizeof(sockaddrout_ipv6->sin6_addr));
298 sockaddrout_ipv6->sin6_scope_id = ntohl(sockaddrin_ipv6->scope_id);
299 break;
300 }
301 #endif
302
303 default:
304 /*
305 * It is neither AF_INET nor AF_INET6 (or, if the OS doesn't
306 * support AF_INET6, it's not AF_INET).
307 */
308 *sockaddrout = NULL;
309 break;
310 }
311 return 0;
312 }
313
314 /* \ingroup remote_pri_func
315 *
316 * \brief It reads a packet from the network socket. This does not make use of
317 * callback (hence the "nocb" string into its name).
318 *
319 * This function is called by the several pcap_next_ex() when they detect that
320 * we have a remote capture and they are the client side. In that case, they need
321 * to read packets from the socket.
322 *
323 * Parameters and return values are exactly the same of the pcap_next_ex().
324 *
325 * \warning By choice, this function does not make use of semaphores. A smarter
326 * implementation should put a semaphore into the data thread, and a signal will
327 * be raised as soon as there is data into the socket buffer.
328 * However this is complicated and it does not bring any advantages when reading
329 * from the network, in which network delays can be much more important than
330 * these optimizations. Therefore, we chose the following approach:
331 * - the 'timeout' chosen by the user is split in two (half on the server side,
332 * with the usual meaning, and half on the client side)
333 * - this function checks for packets; if there are no packets, it waits for
334 * timeout/2 and then it checks again. If packets are still missing, it returns,
335 * otherwise it reads packets.
336 */
337 static int pcap_read_nocb_remote(pcap_t *p, struct pcap_pkthdr **pkt_header, u_char **pkt_data)
338 {
339 struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
340 struct rpcap_header *header; /* general header according to the RPCAP format */
341 struct rpcap_pkthdr *net_pkt_header; /* header of the packet */
342 char netbuf[RPCAP_NETBUF_SIZE]; /* size of the network buffer in which the packet is copied, just for UDP */
343 uint32 totread; /* number of bytes (of payload) currently read from the network (referred to the current pkt) */
344 int nread;
345 int retval; /* generic return value */
346
347 /* Structures needed for the select() call */
348 struct timeval tv; /* maximum time the select() can block waiting for data */
349 fd_set rfds; /* set of socket descriptors we have to check */
350
351 /*
352 * Define the packet buffer timeout, to be used in the select()
353 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
354 */
355 tv.tv_sec = p->opt.timeout / 1000;
356 tv.tv_usec = (p->opt.timeout - tv.tv_sec * 1000) * 1000;
357
358 /* Watch out sockdata to see if it has input */
359 FD_ZERO(&rfds);
360
361 /*
362 * 'fp->rmt_sockdata' has always to be set before calling the select(),
363 * since it is cleared by the select()
364 */
365 FD_SET(pr->rmt_sockdata, &rfds);
366
367 retval = select((int) pr->rmt_sockdata + 1, &rfds, NULL, NULL, &tv);
368 if (retval == -1)
369 {
370 sock_geterror("select(): ", p->errbuf, PCAP_ERRBUF_SIZE);
371 return -1;
372 }
373
374 /* There is no data waiting, so return '0' */
375 if (retval == 0)
376 return 0;
377
378 /*
379 * data is here; so, let's copy it into the user buffer.
380 * I'm going to read a new packet; so I reset the number of bytes (payload only) read
381 */
382 totread = 0;
383
384 /*
385 * We have to define 'header' as a pointer to a larger buffer,
386 * because in case of UDP we have to read all the message within a single call
387 */
388 header = (struct rpcap_header *) netbuf;
389 net_pkt_header = (struct rpcap_pkthdr *) (netbuf + sizeof(struct rpcap_header));
390
391 if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
392 {
393 /* Read the entire message from the network */
394 if (sock_recv(pr->rmt_sockdata, netbuf, RPCAP_NETBUF_SIZE, SOCK_RECEIVEALL_NO, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
395 return -1;
396 }
397 else
398 {
399 if (sock_recv(pr->rmt_sockdata, netbuf, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
400 return -1;
401 }
402
403 /* Checks if the message is correct */
404 retval = rpcap_checkmsg(p->errbuf, pr->rmt_sockdata, header, RPCAP_MSG_PACKET, 0);
405
406 if (retval != RPCAP_MSG_PACKET) /* the message is not the one expected */
407 {
408 switch (retval)
409 {
410 case -3: /* Unrecoverable network error */
411 return -1; /* Do nothing; just exit from here; the error code is already into the errbuf */
412
413 case -2: /* The other endpoint sent a message that is not allowed here */
414 case -1: /* The other endpoint has a version number that is not compatible with our */
415 return 0; /* Return 'no packets received' */
416
417 default:
418 SOCK_ASSERT("Internal error", 1);
419 return 0; /* Return 'no packets received' */
420 }
421 }
422
423 /* In case of TCP, read the remaining of the packet from the socket */
424 if (!(pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
425 {
426 /* Read the RPCAP packet header from the network */
427 nread = sock_recv(pr->rmt_sockdata, (char *)net_pkt_header,
428 sizeof(struct rpcap_pkthdr), SOCK_RECEIVEALL_YES,
429 p->errbuf, PCAP_ERRBUF_SIZE);
430 if (nread == -1)
431 return -1;
432 totread += nread;
433 }
434
435 if ((ntohl(net_pkt_header->caplen) + sizeof(struct pcap_pkthdr)) <= p->bufsize)
436 {
437 /* Initialize returned structures */
438 *pkt_header = (struct pcap_pkthdr *) p->buffer;
439 *pkt_data = (u_char*)p->buffer + sizeof(struct pcap_pkthdr);
440
441 (*pkt_header)->caplen = ntohl(net_pkt_header->caplen);
442 (*pkt_header)->len = ntohl(net_pkt_header->len);
443 (*pkt_header)->ts.tv_sec = ntohl(net_pkt_header->timestamp_sec);
444 (*pkt_header)->ts.tv_usec = ntohl(net_pkt_header->timestamp_usec);
445
446 /*
447 * I don't update the counter of the packets dropped by the network since we're using TCP,
448 * therefore no packets are dropped. Just update the number of packets received correctly
449 */
450 pr->TotCapt++;
451
452 /* Copies the packet into the data buffer */
453 if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
454 {
455 unsigned int npkt;
456
457 /*
458 * In case of UDP the packet has already been read, we have to copy it into 'buffer'.
459 * Another option should be to declare 'netbuf' as 'static'. However this prevents
460 * using several pcap instances within the same process (because the static buffer is shared among
461 * all processes)
462 */
463 memcpy(*pkt_data, netbuf + sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr), (*pkt_header)->caplen);
464
465 /* We're using UDP, so we need to update the counter of the packets dropped by the network */
466 npkt = ntohl(net_pkt_header->npkt);
467
468 if (pr->TotCapt != npkt)
469 {
470 pr->TotNetDrops += (npkt - pr->TotCapt);
471 pr->TotCapt = npkt;
472 }
473 }
474 else
475 {
476 /* In case of TCP, read the remaining of the packet from the socket */
477 nread = sock_recv(pr->rmt_sockdata, *pkt_data,
478 (*pkt_header)->caplen, SOCK_RECEIVEALL_YES,
479 p->errbuf, PCAP_ERRBUF_SIZE);
480 if (nread == -1)
481 return -1;
482 totread += nread;
483
484 /* Checks if all the data has been read; if not, discard the data in excess */
485 /* This check has to be done only on TCP connections */
486 if (totread != ntohl(header->plen))
487 sock_discard(pr->rmt_sockdata, ntohl(header->plen) - totread, NULL, 0);
488 }
489
490 /* Packet read successfully */
491 return 1;
492 }
493 else
494 {
495 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Received a packet that is larger than the internal buffer size.");
496 return -1;
497 }
498 }
499
500 /* \ingroup remote_pri_func
501 *
502 * \brief It reads a packet from the network socket.
503 *
504 * This function is called by the several pcap_read() when they detect that
505 * we have a remote capture and they are the client side. In that case, they need
506 * to read packets from the socket.
507 *
508 * This function relies on the pcap_read_nocb_remote to deliver packets. The
509 * difference, here, is that as soon as a packet is read, it is delivered
510 * to the application by means of a callback function.
511 *
512 * Parameters and return values are exactly the same of the pcap_read().
513 */
514 static int pcap_read_rpcap(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
515 {
516 struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
517 struct pcap_pkthdr *pkt_header;
518 u_char *pkt_data;
519 int n = 0;
520
521 /*
522 * If this is client-side, and we haven't already started
523 * the capture, start it now.
524 */
525 if (pr->rmt_clientside)
526 {
527 /* We are on an remote capture */
528 if (!pr->rmt_capstarted)
529 {
530 /*
531 * The capture isn't started yet, so try to
532 * start it.
533 */
534 if (pcap_startcapture_remote(p))
535 return -1;
536 }
537 }
538
539 while (n < cnt || PACKET_COUNT_IS_UNLIMITED(cnt))
540 {
541 /*
542 * Has "pcap_breakloop()" been called?
543 */
544 if (p->break_loop) {
545 /*
546 * Yes - clear the flag that indicates that it
547 * has, and return PCAP_ERROR_BREAK to indicate
548 * that we were told to break out of the loop.
549 */
550 p->break_loop = 0;
551 return (PCAP_ERROR_BREAK);
552 }
553
554 /*
555 * Read some packets.
556 */
557 if (pcap_read_nocb_remote(p, &pkt_header, &pkt_data) == 1)
558 {
559 (*callback)(user, pkt_header, pkt_data);
560 n++;
561 }
562 else
563 return n;
564 }
565 return n;
566 }
567
568 /* \ingroup remote_pri_func
569 *
570 * \brief It sends a CLOSE command to the capture server.
571 *
572 * This function is called when the user wants to close a pcap_t adapter.
573 * In case we're capturing from the network, it sends a command to the other
574 * peer that says 'ok, let's stop capturing'.
575 * This function is called automatically when the user calls the pcap_close().
576 *
577 * Parameters and return values are exactly the same of the pcap_close().
578 *
579 * \warning Since we're closing the connection, we do not check for errors.
580 */
581 static void pcap_cleanup_rpcap(pcap_t *fp)
582 {
583 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
584 struct rpcap_header header; /* header of the RPCAP packet */
585 struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
586 int active = 0; /* active mode or not? */
587
588 /* detect if we're in active mode */
589 temp = activeHosts;
590 while (temp)
591 {
592 if (temp->sockctrl == pr->rmt_sockctrl)
593 {
594 active = 1;
595 break;
596 }
597 temp = temp->next;
598 }
599
600 if (!active)
601 {
602 rpcap_createhdr(&header, RPCAP_MSG_CLOSE, 0, 0);
603
604 /* I don't check for errors, since I'm going to close everything */
605 sock_send(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), NULL, 0);
606 }
607 else
608 {
609 rpcap_createhdr(&header, RPCAP_MSG_ENDCAP_REQ, 0, 0);
610
611 /* I don't check for errors, since I'm going to close everything */
612 sock_send(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), NULL, 0);
613
614 /* wait for the answer */
615 /* Don't check what we got, since the present libpcap does not uses this pcap_t anymore */
616 sock_recv(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, NULL, 0);
617
618 if (ntohl(header.plen) != 0)
619 sock_discard(pr->rmt_sockctrl, ntohl(header.plen), NULL, 0);
620 }
621
622 if (pr->rmt_sockdata)
623 {
624 sock_close(pr->rmt_sockdata, NULL, 0);
625 pr->rmt_sockdata = 0;
626 }
627
628 if ((!active) && (pr->rmt_sockctrl))
629 sock_close(pr->rmt_sockctrl, NULL, 0);
630
631 pr->rmt_sockctrl = 0;
632
633 if (pr->currentfilter)
634 {
635 free(pr->currentfilter);
636 pr->currentfilter = NULL;
637 }
638
639 /* To avoid inconsistencies in the number of sock_init() */
640 sock_cleanup();
641 }
642
643 /* \ingroup remote_pri_func
644 *
645 * \brief It retrieves network statistics from the other peer.
646 *
647 * This function is just a void cointainer, since the work is done by the rpcap_stats_rpcap().
648 * See that funcion for more details.
649 *
650 * Parameters and return values are exactly the same of the pcap_stats().
651 */
652 static int pcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps)
653 {
654 struct pcap_stat *retval;
655
656 retval = rpcap_stats_rpcap(p, ps, PCAP_STATS_STANDARD);
657
658 if (retval)
659 return 0;
660 else
661 return -1;
662 }
663
664 #ifdef _WIN32
665 /* \ingroup remote_pri_func
666 *
667 * \brief It retrieves network statistics from the other peer.
668 *
669 * This function is just a void cointainer, since the work is done by the rpcap_stats_rpcap().
670 * See that funcion for more details.
671 *
672 * Parameters and return values are exactly the same of the pcap_stats_ex().
673 */
674 static struct pcap_stat *pcap_stats_ex_rpcap(pcap_t *p, int *pcap_stat_size)
675 {
676 *pcap_stat_size = sizeof (p->stat);
677
678 /* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
679 return (rpcap_stats_rpcap(p, &(p->stat), PCAP_STATS_EX));
680 }
681 #endif
682
683 /* \ingroup remote_pri_func
684 *
685 * \brief It retrieves network statistics from the other peer.
686 *
687 * This function can be called in two modes:
688 * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e. the pcap_stats() )
689 * - PCAP_STATS_EX: if we want extended statistics (i.e. the pcap_stats_ex() )
690 *
691 * This 'mode' parameter is needed because in the standard pcap_stats() the variable that keeps the
692 * statistics is allocated by the user. Unfortunately, this structure has been extended in order
693 * to keep new stats. However, if the user has a smaller structure and it passes it to the pcap_stats,
694 * thid function will try to fill in more data than the size of the structure, so that the application
695 * goes in memory overflow.
696 * So, we need to know it we have to copy just the standard fields, or the extended fields as well.
697 *
698 * In case we want to copy the extended fields as well, the problem of memory overflow does no
699 * longer exist because the structure pcap_stat is no longer allocated by the program;
700 * it is allocated by the library instead.
701 *
702 * \param p: the pcap_t structure related to the current instance.
703 *
704 * \param ps: a 'pcap_stat' structure, needed for compatibility with pcap_stat(), in which
705 * the structure is allocated by the user. In case of pcap_stats_ex, this structure and the
706 * function return value point to the same variable.
707 *
708 * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
709 *
710 * \return The structure that keeps the statistics, or NULL in case of error.
711 * The error string is placed in the pcap_t structure.
712 */
713 static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode)
714 {
715 struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
716 struct rpcap_header header; /* header of the RPCAP packet */
717 struct rpcap_stats netstats; /* statistics sent on the network */
718 uint32 totread = 0; /* number of bytes of the payload read from the socket */
719 int nread;
720 int retval; /* temp variable which stores functions return value */
721
722 /*
723 * If the capture has still to start, we cannot ask statistics to the other peer,
724 * so we return a fake number
725 */
726 if (!pr->rmt_capstarted)
727 {
728 ps->ps_drop = 0;
729 ps->ps_ifdrop = 0;
730 ps->ps_recv = 0;
731 #if defined(_WIN32) && defined(HAVE_REMOTE)
732 if (mode == PCAP_STATS_EX)
733 {
734 ps->ps_capt = 0;
735 ps->ps_sent = 0;
736 ps->ps_netdrop = 0;
737 }
738 #endif /* _WIN32 && HAVE_REMOTE */
739
740 return ps;
741 }
742
743 rpcap_createhdr(&header, RPCAP_MSG_STATS_REQ, 0, 0);
744
745 /* Send the PCAP_STATS command */
746 if (sock_send(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), p->errbuf, PCAP_ERRBUF_SIZE))
747 goto error;
748
749 /* Receive the RPCAP stats reply message */
750 if (sock_recv(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
751 goto error;
752
753 /* Checks if the message is correct */
754 retval = rpcap_checkmsg(p->errbuf, pr->rmt_sockctrl, &header, RPCAP_MSG_STATS_REPLY, RPCAP_MSG_ERROR, 0);
755
756 if (retval != RPCAP_MSG_STATS_REPLY) /* the message is not the one expected */
757 {
758 switch (retval)
759 {
760 case -3: /* Unrecoverable network error */
761 case -2: /* The other endpoint send a message that is not allowed here */
762 case -1: /* The other endpoint has a version number that is not compatible with our */
763 goto error;
764
765 case RPCAP_MSG_ERROR: /* The other endpoint reported an error */
766 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
767 totread = ntohl(header.plen);
768
769 /* Do nothing; just exit; the error code is already into the errbuf */
770 goto error;
771
772 default:
773 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
774 goto error;
775 }
776 }
777
778 nread = sock_recv(pr->rmt_sockctrl, (char *)&netstats,
779 sizeof(struct rpcap_stats), SOCK_RECEIVEALL_YES,
780 p->errbuf, PCAP_ERRBUF_SIZE);
781 if (nread == -1)
782 goto error;
783 totread += nread;
784
785 ps->ps_drop = ntohl(netstats.krnldrop);
786 ps->ps_ifdrop = ntohl(netstats.ifdrop);
787 ps->ps_recv = ntohl(netstats.ifrecv);
788 #if defined(_WIN32) && defined(HAVE_REMOTE)
789 if (mode == PCAP_STATS_EX)
790 {
791 ps->ps_capt = pr->TotCapt;
792 ps->ps_netdrop = pr->TotNetDrops;
793 ps->ps_sent = ntohl(netstats.svrcapt);
794 }
795 #endif /* _WIN32 && HAVE_REMOTE */
796
797 /* Checks if all the data has been read; if not, discard the data in excess */
798 if (totread != ntohl(header.plen))
799 {
800 if (sock_discard(pr->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
801 goto error;
802 }
803
804 return ps;
805
806 error:
807 if (totread != ntohl(header.plen))
808 sock_discard(pr->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0);
809
810 return NULL;
811 }
812
813 /* \ingroup remote_pri_func
814 *
815 * \brief It opens a remote adapter by opening an RPCAP connection and so on.
816 *
817 * This function does basically the job of pcap_open_live() for a remote interface.
818 * In other words, we have a pcap_read for win32, which reads packets from NPF,
819 * another for LINUX, and so on. Now, we have a pcap_opensource_remote() as well.
820 * The difference, here, is the capture thread does not start until the
821 * pcap_startcapture_remote() is called.
822 *
823 * This is because, in remote capture, we cannot start capturing data as soon as the
824 * 'open adapter' command is sent. Suppose the remote adapter is already overloaded;
825 * if we start a capture (which, by default, has a NULL filter) the new traffic can
826 * saturate the network.
827 *
828 * Instead, we want to "open" the adapter, then send a "start capture" command only
829 * when we're ready to start the capture.
830 * This function does this job: it sends an "open adapter" command (according to the
831 * RPCAP protocol), but it does not start the capture.
832 *
833 * Since the other libpcap functions do not share this way of life, we have to make
834 * some dirty things in order to make everyting working.
835 *
836 * \param fp: A pointer to a pcap_t structure that has been previously created with
837 * \ref pcap_create().
838 * \param source: see pcap_open().
839 * \param auth: see pcap_open().
840 *
841 * \return 0 in case of success, -1 otherwise. In case of success, the pcap_t pointer in fp can be
842 * used as a parameter to the following calls (pcap_compile() and so on). In case of
843 * problems, fp->errbuf contains a text explanation of error.
844 *
845 * \warning In case we call the pcap_compile() and the capture is not started, the filter
846 * will be saved into the pcap_t structure, and it will be sent to the other host later
847 * (when the pcap_startcapture_remote() is called).
848 */
849 int pcap_opensource_remote(pcap_t *fp, struct pcap_rmtauth *auth)
850 {
851 char host[PCAP_BUF_SIZE], ctrlport[PCAP_BUF_SIZE], iface[PCAP_BUF_SIZE];
852
853 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
854 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
855 uint32 totread = 0; /* number of bytes of the payload read from the socket */
856 int nread;
857 int retval; /* store the return value of the functions */
858 int active = 0; /* '1' if we're in active mode */
859
860 /* socket-related variables */
861 struct addrinfo hints; /* temp, needed to open a socket connection */
862 struct addrinfo *addrinfo; /* temp, needed to open a socket connection */
863 SOCKET sockctrl = 0; /* socket descriptor of the control connection */
864
865 /* RPCAP-related variables */
866 struct rpcap_header header; /* header of the RPCAP packet */
867 struct rpcap_openreply openreply; /* open reply message */
868
869 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
870
871 /*
872 * determine the type of the source (NULL, file, local, remote)
873 * You must have a valid source string even if we're in active mode, because otherwise
874 * the call to the following function will fail.
875 */
876 if (pcap_parsesrcstr(fp->opt.device, &retval, host, ctrlport, iface, fp->errbuf) == -1)
877 return -1;
878
879 if (retval != PCAP_SRC_IFREMOTE)
880 {
881 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "This function is able to open only remote interfaces");
882 return -1;
883 }
884
885 addrinfo = NULL;
886
887 /*
888 * Warning: this call can be the first one called by the user.
889 * For this reason, we have to initialize the WinSock support.
890 */
891 if (sock_init(fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
892 return -1;
893
894 sockctrl = rpcap_remoteact_getsock(host, &active, fp->errbuf);
895 if (sockctrl == INVALID_SOCKET)
896 return -1;
897
898 if (!active)
899 {
900 /*
901 * We're not in active mode; let's try to open a new
902 * control connection.
903 */
904 memset(&hints, 0, sizeof(struct addrinfo));
905 hints.ai_family = PF_UNSPEC;
906 hints.ai_socktype = SOCK_STREAM;
907
908 if (ctrlport[0] == 0)
909 {
910 /* the user chose not to specify the port */
911 if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
912 return -1;
913 }
914 else
915 {
916 /* the user chose not to specify the port */
917 if (sock_initaddress(host, ctrlport, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
918 return -1;
919 }
920
921 if ((sockctrl = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
922 goto error;
923
924 freeaddrinfo(addrinfo);
925 addrinfo = NULL;
926
927 if (rpcap_sendauth(sockctrl, auth, fp->errbuf) == -1)
928 goto error;
929 }
930
931 /*
932 * Now it's time to start playing with the RPCAP protocol
933 * RPCAP open command: create the request message
934 */
935 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
936 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
937 goto error;
938
939 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_OPEN_REQ, 0, (uint32) strlen(iface));
940
941 if (sock_bufferize(iface, (int) strlen(iface), sendbuf, &sendbufidx,
942 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, fp->errbuf, PCAP_ERRBUF_SIZE))
943 goto error;
944
945 if (sock_send(sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
946 goto error;
947
948 /* Receive the RPCAP open reply message */
949 if (sock_recv(sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
950 goto error;
951
952 /* Checks if the message is correct */
953 retval = rpcap_checkmsg(fp->errbuf, sockctrl, &header, RPCAP_MSG_OPEN_REPLY, RPCAP_MSG_ERROR, 0);
954
955 if (retval != RPCAP_MSG_OPEN_REPLY) /* the message is not the one expected */
956 {
957 switch (retval)
958 {
959 case -3: /* Unrecoverable network error */
960 case -2: /* The other endpoint send a message that is not allowed here */
961 case -1: /* The other endpoint has a version number that is not compatible with our */
962 goto error;
963
964 case RPCAP_MSG_ERROR: /* The other endpoint reported an error */
965 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
966 totread = ntohl(header.plen);
967 /* Do nothing; just exit; the error code is already into the errbuf */
968 goto error;
969
970 default:
971 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
972 goto error;
973 }
974 }
975
976 nread = sock_recv(sockctrl, (char *)&openreply,
977 sizeof(struct rpcap_openreply), SOCK_RECEIVEALL_YES,
978 fp->errbuf, PCAP_ERRBUF_SIZE);
979 if (nread == -1)
980 goto error;
981 totread += nread;
982
983 /* Set proper fields into the pcap_t struct */
984 fp->linktype = ntohl(openreply.linktype);
985 fp->tzoff = ntohl(openreply.tzoff);
986 pr->rmt_sockctrl = sockctrl;
987 pr->rmt_clientside = 1;
988
989 /* This code is duplicated from the end of this function */
990 fp->read_op = pcap_read_rpcap;
991 fp->save_current_filter_op = pcap_save_current_filter_rpcap;
992 fp->setfilter_op = pcap_setfilter_rpcap;
993 fp->getnonblock_op = NULL; /* This is not implemented in remote capture */
994 fp->setnonblock_op = NULL; /* This is not implemented in remote capture */
995 fp->stats_op = pcap_stats_rpcap;
996 #ifdef _WIN32
997 fp->stats_ex_op = pcap_stats_ex_rpcap;
998 #endif
999 fp->cleanup_op = pcap_cleanup_rpcap;
1000
1001 /* Checks if all the data has been read; if not, discard the data in excess */
1002 if (totread != ntohl(header.plen))
1003 {
1004 if (sock_discard(sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
1005 goto error;
1006 }
1007 return 0;
1008
1009 error:
1010 /*
1011 * When the connection has been established, we have to close it. So, at the
1012 * beginning of this function, if an error occur we return immediately with
1013 * a return NULL; when the connection is established, we have to come here
1014 * ('goto error;') in order to close everything properly.
1015 *
1016 * Checks if all the data has been read; if not, discard the data in excess
1017 */
1018 if (totread != ntohl(header.plen))
1019 sock_discard(sockctrl, ntohl(header.plen) - totread, NULL, 0);
1020
1021 if (addrinfo)
1022 freeaddrinfo(addrinfo);
1023
1024 if (!active)
1025 sock_close(sockctrl, NULL, 0);
1026
1027 return -1;
1028 }
1029
1030 /* \ingroup remote_pri_func
1031 *
1032 * \brief It starts a remote capture.
1033 *
1034 * This function is required since the RPCAP protocol decouples the 'open' from the
1035 * 'start capture' functions.
1036 * This function takes all the parameters needed (which have been stored into the pcap_t structure)
1037 * and sends them to the server.
1038 * If everything is fine, it creates a new child thread that reads data from the network
1039 * and puts the data into the user buffer.
1040 * The pcap_read() will read data from the user buffer, as usual.
1041 *
1042 * The remote capture acts like a new "kernel", which puts packets directly into
1043 * the buffer pointed by pcap_t.
1044 * In fact, this function does not rely on a kernel that reads packets and puts them
1045 * into the user buffer; it has to do that on its own.
1046 *
1047 * \param fp: the pcap_t descriptor of the device currently open.
1048 *
1049 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1050 * is returned into the 'errbuf' field of the pcap_t structure.
1051 */
1052 int pcap_startcapture_remote(pcap_t *fp)
1053 {
1054 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1055 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
1056 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1057 char portdata[PCAP_BUF_SIZE]; /* temp variable needed to keep the network port for the data connection */
1058 uint32 totread = 0; /* number of bytes of the payload read from the socket */
1059 int nread;
1060 int retval; /* store the return value of the functions */
1061 int active = 0; /* '1' if we're in active mode */
1062 struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
1063 char host[INET6_ADDRSTRLEN + 1]; /* numeric name of the other host */
1064
1065 /* socket-related variables*/
1066 struct addrinfo hints; /* temp, needed to open a socket connection */
1067 struct addrinfo *addrinfo; /* temp, needed to open a socket connection */
1068 SOCKET sockdata = 0; /* socket descriptor of the data connection */
1069 struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
1070 socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
1071 int ai_family; /* temp, keeps the address family used by the control connection */
1072
1073 /* RPCAP-related variables*/
1074 struct rpcap_header header; /* header of the RPCAP packet */
1075 struct rpcap_startcapreq *startcapreq; /* start capture request message */
1076 struct rpcap_startcapreply startcapreply; /* start capture reply message */
1077
1078 /* Variables related to the buffer setting */
1079 int res;
1080 socklen_t itemp;
1081 int sockbufsize = 0;
1082
1083 /*
1084 * Let's check if sampling has been required.
1085 * If so, let's set it first
1086 */
1087 if (pcap_setsampling_remote(fp) != 0)
1088 return -1;
1089
1090 /* detect if we're in active mode */
1091 temp = activeHosts;
1092 while (temp)
1093 {
1094 if (temp->sockctrl == pr->rmt_sockctrl)
1095 {
1096 active = 1;
1097 break;
1098 }
1099 temp = temp->next;
1100 }
1101
1102 addrinfo = NULL;
1103
1104 /*
1105 * Gets the complete sockaddr structure used in the ctrl connection
1106 * This is needed to get the address family of the control socket
1107 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
1108 * since the ctrl socket can already be open in case of active mode;
1109 * so I would have to call getpeername() anyway
1110 */
1111 saddrlen = sizeof(struct sockaddr_storage);
1112 if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1113 {
1114 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1115 goto error;
1116 }
1117 ai_family = ((struct sockaddr_storage *) &saddr)->ss_family;
1118
1119 /* Get the numeric address of the remote host we are connected to */
1120 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, host,
1121 sizeof(host), NULL, 0, NI_NUMERICHOST))
1122 {
1123 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1124 goto error;
1125 }
1126
1127 /*
1128 * Data connection is opened by the server toward the client if:
1129 * - we're using TCP, and the user wants us to be in active mode
1130 * - we're using UDP
1131 */
1132 if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1133 {
1134 /*
1135 * We have to create a new socket to receive packets
1136 * We have to do that immediately, since we have to tell the other
1137 * end which network port we picked up
1138 */
1139 memset(&hints, 0, sizeof(struct addrinfo));
1140 /* TEMP addrinfo is NULL in case of active */
1141 hints.ai_family = ai_family; /* Use the same address family of the control socket */
1142 hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1143 hints.ai_flags = AI_PASSIVE; /* Data connection is opened by the server toward the client */
1144
1145 /* Let's the server pick up a free network port for us */
1146 if (sock_initaddress(NULL, "0", &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1147 goto error;
1148
1149 if ((sockdata = sock_open(addrinfo, SOCKOPEN_SERVER,
1150 1 /* max 1 connection in queue */, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1151 goto error;
1152
1153 /* addrinfo is no longer used */
1154 freeaddrinfo(addrinfo);
1155 addrinfo = NULL;
1156
1157 /* get the complete sockaddr structure used in the data connection */
1158 saddrlen = sizeof(struct sockaddr_storage);
1159 if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1160 {
1161 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1162 goto error;
1163 }
1164
1165 /* Get the local port the system picked up */
1166 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
1167 0, portdata, sizeof(portdata), NI_NUMERICSERV))
1168 {
1169 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1170 goto error;
1171 }
1172 }
1173
1174 /*
1175 * Now it's time to start playing with the RPCAP protocol
1176 * RPCAP start capture command: create the request message
1177 */
1178 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1179 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1180 goto error;
1181
1182 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_STARTCAP_REQ, 0,
1183 sizeof(struct rpcap_startcapreq) + sizeof(struct rpcap_filter) + fp->fcode.bf_len * sizeof(struct rpcap_filterbpf_insn));
1184
1185 /* Fill the structure needed to open an adapter remotely */
1186 startcapreq = (struct rpcap_startcapreq *) &sendbuf[sendbufidx];
1187
1188 if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreq), NULL,
1189 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1190 goto error;
1191
1192 memset(startcapreq, 0, sizeof(struct rpcap_startcapreq));
1193
1194 /* By default, apply half the timeout on one side, half of the other */
1195 fp->opt.timeout = fp->opt.timeout / 2;
1196 startcapreq->read_timeout = htonl(fp->opt.timeout);
1197
1198 /* portdata on the openreq is meaningful only if we're in active mode */
1199 if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1200 {
1201 sscanf(portdata, "%d", (int *)&(startcapreq->portdata)); /* cast to avoid a compiler warning */
1202 startcapreq->portdata = htons(startcapreq->portdata);
1203 }
1204
1205 startcapreq->snaplen = htonl(fp->snapshot);
1206 startcapreq->flags = 0;
1207
1208 if (pr->rmt_flags & PCAP_OPENFLAG_PROMISCUOUS)
1209 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_PROMISC;
1210 if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
1211 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_DGRAM;
1212 if (active)
1213 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN;
1214
1215 startcapreq->flags = htons(startcapreq->flags);
1216
1217 /* Pack the capture filter */
1218 if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, &fp->fcode))
1219 goto error;
1220
1221 if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
1222 goto error;
1223
1224 /* Receive the RPCAP start capture reply message */
1225 if (sock_recv(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1226 goto error;
1227
1228 /* Checks if the message is correct */
1229 retval = rpcap_checkmsg(fp->errbuf, pr->rmt_sockctrl, &header, RPCAP_MSG_STARTCAP_REPLY, RPCAP_MSG_ERROR, 0);
1230
1231 if (retval != RPCAP_MSG_STARTCAP_REPLY) /* the message is not the one expected */
1232 {
1233 switch (retval)
1234 {
1235 case -3: /* Unrecoverable network error */
1236 case -2: /* The other endpoint send a message that is not allowed here */
1237 case -1: /* The other endpoint has a version number that is not compatible with our */
1238 goto error;
1239
1240 case RPCAP_MSG_ERROR: /* The other endpoint reported an error */
1241 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
1242 totread = ntohl(header.plen);
1243 /* Do nothing; just exit; the error code is already into the errbuf */
1244 goto error;
1245
1246 default:
1247 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
1248 goto error;
1249 }
1250 }
1251
1252 nread = sock_recv(pr->rmt_sockctrl, (char *)&startcapreply,
1253 sizeof(struct rpcap_startcapreply), SOCK_RECEIVEALL_YES,
1254 fp->errbuf, PCAP_ERRBUF_SIZE);
1255 if (nread == -1)
1256 goto error;
1257 totread += nread;
1258
1259 /*
1260 * In case of UDP data stream, the connection is always opened by the daemon
1261 * So, this case is already covered by the code above.
1262 * Now, we have still to handle TCP connections, because:
1263 * - if we're in active mode, we have to wait for a remote connection
1264 * - if we're in passive more, we have to start a connection
1265 *
1266 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1267 * to tell the port we're using to the remote side; in case we're accepting a TCP
1268 * connection, we have to wait this info from the remote side.
1269 */
1270 if (!(pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1271 {
1272 if (!active)
1273 {
1274 memset(&hints, 0, sizeof(struct addrinfo));
1275 hints.ai_family = ai_family; /* Use the same address family of the control socket */
1276 hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1277 pcap_snprintf(portdata, PCAP_BUF_SIZE, "%d", ntohs(startcapreply.portdata));
1278
1279 /* Let's the server pick up a free network port for us */
1280 if (sock_initaddress(host, portdata, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1281 goto error;
1282
1283 if ((sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1284 goto error;
1285
1286 /* addrinfo is no longer used */
1287 freeaddrinfo(addrinfo);
1288 addrinfo = NULL;
1289 }
1290 else
1291 {
1292 SOCKET socktemp; /* We need another socket, since we're going to accept() a connection */
1293
1294 /* Connection creation */
1295 saddrlen = sizeof(struct sockaddr_storage);
1296
1297 socktemp = accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
1298
1299 if (socktemp == -1)
1300 {
1301 sock_geterror("accept(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1302 goto error;
1303 }
1304
1305 /* Now that I accepted the connection, the server socket is no longer needed */
1306 sock_close(sockdata, fp->errbuf, PCAP_ERRBUF_SIZE);
1307 sockdata = socktemp;
1308 }
1309 }
1310
1311 /* Let's save the socket of the data connection */
1312 pr->rmt_sockdata = sockdata;
1313
1314 /* Allocates WinPcap/libpcap user buffer, which is a socket buffer in case of a remote capture */
1315 /* It has the same size of the one used on the other side of the connection */
1316 fp->bufsize = ntohl(startcapreply.bufsize);
1317
1318 /* Let's get the actual size of the socket buffer */
1319 itemp = sizeof(sockbufsize);
1320
1321 res = getsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &itemp);
1322 if (res == -1)
1323 {
1324 sock_geterror("pcap_startcapture_remote()", fp->errbuf, PCAP_ERRBUF_SIZE);
1325 SOCK_ASSERT(fp->errbuf, 1);
1326 }
1327
1328 /*
1329 * Warning: on some kernels (e.g. Linux), the size of the user buffer does not take
1330 * into account the pcap_header and such, and it is set equal to the snaplen.
1331 * In my view, this is wrong (the meaning of the bufsize became a bit strange).
1332 * So, here bufsize is the whole size of the user buffer.
1333 * In case the bufsize returned is too small, let's adjust it accordingly.
1334 */
1335 if (fp->bufsize <= (u_int) fp->snapshot)
1336 fp->bufsize += sizeof(struct pcap_pkthdr);
1337
1338 /* if the current socket buffer is smaller than the desired one */
1339 if ((u_int) sockbufsize < fp->bufsize)
1340 {
1341 /* Loop until the buffer size is OK or the original socket buffer size is larger than this one */
1342 while (1)
1343 {
1344 res = setsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&(fp->bufsize), sizeof(fp->bufsize));
1345
1346 if (res == 0)
1347 break;
1348
1349 /*
1350 * If something goes wrong, half the buffer size (checking that it does not become smaller than
1351 * the current one)
1352 */
1353 fp->bufsize /= 2;
1354
1355 if ((u_int) sockbufsize >= fp->bufsize)
1356 {
1357 fp->bufsize = sockbufsize;
1358 break;
1359 }
1360 }
1361 }
1362
1363 /*
1364 * Let's allocate the packet; this is required in order to put the packet somewhere when
1365 * extracting data from the socket
1366 * Since buffering has already been done in the socket buffer, here we need just a buffer,
1367 * whose size is equal to the pcap header plus the snapshot length
1368 */
1369 fp->bufsize = fp->snapshot + sizeof(struct pcap_pkthdr);
1370
1371 fp->buffer = (u_char *)malloc(fp->bufsize);
1372 if (fp->buffer == NULL)
1373 {
1374 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
1375 goto error;
1376 }
1377
1378 /* Checks if all the data has been read; if not, discard the data in excess */
1379 if (totread != ntohl(header.plen))
1380 {
1381 if (sock_discard(pr->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
1382 goto error;
1383 }
1384
1385 /*
1386 * In case the user does not want to capture RPCAP packets, let's update the filter
1387 * We have to update it here (instead of sending it into the 'StartCapture' message
1388 * because when we generate the 'start capture' we do not know (yet) all the ports
1389 * we're currently using.
1390 */
1391 if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1392 {
1393 struct bpf_program fcode;
1394
1395 if (pcap_createfilter_norpcappkt(fp, &fcode) == -1)
1396 goto error;
1397
1398 /* We cannot use 'pcap_setfilter_rpcap' because formally the capture has not been started yet */
1399 /* (the 'pr->rmt_capstarted' variable will be updated some lines below) */
1400 if (pcap_updatefilter_remote(fp, &fcode) == -1)
1401 goto error;
1402
1403 pcap_freecode(&fcode);
1404 }
1405
1406 pr->rmt_capstarted = 1;
1407 return 0;
1408
1409 error:
1410 /*
1411 * When the connection has been established, we have to close it. So, at the
1412 * beginning of this function, if an error occur we return immediately with
1413 * a return NULL; when the connection is established, we have to come here
1414 * ('goto error;') in order to close everything properly.
1415 *
1416 * Checks if all the data has been read; if not, discard the data in excess
1417 */
1418 if (totread != ntohl(header.plen))
1419 sock_discard(pr->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0);
1420
1421 if ((sockdata) && (sockdata != -1)) /* we can be here because sockdata said 'error' */
1422 sock_close(sockdata, NULL, 0);
1423
1424 if (!active)
1425 sock_close(pr->rmt_sockctrl, NULL, 0);
1426
1427 /*
1428 * We do not have to call pcap_close() here, because this function is always called
1429 * by the user in case something bad happens
1430 */
1431 #if 0
1432 if (fp)
1433 {
1434 pcap_close(fp);
1435 fp= NULL;
1436 }
1437 #endif
1438
1439 return -1;
1440 }
1441
1442 /*
1443 * \brief Takes a bpf program and sends it to the other host.
1444 *
1445 * This function can be called in two cases:
1446 * - the pcap_startcapture() is called (we have to send the filter along with
1447 * the 'start capture' command)
1448 * - we want to udpate the filter during a capture (i.e. the pcap_setfilter()
1449 * is called when the capture is still on)
1450 *
1451 * This function serializes the filter into the sending buffer ('sendbuf', passed
1452 * as a parameter) and return back. It does not send anything on the network.
1453 *
1454 * \param fp: the pcap_t descriptor of the device currently opened.
1455 *
1456 * \param sendbuf: the buffer on which the serialized data has to copied.
1457 *
1458 * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1459 *
1460 * \param prog: the bpf program we have to copy.
1461 *
1462 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1463 * is returned into the 'errbuf' field of the pcap_t structure.
1464 */
1465 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog)
1466 {
1467 struct rpcap_filter *filter;
1468 struct rpcap_filterbpf_insn *insn;
1469 struct bpf_insn *bf_insn;
1470 struct bpf_program fake_prog; /* To be used just in case the user forgot to set a filter */
1471 unsigned int i;
1472
1473 if (prog->bf_len == 0) /* No filters have been specified; so, let's apply a "fake" filter */
1474 {
1475 if (pcap_compile(fp, &fake_prog, NULL /* buffer */, 1, 0) == -1)
1476 return -1;
1477
1478 prog = &fake_prog;
1479 }
1480
1481 filter = (struct rpcap_filter *) sendbuf;
1482
1483 if (sock_bufferize(NULL, sizeof(struct rpcap_filter), NULL, sendbufidx,
1484 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1485 return -1;
1486
1487 filter->filtertype = htons(RPCAP_UPDATEFILTER_BPF);
1488 filter->nitems = htonl((int32)prog->bf_len);
1489
1490 if (sock_bufferize(NULL, prog->bf_len * sizeof(struct rpcap_filterbpf_insn),
1491 NULL, sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1492 return -1;
1493
1494 insn = (struct rpcap_filterbpf_insn *) (filter + 1);
1495 bf_insn = prog->bf_insns;
1496
1497 for (i = 0; i < prog->bf_len; i++)
1498 {
1499 insn->code = htons(bf_insn->code);
1500 insn->jf = bf_insn->jf;
1501 insn->jt = bf_insn->jt;
1502 insn->k = htonl(bf_insn->k);
1503
1504 insn++;
1505 bf_insn++;
1506 }
1507
1508 return 0;
1509 }
1510
1511 /* \ingroup remote_pri_func
1512 *
1513 * \brief Update a filter on a remote host.
1514 *
1515 * This function is called when the user wants to update a filter.
1516 * In case we're capturing from the network, it sends the filter to the other peer.
1517 * This function is *not* called automatically when the user calls the pcap_setfilter().
1518 * There will be two cases:
1519 * - the capture is already on: in this case, pcap_setfilter() calls pcap_updatefilter_remote()
1520 * - the capture has not started yet: in this case, pcap_setfilter() stores the filter into
1521 * the pcap_t structure, and then the filter is sent with the pcap_startcap().
1522 *
1523 * Parameters and return values are exactly the same of the pcap_setfilter().
1524 *
1525 * \warning This function *does not* clear the packet currently into the buffers. Therefore,
1526 * the user has to expect to receive some packets that are related to the previous filter.
1527 * If you want to discard all the packets before applying a new filter, you have to close
1528 * the current capture session and start a new one.
1529 */
1530 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog)
1531 {
1532 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1533 int retval; /* general variable used to keep the return value of other functions */
1534 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
1535 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1536 struct rpcap_header header; /* To keep the reply message */
1537
1538 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1539 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1540 return -1;
1541
1542 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_UPDATEFILTER_REQ, 0,
1543 sizeof(struct rpcap_filter) + prog->bf_len * sizeof(struct rpcap_filterbpf_insn));
1544
1545 if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, prog))
1546 return -1;
1547
1548 if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
1549 return -1;
1550
1551 /* Waits for the answer */
1552 if (sock_recv(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1553 return -1;
1554
1555 /* Checks if the message is correct */
1556 retval = rpcap_checkmsg(fp->errbuf, pr->rmt_sockctrl, &header, RPCAP_MSG_UPDATEFILTER_REPLY, 0);
1557
1558 if (retval != RPCAP_MSG_UPDATEFILTER_REPLY) /* the message is not the one expected */
1559 {
1560 switch (retval)
1561 {
1562 case -3: /* Unrecoverable network error */
1563 case -2: /* The other endpoint sent a message that is not allowed here */
1564 case -1: /* The other endpoint has a version number that is not compatible with our */
1565 /* Do nothing; just exit from here; the error code is already into the errbuf */
1566 return -1;
1567
1568 default:
1569 SOCK_ASSERT("Internal error", 0);
1570 return -1;
1571 }
1572 }
1573
1574 if (ntohl(header.plen) != 0) /* the message has an unexpected size */
1575 {
1576 if (sock_discard(pr->rmt_sockctrl, ntohl(header.plen), fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1577 return -1;
1578 }
1579
1580 return 0;
1581 }
1582
1583 static void
1584 pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter)
1585 {
1586 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1587
1588 /*
1589 * Check if:
1590 * - We are on an remote capture
1591 * - we do not want to capture RPCAP traffic
1592 *
1593 * If so, we have to save the current filter, because we have to
1594 * add some piece of stuff later
1595 */
1596 if (pr->rmt_clientside &&
1597 (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP))
1598 {
1599 if (pr->currentfilter)
1600 free(pr->currentfilter);
1601
1602 if (filter == NULL)
1603 filter = "";
1604
1605 pr->currentfilter = strdup(filter);
1606 }
1607 }
1608
1609 /*
1610 * \ingroup remote_pri_func
1611 *
1612 * \brief Send a filter to a remote host.
1613 *
1614 * This function is called when the user wants to set a filter.
1615 * In case we're capturing from the network, it sends the filter to the other peer.
1616 * This function is called automatically when the user calls the pcap_setfilter().
1617 *
1618 * Parameters and return values are exactly the same of the pcap_setfilter().
1619 */
1620 static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog)
1621 {
1622 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1623
1624 if (!pr->rmt_capstarted)
1625 {
1626 /* copy filter into the pcap_t structure */
1627 if (install_bpf_program(fp, prog) == -1)
1628 return -1;
1629 return 0;
1630 }
1631
1632 /* we have to update a filter during run-time */
1633 if (pcap_updatefilter_remote(fp, prog))
1634 return -1;
1635
1636 return 0;
1637 }
1638
1639 /*
1640 * \ingroup remote_pri_func
1641 *
1642 * \brief Update the current filter in order not to capture rpcap packets.
1643 *
1644 * This function is called *only* when the user wants exclude RPCAP packets
1645 * related to the current session from the captured packets.
1646 *
1647 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1648 * is returned into the 'errbuf' field of the pcap_t structure.
1649 */
1650 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog)
1651 {
1652 struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
1653 int RetVal = 0;
1654
1655 /* We do not want to capture our RPCAP traffic. So, let's update the filter */
1656 if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1657 {
1658 struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
1659 socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
1660 char myaddress[128];
1661 char myctrlport[128];
1662 char mydataport[128];
1663 char peeraddress[128];
1664 char peerctrlport[128];
1665 char *newfilter;
1666 const int newstringsize = 1024;
1667 size_t currentfiltersize;
1668
1669 /* Get the name/port of the other peer */
1670 saddrlen = sizeof(struct sockaddr_storage);
1671 if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1672 {
1673 sock_geterror("getpeername(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1674 return -1;
1675 }
1676
1677 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peeraddress,
1678 sizeof(peeraddress), peerctrlport, sizeof(peerctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1679 {
1680 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1681 return -1;
1682 }
1683
1684 /* We cannot check the data port, because this is available only in case of TCP sockets */
1685 /* Get the name/port of the current host */
1686 if (getsockname(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1687 {
1688 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1689 return -1;
1690 }
1691
1692 /* Get the local port the system picked up */
1693 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, myaddress,
1694 sizeof(myaddress), myctrlport, sizeof(myctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1695 {
1696 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1697 return -1;
1698 }
1699
1700 /* Let's now check the data port */
1701 if (getsockname(pr->rmt_sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1702 {
1703 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1704 return -1;
1705 }
1706
1707 /* Get the local port the system picked up */
1708 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL, 0, mydataport, sizeof(mydataport), NI_NUMERICSERV))
1709 {
1710 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1711 return -1;
1712 }
1713
1714 currentfiltersize = pr->currentfilter ? strlen(pr->currentfilter) : 0;
1715
1716 newfilter = (char *)malloc(currentfiltersize + newstringsize + 1);
1717
1718 if (currentfiltersize)
1719 {
1720 pcap_snprintf(newfilter, currentfiltersize + newstringsize,
1721 "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1722 pr->currentfilter, myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
1723 }
1724 else
1725 {
1726 pcap_snprintf(newfilter, currentfiltersize + newstringsize,
1727 "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1728 myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
1729 }
1730
1731 newfilter[currentfiltersize + newstringsize] = 0;
1732
1733 /*
1734 * This is only an hack to prevent the save_current_filter
1735 * routine, which will be called when we call pcap_compile(),
1736 * from saving the modified filter.
1737 */
1738 pr->rmt_clientside = 0;
1739
1740 if (pcap_compile(fp, prog, newfilter, 1, 0) == -1)
1741 RetVal = -1;
1742
1743 /* Undo the hack. */
1744 pr->rmt_clientside = 1;
1745
1746 free(newfilter);
1747 }
1748
1749 return RetVal;
1750 }
1751
1752 /*
1753 * \ingroup remote_pri_func
1754 *
1755 * \brief Set sampling parameters in the remote host.
1756 *
1757 * This function is called when the user wants to set activate sampling on the remote host.
1758 *
1759 * Sampling parameters are defined into the 'pcap_t' structure.
1760 *
1761 * \param p: the pcap_t descriptor of the device currently opened.
1762 *
1763 * \return '0' if everything is OK, '-1' is something goes wrong. The error message is returned
1764 * in the 'errbuf' member of the pcap_t structure.
1765 */
1766 static int pcap_setsampling_remote(pcap_t *p)
1767 {
1768 struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
1769 int retval; /* general variable used to keep the return value of other functions */
1770 char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
1771 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1772 struct rpcap_header header; /* To keep the reply message */
1773 struct rpcap_sampling *sampling_pars; /* Structure that is needed to send sampling parameters to the remote host */
1774
1775 /* If no samping is requested, return 'ok' */
1776 if (p->rmt_samp.method == PCAP_SAMP_NOSAMP)
1777 return 0;
1778
1779 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1780 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, p->errbuf, PCAP_ERRBUF_SIZE))
1781 return -1;
1782
1783 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_SETSAMPLING_REQ, 0, sizeof(struct rpcap_sampling));
1784
1785 /* Fill the structure needed to open an adapter remotely */
1786 sampling_pars = (struct rpcap_sampling *) &sendbuf[sendbufidx];
1787
1788 if (sock_bufferize(NULL, sizeof(struct rpcap_sampling), NULL,
1789 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, p->errbuf, PCAP_ERRBUF_SIZE))
1790 return -1;
1791
1792 memset(sampling_pars, 0, sizeof(struct rpcap_sampling));
1793
1794 sampling_pars->method = p->rmt_samp.method;
1795 sampling_pars->value = htonl(p->rmt_samp.value);
1796
1797 if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, p->errbuf, PCAP_ERRBUF_SIZE))
1798 return -1;
1799
1800 /* Waits for the answer */
1801 if (sock_recv(pr->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
1802 return -1;
1803
1804 /* Checks if the message is correct */
1805 retval = rpcap_checkmsg(p->errbuf, pr->rmt_sockctrl, &header, RPCAP_MSG_SETSAMPLING_REPLY, 0);
1806
1807 if (retval != RPCAP_MSG_SETSAMPLING_REPLY) /* the message is not the one expected */
1808 {
1809 switch (retval)
1810 {
1811 case -3: /* Unrecoverable network error */
1812 case -2: /* The other endpoint sent a message that is not allowed here */
1813 case -1: /* The other endpoint has a version number that is not compatible with our */
1814 case RPCAP_MSG_ERROR:
1815 /* Do nothing; just exit from here; the error code is already into the errbuf */
1816 return -1;
1817
1818 default:
1819 SOCK_ASSERT("Internal error", 0);
1820 return -1;
1821 }
1822 }
1823
1824 if (ntohl(header.plen) != 0) /* the message has an unexpected size */
1825 {
1826 if (sock_discard(pr->rmt_sockctrl, ntohl(header.plen), p->errbuf, PCAP_ERRBUF_SIZE) == -1)
1827 return -1;
1828 }
1829
1830 return 0;
1831
1832 }
1833
1834 /*********************************************************
1835 * *
1836 * Miscellaneous functions *
1837 * *
1838 *********************************************************/
1839
1840 /* \ingroup remote_pri_func
1841 * \brief It sends a RPCAP error to the other peer.
1842 *
1843 * This function has to be called when the main program detects an error. This function
1844 * will send on the other peer the 'buffer' specified by the user.
1845 * This function *does not* request a RPCAP CLOSE connection. A CLOSE command must be sent
1846 * explicitly by the program, since we do not know it the error can be recovered in some
1847 * way or it is a non-recoverable one.
1848 *
1849 * \param sock: the socket we are currently using.
1850 *
1851 * \param error: an user-allocated (and '0' terminated) buffer that contains the error
1852 * description that has to be transmitted on the other peer. The error message cannot
1853 * be longer than PCAP_ERRBUF_SIZE.
1854 *
1855 * \param errcode: a integer which tells the other party the type of error we had;
1856 * currently is is not too much used.
1857 *
1858 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
1859 * that will contain the error message (in case there is one). It could be network problem.
1860 *
1861 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
1862 * in the 'errbuf' variable.
1863 */
1864 int rpcap_senderror(SOCKET sock, char *error, unsigned short errcode, char *errbuf)
1865 {
1866 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
1867 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1868 uint16 length;
1869
1870 length = (uint16)strlen(error);
1871
1872 if (length > PCAP_ERRBUF_SIZE)
1873 length = PCAP_ERRBUF_SIZE;
1874
1875 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_ERROR, errcode, length);
1876
1877 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1878 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1879 return -1;
1880
1881 if (sock_bufferize(error, length, sendbuf, &sendbufidx,
1882 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1883 return -1;
1884
1885 if (sock_send(sock, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE))
1886 return -1;
1887
1888 return 0;
1889 }
1890
1891 /* \ingroup remote_pri_func
1892 * \brief Sends the authentication message.
1893 *
1894 * It sends the authentication parameters on the control socket.
1895 * This function is required in order to open the connection with the other end party.
1896 *
1897 * \param sock: the socket we are currently using.
1898 *
1899 * \param auth: authentication parameters that have to be sent.
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 network problem
1903 * of the fact that the authorization failed.
1904 *
1905 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
1906 * in the 'errbuf' variable.
1907 * The error message could be also 'the authentication failed'.
1908 */
1909 int rpcap_sendauth(SOCKET sock, struct pcap_rmtauth *auth, char *errbuf)
1910 {
1911 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data that has to be sent is buffered */
1912 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1913 uint16 length; /* length of the payload of this message */
1914 struct rpcap_auth *rpauth;
1915 uint16 auth_type;
1916 struct rpcap_header header;
1917 int retval; /* temp variable which stores functions return value */
1918 size_t str_length;
1919
1920 if (auth)
1921 {
1922 auth_type = auth->type;
1923
1924 switch (auth->type)
1925 {
1926 case RPCAP_RMTAUTH_NULL:
1927 length = sizeof(struct rpcap_auth);
1928 break;
1929
1930 case RPCAP_RMTAUTH_PWD:
1931 length = sizeof(struct rpcap_auth);
1932 if (auth->username)
1933 {
1934 str_length = strlen(auth->username);
1935 if (str_length > 65535)
1936 {
1937 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "User name is too long (> 65535 bytes)");
1938 return -1;
1939 }
1940 length += (uint16)str_length;
1941 }
1942 if (auth->password)
1943 {
1944 str_length = strlen(auth->password);
1945 if (str_length > 65535)
1946 {
1947 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Password is too long (> 65535 bytes)");
1948 return -1;
1949 }
1950 length += (uint16)str_length;
1951 }
1952 break;
1953
1954 default:
1955 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized.");
1956 return -1;
1957 }
1958 }
1959 else
1960 {
1961 auth_type = RPCAP_RMTAUTH_NULL;
1962 length = sizeof(struct rpcap_auth);
1963 }
1964
1965
1966 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1967 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1968 return -1;
1969
1970 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_AUTH_REQ, 0, length);
1971
1972 rpauth = (struct rpcap_auth *) &sendbuf[sendbufidx];
1973
1974 if (sock_bufferize(NULL, sizeof(struct rpcap_auth), NULL,
1975 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1976 return -1;
1977
1978 memset(rpauth, 0, sizeof(struct rpcap_auth));
1979
1980 rpauth->type = htons(auth_type);
1981
1982 if (auth_type == RPCAP_RMTAUTH_PWD)
1983 {
1984 if (auth->username)
1985 rpauth->slen1 = (uint16)strlen(auth->username);
1986 else
1987 rpauth->slen1 = 0;
1988
1989 if (sock_bufferize(auth->username, rpauth->slen1, sendbuf,
1990 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1991 return -1;
1992
1993 if (auth->password)
1994 rpauth->slen2 = (uint16)strlen(auth->password);
1995 else
1996 rpauth->slen2 = 0;
1997
1998 if (sock_bufferize(auth->password, rpauth->slen2, sendbuf,
1999 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
2000 return -1;
2001
2002 rpauth->slen1 = htons(rpauth->slen1);
2003 rpauth->slen2 = htons(rpauth->slen2);
2004 }
2005
2006 if (sock_send(sock, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE))
2007 return -1;
2008
2009 if (sock_recv(sock, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1)
2010 return -1;
2011
2012 retval = rpcap_checkmsg(errbuf, sock, &header, RPCAP_MSG_AUTH_REPLY, RPCAP_MSG_ERROR, 0);
2013
2014 if (retval != RPCAP_MSG_AUTH_REPLY) /* the message is not the one expected */
2015 {
2016 switch (retval)
2017 {
2018 case -3: /* Unrecoverable network error */
2019 case -2: /* The other endpoint sent a message that is not allowed here */
2020 case -1: /* The other endpoint has a version number that is not compatible with our */
2021 /* Do nothing; just exit from here; the error code is already into the errbuf */
2022 return -1;
2023
2024 case RPCAP_MSG_ERROR:
2025 return -1;
2026
2027 default:
2028 SOCK_ASSERT("Internal error", 0);
2029 return -1;
2030 }
2031 }
2032
2033 if (ntohl(header.plen))
2034 {
2035 if (sock_discard(sock, ntohl(header.plen), errbuf, PCAP_ERRBUF_SIZE))
2036 return -1;
2037 }
2038
2039 return 0;
2040 }
2041
2042 /* \ingroup remote_pri_func
2043 * \brief Creates a structure of type rpcap_header.
2044 *
2045 * This function is provided just because the creation of an rpcap header is quite a common
2046 * task. It accepts all the values that appears into an rpcap_header, and it puts them in
2047 * place using the proper hton() calls.
2048 *
2049 * \param header: a pointer to a user-allocated buffer which will contain the serialized
2050 * header, ready to be sent on the network.
2051 *
2052 * \param type: a value (in the host by order) which will be placed into the header.type
2053 * field and that represents the type of the current message.
2054 *
2055 * \param value: a value (in the host by order) which will be placed into the header.value
2056 * field and that has a message-dependent meaning.
2057 *
2058 * \param length: a value (in the host by order) which will be placed into the header.length
2059 * field and that represents the payload length of the message.
2060 *
2061 * \return Nothing. The serialized header is returned into the 'header' variable.
2062 */
2063 void rpcap_createhdr(struct rpcap_header *header, uint8 type, uint16 value, uint32 length)
2064 {
2065 memset(header, 0, sizeof(struct rpcap_header));
2066
2067 header->ver = RPCAP_VERSION;
2068 header->type = type;
2069 header->value = htons(value);
2070 header->plen = htonl(length);
2071 }
2072
2073 /* ingroup remote_pri_func
2074 * \brief Checks if the header of the received message is correct.
2075 *
2076 * This function is a way to easily check if the message received, in a certain
2077 * state of the RPCAP protocol Finite State Machine, is valid. This function accepts,
2078 * as a parameter, the list of message types that are allowed in a certain situation,
2079 * and it returns the one which occurs.
2080 *
2081 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
2082 * that will contain the error message (in case there is one). It could be either problem
2083 * occurred inside this function (e.g. a network problem in case it tries to send an
2084 * error on the other peer and the send() call fails), an error message which has been
2085 * sent to us from the other party, or a version error (the message receive has a version
2086 * number that is incompatible with our).
2087 *
2088 * \param sock: the socket that has to be used to receive data. This function can
2089 * read data from socket in case the version contained into the message is not compatible
2090 * with our. In that case, all the message is purged from the socket, so that the following
2091 * recv() calls will return a new message.
2092 *
2093 * \param header: a pointer to and 'rpcap_header' structure that keeps the data received from
2094 * the network (still in network byte order) and that has to be checked.
2095 *
2096 * \param first: this function has a variable number of parameters. From this point on,
2097 * all the messages that are valid in this context must be passed as parameters.
2098 * The message type list must be terminated with a '0' value, the null message type,
2099 * which means 'no more types to check'. The RPCAP protocol does not define anything with
2100 * message type equal to zero, so there is no ambiguity in using this value as a list terminator.
2101 *
2102 * \return The message type of the message that has been detected. In case of errors (e.g. the
2103 * header contains a type that is not listed among the allowed types), this function will
2104 * return the following codes:
2105 * - (-1) if the version is incompatible.
2106 * - (-2) if the code is not among the one listed into the parameters list
2107 * - (-3) if a network error (connection reset, ...)
2108 * - RPCAP_MSG_ERROR if the message is an error message (it follow that the RPCAP_MSG_ERROR
2109 * could not be present in the allowed message-types list, because this function checks
2110 * for errors anyway)
2111 *
2112 * In case either the version is incompatible or nothing matches (i.e. it returns '-1' or '-2'),
2113 * it discards the message body (i.e. it reads the remaining part of the message from the
2114 * network and it discards it) so that the application is ready to receive a new message.
2115 */
2116 int rpcap_checkmsg(char *errbuf, SOCKET sock, struct rpcap_header *header, uint8 first, ...)
2117 {
2118 va_list ap;
2119 uint8 type;
2120 int32 len;
2121
2122 va_start(ap, first);
2123
2124 /* Check if the present version of the protocol can handle this message */
2125 if (rpcap_checkver(sock, header, errbuf))
2126 {
2127 SOCK_ASSERT(errbuf, 1);
2128
2129 va_end(ap);
2130 return -1;
2131 }
2132
2133 type = first;
2134
2135 while (type != 0)
2136 {
2137 /*
2138 * The message matches with one of the types listed
2139 * There is no need of conversions since both values are uint8
2140 *
2141 * Check if the other side reported an error.
2142 * If yes, it retrieves it and it returns it back to the caller
2143 */
2144 if (header->type == RPCAP_MSG_ERROR)
2145 {
2146 len = ntohl(header->plen);
2147
2148 if (len >= PCAP_ERRBUF_SIZE)
2149 {
2150 if (sock_recv(sock, errbuf, PCAP_ERRBUF_SIZE - 1, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE))
2151 return -3;
2152
2153 sock_discard(sock, len - (PCAP_ERRBUF_SIZE - 1), NULL, 0);
2154
2155 /* Put '\0' at the end of the string */
2156 errbuf[PCAP_ERRBUF_SIZE - 1] = 0;
2157 }
2158 else
2159 {
2160 if (sock_recv(sock, errbuf, len, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1)
2161 return -3;
2162
2163 /* Put '\0' at the end of the string */
2164 errbuf[len] = 0;
2165 }
2166
2167 va_end(ap);
2168 return header->type;
2169 }
2170
2171 if (header->type == type)
2172 {
2173 va_end(ap);
2174 return header->type;
2175 }
2176
2177 /* get next argument */
2178 type = va_arg(ap, int);
2179 }
2180
2181 /* we already have an error, so please discard this one */
2182 sock_discard(sock, ntohl(header->plen), NULL, 0);
2183
2184 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The other endpoint sent a message that is not allowed here.");
2185 SOCK_ASSERT(errbuf, 1);
2186
2187 va_end(ap);
2188 return -2;
2189 }
2190
2191 /* \ingroup remote_pri_func
2192 * \brief Checks if the version contained into the message is compatible with
2193 * the one handled by this implementation.
2194 *
2195 * Right now, this function does not have any sophisticated task: if the versions
2196 * are different, it returns -1 and it discards the message.
2197 * It is expected that in the future this message will become more complex.
2198 *
2199 * \param sock: the socket that has to be used to receive data. This function can
2200 * read data from socket in case the version contained into the message is not compatible
2201 * with our. In that case, all the message is purged from the socket, so that the following
2202 * recv() calls will return a new (clean) message.
2203 *
2204 * \param header: a pointer to and 'rpcap_header' structure that keeps the data received from
2205 * the network (still in network byte order) and that has to be checked.
2206 *
2207 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
2208 * that will contain the error message (in case there is one). The error message is
2209 * "incompatible version".
2210 *
2211 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
2212 * in the 'errbuf' variable.
2213 */
2214 static int rpcap_checkver(SOCKET sock, struct rpcap_header *header, char *errbuf)
2215 {
2216 /*
2217 * This is a sample function.
2218 *
2219 * In the real world, you have to check the type code,
2220 * and decide accordingly.
2221 */
2222 if (header->ver != RPCAP_VERSION)
2223 {
2224 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Incompatible version number: message discarded.");
2225
2226 /* we already have an error, so please discard this one */
2227 sock_discard(sock, ntohl(header->plen), NULL, 0);
2228 return -1;
2229 }
2230
2231 return 0;
2232 }
2233
2234 /* \ingroup remote_pri_func
2235 *
2236 * \brief It returns the socket currently used for this active connection
2237 * (active mode only) and provides an indication of whether this connection
2238 * is in active mode or not.
2239 *
2240 * This function is just for internal use; it returns the socket ID of the
2241 * active connection currently opened.
2242 *
2243 * \param host: a string that keeps the host name of the host for which we
2244 * want to get the socket ID for that active connection.
2245 *
2246 * \param isactive: a pointer to an int that is set to 1 if there's an
2247 * active connection to that host and 0 otherwise.
2248 *
2249 * \param errbuf: a pointer to a user-allocated buffer (of size
2250 * PCAP_ERRBUF_SIZE) that will contain the error message (in case
2251 * there is one).
2252 *
2253 * \return the socket identifier if everything is fine, '0' if this host
2254 * is not in the active host list. An indication of whether this host
2255 * is in the active host list is returned into the isactive variable.
2256 * It returns 'INVALID_SOCKET' in case of error. The error message is
2257 * returned into the errbuf variable.
2258 */
2259 SOCKET rpcap_remoteact_getsock(const char *host, int *isactive, char *errbuf)
2260 {
2261 struct activehosts *temp; /* temp var needed to scan the host list chain */
2262 struct addrinfo hints, *addrinfo, *ai_next; /* temp var needed to translate between hostname to its address */
2263 int retval;
2264
2265 /* retrieve the network address corresponding to 'host' */
2266 addrinfo = NULL;
2267 memset(&hints, 0, sizeof(struct addrinfo));
2268 hints.ai_family = PF_UNSPEC;
2269 hints.ai_socktype = SOCK_STREAM;
2270
2271 retval = getaddrinfo(host, "0", &hints, &addrinfo);
2272 if (retval != 0)
2273 {
2274 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "getaddrinfo() %s", gai_strerror(retval));
2275 *isactive = 0;
2276 return INVALID_SOCKET;
2277 }
2278
2279 temp = activeHosts;
2280
2281 while (temp)
2282 {
2283 ai_next = addrinfo;
2284 while (ai_next)
2285 {
2286 if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
2287 {
2288 *isactive = 1;
2289 return (temp->sockctrl);
2290 }
2291
2292 ai_next = ai_next->ai_next;
2293 }
2294 temp = temp->next;
2295 }
2296
2297 if (addrinfo)
2298 freeaddrinfo(addrinfo);
2299
2300 /*
2301 * The host for which you want to get the socket ID does not have an
2302 * active connection.
2303 */
2304 *isactive = 0;
2305 return 0;
2306 }
2307
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 int result;
2314
2315 fp = pcap_create_common(errbuf, sizeof (struct pcap_rpcap));
2316 if (fp == NULL)
2317 {
2318 return NULL;
2319 }
2320 source_str = strdup(source);
2321 if (source_str == NULL) {
2322 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
2323 "malloc: %s", pcap_strerror(errno));
2324 return NULL;
2325 }
2326 fp->opt.device = source_str;
2327 fp->snapshot = snaplen;
2328 fp->opt.timeout = read_timeout;
2329 pr = fp->priv;
2330 pr->rmt_flags = flags;
2331
2332 result = pcap_opensource_remote(fp, auth);
2333
2334 if (result != 0) {
2335 pcap_close(fp);
2336 return NULL;
2337 }
2338
2339 fp->activated = 1;
2340 return fp;
2341 }
2342
2343 /* String identifier to be used in the pcap_findalldevs_ex() */
2344 #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
2345 /* String identifier to be used in the pcap_findalldevs_ex() */
2346 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST "on remote node"
2347
2348 static void
2349 freeaddr(struct pcap_addr *addr)
2350 {
2351 free(addr->addr);
2352 free(addr->netmask);
2353 free(addr->broadaddr);
2354 free(addr->dstaddr);
2355 free(addr);
2356 }
2357
2358 int
2359 pcap_findalldevs_ex_remote(char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf)
2360 {
2361 SOCKET sockctrl; /* socket descriptor of the control connection */
2362 uint32 totread = 0; /* number of bytes of the payload read from the socket */
2363 int nread;
2364 struct addrinfo hints; /* temp variable needed to resolve hostnames into to socket representation */
2365 struct addrinfo *addrinfo; /* temp variable needed to resolve hostnames into to socket representation */
2366 struct rpcap_header header; /* structure that keeps the general header of the rpcap protocol */
2367 int i, j; /* temp variables */
2368 int retval; /* store the return value of the functions */
2369 int nif; /* Number of interfaces listed */
2370 int active = 0; /* 'true' if we the other end-party is in active mode */
2371 int type;
2372 char host[PCAP_BUF_SIZE], port[PCAP_BUF_SIZE];
2373 char tmpstring[PCAP_BUF_SIZE + 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2374 pcap_if_t *dev; /* Previous device into the pcap_if_t chain */
2375
2376 /* Retrieve the needed data for getting adapter list */
2377 if (pcap_parsesrcstr(source, &type, host, port, NULL, errbuf) == -1)
2378 return -1;
2379
2380 /* Warning: this call can be the first one called by the user. */
2381 /* For this reason, we have to initialize the WinSock support. */
2382 if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
2383 return -1;
2384
2385 /* Check for active mode */
2386 sockctrl = rpcap_remoteact_getsock(host, &active, errbuf);
2387 if (sockctrl == INVALID_SOCKET)
2388 return -1;
2389
2390 if (!active) {
2391 /*
2392 * We're not in active mode; let's try to open a new
2393 * control connection.
2394 */
2395 addrinfo = NULL;
2396
2397 memset(&hints, 0, sizeof(struct addrinfo));
2398 hints.ai_family = PF_UNSPEC;
2399 hints.ai_socktype = SOCK_STREAM;
2400
2401 if (port[0] == 0)
2402 {
2403 /* the user chose not to specify the port */
2404 if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2405 return -1;
2406 }
2407 else
2408 {
2409 if (sock_initaddress(host, port, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
2410 return -1;
2411 }
2412
2413 if ((sockctrl = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == -1)
2414 goto error;
2415
2416 /* addrinfo is no longer used */
2417 freeaddrinfo(addrinfo);
2418 addrinfo = NULL;
2419
2420 if (rpcap_sendauth(sockctrl, auth, errbuf) == -1)
2421 {
2422 sock_close(sockctrl, NULL, 0);
2423 return -1;
2424 }
2425 }
2426
2427 /* RPCAP findalldevs command */
2428 rpcap_createhdr(&header, RPCAP_MSG_FINDALLIF_REQ, 0, 0);
2429
2430 if (sock_send(sockctrl, (char *)&header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
2431 goto error;
2432
2433 if (sock_recv(sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1)
2434 goto error;
2435
2436 /* Checks if the message is correct */
2437 retval = rpcap_checkmsg(errbuf, sockctrl, &header, RPCAP_MSG_FINDALLIF_REPLY, RPCAP_MSG_ERROR, 0);
2438
2439 if (retval != RPCAP_MSG_FINDALLIF_REPLY) /* the message is not the one expected */
2440 {
2441 switch (retval)
2442 {
2443 case -3: /* Unrecoverable network error */
2444 case -2: /* The other endpoint send a message that is not allowed here */
2445 case -1: /* The other endpoint has a version number that is not compatible with our */
2446 break;
2447
2448 case RPCAP_MSG_ERROR: /* The other endpoint reported an error */
2449 break;
2450
2451 default:
2452 {
2453 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Internal error");
2454 break;
2455 };
2456 }
2457
2458 if (!active)
2459 sock_close(sockctrl, NULL, 0);
2460
2461 return -1;
2462 }
2463
2464 /* read the number of interfaces */
2465 nif = ntohs(header.value);
2466
2467 /* loop until all interfaces have been received */
2468 for (i = 0; i < nif; i++)
2469 {
2470 struct rpcap_findalldevs_if findalldevs_if;
2471 char tmpstring2[PCAP_BUF_SIZE + 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2472 size_t stringlen;
2473 struct pcap_addr *addr, *prevaddr;
2474
2475 tmpstring2[PCAP_BUF_SIZE] = 0;
2476
2477 /* receive the findalldevs structure from remote host */
2478 nread = sock_recv(sockctrl, (char *)&findalldevs_if,
2479 sizeof(struct rpcap_findalldevs_if), SOCK_RECEIVEALL_YES,
2480 errbuf, PCAP_ERRBUF_SIZE);
2481 if (nread == -1)
2482 goto error;
2483 totread += nread;
2484
2485 findalldevs_if.namelen = ntohs(findalldevs_if.namelen);
2486 findalldevs_if.desclen = ntohs(findalldevs_if.desclen);
2487 findalldevs_if.naddr = ntohs(findalldevs_if.naddr);
2488
2489 /* allocate the main structure */
2490 if (i == 0)
2491 {
2492 (*alldevs) = (pcap_if_t *)malloc(sizeof(pcap_if_t));
2493 dev = (*alldevs);
2494 }
2495 else
2496 {
2497 dev->next = (pcap_if_t *)malloc(sizeof(pcap_if_t));
2498 dev = dev->next;
2499 }
2500
2501 /* check that the malloc() didn't fail */
2502 if (dev == NULL)
2503 {
2504 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
2505 goto error;
2506 }
2507
2508 /* Initialize the structure to 'zero' */
2509 memset(dev, 0, sizeof(pcap_if_t));
2510
2511 /* allocate mem for name and description */
2512 if (findalldevs_if.namelen)
2513 {
2514
2515 if (findalldevs_if.namelen >= sizeof(tmpstring))
2516 {
2517 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface name too long");
2518 goto error;
2519 }
2520
2521 /* Retrieve adapter name */
2522 nread = sock_recv(sockctrl, tmpstring,
2523 findalldevs_if.namelen, SOCK_RECEIVEALL_YES,
2524 errbuf, PCAP_ERRBUF_SIZE);
2525 if (nread == -1)
2526 goto error;
2527 totread += nread;
2528
2529 tmpstring[findalldevs_if.namelen] = 0;
2530
2531 /* Create the new device identifier */
2532 if (pcap_createsrcstr(tmpstring2, PCAP_SRC_IFREMOTE, host, port, tmpstring, errbuf) == -1)
2533 return -1;
2534
2535 stringlen = strlen(tmpstring2);
2536
2537 dev->name = (char *)malloc(stringlen + 1);
2538 if (dev->name == NULL)
2539 {
2540 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
2541 goto error;
2542 }
2543
2544 /* Copy the new device name into the correct memory location */
2545 strlcpy(dev->name, tmpstring2, stringlen + 1);
2546 }
2547
2548 if (findalldevs_if.desclen)
2549 {
2550 if (findalldevs_if.desclen >= sizeof(tmpstring))
2551 {
2552 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface description too long");
2553 goto error;
2554 }
2555
2556 /* Retrieve adapter description */
2557 nread = sock_recv(sockctrl, tmpstring,
2558 findalldevs_if.desclen, SOCK_RECEIVEALL_YES,
2559 errbuf, PCAP_ERRBUF_SIZE);
2560 if (nread == -1)
2561 goto error;
2562 totread += nread;
2563
2564 tmpstring[findalldevs_if.desclen] = 0;
2565
2566 pcap_snprintf(tmpstring2, sizeof(tmpstring2) - 1, "%s '%s' %s %s", PCAP_TEXT_SOURCE_ADAPTER,
2567 tmpstring, PCAP_TEXT_SOURCE_ON_REMOTE_HOST, host);
2568
2569 stringlen = strlen(tmpstring2);
2570
2571 dev->description = (char *)malloc(stringlen + 1);
2572
2573 if (dev->description == NULL)
2574 {
2575 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
2576 goto error;
2577 }
2578
2579 /* Copy the new device description into the correct memory location */
2580 strlcpy(dev->description, tmpstring2, stringlen + 1);
2581 }
2582
2583 dev->flags = ntohl(findalldevs_if.flags);
2584
2585 prevaddr = NULL;
2586 /* loop until all addresses have been received */
2587 for (j = 0; j < findalldevs_if.naddr; j++)
2588 {
2589 struct rpcap_findalldevs_ifaddr ifaddr;
2590
2591 /* Retrieve the interface addresses */
2592 nread = sock_recv(sockctrl, (char *)&ifaddr,
2593 sizeof(struct rpcap_findalldevs_ifaddr),
2594 SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE);
2595 if (nread == -1)
2596 goto error;
2597 totread += nread;
2598
2599 /*
2600 * Deserialize all the address components.
2601 */
2602 addr = (struct pcap_addr *) malloc(sizeof(struct pcap_addr));
2603 if (addr == NULL)
2604 {
2605 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
2606 goto error;
2607 }
2608 addr->next = NULL;
2609 addr->addr = NULL;
2610 addr->netmask = NULL;
2611 addr->broadaddr = NULL;
2612 addr->dstaddr = NULL;
2613
2614 if (rpcap_deseraddr(&ifaddr.addr,
2615 (struct sockaddr_storage **) &addr->addr, errbuf) == -1)
2616 {
2617 freeaddr(addr);
2618 goto error;
2619 }
2620 if (rpcap_deseraddr(&ifaddr.netmask,
2621 (struct sockaddr_storage **) &addr->netmask, errbuf) == -1)
2622 {
2623 freeaddr(addr);
2624 goto error;
2625 }
2626 if (rpcap_deseraddr(&ifaddr.broadaddr,
2627 (struct sockaddr_storage **) &addr->broadaddr, errbuf) == -1)
2628 {
2629 freeaddr(addr);
2630 goto error;
2631 }
2632 if (rpcap_deseraddr(&ifaddr.dstaddr,
2633 (struct sockaddr_storage **) &addr->dstaddr, errbuf) == -1)
2634 {
2635 freeaddr(addr);
2636 goto error;
2637 }
2638
2639 if ((addr->addr == NULL) && (addr->netmask == NULL) &&
2640 (addr->broadaddr == NULL) && (addr->dstaddr == NULL))
2641 {
2642 /*
2643 * None of the addresses are IPv4 or IPv6
2644 * addresses, so throw this entry away.
2645 */
2646 free(addr);
2647 }
2648 else
2649 {
2650 /*
2651 * Add this entry to the list.
2652 */
2653 if (prevaddr == NULL)
2654 {
2655 dev->addresses = addr;
2656 }
2657 else
2658 {
2659 prevaddr->next = addr;
2660 }
2661 prevaddr = addr;
2662 }
2663 }
2664 }
2665
2666 /* Checks if all the data has been read; if not, discard the data in excess */
2667 if (totread != ntohl(header.plen))
2668 {
2669 if (sock_discard(sockctrl, ntohl(header.plen) - totread, errbuf, PCAP_ERRBUF_SIZE) == 1)
2670 return -1;
2671 }
2672
2673 /* Control connection has to be closed only in case the remote machine is in passive mode */
2674 if (!active)
2675 {
2676 /* DO not send RPCAP_CLOSE, since we did not open a pcap_t; no need to free resources */
2677 if (sock_close(sockctrl, errbuf, PCAP_ERRBUF_SIZE))
2678 return -1;
2679 }
2680
2681 /* To avoid inconsistencies in the number of sock_init() */
2682 sock_cleanup();
2683
2684 return 0;
2685
2686 error:
2687 /*
2688 * In case there has been an error, I don't want to overwrite it with a new one
2689 * if the following call fails. I want to return always the original error.
2690 *
2691 * Take care: this connection can already be closed when we try to close it.
2692 * This happens because a previous error in the rpcapd, which requested to
2693 * closed the connection. In that case, we already recognized that into the
2694 * rpspck_isheaderok() and we already acknowledged the closing.
2695 * In that sense, this call is useless here (however it is needed in case
2696 * the client generates the error).
2697 *
2698 * Checks if all the data has been read; if not, discard the data in excess
2699 */
2700 if (totread != ntohl(header.plen))
2701 {
2702 if (sock_discard(sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
2703 return -1;
2704 }
2705
2706 /* Control connection has to be closed only in case the remote machine is in passive mode */
2707 if (!active)
2708 sock_close(sockctrl, NULL, 0);
2709
2710 /* To avoid inconsistencies in the number of sock_init() */
2711 sock_cleanup();
2712
2713 return -1;
2714 }