]> The Tcpdump Group git mirrors - libpcap/blob - rpcapd/daemon.c
Put pcap_win32_err_to_str() into fmtutils.c, and use it for all Win32 errors.
[libpcap] / rpcapd / daemon.c
1 /*
2 * Copyright (c) 2002 - 2003
3 * NetGroup, Politecnico di Torino (Italy)
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 nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
35
36 #include "ftmacros.h"
37 #include "varattrs.h"
38
39 #include <errno.h> // for the errno variable
40 #include <stdlib.h> // for malloc(), free(), ...
41 #include <string.h> // for strlen(), ...
42 #include <limits.h> // for INT_MAX
43
44 #ifdef _WIN32
45 #include <process.h> // for threads
46 #else
47 #include <unistd.h>
48 #include <pthread.h>
49 #include <sys/time.h>
50 #include <sys/types.h> // for select() and such
51 #include <pwd.h> // for password management
52 #endif
53
54 #ifdef HAVE_GETSPNAM
55 #include <shadow.h> // for password management
56 #endif
57
58 #include <pcap.h> // for libpcap/WinPcap calls
59
60 #include "fmtutils.h"
61 #include "sockutils.h" // for socket calls
62 #include "portability.h"
63 #include "rpcap-protocol.h"
64 #include "daemon.h"
65 #include "log.h"
66
67 #ifdef HAVE_OPENSSL
68 #include <openssl/ssl.h>
69 #include "sslutils.h"
70 #endif
71
72 #define RPCAP_TIMEOUT_INIT 90 /* Initial timeout for RPCAP connections (default: 90 sec) */
73 #define RPCAP_TIMEOUT_RUNTIME 180 /* Run-time timeout for RPCAP connections (default: 3 min) */
74 #define RPCAP_SUSPEND_WRONGAUTH 1 /* If the authentication is wrong, stops 1 sec before accepting a new auth message */
75
76 // Parameters for the service loop.
77 struct daemon_slpars
78 {
79 SOCKET sockctrl_in; //!< SOCKET ID of the input side of the control connection
80 SOCKET sockctrl_out; //!< SOCKET ID of the output side of the control connection
81 SSL *ssl; //!< Optional SSL handler for the controlling sockets
82 uint8 protocol_version; //!< negotiated protocol version
83 int isactive; //!< Not null if the daemon has to run in active mode
84 int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise
85 };
86
87 /*
88 * Data for a session managed by a thread.
89 */
90 struct session {
91 SOCKET sockctrl_out;
92 SOCKET sockdata;
93 SSL *ctrl_ssl, *data_ssl; // optional SSL handlers for sockctrl_out and sockdata.
94 uint8 protocol_version;
95 pcap_t *fp;
96 unsigned int TotCapt;
97 };
98
99 //
100 // Structure to refer to a thread.
101 // It includes both a Boolean indicating whether we *have* a thread,
102 // and a platform-dependent (UN*X vs. Windows) identifier for the
103 // thread; on Windows, we could use an invalid handle to indicate
104 // that we don't have a thread, but there *is* no portable "no thread"
105 // value for a pthread_t on UN*X.
106 //
107 struct thread_handle {
108 int have_thread;
109 #ifdef _WIN32
110 HANDLE thread;
111 #else
112 pthread_t thread;
113 #endif
114 };
115
116 // Locally defined functions
117 static int daemon_msg_err(SOCKET sockctrl_in, SSL *, uint32 plen);
118 static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen);
119 static int daemon_AuthUserPwd(char *username, char *password, char *errbuf);
120
121 static int daemon_msg_findallif_req(struct daemon_slpars *pars, uint32 plen);
122
123 static int daemon_msg_open_req(struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen);
124 static int daemon_msg_startcap_req(struct daemon_slpars *pars, uint32 plen, struct thread_handle *threaddata, char *source, struct session **sessionp, struct rpcap_sampling *samp_param, int uses_ssl);
125 static int daemon_msg_endcap_req(struct daemon_slpars *pars, struct session *session, struct thread_handle *threaddata);
126
127 static int daemon_msg_updatefilter_req(struct daemon_slpars *pars, struct session *session, uint32 plen);
128 static int daemon_unpackapplyfilter(SOCKET sockctrl_in, SSL *, struct session *session, uint32 *plenp, char *errbuf);
129
130 static int daemon_msg_stats_req(struct daemon_slpars *pars, struct session *session, uint32 plen, struct pcap_stat *stats, unsigned int svrcapt);
131
132 static int daemon_msg_setsampling_req(struct daemon_slpars *pars, uint32 plen, struct rpcap_sampling *samp_param);
133
134 static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout);
135 #ifdef _WIN32
136 static unsigned __stdcall daemon_thrdatamain(void *ptr);
137 #else
138 static void *daemon_thrdatamain(void *ptr);
139 #endif
140
141 static int rpcapd_recv_msg_header(SOCKET sock, SSL *, struct rpcap_header *headerp);
142 static int rpcapd_recv(SOCKET sock, SSL *, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf);
143 static int rpcapd_discard(SOCKET sock, SSL *, uint32 len);
144 static void session_close(struct session *);
145
146 int
147 daemon_serviceloop(SOCKET sockctrl_in, SOCKET sockctrl_out,
148 int isactive, char *passiveClients, int nullAuthAllowed, int uses_ssl)
149 {
150 struct daemon_slpars pars; // service loop parameters
151 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
152 char errmsgbuf[PCAP_ERRBUF_SIZE + 1]; // buffer for errors to send to the client
153 int host_port_ok;
154 SSL *ssl = NULL;
155 int nrecv;
156 struct rpcap_header header; // RPCAP message general header
157 uint32 plen; // payload length from header
158 int authenticated = 0; // 1 if the client has successfully authenticated
159 char source[PCAP_BUF_SIZE+1]; // keeps the string that contains the interface to open
160 int got_source = 0; // 1 if we've gotten the source from an open request
161 struct session *session = NULL; // struct session main variable
162 const char *msg_type_string; // string for message type
163 int client_told_us_to_close = 0; // 1 if the client told us to close the capture
164
165 struct thread_handle threaddata; // 'read from daemon and send to client' thread
166
167 // needed to save the values of the statistics
168 struct pcap_stat stats;
169 unsigned int svrcapt;
170
171 struct rpcap_sampling samp_param; // in case sampling has been requested
172
173 // Structures needed for the select() call
174 fd_set rfds; // set of socket descriptors we have to check
175 struct timeval tv; // maximum time the select() can block waiting for data
176 int retval; // select() return value
177
178 // We don't have a thread yet.
179 threaddata.have_thread = 0;
180 //
181 // We *shouldn't* have to initialize the thread indicator
182 // itself, because the compiler *should* realize that we
183 // only use this if have_thread isn't 0, but we *do* have
184 // to do it, because not all compilers *do* realize that.
185 //
186 // There is no "invalid thread handle" value for a UN*X
187 // pthread_t, so we just zero it out.
188 //
189 #ifdef _WIN32
190 threaddata.thread = INVALID_HANDLE_VALUE;
191 #else
192 memset(&threaddata.thread, 0, sizeof(threaddata.thread));
193 #endif
194
195 *errbuf = 0; // Initialize errbuf
196
197 // Set parameters structure
198 pars.sockctrl_in = sockctrl_in;
199 pars.sockctrl_out = sockctrl_out;
200 pars.protocol_version = 0; // not yet known
201 pars.isactive = isactive; // active mode
202 pars.nullAuthAllowed = nullAuthAllowed;
203
204 #ifdef HAVE_OPENSSL
205 //
206 // We have to upgrade to TLS as soon as possible, so that the
207 // whole protocol goes through the encrypted tunnel, including
208 // early error messages.
209 //
210 // Even in active mode, the other end has to initiate the TLS
211 // handshake as we still are the server as far as TLS is concerned,
212 // so we don't check isactive.
213 //
214 if (uses_ssl)
215 {
216 ssl = ssl_promotion_rw(1, pars.sockctrl_in, pars.sockctrl_out, errbuf, PCAP_ERRBUF_SIZE);
217 if (! ssl)
218 {
219 rpcapd_log(LOGPRIO_ERROR, "TLS handshake on control connection failed: %s",
220 errbuf);
221 goto end;
222 }
223 }
224 #endif
225 pars.ssl = ssl;
226
227 //
228 // We have a connection.
229 //
230 // If it's a passive mode connection, check whether the connecting
231 // host is among the ones allowed.
232 //
233 // In either case, we were handed a copy of the host list; free it
234 // as soon as we're done with it.
235 //
236 if (pars.isactive)
237 {
238 // Nothing to do.
239 free(passiveClients);
240 passiveClients = NULL;
241 }
242 else
243 {
244 struct sockaddr_storage from;
245 socklen_t fromlen;
246
247 //
248 // Get the address of the other end of the connection.
249 //
250 fromlen = sizeof(struct sockaddr_storage);
251 if (getpeername(pars.sockctrl_in, (struct sockaddr *)&from,
252 &fromlen) == -1)
253 {
254 sock_geterror("getpeername(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
255 if (rpcap_senderror(pars.sockctrl_out, pars.ssl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
256 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
257 goto end;
258 }
259
260 //
261 // Are they in the list of host/port combinations we allow?
262 //
263 host_port_ok = (sock_check_hostlist(passiveClients, RPCAP_HOSTLIST_SEP, &from, errmsgbuf, PCAP_ERRBUF_SIZE) == 0);
264 free(passiveClients);
265 passiveClients = NULL;
266 if (!host_port_ok)
267 {
268 //
269 // Sorry, you're not on the guest list.
270 //
271 if (rpcap_senderror(pars.sockctrl_out, pars.ssl, 0, PCAP_ERR_HOSTNOAUTH, errmsgbuf, errbuf) == -1)
272 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
273 goto end;
274 }
275 }
276
277 //
278 // The client must first authenticate; loop until they send us a
279 // message with a version we support and credentials we accept,
280 // they send us a close message indicating that they're giving up,
281 // or we get a network error or other fatal error.
282 //
283 while (!authenticated)
284 {
285 //
286 // If we're in active mode, we have to check for the
287 // initial timeout.
288 //
289 // XXX - do this on *every* trip through the loop?
290 //
291 if (!pars.isactive)
292 {
293 FD_ZERO(&rfds);
294 // We do not have to block here
295 tv.tv_sec = RPCAP_TIMEOUT_INIT;
296 tv.tv_usec = 0;
297
298 FD_SET(pars.sockctrl_in, &rfds);
299
300 retval = select((int)pars.sockctrl_in + 1, &rfds, NULL, NULL, &tv);
301 if (retval == -1)
302 {
303 sock_geterror("select failed: ", errmsgbuf, PCAP_ERRBUF_SIZE);
304 if (rpcap_senderror(pars.sockctrl_out, pars.ssl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1)
305 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
306 goto end;
307 }
308
309 // The timeout has expired
310 // So, this was a fake connection. Drop it down
311 if (retval == 0)
312 {
313 if (rpcap_senderror(pars.sockctrl_out, pars.ssl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1)
314 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
315 goto end;
316 }
317 }
318
319 //
320 // Read the message header from the client.
321 //
322 nrecv = rpcapd_recv_msg_header(pars.sockctrl_in, pars.ssl, &header);
323 if (nrecv == -1)
324 {
325 // Fatal error.
326 goto end;
327 }
328 if (nrecv == -2)
329 {
330 // Client closed the connection.
331 goto end;
332 }
333
334 plen = header.plen;
335
336 //
337 // Did the client specify a version we can handle?
338 //
339 if (!RPCAP_VERSION_IS_SUPPORTED(header.ver))
340 {
341 //
342 // Tell them it's not a valid protocol version.
343 //
344 uint8 reply_version;
345
346 //
347 // If RPCAP_MIN_VERSION is 0, no version is too
348 // old, as the oldest supported version is 0,
349 // and there are no negative versions.
350 //
351 #if RPCAP_MIN_VERSION != 0
352 if (header.ver < RPCAP_MIN_VERSION)
353 {
354 //
355 // Their maximum version is too old;
356 // there *is* no version we can both
357 // handle, and they might reject
358 // an error with a version they don't
359 // understand, so reply with the
360 // version they sent. That may
361 // make them retry with that version,
362 // but they'll give up on that
363 // failure.
364 //
365 reply_version = header.ver;
366 }
367 else
368 #endif
369 {
370 //
371 // Their maximum version is too new,
372 // but they might be able to handle
373 // *our* maximum version, so reply
374 // with that version.
375 //
376 reply_version = RPCAP_MAX_VERSION;
377 }
378 if (rpcap_senderror(pars.sockctrl_out, pars.ssl, reply_version,
379 PCAP_ERR_WRONGVER, "RPCAP version number mismatch",
380 errbuf) == -1)
381 {
382 // That failed; log a message and give up.
383 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
384 goto end;
385 }
386
387 // Discard the rest of the message.
388 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
389 {
390 // Network error.
391 goto end;
392 }
393
394 // Let them try again.
395 continue;
396 }
397
398 //
399 // OK, we use the version the client specified.
400 //
401 pars.protocol_version = header.ver;
402
403 switch (header.type)
404 {
405 case RPCAP_MSG_AUTH_REQ:
406 retval = daemon_msg_auth_req(&pars, plen);
407 if (retval == -1)
408 {
409 // Fatal error; a message has
410 // been logged, so just give up.
411 goto end;
412 }
413 if (retval == -2)
414 {
415 // Non-fatal error; we sent back
416 // an error message, so let them
417 // try again.
418 continue;
419 }
420
421 // OK, we're authenticated; we sent back
422 // a reply, so start serving requests.
423 authenticated = 1;
424 break;
425
426 case RPCAP_MSG_CLOSE:
427 //
428 // The client is giving up.
429 // Discard the rest of the message, if
430 // there is anything more.
431 //
432 (void)rpcapd_discard(pars.sockctrl_in, pars.ssl, plen);
433 // We're done with this client.
434 goto end;
435
436 case RPCAP_MSG_ERROR:
437 // Log this and close the connection?
438 // XXX - is this what happens in active
439 // mode, where *we* initiate the
440 // connection, and the client gives us
441 // an error message rather than a "let
442 // me log in" message, indicating that
443 // we're not allowed to connect to them?
444 (void)daemon_msg_err(pars.sockctrl_in, pars.ssl, plen);
445 goto end;
446
447 case RPCAP_MSG_FINDALLIF_REQ:
448 case RPCAP_MSG_OPEN_REQ:
449 case RPCAP_MSG_STARTCAP_REQ:
450 case RPCAP_MSG_UPDATEFILTER_REQ:
451 case RPCAP_MSG_STATS_REQ:
452 case RPCAP_MSG_ENDCAP_REQ:
453 case RPCAP_MSG_SETSAMPLING_REQ:
454 //
455 // These requests can't be sent until
456 // the client is authenticated.
457 //
458 msg_type_string = rpcap_msg_type_string(header.type);
459 if (msg_type_string != NULL)
460 {
461 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s request sent before authentication was completed", msg_type_string);
462 }
463 else
464 {
465 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message of type %u sent before authentication was completed", header.type);
466 }
467 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
468 pars.protocol_version, PCAP_ERR_WRONGMSG,
469 errmsgbuf, errbuf) == -1)
470 {
471 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
472 goto end;
473 }
474 // Discard the rest of the message.
475 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
476 {
477 // Network error.
478 goto end;
479 }
480 break;
481
482 case RPCAP_MSG_PACKET:
483 case RPCAP_MSG_FINDALLIF_REPLY:
484 case RPCAP_MSG_OPEN_REPLY:
485 case RPCAP_MSG_STARTCAP_REPLY:
486 case RPCAP_MSG_UPDATEFILTER_REPLY:
487 case RPCAP_MSG_AUTH_REPLY:
488 case RPCAP_MSG_STATS_REPLY:
489 case RPCAP_MSG_ENDCAP_REPLY:
490 case RPCAP_MSG_SETSAMPLING_REPLY:
491 //
492 // These are server-to-client messages.
493 //
494 msg_type_string = rpcap_msg_type_string(header.type);
495 if (msg_type_string != NULL)
496 {
497 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
498 }
499 else
500 {
501 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
502 }
503 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
504 pars.protocol_version, PCAP_ERR_WRONGMSG,
505 errmsgbuf, errbuf) == -1)
506 {
507 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
508 goto end;
509 }
510 // Discard the rest of the message.
511 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
512 {
513 // Fatal error.
514 goto end;
515 }
516 break;
517
518 default:
519 //
520 // Unknown message type.
521 //
522 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
523 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
524 pars.protocol_version, PCAP_ERR_WRONGMSG,
525 errmsgbuf, errbuf) == -1)
526 {
527 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
528 goto end;
529 }
530 // Discard the rest of the message.
531 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
532 {
533 // Fatal error.
534 goto end;
535 }
536 break;
537 }
538 }
539
540 //
541 // OK, the client has authenticated itself, and we can start
542 // processing regular requests from it.
543 //
544
545 //
546 // We don't have any statistics yet.
547 //
548 stats.ps_ifdrop = 0;
549 stats.ps_recv = 0;
550 stats.ps_drop = 0;
551 svrcapt = 0;
552
553 //
554 // Service requests.
555 //
556 for (;;)
557 {
558 errbuf[0] = 0; // clear errbuf
559
560 // Avoid zombies connections; check if the connection is opens but no commands are performed
561 // from more than RPCAP_TIMEOUT_RUNTIME
562 // Conditions:
563 // - I have to be in normal mode (no active mode)
564 // - if the device is open, I don't have to be in the middle of a capture (session->sockdata)
565 // - if the device is closed, I have always to check if a new command arrives
566 //
567 // Be carefully: the capture can have been started, but an error occurred (so session != NULL, but
568 // sockdata is 0
569 if ((!pars.isactive) && ((session == NULL) || ((session != NULL) && (session->sockdata == 0))))
570 {
571 // Check for the initial timeout
572 FD_ZERO(&rfds);
573 // We do not have to block here
574 tv.tv_sec = RPCAP_TIMEOUT_RUNTIME;
575 tv.tv_usec = 0;
576
577 FD_SET(pars.sockctrl_in, &rfds);
578
579 retval = select((int)pars.sockctrl_in + 1, &rfds, NULL, NULL, &tv);
580 if (retval == -1)
581 {
582 sock_geterror("select failed: ", errmsgbuf, PCAP_ERRBUF_SIZE);
583 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
584 pars.protocol_version, PCAP_ERR_NETW,
585 errmsgbuf, errbuf) == -1)
586 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
587 goto end;
588 }
589
590 // The timeout has expired
591 // So, this was a fake connection. Drop it down
592 if (retval == 0)
593 {
594 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
595 pars.protocol_version,
596 PCAP_ERR_INITTIMEOUT,
597 "The RPCAP initial timeout has expired",
598 errbuf) == -1)
599 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
600 goto end;
601 }
602 }
603
604 //
605 // Read the message header from the client.
606 //
607 nrecv = rpcapd_recv_msg_header(pars.sockctrl_in, pars.ssl, &header);
608 if (nrecv == -1)
609 {
610 // Fatal error.
611 goto end;
612 }
613 if (nrecv == -2)
614 {
615 // Client closed the connection.
616 goto end;
617 }
618
619 plen = header.plen;
620
621 //
622 // Did the client specify the version we negotiated?
623 //
624 // For now, there's only one version.
625 //
626 if (header.ver != pars.protocol_version)
627 {
628 //
629 // Tell them it's not the negotiated version.
630 // Send the error message with their version,
631 // so they don't reject it as having the wrong
632 // version.
633 //
634 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
635 header.ver, PCAP_ERR_WRONGVER,
636 "RPCAP version in message isn't the negotiated version",
637 errbuf) == -1)
638 {
639 // That failed; log a message and give up.
640 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
641 goto end;
642 }
643
644 // Discard the rest of the message.
645 (void)rpcapd_discard(pars.sockctrl_in, pars.ssl, plen);
646 // Give up on them.
647 goto end;
648 }
649
650 switch (header.type)
651 {
652 case RPCAP_MSG_ERROR: // The other endpoint reported an error
653 {
654 (void)daemon_msg_err(pars.sockctrl_in, pars.ssl, plen);
655 // Do nothing; just exit; the error code is already into the errbuf
656 // XXX - actually exit....
657 break;
658 }
659
660 case RPCAP_MSG_FINDALLIF_REQ:
661 {
662 if (daemon_msg_findallif_req(&pars, plen) == -1)
663 {
664 // Fatal error; a message has
665 // been logged, so just give up.
666 goto end;
667 }
668 break;
669 }
670
671 case RPCAP_MSG_OPEN_REQ:
672 {
673 //
674 // Process the open request, and keep
675 // the source from it, for use later
676 // when the capture is started.
677 //
678 // XXX - we don't care if the client sends
679 // us multiple open requests, the last
680 // one wins.
681 //
682 retval = daemon_msg_open_req(&pars, plen, source, sizeof(source));
683 if (retval == -1)
684 {
685 // Fatal error; a message has
686 // been logged, so just give up.
687 goto end;
688 }
689 got_source = 1;
690 break;
691 }
692
693 case RPCAP_MSG_STARTCAP_REQ:
694 {
695 if (!got_source)
696 {
697 // They never told us what device
698 // to capture on!
699 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
700 pars.protocol_version,
701 PCAP_ERR_STARTCAPTURE,
702 "No capture device was specified",
703 errbuf) == -1)
704 {
705 // Fatal error; log an
706 // error and give up.
707 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
708 goto end;
709 }
710 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
711 {
712 goto end;
713 }
714 break;
715 }
716
717 if (daemon_msg_startcap_req(&pars, plen, &threaddata, source, &session, &samp_param, uses_ssl) == -1)
718 {
719 // Fatal error; a message has
720 // been logged, so just give up.
721 goto end;
722 }
723 break;
724 }
725
726 case RPCAP_MSG_UPDATEFILTER_REQ:
727 {
728 if (session)
729 {
730 if (daemon_msg_updatefilter_req(&pars, session, plen) == -1)
731 {
732 // Fatal error; a message has
733 // been logged, so just give up.
734 goto end;
735 }
736 }
737 else
738 {
739 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
740 pars.protocol_version,
741 PCAP_ERR_UPDATEFILTER,
742 "Device not opened. Cannot update filter",
743 errbuf) == -1)
744 {
745 // That failed; log a message and give up.
746 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
747 goto end;
748 }
749 }
750 break;
751 }
752
753 case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session
754 {
755 //
756 // Indicate to our caller that the client
757 // closed the control connection.
758 // This is used only in case of active mode.
759 //
760 client_told_us_to_close = 1;
761 rpcapd_log(LOGPRIO_DEBUG, "The other end system asked to close the connection.");
762 goto end;
763 }
764
765 case RPCAP_MSG_STATS_REQ:
766 {
767 if (daemon_msg_stats_req(&pars, session, plen, &stats, svrcapt) == -1)
768 {
769 // Fatal error; a message has
770 // been logged, so just give up.
771 goto end;
772 }
773 break;
774 }
775
776 case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session
777 {
778 if (session)
779 {
780 // Save statistics (we can need them in the future)
781 if (pcap_stats(session->fp, &stats))
782 {
783 svrcapt = session->TotCapt;
784 }
785 else
786 {
787 stats.ps_ifdrop = 0;
788 stats.ps_recv = 0;
789 stats.ps_drop = 0;
790 svrcapt = 0;
791 }
792
793 if (daemon_msg_endcap_req(&pars, session, &threaddata) == -1)
794 {
795 free(session);
796 session = NULL;
797 // Fatal error; a message has
798 // been logged, so just give up.
799 goto end;
800 }
801 free(session);
802 session = NULL;
803 }
804 else
805 {
806 rpcap_senderror(pars.sockctrl_out, pars.ssl,
807 pars.protocol_version,
808 PCAP_ERR_ENDCAPTURE,
809 "Device not opened. Cannot close the capture",
810 errbuf);
811 }
812 break;
813 }
814
815 case RPCAP_MSG_SETSAMPLING_REQ:
816 {
817 if (daemon_msg_setsampling_req(&pars, plen, &samp_param) == -1)
818 {
819 // Fatal error; a message has
820 // been logged, so just give up.
821 goto end;
822 }
823 break;
824 }
825
826 case RPCAP_MSG_AUTH_REQ:
827 {
828 //
829 // We're already authenticated; you don't
830 // get to reauthenticate.
831 //
832 rpcapd_log(LOGPRIO_INFO, "The client sent an RPCAP_MSG_AUTH_REQ message after authentication was completed");
833 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
834 pars.protocol_version,
835 PCAP_ERR_WRONGMSG,
836 "RPCAP_MSG_AUTH_REQ request sent after authentication was completed",
837 errbuf) == -1)
838 {
839 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
840 goto end;
841 }
842 // Discard the rest of the message.
843 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
844 {
845 // Fatal error.
846 goto end;
847 }
848 goto end;
849
850 case RPCAP_MSG_PACKET:
851 case RPCAP_MSG_FINDALLIF_REPLY:
852 case RPCAP_MSG_OPEN_REPLY:
853 case RPCAP_MSG_STARTCAP_REPLY:
854 case RPCAP_MSG_UPDATEFILTER_REPLY:
855 case RPCAP_MSG_AUTH_REPLY:
856 case RPCAP_MSG_STATS_REPLY:
857 case RPCAP_MSG_ENDCAP_REPLY:
858 case RPCAP_MSG_SETSAMPLING_REPLY:
859 //
860 // These are server-to-client messages.
861 //
862 msg_type_string = rpcap_msg_type_string(header.type);
863 if (msg_type_string != NULL)
864 {
865 rpcapd_log(LOGPRIO_INFO, "The client sent a %s server-to-client message", msg_type_string);
866 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string);
867 }
868 else
869 {
870 rpcapd_log(LOGPRIO_INFO, "The client sent a server-to-client message of type %u", header.type);
871 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type);
872 }
873 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
874 pars.protocol_version, PCAP_ERR_WRONGMSG,
875 errmsgbuf, errbuf) == -1)
876 {
877 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
878 goto end;
879 }
880 // Discard the rest of the message.
881 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
882 {
883 // Fatal error.
884 goto end;
885 }
886 goto end;
887
888 default:
889 //
890 // Unknown message type.
891 //
892 rpcapd_log(LOGPRIO_INFO, "The client sent a message of type %u", header.type);
893 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type);
894 if (rpcap_senderror(pars.sockctrl_out, pars.ssl,
895 pars.protocol_version, PCAP_ERR_WRONGMSG,
896 errbuf, errmsgbuf) == -1)
897 {
898 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
899 goto end;
900 }
901 // Discard the rest of the message.
902 if (rpcapd_discard(pars.sockctrl_in, pars.ssl, plen) == -1)
903 {
904 // Fatal error.
905 goto end;
906 }
907 goto end;
908 }
909 }
910 }
911
912 end:
913 // The child thread is about to end
914
915 // perform pcap_t cleanup, in case it has not been done
916 if (session)
917 {
918 if (threaddata.have_thread)
919 {
920 #ifdef _WIN32
921 //
922 // Tell the data connection thread main capture
923 // loop to break out of that loop.
924 //
925 pcap_breakloop(session->fp);
926
927 //
928 // If it's currently blocked waiting for packets
929 // to arrive, try to wake it up, so it can see
930 // the "break out of the loop" indication.
931 //
932 SetEvent(pcap_getevent(session->fp));
933
934 //
935 // Wait for the thread to exit, so we don't close
936 // sockets out from under it.
937 //
938 // XXX - have a timeout, so we don't wait forever?
939 //
940 WaitForSingleObject(threaddata.thread, INFINITE);
941
942 //
943 // Release the thread handle, as we're done with
944 // it.
945 //
946 CloseHandle(threaddata.thread);
947 #else
948 pthread_cancel(threaddata.thread);
949 #endif
950 threaddata.have_thread = 0;
951 }
952
953 session_close(session);
954 free(session);
955 session = NULL;
956 }
957
958 #ifdef HAVE_OPENSSL
959 if (ssl)
960 {
961 SSL_free(ssl);
962 }
963 #endif
964
965 // Print message and return
966 rpcapd_log(LOGPRIO_DEBUG, "I'm exiting from the child loop");
967 rpcapd_log(LOGPRIO_DEBUG, "%s", errbuf);
968
969 return client_told_us_to_close;
970 }
971
972 /*
973 * This handles the RPCAP_MSG_ERR message.
974 */
975 static int
976 daemon_msg_err(SOCKET sockctrl_in, SSL *ssl, uint32 plen)
977 {
978 char errbuf[PCAP_ERRBUF_SIZE];
979 char remote_errbuf[PCAP_ERRBUF_SIZE];
980
981 if (plen >= PCAP_ERRBUF_SIZE)
982 {
983 /*
984 * Message is too long; just read as much of it as we
985 * can into the buffer provided, and discard the rest.
986 */
987 if (sock_recv(sockctrl_in, ssl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
988 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
989 PCAP_ERRBUF_SIZE) == -1)
990 {
991 // Network error.
992 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
993 return -1;
994 }
995 if (rpcapd_discard(sockctrl_in, ssl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1)
996 {
997 // Network error.
998 return -1;
999 }
1000
1001 /*
1002 * Null-terminate it.
1003 */
1004 remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
1005 }
1006 else if (plen == 0)
1007 {
1008 /* Empty error string. */
1009 remote_errbuf[0] = '\0';
1010 }
1011 else
1012 {
1013 if (sock_recv(sockctrl_in, ssl, remote_errbuf, plen,
1014 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
1015 PCAP_ERRBUF_SIZE) == -1)
1016 {
1017 // Network error.
1018 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
1019 return -1;
1020 }
1021
1022 /*
1023 * Null-terminate it.
1024 */
1025 remote_errbuf[plen] = '\0';
1026 }
1027 // Log the message
1028 rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf);
1029 return 0;
1030 }
1031
1032 /*
1033 * This handles the RPCAP_MSG_AUTH_REQ message.
1034 * It checks if the authentication credentials supplied by the user are valid.
1035 *
1036 * This function is called if the daemon receives a RPCAP_MSG_AUTH_REQ
1037 * message in its authentication loop. It reads the body of the
1038 * authentication message from the network and checks whether the
1039 * credentials are valid.
1040 *
1041 * \param sockctrl: the socket for the control connection.
1042 *
1043 * \param nullAuthAllowed: '1' if the NULL authentication is allowed.
1044 *
1045 * \param errbuf: a user-allocated buffer in which the error message
1046 * (if one) has to be written. It must be at least PCAP_ERRBUF_SIZE
1047 * bytes long.
1048 *
1049 * \return '0' if everything is fine, '-1' if an unrecoverable error occurred,
1050 * or '-2' if the authentication failed. For errors, an error message is
1051 * returned in the 'errbuf' variable; this gives a message for the
1052 * unrecoverable error or for the authentication failure.
1053 */
1054 static int
1055 daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen)
1056 {
1057 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1058 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1059 struct rpcap_header header; // RPCAP message general header
1060 int status;
1061 struct rpcap_auth auth; // RPCAP authentication header
1062
1063 status = rpcapd_recv(pars->sockctrl_in, pars->ssl, (char *) &auth, sizeof(struct rpcap_auth), &plen, errmsgbuf);
1064 if (status == -1)
1065 {
1066 return -1;
1067 }
1068 if (status == -2)
1069 {
1070 goto error;
1071 }
1072
1073 switch (ntohs(auth.type))
1074 {
1075 case RPCAP_RMTAUTH_NULL:
1076 {
1077 if (!pars->nullAuthAllowed)
1078 {
1079 // Send the client an error reply.
1080 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Authentication failed; NULL authentication not permitted.");
1081 goto error;
1082 }
1083 break;
1084 }
1085
1086 case RPCAP_RMTAUTH_PWD:
1087 {
1088 char *username, *passwd;
1089 uint32 usernamelen, passwdlen;
1090
1091 usernamelen = ntohs(auth.slen1);
1092 username = (char *) malloc (usernamelen + 1);
1093 if (username == NULL)
1094 {
1095 pcap_fmt_errmsg_for_errno(errmsgbuf,
1096 PCAP_ERRBUF_SIZE, errno, "malloc() failed");
1097 goto error;
1098 }
1099 status = rpcapd_recv(pars->sockctrl_in, pars->ssl, username, usernamelen, &plen, errmsgbuf);
1100 if (status == -1)
1101 {
1102 free(username);
1103 return -1;
1104 }
1105 if (status == -2)
1106 {
1107 free(username);
1108 goto error;
1109 }
1110 username[usernamelen] = '\0';
1111
1112 passwdlen = ntohs(auth.slen2);
1113 passwd = (char *) malloc (passwdlen + 1);
1114 if (passwd == NULL)
1115 {
1116 pcap_fmt_errmsg_for_errno(errmsgbuf,
1117 PCAP_ERRBUF_SIZE, errno, "malloc() failed");
1118 free(username);
1119 goto error;
1120 }
1121 status = rpcapd_recv(pars->sockctrl_in, pars->ssl, passwd, passwdlen, &plen, errmsgbuf);
1122 if (status == -1)
1123 {
1124 free(username);
1125 free(passwd);
1126 return -1;
1127 }
1128 if (status == -2)
1129 {
1130 free(username);
1131 free(passwd);
1132 goto error;
1133 }
1134 passwd[passwdlen] = '\0';
1135
1136 if (daemon_AuthUserPwd(username, passwd, errmsgbuf))
1137 {
1138 //
1139 // Authentication failed. Let the client
1140 // know.
1141 //
1142 free(username);
1143 free(passwd);
1144 if (rpcap_senderror(pars->sockctrl_out, pars->ssl,
1145 pars->protocol_version,
1146 PCAP_ERR_AUTH, errmsgbuf, errbuf) == -1)
1147 {
1148 // That failed; log a message and give up.
1149 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1150 return -1;
1151 }
1152
1153 //
1154 // Suspend for 1 second, so that they can't
1155 // hammer us with repeated tries with an
1156 // attack such as a dictionary attack.
1157 //
1158 // WARNING: this delay is inserted only
1159 // at this point; if the client closes the
1160 // connection and reconnects, the suspension
1161 // time does not have any effect.
1162 //
1163 sleep_secs(RPCAP_SUSPEND_WRONGAUTH);
1164 goto error_noreply;
1165 }
1166
1167 free(username);
1168 free(passwd);
1169 break;
1170 }
1171
1172 default:
1173 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized.");
1174 goto error;
1175 }
1176
1177 // The authentication succeeded; let the client know.
1178 rpcap_createhdr(&header, pars->protocol_version, RPCAP_MSG_AUTH_REPLY, 0, 0);
1179
1180 // Send the ok message back
1181 if (sock_send(pars->sockctrl_out, pars->ssl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
1182 {
1183 // That failed; log a messsage and give up.
1184 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1185 return -1;
1186 }
1187
1188 // Check if all the data has been read; if not, discard the data in excess
1189 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
1190 {
1191 return -1;
1192 }
1193
1194 return 0;
1195
1196 error:
1197 if (rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
1198 PCAP_ERR_AUTH, errmsgbuf, errbuf) == -1)
1199 {
1200 // That failed; log a message and give up.
1201 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1202 return -1;
1203 }
1204
1205 error_noreply:
1206 // Check if all the data has been read; if not, discard the data in excess
1207 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
1208 {
1209 return -1;
1210 }
1211
1212 return -2;
1213 }
1214
1215 static int
1216 daemon_AuthUserPwd(char *username, char *password, char *errbuf)
1217 {
1218 #ifdef _WIN32
1219 /*
1220 * Warning: the user which launches the process must have the
1221 * SE_TCB_NAME right.
1222 * This corresponds to have the "Act as part of the Operating System"
1223 * turned on (administrative tools, local security settings, local
1224 * policies, user right assignment)
1225 * However, it seems to me that if you run it as a service, this
1226 * right should be provided by default.
1227 */
1228 HANDLE Token;
1229 if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
1230 {
1231 pcap_win32_err_to_str(GetLastError(), errbuf);
1232 return -1;
1233 }
1234
1235 // This call should change the current thread to the selected user.
1236 // I didn't test it.
1237 if (ImpersonateLoggedOnUser(Token) == 0)
1238 {
1239 pcap_win32_err_to_str(GetLastError(), errbuf);
1240 CloseHandle(Token);
1241 return -1;
1242 }
1243
1244 CloseHandle(Token);
1245 return 0;
1246
1247 #else
1248 /*
1249 * See
1250 *
1251 * http://www.unixpapa.com/incnote/passwd.html
1252 *
1253 * We use the Solaris/Linux shadow password authentication if
1254 * we have getspnam(), otherwise we just do traditional
1255 * authentication, which, on some platforms, might work, even
1256 * with shadow passwords, if we're running as root. Traditional
1257 * authenticaion won't work if we're not running as root, as
1258 * I think these days all UN*Xes either won't return the password
1259 * at all with getpwnam() or will only do so if you're root.
1260 *
1261 * XXX - perhaps what we *should* be using is PAM, if we have
1262 * it. That might hide all the details of username/password
1263 * authentication, whether it's done with a visible-to-root-
1264 * only password database or some other authentication mechanism,
1265 * behind its API.
1266 */
1267 struct passwd *user;
1268 char *user_password;
1269 #ifdef HAVE_GETSPNAM
1270 struct spwd *usersp;
1271 #endif
1272
1273 // This call is needed to get the uid
1274 if ((user = getpwnam(username)) == NULL)
1275 {
1276 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: no such user");
1277 return -1;
1278 }
1279
1280 #ifdef HAVE_GETSPNAM
1281 // This call is needed to get the password; otherwise 'x' is returned
1282 if ((usersp = getspnam(username)) == NULL)
1283 {
1284 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: no such user");
1285 return -1;
1286 }
1287 user_password = usersp->sp_pwdp;
1288 #else
1289 /*
1290 * XXX - what about other platforms?
1291 * The unixpapa.com page claims this Just Works on *BSD if you're
1292 * running as root - it's from 2000, so it doesn't indicate whether
1293 * macOS (which didn't come out until 2001, under the name Mac OS
1294 * X) behaves like the *BSDs or not, and might also work on AIX.
1295 * HP-UX does something else.
1296 *
1297 * Again, hopefully PAM hides all that.
1298 */
1299 user_password = user->pw_passwd;
1300 #endif
1301
1302 if (strcmp(user_password, (char *) crypt(password, user_password)) != 0)
1303 {
1304 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: password incorrect");
1305 return -1;
1306 }
1307
1308 if (setuid(user->pw_uid))
1309 {
1310 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1311 errno, "setuid");
1312 return -1;
1313 }
1314
1315 /* if (setgid(user->pw_gid))
1316 {
1317 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1318 errno, "setgid");
1319 return -1;
1320 }
1321 */
1322 return 0;
1323
1324 #endif
1325
1326 }
1327
1328 static int
1329 daemon_msg_findallif_req(struct daemon_slpars *pars, uint32 plen)
1330 {
1331 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1332 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1333 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1334 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1335 pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
1336 pcap_if_t *d; // temp pointer needed to scan the interface chain
1337 struct pcap_addr *address; // pcap structure that keeps a network address of an interface
1338 struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
1339 uint16 nif = 0; // counts the number of interface listed
1340
1341 // Discard the rest of the message; there shouldn't be any payload.
1342 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
1343 {
1344 // Network error.
1345 return -1;
1346 }
1347
1348 // Retrieve the device list
1349 if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
1350 goto error;
1351
1352 if (alldevs == NULL)
1353 {
1354 if (rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
1355 PCAP_ERR_NOREMOTEIF,
1356 "No interfaces found! Make sure libpcap/WinPcap is properly installed"
1357 " and you have the right to access to the remote device.",
1358 errbuf) == -1)
1359 {
1360 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1361 return -1;
1362 }
1363 return 0;
1364 }
1365
1366 // checks the number of interfaces and it computes the total length of the payload
1367 for (d = alldevs; d != NULL; d = d->next)
1368 {
1369 nif++;
1370
1371 if (d->description)
1372 plen+= strlen(d->description);
1373 if (d->name)
1374 plen+= strlen(d->name);
1375
1376 plen+= sizeof(struct rpcap_findalldevs_if);
1377
1378 for (address = d->addresses; address != NULL; address = address->next)
1379 {
1380 /*
1381 * Send only IPv4 and IPv6 addresses over the wire.
1382 */
1383 switch (address->addr->sa_family)
1384 {
1385 case AF_INET:
1386 #ifdef AF_INET6
1387 case AF_INET6:
1388 #endif
1389 plen+= (sizeof(struct rpcap_sockaddr) * 4);
1390 break;
1391
1392 default:
1393 break;
1394 }
1395 }
1396 }
1397
1398 // RPCAP findalldevs command
1399 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
1400 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
1401 PCAP_ERRBUF_SIZE) == -1)
1402 goto error;
1403
1404 rpcap_createhdr((struct rpcap_header *) sendbuf, pars->protocol_version,
1405 RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
1406
1407 // send the interface list
1408 for (d = alldevs; d != NULL; d = d->next)
1409 {
1410 uint16 lname, ldescr;
1411
1412 findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
1413
1414 if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
1415 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1416 goto error;
1417
1418 memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
1419
1420 if (d->description) ldescr = (short) strlen(d->description);
1421 else ldescr = 0;
1422 if (d->name) lname = (short) strlen(d->name);
1423 else lname = 0;
1424
1425 findalldevs_if->desclen = htons(ldescr);
1426 findalldevs_if->namelen = htons(lname);
1427 findalldevs_if->flags = htonl(d->flags);
1428
1429 for (address = d->addresses; address != NULL; address = address->next)
1430 {
1431 /*
1432 * Send only IPv4 and IPv6 addresses over the wire.
1433 */
1434 switch (address->addr->sa_family)
1435 {
1436 case AF_INET:
1437 #ifdef AF_INET6
1438 case AF_INET6:
1439 #endif
1440 findalldevs_if->naddr++;
1441 break;
1442
1443 default:
1444 break;
1445 }
1446 }
1447 findalldevs_if->naddr = htons(findalldevs_if->naddr);
1448
1449 if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
1450 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
1451 PCAP_ERRBUF_SIZE) == -1)
1452 goto error;
1453
1454 if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
1455 RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
1456 PCAP_ERRBUF_SIZE) == -1)
1457 goto error;
1458
1459 // send all addresses
1460 for (address = d->addresses; address != NULL; address = address->next)
1461 {
1462 struct rpcap_sockaddr *sockaddr;
1463
1464 /*
1465 * Send only IPv4 and IPv6 addresses over the wire.
1466 */
1467 switch (address->addr->sa_family)
1468 {
1469 case AF_INET:
1470 #ifdef AF_INET6
1471 case AF_INET6:
1472 #endif
1473 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1474 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1475 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1476 goto error;
1477 daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
1478
1479 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1480 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1481 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1482 goto error;
1483 daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
1484
1485 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1486 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1487 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1488 goto error;
1489 daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
1490
1491 sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
1492 if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
1493 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1494 goto error;
1495 daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
1496 break;
1497
1498 default:
1499 break;
1500 }
1501 }
1502 }
1503
1504 // We no longer need the device list. Free it.
1505 pcap_freealldevs(alldevs);
1506
1507 // Send a final command that says "now send it!"
1508 if (sock_send(pars->sockctrl_out, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1509 {
1510 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1511 return -1;
1512 }
1513
1514 return 0;
1515
1516 error:
1517 if (alldevs)
1518 pcap_freealldevs(alldevs);
1519
1520 if (rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
1521 PCAP_ERR_FINDALLIF, errmsgbuf, errbuf) == -1)
1522 {
1523 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1524 return -1;
1525 }
1526 return 0;
1527 }
1528
1529 /*
1530 \param plen: the length of the current message (needed in order to be able
1531 to discard excess data in the message, if present)
1532 */
1533 static int
1534 daemon_msg_open_req(struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen)
1535 {
1536 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1537 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1538 pcap_t *fp; // pcap_t main variable
1539 int nread;
1540 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1541 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1542 struct rpcap_openreply *openreply; // open reply message
1543
1544 if (plen > sourcelen - 1)
1545 {
1546 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long");
1547 goto error;
1548 }
1549
1550 nread = sock_recv(pars->sockctrl_in, pars->ssl, source, plen,
1551 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
1552 if (nread == -1)
1553 {
1554 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
1555 return -1;
1556 }
1557 source[nread] = '\0';
1558 plen -= nread;
1559
1560 // XXX - make sure it's *not* a URL; we don't support opening
1561 // remote devices here.
1562
1563 // Open the selected device
1564 // This is a fake open, since we do that only to get the needed parameters, then we close the device again
1565 if ((fp = pcap_open_live(source,
1566 1500 /* fake snaplen */,
1567 0 /* no promis */,
1568 1000 /* fake timeout */,
1569 errmsgbuf)) == NULL)
1570 goto error;
1571
1572 // Now, I can send a RPCAP open reply message
1573 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1574 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1575 goto error;
1576
1577 rpcap_createhdr((struct rpcap_header *) sendbuf, pars->protocol_version,
1578 RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply));
1579
1580 openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx];
1581
1582 if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx,
1583 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1584 goto error;
1585
1586 memset(openreply, 0, sizeof(struct rpcap_openreply));
1587 openreply->linktype = htonl(pcap_datalink(fp));
1588
1589 // We're done with the pcap_t.
1590 pcap_close(fp);
1591
1592 // Send the reply.
1593 if (sock_send(pars->sockctrl_out, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1594 {
1595 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1596 return -1;
1597 }
1598 return 0;
1599
1600 error:
1601 if (rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
1602 PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1)
1603 {
1604 // That failed; log a message and give up.
1605 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1606 return -1;
1607 }
1608
1609 // Check if all the data has been read; if not, discard the data in excess
1610 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
1611 {
1612 return -1;
1613 }
1614 return 0;
1615 }
1616
1617 /*
1618 \param plen: the length of the current message (needed in order to be able
1619 to discard excess data in the message, if present)
1620 */
1621 static int
1622 daemon_msg_startcap_req(struct daemon_slpars *pars, uint32 plen, struct thread_handle *threaddata, char *source, struct session **sessionp, struct rpcap_sampling *samp_param _U_, int uses_ssl)
1623 {
1624 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
1625 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
1626 char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port
1627 char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer
1628 struct session *session = NULL; // saves state of session
1629 int status;
1630 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
1631 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
1632
1633 // socket-related variables
1634 SOCKET sockdata = INVALID_SOCKET; // socket descriptor of the data connection
1635 struct addrinfo hints; // temp, needed to open a socket connection
1636 struct addrinfo *addrinfo; // temp, needed to open a socket connection
1637 struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine
1638 socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine
1639 int ret; // return value from functions
1640
1641 #ifndef _WIN32
1642 pthread_attr_t detachedAttribute; // temp, needed to set the created thread as detached
1643 #endif
1644
1645 // RPCAP-related variables
1646 struct rpcap_startcapreq startcapreq; // start capture request message
1647 struct rpcap_startcapreply *startcapreply; // start capture reply message
1648 int serveropen_dp; // keeps who is going to open the data connection
1649
1650 addrinfo = NULL;
1651
1652 status = rpcapd_recv(pars->sockctrl_in, pars->ssl, (char *) &startcapreq,
1653 sizeof(struct rpcap_startcapreq), &plen, errmsgbuf);
1654 if (status == -1)
1655 {
1656 goto fatal_error;
1657 }
1658 if (status == -2)
1659 {
1660 goto error;
1661 }
1662
1663 startcapreq.flags = ntohs(startcapreq.flags);
1664
1665 // Check that the client does not ask for UDP is the server has been asked
1666 // to enforce encryption, as SSL is not supported yet with UDP:
1667 if (uses_ssl && (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM))
1668 {
1669 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1670 "SSL not supported with UDP forward of remote packets");
1671 goto error;
1672 }
1673
1674 // Create a session structure
1675 session = malloc(sizeof(struct session));
1676 if (session == NULL)
1677 {
1678 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure");
1679 goto error;
1680 }
1681
1682 session->ctrl_ssl = session->data_ssl = NULL;
1683
1684 // Open the selected device
1685 if ((session->fp = pcap_open_live(source,
1686 ntohl(startcapreq.snaplen),
1687 (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */,
1688 ntohl(startcapreq.read_timeout),
1689 errmsgbuf)) == NULL)
1690 goto error;
1691
1692 #if 0
1693 // Apply sampling parameters
1694 fp->rmt_samp.method = samp_param->method;
1695 fp->rmt_samp.value = samp_param->value;
1696 #endif
1697
1698 /*
1699 We're in active mode if:
1700 - we're using TCP, and the user wants us to be in active mode
1701 - we're using UDP
1702 */
1703 serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive;
1704
1705 /*
1706 Gets the sockaddr structure referred to the other peer in the ctrl connection
1707
1708 We need that because:
1709 - if we're in passive mode, we need to know the address family we want to use
1710 (the same used for the ctrl socket)
1711 - if we're in active mode, we need to know the network address of the other host
1712 we want to connect to
1713 */
1714 saddrlen = sizeof(struct sockaddr_storage);
1715 if (getpeername(pars->sockctrl_in, (struct sockaddr *) &saddr, &saddrlen) == -1)
1716 {
1717 sock_geterror("getpeername(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1718 goto error;
1719 }
1720
1721 memset(&hints, 0, sizeof(struct addrinfo));
1722 hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM;
1723 hints.ai_family = saddr.ss_family;
1724
1725 // Now we have to create a new socket to send packets
1726 if (serveropen_dp) // Data connection is opened by the server toward the client
1727 {
1728 pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata));
1729
1730 // Get the name of the other peer (needed to connect to that specific network address)
1731 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost,
1732 sizeof(peerhost), NULL, 0, NI_NUMERICHOST))
1733 {
1734 sock_geterror("getnameinfo(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1735 goto error;
1736 }
1737
1738 if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1739 goto error;
1740
1741 if ((sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1742 goto error;
1743 }
1744 else // Data connection is opened by the client toward the server
1745 {
1746 hints.ai_flags = AI_PASSIVE;
1747
1748 // Let's the server socket pick up a free network port for us
1749 if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1750 goto error;
1751
1752 if ((sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1753 goto error;
1754
1755 // get the complete sockaddr structure used in the data connection
1756 saddrlen = sizeof(struct sockaddr_storage);
1757 if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
1758 {
1759 sock_geterror("getsockname(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1760 goto error;
1761 }
1762
1763 // Get the local port the system picked up
1764 if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
1765 0, portdata, sizeof(portdata), NI_NUMERICSERV))
1766 {
1767 sock_geterror("getnameinfo(): ", errmsgbuf, PCAP_ERRBUF_SIZE);
1768 goto error;
1769 }
1770 }
1771
1772 // addrinfo is no longer used
1773 freeaddrinfo(addrinfo);
1774 addrinfo = NULL;
1775
1776 // Needed to send an error on the ctrl connection
1777 session->sockctrl_out = pars->sockctrl_out;
1778 session->ctrl_ssl = pars->ssl;
1779 session->protocol_version = pars->protocol_version;
1780
1781 // Now I can set the filter
1782 ret = daemon_unpackapplyfilter(pars->sockctrl_in, pars->ssl, session, &plen, errmsgbuf);
1783 if (ret == -1)
1784 {
1785 // Fatal error. A message has been logged; just give up.
1786 goto fatal_error;
1787 }
1788 if (ret == -2)
1789 {
1790 // Non-fatal error. Send an error message to the client.
1791 goto error;
1792 }
1793
1794 // Now, I can send a RPCAP start capture reply message
1795 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
1796 RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1797 goto error;
1798
1799 rpcap_createhdr((struct rpcap_header *) sendbuf, pars->protocol_version,
1800 RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply));
1801
1802 startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx];
1803
1804 if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL,
1805 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
1806 goto error;
1807
1808 memset(startcapreply, 0, sizeof(struct rpcap_startcapreply));
1809 startcapreply->bufsize = htonl(pcap_bufsize(session->fp));
1810
1811 if (!serveropen_dp)
1812 {
1813 unsigned short port = (unsigned short)strtoul(portdata,NULL,10);
1814 startcapreply->portdata = htons(port);
1815 }
1816
1817 if (sock_send(pars->sockctrl_out, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
1818 {
1819 // That failed; log a message and give up.
1820 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1821 goto fatal_error;
1822 }
1823
1824 if (!serveropen_dp)
1825 {
1826 SOCKET socktemp; // We need another socket, since we're going to accept() a connection
1827
1828 // Connection creation
1829 saddrlen = sizeof(struct sockaddr_storage);
1830
1831 socktemp = accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
1832
1833 if (socktemp == INVALID_SOCKET)
1834 {
1835 sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE);
1836 rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s",
1837 errbuf);
1838 goto error;
1839 }
1840
1841 // Now that I accepted the connection, the server socket is no longer needed
1842 sock_close(sockdata, NULL, 0);
1843 sockdata = socktemp;
1844 }
1845
1846 SSL *ssl = NULL;
1847 if (uses_ssl)
1848 {
1849 #ifdef HAVE_OPENSSL
1850 /* In both active or passive cases, wait for the client to initiate the
1851 * TLS handshake. Yes during that time the control socket will not be
1852 * served, but the same was true from the above call to accept(). */
1853 ssl = ssl_promotion(1, sockdata, errbuf, PCAP_ERRBUF_SIZE);
1854 if (! ssl)
1855 {
1856 rpcapd_log(LOGPRIO_ERROR, "TLS handshake failed: %s", errbuf);
1857 goto error;
1858 }
1859 #endif
1860 }
1861 session->data_ssl = ssl;
1862 session->sockdata = sockdata;
1863
1864 // Now we have to create a new thread to receive packets
1865 #ifdef _WIN32
1866 threaddata->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain,
1867 (void *) session, 0, NULL);
1868 if (threaddata->thread == 0)
1869 {
1870 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread");
1871 goto error;
1872 }
1873 #else
1874 /* GV we need this to create the thread as detached. */
1875 /* GV otherwise, the thread handle is not destroyed */
1876 pthread_attr_init(&detachedAttribute);
1877 pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED);
1878 ret = pthread_create(&threaddata->thread, &detachedAttribute,
1879 daemon_thrdatamain, (void *) session);
1880 if (ret != 0)
1881 {
1882 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1883 ret, "Error creating the data thread");
1884 pthread_attr_destroy(&detachedAttribute);
1885 goto error;
1886 }
1887 pthread_attr_destroy(&detachedAttribute);
1888 #endif
1889 threaddata->have_thread = 1;
1890
1891 // Check if all the data has been read; if not, discard the data in excess
1892 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
1893 goto fatal_error;
1894
1895 *sessionp = session;
1896 return 0;
1897
1898 error:
1899 //
1900 // Not a fatal error, so send the client an error message and
1901 // keep serving client requests.
1902 //
1903 *sessionp = NULL;
1904
1905 if (addrinfo)
1906 freeaddrinfo(addrinfo);
1907
1908 if (threaddata->have_thread)
1909 {
1910 #ifdef _WIN32
1911 if (session->fp)
1912 {
1913 pcap_breakloop(session->fp);
1914 SetEvent(pcap_getevent(session->fp));
1915 }
1916 CloseHandle(threaddata->thread);
1917 #else
1918 pthread_cancel(threaddata->thread);
1919 #endif
1920 threaddata->have_thread = 0;
1921 }
1922
1923 if (sockdata != INVALID_SOCKET)
1924 sock_close(sockdata, NULL, 0);
1925
1926 if (session)
1927 {
1928 if (session->fp)
1929 pcap_close(session->fp);
1930 #ifdef HAVE_OPENSSL
1931 if (session->ctrl_ssl)
1932 SSL_free(session->ctrl_ssl);
1933 if (session->data_ssl)
1934 SSL_free(session->data_ssl);
1935 #endif
1936 free(session);
1937 }
1938
1939 if (rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
1940 PCAP_ERR_STARTCAPTURE, errmsgbuf, errbuf) == -1)
1941 {
1942 // That failed; log a message and give up.
1943 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
1944 return -1;
1945 }
1946
1947 // Check if all the data has been read; if not, discard the data in excess
1948 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
1949 {
1950 // Network error.
1951 return -1;
1952 }
1953
1954 return 0;
1955
1956 fatal_error:
1957 //
1958 // Fatal network error, so don't try to communicate with
1959 // the client, just give up.
1960 //
1961 *sessionp = NULL;
1962
1963 if (threaddata->have_thread)
1964 {
1965 #ifdef _WIN32
1966 if (session && session->fp)
1967 {
1968 //
1969 // Tell the data connection thread main capture
1970 // loop to break out of that loop.
1971 //
1972 pcap_breakloop(session->fp);
1973
1974 //
1975 // If it's currently blocked waiting for packets
1976 // to arrive, try to wake it up, so it can see
1977 // the "break out of the loop" indication.
1978 //
1979 SetEvent(pcap_getevent(session->fp));
1980 }
1981
1982 //
1983 // Wait for the thread to exit, so we don't close
1984 // sockets out from under it.
1985 //
1986 // XXX - have a timeout, so we don't wait forever?
1987 //
1988 WaitForSingleObject(threaddata->thread, INFINITE);
1989
1990 //
1991 // Release the thread handle, as we're done with
1992 // it.
1993 //
1994 CloseHandle(threaddata->thread);
1995 #else
1996 pthread_cancel(threaddata->thread);
1997 #endif
1998 threaddata->have_thread = 0;
1999 }
2000
2001 if (sockdata != INVALID_SOCKET)
2002 sock_close(sockdata, NULL, 0);
2003
2004 if (session)
2005 {
2006 if (session->fp)
2007 pcap_close(session->fp);
2008 #ifdef HAVE_OPENSSL
2009 if (session->ctrl_ssl)
2010 SSL_free(session->ctrl_ssl);
2011 if (session->data_ssl)
2012 SSL_free(session->data_ssl);
2013 #endif
2014 free(session);
2015 }
2016
2017 return -1;
2018 }
2019
2020 static int
2021 daemon_msg_endcap_req(struct daemon_slpars *pars, struct session *session, struct thread_handle *threaddata)
2022 {
2023 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2024 struct rpcap_header header;
2025
2026 if (threaddata->have_thread)
2027 {
2028 #ifdef _WIN32
2029 //
2030 // Tell the data connection thread main capture loop to
2031 // break out of that loop.
2032 //
2033 pcap_breakloop(session->fp);
2034
2035 //
2036 // If it's currently blocked waiting for packets to
2037 // arrive, try to wake it up, so it can see the "break
2038 // out of the loop" indication.
2039 //
2040 SetEvent(pcap_getevent(session->fp));
2041
2042 //
2043 // Wait for the thread to exit, so we don't close
2044 // sockets out from under it.
2045 //
2046 // XXX - have a timeout, so we don't wait forever?
2047 //
2048 WaitForSingleObject(threaddata->thread, INFINITE);
2049
2050 //
2051 // Release the thread handle, as we're done with
2052 // it.
2053 //
2054 CloseHandle(threaddata->thread);
2055 #else
2056 pthread_cancel(threaddata->thread);
2057 #endif
2058 threaddata->have_thread = 0;
2059 }
2060
2061 session_close(session);
2062
2063 rpcap_createhdr(&header, pars->protocol_version,
2064 RPCAP_MSG_ENDCAP_REPLY, 0, 0);
2065
2066 if (sock_send(pars->sockctrl_out, pars->ssl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
2067 {
2068 // That failed; log a message and give up.
2069 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2070 return -1;
2071 }
2072
2073 return 0;
2074 }
2075
2076 static int
2077 daemon_unpackapplyfilter(SOCKET sockctrl_in, SSL *ctrl_ssl, struct session *session, uint32 *plenp, char *errmsgbuf)
2078 {
2079 int status;
2080 struct rpcap_filter filter;
2081 struct rpcap_filterbpf_insn insn;
2082 struct bpf_insn *bf_insn;
2083 struct bpf_program bf_prog;
2084 unsigned int i;
2085
2086 status = rpcapd_recv(sockctrl_in, ctrl_ssl, (char *) &filter,
2087 sizeof(struct rpcap_filter), plenp, errmsgbuf);
2088 if (status == -1)
2089 {
2090 return -1;
2091 }
2092 if (status == -2)
2093 {
2094 return -2;
2095 }
2096
2097 bf_prog.bf_len = ntohl(filter.nitems);
2098
2099 if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF)
2100 {
2101 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported");
2102 return -2;
2103 }
2104
2105 bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len);
2106 if (bf_insn == NULL)
2107 {
2108 pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE,
2109 errno, "malloc() failed");
2110 return -2;
2111 }
2112
2113 bf_prog.bf_insns = bf_insn;
2114
2115 for (i = 0; i < bf_prog.bf_len; i++)
2116 {
2117 status = rpcapd_recv(sockctrl_in, ctrl_ssl, (char *) &insn,
2118 sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf);
2119 if (status == -1)
2120 {
2121 return -1;
2122 }
2123 if (status == -2)
2124 {
2125 return -2;
2126 }
2127
2128 bf_insn->code = ntohs(insn.code);
2129 bf_insn->jf = insn.jf;
2130 bf_insn->jt = insn.jt;
2131 bf_insn->k = ntohl(insn.k);
2132
2133 bf_insn++;
2134 }
2135
2136 //
2137 // XXX - pcap_setfilter() should do the validation for us.
2138 //
2139 if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0)
2140 {
2141 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions");
2142 return -2;
2143 }
2144
2145 if (pcap_setfilter(session->fp, &bf_prog))
2146 {
2147 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp));
2148 return -2;
2149 }
2150
2151 return 0;
2152 }
2153
2154 static int
2155 daemon_msg_updatefilter_req(struct daemon_slpars *pars, struct session *session, uint32 plen)
2156 {
2157 char errbuf[PCAP_ERRBUF_SIZE];
2158 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
2159 int ret; // status of daemon_unpackapplyfilter()
2160 struct rpcap_header header; // keeps the answer to the updatefilter command
2161
2162 ret = daemon_unpackapplyfilter(pars->sockctrl_in, pars->ssl, session, &plen, errmsgbuf);
2163 if (ret == -1)
2164 {
2165 // Fatal error. A message has been logged; just give up.
2166 return -1;
2167 }
2168 if (ret == -2)
2169 {
2170 // Non-fatal error. Send an error reply to the client.
2171 goto error;
2172 }
2173
2174 // Check if all the data has been read; if not, discard the data in excess
2175 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
2176 {
2177 // Network error.
2178 return -1;
2179 }
2180
2181 // A response is needed, otherwise the other host does not know that everything went well
2182 rpcap_createhdr(&header, pars->protocol_version,
2183 RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0);
2184
2185 if (sock_send(pars->sockctrl_out, pars->ssl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE))
2186 {
2187 // That failed; log a messsage and give up.
2188 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2189 return -1;
2190 }
2191
2192 return 0;
2193
2194 error:
2195 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
2196 {
2197 return -1;
2198 }
2199 rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
2200 PCAP_ERR_UPDATEFILTER, errmsgbuf, NULL);
2201
2202 return 0;
2203 }
2204
2205 /*!
2206 \brief Received the sampling parameters from remote host and it stores in the pcap_t structure.
2207 */
2208 static int
2209 daemon_msg_setsampling_req(struct daemon_slpars *pars, uint32 plen, struct rpcap_sampling *samp_param)
2210 {
2211 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2212 char errmsgbuf[PCAP_ERRBUF_SIZE];
2213 struct rpcap_header header;
2214 struct rpcap_sampling rpcap_samp;
2215 int status;
2216
2217 status = rpcapd_recv(pars->sockctrl_in, pars->ssl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf);
2218 if (status == -1)
2219 {
2220 return -1;
2221 }
2222 if (status == -2)
2223 {
2224 goto error;
2225 }
2226
2227 // Save these settings in the pcap_t
2228 samp_param->method = rpcap_samp.method;
2229 samp_param->value = ntohl(rpcap_samp.value);
2230
2231 // A response is needed, otherwise the other host does not know that everything went well
2232 rpcap_createhdr(&header, pars->protocol_version,
2233 RPCAP_MSG_SETSAMPLING_REPLY, 0, 0);
2234
2235 if (sock_send(pars->sockctrl_out, pars->ssl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1)
2236 {
2237 // That failed; log a messsage and give up.
2238 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2239 return -1;
2240 }
2241
2242 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
2243 {
2244 return -1;
2245 }
2246
2247 return 0;
2248
2249 error:
2250 if (rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
2251 PCAP_ERR_AUTH, errmsgbuf, errbuf) == -1)
2252 {
2253 // That failed; log a message and give up.
2254 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2255 return -1;
2256 }
2257
2258 // Check if all the data has been read; if not, discard the data in excess
2259 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
2260 {
2261 return -1;
2262 }
2263
2264 return 0;
2265 }
2266
2267 static int
2268 daemon_msg_stats_req(struct daemon_slpars *pars, struct session *session, uint32 plen, struct pcap_stat *stats, unsigned int svrcapt)
2269 {
2270 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2271 char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
2272 char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
2273 int sendbufidx = 0; // index which keeps the number of bytes currently buffered
2274 struct rpcap_stats *netstats; // statistics sent on the network
2275
2276 // Checks that the header does not contain other data; if so, discard it
2277 if (rpcapd_discard(pars->sockctrl_in, pars->ssl, plen) == -1)
2278 {
2279 // Network error.
2280 return -1;
2281 }
2282
2283 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2284 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2285 goto error;
2286
2287 rpcap_createhdr((struct rpcap_header *) sendbuf, pars->protocol_version,
2288 RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats));
2289
2290 netstats = (struct rpcap_stats *) &sendbuf[sendbufidx];
2291
2292 if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL,
2293 &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
2294 goto error;
2295
2296 if (session && session->fp)
2297 {
2298 if (pcap_stats(session->fp, stats) == -1)
2299 {
2300 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp));
2301 goto error;
2302 }
2303
2304 netstats->ifdrop = htonl(stats->ps_ifdrop);
2305 netstats->ifrecv = htonl(stats->ps_recv);
2306 netstats->krnldrop = htonl(stats->ps_drop);
2307 netstats->svrcapt = htonl(session->TotCapt);
2308 }
2309 else
2310 {
2311 // We have to keep compatibility with old applications,
2312 // which ask for statistics also when the capture has
2313 // already stopped.
2314 netstats->ifdrop = htonl(stats->ps_ifdrop);
2315 netstats->ifrecv = htonl(stats->ps_recv);
2316 netstats->krnldrop = htonl(stats->ps_drop);
2317 netstats->svrcapt = htonl(svrcapt);
2318 }
2319
2320 // Send the packet
2321 if (sock_send(pars->sockctrl_out, pars->ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
2322 {
2323 rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
2324 return -1;
2325 }
2326
2327 return 0;
2328
2329 error:
2330 rpcap_senderror(pars->sockctrl_out, pars->ssl, pars->protocol_version,
2331 PCAP_ERR_GETSTATS, errmsgbuf, NULL);
2332 return 0;
2333 }
2334
2335 #ifdef _WIN32
2336 static unsigned __stdcall
2337 #else
2338 static void *
2339 #endif
2340 daemon_thrdatamain(void *ptr)
2341 {
2342 char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer
2343 struct session *session; // pointer to the struct session for this session
2344 int retval; // general variable used to keep the return value of other functions
2345 struct rpcap_pkthdr *net_pkt_header;// header of the packet
2346 struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet
2347 u_char *pkt_data; // pointer to the buffer that contains the current packet
2348 size_t sendbufsize; // size for the send buffer
2349 char *sendbuf; // temporary buffer in which data to be sent is buffered
2350 int sendbufidx; // index which keeps the number of bytes currently buffered
2351 int status;
2352
2353 session = (struct session *) ptr;
2354
2355 session->TotCapt = 0; // counter which is incremented each time a packet is received
2356
2357 // Initialize errbuf
2358 memset(errbuf, 0, sizeof(errbuf));
2359
2360 //
2361 // We need a buffer large enough to hold a buffer large enough
2362 // for a maximum-size packet for this pcap_t.
2363 //
2364 if (pcap_snapshot(session->fp) < 0)
2365 {
2366 //
2367 // The snapshot length is negative.
2368 // This "should not happen".
2369 //
2370 rpcapd_log(LOGPRIO_ERROR,
2371 "Unable to allocate the buffer for this child thread: snapshot length of %d is negative",
2372 pcap_snapshot(session->fp));
2373 sendbuf = NULL; // we can't allocate a buffer, so nothing to free
2374 goto error;
2375 }
2376 //
2377 // size_t is unsigned, and the result of pcap_snapshot() is signed;
2378 // on no platform that we support is int larger than size_t.
2379 // This means that, unless the extra information we prepend to
2380 // a maximum-sized packet is impossibly large, the sum of the
2381 // snapshot length and the size of that extra information will
2382 // fit in a size_t.
2383 //
2384 // So we don't need to make sure that sendbufsize will overflow.
2385 //
2386 // However, we *do* need to make sure its value fits in an int,
2387 // because sock_send() can't send more than INT_MAX bytes (it could
2388 // do so on 64-bit UN*Xes, but can't do so on Windows, not even
2389 // 64-bit Windows, as the send() buffer size argument is an int
2390 // in Winsock).
2391 //
2392 sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp);
2393 if (sendbufsize > INT_MAX)
2394 {
2395 rpcapd_log(LOGPRIO_ERROR,
2396 "Buffer size for this child thread would be larger than %d",
2397 INT_MAX);
2398 sendbuf = NULL; // we haven't allocated a buffer, so nothing to free
2399 goto error;
2400 }
2401 sendbuf = (char *) malloc (sendbufsize);
2402 if (sendbuf == NULL)
2403 {
2404 rpcapd_log(LOGPRIO_ERROR,
2405 "Unable to allocate the buffer for this child thread");
2406 goto error;
2407 }
2408
2409 #ifndef _WIN32
2410 // Modify thread params so that it can be killed at any time
2411 retval = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
2412 if (retval != 0)
2413 {
2414 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2415 retval, "pthread_setcancelstate");
2416 rpcapd_log(LOGPRIO_ERROR,
2417 "Can't set cancel state on data thread: %s", errbuf);
2418 goto error;
2419 }
2420 retval = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
2421 if (retval != 0)
2422 {
2423 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2424 retval, "pthread_setcanceltype");
2425 rpcapd_log(LOGPRIO_ERROR,
2426 "Can't set cancel type on data thread: %s", errbuf);
2427 goto error;
2428 }
2429 #endif
2430
2431 // Retrieve the packets
2432 while ((retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data)) >= 0) // cast to avoid a compiler warning
2433 {
2434 if (retval == 0) // Read timeout elapsed
2435 continue;
2436
2437 sendbufidx = 0;
2438
2439 // Bufferize the general header
2440 if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
2441 &sendbufidx, (int)sendbufsize, SOCKBUF_CHECKONLY, errbuf,
2442 PCAP_ERRBUF_SIZE) == -1)
2443 {
2444 rpcapd_log(LOGPRIO_ERROR,
2445 "sock_bufferize() error sending packet message: %s",
2446 errbuf);
2447 goto error;
2448 }
2449
2450 rpcap_createhdr((struct rpcap_header *) sendbuf,
2451 session->protocol_version, RPCAP_MSG_PACKET, 0,
2452 (uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen));
2453
2454 net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx];
2455
2456 // Bufferize the pkt header
2457 if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL,
2458 &sendbufidx, (int)sendbufsize, SOCKBUF_CHECKONLY, errbuf,
2459 PCAP_ERRBUF_SIZE) == -1)
2460 {
2461 rpcapd_log(LOGPRIO_ERROR,
2462 "sock_bufferize() error sending packet message: %s",
2463 errbuf);
2464 goto error;
2465 }
2466
2467 net_pkt_header->caplen = htonl(pkt_header->caplen);
2468 net_pkt_header->len = htonl(pkt_header->len);
2469 net_pkt_header->npkt = htonl(++(session->TotCapt));
2470 //
2471 // This protocol needs to be updated with a new version
2472 // before 2038-01-19 03:14:07 UTC.
2473 //
2474 net_pkt_header->timestamp_sec = htonl((uint32)pkt_header->ts.tv_sec);
2475 net_pkt_header->timestamp_usec = htonl((uint32)pkt_header->ts.tv_usec);
2476
2477 // Bufferize the pkt data
2478 if (sock_bufferize((char *) pkt_data, pkt_header->caplen,
2479 sendbuf, &sendbufidx, (int)sendbufsize, SOCKBUF_BUFFERIZE,
2480 errbuf, PCAP_ERRBUF_SIZE) == -1)
2481 {
2482 rpcapd_log(LOGPRIO_ERROR,
2483 "sock_bufferize() error sending packet message: %s",
2484 errbuf);
2485 goto error;
2486 }
2487
2488 // Send the packet
2489 // If the client dropped the connection, don't report an
2490 // error, just quit.
2491 status = sock_send(session->sockdata, session->data_ssl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE);
2492 if (status < 0)
2493 {
2494 if (status == -1)
2495 {
2496 //
2497 // Error other than "client closed the
2498 // connection out from under us"; report
2499 // it.
2500 //
2501 rpcapd_log(LOGPRIO_ERROR,
2502 "Send of packet to client failed: %s",
2503 errbuf);
2504 }
2505
2506 //
2507 // Give up in either case.
2508 //
2509 goto error;
2510 }
2511 }
2512
2513 if (retval == -1)
2514 {
2515 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp));
2516 rpcap_senderror(session->sockctrl_out, session->ctrl_ssl, session->protocol_version,
2517 PCAP_ERR_READEX, errbuf, NULL);
2518 goto error;
2519 }
2520
2521 error:
2522 session_close(session);
2523
2524 free(sendbuf);
2525
2526 return 0;
2527 }
2528
2529 /*!
2530 \brief It serializes a network address.
2531
2532 It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format
2533 that can be used to be sent on the network. Basically, it applies all the hton()
2534 conversion required to the input variable.
2535
2536 \param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be
2537 serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'.
2538
2539 \param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain
2540 the serialized data. This variable has to be allocated by the user.
2541
2542 \warning This function supports only AF_INET and AF_INET6 address families.
2543 */
2544 static void
2545 daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout)
2546 {
2547 memset(sockaddrout, 0, sizeof(struct sockaddr_storage));
2548
2549 // There can be the case in which the sockaddrin is not available
2550 if (sockaddrin == NULL) return;
2551
2552 // Warning: we support only AF_INET and AF_INET6
2553 switch (sockaddrin->ss_family)
2554 {
2555 case AF_INET:
2556 {
2557 struct sockaddr_in *sockaddrin_ipv4;
2558 struct rpcap_sockaddr_in *sockaddrout_ipv4;
2559
2560 sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin;
2561 sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout;
2562 sockaddrout_ipv4->family = htons(RPCAP_AF_INET);
2563 sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port);
2564 memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr));
2565 memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero));
2566 break;
2567 }
2568
2569 #ifdef AF_INET6
2570 case AF_INET6:
2571 {
2572 struct sockaddr_in6 *sockaddrin_ipv6;
2573 struct rpcap_sockaddr_in6 *sockaddrout_ipv6;
2574
2575 sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin;
2576 sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout;
2577 sockaddrout_ipv6->family = htons(RPCAP_AF_INET6);
2578 sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port);
2579 sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo);
2580 memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr));
2581 sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id);
2582 break;
2583 }
2584 #endif
2585 }
2586 }
2587
2588
2589 /*!
2590 \brief Suspends a thread for secs seconds.
2591 */
2592 void sleep_secs(int secs)
2593 {
2594 #ifdef _WIN32
2595 Sleep(secs*1000);
2596 #else
2597 unsigned secs_remaining;
2598
2599 if (secs <= 0)
2600 return;
2601 secs_remaining = secs;
2602 while (secs_remaining != 0)
2603 secs_remaining = sleep(secs_remaining);
2604 #endif
2605 }
2606
2607 /*
2608 * Read the header of a message.
2609 */
2610 static int
2611 rpcapd_recv_msg_header(SOCKET sock, SSL *ssl, struct rpcap_header *headerp)
2612 {
2613 int nread;
2614 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2615
2616 nread = sock_recv(sock, ssl, (char *) headerp, sizeof(struct rpcap_header),
2617 SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE);
2618 if (nread == -1)
2619 {
2620 // Network error.
2621 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2622 return -1;
2623 }
2624 if (nread == 0)
2625 {
2626 // Immediate EOF; that's treated like a close message.
2627 return -2;
2628 }
2629 headerp->plen = ntohl(headerp->plen);
2630 return 0;
2631 }
2632
2633 /*
2634 * Read data from a message.
2635 * If we're trying to read more data that remains, puts an error
2636 * message into errmsgbuf and returns -2. Otherwise, tries to read
2637 * the data and, if that succeeds, subtracts the amount read from
2638 * the number of bytes of data that remains.
2639 * Returns 0 on success, logs a message and returns -1 on a network
2640 * error.
2641 */
2642 static int
2643 rpcapd_recv(SOCKET sock, SSL *ssl, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf)
2644 {
2645 int nread;
2646 char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
2647
2648 if (toread > *plen)
2649 {
2650 // Tell the client and continue.
2651 pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
2652 return -2;
2653 }
2654 nread = sock_recv(sock, ssl, buffer, toread,
2655 SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
2656 if (nread == -1)
2657 {
2658 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2659 return -1;
2660 }
2661 *plen -= nread;
2662 return 0;
2663 }
2664
2665 /*
2666 * Discard data from a connection.
2667 * Mostly used to discard wrong-sized messages.
2668 * Returns 0 on success, logs a message and returns -1 on a network
2669 * error.
2670 */
2671 static int
2672 rpcapd_discard(SOCKET sock, SSL *ssl, uint32 len)
2673 {
2674 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
2675
2676 if (len != 0)
2677 {
2678 if (sock_discard(sock, ssl, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
2679 {
2680 // Network error.
2681 rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf);
2682 return -1;
2683 }
2684 }
2685 return 0;
2686 }
2687
2688 /*
2689 * Close the socket associated with the session, the optional SSL handle,
2690 * and the underlying packet capture handle. We of course do not touch
2691 * the controlling socket that's also copied into the session.
2692 */
2693 static void session_close(struct session *session)
2694 {
2695 #ifdef HAVE_OPENSSL
2696 if (session->data_ssl)
2697 {
2698 SSL_free(session->data_ssl); // Must happen *before* the socket is closed
2699 session->data_ssl = NULL;
2700 }
2701 #endif
2702
2703 if (session->sockdata)
2704 {
2705 sock_close(session->sockdata, NULL, 0);
2706 session->sockdata = 0;
2707 }
2708
2709 pcap_close(session->fp);
2710 }