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 "portability.h"
49 #include "config_params.h" // configuration file parameters
50 #include "fileconf.h" // for the configuration file management
51 #include "rpcap-protocol.h"
52 #include "daemon.h" // the true main() method of this daemon
56 #include <process.h> // for thread stuff
57 #include "win32-svc.h" // for Win32 service stuff
58 #include "getopt.h" // for getopt()-for-Windows
60 #include <fcntl.h> // for open()
61 #include <unistd.h> // for exit()
62 #include <sys/wait.h> // waitpid()
66 // Element in list of sockets on which we're listening for connections.
69 struct listen_sock
*next
;
74 char hostlist
[MAX_HOST_LIST
+ 1]; //!< Keeps the list of the hosts that are allowed to connect to this server
75 struct active_pars activelist
[MAX_ACTIVE_LIST
]; //!< Keeps the list of the hosts (host, port) on which I want to connect to (active mode)
76 int nullAuthAllowed
; //!< '1' if we permit NULL authentication, '0' otherwise
77 static struct listen_sock
*listen_socks
; //!< sockets on which we listen
78 char loadfile
[MAX_LINE
+ 1]; //!< Name of the file from which we have to load the configuration
79 int passivemode
= 1; //!< '1' if we want to run in passive mode as well
80 struct addrinfo mainhints
; //!< temporary struct to keep settings needed to open the new socket
81 char address
[MAX_LINE
+ 1]; //!< keeps the network address (either numeric or literal) to bind to
82 char port
[MAX_LINE
+ 1]; //!< keeps the network port to bind to
84 static HANDLE state_change_event
; //!< event to signal that a state change should take place
86 static volatile sig_atomic_t shutdown_server
; //!< '1' if the server is to shut down
87 static volatile sig_atomic_t reread_config
; //!< '1' if the server is to re-read its configuration
89 extern char *optarg
; // for getopt()
91 // Function definition
93 static unsigned __stdcall
main_active(void *ptr
);
94 static BOOL WINAPI
main_ctrl_event(DWORD
);
96 static void *main_active(void *ptr
);
97 static void main_terminate(int sign
);
98 static void main_reread_config(int sign
);
100 static void accept_connections(void);
101 static void accept_connection(SOCKET listen_sock
);
103 static void main_reap_children(int sign
);
106 static unsigned __stdcall
main_passive_serviceloop_thread(void *ptr
);
109 #define RPCAP_ACTIVE_WAIT 30 /* Waiting time between two attempts to open a connection, in active mode (default: 30 sec) */
112 \brief Prints the usage screen if it is launched in console mode.
114 static void printusage(void)
118 " " PROGRAM_NAME
" [-b <address>] [-p <port>] [-4] [-l <host_list>] [-a <host,port>]\n"
123 "[-s <file>] [-f <file>]\n\n"
124 " -b <address> the address to bind to (either numeric or literal).\n"
125 " Default: binds to all local IPv4 and IPv6 addresses\n\n"
126 " -p <port> the port to bind to.\n"
127 " Default: binds to port " RPCAP_DEFAULT_NETPORT
"\n\n"
128 " -4 use only IPv4.\n"
129 " Default: use both IPv4 and IPv6 waiting sockets\n\n"
130 " -l <host_list> a file that contains a list of hosts that are allowed\n"
131 " to connect to this server (if more than one, list them one\n"
133 " We suggest to use literal names (instead of numeric ones)\n"
134 " in order to avoid problems with different address families.\n\n"
135 " -n permit NULL authentication (usually used with '-l')\n\n"
136 " -a <host,port> run in active mode when connecting to 'host' on port 'port'\n"
137 " In case 'port' is omitted, the default port (" RPCAP_DEFAULT_NETPORT_ACTIVE
") is used\n\n"
138 " -v run in active mode only (default: if '-a' is specified, it\n"
139 " accepts passive connections as well)\n\n"
140 " -d run in daemon mode (UNIX only) or as a service (Win32 only)\n"
141 " Warning (Win32): this switch is provided automatically when\n"
142 " the service is started from the control panel\n\n"
144 " -i run in inetd mode (UNIX only)\n\n"
146 " -s <file> save the current configuration to file\n\n"
147 " -f <file> load the current configuration from file; all switches\n"
148 " specified from the command line are ignored\n\n"
149 " -h print this help screen\n\n";
151 (void)fprintf(stderr
, "RPCAPD, a remote packet capture daemon.\n"
152 "Compiled with %s\n\n", pcap_lib_version());
153 printf("%s", usagetext
);
159 int main(int argc
, char *argv
[])
161 char savefile
[MAX_LINE
+ 1]; // name of the file on which we have to save the configuration
162 int isdaemon
= 0; // Non-zero if the user wants to run this program as a daemon
164 int isrunbyinetd
= 0; // Non-zero if this is being run by inetd or something inetd-like
166 int retval
; // keeps the returning value from several functions
167 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
169 struct sigaction action
;
177 memset(errbuf
, 0, sizeof(errbuf
));
179 if (sock_init(errbuf
, PCAP_ERRBUF_SIZE
) == -1)
181 SOCK_MESSAGE(errbuf
);
185 strncpy(address
, RPCAP_DEFAULT_NETADDR
, MAX_LINE
);
186 strncpy(port
, RPCAP_DEFAULT_NETPORT
, MAX_LINE
);
188 // Prepare to open a new server socket
189 memset(&mainhints
, 0, sizeof(struct addrinfo
));
191 mainhints
.ai_family
= PF_UNSPEC
;
192 mainhints
.ai_flags
= AI_PASSIVE
; // Ready to a bind() socket
193 mainhints
.ai_socktype
= SOCK_STREAM
;
195 // Getting the proper command line options
196 while ((retval
= getopt(argc
, argv
, "b:dhip:4l:na:s:f:v")) != -1)
201 strncpy(address
, optarg
, MAX_LINE
);
204 strncpy(port
, optarg
, MAX_LINE
);
207 mainhints
.ai_family
= PF_INET
; // IPv4 server only
228 strncpy(hostlist
, optarg
, sizeof(hostlist
));
233 char *tmpaddress
, *tmpport
;
237 tmpaddress
= pcap_strtok_r(optarg
, RPCAP_HOSTLIST_SEP
, &lasts
);
239 while ((tmpaddress
!= NULL
) && (i
< MAX_ACTIVE_LIST
))
241 tmpport
= pcap_strtok_r(NULL
, RPCAP_HOSTLIST_SEP
, &lasts
);
243 strlcpy(activelist
[i
].address
, tmpaddress
, MAX_LINE
);
245 if ((tmpport
== NULL
) || (strcmp(tmpport
, "DEFAULT") == 0)) // the user choose a custom port
246 strlcpy(activelist
[i
].port
, RPCAP_DEFAULT_NETPORT_ACTIVE
, MAX_LINE
);
248 strlcpy(activelist
[i
].port
, tmpport
, MAX_LINE
);
250 tmpaddress
= pcap_strtok_r(NULL
, RPCAP_HOSTLIST_SEP
, &lasts
);
255 if (i
> MAX_ACTIVE_LIST
)
256 SOCK_MESSAGE("Only MAX_ACTIVE_LIST active connections are currently supported.");
258 // I don't initialize the remaining part of the structure, since
259 // it is already zeroed (it is a global var)
263 strlcpy(loadfile
, optarg
, MAX_LINE
);
266 strlcpy(savefile
, optarg
, MAX_LINE
);
279 if (isdaemon
&& isrunbyinetd
)
281 fprintf(stderr
, "rpcapd: -d and -i can't be used together\n");
286 if (savefile
[0] && fileconf_save(savefile
))
287 SOCK_MESSAGE("Error when saving the configuration to file");
289 // If the file does not exist, it keeps the settings provided by the command line
295 // Create a handle to signal the main loop to tell it to do
298 state_change_event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
299 if (state_change_event
== NULL
)
301 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
302 rpcapd_log(LOGPRIO_ERROR
, "Can't create state change event: %s",
308 // Catch control signals.
310 if (!SetConsoleCtrlHandler(main_ctrl_event
, TRUE
))
312 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
313 rpcapd_log(LOGPRIO_ERROR
, "Can't set control handler: %s",
318 memset(&action
, 0, sizeof (action
));
319 action
.sa_handler
= main_terminate
;
321 sigemptyset(&action
.sa_mask
);
322 sigaction(SIGTERM
, &action
, NULL
);
323 memset(&action
, 0, sizeof (action
));
324 action
.sa_handler
= main_reap_children
;
326 sigemptyset(&action
.sa_mask
);
327 sigaction(SIGCHLD
, &action
, NULL
);
328 // Ignore SIGPIPE - we'll get EPIPE when trying to write to a closed
329 // connection, we don't want to get killed by a signal in that case
330 signal(SIGPIPE
, SIG_IGN
);
337 // -i was specified, indicating that this is being run
338 // by inetd or something that can run network daemons
339 // as if it were inetd (xinetd, launchd, systemd, etc.).
341 // Our standard input is the input side of a connection,
342 // and our standard output is the output side of a
345 int sockctrl_in
, sockctrl_out
;
349 // Duplicate the standard input and output, making them
350 // the input and output side of the control connection.
352 sockctrl_in
= dup(0);
353 if (sockctrl_in
== -1)
355 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
356 rpcapd_log(LOGPRIO_ERROR
, "Can't dup standard input: %s",
360 sockctrl_out
= dup(1);
361 if (sockctrl_out
== -1)
363 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
364 rpcapd_log(LOGPRIO_ERROR
, "Can't dup standard output: %s",
370 // Try to set the standard input and output to /dev/null.
372 devnull_fd
= open("/dev/null", O_RDWR
);
373 if (devnull_fd
!= -1)
376 // If this fails, just drive on.
378 (void)dup2(devnull_fd
, 0);
379 (void)dup2(devnull_fd
, 1);
384 // Handle this client.
385 // This is passive mode, so we don't care whether we were
386 // told by the client to close.
388 (void)daemon_serviceloop(sockctrl_in
, sockctrl_out
, 0,
392 // Nothing more to do.
401 // This is being run as a daemon.
402 // On UN*X, it might be manually run, or run from an
409 // Daemonize ourselves.
411 // Unix Network Programming, pg 336
413 if ((pid
= fork()) != 0)
414 exit(0); // Parent terminates
416 // First child continues
420 // generated under unix with 'kill -HUP', needed to reload the configuration
421 memset(&action
, 0, sizeof (action
));
422 action
.sa_handler
= main_reread_config
;
424 sigemptyset(&action
.sa_mask
);
425 sigaction(SIGHUP
, &action
, NULL
);
427 if ((pid
= fork()) != 0)
428 exit(0); // First child terminates
430 // LINUX WARNING: the current linux implementation of pthreads requires a management thread
431 // to handle some hidden stuff. So, as soon as you create the first thread, two threads are
432 // created. Fom this point on, the number of threads active are always one more compared
433 // to the number you're expecting
435 // Second child continues
440 // This is being run as a service on Windows.
442 // If this call succeeds, it is blocking on Win32
444 if (svc_start() != 1)
445 SOCK_MESSAGE("Unable to start the service");
447 // When the previous call returns, the entire application has to be stopped.
454 // Enable the catching of Ctrl+C
455 memset(&action
, 0, sizeof (action
));
456 action
.sa_handler
= main_terminate
;
458 sigemptyset(&action
.sa_mask
);
459 sigaction(SIGINT
, &action
, NULL
);
461 // generated under unix with 'kill -HUP', needed to reload the configuration
462 // We do not have this kind of signal in Win32
463 memset(&action
, 0, sizeof (action
));
464 action
.sa_handler
= main_reread_config
;
466 sigemptyset(&action
.sa_mask
);
467 sigaction(SIGHUP
, &action
, NULL
);
470 printf("Press CTRL + C to stop the server...\n");
473 // If we're a Win32 service, we have already called this function in the service_main
476 // The code should never arrive here (since the main_startup is blocking)
477 // however this avoids a compiler warning
481 void main_startup(void)
483 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
484 struct addrinfo
*addrinfo
; // keeps the addrinfo chain; required to open a new socket
487 HANDLE threadId
; // handle for the subthread
494 memset(errbuf
, 0, sizeof(errbuf
));
496 // Starts all the active threads
497 while ((i
< MAX_ACTIVE_LIST
) && (activelist
[i
].address
[0] != 0))
499 activelist
[i
].ai_family
= mainhints
.ai_family
;
502 threadId
= (HANDLE
)_beginthreadex(NULL
, 0, main_active
,
503 (void *)&activelist
[i
], 0, NULL
);
506 SOCK_MESSAGE("Error creating the active child threads");
509 CloseHandle(threadId
);
511 if ((pid
= fork()) == 0) // I am the child
513 main_active((void *) &activelist
[i
]);
521 * The code that manages the active connections is not blocking;
522 * the code that manages the passive connection is blocking.
523 * So, if the user does not want to run in passive mode, we have
524 * to block the main thread here, otherwise the program ends and
525 * all threads are stopped.
527 * WARNING: this means that in case we have only active mode,
528 * the program does not terminate even if all the child thread
529 * terminates. The user has always to press Ctrl+C (or send a
530 * SIGTERM) to terminate the program.
534 struct addrinfo
*tempaddrinfo
;
537 // Get a list of sockets on which to listen.
539 if (sock_initaddress((address
[0]) ? address
: NULL
, port
, &mainhints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
541 SOCK_MESSAGE(errbuf
);
545 for (tempaddrinfo
= addrinfo
; tempaddrinfo
;
546 tempaddrinfo
= tempaddrinfo
->ai_next
)
549 struct listen_sock
*sock_info
;
551 if ((sock
= sock_open(tempaddrinfo
, SOCKOPEN_SERVER
, SOCKET_MAXCONN
, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
553 SOCK_MESSAGE(errbuf
);
557 sock_info
= (struct listen_sock
*) malloc(sizeof (struct listen_sock
));
558 if (sock_info
== NULL
)
560 rpcapd_log(LOGPRIO_ERROR
, "Can't allocate structure for listen socket");
563 sock_info
->sock
= sock
;
564 sock_info
->next
= listen_socks
;
565 listen_socks
= sock_info
;
568 freeaddrinfo(addrinfo
);
571 // Now listen on all of them, waiting for connections.
573 accept_connections();
579 SOCK_MESSAGE(PROGRAM_NAME
" is closing.\n");
583 // Sends a KILL signal to all the processes in this process's
584 // process group; i.e., it kills all the child processes
587 // XXX - that also includes us, so we will be killed as well;
588 // that may cause a message to be printed or logged.
594 // Just leave. We shouldn't need to clean up sockets or
595 // anything else, and if we try to do so, we'll could end
596 // up closing sockets, or shutting Winsock down, out from
597 // under service loops, causing all sorts of noisy error
600 // We shouldn't need to worry about cleaning up any resources
601 // such as handles, sockets, threads, etc. - exit() should
602 // terminate the process, causing all those resources to be
603 // cleaned up (including the threads; Microsoft claims in the
604 // ExitProcess() documentation that, if ExitProcess() is called,
605 // "If a thread is waiting on a kernel object, it will not be
606 // terminated until the wait has completed.", but claims in the
607 // _beginthread()/_beginthreadex() documentation that "All threads
608 // are terminated if any thread calls abort, exit, _exit, or
609 // ExitProcess." - the latter appears to be the case, even for
610 // threads waiting on the event for a pcap_t).
617 send_state_change_event(void)
619 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
621 if (!SetEvent(state_change_event
))
623 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
624 rpcapd_log(LOGPRIO_ERROR
, "SetEvent on shutdown event failed: %s", errbuf
);
629 send_shutdown_notification(void)
632 // Indicate that the server should shut down.
637 // Send a state change event, to wake up WSAWaitForMultipleEvents().
639 send_state_change_event();
643 send_reread_configuration_notification(void)
646 // Indicate that the server should re-read its configuration file.
651 // Send a state change event, to wake up WSAWaitForMultipleEvents().
653 send_state_change_event();
656 static BOOL WINAPI
main_ctrl_event(DWORD ctrltype
)
659 // ctrltype is one of:
661 // CTRL_C_EVENT - we got a ^C; this is like SIGINT
662 // CTRL_BREAK_EVENT - we got Ctrl+Break
663 // CTRL_CLOSE_EVENT - the console was closed; this is like SIGHUP
664 // CTRL_LOGOFF_EVENT - a user is logging off; this is received
666 // CTRL_SHUTDOWN_EVENT - the systemis shutting down; this is
667 // received only by services
669 // For now, we treat all but CTRL_LOGOFF_EVENT as indications
670 // that we should shut down.
675 case CTRL_BREAK_EVENT
:
676 case CTRL_CLOSE_EVENT
:
677 case CTRL_SHUTDOWN_EVENT
:
679 // Set a shutdown notification.
681 send_shutdown_notification();
694 static void main_terminate(int sign
)
697 // Note that the server should shut down.
698 // select() should get an EINTR error when we return,
699 // so it will wake up and know it needs to check the flag.
704 static void main_reread_config(int sign
)
707 // Note that the server should re-read its configuration file.
708 // select() should get an EINTR error when we return,
709 // so it will wake up and know it needs to check the flag.
716 static void main_reap_children(int sign
)
721 // Reap all child processes that have exited.
722 // For reference, Stevens, pg 128
724 while ((pid
= waitpid(-1, &exitstat
, WNOHANG
)) > 0)
725 SOCK_MESSAGE("Child terminated");
732 // Loop waiting for incoming connections and accepting them.
735 accept_connections(void)
738 struct listen_sock
*sock_info
;
742 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
745 // How big does the set of events need to be?
746 // One for the shutdown event, plus one for every socket on which
747 // we'll be listening.
749 num_events
= 1; // shutdown event
750 for (sock_info
= listen_socks
; sock_info
;
751 sock_info
= sock_info
->next
)
753 if (num_events
== WSA_MAXIMUM_WAIT_EVENTS
)
756 // WSAWaitForMultipleEvents() doesn't support
757 // more than WSA_MAXIMUM_WAIT_EVENTS events
760 rpcapd_log(LOGPRIO_ERROR
, "Too many sockets on which to listen");
767 // Allocate the array of events.
769 events
= (WSAEVENT
*) malloc(num_events
* sizeof (WSAEVENT
));
772 rpcapd_log(LOGPRIO_ERROR
, "Can't allocate array of events which to listen");
779 events
[0] = state_change_event
; // state change event first
780 for (sock_info
= listen_socks
, i
= 1; sock_info
;
781 sock_info
= sock_info
->next
, i
++)
786 // Create an event that is signaled if there's a connection
787 // to accept on the socket in question.
789 event
= WSACreateEvent();
790 if (event
== WSA_INVALID_EVENT
)
792 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
793 rpcapd_log(LOGPRIO_ERROR
, "Can't create socket event: %s", errbuf
);
796 if (WSAEventSelect(sock_info
->sock
, event
, FD_ACCEPT
) == SOCKET_ERROR
)
798 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
799 rpcapd_log(LOGPRIO_ERROR
, "Can't setup socket event: %s", errbuf
);
808 // Wait for incoming connections.
812 ret
= WSAWaitForMultipleEvents(num_events
, events
, FALSE
,
813 WSA_INFINITE
, FALSE
);
814 if (ret
== WSA_WAIT_FAILED
)
816 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
817 rpcapd_log(LOGPRIO_ERROR
, "WSAWaitForMultipleEvents failed: %s", errbuf
);
821 if (ret
== WSA_WAIT_EVENT_0
)
824 // The state change event was set.
829 // Time to quit. Exit the loop.
836 // We should re-read the configuration
839 reread_config
= 0; // clear the indicator
845 // Check each socket.
847 for (sock_info
= listen_socks
, i
= 1; sock_info
;
848 sock_info
= sock_info
->next
, i
++)
850 WSANETWORKEVENTS network_events
;
852 if (WSAEnumNetworkEvents(sock_info
->sock
,
853 events
[i
], &network_events
) == SOCKET_ERROR
)
855 sock_geterror(NULL
, errbuf
, PCAP_ERRBUF_SIZE
);
856 rpcapd_log(LOGPRIO_ERROR
, "WSAEnumNetworkEvents failed: %s", errbuf
);
859 if (network_events
.lNetworkEvents
& FD_ACCEPT
)
862 // Did an error occur?
864 if (network_events
.iErrorCode
[FD_ACCEPT_BIT
] != 0)
867 // Yes - report it and keep going.
870 network_events
.iErrorCode
[FD_ACCEPT_BIT
],
873 rpcapd_log(LOGPRIO_ERROR
, "Socket error: %s", errbuf
);
878 // Accept the connection.
880 accept_connection(sock_info
->sock
);
885 struct listen_sock
*sock_info
;
889 // How big does the bitset of sockets on which to select() have
893 for (sock_info
= listen_socks
; sock_info
; sock_info
= sock_info
->next
)
895 if (sock_info
->sock
+ 1 > num_sock_fds
)
897 if (sock_info
->sock
+ 1 > FD_SETSIZE
)
899 rpcapd_log(LOGPRIO_ERROR
, "Socket FD is too bit for an fd_set");
902 num_sock_fds
= sock_info
->sock
+ 1;
912 // Set up an fd_set for all the sockets on which we're
915 // This set is modified by select(), so we have to
916 // construct it anew each time.
919 for (sock_info
= listen_socks
; sock_info
;
920 sock_info
= sock_info
->next
)
922 FD_SET(sock_info
->sock
, &sock_fds
);
926 // Wait for incoming connections.
928 ret
= select(num_sock_fds
, &sock_fds
, NULL
, NULL
, NULL
);
934 // If this is a "terminate the
935 // server" signal, exit the loop,
936 // otherwise just keep trying.
941 // Time to quit. Exit the loop.
948 // We should re-read the configuration
951 reread_config
= 0; // clear the indicator
956 // Go back and wait again.
962 rpcapd_log(LOGPRIO_ERROR
, "select failed: %s",
969 // Check each socket.
971 for (sock_info
= listen_socks
; sock_info
;
972 sock_info
= sock_info
->next
)
974 if (FD_ISSET(sock_info
->sock
, &sock_fds
))
977 // Accept the connection.
979 accept_connection(sock_info
->sock
);
986 // Close all the listen sockets.
988 for (sock_info
= listen_socks
; sock_info
; sock_info
= sock_info
->next
)
990 closesocket(sock_info
->sock
);
996 // Accept a connection and start a worker thread, on Windows, or a
997 // worker process, on UN*X, to handle the connection.
1000 accept_connection(SOCKET listen_sock
)
1002 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
1003 SOCKET sockctrl
; // keeps the socket ID for this control connection
1004 struct sockaddr_storage from
; // generic sockaddr_storage variable
1005 socklen_t fromlen
; // keeps the length of the sockaddr_storage variable
1008 HANDLE threadId
; // handle for the subthread
1010 SOCKET
*sockctrl_temp
;
1015 // Initialize errbuf
1016 memset(errbuf
, 0, sizeof(errbuf
));
1020 // Accept the connection
1021 fromlen
= sizeof(struct sockaddr_storage
);
1023 sockctrl
= accept(listen_sock
, (struct sockaddr
*) &from
, &fromlen
);
1025 if (sockctrl
!= INVALID_SOCKET
)
1031 // The accept() call can return this error when a signal is catched
1032 // In this case, we have simply to ignore this error code
1035 if (WSAGetLastError() == WSAEINTR
)
1041 // Don't check for errors here, since the error can be due to the fact that the thread
1043 sock_geterror("accept(): ", errbuf
, PCAP_ERRBUF_SIZE
);
1044 rpcapd_log(LOGPRIO_ERROR
, "Accept of control connection from client failed: %s",
1050 // We have a connection.
1051 // Check whether the connecting host is among the ones allowed.
1053 if (sock_check_hostlist(hostlist
, RPCAP_HOSTLIST_SEP
, &from
, errbuf
, PCAP_ERRBUF_SIZE
) < 0)
1055 rpcap_senderror(sockctrl
, 0, PCAP_ERR_HOSTNOAUTH
, errbuf
, NULL
);
1056 sock_close(sockctrl
, NULL
, 0);
1062 // Put the socket back into blocking mode; doing WSAEventSelect()
1063 // on the listen socket makes that socket non-blocking, and it
1064 // appears that sockets returned from an accept() on that socket
1065 // are also non-blocking.
1067 // First, we have to un-WSAEventSelect() this socket, and then
1068 // we can turn non-blocking mode off.
1070 if (WSAEventSelect(sockctrl
, NULL
, 0) == SOCKET_ERROR
)
1072 sock_geterror("ioctlsocket(FIONBIO): ", errbuf
, PCAP_ERRBUF_SIZE
);
1073 rpcap_senderror(sockctrl
, 0, PCAP_ERR_HOSTNOAUTH
, errbuf
, NULL
);
1074 sock_close(sockctrl
, NULL
, 0);
1077 if (ioctlsocket(sockctrl
, FIONBIO
, &off
) == SOCKET_ERROR
)
1079 sock_geterror("ioctlsocket(FIONBIO): ", errbuf
, PCAP_ERRBUF_SIZE
);
1080 rpcap_senderror(sockctrl
, 0, PCAP_ERR_HOSTNOAUTH
, errbuf
, NULL
);
1081 sock_close(sockctrl
, NULL
, 0);
1086 // Allocate a location to hold the value of sockctrl.
1087 // It will be freed in the newly-created thread once it's
1088 // finished with it.
1089 // I guess we *could* just cast sockctrl to a void *, but that's
1092 sockctrl_temp
= (SOCKET
*)malloc(sizeof (SOCKET
));
1093 if (sockctrl_temp
== NULL
)
1095 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1096 errno
, "malloc() failed");
1097 rpcap_senderror(sockctrl
, 0, PCAP_ERR_OPEN
, errbuf
, NULL
);
1098 sock_close(sockctrl
, NULL
, 0);
1101 *sockctrl_temp
= sockctrl
;
1103 threadId
= (HANDLE
)_beginthreadex(NULL
, 0,
1104 main_passive_serviceloop_thread
, (void *) sockctrl_temp
, 0, NULL
);
1107 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Error creating the child thread");
1108 rpcap_senderror(sockctrl
, 0, PCAP_ERR_OPEN
, errbuf
, NULL
);
1109 sock_close(sockctrl
, NULL
, 0);
1110 free(sockctrl_temp
);
1113 CloseHandle(threadId
);
1118 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Error creating the child process");
1119 rpcap_senderror(sockctrl
, 0, PCAP_ERR_OPEN
, errbuf
, NULL
);
1120 sock_close(sockctrl
, NULL
, 0);
1128 // Close the socket on which we're listening (must
1129 // be open only in the parent).
1131 closesocket(listen_sock
);
1135 // Modify thread params so that it can be killed at any time
1136 // XXX - is this necessary? This is the main and, currently,
1137 // only thread in the child process, and nobody tries to
1138 // cancel us, although *we* may cancel the thread that's
1139 // handling the capture loop.
1141 if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE
, NULL
))
1143 if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS
, NULL
))
1148 // Run the service loop.
1149 // This is passive mode, so we don't care whether we were
1150 // told by the client to close.
1152 (void)daemon_serviceloop(sockctrl
, sockctrl
, 0,
1161 // Close the socket for this session (must be open only in the child)
1162 closesocket(sockctrl
);
1167 \brief 'true' main of the program in case the active mode is turned on.
1169 This function loops forever trying to connect to the remote host, until the
1170 daemon is turned down.
1172 \param ptr: it keeps the 'activepars' parameters. It is a 'void *'
1173 just because the thread APIs want this format.
1176 static unsigned __stdcall
1180 main_active(void *ptr
)
1182 char errbuf
[PCAP_ERRBUF_SIZE
+ 1]; // keeps the error string, prior to be printed
1183 SOCKET sockctrl
; // keeps the socket ID for this control connection
1184 struct addrinfo hints
; // temporary struct to keep settings needed to open the new socket
1185 struct addrinfo
*addrinfo
; // keeps the addrinfo chain; required to open a new socket
1186 struct active_pars
*activepars
;
1188 activepars
= (struct active_pars
*) ptr
;
1190 // Prepare to open a new server socket
1191 memset(&hints
, 0, sizeof(struct addrinfo
));
1192 // WARNING Currently it supports only ONE socket family among IPv4 and IPv6
1193 hints
.ai_family
= AF_INET
; // PF_UNSPEC to have both IPv4 and IPv6 server
1194 hints
.ai_socktype
= SOCK_STREAM
;
1195 hints
.ai_family
= activepars
->ai_family
;
1197 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Connecting to host %s, port %s, using protocol %s",
1198 activepars
->address
, activepars
->port
, (hints
.ai_family
== AF_INET
) ? "IPv4":
1199 (hints
.ai_family
== AF_INET6
) ? "IPv6" : "Unspecified");
1200 SOCK_MESSAGE(errbuf
);
1202 // Initialize errbuf
1203 memset(errbuf
, 0, sizeof(errbuf
));
1206 if (sock_initaddress(activepars
->address
, activepars
->port
, &hints
, &addrinfo
, errbuf
, PCAP_ERRBUF_SIZE
) == -1)
1208 SOCK_MESSAGE(errbuf
);
1216 if ((sockctrl
= sock_open(addrinfo
, SOCKOPEN_CLIENT
, 0, errbuf
, PCAP_ERRBUF_SIZE
)) == INVALID_SOCKET
)
1218 SOCK_MESSAGE(errbuf
);
1220 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Error connecting to host %s, port %s, using protocol %s",
1221 activepars
->address
, activepars
->port
, (hints
.ai_family
== AF_INET
) ? "IPv4":
1222 (hints
.ai_family
== AF_INET6
) ? "IPv6" : "Unspecified");
1224 SOCK_MESSAGE(errbuf
);
1226 sleep_secs(RPCAP_ACTIVE_WAIT
);
1231 activeclose
= daemon_serviceloop(sockctrl
, sockctrl
, 1,
1234 sock_close(sockctrl
, NULL
, 0);
1236 // If the connection is closed by the user explicitely, don't try to connect to it again
1237 // just exit the program
1238 if (activeclose
== 1)
1242 freeaddrinfo(addrinfo
);
1248 // Main routine of a passive-mode service thread.
1250 unsigned __stdcall
main_passive_serviceloop_thread(void *ptr
)
1254 sockctrl
= *((SOCKET
*)ptr
);
1258 // Handle this client.
1259 // This is passive mode, so we don't care whether we were
1260 // told by the client to close.
1262 (void)daemon_serviceloop(sockctrl
, sockctrl
, 0, nullAuthAllowed
);
1264 sock_close(sockctrl
, NULL
, 0);