2 * Copyright (c) 2002 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2008 CACE Technologies, Davis (California)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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
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.
39 #include "diag-control.h"
41 #include <string.h> /* for strlen(), ... */
42 #include <stdlib.h> /* for malloc(), free(), ... */
43 #include <stdarg.h> /* for functions with variable number of arguments */
44 #include <errno.h> /* for the errno variable */
45 #include <limits.h> /* for INT_MAX */
46 #include "sockutils.h"
48 #include "pcap-util.h"
49 #include "rpcap-protocol.h"
50 #include "pcap-rpcap.h"
53 #include "charconv.h" /* for utf_8_to_acp_truncated() */
61 * This file contains the pcap module for capturing from a remote machine's
62 * interfaces using the RPCAP protocol.
64 * WARNING: All the RPCAP functions that are allowed to return a buffer
65 * containing the error description can return max PCAP_ERRBUF_SIZE characters.
66 * However there is no guarantees that the string will be zero-terminated.
67 * Best practice is to define the errbuf variable as a char of size
68 * 'PCAP_ERRBUF_SIZE+1' and to insert manually a NULL character at the end
69 * of the buffer. This will guarantee that no buffer overflows occur even
70 * if we use the printf() to show the error on the screen.
72 * XXX - actually, null-terminating the error string is part of the
73 * contract for the pcap API; if there's any place in the pcap code
74 * that doesn't guarantee null-termination, even at the expense of
75 * cutting the message short, that's a bug and needs to be fixed.
78 #define PCAP_STATS_STANDARD 0 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
80 #define PCAP_STATS_EX 1 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
84 * \brief Keeps a list of all the opened connections in the active mode.
86 * This structure defines a linked list of items that are needed to keep the info required to
87 * manage the active mode.
88 * In other words, when a new connection in active mode starts, this structure is updated so that
89 * it reflects the list of active mode connections currently opened.
90 * This structure is required by findalldevs() and open_remote() to see if they have to open a new
91 * control connection toward the host, or they already have a control connection in place.
95 struct sockaddr_storage host
;
98 uint8_t protocol_version
;
100 struct activehosts
*next
;
103 /* Keeps a list of all the opened connections in the active mode. */
104 static struct activehosts
*activeHosts
;
107 * Keeps the main socket identifier when we want to accept a new remote
108 * connection (active mode only).
109 * See the documentation of pcap_remoteact_accept() and
110 * pcap_remoteact_cleanup() for more details.
112 static SOCKET sockmain
;
113 static SSL
*ssl_main
;
116 * Private data for capturing remotely using the rpcap protocol.
120 * This is '1' if we're the network client; it is needed by several
121 * functions (such as pcap_setfilter()) to know whether they have
122 * to use the socket or have to open the local adapter.
126 SOCKET rmt_sockctrl
; /* socket ID of the socket used for the control connection */
127 SOCKET rmt_sockdata
; /* socket ID of the socket used for the data connection */
128 SSL
*ctrl_ssl
, *data_ssl
; /* optional transport of rmt_sockctrl and rmt_sockdata via TLS */
129 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() */
130 int rmt_capstarted
; /* 'true' if the capture is already started (needed to knoe if we have to call the pcap_startcapture() */
131 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. */
133 uint8_t protocol_version
; /* negotiated protocol version */
134 uint8_t uses_ssl
; /* User asked for rpcaps scheme */
135 int byte_swapped
; /* Server byte order is swapped from ours */
137 unsigned int TotNetDrops
; /* keeps the number of packets that have been dropped by the network */
140 * This keeps the number of packets that have been received by the
143 * Packets dropped by the kernel buffer are not counted in this
144 * variable. It is always equal to (TotAccepted - TotDrops),
145 * except for the case of remote capture, in which we have also
146 * packets in flight, i.e. that have been transmitted by the remote
147 * host, but that have not been received (yet) from the client.
148 * In this case, (TotAccepted - TotDrops - TotNetDrops) gives a
149 * wrong result, since this number does not corresponds always to
150 * the number of packet received by the application. For this reason,
151 * in the remote capture we need another variable that takes into
152 * account of the number of packets actually received by the
155 unsigned int TotCapt
;
157 struct pcap_stat stat
;
159 struct pcap
*next
; /* list of open pcaps that need stuff cleared on close */
162 /****************************************************
164 * Locally defined functions *
166 ****************************************************/
167 static struct pcap_stat
*rpcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
, int mode
);
168 static int pcap_pack_bpffilter(pcap_t
*fp
, char *sendbuf
, int *sendbufidx
, struct bpf_program
*prog
);
169 static int pcap_createfilter_norpcappkt(pcap_t
*fp
, struct bpf_program
*prog
);
170 static int pcap_updatefilter_remote(pcap_t
*fp
, struct bpf_program
*prog
);
171 static void pcap_save_current_filter_rpcap(pcap_t
*fp
, const char *filter
);
172 static int pcap_setfilter_rpcap(pcap_t
*fp
, struct bpf_program
*prog
);
173 static int pcap_setsampling_remote(pcap_t
*fp
);
174 static int pcap_startcapture_remote(pcap_t
*fp
);
175 static int rpcap_recv_msg_header(SOCKET sock
, SSL
*, struct rpcap_header
*header
, char *errbuf
);
176 static int rpcap_check_msg_ver(SOCKET sock
, SSL
*, uint8_t expected_ver
, struct rpcap_header
*header
, char *errbuf
);
177 static int rpcap_check_msg_type(SOCKET sock
, SSL
*, uint8_t request_type
, struct rpcap_header
*header
, uint16_t *errcode
, char *errbuf
);
178 static int rpcap_process_msg_header(SOCKET sock
, SSL
*, uint8_t ver
, uint8_t request_type
, struct rpcap_header
*header
, char *errbuf
);
179 static int rpcap_recv(SOCKET sock
, SSL
*, void *buffer
, size_t toread
, uint32_t *plen
, char *errbuf
);
180 static void rpcap_msg_err(SOCKET sockctrl
, SSL
*, uint32_t plen
, char *remote_errbuf
);
181 static int rpcap_discard(SOCKET sock
, SSL
*, uint32_t len
, char *errbuf
);
182 static int rpcap_read_packet_msg(struct pcap_rpcap
const *, pcap_t
*p
, size_t size
);
184 /****************************************************
188 ****************************************************/
191 * This function translates (i.e. de-serializes) a 'rpcap_sockaddr'
192 * structure from the network byte order to a 'sockaddr_in" or
193 * 'sockaddr_in6' structure in the host byte order.
195 * It accepts an 'rpcap_sockaddr' structure as it is received from the
196 * network, and checks the address family field against various values
197 * to see whether it looks like an IPv4 address, an IPv6 address, or
198 * neither of those. It checks for multiple values in order to try
199 * to handle older rpcap daemons that sent the native OS's 'sockaddr_in'
200 * or 'sockaddr_in6' structures over the wire with some members
201 * byte-swapped, and to handle the fact that AF_INET6 has different
202 * values on different OSes.
204 * For IPv4 addresses, it converts the address family to host byte
205 * order from network byte order and puts it into the structure,
206 * sets the length if a sockaddr structure has a length, converts the
207 * port number to host byte order from network byte order and puts
208 * it into the structure, copies over the IPv4 address, and zeroes
209 * out the zero padding.
211 * For IPv6 addresses, it converts the address family to host byte
212 * order from network byte order and puts it into the structure,
213 * sets the length if a sockaddr structure has a length, converts the
214 * port number and flow information to host byte order from network
215 * byte order and puts them into the structure, copies over the IPv6
216 * address, and converts the scope ID to host byte order from network
217 * byte order and puts it into the structure.
219 * The function will allocate the 'sockaddrout' variable according to the
220 * address family in use. In case the address does not belong to the
221 * AF_INET nor AF_INET6 families, 'sockaddrout' is not allocated and a
222 * NULL pointer is returned. This usually happens because that address
223 * does not exist on the other host, or is of an address family other
224 * than AF_INET or AF_INET6, so the RPCAP daemon sent a 'sockaddr_storage'
225 * structure containing all 'zero' values.
227 * Older RPCAPDs sent the addresses over the wire in the OS's native
228 * structure format. For most OSes, this looks like the over-the-wire
229 * format, but might have a different value for AF_INET6 than the value
230 * on the machine receiving the reply. For OSes with the newer BSD-style
231 * sockaddr structures, this has, instead of a 2-byte address family,
232 * a 1-byte structure length followed by a 1-byte address family. The
233 * RPCAPD code would put the address family in network byte order before
234 * sending it; that would set it to 0 on a little-endian machine, as
235 * htons() of any value between 1 and 255 would result in a value > 255,
236 * with its lower 8 bits zero, so putting that back into a 1-byte field
239 * Therefore, for older RPCAPDs running on an OS with newer BSD-style
240 * sockaddr structures, the family field, if treated as a big-endian
241 * (network byte order) 16-bit field, would be:
243 * (length << 8) | family if sent by a big-endian machine
244 * (length << 8) if sent by a little-endian machine
246 * For current RPCAPDs, and for older RPCAPDs running on an OS with
247 * older BSD-style sockaddr structures, the family field, if treated
248 * as a big-endian 16-bit field, would just contain the family.
250 * \param sockaddrin: a 'rpcap_sockaddr' pointer to the variable that has
251 * to be de-serialized.
253 * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
254 * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
255 * This variable will be allocated automatically inside this function.
257 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
258 * that will contain the error message (in case there is one).
260 * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
261 * can be only the fact that the malloc() failed to allocate memory.
262 * The error message is returned in the 'errbuf' variable, while the deserialized address
263 * is returned into the 'sockaddrout' variable.
265 * \warning This function supports only AF_INET and AF_INET6 address families.
267 * \warning The sockaddrout (if not NULL) must be deallocated by the user.
271 * Possible IPv4 family values other than the designated over-the-wire value,
272 * which is 2 (because everybody, except for Haiku uses 2 for AF_INET,
273 * and Haiku has probably never run the old rpcapd code that put address
274 * structures directly on the wire, rather than the new rpcapd code
275 * that serializes addresses, using 2 for AF_INET).
277 #define SOCKADDR_IN_LEN 16 /* length of struct sockaddr_in */
278 #define SOCKADDR_IN6_LEN 28 /* length of struct sockaddr_in6 */
279 #define NEW_BSD_AF_INET_BE ((SOCKADDR_IN_LEN << 8) | 2)
280 #define NEW_BSD_AF_INET_LE (SOCKADDR_IN_LEN << 8)
283 * Possible IPv6 family values other than the designated over-the-wire value,
284 * which is 23 (because that's what Windows uses, and most RPCAP servers
285 * out there are probably running Windows, as WinPcap includes the server
286 * but few if any UN*Xes build and ship it).
288 * The new BSD sockaddr structure format was in place before 4.4-Lite, so
289 * all the free-software BSDs use it.
291 #define NEW_BSD_AF_INET6_BSD_BE ((SOCKADDR_IN6_LEN << 8) | 24) /* NetBSD, OpenBSD, BSD/OS */
292 #define NEW_BSD_AF_INET6_FREEBSD_BE ((SOCKADDR_IN6_LEN << 8) | 28) /* FreeBSD, DragonFly BSD */
293 #define NEW_BSD_AF_INET6_DARWIN_BE ((SOCKADDR_IN6_LEN << 8) | 30) /* macOS, iOS, anything else Darwin-based */
294 #define NEW_BSD_AF_INET6_LE (SOCKADDR_IN6_LEN << 8)
295 #define LINUX_AF_INET6 10
296 #define HPUX_AF_INET6 22
297 #define AIX_AF_INET6 24
298 #define SOLARIS_AF_INET6 26
301 rpcap_deseraddr(struct rpcap_sockaddr
*sockaddrin
, struct sockaddr_storage
**sockaddrout
, char *errbuf
)
303 /* Warning: we support only AF_INET and AF_INET6 */
304 switch (ntohs(sockaddrin
->family
))
307 case NEW_BSD_AF_INET_BE
:
308 case NEW_BSD_AF_INET_LE
:
310 struct rpcap_sockaddr_in
*sockaddrin_ipv4
;
311 struct sockaddr_in
*sockaddrout_ipv4
;
313 (*sockaddrout
) = (struct sockaddr_storage
*) malloc(sizeof(struct sockaddr_in
));
314 if ((*sockaddrout
) == NULL
)
316 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
317 errno
, "malloc() failed");
320 sockaddrin_ipv4
= (struct rpcap_sockaddr_in
*) sockaddrin
;
321 sockaddrout_ipv4
= (struct sockaddr_in
*) (*sockaddrout
);
322 sockaddrout_ipv4
->sin_family
= AF_INET
;
323 sockaddrout_ipv4
->sin_port
= ntohs(sockaddrin_ipv4
->port
);
324 memcpy(&sockaddrout_ipv4
->sin_addr
, &sockaddrin_ipv4
->addr
, sizeof(sockaddrout_ipv4
->sin_addr
));
325 memset(sockaddrout_ipv4
->sin_zero
, 0, sizeof(sockaddrout_ipv4
->sin_zero
));
331 case NEW_BSD_AF_INET6_BSD_BE
:
332 case NEW_BSD_AF_INET6_FREEBSD_BE
:
333 case NEW_BSD_AF_INET6_DARWIN_BE
:
334 case NEW_BSD_AF_INET6_LE
:
338 case SOLARIS_AF_INET6
:
340 struct rpcap_sockaddr_in6
*sockaddrin_ipv6
;
341 struct sockaddr_in6
*sockaddrout_ipv6
;
343 (*sockaddrout
) = (struct sockaddr_storage
*) malloc(sizeof(struct sockaddr_in6
));
344 if ((*sockaddrout
) == NULL
)
346 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
347 errno
, "malloc() failed");
350 sockaddrin_ipv6
= (struct rpcap_sockaddr_in6
*) sockaddrin
;
351 sockaddrout_ipv6
= (struct sockaddr_in6
*) (*sockaddrout
);
352 sockaddrout_ipv6
->sin6_family
= AF_INET6
;
353 sockaddrout_ipv6
->sin6_port
= ntohs(sockaddrin_ipv6
->port
);
354 sockaddrout_ipv6
->sin6_flowinfo
= ntohl(sockaddrin_ipv6
->flowinfo
);
355 memcpy(&sockaddrout_ipv6
->sin6_addr
, &sockaddrin_ipv6
->addr
, sizeof(sockaddrout_ipv6
->sin6_addr
));
356 sockaddrout_ipv6
->sin6_scope_id
= ntohl(sockaddrin_ipv6
->scope_id
);
363 * It is neither AF_INET nor AF_INET6 (or, if the OS doesn't
364 * support AF_INET6, it's not AF_INET).
373 * This function reads a packet from the network socket. It does not
374 * deliver the packet to a pcap_dispatch()/pcap_loop() callback (hence
375 * the "nocb" string into its name).
377 * This function is called by pcap_read_rpcap().
379 * WARNING: By choice, this function does not make use of semaphores. A smarter
380 * implementation should put a semaphore into the data thread, and a signal will
381 * be raised as soon as there is data into the socket buffer.
382 * However this is complicated and it does not bring any advantages when reading
383 * from the network, in which network delays can be much more important than
384 * these optimizations. Therefore, we chose the following approach:
385 * - the 'timeout' chosen by the user is split in two (half on the server side,
386 * with the usual meaning, and half on the client side)
387 * - this function checks for packets; if there are no packets, it waits for
388 * timeout/2 and then it checks again. If packets are still missing, it returns,
389 * otherwise it reads packets.
391 static int pcap_read_nocb_remote(pcap_t
*p
, struct pcap_pkthdr
*pkt_header
, u_char
**pkt_data
)
393 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
394 struct rpcap_header
*header
; /* general header according to the RPCAP format */
395 struct rpcap_pkthdr
*net_pkt_header
; /* header of the packet, from the message */
396 u_char
*net_pkt_data
; /* packet data from the message */
398 int retval
= 0; /* generic return value */
401 /* Structures needed for the select() call */
402 struct timeval tv
; /* maximum time the select() can block waiting for data */
403 fd_set rfds
; /* set of socket descriptors we have to check */
406 * Define the packet buffer timeout, to be used in the select()
407 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
409 tv
.tv_sec
= p
->opt
.timeout
/ 1000;
410 tv
.tv_usec
= (suseconds_t
)((p
->opt
.timeout
- tv
.tv_sec
* 1000) * 1000);
413 /* Check if we still have bytes available in the last decoded TLS record.
414 * If that's the case, we know SSL_read will not block. */
415 retval
= pr
->data_ssl
&& SSL_pending(pr
->data_ssl
) > 0;
419 /* Watch out sockdata to see if it has input */
423 * 'fp->rmt_sockdata' has always to be set before calling the select(),
424 * since it is cleared by the select()
426 FD_SET(pr
->rmt_sockdata
, &rfds
);
428 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
431 retval
= select((int) pr
->rmt_sockdata
+ 1, &rfds
, NULL
, NULL
, &tv
);
443 sock_geterrmsg(p
->errbuf
, PCAP_ERRBUF_SIZE
,
449 /* There is no data waiting, so return '0' */
454 * We have to define 'header' as a pointer to a larger buffer,
455 * because in case of UDP we have to read all the message within a single call
457 header
= (struct rpcap_header
*) p
->buffer
;
458 net_pkt_header
= (struct rpcap_pkthdr
*) ((char *)p
->buffer
+ sizeof(struct rpcap_header
));
459 net_pkt_data
= p
->buffer
+ sizeof(struct rpcap_header
) + sizeof(struct rpcap_pkthdr
);
461 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
463 /* Read the entire message from the network */
464 msglen
= sock_recv_dgram(pr
->rmt_sockdata
, pr
->data_ssl
, p
->buffer
,
465 p
->bufsize
, p
->errbuf
, PCAP_ERRBUF_SIZE
);
473 /* Interrupted receive. */
476 if ((size_t)msglen
< sizeof(struct rpcap_header
))
479 * Message is shorter than an rpcap header.
481 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
482 "UDP packet message is shorter than an rpcap header");
485 plen
= ntohl(header
->plen
);
486 if ((size_t)msglen
< sizeof(struct rpcap_header
) + plen
)
489 * Message is shorter than the header claims it
492 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
493 "UDP packet message is shorter than its rpcap header claims");
501 if ((size_t)p
->cc
< sizeof(struct rpcap_header
))
504 * We haven't read any of the packet header yet.
505 * The size we should get is the size of the
508 status
= rpcap_read_packet_msg(pr
, p
, sizeof(struct rpcap_header
));
516 /* Interrupted receive. */
522 * We have the header, so we know how long the
523 * message payload is. The size we should get
524 * is the size of the packet header plus the
525 * size of the payload.
527 plen
= ntohl(header
->plen
);
528 if (plen
> p
->bufsize
- sizeof(struct rpcap_header
))
531 * This is bigger than the largest
532 * record we'd expect. (We do it by
533 * subtracting in order to avoid an
536 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
537 "Server sent us a message larger than the largest expected packet message");
540 status
= rpcap_read_packet_msg(pr
, p
, sizeof(struct rpcap_header
) + plen
);
548 /* Interrupted receive. */
553 * We have the entire message; reset the buffer pointer
554 * and count, as the next read should start a new
562 * We have the entire message.
567 * Did the server specify the version we negotiated?
569 if (rpcap_check_msg_ver(pr
->rmt_sockdata
, pr
->data_ssl
, pr
->protocol_version
,
570 header
, p
->errbuf
) == -1)
572 return 0; /* Return 'no packets received' */
576 * Is this a RPCAP_MSG_PACKET message?
578 if (header
->type
!= RPCAP_MSG_PACKET
)
580 return 0; /* Return 'no packets received' */
583 if (ntohl(net_pkt_header
->caplen
) > plen
)
585 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
586 "Packet's captured data goes past the end of the received packet message.");
590 /* Fill in packet header */
591 pkt_header
->caplen
= ntohl(net_pkt_header
->caplen
);
592 pkt_header
->len
= ntohl(net_pkt_header
->len
);
593 pkt_header
->ts
.tv_sec
= ntohl(net_pkt_header
->timestamp_sec
);
594 pkt_header
->ts
.tv_usec
= ntohl(net_pkt_header
->timestamp_usec
);
596 /* Supply a pointer to the beginning of the packet data */
597 *pkt_data
= net_pkt_data
;
600 * I don't update the counter of the packets dropped by the network since we're using TCP,
601 * therefore no packets are dropped. Just update the number of packets received correctly
605 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
609 /* We're using UDP, so we need to update the counter of the packets dropped by the network */
610 npkt
= ntohl(net_pkt_header
->npkt
);
612 if (pr
->TotCapt
!= npkt
)
614 pr
->TotNetDrops
+= (npkt
- pr
->TotCapt
);
619 /* Packet read successfully */
624 * This function reads a packet from the network socket.
626 * This function relies on the pcap_read_nocb_remote to deliver packets. The
627 * difference, here, is that as soon as a packet is read, it is delivered
628 * to the application by means of a callback function.
630 static int pcap_read_rpcap(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
632 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
633 struct pcap_pkthdr pkt_header
;
639 * If this is client-side, and we haven't already started
640 * the capture, start it now.
642 if (pr
->rmt_clientside
)
644 /* We are on an remote capture */
645 if (!pr
->rmt_capstarted
)
648 * The capture isn't started yet, so try to
651 if (pcap_startcapture_remote(p
))
657 * This can conceivably process more than INT_MAX packets,
658 * which would overflow the packet count, causing it either
659 * to look like a negative number, and thus cause us to
660 * return a value that looks like an error, or overflow
661 * back into positive territory, and thus cause us to
662 * return a too-low count.
664 * Therefore, if the packet count is unlimited, we clip
665 * it at INT_MAX; this routine is not expected to
666 * process packets indefinitely, so that's not an issue.
668 if (PACKET_COUNT_IS_UNLIMITED(cnt
))
671 while (n
< cnt
|| PACKET_COUNT_IS_UNLIMITED(cnt
))
674 * Has "pcap_breakloop()" been called?
678 * Yes - clear the flag that indicates that it
679 * has, and return PCAP_ERROR_BREAK to indicate
680 * that we were told to break out of the loop.
683 return (PCAP_ERROR_BREAK
);
689 ret
= pcap_read_nocb_remote(p
, &pkt_header
, &pkt_data
);
695 * Do whatever post-processing is necessary, hand
696 * it to the callback, and count it so we can
699 pcap_post_process(p
->linktype
, pr
->byte_swapped
,
700 &pkt_header
, pkt_data
);
701 (*callback
)(user
, &pkt_header
, pkt_data
);
712 * No packet; this could mean that we timed
713 * out, or that we got interrupted, or that
714 * we got a bad packet.
716 * Were we told to break out of the loop?
723 return (PCAP_ERROR_BREAK
);
725 /* No - return the number of packets we've processed. */
733 * This function sends a CLOSE command to the capture server if we're in
734 * passive mode and an ENDCAP command to the capture server if we're in
737 * It is called when the user calls pcap_close(). It sends a command
738 * to our peer that says 'ok, let's stop capturing'.
740 * WARNING: Since we're closing the connection, we do not check for errors.
742 static void pcap_cleanup_rpcap(pcap_t
*fp
)
744 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
745 struct rpcap_header header
; /* header of the RPCAP packet */
746 struct activehosts
*temp
; /* temp var needed to scan the host list chain, to detect if we're in active mode */
747 int active
= 0; /* active mode or not? */
749 /* detect if we're in active mode */
753 if (temp
->sockctrl
== pr
->rmt_sockctrl
)
763 rpcap_createhdr(&header
, pr
->protocol_version
,
764 RPCAP_MSG_CLOSE
, 0, 0);
767 * Send the close request; don't report any errors, as
768 * we're closing this pcap_t, and have no place to report
769 * the error. No reply is sent to this message.
771 (void)sock_send(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, (char *)&header
,
772 sizeof(struct rpcap_header
), NULL
, 0);
776 rpcap_createhdr(&header
, pr
->protocol_version
,
777 RPCAP_MSG_ENDCAP_REQ
, 0, 0);
780 * Send the end capture request; don't report any errors,
781 * as we're closing this pcap_t, and have no place to
784 if (sock_send(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, (char *)&header
,
785 sizeof(struct rpcap_header
), NULL
, 0) == 0)
788 * Wait for the answer; don't report any errors,
789 * as we're closing this pcap_t, and have no
790 * place to report the error.
792 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->ctrl_ssl
,
793 pr
->protocol_version
, RPCAP_MSG_ENDCAP_REQ
,
796 (void)rpcap_discard(pr
->rmt_sockctrl
, pr
->ctrl_ssl
,
802 if (pr
->rmt_sockdata
)
807 // Finish using the SSL handle for the data socket.
808 // This must be done *before* the socket is closed.
809 ssl_finish(pr
->data_ssl
);
813 sock_close(pr
->rmt_sockdata
, NULL
, 0);
814 pr
->rmt_sockdata
= 0;
817 if ((!active
) && (pr
->rmt_sockctrl
))
822 // Finish using the SSL handle for the control socket.
823 // This must be done *before* the socket is closed.
824 ssl_finish(pr
->ctrl_ssl
);
828 sock_close(pr
->rmt_sockctrl
, NULL
, 0);
831 pr
->rmt_sockctrl
= 0;
834 if (pr
->currentfilter
)
836 free(pr
->currentfilter
);
837 pr
->currentfilter
= NULL
;
840 pcap_cleanup_live_common(fp
);
842 /* To avoid inconsistencies in the number of sock_init() */
847 * This function retrieves network statistics from our peer;
848 * it provides only the standard statistics.
850 static int pcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
)
852 struct pcap_stat
*retval
;
854 retval
= rpcap_stats_rpcap(p
, ps
, PCAP_STATS_STANDARD
);
864 * This function retrieves network statistics from our peer;
865 * it provides the additional statistics supported by pcap_stats_ex().
867 static struct pcap_stat
*pcap_stats_ex_rpcap(pcap_t
*p
, int *pcap_stat_size
)
869 *pcap_stat_size
= sizeof (p
->stat
);
871 /* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
872 return (rpcap_stats_rpcap(p
, &(p
->stat
), PCAP_STATS_EX
));
877 * This function retrieves network statistics from our peer. It
878 * is used by the two previous functions.
880 * It can be called in two modes:
881 * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e.,
883 * - PCAP_STATS_EX: if we want extended statistics (i.e., for
886 * This 'mode' parameter is needed because in pcap_stats() the variable that
887 * keeps the statistics is allocated by the user. On Windows, this structure
888 * has been extended in order to keep new stats. However, if the user has a
889 * smaller structure and it passes it to pcap_stats(), this function will
890 * try to fill in more data than the size of the structure, so that memory
891 * after the structure will be overwritten.
893 * So, we need to know it we have to copy just the standard fields, or the
894 * extended fields as well.
896 * In case we want to copy the extended fields as well, the problem of
897 * memory overflow no longer exists because the structure that's filled
898 * in is part of the pcap_t, so that it can be guaranteed to be large
899 * enough for the additional statistics.
901 * \param p: the pcap_t structure related to the current instance.
903 * \param ps: a pointer to a 'pcap_stat' structure, needed for compatibility
904 * with pcap_stat(), where the structure is allocated by the user. In case
905 * of pcap_stats_ex(), this structure and the function return value point
906 * to the same variable.
908 * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
910 * \return The structure that keeps the statistics, or NULL in case of error.
911 * The error string is placed in the pcap_t structure.
913 static struct pcap_stat
*rpcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
, int mode
)
915 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
916 struct rpcap_header header
; /* header of the RPCAP packet */
917 struct rpcap_stats netstats
; /* statistics sent on the network */
918 uint32_t plen
; /* data remaining in the message */
921 if (mode
!= PCAP_STATS_STANDARD
&& mode
!= PCAP_STATS_EX
)
923 if (mode
!= PCAP_STATS_STANDARD
)
926 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
927 "Invalid stats mode %d", mode
);
932 * If the capture has not yet started, we cannot request statistics
933 * for the capture from our peer, so we return 0 for all statistics,
934 * as nothing's been seen yet.
936 if (!pr
->rmt_capstarted
)
942 if (mode
== PCAP_STATS_EX
)
953 rpcap_createhdr(&header
, pr
->protocol_version
,
954 RPCAP_MSG_STATS_REQ
, 0, 0);
956 /* Send the PCAP_STATS command */
957 if (sock_send(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, (char *)&header
,
958 sizeof(struct rpcap_header
), p
->errbuf
, PCAP_ERRBUF_SIZE
) < 0)
959 return NULL
; /* Unrecoverable network error */
961 /* Receive and process the reply message header. */
962 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, pr
->protocol_version
,
963 RPCAP_MSG_STATS_REQ
, &header
, p
->errbuf
) == -1)
964 return NULL
; /* Error */
968 /* Read the reply body */
969 if (rpcap_recv(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, (char *)&netstats
,
970 sizeof(struct rpcap_stats
), &plen
, p
->errbuf
) == -1)
973 ps
->ps_drop
= ntohl(netstats
.krnldrop
);
974 ps
->ps_ifdrop
= ntohl(netstats
.ifdrop
);
975 ps
->ps_recv
= ntohl(netstats
.ifrecv
);
977 if (mode
== PCAP_STATS_EX
)
979 ps
->ps_capt
= pr
->TotCapt
;
980 ps
->ps_netdrop
= pr
->TotNetDrops
;
981 ps
->ps_sent
= ntohl(netstats
.svrcapt
);
985 /* Discard the rest of the message. */
986 if (rpcap_discard(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, plen
, p
->errbuf
) == -1)
987 goto error_nodiscard
;
993 * Discard the rest of the message.
994 * We already reported an error; if this gets an error, just
997 (void)rpcap_discard(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, plen
, NULL
);
1004 * This function returns the entry in the list of active hosts for this
1005 * active connection (active mode only), or NULL if there is no
1006 * active connection or an error occurred. It is just for internal
1009 * \param host: a string that keeps the host name of the host for which we
1010 * want to get the socket ID for that active connection.
1012 * \param error: a pointer to an int that is set to 1 if an error occurred
1015 * \param errbuf: a pointer to a user-allocated buffer (of size
1016 * PCAP_ERRBUF_SIZE) that will contain the error message (in case
1019 * \return the entry for this host in the list of active connections
1020 * if found, NULL if it's not found or there's an error.
1022 static struct activehosts
*
1023 rpcap_remoteact_getsock(const char *host
, int *error
, char *errbuf
)
1025 struct activehosts
*temp
; /* temp var needed to scan the host list chain */
1026 struct addrinfo hints
, *addrinfo
, *ai_next
; /* temp var needed to translate between hostname to its address */
1029 /* retrieve the network address corresponding to 'host' */
1031 memset(&hints
, 0, sizeof(struct addrinfo
));
1032 hints
.ai_family
= PF_UNSPEC
;
1033 hints
.ai_socktype
= SOCK_STREAM
;
1035 retval
= sock_initaddress(host
, NULL
, &hints
, &addrinfo
, errbuf
,
1050 if (sock_cmpaddr(&temp
->host
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
1053 freeaddrinfo(addrinfo
);
1057 ai_next
= ai_next
->ai_next
;
1063 freeaddrinfo(addrinfo
);
1066 * The host for which you want to get the socket ID does not have an
1067 * active connection.
1074 * This function starts a remote capture.
1076 * This function is required since the RPCAP protocol decouples the 'open'
1077 * from the 'start capture' functions.
1078 * This function takes all the parameters needed (which have been stored
1079 * into the pcap_t structure) and sends them to the server.
1081 * \param fp: the pcap_t descriptor of the device currently open.
1083 * \return '0' if everything is fine, '-1' otherwise. The error message
1084 * (if one) is returned into the 'errbuf' field of the pcap_t structure.
1086 static int pcap_startcapture_remote(pcap_t
*fp
)
1088 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1089 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
1090 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1091 uint16_t portdata
= 0; /* temp variable needed to keep the network port for the data connection */
1093 int active
= 0; /* '1' if we're in active mode */
1094 struct activehosts
*temp
; /* temp var needed to scan the host list chain, to detect if we're in active mode */
1095 char host
[INET6_ADDRSTRLEN
+ 1]; /* numeric name of the other host */
1097 /* socket-related variables*/
1098 struct addrinfo hints
; /* temp, needed to open a socket connection */
1099 struct addrinfo
*addrinfo
; /* temp, needed to open a socket connection */
1100 SOCKET sockdata
= 0; /* socket descriptor of the data connection */
1101 struct sockaddr_storage saddr
; /* temp, needed to retrieve the network data port chosen on the local machine */
1102 socklen_t saddrlen
; /* temp, needed to retrieve the network data port chosen on the local machine */
1103 int ai_family
; /* temp, keeps the address family used by the control connection */
1104 struct sockaddr_in
*sin4
;
1105 struct sockaddr_in6
*sin6
;
1107 /* RPCAP-related variables*/
1108 struct rpcap_header header
; /* header of the RPCAP packet */
1109 struct rpcap_startcapreq
*startcapreq
; /* start capture request message */
1110 struct rpcap_startcapreply startcapreply
; /* start capture reply message */
1112 /* Variables related to the buffer setting */
1115 int sockbufsize
= 0;
1116 uint32_t server_sockbufsize
;
1118 // Take the opportunity to clear pr->data_ssl before any goto error,
1119 // as it seems p->priv is not zeroed after its malloced.
1120 // XXX - it now should be, as it's allocated by pcap_alloc_pcap_t(),
1121 // which does a calloc().
1122 pr
->data_ssl
= NULL
;
1125 * Let's check if sampling has been required.
1126 * If so, let's set it first
1128 if (pcap_setsampling_remote(fp
) != 0)
1131 /* detect if we're in active mode */
1135 if (temp
->sockctrl
== pr
->rmt_sockctrl
)
1146 * Gets the complete sockaddr structure used in the ctrl connection
1147 * This is needed to get the address family of the control socket
1148 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
1149 * since the ctrl socket can already be open in case of active mode;
1150 * so I would have to call getpeername() anyway
1152 saddrlen
= sizeof(struct sockaddr_storage
);
1153 if (getpeername(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1155 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1156 "getsockname() failed");
1157 goto error_nodiscard
;
1159 ai_family
= ((struct sockaddr_storage
*) &saddr
)->ss_family
;
1161 /* Get the numeric address of the remote host we are connected to */
1162 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, host
,
1163 sizeof(host
), NULL
, 0, NI_NUMERICHOST
))
1165 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1166 "getnameinfo() failed");
1167 goto error_nodiscard
;
1171 * Data connection is opened by the server toward the client if:
1172 * - we're using TCP, and the user wants us to be in active mode
1175 if ((active
) || (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1178 * We have to create a new socket to receive packets
1179 * We have to do that immediately, since we have to tell the other
1180 * end which network port we picked up
1182 memset(&hints
, 0, sizeof(struct addrinfo
));
1183 /* TEMP addrinfo is NULL in case of active */
1184 hints
.ai_family
= ai_family
; /* Use the same address family of the control socket */
1185 hints
.ai_socktype
= (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
) ? SOCK_DGRAM
: SOCK_STREAM
;
1186 hints
.ai_flags
= AI_PASSIVE
; /* Data connection is opened by the server toward the client */
1188 /* Let's the server pick up a free network port for us */
1189 if (sock_initaddress(NULL
, NULL
, &hints
, &addrinfo
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1190 goto error_nodiscard
;
1192 if ((sockdata
= sock_open(NULL
, addrinfo
, SOCKOPEN_SERVER
,
1193 1 /* max 1 connection in queue */, fp
->errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1194 goto error_nodiscard
;
1196 /* addrinfo is no longer used */
1197 freeaddrinfo(addrinfo
);
1200 /* get the complete sockaddr structure used in the data connection */
1201 saddrlen
= sizeof(struct sockaddr_storage
);
1202 if (getsockname(sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1204 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1205 "getsockname() failed");
1206 goto error_nodiscard
;
1209 switch (saddr
.ss_family
) {
1212 sin4
= (struct sockaddr_in
*)&saddr
;
1213 portdata
= sin4
->sin_port
;
1217 sin6
= (struct sockaddr_in6
*)&saddr
;
1218 portdata
= sin6
->sin6_port
;
1222 snprintf(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1223 "Local address has unknown address family %u",
1225 goto error_nodiscard
;
1230 * Now it's time to start playing with the RPCAP protocol
1231 * RPCAP start capture command: create the request message
1233 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1234 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1235 goto error_nodiscard
;
1237 rpcap_createhdr((struct rpcap_header
*) sendbuf
,
1238 pr
->protocol_version
, RPCAP_MSG_STARTCAP_REQ
, 0,
1239 sizeof(struct rpcap_startcapreq
) + sizeof(struct rpcap_filter
) + fp
->fcode
.bf_len
* sizeof(struct rpcap_filterbpf_insn
));
1241 /* Fill the structure needed to open an adapter remotely */
1242 startcapreq
= (struct rpcap_startcapreq
*) &sendbuf
[sendbufidx
];
1244 if (sock_bufferize(NULL
, sizeof(struct rpcap_startcapreq
), NULL
,
1245 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1246 goto error_nodiscard
;
1248 memset(startcapreq
, 0, sizeof(struct rpcap_startcapreq
));
1250 /* By default, apply half the timeout on one side, half of the other */
1251 fp
->opt
.timeout
= fp
->opt
.timeout
/ 2;
1252 startcapreq
->read_timeout
= htonl(fp
->opt
.timeout
);
1254 /* portdata on the openreq is meaningful only if we're in active mode */
1255 if ((active
) || (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1257 startcapreq
->portdata
= portdata
;
1260 startcapreq
->snaplen
= htonl(fp
->snapshot
);
1261 startcapreq
->flags
= 0;
1263 if (pr
->rmt_flags
& PCAP_OPENFLAG_PROMISCUOUS
)
1264 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_PROMISC
;
1265 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
1266 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_DGRAM
;
1268 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN
;
1270 startcapreq
->flags
= htons(startcapreq
->flags
);
1272 /* Pack the capture filter */
1273 if (pcap_pack_bpffilter(fp
, &sendbuf
[sendbufidx
], &sendbufidx
, &fp
->fcode
))
1274 goto error_nodiscard
;
1276 if (sock_send(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, sendbuf
, sendbufidx
, fp
->errbuf
,
1277 PCAP_ERRBUF_SIZE
) < 0)
1278 goto error_nodiscard
;
1280 /* Receive and process the reply message header. */
1281 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, pr
->protocol_version
,
1282 RPCAP_MSG_STARTCAP_REQ
, &header
, fp
->errbuf
) == -1)
1283 goto error_nodiscard
;
1287 if (rpcap_recv(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, (char *)&startcapreply
,
1288 sizeof(struct rpcap_startcapreply
), &plen
, fp
->errbuf
) == -1)
1292 * In case of UDP data stream, the connection is always opened by the daemon
1293 * So, this case is already covered by the code above.
1294 * Now, we have still to handle TCP connections, because:
1295 * - if we're in active mode, we have to wait for a remote connection
1296 * - if we're in passive more, we have to start a connection
1298 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1299 * to tell the port we're using to the remote side; in case we're accepting a TCP
1300 * connection, we have to wait this info from the remote side.
1302 if (!(pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1306 char portstring
[PCAP_BUF_SIZE
];
1308 memset(&hints
, 0, sizeof(struct addrinfo
));
1309 hints
.ai_family
= ai_family
; /* Use the same address family of the control socket */
1310 hints
.ai_socktype
= (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
) ? SOCK_DGRAM
: SOCK_STREAM
;
1311 snprintf(portstring
, PCAP_BUF_SIZE
, "%d", ntohs(startcapreply
.portdata
));
1313 /* Let's the server pick up a free network port for us */
1314 if (sock_initaddress(host
, portstring
, &hints
, &addrinfo
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1317 if ((sockdata
= sock_open(host
, addrinfo
, SOCKOPEN_CLIENT
, 0, fp
->errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1320 /* addrinfo is no longer used */
1321 freeaddrinfo(addrinfo
);
1326 SOCKET socktemp
; /* We need another socket, since we're going to accept() a connection */
1328 /* Connection creation */
1329 saddrlen
= sizeof(struct sockaddr_storage
);
1331 socktemp
= accept(sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
);
1333 if (socktemp
== INVALID_SOCKET
)
1335 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1340 /* Now that I accepted the connection, the server socket is no longer needed */
1341 sock_close(sockdata
, fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1342 sockdata
= socktemp
;
1346 /* Let's save the socket of the data connection */
1347 pr
->rmt_sockdata
= sockdata
;
1352 pr
->data_ssl
= ssl_promotion(0, sockdata
, fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1353 if (! pr
->data_ssl
) goto error
;
1358 * Set the size of the socket buffer for the data socket.
1359 * It has the same size as the local capture buffer used
1360 * on the other side of the connection.
1362 server_sockbufsize
= ntohl(startcapreply
.bufsize
);
1364 /* Let's get the actual size of the socket buffer */
1365 itemp
= sizeof(sockbufsize
);
1367 res
= getsockopt(sockdata
, SOL_SOCKET
, SO_RCVBUF
, (char *)&sockbufsize
, &itemp
);
1370 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1371 "pcap_startcapture_remote(): getsockopt() failed");
1376 * Warning: on some kernels (e.g. Linux), the size of the user
1377 * buffer does not take into account the pcap_header and such,
1378 * and it is set equal to the snaplen.
1380 * In my view, this is wrong (the meaning of the bufsize became
1381 * a bit strange). So, here bufsize is the whole size of the
1382 * user buffer. In case the bufsize returned is too small,
1383 * let's adjust it accordingly.
1385 if (server_sockbufsize
<= (u_int
) fp
->snapshot
)
1386 server_sockbufsize
+= sizeof(struct pcap_pkthdr
);
1388 /* if the current socket buffer is smaller than the desired one */
1389 if ((u_int
) sockbufsize
< server_sockbufsize
)
1392 * Loop until the buffer size is OK or the original
1393 * socket buffer size is larger than this one.
1397 res
= setsockopt(sockdata
, SOL_SOCKET
, SO_RCVBUF
,
1398 (char *)&(server_sockbufsize
),
1399 sizeof(server_sockbufsize
));
1405 * If something goes wrong, halve the buffer size
1406 * (checking that it does not become smaller than
1409 server_sockbufsize
/= 2;
1411 if ((u_int
) sockbufsize
>= server_sockbufsize
)
1413 server_sockbufsize
= sockbufsize
;
1420 * Let's allocate the packet; this is required in order to put
1421 * the packet somewhere when extracting data from the socket.
1422 * Since buffering has already been done in the socket buffer,
1423 * here we need just a buffer whose size is equal to the
1424 * largest possible packet message for the snapshot size,
1425 * namely the length of the message header plus the length
1426 * of the packet header plus the snapshot length.
1428 fp
->bufsize
= sizeof(struct rpcap_header
) + sizeof(struct rpcap_pkthdr
) + fp
->snapshot
;
1430 fp
->buffer
= (u_char
*)malloc(fp
->bufsize
);
1431 if (fp
->buffer
== NULL
)
1433 pcap_fmt_errmsg_for_errno(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1439 * The buffer is currently empty.
1441 fp
->bp
= fp
->buffer
;
1444 /* Discard the rest of the message. */
1445 if (rpcap_discard(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, plen
, fp
->errbuf
) == -1)
1446 goto error_nodiscard
;
1449 * In case the user does not want to capture RPCAP packets, let's update the filter
1450 * We have to update it here (instead of sending it into the 'StartCapture' message
1451 * because when we generate the 'start capture' we do not know (yet) all the ports
1452 * we're currently using.
1454 if (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
)
1456 struct bpf_program fcode
;
1458 if (pcap_createfilter_norpcappkt(fp
, &fcode
) == -1)
1461 /* We cannot use 'pcap_setfilter_rpcap' because formally the capture has not been started yet */
1462 /* (the 'pr->rmt_capstarted' variable will be updated some lines below) */
1463 if (pcap_updatefilter_remote(fp
, &fcode
) == -1)
1466 pcap_freecode(&fcode
);
1469 pr
->rmt_capstarted
= 1;
1474 * When the connection has been established, we have to close it. So, at the
1475 * beginning of this function, if an error occur we return immediately with
1476 * a return NULL; when the connection is established, we have to come here
1477 * ('goto error;') in order to close everything properly.
1481 * Discard the rest of the message.
1482 * We already reported an error; if this gets an error, just
1485 (void)rpcap_discard(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, plen
, NULL
);
1491 // Finish using the SSL handle for the data socket.
1492 // This must be done *before* the socket is closed.
1493 ssl_finish(pr
->data_ssl
);
1494 pr
->data_ssl
= NULL
;
1498 /* we can be here because sockdata said 'error' */
1499 if ((sockdata
!= 0) && (sockdata
!= INVALID_SOCKET
))
1500 sock_close(sockdata
, NULL
, 0);
1507 // Finish using the SSL handle for the control socket.
1508 // This must be done *before* the socket is closed.
1509 ssl_finish(pr
->ctrl_ssl
);
1510 pr
->ctrl_ssl
= NULL
;
1513 sock_close(pr
->rmt_sockctrl
, NULL
, 0);
1516 if (addrinfo
!= NULL
)
1517 freeaddrinfo(addrinfo
);
1520 * We do not have to call pcap_close() here, because this function is always called
1521 * by the user in case something bad happens
1535 * This function takes a bpf program and sends it to the other host.
1537 * This function can be called in two cases:
1538 * - pcap_startcapture_remote() is called (we have to send the filter
1539 * along with the 'start capture' command)
1540 * - we want to update the filter during a capture (i.e. pcap_setfilter()
1541 * after the capture has been started)
1543 * This function serializes the filter into the sending buffer ('sendbuf',
1544 * passed as a parameter) and return back. It does not send anything on
1547 * \param fp: the pcap_t descriptor of the device currently opened.
1549 * \param sendbuf: the buffer on which the serialized data has to copied.
1551 * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1553 * \param prog: the bpf program we have to copy.
1555 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1556 * is returned into the 'errbuf' field of the pcap_t structure.
1558 static int pcap_pack_bpffilter(pcap_t
*fp
, char *sendbuf
, int *sendbufidx
, struct bpf_program
*prog
)
1560 struct rpcap_filter
*filter
;
1561 struct rpcap_filterbpf_insn
*insn
;
1562 struct bpf_insn
*bf_insn
;
1563 struct bpf_program fake_prog
; /* To be used just in case the user forgot to set a filter */
1566 if (prog
->bf_len
== 0) /* No filters have been specified; so, let's apply a "fake" filter */
1568 if (pcap_compile(fp
, &fake_prog
, NULL
/* buffer */, 1, 0) == -1)
1574 filter
= (struct rpcap_filter
*) sendbuf
;
1576 if (sock_bufferize(NULL
, sizeof(struct rpcap_filter
), NULL
, sendbufidx
,
1577 RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1580 filter
->filtertype
= htons(RPCAP_UPDATEFILTER_BPF
);
1581 filter
->nitems
= htonl((int32_t)prog
->bf_len
);
1583 if (sock_bufferize(NULL
, prog
->bf_len
* sizeof(struct rpcap_filterbpf_insn
),
1584 NULL
, sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1587 insn
= (struct rpcap_filterbpf_insn
*) (filter
+ 1);
1588 bf_insn
= prog
->bf_insns
;
1590 for (i
= 0; i
< prog
->bf_len
; i
++)
1592 insn
->code
= htons(bf_insn
->code
);
1593 insn
->jf
= bf_insn
->jf
;
1594 insn
->jt
= bf_insn
->jt
;
1595 insn
->k
= htonl(bf_insn
->k
);
1605 * This function updates a filter on a remote host.
1607 * It is called when the user wants to update a filter.
1608 * In case we're capturing from the network, it sends the filter to our
1610 * This function is *not* called automatically when the user calls
1612 * There will be two cases:
1613 * - the capture has been started: in this case, pcap_setfilter_rpcap()
1614 * calls pcap_updatefilter_remote()
1615 * - the capture has not started yet: in this case, pcap_setfilter_rpcap()
1616 * stores the filter into the pcap_t structure, and then the filter is
1617 * sent with pcap_startcap().
1619 * WARNING This function *does not* clear the packet currently into the
1620 * buffers. Therefore, the user has to expect to receive some packets
1621 * that are related to the previous filter. If you want to discard all
1622 * the packets before applying a new filter, you have to close the
1623 * current capture session and start a new one.
1625 * XXX - we really should have pcap_setfilter() always discard packets
1626 * received with the old filter, and have a separate pcap_setfilter_noflush()
1627 * function that doesn't discard any packets.
1629 static int pcap_updatefilter_remote(pcap_t
*fp
, struct bpf_program
*prog
)
1631 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1632 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
1633 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1634 struct rpcap_header header
; /* To keep the reply message */
1636 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
, &sendbufidx
,
1637 RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1640 rpcap_createhdr((struct rpcap_header
*) sendbuf
,
1641 pr
->protocol_version
, RPCAP_MSG_UPDATEFILTER_REQ
, 0,
1642 sizeof(struct rpcap_filter
) + prog
->bf_len
* sizeof(struct rpcap_filterbpf_insn
));
1644 if (pcap_pack_bpffilter(fp
, &sendbuf
[sendbufidx
], &sendbufidx
, prog
))
1647 if (sock_send(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, sendbuf
, sendbufidx
, fp
->errbuf
,
1648 PCAP_ERRBUF_SIZE
) < 0)
1651 /* Receive and process the reply message header. */
1652 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, pr
->protocol_version
,
1653 RPCAP_MSG_UPDATEFILTER_REQ
, &header
, fp
->errbuf
) == -1)
1657 * It shouldn't have any contents; discard it if it does.
1659 if (rpcap_discard(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, header
.plen
, fp
->errbuf
) == -1)
1666 pcap_save_current_filter_rpcap(pcap_t
*fp
, const char *filter
)
1668 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1672 * - We are on an remote capture
1673 * - we do not want to capture RPCAP traffic
1675 * If so, we have to save the current filter, because we have to
1676 * add some piece of stuff later
1678 if (pr
->rmt_clientside
&&
1679 (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
))
1681 if (pr
->currentfilter
)
1682 free(pr
->currentfilter
);
1687 pr
->currentfilter
= strdup(filter
);
1692 * This function sends a filter to a remote host.
1694 * This function is called when the user wants to set a filter.
1695 * It sends the filter to our peer.
1696 * This function is called automatically when the user calls pcap_setfilter().
1698 * Parameters and return values are exactly the same of pcap_setfilter().
1700 static int pcap_setfilter_rpcap(pcap_t
*fp
, struct bpf_program
*prog
)
1702 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1704 if (!pr
->rmt_capstarted
)
1706 /* copy filter into the pcap_t structure */
1707 if (pcap_install_bpf_program(fp
, prog
) == -1)
1712 /* we have to update a filter during run-time */
1713 if (pcap_updatefilter_remote(fp
, prog
))
1720 * This function updates the current filter in order not to capture rpcap
1723 * This function is called *only* when the user wants exclude RPCAP packets
1724 * related to the current session from the captured packets.
1726 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1727 * is returned into the 'errbuf' field of the pcap_t structure.
1729 static int pcap_createfilter_norpcappkt(pcap_t
*fp
, struct bpf_program
*prog
)
1731 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1734 /* We do not want to capture our RPCAP traffic. So, let's update the filter */
1735 if (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
)
1737 struct sockaddr_storage saddr
; /* temp, needed to retrieve the network data port chosen on the local machine */
1738 socklen_t saddrlen
; /* temp, needed to retrieve the network data port chosen on the local machine */
1739 char myaddress
[128];
1740 char myctrlport
[128];
1741 char mydataport
[128];
1742 char peeraddress
[128];
1743 char peerctrlport
[128];
1746 /* Get the name/port of our peer */
1747 saddrlen
= sizeof(struct sockaddr_storage
);
1748 if (getpeername(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1750 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1751 "getpeername() failed");
1755 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, peeraddress
,
1756 sizeof(peeraddress
), peerctrlport
, sizeof(peerctrlport
), NI_NUMERICHOST
| NI_NUMERICSERV
))
1758 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1759 "getnameinfo() failed");
1763 /* We cannot check the data port, because this is available only in case of TCP sockets */
1764 /* Get the name/port of the current host */
1765 if (getsockname(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1767 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1768 "getsockname() failed");
1772 /* Get the local port the system picked up */
1773 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, myaddress
,
1774 sizeof(myaddress
), myctrlport
, sizeof(myctrlport
), NI_NUMERICHOST
| NI_NUMERICSERV
))
1776 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1777 "getnameinfo() failed");
1781 /* Let's now check the data port */
1782 if (getsockname(pr
->rmt_sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1784 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1785 "getsockname() failed");
1789 /* Get the local port the system picked up */
1790 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, NULL
, 0, mydataport
, sizeof(mydataport
), NI_NUMERICSERV
))
1792 sock_geterrmsg(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1793 "getnameinfo() failed");
1797 if (pr
->currentfilter
&& pr
->currentfilter
[0] != '\0')
1800 * We have a current filter; add items to it to
1801 * filter out this rpcap session.
1803 if (pcap_asprintf(&newfilter
,
1804 "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1805 pr
->currentfilter
, myaddress
, peeraddress
,
1806 myctrlport
, peerctrlport
, myaddress
, peeraddress
,
1810 snprintf(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1811 "Can't allocate memory for new filter");
1818 * We have no current filter; construct a filter to
1819 * filter out this rpcap session.
1821 if (pcap_asprintf(&newfilter
,
1822 "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1823 myaddress
, peeraddress
, myctrlport
, peerctrlport
,
1824 myaddress
, peeraddress
, mydataport
) == -1)
1827 snprintf(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1828 "Can't allocate memory for new filter");
1834 * This is only an hack to prevent the save_current_filter
1835 * routine, which will be called when we call pcap_compile(),
1836 * from saving the modified filter.
1838 pr
->rmt_clientside
= 0;
1840 if (pcap_compile(fp
, prog
, newfilter
, 1, 0) == -1)
1843 /* Undo the hack. */
1844 pr
->rmt_clientside
= 1;
1853 * This function sets sampling parameters in the remote host.
1855 * It is called when the user wants to set activate sampling on the
1858 * Sampling parameters are defined into the 'pcap_t' structure.
1860 * \param p: the pcap_t descriptor of the device currently opened.
1862 * \return '0' if everything is OK, '-1' is something goes wrong. The
1863 * error message is returned in the 'errbuf' member of the pcap_t structure.
1865 static int pcap_setsampling_remote(pcap_t
*fp
)
1867 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1868 char sendbuf
[RPCAP_NETBUF_SIZE
];/* temporary buffer in which data to be sent is buffered */
1869 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1870 struct rpcap_header header
; /* To keep the reply message */
1871 struct rpcap_sampling
*sampling_pars
; /* Structure that is needed to send sampling parameters to the remote host */
1873 /* If no samping is requested, return 'ok' */
1874 if (fp
->rmt_samp
.method
== PCAP_SAMP_NOSAMP
)
1878 * Check for sampling parameters that don't fit in a message.
1879 * We'll let the server complain about invalid parameters
1880 * that do fit into the message.
1882 if (fp
->rmt_samp
.method
< 0 || fp
->rmt_samp
.method
> 255) {
1883 snprintf(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1884 "Invalid sampling method %d", fp
->rmt_samp
.method
);
1887 if (fp
->rmt_samp
.value
< 0 || fp
->rmt_samp
.value
> 65535) {
1888 snprintf(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1889 "Invalid sampling value %d", fp
->rmt_samp
.value
);
1893 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1894 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1897 rpcap_createhdr((struct rpcap_header
*) sendbuf
,
1898 pr
->protocol_version
, RPCAP_MSG_SETSAMPLING_REQ
, 0,
1899 sizeof(struct rpcap_sampling
));
1901 /* Fill the structure needed to open an adapter remotely */
1902 sampling_pars
= (struct rpcap_sampling
*) &sendbuf
[sendbufidx
];
1904 if (sock_bufferize(NULL
, sizeof(struct rpcap_sampling
), NULL
,
1905 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1908 memset(sampling_pars
, 0, sizeof(struct rpcap_sampling
));
1910 sampling_pars
->method
= (uint8_t)fp
->rmt_samp
.method
;
1911 sampling_pars
->value
= (uint16_t)htonl(fp
->rmt_samp
.value
);
1913 if (sock_send(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, sendbuf
, sendbufidx
, fp
->errbuf
,
1914 PCAP_ERRBUF_SIZE
) < 0)
1917 /* Receive and process the reply message header. */
1918 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, pr
->protocol_version
,
1919 RPCAP_MSG_SETSAMPLING_REQ
, &header
, fp
->errbuf
) == -1)
1923 * It shouldn't have any contents; discard it if it does.
1925 if (rpcap_discard(pr
->rmt_sockctrl
, pr
->ctrl_ssl
, header
.plen
, fp
->errbuf
) == -1)
1931 /*********************************************************
1933 * Miscellaneous functions *
1935 *********************************************************/
1938 * This function performs authentication and protocol version
1939 * negotiation. It is required in order to open the connection
1940 * with the other end party.
1942 * It sends authentication parameters on the control socket and
1943 * reads the reply. If the reply is a success indication, it
1944 * checks whether the reply includes minimum and maximum supported
1945 * versions from the server; if not, it assumes both are 0, as
1946 * that means it's an older server that doesn't return supported
1947 * version numbers in authentication replies, so it only supports
1948 * version 0. It then tries to determine the maximum version
1949 * supported both by us and by the server. If it can find such a
1950 * version, it sets us up to use that version; otherwise, it fails,
1951 * indicating that there is no version supported by us and by the
1954 * \param sock: the socket we are currently using.
1956 * \param ver: pointer to variable to which to set the protocol version
1957 * number we selected.
1959 * \param byte_swapped: pointer to variable to which to set 1 if the
1960 * byte order the server says it has is byte-swapped from ours, 0
1961 * otherwise (whether it's the same as ours or is unknown).
1963 * \param auth: authentication parameters that have to be sent.
1965 * \param errbuf: a pointer to a user-allocated buffer (of size
1966 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1967 * is one). It could be a network problem or the fact that the authorization
1970 * \return '0' if everything is fine, '-1' for an error. For errors,
1971 * an error message string is returned in the 'errbuf' variable.
1973 static int rpcap_doauth(SOCKET sockctrl
, SSL
*ssl
, uint8_t *ver
,
1974 int *byte_swapped
, struct pcap_rmtauth
*auth
, char *errbuf
)
1976 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data that has to be sent is buffered */
1977 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1978 uint16_t length
; /* length of the payload of this message */
1979 struct rpcap_auth
*rpauth
;
1981 struct rpcap_header header
;
1984 struct rpcap_authreply authreply
; /* authentication reply message */
1986 int has_byte_order
; /* The server sent its version of the byte-order magic number */
1987 u_int their_byte_order_magic
; /* Here's what it is */
1993 case RPCAP_RMTAUTH_NULL
:
1994 length
= sizeof(struct rpcap_auth
);
1997 case RPCAP_RMTAUTH_PWD
:
1998 length
= sizeof(struct rpcap_auth
);
2001 str_length
= strlen(auth
->username
);
2002 if (str_length
> 65535)
2004 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "User name is too long (> 65535 bytes)");
2007 length
+= (uint16_t)str_length
;
2011 str_length
= strlen(auth
->password
);
2012 if (str_length
> 65535)
2014 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Password is too long (> 65535 bytes)");
2017 length
+= (uint16_t)str_length
;
2022 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Authentication type not recognized.");
2026 auth_type
= (uint16_t)auth
->type
;
2030 auth_type
= RPCAP_RMTAUTH_NULL
;
2031 length
= sizeof(struct rpcap_auth
);
2034 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
2035 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
2038 rpcap_createhdr((struct rpcap_header
*) sendbuf
, 0,
2039 RPCAP_MSG_AUTH_REQ
, 0, length
);
2041 rpauth
= (struct rpcap_auth
*) &sendbuf
[sendbufidx
];
2043 if (sock_bufferize(NULL
, sizeof(struct rpcap_auth
), NULL
,
2044 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
2047 memset(rpauth
, 0, sizeof(struct rpcap_auth
));
2049 rpauth
->type
= htons(auth_type
);
2051 if (auth_type
== RPCAP_RMTAUTH_PWD
)
2054 rpauth
->slen1
= (uint16_t)strlen(auth
->username
);
2058 if (sock_bufferize(auth
->username
, rpauth
->slen1
, sendbuf
,
2059 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
2063 rpauth
->slen2
= (uint16_t)strlen(auth
->password
);
2067 if (sock_bufferize(auth
->password
, rpauth
->slen2
, sendbuf
,
2068 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
2071 rpauth
->slen1
= htons(rpauth
->slen1
);
2072 rpauth
->slen2
= htons(rpauth
->slen2
);
2075 if (sock_send(sockctrl
, ssl
, sendbuf
, sendbufidx
, errbuf
,
2076 PCAP_ERRBUF_SIZE
) < 0)
2079 /* Receive and process the reply message header */
2080 if (rpcap_process_msg_header(sockctrl
, ssl
, 0, RPCAP_MSG_AUTH_REQ
,
2081 &header
, errbuf
) == -1)
2085 * OK, it's an authentication reply, so we're logged in.
2087 * Did it send any additional information?
2094 /* Yes - is it big enough to include version information? */
2095 if (plen
< sizeof(struct rpcap_authreply_old
))
2097 /* No - discard it and fail. */
2098 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2099 "Authenticaton reply from server is too short");
2100 (void)rpcap_discard(sockctrl
, ssl
, plen
, NULL
);
2104 /* Yes - does it include server byte order information? */
2105 if (plen
== sizeof(struct rpcap_authreply_old
))
2107 /* No - just read the version information */
2109 reply_len
= sizeof(struct rpcap_authreply_old
);
2111 else if (plen
>= sizeof(struct rpcap_authreply_old
))
2113 /* Yes - read it all. */
2115 reply_len
= sizeof(struct rpcap_authreply
);
2120 * Too long for old reply, too short for new reply.
2121 * Discard it and fail.
2123 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2124 "Authenticaton reply from server is too short");
2125 (void)rpcap_discard(sockctrl
, ssl
, plen
, NULL
);
2129 /* Read the reply body */
2130 if (rpcap_recv(sockctrl
, ssl
, (char *)&authreply
,
2131 reply_len
, &plen
, errbuf
) == -1)
2133 (void)rpcap_discard(sockctrl
, ssl
, plen
, NULL
);
2137 /* Discard the rest of the message, if there is any. */
2138 if (rpcap_discard(sockctrl
, ssl
, plen
, errbuf
) == -1)
2142 * Check the minimum and maximum versions for sanity;
2143 * the minimum must be <= the maximum.
2145 if (authreply
.minvers
> authreply
.maxvers
)
2148 * Bogus - give up on this server.
2150 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2151 "The server's minimum supported protocol version is greater than its maximum supported protocol version");
2157 their_byte_order_magic
= authreply
.byte_order_magic
;
2162 * The server didn't tell us what its byte
2163 * order is; assume it's ours.
2165 their_byte_order_magic
= RPCAP_BYTE_ORDER_MAGIC
;
2170 /* No - it supports only version 0. */
2171 authreply
.minvers
= 0;
2172 authreply
.maxvers
= 0;
2175 * And it didn't tell us what its byte order is; assume
2179 their_byte_order_magic
= RPCAP_BYTE_ORDER_MAGIC
;
2183 * OK, let's start with the maximum version the server supports.
2185 ourvers
= authreply
.maxvers
;
2187 #if RPCAP_MIN_VERSION != 0
2189 * If that's less than the minimum version we support, we
2190 * can't communicate.
2192 if (ourvers
< RPCAP_MIN_VERSION
)
2197 * If that's greater than the maximum version we support,
2198 * choose the maximum version we support.
2200 if (ourvers
> RPCAP_MAX_VERSION
)
2202 ourvers
= RPCAP_MAX_VERSION
;
2205 * If that's less than the minimum version they
2206 * support, we can't communicate.
2208 if (ourvers
< authreply
.minvers
)
2213 * Is the server byte order the opposite of ours?
2215 if (their_byte_order_magic
== RPCAP_BYTE_ORDER_MAGIC
)
2217 /* No, it's the same. */
2220 else if (their_byte_order_magic
== RPCAP_BYTE_ORDER_MAGIC_SWAPPED
)
2222 /* Yes, it's the opposite of ours. */
2227 /* They sent us something bogus. */
2228 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2229 "The server did not send us a valid byte order value");
2238 * There is no version we both support; that is a fatal error.
2240 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2241 "The server doesn't support any protocol version that we support");
2245 /* non-alphanumeric unreserved characters plus sub-delims (RFC3986) */
2246 static const char userinfo_allowed_symbols
[] = "-._~!&'()*+,;=";
2249 * This function is a thin wrapper around rpcap_doauth which will use an auth
2250 * struct created from a username and password parsed out of the userinfo
2253 static int rpcap_doauth_userinfo(SOCKET sockctrl
, SSL
*ssl
, uint8_t *ver
,
2254 int *byte_swapped
, const char *userinfo
, char *errbuf
)
2256 struct pcap_rmtauth auth
;
2258 char *buf
, username
[256], password
[256];
2260 auth
.type
= RPCAP_RMTAUTH_PWD
;
2261 auth
.username
= username
;
2262 auth
.password
= password
;
2265 username
[0] = password
[0] = '\0';
2267 if ((ptr
= userinfo
) != NULL
)
2269 for (int pos
= -1; (buf
[++pos
] = *ptr
) != '\0'; ++ptr
)
2271 /* handle %xx encoded characters */
2274 /* the pedantic thing to do here would be throwing an error on
2275 * a sequence like `%hi', however a lot of common tools just accept
2276 * such malarkey, so... probably it will be fine? */
2277 if (sscanf(ptr
, "%%%02hhx", (unsigned char *)(buf
+pos
)) == 1)
2279 /* other implementations aside, rejecting null bytes seems prudent */
2280 if (buf
[pos
] == '\0')
2282 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Invalid escape `%%00` in userinfo");
2286 else if (*ptr
== ':' && buf
== username
)
2288 /* terminate username string and switch to password string */
2293 /* constrain to characters allowed by RFC3986 */
2294 else if (*ptr
>= 'A' && *ptr
<= 'Z')
2296 else if (*ptr
>= 'a' && *ptr
<= 'z')
2298 else if (*ptr
>= '0' && *ptr
<= '9')
2300 else if (*ptr
< ' ' || *ptr
> '~')
2302 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Invalid character `\\%o` in userinfo", *ptr
);
2305 else if (strchr(userinfo_allowed_symbols
, *ptr
) == NULL
)
2307 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Invalid character `%c` in userinfo", *ptr
);
2312 return rpcap_doauth(sockctrl
, ssl
, ver
, byte_swapped
, &auth
,
2316 return rpcap_doauth(sockctrl
, ssl
, ver
, byte_swapped
, NULL
, errbuf
);
2320 /* We don't currently support non-blocking mode. */
2322 pcap_getnonblock_rpcap(pcap_t
*p
)
2324 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
2325 "Non-blocking mode isn't supported for capturing remotely with rpcap");
2330 pcap_setnonblock_rpcap(pcap_t
*p
, int nonblock _U_
)
2332 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
2333 "Non-blocking mode isn't supported for capturing remotely with rpcap");
2338 rpcap_setup_session(const char *source
, struct pcap_rmtauth
*auth
,
2339 int *activep
, SOCKET
*sockctrlp
, uint8_t *uses_sslp
, SSL
**sslp
,
2340 int rmt_flags
, uint8_t *protocol_versionp
, int *byte_swappedp
,
2341 char *host
, char *port
, char *iface
, char *errbuf
)
2345 char userinfo
[512]; /* 256 characters each for username and password */
2346 struct activehosts
*activeconn
; /* active connection, if there is one */
2347 int error
; /* 1 if rpcap_remoteact_getsock got an error */
2351 * Determine the type of the source (NULL, file, local, remote).
2352 * You must have a valid source string even if we're in active mode,
2353 * because otherwise the call to the following function will fail.
2355 if (pcap_parsesrcstr_ex(source
, &type
, userinfo
, host
, port
, iface
, uses_sslp
,
2360 * It must be remote.
2362 if (type
!= PCAP_SRC_IFREMOTE
)
2364 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2365 "Non-remote interface passed to remote capture routine");
2370 * We don't yet support DTLS, so if the user asks for a TLS
2371 * connection and asks for data packets to be sent over UDP,
2372 * we have to give up.
2374 if (*uses_sslp
&& (rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
2376 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2377 "TLS not supported with UDP forward of remote packets");
2381 /* Warning: this call can be the first one called by the user. */
2382 /* For this reason, we have to initialize the Winsock support. */
2383 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2386 /* Check for active mode */
2387 activeconn
= rpcap_remoteact_getsock(host
, &error
, errbuf
);
2388 if (activeconn
!= NULL
)
2391 *sockctrlp
= activeconn
->sockctrl
;
2392 *sslp
= activeconn
->ssl
;
2393 *protocol_versionp
= activeconn
->protocol_version
;
2394 *byte_swappedp
= activeconn
->byte_swapped
;
2399 struct addrinfo hints
; /* temp variable needed to resolve hostnames into to socket representation */
2400 struct addrinfo
*addrinfo
; /* temp variable needed to resolve hostnames into to socket representation */
2411 * We're not in active mode; let's try to open a new
2412 * control connection.
2414 memset(&hints
, 0, sizeof(struct addrinfo
));
2415 hints
.ai_family
= PF_UNSPEC
;
2416 hints
.ai_socktype
= SOCK_STREAM
;
2420 /* the user chose not to specify the port */
2421 if (sock_initaddress(host
, RPCAP_DEFAULT_NETPORT
,
2422 &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2427 if (sock_initaddress(host
, port
, &hints
, &addrinfo
,
2428 errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2432 if ((*sockctrlp
= sock_open(host
, addrinfo
, SOCKOPEN_CLIENT
, 0,
2433 errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
2435 freeaddrinfo(addrinfo
);
2439 /* addrinfo is no longer used */
2440 freeaddrinfo(addrinfo
);
2446 *sslp
= ssl_promotion(0, *sockctrlp
, errbuf
,
2450 sock_close(*sockctrlp
, NULL
, 0);
2454 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2456 sock_close(*sockctrlp
, NULL
, 0);
2461 if (auth
== NULL
&& *userinfo
!= '\0')
2463 auth_result
= rpcap_doauth_userinfo(*sockctrlp
, *sslp
,
2464 protocol_versionp
, byte_swappedp
, userinfo
, errbuf
);
2468 auth_result
= rpcap_doauth(*sockctrlp
, *sslp
,
2469 protocol_versionp
, byte_swappedp
, auth
, errbuf
);
2472 if (auth_result
== -1)
2477 // Finish using the SSL handle for the socket.
2478 // This must be done *before* the socket is
2483 sock_close(*sockctrlp
, NULL
, 0);
2491 * This function opens a remote adapter by opening an RPCAP connection and
2494 * It does the job of pcap_open_live() for a remote interface; it's called
2495 * by pcap_open() for remote interfaces.
2497 * We do not start the capture until pcap_startcapture_remote() is called.
2499 * This is because, when doing a remote capture, we cannot start capturing
2500 * data as soon as the 'open adapter' command is sent. Suppose the remote
2501 * adapter is already overloaded; if we start a capture (which, by default,
2502 * has a NULL filter) the new traffic can saturate the network.
2504 * Instead, we want to "open" the adapter, then send a "start capture"
2505 * command only when we're ready to start the capture.
2506 * This function does this job: it sends an "open adapter" command
2507 * (according to the RPCAP protocol), but it does not start the capture.
2509 * Since the other libpcap functions do not share this way of life, we
2510 * have to do some dirty things in order to make everything work.
2512 * \param source: see pcap_open().
2513 * \param snaplen: see pcap_open().
2514 * \param flags: see pcap_open().
2515 * \param read_timeout: see pcap_open().
2516 * \param auth: see pcap_open().
2517 * \param errbuf: see pcap_open().
2519 * \return a pcap_t pointer in case of success, NULL otherwise. In case of
2520 * success, the pcap_t pointer can be used as a parameter to the following
2521 * calls (pcap_compile() and so on). In case of problems, errbuf contains
2522 * a text explanation of error.
2524 * WARNING: In case we call pcap_compile() and the capture has not yet
2525 * been started, the filter will be saved into the pcap_t structure,
2526 * and it will be sent to the other host later (when
2527 * pcap_startcapture_remote() is called).
2529 pcap_t
*pcap_open_rpcap(const char *source
, int snaplen
, int flags
, int read_timeout
, struct pcap_rmtauth
*auth
, char *errbuf
)
2533 struct pcap_rpcap
*pr
; /* structure used when doing a remote live capture */
2534 char host
[PCAP_BUF_SIZE
], ctrlport
[PCAP_BUF_SIZE
], iface
[PCAP_BUF_SIZE
];
2537 uint8_t protocol_version
; /* negotiated protocol version */
2538 int byte_swapped
; /* server is known to be byte-swapped */
2541 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
2542 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
2544 /* RPCAP-related variables */
2545 struct rpcap_header header
; /* header of the RPCAP packet */
2546 struct rpcap_openreply openreply
; /* open reply message */
2548 fp
= PCAP_CREATE_COMMON(errbuf
, struct pcap_rpcap
);
2553 source_str
= strdup(source
);
2554 if (source_str
== NULL
) {
2555 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2561 * Turn a negative snapshot value (invalid), a snapshot value of
2562 * 0 (unspecified), or a value bigger than the normal maximum
2563 * value, into the maximum allowed value.
2565 * If some application really *needs* a bigger snapshot
2566 * length, we should just increase MAXIMUM_SNAPLEN.
2568 * XXX - should we leave this up to the remote server to
2571 if (snaplen
<= 0 || snaplen
> MAXIMUM_SNAPLEN
)
2572 snaplen
= MAXIMUM_SNAPLEN
;
2574 fp
->opt
.device
= source_str
;
2575 fp
->snapshot
= snaplen
;
2576 fp
->opt
.timeout
= read_timeout
;
2578 pr
->rmt_flags
= flags
;
2581 * Attempt to set up the session with the server.
2583 if (rpcap_setup_session(fp
->opt
.device
, auth
, &active
, &sockctrl
,
2584 &pr
->uses_ssl
, &ssl
, flags
, &protocol_version
, &byte_swapped
,
2585 host
, ctrlport
, iface
, errbuf
) == -1)
2587 /* Session setup failed. */
2592 /* All good so far, save the ssl handler */
2596 * Now it's time to start playing with the RPCAP protocol
2597 * RPCAP open command: create the request message
2599 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
2600 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
2601 goto error_nodiscard
;
2603 rpcap_createhdr((struct rpcap_header
*) sendbuf
, protocol_version
,
2604 RPCAP_MSG_OPEN_REQ
, 0, (uint32_t) strlen(iface
));
2606 if (sock_bufferize(iface
, (int) strlen(iface
), sendbuf
, &sendbufidx
,
2607 RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
2608 goto error_nodiscard
;
2610 if (sock_send(sockctrl
, ssl
, sendbuf
, sendbufidx
, errbuf
,
2611 PCAP_ERRBUF_SIZE
) < 0)
2612 goto error_nodiscard
;
2614 /* Receive and process the reply message header. */
2615 if (rpcap_process_msg_header(sockctrl
, ssl
, protocol_version
,
2616 RPCAP_MSG_OPEN_REQ
, &header
, errbuf
) == -1)
2617 goto error_nodiscard
;
2620 /* Read the reply body */
2621 if (rpcap_recv(sockctrl
, ssl
, (char *)&openreply
,
2622 sizeof(struct rpcap_openreply
), &plen
, errbuf
) == -1)
2625 /* Discard the rest of the message, if there is any. */
2626 if (rpcap_discard(sockctrl
, ssl
, plen
, errbuf
) == -1)
2627 goto error_nodiscard
;
2629 /* Set proper fields into the pcap_t struct */
2630 fp
->linktype
= ntohl(openreply
.linktype
);
2631 pr
->rmt_sockctrl
= sockctrl
;
2633 pr
->protocol_version
= protocol_version
;
2634 pr
->byte_swapped
= byte_swapped
;
2635 pr
->rmt_clientside
= 1;
2637 /* This code is duplicated from the end of this function */
2638 fp
->read_op
= pcap_read_rpcap
;
2639 fp
->save_current_filter_op
= pcap_save_current_filter_rpcap
;
2640 fp
->setfilter_op
= pcap_setfilter_rpcap
;
2641 fp
->getnonblock_op
= pcap_getnonblock_rpcap
;
2642 fp
->setnonblock_op
= pcap_setnonblock_rpcap
;
2643 fp
->stats_op
= pcap_stats_rpcap
;
2645 fp
->stats_ex_op
= pcap_stats_ex_rpcap
;
2647 fp
->cleanup_op
= pcap_cleanup_rpcap
;
2654 * When the connection has been established, we have to close it. So, at the
2655 * beginning of this function, if an error occur we return immediately with
2656 * a return NULL; when the connection is established, we have to come here
2657 * ('goto error;') in order to close everything properly.
2661 * Discard the rest of the message.
2662 * We already reported an error; if this gets an error, just
2665 (void)rpcap_discard(sockctrl
, pr
->ctrl_ssl
, plen
, NULL
);
2673 // Finish using the SSL handle for the socket.
2674 // This must be done *before* the socket is closed.
2678 sock_close(sockctrl
, NULL
, 0);
2685 /* String identifier to be used in the pcap_findalldevs_ex() */
2686 #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
2687 #define PCAP_TEXT_SOURCE_ADAPTER_LEN (sizeof PCAP_TEXT_SOURCE_ADAPTER - 1)
2688 /* String identifier to be used in the pcap_findalldevs_ex() */
2689 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST "on remote node"
2690 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST_LEN (sizeof PCAP_TEXT_SOURCE_ON_REMOTE_HOST - 1)
2693 freeaddr(struct pcap_addr
*addr
)
2696 free(addr
->netmask
);
2697 free(addr
->broadaddr
);
2698 free(addr
->dstaddr
);
2703 pcap_findalldevs_ex_remote(const char *source
, struct pcap_rmtauth
*auth
, pcap_if_t
**alldevs
, char *errbuf
)
2705 uint8_t protocol_version
; /* protocol version */
2706 int byte_swapped
; /* Server byte order is swapped from ours */
2707 SOCKET sockctrl
; /* socket descriptor of the control connection */
2708 SSL
*ssl
= NULL
; /* optional SSL handler for sockctrl */
2710 struct rpcap_header header
; /* structure that keeps the general header of the rpcap protocol */
2711 int i
, j
; /* temp variables */
2712 int nif
; /* Number of interfaces listed */
2713 int active
; /* 'true' if we the other end-party is in active mode */
2715 char host
[PCAP_BUF_SIZE
], port
[PCAP_BUF_SIZE
];
2716 char tmpstring
[PCAP_BUF_SIZE
+ 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2717 pcap_if_t
*lastdev
; /* Last device in the pcap_if_t list */
2718 pcap_if_t
*dev
; /* Device we're adding to the pcap_if_t list */
2720 /* List starts out empty. */
2725 * Attempt to set up the session with the server.
2727 if (rpcap_setup_session(source
, auth
, &active
, &sockctrl
, &uses_ssl
,
2728 &ssl
, 0, &protocol_version
, &byte_swapped
, host
, port
, NULL
,
2731 /* Session setup failed. */
2735 /* RPCAP findalldevs command */
2736 rpcap_createhdr(&header
, protocol_version
, RPCAP_MSG_FINDALLIF_REQ
,
2739 if (sock_send(sockctrl
, ssl
, (char *)&header
, sizeof(struct rpcap_header
),
2740 errbuf
, PCAP_ERRBUF_SIZE
) < 0)
2741 goto error_nodiscard
;
2743 /* Receive and process the reply message header. */
2744 if (rpcap_process_msg_header(sockctrl
, ssl
, protocol_version
,
2745 RPCAP_MSG_FINDALLIF_REQ
, &header
, errbuf
) == -1)
2746 goto error_nodiscard
;
2750 /* read the number of interfaces */
2751 nif
= ntohs(header
.value
);
2753 /* loop until all interfaces have been received */
2754 for (i
= 0; i
< nif
; i
++)
2756 struct rpcap_findalldevs_if findalldevs_if
;
2757 char tmpstring2
[PCAP_BUF_SIZE
+ 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2758 struct pcap_addr
*addr
, *prevaddr
;
2760 tmpstring2
[PCAP_BUF_SIZE
] = 0;
2762 /* receive the findalldevs structure from remote host */
2763 if (rpcap_recv(sockctrl
, ssl
, (char *)&findalldevs_if
,
2764 sizeof(struct rpcap_findalldevs_if
), &plen
, errbuf
) == -1)
2767 findalldevs_if
.namelen
= ntohs(findalldevs_if
.namelen
);
2768 findalldevs_if
.desclen
= ntohs(findalldevs_if
.desclen
);
2769 findalldevs_if
.naddr
= ntohs(findalldevs_if
.naddr
);
2771 /* allocate the main structure */
2772 dev
= (pcap_if_t
*)malloc(sizeof(pcap_if_t
));
2775 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2776 errno
, "malloc() failed");
2780 /* Initialize the structure to 'zero' */
2781 memset(dev
, 0, sizeof(pcap_if_t
));
2783 /* Append it to the list. */
2784 if (lastdev
== NULL
)
2787 * List is empty, so it's also the first device.
2794 * Append after the last device.
2796 lastdev
->next
= dev
;
2798 /* It's now the last device. */
2801 /* allocate mem for name and description */
2802 if (findalldevs_if
.namelen
)
2805 if (findalldevs_if
.namelen
>= sizeof(tmpstring
))
2807 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Interface name too long");
2811 /* Retrieve adapter name */
2812 if (rpcap_recv(sockctrl
, ssl
, tmpstring
,
2813 findalldevs_if
.namelen
, &plen
, errbuf
) == -1)
2816 tmpstring
[findalldevs_if
.namelen
] = 0;
2818 /* Create the new device identifier */
2819 if (pcap_createsrcstr_ex(tmpstring2
, PCAP_SRC_IFREMOTE
,
2820 NULL
, host
, port
, tmpstring
, uses_ssl
, errbuf
) == -1)
2823 dev
->name
= strdup(tmpstring2
);
2824 if (dev
->name
== NULL
)
2826 pcap_fmt_errmsg_for_errno(errbuf
,
2827 PCAP_ERRBUF_SIZE
, errno
, "malloc() failed");
2832 if (findalldevs_if
.desclen
)
2834 if (findalldevs_if
.desclen
>= sizeof(tmpstring
))
2836 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Interface description too long");
2840 /* Retrieve adapter description */
2841 if (rpcap_recv(sockctrl
, ssl
, tmpstring
,
2842 findalldevs_if
.desclen
, &plen
, errbuf
) == -1)
2845 tmpstring
[findalldevs_if
.desclen
] = 0;
2847 if (pcap_asprintf(&dev
->description
,
2848 "%s '%s' %s %s", PCAP_TEXT_SOURCE_ADAPTER
,
2849 tmpstring
, PCAP_TEXT_SOURCE_ON_REMOTE_HOST
, host
) == -1)
2851 pcap_fmt_errmsg_for_errno(errbuf
,
2852 PCAP_ERRBUF_SIZE
, errno
, "malloc() failed");
2857 dev
->flags
= ntohl(findalldevs_if
.flags
);
2860 /* loop until all addresses have been received */
2861 for (j
= 0; j
< findalldevs_if
.naddr
; j
++)
2863 struct rpcap_findalldevs_ifaddr ifaddr
;
2865 /* Retrieve the interface addresses */
2866 if (rpcap_recv(sockctrl
, ssl
, (char *)&ifaddr
,
2867 sizeof(struct rpcap_findalldevs_ifaddr
),
2868 &plen
, errbuf
) == -1)
2872 * Deserialize all the address components.
2874 addr
= (struct pcap_addr
*) malloc(sizeof(struct pcap_addr
));
2877 pcap_fmt_errmsg_for_errno(errbuf
,
2878 PCAP_ERRBUF_SIZE
, errno
, "malloc() failed");
2883 addr
->netmask
= NULL
;
2884 addr
->broadaddr
= NULL
;
2885 addr
->dstaddr
= NULL
;
2887 if (rpcap_deseraddr(&ifaddr
.addr
,
2888 (struct sockaddr_storage
**) &addr
->addr
, errbuf
) == -1)
2893 if (rpcap_deseraddr(&ifaddr
.netmask
,
2894 (struct sockaddr_storage
**) &addr
->netmask
, errbuf
) == -1)
2899 if (rpcap_deseraddr(&ifaddr
.broadaddr
,
2900 (struct sockaddr_storage
**) &addr
->broadaddr
, errbuf
) == -1)
2905 if (rpcap_deseraddr(&ifaddr
.dstaddr
,
2906 (struct sockaddr_storage
**) &addr
->dstaddr
, errbuf
) == -1)
2912 if ((addr
->addr
== NULL
) && (addr
->netmask
== NULL
) &&
2913 (addr
->broadaddr
== NULL
) && (addr
->dstaddr
== NULL
))
2916 * None of the addresses are IPv4 or IPv6
2917 * addresses, so throw this entry away.
2924 * Add this entry to the list.
2926 if (prevaddr
== NULL
)
2928 dev
->addresses
= addr
;
2932 prevaddr
->next
= addr
;
2939 /* Discard the rest of the message. */
2940 if (rpcap_discard(sockctrl
, ssl
, plen
, errbuf
) == 1)
2941 goto error_nodiscard
;
2943 /* Control connection has to be closed only in case the remote machine is in passive mode */
2946 /* DO not send RPCAP_CLOSE, since we did not open a pcap_t; no need to free resources */
2950 // Finish using the SSL handle for the socket.
2951 // This must be done *before* the socket is closed.
2955 if (sock_close(sockctrl
, errbuf
, PCAP_ERRBUF_SIZE
))
2959 /* To avoid inconsistencies in the number of sock_init() */
2966 * In case there has been an error, I don't want to overwrite it with a new one
2967 * if the following call fails. I want to return always the original error.
2969 * Take care: this connection can already be closed when we try to close it.
2970 * This happens because a previous error in the rpcapd, which requested to
2971 * closed the connection. In that case, we already recognized that into the
2972 * rpspck_isheaderok() and we already acknowledged the closing.
2973 * In that sense, this call is useless here (however it is needed in case
2974 * the client generates the error).
2976 * Checks if all the data has been read; if not, discard the data in excess
2978 (void) rpcap_discard(sockctrl
, ssl
, plen
, NULL
);
2981 /* Control connection has to be closed only in case the remote machine is in passive mode */
2987 // Finish using the SSL handle for the socket.
2988 // This must be done *before* the socket is closed.
2992 sock_close(sockctrl
, NULL
, 0);
2995 /* To avoid inconsistencies in the number of sock_init() */
2998 /* Free whatever interfaces we've allocated. */
2999 pcap_freealldevs(*alldevs
);
3005 * Active mode routines.
3007 * The old libpcap API is somewhat ugly, and makes active mode difficult
3008 * to implement; we provide some APIs for it that work only with rpcap.
3011 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
)
3013 /* socket-related variables */
3014 struct addrinfo hints
; /* temporary struct to keep settings needed to open the new socket */
3015 struct addrinfo
*addrinfo
; /* keeps the addrinfo chain; required to open a new socket */
3016 struct sockaddr_storage from
; /* generic sockaddr_storage variable */
3017 socklen_t fromlen
; /* keeps the length of the sockaddr_storage variable */
3018 SOCKET sockctrl
; /* keeps the main socket identifier */
3019 SSL
*ssl
= NULL
; /* Optional SSL handler for sockctrl */
3020 uint8_t protocol_version
; /* negotiated protocol version */
3021 int byte_swapped
; /* 1 if server byte order is known to be the reverse of ours */
3022 struct activehosts
*temp
, *prev
; /* temp var needed to scan he host list chain */
3024 *connectinghost
= 0; /* just in case */
3026 /* Prepare to open a new server socket */
3027 memset(&hints
, 0, sizeof(struct addrinfo
));
3028 /* WARNING Currently it supports only ONE socket family among ipv4 and IPv6 */
3029 hints
.ai_family
= AF_INET
; /* PF_UNSPEC to have both IPv4 and IPv6 server */
3030 hints
.ai_flags
= AI_PASSIVE
; /* Ready to a bind() socket */
3031 hints
.ai_socktype
= SOCK_STREAM
;
3033 /* Warning: this call can be the first one called by the user. */
3034 /* For this reason, we have to initialize the Winsock support. */
3035 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
3039 if ((port
== NULL
) || (port
[0] == 0))
3041 if (sock_initaddress(address
, RPCAP_DEFAULT_NETPORT_ACTIVE
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
3048 if (sock_initaddress(address
, port
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
3055 if ((sockmain
= sock_open(NULL
, addrinfo
, SOCKOPEN_SERVER
, 1, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
3057 freeaddrinfo(addrinfo
);
3060 freeaddrinfo(addrinfo
);
3062 /* Connection creation */
3063 fromlen
= sizeof(struct sockaddr_storage
);
3065 sockctrl
= accept(sockmain
, (struct sockaddr
*) &from
, &fromlen
);
3067 /* We're not using sock_close, since we do not want to send a shutdown */
3068 /* (which is not allowed on a non-connected socket) */
3069 closesocket(sockmain
);
3072 if (sockctrl
== INVALID_SOCKET
)
3074 sock_geterrmsg(errbuf
, PCAP_ERRBUF_SIZE
, "accept() failed");
3078 /* Promote to SSL early before any error message may be sent */
3082 ssl
= ssl_promotion(0, sockctrl
, errbuf
, PCAP_ERRBUF_SIZE
);
3085 sock_close(sockctrl
, NULL
, 0);
3089 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "No TLS support");
3090 sock_close(sockctrl
, NULL
, 0);
3095 /* Get the numeric for of the name of the connecting host */
3096 if (getnameinfo((struct sockaddr
*) &from
, fromlen
, connectinghost
, RPCAP_HOSTLIST_SIZE
, NULL
, 0, NI_NUMERICHOST
))
3098 sock_geterrmsg(errbuf
, PCAP_ERRBUF_SIZE
,
3099 "getnameinfo() failed");
3100 rpcap_senderror(sockctrl
, ssl
, 0, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
3104 // Finish using the SSL handle for the socket.
3105 // This must be done *before* the socket is closed.
3109 sock_close(sockctrl
, NULL
, 0);
3113 /* checks if the connecting host is among the ones allowed */
3114 if (sock_check_hostlist((char *)hostlist
, RPCAP_HOSTLIST_SEP
, &from
, errbuf
, PCAP_ERRBUF_SIZE
) < 0)
3116 rpcap_senderror(sockctrl
, ssl
, 0, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
3120 // Finish using the SSL handle for the socket.
3121 // This must be done *before* the socket is closed.
3125 sock_close(sockctrl
, NULL
, 0);
3130 * Send authentication to the remote machine.
3132 if (rpcap_doauth(sockctrl
, ssl
, &protocol_version
, &byte_swapped
,
3133 auth
, errbuf
) == -1)
3135 /* Unrecoverable error. */
3136 rpcap_senderror(sockctrl
, ssl
, 0, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
3140 // Finish using the SSL handle for the socket.
3141 // This must be done *before* the socket is closed.
3145 sock_close(sockctrl
, NULL
, 0);
3149 /* Checks that this host does not already have a cntrl connection in place */
3151 /* Initialize pointers */
3157 /* This host already has an active connection in place, so I don't have to update the host list */
3158 if (sock_cmpaddr(&temp
->host
, &from
) == 0)
3165 /* The host does not exist in the list; so I have to update the list */
3168 prev
->next
= (struct activehosts
*) malloc(sizeof(struct activehosts
));
3173 activeHosts
= (struct activehosts
*) malloc(sizeof(struct activehosts
));
3179 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
3180 errno
, "malloc() failed");
3181 rpcap_senderror(sockctrl
, ssl
, protocol_version
, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
3185 // Finish using the SSL handle for the socket.
3186 // This must be done *before* the socket is closed.
3190 sock_close(sockctrl
, NULL
, 0);
3194 memcpy(&temp
->host
, &from
, fromlen
);
3195 temp
->sockctrl
= sockctrl
;
3197 temp
->protocol_version
= protocol_version
;
3198 temp
->byte_swapped
= byte_swapped
;
3204 SOCKET
pcap_remoteact_accept(const char *address
, const char *port
, const char *hostlist
, char *connectinghost
, struct pcap_rmtauth
*auth
, char *errbuf
)
3206 return pcap_remoteact_accept_ex(address
, port
, hostlist
, connectinghost
, auth
, 0, errbuf
);
3209 int pcap_remoteact_close(const char *host
, char *errbuf
)
3211 struct activehosts
*temp
, *prev
; /* temp var needed to scan the host list chain */
3212 struct addrinfo hints
, *addrinfo
, *ai_next
; /* temp var needed to translate between hostname to its address */
3218 /* retrieve the network address corresponding to 'host' */
3220 memset(&hints
, 0, sizeof(struct addrinfo
));
3221 hints
.ai_family
= PF_UNSPEC
;
3222 hints
.ai_socktype
= SOCK_STREAM
;
3224 retval
= sock_initaddress(host
, NULL
, &hints
, &addrinfo
, errbuf
,
3236 if (sock_cmpaddr(&temp
->host
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
3238 struct rpcap_header header
;
3241 /* Close this connection */
3242 rpcap_createhdr(&header
, temp
->protocol_version
,
3243 RPCAP_MSG_CLOSE
, 0, 0);
3246 * Don't check for errors, since we're
3249 if (sock_send(temp
->sockctrl
, temp
->ssl
,
3251 sizeof(struct rpcap_header
), errbuf
,
3252 PCAP_ERRBUF_SIZE
) < 0)
3255 * Let that error be the one we
3261 // Finish using the SSL handle
3263 // This must be done *before*
3264 // the socket is closed.
3265 ssl_finish(temp
->ssl
);
3268 (void)sock_close(temp
->sockctrl
, NULL
,
3277 // Finish using the SSL handle
3279 // This must be done *before*
3280 // the socket is closed.
3281 ssl_finish(temp
->ssl
);
3284 if (sock_close(temp
->sockctrl
, errbuf
,
3285 PCAP_ERRBUF_SIZE
) == -1)
3290 * Remove the host from the list of active
3294 prev
->next
= temp
->next
;
3296 activeHosts
= temp
->next
;
3298 freeaddrinfo(addrinfo
);
3302 /* To avoid inconsistencies in the number of sock_init() */
3308 ai_next
= ai_next
->ai_next
;
3315 freeaddrinfo(addrinfo
);
3317 /* To avoid inconsistencies in the number of sock_init() */
3320 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The host you want to close the active connection is not known");
3324 void pcap_remoteact_cleanup(void)
3326 # ifdef HAVE_OPENSSL
3329 // Finish using the SSL handle for the main active socket.
3330 // This must be done *before* the socket is closed.
3331 ssl_finish(ssl_main
);
3336 /* Very dirty, but it works */
3339 closesocket(sockmain
);
3341 /* To avoid inconsistencies in the number of sock_init() */
3346 int pcap_remoteact_list(char *hostlist
, char sep
, int size
, char *errbuf
)
3348 struct activehosts
*temp
; /* temp var needed to scan the host list chain */
3350 char hoststr
[RPCAP_HOSTLIST_SIZE
+ 1];
3359 /*int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen) */
3361 /* Get the numeric form of the name of the connecting host */
3362 if (sock_getascii_addrport((struct sockaddr_storage
*) &temp
->host
, hoststr
,
3363 RPCAP_HOSTLIST_SIZE
, NULL
, 0, NI_NUMERICHOST
, errbuf
, PCAP_ERRBUF_SIZE
) != -1)
3364 /* if (getnameinfo( (struct sockaddr *) &temp->host, sizeof (struct sockaddr_storage), hoststr, */
3365 /* RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST) ) */
3367 /* sock_geterrmsg(errbuf, PCAP_ERRBUF_SIZE, */
3368 /* "getnameinfo() failed"); */
3372 len
= len
+ strlen(hoststr
) + 1 /* the separator */;
3374 if ((size
< 0) || (len
>= (size_t)size
))
3376 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The string you provided is not able to keep "
3377 "the hostnames for all the active connections");
3381 pcap_strlcat(hostlist
, hoststr
, PCAP_ERRBUF_SIZE
);
3382 hostlist
[len
- 1] = sep
;
3392 * Receive the header of a message.
3394 static int rpcap_recv_msg_header(SOCKET sock
, SSL
*ssl
, struct rpcap_header
*header
, char *errbuf
)
3398 nrecv
= sock_recv(sock
, ssl
, (char *) header
, sizeof(struct rpcap_header
),
3399 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
,
3403 /* Network error. */
3406 header
->plen
= ntohl(header
->plen
);
3411 * Make sure the protocol version of a received message is what we were
3414 static int rpcap_check_msg_ver(SOCKET sock
, SSL
*ssl
, uint8_t expected_ver
, struct rpcap_header
*header
, char *errbuf
)
3417 * Did the server specify the version we negotiated?
3419 if (header
->ver
!= expected_ver
)
3422 * Discard the rest of the message.
3424 if (rpcap_discard(sock
, ssl
, header
->plen
, errbuf
) == -1)
3428 * Tell our caller that it's not the negotiated version.
3432 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3433 "Server sent us a message with version %u when we were expecting %u",
3434 header
->ver
, expected_ver
);
3442 * Check the message type of a received message, which should either be
3443 * the expected message type or RPCAP_MSG_ERROR.
3445 static int rpcap_check_msg_type(SOCKET sock
, SSL
*ssl
, uint8_t request_type
, struct rpcap_header
*header
, uint16_t *errcode
, char *errbuf
)
3447 const char *request_type_string
;
3448 const char *msg_type_string
;
3451 * What type of message is it?
3453 if (header
->type
== RPCAP_MSG_ERROR
)
3456 * The server reported an error.
3457 * Hand that error back to our caller.
3459 *errcode
= ntohs(header
->value
);
3460 rpcap_msg_err(sock
, ssl
, header
->plen
, errbuf
);
3467 * For a given request type value, the expected reply type value
3468 * is the request type value with ORed with RPCAP_MSG_IS_REPLY.
3470 if (header
->type
!= (request_type
| RPCAP_MSG_IS_REPLY
))
3473 * This isn't a reply to the request we sent.
3477 * Discard the rest of the message.
3479 if (rpcap_discard(sock
, ssl
, header
->plen
, errbuf
) == -1)
3483 * Tell our caller about it.
3485 request_type_string
= rpcap_msg_type_string(request_type
);
3486 msg_type_string
= rpcap_msg_type_string(header
->type
);
3489 if (request_type_string
== NULL
)
3491 /* This should not happen. */
3492 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3493 "rpcap_check_msg_type called for request message with type %u",
3497 if (msg_type_string
!= NULL
)
3498 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3499 "%s message received in response to a %s message",
3500 msg_type_string
, request_type_string
);
3502 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3503 "Message of unknown type %u message received in response to a %s request",
3504 header
->type
, request_type_string
);
3513 * Receive and process the header of a message.
3515 static int rpcap_process_msg_header(SOCKET sock
, SSL
*ssl
, uint8_t expected_ver
, uint8_t request_type
, struct rpcap_header
*header
, char *errbuf
)
3519 if (rpcap_recv_msg_header(sock
, ssl
, header
, errbuf
) == -1)
3521 /* Network error. */
3526 * Did the server specify the version we negotiated?
3528 if (rpcap_check_msg_ver(sock
, ssl
, expected_ver
, header
, errbuf
) == -1)
3532 * Check the message type.
3534 return rpcap_check_msg_type(sock
, ssl
, request_type
, header
,
3539 * Read data from a message.
3540 * If we're trying to read more data that remains, puts an error
3541 * message into errmsgbuf and returns -2. Otherwise, tries to read
3542 * the data and, if that succeeds, subtracts the amount read from
3543 * the number of bytes of data that remains.
3544 * Returns 0 on success, logs a message and returns -1 on a network
3547 static int rpcap_recv(SOCKET sock
, SSL
*ssl
, void *buffer
, size_t toread
, uint32_t *plen
, char *errbuf
)
3553 /* The server sent us a bad message */
3554 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Message payload is too short");
3557 nread
= sock_recv(sock
, ssl
, buffer
, toread
,
3558 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
, PCAP_ERRBUF_SIZE
);
3568 * This handles the RPCAP_MSG_ERROR message.
3570 static void rpcap_msg_err(SOCKET sockctrl
, SSL
*ssl
, uint32_t plen
, char *remote_errbuf
)
3572 char errbuf
[PCAP_ERRBUF_SIZE
];
3574 if (plen
>= PCAP_ERRBUF_SIZE
)
3577 * Message is too long; just read as much of it as we
3578 * can into the buffer provided, and discard the rest.
3580 if (sock_recv(sockctrl
, ssl
, remote_errbuf
, PCAP_ERRBUF_SIZE
- 1,
3581 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
,
3582 PCAP_ERRBUF_SIZE
) == -1)
3585 DIAG_OFF_FORMAT_TRUNCATION
3586 snprintf(remote_errbuf
, PCAP_ERRBUF_SIZE
, "Read of error message from client failed: %s", errbuf
);
3587 DIAG_ON_FORMAT_TRUNCATION
3592 * Null-terminate it.
3594 remote_errbuf
[PCAP_ERRBUF_SIZE
- 1] = '\0';
3598 * If we're not in UTF-8 mode, convert it to the local
3601 if (!pcap_utf_8_mode
)
3602 utf_8_to_acp_truncated(remote_errbuf
);
3606 * Throw away the rest.
3608 (void)rpcap_discard(sockctrl
, ssl
, plen
- (PCAP_ERRBUF_SIZE
- 1), remote_errbuf
);
3612 /* Empty error string. */
3613 remote_errbuf
[0] = '\0';
3617 if (sock_recv(sockctrl
, ssl
, remote_errbuf
, plen
,
3618 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
,
3619 PCAP_ERRBUF_SIZE
) == -1)
3622 DIAG_OFF_FORMAT_TRUNCATION
3623 snprintf(remote_errbuf
, PCAP_ERRBUF_SIZE
, "Read of error message from client failed: %s", errbuf
);
3624 DIAG_ON_FORMAT_TRUNCATION
3629 * Null-terminate it.
3631 remote_errbuf
[plen
] = '\0';
3636 * Discard data from a connection.
3637 * Mostly used to discard wrong-sized messages.
3638 * Returns 0 on success, logs a message and returns -1 on a network
3641 static int rpcap_discard(SOCKET sock
, SSL
*ssl
, uint32_t len
, char *errbuf
)
3645 if (sock_discard(sock
, ssl
, len
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
3655 * Read bytes into the pcap_t's buffer until we have the specified
3656 * number of bytes read or we get an error or interrupt indication.
3658 static int rpcap_read_packet_msg(struct pcap_rpcap
const *rp
, pcap_t
*p
, size_t size
)
3668 * Loop until we have the amount of data requested or we get
3669 * an error or interrupt.
3671 while ((size_t)cc
< size
)
3674 * We haven't read all of the packet header yet.
3675 * Read what remains, which could be all of it.
3677 bytes_read
= sock_recv(rp
->rmt_sockdata
, rp
->data_ssl
, bp
, size
- cc
,
3678 SOCK_RECEIVEALL_NO
|SOCK_EOF_IS_ERROR
, p
->errbuf
,
3681 if (bytes_read
== -1)
3684 * Network error. Update the read pointer and
3685 * byte count, and return an error indication.
3691 if (bytes_read
== -3)
3694 * Interrupted receive. Update the read
3695 * pointer and byte count, and return
3696 * an interrupted indication.
3702 if (bytes_read
== 0)
3705 * EOF - server terminated the connection.
3706 * Update the read pointer and byte count, and
3707 * return an error indication.
3709 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
3710 "The server terminated the connection.");