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