64using std::ostringstream;
67#include "ServerExitConditions.h"
68#include "SocketListener.h"
70#include "UnixSocket.h"
72#include "BESModuleApp.h"
73#include "DaemonCommandHandler.h"
74#include "BESServerUtils.h"
78#include "TheBESKeys.h"
80#include "BESDaemonConstants.h"
82#define BES_SERVER "/beslistener"
83#define BES_SERVER_PID "/bes.pid"
84#define DAEMON_PORT_STR "BES.DaemonPort"
85#define DAEMON_UNIX_SOCK_STR "BES.DaemonUnixSocket"
88extern "C" int set_sups(
const int target_sups_size,
const gid_t*
const target_sups_list);
92void unblock_signals();
93int start_master_beslistener();
94bool stop_all_beslisteners(
int sig);
96static string daemon_name;
99static string beslistener_path;
100static string file_for_daemon_pid;
103volatile int master_beslistener_status = BESLISTENER_STOPPED;
104volatile int num_children = 0;
105static volatile int master_beslistener_pid = -1;
107typedef map<string, string> arg_map;
108static arg_map global_args;
109static string debug_sink =
"";
117static volatile sig_atomic_t sigchild = 0;
118static volatile sig_atomic_t sigterm = 0;
119static volatile sig_atomic_t sighup = 0;
121static string errno_str(
const string &msg)
124 oss << daemon_name << msg;
125 const char *perror_string = strerror(errno);
126 if (perror_string) oss << perror_string;
139static int pr_exit(
int status)
141 if (WIFEXITED(status)) {
142 switch (WEXITSTATUS(status)) {
143 case SERVER_EXIT_NORMAL_SHUTDOWN:
146 case SERVER_EXIT_FATAL_CANNOT_START:
147 cerr << daemon_name <<
": server cannot start, exited with status " << WEXITSTATUS(status) << endl;
148 cerr <<
"Please check all error messages " <<
"and adjust server installation" << endl;
151 case SERVER_EXIT_ABNORMAL_TERMINATION:
152 cerr << daemon_name <<
": abnormal server termination, exited with status " << WEXITSTATUS(status) << endl;
155 case SERVER_EXIT_RESTART:
156 cerr << daemon_name <<
": server has been requested to re-start." << endl;
157 return SERVER_EXIT_RESTART;
163 else if (WIFSIGNALED(status)) {
164 cerr << daemon_name <<
": abnormal server termination, signaled with signal number " << WTERMSIG(status)
167 if (WCOREDUMP(status)) {
168 cerr << daemon_name <<
": server dumped core." << endl;
174 else if (WIFSTOPPED(status)) {
175 cerr << daemon_name <<
": abnormal server termination, stopped with signal number " << WSTOPSIG(status) << endl;
190 sigaddset(&set, SIGCHLD);
191 sigaddset(&set, SIGHUP);
192 sigaddset(&set, SIGTERM);
194 if (sigprocmask(SIG_BLOCK, &set, 0) < 0) {
195 cerr << errno_str(
": sigprocmask error, blocking signals in stop_all_beslisteners ");
200void unblock_signals()
204 sigaddset(&set, SIGCHLD);
205 sigaddset(&set, SIGHUP);
206 sigaddset(&set, SIGTERM);
208 if (sigprocmask(SIG_UNBLOCK, &set, 0) < 0) {
209 cerr << errno_str(
": sigprocmask error unblocking signals in stop_all_beslisteners ");
226bool stop_all_beslisteners(
int sig)
228 BESDEBUG(
"besdaemon",
"besdaemon: stopping listeners" << endl);
232 BESDEBUG(
"besdaemon",
"besdaemon: master_beslistener_pid " << master_beslistener_pid << endl);
235 int status = killpg(master_beslistener_pid, sig);
238 cerr <<
"The sig argument is not a valid signal number." << endl;
243 <<
"The sending process is not the super-user and one or more of the target processes has an effective user ID different from that of the sending process."
248 cerr <<
"No process can be found in the process group specified by the process group ("
249 << master_beslistener_pid <<
")." << endl;
256 bool mbes_status_caught =
false;
258 while ((pid = wait(&status)) > 0) {
259 BESDEBUG(
"besdaemon",
"besdaemon: caught listener: " << pid <<
" raw status: " << status << endl);
260 if (pid == master_beslistener_pid) {
261 master_beslistener_status = pr_exit(status);
262 mbes_status_caught =
true;
263 BESDEBUG(
"besdaemon",
264 "besdaemon: caught master beslistener: " << pid <<
" status: " << master_beslistener_status << endl);
268 BESDEBUG(
"besdaemon",
"besdaemon: done catching listeners (last pid:" << pid <<
")" << endl);
271 BESDEBUG(
"besdaemon",
"besdaemon: unblocking signals " << endl);
272 return mbes_status_caught;
282char **update_beslistener_args()
284 char **arguments =
new char*[global_args.size() * 2 + 1];
288 arguments[0] = strdup(global_args[
"beslistener"].c_str());
291 arg_map::iterator it;
292 for (it = global_args.begin(); it != global_args.end(); ++it) {
293 BESDEBUG(
"besdaemon",
"besdaemon; global_args " << (*it).first <<
" => " << (*it).second << endl);
297 if ((*it).first ==
"-d") {
298 arguments[i++] = strdup(
"-d");
303 arguments[i++] = strdup(debug_opts.c_str());
305 else if ((*it).first !=
"beslistener") {
306 arguments[i++] = strdup((*it).first.c_str());
307 arguments[i++] = strdup((*it).second.c_str());
327int start_master_beslistener()
332 if (pipe(pipefd) < 0) {
333 cerr << errno_str(
": pipe error ");
338 if ((pid = fork()) < 0) {
339 cerr << errno_str(
": fork error ");
353 if (dup2(pipefd[1], BESLISTENER_PIPE_FD) != BESLISTENER_PIPE_FD) {
354 cerr << errno_str(
": dup2 error ");
360 char **arguments = update_beslistener_args();
362 BESDEBUG(
"besdaemon",
"Starting: " << arguments[0] << endl);
367 if (command_server) command_server->closeConnection();
370 execvp(arguments[0], arguments);
373 cerr << errno_str(
": mounting listener, subprocess failed: ");
384 BESDEBUG(
"besdaemon",
"besdaemon: master beslistener pid: " << pid << endl);
387 int beslistener_start_status;
388 int status = read(pipefd[0], &beslistener_start_status,
sizeof(beslistener_start_status));
391 cerr <<
"Could not read master beslistener status; the master pid was not changed." << endl;
395 else if (beslistener_start_status != BESLISTENER_RUNNING) {
396 cerr <<
"The beslistener status is not 'BESLISTENER_RUNNING' (it is '" << beslistener_start_status
397 <<
"') the master pid was not changed." << endl;
402 BESDEBUG(
"besdaemon",
"besdaemon: master beslistener start status: " << beslistener_start_status << endl);
405 master_beslistener_pid = pid;
406 master_beslistener_status = BESLISTENER_RUNNING;
416static void cleanup_resources()
422 if (!access(file_for_daemon_pid.c_str(), F_OK)) {
423 (void) remove(file_for_daemon_pid.c_str());
427 (void) remove(file_for_daemon_pid.c_str());
433static void CatchSigChild(
int signal)
435 if (signal == SIGCHLD) {
440static void CatchSigHup(
int signal)
442 if (signal == SIGHUP) {
447static void CatchSigTerm(
int signal)
449 if (signal == SIGTERM) {
454static void process_signals()
464 int pid = wait(&status);
471 if (pid == master_beslistener_pid) master_beslistener_status = pr_exit(status);
488 stop_all_beslisteners(SIGHUP);
491 if (start_master_beslistener() == 0) {
492 cerr <<
"Could not restart the master beslistener." << endl;
493 stop_all_beslisteners(SIGTERM);
506 stop_all_beslisteners(SIGTERM);
530 BESDEBUG(
"besdaemon",
"besdaemon: Starting command processor." << endl);
541 port = strtol(port_str.c_str(), &ptr, 10);
543 cerr <<
"Invalid port number for daemon command interface: " << port_str << endl;
549 BESDEBUG(
"besdaemon",
"besdaemon: listening on port: " << port << endl);
551 listener.listen(my_socket);
558 if (!usock_str.empty()) {
559 BESDEBUG(
"besdaemon",
"besdaemon: listening on unix socket: " << usock_str << endl);
561 listener.listen(unix_socket);
564 if (!port_found && !usock_found) {
565 BESDEBUG(
"besdaemon",
"Neither a port nor a unix socket was set for the daemon command interface." << endl);
569 BESDEBUG(
"besdaemon",
"besdaemon: starting command interface on port: " << port << endl);
570 command_server =
new PPTServer(&handler, &listener,
false);
580 command_server->closeConnection();
586 cerr <<
"daemon: " <<
"caught unknown exception" << endl;
589 delete command_server;
599 stop_all_beslisteners(SIGTERM);
612static void register_signal_handlers()
614 struct sigaction act;
617 sigemptyset(&act.sa_mask);
618 sigaddset(&act.sa_mask, SIGCHLD);
619 sigaddset(&act.sa_mask, SIGTERM);
620 sigaddset(&act.sa_mask, SIGHUP);
623 BESDEBUG(
"besdaemon",
"besdaemon: setting restart for sigchld." << endl);
624 act.sa_flags |= SA_RESTART;
627 act.sa_handler = CatchSigChild;
628 if (sigaction(SIGCHLD, &act, 0)) {
629 cerr <<
"Could not register a handler to catch beslistener status." << endl;
633 act.sa_handler = CatchSigTerm;
634 if (sigaction(SIGTERM, &act, 0) < 0) {
635 cerr <<
"Could not register a handler to catch the terminate signal." << endl;
639 act.sa_handler = CatchSigHup;
640 if (sigaction(SIGHUP, &act, 0) < 0) {
641 cerr <<
"Could not register a handler to catch the hang-up signal." << endl;
652static int daemon_init()
655 if ((pid = fork()) < 0)
669static void store_daemon_id(
int pid)
671 ofstream f(file_for_daemon_pid.c_str());
673 cerr << errno_str(
": unable to create pid file " + file_for_daemon_pid +
": ");
681 mode_t new_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
682 (void) chmod(file_for_daemon_pid.c_str(), new_mode);
694static bool load_names(
const string &install_dir,
const string &pid_dir)
696 string bindir =
"/bin";
697 if (!pid_dir.empty()) {
698 file_for_daemon_pid = pid_dir;
701 if (!install_dir.empty()) {
702 beslistener_path = install_dir;
703 beslistener_path += bindir;
704 if (file_for_daemon_pid.empty()) {
705 file_for_daemon_pid = install_dir +
"/var/run";
714 string prog = daemon_name;
715 string::size_type slash = prog.find_last_of(
'/');
716 if (slash != string::npos) {
717 beslistener_path = prog.substr(0, slash);
718 slash = prog.find_last_of(
'/');
719 if (slash != string::npos) {
720 string root = prog.substr(0, slash);
721 if (file_for_daemon_pid.empty()) {
722 file_for_daemon_pid = root +
"/var/run";
728 if (file_for_daemon_pid.empty()) {
729 file_for_daemon_pid = beslistener_path;
735 if (beslistener_path ==
"") {
736 beslistener_path =
".";
737 if (file_for_daemon_pid.empty()) {
738 file_for_daemon_pid =
"./run";
742 beslistener_path += BES_SERVER;
743 file_for_daemon_pid += BES_SERVER_PID;
745 if (access(beslistener_path.c_str(), F_OK) != 0) {
746 cerr << daemon_name <<
": cannot find " << beslistener_path << endl
747 <<
"Please either pass -i <install_dir> on the command line." << endl;
752 global_args[
"beslistener"] = beslistener_path;
757static void set_group_id()
759#if !defined(OS2) && !defined(TPF)
765 BESDEBUG(
"server",
"beslistener: Setting group id ... " << endl);
767 string key =
"BES.Group";
773 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
776 ERROR_LOG(err << endl);
777 exit(SERVER_EXIT_FATAL_CANNOT_START);
780 if (!found || group_str.empty()) {
781 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
782 string err =
"FAILED: Group not specified in BES configuration file";
784 ERROR_LOG(err << endl);
785 exit(SERVER_EXIT_FATAL_CANNOT_START);
787 BESDEBUG(
"server",
"to " << group_str <<
" ... " << endl);
790 if (group_str[0] ==
'#') {
792 const char *group_c = group_str.c_str();
794 new_gid = atoi(group_c);
800 ent = getgrnam(group_str.c_str());
802 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
803 string err = (string)
"FAILED: Group " + group_str +
" does not exist";
805 ERROR_LOG(err << endl);
806 exit(SERVER_EXIT_FATAL_CANNOT_START);
808 new_gid = ent->gr_gid;
812 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
814 err <<
"FAILED: Group id " << new_gid <<
" not a valid group id for BES";
815 cerr << err.str() << endl;
816 ERROR_LOG(err.str() << endl);
817 exit(SERVER_EXIT_FATAL_CANNOT_START);
820 BESDEBUG(
"server",
"to id " << new_gid <<
" ... " << endl);
821 if (setgid(new_gid) == -1) {
822 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
824 err <<
"FAILED: unable to set the group id to " << new_gid;
825 cerr << err.str() << endl;
826 ERROR_LOG(err.str() << endl);
827 exit(SERVER_EXIT_FATAL_CANNOT_START);
830 BESDEBUG(
"server",
"OK" << endl);
832 BESDEBUG(
"server",
"beslistener: Groups not supported in this OS" << endl );
836static void set_user_id()
838 BESDEBUG(
"server",
"beslistener: Setting user id ... " << endl);
845 string key =
"BES.User";
851 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
852 string err = (string)
"FAILED: " + e.
get_message();
854 ERROR_LOG(err << endl);
855 exit(SERVER_EXIT_FATAL_CANNOT_START);
858 if (!found || user_str.empty()) {
859 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
860 string err = (string)
"FAILED: User not specified in BES config file";
862 ERROR_LOG(err << endl);
863 exit(SERVER_EXIT_FATAL_CANNOT_START);
865 BESDEBUG(
"server",
"to " << user_str <<
" ... " << endl);
868 if (user_str[0] ==
'#') {
869 const char *user_str_c = user_str.c_str();
871 new_id = atoi(user_str_c);
875 ent = getpwnam(user_str.c_str());
877 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
878 string err = (string)
"FAILED: Bad user name specified: " + user_str;
880 ERROR_LOG(err << endl);
881 exit(SERVER_EXIT_FATAL_CANNOT_START);
883 new_id = ent->pw_uid;
888 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
889 string err = (string)
"FAILED: BES cannot run as root";
891 ERROR_LOG(err << endl);
892 exit(SERVER_EXIT_FATAL_CANNOT_START);
897 vector<gid_t> groups(1);
898 groups.at(0) = getegid();
899 if (set_sups(groups.size(), &groups[0]) == -1) {
900 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
902 err <<
"FAILED: Unable to relinquish supplementary groups (" << new_id <<
")";
903 cerr << err.str() << endl;
904 ERROR_LOG(err.str() << endl);
905 exit(SERVER_EXIT_FATAL_CANNOT_START);
908 BESDEBUG(
"server",
"to " << new_id <<
" ... " << endl);
909 if (setuid(new_id) == -1) {
910 BESDEBUG(
"server",
"beslistener: FAILED" << endl);
912 err <<
"FAILED: Unable to set user id to " << new_id;
913 cerr << err.str() << endl;
914 ERROR_LOG(err.str() << endl);
915 exit(SERVER_EXIT_FATAL_CANNOT_START);
918 BESDEBUG(
"server",
"OK" << endl);
924int main(
int argc,
char *argv[])
926 uid_t curr_euid = geteuid();
931 cerr <<
"FAILED: Must be root to run BES" << endl;
932 exit(SERVER_EXIT_FATAL_CANNOT_START);
935 cerr <<
"Developer Mode: Not testing if BES is run by root" << endl;
938 daemon_name =
"besdaemon";
943 bool become_daemon =
true;
949 BESServerUtils::show_usage(daemon_name);
955 string config_file =
"";
957 unsigned short num_args = 1;
962 while ((c = getopt(argc, argv,
"hvsd:c:p:u:i:r:n")) != -1) {
965 BESServerUtils::show_version(daemon_name);
969 BESServerUtils::show_usage(daemon_name);
973 cerr <<
"Running in foreground!" << endl;
977 install_dir = optarg;
979 cout <<
"The specified install directory (-i option) "
980 <<
"is incorrectly formatted. Must be less than "
981 <<
"255 characters and include the characters " <<
"[0-9A-z_./-]" << endl;
984 global_args[
"-i"] = install_dir;
988 global_args[
"-s"] =
"";
994 cout <<
"The specified state directory (-r option) "
995 <<
"is incorrectly formatted. Must be less than "
996 <<
"255 characters and include the characters " <<
"[0-9A-z_./-]" << endl;
999 global_args[
"-r"] = pid_dir;
1003 config_file = optarg;
1005 cout <<
"The specified configuration file (-c option) "
1006 <<
"is incorrectly formatted. Must be less than "
1007 <<
"255 characters and include the characters " <<
"[0-9A-z_./-]" << endl;
1010 global_args[
"-c"] = config_file;
1015 string check_path = optarg;
1017 cout <<
"The specified unix socket (-u option) " <<
"is incorrectly formatted. Must be less than "
1018 <<
"255 characters and include the characters " <<
"[0-9A-z_./-]" << endl;
1021 global_args[
"-u"] = check_path;
1027 string port_num = optarg;
1028 for (
unsigned int i = 0; i < port_num.length(); i++) {
1029 if (!isdigit(port_num[i])) {
1030 cout <<
"The specified port contains non-digit " <<
"characters: " << port_num << endl;
1034 global_args[
"-p"] = port_num;
1040 string check_arg = optarg;
1042 cout <<
"The specified debug options \"" << check_arg <<
"\" contains invalid characters" << endl;
1046 global_args[
"-d"] = check_arg;
1047 debug_sink = check_arg.substr(0, check_arg.find(
','));
1052 BESServerUtils::show_usage(daemon_name);
1060 if (argc > num_args) {
1061 cout << daemon_name <<
": too many arguments passed to the BES";
1062 BESServerUtils::show_usage(daemon_name);
1065 if (pid_dir.empty()) {
1066 pid_dir = install_dir;
1070 if (!config_file.empty()) {
1077 if (config_file.empty() && !install_dir.empty()) {
1078 if (install_dir[install_dir.length() - 1] !=
'/') {
1081 string conf_file = install_dir +
"etc/bes/bes.conf";
1088 cerr <<
"Caught BES Error while processing the daemon's options: " << e.
get_message() << endl;
1091 catch (std::exception &e) {
1092 cerr <<
"Caught C++ error while processing the daemon's options: " << e.what() << endl;
1096 cerr <<
"Caught unknown error while processing the daemon's options." << endl;
1102 if (!load_names(install_dir, pid_dir))
return 1;
1104 if (!access(file_for_daemon_pid.c_str(), F_OK)) {
1105 ifstream temp(file_for_daemon_pid.c_str());
1106 cout << daemon_name <<
": there seems to be a BES daemon already running at ";
1108 temp.getline(buf, 500);
1109 cout << buf << endl;
1118 store_daemon_id(getpid());
1120 if (curr_euid == 0) {
1122 cerr <<
"Developer Mode: Running as root - setting group and user ids" << endl;
1128 cerr <<
"Developer Mode: Not setting group or user ids" << endl;
1131 register_signal_handlers();
1138 cerr <<
"Could not initialize the modules to get the log contexts." << endl;
1156 if (global_args.count(
"-d") == 0) {
1184 master_beslistener_pid = start_master_beslistener();
1185 if (master_beslistener_pid == 0) {
1186 cerr << daemon_name <<
": server cannot mount at first try (core dump). "
1187 <<
"Please correct problems on the process manager " << beslistener_path << endl;
1188 return master_beslistener_pid;
1191 BESDEBUG(
"besdaemon",
"besdaemon: master_beslistener_pid: " << master_beslistener_pid << endl);
1196 cerr <<
"Caught BES Error during initialization: " << e.
get_message() << endl;
1199 catch (std::exception &e) {
1200 cerr <<
"Caught C++ error during initialization: " << e.what() << endl;
1204 cerr <<
"Caught unknown error during initialization." << endl;
1214 status = start_command_processor(handler);
1225 BESDEBUG(
"besdaemon",
"besdaemon: master_beslistener_status: " << master_beslistener_status << endl);
1226 if (master_beslistener_status == BESLISTENER_RESTART) {
1227 master_beslistener_status = BESLISTENER_STOPPED;
1229 start_master_beslistener();
1232 else if (master_beslistener_status != BESLISTENER_RUNNING) {
1242 cerr <<
"Caught BES Error while starting the command handler: " << e.
get_message() << endl;
1244 catch (std::exception &e) {
1246 cerr <<
"Caught C++ error while starting the command handler: " << e.what() << endl;
1250 cerr <<
"Caught unknown error while starting the command handler." << endl;
1253 BESDEBUG(
"besdaemon",
"besdaemon: past the command processor start" << endl);
1255 cleanup_resources();
static void SetStrm(std::ostream *strm, bool created)
set the debug output stream to the specified stream
static void SetUp(const std::string &values)
Sets up debugging for the bes.
static void Register(const std::string &flagName)
register the specified debug flag
static std::string GetOptionsString()
Abstract exception class for the BES with basic string message.
virtual std::string get_message()
get the error message for this exception
Base application object for all BES applications.
virtual int initialize(int argC, char **argV)
Load and initialize any BES modules.
static bool pathname_ok(const std::string &path, bool strict)
Does the string name a potentailly valid pathname? Test the given pathname to verfiy that it is a val...
static bool command_line_arg_ok(const std::string &arg)
sanitize command line arguments
virtual void initConnection()
void get_value(const std::string &s, std::string &val, bool &found)
Retrieve the value of a given key, if set.
static TheBESKeys * TheKeys()
static std::string ConfigFile