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