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