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