Kea 3.2.0
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 exit(EXIT_FAILURE);
73}
74} // namespace
75
76int
77main(int argc, char* argv[]) {
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
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
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);
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.
234
235 // Initialize logging. If verbose, we'll use maximum verbosity.
238 .arg(getpid())
239 .arg(server_port_number)
240 .arg(client_port_number)
241 .arg(verbose_mode ? "yes" : "no");
242
244 .arg(VERSION)
245 .arg(PACKAGE_VERSION_TYPE);
246
247 if (string(PACKAGE_VERSION_TYPE) == "development") {
249 }
250
251 if (amRunningAsRoot()) {
253 }
254
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.
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
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 {
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 {
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}
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 setVerbose(const bool verbose)
Sets or clears verbose mode.
Definition daemon.cc:82
static void loggerInit(const char *log_name, bool verbose)
Initializes logger.
Definition daemon.cc:91
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:159
void createPIDFile(int pid=0)
Creates the PID file.
Definition daemon.cc:236
void setConfigFile(const std::string &config_file)
Sets the configuration file name.
Definition daemon.cc:112
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:77
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