]> The Tcpdump Group git mirrors - libpcap/blob - rpcapd/rpcapd.c
26b6e8ab5d06ba8be3ab94fd1b5873786644d5d6
[libpcap] / rpcapd / rpcapd.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
33 #ifdef HAVE_CONFIG_H
34 #include <config.h>
35 #endif
36
37 #include "ftmacros.h"
38
39 #include <errno.h> // for the errno variable
40 #include <string.h> // for strtok, etc
41 #include <stdlib.h> // for malloc(), free(), ...
42 #include <pcap.h> // for PCAP_ERRBUF_SIZE
43 #include <signal.h> // for signal()
44
45 #include "fmtutils.h"
46 #include "sockutils.h" // for socket calls
47 #include "varattrs.h" // for _U_
48 #include "portability.h"
49 #include "rpcapd.h"
50 #include "config_params.h" // configuration file parameters
51 #include "fileconf.h" // for the configuration file management
52 #include "rpcap-protocol.h"
53 #include "daemon.h" // the true main() method of this daemon
54 #include "log.h"
55
56 #ifdef HAVE_OPENSSL
57 #include "sslutils.h"
58 #endif
59
60 #ifdef _WIN32
61 #include <process.h> // for thread stuff
62 #include "win32-svc.h" // for Win32 service stuff
63 #include "getopt.h" // for getopt()-for-Windows
64 #else
65 #include <fcntl.h> // for open()
66 #include <unistd.h> // for exit()
67 #include <sys/wait.h> // waitpid()
68 #endif
69
70 //
71 // Element in list of sockets on which we're listening for connections.
72 //
73 struct listen_sock {
74 struct listen_sock *next;
75 SOCKET sock;
76 };
77
78 // Global variables
79 char hostlist[MAX_HOST_LIST + 1]; //!< Keeps the list of the hosts that are allowed to connect to this server
80 struct active_pars activelist[MAX_ACTIVE_LIST]; //!< Keeps the list of the hosts (host, port) on which I want to connect to (active mode)
81 int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise
82 static struct listen_sock *listen_socks; //!< sockets on which we listen
83 char loadfile[MAX_LINE + 1]; //!< Name of the file from which we have to load the configuration
84 static int passivemode = 1; //!< '1' if we want to run in passive mode as well
85 static struct addrinfo mainhints; //!< temporary struct to keep settings needed to open the new socket
86 static char address[MAX_LINE + 1]; //!< keeps the network address (either numeric or literal) to bind to
87 static char port[MAX_LINE + 1]; //!< keeps the network port to bind to
88 #ifdef _WIN32
89 static HANDLE state_change_event; //!< event to signal that a state change should take place
90 #endif
91 static volatile sig_atomic_t shutdown_server; //!< '1' if the server is to shut down
92 static volatile sig_atomic_t reread_config; //!< '1' if the server is to re-read its configuration
93 static int uses_ssl; //!< '1' to use TLS over the data socket
94
95 extern char *optarg; // for getopt()
96
97 // Function definition
98 #ifdef _WIN32
99 static unsigned __stdcall main_active(void *ptr);
100 static BOOL WINAPI main_ctrl_event(DWORD);
101 #else
102 static void *main_active(void *ptr);
103 static void main_terminate(int sign);
104 static void main_reread_config(int sign);
105 #endif
106 static void accept_connections(void);
107 static void accept_connection(SOCKET listen_sock);
108 #ifndef _WIN32
109 static void main_reap_children(int sign);
110 #endif
111 #ifdef _WIN32
112 static unsigned __stdcall main_passive_serviceloop_thread(void *ptr);
113 #endif
114
115 #define RPCAP_ACTIVE_WAIT 30 /* Waiting time between two attempts to open a connection, in active mode (default: 30 sec) */
116
117 /*!
118 \brief Prints the usage screen if it is launched in console mode.
119 */
120 static void printusage(void)
121 {
122 const char *usagetext =
123 "USAGE:"
124 " " PROGRAM_NAME " [-b <address>] [-p <port>] [-4] [-l <host_list>] [-a <host,port>]\n"
125 " [-n] [-v] [-d] "
126 #ifndef _WIN32
127 "[-i] "
128 #endif
129 "[-s <config_file>] [-f <config_file>]\n\n"
130 " -b <address> the address to bind to (either numeric or literal).\n"
131 " Default: binds to all local IPv4 and IPv6 addresses\n\n"
132 " -p <port> the port to bind to.\n"
133 " Default: binds to port " RPCAP_DEFAULT_NETPORT "\n\n"
134 " -4 use only IPv4.\n"
135 " Default: use both IPv4 and IPv6 waiting sockets\n\n"
136 " -l <host_list> a file that contains a list of hosts that are allowed\n"
137 " to connect to this server (if more than one, list them one\n"
138 " per line).\n"
139 " We suggest to use literal names (instead of numeric ones)\n"
140 " in order to avoid problems with different address families.\n\n"
141 " -n permit NULL authentication (usually used with '-l')\n\n"
142 " -a <host,port> run in active mode when connecting to 'host' on port 'port'\n"
143 " In case 'port' is omitted, the default port (" RPCAP_DEFAULT_NETPORT_ACTIVE ") is used\n\n"
144 " -v run in active mode only (default: if '-a' is specified, it\n"
145 " accepts passive connections as well)\n\n"
146 " -d run in daemon mode (UNIX only) or as a service (Win32 only)\n"
147 " Warning (Win32): this switch is provided automatically when\n"
148 " the service is started from the control panel\n\n"
149 #ifndef _WIN32
150 " -i run in inetd mode (UNIX only)\n\n"
151 #endif
152 #ifdef HAVE_OPENSSL
153 " -S encrypt all communication with SSL (implements rpcaps://)\n"
154 " -C enable compression\n"
155 " -K <pem_file> uses the SSL private key in this file (default: key.pem)\n"
156 " -X <pem_file> uses the certificate from this file (default: cert.pem)\n"
157 #endif
158 " -s <config_file> save the current configuration to file\n\n"
159 " -f <config_file> load the current configuration from file; all switches\n"
160 " specified from the command line are ignored\n\n"
161 " -h print this help screen\n\n";
162
163 (void)fprintf(stderr, "RPCAPD, a remote packet capture daemon.\n"
164 "Compiled with %s\n\n", pcap_lib_version());
165 printf("%s", usagetext);
166 }
167
168
169
170 //! Program main
171 int main(int argc, char *argv[])
172 {
173 char savefile[MAX_LINE + 1]; // name of the file on which we have to save the configuration
174 int log_to_systemlog = 0; // Non-zero if we should log to the "system log" rather than the standard error
175 int isdaemon = 0; // Non-zero if the user wants to run this program as a daemon
176 #ifndef _WIN32
177 int isrunbyinetd = 0; // Non-zero if this is being run by inetd or something inetd-like
178 #endif
179 int log_debug_messages = 0; // Non-zero if the user wants debug messages logged
180 int retval; // keeps the returning value from several functions
181 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
182 #ifndef _WIN32
183 struct sigaction action;
184 #endif
185 #ifdef HAVE_OPENSSL
186 int enable_compression = 0;
187 #endif
188
189 savefile[0] = 0;
190 loadfile[0] = 0;
191 hostlist[0] = 0;
192
193 // Initialize errbuf
194 memset(errbuf, 0, sizeof(errbuf));
195
196 strncpy(address, RPCAP_DEFAULT_NETADDR, MAX_LINE);
197 strncpy(port, RPCAP_DEFAULT_NETPORT, MAX_LINE);
198
199 // Prepare to open a new server socket
200 memset(&mainhints, 0, sizeof(struct addrinfo));
201
202 mainhints.ai_family = PF_UNSPEC;
203 mainhints.ai_flags = AI_PASSIVE; // Ready to a bind() socket
204 mainhints.ai_socktype = SOCK_STREAM;
205
206 // Getting the proper command line options
207 # ifdef HAVE_OPENSSL
208 # define SSL_CLOPTS "SK:X:C"
209 # else
210 # define SSL_CLOPTS ""
211 # endif
212
213 # define CLOPTS "b:dDhip:4l:na:s:f:v" SSL_CLOPTS
214
215 while ((retval = getopt(argc, argv, CLOPTS)) != -1)
216 {
217 switch (retval)
218 {
219 case 'D':
220 log_debug_messages = 1;
221 rpcapd_log_set(log_to_systemlog, log_debug_messages);
222 break;
223 case 'b':
224 strncpy(address, optarg, MAX_LINE);
225 break;
226 case 'p':
227 strncpy(port, optarg, MAX_LINE);
228 break;
229 case '4':
230 mainhints.ai_family = PF_INET; // IPv4 server only
231 break;
232 case 'd':
233 isdaemon = 1;
234 log_to_systemlog = 1;
235 rpcapd_log_set(log_to_systemlog, log_debug_messages);
236 break;
237 case 'i':
238 #ifdef _WIN32
239 printusage();
240 exit(1);
241 #else
242 isrunbyinetd = 1;
243 log_to_systemlog = 1;
244 rpcapd_log_set(log_to_systemlog, log_debug_messages);
245 #endif
246 break;
247 case 'n':
248 nullAuthAllowed = 1;
249 break;
250 case 'v':
251 passivemode = 0;
252 break;
253 case 'l':
254 {
255 strncpy(hostlist, optarg, sizeof(hostlist));
256 break;
257 }
258 case 'a':
259 {
260 char *tmpaddress, *tmpport;
261 char *lasts;
262 int i = 0;
263
264 tmpaddress = pcap_strtok_r(optarg, RPCAP_HOSTLIST_SEP, &lasts);
265
266 while ((tmpaddress != NULL) && (i < MAX_ACTIVE_LIST))
267 {
268 tmpport = pcap_strtok_r(NULL, RPCAP_HOSTLIST_SEP, &lasts);
269
270 pcap_strlcpy(activelist[i].address, tmpaddress, MAX_LINE);
271
272 if ((tmpport == NULL) || (strcmp(tmpport, "DEFAULT") == 0)) // the user choose a custom port
273 pcap_strlcpy(activelist[i].port, RPCAP_DEFAULT_NETPORT_ACTIVE, MAX_LINE);
274 else
275 pcap_strlcpy(activelist[i].port, tmpport, MAX_LINE);
276
277 tmpaddress = pcap_strtok_r(NULL, RPCAP_HOSTLIST_SEP, &lasts);
278
279 i++;
280 }
281
282 if (i > MAX_ACTIVE_LIST)
283 rpcapd_log(LOGPRIO_ERROR, "Only MAX_ACTIVE_LIST active connections are currently supported.");
284
285 // I don't initialize the remaining part of the structure, since
286 // it is already zeroed (it is a global var)
287 break;
288 }
289 case 'f':
290 pcap_strlcpy(loadfile, optarg, MAX_LINE);
291 break;
292 case 's':
293 pcap_strlcpy(savefile, optarg, MAX_LINE);
294 break;
295 #ifdef HAVE_OPENSSL
296 case 'S':
297 uses_ssl = 1;
298 break;
299 case 'C':
300 enable_compression = 1;
301 break;
302 case 'K':
303 ssl_set_keyfile(optarg);
304 break;
305 case 'X':
306 ssl_set_certfile(optarg);
307 break;
308 #endif
309 case 'h':
310 printusage();
311 exit(0);
312 /*NOTREACHED*/
313 default:
314 exit(1);
315 /*NOTREACHED*/
316 }
317 }
318
319 #ifndef _WIN32
320 if (isdaemon && isrunbyinetd)
321 {
322 rpcapd_log(LOGPRIO_ERROR, "rpcapd: -d and -i can't be used together");
323 exit(1);
324 }
325 #endif
326
327 if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
328 {
329 rpcapd_log(LOGPRIO_ERROR, "%s", errbuf);
330 exit(-1);
331 }
332
333 if (savefile[0] && fileconf_save(savefile))
334 rpcapd_log(LOGPRIO_DEBUG, "Error when saving the configuration to file");
335
336 // If the file does not exist, it keeps the settings provided by the command line
337 if (loadfile[0])
338 fileconf_read();
339
340 #ifdef WIN32
341 //
342 // Create a handle to signal the main loop to tell it to do
343 // something.
344 //
345 state_change_event = CreateEvent(NULL, FALSE, FALSE, NULL);
346 if (state_change_event == NULL)
347 {
348 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
349 rpcapd_log(LOGPRIO_ERROR, "Can't create state change event: %s",
350 errbuf);
351 exit(2);
352 }
353
354 //
355 // Catch control signals.
356 //
357 if (!SetConsoleCtrlHandler(main_ctrl_event, TRUE))
358 {
359 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
360 rpcapd_log(LOGPRIO_ERROR, "Can't set control handler: %s",
361 errbuf);
362 exit(2);
363 }
364 #else
365 memset(&action, 0, sizeof (action));
366 action.sa_handler = main_terminate;
367 action.sa_flags = 0;
368 sigemptyset(&action.sa_mask);
369 sigaction(SIGTERM, &action, NULL);
370 memset(&action, 0, sizeof (action));
371 action.sa_handler = main_reap_children;
372 action.sa_flags = 0;
373 sigemptyset(&action.sa_mask);
374 sigaction(SIGCHLD, &action, NULL);
375 // Ignore SIGPIPE - we'll get EPIPE when trying to write to a closed
376 // connection, we don't want to get killed by a signal in that case
377 signal(SIGPIPE, SIG_IGN);
378 #endif
379
380 # ifdef HAVE_OPENSSL
381 if (uses_ssl) {
382 if (ssl_init_once(1, enable_compression, errbuf, PCAP_ERRBUF_SIZE) < 0)
383 {
384 rpcapd_log(LOGPRIO_ERROR, "Can't initialize SSL: %s",
385 errbuf);
386 exit(2);
387 }
388 }
389 # endif
390
391 #ifndef _WIN32
392 if (isrunbyinetd)
393 {
394 //
395 // -i was specified, indicating that this is being run
396 // by inetd or something that can run network daemons
397 // as if it were inetd (xinetd, launchd, systemd, etc.).
398 //
399 // Our standard input is the input side of a connection,
400 // and our standard output is the output side of a
401 // connection.
402 //
403 int sockctrl_in, sockctrl_out;
404 int devnull_fd;
405
406 //
407 // Duplicate the standard input and output, making them
408 // the input and output side of the control connection.
409 //
410 sockctrl_in = dup(0);
411 if (sockctrl_in == -1)
412 {
413 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
414 rpcapd_log(LOGPRIO_ERROR, "Can't dup standard input: %s",
415 errbuf);
416 exit(2);
417 }
418 sockctrl_out = dup(1);
419 if (sockctrl_out == -1)
420 {
421 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
422 rpcapd_log(LOGPRIO_ERROR, "Can't dup standard output: %s",
423 errbuf);
424 exit(2);
425 }
426
427 //
428 // Try to set the standard input, output, and error
429 // to /dev/null.
430 //
431 devnull_fd = open("/dev/null", O_RDWR);
432 if (devnull_fd != -1)
433 {
434 //
435 // If this fails, just drive on.
436 //
437 (void)dup2(devnull_fd, 0);
438 (void)dup2(devnull_fd, 1);
439 (void)dup2(devnull_fd, 2);
440 close(devnull_fd);
441 }
442
443 //
444 // Handle this client.
445 // This is passive mode, so we don't care whether we were
446 // told by the client to close.
447 //
448 char *hostlist_copy = strdup(hostlist);
449 if (hostlist_copy == NULL)
450 {
451 rpcapd_log(LOGPRIO_ERROR, "Out of memory copying the host/port list");
452 exit(0);
453 }
454 (void)daemon_serviceloop(sockctrl_in, sockctrl_out, 0,
455 hostlist_copy, nullAuthAllowed, uses_ssl);
456
457 sock_close(sockctrl_out, NULL, 0);
458
459 //
460 // Nothing more to do.
461 //
462 exit(0);
463 }
464 #endif
465
466 if (isdaemon)
467 {
468 //
469 // This is being run as a daemon.
470 // On UN*X, it might be manually run, or run from an
471 // rc file.
472 //
473 #ifndef _WIN32
474 int pid;
475
476 //
477 // Daemonize ourselves.
478 //
479 // Unix Network Programming, pg 336
480 //
481 if ((pid = fork()) != 0)
482 exit(0); // Parent terminates
483
484 // First child continues
485 // Set daemon mode
486 setsid();
487
488 // generated under unix with 'kill -HUP', needed to reload the configuration
489 memset(&action, 0, sizeof (action));
490 action.sa_handler = main_reread_config;
491 action.sa_flags = 0;
492 sigemptyset(&action.sa_mask);
493 sigaction(SIGHUP, &action, NULL);
494
495 if ((pid = fork()) != 0)
496 exit(0); // First child terminates
497
498 // LINUX WARNING: the current linux implementation of pthreads requires a management thread
499 // to handle some hidden stuff. So, as soon as you create the first thread, two threads are
500 // created. Fom this point on, the number of threads active are always one more compared
501 // to the number you're expecting
502
503 // Second child continues
504 // umask(0);
505 // chdir("/");
506 #else
507 //
508 // This is being run as a service on Windows.
509 //
510 // If this call succeeds, it is blocking on Win32
511 //
512 if (svc_start() != 1)
513 rpcapd_log(LOGPRIO_DEBUG, "Unable to start the service");
514
515 // When the previous call returns, the entire application has to be stopped.
516 exit(0);
517 #endif
518 }
519 else // Console mode
520 {
521 #ifndef _WIN32
522 // Enable the catching of Ctrl+C
523 memset(&action, 0, sizeof (action));
524 action.sa_handler = main_terminate;
525 action.sa_flags = 0;
526 sigemptyset(&action.sa_mask);
527 sigaction(SIGINT, &action, NULL);
528
529 // generated under unix with 'kill -HUP', needed to reload the configuration
530 // We do not have this kind of signal in Win32
531 memset(&action, 0, sizeof (action));
532 action.sa_handler = main_reread_config;
533 action.sa_flags = 0;
534 sigemptyset(&action.sa_mask);
535 sigaction(SIGHUP, &action, NULL);
536 #endif
537
538 printf("Press CTRL + C to stop the server...\n");
539 }
540
541 // If we're a Win32 service, we have already called this function in the service_main
542 main_startup();
543
544 // The code should never arrive here (since the main_startup is blocking)
545 // however this avoids a compiler warning
546 exit(0);
547 }
548
549 void main_startup(void)
550 {
551 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
552 struct addrinfo *addrinfo; // keeps the addrinfo chain; required to open a new socket
553 int i;
554 #ifdef _WIN32
555 HANDLE threadId; // handle for the subthread
556 #else
557 pid_t pid;
558 #endif
559
560 i = 0;
561 addrinfo = NULL;
562 memset(errbuf, 0, sizeof(errbuf));
563
564 // Starts all the active threads
565 while ((i < MAX_ACTIVE_LIST) && (activelist[i].address[0] != 0))
566 {
567 activelist[i].ai_family = mainhints.ai_family;
568
569 #ifdef _WIN32
570 threadId = (HANDLE)_beginthreadex(NULL, 0, main_active,
571 (void *)&activelist[i], 0, NULL);
572 if (threadId == 0)
573 {
574 rpcapd_log(LOGPRIO_DEBUG, "Error creating the active child threads");
575 continue;
576 }
577 CloseHandle(threadId);
578 #else
579 if ((pid = fork()) == 0) // I am the child
580 {
581 main_active((void *) &activelist[i]);
582 exit(0);
583 }
584 #endif
585 i++;
586 }
587
588 /*
589 * The code that manages the active connections is not blocking;
590 * the code that manages the passive connection is blocking.
591 * So, if the user does not want to run in passive mode, we have
592 * to block the main thread here, otherwise the program ends and
593 * all threads are stopped.
594 *
595 * WARNING: this means that in case we have only active mode,
596 * the program does not terminate even if all the child thread
597 * terminates. The user has always to press Ctrl+C (or send a
598 * SIGTERM) to terminate the program.
599 */
600 if (passivemode)
601 {
602 struct addrinfo *tempaddrinfo;
603
604 //
605 // Get a list of sockets on which to listen.
606 //
607 if (sock_initaddress((address[0]) ? address : NULL, port, &mainhints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
608 {
609 rpcapd_log(LOGPRIO_DEBUG, "%s", errbuf);
610 return;
611 }
612
613 for (tempaddrinfo = addrinfo; tempaddrinfo;
614 tempaddrinfo = tempaddrinfo->ai_next)
615 {
616 SOCKET sock;
617 struct listen_sock *sock_info;
618
619 if ((sock = sock_open(tempaddrinfo, SOCKOPEN_SERVER, SOCKET_MAXCONN, errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
620 {
621 switch (tempaddrinfo->ai_family)
622 {
623 case AF_INET:
624 {
625 struct sockaddr_in *in;
626 char addrbuf[INET_ADDRSTRLEN];
627
628 in = (struct sockaddr_in *)tempaddrinfo->ai_addr;
629 rpcapd_log(LOGPRIO_WARNING, "Can't listen on socket for %s:%u: %s",
630 inet_ntop(AF_INET, &in->sin_addr,
631 addrbuf, sizeof (addrbuf)),
632 ntohs(in->sin_port),
633 errbuf);
634 break;
635 }
636
637 case AF_INET6:
638 {
639 struct sockaddr_in6 *in6;
640 char addrbuf[INET6_ADDRSTRLEN];
641
642 in6 = (struct sockaddr_in6 *)tempaddrinfo->ai_addr;
643 rpcapd_log(LOGPRIO_WARNING, "Can't listen on socket for %s:%u: %s",
644 inet_ntop(AF_INET6, &in6->sin6_addr,
645 addrbuf, sizeof (addrbuf)),
646 ntohs(in6->sin6_port),
647 errbuf);
648 break;
649 }
650
651 default:
652 rpcapd_log(LOGPRIO_WARNING, "Can't listen on socket for address family %u: %s",
653 tempaddrinfo->ai_family,
654 errbuf);
655 break;
656 }
657 continue;
658 }
659
660 sock_info = (struct listen_sock *) malloc(sizeof (struct listen_sock));
661 if (sock_info == NULL)
662 {
663 rpcapd_log(LOGPRIO_ERROR, "Can't allocate structure for listen socket");
664 exit(2);
665 }
666 sock_info->sock = sock;
667 sock_info->next = listen_socks;
668 listen_socks = sock_info;
669 }
670
671 freeaddrinfo(addrinfo);
672
673 if (listen_socks == NULL)
674 {
675 rpcapd_log(LOGPRIO_ERROR, "Can't listen on any address");
676 exit(2);
677 }
678
679 //
680 // Now listen on all of them, waiting for connections.
681 //
682 accept_connections();
683 }
684
685 //
686 // We're done; exit.
687 //
688 rpcapd_log(LOGPRIO_DEBUG, PROGRAM_NAME " is closing.\n");
689
690 #ifndef _WIN32
691 //
692 // Sends a KILL signal to all the processes in this process's
693 // process group; i.e., it kills all the child processes
694 // we've created.
695 //
696 // XXX - that also includes us, so we will be killed as well;
697 // that may cause a message to be printed or logged.
698 //
699 kill(0, SIGKILL);
700 #endif
701
702 //
703 // Just leave. We shouldn't need to clean up sockets or
704 // anything else, and if we try to do so, we'll could end
705 // up closing sockets, or shutting Winsock down, out from
706 // under service loops, causing all sorts of noisy error
707 // messages.
708 //
709 // We shouldn't need to worry about cleaning up any resources
710 // such as handles, sockets, threads, etc. - exit() should
711 // terminate the process, causing all those resources to be
712 // cleaned up (including the threads; Microsoft claims in the
713 // ExitProcess() documentation that, if ExitProcess() is called,
714 // "If a thread is waiting on a kernel object, it will not be
715 // terminated until the wait has completed.", but claims in the
716 // _beginthread()/_beginthreadex() documentation that "All threads
717 // are terminated if any thread calls abort, exit, _exit, or
718 // ExitProcess." - the latter appears to be the case, even for
719 // threads waiting on the event for a pcap_t).
720 //
721 exit(0);
722 }
723
724 #ifdef _WIN32
725 static void
726 send_state_change_event(void)
727 {
728 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
729
730 if (!SetEvent(state_change_event))
731 {
732 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
733 rpcapd_log(LOGPRIO_ERROR, "SetEvent on shutdown event failed: %s", errbuf);
734 }
735 }
736
737 void
738 send_shutdown_notification(void)
739 {
740 //
741 // Indicate that the server should shut down.
742 //
743 shutdown_server = 1;
744
745 //
746 // Send a state change event, to wake up WSAWaitForMultipleEvents().
747 //
748 send_state_change_event();
749 }
750
751 void
752 send_reread_configuration_notification(void)
753 {
754 //
755 // Indicate that the server should re-read its configuration file.
756 //
757 reread_config = 1;
758
759 //
760 // Send a state change event, to wake up WSAWaitForMultipleEvents().
761 //
762 send_state_change_event();
763 }
764
765 static BOOL WINAPI main_ctrl_event(DWORD ctrltype)
766 {
767 //
768 // ctrltype is one of:
769 //
770 // CTRL_C_EVENT - we got a ^C; this is like SIGINT
771 // CTRL_BREAK_EVENT - we got Ctrl+Break
772 // CTRL_CLOSE_EVENT - the console was closed; this is like SIGHUP
773 // CTRL_LOGOFF_EVENT - a user is logging off; this is received
774 // only by services
775 // CTRL_SHUTDOWN_EVENT - the systemis shutting down; this is
776 // received only by services
777 //
778 // For now, we treat all but CTRL_LOGOFF_EVENT as indications
779 // that we should shut down.
780 //
781 switch (ctrltype)
782 {
783 case CTRL_C_EVENT:
784 case CTRL_BREAK_EVENT:
785 case CTRL_CLOSE_EVENT:
786 case CTRL_SHUTDOWN_EVENT:
787 //
788 // Set a shutdown notification.
789 //
790 send_shutdown_notification();
791 break;
792
793 default:
794 break;
795 }
796
797 //
798 // We handled this.
799 //
800 return TRUE;
801 }
802 #else
803 static void main_terminate(int sign _U_)
804 {
805 //
806 // Note that the server should shut down.
807 // select() should get an EINTR error when we return,
808 // so it will wake up and know it needs to check the flag.
809 //
810 shutdown_server = 1;
811 }
812
813 static void main_reread_config(int sign _U_)
814 {
815 //
816 // Note that the server should re-read its configuration file.
817 // select() should get an EINTR error when we return,
818 // so it will wake up and know it needs to check the flag.
819 //
820 reread_config = 1;
821 }
822
823 static void main_reap_children(int sign _U_)
824 {
825 pid_t pid;
826 int exitstat;
827
828 // Reap all child processes that have exited.
829 // For reference, Stevens, pg 128
830
831 while ((pid = waitpid(-1, &exitstat, WNOHANG)) > 0)
832 rpcapd_log(LOGPRIO_DEBUG, "Child terminated");
833
834 return;
835 }
836 #endif
837
838 //
839 // Loop waiting for incoming connections and accepting them.
840 //
841 static void
842 accept_connections(void)
843 {
844 #ifdef _WIN32
845 struct listen_sock *sock_info;
846 DWORD num_events;
847 WSAEVENT *events;
848 int i;
849 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
850
851 //
852 // How big does the set of events need to be?
853 // One for the shutdown event, plus one for every socket on which
854 // we'll be listening.
855 //
856 num_events = 1; // shutdown event
857 for (sock_info = listen_socks; sock_info;
858 sock_info = sock_info->next)
859 {
860 if (num_events == WSA_MAXIMUM_WAIT_EVENTS)
861 {
862 //
863 // WSAWaitForMultipleEvents() doesn't support
864 // more than WSA_MAXIMUM_WAIT_EVENTS events
865 // on which to wait.
866 //
867 rpcapd_log(LOGPRIO_ERROR, "Too many sockets on which to listen");
868 exit(2);
869 }
870 num_events++;
871 }
872
873 //
874 // Allocate the array of events.
875 //
876 events = (WSAEVENT *) malloc(num_events * sizeof (WSAEVENT));
877 if (events == NULL)
878 {
879 rpcapd_log(LOGPRIO_ERROR, "Can't allocate array of events which to listen");
880 exit(2);
881 }
882
883 //
884 // Fill it in.
885 //
886 events[0] = state_change_event; // state change event first
887 for (sock_info = listen_socks, i = 1; sock_info;
888 sock_info = sock_info->next, i++)
889 {
890 WSAEVENT event;
891
892 //
893 // Create an event that is signaled if there's a connection
894 // to accept on the socket in question.
895 //
896 event = WSACreateEvent();
897 if (event == WSA_INVALID_EVENT)
898 {
899 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
900 rpcapd_log(LOGPRIO_ERROR, "Can't create socket event: %s", errbuf);
901 exit(2);
902 }
903 if (WSAEventSelect(sock_info->sock, event, FD_ACCEPT) == SOCKET_ERROR)
904 {
905 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
906 rpcapd_log(LOGPRIO_ERROR, "Can't setup socket event: %s", errbuf);
907 exit(2);
908 }
909 events[i] = event;
910 }
911
912 for (;;)
913 {
914 //
915 // Wait for incoming connections.
916 //
917 DWORD ret;
918
919 ret = WSAWaitForMultipleEvents(num_events, events, FALSE,
920 WSA_INFINITE, FALSE);
921 if (ret == WSA_WAIT_FAILED)
922 {
923 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
924 rpcapd_log(LOGPRIO_ERROR, "WSAWaitForMultipleEvents failed: %s", errbuf);
925 exit(2);
926 }
927
928 if (ret == WSA_WAIT_EVENT_0)
929 {
930 //
931 // The state change event was set.
932 //
933 if (shutdown_server)
934 {
935 //
936 // Time to quit. Exit the loop.
937 //
938 break;
939 }
940 if (reread_config)
941 {
942 //
943 // We should re-read the configuration
944 // file.
945 //
946 reread_config = 0; // clear the indicator
947 fileconf_read();
948 }
949 }
950
951 //
952 // Check each socket.
953 //
954 for (sock_info = listen_socks, i = 1; sock_info;
955 sock_info = sock_info->next, i++)
956 {
957 WSANETWORKEVENTS network_events;
958
959 if (WSAEnumNetworkEvents(sock_info->sock,
960 events[i], &network_events) == SOCKET_ERROR)
961 {
962 sock_geterror(NULL, errbuf, PCAP_ERRBUF_SIZE);
963 rpcapd_log(LOGPRIO_ERROR, "WSAEnumNetworkEvents failed: %s", errbuf);
964 exit(2);
965 }
966 if (network_events.lNetworkEvents & FD_ACCEPT)
967 {
968 //
969 // Did an error occur?
970 //
971 if (network_events.iErrorCode[FD_ACCEPT_BIT] != 0)
972 {
973 //
974 // Yes - report it and keep going.
975 //
976 sock_fmterror(NULL,
977 network_events.iErrorCode[FD_ACCEPT_BIT],
978 errbuf,
979 PCAP_ERRBUF_SIZE);
980 rpcapd_log(LOGPRIO_ERROR, "Socket error: %s", errbuf);
981 continue;
982 }
983
984 //
985 // Accept the connection.
986 //
987 accept_connection(sock_info->sock);
988 }
989 }
990 }
991 #else
992 struct listen_sock *sock_info;
993 int num_sock_fds;
994
995 //
996 // How big does the bitset of sockets on which to select() have
997 // to be?
998 //
999 num_sock_fds = 0;
1000 for (sock_info = listen_socks; sock_info; sock_info = sock_info->next)
1001 {
1002 if (sock_info->sock + 1 > num_sock_fds)
1003 {
1004 if ((unsigned int)(sock_info->sock + 1) >
1005 (unsigned int)FD_SETSIZE)
1006 {
1007 rpcapd_log(LOGPRIO_ERROR, "Socket FD is too bit for an fd_set");
1008 exit(2);
1009 }
1010 num_sock_fds = sock_info->sock + 1;
1011 }
1012 }
1013
1014 for (;;)
1015 {
1016 fd_set sock_fds;
1017 int ret;
1018
1019 //
1020 // Set up an fd_set for all the sockets on which we're
1021 // listening.
1022 //
1023 // This set is modified by select(), so we have to
1024 // construct it anew each time.
1025 //
1026 FD_ZERO(&sock_fds);
1027 for (sock_info = listen_socks; sock_info;
1028 sock_info = sock_info->next)
1029 {
1030 FD_SET(sock_info->sock, &sock_fds);
1031 }
1032
1033 //
1034 // Wait for incoming connections.
1035 //
1036 ret = select(num_sock_fds, &sock_fds, NULL, NULL, NULL);
1037 if (ret == -1)
1038 {
1039 if (errno == EINTR)
1040 {
1041 //
1042 // If this is a "terminate the
1043 // server" signal, exit the loop,
1044 // otherwise just keep trying.
1045 //
1046 if (shutdown_server)
1047 {
1048 //
1049 // Time to quit. Exit the loop.
1050 //
1051 break;
1052 }
1053 if (reread_config)
1054 {
1055 //
1056 // We should re-read the configuration
1057 // file.
1058 //
1059 reread_config = 0; // clear the indicator
1060 fileconf_read();
1061 }
1062
1063 //
1064 // Go back and wait again.
1065 //
1066 continue;
1067 }
1068 else
1069 {
1070 rpcapd_log(LOGPRIO_ERROR, "select failed: %s",
1071 strerror(errno));
1072 exit(2);
1073 }
1074 }
1075
1076 //
1077 // Check each socket.
1078 //
1079 for (sock_info = listen_socks; sock_info;
1080 sock_info = sock_info->next)
1081 {
1082 if (FD_ISSET(sock_info->sock, &sock_fds))
1083 {
1084 //
1085 // Accept the connection.
1086 //
1087 accept_connection(sock_info->sock);
1088 }
1089 }
1090 }
1091 #endif
1092
1093 //
1094 // Close all the listen sockets.
1095 //
1096 for (sock_info = listen_socks; sock_info; sock_info = sock_info->next)
1097 {
1098 closesocket(sock_info->sock);
1099 }
1100 sock_cleanup();
1101 }
1102
1103 #ifdef _WIN32
1104 //
1105 // A structure to hold the parameter to the windows thread
1106 // (on unix there is no need for this explicit copy since the
1107 // fork "inherits" the parent stack)
1108 //
1109 struct sock_copy {
1110 SOCKET sockctrl;
1111 };
1112 #endif
1113
1114 //
1115 // Accept a connection and start a worker thread, on Windows, or a
1116 // worker process, on UN*X, to handle the connection.
1117 //
1118 static void
1119 accept_connection(SOCKET listen_sock)
1120 {
1121 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
1122 SOCKET sockctrl; // keeps the socket ID for this control connection
1123 struct sockaddr_storage from; // generic sockaddr_storage variable
1124 socklen_t fromlen; // keeps the length of the sockaddr_storage variable
1125
1126 #ifdef _WIN32
1127 HANDLE threadId; // handle for the subthread
1128 u_long off = 0;
1129 struct sock_copy *sock_copy = NULL;
1130 #else
1131 pid_t pid;
1132 #endif
1133
1134 // Initialize errbuf
1135 memset(errbuf, 0, sizeof(errbuf));
1136
1137 for (;;)
1138 {
1139 // Accept the connection
1140 fromlen = sizeof(struct sockaddr_storage);
1141
1142 sockctrl = accept(listen_sock, (struct sockaddr *) &from, &fromlen);
1143
1144 if (sockctrl != INVALID_SOCKET)
1145 {
1146 // Success.
1147 break;
1148 }
1149
1150 // The accept() call can return this error when a signal is catched
1151 // In this case, we have simply to ignore this error code
1152 // Stevens, pg 124
1153 #ifdef _WIN32
1154 if (WSAGetLastError() == WSAEINTR)
1155 #else
1156 if (errno == EINTR)
1157 #endif
1158 continue;
1159
1160 // Don't check for errors here, since the error can be due to the fact that the thread
1161 // has been killed
1162 sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE);
1163 rpcapd_log(LOGPRIO_ERROR, "Accept of control connection from client failed: %s",
1164 errbuf);
1165 return;
1166 }
1167
1168 #ifdef _WIN32
1169 //
1170 // Put the socket back into blocking mode; doing WSAEventSelect()
1171 // on the listen socket makes that socket non-blocking, and it
1172 // appears that sockets returned from an accept() on that socket
1173 // are also non-blocking.
1174 //
1175 // First, we have to un-WSAEventSelect() this socket, and then
1176 // we can turn non-blocking mode off.
1177 //
1178 // If this fails, we aren't guaranteed that, for example, any
1179 // of the error message will be sent - if it can't be put in
1180 // the socket queue, the send will just fail.
1181 //
1182 // So we just log the message and close the connection.
1183 //
1184 if (WSAEventSelect(sockctrl, NULL, 0) == SOCKET_ERROR)
1185 {
1186 sock_geterror("WSAEventSelect: ", errbuf, PCAP_ERRBUF_SIZE);
1187 rpcapd_log(LOGPRIO_ERROR, "%s", errbuf);
1188 sock_close(sockctrl, NULL, 0);
1189 return;
1190 }
1191 if (ioctlsocket(sockctrl, FIONBIO, &off) == SOCKET_ERROR)
1192 {
1193 sock_geterror("ioctlsocket(FIONBIO): ", errbuf, PCAP_ERRBUF_SIZE);
1194 rpcapd_log(LOGPRIO_ERROR, "%s", errbuf);
1195 sock_close(sockctrl, NULL, 0);
1196 return;
1197 }
1198
1199 //
1200 // Allocate a location to hold the value of sockctrl.
1201 // It will be freed in the newly-created thread once it's
1202 // finished with it.
1203 // I guess we *could* just cast sockctrl to a void *, but that's
1204 // a bit ugly.
1205 //
1206 sock_copy = malloc(sizeof(*sock_copy));
1207 if (sock_copy == NULL)
1208 {
1209 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1210 errno, "malloc() failed");
1211 rpcap_senderror(sockctrl, ssl, 0, PCAP_ERR_OPEN, errbuf, NULL);
1212 goto error;
1213 }
1214 sock_copy->sockctrl = sockctrl;
1215
1216 threadId = (HANDLE)_beginthreadex(NULL, 0,
1217 main_passive_serviceloop_thread, (void *) sock_copy, 0, NULL);
1218 if (threadId == 0)
1219 {
1220 rpcapd_log(LOG_ERROR, "Error creating the child thread");
1221 goto error;
1222 }
1223 CloseHandle(threadId);
1224 #else /* _WIN32 */
1225 pid = fork();
1226 if (pid == -1)
1227 {
1228 rpcapd_log(LOGPRIO_ERROR, "Error creating the child process: %s",
1229 strerror(errno));
1230 goto error;
1231 }
1232 if (pid == 0)
1233 {
1234 //
1235 // Child process.
1236 //
1237 // Close the socket on which we're listening (must
1238 // be open only in the parent).
1239 //
1240 closesocket(listen_sock);
1241
1242 #if 0
1243 //
1244 // Modify thread params so that it can be killed at any time
1245 // XXX - is this necessary? This is the main and, currently,
1246 // only thread in the child process, and nobody tries to
1247 // cancel us, although *we* may cancel the thread that's
1248 // handling the capture loop.
1249 //
1250 if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL))
1251 goto end;
1252 if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL))
1253 goto end;
1254 #endif
1255
1256 //
1257 // Run the service loop.
1258 // This is passive mode, so we don't care whether we were
1259 // told by the client to close.
1260 //
1261 char *hostlist_copy = strdup(hostlist);
1262 if (hostlist_copy == NULL)
1263 {
1264 rpcapd_log(LOGPRIO_ERROR, "Out of memory copying the host/port list");
1265 exit(0);
1266 }
1267 (void)daemon_serviceloop(sockctrl, sockctrl, 0,
1268 hostlist_copy, nullAuthAllowed, uses_ssl);
1269
1270 sock_close(sockctrl, NULL, 0);
1271
1272 exit(0);
1273 }
1274
1275 // I am the parent
1276 // Close the socket for this session (must be open only in the child)
1277 closesocket(sockctrl);
1278 #endif /* _WIN32 */
1279 return;
1280
1281 error:
1282 #ifdef _WIN32
1283 if (sock_copy) free(sock_copy);
1284 #endif
1285 sock_close(sockctrl, NULL, 0);
1286 }
1287
1288 /*!
1289 \brief 'true' main of the program in case the active mode is turned on.
1290
1291 This function loops forever trying to connect to the remote host, until the
1292 daemon is turned down.
1293
1294 \param ptr: it keeps the 'activepars' parameters. It is a 'void *'
1295 just because the thread APIs want this format.
1296 */
1297 #ifdef _WIN32
1298 static unsigned __stdcall
1299 #else
1300 static void *
1301 #endif
1302 main_active(void *ptr)
1303 {
1304 char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed
1305 SOCKET sockctrl; // keeps the socket ID for this control connection
1306 struct addrinfo hints; // temporary struct to keep settings needed to open the new socket
1307 struct addrinfo *addrinfo; // keeps the addrinfo chain; required to open a new socket
1308 struct active_pars *activepars;
1309
1310 activepars = (struct active_pars *) ptr;
1311
1312 // Prepare to open a new server socket
1313 memset(&hints, 0, sizeof(struct addrinfo));
1314 // WARNING Currently it supports only ONE socket family among IPv4 and IPv6
1315 hints.ai_family = AF_INET; // PF_UNSPEC to have both IPv4 and IPv6 server
1316 hints.ai_socktype = SOCK_STREAM;
1317 hints.ai_family = activepars->ai_family;
1318
1319 rpcapd_log(LOGPRIO_DEBUG, "Connecting to host %s, port %s, using protocol %s",
1320 activepars->address, activepars->port, (hints.ai_family == AF_INET) ? "IPv4":
1321 (hints.ai_family == AF_INET6) ? "IPv6" : "Unspecified");
1322
1323 // Initialize errbuf
1324 memset(errbuf, 0, sizeof(errbuf));
1325
1326 // Do the work
1327 if (sock_initaddress(activepars->address, activepars->port, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
1328 {
1329 rpcapd_log(LOGPRIO_DEBUG, "%s", errbuf);
1330 return 0;
1331 }
1332
1333 for (;;)
1334 {
1335 int activeclose;
1336
1337 if ((sockctrl = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
1338 {
1339 rpcapd_log(LOGPRIO_DEBUG, "%s", errbuf);
1340
1341 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error connecting to host %s, port %s, using protocol %s",
1342 activepars->address, activepars->port, (hints.ai_family == AF_INET) ? "IPv4":
1343 (hints.ai_family == AF_INET6) ? "IPv6" : "Unspecified");
1344
1345 rpcapd_log(LOGPRIO_DEBUG, "%s", errbuf);
1346
1347 sleep_secs(RPCAP_ACTIVE_WAIT);
1348
1349 continue;
1350 }
1351
1352 char *hostlist_copy = strdup(hostlist);
1353 if (hostlist_copy == NULL)
1354 {
1355 rpcapd_log(LOGPRIO_ERROR, "Out of memory copying the host/port list");
1356 activeclose = 0;
1357 }
1358 else
1359 {
1360 //
1361 // daemon_serviceloop() will free the copy.
1362 //
1363 activeclose = daemon_serviceloop(sockctrl, sockctrl, 1,
1364 hostlist_copy, nullAuthAllowed, uses_ssl);
1365 }
1366
1367 sock_close(sockctrl, NULL, 0);
1368
1369 // If the connection is closed by the user explicitely, don't try to connect to it again
1370 // just exit the program
1371 if (activeclose == 1)
1372 break;
1373 }
1374
1375 freeaddrinfo(addrinfo);
1376 return 0;
1377 }
1378
1379 #ifdef _WIN32
1380 //
1381 // Main routine of a passive-mode service thread.
1382 //
1383 unsigned __stdcall main_passive_serviceloop_thread(void *ptr)
1384 {
1385 struct sock_copy sock = *(struct sock_copy *)ptr;
1386 free(ptr);
1387
1388 //
1389 // Handle this client.
1390 // This is passive mode, so we don't care whether we were
1391 // told by the client to close.
1392 //
1393 (void)daemon_serviceloop(sock.sockctrl, sock.sockctrl, 0,
1394 nullAuthAllowed, uses_ssl);
1395
1396 sock_close(sock.sockctrl, NULL, 0);
1397
1398 return 0;
1399 }
1400 #endif