Kea: main.cc Source File

| Kea 3.2.0-git

dhcp4/main.cc
Go to the documentation of this file.
1// Copyright (C) 2011-2026 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8#include <kea_version.h>
9
10#include <dhcp4/ctrl_dhcp4_srv.h>
11#include <dhcp4/dhcp4_log.h>
12#include <dhcp4/parser_context.h>
13#include <dhcp4/json_config_parser.h>
14#include <dhcpsrv/cfgmgr.h>
15#include <exceptions/exceptions.h>
16#include <log/logger_support.h>
17#include <log/logger_manager.h>
18#include <log/output_option.h>
19#include <process/cfgrpt/config_report.h>
20#include <process/daemon.h>
21#include <util/filesystem.h>
22
23#include <boost/lexical_cast.hpp>
24
25#include <cstdlib>
26#include <iostream>
27
28using namespace isc::data;
29using namespace isc::dhcp;
30using namespace isc::process;
31using namespace isc::util::file;
32using namespace std;
33
42
43namespace {
44
45const char* const DHCP4_NAME = "kea-dhcp4";
46
50void
51 usage() {
52 cerr << "Kea DHCPv4 server, "
53 << "version " << VERSION
54 << " (" << PACKAGE_VERSION_TYPE << ")"
55 << endl;
56 cerr << endl;
57 cerr << "Usage: " << DHCP4_NAME
58 << " -[v|V|W|X] [-d] [-{c|t|T} cfgfile] [-p number] [-P number]" << endl;
59 cerr << " -v: print version number and exit" << endl;
60 cerr << " -V: print extended version and exit" << endl;
61 cerr << " -W: display the configuration report and exit" << endl;
62 cerr << " -d: debug mode with extra verbosity (former -v)" << endl;
63 cerr << " -c file: specify configuration file" << endl;
64 cerr << " -t file: check the configuration file syntax and exit" << endl;
65 cerr << " -T file: check the configuration file doing hooks load and extra "
66 << "checks and exit" << endl;
67 cerr << " -p number: specify non-standard server port number 1-65535 "
68 << "(useful for testing only)" << endl;
69 cerr << " -P number: specify non-standard client port number 1-65535 "
70 << "(useful for testing only)" << endl;
71 cerr << " -X: disables security restrictions" << endl;
72 exit(EXIT_FAILURE);
73}
74} // namespace
75
76int
77main(int argc, char* argv[]) {
78 isc::util::file::setUmask();
79
80 int ch;
81 // The default. Any other values are useful for testing only.
82 int server_port_number = DHCP4_SERVER_PORT;
83 // Not zero values are useful for testing only.
84 int client_port_number = 0;
85 bool verbose_mode = false; // Should server be verbose?
86 bool check_mode = false; // Check syntax
87 bool load_hooks = false; // Check hooks config
88
89 // The standard config file
90 std::string config_file("");
91
92 // This is the DHCPv4 server
93 IfaceMgr::instance().setFamily(AF_INET);
94 CfgMgr::instance().setFamily(AF_INET);
95
96 while ((ch = getopt(argc, argv, "dvVWc:p:P:t:T:X")) != -1) {
97 switch (ch) {
98 case 'd':
99 verbose_mode = true;
100 break;
101
102 case 'v':
103 cout << Dhcpv4Srv::getVersion(false) << endl;
104 return (EXIT_SUCCESS);
105
106 case 'V':
107 cout << Dhcpv4Srv::getVersion(true) << endl;
108 return (EXIT_SUCCESS);
109
110 case 'W':
111 cout << isc::detail::getConfigReport() << endl;
112 return (EXIT_SUCCESS);
113
114 case 'T':
115 load_hooks = true;
116 check_mode = true;
117 config_file = optarg;
118 break;
119
120 case 't':
121 check_mode = true;
122 config_file = optarg;
123 break;
124
125 case 'c': // config file
126 config_file = optarg;
127 break;
128
129 case 'p': // server port number
130 try {
131 server_port_number = boost::lexical_cast<int>(optarg);
132 } catch (const boost::bad_lexical_cast &) {
133 cerr << "Failed to parse server port number: [" << optarg
134 << "], 1-65535 allowed." << endl;
135 usage();
136 }
137 if (server_port_number <= 0 || server_port_number > 65535) {
138 cerr << "Failed to parse server port number: [" << optarg
139 << "], 1-65535 allowed." << endl;
140 usage();
141 }
142 break;
143
144 case 'P': // client port number
145 try {
146 client_port_number = boost::lexical_cast<int>(optarg);
147 } catch (const boost::bad_lexical_cast &) {
148 cerr << "Failed to parse client port number: [" << optarg
149 << "], 1-65535 allowed." << endl;
150 usage();
151 }
152 if (client_port_number <= 0 || client_port_number > 65535) {
153 cerr << "Failed to parse client port number: [" << optarg
154 << "], 1-65535 allowed." << endl;
155 usage();
156 }
157 break;
158
159 case 'X': // relax security checks
160 PathChecker::enableEnforcement(false);
161 break;
162
163 default:
164 usage();
165 }
166 }
167
168 // Check for extraneous parameters.
169 if (argc > optind) {
170 usage();
171 }
172
173 // Configuration file is required.
174 if (config_file.empty()) {
175 cerr << "Configuration file not specified." << endl;
176 usage();
177 }
178
179 if (check_mode) {
180 try {
181 // We need to initialize logging, in case any error messages are to be printed.
182 // This is just a test, so we don't care about lockfile.
183 setenv("KEA_LOCKFILE_DIR", "none", 0);
184 Daemon::setDefaultLoggerName(DHCP4_ROOT_LOGGER_NAME);
185 Daemon::loggerInit(DHCP4_ROOT_LOGGER_NAME, verbose_mode);
186
187 // Check the syntax first.
188 Parser4Context parser;
189 ConstElementPtr json;
190 json = parser.parseFile(config_file, Parser4Context::PARSER_DHCP4);
191 if (!json) {
192 cerr << "No configuration found" << endl;
193 return (EXIT_FAILURE);
194 }
195 if (verbose_mode) {
196 cerr << "Syntax check OK" << endl;
197 }
198
199 // Check the logic next.
200 ConstElementPtr dhcp4 = json->get("Dhcp4");
201 if (!dhcp4) {
202 cerr << "Missing mandatory Dhcp4 element" << endl;
203 return (EXIT_FAILURE);
204 }
205 ControlledDhcpv4Srv server(0);
206 ConstElementPtr answer;
207
208 server.setProcName(DHCP4_NAME);
209
210 // Now we pass the Dhcp4 configuration to the server, but
211 // tell it to check the configuration only (check_only = true)
212 answer = configureDhcp4Server(server, dhcp4, true, load_hooks);
213
214 int status_code = 0;
215 answer = isc::config::parseAnswer(status_code, answer);
216 if (status_code == 0) {
217 return (EXIT_SUCCESS);
218 } else {
219 cerr << "Error encountered: " << answer->stringValue() << endl;
220 return (EXIT_FAILURE);
221 }
222 } catch (const std::exception& ex) {
223 cerr << "Syntax check failed with: " << ex.what() << endl;
224 }
225 return (EXIT_FAILURE);
226 }
227
228 int ret = EXIT_SUCCESS;
229 try {
230 // It is important that we set a default logger name because this name
231 // will be used when the user doesn't provide the logging configuration
232 // in the Kea configuration file.
233 Daemon::setDefaultLoggerName(DHCP4_ROOT_LOGGER_NAME);
234
235 // Initialize logging. If verbose, we'll use maximum verbosity.
236 Daemon::loggerInit(DHCP4_ROOT_LOGGER_NAME, verbose_mode);
237 LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_START_INFO)
238 .arg(getpid())
239 .arg(server_port_number)
240 .arg(client_port_number)
241 .arg(verbose_mode ? "yes" : "no");
242
243 LOG_INFO(dhcp4_logger, DHCP4_STARTING)
244 .arg(VERSION)
245 .arg(PACKAGE_VERSION_TYPE);
246
247 if (string(PACKAGE_VERSION_TYPE) == "development") {
248 LOG_WARN(dhcp4_logger, DHCP4_DEVELOPMENT_VERSION);
249 }
250
251 if (amRunningAsRoot()) {
252 LOG_WARN(dhcp4_logger, DHCP4_ROOT_USER_SECURITY_WARNING);
253 }
254
255 if (!PathChecker::shouldEnforceSecurity()) {
256 LOG_WARN(dhcp4_logger, DHCP4_SECURITY_CHECKS_DISABLED);
257 }
258
259 // Create the server instance.
260 ControlledDhcpv4Srv server(server_port_number, client_port_number);
261
262 // Remember verbose-mode
263 server.setVerbose(verbose_mode);
264
265 // Create our PID file.
266 server.setProcName(DHCP4_NAME);
267 server.setConfigFile(config_file);
268 server.createPIDFile();
269
270 try {
271 // Initialize the server.
272 server.init(config_file);
273 } catch (const std::exception& ex) {
274
275 // Let's log out what went wrong.
276 try {
277 // Log with the current logger, but only if it's not
278 // configured with console output so as to not log twice.
279 if (!dhcp4_logger.hasAppender(isc::log::OutputOption::DEST_CONSOLE)) {
280 LOG_ERROR(dhcp4_logger, DHCP4_INIT_FAIL).arg(ex.what());
281 }
282
283 // Log on the console as well.
284 isc::log::LoggerManager log_manager;
285 log_manager.process();
286 LOG_ERROR(dhcp4_logger, DHCP4_INIT_FAIL).arg(ex.what());
287 } catch (...) {
288 // The exception thrown during the initialization could
289 // originate from logger subsystem. Therefore LOG_ERROR()
290 // may fail as well.
291 cerr << "Failed to initialize server: " << ex.what() << endl;
292 }
293
294 return (EXIT_FAILURE);
295 }
296
297 // Tell the admin we are ready to process packets
298 LOG_INFO(dhcp4_logger, DHCP4_STARTED).arg(VERSION);
299
300 // And run the main loop of the server.
301 ret = server.run();
302
303 LOG_INFO(dhcp4_logger, DHCP4_SHUTDOWN);
304
305 } catch (const isc::process::DaemonPIDExists& ex) {
306 // First, we print the error on stderr (that should always work)
307 cerr << DHCP4_NAME << " already running? " << ex.what()
308 << endl;
309
310 // Let's also try to log it using logging system, but we're not
311 // sure if it's usable (the exception may have been thrown from
312 // the logger subsystem)
313 try {
314 LOG_FATAL(dhcp4_logger, DHCP4_ALREADY_RUNNING)
315 .arg(DHCP4_NAME).arg(ex.what());
316 } catch (...) {
317 // Already logged so ignore
318 }
319 ret = EXIT_FAILURE;
320 } catch (const std::exception& ex) {
321 // First, we print the error on stderr (that should always work)
322 cerr << DHCP4_NAME << ": Fatal error during start up: " << ex.what()
323 << endl;
324
325 // Let's also try to log it using logging system, but we're not
326 // sure if it's usable (the exception may have been thrown from
327 // the logger subsystem)
328 try {
329 LOG_FATAL(dhcp4_logger, DHCP4_SERVER_FAILED).arg(ex.what());
330 } catch (...) {
331 // Already logged so ignore
332 }
333 ret = EXIT_FAILURE;
334 } catch (...) {
335 cerr << DHCP4_NAME << ": Fatal error during start up"
336 << endl;
337 ret = EXIT_FAILURE;
338 }
339
340 return (ret);
341}
cfgmgr.h
isc::Exception::what
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
Definition exceptions/exceptions.cc:32
isc::dhcp::CfgMgr::setFamily
void setFamily(uint16_t family)
Sets address family (AF_INET or AF_INET6).
Definition cfgmgr.h:241
isc::dhcp::CfgMgr::instance
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition cfgmgr.cc:29
isc::dhcp::ControlledDhcpv4Srv
Controlled version of the DHCPv4 server.
Definition ctrl_dhcp4_srv.h:26
isc::dhcp::ControlledDhcpv4Srv::init
void init(const std::string &config_file)
Initializes the server.
Definition ctrl_dhcp4_srv.cc:99
isc::dhcp::Dhcpv4Srv::run
int run()
Main server processing loop.
Definition dhcp4_srv.cc:1191
isc::dhcp::Dhcpv4Srv::getVersion
static std::string getVersion(bool extended)
returns Kea version on stdout and exit.
Definition dhcp4_srv.cc:5281
isc::dhcp::IfaceMgr::setFamily
void setFamily(uint16_t family)
Sets address family (AF_INET or AF_INET6).
Definition iface_mgr.h:1517
isc::dhcp::IfaceMgr::instance
static IfaceMgr & instance()
IfaceMgr is a singleton class.
Definition iface_mgr.cc:52
isc::dhcp::Parser4Context
Evaluation context, an interface to the expression evaluation.
Definition dhcp4/parser_context.h:36
isc::dhcp::Parser4Context::parseFile
isc::data::ElementPtr parseFile(const std::string &filename, ParserType parser_type)
Run the parser on the file specified.
Definition dhcp4/parser_context.cc:37
isc::dhcp::Parser4Context::PARSER_DHCP4
@ PARSER_DHCP4
This parser will parse the content as Dhcp4 config wrapped in a map (that's the regular config file).
Definition dhcp4/parser_context.h:55
isc::log::LoggerManager
Logger Manager.
Definition logger_manager.h:39
isc::log::LoggerManager::process
void process(T start, T finish)
Process Specifications.
Definition logger_manager.h:56
isc::process::DaemonPIDExists
Exception thrown when the PID file points to a live PID.
Definition daemon.h:25
isc::process::Daemon::setVerbose
static void setVerbose(const bool verbose)
Sets or clears verbose mode.
Definition daemon.cc:82
isc::process::Daemon::loggerInit
static void loggerInit(const char *log_name, bool verbose)
Initializes logger.
Definition daemon.cc:91
isc::process::Daemon::setDefaultLoggerName
static void setDefaultLoggerName(const std::string &logger)
Sets the default logger name.
Definition daemon.h:230
isc::process::Daemon::setProcName
static void setProcName(const std::string &proc_name)
Sets the process name.
Definition daemon.cc:159
isc::process::Daemon::createPIDFile
void createPIDFile(int pid=0)
Creates the PID file.
Definition daemon.cc:236
isc::process::Daemon::setConfigFile
void setConfigFile(const std::string &config_file)
Sets the configuration file name.
Definition daemon.cc:112
isc::util::file::PathChecker::shouldEnforceSecurity
static bool shouldEnforceSecurity()
Indicates security checks should be enforced.
Definition filesystem.cc:361
isc::util::file::PathChecker::enableEnforcement
static void enableEnforcement(bool enable)
Enables or disables security enforcement checks.
Definition filesystem.cc:365
config_report.h
ctrl_dhcp4_srv.h
daemon.h
json_config_parser.h
main
int main(int argc, char *argv[])
Definition dhcp4/main.cc:77
parser_context.h
dhcp4_log.h
Contains declarations for loggers used by the DHCPv4 server component.
exceptions.h
filesystem.h
usage
void usage()
Print Usage.
Definition log/compiler/message.cc:82
logger_manager.h
logger_support.h
Logging initialization functions.
LOG_ERROR
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition macros.h:32
LOG_INFO
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition macros.h:20
LOG_WARN
#define LOG_WARN(LOGGER, MESSAGE)
Macro to conveniently test warn output and log it.
Definition macros.h:26
LOG_FATAL
#define LOG_FATAL(LOGGER, MESSAGE)
Macro to conveniently test fatal output and log it.
Definition macros.h:38
LOG_DEBUG
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition macros.h:14
isc::config::parseAnswer
ConstElementPtr parseAnswer(int &rcode, const ConstElementPtr &msg)
Parses a standard config/command level answer and returns arguments or text status code.
Definition command_interpreter.cc:96
isc::data
Definition base_stamped_element.cc:12
isc::data::ConstElementPtr
boost::shared_ptr< const Element > ConstElementPtr
Definition data.h:30
isc::detail::getConfigReport
std::string getConfigReport()
Definition cfgrpt.cc:20
isc::dhcp
Definition dhcp4/client_handler.cc:20
isc::dhcp::DHCP4_ROOT_LOGGER_NAME
const char * DHCP4_ROOT_LOGGER_NAME
Defines the name of the root level (default) logger.
Definition dhcp4_log.cc:26
isc::dhcp::DHCP4_ALREADY_RUNNING
const isc::log::MessageID DHCP4_ALREADY_RUNNING
Definition dhcp4_messages.h:15
isc::dhcp::DHCP4_STARTED
const isc::log::MessageID DHCP4_STARTED
Definition dhcp4_messages.h:178
isc::dhcp::DHCP4_START_INFO
const isc::log::MessageID DHCP4_START_INFO
Definition dhcp4_messages.h:180
isc::dhcp::DHCP4_SERVER_FAILED
const isc::log::MessageID DHCP4_SERVER_FAILED
Definition dhcp4_messages.h:167
isc::dhcp::DHCP4_SECURITY_CHECKS_DISABLED
const isc::log::MessageID DHCP4_SECURITY_CHECKS_DISABLED
Definition dhcp4_messages.h:166
isc::dhcp::DHCP4_INIT_FAIL
const isc::log::MessageID DHCP4_INIT_FAIL
Definition dhcp4_messages.h:99
isc::dhcp::configureDhcp4Server
isc::data::ConstElementPtr configureDhcp4Server(Dhcpv4Srv &server, isc::data::ConstElementPtr config_set, bool check_only, bool extra_checks)
Configure DHCPv4 server (Dhcpv4Srv) with a set of configuration values.
Definition dhcp4/json_config_parser.cc:752
isc::dhcp::DHCP4_SHUTDOWN
const isc::log::MessageID DHCP4_SHUTDOWN
Definition dhcp4_messages.h:172
isc::dhcp::DHCP4_STARTING
const isc::log::MessageID DHCP4_STARTING
Definition dhcp4_messages.h:179
isc::dhcp::dhcp4_logger
isc::log::Logger dhcp4_logger(DHCP4_APP_LOGGER_NAME)
Base logger for DHCPv4 server.
Definition dhcp4_log.h:90
isc::dhcp::DHCP4_ROOT_USER_SECURITY_WARNING
const isc::log::MessageID DHCP4_ROOT_USER_SECURITY_WARNING
Definition dhcp4_messages.h:165
isc::dhcp::DHCP4_DEVELOPMENT_VERSION
const isc::log::MessageID DHCP4_DEVELOPMENT_VERSION
Definition dhcp4_messages.h:56
isc::dhcp::DBG_DHCP4_START
const int DBG_DHCP4_START
Debug level used to log information during server startup.
Definition dhcp4_log.h:24
isc::process
Definition cb_ctl_base.h:22
isc::util::file
Definition filesystem.cc:29
isc::util::file::amRunningAsRoot
bool amRunningAsRoot()
Indicates if current user is root.
Definition filesystem.cc:115
isc::util::file::setUmask
void setUmask()
Set umask (at least 0027 i.e. no group write and no other access).
Definition filesystem.cc:98
output_option.h
isc::log::OutputOption::DEST_CONSOLE
@ DEST_CONSOLE
Definition output_option.h:49