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.
38 #include <string.h> /* for strlen(), ... */
39 #include <stdlib.h> /* for malloc(), free(), ... */
40 #include <stdarg.h> /* for functions with variable number of arguments */
41 #include <errno.h> /* for the errno variable */
42 #include "sockutils.h"
44 #include "rpcap-protocol.h"
45 #include "pcap-rpcap.h"
48 * This file contains the pcap module for capturing from a remote machine's
49 * interfaces using the RPCAP protocol.
51 * WARNING: All the RPCAP functions that are allowed to return a buffer
52 * containing the error description can return max PCAP_ERRBUF_SIZE characters.
53 * However there is no guarantees that the string will be zero-terminated.
54 * Best practice is to define the errbuf variable as a char of size
55 * 'PCAP_ERRBUF_SIZE+1' and to insert manually a NULL character at the end
56 * of the buffer. This will guarantee that no buffer overflows occur even
57 * if we use the printf() to show the error on the screen.
59 * XXX - actually, null-terminating the error string is part of the
60 * contract for the pcap API; if there's any place in the pcap code
61 * that doesn't guarantee null-termination, even at the expense of
62 * cutting the message short, that's a bug and needs to be fixed.
65 #define PCAP_STATS_STANDARD 0 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
67 #define PCAP_STATS_EX 1 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
71 * \brief Keeps a list of all the opened connections in the active mode.
73 * This structure defines a linked list of items that are needed to keep the info required to
74 * manage the active mode.
75 * In other words, when a new connection in active mode starts, this structure is updated so that
76 * it reflects the list of active mode connections currently opened.
77 * This structure is required by findalldevs() and open_remote() to see if they have to open a new
78 * control connection toward the host, or they already have a control connection in place.
82 struct sockaddr_storage host
;
84 uint8 protocol_version
;
85 struct activehosts
*next
;
88 /* Keeps a list of all the opened connections in the active mode. */
89 static struct activehosts
*activeHosts
;
92 * Keeps the main socket identifier when we want to accept a new remote
93 * connection (active mode only).
94 * See the documentation of pcap_remoteact_accept() and
95 * pcap_remoteact_cleanup() for more details.
97 static SOCKET sockmain
;
100 * Private data for capturing remotely using the rpcap protocol.
104 * This is '1' if we're the network client; it is needed by several
105 * functions (such as pcap_setfilter()) to know whether they have
106 * to use the socket or have to open the local adapter.
110 SOCKET rmt_sockctrl
; /* socket ID of the socket used for the control connection */
111 SOCKET rmt_sockdata
; /* socket ID of the socket used for the data connection */
112 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() */
113 int rmt_capstarted
; /* 'true' if the capture is already started (needed to knoe if we have to call the pcap_startcapture() */
114 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. */
116 uint8 protocol_version
; /* negotiated protocol version */
118 unsigned int TotNetDrops
; /* keeps the number of packets that have been dropped by the network */
121 * This keeps the number of packets that have been received by the
124 * Packets dropped by the kernel buffer are not counted in this
125 * variable. It is always equal to (TotAccepted - TotDrops),
126 * except for the case of remote capture, in which we have also
127 * packets in flight, i.e. that have been transmitted by the remote
128 * host, but that have not been received (yet) from the client.
129 * In this case, (TotAccepted - TotDrops - TotNetDrops) gives a
130 * wrong result, since this number does not corresponds always to
131 * the number of packet received by the application. For this reason,
132 * in the remote capture we need another variable that takes into
133 * account of the number of packets actually received by the
136 unsigned int TotCapt
;
138 struct pcap_stat stat
;
140 struct pcap
*next
; /* list of open pcaps that need stuff cleared on close */
143 /****************************************************
145 * Locally defined functions *
147 ****************************************************/
148 static struct pcap_stat
*rpcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
, int mode
);
149 static int pcap_pack_bpffilter(pcap_t
*fp
, char *sendbuf
, int *sendbufidx
, struct bpf_program
*prog
);
150 static int pcap_createfilter_norpcappkt(pcap_t
*fp
, struct bpf_program
*prog
);
151 static int pcap_updatefilter_remote(pcap_t
*fp
, struct bpf_program
*prog
);
152 static void pcap_save_current_filter_rpcap(pcap_t
*fp
, const char *filter
);
153 static int pcap_setfilter_rpcap(pcap_t
*fp
, struct bpf_program
*prog
);
154 static int pcap_setsampling_remote(pcap_t
*fp
);
155 static int pcap_startcapture_remote(pcap_t
*fp
);
156 static int rpcap_sendauth(SOCKET sock
, uint8
*ver
, struct pcap_rmtauth
*auth
, char *errbuf
);
157 static int rpcap_recv_msg_header(SOCKET sock
, struct rpcap_header
*header
, char *errbuf
);
158 static int rpcap_check_msg_ver(SOCKET sock
, uint8 expected_ver
, struct rpcap_header
*header
, char *errbuf
);
159 static int rpcap_check_msg_type(SOCKET sock
, uint8 request_type
, struct rpcap_header
*header
, uint16
*errcode
, char *errbuf
);
160 static int rpcap_process_msg_header(SOCKET sock
, uint8 ver
, uint8 request_type
, struct rpcap_header
*header
, char *errbuf
);
161 static int rpcap_recv(SOCKET sock
, void *buffer
, size_t toread
, uint32
*plen
, char *errbuf
);
162 static void rpcap_msg_err(SOCKET sockctrl
, uint32 plen
, char *remote_errbuf
);
163 static int rpcap_discard(SOCKET sock
, uint32 len
, char *errbuf
);
164 static int rpcap_read_packet_msg(SOCKET sock
, pcap_t
*p
, size_t size
);
166 /****************************************************
170 ****************************************************/
173 * This function translates (i.e. de-serializes) a 'rpcap_sockaddr'
174 * structure from the network byte order to a 'sockaddr_in" or
175 * 'sockaddr_in6' structure in the host byte order.
177 * It accepts an 'rpcap_sockaddr' structure as it is received from the
178 * network, and checks the address family field against various values
179 * to see whether it looks like an IPv4 address, an IPv6 address, or
180 * neither of those. It checks for multiple values in order to try
181 * to handle older rpcap daemons that sent the native OS's 'sockaddr_in'
182 * or 'sockaddr_in6' structures over the wire with some members
183 * byte-swapped, and to handle the fact that AF_INET6 has different
184 * values on different OSes.
186 * For IPv4 addresses, it converts the address family to host byte
187 * order from network byte order and puts it into the structure,
188 * sets the length if a sockaddr structure has a length, converts the
189 * port number to host byte order from network byte order and puts
190 * it into the structure, copies over the IPv4 address, and zeroes
191 * out the zero padding.
193 * For IPv6 addresses, it converts the address family to host byte
194 * order from network byte order and puts it into the structure,
195 * sets the length if a sockaddr structure has a length, converts the
196 * port number and flow information to host byte order from network
197 * byte order and puts them into the structure, copies over the IPv6
198 * address, and converts the scope ID to host byte order from network
199 * byte order and puts it into the structure.
201 * The function will allocate the 'sockaddrout' variable according to the
202 * address family in use. In case the address does not belong to the
203 * AF_INET nor AF_INET6 families, 'sockaddrout' is not allocated and a
204 * NULL pointer is returned. This usually happens because that address
205 * does not exist on the other host, or is of an address family other
206 * than AF_INET or AF_INET6, so the RPCAP daemon sent a 'sockaddr_storage'
207 * structure containing all 'zero' values.
209 * Older RPCAPDs sent the addresses over the wire in the OS's native
210 * structure format. For most OSes, this looks like the over-the-wire
211 * format, but might have a different value for AF_INET6 than the value
212 * on the machine receiving the reply. For OSes with the newer BSD-style
213 * sockaddr structures, this has, instead of a 2-byte address family,
214 * a 1-byte structure length followed by a 1-byte address family. The
215 * RPCAPD code would put the address family in network byte order before
216 * sending it; that would set it to 0 on a little-endian machine, as
217 * htons() of any value between 1 and 255 would result in a value > 255,
218 * with its lower 8 bits zero, so putting that back into a 1-byte field
221 * Therefore, for older RPCAPDs running on an OS with newer BSD-style
222 * sockaddr structures, the family field, if treated as a big-endian
223 * (network byte order) 16-bit field, would be:
225 * (length << 8) | family if sent by a big-endian machine
226 * (length << 8) if sent by a little-endian machine
228 * For current RPCAPDs, and for older RPCAPDs running on an OS with
229 * older BSD-style sockaddr structures, the family field, if treated
230 * as a big-endian 16-bit field, would just contain the family.
232 * \param sockaddrin: a 'rpcap_sockaddr' pointer to the variable that has
233 * to be de-serialized.
235 * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
236 * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
237 * This variable will be allocated automatically inside this function.
239 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
240 * that will contain the error message (in case there is one).
242 * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
243 * can be only the fact that the malloc() failed to allocate memory.
244 * The error message is returned in the 'errbuf' variable, while the deserialized address
245 * is returned into the 'sockaddrout' variable.
247 * \warning This function supports only AF_INET and AF_INET6 address families.
249 * \warning The sockaddrout (if not NULL) must be deallocated by the user.
253 * Possible IPv4 family values other than the designated over-the-wire value,
254 * which is 2 (because everybody uses 2 for AF_INET4).
256 #define SOCKADDR_IN_LEN 16 /* length of struct sockaddr_in */
257 #define SOCKADDR_IN6_LEN 28 /* length of struct sockaddr_in6 */
258 #define NEW_BSD_AF_INET_BE ((SOCKADDR_IN_LEN << 8) | 2)
259 #define NEW_BSD_AF_INET_LE (SOCKADDR_IN_LEN << 8)
262 * Possible IPv6 family values other than the designated over-the-wire value,
263 * which is 23 (because that's what Windows uses, and most RPCAP servers
264 * out there are probably running Windows, as WinPcap includes the server
265 * but few if any UN*Xes build and ship it).
267 * The new BSD sockaddr structure format was in place before 4.4-Lite, so
268 * all the free-software BSDs use it.
270 #define NEW_BSD_AF_INET6_BSD_BE ((SOCKADDR_IN6_LEN << 8) | 24) /* NetBSD, OpenBSD, BSD/OS */
271 #define NEW_BSD_AF_INET6_FREEBSD_BE ((SOCKADDR_IN6_LEN << 8) | 28) /* FreeBSD, DragonFly BSD */
272 #define NEW_BSD_AF_INET6_DARWIN_BE ((SOCKADDR_IN6_LEN << 8) | 30) /* macOS, iOS, anything else Darwin-based */
273 #define NEW_BSD_AF_INET6_LE (SOCKADDR_IN6_LEN << 8)
274 #define LINUX_AF_INET6 10
275 #define HPUX_AF_INET6 22
276 #define AIX_AF_INET6 24
277 #define SOLARIS_AF_INET6 26
280 rpcap_deseraddr(struct rpcap_sockaddr
*sockaddrin
, struct sockaddr_storage
**sockaddrout
, char *errbuf
)
282 /* Warning: we support only AF_INET and AF_INET6 */
283 switch (ntohs(sockaddrin
->family
))
286 case NEW_BSD_AF_INET_BE
:
287 case NEW_BSD_AF_INET_LE
:
289 struct rpcap_sockaddr_in
*sockaddrin_ipv4
;
290 struct sockaddr_in
*sockaddrout_ipv4
;
292 (*sockaddrout
) = (struct sockaddr_storage
*) malloc(sizeof(struct sockaddr_in
));
293 if ((*sockaddrout
) == NULL
)
295 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
296 errno
, "malloc() failed");
299 sockaddrin_ipv4
= (struct rpcap_sockaddr_in
*) sockaddrin
;
300 sockaddrout_ipv4
= (struct sockaddr_in
*) (*sockaddrout
);
301 sockaddrout_ipv4
->sin_family
= AF_INET
;
302 sockaddrout_ipv4
->sin_port
= ntohs(sockaddrin_ipv4
->port
);
303 memcpy(&sockaddrout_ipv4
->sin_addr
, &sockaddrin_ipv4
->addr
, sizeof(sockaddrout_ipv4
->sin_addr
));
304 memset(sockaddrout_ipv4
->sin_zero
, 0, sizeof(sockaddrout_ipv4
->sin_zero
));
310 case NEW_BSD_AF_INET6_BSD_BE
:
311 case NEW_BSD_AF_INET6_FREEBSD_BE
:
312 case NEW_BSD_AF_INET6_DARWIN_BE
:
313 case NEW_BSD_AF_INET6_LE
:
317 case SOLARIS_AF_INET6
:
319 struct rpcap_sockaddr_in6
*sockaddrin_ipv6
;
320 struct sockaddr_in6
*sockaddrout_ipv6
;
322 (*sockaddrout
) = (struct sockaddr_storage
*) malloc(sizeof(struct sockaddr_in6
));
323 if ((*sockaddrout
) == NULL
)
325 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
326 errno
, "malloc() failed");
329 sockaddrin_ipv6
= (struct rpcap_sockaddr_in6
*) sockaddrin
;
330 sockaddrout_ipv6
= (struct sockaddr_in6
*) (*sockaddrout
);
331 sockaddrout_ipv6
->sin6_family
= AF_INET6
;
332 sockaddrout_ipv6
->sin6_port
= ntohs(sockaddrin_ipv6
->port
);
333 sockaddrout_ipv6
->sin6_flowinfo
= ntohl(sockaddrin_ipv6
->flowinfo
);
334 memcpy(&sockaddrout_ipv6
->sin6_addr
, &sockaddrin_ipv6
->addr
, sizeof(sockaddrout_ipv6
->sin6_addr
));
335 sockaddrout_ipv6
->sin6_scope_id
= ntohl(sockaddrin_ipv6
->scope_id
);
342 * It is neither AF_INET nor AF_INET6 (or, if the OS doesn't
343 * support AF_INET6, it's not AF_INET).
352 * This function reads a packet from the network socket. It does not
353 * deliver the packet to a pcap_dispatch()/pcap_loop() callback (hence
354 * the "nocb" string into its name).
356 * This function is called by pcap_read_rpcap().
358 * WARNING: By choice, this function does not make use of semaphores. A smarter
359 * implementation should put a semaphore into the data thread, and a signal will
360 * be raised as soon as there is data into the socket buffer.
361 * However this is complicated and it does not bring any advantages when reading
362 * from the network, in which network delays can be much more important than
363 * these optimizations. Therefore, we chose the following approach:
364 * - the 'timeout' chosen by the user is split in two (half on the server side,
365 * with the usual meaning, and half on the client side)
366 * - this function checks for packets; if there are no packets, it waits for
367 * timeout/2 and then it checks again. If packets are still missing, it returns,
368 * otherwise it reads packets.
370 static int pcap_read_nocb_remote(pcap_t
*p
, struct pcap_pkthdr
*pkt_header
, u_char
**pkt_data
)
372 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
373 struct rpcap_header
*header
; /* general header according to the RPCAP format */
374 struct rpcap_pkthdr
*net_pkt_header
; /* header of the packet, from the message */
375 u_char
*net_pkt_data
; /* packet data from the message */
377 int retval
; /* generic return value */
380 /* Structures needed for the select() call */
381 struct timeval tv
; /* maximum time the select() can block waiting for data */
382 fd_set rfds
; /* set of socket descriptors we have to check */
385 * Define the packet buffer timeout, to be used in the select()
386 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
388 tv
.tv_sec
= p
->opt
.timeout
/ 1000;
389 tv
.tv_usec
= (p
->opt
.timeout
- tv
.tv_sec
* 1000) * 1000;
391 /* Watch out sockdata to see if it has input */
395 * 'fp->rmt_sockdata' has always to be set before calling the select(),
396 * since it is cleared by the select()
398 FD_SET(pr
->rmt_sockdata
, &rfds
);
400 retval
= select((int) pr
->rmt_sockdata
+ 1, &rfds
, NULL
, NULL
, &tv
);
410 sock_geterror("select(): ", p
->errbuf
, PCAP_ERRBUF_SIZE
);
414 /* There is no data waiting, so return '0' */
419 * We have to define 'header' as a pointer to a larger buffer,
420 * because in case of UDP we have to read all the message within a single call
422 header
= (struct rpcap_header
*) p
->buffer
;
423 net_pkt_header
= (struct rpcap_pkthdr
*) ((char *)p
->buffer
+ sizeof(struct rpcap_header
));
424 net_pkt_data
= (u_char
*)p
->buffer
+ sizeof(struct rpcap_header
) + sizeof(struct rpcap_pkthdr
);
426 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
428 /* Read the entire message from the network */
429 msglen
= sock_recv_dgram(pr
->rmt_sockdata
, p
->buffer
,
430 p
->bufsize
, p
->errbuf
, PCAP_ERRBUF_SIZE
);
438 /* Interrupted receive. */
441 if ((size_t)msglen
< sizeof(struct rpcap_header
))
444 * Message is shorter than an rpcap header.
446 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
447 "UDP packet message is shorter than an rpcap header");
450 plen
= ntohl(header
->plen
);
451 if ((size_t)msglen
< sizeof(struct rpcap_header
) + plen
)
454 * Message is shorter than the header claims it
457 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
458 "UDP packet message is shorter than its rpcap header claims");
466 if ((size_t)p
->cc
< sizeof(struct rpcap_header
))
469 * We haven't read any of the packet header yet.
470 * The size we should get is the size of the
473 status
= rpcap_read_packet_msg(pr
->rmt_sockdata
, p
,
474 sizeof(struct rpcap_header
));
482 /* Interrupted receive. */
488 * We have the header, so we know how long the
489 * message payload is. The size we should get
490 * is the size of the packet header plus the
491 * size of the payload.
493 plen
= ntohl(header
->plen
);
494 if (plen
> p
->bufsize
- sizeof(struct rpcap_header
))
497 * This is bigger than the largest
498 * record we'd expect. (We do it by
499 * subtracting in order to avoid an
502 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
503 "Server sent us a message larger than the largest expected packet message");
506 status
= rpcap_read_packet_msg(pr
->rmt_sockdata
, p
,
507 sizeof(struct rpcap_header
) + plen
);
515 /* Interrupted receive. */
520 * We have the entire message; reset the buffer pointer
521 * and count, as the next read should start a new
529 * We have the entire message.
534 * Did the server specify the version we negotiated?
536 if (rpcap_check_msg_ver(pr
->rmt_sockdata
, pr
->protocol_version
,
537 header
, p
->errbuf
) == -1)
539 return 0; /* Return 'no packets received' */
543 * Is this a RPCAP_MSG_PACKET message?
545 if (header
->type
!= RPCAP_MSG_PACKET
)
547 return 0; /* Return 'no packets received' */
550 if (ntohl(net_pkt_header
->caplen
) > plen
)
552 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
553 "Packet's captured data goes past the end of the received packet message.");
557 /* Fill in packet header */
558 pkt_header
->caplen
= ntohl(net_pkt_header
->caplen
);
559 pkt_header
->len
= ntohl(net_pkt_header
->len
);
560 pkt_header
->ts
.tv_sec
= ntohl(net_pkt_header
->timestamp_sec
);
561 pkt_header
->ts
.tv_usec
= ntohl(net_pkt_header
->timestamp_usec
);
563 /* Supply a pointer to the beginning of the packet data */
564 *pkt_data
= net_pkt_data
;
567 * I don't update the counter of the packets dropped by the network since we're using TCP,
568 * therefore no packets are dropped. Just update the number of packets received correctly
572 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
576 /* We're using UDP, so we need to update the counter of the packets dropped by the network */
577 npkt
= ntohl(net_pkt_header
->npkt
);
579 if (pr
->TotCapt
!= npkt
)
581 pr
->TotNetDrops
+= (npkt
- pr
->TotCapt
);
586 /* Packet read successfully */
591 * This function reads a packet from the network socket.
593 * This function relies on the pcap_read_nocb_remote to deliver packets. The
594 * difference, here, is that as soon as a packet is read, it is delivered
595 * to the application by means of a callback function.
597 static int pcap_read_rpcap(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
599 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
600 struct pcap_pkthdr pkt_header
;
606 * If this is client-side, and we haven't already started
607 * the capture, start it now.
609 if (pr
->rmt_clientside
)
611 /* We are on an remote capture */
612 if (!pr
->rmt_capstarted
)
615 * The capture isn't started yet, so try to
618 if (pcap_startcapture_remote(p
))
623 while (n
< cnt
|| PACKET_COUNT_IS_UNLIMITED(cnt
))
626 * Has "pcap_breakloop()" been called?
630 * Yes - clear the flag that indicates that it
631 * has, and return PCAP_ERROR_BREAK to indicate
632 * that we were told to break out of the loop.
635 return (PCAP_ERROR_BREAK
);
641 ret
= pcap_read_nocb_remote(p
, &pkt_header
, &pkt_data
);
645 * We got a packet. Hand it to the callback
646 * and count it so we can return the count.
648 (*callback
)(user
, &pkt_header
, pkt_data
);
659 * No packet; this could mean that we timed
660 * out, or that we got interrupted, or that
661 * we got a bad packet.
663 * Were we told to break out of the loop?
670 return (PCAP_ERROR_BREAK
);
672 /* No - return the number of packets we've processed. */
680 * This function sends a CLOSE command to the capture server.
682 * It is called when the user calls pcap_close(). It sends a command
683 * to our peer that says 'ok, let's stop capturing'.
685 * WARNING: Since we're closing the connection, we do not check for errors.
687 static void pcap_cleanup_rpcap(pcap_t
*fp
)
689 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
690 struct rpcap_header header
; /* header of the RPCAP packet */
691 struct activehosts
*temp
; /* temp var needed to scan the host list chain, to detect if we're in active mode */
692 int active
= 0; /* active mode or not? */
694 /* detect if we're in active mode */
698 if (temp
->sockctrl
== pr
->rmt_sockctrl
)
708 rpcap_createhdr(&header
, pr
->protocol_version
,
709 RPCAP_MSG_CLOSE
, 0, 0);
712 * Send the close request; don't report any errors, as
713 * we're closing this pcap_t, and have no place to report
716 (void)sock_send(pr
->rmt_sockctrl
, (char *)&header
,
717 sizeof(struct rpcap_header
), NULL
, 0);
721 rpcap_createhdr(&header
, pr
->protocol_version
,
722 RPCAP_MSG_ENDCAP_REQ
, 0, 0);
725 * Send the end capture request; don't report any errors,
726 * as we're closing this pcap_t, and have no place to
729 if (sock_send(pr
->rmt_sockctrl
, (char *)&header
,
730 sizeof(struct rpcap_header
), NULL
, 0) == 0)
733 * Wait for the answer; don't report any errors,
734 * as we're closing this pcap_t, and have no
735 * place to report the error.
737 if (rpcap_process_msg_header(pr
->rmt_sockctrl
,
738 pr
->protocol_version
, RPCAP_MSG_ENDCAP_REQ
,
741 (void)rpcap_discard(pr
->rmt_sockctrl
,
747 if (pr
->rmt_sockdata
)
749 sock_close(pr
->rmt_sockdata
, NULL
, 0);
750 pr
->rmt_sockdata
= 0;
753 if ((!active
) && (pr
->rmt_sockctrl
))
754 sock_close(pr
->rmt_sockctrl
, NULL
, 0);
756 pr
->rmt_sockctrl
= 0;
758 if (pr
->currentfilter
)
760 free(pr
->currentfilter
);
761 pr
->currentfilter
= NULL
;
764 /* To avoid inconsistencies in the number of sock_init() */
769 * This function retrieves network statistics from our peer;
770 * it provides only the standard statistics.
772 static int pcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
)
774 struct pcap_stat
*retval
;
776 retval
= rpcap_stats_rpcap(p
, ps
, PCAP_STATS_STANDARD
);
786 * This function retrieves network statistics from our peer;
787 * it provides the additional statistics supported by pcap_stats_ex().
789 static struct pcap_stat
*pcap_stats_ex_rpcap(pcap_t
*p
, int *pcap_stat_size
)
791 *pcap_stat_size
= sizeof (p
->stat
);
793 /* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
794 return (rpcap_stats_rpcap(p
, &(p
->stat
), PCAP_STATS_EX
));
799 * This function retrieves network statistics from our peer. It
800 * is used by the two previous functions.
802 * It can be called in two modes:
803 * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e.,
805 * - PCAP_STATS_EX: if we want extended statistics (i.e., for
808 * This 'mode' parameter is needed because in pcap_stats() the variable that
809 * keeps the statistics is allocated by the user. On Windows, this structure
810 * has been extended in order to keep new stats. However, if the user has a
811 * smaller structure and it passes it to pcap_stats(), this function will
812 * try to fill in more data than the size of the structure, so that memory
813 * after the structure will be overwritten.
815 * So, we need to know it we have to copy just the standard fields, or the
816 * extended fields as well.
818 * In case we want to copy the extended fields as well, the problem of
819 * memory overflow no longer exists because the structure that's filled
820 * in is part of the pcap_t, so that it can be guaranteed to be large
821 * enough for the additional statistics.
823 * \param p: the pcap_t structure related to the current instance.
825 * \param ps: a pointer to a 'pcap_stat' structure, needed for compatibility
826 * with pcap_stat(), where the structure is allocated by the user. In case
827 * of pcap_stats_ex(), this structure and the function return value point
828 * to the same variable.
830 * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
832 * \return The structure that keeps the statistics, or NULL in case of error.
833 * The error string is placed in the pcap_t structure.
835 static struct pcap_stat
*rpcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
, int mode
)
837 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
838 struct rpcap_header header
; /* header of the RPCAP packet */
839 struct rpcap_stats netstats
; /* statistics sent on the network */
840 uint32 plen
; /* data remaining in the message */
843 * If the capture has not yet started, we cannot request statistics
844 * for the capture from our peer, so we return 0 for all statistics,
845 * as nothing's been seen yet.
847 if (!pr
->rmt_capstarted
)
852 #if defined(_WIN32) && defined(ENABLE_REMOTE)
853 if (mode
== PCAP_STATS_EX
)
859 #endif /* _WIN32 && ENABLE_REMOTE */
864 rpcap_createhdr(&header
, pr
->protocol_version
,
865 RPCAP_MSG_STATS_REQ
, 0, 0);
867 /* Send the PCAP_STATS command */
868 if (sock_send(pr
->rmt_sockctrl
, (char *)&header
,
869 sizeof(struct rpcap_header
), p
->errbuf
, PCAP_ERRBUF_SIZE
) < 0)
870 return NULL
; /* Unrecoverable network error */
872 /* Receive and process the reply message header. */
873 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->protocol_version
,
874 RPCAP_MSG_STATS_REQ
, &header
, p
->errbuf
) == -1)
875 return NULL
; /* Error */
879 /* Read the reply body */
880 if (rpcap_recv(pr
->rmt_sockctrl
, (char *)&netstats
,
881 sizeof(struct rpcap_stats
), &plen
, p
->errbuf
) == -1)
884 ps
->ps_drop
= ntohl(netstats
.krnldrop
);
885 ps
->ps_ifdrop
= ntohl(netstats
.ifdrop
);
886 ps
->ps_recv
= ntohl(netstats
.ifrecv
);
887 #if defined(_WIN32) && defined(ENABLE_REMOTE)
888 if (mode
== PCAP_STATS_EX
)
890 ps
->ps_capt
= pr
->TotCapt
;
891 ps
->ps_netdrop
= pr
->TotNetDrops
;
892 ps
->ps_sent
= ntohl(netstats
.svrcapt
);
894 #endif /* _WIN32 && ENABLE_REMOTE */
896 /* Discard the rest of the message. */
897 if (rpcap_discard(pr
->rmt_sockctrl
, plen
, p
->errbuf
) == -1)
904 * Discard the rest of the message.
905 * We already reported an error; if this gets an error, just
908 (void)rpcap_discard(pr
->rmt_sockctrl
, plen
, NULL
);
914 * This function returns the entry in the list of active hosts for this
915 * active connection (active mode only), or NULL if there is no
916 * active connection or an error occurred. It is just for internal
919 * \param host: a string that keeps the host name of the host for which we
920 * want to get the socket ID for that active connection.
922 * \param error: a pointer to an int that is set to 1 if an error occurred
925 * \param errbuf: a pointer to a user-allocated buffer (of size
926 * PCAP_ERRBUF_SIZE) that will contain the error message (in case
929 * \return the entry for this host in the list of active connections
930 * if found, NULL if it's not found or there's an error.
932 static struct activehosts
*
933 rpcap_remoteact_getsock(const char *host
, int *error
, char *errbuf
)
935 struct activehosts
*temp
; /* temp var needed to scan the host list chain */
936 struct addrinfo hints
, *addrinfo
, *ai_next
; /* temp var needed to translate between hostname to its address */
939 /* retrieve the network address corresponding to 'host' */
941 memset(&hints
, 0, sizeof(struct addrinfo
));
942 hints
.ai_family
= PF_UNSPEC
;
943 hints
.ai_socktype
= SOCK_STREAM
;
945 retval
= getaddrinfo(host
, "0", &hints
, &addrinfo
);
948 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "getaddrinfo() %s",
949 gai_strerror(retval
));
961 if (sock_cmpaddr(&temp
->host
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
964 freeaddrinfo(addrinfo
);
968 ai_next
= ai_next
->ai_next
;
974 freeaddrinfo(addrinfo
);
977 * The host for which you want to get the socket ID does not have an
985 * This function starts a remote capture.
987 * This function is required since the RPCAP protocol decouples the 'open'
988 * from the 'start capture' functions.
989 * This function takes all the parameters needed (which have been stored
990 * into the pcap_t structure) and sends them to the server.
992 * \param fp: the pcap_t descriptor of the device currently open.
994 * \return '0' if everything is fine, '-1' otherwise. The error message
995 * (if one) is returned into the 'errbuf' field of the pcap_t structure.
997 static int pcap_startcapture_remote(pcap_t
*fp
)
999 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1000 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
1001 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1002 char portdata
[PCAP_BUF_SIZE
]; /* temp variable needed to keep the network port for the data connection */
1004 int active
= 0; /* '1' if we're in active mode */
1005 struct activehosts
*temp
; /* temp var needed to scan the host list chain, to detect if we're in active mode */
1006 char host
[INET6_ADDRSTRLEN
+ 1]; /* numeric name of the other host */
1008 /* socket-related variables*/
1009 struct addrinfo hints
; /* temp, needed to open a socket connection */
1010 struct addrinfo
*addrinfo
; /* temp, needed to open a socket connection */
1011 SOCKET sockdata
= 0; /* socket descriptor of the data connection */
1012 struct sockaddr_storage saddr
; /* temp, needed to retrieve the network data port chosen on the local machine */
1013 socklen_t saddrlen
; /* temp, needed to retrieve the network data port chosen on the local machine */
1014 int ai_family
; /* temp, keeps the address family used by the control connection */
1016 /* RPCAP-related variables*/
1017 struct rpcap_header header
; /* header of the RPCAP packet */
1018 struct rpcap_startcapreq
*startcapreq
; /* start capture request message */
1019 struct rpcap_startcapreply startcapreply
; /* start capture reply message */
1021 /* Variables related to the buffer setting */
1024 int sockbufsize
= 0;
1025 uint32 server_sockbufsize
;
1028 * Let's check if sampling has been required.
1029 * If so, let's set it first
1031 if (pcap_setsampling_remote(fp
) != 0)
1034 /* detect if we're in active mode */
1038 if (temp
->sockctrl
== pr
->rmt_sockctrl
)
1049 * Gets the complete sockaddr structure used in the ctrl connection
1050 * This is needed to get the address family of the control socket
1051 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
1052 * since the ctrl socket can already be open in case of active mode;
1053 * so I would have to call getpeername() anyway
1055 saddrlen
= sizeof(struct sockaddr_storage
);
1056 if (getpeername(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1058 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1059 goto error_nodiscard
;
1061 ai_family
= ((struct sockaddr_storage
*) &saddr
)->ss_family
;
1063 /* Get the numeric address of the remote host we are connected to */
1064 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, host
,
1065 sizeof(host
), NULL
, 0, NI_NUMERICHOST
))
1067 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1068 goto error_nodiscard
;
1072 * Data connection is opened by the server toward the client if:
1073 * - we're using TCP, and the user wants us to be in active mode
1076 if ((active
) || (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1079 * We have to create a new socket to receive packets
1080 * We have to do that immediately, since we have to tell the other
1081 * end which network port we picked up
1083 memset(&hints
, 0, sizeof(struct addrinfo
));
1084 /* TEMP addrinfo is NULL in case of active */
1085 hints
.ai_family
= ai_family
; /* Use the same address family of the control socket */
1086 hints
.ai_socktype
= (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
) ? SOCK_DGRAM
: SOCK_STREAM
;
1087 hints
.ai_flags
= AI_PASSIVE
; /* Data connection is opened by the server toward the client */
1089 /* Let's the server pick up a free network port for us */
1090 if (sock_initaddress(NULL
, "0", &hints
, &addrinfo
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1091 goto error_nodiscard
;
1093 if ((sockdata
= sock_open(addrinfo
, SOCKOPEN_SERVER
,
1094 1 /* max 1 connection in queue */, fp
->errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1095 goto error_nodiscard
;
1097 /* addrinfo is no longer used */
1098 freeaddrinfo(addrinfo
);
1101 /* get the complete sockaddr structure used in the data connection */
1102 saddrlen
= sizeof(struct sockaddr_storage
);
1103 if (getsockname(sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1105 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1106 goto error_nodiscard
;
1109 /* Get the local port the system picked up */
1110 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, NULL
,
1111 0, portdata
, sizeof(portdata
), NI_NUMERICSERV
))
1113 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1114 goto error_nodiscard
;
1119 * Now it's time to start playing with the RPCAP protocol
1120 * RPCAP start capture command: create the request message
1122 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1123 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1124 goto error_nodiscard
;
1126 rpcap_createhdr((struct rpcap_header
*) sendbuf
,
1127 pr
->protocol_version
, RPCAP_MSG_STARTCAP_REQ
, 0,
1128 sizeof(struct rpcap_startcapreq
) + sizeof(struct rpcap_filter
) + fp
->fcode
.bf_len
* sizeof(struct rpcap_filterbpf_insn
));
1130 /* Fill the structure needed to open an adapter remotely */
1131 startcapreq
= (struct rpcap_startcapreq
*) &sendbuf
[sendbufidx
];
1133 if (sock_bufferize(NULL
, sizeof(struct rpcap_startcapreq
), NULL
,
1134 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1135 goto error_nodiscard
;
1137 memset(startcapreq
, 0, sizeof(struct rpcap_startcapreq
));
1139 /* By default, apply half the timeout on one side, half of the other */
1140 fp
->opt
.timeout
= fp
->opt
.timeout
/ 2;
1141 startcapreq
->read_timeout
= htonl(fp
->opt
.timeout
);
1143 /* portdata on the openreq is meaningful only if we're in active mode */
1144 if ((active
) || (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1146 sscanf(portdata
, "%d", (int *)&(startcapreq
->portdata
)); /* cast to avoid a compiler warning */
1147 startcapreq
->portdata
= htons(startcapreq
->portdata
);
1150 startcapreq
->snaplen
= htonl(fp
->snapshot
);
1151 startcapreq
->flags
= 0;
1153 if (pr
->rmt_flags
& PCAP_OPENFLAG_PROMISCUOUS
)
1154 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_PROMISC
;
1155 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
1156 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_DGRAM
;
1158 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN
;
1160 startcapreq
->flags
= htons(startcapreq
->flags
);
1162 /* Pack the capture filter */
1163 if (pcap_pack_bpffilter(fp
, &sendbuf
[sendbufidx
], &sendbufidx
, &fp
->fcode
))
1164 goto error_nodiscard
;
1166 if (sock_send(pr
->rmt_sockctrl
, sendbuf
, sendbufidx
, fp
->errbuf
,
1167 PCAP_ERRBUF_SIZE
) < 0)
1168 goto error_nodiscard
;
1170 /* Receive and process the reply message header. */
1171 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->protocol_version
,
1172 RPCAP_MSG_STARTCAP_REQ
, &header
, fp
->errbuf
) == -1)
1173 goto error_nodiscard
;
1177 if (rpcap_recv(pr
->rmt_sockctrl
, (char *)&startcapreply
,
1178 sizeof(struct rpcap_startcapreply
), &plen
, fp
->errbuf
) == -1)
1182 * In case of UDP data stream, the connection is always opened by the daemon
1183 * So, this case is already covered by the code above.
1184 * Now, we have still to handle TCP connections, because:
1185 * - if we're in active mode, we have to wait for a remote connection
1186 * - if we're in passive more, we have to start a connection
1188 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1189 * to tell the port we're using to the remote side; in case we're accepting a TCP
1190 * connection, we have to wait this info from the remote side.
1192 if (!(pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1196 memset(&hints
, 0, sizeof(struct addrinfo
));
1197 hints
.ai_family
= ai_family
; /* Use the same address family of the control socket */
1198 hints
.ai_socktype
= (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
) ? SOCK_DGRAM
: SOCK_STREAM
;
1199 pcap_snprintf(portdata
, PCAP_BUF_SIZE
, "%d", ntohs(startcapreply
.portdata
));
1201 /* Let's the server pick up a free network port for us */
1202 if (sock_initaddress(host
, portdata
, &hints
, &addrinfo
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1205 if ((sockdata
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, fp
->errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1208 /* addrinfo is no longer used */
1209 freeaddrinfo(addrinfo
);
1214 SOCKET socktemp
; /* We need another socket, since we're going to accept() a connection */
1216 /* Connection creation */
1217 saddrlen
= sizeof(struct sockaddr_storage
);
1219 socktemp
= accept(sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
);
1221 if (socktemp
== INVALID_SOCKET
)
1223 sock_geterror("accept(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1227 /* Now that I accepted the connection, the server socket is no longer needed */
1228 sock_close(sockdata
, fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1229 sockdata
= socktemp
;
1233 /* Let's save the socket of the data connection */
1234 pr
->rmt_sockdata
= sockdata
;
1237 * Set the size of the socket buffer for the data socket.
1238 * It has the same size as the local capture buffer used
1239 * on the other side of the connection.
1241 server_sockbufsize
= ntohl(startcapreply
.bufsize
);
1243 /* Let's get the actual size of the socket buffer */
1244 itemp
= sizeof(sockbufsize
);
1246 res
= getsockopt(sockdata
, SOL_SOCKET
, SO_RCVBUF
, (char *)&sockbufsize
, &itemp
);
1249 sock_geterror("pcap_startcapture_remote()", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1250 SOCK_ASSERT(fp
->errbuf
, 1);
1254 * Warning: on some kernels (e.g. Linux), the size of the user
1255 * buffer does not take into account the pcap_header and such,
1256 * and it is set equal to the snaplen.
1258 * In my view, this is wrong (the meaning of the bufsize became
1259 * a bit strange). So, here bufsize is the whole size of the
1260 * user buffer. In case the bufsize returned is too small,
1261 * let's adjust it accordingly.
1263 if (server_sockbufsize
<= (u_int
) fp
->snapshot
)
1264 server_sockbufsize
+= sizeof(struct pcap_pkthdr
);
1266 /* if the current socket buffer is smaller than the desired one */
1267 if ((u_int
) sockbufsize
< server_sockbufsize
)
1270 * Loop until the buffer size is OK or the original
1271 * socket buffer size is larger than this one.
1275 res
= setsockopt(sockdata
, SOL_SOCKET
, SO_RCVBUF
,
1276 (char *)&(server_sockbufsize
),
1277 sizeof(server_sockbufsize
));
1283 * If something goes wrong, halve the buffer size
1284 * (checking that it does not become smaller than
1287 server_sockbufsize
/= 2;
1289 if ((u_int
) sockbufsize
>= server_sockbufsize
)
1291 server_sockbufsize
= sockbufsize
;
1298 * Let's allocate the packet; this is required in order to put
1299 * the packet somewhere when extracting data from the socket.
1300 * Since buffering has already been done in the socket buffer,
1301 * here we need just a buffer whose size is equal to the
1302 * largest possible packet message for the snapshot size,
1303 * namely the length of the message header plus the length
1304 * of the packet header plus the snapshot length.
1306 fp
->bufsize
= sizeof(struct rpcap_header
) + sizeof(struct rpcap_pkthdr
) + fp
->snapshot
;
1308 fp
->buffer
= (u_char
*)malloc(fp
->bufsize
);
1309 if (fp
->buffer
== NULL
)
1311 pcap_fmt_errmsg_for_errno(fp
->errbuf
, PCAP_ERRBUF_SIZE
,
1317 * The buffer is currently empty.
1319 fp
->bp
= fp
->buffer
;
1322 /* Discard the rest of the message. */
1323 if (rpcap_discard(pr
->rmt_sockctrl
, plen
, fp
->errbuf
) == -1)
1327 * In case the user does not want to capture RPCAP packets, let's update the filter
1328 * We have to update it here (instead of sending it into the 'StartCapture' message
1329 * because when we generate the 'start capture' we do not know (yet) all the ports
1330 * we're currently using.
1332 if (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
)
1334 struct bpf_program fcode
;
1336 if (pcap_createfilter_norpcappkt(fp
, &fcode
) == -1)
1339 /* We cannot use 'pcap_setfilter_rpcap' because formally the capture has not been started yet */
1340 /* (the 'pr->rmt_capstarted' variable will be updated some lines below) */
1341 if (pcap_updatefilter_remote(fp
, &fcode
) == -1)
1344 pcap_freecode(&fcode
);
1347 pr
->rmt_capstarted
= 1;
1352 * When the connection has been established, we have to close it. So, at the
1353 * beginning of this function, if an error occur we return immediately with
1354 * a return NULL; when the connection is established, we have to come here
1355 * ('goto error;') in order to close everything properly.
1359 * Discard the rest of the message.
1360 * We already reported an error; if this gets an error, just
1363 (void)rpcap_discard(pr
->rmt_sockctrl
, plen
, NULL
);
1366 if ((sockdata
) && (sockdata
!= -1)) /* we can be here because sockdata said 'error' */
1367 sock_close(sockdata
, NULL
, 0);
1370 sock_close(pr
->rmt_sockctrl
, NULL
, 0);
1373 * We do not have to call pcap_close() here, because this function is always called
1374 * by the user in case something bad happens
1388 * This function takes a bpf program and sends it to the other host.
1390 * This function can be called in two cases:
1391 * - pcap_startcapture_remote() is called (we have to send the filter
1392 * along with the 'start capture' command)
1393 * - we want to udpate the filter during a capture (i.e. pcap_setfilter()
1394 * after the capture has been started)
1396 * This function serializes the filter into the sending buffer ('sendbuf',
1397 * passed as a parameter) and return back. It does not send anything on
1400 * \param fp: the pcap_t descriptor of the device currently opened.
1402 * \param sendbuf: the buffer on which the serialized data has to copied.
1404 * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1406 * \param prog: the bpf program we have to copy.
1408 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1409 * is returned into the 'errbuf' field of the pcap_t structure.
1411 static int pcap_pack_bpffilter(pcap_t
*fp
, char *sendbuf
, int *sendbufidx
, struct bpf_program
*prog
)
1413 struct rpcap_filter
*filter
;
1414 struct rpcap_filterbpf_insn
*insn
;
1415 struct bpf_insn
*bf_insn
;
1416 struct bpf_program fake_prog
; /* To be used just in case the user forgot to set a filter */
1419 if (prog
->bf_len
== 0) /* No filters have been specified; so, let's apply a "fake" filter */
1421 if (pcap_compile(fp
, &fake_prog
, NULL
/* buffer */, 1, 0) == -1)
1427 filter
= (struct rpcap_filter
*) sendbuf
;
1429 if (sock_bufferize(NULL
, sizeof(struct rpcap_filter
), NULL
, sendbufidx
,
1430 RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1433 filter
->filtertype
= htons(RPCAP_UPDATEFILTER_BPF
);
1434 filter
->nitems
= htonl((int32
)prog
->bf_len
);
1436 if (sock_bufferize(NULL
, prog
->bf_len
* sizeof(struct rpcap_filterbpf_insn
),
1437 NULL
, sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1440 insn
= (struct rpcap_filterbpf_insn
*) (filter
+ 1);
1441 bf_insn
= prog
->bf_insns
;
1443 for (i
= 0; i
< prog
->bf_len
; i
++)
1445 insn
->code
= htons(bf_insn
->code
);
1446 insn
->jf
= bf_insn
->jf
;
1447 insn
->jt
= bf_insn
->jt
;
1448 insn
->k
= htonl(bf_insn
->k
);
1458 * This function updates a filter on a remote host.
1460 * It is called when the user wants to update a filter.
1461 * In case we're capturing from the network, it sends the filter to our
1463 * This function is *not* called automatically when the user calls
1465 * There will be two cases:
1466 * - the capture has been started: in this case, pcap_setfilter_rpcap()
1467 * calls pcap_updatefilter_remote()
1468 * - the capture has not started yet: in this case, pcap_setfilter_rpcap()
1469 * stores the filter into the pcap_t structure, and then the filter is
1470 * sent with pcap_startcap().
1472 * WARNING This function *does not* clear the packet currently into the
1473 * buffers. Therefore, the user has to expect to receive some packets
1474 * that are related to the previous filter. If you want to discard all
1475 * the packets before applying a new filter, you have to close the
1476 * current capture session and start a new one.
1478 * XXX - we really should have pcap_setfilter() always discard packets
1479 * received with the old filter, and have a separate pcap_setfilter_noflush()
1480 * function that doesn't discard any packets.
1482 static int pcap_updatefilter_remote(pcap_t
*fp
, struct bpf_program
*prog
)
1484 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1485 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
1486 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1487 struct rpcap_header header
; /* To keep the reply message */
1489 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
, &sendbufidx
,
1490 RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1493 rpcap_createhdr((struct rpcap_header
*) sendbuf
,
1494 pr
->protocol_version
, RPCAP_MSG_UPDATEFILTER_REQ
, 0,
1495 sizeof(struct rpcap_filter
) + prog
->bf_len
* sizeof(struct rpcap_filterbpf_insn
));
1497 if (pcap_pack_bpffilter(fp
, &sendbuf
[sendbufidx
], &sendbufidx
, prog
))
1500 if (sock_send(pr
->rmt_sockctrl
, sendbuf
, sendbufidx
, fp
->errbuf
,
1501 PCAP_ERRBUF_SIZE
) < 0)
1504 /* Receive and process the reply message header. */
1505 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->protocol_version
,
1506 RPCAP_MSG_UPDATEFILTER_REQ
, &header
, fp
->errbuf
) == -1)
1510 * It shouldn't have any contents; discard it if it does.
1512 if (rpcap_discard(pr
->rmt_sockctrl
, header
.plen
, fp
->errbuf
) == -1)
1519 pcap_save_current_filter_rpcap(pcap_t
*fp
, const char *filter
)
1521 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1525 * - We are on an remote capture
1526 * - we do not want to capture RPCAP traffic
1528 * If so, we have to save the current filter, because we have to
1529 * add some piece of stuff later
1531 if (pr
->rmt_clientside
&&
1532 (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
))
1534 if (pr
->currentfilter
)
1535 free(pr
->currentfilter
);
1540 pr
->currentfilter
= strdup(filter
);
1545 * This function sends a filter to a remote host.
1547 * This function is called when the user wants to set a filter.
1548 * It sends the filter to our peer.
1549 * This function is called automatically when the user calls pcap_setfilter().
1551 * Parameters and return values are exactly the same of pcap_setfilter().
1553 static int pcap_setfilter_rpcap(pcap_t
*fp
, struct bpf_program
*prog
)
1555 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1557 if (!pr
->rmt_capstarted
)
1559 /* copy filter into the pcap_t structure */
1560 if (install_bpf_program(fp
, prog
) == -1)
1565 /* we have to update a filter during run-time */
1566 if (pcap_updatefilter_remote(fp
, prog
))
1573 * This function updates the current filter in order not to capture rpcap
1576 * This function is called *only* when the user wants exclude RPCAP packets
1577 * related to the current session from the captured packets.
1579 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1580 * is returned into the 'errbuf' field of the pcap_t structure.
1582 static int pcap_createfilter_norpcappkt(pcap_t
*fp
, struct bpf_program
*prog
)
1584 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1587 /* We do not want to capture our RPCAP traffic. So, let's update the filter */
1588 if (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
)
1590 struct sockaddr_storage saddr
; /* temp, needed to retrieve the network data port chosen on the local machine */
1591 socklen_t saddrlen
; /* temp, needed to retrieve the network data port chosen on the local machine */
1592 char myaddress
[128];
1593 char myctrlport
[128];
1594 char mydataport
[128];
1595 char peeraddress
[128];
1596 char peerctrlport
[128];
1598 const int newstringsize
= 1024;
1599 size_t currentfiltersize
;
1601 /* Get the name/port of our peer */
1602 saddrlen
= sizeof(struct sockaddr_storage
);
1603 if (getpeername(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1605 sock_geterror("getpeername(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1609 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, peeraddress
,
1610 sizeof(peeraddress
), peerctrlport
, sizeof(peerctrlport
), NI_NUMERICHOST
| NI_NUMERICSERV
))
1612 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1616 /* We cannot check the data port, because this is available only in case of TCP sockets */
1617 /* Get the name/port of the current host */
1618 if (getsockname(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1620 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1624 /* Get the local port the system picked up */
1625 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, myaddress
,
1626 sizeof(myaddress
), myctrlport
, sizeof(myctrlport
), NI_NUMERICHOST
| NI_NUMERICSERV
))
1628 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1632 /* Let's now check the data port */
1633 if (getsockname(pr
->rmt_sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1635 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1639 /* Get the local port the system picked up */
1640 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, NULL
, 0, mydataport
, sizeof(mydataport
), NI_NUMERICSERV
))
1642 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1646 currentfiltersize
= pr
->currentfilter
? strlen(pr
->currentfilter
) : 0;
1648 newfilter
= (char *)malloc(currentfiltersize
+ newstringsize
+ 1);
1650 if (currentfiltersize
)
1652 pcap_snprintf(newfilter
, currentfiltersize
+ newstringsize
,
1653 "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1654 pr
->currentfilter
, myaddress
, peeraddress
, myctrlport
, peerctrlport
, myaddress
, peeraddress
, mydataport
);
1658 pcap_snprintf(newfilter
, currentfiltersize
+ newstringsize
,
1659 "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1660 myaddress
, peeraddress
, myctrlport
, peerctrlport
, myaddress
, peeraddress
, mydataport
);
1663 newfilter
[currentfiltersize
+ newstringsize
] = 0;
1666 * This is only an hack to prevent the save_current_filter
1667 * routine, which will be called when we call pcap_compile(),
1668 * from saving the modified filter.
1670 pr
->rmt_clientside
= 0;
1672 if (pcap_compile(fp
, prog
, newfilter
, 1, 0) == -1)
1675 /* Undo the hack. */
1676 pr
->rmt_clientside
= 1;
1685 * This function sets sampling parameters in the remote host.
1687 * It is called when the user wants to set activate sampling on the
1690 * Sampling parameters are defined into the 'pcap_t' structure.
1692 * \param p: the pcap_t descriptor of the device currently opened.
1694 * \return '0' if everything is OK, '-1' is something goes wrong. The
1695 * error message is returned in the 'errbuf' member of the pcap_t structure.
1697 static int pcap_setsampling_remote(pcap_t
*fp
)
1699 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1700 char sendbuf
[RPCAP_NETBUF_SIZE
];/* temporary buffer in which data to be sent is buffered */
1701 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1702 struct rpcap_header header
; /* To keep the reply message */
1703 struct rpcap_sampling
*sampling_pars
; /* Structure that is needed to send sampling parameters to the remote host */
1705 /* If no samping is requested, return 'ok' */
1706 if (fp
->rmt_samp
.method
== PCAP_SAMP_NOSAMP
)
1709 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1710 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1713 rpcap_createhdr((struct rpcap_header
*) sendbuf
,
1714 pr
->protocol_version
, RPCAP_MSG_SETSAMPLING_REQ
, 0,
1715 sizeof(struct rpcap_sampling
));
1717 /* Fill the structure needed to open an adapter remotely */
1718 sampling_pars
= (struct rpcap_sampling
*) &sendbuf
[sendbufidx
];
1720 if (sock_bufferize(NULL
, sizeof(struct rpcap_sampling
), NULL
,
1721 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1724 memset(sampling_pars
, 0, sizeof(struct rpcap_sampling
));
1726 sampling_pars
->method
= fp
->rmt_samp
.method
;
1727 sampling_pars
->value
= htonl(fp
->rmt_samp
.value
);
1729 if (sock_send(pr
->rmt_sockctrl
, sendbuf
, sendbufidx
, fp
->errbuf
,
1730 PCAP_ERRBUF_SIZE
) < 0)
1733 /* Receive and process the reply message header. */
1734 if (rpcap_process_msg_header(pr
->rmt_sockctrl
, pr
->protocol_version
,
1735 RPCAP_MSG_SETSAMPLING_REQ
, &header
, fp
->errbuf
) == -1)
1739 * It shouldn't have any contents; discard it if it does.
1741 if (rpcap_discard(pr
->rmt_sockctrl
, header
.plen
, fp
->errbuf
) == -1)
1747 /*********************************************************
1749 * Miscellaneous functions *
1751 *********************************************************/
1754 * This function performs authentication and protocol version
1755 * negotiation. It first tries to authenticate with the maximum
1756 * version we support and, if that fails with an "I don't support
1757 * that version" error from the server, and the version number in
1758 * the reply from the server is one we support, tries again with
1761 * \param sock: the socket we are currently using.
1763 * \param ver: pointer to variable holding protocol version number to send
1764 * and to set to the protocol version number in the reply.
1766 * \param auth: authentication parameters that have to be sent.
1768 * \param errbuf: a pointer to a user-allocated buffer (of size
1769 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1770 * is one). It could be a network problem or the fact that the authorization
1773 * \return '0' if everything is fine, '-1' for an error. For errors,
1774 * an error message string is returned in the 'errbuf' variable.
1776 static int rpcap_doauth(SOCKET sockctrl
, uint8
*ver
, struct pcap_rmtauth
*auth
, char *errbuf
)
1781 * Send authentication to the remote machine.
1783 * First try with the maximum version number we support.
1785 *ver
= RPCAP_MAX_VERSION
;
1786 status
= rpcap_sendauth(sockctrl
, ver
, auth
, errbuf
);
1796 /* Unrecoverable error. */
1801 * The server doesn't support the version we used in the initial
1802 * message, and it sent us back a reply either with the maximum
1803 * version they do support, or with the version we sent, and we
1804 * support that version. *ver has been set to that version; try
1805 * authenticating again with that version.
1807 status
= rpcap_sendauth(sockctrl
, ver
, auth
, errbuf
);
1817 /* Unrecoverable error. */
1823 * The server doesn't support that version, which
1824 * means there is no version we both support, so
1825 * this is a fatal error.
1827 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The server doesn't support any protocol version that we support");
1830 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "rpcap_sendauth() returned %d", status
);
1835 * This function sends the authentication message.
1837 * It sends the authentication parameters on the control socket.
1838 * It is required in order to open the connection with the other end party.
1840 * \param sock: the socket we are currently using.
1842 * \param ver: pointer to variable holding protocol version number to send
1843 * and to set to the protocol version number in the reply.
1845 * \param auth: authentication parameters that have to be sent.
1847 * \param errbuf: a pointer to a user-allocated buffer (of size
1848 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1849 * is one). It could be a network problem or the fact that the authorization
1852 * \return '0' if everything is fine, '-2' if the server didn't reply with
1853 * the protocol version we requested but replied with a version we do
1854 * support, or '-1' for other errors. For errors, an error message string
1855 * is returned in the 'errbuf' variable.
1857 static int rpcap_sendauth(SOCKET sock
, uint8
*ver
, struct pcap_rmtauth
*auth
, char *errbuf
)
1859 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data that has to be sent is buffered */
1860 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1861 uint16 length
; /* length of the payload of this message */
1863 struct rpcap_auth
*rpauth
;
1865 struct rpcap_header header
;
1870 auth_type
= auth
->type
;
1874 case RPCAP_RMTAUTH_NULL
:
1875 length
= sizeof(struct rpcap_auth
);
1878 case RPCAP_RMTAUTH_PWD
:
1879 length
= sizeof(struct rpcap_auth
);
1882 str_length
= strlen(auth
->username
);
1883 if (str_length
> 65535)
1885 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "User name is too long (> 65535 bytes)");
1888 length
+= (uint16
)str_length
;
1892 str_length
= strlen(auth
->password
);
1893 if (str_length
> 65535)
1895 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Password is too long (> 65535 bytes)");
1898 length
+= (uint16
)str_length
;
1903 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Authentication type not recognized.");
1909 auth_type
= RPCAP_RMTAUTH_NULL
;
1910 length
= sizeof(struct rpcap_auth
);
1914 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1915 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
1918 rpcap_createhdr((struct rpcap_header
*) sendbuf
, *ver
,
1919 RPCAP_MSG_AUTH_REQ
, 0, length
);
1921 rpauth
= (struct rpcap_auth
*) &sendbuf
[sendbufidx
];
1923 if (sock_bufferize(NULL
, sizeof(struct rpcap_auth
), NULL
,
1924 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
1927 memset(rpauth
, 0, sizeof(struct rpcap_auth
));
1929 rpauth
->type
= htons(auth_type
);
1931 if (auth_type
== RPCAP_RMTAUTH_PWD
)
1934 rpauth
->slen1
= (uint16
)strlen(auth
->username
);
1938 if (sock_bufferize(auth
->username
, rpauth
->slen1
, sendbuf
,
1939 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
1943 rpauth
->slen2
= (uint16
)strlen(auth
->password
);
1947 if (sock_bufferize(auth
->password
, rpauth
->slen2
, sendbuf
,
1948 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
1951 rpauth
->slen1
= htons(rpauth
->slen1
);
1952 rpauth
->slen2
= htons(rpauth
->slen2
);
1955 if (sock_send(sock
, sendbuf
, sendbufidx
, errbuf
, PCAP_ERRBUF_SIZE
) < 0)
1958 /* Receive the reply */
1959 if (rpcap_recv_msg_header(sock
, &header
, errbuf
) == -1)
1962 if (rpcap_check_msg_type(sock
, RPCAP_MSG_AUTH_REQ
, &header
,
1963 &errcode
, errbuf
) == -1)
1965 /* Error message - or something else, which is a protocol error. */
1966 if (header
.type
== RPCAP_MSG_ERROR
&&
1967 errcode
== PCAP_ERR_WRONGVER
)
1970 * The server didn't support the version we sent,
1971 * and replied with the maximum version it supports
1972 * if our version was too big or with the version
1973 * we sent if out version was too small.
1975 * Do we also support it?
1977 if (header
.ver
< RPCAP_MIN_VERSION
||
1978 header
.ver
> RPCAP_MAX_VERSION
)
1981 * No, so there's no version we both support.
1982 * This is an unrecoverable error.
1984 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The server doesn't support any protocol version that we support");
1989 * OK, use that version, and tell our caller to
1997 * Other error - unrecoverable.
2003 * OK, it's an authentication reply, so they're OK with the
2004 * protocol version we sent.
2006 * Discard the rest of it.
2008 if (rpcap_discard(sock
, header
.plen
, errbuf
) == -1)
2014 /* We don't currently support non-blocking mode. */
2016 pcap_getnonblock_rpcap(pcap_t
*p
)
2018 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
2019 "Non-blocking mode isn't supported for capturing remotely with rpcap");
2024 pcap_setnonblock_rpcap(pcap_t
*p
, int nonblock _U_
)
2026 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
2027 "Non-blocking mode isn't supported for capturing remotely with rpcap");
2032 * This function opens a remote adapter by opening an RPCAP connection and
2035 * It does the job of pcap_open_live() for a remote interface; it's called
2036 * by pcap_open() for remote interfaces.
2038 * We do not start the capture until pcap_startcapture_remote() is called.
2040 * This is because, when doing a remote capture, we cannot start capturing
2041 * data as soon as the 'open adapter' command is sent. Suppose the remote
2042 * adapter is already overloaded; if we start a capture (which, by default,
2043 * has a NULL filter) the new traffic can saturate the network.
2045 * Instead, we want to "open" the adapter, then send a "start capture"
2046 * command only when we're ready to start the capture.
2047 * This function does this job: it sends an "open adapter" command
2048 * (according to the RPCAP protocol), but it does not start the capture.
2050 * Since the other libpcap functions do not share this way of life, we
2051 * have to do some dirty things in order to make everything work.
2053 * \param source: see pcap_open().
2054 * \param snaplen: see pcap_open().
2055 * \param flags: see pcap_open().
2056 * \param read_timeout: see pcap_open().
2057 * \param auth: see pcap_open().
2058 * \param errbuf: see pcap_open().
2060 * \return a pcap_t pointer in case of success, NULL otherwise. In case of
2061 * success, the pcap_t pointer can be used as a parameter to the following
2062 * calls (pcap_compile() and so on). In case of problems, errbuf contains
2063 * a text explanation of error.
2065 * WARNING: In case we call pcap_compile() and the capture has not yet
2066 * been started, the filter will be saved into the pcap_t structure,
2067 * and it will be sent to the other host later (when
2068 * pcap_startcapture_remote() is called).
2070 pcap_t
*pcap_open_rpcap(const char *source
, int snaplen
, int flags
, int read_timeout
, struct pcap_rmtauth
*auth
, char *errbuf
)
2074 struct pcap_rpcap
*pr
; /* structure used when doing a remote live capture */
2075 char host
[PCAP_BUF_SIZE
], ctrlport
[PCAP_BUF_SIZE
], iface
[PCAP_BUF_SIZE
];
2076 struct activehosts
*activeconn
; /* active connection, if there is one */
2077 int error
; /* '1' if rpcap_remoteact_getsock returned an error */
2079 uint8 protocol_version
; /* negotiated protocol version */
2082 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
2083 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
2084 int retval
; /* store the return value of the functions */
2086 /* RPCAP-related variables */
2087 struct rpcap_header header
; /* header of the RPCAP packet */
2088 struct rpcap_openreply openreply
; /* open reply message */
2090 fp
= pcap_create_common(errbuf
, sizeof (struct pcap_rpcap
));
2095 source_str
= strdup(source
);
2096 if (source_str
== NULL
) {
2097 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2103 * Turn a negative snapshot value (invalid), a snapshot value of
2104 * 0 (unspecified), or a value bigger than the normal maximum
2105 * value, into the maximum allowed value.
2107 * If some application really *needs* a bigger snapshot
2108 * length, we should just increase MAXIMUM_SNAPLEN.
2110 * XXX - should we leave this up to the remote server to
2113 if (snaplen
<= 0 || snaplen
> MAXIMUM_SNAPLEN
)
2114 snaplen
= MAXIMUM_SNAPLEN
;
2116 fp
->opt
.device
= source_str
;
2117 fp
->snapshot
= snaplen
;
2118 fp
->opt
.timeout
= read_timeout
;
2120 pr
->rmt_flags
= flags
;
2123 * determine the type of the source (NULL, file, local, remote)
2124 * You must have a valid source string even if we're in active mode, because otherwise
2125 * the call to the following function will fail.
2127 if (pcap_parsesrcstr(fp
->opt
.device
, &retval
, host
, ctrlport
, iface
, errbuf
) == -1)
2133 if (retval
!= PCAP_SRC_IFREMOTE
)
2135 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "This function is able to open only remote interfaces");
2141 * Warning: this call can be the first one called by the user.
2142 * For this reason, we have to initialize the WinSock support.
2144 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2150 /* Check for active mode */
2151 activeconn
= rpcap_remoteact_getsock(host
, &error
, errbuf
);
2152 if (activeconn
!= NULL
)
2154 sockctrl
= activeconn
->sockctrl
;
2155 protocol_version
= activeconn
->protocol_version
;
2160 struct addrinfo hints
; /* temp, needed to open a socket connection */
2161 struct addrinfo
*addrinfo
; /* temp, needed to open a socket connection */
2173 * We're not in active mode; let's try to open a new
2174 * control connection.
2176 memset(&hints
, 0, sizeof(struct addrinfo
));
2177 hints
.ai_family
= PF_UNSPEC
;
2178 hints
.ai_socktype
= SOCK_STREAM
;
2180 if (ctrlport
[0] == 0)
2182 /* the user chose not to specify the port */
2183 if (sock_initaddress(host
, RPCAP_DEFAULT_NETPORT
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2191 if (sock_initaddress(host
, ctrlport
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2198 if ((sockctrl
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
2200 freeaddrinfo(addrinfo
);
2205 /* addrinfo is no longer used */
2206 freeaddrinfo(addrinfo
);
2208 if (rpcap_doauth(sockctrl
, &protocol_version
, auth
, errbuf
) == -1)
2210 sock_close(sockctrl
, NULL
, 0);
2218 * Now it's time to start playing with the RPCAP protocol
2219 * RPCAP open command: create the request message
2221 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
2222 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
2223 goto error_nodiscard
;
2225 rpcap_createhdr((struct rpcap_header
*) sendbuf
, protocol_version
,
2226 RPCAP_MSG_OPEN_REQ
, 0, (uint32
) strlen(iface
));
2228 if (sock_bufferize(iface
, (int) strlen(iface
), sendbuf
, &sendbufidx
,
2229 RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
2230 goto error_nodiscard
;
2232 if (sock_send(sockctrl
, sendbuf
, sendbufidx
, errbuf
,
2233 PCAP_ERRBUF_SIZE
) < 0)
2234 goto error_nodiscard
;
2236 /* Receive and process the reply message header. */
2237 if (rpcap_process_msg_header(sockctrl
, protocol_version
,
2238 RPCAP_MSG_OPEN_REQ
, &header
, errbuf
) == -1)
2239 goto error_nodiscard
;
2242 /* Read the reply body */
2243 if (rpcap_recv(sockctrl
, (char *)&openreply
,
2244 sizeof(struct rpcap_openreply
), &plen
, errbuf
) == -1)
2247 /* Discard the rest of the message, if there is any. */
2248 if (rpcap_discard(pr
->rmt_sockctrl
, plen
, errbuf
) == -1)
2249 goto error_nodiscard
;
2251 /* Set proper fields into the pcap_t struct */
2252 fp
->linktype
= ntohl(openreply
.linktype
);
2253 fp
->tzoff
= ntohl(openreply
.tzoff
);
2254 pr
->rmt_sockctrl
= sockctrl
;
2255 pr
->protocol_version
= protocol_version
;
2256 pr
->rmt_clientside
= 1;
2258 /* This code is duplicated from the end of this function */
2259 fp
->read_op
= pcap_read_rpcap
;
2260 fp
->save_current_filter_op
= pcap_save_current_filter_rpcap
;
2261 fp
->setfilter_op
= pcap_setfilter_rpcap
;
2262 fp
->getnonblock_op
= pcap_getnonblock_rpcap
;
2263 fp
->setnonblock_op
= pcap_setnonblock_rpcap
;
2264 fp
->stats_op
= pcap_stats_rpcap
;
2266 fp
->stats_ex_op
= pcap_stats_ex_rpcap
;
2268 fp
->cleanup_op
= pcap_cleanup_rpcap
;
2275 * When the connection has been established, we have to close it. So, at the
2276 * beginning of this function, if an error occur we return immediately with
2277 * a return NULL; when the connection is established, we have to come here
2278 * ('goto error;') in order to close everything properly.
2282 * Discard the rest of the message.
2283 * We already reported an error; if this gets an error, just
2286 (void)rpcap_discard(pr
->rmt_sockctrl
, plen
, NULL
);
2290 sock_close(sockctrl
, NULL
, 0);
2296 /* String identifier to be used in the pcap_findalldevs_ex() */
2297 #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
2298 /* String identifier to be used in the pcap_findalldevs_ex() */
2299 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST "on remote node"
2302 freeaddr(struct pcap_addr
*addr
)
2305 free(addr
->netmask
);
2306 free(addr
->broadaddr
);
2307 free(addr
->dstaddr
);
2312 pcap_findalldevs_ex_remote(char *source
, struct pcap_rmtauth
*auth
, pcap_if_t
**alldevs
, char *errbuf
)
2314 struct activehosts
*activeconn
; /* active connection, if there is one */
2315 int error
; /* '1' if rpcap_remoteact_getsock returned an error */
2316 uint8 protocol_version
; /* protocol version */
2317 SOCKET sockctrl
; /* socket descriptor of the control connection */
2319 struct rpcap_header header
; /* structure that keeps the general header of the rpcap protocol */
2320 int i
, j
; /* temp variables */
2321 int nif
; /* Number of interfaces listed */
2322 int active
; /* 'true' if we the other end-party is in active mode */
2324 char host
[PCAP_BUF_SIZE
], port
[PCAP_BUF_SIZE
];
2325 char tmpstring
[PCAP_BUF_SIZE
+ 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2326 pcap_if_t
*lastdev
; /* Last device in the pcap_if_t list */
2327 pcap_if_t
*dev
; /* Device we're adding to the pcap_if_t list */
2329 /* List starts out empty. */
2333 /* Retrieve the needed data for getting adapter list */
2334 if (pcap_parsesrcstr(source
, &type
, host
, port
, NULL
, errbuf
) == -1)
2337 /* Warning: this call can be the first one called by the user. */
2338 /* For this reason, we have to initialize the WinSock support. */
2339 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2342 /* Check for active mode */
2343 activeconn
= rpcap_remoteact_getsock(host
, &error
, errbuf
);
2344 if (activeconn
!= NULL
)
2346 sockctrl
= activeconn
->sockctrl
;
2347 protocol_version
= activeconn
->protocol_version
;
2352 struct addrinfo hints
; /* temp variable needed to resolve hostnames into to socket representation */
2353 struct addrinfo
*addrinfo
; /* temp variable needed to resolve hostnames into to socket representation */
2364 * We're not in active mode; let's try to open a new
2365 * control connection.
2367 memset(&hints
, 0, sizeof(struct addrinfo
));
2368 hints
.ai_family
= PF_UNSPEC
;
2369 hints
.ai_socktype
= SOCK_STREAM
;
2373 /* the user chose not to specify the port */
2374 if (sock_initaddress(host
, RPCAP_DEFAULT_NETPORT
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2379 if (sock_initaddress(host
, port
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2383 if ((sockctrl
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
2385 freeaddrinfo(addrinfo
);
2389 /* addrinfo is no longer used */
2390 freeaddrinfo(addrinfo
);
2393 if (rpcap_doauth(sockctrl
, &protocol_version
, auth
, errbuf
) == -1)
2395 sock_close(sockctrl
, NULL
, 0);
2401 /* RPCAP findalldevs command */
2402 rpcap_createhdr(&header
, protocol_version
, RPCAP_MSG_FINDALLIF_REQ
,
2405 if (sock_send(sockctrl
, (char *)&header
, sizeof(struct rpcap_header
),
2406 errbuf
, PCAP_ERRBUF_SIZE
) < 0)
2407 goto error_nodiscard
;
2409 /* Receive and process the reply message header. */
2410 if (rpcap_process_msg_header(sockctrl
, protocol_version
,
2411 RPCAP_MSG_FINDALLIF_REQ
, &header
, errbuf
) == -1)
2412 goto error_nodiscard
;
2416 /* read the number of interfaces */
2417 nif
= ntohs(header
.value
);
2419 /* loop until all interfaces have been received */
2420 for (i
= 0; i
< nif
; i
++)
2422 struct rpcap_findalldevs_if findalldevs_if
;
2423 char tmpstring2
[PCAP_BUF_SIZE
+ 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2425 struct pcap_addr
*addr
, *prevaddr
;
2427 tmpstring2
[PCAP_BUF_SIZE
] = 0;
2429 /* receive the findalldevs structure from remote host */
2430 if (rpcap_recv(sockctrl
, (char *)&findalldevs_if
,
2431 sizeof(struct rpcap_findalldevs_if
), &plen
, errbuf
) == -1)
2434 findalldevs_if
.namelen
= ntohs(findalldevs_if
.namelen
);
2435 findalldevs_if
.desclen
= ntohs(findalldevs_if
.desclen
);
2436 findalldevs_if
.naddr
= ntohs(findalldevs_if
.naddr
);
2438 /* allocate the main structure */
2439 dev
= (pcap_if_t
*)malloc(sizeof(pcap_if_t
));
2442 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2443 errno
, "malloc() failed");
2447 /* Initialize the structure to 'zero' */
2448 memset(dev
, 0, sizeof(pcap_if_t
));
2450 /* Append it to the list. */
2451 if (lastdev
== NULL
)
2454 * List is empty, so it's also the first device.
2461 * Append after the last device.
2463 lastdev
->next
= dev
;
2465 /* It's now the last device. */
2468 /* allocate mem for name and description */
2469 if (findalldevs_if
.namelen
)
2472 if (findalldevs_if
.namelen
>= sizeof(tmpstring
))
2474 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Interface name too long");
2478 /* Retrieve adapter name */
2479 if (rpcap_recv(sockctrl
, tmpstring
,
2480 findalldevs_if
.namelen
, &plen
, errbuf
) == -1)
2483 tmpstring
[findalldevs_if
.namelen
] = 0;
2485 /* Create the new device identifier */
2486 if (pcap_createsrcstr(tmpstring2
, PCAP_SRC_IFREMOTE
, host
, port
, tmpstring
, errbuf
) == -1)
2489 stringlen
= strlen(tmpstring2
);
2491 dev
->name
= (char *)malloc(stringlen
+ 1);
2492 if (dev
->name
== NULL
)
2494 pcap_fmt_errmsg_for_errno(errbuf
,
2495 PCAP_ERRBUF_SIZE
, errno
, "malloc() failed");
2499 /* Copy the new device name into the correct memory location */
2500 strlcpy(dev
->name
, tmpstring2
, stringlen
+ 1);
2503 if (findalldevs_if
.desclen
)
2505 if (findalldevs_if
.desclen
>= sizeof(tmpstring
))
2507 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Interface description too long");
2511 /* Retrieve adapter description */
2512 if (rpcap_recv(sockctrl
, tmpstring
,
2513 findalldevs_if
.desclen
, &plen
, errbuf
) == -1)
2516 tmpstring
[findalldevs_if
.desclen
] = 0;
2518 pcap_snprintf(tmpstring2
, sizeof(tmpstring2
) - 1, "%s '%s' %s %s", PCAP_TEXT_SOURCE_ADAPTER
,
2519 tmpstring
, PCAP_TEXT_SOURCE_ON_REMOTE_HOST
, host
);
2521 stringlen
= strlen(tmpstring2
);
2523 dev
->description
= (char *)malloc(stringlen
+ 1);
2525 if (dev
->description
== NULL
)
2527 pcap_fmt_errmsg_for_errno(errbuf
,
2528 PCAP_ERRBUF_SIZE
, errno
, "malloc() failed");
2532 /* Copy the new device description into the correct memory location */
2533 strlcpy(dev
->description
, tmpstring2
, stringlen
+ 1);
2536 dev
->flags
= ntohl(findalldevs_if
.flags
);
2539 /* loop until all addresses have been received */
2540 for (j
= 0; j
< findalldevs_if
.naddr
; j
++)
2542 struct rpcap_findalldevs_ifaddr ifaddr
;
2544 /* Retrieve the interface addresses */
2545 if (rpcap_recv(sockctrl
, (char *)&ifaddr
,
2546 sizeof(struct rpcap_findalldevs_ifaddr
),
2547 &plen
, errbuf
) == -1)
2551 * Deserialize all the address components.
2553 addr
= (struct pcap_addr
*) malloc(sizeof(struct pcap_addr
));
2556 pcap_fmt_errmsg_for_errno(errbuf
,
2557 PCAP_ERRBUF_SIZE
, errno
, "malloc() failed");
2562 addr
->netmask
= NULL
;
2563 addr
->broadaddr
= NULL
;
2564 addr
->dstaddr
= NULL
;
2566 if (rpcap_deseraddr(&ifaddr
.addr
,
2567 (struct sockaddr_storage
**) &addr
->addr
, errbuf
) == -1)
2572 if (rpcap_deseraddr(&ifaddr
.netmask
,
2573 (struct sockaddr_storage
**) &addr
->netmask
, errbuf
) == -1)
2578 if (rpcap_deseraddr(&ifaddr
.broadaddr
,
2579 (struct sockaddr_storage
**) &addr
->broadaddr
, errbuf
) == -1)
2584 if (rpcap_deseraddr(&ifaddr
.dstaddr
,
2585 (struct sockaddr_storage
**) &addr
->dstaddr
, errbuf
) == -1)
2591 if ((addr
->addr
== NULL
) && (addr
->netmask
== NULL
) &&
2592 (addr
->broadaddr
== NULL
) && (addr
->dstaddr
== NULL
))
2595 * None of the addresses are IPv4 or IPv6
2596 * addresses, so throw this entry away.
2603 * Add this entry to the list.
2605 if (prevaddr
== NULL
)
2607 dev
->addresses
= addr
;
2611 prevaddr
->next
= addr
;
2618 /* Discard the rest of the message. */
2619 if (rpcap_discard(sockctrl
, plen
, errbuf
) == 1)
2622 /* Control connection has to be closed only in case the remote machine is in passive mode */
2625 /* DO not send RPCAP_CLOSE, since we did not open a pcap_t; no need to free resources */
2626 if (sock_close(sockctrl
, errbuf
, PCAP_ERRBUF_SIZE
))
2630 /* To avoid inconsistencies in the number of sock_init() */
2637 * In case there has been an error, I don't want to overwrite it with a new one
2638 * if the following call fails. I want to return always the original error.
2640 * Take care: this connection can already be closed when we try to close it.
2641 * This happens because a previous error in the rpcapd, which requested to
2642 * closed the connection. In that case, we already recognized that into the
2643 * rpspck_isheaderok() and we already acknowledged the closing.
2644 * In that sense, this call is useless here (however it is needed in case
2645 * the client generates the error).
2647 * Checks if all the data has been read; if not, discard the data in excess
2649 (void) rpcap_discard(sockctrl
, plen
, NULL
);
2652 /* Control connection has to be closed only in case the remote machine is in passive mode */
2654 sock_close(sockctrl
, NULL
, 0);
2656 /* To avoid inconsistencies in the number of sock_init() */
2659 /* Free whatever interfaces we've allocated. */
2660 pcap_freealldevs(*alldevs
);
2666 * Active mode routines.
2668 * The old libpcap API is somewhat ugly, and makes active mode difficult
2669 * to implement; we provide some APIs for it that work only with rpcap.
2672 SOCKET
pcap_remoteact_accept(const char *address
, const char *port
, const char *hostlist
, char *connectinghost
, struct pcap_rmtauth
*auth
, char *errbuf
)
2674 /* socket-related variables */
2675 struct addrinfo hints
; /* temporary struct to keep settings needed to open the new socket */
2676 struct addrinfo
*addrinfo
; /* keeps the addrinfo chain; required to open a new socket */
2677 struct sockaddr_storage from
; /* generic sockaddr_storage variable */
2678 socklen_t fromlen
; /* keeps the length of the sockaddr_storage variable */
2679 SOCKET sockctrl
; /* keeps the main socket identifier */
2680 uint8 protocol_version
; /* negotiated protocol version */
2681 struct activehosts
*temp
, *prev
; /* temp var needed to scan he host list chain */
2683 *connectinghost
= 0; /* just in case */
2685 /* Prepare to open a new server socket */
2686 memset(&hints
, 0, sizeof(struct addrinfo
));
2687 /* WARNING Currently it supports only ONE socket family among ipv4 and IPv6 */
2688 hints
.ai_family
= AF_INET
; /* PF_UNSPEC to have both IPv4 and IPv6 server */
2689 hints
.ai_flags
= AI_PASSIVE
; /* Ready to a bind() socket */
2690 hints
.ai_socktype
= SOCK_STREAM
;
2692 /* Warning: this call can be the first one called by the user. */
2693 /* For this reason, we have to initialize the WinSock support. */
2694 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2698 if ((port
== NULL
) || (port
[0] == 0))
2700 if (sock_initaddress(address
, RPCAP_DEFAULT_NETPORT_ACTIVE
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2702 SOCK_ASSERT(errbuf
, 1);
2708 if (sock_initaddress(address
, port
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2710 SOCK_ASSERT(errbuf
, 1);
2716 if ((sockmain
= sock_open(addrinfo
, SOCKOPEN_SERVER
, 1, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
2718 SOCK_ASSERT(errbuf
, 1);
2719 freeaddrinfo(addrinfo
);
2722 freeaddrinfo(addrinfo
);
2724 /* Connection creation */
2725 fromlen
= sizeof(struct sockaddr_storage
);
2727 sockctrl
= accept(sockmain
, (struct sockaddr
*) &from
, &fromlen
);
2729 /* We're not using sock_close, since we do not want to send a shutdown */
2730 /* (which is not allowed on a non-connected socket) */
2731 closesocket(sockmain
);
2734 if (sockctrl
== INVALID_SOCKET
)
2736 sock_geterror("accept(): ", errbuf
, PCAP_ERRBUF_SIZE
);
2740 /* Get the numeric for of the name of the connecting host */
2741 if (getnameinfo((struct sockaddr
*) &from
, fromlen
, connectinghost
, RPCAP_HOSTLIST_SIZE
, NULL
, 0, NI_NUMERICHOST
))
2743 sock_geterror("getnameinfo(): ", errbuf
, PCAP_ERRBUF_SIZE
);
2744 rpcap_senderror(sockctrl
, 0, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
2745 sock_close(sockctrl
, NULL
, 0);
2749 /* checks if the connecting host is among the ones allowed */
2750 if (sock_check_hostlist((char *)hostlist
, RPCAP_HOSTLIST_SEP
, &from
, errbuf
, PCAP_ERRBUF_SIZE
) < 0)
2752 rpcap_senderror(sockctrl
, 0, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
2753 sock_close(sockctrl
, NULL
, 0);
2758 * Send authentication to the remote machine.
2760 if (rpcap_doauth(sockctrl
, &protocol_version
, auth
, errbuf
) == -1)
2762 /* Unrecoverable error. */
2763 rpcap_senderror(sockctrl
, 0, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
2764 sock_close(sockctrl
, NULL
, 0);
2768 /* Checks that this host does not already have a cntrl connection in place */
2770 /* Initialize pointers */
2776 /* This host already has an active connection in place, so I don't have to update the host list */
2777 if (sock_cmpaddr(&temp
->host
, &from
) == 0)
2784 /* The host does not exist in the list; so I have to update the list */
2787 prev
->next
= (struct activehosts
*) malloc(sizeof(struct activehosts
));
2792 activeHosts
= (struct activehosts
*) malloc(sizeof(struct activehosts
));
2798 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2799 errno
, "malloc() failed");
2800 rpcap_senderror(sockctrl
, protocol_version
, PCAP_ERR_REMOTEACCEPT
, errbuf
, NULL
);
2801 sock_close(sockctrl
, NULL
, 0);
2805 memcpy(&temp
->host
, &from
, fromlen
);
2806 temp
->sockctrl
= sockctrl
;
2807 temp
->protocol_version
= protocol_version
;
2813 int pcap_remoteact_close(const char *host
, char *errbuf
)
2815 struct activehosts
*temp
, *prev
; /* temp var needed to scan the host list chain */
2816 struct addrinfo hints
, *addrinfo
, *ai_next
; /* temp var needed to translate between hostname to its address */
2822 /* retrieve the network address corresponding to 'host' */
2824 memset(&hints
, 0, sizeof(struct addrinfo
));
2825 hints
.ai_family
= PF_UNSPEC
;
2826 hints
.ai_socktype
= SOCK_STREAM
;
2828 retval
= getaddrinfo(host
, "0", &hints
, &addrinfo
);
2831 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "getaddrinfo() %s", gai_strerror(retval
));
2840 if (sock_cmpaddr(&temp
->host
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
2842 struct rpcap_header header
;
2845 /* Close this connection */
2846 rpcap_createhdr(&header
, temp
->protocol_version
,
2847 RPCAP_MSG_CLOSE
, 0, 0);
2850 * Don't check for errors, since we're
2853 if (sock_send(temp
->sockctrl
,
2855 sizeof(struct rpcap_header
), errbuf
,
2856 PCAP_ERRBUF_SIZE
) < 0)
2859 * Let that error be the one we
2862 (void)sock_close(temp
->sockctrl
, NULL
,
2868 if (sock_close(temp
->sockctrl
, errbuf
,
2869 PCAP_ERRBUF_SIZE
) == -1)
2874 * Remove the host from the list of active
2878 prev
->next
= temp
->next
;
2880 activeHosts
= temp
->next
;
2882 freeaddrinfo(addrinfo
);
2886 /* To avoid inconsistencies in the number of sock_init() */
2892 ai_next
= ai_next
->ai_next
;
2899 freeaddrinfo(addrinfo
);
2901 /* To avoid inconsistencies in the number of sock_init() */
2904 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The host you want to close the active connection is not known");
2908 void pcap_remoteact_cleanup(void)
2910 /* Very dirty, but it works */
2913 closesocket(sockmain
);
2915 /* To avoid inconsistencies in the number of sock_init() */
2921 int pcap_remoteact_list(char *hostlist
, char sep
, int size
, char *errbuf
)
2923 struct activehosts
*temp
; /* temp var needed to scan the host list chain */
2925 char hoststr
[RPCAP_HOSTLIST_SIZE
+ 1];
2934 /*int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen) */
2936 /* Get the numeric form of the name of the connecting host */
2937 if (sock_getascii_addrport((struct sockaddr_storage
*) &temp
->host
, hoststr
,
2938 RPCAP_HOSTLIST_SIZE
, NULL
, 0, NI_NUMERICHOST
, errbuf
, PCAP_ERRBUF_SIZE
) != -1)
2939 /* if (getnameinfo( (struct sockaddr *) &temp->host, sizeof (struct sockaddr_storage), hoststr, */
2940 /* RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST) ) */
2942 /* sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); */
2946 len
= len
+ strlen(hoststr
) + 1 /* the separator */;
2948 if ((size
< 0) || (len
>= (size_t)size
))
2950 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The string you provided is not able to keep "
2951 "the hostnames for all the active connections");
2955 strlcat(hostlist
, hoststr
, PCAP_ERRBUF_SIZE
);
2956 hostlist
[len
- 1] = sep
;
2966 * Receive the header of a message.
2968 static int rpcap_recv_msg_header(SOCKET sock
, struct rpcap_header
*header
, char *errbuf
)
2972 nrecv
= sock_recv(sock
, (char *) header
, sizeof(struct rpcap_header
),
2973 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
,
2977 /* Network error. */
2980 header
->plen
= ntohl(header
->plen
);
2985 * Make sure the protocol version of a received message is what we were
2988 static int rpcap_check_msg_ver(SOCKET sock
, uint8 expected_ver
, struct rpcap_header
*header
, char *errbuf
)
2991 * Did the server specify the version we negotiated?
2993 if (header
->ver
!= expected_ver
)
2996 * Discard the rest of the message.
2998 if (rpcap_discard(sock
, header
->plen
, errbuf
) == -1)
3002 * Tell our caller that it's not the negotiated version.
3006 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3007 "Server sent us a message with version %u when we were expecting %u",
3008 header
->ver
, expected_ver
);
3016 * Check the message type of a received message, which should either be
3017 * the expected message type or RPCAP_MSG_ERROR.
3019 static int rpcap_check_msg_type(SOCKET sock
, uint8 request_type
, struct rpcap_header
*header
, uint16
*errcode
, char *errbuf
)
3021 const char *request_type_string
;
3022 const char *msg_type_string
;
3025 * What type of message is it?
3027 if (header
->type
== RPCAP_MSG_ERROR
)
3030 * The server reported an error.
3031 * Hand that error back to our caller.
3033 *errcode
= ntohs(header
->value
);
3034 rpcap_msg_err(sock
, header
->plen
, errbuf
);
3041 * For a given request type value, the expected reply type value
3042 * is the request type value with ORed with RPCAP_MSG_IS_REPLY.
3044 if (header
->type
!= (request_type
| RPCAP_MSG_IS_REPLY
))
3047 * This isn't a reply to the request we sent.
3051 * Discard the rest of the message.
3053 if (rpcap_discard(sock
, header
->plen
, errbuf
) == -1)
3057 * Tell our caller about it.
3059 request_type_string
= rpcap_msg_type_string(request_type
);
3060 msg_type_string
= rpcap_msg_type_string(header
->type
);
3063 if (request_type_string
== NULL
)
3065 /* This should not happen. */
3066 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3067 "rpcap_check_msg_type called for request message with type %u",
3071 if (msg_type_string
!= NULL
)
3072 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3073 "%s message received in response to a %s message",
3074 msg_type_string
, request_type_string
);
3076 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3077 "Message of unknown type %u message received in response to a %s request",
3078 header
->type
, request_type_string
);
3087 * Receive and process the header of a message.
3089 static int rpcap_process_msg_header(SOCKET sock
, uint8 expected_ver
, uint8 request_type
, struct rpcap_header
*header
, char *errbuf
)
3093 if (rpcap_recv_msg_header(sock
, header
, errbuf
) == -1)
3095 /* Network error. */
3100 * Did the server specify the version we negotiated?
3102 if (rpcap_check_msg_ver(sock
, expected_ver
, header
, errbuf
) == -1)
3106 * Check the message type.
3108 return rpcap_check_msg_type(sock
, request_type
, header
,
3113 * Read data from a message.
3114 * If we're trying to read more data that remains, puts an error
3115 * message into errmsgbuf and returns -2. Otherwise, tries to read
3116 * the data and, if that succeeds, subtracts the amount read from
3117 * the number of bytes of data that remains.
3118 * Returns 0 on success, logs a message and returns -1 on a network
3121 static int rpcap_recv(SOCKET sock
, void *buffer
, size_t toread
, uint32
*plen
, char *errbuf
)
3127 /* The server sent us a bad message */
3128 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Message payload is too short");
3131 nread
= sock_recv(sock
, buffer
, toread
,
3132 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
, PCAP_ERRBUF_SIZE
);
3142 * This handles the RPCAP_MSG_ERROR message.
3144 static void rpcap_msg_err(SOCKET sockctrl
, uint32 plen
, char *remote_errbuf
)
3146 char errbuf
[PCAP_ERRBUF_SIZE
];
3148 if (plen
>= PCAP_ERRBUF_SIZE
)
3151 * Message is too long; just read as much of it as we
3152 * can into the buffer provided, and discard the rest.
3154 if (sock_recv(sockctrl
, remote_errbuf
, PCAP_ERRBUF_SIZE
- 1,
3155 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
,
3156 PCAP_ERRBUF_SIZE
) == -1)
3159 pcap_snprintf(remote_errbuf
, PCAP_ERRBUF_SIZE
, "Read of error message from client failed: %s", errbuf
);
3164 * Null-terminate it.
3166 remote_errbuf
[PCAP_ERRBUF_SIZE
- 1] = '\0';
3169 * Throw away the rest.
3171 (void)rpcap_discard(sockctrl
, plen
- (PCAP_ERRBUF_SIZE
- 1), remote_errbuf
);
3175 /* Empty error string. */
3176 remote_errbuf
[0] = '\0';
3180 if (sock_recv(sockctrl
, remote_errbuf
, plen
,
3181 SOCK_RECEIVEALL_YES
|SOCK_EOF_IS_ERROR
, errbuf
,
3182 PCAP_ERRBUF_SIZE
) == -1)
3185 pcap_snprintf(remote_errbuf
, PCAP_ERRBUF_SIZE
, "Read of error message from client failed: %s", errbuf
);
3190 * Null-terminate it.
3192 remote_errbuf
[plen
] = '\0';
3197 * Discard data from a connection.
3198 * Mostly used to discard wrong-sized messages.
3199 * Returns 0 on success, logs a message and returns -1 on a network
3202 static int rpcap_discard(SOCKET sock
, uint32 len
, char *errbuf
)
3206 if (sock_discard(sock
, len
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
3216 * Read bytes into the pcap_t's buffer until we have the specified
3217 * number of bytes read or we get an error or interrupt indication.
3219 static int rpcap_read_packet_msg(SOCKET sock
, pcap_t
*p
, size_t size
)
3229 * Loop until we have the amount of data requested or we get
3230 * an error or interrupt.
3232 while ((size_t)cc
< size
)
3235 * We haven't read all of the packet header yet.
3236 * Read what remains, which could be all of it.
3238 bytes_read
= sock_recv(sock
, bp
, size
- cc
,
3239 SOCK_RECEIVEALL_NO
|SOCK_EOF_IS_ERROR
, p
->errbuf
,
3241 if (bytes_read
== -1)
3244 * Network error. Update the read pointer and
3245 * byte count, and return an error indication.
3251 if (bytes_read
== -3)
3254 * Interrupted receive. Update the read
3255 * pointer and byte count, and return
3256 * an interrupted indication.
3262 if (bytes_read
== 0)
3265 * EOF - server terminated the connection.
3266 * Update the read pointer and byte count, and
3267 * return an error indication.
3269 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
3270 "The server terminated the connection.");