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