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 */
43 #include "sockutils.h"
44 #include "rpcap-protocol.h"
45 #include "pcap-rpcap-int.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 struct activehosts
*next
;
87 /* Keeps a list of all the opened connections in the active mode. */
88 static struct activehosts
*activeHosts
;
91 * Keeps the main socket identifier when we want to accept a new remote
92 * connection (active mode only).
93 * See the documentation of pcap_remoteact_accept() and
94 * pcap_remoteact_cleanup() for more details.
96 static SOCKET sockmain
;
99 * Private data for capturing remotely using the rpcap protocol.
103 * This is '1' if we're the network client; it is needed by several
104 * functions (such as pcap_setfilter()) to know whether they have
105 * to use the socket or have to open the local adapter.
109 SOCKET rmt_sockctrl
; /* socket ID of the socket used for the control connection */
110 SOCKET rmt_sockdata
; /* socket ID of the socket used for the data connection */
111 int rmt_flags
; /* we have to save flags, since they are passed by the pcap_open_live(), but they are used by the pcap_startcapture() */
112 int rmt_capstarted
; /* 'true' if the capture is already started (needed to knoe if we have to call the pcap_startcapture() */
113 char *currentfilter
; /* Pointer to a buffer (allocated at run-time) that stores the current filter. Needed when flag PCAP_OPENFLAG_NOCAPTURE_RPCAP is turned on. */
115 unsigned int TotNetDrops
; /* keeps the number of packets that have been dropped by the network */
118 * This keeps the number of packets that have been received by the
121 * Packets dropped by the kernel buffer are not counted in this
122 * variable. It is always equal to (TotAccepted - TotDrops),
123 * except for the case of remote capture, in which we have also
124 * packets in flight, i.e. that have been transmitted by the remote
125 * host, but that have not been received (yet) from the client.
126 * In this case, (TotAccepted - TotDrops - TotNetDrops) gives a
127 * wrong result, since this number does not corresponds always to
128 * the number of packet received by the application. For this reason,
129 * in the remote capture we need another variable that takes into
130 * account of the number of packets actually received by the
133 unsigned int TotCapt
;
135 struct pcap_stat stat
;
137 struct pcap
*next
; /* list of open pcaps that need stuff cleared on close */
140 /****************************************************
142 * Locally defined functions *
144 ****************************************************/
145 static int rpcap_checkver(SOCKET sock
, struct rpcap_header
*header
, char *errbuf
);
146 static struct pcap_stat
*rpcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
, int mode
);
147 static int pcap_pack_bpffilter(pcap_t
*fp
, char *sendbuf
, int *sendbufidx
, struct bpf_program
*prog
);
148 static int pcap_createfilter_norpcappkt(pcap_t
*fp
, struct bpf_program
*prog
);
149 static int pcap_updatefilter_remote(pcap_t
*fp
, struct bpf_program
*prog
);
150 static void pcap_save_current_filter_rpcap(pcap_t
*fp
, const char *filter
);
151 static int pcap_setfilter_rpcap(pcap_t
*fp
, struct bpf_program
*prog
);
152 static int pcap_setsampling_remote(pcap_t
*fp
);
153 static int pcap_startcapture_remote(pcap_t
*fp
);
154 static int rpcap_sendauth(SOCKET sock
, struct pcap_rmtauth
*auth
, char *errbuf
);
156 /****************************************************
160 ****************************************************/
163 * This function translates (i.e. de-serializes) a 'rpcap_sockaddr'
164 * structure from the network byte order to a 'sockaddr_in" or
165 * 'sockaddr_in6' structure in the host byte order.
167 * It accepts an 'rpcap_sockaddr' structure as it is received from the
168 * network, and checks the address family field against various values
169 * to see whether it looks like an IPv4 address, an IPv6 address, or
170 * neither of those. It checks for multiple values in order to try
171 * to handle older rpcap daemons that sent the native OS's 'sockaddr_in'
172 * or 'sockaddr_in6' structures over the wire with some members
173 * byte-swapped, and to handle the fact that AF_INET6 has different
174 * values on different OSes.
176 * For IPv4 addresses, it converts the address family to host byte
177 * order from network byte order and puts it into the structure,
178 * sets the length if a sockaddr structure has a length, converts the
179 * port number to host byte order from network byte order and puts
180 * it into the structure, copies over the IPv4 address, and zeroes
181 * out the zero padding.
183 * For IPv6 addresses, it converts the address family to host byte
184 * order from network byte order and puts it into the structure,
185 * sets the length if a sockaddr structure has a length, converts the
186 * port number and flow information to host byte order from network
187 * byte order and puts them into the structure, copies over the IPv6
188 * address, and converts the scope ID to host byte order from network
189 * byte order and puts it into the structure.
191 * The function will allocate the 'sockaddrout' variable according to the
192 * address family in use. In case the address does not belong to the
193 * AF_INET nor AF_INET6 families, 'sockaddrout' is not allocated and a
194 * NULL pointer is returned. This usually happens because that address
195 * does not exist on the other host, or is of an address family other
196 * than AF_INET or AF_INET6, so the RPCAP daemon sent a 'sockaddr_storage'
197 * structure containing all 'zero' values.
199 * Older RPCAPDs sent the addresses over the wire in the OS's native
200 * structure format. For most OSes, this looks like the over-the-wire
201 * format, but might have a different value for AF_INET6 than the value
202 * on the machine receiving the reply. For OSes with the newer BSD-style
203 * sockaddr structures, this has, instead of a 2-byte address family,
204 * a 1-byte structure length followed by a 1-byte address family. The
205 * RPCAPD code would put the address family in network byte order before
206 * sending it; that would set it to 0 on a little-endian machine, as
207 * htons() of any value between 1 and 255 would result in a value > 255,
208 * with its lower 8 bits zero, so putting that back into a 1-byte field
211 * Therefore, for older RPCAPDs running on an OS with newer BSD-style
212 * sockaddr structures, the family field, if treated as a big-endian
213 * (network byte order) 16-bit field, would be:
215 * (length << 8) | family if sent by a big-endian machine
216 * (length << 8) if sent by a little-endian machine
218 * For current RPCAPDs, and for older RPCAPDs running on an OS with
219 * older BSD-style sockaddr structures, the family field, if treated
220 * as a big-endian 16-bit field, would just contain the family.
222 * \param sockaddrin: a 'rpcap_sockaddr' pointer to the variable that has
223 * to be de-serialized.
225 * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
226 * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
227 * This variable will be allocated automatically inside this function.
229 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
230 * that will contain the error message (in case there is one).
232 * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
233 * can be only the fact that the malloc() failed to allocate memory.
234 * The error message is returned in the 'errbuf' variable, while the deserialized address
235 * is returned into the 'sockaddrout' variable.
237 * \warning This function supports only AF_INET and AF_INET6 address families.
239 * \warning The sockaddrout (if not NULL) must be deallocated by the user.
243 * Possible IPv4 family values other than the designated over-the-wire value,
244 * which is 2 (because everybody uses 2 for AF_INET4).
246 #define SOCKADDR_IN_LEN 16 /* length of struct sockaddr_in */
247 #define SOCKADDR_IN6_LEN 28 /* length of struct sockaddr_in6 */
248 #define NEW_BSD_AF_INET_BE ((SOCKADDR_IN_LEN << 8) | 2)
249 #define NEW_BSD_AF_INET_LE (SOCKADDR_IN_LEN << 8)
252 * Possible IPv6 family values other than the designated over-the-wire value,
253 * which is 23 (because that's what Windows uses, and most RPCAP servers
254 * out there are probably running Windows, as WinPcap includes the server
255 * but few if any UN*Xes build and ship it).
257 * The new BSD sockaddr structure format was in place before 4.4-Lite, so
258 * all the free-software BSDs use it.
260 #define NEW_BSD_AF_INET6_BSD_BE ((SOCKADDR_IN6_LEN << 8) | 24) /* NetBSD, OpenBSD, BSD/OS */
261 #define NEW_BSD_AF_INET6_FREEBSD_BE ((SOCKADDR_IN6_LEN << 8) | 28) /* FreeBSD, DragonFly BSD */
262 #define NEW_BSD_AF_INET6_DARWIN_BE ((SOCKADDR_IN6_LEN << 8) | 30) /* macOS, iOS, anything else Darwin-based */
263 #define NEW_BSD_AF_INET6_LE (SOCKADDR_IN6_LEN << 8)
264 #define LINUX_AF_INET6 10
265 #define HPUX_AF_INET6 22
266 #define AIX_AF_INET6 24
267 #define SOLARIS_AF_INET6 26
270 rpcap_deseraddr(struct rpcap_sockaddr
*sockaddrin
, struct sockaddr_storage
**sockaddrout
, char *errbuf
)
272 /* Warning: we support only AF_INET and AF_INET6 */
273 switch (ntohs(sockaddrin
->family
))
276 case NEW_BSD_AF_INET_BE
:
277 case NEW_BSD_AF_INET_LE
:
279 struct rpcap_sockaddr_in
*sockaddrin_ipv4
;
280 struct sockaddr_in
*sockaddrout_ipv4
;
282 (*sockaddrout
) = (struct sockaddr_storage
*) malloc(sizeof(struct sockaddr_in
));
283 if ((*sockaddrout
) == NULL
)
285 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "malloc() failed: %s", pcap_strerror(errno
));
288 sockaddrin_ipv4
= (struct rpcap_sockaddr_in
*) sockaddrin
;
289 sockaddrout_ipv4
= (struct sockaddr_in
*) (*sockaddrout
);
290 sockaddrout_ipv4
->sin_family
= AF_INET
;
291 sockaddrout_ipv4
->sin_port
= ntohs(sockaddrin_ipv4
->port
);
292 memcpy(&sockaddrout_ipv4
->sin_addr
, &sockaddrin_ipv4
->addr
, sizeof(sockaddrout_ipv4
->sin_addr
));
293 memset(sockaddrout_ipv4
->sin_zero
, 0, sizeof(sockaddrout_ipv4
->sin_zero
));
299 case NEW_BSD_AF_INET6_BSD_BE
:
300 case NEW_BSD_AF_INET6_FREEBSD_BE
:
301 case NEW_BSD_AF_INET6_DARWIN_BE
:
302 case NEW_BSD_AF_INET6_LE
:
306 case SOLARIS_AF_INET6
:
308 struct rpcap_sockaddr_in6
*sockaddrin_ipv6
;
309 struct sockaddr_in6
*sockaddrout_ipv6
;
311 (*sockaddrout
) = (struct sockaddr_storage
*) malloc(sizeof(struct sockaddr_in6
));
312 if ((*sockaddrout
) == NULL
)
314 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "malloc() failed: %s", pcap_strerror(errno
));
317 sockaddrin_ipv6
= (struct rpcap_sockaddr_in6
*) sockaddrin
;
318 sockaddrout_ipv6
= (struct sockaddr_in6
*) (*sockaddrout
);
319 sockaddrout_ipv6
->sin6_family
= AF_INET6
;
320 sockaddrout_ipv6
->sin6_port
= ntohs(sockaddrin_ipv6
->port
);
321 sockaddrout_ipv6
->sin6_flowinfo
= ntohl(sockaddrin_ipv6
->flowinfo
);
322 memcpy(&sockaddrout_ipv6
->sin6_addr
, &sockaddrin_ipv6
->addr
, sizeof(sockaddrout_ipv6
->sin6_addr
));
323 sockaddrout_ipv6
->sin6_scope_id
= ntohl(sockaddrin_ipv6
->scope_id
);
330 * It is neither AF_INET nor AF_INET6 (or, if the OS doesn't
331 * support AF_INET6, it's not AF_INET).
340 * This function reads a packet from the network socket. It does not
341 * deliver the packet to a pcap_dispatch()/pcap_loop() callback (hence
342 * the "nocb" string into its name).
344 * This function is called by pcap_read_rpcap().
346 * WARNING: By choice, this function does not make use of semaphores. A smarter
347 * implementation should put a semaphore into the data thread, and a signal will
348 * be raised as soon as there is data into the socket buffer.
349 * However this is complicated and it does not bring any advantages when reading
350 * from the network, in which network delays can be much more important than
351 * these optimizations. Therefore, we chose the following approach:
352 * - the 'timeout' chosen by the user is split in two (half on the server side,
353 * with the usual meaning, and half on the client side)
354 * - this function checks for packets; if there are no packets, it waits for
355 * timeout/2 and then it checks again. If packets are still missing, it returns,
356 * otherwise it reads packets.
358 static int pcap_read_nocb_remote(pcap_t
*p
, struct pcap_pkthdr
**pkt_header
, u_char
**pkt_data
)
360 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
361 struct rpcap_header
*header
; /* general header according to the RPCAP format */
362 struct rpcap_pkthdr
*net_pkt_header
; /* header of the packet */
363 char netbuf
[RPCAP_NETBUF_SIZE
]; /* size of the network buffer in which the packet is copied, just for UDP */
364 uint32 totread
; /* number of bytes (of payload) currently read from the network (referred to the current pkt) */
366 int retval
; /* generic return value */
368 /* Structures needed for the select() call */
369 struct timeval tv
; /* maximum time the select() can block waiting for data */
370 fd_set rfds
; /* set of socket descriptors we have to check */
373 * Define the packet buffer timeout, to be used in the select()
374 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
376 tv
.tv_sec
= p
->opt
.timeout
/ 1000;
377 tv
.tv_usec
= (p
->opt
.timeout
- tv
.tv_sec
* 1000) * 1000;
379 /* Watch out sockdata to see if it has input */
383 * 'fp->rmt_sockdata' has always to be set before calling the select(),
384 * since it is cleared by the select()
386 FD_SET(pr
->rmt_sockdata
, &rfds
);
388 retval
= select((int) pr
->rmt_sockdata
+ 1, &rfds
, NULL
, NULL
, &tv
);
391 sock_geterror("select(): ", p
->errbuf
, PCAP_ERRBUF_SIZE
);
395 /* There is no data waiting, so return '0' */
400 * data is here; so, let's copy it into the user buffer.
401 * I'm going to read a new packet; so I reset the number of bytes (payload only) read
406 * We have to define 'header' as a pointer to a larger buffer,
407 * because in case of UDP we have to read all the message within a single call
409 header
= (struct rpcap_header
*) netbuf
;
410 net_pkt_header
= (struct rpcap_pkthdr
*) (netbuf
+ sizeof(struct rpcap_header
));
412 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
414 /* Read the entire message from the network */
415 if (sock_recv(pr
->rmt_sockdata
, netbuf
, RPCAP_NETBUF_SIZE
, SOCK_RECEIVEALL_NO
, p
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
420 if (sock_recv(pr
->rmt_sockdata
, netbuf
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, p
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
424 /* Checks if the message is correct */
425 retval
= rpcap_checkmsg(p
->errbuf
, pr
->rmt_sockdata
, header
, RPCAP_MSG_PACKET
, 0);
427 if (retval
!= RPCAP_MSG_PACKET
) /* the message is not the one expected */
431 case -3: /* Unrecoverable network error */
432 return -1; /* Do nothing; just exit from here; the error code is already into the errbuf */
434 case -2: /* The other endpoint sent a message that is not allowed here */
435 case -1: /* The other endpoint has a version number that is not compatible with our */
436 return 0; /* Return 'no packets received' */
439 SOCK_ASSERT("Internal error", 1);
440 return 0; /* Return 'no packets received' */
444 /* In case of TCP, read the remaining of the packet from the socket */
445 if (!(pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
447 /* Read the RPCAP packet header from the network */
448 nread
= sock_recv(pr
->rmt_sockdata
, (char *)net_pkt_header
,
449 sizeof(struct rpcap_pkthdr
), SOCK_RECEIVEALL_YES
,
450 p
->errbuf
, PCAP_ERRBUF_SIZE
);
456 if ((ntohl(net_pkt_header
->caplen
) + sizeof(struct pcap_pkthdr
)) <= p
->bufsize
)
458 /* Initialize returned structures */
459 *pkt_header
= (struct pcap_pkthdr
*) p
->buffer
;
460 *pkt_data
= (u_char
*)p
->buffer
+ sizeof(struct pcap_pkthdr
);
462 (*pkt_header
)->caplen
= ntohl(net_pkt_header
->caplen
);
463 (*pkt_header
)->len
= ntohl(net_pkt_header
->len
);
464 (*pkt_header
)->ts
.tv_sec
= ntohl(net_pkt_header
->timestamp_sec
);
465 (*pkt_header
)->ts
.tv_usec
= ntohl(net_pkt_header
->timestamp_usec
);
468 * I don't update the counter of the packets dropped by the network since we're using TCP,
469 * therefore no packets are dropped. Just update the number of packets received correctly
473 /* Copies the packet into the data buffer */
474 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
479 * In case of UDP the packet has already been read, we have to copy it into 'buffer'.
480 * Another option should be to declare 'netbuf' as 'static'. However this prevents
481 * using several pcap instances within the same process (because the static buffer is shared among
484 memcpy(*pkt_data
, netbuf
+ sizeof(struct rpcap_header
) + sizeof(struct rpcap_pkthdr
), (*pkt_header
)->caplen
);
486 /* We're using UDP, so we need to update the counter of the packets dropped by the network */
487 npkt
= ntohl(net_pkt_header
->npkt
);
489 if (pr
->TotCapt
!= npkt
)
491 pr
->TotNetDrops
+= (npkt
- pr
->TotCapt
);
497 /* In case of TCP, read the remaining of the packet from the socket */
498 nread
= sock_recv(pr
->rmt_sockdata
, *pkt_data
,
499 (*pkt_header
)->caplen
, SOCK_RECEIVEALL_YES
,
500 p
->errbuf
, PCAP_ERRBUF_SIZE
);
505 /* Checks if all the data has been read; if not, discard the data in excess */
506 /* This check has to be done only on TCP connections */
507 if (totread
!= ntohl(header
->plen
))
508 sock_discard(pr
->rmt_sockdata
, ntohl(header
->plen
) - totread
, NULL
, 0);
511 /* Packet read successfully */
516 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "Received a packet that is larger than the internal buffer size.");
522 * This function reads a packet from the network socket.
524 * This function relies on the pcap_read_nocb_remote to deliver packets. The
525 * difference, here, is that as soon as a packet is read, it is delivered
526 * to the application by means of a callback function.
528 static int pcap_read_rpcap(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
530 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
531 struct pcap_pkthdr
*pkt_header
;
536 * If this is client-side, and we haven't already started
537 * the capture, start it now.
539 if (pr
->rmt_clientside
)
541 /* We are on an remote capture */
542 if (!pr
->rmt_capstarted
)
545 * The capture isn't started yet, so try to
548 if (pcap_startcapture_remote(p
))
553 while (n
< cnt
|| PACKET_COUNT_IS_UNLIMITED(cnt
))
556 * Has "pcap_breakloop()" been called?
560 * Yes - clear the flag that indicates that it
561 * has, and return PCAP_ERROR_BREAK to indicate
562 * that we were told to break out of the loop.
565 return (PCAP_ERROR_BREAK
);
571 if (pcap_read_nocb_remote(p
, &pkt_header
, &pkt_data
) == 1)
573 (*callback
)(user
, pkt_header
, pkt_data
);
583 * This function sends a CLOSE command to the capture server.
585 * It is called when the user calls pcap_close(). It sends a command
586 * to our peer that says 'ok, let's stop capturing'.
588 * WARNING: Since we're closing the connection, we do not check for errors.
590 static void pcap_cleanup_rpcap(pcap_t
*fp
)
592 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
593 struct rpcap_header header
; /* header of the RPCAP packet */
594 struct activehosts
*temp
; /* temp var needed to scan the host list chain, to detect if we're in active mode */
595 int active
= 0; /* active mode or not? */
597 /* detect if we're in active mode */
601 if (temp
->sockctrl
== pr
->rmt_sockctrl
)
611 rpcap_createhdr(&header
, RPCAP_MSG_CLOSE
, 0, 0);
613 /* I don't check for errors, since I'm going to close everything */
614 sock_send(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), NULL
, 0);
618 rpcap_createhdr(&header
, RPCAP_MSG_ENDCAP_REQ
, 0, 0);
620 /* I don't check for errors, since I'm going to close everything */
621 sock_send(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), NULL
, 0);
623 /* wait for the answer */
624 /* Don't check what we got, since the present libpcap does not uses this pcap_t anymore */
625 sock_recv(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, NULL
, 0);
627 if (ntohl(header
.plen
) != 0)
628 sock_discard(pr
->rmt_sockctrl
, ntohl(header
.plen
), NULL
, 0);
631 if (pr
->rmt_sockdata
)
633 sock_close(pr
->rmt_sockdata
, NULL
, 0);
634 pr
->rmt_sockdata
= 0;
637 if ((!active
) && (pr
->rmt_sockctrl
))
638 sock_close(pr
->rmt_sockctrl
, NULL
, 0);
640 pr
->rmt_sockctrl
= 0;
642 if (pr
->currentfilter
)
644 free(pr
->currentfilter
);
645 pr
->currentfilter
= NULL
;
648 /* To avoid inconsistencies in the number of sock_init() */
653 * This function retrieves network statistics from our peer;
654 * it provides only the standard statistics.
656 static int pcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
)
658 struct pcap_stat
*retval
;
660 retval
= rpcap_stats_rpcap(p
, ps
, PCAP_STATS_STANDARD
);
670 * This function retrieves network statistics from our peer;
671 * it provides the additional statistics supported by pcap_stats_ex().
673 static struct pcap_stat
*pcap_stats_ex_rpcap(pcap_t
*p
, int *pcap_stat_size
)
675 *pcap_stat_size
= sizeof (p
->stat
);
677 /* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
678 return (rpcap_stats_rpcap(p
, &(p
->stat
), PCAP_STATS_EX
));
683 * This function retrieves network statistics from our peer. It
684 * is used by the two previous functions.
686 * It can be called in two modes:
687 * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e.,
689 * - PCAP_STATS_EX: if we want extended statistics (i.e., for
692 * This 'mode' parameter is needed because in pcap_stats() the variable that
693 * keeps the statistics is allocated by the user. On Windows, this structure
694 * has been extended in order to keep new stats. However, if the user has a
695 * smaller structure and it passes it to pcap_stats(), this function will
696 * try to fill in more data than the size of the structure, so that memory
697 * after the structure will be overwritten.
699 * So, we need to know it we have to copy just the standard fields, or the
700 * extended fields as well.
702 * In case we want to copy the extended fields as well, the problem of
703 * memory overflow no longer exists because the structure that's filled
704 * in is part of the pcap_t, so that it can be guaranteed to be large
705 * enough for the additional statistics.
707 * \param p: the pcap_t structure related to the current instance.
709 * \param ps: a pointer to a 'pcap_stat' structure, needed for compatibility
710 * with pcap_stat(), where the structure is allocated by the user. In case
711 * of pcap_stats_ex(), this structure and the function return value point
712 * to the same variable.
714 * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
716 * \return The structure that keeps the statistics, or NULL in case of error.
717 * The error string is placed in the pcap_t structure.
719 static struct pcap_stat
*rpcap_stats_rpcap(pcap_t
*p
, struct pcap_stat
*ps
, int mode
)
721 struct pcap_rpcap
*pr
= p
->priv
; /* structure used when doing a remote live capture */
722 struct rpcap_header header
; /* header of the RPCAP packet */
723 struct rpcap_stats netstats
; /* statistics sent on the network */
724 uint32 totread
= 0; /* number of bytes of the payload read from the socket */
726 int retval
; /* temp variable which stores functions return value */
729 * If the capture has not yet started, we cannot request statistics
730 * for the capture from our peer, so we return 0 for all statistics,
731 * as nothing's been seen yet.
733 if (!pr
->rmt_capstarted
)
738 #if defined(_WIN32) && defined(HAVE_REMOTE)
739 if (mode
== PCAP_STATS_EX
)
745 #endif /* _WIN32 && HAVE_REMOTE */
750 rpcap_createhdr(&header
, RPCAP_MSG_STATS_REQ
, 0, 0);
752 /* Send the PCAP_STATS command */
753 if (sock_send(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), p
->errbuf
, PCAP_ERRBUF_SIZE
))
756 /* Receive the RPCAP stats reply message */
757 if (sock_recv(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, p
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
760 /* Checks if the message is correct */
761 retval
= rpcap_checkmsg(p
->errbuf
, pr
->rmt_sockctrl
, &header
, RPCAP_MSG_STATS_REPLY
, RPCAP_MSG_ERROR
, 0);
763 if (retval
!= RPCAP_MSG_STATS_REPLY
) /* the message is not the one expected */
767 case -3: /* Unrecoverable network error */
768 case -2: /* The other endpoint send a message that is not allowed here */
769 case -1: /* The other endpoint has a version number that is not compatible with our */
772 case RPCAP_MSG_ERROR
: /* The other endpoint reported an error */
773 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
774 totread
= ntohl(header
.plen
);
776 /* Do nothing; just exit; the error code is already into the errbuf */
780 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "Internal error");
785 nread
= sock_recv(pr
->rmt_sockctrl
, (char *)&netstats
,
786 sizeof(struct rpcap_stats
), SOCK_RECEIVEALL_YES
,
787 p
->errbuf
, PCAP_ERRBUF_SIZE
);
792 ps
->ps_drop
= ntohl(netstats
.krnldrop
);
793 ps
->ps_ifdrop
= ntohl(netstats
.ifdrop
);
794 ps
->ps_recv
= ntohl(netstats
.ifrecv
);
795 #if defined(_WIN32) && defined(HAVE_REMOTE)
796 if (mode
== PCAP_STATS_EX
)
798 ps
->ps_capt
= pr
->TotCapt
;
799 ps
->ps_netdrop
= pr
->TotNetDrops
;
800 ps
->ps_sent
= ntohl(netstats
.svrcapt
);
802 #endif /* _WIN32 && HAVE_REMOTE */
804 /* Checks if all the data has been read; if not, discard the data in excess */
805 if (totread
!= ntohl(header
.plen
))
807 if (sock_discard(pr
->rmt_sockctrl
, ntohl(header
.plen
) - totread
, NULL
, 0) == 1)
814 if (totread
!= ntohl(header
.plen
))
815 sock_discard(pr
->rmt_sockctrl
, ntohl(header
.plen
) - totread
, NULL
, 0);
821 * This function returns the socket currently used for this active connection
822 * (active mode only) and provides an indication of whether this connection
823 * is in active mode or not.
825 * It is just for internal use; it returns the socket ID of the active
826 * connection currently opened.
828 * \param host: a string that keeps the host name of the host for which we
829 * want to get the socket ID for that active connection.
831 * \param isactive: a pointer to an int that is set to 1 if there's an
832 * active connection to that host and 0 otherwise.
834 * \param errbuf: a pointer to a user-allocated buffer (of size
835 * PCAP_ERRBUF_SIZE) that will contain the error message (in case
838 * \return the socket identifier if everything is fine, '0' if this host
839 * is not in the active host list. An indication of whether this host
840 * is in the active host list is returned into the isactive variable.
841 * It returns 'INVALID_SOCKET' in case of error. The error message is
842 * returned into the errbuf variable.
845 rpcap_remoteact_getsock(const char *host
, int *isactive
, char *errbuf
)
847 struct activehosts
*temp
; /* temp var needed to scan the host list chain */
848 struct addrinfo hints
, *addrinfo
, *ai_next
; /* temp var needed to translate between hostname to its address */
851 /* retrieve the network address corresponding to 'host' */
853 memset(&hints
, 0, sizeof(struct addrinfo
));
854 hints
.ai_family
= PF_UNSPEC
;
855 hints
.ai_socktype
= SOCK_STREAM
;
857 retval
= getaddrinfo(host
, "0", &hints
, &addrinfo
);
860 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "getaddrinfo() %s", gai_strerror(retval
));
862 return INVALID_SOCKET
;
872 if (sock_cmpaddr(&temp
->host
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
875 return (temp
->sockctrl
);
878 ai_next
= ai_next
->ai_next
;
884 freeaddrinfo(addrinfo
);
887 * The host for which you want to get the socket ID does not have an
895 * This function starts a remote capture.
897 * This function is required since the RPCAP protocol decouples the 'open'
898 * from the 'start capture' functions.
899 * This function takes all the parameters needed (which have been stored
900 * into the pcap_t structure) and sends them to the server.
902 * \param fp: the pcap_t descriptor of the device currently open.
904 * \return '0' if everything is fine, '-1' otherwise. The error message
905 * (if one) is returned into the 'errbuf' field of the pcap_t structure.
907 static int pcap_startcapture_remote(pcap_t
*fp
)
909 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
910 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
911 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
912 char portdata
[PCAP_BUF_SIZE
]; /* temp variable needed to keep the network port for the data connection */
913 uint32 totread
= 0; /* number of bytes of the payload read from the socket */
915 int retval
; /* store the return value of the functions */
916 int active
= 0; /* '1' if we're in active mode */
917 struct activehosts
*temp
; /* temp var needed to scan the host list chain, to detect if we're in active mode */
918 char host
[INET6_ADDRSTRLEN
+ 1]; /* numeric name of the other host */
920 /* socket-related variables*/
921 struct addrinfo hints
; /* temp, needed to open a socket connection */
922 struct addrinfo
*addrinfo
; /* temp, needed to open a socket connection */
923 SOCKET sockdata
= 0; /* socket descriptor of the data connection */
924 struct sockaddr_storage saddr
; /* temp, needed to retrieve the network data port chosen on the local machine */
925 socklen_t saddrlen
; /* temp, needed to retrieve the network data port chosen on the local machine */
926 int ai_family
; /* temp, keeps the address family used by the control connection */
928 /* RPCAP-related variables*/
929 struct rpcap_header header
; /* header of the RPCAP packet */
930 struct rpcap_startcapreq
*startcapreq
; /* start capture request message */
931 struct rpcap_startcapreply startcapreply
; /* start capture reply message */
933 /* Variables related to the buffer setting */
939 * Let's check if sampling has been required.
940 * If so, let's set it first
942 if (pcap_setsampling_remote(fp
) != 0)
945 /* detect if we're in active mode */
949 if (temp
->sockctrl
== pr
->rmt_sockctrl
)
960 * Gets the complete sockaddr structure used in the ctrl connection
961 * This is needed to get the address family of the control socket
962 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
963 * since the ctrl socket can already be open in case of active mode;
964 * so I would have to call getpeername() anyway
966 saddrlen
= sizeof(struct sockaddr_storage
);
967 if (getpeername(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
969 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
972 ai_family
= ((struct sockaddr_storage
*) &saddr
)->ss_family
;
974 /* Get the numeric address of the remote host we are connected to */
975 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, host
,
976 sizeof(host
), NULL
, 0, NI_NUMERICHOST
))
978 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
983 * Data connection is opened by the server toward the client if:
984 * - we're using TCP, and the user wants us to be in active mode
987 if ((active
) || (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
990 * We have to create a new socket to receive packets
991 * We have to do that immediately, since we have to tell the other
992 * end which network port we picked up
994 memset(&hints
, 0, sizeof(struct addrinfo
));
995 /* TEMP addrinfo is NULL in case of active */
996 hints
.ai_family
= ai_family
; /* Use the same address family of the control socket */
997 hints
.ai_socktype
= (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
) ? SOCK_DGRAM
: SOCK_STREAM
;
998 hints
.ai_flags
= AI_PASSIVE
; /* Data connection is opened by the server toward the client */
1000 /* Let's the server pick up a free network port for us */
1001 if (sock_initaddress(NULL
, "0", &hints
, &addrinfo
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1004 if ((sockdata
= sock_open(addrinfo
, SOCKOPEN_SERVER
,
1005 1 /* max 1 connection in queue */, fp
->errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1008 /* addrinfo is no longer used */
1009 freeaddrinfo(addrinfo
);
1012 /* get the complete sockaddr structure used in the data connection */
1013 saddrlen
= sizeof(struct sockaddr_storage
);
1014 if (getsockname(sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1016 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1020 /* Get the local port the system picked up */
1021 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, NULL
,
1022 0, portdata
, sizeof(portdata
), NI_NUMERICSERV
))
1024 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1030 * Now it's time to start playing with the RPCAP protocol
1031 * RPCAP start capture command: create the request message
1033 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1034 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1037 rpcap_createhdr((struct rpcap_header
*) sendbuf
, RPCAP_MSG_STARTCAP_REQ
, 0,
1038 sizeof(struct rpcap_startcapreq
) + sizeof(struct rpcap_filter
) + fp
->fcode
.bf_len
* sizeof(struct rpcap_filterbpf_insn
));
1040 /* Fill the structure needed to open an adapter remotely */
1041 startcapreq
= (struct rpcap_startcapreq
*) &sendbuf
[sendbufidx
];
1043 if (sock_bufferize(NULL
, sizeof(struct rpcap_startcapreq
), NULL
,
1044 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1047 memset(startcapreq
, 0, sizeof(struct rpcap_startcapreq
));
1049 /* By default, apply half the timeout on one side, half of the other */
1050 fp
->opt
.timeout
= fp
->opt
.timeout
/ 2;
1051 startcapreq
->read_timeout
= htonl(fp
->opt
.timeout
);
1053 /* portdata on the openreq is meaningful only if we're in active mode */
1054 if ((active
) || (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1056 sscanf(portdata
, "%d", (int *)&(startcapreq
->portdata
)); /* cast to avoid a compiler warning */
1057 startcapreq
->portdata
= htons(startcapreq
->portdata
);
1060 startcapreq
->snaplen
= htonl(fp
->snapshot
);
1061 startcapreq
->flags
= 0;
1063 if (pr
->rmt_flags
& PCAP_OPENFLAG_PROMISCUOUS
)
1064 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_PROMISC
;
1065 if (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
)
1066 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_DGRAM
;
1068 startcapreq
->flags
|= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN
;
1070 startcapreq
->flags
= htons(startcapreq
->flags
);
1072 /* Pack the capture filter */
1073 if (pcap_pack_bpffilter(fp
, &sendbuf
[sendbufidx
], &sendbufidx
, &fp
->fcode
))
1076 if (sock_send(pr
->rmt_sockctrl
, sendbuf
, sendbufidx
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1079 /* Receive the RPCAP start capture reply message */
1080 if (sock_recv(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1083 /* Checks if the message is correct */
1084 retval
= rpcap_checkmsg(fp
->errbuf
, pr
->rmt_sockctrl
, &header
, RPCAP_MSG_STARTCAP_REPLY
, RPCAP_MSG_ERROR
, 0);
1086 if (retval
!= RPCAP_MSG_STARTCAP_REPLY
) /* the message is not the one expected */
1090 case -3: /* Unrecoverable network error */
1091 case -2: /* The other endpoint send a message that is not allowed here */
1092 case -1: /* The other endpoint has a version number that is not compatible with our */
1095 case RPCAP_MSG_ERROR
: /* The other endpoint reported an error */
1096 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
1097 totread
= ntohl(header
.plen
);
1098 /* Do nothing; just exit; the error code is already into the errbuf */
1102 pcap_snprintf(fp
->errbuf
, PCAP_ERRBUF_SIZE
, "Internal error");
1107 nread
= sock_recv(pr
->rmt_sockctrl
, (char *)&startcapreply
,
1108 sizeof(struct rpcap_startcapreply
), SOCK_RECEIVEALL_YES
,
1109 fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1115 * In case of UDP data stream, the connection is always opened by the daemon
1116 * So, this case is already covered by the code above.
1117 * Now, we have still to handle TCP connections, because:
1118 * - if we're in active mode, we have to wait for a remote connection
1119 * - if we're in passive more, we have to start a connection
1121 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1122 * to tell the port we're using to the remote side; in case we're accepting a TCP
1123 * connection, we have to wait this info from the remote side.
1125 if (!(pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
))
1129 memset(&hints
, 0, sizeof(struct addrinfo
));
1130 hints
.ai_family
= ai_family
; /* Use the same address family of the control socket */
1131 hints
.ai_socktype
= (pr
->rmt_flags
& PCAP_OPENFLAG_DATATX_UDP
) ? SOCK_DGRAM
: SOCK_STREAM
;
1132 pcap_snprintf(portdata
, PCAP_BUF_SIZE
, "%d", ntohs(startcapreply
.portdata
));
1134 /* Let's the server pick up a free network port for us */
1135 if (sock_initaddress(host
, portdata
, &hints
, &addrinfo
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1138 if ((sockdata
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, fp
->errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1141 /* addrinfo is no longer used */
1142 freeaddrinfo(addrinfo
);
1147 SOCKET socktemp
; /* We need another socket, since we're going to accept() a connection */
1149 /* Connection creation */
1150 saddrlen
= sizeof(struct sockaddr_storage
);
1152 socktemp
= accept(sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
);
1154 if (socktemp
== INVALID_SOCKET
)
1156 sock_geterror("accept(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1160 /* Now that I accepted the connection, the server socket is no longer needed */
1161 sock_close(sockdata
, fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1162 sockdata
= socktemp
;
1166 /* Let's save the socket of the data connection */
1167 pr
->rmt_sockdata
= sockdata
;
1169 /* Allocates WinPcap/libpcap user buffer, which is a socket buffer in case of a remote capture */
1170 /* It has the same size of the one used on the other side of the connection */
1171 fp
->bufsize
= ntohl(startcapreply
.bufsize
);
1173 /* Let's get the actual size of the socket buffer */
1174 itemp
= sizeof(sockbufsize
);
1176 res
= getsockopt(sockdata
, SOL_SOCKET
, SO_RCVBUF
, (char *)&sockbufsize
, &itemp
);
1179 sock_geterror("pcap_startcapture_remote()", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1180 SOCK_ASSERT(fp
->errbuf
, 1);
1184 * Warning: on some kernels (e.g. Linux), the size of the user buffer does not take
1185 * into account the pcap_header and such, and it is set equal to the snaplen.
1186 * In my view, this is wrong (the meaning of the bufsize became a bit strange).
1187 * So, here bufsize is the whole size of the user buffer.
1188 * In case the bufsize returned is too small, let's adjust it accordingly.
1190 if (fp
->bufsize
<= (u_int
) fp
->snapshot
)
1191 fp
->bufsize
+= sizeof(struct pcap_pkthdr
);
1193 /* if the current socket buffer is smaller than the desired one */
1194 if ((u_int
) sockbufsize
< fp
->bufsize
)
1196 /* Loop until the buffer size is OK or the original socket buffer size is larger than this one */
1199 res
= setsockopt(sockdata
, SOL_SOCKET
, SO_RCVBUF
, (char *)&(fp
->bufsize
), sizeof(fp
->bufsize
));
1205 * If something goes wrong, half the buffer size (checking that it does not become smaller than
1210 if ((u_int
) sockbufsize
>= fp
->bufsize
)
1212 fp
->bufsize
= sockbufsize
;
1219 * Let's allocate the packet; this is required in order to put the packet somewhere when
1220 * extracting data from the socket
1221 * Since buffering has already been done in the socket buffer, here we need just a buffer,
1222 * whose size is equal to the pcap header plus the snapshot length
1224 fp
->bufsize
= fp
->snapshot
+ sizeof(struct pcap_pkthdr
);
1226 fp
->buffer
= (u_char
*)malloc(fp
->bufsize
);
1227 if (fp
->buffer
== NULL
)
1229 pcap_snprintf(fp
->errbuf
, PCAP_ERRBUF_SIZE
, "malloc: %s", pcap_strerror(errno
));
1233 /* Checks if all the data has been read; if not, discard the data in excess */
1234 if (totread
!= ntohl(header
.plen
))
1236 if (sock_discard(pr
->rmt_sockctrl
, ntohl(header
.plen
) - totread
, NULL
, 0) == 1)
1241 * In case the user does not want to capture RPCAP packets, let's update the filter
1242 * We have to update it here (instead of sending it into the 'StartCapture' message
1243 * because when we generate the 'start capture' we do not know (yet) all the ports
1244 * we're currently using.
1246 if (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
)
1248 struct bpf_program fcode
;
1250 if (pcap_createfilter_norpcappkt(fp
, &fcode
) == -1)
1253 /* We cannot use 'pcap_setfilter_rpcap' because formally the capture has not been started yet */
1254 /* (the 'pr->rmt_capstarted' variable will be updated some lines below) */
1255 if (pcap_updatefilter_remote(fp
, &fcode
) == -1)
1258 pcap_freecode(&fcode
);
1261 pr
->rmt_capstarted
= 1;
1266 * When the connection has been established, we have to close it. So, at the
1267 * beginning of this function, if an error occur we return immediately with
1268 * a return NULL; when the connection is established, we have to come here
1269 * ('goto error;') in order to close everything properly.
1271 * Checks if all the data has been read; if not, discard the data in excess
1273 if (totread
!= ntohl(header
.plen
))
1274 sock_discard(pr
->rmt_sockctrl
, ntohl(header
.plen
) - totread
, NULL
, 0);
1276 if ((sockdata
) && (sockdata
!= -1)) /* we can be here because sockdata said 'error' */
1277 sock_close(sockdata
, NULL
, 0);
1280 sock_close(pr
->rmt_sockctrl
, NULL
, 0);
1283 * We do not have to call pcap_close() here, because this function is always called
1284 * by the user in case something bad happens
1298 * This function takes a bpf program and sends it to the other host.
1300 * This function can be called in two cases:
1301 * - pcap_startcapture_remote() is called (we have to send the filter
1302 * along with the 'start capture' command)
1303 * - we want to udpate the filter during a capture (i.e. pcap_setfilter()
1304 * after the capture has been started)
1306 * This function serializes the filter into the sending buffer ('sendbuf',
1307 * passed as a parameter) and return back. It does not send anything on
1310 * \param fp: the pcap_t descriptor of the device currently opened.
1312 * \param sendbuf: the buffer on which the serialized data has to copied.
1314 * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1316 * \param prog: the bpf program we have to copy.
1318 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1319 * is returned into the 'errbuf' field of the pcap_t structure.
1321 static int pcap_pack_bpffilter(pcap_t
*fp
, char *sendbuf
, int *sendbufidx
, struct bpf_program
*prog
)
1323 struct rpcap_filter
*filter
;
1324 struct rpcap_filterbpf_insn
*insn
;
1325 struct bpf_insn
*bf_insn
;
1326 struct bpf_program fake_prog
; /* To be used just in case the user forgot to set a filter */
1329 if (prog
->bf_len
== 0) /* No filters have been specified; so, let's apply a "fake" filter */
1331 if (pcap_compile(fp
, &fake_prog
, NULL
/* buffer */, 1, 0) == -1)
1337 filter
= (struct rpcap_filter
*) sendbuf
;
1339 if (sock_bufferize(NULL
, sizeof(struct rpcap_filter
), NULL
, sendbufidx
,
1340 RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1343 filter
->filtertype
= htons(RPCAP_UPDATEFILTER_BPF
);
1344 filter
->nitems
= htonl((int32
)prog
->bf_len
);
1346 if (sock_bufferize(NULL
, prog
->bf_len
* sizeof(struct rpcap_filterbpf_insn
),
1347 NULL
, sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1350 insn
= (struct rpcap_filterbpf_insn
*) (filter
+ 1);
1351 bf_insn
= prog
->bf_insns
;
1353 for (i
= 0; i
< prog
->bf_len
; i
++)
1355 insn
->code
= htons(bf_insn
->code
);
1356 insn
->jf
= bf_insn
->jf
;
1357 insn
->jt
= bf_insn
->jt
;
1358 insn
->k
= htonl(bf_insn
->k
);
1368 * This function updates a filter on a remote host.
1370 * It is called when the user wants to update a filter.
1371 * In case we're capturing from the network, it sends the filter to our
1373 * This function is *not* called automatically when the user calls
1375 * There will be two cases:
1376 * - the capture has been started: in this case, pcap_setfilter_rpcap()
1377 * calls pcap_updatefilter_remote()
1378 * - the capture has not started yet: in this case, pcap_setfilter_rpcap()
1379 * stores the filter into the pcap_t structure, and then the filter is
1380 * sent with pcap_startcap().
1382 * WARNING This function *does not* clear the packet currently into the
1383 * buffers. Therefore, the user has to expect to receive some packets
1384 * that are related to the previous filter. If you want to discard all
1385 * the packets before applying a new filter, you have to close the
1386 * current capture session and start a new one.
1388 * XXX - we really should have pcap_setfilter() always discard packets
1389 * received with the old filter, and have a separate pcap_setfilter_noflush()
1390 * function that doesn't discard any packets.
1392 static int pcap_updatefilter_remote(pcap_t
*fp
, struct bpf_program
*prog
)
1394 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1395 int retval
; /* general variable used to keep the return value of other functions */
1396 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
1397 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1398 struct rpcap_header header
; /* To keep the reply message */
1400 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
, &sendbufidx
,
1401 RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1404 rpcap_createhdr((struct rpcap_header
*) sendbuf
, RPCAP_MSG_UPDATEFILTER_REQ
, 0,
1405 sizeof(struct rpcap_filter
) + prog
->bf_len
* sizeof(struct rpcap_filterbpf_insn
));
1407 if (pcap_pack_bpffilter(fp
, &sendbuf
[sendbufidx
], &sendbufidx
, prog
))
1410 if (sock_send(pr
->rmt_sockctrl
, sendbuf
, sendbufidx
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1413 /* Waits for the answer */
1414 if (sock_recv(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1417 /* Checks if the message is correct */
1418 retval
= rpcap_checkmsg(fp
->errbuf
, pr
->rmt_sockctrl
, &header
, RPCAP_MSG_UPDATEFILTER_REPLY
, 0);
1420 if (retval
!= RPCAP_MSG_UPDATEFILTER_REPLY
) /* the message is not the one expected */
1424 case -3: /* Unrecoverable network error */
1425 case -2: /* The other endpoint sent a message that is not allowed here */
1426 case -1: /* The other endpoint has a version number that is not compatible with our */
1427 /* Do nothing; just exit from here; the error code is already into the errbuf */
1431 SOCK_ASSERT("Internal error", 0);
1436 if (ntohl(header
.plen
) != 0) /* the message has an unexpected size */
1438 if (sock_discard(pr
->rmt_sockctrl
, ntohl(header
.plen
), fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1446 pcap_save_current_filter_rpcap(pcap_t
*fp
, const char *filter
)
1448 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1452 * - We are on an remote capture
1453 * - we do not want to capture RPCAP traffic
1455 * If so, we have to save the current filter, because we have to
1456 * add some piece of stuff later
1458 if (pr
->rmt_clientside
&&
1459 (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
))
1461 if (pr
->currentfilter
)
1462 free(pr
->currentfilter
);
1467 pr
->currentfilter
= strdup(filter
);
1472 * This function sends a filter to a remote host.
1474 * This function is called when the user wants to set a filter.
1475 * It sends the filter to our peer.
1476 * This function is called automatically when the user calls pcap_setfilter().
1478 * Parameters and return values are exactly the same of pcap_setfilter().
1480 static int pcap_setfilter_rpcap(pcap_t
*fp
, struct bpf_program
*prog
)
1482 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1484 if (!pr
->rmt_capstarted
)
1486 /* copy filter into the pcap_t structure */
1487 if (install_bpf_program(fp
, prog
) == -1)
1492 /* we have to update a filter during run-time */
1493 if (pcap_updatefilter_remote(fp
, prog
))
1500 * This function updates the current filter in order not to capture rpcap
1503 * This function is called *only* when the user wants exclude RPCAP packets
1504 * related to the current session from the captured packets.
1506 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1507 * is returned into the 'errbuf' field of the pcap_t structure.
1509 static int pcap_createfilter_norpcappkt(pcap_t
*fp
, struct bpf_program
*prog
)
1511 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1514 /* We do not want to capture our RPCAP traffic. So, let's update the filter */
1515 if (pr
->rmt_flags
& PCAP_OPENFLAG_NOCAPTURE_RPCAP
)
1517 struct sockaddr_storage saddr
; /* temp, needed to retrieve the network data port chosen on the local machine */
1518 socklen_t saddrlen
; /* temp, needed to retrieve the network data port chosen on the local machine */
1519 char myaddress
[128];
1520 char myctrlport
[128];
1521 char mydataport
[128];
1522 char peeraddress
[128];
1523 char peerctrlport
[128];
1525 const int newstringsize
= 1024;
1526 size_t currentfiltersize
;
1528 /* Get the name/port of our peer */
1529 saddrlen
= sizeof(struct sockaddr_storage
);
1530 if (getpeername(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1532 sock_geterror("getpeername(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1536 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, peeraddress
,
1537 sizeof(peeraddress
), peerctrlport
, sizeof(peerctrlport
), NI_NUMERICHOST
| NI_NUMERICSERV
))
1539 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1543 /* We cannot check the data port, because this is available only in case of TCP sockets */
1544 /* Get the name/port of the current host */
1545 if (getsockname(pr
->rmt_sockctrl
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1547 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1551 /* Get the local port the system picked up */
1552 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, myaddress
,
1553 sizeof(myaddress
), myctrlport
, sizeof(myctrlport
), NI_NUMERICHOST
| NI_NUMERICSERV
))
1555 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1559 /* Let's now check the data port */
1560 if (getsockname(pr
->rmt_sockdata
, (struct sockaddr
*) &saddr
, &saddrlen
) == -1)
1562 sock_geterror("getsockname(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1566 /* Get the local port the system picked up */
1567 if (getnameinfo((struct sockaddr
*) &saddr
, saddrlen
, NULL
, 0, mydataport
, sizeof(mydataport
), NI_NUMERICSERV
))
1569 sock_geterror("getnameinfo(): ", fp
->errbuf
, PCAP_ERRBUF_SIZE
);
1573 currentfiltersize
= pr
->currentfilter
? strlen(pr
->currentfilter
) : 0;
1575 newfilter
= (char *)malloc(currentfiltersize
+ newstringsize
+ 1);
1577 if (currentfiltersize
)
1579 pcap_snprintf(newfilter
, currentfiltersize
+ newstringsize
,
1580 "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1581 pr
->currentfilter
, myaddress
, peeraddress
, myctrlport
, peerctrlport
, myaddress
, peeraddress
, mydataport
);
1585 pcap_snprintf(newfilter
, currentfiltersize
+ newstringsize
,
1586 "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1587 myaddress
, peeraddress
, myctrlport
, peerctrlport
, myaddress
, peeraddress
, mydataport
);
1590 newfilter
[currentfiltersize
+ newstringsize
] = 0;
1593 * This is only an hack to prevent the save_current_filter
1594 * routine, which will be called when we call pcap_compile(),
1595 * from saving the modified filter.
1597 pr
->rmt_clientside
= 0;
1599 if (pcap_compile(fp
, prog
, newfilter
, 1, 0) == -1)
1602 /* Undo the hack. */
1603 pr
->rmt_clientside
= 1;
1612 * This function sets sampling parameters in the remote host.
1614 * It is called when the user wants to set activate sampling on the
1617 * Sampling parameters are defined into the 'pcap_t' structure.
1619 * \param p: the pcap_t descriptor of the device currently opened.
1621 * \return '0' if everything is OK, '-1' is something goes wrong. The
1622 * error message is returned in the 'errbuf' member of the pcap_t structure.
1624 static int pcap_setsampling_remote(pcap_t
*fp
)
1626 struct pcap_rpcap
*pr
= fp
->priv
; /* structure used when doing a remote live capture */
1627 int retval
; /* general variable used to keep the return value of other functions */
1628 char sendbuf
[RPCAP_NETBUF_SIZE
];/* temporary buffer in which data to be sent is buffered */
1629 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1630 struct rpcap_header header
; /* To keep the reply message */
1631 struct rpcap_sampling
*sampling_pars
; /* Structure that is needed to send sampling parameters to the remote host */
1633 /* If no samping is requested, return 'ok' */
1634 if (fp
->rmt_samp
.method
== PCAP_SAMP_NOSAMP
)
1637 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1638 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1641 rpcap_createhdr((struct rpcap_header
*) sendbuf
, RPCAP_MSG_SETSAMPLING_REQ
, 0, sizeof(struct rpcap_sampling
));
1643 /* Fill the structure needed to open an adapter remotely */
1644 sampling_pars
= (struct rpcap_sampling
*) &sendbuf
[sendbufidx
];
1646 if (sock_bufferize(NULL
, sizeof(struct rpcap_sampling
), NULL
,
1647 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1650 memset(sampling_pars
, 0, sizeof(struct rpcap_sampling
));
1652 sampling_pars
->method
= fp
->rmt_samp
.method
;
1653 sampling_pars
->value
= htonl(fp
->rmt_samp
.value
);
1655 if (sock_send(pr
->rmt_sockctrl
, sendbuf
, sendbufidx
, fp
->errbuf
, PCAP_ERRBUF_SIZE
))
1658 /* Waits for the answer */
1659 if (sock_recv(pr
->rmt_sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1662 /* Checks if the message is correct */
1663 retval
= rpcap_checkmsg(fp
->errbuf
, pr
->rmt_sockctrl
, &header
, RPCAP_MSG_SETSAMPLING_REPLY
, 0);
1665 if (retval
!= RPCAP_MSG_SETSAMPLING_REPLY
) /* the message is not the one expected */
1669 case -3: /* Unrecoverable network error */
1670 case -2: /* The other endpoint sent a message that is not allowed here */
1671 case -1: /* The other endpoint has a version number that is not compatible with our */
1672 case RPCAP_MSG_ERROR
:
1673 /* Do nothing; just exit from here; the error code is already into the errbuf */
1677 SOCK_ASSERT("Internal error", 0);
1682 if (ntohl(header
.plen
) != 0) /* the message has an unexpected size */
1684 if (sock_discard(pr
->rmt_sockctrl
, ntohl(header
.plen
), fp
->errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1692 /*********************************************************
1694 * Miscellaneous functions *
1696 *********************************************************/
1699 * This function sends a RPCAP error to our peer.
1701 * It has to be called when the main program detects an error.
1702 * It will send to our peer the 'buffer' specified by the user.
1703 * This function *does not* request a RPCAP CLOSE connection. A CLOSE
1704 * command must be sent explicitly by the program, since we do not know
1705 * whether the error can be recovered in some way or if it is a
1706 * non-recoverable one.
1708 * \param sock: the socket we are currently using.
1710 * \param error: an user-allocated (and '0' terminated) buffer that contains
1711 * the error description that has to be transmitted to our peer. The
1712 * error message cannot be longer than PCAP_ERRBUF_SIZE.
1714 * \param errcode: a integer which tells the other party the type of error
1715 * we had; currently is is not too much used.
1717 * \param errbuf: a pointer to a user-allocated buffer (of size
1718 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1719 * is one). It could be network problem.
1721 * \return '0' if everything is fine, '-1' if some errors occurred. The
1722 * error message is returned in the 'errbuf' variable.
1724 int rpcap_senderror(SOCKET sock
, char *error
, unsigned short errcode
, char *errbuf
)
1726 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
1727 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1730 length
= (uint16
)strlen(error
);
1732 if (length
> PCAP_ERRBUF_SIZE
)
1733 length
= PCAP_ERRBUF_SIZE
;
1735 rpcap_createhdr((struct rpcap_header
*) sendbuf
, RPCAP_MSG_ERROR
, errcode
, length
);
1737 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
, &sendbufidx
,
1738 RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
1741 if (sock_bufferize(error
, length
, sendbuf
, &sendbufidx
,
1742 RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
1745 if (sock_send(sock
, sendbuf
, sendbufidx
, errbuf
, PCAP_ERRBUF_SIZE
))
1752 * This function sends the authentication message.
1754 * It sends the authentication parameters on the control socket.
1755 * It is required in order to open the connection with the other end party.
1757 * \param sock: the socket we are currently using.
1759 * \param auth: authentication parameters that have to be sent.
1761 * \param errbuf: a pointer to a user-allocated buffer (of size
1762 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1763 * is one). It could be a network problem or the fact that the authorization
1766 * \return '0' if everything is fine, '-1' if some errors occurred. The
1767 * error message is returned in the 'errbuf' variable.
1768 * The error message could be also 'the authentication failed'.
1770 static int rpcap_sendauth(SOCKET sock
, struct pcap_rmtauth
*auth
, char *errbuf
)
1772 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data that has to be sent is buffered */
1773 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
1774 uint16 length
; /* length of the payload of this message */
1775 struct rpcap_auth
*rpauth
;
1777 struct rpcap_header header
;
1778 int retval
; /* temp variable which stores functions return value */
1783 auth_type
= auth
->type
;
1787 case RPCAP_RMTAUTH_NULL
:
1788 length
= sizeof(struct rpcap_auth
);
1791 case RPCAP_RMTAUTH_PWD
:
1792 length
= sizeof(struct rpcap_auth
);
1795 str_length
= strlen(auth
->username
);
1796 if (str_length
> 65535)
1798 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "User name is too long (> 65535 bytes)");
1801 length
+= (uint16
)str_length
;
1805 str_length
= strlen(auth
->password
);
1806 if (str_length
> 65535)
1808 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Password is too long (> 65535 bytes)");
1811 length
+= (uint16
)str_length
;
1816 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Authentication type not recognized.");
1822 auth_type
= RPCAP_RMTAUTH_NULL
;
1823 length
= sizeof(struct rpcap_auth
);
1827 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
1828 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
1831 rpcap_createhdr((struct rpcap_header
*) sendbuf
, RPCAP_MSG_AUTH_REQ
, 0, length
);
1833 rpauth
= (struct rpcap_auth
*) &sendbuf
[sendbufidx
];
1835 if (sock_bufferize(NULL
, sizeof(struct rpcap_auth
), NULL
,
1836 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
1839 memset(rpauth
, 0, sizeof(struct rpcap_auth
));
1841 rpauth
->type
= htons(auth_type
);
1843 if (auth_type
== RPCAP_RMTAUTH_PWD
)
1846 rpauth
->slen1
= (uint16
)strlen(auth
->username
);
1850 if (sock_bufferize(auth
->username
, rpauth
->slen1
, sendbuf
,
1851 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
1855 rpauth
->slen2
= (uint16
)strlen(auth
->password
);
1859 if (sock_bufferize(auth
->password
, rpauth
->slen2
, sendbuf
,
1860 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
1863 rpauth
->slen1
= htons(rpauth
->slen1
);
1864 rpauth
->slen2
= htons(rpauth
->slen2
);
1867 if (sock_send(sock
, sendbuf
, sendbufidx
, errbuf
, PCAP_ERRBUF_SIZE
))
1870 if (sock_recv(sock
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1873 retval
= rpcap_checkmsg(errbuf
, sock
, &header
, RPCAP_MSG_AUTH_REPLY
, RPCAP_MSG_ERROR
, 0);
1875 if (retval
!= RPCAP_MSG_AUTH_REPLY
) /* the message is not the one expected */
1879 case -3: /* Unrecoverable network error */
1880 case -2: /* The other endpoint sent a message that is not allowed here */
1881 case -1: /* The other endpoint has a version number that is not compatible with our */
1882 /* Do nothing; just exit from here; the error code is already into the errbuf */
1885 case RPCAP_MSG_ERROR
:
1889 SOCK_ASSERT("Internal error", 0);
1894 if (ntohl(header
.plen
))
1896 if (sock_discard(sock
, ntohl(header
.plen
), errbuf
, PCAP_ERRBUF_SIZE
))
1904 * This function fills in a structure of type rpcap_header.
1906 * It is provided just because the creation of an rpcap header is a common
1907 * task. It accepts all the values that appears into an rpcap_header, and
1908 * it puts them in place using the proper hton() calls.
1910 * \param header: a pointer to a user-allocated buffer which will contain
1911 * the serialized header, ready to be sent on the network.
1913 * \param type: a value (in the host by order) which will be placed into the
1914 * header.type field and that represents the type of the current message.
1916 * \param value: a value (in the host by order) which will be placed into
1917 * the header.value field and that has a message-dependent meaning.
1919 * \param length: a value (in the host by order) which will be placed into
1920 * the header.length field, representing the payload length of the message.
1922 * \return Nothing. The serialized header is returned into the 'header'
1925 void rpcap_createhdr(struct rpcap_header
*header
, uint8 type
, uint16 value
, uint32 length
)
1927 memset(header
, 0, sizeof(struct rpcap_header
));
1929 header
->ver
= RPCAP_VERSION
;
1930 header
->type
= type
;
1931 header
->value
= htons(value
);
1932 header
->plen
= htonl(length
);
1936 * This function checks whether the header of the received message is correct.
1938 * It is a way to easily check if the message received, in a certain state
1939 * of the RPCAP protocol Finite State Machine, is valid. This function accepts,
1940 * as a parameter, the list of message types that are allowed in a certain
1941 * situation, and it returns the one that occurs.
1943 * \param errbuf: a pointer to a user-allocated buffer (of size
1944 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
1945 * is one). It could either be a problem that occurred inside this function
1946 * (e.g. a network problem in case it tries to send an error to our peer
1947 * and the send() call fails), an error message thathas been sent to us
1948 * from the other party, or a version error (the message received has a
1949 * version number that is incompatible with ours).
1951 * \param sock: the socket that has to be used to receive data. This
1952 * function can read data from socket in case the version contained into
1953 * the message is not compatible with ours. In that case, all the message
1954 * is purged from the socket, so that the following recv() calls will
1955 * return a new message.
1957 * \param header: a pointer to and 'rpcap_header' structure that keeps
1958 * the data received from the network (still in network byte order) and
1959 * that has to be checked.
1961 * \param first: this function has a variable number of parameters. From
1962 * this point on, all the messages that are valid in this context must be
1963 * passed as parameters. The message type list must be terminated with a
1964 * '0' value, the null message type, which means 'no more types to check'.
1965 * The RPCAP protocol does not define anything with message type equal to
1966 * zero, so there is no ambiguity in using this value as a list terminator.
1968 * \return The message type of the message that has been detected. In case
1969 * of errors (e.g. the header contains a type that is not listed among the
1970 * allowed types), this function will return the following codes:
1971 * - (-1) if the version is incompatible.
1972 * - (-2) if the code is not among the one listed into the parameters list
1973 * - (-3) if a network error (connection reset, ...)
1974 * - RPCAP_MSG_ERROR if the message is an error message (it follows that
1975 * the RPCAP_MSG_ERROR could not be present in the allowed message-types
1976 * list, because this function checks for errors anyway)
1978 * In case either the version is incompatible or nothing matches (i.e. it
1979 * returns '-1' or '-2'), it discards the message body (i.e. it reads the
1980 * remaining part of the message from the network and it discards it) so
1981 * that the application is ready to receive a new message.
1983 int rpcap_checkmsg(char *errbuf
, SOCKET sock
, struct rpcap_header
*header
, uint8 first
, ...)
1989 va_start(ap
, first
);
1991 /* Check if the present version of the protocol can handle this message */
1992 if (rpcap_checkver(sock
, header
, errbuf
))
1994 SOCK_ASSERT(errbuf
, 1);
2005 * The message matches with one of the types listed
2006 * There is no need of conversions since both values are uint8
2008 * Check if the other side reported an error.
2009 * If yes, it retrieves it and it returns it back to the caller
2011 if (header
->type
== RPCAP_MSG_ERROR
)
2013 len
= ntohl(header
->plen
);
2015 if (len
>= PCAP_ERRBUF_SIZE
)
2017 if (sock_recv(sock
, errbuf
, PCAP_ERRBUF_SIZE
- 1, SOCK_RECEIVEALL_YES
, errbuf
, PCAP_ERRBUF_SIZE
))
2020 sock_discard(sock
, len
- (PCAP_ERRBUF_SIZE
- 1), NULL
, 0);
2022 /* Put '\0' at the end of the string */
2023 errbuf
[PCAP_ERRBUF_SIZE
- 1] = 0;
2027 if (sock_recv(sock
, errbuf
, len
, SOCK_RECEIVEALL_YES
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2030 /* Put '\0' at the end of the string */
2035 return header
->type
;
2038 if (header
->type
== type
)
2041 return header
->type
;
2044 /* get next argument */
2045 type
= va_arg(ap
, int);
2048 /* we already have an error, so please discard this one */
2049 sock_discard(sock
, ntohl(header
->plen
), NULL
, 0);
2051 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The other endpoint sent a message that is not allowed here.");
2052 SOCK_ASSERT(errbuf
, 1);
2059 * This function checks whether the version contained into the message is
2060 * compatible with the one handled by this implementation.
2062 * Right now, this function does not have any sophisticated task: if the
2063 * versions are different, it returns -1 and it discards the message.
2064 * If new versions of the protocol are created, there will need to be
2065 * a negotiation phase early in the process of connecting to our peer,
2066 * so that the highest version supported by both sides can be used.
2068 * \param sock: the socket that has to be used to receive data. This
2069 * function can read data from socket in case the version contained into
2070 * the message is not compatible with ours. In that case, all the message
2071 * is purged from the socket, so that the following recv() calls will
2072 * return a new (clean) message.
2074 * \param header: a pointer to and 'rpcap_header' structure that keeps
2075 * the data received from the network (still in network byte order) and
2076 * that has to be checked.
2078 * \param errbuf: a pointer to a user-allocated buffer (of size
2079 * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
2080 * is one). The error message is "incompatible version".
2082 * \return '0' if everything is fine, '-1' if some errors occurred. The
2083 * error message is returned in the 'errbuf' variable.
2085 static int rpcap_checkver(SOCKET sock
, struct rpcap_header
*header
, char *errbuf
)
2088 * This is a sample function.
2090 * In the real world, you have to check the type code,
2091 * and decide accordingly.
2093 if (header
->ver
!= RPCAP_VERSION
)
2095 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Incompatible version number: message discarded.");
2097 /* we already have an error, so please discard this one */
2098 sock_discard(sock
, ntohl(header
->plen
), NULL
, 0);
2106 * This function opens a remote adapter by opening an RPCAP connection and
2109 * It does the job of pcap_open_live() for a remote interface; it's called
2110 * by pcap_open() for remote interfaces.
2112 * We do not start the capture until pcap_startcapture_remote() is called.
2114 * This is because, when doing a remote capture, we cannot start capturing
2115 * data as soon as the 'open adapter' command is sent. Suppose the remote
2116 * adapter is already overloaded; if we start a capture (which, by default,
2117 * has a NULL filter) the new traffic can saturate the network.
2119 * Instead, we want to "open" the adapter, then send a "start capture"
2120 * command only when we're ready to start the capture.
2121 * This function does this job: it sends an "open adapter" command
2122 * (according to the RPCAP protocol), but it does not start the capture.
2124 * Since the other libpcap functions do not share this way of life, we
2125 * have to do some dirty things in order to make everything work.
2127 * \param source: see pcap_open().
2128 * \param snaplen: see pcap_open().
2129 * \param flags: see pcap_open().
2130 * \param read_timeout: see pcap_open().
2131 * \param auth: see pcap_open().
2132 * \param errbuf: see pcap_open().
2134 * \return a pcap_t pointer in case of success, NULL otherwise. In case of
2135 * success, the pcap_t pointer can be used as a parameter to the following
2136 * calls (pcap_compile() and so on). In case of problems, errbuf contains
2137 * a text explanation of error.
2139 * WARNING: In case we call pcap_compile() and the capture has not yet
2140 * been started, the filter will be saved into the pcap_t structure,
2141 * and it will be sent to the other host later (when
2142 * pcap_startcapture_remote() is called).
2144 pcap_t
*pcap_open_rpcap(const char *source
, int snaplen
, int flags
, int read_timeout
, struct pcap_rmtauth
*auth
, char *errbuf
)
2148 struct pcap_rpcap
*pr
; /* structure used when doing a remote live capture */
2149 char host
[PCAP_BUF_SIZE
], ctrlport
[PCAP_BUF_SIZE
], iface
[PCAP_BUF_SIZE
];
2151 char sendbuf
[RPCAP_NETBUF_SIZE
]; /* temporary buffer in which data to be sent is buffered */
2152 int sendbufidx
= 0; /* index which keeps the number of bytes currently buffered */
2153 uint32 totread
= 0; /* number of bytes of the payload read from the socket */
2155 int retval
; /* store the return value of the functions */
2156 int active
= 0; /* '1' if we're in active mode */
2158 /* socket-related variables */
2159 struct addrinfo hints
; /* temp, needed to open a socket connection */
2160 struct addrinfo
*addrinfo
; /* temp, needed to open a socket connection */
2161 SOCKET sockctrl
= 0; /* socket descriptor of the control connection */
2163 /* RPCAP-related variables */
2164 struct rpcap_header header
; /* header of the RPCAP packet */
2165 struct rpcap_openreply openreply
; /* open reply message */
2167 fp
= pcap_create_common(errbuf
, sizeof (struct pcap_rpcap
));
2172 source_str
= strdup(source
);
2173 if (source_str
== NULL
) {
2174 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2175 "malloc: %s", pcap_strerror(errno
));
2178 fp
->opt
.device
= source_str
;
2179 fp
->snapshot
= snaplen
;
2180 fp
->opt
.timeout
= read_timeout
;
2182 pr
->rmt_flags
= flags
;
2185 * determine the type of the source (NULL, file, local, remote)
2186 * You must have a valid source string even if we're in active mode, because otherwise
2187 * the call to the following function will fail.
2189 if (pcap_parsesrcstr(fp
->opt
.device
, &retval
, host
, ctrlport
, iface
, errbuf
) == -1)
2195 if (retval
!= PCAP_SRC_IFREMOTE
)
2197 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "This function is able to open only remote interfaces");
2205 * Warning: this call can be the first one called by the user.
2206 * For this reason, we have to initialize the WinSock support.
2208 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2214 sockctrl
= rpcap_remoteact_getsock(host
, &active
, errbuf
);
2215 if (sockctrl
== INVALID_SOCKET
)
2224 * We're not in active mode; let's try to open a new
2225 * control connection.
2227 memset(&hints
, 0, sizeof(struct addrinfo
));
2228 hints
.ai_family
= PF_UNSPEC
;
2229 hints
.ai_socktype
= SOCK_STREAM
;
2231 if (ctrlport
[0] == 0)
2233 /* the user chose not to specify the port */
2234 if (sock_initaddress(host
, RPCAP_DEFAULT_NETPORT
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2242 /* the user chose not to specify the port */
2243 if (sock_initaddress(host
, ctrlport
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2250 if ((sockctrl
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
2253 freeaddrinfo(addrinfo
);
2256 if (rpcap_sendauth(sockctrl
, auth
, errbuf
) == -1)
2261 * Now it's time to start playing with the RPCAP protocol
2262 * RPCAP open command: create the request message
2264 if (sock_bufferize(NULL
, sizeof(struct rpcap_header
), NULL
,
2265 &sendbufidx
, RPCAP_NETBUF_SIZE
, SOCKBUF_CHECKONLY
, errbuf
, PCAP_ERRBUF_SIZE
))
2268 rpcap_createhdr((struct rpcap_header
*) sendbuf
, RPCAP_MSG_OPEN_REQ
, 0, (uint32
) strlen(iface
));
2270 if (sock_bufferize(iface
, (int) strlen(iface
), sendbuf
, &sendbufidx
,
2271 RPCAP_NETBUF_SIZE
, SOCKBUF_BUFFERIZE
, errbuf
, PCAP_ERRBUF_SIZE
))
2274 if (sock_send(sockctrl
, sendbuf
, sendbufidx
, errbuf
, PCAP_ERRBUF_SIZE
))
2277 /* Receive the RPCAP open reply message */
2278 if (sock_recv(sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2281 /* Checks if the message is correct */
2282 retval
= rpcap_checkmsg(errbuf
, sockctrl
, &header
, RPCAP_MSG_OPEN_REPLY
, RPCAP_MSG_ERROR
, 0);
2284 if (retval
!= RPCAP_MSG_OPEN_REPLY
) /* the message is not the one expected */
2288 case -3: /* Unrecoverable network error */
2289 case -2: /* The other endpoint send a message that is not allowed here */
2290 case -1: /* The other endpoint has a version number that is not compatible with our */
2293 case RPCAP_MSG_ERROR
: /* The other endpoint reported an error */
2294 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
2295 totread
= ntohl(header
.plen
);
2296 /* Do nothing; just exit; the error code is already into the errbuf */
2300 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Internal error");
2305 nread
= sock_recv(sockctrl
, (char *)&openreply
,
2306 sizeof(struct rpcap_openreply
), SOCK_RECEIVEALL_YES
,
2307 errbuf
, PCAP_ERRBUF_SIZE
);
2312 /* Checks if all the data has been read; if not, discard the data in excess */
2313 if (totread
!= ntohl(header
.plen
))
2315 if (sock_discard(sockctrl
, ntohl(header
.plen
) - totread
, NULL
, 0) == 1)
2319 /* Set proper fields into the pcap_t struct */
2320 fp
->linktype
= ntohl(openreply
.linktype
);
2321 fp
->tzoff
= ntohl(openreply
.tzoff
);
2322 pr
->rmt_sockctrl
= sockctrl
;
2323 pr
->rmt_clientside
= 1;
2325 /* This code is duplicated from the end of this function */
2326 fp
->read_op
= pcap_read_rpcap
;
2327 fp
->save_current_filter_op
= pcap_save_current_filter_rpcap
;
2328 fp
->setfilter_op
= pcap_setfilter_rpcap
;
2329 fp
->getnonblock_op
= NULL
; /* This is not implemented in remote capture */
2330 fp
->setnonblock_op
= NULL
; /* This is not implemented in remote capture */
2331 fp
->stats_op
= pcap_stats_rpcap
;
2333 fp
->stats_ex_op
= pcap_stats_ex_rpcap
;
2335 fp
->cleanup_op
= pcap_cleanup_rpcap
;
2342 * When the connection has been established, we have to close it. So, at the
2343 * beginning of this function, if an error occur we return immediately with
2344 * a return NULL; when the connection is established, we have to come here
2345 * ('goto error;') in order to close everything properly.
2347 * Checks if all the data has been read; if not, discard the data in excess
2349 if (totread
!= ntohl(header
.plen
))
2350 sock_discard(sockctrl
, ntohl(header
.plen
) - totread
, NULL
, 0);
2353 freeaddrinfo(addrinfo
);
2356 sock_close(sockctrl
, NULL
, 0);
2362 /* String identifier to be used in the pcap_findalldevs_ex() */
2363 #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
2364 /* String identifier to be used in the pcap_findalldevs_ex() */
2365 #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST "on remote node"
2368 freeaddr(struct pcap_addr
*addr
)
2371 free(addr
->netmask
);
2372 free(addr
->broadaddr
);
2373 free(addr
->dstaddr
);
2378 pcap_findalldevs_ex_remote(char *source
, struct pcap_rmtauth
*auth
, pcap_if_t
**alldevs
, char *errbuf
)
2380 SOCKET sockctrl
; /* socket descriptor of the control connection */
2381 uint32 totread
= 0; /* number of bytes of the payload read from the socket */
2383 struct addrinfo hints
; /* temp variable needed to resolve hostnames into to socket representation */
2384 struct addrinfo
*addrinfo
; /* temp variable needed to resolve hostnames into to socket representation */
2385 struct rpcap_header header
; /* structure that keeps the general header of the rpcap protocol */
2386 int i
, j
; /* temp variables */
2387 int retval
; /* store the return value of the functions */
2388 int nif
; /* Number of interfaces listed */
2389 int active
= 0; /* 'true' if we the other end-party is in active mode */
2391 char host
[PCAP_BUF_SIZE
], port
[PCAP_BUF_SIZE
];
2392 char tmpstring
[PCAP_BUF_SIZE
+ 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2393 pcap_if_t
*dev
; /* Previous device into the pcap_if_t chain */
2395 /* Retrieve the needed data for getting adapter list */
2396 if (pcap_parsesrcstr(source
, &type
, host
, port
, NULL
, errbuf
) == -1)
2399 /* Warning: this call can be the first one called by the user. */
2400 /* For this reason, we have to initialize the WinSock support. */
2401 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2404 /* Check for active mode */
2405 sockctrl
= rpcap_remoteact_getsock(host
, &active
, errbuf
);
2406 if (sockctrl
== INVALID_SOCKET
)
2411 * We're not in active mode; let's try to open a new
2412 * control connection.
2416 memset(&hints
, 0, sizeof(struct addrinfo
));
2417 hints
.ai_family
= PF_UNSPEC
;
2418 hints
.ai_socktype
= SOCK_STREAM
;
2422 /* the user chose not to specify the port */
2423 if (sock_initaddress(host
, RPCAP_DEFAULT_NETPORT
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2428 if (sock_initaddress(host
, port
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2432 if ((sockctrl
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, errbuf
, PCAP_ERRBUF_SIZE
)) == -1)
2435 /* addrinfo is no longer used */
2436 freeaddrinfo(addrinfo
);
2439 if (rpcap_sendauth(sockctrl
, auth
, errbuf
) == -1)
2441 sock_close(sockctrl
, NULL
, 0);
2446 /* RPCAP findalldevs command */
2447 rpcap_createhdr(&header
, RPCAP_MSG_FINDALLIF_REQ
, 0, 0);
2449 if (sock_send(sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2452 if (sock_recv(sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), SOCK_RECEIVEALL_YES
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2455 /* Checks if the message is correct */
2456 retval
= rpcap_checkmsg(errbuf
, sockctrl
, &header
, RPCAP_MSG_FINDALLIF_REPLY
, RPCAP_MSG_ERROR
, 0);
2458 if (retval
!= RPCAP_MSG_FINDALLIF_REPLY
) /* the message is not the one expected */
2462 case -3: /* Unrecoverable network error */
2463 case -2: /* The other endpoint send a message that is not allowed here */
2464 case -1: /* The other endpoint has a version number that is not compatible with our */
2467 case RPCAP_MSG_ERROR
: /* The other endpoint reported an error */
2471 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Internal error");
2476 sock_close(sockctrl
, NULL
, 0);
2481 /* read the number of interfaces */
2482 nif
= ntohs(header
.value
);
2484 /* loop until all interfaces have been received */
2485 for (i
= 0; i
< nif
; i
++)
2487 struct rpcap_findalldevs_if findalldevs_if
;
2488 char tmpstring2
[PCAP_BUF_SIZE
+ 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
2490 struct pcap_addr
*addr
, *prevaddr
;
2492 tmpstring2
[PCAP_BUF_SIZE
] = 0;
2494 /* receive the findalldevs structure from remote host */
2495 nread
= sock_recv(sockctrl
, (char *)&findalldevs_if
,
2496 sizeof(struct rpcap_findalldevs_if
), SOCK_RECEIVEALL_YES
,
2497 errbuf
, PCAP_ERRBUF_SIZE
);
2502 findalldevs_if
.namelen
= ntohs(findalldevs_if
.namelen
);
2503 findalldevs_if
.desclen
= ntohs(findalldevs_if
.desclen
);
2504 findalldevs_if
.naddr
= ntohs(findalldevs_if
.naddr
);
2506 /* allocate the main structure */
2509 (*alldevs
) = (pcap_if_t
*)malloc(sizeof(pcap_if_t
));
2514 dev
->next
= (pcap_if_t
*)malloc(sizeof(pcap_if_t
));
2518 /* check that the malloc() didn't fail */
2521 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "malloc() failed: %s", pcap_strerror(errno
));
2525 /* Initialize the structure to 'zero' */
2526 memset(dev
, 0, sizeof(pcap_if_t
));
2528 /* allocate mem for name and description */
2529 if (findalldevs_if
.namelen
)
2532 if (findalldevs_if
.namelen
>= sizeof(tmpstring
))
2534 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Interface name too long");
2538 /* Retrieve adapter name */
2539 nread
= sock_recv(sockctrl
, tmpstring
,
2540 findalldevs_if
.namelen
, SOCK_RECEIVEALL_YES
,
2541 errbuf
, PCAP_ERRBUF_SIZE
);
2546 tmpstring
[findalldevs_if
.namelen
] = 0;
2548 /* Create the new device identifier */
2549 if (pcap_createsrcstr(tmpstring2
, PCAP_SRC_IFREMOTE
, host
, port
, tmpstring
, errbuf
) == -1)
2552 stringlen
= strlen(tmpstring2
);
2554 dev
->name
= (char *)malloc(stringlen
+ 1);
2555 if (dev
->name
== NULL
)
2557 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "malloc() failed: %s", pcap_strerror(errno
));
2561 /* Copy the new device name into the correct memory location */
2562 strlcpy(dev
->name
, tmpstring2
, stringlen
+ 1);
2565 if (findalldevs_if
.desclen
)
2567 if (findalldevs_if
.desclen
>= sizeof(tmpstring
))
2569 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Interface description too long");
2573 /* Retrieve adapter description */
2574 nread
= sock_recv(sockctrl
, tmpstring
,
2575 findalldevs_if
.desclen
, SOCK_RECEIVEALL_YES
,
2576 errbuf
, PCAP_ERRBUF_SIZE
);
2581 tmpstring
[findalldevs_if
.desclen
] = 0;
2583 pcap_snprintf(tmpstring2
, sizeof(tmpstring2
) - 1, "%s '%s' %s %s", PCAP_TEXT_SOURCE_ADAPTER
,
2584 tmpstring
, PCAP_TEXT_SOURCE_ON_REMOTE_HOST
, host
);
2586 stringlen
= strlen(tmpstring2
);
2588 dev
->description
= (char *)malloc(stringlen
+ 1);
2590 if (dev
->description
== NULL
)
2592 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "malloc() failed: %s", pcap_strerror(errno
));
2596 /* Copy the new device description into the correct memory location */
2597 strlcpy(dev
->description
, tmpstring2
, stringlen
+ 1);
2600 dev
->flags
= ntohl(findalldevs_if
.flags
);
2603 /* loop until all addresses have been received */
2604 for (j
= 0; j
< findalldevs_if
.naddr
; j
++)
2606 struct rpcap_findalldevs_ifaddr ifaddr
;
2608 /* Retrieve the interface addresses */
2609 nread
= sock_recv(sockctrl
, (char *)&ifaddr
,
2610 sizeof(struct rpcap_findalldevs_ifaddr
),
2611 SOCK_RECEIVEALL_YES
, errbuf
, PCAP_ERRBUF_SIZE
);
2617 * Deserialize all the address components.
2619 addr
= (struct pcap_addr
*) malloc(sizeof(struct pcap_addr
));
2622 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "malloc() failed: %s", pcap_strerror(errno
));
2627 addr
->netmask
= NULL
;
2628 addr
->broadaddr
= NULL
;
2629 addr
->dstaddr
= NULL
;
2631 if (rpcap_deseraddr(&ifaddr
.addr
,
2632 (struct sockaddr_storage
**) &addr
->addr
, errbuf
) == -1)
2637 if (rpcap_deseraddr(&ifaddr
.netmask
,
2638 (struct sockaddr_storage
**) &addr
->netmask
, errbuf
) == -1)
2643 if (rpcap_deseraddr(&ifaddr
.broadaddr
,
2644 (struct sockaddr_storage
**) &addr
->broadaddr
, errbuf
) == -1)
2649 if (rpcap_deseraddr(&ifaddr
.dstaddr
,
2650 (struct sockaddr_storage
**) &addr
->dstaddr
, errbuf
) == -1)
2656 if ((addr
->addr
== NULL
) && (addr
->netmask
== NULL
) &&
2657 (addr
->broadaddr
== NULL
) && (addr
->dstaddr
== NULL
))
2660 * None of the addresses are IPv4 or IPv6
2661 * addresses, so throw this entry away.
2668 * Add this entry to the list.
2670 if (prevaddr
== NULL
)
2672 dev
->addresses
= addr
;
2676 prevaddr
->next
= addr
;
2683 /* Checks if all the data has been read; if not, discard the data in excess */
2684 if (totread
!= ntohl(header
.plen
))
2686 if (sock_discard(sockctrl
, ntohl(header
.plen
) - totread
, errbuf
, PCAP_ERRBUF_SIZE
) == 1)
2690 /* Control connection has to be closed only in case the remote machine is in passive mode */
2693 /* DO not send RPCAP_CLOSE, since we did not open a pcap_t; no need to free resources */
2694 if (sock_close(sockctrl
, errbuf
, PCAP_ERRBUF_SIZE
))
2698 /* To avoid inconsistencies in the number of sock_init() */
2705 * In case there has been an error, I don't want to overwrite it with a new one
2706 * if the following call fails. I want to return always the original error.
2708 * Take care: this connection can already be closed when we try to close it.
2709 * This happens because a previous error in the rpcapd, which requested to
2710 * closed the connection. In that case, we already recognized that into the
2711 * rpspck_isheaderok() and we already acknowledged the closing.
2712 * In that sense, this call is useless here (however it is needed in case
2713 * the client generates the error).
2715 * Checks if all the data has been read; if not, discard the data in excess
2717 if (totread
!= ntohl(header
.plen
))
2719 if (sock_discard(sockctrl
, ntohl(header
.plen
) - totread
, NULL
, 0) == 1)
2723 /* Control connection has to be closed only in case the remote machine is in passive mode */
2725 sock_close(sockctrl
, NULL
, 0);
2727 /* To avoid inconsistencies in the number of sock_init() */
2734 * Active mode routines.
2736 * The old libpcap API is somewhat ugly, and makes active mode difficult
2737 * to implement; we provide some APIs for it that work only with rpcap.
2740 SOCKET
pcap_remoteact_accept(const char *address
, const char *port
, const char *hostlist
, char *connectinghost
, struct pcap_rmtauth
*auth
, char *errbuf
)
2742 /* socket-related variables */
2743 struct addrinfo hints
; /* temporary struct to keep settings needed to open the new socket */
2744 struct addrinfo
*addrinfo
; /* keeps the addrinfo chain; required to open a new socket */
2745 struct sockaddr_storage from
; /* generic sockaddr_storage variable */
2746 socklen_t fromlen
; /* keeps the length of the sockaddr_storage variable */
2747 SOCKET sockctrl
; /* keeps the main socket identifier */
2748 struct activehosts
*temp
, *prev
; /* temp var needed to scan he host list chain */
2750 *connectinghost
= 0; /* just in case */
2752 /* Prepare to open a new server socket */
2753 memset(&hints
, 0, sizeof(struct addrinfo
));
2754 /* WARNING Currently it supports only ONE socket family among ipv4 and IPv6 */
2755 hints
.ai_family
= AF_INET
; /* PF_UNSPEC to have both IPv4 and IPv6 server */
2756 hints
.ai_flags
= AI_PASSIVE
; /* Ready to a bind() socket */
2757 hints
.ai_socktype
= SOCK_STREAM
;
2759 /* Warning: this call can be the first one called by the user. */
2760 /* For this reason, we have to initialize the WinSock support. */
2761 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2765 if ((port
== NULL
) || (port
[0] == 0))
2767 if (sock_initaddress(address
, RPCAP_DEFAULT_NETPORT_ACTIVE
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2769 SOCK_ASSERT(errbuf
, 1);
2775 if (sock_initaddress(address
, port
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
2777 SOCK_ASSERT(errbuf
, 1);
2783 if ((sockmain
= sock_open(addrinfo
, SOCKOPEN_SERVER
, 1, errbuf
, PCAP_ERRBUF_SIZE
)) == -1)
2785 SOCK_ASSERT(errbuf
, 1);
2789 /* Connection creation */
2790 fromlen
= sizeof(struct sockaddr_storage
);
2792 sockctrl
= accept(sockmain
, (struct sockaddr
*) &from
, &fromlen
);
2794 /* We're not using sock_close, since we do not want to send a shutdown */
2795 /* (which is not allowed on a non-connected socket) */
2796 closesocket(sockmain
);
2801 sock_geterror("accept(): ", errbuf
, PCAP_ERRBUF_SIZE
);
2805 /* Get the numeric for of the name of the connecting host */
2806 if (getnameinfo((struct sockaddr
*) &from
, fromlen
, connectinghost
, RPCAP_HOSTLIST_SIZE
, NULL
, 0, NI_NUMERICHOST
))
2808 sock_geterror("getnameinfo(): ", errbuf
, PCAP_ERRBUF_SIZE
);
2809 rpcap_senderror(sockctrl
, errbuf
, PCAP_ERR_REMOTEACCEPT
, NULL
);
2810 sock_close(sockctrl
, NULL
, 0);
2814 /* checks if the connecting host is among the ones allowed */
2815 if (sock_check_hostlist((char *)hostlist
, RPCAP_HOSTLIST_SEP
, &from
, errbuf
, PCAP_ERRBUF_SIZE
) < 0)
2817 rpcap_senderror(sockctrl
, errbuf
, PCAP_ERR_REMOTEACCEPT
, NULL
);
2818 sock_close(sockctrl
, NULL
, 0);
2822 /* Send authentication to the remote machine */
2823 if (rpcap_sendauth(sockctrl
, auth
, errbuf
) == -1)
2825 rpcap_senderror(sockctrl
, errbuf
, PCAP_ERR_REMOTEACCEPT
, NULL
);
2826 sock_close(sockctrl
, NULL
, 0);
2830 /* Checks that this host does not already have a cntrl connection in place */
2832 /* Initialize pointers */
2838 /* This host already has an active connection in place, so I don't have to update the host list */
2839 if (sock_cmpaddr(&temp
->host
, &from
) == 0)
2846 /* The host does not exist in the list; so I have to update the list */
2849 prev
->next
= (struct activehosts
*) malloc(sizeof(struct activehosts
));
2854 activeHosts
= (struct activehosts
*) malloc(sizeof(struct activehosts
));
2860 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "malloc() failed: %s", pcap_strerror(errno
));
2861 rpcap_senderror(sockctrl
, errbuf
, PCAP_ERR_REMOTEACCEPT
, NULL
);
2862 sock_close(sockctrl
, NULL
, 0);
2866 memcpy(&temp
->host
, &from
, fromlen
);
2867 temp
->sockctrl
= sockctrl
;
2873 int pcap_remoteact_close(const char *host
, char *errbuf
)
2875 struct activehosts
*temp
, *prev
; /* temp var needed to scan the host list chain */
2876 struct addrinfo hints
, *addrinfo
, *ai_next
; /* temp var needed to translate between hostname to its address */
2882 /* retrieve the network address corresponding to 'host' */
2884 memset(&hints
, 0, sizeof(struct addrinfo
));
2885 hints
.ai_family
= PF_UNSPEC
;
2886 hints
.ai_socktype
= SOCK_STREAM
;
2888 retval
= getaddrinfo(host
, "0", &hints
, &addrinfo
);
2891 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "getaddrinfo() %s", gai_strerror(retval
));
2900 if (sock_cmpaddr(&temp
->host
, (struct sockaddr_storage
*) ai_next
->ai_addr
) == 0)
2902 struct rpcap_header header
;
2904 /* Close this connection */
2905 rpcap_createhdr(&header
, RPCAP_MSG_CLOSE
, 0, 0);
2907 /* I don't check for errors, since I'm going to close everything */
2908 sock_send(temp
->sockctrl
, (char *)&header
, sizeof(struct rpcap_header
), errbuf
, PCAP_ERRBUF_SIZE
);
2910 if (sock_close(temp
->sockctrl
, errbuf
, PCAP_ERRBUF_SIZE
))
2912 /* To avoid inconsistencies in the number of sock_init() */
2919 prev
->next
= temp
->next
;
2921 activeHosts
= temp
->next
;
2923 freeaddrinfo(addrinfo
);
2927 /* To avoid inconsistencies in the number of sock_init() */
2933 ai_next
= ai_next
->ai_next
;
2940 freeaddrinfo(addrinfo
);
2942 /* To avoid inconsistencies in the number of sock_init() */
2945 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The host you want to close the active connection is not known");
2949 void pcap_remoteact_cleanup(void)
2951 /* Very dirty, but it works */
2954 closesocket(sockmain
);
2956 /* To avoid inconsistencies in the number of sock_init() */
2962 int pcap_remoteact_list(char *hostlist
, char sep
, int size
, char *errbuf
)
2964 struct activehosts
*temp
; /* temp var needed to scan the host list chain */
2966 char hoststr
[RPCAP_HOSTLIST_SIZE
+ 1];
2975 /*int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen) */
2977 /* Get the numeric form of the name of the connecting host */
2978 if (sock_getascii_addrport((struct sockaddr_storage
*) &temp
->host
, hoststr
,
2979 RPCAP_HOSTLIST_SIZE
, NULL
, 0, NI_NUMERICHOST
, errbuf
, PCAP_ERRBUF_SIZE
) != -1)
2980 /* if (getnameinfo( (struct sockaddr *) &temp->host, sizeof (struct sockaddr_storage), hoststr, */
2981 /* RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST) ) */
2983 /* sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); */
2987 len
= len
+ strlen(hoststr
) + 1 /* the separator */;
2989 if ((size
< 0) || (len
>= (size_t)size
))
2991 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "The string you provided is not able to keep "
2992 "the hostnames for all the active connections");
2996 strlcat(hostlist
, hoststr
, PCAP_ERRBUF_SIZE
);
2997 hostlist
[len
- 1] = sep
;