2 * Copyright (c) 2002 - 2003
3 * NetGroup, Politecnico di Torino (Italy)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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.
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()
46 #include "sockutils.h" // for socket calls
47 #include "varattrs.h" // for _U_
48 #include "portability.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
61 #include <process.h> // for thread stuff
62 #include "win32-svc.h" // for Win32 service stuff
63 #include "getopt.h" // for getopt()-for-Windows
65 #include <fcntl.h> // for open()
66 #include <unistd.h> // for exit()
67 #include <sys/wait.h> // waitpid()
71 // Element in list of sockets on which we're listening for connections.
74 struct listen_sock
*next
;
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
89 static HANDLE state_change_event
; //!< event to signal that a state change should take place
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
95 extern char *optarg
; // for getopt()
97 // Function definition
99 static unsigned __stdcall
main_active(void *ptr
);
100 static BOOL WINAPI
main_ctrl_event(DWORD
);
102 static void *main_active(void *ptr
);
103 static void main_terminate(int sign
);
104 static void main_reread_config(int sign
);
106 static void accept_connections(void);
107 static void accept_connection(SOCKET listen_sock
);
109 static void main_reap_children(int sign
);
112 static unsigned __stdcall
main_passive_serviceloop_thread(void *ptr
);
115 #define RPCAP_ACTIVE_WAIT 30 /* Waiting time between two attempts to open a connection, in active mode (default: 30 sec) */
118 \brief Prints the usage screen if it is launched in console mode.
120 static void printusage(void)
122 const char *usagetext
=
124 " " PROGRAM_NAME
" [-b <address>] [-p <port>] [-4] [-l <host_list>] [-a <host,port>]\n"
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"
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"
150 " -i run in inetd mode (UNIX only)\n\n"
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"
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";
163 (void)fprintf(stderr
, "RPCAPD, a remote packet capture daemon.\n"
164 "Compiled with %s\n\n", pcap_lib_version());
165 printf("%s", usagetext
);
171 int main(int argc
, char *argv
[])
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
177 int isrunbyinetd
= 0; // Non-zero if this is being run by inetd or something inetd-like
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
183 struct sigaction action
;
186 int enable_compression
= 0;
194 memset(errbuf
, 0, sizeof(errbuf
));
196 strncpy(address
, RPCAP_DEFAULT_NETADDR
, MAX_LINE
);
197 strncpy(port
, RPCAP_DEFAULT_NETPORT
, MAX_LINE
);
199 // Prepare to open a new server socket
200 memset(&mainhints
, 0, sizeof(struct addrinfo
));
202 mainhints
.ai_family
= PF_UNSPEC
;
203 mainhints
.ai_flags
= AI_PASSIVE
; // Ready to a bind() socket
204 mainhints
.ai_socktype
= SOCK_STREAM
;
206 // Getting the proper command line options
208 # define SSL_CLOPTS "SK:X:C"
210 # define SSL_CLOPTS ""
213 # define CLOPTS "b:dDhip:4l:na:s:f:v" SSL_CLOPTS
215 while ((retval
= getopt(argc
, argv
, CLOPTS
)) != -1)
220 log_debug_messages
= 1;
221 rpcapd_log_set(log_to_systemlog
, log_debug_messages
);
224 strncpy(address
, optarg
, MAX_LINE
);
227 strncpy(port
, optarg
, MAX_LINE
);
230 mainhints
.ai_family
= PF_INET
; // IPv4 server only
234 log_to_systemlog
= 1;
235 rpcapd_log_set(log_to_systemlog
, log_debug_messages
);
243 log_to_systemlog
= 1;
244 rpcapd_log_set(log_to_systemlog
, log_debug_messages
);
255 strncpy(hostlist
, optarg
, sizeof(hostlist
));
260 char *tmpaddress
, *tmpport
;
264 tmpaddress
= pcap_strtok_r(optarg
, RPCAP_HOSTLIST_SEP
, &lasts
);
266 while ((tmpaddress
!= NULL
) && (i
< MAX_ACTIVE_LIST
))
268 tmpport
= pcap_strtok_r(NULL
, RPCAP_HOSTLIST_SEP
, &lasts
);
270 pcap_strlcpy(activelist
[i
].address
, tmpaddress
, MAX_LINE
);
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
);
275 pcap_strlcpy(activelist
[i
].port
, tmpport
, MAX_LINE
);
277 tmpaddress
= pcap_strtok_r(NULL
, RPCAP_HOSTLIST_SEP
, &lasts
);
282 if (i
> MAX_ACTIVE_LIST
)
283 rpcapd_log(LOGPRIO_ERROR
, "Only MAX_ACTIVE_LIST active connections are currently supported.");
285 // I don't initialize the remaining part of the structure, since
286 // it is already zeroed (it is a global var)
290 pcap_strlcpy(loadfile
, optarg
, MAX_LINE
);
293 pcap_strlcpy(savefile
, optarg
, MAX_LINE
);
300 enable_compression
= 1;
303 ssl_set_keyfile(optarg
);
306 ssl_set_certfile(optarg
);
320 if (isdaemon
&& isrunbyinetd
)
322 rpcapd_log(LOGPRIO_ERROR
, "rpcapd: -d and -i can't be used together");
327 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
329 rpcapd_log(LOGPRIO_ERROR
, "%s", errbuf
);
333 if (savefile
[0] && fileconf_save(savefile
))
334 rpcapd_log(LOGPRIO_DEBUG
, "Error when saving the configuration to file");
336 // If the file does not exist, it keeps the settings provided by the command line
342 // Create a handle to signal the main loop to tell it to do
345 state_change_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
346 if (state_change_event
== NULL
)
348 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
349 rpcapd_log(LOGPRIO_ERROR
, "Can't create state change event: %s",
355 // Catch control signals.
357 if (!SetConsoleCtrlHandler(main_ctrl_event
, TRUE
))
359 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
360 rpcapd_log(LOGPRIO_ERROR
, "Can't set control handler: %s",
365 memset(&action
, 0, sizeof (action
));
366 action
.sa_handler
= main_terminate
;
368 sigemptyset(&action
.sa_mask
);
369 sigaction(SIGTERM
, &action
, NULL
);
370 memset(&action
, 0, sizeof (action
));
371 action
.sa_handler
= main_reap_children
;
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
);
382 if (ssl_init_once(1, enable_compression
, errbuf
, PCAP_ERRBUF_SIZE
) < 0)
384 rpcapd_log(LOGPRIO_ERROR
, "Can't initialize SSL: %s",
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.).
399 // Our standard input is the input side of a connection,
400 // and our standard output is the output side of a
403 int sockctrl_in
, sockctrl_out
;
407 // Duplicate the standard input and output, making them
408 // the input and output side of the control connection.
410 sockctrl_in
= dup(0);
411 if (sockctrl_in
== -1)
413 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
414 rpcapd_log(LOGPRIO_ERROR
, "Can't dup standard input: %s",
418 sockctrl_out
= dup(1);
419 if (sockctrl_out
== -1)
421 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
422 rpcapd_log(LOGPRIO_ERROR
, "Can't dup standard output: %s",
428 // Try to set the standard input, output, and error
431 devnull_fd
= open("/dev/null", O_RDWR
);
432 if (devnull_fd
!= -1)
435 // If this fails, just drive on.
437 (void)dup2(devnull_fd
, 0);
438 (void)dup2(devnull_fd
, 1);
439 (void)dup2(devnull_fd
, 2);
444 // Handle this client.
445 // This is passive mode, so we don't care whether we were
446 // told by the client to close.
448 char *hostlist_copy
= strdup(hostlist
);
449 if (hostlist_copy
== NULL
)
451 rpcapd_log(LOGPRIO_ERROR
, "Out of memory copying the host/port list");
454 (void)daemon_serviceloop(sockctrl_in
, sockctrl_out
, 0,
455 hostlist_copy
, nullAuthAllowed
, uses_ssl
);
457 sock_close(sockctrl_out
, NULL
, 0);
460 // Nothing more to do.
469 // This is being run as a daemon.
470 // On UN*X, it might be manually run, or run from an
477 // Daemonize ourselves.
479 // Unix Network Programming, pg 336
481 if ((pid
= fork()) != 0)
482 exit(0); // Parent terminates
484 // First child continues
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
;
492 sigemptyset(&action
.sa_mask
);
493 sigaction(SIGHUP
, &action
, NULL
);
495 if ((pid
= fork()) != 0)
496 exit(0); // First child terminates
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
503 // Second child continues
508 // This is being run as a service on Windows.
510 // If this call succeeds, it is blocking on Win32
512 if (svc_start() != 1)
513 rpcapd_log(LOGPRIO_DEBUG
, "Unable to start the service");
515 // When the previous call returns, the entire application has to be stopped.
522 // Enable the catching of Ctrl+C
523 memset(&action
, 0, sizeof (action
));
524 action
.sa_handler
= main_terminate
;
526 sigemptyset(&action
.sa_mask
);
527 sigaction(SIGINT
, &action
, NULL
);
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
;
534 sigemptyset(&action
.sa_mask
);
535 sigaction(SIGHUP
, &action
, NULL
);
538 printf("Press CTRL + C to stop the server...\n");
541 // If we're a Win32 service, we have already called this function in the service_main
544 // The code should never arrive here (since the main_startup is blocking)
545 // however this avoids a compiler warning
549 void main_startup(void)
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
555 HANDLE threadId
; // handle for the subthread
562 memset(errbuf
, 0, sizeof(errbuf
));
564 // Starts all the active threads
565 while ((i
< MAX_ACTIVE_LIST
) && (activelist
[i
].address
[0] != 0))
567 activelist
[i
].ai_family
= mainhints
.ai_family
;
570 threadId
= (HANDLE
)_beginthreadex(NULL
, 0, main_active
,
571 (void *)&activelist
[i
], 0, NULL
);
574 rpcapd_log(LOGPRIO_DEBUG
, "Error creating the active child threads");
577 CloseHandle(threadId
);
579 if ((pid
= fork()) == 0) // I am the child
581 main_active((void *) &activelist
[i
]);
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.
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.
602 struct addrinfo
*tempaddrinfo
;
605 // Get a list of sockets on which to listen.
607 if (sock_initaddress((address
[0]) ? address
: NULL
, port
, &mainhints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
609 rpcapd_log(LOGPRIO_DEBUG
, "%s", errbuf
);
613 for (tempaddrinfo
= addrinfo
; tempaddrinfo
;
614 tempaddrinfo
= tempaddrinfo
->ai_next
)
617 struct listen_sock
*sock_info
;
619 if ((sock
= sock_open(tempaddrinfo
, SOCKOPEN_SERVER
, SOCKET_MAXCONN
, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
621 switch (tempaddrinfo
->ai_family
)
625 struct sockaddr_in
*in
;
626 char addrbuf
[INET_ADDRSTRLEN
];
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
)),
639 struct sockaddr_in6
*in6
;
640 char addrbuf
[INET6_ADDRSTRLEN
];
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
),
652 rpcapd_log(LOGPRIO_WARNING
, "Can't listen on socket for address family %u: %s",
653 tempaddrinfo
->ai_family
,
660 sock_info
= (struct listen_sock
*) malloc(sizeof (struct listen_sock
));
661 if (sock_info
== NULL
)
663 rpcapd_log(LOGPRIO_ERROR
, "Can't allocate structure for listen socket");
666 sock_info
->sock
= sock
;
667 sock_info
->next
= listen_socks
;
668 listen_socks
= sock_info
;
671 freeaddrinfo(addrinfo
);
673 if (listen_socks
== NULL
)
675 rpcapd_log(LOGPRIO_ERROR
, "Can't listen on any address");
680 // Now listen on all of them, waiting for connections.
682 accept_connections();
688 rpcapd_log(LOGPRIO_DEBUG
, PROGRAM_NAME
" is closing.\n");
692 // Sends a KILL signal to all the processes in this process's
693 // process group; i.e., it kills all the child processes
696 // XXX - that also includes us, so we will be killed as well;
697 // that may cause a message to be printed or logged.
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
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).
726 send_state_change_event(void)
728 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
730 if (!SetEvent(state_change_event
))
732 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
733 rpcapd_log(LOGPRIO_ERROR
, "SetEvent on shutdown event failed: %s", errbuf
);
738 send_shutdown_notification(void)
741 // Indicate that the server should shut down.
746 // Send a state change event, to wake up WSAWaitForMultipleEvents().
748 send_state_change_event();
752 send_reread_configuration_notification(void)
755 // Indicate that the server should re-read its configuration file.
760 // Send a state change event, to wake up WSAWaitForMultipleEvents().
762 send_state_change_event();
765 static BOOL WINAPI
main_ctrl_event(DWORD ctrltype
)
768 // ctrltype is one of:
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
775 // CTRL_SHUTDOWN_EVENT - the systemis shutting down; this is
776 // received only by services
778 // For now, we treat all but CTRL_LOGOFF_EVENT as indications
779 // that we should shut down.
784 case CTRL_BREAK_EVENT
:
785 case CTRL_CLOSE_EVENT
:
786 case CTRL_SHUTDOWN_EVENT
:
788 // Set a shutdown notification.
790 send_shutdown_notification();
803 static void main_terminate(int sign _U_
)
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.
813 static void main_reread_config(int sign _U_
)
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.
823 static void main_reap_children(int sign _U_
)
828 // Reap all child processes that have exited.
829 // For reference, Stevens, pg 128
831 while ((pid
= waitpid(-1, &exitstat
, WNOHANG
)) > 0)
832 rpcapd_log(LOGPRIO_DEBUG
, "Child terminated");
839 // Loop waiting for incoming connections and accepting them.
842 accept_connections(void)
845 struct listen_sock
*sock_info
;
849 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
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.
856 num_events
= 1; // shutdown event
857 for (sock_info
= listen_socks
; sock_info
;
858 sock_info
= sock_info
->next
)
860 if (num_events
== WSA_MAXIMUM_WAIT_EVENTS
)
863 // WSAWaitForMultipleEvents() doesn't support
864 // more than WSA_MAXIMUM_WAIT_EVENTS events
867 rpcapd_log(LOGPRIO_ERROR
, "Too many sockets on which to listen");
874 // Allocate the array of events.
876 events
= (WSAEVENT
*) malloc(num_events
* sizeof (WSAEVENT
));
879 rpcapd_log(LOGPRIO_ERROR
, "Can't allocate array of events which to listen");
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
++)
893 // Create an event that is signaled if there's a connection
894 // to accept on the socket in question.
896 event
= WSACreateEvent();
897 if (event
== WSA_INVALID_EVENT
)
899 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
900 rpcapd_log(LOGPRIO_ERROR
, "Can't create socket event: %s", errbuf
);
903 if (WSAEventSelect(sock_info
->sock
, event
, FD_ACCEPT
) == SOCKET_ERROR
)
905 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
906 rpcapd_log(LOGPRIO_ERROR
, "Can't setup socket event: %s", errbuf
);
915 // Wait for incoming connections.
919 ret
= WSAWaitForMultipleEvents(num_events
, events
, FALSE
,
920 WSA_INFINITE
, FALSE
);
921 if (ret
== WSA_WAIT_FAILED
)
923 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
924 rpcapd_log(LOGPRIO_ERROR
, "WSAWaitForMultipleEvents failed: %s", errbuf
);
928 if (ret
== WSA_WAIT_EVENT_0
)
931 // The state change event was set.
936 // Time to quit. Exit the loop.
943 // We should re-read the configuration
946 reread_config
= 0; // clear the indicator
952 // Check each socket.
954 for (sock_info
= listen_socks
, i
= 1; sock_info
;
955 sock_info
= sock_info
->next
, i
++)
957 WSANETWORKEVENTS network_events
;
959 if (WSAEnumNetworkEvents(sock_info
->sock
,
960 events
[i
], &network_events
) == SOCKET_ERROR
)
962 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
963 rpcapd_log(LOGPRIO_ERROR
, "WSAEnumNetworkEvents failed: %s", errbuf
);
966 if (network_events
.lNetworkEvents
& FD_ACCEPT
)
969 // Did an error occur?
971 if (network_events
.iErrorCode
[FD_ACCEPT_BIT
] != 0)
974 // Yes - report it and keep going.
977 network_events
.iErrorCode
[FD_ACCEPT_BIT
],
980 rpcapd_log(LOGPRIO_ERROR
, "Socket error: %s", errbuf
);
985 // Accept the connection.
987 accept_connection(sock_info
->sock
);
992 struct listen_sock
*sock_info
;
996 // How big does the bitset of sockets on which to select() have
1000 for (sock_info
= listen_socks
; sock_info
; sock_info
= sock_info
->next
)
1002 if (sock_info
->sock
+ 1 > num_sock_fds
)
1004 if ((unsigned int)(sock_info
->sock
+ 1) >
1005 (unsigned int)FD_SETSIZE
)
1007 rpcapd_log(LOGPRIO_ERROR
, "Socket FD is too bit for an fd_set");
1010 num_sock_fds
= sock_info
->sock
+ 1;
1020 // Set up an fd_set for all the sockets on which we're
1023 // This set is modified by select(), so we have to
1024 // construct it anew each time.
1027 for (sock_info
= listen_socks
; sock_info
;
1028 sock_info
= sock_info
->next
)
1030 FD_SET(sock_info
->sock
, &sock_fds
);
1034 // Wait for incoming connections.
1036 ret
= select(num_sock_fds
, &sock_fds
, NULL
, NULL
, NULL
);
1042 // If this is a "terminate the
1043 // server" signal, exit the loop,
1044 // otherwise just keep trying.
1046 if (shutdown_server
)
1049 // Time to quit. Exit the loop.
1056 // We should re-read the configuration
1059 reread_config
= 0; // clear the indicator
1064 // Go back and wait again.
1070 rpcapd_log(LOGPRIO_ERROR
, "select failed: %s",
1077 // Check each socket.
1079 for (sock_info
= listen_socks
; sock_info
;
1080 sock_info
= sock_info
->next
)
1082 if (FD_ISSET(sock_info
->sock
, &sock_fds
))
1085 // Accept the connection.
1087 accept_connection(sock_info
->sock
);
1094 // Close all the listen sockets.
1096 for (sock_info
= listen_socks
; sock_info
; sock_info
= sock_info
->next
)
1098 closesocket(sock_info
->sock
);
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)
1115 // Accept a connection and start a worker thread, on Windows, or a
1116 // worker process, on UN*X, to handle the connection.
1119 accept_connection(SOCKET listen_sock
)
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
1127 HANDLE threadId
; // handle for the subthread
1129 struct sock_copy
*sock_copy
= NULL
;
1134 // Initialize errbuf
1135 memset(errbuf
, 0, sizeof(errbuf
));
1139 // Accept the connection
1140 fromlen
= sizeof(struct sockaddr_storage
);
1142 sockctrl
= accept(listen_sock
, (struct sockaddr
*) &from
, &fromlen
);
1144 if (sockctrl
!= INVALID_SOCKET
)
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
1154 if (WSAGetLastError() == WSAEINTR
)
1160 // Don't check for errors here, since the error can be due to the fact that the thread
1162 sock_geterror("accept(): ", errbuf
, PCAP_ERRBUF_SIZE
);
1163 rpcapd_log(LOGPRIO_ERROR
, "Accept of control connection from client failed: %s",
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.
1175 // First, we have to un-WSAEventSelect() this socket, and then
1176 // we can turn non-blocking mode off.
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.
1182 // So we just log the message and close the connection.
1184 if (WSAEventSelect(sockctrl
, NULL
, 0) == SOCKET_ERROR
)
1186 sock_geterror("WSAEventSelect: ", errbuf
, PCAP_ERRBUF_SIZE
);
1187 rpcapd_log(LOGPRIO_ERROR
, "%s", errbuf
);
1188 sock_close(sockctrl
, NULL
, 0);
1191 if (ioctlsocket(sockctrl
, FIONBIO
, &off
) == SOCKET_ERROR
)
1193 sock_geterror("ioctlsocket(FIONBIO): ", errbuf
, PCAP_ERRBUF_SIZE
);
1194 rpcapd_log(LOGPRIO_ERROR
, "%s", errbuf
);
1195 sock_close(sockctrl
, NULL
, 0);
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
1206 sock_copy
= malloc(sizeof(*sock_copy
));
1207 if (sock_copy
== NULL
)
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
);
1214 sock_copy
->sockctrl
= sockctrl
;
1216 threadId
= (HANDLE
)_beginthreadex(NULL
, 0,
1217 main_passive_serviceloop_thread
, (void *) sock_copy
, 0, NULL
);
1220 rpcapd_log(LOG_ERROR
, "Error creating the child thread");
1223 CloseHandle(threadId
);
1228 rpcapd_log(LOGPRIO_ERROR
, "Error creating the child process: %s",
1237 // Close the socket on which we're listening (must
1238 // be open only in the parent).
1240 closesocket(listen_sock
);
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.
1250 if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE
, NULL
))
1252 if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS
, NULL
))
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.
1261 char *hostlist_copy
= strdup(hostlist
);
1262 if (hostlist_copy
== NULL
)
1264 rpcapd_log(LOGPRIO_ERROR
, "Out of memory copying the host/port list");
1267 (void)daemon_serviceloop(sockctrl
, sockctrl
, 0,
1268 hostlist_copy
, nullAuthAllowed
, uses_ssl
);
1270 sock_close(sockctrl
, NULL
, 0);
1276 // Close the socket for this session (must be open only in the child)
1277 closesocket(sockctrl
);
1283 if (sock_copy
) free(sock_copy
);
1285 sock_close(sockctrl
, NULL
, 0);
1289 \brief 'true' main of the program in case the active mode is turned on.
1291 This function loops forever trying to connect to the remote host, until the
1292 daemon is turned down.
1294 \param ptr: it keeps the 'activepars' parameters. It is a 'void *'
1295 just because the thread APIs want this format.
1298 static unsigned __stdcall
1302 main_active(void *ptr
)
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
;
1310 activepars
= (struct active_pars
*) ptr
;
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
;
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");
1323 // Initialize errbuf
1324 memset(errbuf
, 0, sizeof(errbuf
));
1327 if (sock_initaddress(activepars
->address
, activepars
->port
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1329 rpcapd_log(LOGPRIO_DEBUG
, "%s", errbuf
);
1337 if ((sockctrl
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1339 rpcapd_log(LOGPRIO_DEBUG
, "%s", errbuf
);
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");
1345 rpcapd_log(LOGPRIO_DEBUG
, "%s", errbuf
);
1347 sleep_secs(RPCAP_ACTIVE_WAIT
);
1352 char *hostlist_copy
= strdup(hostlist
);
1353 if (hostlist_copy
== NULL
)
1355 rpcapd_log(LOGPRIO_ERROR
, "Out of memory copying the host/port list");
1361 // daemon_serviceloop() will free the copy.
1363 activeclose
= daemon_serviceloop(sockctrl
, sockctrl
, 1,
1364 hostlist_copy
, nullAuthAllowed
, uses_ssl
);
1367 sock_close(sockctrl
, NULL
, 0);
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)
1375 freeaddrinfo(addrinfo
);
1381 // Main routine of a passive-mode service thread.
1383 unsigned __stdcall
main_passive_serviceloop_thread(void *ptr
)
1385 struct sock_copy sock
= *(struct sock_copy
*)ptr
;
1389 // Handle this client.
1390 // This is passive mode, so we don't care whether we were
1391 // told by the client to close.
1393 (void)daemon_serviceloop(sock
.sockctrl
, sock
.sockctrl
, 0,
1394 nullAuthAllowed
, uses_ssl
);
1396 sock_close(sock
.sockctrl
, NULL
, 0);