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