| Kea 3.0.2-git

dhcp4/main.cc
Go to the documentation of this file.
1// Copyright (C) 2011-2025 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 <iostream>
26
27 using namespace isc::data;
28 using namespace isc::dhcp;
29 using namespace isc::process;
30 using namespace isc::util::file;
31 using namespace std;
32
41
42 namespace {
43
44 const char* const DHCP4_NAME = "kea-dhcp4";
45
49 void
50 usage() {
51 cerr << "Kea DHCPv4 server, "
52 << "version " << VERSION
53 << " (" << PACKAGE_VERSION_TYPE << ")"
54 << endl;
55 cerr << endl;
56 cerr << "Usage: " << DHCP4_NAME
57 << " -[v|V|W|X] [-d] [-{c|t|T} cfgfile] [-p number] [-P number]" << endl;
58 cerr << " -v: print version number and exit" << endl;
59 cerr << " -V: print extended version and exit" << endl;
60 cerr << " -W: display the configuration report and exit" << endl;
61 cerr << " -d: debug mode with extra verbosity (former -v)" << endl;
62 cerr << " -c file: specify configuration file" << endl;
63 cerr << " -t file: check the configuration file syntax and exit" << endl;
64 cerr << " -T file: check the configuration file doing hooks load and extra "
65 << "checks and exit" << endl;
66 cerr << " -p number: specify non-standard server port number 1-65535 "
67 << "(useful for testing only)" << endl;
68 cerr << " -P number: specify non-standard client port number 1-65535 "
69 << "(useful for testing only)" << endl;
70 cerr << " -X: disables security restrictions" << endl;
71 exit(EXIT_FAILURE);
72}
73} // namespace
74
75 int
76 main(int argc, char* argv[]) {
77 isc::util::file::setUmask();
78
79 int ch;
80 // The default. Any other values are useful for testing only.
81 int server_port_number = DHCP4_SERVER_PORT;
82 // Not zero values are useful for testing only.
83 int client_port_number = 0;
84 bool verbose_mode = false; // Should server be verbose?
85 bool check_mode = false; // Check syntax
86 bool load_hooks = false; // Check hooks config
87
88 // The standard config file
89 std::string config_file("");
90
91 // This is the DHCPv4 server
92 CfgMgr::instance().setFamily(AF_INET);
93
94 while ((ch = getopt(argc, argv, "dvVWc:p:P:t:T:X")) != -1) {
95 switch (ch) {
96 case 'd':
97 verbose_mode = true;
98 break;
99
100 case 'v':
101 cout << Dhcpv4Srv::getVersion(false) << endl;
102 return (EXIT_SUCCESS);
103
104 case 'V':
105 cout << Dhcpv4Srv::getVersion(true) << endl;
106 return (EXIT_SUCCESS);
107
108 case 'W':
109 cout << isc::detail::getConfigReport() << endl;
110 return (EXIT_SUCCESS);
111
112 case 'T':
113 load_hooks = true;
114 check_mode = true;
115 config_file = optarg;
116 break;
117
118 case 't':
119 check_mode = true;
120 config_file = optarg;
121 break;
122
123 case 'c': // config file
124 config_file = optarg;
125 break;
126
127 case 'p': // server port number
128 try {
129 server_port_number = boost::lexical_cast<int>(optarg);
130 } catch (const boost::bad_lexical_cast &) {
131 cerr << "Failed to parse server port number: [" << optarg
132 << "], 1-65535 allowed." << endl;
133 usage();
134 }
135 if (server_port_number <= 0 || server_port_number > 65535) {
136 cerr << "Failed to parse server port number: [" << optarg
137 << "], 1-65535 allowed." << endl;
138 usage();
139 }
140 break;
141
142 case 'P': // client port number
143 try {
144 client_port_number = boost::lexical_cast<int>(optarg);
145 } catch (const boost::bad_lexical_cast &) {
146 cerr << "Failed to parse client port number: [" << optarg
147 << "], 1-65535 allowed." << endl;
148 usage();
149 }
150 if (client_port_number <= 0 || client_port_number > 65535) {
151 cerr << "Failed to parse client port number: [" << optarg
152 << "], 1-65535 allowed." << endl;
153 usage();
154 }
155 break;
156
157 case 'X': // relax security checks
158 PathChecker::enableEnforcement(false);
159 break;
160
161 default:
162 usage();
163 }
164 }
165
166 // Check for extraneous parameters.
167 if (argc > optind) {
168 usage();
169 }
170
171 // Configuration file is required.
172 if (config_file.empty()) {
173 cerr << "Configuration file not specified." << endl;
174 usage();
175 }
176
177 if (check_mode) {
178 try {
179 // We need to initialize logging, in case any error messages are to be printed.
180 // This is just a test, so we don't care about lockfile.
181 setenv("KEA_LOCKFILE_DIR", "none", 0);
182 Daemon::setDefaultLoggerName(DHCP4_ROOT_LOGGER_NAME);
183 Daemon::loggerInit(DHCP4_ROOT_LOGGER_NAME, verbose_mode);
184
185 // Check the syntax first.
186 Parser4Context parser;
187 ConstElementPtr json;
188 json = parser.parseFile(config_file, Parser4Context::PARSER_DHCP4);
189 if (!json) {
190 cerr << "No configuration found" << endl;
191 return (EXIT_FAILURE);
192 }
193 if (verbose_mode) {
194 cerr << "Syntax check OK" << endl;
195 }
196
197 // Check the logic next.
198 ConstElementPtr dhcp4 = json->get("Dhcp4");
199 if (!dhcp4) {
200 cerr << "Missing mandatory Dhcp4 element" << endl;
201 return (EXIT_FAILURE);
202 }
203 ControlledDhcpv4Srv server(0);
204 ConstElementPtr answer;
205
206 server.setProcName(DHCP4_NAME);
207
208 // Now we pass the Dhcp4 configuration to the server, but
209 // tell it to check the configuration only (check_only = true)
210 answer = configureDhcp4Server(server, dhcp4, true, load_hooks);
211
212 int status_code = 0;
213 answer = isc::config::parseAnswer(status_code, answer);
214 if (status_code == 0) {
215 return (EXIT_SUCCESS);
216 } else {
217 cerr << "Error encountered: " << answer->stringValue() << endl;
218 return (EXIT_FAILURE);
219 }
220 } catch (const std::exception& ex) {
221 cerr << "Syntax check failed with: " << ex.what() << endl;
222 }
223 return (EXIT_FAILURE);
224 }
225
226 int ret = EXIT_SUCCESS;
227 try {
228 // It is important that we set a default logger name because this name
229 // will be used when the user doesn't provide the logging configuration
230 // in the Kea configuration file.
231 Daemon::setDefaultLoggerName(DHCP4_ROOT_LOGGER_NAME);
232
233 // Initialize logging. If verbose, we'll use maximum verbosity.
234 Daemon::loggerInit(DHCP4_ROOT_LOGGER_NAME, verbose_mode);
235 LOG_DEBUG(dhcp4_logger, DBG_DHCP4_START, DHCP4_START_INFO)
236 .arg(getpid())
237 .arg(server_port_number)
238 .arg(client_port_number)
239 .arg(verbose_mode ? "yes" : "no");
240
241 LOG_INFO(dhcp4_logger, DHCP4_STARTING)
242 .arg(VERSION)
243 .arg(PACKAGE_VERSION_TYPE);
244
245 if (string(PACKAGE_VERSION_TYPE) == "development") {
246 LOG_WARN(dhcp4_logger, DHCP4_DEVELOPMENT_VERSION);
247 }
248
249 if (!PathChecker::shouldEnforceSecurity()) {
250 LOG_WARN(dhcp4_logger, DHCP4_SECURITY_CHECKS_DISABLED);
251 }
252
253 // Create the server instance.
254 ControlledDhcpv4Srv server(server_port_number, client_port_number);
255
256 // Remember verbose-mode
257 server.setVerbose(verbose_mode);
258
259 // Create our PID file.
260 server.setProcName(DHCP4_NAME);
261 server.setConfigFile(config_file);
262 server.createPIDFile();
263
264 try {
265 // Initialize the server.
266 server.init(config_file);
267 } catch (const std::exception& ex) {
268
269 // Let's log out what went wrong.
270 try {
271 // Log with the current logger, but only if it's not
272 // configured with console output so as to not log twice.
273 if (!dhcp4_logger.hasAppender(isc::log::OutputOption::DEST_CONSOLE)) {
274 LOG_ERROR(dhcp4_logger, DHCP4_INIT_FAIL).arg(ex.what());
275 }
276
277 // Log on the console as well.
278 isc::log::LoggerManager log_manager;
279 log_manager.process();
280 LOG_ERROR(dhcp4_logger, DHCP4_INIT_FAIL).arg(ex.what());
281 } catch (...) {
282 // The exception thrown during the initialization could
283 // originate from logger subsystem. Therefore LOG_ERROR()
284 // may fail as well.
285 cerr << "Failed to initialize server: " << ex.what() << endl;
286 }
287
288 return (EXIT_FAILURE);
289 }
290
291 // Tell the admin we are ready to process packets
292 LOG_INFO(dhcp4_logger, DHCP4_STARTED).arg(VERSION);
293
294 // And run the main loop of the server.
295 ret = server.run();
296
297 LOG_INFO(dhcp4_logger, DHCP4_SHUTDOWN);
298
299 } catch (const isc::process::DaemonPIDExists& ex) {
300 // First, we print the error on stderr (that should always work)
301 cerr << DHCP4_NAME << " already running? " << ex.what()
302 << endl;
303
304 // Let's also try to log it using logging system, but we're not
305 // sure if it's usable (the exception may have been thrown from
306 // the logger subsystem)
307 try {
308 LOG_FATAL(dhcp4_logger, DHCP4_ALREADY_RUNNING)
309 .arg(DHCP4_NAME).arg(ex.what());
310 } catch (...) {
311 // Already logged so ignore
312 }
313 ret = EXIT_FAILURE;
314 } catch (const std::exception& ex) {
315 // First, we print the error on stderr (that should always work)
316 cerr << DHCP4_NAME << ": Fatal error during start up: " << ex.what()
317 << endl;
318
319 // Let's also try to log it using logging system, but we're not
320 // sure if it's usable (the exception may have been thrown from
321 // the logger subsystem)
322 try {
323 LOG_FATAL(dhcp4_logger, DHCP4_SERVER_FAILED).arg(ex.what());
324 } catch (...) {
325 // Already logged so ignore
326 }
327 ret = EXIT_FAILURE;
328 } catch (...) {
329 cerr << DHCP4_NAME << ": Fatal error during start up"
330 << endl;
331 ret = EXIT_FAILURE;
332 }
333
334 return (ret);
335}
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:25
isc::dhcp::ControlledDhcpv4Srv::init
void init(const std::string &config_file)
Initializes the server.
Definition ctrl_dhcp4_srv.cc:96
isc::dhcp::Dhcpv4Srv::run
int run()
Main server processing loop.
Definition dhcp4_srv.cc:1170
isc::dhcp::Dhcpv4Srv::getVersion
static std::string getVersion(bool extended)
returns Kea version on stdout and exit.
Definition dhcp4_srv.cc:5127
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:79
isc::process::Daemon::loggerInit
static void loggerInit(const char *log_name, bool verbose)
Initializes logger.
Definition daemon.cc:88
isc::process::Daemon::setDefaultLoggerName
static void setDefaultLoggerName(const std::string &logger)
Sets the default logger name.
Definition daemon.h:224
isc::process::Daemon::setProcName
static void setProcName(const std::string &proc_name)
Sets the process name.
Definition daemon.cc:156
isc::process::Daemon::createPIDFile
void createPIDFile(int pid=0)
Creates the PID file.
Definition daemon.cc:224
isc::process::Daemon::setConfigFile
void setConfigFile(const std::string &config_file)
Sets the configuration file name.
Definition daemon.cc:109
isc::util::file::PathChecker::shouldEnforceSecurity
static bool shouldEnforceSecurity()
Indicates security checks should be enforced.
Definition filesystem.cc:341
isc::util::file::PathChecker::enableEnforcement
static void enableEnforcement(bool enable)
Enables or disables security enforcment checks.
Definition filesystem.cc:345
config_report.h
ctrl_dhcp4_srv.h
daemon.h
json_config_parser.h
main
int main(int argc, char *argv[])
Definition dhcp4/main.cc:76
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:76
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:29
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:175
isc::dhcp::DHCP4_START_INFO
const isc::log::MessageID DHCP4_START_INFO
Definition dhcp4_messages.h:177
isc::dhcp::DHCP4_SERVER_FAILED
const isc::log::MessageID DHCP4_SERVER_FAILED
Definition dhcp4_messages.h:164
isc::dhcp::DHCP4_SECURITY_CHECKS_DISABLED
const isc::log::MessageID DHCP4_SECURITY_CHECKS_DISABLED
Definition dhcp4_messages.h:163
isc::dhcp::DHCP4_INIT_FAIL
const isc::log::MessageID DHCP4_INIT_FAIL
Definition dhcp4_messages.h:98
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:744
isc::dhcp::DHCP4_SHUTDOWN
const isc::log::MessageID DHCP4_SHUTDOWN
Definition dhcp4_messages.h:169
isc::dhcp::DHCP4_STARTING
const isc::log::MessageID DHCP4_STARTING
Definition dhcp4_messages.h:176
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_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:28
isc::util::file::setUmask
void setUmask()
Set umask (at least 0027 i.e. no group write and no other access).
Definition filesystem.cc:97
output_option.h
isc::log::OutputOption::DEST_CONSOLE
@ DEST_CONSOLE
Definition output_option.h:49