]> The Tcpdump Group git mirrors - libpcap/blob - pcap-rpcap.c
Get rid of an unused variable.
[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 <string.h> /* for strlen(), ... */
39 #include <stdlib.h> /* for malloc(), free(), ... */
40 #include <stdarg.h> /* for functions with variable number of arguments */
41 #include <errno.h> /* for the errno variable */
42 #include "pcap-int.h"
43 #include "pcap-rpcap.h"
44 #include "sockutils.h"
45
46 /*
47 * \file pcap-rpcap.c
48 *
49 * This file keeps all the new funtions that are needed for the RPCAP protocol.
50 * Almost all the pcap functions need to be modified in order to become compatible
51 * with the RPCAP protocol. However, you can find here only the ones that are completely new.
52 *
53 * This file keeps also the functions that are 'private', i.e. are needed by the RPCAP
54 * protocol but are not exported to the user.
55 *
56 * \warning All the RPCAP functions that are allowed to return a buffer containing
57 * the error description can return max PCAP_ERRBUF_SIZE characters.
58 * However there is no guarantees that the string will be zero-terminated.
59 * Best practice is to define the errbuf variable as a char of size 'PCAP_ERRBUF_SIZE+1'
60 * and to insert manually a NULL character at the end of the buffer. This will
61 * guarantee that no buffer overflows occur even if we use the printf() to show
62 * the error on the screen.
63 */
64
65 #define PCAP_STATS_STANDARD 0 /* Used by pcap_stats_remote to see if we want standard or extended statistics */
66 #define PCAP_STATS_EX 1 /* Used by pcap_stats_remote to see if we want standard or extended statistics */
67
68 /* Keeps a list of all the opened connections in the active mode. */
69 struct activehosts *activeHosts;
70
71 /*
72 * Private data for capturing on WinPcap devices.
73 */
74 struct pcap_win {
75 int nonblock;
76 int rfmon_selfstart; /* a flag tells whether the monitor mode is set by itself */
77 int filtering_in_kernel; /* using kernel filter */
78
79 #ifdef HAVE_DAG_API
80 int dag_fcs_bits; /* Number of checksum bits from link layer */
81 #endif
82 };
83
84 /****************************************************
85 * *
86 * Locally defined functions *
87 * *
88 ****************************************************/
89 static int rpcap_checkver(SOCKET sock, struct rpcap_header *header, char *errbuf);
90 static struct pcap_stat *rpcap_stats_remote(pcap_t *p, struct pcap_stat *ps, int mode);
91 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog);
92 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog);
93 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog);
94 static int pcap_setfilter_remote(pcap_t *fp, struct bpf_program *prog);
95 static int pcap_setsampling_remote(pcap_t *p);
96
97
98 /****************************************************
99 * *
100 * Function bodies *
101 * *
102 ****************************************************/
103
104 /*
105 * \ingroup remote_pri_func
106 *
107 * \brief It traslates (i.e. de-serializes) a 'sockaddr_storage' structure from
108 * the network byte order to the host byte order.
109 *
110 * It accepts a 'sockaddr_storage' structure as it is received from the network and it
111 * converts it into the host byte order (by means of a set of ntoh() ).
112 * The function will allocate the 'sockaddrout' variable according to the address family
113 * in use. In case the address does not belong to the AF_INET nor AF_INET6 families,
114 * 'sockaddrout' is not allocated and a NULL pointer is returned.
115 * This usually happens because that address does not exist on the other host, so the
116 * RPCAP daemon sent a 'sockaddr_storage' structure containing all 'zero' values.
117 *
118 * \param sockaddrin: a 'sockaddr_storage' pointer to the variable that has to be
119 * de-serialized.
120 *
121 * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
122 * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
123 * This variable will be allocated automatically inside this function.
124 *
125 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
126 * that will contain the error message (in case there is one).
127 *
128 * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
129 * can be only the fact that the malloc() failed to allocate memory.
130 * The error message is returned in the 'errbuf' variable, while the deserialized address
131 * is returned into the 'sockaddrout' variable.
132 *
133 * \warning This function supports only AF_INET and AF_INET6 address families.
134 *
135 * \warning The sockaddrout (if not NULL) must be deallocated by the user.
136 */
137 int rpcap_deseraddr(struct sockaddr_storage *sockaddrin, struct sockaddr_storage **sockaddrout, char *errbuf)
138 {
139 /* Warning: we support only AF_INET and AF_INET6 */
140 if (ntohs(sockaddrin->ss_family) == AF_INET)
141 {
142 struct sockaddr_in *sockaddr;
143
144 sockaddr = (struct sockaddr_in *) sockaddrin;
145 sockaddr->sin_family = ntohs(sockaddr->sin_family);
146 sockaddr->sin_port = ntohs(sockaddr->sin_port);
147
148 (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in));
149 if ((*sockaddrout) == NULL)
150 {
151 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
152 return -1;
153 }
154 memcpy(*sockaddrout, sockaddr, sizeof(struct sockaddr_in));
155 return 0;
156 }
157 if (ntohs(sockaddrin->ss_family) == AF_INET6)
158 {
159 struct sockaddr_in6 *sockaddr;
160
161 sockaddr = (struct sockaddr_in6 *) sockaddrin;
162 sockaddr->sin6_family = ntohs(sockaddr->sin6_family);
163 sockaddr->sin6_port = ntohs(sockaddr->sin6_port);
164 sockaddr->sin6_flowinfo = ntohl(sockaddr->sin6_flowinfo);
165 sockaddr->sin6_scope_id = ntohl(sockaddr->sin6_scope_id);
166
167 (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in6));
168 if ((*sockaddrout) == NULL)
169 {
170 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno));
171 return -1;
172 }
173 memcpy(*sockaddrout, sockaddr, sizeof(struct sockaddr_in6));
174 return 0;
175 }
176
177 /* It is neither AF_INET nor AF_INET6 */
178 *sockaddrout = NULL;
179 return 0;
180 }
181
182 /* \ingroup remote_pri_func
183 *
184 * \brief It reads a packet from the network socket. This does not make use of
185 * callback (hence the "nocb" string into its name).
186 *
187 * This function is called by the several pcap_next_ex() when they detect that
188 * we have a remote capture and they are the client side. In that case, they need
189 * to read packets from the socket.
190 *
191 * Parameters and return values are exactly the same of the pcap_next_ex().
192 *
193 * \warning By choice, this function does not make use of semaphores. A smarter
194 * implementation should put a semaphore into the data thread, and a signal will
195 * be raised as soon as there is data into the socket buffer.
196 * However this is complicated and it does not bring any advantages when reading
197 * from the network, in which network delays can be much more important than
198 * these optimizations. Therefore, we chose the following approach:
199 * - the 'timeout' chosen by the user is split in two (half on the server side,
200 * with the usual meaning, and half on the client side)
201 * - this function checks for packets; if there are no packets, it waits for
202 * timeout/2 and then it checks again. If packets are still missing, it returns,
203 * otherwise it reads packets.
204 */
205 static int pcap_read_nocb_remote(pcap_t *p, struct pcap_pkthdr **pkt_header, u_char **pkt_data)
206 {
207 struct rpcap_header *header; /* general header according to the RPCAP format */
208 struct rpcap_pkthdr *net_pkt_header; /* header of the packet */
209 char netbuf[RPCAP_NETBUF_SIZE]; /* size of the network buffer in which the packet is copied, just for UDP */
210 uint32 totread; /* number of bytes (of payload) currently read from the network (referred to the current pkt) */
211 int nread;
212 int retval; /* generic return value */
213
214 /* Structures needed for the select() call */
215 fd_set rfds; /* set of socket descriptors we have to check */
216 struct timeval tv; /* maximum time the select() can block waiting for data */
217 struct pcap_md *md; /* structure used when doing a remote live capture */
218
219 md = (struct pcap_md *) ((u_char*)p->priv + sizeof(struct pcap_win));
220
221 /*
222 * Define the read timeout, to be used in the select()
223 * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
224 */
225 tv.tv_sec = p->opt.timeout / 1000;
226 tv.tv_usec = (p->opt.timeout - tv.tv_sec * 1000) * 1000;
227
228 /* Watch out sockdata to see if it has input */
229 FD_ZERO(&rfds);
230
231 /*
232 * 'fp->rmt_sockdata' has always to be set before calling the select(),
233 * since it is cleared by the select()
234 */
235 FD_SET(md->rmt_sockdata, &rfds);
236
237 retval = select((int) md->rmt_sockdata + 1, &rfds, NULL, NULL, &tv);
238 if (retval == -1)
239 {
240 sock_geterror("select(): ", p->errbuf, PCAP_ERRBUF_SIZE);
241 return -1;
242 }
243
244 /* There is no data waiting, so return '0' */
245 if (retval == 0)
246 return 0;
247
248 /*
249 * data is here; so, let's copy it into the user buffer.
250 * I'm going to read a new packet; so I reset the number of bytes (payload only) read
251 */
252 totread = 0;
253
254 /*
255 * We have to define 'header' as a pointer to a larger buffer,
256 * because in case of UDP we have to read all the message within a single call
257 */
258 header = (struct rpcap_header *) netbuf;
259 net_pkt_header = (struct rpcap_pkthdr *) (netbuf + sizeof(struct rpcap_header));
260
261 if (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
262 {
263 /* Read the entire message from the network */
264 if (sock_recv(md->rmt_sockdata, netbuf, RPCAP_NETBUF_SIZE, SOCK_RECEIVEALL_NO, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
265 return -1;
266 }
267 else
268 {
269 if (sock_recv(md->rmt_sockdata, netbuf, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
270 return -1;
271 }
272
273 /* Checks if the message is correct */
274 retval = rpcap_checkmsg(p->errbuf, md->rmt_sockdata, header, RPCAP_MSG_PACKET, 0);
275
276 if (retval != RPCAP_MSG_PACKET) /* the message is not the one expected */
277 {
278 switch (retval)
279 {
280 case -3: /* Unrecoverable network error */
281 return -1; /* Do nothing; just exit from here; the error code is already into the errbuf */
282
283 case -2: /* The other endpoint sent a message that is not allowed here */
284 case -1: /* The other endpoint has a version number that is not compatible with our */
285 return 0; /* Return 'no packets received' */
286
287 default:
288 SOCK_ASSERT("Internal error", 1);
289 return 0; /* Return 'no packets received' */
290 }
291 }
292
293 /* In case of TCP, read the remaining of the packet from the socket */
294 if (!(md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
295 {
296 /* Read the RPCAP packet header from the network */
297 nread = sock_recv(md->rmt_sockdata, (char *)net_pkt_header,
298 sizeof(struct rpcap_pkthdr), SOCK_RECEIVEALL_YES,
299 p->errbuf, PCAP_ERRBUF_SIZE);
300 if (nread == -1)
301 return -1;
302 totread += nread;
303 }
304
305 if ((ntohl(net_pkt_header->caplen) + sizeof(struct pcap_pkthdr)) <= p->bufsize)
306 {
307 /* Initialize returned structures */
308 *pkt_header = (struct pcap_pkthdr *) p->buffer;
309 *pkt_data = (u_char*)p->buffer + sizeof(struct pcap_pkthdr);
310
311 (*pkt_header)->caplen = ntohl(net_pkt_header->caplen);
312 (*pkt_header)->len = ntohl(net_pkt_header->len);
313 (*pkt_header)->ts.tv_sec = ntohl(net_pkt_header->timestamp_sec);
314 (*pkt_header)->ts.tv_usec = ntohl(net_pkt_header->timestamp_usec);
315
316 /*
317 * I don't update the counter of the packets dropped by the network since we're using TCP,
318 * therefore no packets are dropped. Just update the number of packets received correctly
319 */
320 md->TotCapt++;
321
322 /* Copies the packet into the data buffer */
323 if (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
324 {
325 unsigned int npkt;
326
327 /*
328 * In case of UDP the packet has already been read, we have to copy it into 'buffer'.
329 * Another option should be to declare 'netbuf' as 'static'. However this prevents
330 * using several pcap instances within the same process (because the static buffer is shared among
331 * all processes)
332 */
333 memcpy(*pkt_data, netbuf + sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr), (*pkt_header)->caplen);
334
335 /* We're using UDP, so we need to update the counter of the packets dropped by the network */
336 npkt = ntohl(net_pkt_header->npkt);
337
338 if (md->TotCapt != npkt)
339 {
340 md->TotNetDrops += (npkt - md->TotCapt);
341 md->TotCapt = npkt;
342 }
343
344 }
345 else
346 {
347 /* In case of TCP, read the remaining of the packet from the socket */
348 nread = sock_recv(md->rmt_sockdata, *pkt_data,
349 (*pkt_header)->caplen, SOCK_RECEIVEALL_YES,
350 p->errbuf, PCAP_ERRBUF_SIZE);
351 if (nread == -1)
352 return -1;
353 totread += nread;
354
355 /* Checks if all the data has been read; if not, discard the data in excess */
356 /* This check has to be done only on TCP connections */
357 if (totread != ntohl(header->plen))
358 sock_discard(md->rmt_sockdata, ntohl(header->plen) - totread, NULL, 0);
359 }
360
361
362 /* Packet read successfully */
363 return 1;
364 }
365 else
366 {
367 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Received a packet that is larger than the internal buffer size.");
368 return -1;
369 }
370
371 }
372
373 /* \ingroup remote_pri_func
374 *
375 * \brief It reads a packet from the network socket.
376 *
377 * This function is called by the several pcap_read() when they detect that
378 * we have a remote capture and they are the client side. In that case, they need
379 * to read packets from the socket.
380 *
381 * This function relies on the pcap_read_nocb_remote to deliver packets. The
382 * difference, here, is that as soon as a packet is read, it is delivered
383 * to the application by means of a callback function.
384 *
385 * Parameters and return values are exactly the same of the pcap_read().
386 */
387 static int pcap_read_remote(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
388 {
389 struct pcap_pkthdr *pkt_header;
390 u_char *pkt_data;
391 int n = 0;
392
393 while ((n < cnt) || (cnt < 0))
394 {
395 if (pcap_read_nocb_remote(p, &pkt_header, &pkt_data) == 1)
396 {
397 (*callback)(user, pkt_header, pkt_data);
398 n++;
399 }
400 else
401 return n;
402 }
403 return n;
404 }
405
406 /* \ingroup remote_pri_func
407 *
408 * \brief It sends a CLOSE command to the capture server.
409 *
410 * This function is called when the user wants to close a pcap_t adapter.
411 * In case we're capturing from the network, it sends a command to the other
412 * peer that says 'ok, let's stop capturing'.
413 * This function is called automatically when the user calls the pcap_close().
414 *
415 * Parameters and return values are exactly the same of the pcap_close().
416 *
417 * \warning Since we're closing the connection, we do not check for errors.
418 */
419 static void pcap_cleanup_remote(pcap_t *fp)
420 {
421 struct rpcap_header header; /* header of the RPCAP packet */
422 struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
423 int active = 0; /* active mode or not? */
424 struct pcap_md *md; /* structure used when doing a remote live capture */
425
426 md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
427
428 /* detect if we're in active mode */
429 temp = activeHosts;
430 while (temp)
431 {
432 if (temp->sockctrl == md->rmt_sockctrl)
433 {
434 active = 1;
435 break;
436 }
437 temp = temp->next;
438 }
439
440 if (!active)
441 {
442 rpcap_createhdr(&header, RPCAP_MSG_CLOSE, 0, 0);
443
444 /* I don't check for errors, since I'm going to close everything */
445 sock_send(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), NULL, 0);
446 }
447 else
448 {
449 rpcap_createhdr(&header, RPCAP_MSG_ENDCAP_REQ, 0, 0);
450
451 /* I don't check for errors, since I'm going to close everything */
452 sock_send(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), NULL, 0);
453
454 /* wait for the answer */
455 /* Don't check what we got, since the present libpcap does not uses this pcap_t anymore */
456 sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, NULL, 0);
457
458 if (ntohl(header.plen) != 0)
459 sock_discard(md->rmt_sockctrl, ntohl(header.plen), NULL, 0);
460 }
461
462 if (md->rmt_sockdata)
463 {
464 sock_close(md->rmt_sockdata, NULL, 0);
465 md->rmt_sockdata = 0;
466 }
467
468 if ((!active) && (md->rmt_sockctrl))
469 sock_close(md->rmt_sockctrl, NULL, 0);
470
471 md->rmt_sockctrl = 0;
472
473 if (md->currentfilter)
474 {
475 free(md->currentfilter);
476 md->currentfilter = NULL;
477 }
478
479 /* To avoid inconsistencies in the number of sock_init() */
480 sock_cleanup();
481 }
482
483 /* \ingroup remote_pri_func
484 *
485 * \brief It retrieves network statistics from the other peer.
486 *
487 * This function is just a void cointainer, since the work is done by the rpcap_stats_remote().
488 * See that funcion for more details.
489 *
490 * Parameters and return values are exactly the same of the pcap_stats().
491 */
492 static int pcap_stats_remote(pcap_t *p, struct pcap_stat *ps)
493 {
494 struct pcap_stat *retval;
495
496 retval = rpcap_stats_remote(p, ps, PCAP_STATS_STANDARD);
497
498 if (retval)
499 return 0;
500 else
501 return -1;
502 }
503
504 #ifdef _WIN32
505 /* \ingroup remote_pri_func
506 *
507 * \brief It retrieves network statistics from the other peer.
508 *
509 * This function is just a void cointainer, since the work is done by the rpcap_stats_remote().
510 * See that funcion for more details.
511 *
512 * Parameters and return values are exactly the same of the pcap_stats_ex().
513 */
514 static struct pcap_stat *pcap_stats_ex_remote(pcap_t *p, int *pcap_stat_size)
515 {
516 *pcap_stat_size = sizeof (p->stat);
517
518 /* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
519 return (rpcap_stats_remote(p, &(p->stat), PCAP_STATS_EX));
520 }
521 #endif
522
523 /* \ingroup remote_pri_func
524 *
525 * \brief It retrieves network statistics from the other peer.
526 *
527 * This function can be called in two modes:
528 * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e. the pcap_stats() )
529 * - PCAP_STATS_EX: if we want extended statistics (i.e. the pcap_stats_ex() )
530 *
531 * This 'mode' parameter is needed because in the standard pcap_stats() the variable that keeps the
532 * statistics is allocated by the user. Unfortunately, this structure has been extended in order
533 * to keep new stats. However, if the user has a smaller structure and it passes it to the pcap_stats,
534 * thid function will try to fill in more data than the size of the structure, so that the application
535 * goes in memory overflow.
536 * So, we need to know it we have to copy just the standard fields, or the extended fields as well.
537 *
538 * In case we want to copy the extended fields as well, the problem of memory overflow does no
539 * longer exist because the structure pcap_stat is no longer allocated by the program;
540 * it is allocated by the library instead.
541 *
542 * \param p: the pcap_t structure related to the current instance.
543 *
544 * \param ps: a 'pcap_stat' structure, needed for compatibility with pcap_stat(), in which
545 * the structure is allocated by the user. In case of pcap_stats_ex, this structure and the
546 * function return value point to the same variable.
547 *
548 * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
549 *
550 * \return The structure that keeps the statistics, or NULL in case of error.
551 * The error string is placed in the pcap_t structure.
552 */
553 static struct pcap_stat *rpcap_stats_remote(pcap_t *p, struct pcap_stat *ps, int mode)
554 {
555 struct rpcap_header header; /* header of the RPCAP packet */
556 struct rpcap_stats netstats; /* statistics sent on the network */
557 uint32 totread = 0; /* number of bytes of the payload read from the socket */
558 int nread;
559 int retval; /* temp variable which stores functions return value */
560 struct pcap_md *md; /* structure used when doing a remote live capture */
561
562 md = (struct pcap_md *) ((u_char*)p->priv + sizeof(struct pcap_win));
563
564 /*
565 * If the capture has still to start, we cannot ask statistics to the other peer,
566 * so we return a fake number
567 */
568 if (!md->rmt_capstarted)
569 {
570 ps->ps_drop = 0;
571 ps->ps_ifdrop = 0;
572 ps->ps_recv = 0;
573 #if defined(_WIN32) && defined(HAVE_REMOTE)
574 if (mode == PCAP_STATS_EX)
575 {
576 ps->ps_capt = 0;
577 ps->ps_sent = 0;
578 ps->ps_netdrop = 0;
579 }
580 #endif /* _WIN32 && HAVE_REMOTE */
581
582 return ps;
583 }
584
585 rpcap_createhdr(&header, RPCAP_MSG_STATS_REQ, 0, 0);
586
587 /* Send the PCAP_STATS command */
588 if (sock_send(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), p->errbuf, PCAP_ERRBUF_SIZE))
589 goto error;
590
591 /* Receive the RPCAP stats reply message */
592 if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
593 goto error;
594
595 /* Checks if the message is correct */
596 retval = rpcap_checkmsg(p->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_STATS_REPLY, RPCAP_MSG_ERROR, 0);
597
598 if (retval != RPCAP_MSG_STATS_REPLY) /* the message is not the one expected */
599 {
600 switch (retval)
601 {
602 case -3: /* Unrecoverable network error */
603 case -2: /* The other endpoint send a message that is not allowed here */
604 case -1: /* The other endpoint has a version number that is not compatible with our */
605 goto error;
606
607 case RPCAP_MSG_ERROR: /* The other endpoint reported an error */
608 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
609 totread = ntohl(header.plen);
610
611 /* Do nothing; just exit; the error code is already into the errbuf */
612 goto error;
613
614 default:
615 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
616 goto error;
617 }
618 }
619
620 nread = sock_recv(md->rmt_sockctrl, (char *)&netstats,
621 sizeof(struct rpcap_stats), SOCK_RECEIVEALL_YES,
622 p->errbuf, PCAP_ERRBUF_SIZE);
623 if (nread == -1)
624 goto error;
625 totread += nread;
626
627 ps->ps_drop = ntohl(netstats.krnldrop);
628 ps->ps_ifdrop = ntohl(netstats.ifdrop);
629 ps->ps_recv = ntohl(netstats.ifrecv);
630 #if defined(_WIN32) && defined(HAVE_REMOTE)
631 if (mode == PCAP_STATS_EX)
632 {
633 ps->ps_capt = md->TotCapt;
634 ps->ps_netdrop = md->TotNetDrops;
635 ps->ps_sent = ntohl(netstats.svrcapt);
636 }
637 #endif /* _WIN32 && HAVE_REMOTE */
638
639 /* Checks if all the data has been read; if not, discard the data in excess */
640 if (totread != ntohl(header.plen))
641 {
642 if (sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
643 goto error;
644 }
645
646 return ps;
647
648 error:
649 if (totread != ntohl(header.plen))
650 sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0);
651
652 return NULL;
653 }
654
655 /* \ingroup remote_pri_func
656 *
657 * \brief It opens a remote adapter by opening an RPCAP connection and so on.
658 *
659 * This function does basically the job of pcap_open_live() for a remote interface.
660 * In other words, we have a pcap_read for win32, which reads packets from NPF,
661 * another for LINUX, and so on. Now, we have a pcap_opensource_remote() as well.
662 * The difference, here, is the capture thread does not start until the
663 * pcap_startcapture_remote() is called.
664 *
665 * This is because, in remote capture, we cannot start capturing data as soon ad the
666 * 'open adapter' command is sent. Suppose the remote adapter is already overloaded;
667 * if we start a capture (which, by default, has a NULL filter) the new traffic can
668 * saturate the network.
669 *
670 * Instead, we want to "open" the adapter, then send a "start capture" command only
671 * when we're ready to start the capture.
672 * This funtion does this job: it sends a "open adapter" command (according to the
673 * RPCAP protocol), but it does not start the capture.
674 *
675 * Since the other libpcap functions do not share this way of life, we have to make
676 * some dirty things in order to make everyting working.
677 *
678 * \param fp: A pointer to a pcap_t structure that has been previously created with
679 * \ref pcap_create().
680 * \param source: see pcap_open().
681 * \param auth: see pcap_open().
682 *
683 * \return 0 in case of success, -1 otherwise. In case of success, the pcap_t pointer in fp can be
684 * used as a parameter to the following calls (pcap_compile() and so on). In case of
685 * problems, fp->errbuf contains a text explanation of error.
686 *
687 * \warning In case we call the pcap_compile() and the capture is not started, the filter
688 * will be saved into the pcap_t structure, and it will be sent to the other host later
689 * (when the pcap_startcapture_remote() is called).
690 */
691 int pcap_opensource_remote(pcap_t *fp, struct pcap_rmtauth *auth)
692 {
693 char host[PCAP_BUF_SIZE], ctrlport[PCAP_BUF_SIZE], iface[PCAP_BUF_SIZE];
694
695 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
696 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
697 uint32 totread = 0; /* number of bytes of the payload read from the socket */
698 int nread;
699 int retval; /* store the return value of the functions */
700 int active = 0; /* '1' if we're in active mode */
701
702 /* socket-related variables */
703 struct addrinfo hints; /* temp, needed to open a socket connection */
704 struct addrinfo *addrinfo; /* temp, needed to open a socket connection */
705 SOCKET sockctrl = 0; /* socket descriptor of the control connection */
706
707 /* RPCAP-related variables */
708 struct rpcap_header header; /* header of the RPCAP packet */
709 struct rpcap_openreply openreply; /* open reply message */
710
711 struct pcap_md *md; /* structure used when doing a remote live capture */
712
713 md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
714
715
716 /*
717 * determine the type of the source (NULL, file, local, remote)
718 * You must have a valid source string even if we're in active mode, because otherwise
719 * the call to the following function will fail.
720 */
721 if (pcap_parsesrcstr(fp->opt.device, &retval, host, ctrlport, iface, fp->errbuf) == -1)
722 return -1;
723
724 if (retval != PCAP_SRC_IFREMOTE)
725 {
726 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "This function is able to open only remote interfaces");
727 return -1;
728 }
729
730 addrinfo = NULL;
731
732 /*
733 * Warning: this call can be the first one called by the user.
734 * For this reason, we have to initialize the WinSock support.
735 */
736 if (sock_init(fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
737 return -1;
738
739 sockctrl = rpcap_remoteact_getsock(host, &active, fp->errbuf);
740 if (sockctrl == INVALID_SOCKET)
741 return -1;
742
743 if (!active)
744 {
745 /*
746 * We're not in active mode; let's try to open a new
747 * control connection.
748 */
749 memset(&hints, 0, sizeof(struct addrinfo));
750 hints.ai_family = PF_UNSPEC;
751 hints.ai_socktype = SOCK_STREAM;
752
753 if ((ctrlport == NULL) || (ctrlport[0] == 0))
754 {
755 /* the user chose not to specify the port */
756 if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
757 return -1;
758 }
759 else
760 {
761 /* the user chose not to specify the port */
762 if (sock_initaddress(host, ctrlport, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
763 return -1;
764 }
765
766 if ((sockctrl = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
767 goto error;
768
769 freeaddrinfo(addrinfo);
770 addrinfo = NULL;
771
772 if (rpcap_sendauth(sockctrl, auth, fp->errbuf) == -1)
773 goto error;
774 }
775
776 /*
777 * Now it's time to start playing with the RPCAP protocol
778 * RPCAP open command: create the request message
779 */
780 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
781 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
782 goto error;
783
784 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_OPEN_REQ, 0, (uint32) strlen(iface));
785
786 if (sock_bufferize(iface, (int) strlen(iface), sendbuf, &sendbufidx,
787 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, fp->errbuf, PCAP_ERRBUF_SIZE))
788 goto error;
789
790 if (sock_send(sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
791 goto error;
792
793 /* Receive the RPCAP open reply message */
794 if (sock_recv(sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
795 goto error;
796
797 /* Checks if the message is correct */
798 retval = rpcap_checkmsg(fp->errbuf, sockctrl, &header, RPCAP_MSG_OPEN_REPLY, RPCAP_MSG_ERROR, 0);
799
800 if (retval != RPCAP_MSG_OPEN_REPLY) /* the message is not the one expected */
801 {
802 switch (retval)
803 {
804 case -3: /* Unrecoverable network error */
805 case -2: /* The other endpoint send a message that is not allowed here */
806 case -1: /* The other endpoint has a version number that is not compatible with our */
807 goto error;
808
809 case RPCAP_MSG_ERROR: /* The other endpoint reported an error */
810 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
811 totread = ntohl(header.plen);
812 /* Do nothing; just exit; the error code is already into the errbuf */
813 goto error;
814
815 default:
816 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
817 goto error;
818 }
819 }
820
821 nread = sock_recv(sockctrl, (char *)&openreply,
822 sizeof(struct rpcap_openreply), SOCK_RECEIVEALL_YES,
823 fp->errbuf, PCAP_ERRBUF_SIZE);
824 if (nread == -1)
825 goto error;
826 totread += nread;
827
828 /* Set proper fields into the pcap_t struct */
829 fp->linktype = ntohl(openreply.linktype);
830 fp->tzoff = ntohl(openreply.tzoff);
831 md->rmt_sockctrl = sockctrl;
832 md->rmt_clientside = 1;
833
834
835 /* This code is duplicated from the end of this function */
836 fp->read_op = pcap_read_remote;
837 fp->setfilter_op = pcap_setfilter_remote;
838 fp->getnonblock_op = NULL; /* This is not implemented in remote capture */
839 fp->setnonblock_op = NULL; /* This is not implemented in remote capture */
840 fp->stats_op = pcap_stats_remote;
841 #ifdef _WIN32
842 fp->stats_ex_op = pcap_stats_ex_remote;
843 #endif
844 fp->cleanup_op = pcap_cleanup_remote;
845
846 /* Checks if all the data has been read; if not, discard the data in excess */
847 if (totread != ntohl(header.plen))
848 {
849 if (sock_discard(sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
850 goto error;
851 }
852 return 0;
853
854 error:
855 /*
856 * When the connection has been established, we have to close it. So, at the
857 * beginning of this function, if an error occur we return immediately with
858 * a return NULL; when the connection is established, we have to come here
859 * ('goto error;') in order to close everything properly.
860 *
861 * Checks if all the data has been read; if not, discard the data in excess
862 */
863 if (totread != ntohl(header.plen))
864 sock_discard(sockctrl, ntohl(header.plen) - totread, NULL, 0);
865
866 if (addrinfo)
867 freeaddrinfo(addrinfo);
868
869 if (!active)
870 sock_close(sockctrl, NULL, 0);
871
872 return -1;
873 }
874
875 /* \ingroup remote_pri_func
876 *
877 * \brief It starts a remote capture.
878 *
879 * This function is requires since the RPCAP protocol decouples the 'open' from the
880 * 'start capture' functions.
881 * This function takes all the parameters needed (which have been stored into the pcap_t structure)
882 * and sends them to the server.
883 * If everything is fine, it creates a new child thread that reads data from the network
884 * and puts data it into the user buffer.
885 * The pcap_read() will read data from the user buffer, as usual.
886 *
887 * The remote capture acts like a new "kernel", which puts packets directly into
888 * the buffer pointed by pcap_t.
889 * In fact, this function does not rely on a kernel that reads packets and put them
890 * into the user buffer; it has to do that on its own.
891 *
892 * \param fp: the pcap_t descriptor of the device currently open.
893 *
894 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
895 * is returned into the 'errbuf' field of the pcap_t structure.
896 */
897 int pcap_startcapture_remote(pcap_t *fp)
898 {
899 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
900 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
901 char portdata[PCAP_BUF_SIZE]; /* temp variable needed to keep the network port for the the data connection */
902 uint32 totread = 0; /* number of bytes of the payload read from the socket */
903 int nread;
904 int retval; /* store the return value of the functions */
905 int active = 0; /* '1' if we're in active mode */
906 struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
907 char host[INET6_ADDRSTRLEN + 1]; /* numeric name of the other host */
908
909 /* socket-related variables*/
910 struct addrinfo hints; /* temp, needed to open a socket connection */
911 struct addrinfo *addrinfo; /* temp, needed to open a socket connection */
912 SOCKET sockdata = 0; /* socket descriptor of the data connection */
913 struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
914 socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
915 int ai_family; /* temp, keeps the address family used by the control connection */
916
917 /* RPCAP-related variables*/
918 struct rpcap_header header; /* header of the RPCAP packet */
919 struct rpcap_startcapreq *startcapreq; /* start capture request message */
920 struct rpcap_startcapreply startcapreply; /* start capture reply message */
921
922 /* Variables related to the buffer setting */
923 int res, itemp;
924 int sockbufsize = 0;
925
926 struct pcap_md *md; /* structure used when doing a remote live capture */
927
928 md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
929
930 /*
931 * Let's check if sampling has been required.
932 * If so, let's set it first
933 */
934 if (pcap_setsampling_remote(fp) != 0)
935 return -1;
936
937
938 /* detect if we're in active mode */
939 temp = activeHosts;
940 while (temp)
941 {
942 if (temp->sockctrl == md->rmt_sockctrl)
943 {
944 active = 1;
945 break;
946 }
947 temp = temp->next;
948 }
949
950 addrinfo = NULL;
951
952 /*
953 * Gets the complete sockaddr structure used in the ctrl connection
954 * This is needed to get the address family of the control socket
955 * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
956 * since the ctrl socket can already be open in case of active mode;
957 * so I would have to call getpeername() anyway
958 */
959 saddrlen = sizeof(struct sockaddr_storage);
960 if (getpeername(md->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
961 {
962 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
963 goto error;
964 }
965 ai_family = ((struct sockaddr_storage *) &saddr)->ss_family;
966
967 /* Get the numeric address of the remote host we are connected to */
968 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, host,
969 sizeof(host), NULL, 0, NI_NUMERICHOST))
970 {
971 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
972 goto error;
973 }
974
975 /*
976 * Data connection is opened by the server toward the client if:
977 * - we're using TCP, and the user wants us to be in active mode
978 * - we're using UDP
979 */
980 if ((active) || (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
981 {
982 /*
983 * We have to create a new socket to receive packets
984 * We have to do that immediately, since we have to tell the other
985 * end which network port we picked up
986 */
987 memset(&hints, 0, sizeof(struct addrinfo));
988 /* TEMP addrinfo is NULL in case of active */
989 hints.ai_family = ai_family; /* Use the same address family of the control socket */
990 hints.ai_socktype = (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
991 hints.ai_flags = AI_PASSIVE; /* Data connection is opened by the server toward the client */
992
993 /* Let's the server pick up a free network port for us */
994 if (sock_initaddress(NULL, "0", &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
995 goto error;
996
997 if ((sockdata = sock_open(addrinfo, SOCKOPEN_SERVER,
998 1 /* max 1 connection in queue */, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
999 goto error;
1000
1001 /* addrinfo is no longer used */
1002 freeaddrinfo(addrinfo);
1003 addrinfo = NULL;
1004
1005 /* get the complete sockaddr structure used in the data connection */
1006 saddrlen = sizeof(struct sockaddr_storage);
1007 if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1008 {
1009 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1010 goto error;
1011 }
1012
1013 /* Get the local port the system picked up */
1014 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
1015 0, portdata, sizeof(portdata), NI_NUMERICSERV))
1016 {
1017 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1018 goto error;
1019 }
1020 }
1021
1022 /*
1023 * Now it's time to start playing with the RPCAP protocol
1024 * RPCAP start capture command: create the request message
1025 */
1026 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1027 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1028 goto error;
1029
1030 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_STARTCAP_REQ, 0,
1031 sizeof(struct rpcap_startcapreq) + sizeof(struct rpcap_filter) + fp->fcode.bf_len * sizeof(struct rpcap_filterbpf_insn));
1032
1033 /* Fill the structure needed to open an adapter remotely */
1034 startcapreq = (struct rpcap_startcapreq *) &sendbuf[sendbufidx];
1035
1036 if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreq), NULL,
1037 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1038 goto error;
1039
1040 memset(startcapreq, 0, sizeof(struct rpcap_startcapreq));
1041
1042 /* By default, apply half the timeout on one side, half of the other */
1043 fp->opt.timeout = fp->opt.timeout / 2;
1044 startcapreq->read_timeout = htonl(fp->opt.timeout);
1045
1046 /* portdata on the openreq is meaningful only if we're in active mode */
1047 if ((active) || (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1048 {
1049 sscanf(portdata, "%d", (int *)&(startcapreq->portdata)); /* cast to avoid a compiler warning */
1050 startcapreq->portdata = htons(startcapreq->portdata);
1051 }
1052
1053 startcapreq->snaplen = htonl(fp->snapshot);
1054 startcapreq->flags = 0;
1055
1056 if (md->rmt_flags & PCAP_OPENFLAG_PROMISCUOUS)
1057 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_PROMISC;
1058 if (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
1059 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_DGRAM;
1060 if (active)
1061 startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN;
1062
1063 startcapreq->flags = htons(startcapreq->flags);
1064
1065 /* Pack the capture filter */
1066 if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, &fp->fcode))
1067 goto error;
1068
1069 if (sock_send(md->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
1070 goto error;
1071
1072
1073 /* Receive the RPCAP start capture reply message */
1074 if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1075 goto error;
1076
1077 /* Checks if the message is correct */
1078 retval = rpcap_checkmsg(fp->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_STARTCAP_REPLY, RPCAP_MSG_ERROR, 0);
1079
1080 if (retval != RPCAP_MSG_STARTCAP_REPLY) /* the message is not the one expected */
1081 {
1082 switch (retval)
1083 {
1084 case -3: /* Unrecoverable network error */
1085 case -2: /* The other endpoint send a message that is not allowed here */
1086 case -1: /* The other endpoint has a version number that is not compatible with our */
1087 goto error;
1088
1089 case RPCAP_MSG_ERROR: /* The other endpoint reported an error */
1090 /* Update totread, since the rpcap_checkmsg() already purged the buffer */
1091 totread = ntohl(header.plen);
1092 /* Do nothing; just exit; the error code is already into the errbuf */
1093 goto error;
1094
1095 default:
1096 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "Internal error");
1097 goto error;
1098 }
1099 }
1100
1101 nread = sock_recv(md->rmt_sockctrl, (char *)&startcapreply,
1102 sizeof(struct rpcap_startcapreply), SOCK_RECEIVEALL_YES,
1103 fp->errbuf, PCAP_ERRBUF_SIZE);
1104 if (nread == -1)
1105 goto error;
1106 totread += nread;
1107
1108 /*
1109 * In case of UDP data stream, the connection is always opened by the daemon
1110 * So, this case is already covered by the code above.
1111 * Now, we have still to handle TCP connections, because:
1112 * - if we're in active mode, we have to wait for a remote connection
1113 * - if we're in passive more, we have to start a connection
1114 *
1115 * We have to do he job in two steps because in case we're opening a TCP connection, we have
1116 * to tell the port we're using to the remote side; in case we're accepting a TCP
1117 * connection, we have to wait this info from the remote side.
1118 */
1119
1120 if (!(md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
1121 {
1122 if (!active)
1123 {
1124 memset(&hints, 0, sizeof(struct addrinfo));
1125 hints.ai_family = ai_family; /* Use the same address family of the control socket */
1126 hints.ai_socktype = (md->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
1127 pcap_snprintf(portdata, PCAP_BUF_SIZE, "%d", ntohs(startcapreply.portdata));
1128
1129 /* Let's the server pick up a free network port for us */
1130 if (sock_initaddress(host, portdata, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1131 goto error;
1132
1133 if ((sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1134 goto error;
1135
1136 /* addrinfo is no longer used */
1137 freeaddrinfo(addrinfo);
1138 addrinfo = NULL;
1139 }
1140 else
1141 {
1142 SOCKET socktemp; /* We need another socket, since we're going to accept() a connection */
1143
1144 /* Connection creation */
1145 saddrlen = sizeof(struct sockaddr_storage);
1146
1147 socktemp = accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
1148
1149 if (socktemp == -1)
1150 {
1151 sock_geterror("accept(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1152 goto error;
1153 }
1154
1155 /* Now that I accepted the connection, the server socket is no longer needed */
1156 sock_close(sockdata, fp->errbuf, PCAP_ERRBUF_SIZE);
1157 sockdata = socktemp;
1158 }
1159 }
1160
1161 /* Let's save the socket of the data connection */
1162 md->rmt_sockdata = sockdata;
1163
1164 /* Allocates WinPcap/libpcap user buffer, which is a socket buffer in case of a remote capture */
1165 /* It has the same size of the one used on the other side of the connection */
1166 fp->bufsize = ntohl(startcapreply.bufsize);
1167
1168 /* Let's get the actual size of the socket buffer */
1169 itemp = sizeof(sockbufsize);
1170
1171 res = getsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &itemp);
1172 if (res == -1)
1173 {
1174 sock_geterror("pcap_startcapture_remote()", fp->errbuf, PCAP_ERRBUF_SIZE);
1175 SOCK_ASSERT(fp->errbuf, 1);
1176 }
1177
1178 /*
1179 * Warning: on some kernels (e.g. Linux), the size of the user buffer does not take
1180 * into account the pcap_header and such, and it is set equal to the snaplen.
1181 * In my view, this is wrong (the meaning of the bufsize became a bit strange).
1182 * So, here bufsize is the whole size of the user buffer.
1183 * In case the bufsize returned is too small, let's adjust it accordingly.
1184 */
1185 if (fp->bufsize <= (u_int) fp->snapshot)
1186 fp->bufsize += sizeof(struct pcap_pkthdr);
1187
1188 /* if the current socket buffer is smaller than the desired one */
1189 if ((u_int) sockbufsize < fp->bufsize)
1190 {
1191 /* Loop until the buffer size is OK or the original socket buffer size is larger than this one */
1192 while (1)
1193 {
1194 res = setsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&(fp->bufsize), sizeof(fp->bufsize));
1195
1196 if (res == 0)
1197 break;
1198
1199 /*
1200 * If something goes wrong, half the buffer size (checking that it does not become smaller than
1201 * the current one)
1202 */
1203 fp->bufsize /= 2;
1204
1205 if ((u_int) sockbufsize >= fp->bufsize)
1206 {
1207 fp->bufsize = sockbufsize;
1208 break;
1209 }
1210 }
1211 }
1212
1213 /*
1214 * Let's allocate the packet; this is required in order to put the packet somewhere when
1215 * extracting data from the socket
1216 * Since buffering has already been done in the socket buffer, here we need just a buffer,
1217 * whose size is equal to the pcap header plus the snapshot length
1218 */
1219 fp->bufsize = fp->snapshot + sizeof(struct pcap_pkthdr);
1220
1221 fp->buffer = (u_char *)malloc(fp->bufsize);
1222 if (fp->buffer == NULL)
1223 {
1224 pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
1225 goto error;
1226 }
1227
1228
1229 /* Checks if all the data has been read; if not, discard the data in excess */
1230 if (totread != ntohl(header.plen))
1231 {
1232 if (sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0) == 1)
1233 goto error;
1234 }
1235
1236 /*
1237 * In case the user does not want to capture RPCAP packets, let's update the filter
1238 * We have to update it here (instead of sending it into the 'StartCapture' message
1239 * because when we generate the 'start capture' we do not know (yet) all the ports
1240 * we're currently using.
1241 */
1242 if (md->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1243 {
1244 struct bpf_program fcode;
1245
1246 if (pcap_createfilter_norpcappkt(fp, &fcode) == -1)
1247 goto error;
1248
1249 /* We cannot use 'pcap_setfilter_remote' because formally the capture has not been started yet */
1250 /* (the 'fp->rmt_capstarted' variable will be updated some lines below) */
1251 if (pcap_updatefilter_remote(fp, &fcode) == -1)
1252 goto error;
1253
1254 pcap_freecode(&fcode);
1255 }
1256
1257 md->rmt_capstarted = 1;
1258 return 0;
1259
1260 error:
1261 /*
1262 * When the connection has been established, we have to close it. So, at the
1263 * beginning of this function, if an error occur we return immediately with
1264 * a return NULL; when the connection is established, we have to come here
1265 * ('goto error;') in order to close everything properly.
1266 *
1267 * Checks if all the data has been read; if not, discard the data in excess
1268 */
1269 if (totread != ntohl(header.plen))
1270 sock_discard(md->rmt_sockctrl, ntohl(header.plen) - totread, NULL, 0);
1271
1272 if ((sockdata) && (sockdata != -1)) /* we can be here because sockdata said 'error' */
1273 sock_close(sockdata, NULL, 0);
1274
1275 if (!active)
1276 sock_close(md->rmt_sockctrl, NULL, 0);
1277
1278 /*
1279 * We do not have to call pcap_close() here, because this function is always called
1280 * by the user in case something bad happens
1281 */
1282 // if (fp)
1283 // {
1284 // pcap_close(fp);
1285 // fp= NULL;
1286 // }
1287
1288 return -1;
1289 }
1290
1291 /*
1292 * \brief Takes a bpf program and sends it to the other host.
1293 *
1294 * This function can be called in two cases:
1295 * - the pcap_startcapture() is called (we have to send the filter along with
1296 * the 'start capture' command)
1297 * - we want to udpate the filter during a capture (i.e. the pcap_setfilter()
1298 * is called when the capture is still on)
1299 *
1300 * This function serializes the filter into the sending buffer ('sendbuf', passed
1301 * as a parameter) and return back. It does not send anything on the network.
1302 *
1303 * \param fp: the pcap_t descriptor of the device currently opened.
1304 *
1305 * \param sendbuf: the buffer on which the serialized data has to copied.
1306 *
1307 * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
1308 *
1309 * \param prog: the bpf program we have to copy.
1310 *
1311 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1312 * is returned into the 'errbuf' field of the pcap_t structure.
1313 */
1314 static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog)
1315 {
1316 struct rpcap_filter *filter;
1317 struct rpcap_filterbpf_insn *insn;
1318 struct bpf_insn *bf_insn;
1319 struct bpf_program fake_prog; /* To be used just in case the user forgot to set a filter */
1320 unsigned int i;
1321
1322
1323 if (prog->bf_len == 0) /* No filters have been specified; so, let's apply a "fake" filter */
1324 {
1325 if (pcap_compile(fp, &fake_prog, NULL /* buffer */, 1, 0) == -1)
1326 return -1;
1327
1328 prog = &fake_prog;
1329 }
1330
1331 filter = (struct rpcap_filter *) sendbuf;
1332
1333 if (sock_bufferize(NULL, sizeof(struct rpcap_filter), NULL, sendbufidx,
1334 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1335 return -1;
1336
1337 filter->filtertype = htons(RPCAP_UPDATEFILTER_BPF);
1338 filter->nitems = htonl((int32)prog->bf_len);
1339
1340 if (sock_bufferize(NULL, prog->bf_len * sizeof(struct rpcap_filterbpf_insn),
1341 NULL, sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1342 return -1;
1343
1344 insn = (struct rpcap_filterbpf_insn *) (filter + 1);
1345 bf_insn = prog->bf_insns;
1346
1347 for (i = 0; i < prog->bf_len; i++)
1348 {
1349 insn->code = htons(bf_insn->code);
1350 insn->jf = bf_insn->jf;
1351 insn->jt = bf_insn->jt;
1352 insn->k = htonl(bf_insn->k);
1353
1354 insn++;
1355 bf_insn++;
1356 }
1357
1358 return 0;
1359 }
1360
1361 /* \ingroup remote_pri_func
1362 *
1363 * \brief Update a filter on a remote host.
1364 *
1365 * This function is called when the user wants to update a filter.
1366 * In case we're capturing from the network, it sends the filter to the other peer.
1367 * This function is *not* called automatically when the user calls the pcap_setfilter().
1368 * There will be two cases:
1369 * - the capture is already on: in this case, pcap_setfilter() calls pcap_updatefilter_remote()
1370 * - the capture has not started yet: in this case, pcap_setfilter() stores the filter into
1371 * the pcap_t structure, and then the filter is sent with the pcap_startcap().
1372 *
1373 * Parameters and return values are exactly the same of the pcap_setfilter().
1374 *
1375 * \warning This function *does not* clear the packet currently into the buffers. Therefore,
1376 * the user has to expect to receive some packets that are related to the previous filter.
1377 * If you want to discard all the packets before applying a new filter, you have to close
1378 * the current capture session and start a new one.
1379 */
1380 static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog)
1381 {
1382 int retval; /* general variable used to keep the return value of other functions */
1383 char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
1384 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1385 struct rpcap_header header; /* To keep the reply message */
1386 struct pcap_md *md; /* structure used when doing a remote live capture */
1387
1388 md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
1389
1390
1391 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1392 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
1393 return -1;
1394
1395 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_UPDATEFILTER_REQ, 0,
1396 sizeof(struct rpcap_filter) + prog->bf_len * sizeof(struct rpcap_filterbpf_insn));
1397
1398 if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, prog))
1399 return -1;
1400
1401 if (sock_send(md->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf, PCAP_ERRBUF_SIZE))
1402 return -1;
1403
1404 /* Waits for the answer */
1405 if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1406 return -1;
1407
1408 /* Checks if the message is correct */
1409 retval = rpcap_checkmsg(fp->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_UPDATEFILTER_REPLY, 0);
1410
1411 if (retval != RPCAP_MSG_UPDATEFILTER_REPLY) /* the message is not the one expected */
1412 {
1413 switch (retval)
1414 {
1415 case -3: /* Unrecoverable network error */
1416 case -2: /* The other endpoint sent a message that is not allowed here */
1417 case -1: /* The other endpoint has a version number that is not compatible with our */
1418 /* Do nothing; just exit from here; the error code is already into the errbuf */
1419 return -1;
1420
1421 default:
1422 SOCK_ASSERT("Internal error", 0);
1423 return -1;
1424 }
1425 }
1426
1427 if (ntohl(header.plen) != 0) /* the message has an unexpected size */
1428 {
1429 if (sock_discard(md->rmt_sockctrl, ntohl(header.plen), fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
1430 return -1;
1431 }
1432
1433 return 0;
1434 }
1435
1436 /*
1437 * \ingroup remote_pri_func
1438 *
1439 * \brief Send a filter to a remote host.
1440 *
1441 * This function is called when the user wants to set a filter.
1442 * In case we're capturing from the network, it sends the filter to the other peer.
1443 * This function is called automatically when the user calls the pcap_setfilter().
1444 *
1445 * Parameters and return values are exactly the same of the pcap_setfilter().
1446 */
1447 static int pcap_setfilter_remote(pcap_t *fp, struct bpf_program *prog)
1448 {
1449 struct pcap_md *md; /* structure used when doing a remote live capture */
1450
1451 md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
1452
1453 if (!md->rmt_capstarted)
1454 {
1455 /* copy filter into the pcap_t structure */
1456 if (install_bpf_program(fp, prog) == -1)
1457 return -1;
1458 return 0;
1459 }
1460
1461 /* we have to update a filter during run-time */
1462 if (pcap_updatefilter_remote(fp, prog))
1463 return -1;
1464
1465 return 0;
1466 }
1467
1468 /*
1469 * \ingroup remote_pri_func
1470 *
1471 * \brief Update the current filter in order not to capture rpcap packets.
1472 *
1473 * This function is called *only* when the user wants exclude RPCAP packets
1474 * related to the current session from the captured packets.
1475 *
1476 * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
1477 * is returned into the 'errbuf' field of the pcap_t structure.
1478 */
1479 static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog)
1480 {
1481 int RetVal = 0;
1482 struct pcap_md *md; /* structure used when doing a remote live capture */
1483
1484 md = (struct pcap_md *) ((u_char*)fp->priv + sizeof(struct pcap_win));
1485
1486 /* We do not want to capture our RPCAP traffic. So, let's update the filter */
1487 if (md->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
1488 {
1489 struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
1490 socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
1491 char myaddress[128];
1492 char myctrlport[128];
1493 char mydataport[128];
1494 char peeraddress[128];
1495 char peerctrlport[128];
1496 char *newfilter;
1497 const int newstringsize = 1024;
1498 size_t currentfiltersize;
1499
1500 /* Get the name/port of the other peer */
1501 saddrlen = sizeof(struct sockaddr_storage);
1502 if (getpeername(md->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1503 {
1504 sock_geterror("getpeername(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1505 return -1;
1506 }
1507
1508 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peeraddress,
1509 sizeof(peeraddress), peerctrlport, sizeof(peerctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1510 {
1511 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1512 return -1;
1513 }
1514
1515 /* We cannot check the data port, because this is available only in case of TCP sockets */
1516 /* Get the name/port of the current host */
1517 if (getsockname(md->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
1518 {
1519 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1520 return -1;
1521 }
1522
1523 /* Get the local port the system picked up */
1524 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, myaddress,
1525 sizeof(myaddress), myctrlport, sizeof(myctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
1526 {
1527 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1528 return -1;
1529 }
1530
1531 /* Let's now check the data port */
1532 if (getsockname(md->rmt_sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1533 {
1534 sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1535 return -1;
1536 }
1537
1538 /* Get the local port the system picked up */
1539 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL, 0, mydataport, sizeof(mydataport), NI_NUMERICSERV))
1540 {
1541 sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
1542 return -1;
1543 }
1544
1545 currentfiltersize = strlen(md->currentfilter);
1546
1547 newfilter = (char *)malloc(currentfiltersize + newstringsize + 1);
1548
1549 if (currentfiltersize)
1550 {
1551 pcap_snprintf(newfilter, currentfiltersize + newstringsize,
1552 "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1553 md->currentfilter, myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
1554 }
1555 else
1556 {
1557 pcap_snprintf(newfilter, currentfiltersize + newstringsize,
1558 "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
1559 myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
1560 }
1561
1562 newfilter[currentfiltersize + newstringsize] = 0;
1563
1564 /* This is only an hack to make the pcap_compile() working properly */
1565 md->rmt_clientside = 0;
1566
1567 if (pcap_compile(fp, prog, newfilter, 1, 0) == -1)
1568 RetVal = -1;
1569
1570 /* This is only an hack to make the pcap_compile() working properly */
1571 md->rmt_clientside = 1;
1572
1573 free(newfilter);
1574 }
1575
1576 return RetVal;
1577 }
1578
1579 /*
1580 * \ingroup remote_pri_func
1581 *
1582 * \brief Set sampling parameters in the remote host.
1583 *
1584 * This function is called when the user wants to set activate sampling on the remote host.
1585 *
1586 * Sampling parameters are defined into the 'pcap_t' structure.
1587 *
1588 * \param p: the pcap_t descriptor of the device currently opened.
1589 *
1590 * \return '0' if everything is OK, '-1' is something goes wrong. The error message is returned
1591 * in the 'errbuf' member of the pcap_t structure.
1592 */
1593 static int pcap_setsampling_remote(pcap_t *p)
1594 {
1595 int retval; /* general variable used to keep the return value of other functions */
1596 char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
1597 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1598 struct rpcap_header header; /* To keep the reply message */
1599 struct rpcap_sampling *sampling_pars; /* Structure that is needed to send sampling parameters to the remote host */
1600 struct pcap_md *md; /* structure used when doing a remote live capture */
1601
1602 md = (struct pcap_md *) ((u_char*)p->priv + sizeof(struct pcap_win));
1603
1604 /* If no samping is requested, return 'ok' */
1605 if (md->rmt_samp.method == PCAP_SAMP_NOSAMP)
1606 return 0;
1607
1608 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1609 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, p->errbuf, PCAP_ERRBUF_SIZE))
1610 return -1;
1611
1612 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_SETSAMPLING_REQ, 0, sizeof(struct rpcap_sampling));
1613
1614 /* Fill the structure needed to open an adapter remotely */
1615 sampling_pars = (struct rpcap_sampling *) &sendbuf[sendbufidx];
1616
1617 if (sock_bufferize(NULL, sizeof(struct rpcap_sampling), NULL,
1618 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, p->errbuf, PCAP_ERRBUF_SIZE))
1619 return -1;
1620
1621 memset(sampling_pars, 0, sizeof(struct rpcap_sampling));
1622
1623 sampling_pars->method = md->rmt_samp.method;
1624 sampling_pars->value = htonl(md->rmt_samp.value);
1625
1626 if (sock_send(md->rmt_sockctrl, sendbuf, sendbufidx, p->errbuf, PCAP_ERRBUF_SIZE))
1627 return -1;
1628
1629 /* Waits for the answer */
1630 if (sock_recv(md->rmt_sockctrl, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, p->errbuf, PCAP_ERRBUF_SIZE) == -1)
1631 return -1;
1632
1633 /* Checks if the message is correct */
1634 retval = rpcap_checkmsg(p->errbuf, md->rmt_sockctrl, &header, RPCAP_MSG_SETSAMPLING_REPLY, 0);
1635
1636 if (retval != RPCAP_MSG_SETSAMPLING_REPLY) /* the message is not the one expected */
1637 {
1638 switch (retval)
1639 {
1640 case -3: /* Unrecoverable network error */
1641 case -2: /* The other endpoint sent a message that is not allowed here */
1642 case -1: /* The other endpoint has a version number that is not compatible with our */
1643 case RPCAP_MSG_ERROR:
1644 /* Do nothing; just exit from here; the error code is already into the errbuf */
1645 return -1;
1646
1647 default:
1648 SOCK_ASSERT("Internal error", 0);
1649 return -1;
1650 }
1651 }
1652
1653 if (ntohl(header.plen) != 0) /* the message has an unexpected size */
1654 {
1655 if (sock_discard(md->rmt_sockctrl, ntohl(header.plen), p->errbuf, PCAP_ERRBUF_SIZE) == -1)
1656 return -1;
1657 }
1658
1659 return 0;
1660
1661 }
1662
1663 /*********************************************************
1664 * *
1665 * Miscellaneous functions *
1666 * *
1667 *********************************************************/
1668
1669
1670 /* \ingroup remote_pri_func
1671 * \brief It sends a RPCAP error to the other peer.
1672 *
1673 * This function has to be called when the main program detects an error. This function
1674 * will send on the other peer the 'buffer' specified by the user.
1675 * This function *does not* request a RPCAP CLOSE connection. A CLOSE command must be sent
1676 * explicitly by the program, since we do not know it the error can be recovered in some
1677 * way or it is a non-recoverable one.
1678 *
1679 * \param sock: the socket we are currently using.
1680 *
1681 * \param error: an user-allocated (and '0' terminated) buffer that contains the error
1682 * description that has to be transmitted on the other peer. The error message cannot
1683 * be longer than PCAP_ERRBUF_SIZE.
1684 *
1685 * \param errcode: a integer which tells the other party the type of error we had;
1686 * currently is is not too much used.
1687 *
1688 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
1689 * that will contain the error message (in case there is one). It could be network problem.
1690 *
1691 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
1692 * in the 'errbuf' variable.
1693 */
1694 int rpcap_senderror(SOCKET sock, char *error, unsigned short errcode, char *errbuf)
1695 {
1696 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
1697 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1698 uint16 length;
1699
1700 length = (uint16)strlen(error);
1701
1702 if (length > PCAP_ERRBUF_SIZE)
1703 length = PCAP_ERRBUF_SIZE;
1704
1705 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_ERROR, errcode, length);
1706
1707 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1708 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1709 return -1;
1710
1711 if (sock_bufferize(error, length, sendbuf, &sendbufidx,
1712 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1713 return -1;
1714
1715 if (sock_send(sock, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE))
1716 return -1;
1717
1718 return 0;
1719 }
1720
1721 /* \ingroup remote_pri_func
1722 * \brief Sends the authentication message.
1723 *
1724 * It sends the authentication parameters on the control socket.
1725 * This function is required in order to open the connection with the other end party.
1726 *
1727 * \param sock: the socket we are currently using.
1728 *
1729 * \param auth: authentication parameters that have to be sent.
1730 *
1731 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
1732 * that will contain the error message (in case there is one). It could be network problem
1733 * of the fact that the authorization failed.
1734 *
1735 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
1736 * in the 'errbuf' variable.
1737 * The error message could be also 'the authentication failed'.
1738 */
1739 int rpcap_sendauth(SOCKET sock, struct pcap_rmtauth *auth, char *errbuf)
1740 {
1741 char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data that has to be sent is buffered */
1742 int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
1743 uint16 length; /* length of the payload of this message */
1744 struct rpcap_auth *rpauth;
1745 uint16 auth_type;
1746 struct rpcap_header header;
1747 int retval; /* temp variable which stores functions return value */
1748
1749 if (auth)
1750 {
1751 auth_type = auth->type;
1752
1753 switch (auth->type)
1754 {
1755 case RPCAP_RMTAUTH_NULL:
1756 length = sizeof(struct rpcap_auth);
1757 break;
1758
1759 case RPCAP_RMTAUTH_PWD:
1760 length = sizeof(struct rpcap_auth);
1761 if (auth->username) length += (uint16) strlen(auth->username);
1762 if (auth->password) length += (uint16) strlen(auth->password);
1763 break;
1764
1765 default:
1766 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized.");
1767 return -1;
1768 }
1769 }
1770 else
1771 {
1772 auth_type = RPCAP_RMTAUTH_NULL;
1773 length = sizeof(struct rpcap_auth);
1774 }
1775
1776
1777 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1778 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1779 return -1;
1780
1781 rpcap_createhdr((struct rpcap_header *) sendbuf, RPCAP_MSG_AUTH_REQ, 0, length);
1782
1783 rpauth = (struct rpcap_auth *) &sendbuf[sendbufidx];
1784
1785 if (sock_bufferize(NULL, sizeof(struct rpcap_auth), NULL,
1786 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
1787 return -1;
1788
1789 memset(rpauth, 0, sizeof(struct rpcap_auth));
1790
1791 rpauth->type = htons(auth_type);
1792
1793 if (auth_type == RPCAP_RMTAUTH_PWD)
1794 {
1795
1796 if (auth->username)
1797 rpauth->slen1 = (uint16) strlen(auth->username);
1798 else
1799 rpauth->slen1 = 0;
1800
1801 if (sock_bufferize(auth->username, rpauth->slen1, sendbuf,
1802 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1803 return -1;
1804
1805 if (auth->password)
1806 rpauth->slen2 = (uint16) strlen(auth->password);
1807 else
1808 rpauth->slen2 = 0;
1809
1810 if (sock_bufferize(auth->password, rpauth->slen2, sendbuf,
1811 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
1812 return -1;
1813
1814 rpauth->slen1 = htons(rpauth->slen1);
1815 rpauth->slen2 = htons(rpauth->slen2);
1816 }
1817
1818 if (sock_send(sock, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE))
1819 return -1;
1820
1821 if (sock_recv(sock, (char *)&header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1)
1822 return -1;
1823
1824 retval = rpcap_checkmsg(errbuf, sock, &header, RPCAP_MSG_AUTH_REPLY, RPCAP_MSG_ERROR, 0);
1825
1826 if (retval != RPCAP_MSG_AUTH_REPLY) /* the message is not the one expected */
1827 {
1828 switch (retval)
1829 {
1830 case -3: /* Unrecoverable network error */
1831 case -2: /* The other endpoint sent a message that is not allowed here */
1832 case -1: /* The other endpoint has a version number that is not compatible with our */
1833 /* Do nothing; just exit from here; the error code is already into the errbuf */
1834 return -1;
1835
1836 case RPCAP_MSG_ERROR:
1837 return -1;
1838
1839 default:
1840 SOCK_ASSERT("Internal error", 0);
1841 return -1;
1842 }
1843 }
1844
1845 if (ntohl(header.plen))
1846 {
1847 if (sock_discard(sock, ntohl(header.plen), errbuf, PCAP_ERRBUF_SIZE))
1848 return -1;
1849 }
1850
1851 return 0;
1852 }
1853
1854 /* \ingroup remote_pri_func
1855 * \brief Creates a structure of type rpcap_header.
1856 *
1857 * This function is provided just because the creation of an rpcap header is quite a common
1858 * task. It accepts all the values that appears into an rpcap_header, and it puts them in
1859 * place using the proper hton() calls.
1860 *
1861 * \param header: a pointer to a user-allocated buffer which will contain the serialized
1862 * header, ready to be sent on the network.
1863 *
1864 * \param type: a value (in the host by order) which will be placed into the header.type
1865 * field and that represents the type of the current message.
1866 *
1867 * \param value: a value (in the host by order) which will be placed into the header.value
1868 * field and that has a message-dependent meaning.
1869 *
1870 * \param length: a value (in the host by order) which will be placed into the header.length
1871 * field and that represents the payload length of the message.
1872 *
1873 * \return Nothing. The serialized header is returned into the 'header' variable.
1874 */
1875 void rpcap_createhdr(struct rpcap_header *header, uint8 type, uint16 value, uint32 length)
1876 {
1877 memset(header, 0, sizeof(struct rpcap_header));
1878
1879 header->ver = RPCAP_VERSION;
1880 header->type = type;
1881 header->value = htons(value);
1882 header->plen = htonl(length);
1883 }
1884
1885 /* ingroup remote_pri_func
1886 * \brief Checks if the header of the received message is correct.
1887 *
1888 * This function is a way to easily check if the message received, in a certain
1889 * state of the RPCAP protocol Finite State Machine, is valid. This function accepts,
1890 * as a parameter, the list of message types that are allowed in a certain situation,
1891 * and it returns the one which occurs.
1892 *
1893 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
1894 * that will contain the error message (in case there is one). It could be either problem
1895 * occurred inside this function (e.g. a network problem in case it tries to send an
1896 * error on the other peer and the send() call fails), an error message which has been
1897 * sent to us from the other party, or a version error (the message receive has a version
1898 * number that is incompatible with our).
1899 *
1900 * \param sock: the socket that has to be used to receive data. This function can
1901 * read data from socket in case the version contained into the message is not compatible
1902 * with our. In that case, all the message is purged from the socket, so that the following
1903 * recv() calls will return a new message.
1904 *
1905 * \param header: a pointer to and 'rpcap_header' structure that keeps the data received from
1906 * the network (still in network byte order) and that has to be checked.
1907 *
1908 * \param first: this function has a variable number of parameters. From this point on,
1909 * all the messages that are valid in this context must be passed as parameters.
1910 * The message type list must be terminated with a '0' value, the null message type,
1911 * which means 'no more types to check'. The RPCAP protocol does not define anything with
1912 * message type equal to zero, so there is no ambiguity in using this value as a list terminator.
1913 *
1914 * \return The message type of the message that has been detected. In case of errors (e.g. the
1915 * header contains a type that is not listed among the allowed types), this function will
1916 * return the following codes:
1917 * - (-1) if the version is incompatible.
1918 * - (-2) if the code is not among the one listed into the parameters list
1919 * - (-3) if a network error (connection reset, ...)
1920 * - RPCAP_MSG_ERROR if the message is an error message (it follow that the RPCAP_MSG_ERROR
1921 * could not be present in the allowed message-types list, because this function checks
1922 * for errors anyway)
1923 *
1924 * In case either the version is incompatible or nothing matches (i.e. it returns '-1' or '-2'),
1925 * it discards the message body (i.e. it reads the remaining part of the message from the
1926 * network and it discards it) so that the application is ready to receive a new message.
1927 */
1928 int rpcap_checkmsg(char *errbuf, SOCKET sock, struct rpcap_header *header, uint8 first, ...)
1929 {
1930 va_list ap;
1931 uint8 type;
1932 int32 len;
1933
1934 va_start(ap, first);
1935
1936 /* Check if the present version of the protocol can handle this message */
1937 if (rpcap_checkver(sock, header, errbuf))
1938 {
1939 SOCK_ASSERT(errbuf, 1);
1940
1941 va_end(ap);
1942 return -1;
1943 }
1944
1945 type = first;
1946
1947 while (type != 0)
1948 {
1949 /*
1950 * The message matches with one of the types listed
1951 * There is no need of conversions since both values are uint8
1952 *
1953 * Check if the other side reported an error.
1954 * If yes, it retrieves it and it returns it back to the caller
1955 */
1956 if (header->type == RPCAP_MSG_ERROR)
1957 {
1958 len = ntohl(header->plen);
1959
1960 if (len >= PCAP_ERRBUF_SIZE)
1961 {
1962 if (sock_recv(sock, errbuf, PCAP_ERRBUF_SIZE - 1, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE))
1963 return -3;
1964
1965 sock_discard(sock, len - (PCAP_ERRBUF_SIZE - 1), NULL, 0);
1966
1967 /* Put '\0' at the end of the string */
1968 errbuf[PCAP_ERRBUF_SIZE - 1] = 0;
1969 }
1970 else
1971 {
1972 if (sock_recv(sock, errbuf, len, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1)
1973 return -3;
1974
1975 /* Put '\0' at the end of the string */
1976 errbuf[len] = 0;
1977 }
1978
1979
1980 va_end(ap);
1981 return header->type;
1982 }
1983
1984 if (header->type == type)
1985 {
1986 va_end(ap);
1987 return header->type;
1988 }
1989
1990 /* get next argument */
1991 type = va_arg(ap, int);
1992 }
1993
1994 /* we already have an error, so please discard this one */
1995 sock_discard(sock, ntohl(header->plen), NULL, 0);
1996
1997 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The other endpoint sent a message that is not allowed here.");
1998 SOCK_ASSERT(errbuf, 1);
1999
2000 va_end(ap);
2001 return -2;
2002 }
2003
2004 /* \ingroup remote_pri_func
2005 * \brief Checks if the version contained into the message is compatible with
2006 * the one handled by this implementation.
2007 *
2008 * Right now, this function does not have any sophisticated task: if the versions
2009 * are different, it returns -1 and it discards the message.
2010 * It is expected that in the future this message will become more complex.
2011 *
2012 * \param sock: the socket that has to be used to receive data. This function can
2013 * read data from socket in case the version contained into the message is not compatible
2014 * with our. In that case, all the message is purged from the socket, so that the following
2015 * recv() calls will return a new (clean) message.
2016 *
2017 * \param header: a pointer to and 'rpcap_header' structure that keeps the data received from
2018 * the network (still in network byte order) and that has to be checked.
2019 *
2020 * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
2021 * that will contain the error message (in case there is one). The error message is
2022 * "incompatible version".
2023 *
2024 * \return '0' if everything is fine, '-1' if some errors occurred. The error message is returned
2025 * in the 'errbuf' variable.
2026 */
2027 static int rpcap_checkver(SOCKET sock, struct rpcap_header *header, char *errbuf)
2028 {
2029 /*
2030 * This is a sample function.
2031 *
2032 * In the real world, you have to check at the type code,
2033 * and decide accordingly.
2034 */
2035
2036 if (header->ver != RPCAP_VERSION)
2037 {
2038 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Incompatible version number: message discarded.");
2039
2040 /* we already have an error, so please discard this one */
2041 sock_discard(sock, ntohl(header->plen), NULL, 0);
2042 return -1;
2043 }
2044
2045 return 0;
2046 }
2047
2048 /* \ingroup remote_pri_func
2049 *
2050 * \brief It returns the socket currently used for this active connection
2051 * (active mode only) and provides an indication of whether this connection
2052 * is in active mode or not.
2053 *
2054 * This function is just for internal use; it returns the socket ID of the
2055 * active connection currently opened.
2056 *
2057 * \param host: a string that keeps the host name of the host for which we
2058 * want to get the socket ID for that active connection.
2059 *
2060 * \param isactive: a pointer to an int that is set to 1 if there's an
2061 * active connection to that host and 0 otherwise.
2062 *
2063 * \param errbuf: a pointer to a user-allocated buffer (of size
2064 * PCAP_ERRBUF_SIZE) that will contain the error message (in case
2065 * there is one).
2066 *
2067 * \return the socket identifier if everything is fine, '0' if this host
2068 * is not in the active host list. An indication of whether this host
2069 * is in the active host list is returned into the isactive variable.
2070 * It returns 'INVALID_SOCKET' in case of error. The error message is
2071 * returned into the errbuf variable.
2072 */
2073 SOCKET rpcap_remoteact_getsock(const char *host, int *isactive, char *errbuf)
2074 {
2075 struct activehosts *temp; /* temp var needed to scan the host list chain */
2076 struct addrinfo hints, *addrinfo, *ai_next; /* temp var needed to translate between hostname to its address */
2077 int retval;
2078
2079 /* retrieve the network address corresponding to 'host' */
2080 addrinfo = NULL;
2081 memset(&hints, 0, sizeof(struct addrinfo));
2082 hints.ai_family = PF_UNSPEC;
2083 hints.ai_socktype = SOCK_STREAM;
2084
2085 retval = getaddrinfo(host, "0", &hints, &addrinfo);
2086 if (retval != 0)
2087 {
2088 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "getaddrinfo() %s", gai_strerror(retval));
2089 *isactive = 0;
2090 return INVALID_SOCKET;
2091 }
2092
2093 temp = activeHosts;
2094
2095 while (temp)
2096 {
2097 ai_next = addrinfo;
2098 while (ai_next)
2099 {
2100 if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0) {
2101 *isactive = 1;
2102 return (temp->sockctrl);
2103 }
2104
2105 ai_next = ai_next->ai_next;
2106 }
2107 temp = temp->next;
2108 }
2109
2110 if (addrinfo)
2111 freeaddrinfo(addrinfo);
2112
2113 /*
2114 * The host for which you want to get the socket ID does not have an
2115 * active connection.
2116 */
2117 *isactive = 0;
2118 return 0;
2119 }