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