bes Updated for version 3.21.1
The Backend Server (BES) is the lower two tiers of the Hyrax data server
daemon.cc
1// daemon.cc
2
3// This file is part of bes, A C++ back-end server implementation framework
4// for the OPeNDAP Data Access Protocol.
5
6// Copyright (c) 2004-2009 University Corporation for Atmospheric Research
7// Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu>
8//
9// This library is free software; you can redistribute it and/or
10// modify it under the terms of the GNU Lesser General Public
11// License as published by the Free Software Foundation; either
12// version 2.1 of the License, or (at your option) any later version.
13//
14// This library is distributed in the hope that it will be useful,
15// but WITHOUT ANY WARRANTY; without even the implied warranty of
16// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17// Lesser General Public License for more details.
18//
19// You should have received a copy of the GNU Lesser General Public
20// License along with this library; if not, write to the Free Software
21// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22//
23// You can contact University Corporation for Atmospheric Research at
24// 3080 Center Green Drive, Boulder, CO 80301
25
26// (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005
27// Please read the full copyright statement in the file COPYRIGHT_UCAR.
28//
29// Authors:
30// pwest Patrick West <pwest@ucar.edu>
31// jgarcia Jose Garcia <jgarcia@ucar.edu>
32
33#include "config.h"
34
35#include <unistd.h> // for getopt fork setsid execvp access geteuid
36
37#include <grp.h> // for getgrnam
38#include <pwd.h> // for getpwnam
39
40#include <sys/wait.h> // for waitpid
41#include <sys/stat.h> // for chmod
42#include <cctype> // for isdigit
43#include <csignal>
44
45#include <iostream>
46#include <string>
47#include <sstream>
48#include <cstring>
49#include <cstdlib>
50#include <cerrno>
51#include <map>
52#include <vector>
53
54#include "ServerExitConditions.h"
55#include "SocketListener.h"
56#include "TcpSocket.h"
57#include "UnixSocket.h"
58#include "PPTServer.h"
59#include "BESModuleApp.h"
60#include "DaemonCommandHandler.h"
61#include "BESServerUtils.h"
62#include "BESScrub.h"
63#include "BESError.h"
64#include "BESDebug.h"
65#include "TheBESKeys.h"
66#include "BESLog.h"
67#include "BESDaemonConstants.h"
68#include "BESUtil.h"
69
70#define BES_SERVER "/beslistener"
71#define BES_SERVER_PID "/bes.pid"
72#define DAEMON_PORT_STR "BES.DaemonPort"
73#define DAEMON_UNIX_SOCK_STR "BES.DaemonUnixSocket"
74
75using namespace std;
76
77// Defined in setgroups.c
78extern "C" int set_sups(int target_sups_size, gid_t* target_sups_list);
79
80// These are called from DaemonCommandHandler
81void block_signals();
82void unblock_signals();
83int start_master_beslistener();
84bool stop_all_beslisteners(int sig);
85
86static string daemon_name;
87
88// This two variables are set by load_names
89static string beslistener_path;
90static string file_for_daemon_pid;
91
92// This can be used to see if HUP or TERM has been sent to the master bes
93volatile int master_beslistener_status = BESLISTENER_STOPPED;
94#if 0
95volatile int num_children = 0;
96#endif
97static volatile int master_beslistener_pid = -1; // This is also the process group id
98
99typedef map<string, string> arg_map;
100static arg_map global_args;
101static string debug_sink;
102
103static TcpSocket *my_socket = nullptr;
104static UnixSocket *unix_socket = nullptr;
105static PPTServer *command_server = nullptr;
106
107// These are set to 1 by their respective handlers and then processed in the
108// signal processing loop. jhrg 3/5/14
109static volatile sig_atomic_t sigchild = 0;
110static volatile sig_atomic_t sigterm = 0;
111static volatile sig_atomic_t sighup = 0;
112
113static string errno_str(const string &msg)
114{
115 ostringstream oss;
116 oss << daemon_name << msg;
117 const char *perror_string = strerror(errno);
118 if (perror_string) oss << perror_string;
119 oss << endl;
120 return oss.str();
121}
122
131static int pr_exit(int status)
132{
133 if (WIFEXITED(status)) {
134 switch (WEXITSTATUS(status)) {
135 case SERVER_EXIT_NORMAL_SHUTDOWN:
136 return 0;
137
138 case SERVER_EXIT_FATAL_CANNOT_START:
139 cerr << daemon_name << ": server cannot start, exited with status " << WEXITSTATUS(status) << endl;
140 cerr << "Please check all error messages " << "and adjust server installation" << endl;
141 return 1;
142
143 case SERVER_EXIT_ABNORMAL_TERMINATION:
144 cerr << daemon_name << ": abnormal server termination, exited with status " << WEXITSTATUS(status) << endl;
145 return 1;
146
147 case SERVER_EXIT_RESTART:
148 cerr << daemon_name << ": server has been requested to re-start." << endl;
149 return SERVER_EXIT_RESTART;
150
151 default:
152 return 1;
153 }
154 }
155 else if (WIFSIGNALED(status)) {
156 cerr << daemon_name << ": abnormal server termination, signaled with signal number " << WTERMSIG(status)
157 << endl;
158#ifdef WCOREDUMP
159 if (WCOREDUMP(status)) {
160 cerr << daemon_name << ": server dumped core." << endl;
161 return 1;
162 }
163#endif
164 return 1;
165 }
166 else if (WIFSTOPPED(status)) {
167 cerr << daemon_name << ": abnormal server termination, stopped with signal number " << WSTOPSIG(status) << endl;
168 return 1;
169 }
170
171 return 0;
172}
173
178void block_signals()
179{
180 sigset_t set;
181 sigemptyset(&set);
182 sigaddset(&set, SIGCHLD);
183 sigaddset(&set, SIGHUP);
184 sigaddset(&set, SIGTERM);
185
186 if (sigprocmask(SIG_BLOCK, &set, nullptr) < 0) {
187 cerr << errno_str(": sigprocmask error, blocking signals in stop_all_beslisteners ");
188 }
189}
190
192void unblock_signals()
193{
194 sigset_t set;
195 sigemptyset(&set);
196 sigaddset(&set, SIGCHLD);
197 sigaddset(&set, SIGHUP);
198 sigaddset(&set, SIGTERM);
199
200 if (sigprocmask(SIG_UNBLOCK, &set, nullptr) < 0) {
201 cerr << errno_str(": sigprocmask error unblocking signals in stop_all_beslisteners ");
202 }
203}
204
218bool stop_all_beslisteners(int sig)
219{
220 BESDEBUG("besdaemon", "besdaemon: stopping listeners" << endl);
221
222 block_signals();
223
224 BESDEBUG("besdaemon", "besdaemon: master_beslistener_pid " << master_beslistener_pid << endl);
225 // Send 'sig' to all members of the process group with/of the master bes.
226 // The master beslistener pid is the group id of all the beslisteners.
227 int status = killpg(master_beslistener_pid, sig);
228 switch (status) {
229 case EINVAL:
230 cerr << "The sig argument is not a valid signal number." << endl;
231 break;
232
233 case EPERM:
234 cerr
235 << "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."
236 << endl;
237 break;
238
239 case ESRCH:
240 cerr << "No process can be found in the process group specified by the process group ("
241 << master_beslistener_pid << ")." << endl;
242 break;
243
244 default: // No error
245 break;
246 }
247
248 bool mbes_status_caught = false;
249 int pid;
250 while ((pid = wait(&status)) > 0) {
251 BESDEBUG("besdaemon", "besdaemon: caught listener: " << pid << " raw status: " << status << endl);
252 if (pid == master_beslistener_pid) {
253 master_beslistener_status = pr_exit(status);
254 mbes_status_caught = true;
255 BESDEBUG("besdaemon",
256 "besdaemon: caught master beslistener: " << pid << " status: " << master_beslistener_status << endl);
257 }
258 }
259
260 BESDEBUG("besdaemon", "besdaemon: done catching listeners (last pid:" << pid << ")" << endl);
261
262 unblock_signals();
263
264 BESDEBUG("besdaemon", "besdaemon: unblocking signals " << endl);
265
266 return mbes_status_caught;
267}
268
276char **update_beslistener_args()
277{
278 char **arguments = new char*[global_args.size() * 2 + 1];
279
280 // Marshal the arguments to the listener from the command line
281 // arguments to the daemon
282 arguments[0] = strdup(global_args["beslistener"].c_str());
283
284 int i = 1;
285 arg_map::iterator it;
286 for (it = global_args.begin(); it != global_args.end(); ++it) {
287 BESDEBUG("besdaemon", "besdaemon; global_args " << (*it).first << " => " << (*it).second << endl);
288 // Build the complete command line args for the beslistener, with
289 // special case code for -d and to omit the 'beslistener' line
290 // since it's already set in arguments[0].
291 if ((*it).first == "-d") {
292 arguments[i++] = strdup("-d");
293 // This is where the current debug/log settings are grabbed and
294 // used to build the correct '-d' option value for the new
295 // beslistener.
296 string debug_opts = debug_sink + "," + BESDebug::GetOptionsString();
297 arguments[i++] = strdup(debug_opts.c_str());
298 }
299 else if ((*it).first != "beslistener") {
300 arguments[i++] = strdup((*it).first.c_str());
301 arguments[i++] = strdup((*it).second.c_str());
302 }
303 }
304 arguments[i] = nullptr; // terminal null
305
306 return arguments;
307}
308
321int start_master_beslistener()
322{
323 // The only certain way to know that the beslistener master has started is
324 // to pass back its status once it is initialized. Use a pipe for that.
325 int pipefd[2];
326 if (pipe(pipefd) < 0) {
327 cerr << errno_str(": pipe error ");
328 return 0;
329 }
330
331 int pid;
332 if ((pid = fork()) < 0) {
333 cerr << errno_str(": fork error ");
334 return 0;
335 }
336 else if (pid == 0) { // child process (the master beslistener)
337 // See 'int ServerApp::run()' for the place where the program exec'd
338 // below writes the pid value to the pipe.
339
340 close(pipefd[0]); // Close the read end of the pipe in the child
341
342 // dup2 so we know the FD to write to in the child (the beslistener).
343 // BESLISTENER_PIPE_FD is '1' which is stdout; since beslistener is a
344 // daemon process both stdin and out have been closed so these descriptors
345 // are available. Using higher numbers can cause problems (see ticket
346 // 1783). jhrg 7/15/11
347 if (dup2(pipefd[1], MASTER_TO_DAEMON_PIPE_FD) != MASTER_TO_DAEMON_PIPE_FD) {
348 cerr << errno_str(": dup2 error ");
349 return 0;
350 }
351
352 // We don't have to free this because this is a different process
353 // than the parent.
354 char **arguments = update_beslistener_args();
355
356 BESDEBUG("besdaemon", "Starting: " << arguments[0] << endl);
357
358 // Close the socket for the besdaemon here. This keeps it from being
359 // passed into the master beslistener and then entering the state
360 // CLOSE_WAIT once the besdaemon's client closes its end.
361 if (command_server) command_server->closeConnection();
362
363 // This is where beslistener - the master listener - is started
364 execvp(arguments[0], arguments);
365
366 // if we are still here, it's an error...
367 cerr << errno_str(": mounting listener, subprocess failed: ");
368 exit(1); //NB: This exits from the child process.
369 }
370
371 // parent process (the besdaemon)
372
373 // The daemon records the pid of the master beslistener, but only does so
374 // when that process writes its status to the pipe 'fd'.
375
376 close(pipefd[1]); // close the write end of the pipe in the parent.
377
378 BESDEBUG("besdaemon", "besdaemon: master beslistener pid: " << pid << endl);
379
380 // Read the status from the child (beslistener).
381 int beslistener_start_status;
382 long status = read(pipefd[0], &beslistener_start_status, sizeof(beslistener_start_status));
383
384 if (status < 0) {
385 cerr << "Could not read master beslistener status; the master pid was not changed." << endl;
386 close(pipefd[0]);
387 return 0;
388 }
389 else if (beslistener_start_status != BESLISTENER_RUNNING) {
390 cerr << "The beslistener status is not 'BESLISTENER_RUNNING' (it is '" << beslistener_start_status
391 << "') the master pid was not changed." << endl;
392 close(pipefd[0]);
393 return 0;
394 }
395 else {
396 BESDEBUG("besdaemon", "besdaemon: master beslistener start status: " << beslistener_start_status << endl);
397 // Setting master_beslistener_pid here and not forcing callers to use the
398 // return value means that this global can be local to this file.
399 master_beslistener_pid = pid;
400 master_beslistener_status = BESLISTENER_RUNNING;
401 }
402
403 close(pipefd[0]);
404 return pid;
405}
406
410static void cleanup_resources()
411{
412 // TOCTOU error. Since the code ignores the error code from
413 // remove(), we might as well drop the test. We could test for an
414 // error and print a warning to the log... jhrg 10/23/15
415#if 0
416 if (!access(file_for_daemon_pid.c_str(), F_OK)) {
417 (void) remove(file_for_daemon_pid.c_str());
418 }
419#endif
420
421 (void) remove(file_for_daemon_pid.c_str());
422}
423
424// Note that SIGCHLD, SIGTERM and SIGHUP are blocked while in these three
425// signal handlers below.
426
427static void catch_sig_child(int signal)
428{
429 if (signal == SIGCHLD) {
430 sigchild = 1;
431 }
432}
433
434static void catch_sig_hup(int signal)
435{
436 if (signal == SIGHUP) {
437 sighup = 1;
438 }
439}
440
441static void catch_sig_term(int signal)
442{
443 if (signal == SIGTERM) {
444 sigterm = 1;
445 }
446}
447
448static void process_signals()
449{
450 block_signals();
451
452 // Process SIGCHLD. This is used to detect if the HUP signal was sent to the
453 // master listener and it has returned SERVER_EXIT_RESTART by recording
454 // that value in the global 'master_beslistener_status'. Other code needs
455 // to test that (static) global to see if the beslistener should be restarted.
456 if (sigchild) {
457 int status;
458 int pid = wait(&status);
459
460 // Decode and record the exit status, but only if it really is the
461 // master beslistener this daemon is using. If two or more Start commands
462 // are sent in a row, a master beslistener will start, fail to bind to
463 // the port (because another master beslstener is already bound to it)
464 // and exit. We don't want to record that second process's exit status here.
465 if (pid == master_beslistener_pid) master_beslistener_status = pr_exit(status);
466
467 sigchild = 0;
468 }
469
470 // The two following signals implement a simple stop/restart behavior
471 // for the daemon. The TERM signal (which is the default for the 'kill'
472 // command) is used to stop the entire server, including the besdaemon. The HUP
473 // signal is used to stop all beslisteners and then restart the master
474 // beslistener, forcing a re-read of the config file. Note that the daemon
475 // does not re-read the config file.
476
477 // When the daemon gets the HUP signal, it forwards that to each beslistener.
478 // They then all exit, returning the 'restart' code so that the daemon knows
479 // to restart the master beslistener.
480 if (sighup) {
481 // restart the beslistener(s); read their exit status
482 stop_all_beslisteners(SIGHUP);
483
484 // FIXME jhrg 3/5/14
485 if (start_master_beslistener() == 0) {
486 cerr << "Could not restart the master beslistener." << endl;
487 stop_all_beslisteners(SIGTERM);
488 cleanup_resources();
489 exit(1);
490 }
491
492 sighup = 0;
493 }
494
495 // When TERM (the default for 'kill') is sent to this process, send it also
496 // to each beslistener. This will cause the beslisteners to all exit with a zero
497 // value (the code for 'do not restart').
498 if (sigterm) {
499 // Stop all the beslistener(s); read their exit status
500 stop_all_beslisteners(SIGTERM);
501
502 // FIXME jhrg 3/5/14
503 cleanup_resources();
504 // Once all the child exit status values are read, exit the daemon
505 exit(0);
506 }
507
508 unblock_signals();
509}
510
522static int start_command_processor(DaemonCommandHandler &handler)
523{
524 BESDEBUG("besdaemon", "besdaemon: Starting command processor." << endl);
525
526 try {
527 SocketListener listener;
528
529 string port_str;
530 bool port_found;
531 int port = 0;
532 TheBESKeys::TheKeys()->get_value(DAEMON_PORT_STR, port_str, port_found);
533 if (port_found) {
534 port = std::stoi(port_str);
535 if (port == 0) {
536 cerr << "Invalid port number for daemon command interface: " << port_str << endl;
537 exit(1);
538 }
539 }
540
541 if (port) {
542 BESDEBUG("besdaemon", "besdaemon: listening on port: " << port << endl);
543 my_socket = new TcpSocket(port);
544 listener.listen(my_socket);
545 }
546
547 string usock_str;
548 bool usock_found;
549 TheBESKeys::TheKeys()->get_value(DAEMON_UNIX_SOCK_STR, usock_str, usock_found);
550
551 if (!usock_str.empty()) {
552 BESDEBUG("besdaemon", "besdaemon: listening on unix socket: " << usock_str << endl);
553 unix_socket = new UnixSocket(usock_str);
554 listener.listen(unix_socket);
555 }
556
557 if (!port_found && !usock_found) {
558 BESDEBUG("besdaemon", "Neither a port nor a unix socket was set for the daemon command interface." << endl);
559 return 0;
560 }
561
562 BESDEBUG("besdaemon", "besdaemon: starting command interface on port: " << port << endl);
563 command_server = new PPTServer(&handler, &listener, /*is_secure*/false);
564
565 // Once initialized, 'handler' loops until it's told to exit.
566 while (true) {
567 process_signals();
568
569 command_server->initConnection();
570 }
571 }
572 catch (BESError &se) {
573 cerr << "daemon: " << se.get_message() << endl;
574 }
575 catch (...) {
576 cerr << "daemon: " << "caught unknown exception" << endl;
577 }
578
579 // Once the handler exits, close sockets and free memory
580 command_server->closeConnection();
581
582 delete command_server;
583 command_server = nullptr;
584
585 // delete closes the sockets
586 delete my_socket;
587 my_socket = nullptr;
588 delete unix_socket;
589 unix_socket = nullptr;
590
591 // When/if the command interpreter exits, stop the all listeners.
592 stop_all_beslisteners(SIGTERM);
593
594 return 1;
595}
596
605static void register_signal_handlers()
606{
607 struct sigaction act;
608
609 // block child, term and hup in the handlers
610 sigemptyset(&act.sa_mask);
611 sigaddset(&act.sa_mask, SIGCHLD);
612 sigaddset(&act.sa_mask, SIGTERM);
613 sigaddset(&act.sa_mask, SIGHUP);
614 act.sa_flags = 0;
615#ifdef SA_RESTART
616 BESDEBUG("besdaemon", "besdaemon: setting restart for sigchld." << endl);
617 act.sa_flags |= SA_RESTART;
618#endif
619
620 act.sa_handler = catch_sig_child;
621 if (sigaction(SIGCHLD, &act, 0)) {
622 cerr << "Could not register a handler to catch beslistener status." << endl;
623 exit(1);
624 }
625
626 act.sa_handler = catch_sig_term;
627 if (sigaction(SIGTERM, &act, 0) < 0) {
628 cerr << "Could not register a handler to catch the terminate signal." << endl;
629 exit(1);
630 }
631
632 act.sa_handler = catch_sig_hup;
633 if (sigaction(SIGHUP, &act, 0) < 0) {
634 cerr << "Could not register a handler to catch the hang-up signal." << endl;
635 exit(1);
636 }
637}
638
645static int daemon_init()
646{
647 pid_t pid;
648 if ((pid = fork()) < 0) // error
649 return -1;
650 else if (pid != 0) // parent exits
651 exit(0);
652 setsid(); // child establishes its own process group
653 return 0;
654}
655
662static void store_daemon_id(int pid)
663{
664 ofstream f(file_for_daemon_pid.c_str());
665 if (!f) {
666 cerr << errno_str(": unable to create pid file " + file_for_daemon_pid + ": ");
667 }
668 else {
669 f << pid << endl;
670 f.close();
671 mode_t new_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
672 (void) chmod(file_for_daemon_pid.c_str(), new_mode);
673 }
674}
675
684static bool load_names(const string &install_dir, const string &pid_dir)
685{
686 string bindir = "/bin";
687 if (!pid_dir.empty()) {
688 file_for_daemon_pid = pid_dir;
689 }
690
691 if (!install_dir.empty()) {
692 beslistener_path = install_dir;
693 beslistener_path += bindir;
694 if (file_for_daemon_pid.empty()) {
695 file_for_daemon_pid = install_dir + "/var/run";
696 // Added jhrg 2/9/12 ... and removed 1/31/19. The special dir breaks
697 // systemctl/systemd on CentOS 7. We might be able to tweak things so
698 // it would work, but I'm switching back to what other daemons do. jhrg
699 // file_for_daemon_pid = install_dir + "/var/run/bes";
700
701 }
702 }
703 else {
704 string prog = daemon_name;
705 string::size_type slash = prog.find_last_of('/');
706 if (slash != string::npos) {
707 beslistener_path = prog.substr(0, slash);
708 slash = prog.find_last_of('/');
709 if (slash != string::npos) {
710 string root = prog.substr(0, slash);
711 if (file_for_daemon_pid.empty()) {
712 file_for_daemon_pid = root + "/var/run";
713 // Added jhrg 2/9/12. See about 1/31/19 jhrg
714 // file_for_daemon_pid = root + "/var/run/bes";
715 }
716 }
717 else {
718 if (file_for_daemon_pid.empty()) {
719 file_for_daemon_pid = beslistener_path;
720 }
721 }
722 }
723 }
724
725 if (beslistener_path.empty()) {
726 beslistener_path = ".";
727 if (file_for_daemon_pid.empty()) {
728 file_for_daemon_pid = "./run";
729 }
730 }
731
732 beslistener_path += BES_SERVER;
733 file_for_daemon_pid += BES_SERVER_PID;
734
735 if (access(beslistener_path.c_str(), F_OK) != 0) {
736 cerr << daemon_name << ": cannot find " << beslistener_path << endl
737 << "Please either pass -i <install_dir> on the command line." << endl;
738 return false;
739 }
740
741 // Record the name for use when building the arg list for the beslistener
742 global_args["beslistener"] = beslistener_path;
743
744 return true;
745}
746
747static void set_group_id()
748{
749#if !defined(OS2) && !defined(TPF)
750 // OS/2 and TPF don't support groups.
751
752 // get group id or name from BES configuration file
753 // If BES.Group begins with # then it is a group id,
754 // else it is a group name and look up the id.
755 BESDEBUG("server", "beslistener: Setting group id ... " << endl);
756 bool found = false;
757 string key = "BES.Group";
758 string group_str;
759 try {
760 TheBESKeys::TheKeys()->get_value(key, group_str, found);
761 }
762 catch (BESError &e) {
763 BESDEBUG("server", "beslistener: FAILED" << endl);
764 string err = string("FAILED: ") + e.get_message();
765 cerr << err << endl;
766 ERROR_LOG(err);
767 exit(SERVER_EXIT_FATAL_CANNOT_START);
768 }
769
770 if (!found || group_str.empty()) {
771 BESDEBUG("server", "beslistener: FAILED" << endl);
772 string err = "FAILED: Group not specified in BES configuration file";
773 cerr << err << endl;
774 ERROR_LOG(err);
775 exit(SERVER_EXIT_FATAL_CANNOT_START);
776 }
777 BESDEBUG("server", "to " << group_str << " ... " << endl);
778
779 gid_t new_gid = 0;
780 if (group_str[0] == '#') {
781 // group id starts with a #, so is a group id
782 const char *group_c = group_str.c_str();
783 group_c++;
784 new_gid = atoi(group_c);
785 }
786 else {
787 // specified group is a group name
788#if 0
789 struct group *ent;
790 // FIXME replace getgrname() and getpwnam() with the _r versions. jhrg 8/11/21
791 ent = getgrnam(group_str.c_str());
792#endif
793 struct group in;
794 struct group *result = nullptr;
795 vector<char> buffer(1024);
796 int rc = getgrnam_r(group_str.c_str(), &in, buffer.data(), buffer.size(), &result);
797 if (rc != 0 || result == nullptr) {
798 BESDEBUG("server", "beslistener: FAILED" << endl);
799 string err = string( "FAILED: Group ") + group_str + " does not exist (" + strerror(errno) + ").";
800 cerr << err << endl;
801 ERROR_LOG(err);
802 exit(SERVER_EXIT_FATAL_CANNOT_START);
803 }
804 new_gid = result->gr_gid;
805 }
806
807 if (new_gid < 1) {
808 BESDEBUG("server", "beslistener: FAILED" << endl);
809 ostringstream err;
810 err << "FAILED: Group id " << new_gid << " not a valid group id for BES";
811 cerr << err.str() << endl;
812 ERROR_LOG(err.str());
813 exit(SERVER_EXIT_FATAL_CANNOT_START);
814 }
815
816 BESDEBUG("server", "to id " << new_gid << " ... " << endl);
817 if (setgid(new_gid) == -1) {
818 BESDEBUG("server", "beslistener: FAILED" << endl);
819 ostringstream err;
820 err << "FAILED: unable to set the group id to " << new_gid;
821 cerr << err.str() << endl;
822 ERROR_LOG(err.str());
823 exit(SERVER_EXIT_FATAL_CANNOT_START);
824 }
825
826 BESDEBUG("server", "OK" << endl);
827#else
828 BESDEBUG( "server", "beslistener: Groups not supported in this OS" << endl );
829#endif
830}
831
832static void set_user_id()
833{
834 BESDEBUG("server", "beslistener: Setting user id ... " << endl);
835
836 // Get user name or id from the BES configuration file.
837 // If the BES.User value begins with # then it is a user
838 // id, else it is a user name and need to look up the
839 // user id.
840 bool found = false;
841 string key = "BES.User";
842 string user_str;
843 try {
844 TheBESKeys::TheKeys()->get_value(key, user_str, found);
845 }
846 catch (BESError &e) {
847 BESDEBUG("server", "beslistener: FAILED" << endl);
848 string err = "FAILED: " + e.get_message();
849 cerr << err << endl;
850 ERROR_LOG(err);
851 exit(SERVER_EXIT_FATAL_CANNOT_START);
852 }
853
854 if (!found || user_str.empty()) {
855 BESDEBUG("server", "beslistener: FAILED" << endl);
856 auto err = "FAILED: User not specified in BES config file";
857 cerr << err << endl;
858 ERROR_LOG(err);
859 exit(SERVER_EXIT_FATAL_CANNOT_START);
860 }
861 BESDEBUG("server", "to " << user_str << " ... " << endl);
862
863 uid_t new_id = 0;
864 if (user_str[0] == '#') {
865 const char *user_str_c = user_str.c_str();
866 user_str_c++;
867 new_id = atoi(user_str_c);
868 }
869 else {
870#if 0
871 struct passwd *ent;
872 ent = getpwnam(user_str.c_str());
873#endif
874
875 struct passwd in;
876 struct passwd *result = nullptr;
877 vector<char> buffer(1024);
878 int rc = getpwnam_r(user_str.c_str(), &in, buffer.data(), buffer.size(), &result);
879 if (rc != 0 || result == nullptr) {
880 BESDEBUG("server", "beslistener: FAILED" << endl);
881 string err = (string) "FAILED: Bad user name specified: " + user_str + "(" + strerror(errno) + ").";
882 cerr << err << endl;
883 ERROR_LOG(err);
884 exit(SERVER_EXIT_FATAL_CANNOT_START);
885 }
886 new_id = result->pw_uid;
887 }
888
889 // new user id cannot be root (0)
890 if (!new_id) {
891 BESDEBUG("server", "beslistener: FAILED" << endl);
892 auto err = (string) "FAILED: BES cannot run as root";
893 cerr << err << endl;
894 ERROR_LOG(err);
895 exit(SERVER_EXIT_FATAL_CANNOT_START);
896 }
897
898 // Right before we relinquish root, remove any 'supplementary groups'
899 //int set_sups(const int target_sups_size, const gid_t* const target_sups_list)
900 vector<gid_t> groups(1);
901 groups.at(0) = getegid();
902 if (set_sups(groups.size(), groups.data()) == -1) {
903 BESDEBUG("server", "beslistener: FAILED" << endl);
904 ostringstream err;
905 err << "FAILED: Unable to relinquish supplementary groups (" << new_id << ")";
906 cerr << err.str() << endl;
907 ERROR_LOG(err.str());
908 exit(SERVER_EXIT_FATAL_CANNOT_START);
909 }
910
911 BESDEBUG("server", "to " << new_id << " ... " << endl);
912 if (setuid(new_id) == -1) {
913 BESDEBUG("server", "beslistener: FAILED" << endl);
914 ostringstream err;
915 err << "FAILED: Unable to set user id to " << new_id;
916 cerr << err.str() << endl;
917 ERROR_LOG(err.str());
918 exit(SERVER_EXIT_FATAL_CANNOT_START);
919 }
920
921 BESDEBUG("server", "OK" << endl);
922}
923
927int main(int argc, char *argv[])
928{
929 uid_t curr_euid = geteuid();
930
931#ifndef BES_DEVELOPER
932 // must be root to run this app and to set user id and group id later
933 if (curr_euid) {
934 cerr << "FAILED: Must be root to run BES" << endl;
935 exit(SERVER_EXIT_FATAL_CANNOT_START);
936 }
937#else
938 cerr << "Developer Mode: Not testing if BES is run by root" << endl;
939#endif
940
941 daemon_name = "besdaemon";
942
943 string install_dir;
944 string pid_dir;
945
946 bool become_daemon = true;
947
948 // there are 16 arguments allowed to the daemon, including the program
949 // name. 3 options do not have arguments and 6 have arguments
950 if (argc > 16) {
951 // the show_usage method exits
952 BESServerUtils::show_usage(daemon_name);
953 }
954
955 try {
956 // Most of the argument processing is just for vetting the arguments
957 // that will be passed onto the beslistener(s), but we do grab some info
958 string config_file;
959 // argv[0] is the name of the program, so start num_args at 1
960 unsigned short num_args = 1;
961
962 // If you change the getopt statement below, be sure to make the
963 // corresponding change in ServerApp.cc and besctl.in
964 int c = 0;
965 while ((c = getopt(argc, argv, "hvsd:c:p:u:i:r:n")) != -1) {
966 switch (c) {
967 case 'v': // version
968 BESServerUtils::show_version(daemon_name);
969 break;
970 case '?': // unknown option
971 case 'h': // help
972 BESServerUtils::show_usage(daemon_name);
973 break;
974 case 'n': // no-daemon (Do Not Become A daemon process)
975 become_daemon=false;
976 cerr << "Running in foreground!" << endl;
977 num_args++;
978 break;
979 case 'i': // BES install directory
980 install_dir = optarg;
981 if (!BESScrub::pathname_ok(install_dir, true)) {
982 cout << "The specified install directory (-i option) "
983 << "is incorrectly formatted. Must be less than "
984 << "255 characters and include the characters " << "[0-9A-z_./-]" << endl;
985 return 1;
986 }
987 global_args["-i"] = install_dir;
988 num_args += 2;
989 break;
990 case 's': // secure server
991 global_args["-s"] = "";
992 num_args++;
993 break;
994 case 'r': // where to write the pid file
995 pid_dir = optarg;
996 if (!BESScrub::pathname_ok(pid_dir, true)) {
997 cout << "The specified state directory (-r option) "
998 << "is incorrectly formatted. Must be less than "
999 << "255 characters and include the characters " << "[0-9A-z_./-]" << endl;
1000 return 1;
1001 }
1002 global_args["-r"] = pid_dir;
1003 num_args += 2;
1004 break;
1005 case 'c': // configuration file
1006 config_file = optarg;
1007 if (!BESScrub::pathname_ok(config_file, true)) {
1008 cout << "The specified configuration file (-c option) "
1009 << "is incorrectly formatted. Must be less than "
1010 << "255 characters and include the characters " << "[0-9A-z_./-]" << endl;
1011 return 1;
1012 }
1013 global_args["-c"] = config_file;
1014 num_args += 2;
1015 break;
1016 case 'u': // unix socket
1017 {
1018 string check_path = optarg;
1019 if (!BESScrub::pathname_ok(check_path, true)) {
1020 cout << "The specified unix socket (-u option) " << "is incorrectly formatted. Must be less than "
1021 << "255 characters and include the characters " << "[0-9A-z_./-]" << endl;
1022 return 1;
1023 }
1024 global_args["-u"] = check_path;
1025 num_args += 2;
1026 break;
1027 }
1028 case 'p': // TCP port
1029 {
1030 string port_num = optarg;
1031 for (unsigned int i = 0; i < port_num.size(); i++) {
1032 if (!isdigit(port_num[i])) {
1033 cout << "The specified port contains non-digit " << "characters: " << port_num << endl;
1034 return 1;
1035 }
1036 }
1037 global_args["-p"] = port_num;
1038 num_args += 2;
1039 }
1040 break;
1041 case 'd': // debug
1042 {
1043 string check_arg = optarg;
1044 if (!BESScrub::command_line_arg_ok(check_arg)) {
1045 cout << "The specified debug options \"" << check_arg << "\" contains invalid characters" << endl;
1046 return 1;
1047 }
1048 BESDebug::SetUp(check_arg);
1049 global_args["-d"] = check_arg;
1050 debug_sink = check_arg.substr(0, check_arg.find(','));
1051 num_args += 2;
1052 break;
1053 }
1054 default:
1055 BESServerUtils::show_usage(daemon_name);
1056 break;
1057 }
1058 }
1059
1060 // if the number of arguments is greater than the number of allowed arguments
1061 // then extra arguments were passed that aren't options. Show usage and
1062 // exit.
1063 if (argc > num_args) {
1064 cout << daemon_name << ": too many arguments passed to the BES";
1065 BESServerUtils::show_usage(daemon_name);
1066 }
1067
1068 if (pid_dir.empty()) {
1069 pid_dir = install_dir;
1070 }
1071
1072 // If the -c option was passed, set the config file name in TheBESKeys
1073 if (!config_file.empty()) {
1074 TheBESKeys::ConfigFile = config_file;
1075 }
1076
1077 // If the -c option was not passed, but the -i option
1078 // was passed, then use the -i option to construct
1079 // the path to the config file
1080 if (config_file.empty() && !install_dir.empty()) {
1082 string conf_file = install_dir + "etc/bes/bes.conf";
1083 TheBESKeys::ConfigFile = conf_file;
1084 }
1085 }
1086 catch (BESError &e) {
1087 // (*BESLog::TheLog())
1088 // BESLog::TheLog throws exceptions...
1089 cerr << "Caught BES Error while processing the daemon's options: " << e.get_message() << endl;
1090 return 1;
1091 }
1092 catch (const std::exception &e) {
1093 cerr << "Caught C++ error while processing the daemon's options: " << e.what() << endl;
1094 return 2;
1095 }
1096 catch (...) {
1097 cerr << "Caught unknown error while processing the daemon's options." << endl;
1098 return 3;
1099 }
1100
1101 try {
1102 // Set the name of the listener and the file for the listener pid
1103 if (!load_names(install_dir, pid_dir)) return 1;
1104
1105 if (!access(file_for_daemon_pid.c_str(), F_OK)) {
1106 ifstream temp(file_for_daemon_pid.c_str());
1107 cout << daemon_name << ": there seems to be a BES daemon already running at ";
1108 char buf[500];
1109 temp.getline(buf, 500);
1110 cout << buf << endl;
1111 temp.close();
1112 return 1;
1113 }
1114
1115 if(become_daemon){
1116 daemon_init();
1117 }
1118
1119 store_daemon_id(getpid());
1120
1121 if (curr_euid == 0) {
1122#ifdef BES_DEVELOPER
1123 cerr << "Developer Mode: Running as root - setting group and user ids" << endl;
1124#endif
1125 set_group_id();
1126 set_user_id();
1127 }
1128 else {
1129 cerr << "Developer Mode: Not setting group or user ids" << endl;
1130 }
1131
1132 register_signal_handlers();
1133
1134 // Load the modules in the conf file(s) so that the debug (log) contexts
1135 // will be available to the BESDebug singleton so we can tell the OLFS/HAI
1136 // about them. Then Register the 'besdaemon' context.
1137 BESModuleApp app;
1138 if (app.initialize(argc, argv) != 0) {
1139 cerr << "Could not initialize the modules to get the log contexts." << endl;
1140 }
1141 BESDebug::Register("besdaemon");
1142
1143 // These are from the beslistener - they are valid contexts but are not
1144 // registered by a module. See ServerApp.cc
1145 BESDebug::Register("server");
1146 BESDebug::Register("ppt");
1147
1148
1149 // The stuff in global_args is used whenever a call to start_master_beslistener()
1150 // is made, so any time the BESDebug contexts are changed, a change to the
1151 // global_args will change the way the the beslistener is started. In fact,
1152 // it's not limited to the debug stuff, but that's we're using it for now.
1153 // jhrg 6/16/11
1154
1155 // The -d option was not given; add one setting up a default log sink using
1156 // the log file from the bes.conf file or the name "LOG".
1157 if (global_args.count("-d") == 0) {
1158 bool found = false;
1159 TheBESKeys::TheKeys()->get_value("BES.LogName", debug_sink, found);
1160 if (!found) {
1161 // This is a crude fallback that avoids a value without any name
1162 // for a log file (which would be a syntax error).
1163 global_args["-d"] = "cerr," + BESDebug::GetOptionsString();
1164 }
1165 else {
1166 // I use false for the 'created' flag so that subsequent changes to the
1167 // debug stream won't do odd things like delete the ostream pointer.
1168 // Note that the beslistener has to recognize that "LOG" means to use
1169 // the bes.log file for a debug/log sink
1170 BESDebug::SetStrm(BESLog::TheLog()->get_log_ostream(), false);
1171
1172 global_args["-d"] = debug_sink + "," + BESDebug::GetOptionsString();
1173 }
1174 }
1175 // The option was given; use the token read from the options for the sink
1176 // so that the beslistener will open the correct thing.
1177 else {
1178 global_args["-d"] = debug_sink + "," + BESDebug::GetOptionsString();
1179 }
1180
1181 // master_beslistener_pid is global so that the signal handlers can use it;
1182 // it is actually assigned a value in start_master_beslistener but it's
1183 // assigned here to make it clearer what's going on.
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;
1189 }
1190
1191 BESDEBUG("besdaemon", "besdaemon: master_beslistener_pid: " << master_beslistener_pid << endl);
1192 }
1193 catch (BESError &e) {
1194 cerr << "Caught BES Error during initialization: " << e.get_message() << endl;
1195 return 1;
1196 }
1197 catch (const std::exception &e) {
1198 cerr << "Caught C++ error during initialization: " << e.what() << endl;
1199 return 2;
1200 }
1201 catch (...) {
1202 cerr << "Caught unknown error during initialization." << endl;
1203 return 3;
1204 }
1205
1206 int status = 0;
1207 try {
1208 // start_command_processor() does not return unless all commands have been
1209 // processed and the daemon has been told to exit (status == 1) or the
1210 // bes.conf file was set so that the processor never starts (status == 0).
1212 status = start_command_processor(handler);
1213
1214 // if the command processor does not start, drop into this loop which
1215 // implements the simple restart-on-HUP behavior of the daemon.
1216 if (status == 0) {
1217 bool done = false;
1218 while (!done) {
1219 pause();
1220
1221 process_signals();
1222
1223 BESDEBUG("besdaemon", "besdaemon: master_beslistener_status: " << master_beslistener_status << endl);
1224 if (master_beslistener_status == BESLISTENER_RESTART) {
1225 master_beslistener_status = BESLISTENER_STOPPED;
1226 // master_beslistener_pid = start_master_beslistener();
1227 start_master_beslistener();
1228 }
1229 // If the status is not 'restart' and not running, then exit loop
1230 else if (master_beslistener_status != BESLISTENER_RUNNING) {
1231 done = true;
1232 }
1233 }
1234 }
1235 }
1236 catch (BESError &e) {
1237 status = 1;
1238 // (*BESLog::TheLog())
1239 // BESLog::TheLog throws exceptions...
1240 cerr << "Caught BES Error while starting the command handler: " << e.get_message() << endl;
1241 }
1242 catch (const std::exception &e) {
1243 status = 2;
1244 cerr << "Caught C++ error while starting the command handler: " << e.what() << endl;
1245 }
1246 catch (...) {
1247 status = 3;
1248 cerr << "Caught unknown error while starting the command handler." << endl;
1249 }
1250
1251 BESDEBUG("besdaemon", "besdaemon: past the command processor start" << endl);
1252
1253 cleanup_resources();
1254
1255 return status;
1256}
1257
static void SetStrm(std::ostream *strm, bool created)
set the debug output stream to the specified stream
Definition BESDebug.h:185
static void SetUp(const std::string &values)
Sets up debugging for the bes.
Definition BESDebug.cc:91
static void Register(const std::string &flagName)
register the specified debug flag
Definition BESDebug.h:126
static std::string GetOptionsString()
Definition BESDebug.cc:205
Base exception class for the BES with basic string message.
Definition BESError.h:66
std::string get_message() const
get the error message for this exception
Definition BESError.h:132
Base application object for all BES applications.
int initialize(int argC, char **argV) override
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...
Definition BESScrub.cc:92
static bool command_line_arg_ok(const std::string &arg)
sanitize command line arguments
Definition BESScrub.cc:56
static void trim_if_trailing_slash(std::string &value)
If the string ends in a slash, remove it This function works for empty strings (doing nothing)....
Definition BESUtil.cc:113
void get_value(const std::string &s, std::string &val, bool &found)
Retrieve the value of a given key, if set.
static TheBESKeys * TheKeys()
Access to the singleton.
Definition TheBESKeys.cc:85
static std::string ConfigFile
Definition TheBESKeys.h:117