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