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