ctrl_dhcp6_srv_unittest.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. // Copyright (C) 2012-2013, 2015 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <cc/command_interpreter.h>
  16. #include <config/command_mgr.h>
  17. #include <dhcpsrv/cfgmgr.h>
  18. #include <dhcp6/ctrl_dhcp6_srv.h>
  19. #include <hooks/hooks_manager.h>
  20. #include "marker_file.h"
  21. #include "test_libraries.h"
  22. #include <boost/scoped_ptr.hpp>
  23. #include <gtest/gtest.h>
  24. #include <sys/select.h>
  25. #include <sys/ioctl.h>
  26. using namespace std;
  27. using namespace isc::config;
  28. using namespace isc::data;
  29. using namespace isc::dhcp;
  30. using namespace isc::dhcp::test;
  31. using namespace isc::hooks;
  32. namespace {
  33. /// Class that acts as a UnixCommandSocket client
  34. /// It can connect to an open UnixCommandSocket and exchange ControlChannel
  35. /// commands and responses.
  36. class UnixControlClient {
  37. public:
  38. UnixControlClient() {
  39. socket_fd_ = -1;
  40. }
  41. ~UnixControlClient() {
  42. disconnectFromServer();
  43. }
  44. /// @brief Closes the Control Channel socket
  45. void disconnectFromServer() {
  46. if (socket_fd_ >= 0) {
  47. static_cast<void>(close(socket_fd_));
  48. socket_fd_ = -1;
  49. }
  50. }
  51. /// @brief Connects to a Unix socket at the given path
  52. /// @param socket_path pathname of the socket to open
  53. /// @return true if the connect was successful, false otherwise
  54. bool connectToServer(const std::string& socket_path) {
  55. // Create UNIX socket
  56. socket_fd_ = socket(AF_UNIX, SOCK_STREAM, 0);
  57. if (socket_fd_ < 0) {
  58. const char* errmsg = strerror(errno);
  59. ADD_FAILURE() << "Failed to open unix stream socket: " << errmsg;
  60. return (false);
  61. }
  62. // Prepare socket address
  63. struct sockaddr_un srv_addr;
  64. memset(&srv_addr, 0, sizeof(srv_addr));
  65. srv_addr.sun_family = AF_UNIX;
  66. strncpy(srv_addr.sun_path, socket_path.c_str(),
  67. sizeof(srv_addr.sun_path));
  68. socklen_t len = sizeof(srv_addr);
  69. // Connect to the specified UNIX socket
  70. int status = connect(socket_fd_, (struct sockaddr*)&srv_addr, len);
  71. if (status == -1) {
  72. const char* errmsg = strerror(errno);
  73. ADD_FAILURE() << "Failed to connect unix socket: fd=" << socket_fd_
  74. << ", path=" << socket_path << " : " << errmsg;
  75. disconnectFromServer();
  76. return (false);
  77. }
  78. return (true);
  79. }
  80. /// @brief Sends the given command across the open Control Channel
  81. /// @param command the command text to execute in JSON form
  82. /// @return true if the send succeeds, false otherwise
  83. bool sendCommand(const std::string& command) {
  84. // Send command
  85. int bytes_sent = send(socket_fd_, command.c_str(), command.length(), 0);
  86. if (bytes_sent < command.length()) {
  87. const char* errmsg = strerror(errno);
  88. ADD_FAILURE() << "Failed to send " << command.length()
  89. << " bytes, send() returned " << bytes_sent
  90. << " : " << errmsg;
  91. return (false);
  92. }
  93. return (true);
  94. }
  95. /// @brief Reads the response text from the open Control Channel
  96. /// @param response variable into which the received response should be
  97. /// placed.
  98. /// @return true if data was successfully read from the socket,
  99. /// false otherwise
  100. bool getResponse(std::string& response) {
  101. // Receive response
  102. // @todo implement select check to see if data is waiting
  103. char buf[65536];
  104. memset(buf, 0, sizeof(buf));
  105. switch (selectCheck()) {
  106. case -1: {
  107. const char* errmsg = strerror(errno);
  108. ADD_FAILURE() << "getResponse - select failed: " << errmsg;
  109. return (false);
  110. }
  111. case 0:
  112. ADD_FAILURE() << "No response data sent";
  113. return (false);
  114. default:
  115. break;
  116. }
  117. int bytes_rcvd = recv(socket_fd_, buf, sizeof(buf), 0);
  118. if (bytes_rcvd < 0) {
  119. const char* errmsg = strerror(errno);
  120. ADD_FAILURE() << "Failed to receive a response. recv() returned "
  121. << bytes_rcvd << " : " << errmsg;
  122. return (false);
  123. }
  124. if (bytes_rcvd >= sizeof(buf)) {
  125. ADD_FAILURE() << "Response size too large: " << bytes_rcvd;
  126. return (false);
  127. }
  128. // Convert the response to a string
  129. response = string(buf, bytes_rcvd);
  130. return (true);
  131. }
  132. /// @brief Uses select to poll the Control Channel for data waiting
  133. /// @return -1 on error, 0 if no data is available, 1 if data is ready
  134. int selectCheck() {
  135. int maxfd = 0;
  136. fd_set read_fds;
  137. FD_ZERO(&read_fds);
  138. // Add this socket to listening set
  139. FD_SET(socket_fd_, &read_fds);
  140. maxfd = socket_fd_;
  141. struct timeval select_timeout;
  142. select_timeout.tv_sec = 0;
  143. select_timeout.tv_usec = 0;
  144. return (select(maxfd + 1, &read_fds, NULL, NULL, &select_timeout));
  145. }
  146. /// @brief Retains the fd of the open socket
  147. int socket_fd_;
  148. };
  149. class NakedControlledDhcpv6Srv: public ControlledDhcpv6Srv {
  150. // "Naked" DHCPv6 server, exposes internal fields
  151. public:
  152. NakedControlledDhcpv6Srv():ControlledDhcpv6Srv(DHCP6_SERVER_PORT + 10000) {
  153. }
  154. /// @brief Exposes server's receivePacket method
  155. virtual Pkt6Ptr receivePacket(int timeout) {
  156. return(Dhcpv6Srv::receivePacket(timeout));
  157. }
  158. };
  159. class CtrlDhcpv6SrvTest : public ::testing::Test {
  160. public:
  161. CtrlDhcpv6SrvTest() {
  162. reset();
  163. }
  164. virtual ~CtrlDhcpv6SrvTest() {
  165. reset();
  166. };
  167. /// @brief Reset hooks data
  168. ///
  169. /// Resets the data for the hooks-related portion of the test by ensuring
  170. /// that no libraries are loaded and that any marker files are deleted.
  171. virtual void reset() {
  172. // Unload any previously-loaded libraries.
  173. HooksManager::unloadLibraries();
  174. // Get rid of any marker files.
  175. static_cast<void>(unlink(LOAD_MARKER_FILE));
  176. static_cast<void>(unlink(UNLOAD_MARKER_FILE));
  177. IfaceMgr::instance().deleteAllExternalSockets();
  178. CfgMgr::instance().clear();
  179. }
  180. };
  181. class CtrlChannelDhcpv6SrvTest : public CtrlDhcpv6SrvTest {
  182. public:
  183. std::string socket_path_;
  184. boost::shared_ptr<NakedControlledDhcpv6Srv> server_;
  185. CtrlChannelDhcpv6SrvTest() {
  186. socket_path_ = string(TEST_DATA_BUILDDIR) + "/kea6.sock";
  187. reset();
  188. }
  189. ~CtrlChannelDhcpv6SrvTest() {
  190. server_.reset();
  191. reset();
  192. };
  193. void createUnixChannelServer() {
  194. ::remove(socket_path_.c_str());
  195. // Just a simple config. The important part here is the socket
  196. // location information.
  197. std::string header =
  198. "{"
  199. " \"interfaces-config\": {"
  200. " \"interfaces\": [ \"*\" ]"
  201. " },"
  202. " \"rebind-timer\": 2000, "
  203. " \"renew-timer\": 1000, "
  204. " \"subnet6\": [ ],"
  205. " \"valid-lifetime\": 4000,"
  206. " \"control-socket\": {"
  207. " \"socket-type\": \"unix\","
  208. " \"socket-name\": \"";
  209. std::string footer =
  210. "\" },"
  211. " \"lease-database\": {"
  212. " \"type\": \"memfile\", \"persist\": false }"
  213. "}";
  214. // Fill in the socket-name value with socket_path_ to
  215. // make the actual configuration text.
  216. std::string config_txt = header + socket_path_ + footer;
  217. ASSERT_NO_THROW(server_.reset(new NakedControlledDhcpv6Srv()));
  218. ConstElementPtr config = Element::fromJSON(config_txt);
  219. ConstElementPtr answer = server_->processConfig(config);
  220. ASSERT_TRUE(answer);
  221. int status = 0;
  222. isc::config::parseAnswer(status, answer);
  223. ASSERT_EQ(0, status);
  224. // Now check that the socket was indeed open.
  225. ASSERT_GT(isc::config::CommandMgr::instance().getControlSocketFD(), -1);
  226. }
  227. /// @brief Reset
  228. void reset() {
  229. CtrlDhcpv6SrvTest::reset();
  230. ::remove(socket_path_.c_str());
  231. }
  232. /// @brief Conducts a command/response exchange via UnixCommandSocket
  233. ///
  234. /// This method connects to the given server over the given socket path.
  235. /// If successful, it then sends the given command and retrieves the
  236. /// server's response. Note that it calls the server's receivePacket()
  237. /// method where needed to cause the server to process IO events on
  238. /// control channel the control channel sockets.
  239. ///
  240. /// @param command the command text to execute in JSON form
  241. /// @param response variable into which the received response should be
  242. /// placed.
  243. void sendUnixCommand(const std::string& command, std::string& response) {
  244. response = "";
  245. boost::scoped_ptr<UnixControlClient> client;
  246. client.reset(new UnixControlClient());
  247. ASSERT_TRUE(client);
  248. // Connect and then call server's receivePacket() so it can
  249. // detect the control socket connect and call the accept handler
  250. ASSERT_TRUE(client->connectToServer(socket_path_));
  251. ASSERT_NO_THROW(server_->receivePacket(0));
  252. // Send the command and then call server's receivePacket() so it can
  253. // detect the inbound data and call the read handler
  254. ASSERT_TRUE(client->sendCommand(command));
  255. ASSERT_NO_THROW(server_->receivePacket(0));
  256. // Read the response generated by the server. Note that getResponse
  257. // only fails if there an IO error or no response data was present.
  258. // It is not based on the response content.
  259. ASSERT_TRUE(client->getResponse(response));
  260. // Now disconnect and process the close event
  261. client->disconnectFromServer();
  262. ASSERT_NO_THROW(server_->receivePacket(0));
  263. }
  264. };
  265. TEST_F(CtrlDhcpv6SrvTest, commands) {
  266. boost::scoped_ptr<ControlledDhcpv6Srv> srv;
  267. ASSERT_NO_THROW(
  268. srv.reset(new ControlledDhcpv6Srv(DHCP6_SERVER_PORT + 10000))
  269. );
  270. // Use empty parameters list
  271. ElementPtr params(new isc::data::MapElement());
  272. int rcode = -1;
  273. // Case 1: send bogus command
  274. ConstElementPtr result = ControlledDhcpv6Srv::processCommand("blah", params);
  275. ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
  276. EXPECT_EQ(1, rcode); // expect failure (no such command as blah)
  277. // Case 2: send shutdown command without any parameters
  278. result = ControlledDhcpv6Srv::processCommand("shutdown", params);
  279. comment = isc::config::parseAnswer(rcode, result);
  280. EXPECT_EQ(0, rcode); // expect success
  281. const pid_t pid(getpid());
  282. ConstElementPtr x(new isc::data::IntElement(pid));
  283. params->set("pid", x);
  284. // Case 3: send shutdown command with 1 parameter: pid
  285. result = ControlledDhcpv6Srv::processCommand("shutdown", params);
  286. comment = isc::config::parseAnswer(rcode, result);
  287. EXPECT_EQ(0, rcode); // Expect success
  288. }
  289. // Check that the "libreload" command will reload libraries
  290. TEST_F(CtrlDhcpv6SrvTest, libreload) {
  291. // Sending commands for processing now requires a server that can process
  292. // them.
  293. boost::scoped_ptr<ControlledDhcpv6Srv> srv;
  294. ASSERT_NO_THROW(
  295. srv.reset(new ControlledDhcpv6Srv(0))
  296. );
  297. // Ensure no marker files to start with.
  298. ASSERT_FALSE(checkMarkerFileExists(LOAD_MARKER_FILE));
  299. ASSERT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  300. // Load two libraries
  301. std::vector<std::string> libraries;
  302. libraries.push_back(CALLOUT_LIBRARY_1);
  303. libraries.push_back(CALLOUT_LIBRARY_2);
  304. HooksManager::loadLibraries(libraries);
  305. // Check they are loaded.
  306. std::vector<std::string> loaded_libraries =
  307. HooksManager::getLibraryNames();
  308. ASSERT_TRUE(libraries == loaded_libraries);
  309. // ... which also included checking that the marker file created by the
  310. // load functions exists and holds the correct value (of "12" - the
  311. // first library appends "1" to the file, the second appends "2"). Also
  312. // check that the unload marker file does not yet exist.
  313. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "12"));
  314. EXPECT_FALSE(checkMarkerFileExists(UNLOAD_MARKER_FILE));
  315. // Now execute the "libreload" command. This should cause the libraries
  316. // to unload and to reload.
  317. // Use empty parameters list
  318. ElementPtr params(new isc::data::MapElement());
  319. int rcode = -1;
  320. ConstElementPtr result =
  321. ControlledDhcpv6Srv::processCommand("libreload", params);
  322. ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
  323. EXPECT_EQ(0, rcode); // Expect success
  324. // Check that the libraries have unloaded and reloaded. The libraries are
  325. // unloaded in the reverse order to which they are loaded. When they load,
  326. // they should append information to the loading marker file.
  327. EXPECT_TRUE(checkMarkerFile(UNLOAD_MARKER_FILE, "21"));
  328. EXPECT_TRUE(checkMarkerFile(LOAD_MARKER_FILE, "1212"));
  329. }
  330. // Check that the "configReload" command will reload libraries
  331. TEST_F(CtrlDhcpv6SrvTest, configReload) {
  332. // Sending commands for processing now requires a server that can process
  333. // them.
  334. boost::scoped_ptr<ControlledDhcpv6Srv> srv;
  335. ASSERT_NO_THROW(
  336. srv.reset(new ControlledDhcpv6Srv(0))
  337. );
  338. // Now execute the "libreload" command. This should cause the libraries
  339. // to unload and to reload.
  340. // Use empty parameters list
  341. // Prepare configuration file.
  342. string config_txt = "{ \"interfaces-config\": {"
  343. " \"interfaces\": [ \"*\" ]"
  344. "},"
  345. "\"preferred-lifetime\": 3000,"
  346. "\"rebind-timer\": 2000, "
  347. "\"renew-timer\": 1000, "
  348. "\"subnet6\": [ { "
  349. " \"pools\": [ { \"pool\": \"2001:db8:1::/80\" } ],"
  350. " \"subnet\": \"2001:db8:1::/64\" "
  351. " },"
  352. " {"
  353. " \"pools\": [ { \"pool\": \"2001:db8:2::/80\" } ],"
  354. " \"subnet\": \"2001:db8:2::/64\", "
  355. " \"id\": 0"
  356. " },"
  357. " {"
  358. " \"pools\": [ { \"pool\": \"2001:db8:3::/80\" } ],"
  359. " \"subnet\": \"2001:db8:3::/64\" "
  360. " } ],"
  361. "\"valid-lifetime\": 4000 }";
  362. ElementPtr config = Element::fromJSON(config_txt);
  363. // Make sure there are no subnets configured.
  364. CfgMgr::instance().clear();
  365. // Now send the command
  366. int rcode = -1;
  367. ConstElementPtr result =
  368. ControlledDhcpv6Srv::processCommand("config-reload", config);
  369. ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
  370. EXPECT_EQ(0, rcode); // Expect success
  371. // Check that the config was indeed applied.
  372. const Subnet6Collection* subnets =
  373. CfgMgr::instance().getStagingCfg()->getCfgSubnets6()->getAll();
  374. EXPECT_EQ(3, subnets->size());
  375. // Clean up after the test.
  376. CfgMgr::instance().clear();
  377. }
  378. typedef std::map<std::string, isc::data::ConstElementPtr> ElementMap;
  379. // This test checks which commands are registered by the DHCPv4 server.
  380. TEST_F(CtrlDhcpv6SrvTest, commandsRegistration) {
  381. ConstElementPtr list_cmds = createCommand("list-commands");
  382. ConstElementPtr answer;
  383. // By default the list should be empty (except the standard list-commands
  384. // supported by the CommandMgr itself)
  385. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  386. ASSERT_TRUE(answer);
  387. ASSERT_TRUE(answer->get("arguments"));
  388. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  389. // Created server should register several additional commands.
  390. boost::scoped_ptr<ControlledDhcpv6Srv> srv;
  391. ASSERT_NO_THROW(
  392. srv.reset(new ControlledDhcpv6Srv(0));
  393. );
  394. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  395. ASSERT_TRUE(answer);
  396. ASSERT_TRUE(answer->get("arguments"));
  397. std::string command_list = answer->get("arguments")->str();
  398. EXPECT_TRUE(command_list.find("\"list-commands\"") != string::npos);
  399. EXPECT_TRUE(command_list.find("\"statistic-get\"") != string::npos);
  400. EXPECT_TRUE(command_list.find("\"statistic-get-all\"") != string::npos);
  401. EXPECT_TRUE(command_list.find("\"statistic-remove\"") != string::npos);
  402. EXPECT_TRUE(command_list.find("\"statistic-remove-all\"") != string::npos);
  403. EXPECT_TRUE(command_list.find("\"statistic-reset\"") != string::npos);
  404. EXPECT_TRUE(command_list.find("\"statistic-reset-all\"") != string::npos);
  405. // Ok, and now delete the server. It should deregister its commands.
  406. srv.reset();
  407. // The list should be (almost) empty again.
  408. EXPECT_NO_THROW(answer = CommandMgr::instance().processCommand(list_cmds));
  409. ASSERT_TRUE(answer);
  410. ASSERT_TRUE(answer->get("arguments"));
  411. EXPECT_EQ("[ \"list-commands\" ]", answer->get("arguments")->str());
  412. }
  413. // Tests that the server properly responds to invalid commands sent
  414. // via ControlChannel
  415. TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelNegative) {
  416. createUnixChannelServer();
  417. std::string response;
  418. sendUnixCommand("{ \"command\": \"bogus\" }", response);
  419. EXPECT_EQ("{ \"result\": 1,"
  420. " \"text\": \"'bogus' command not supported.\" }", response);
  421. sendUnixCommand("utter nonsense", response);
  422. EXPECT_EQ("{ \"result\": 1, "
  423. "\"text\": \"error: unexpected character u in <string>:1:2\" }",
  424. response);
  425. }
  426. // Tests that the server properly responds to shtudown command sent
  427. // via ControlChannel
  428. TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelShutdown) {
  429. createUnixChannelServer();
  430. std::string response;
  431. sendUnixCommand("{ \"command\": \"shutdown\" }", response);
  432. EXPECT_EQ("{ \"result\": 0, \"text\": \"Shutting down.\" }",response);
  433. }
  434. // Tests that the server properly responds to statistics commands. Note this
  435. // is really only intended to verify that the appropriate Statistics handler
  436. // is called based on the command. It is not intended to be an exhaustive
  437. // test of Dhcpv6 statistics.
  438. TEST_F(CtrlChannelDhcpv6SrvTest, controlChannelStats) {
  439. createUnixChannelServer();
  440. std::string response;
  441. // Check statistic-get
  442. sendUnixCommand("{ \"command\" : \"statistic-get\", "
  443. " \"arguments\": {"
  444. " \"name\":\"bogus\" }}", response);
  445. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  446. // Check statistic-get-all
  447. sendUnixCommand("{ \"command\" : \"statistic-get-all\", "
  448. " \"arguments\": {}}", response);
  449. EXPECT_EQ("{ \"arguments\": { }, \"result\": 0 }", response);
  450. // Check statistic-reset
  451. sendUnixCommand("{ \"command\" : \"statistic-reset\", "
  452. " \"arguments\": {"
  453. " \"name\":\"bogus\" }}", response);
  454. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  455. response);
  456. // Check statistic-reset-all
  457. sendUnixCommand("{ \"command\" : \"statistic-reset-all\", "
  458. " \"arguments\": {}}", response);
  459. EXPECT_EQ("{ \"result\": 0, \"text\": "
  460. "\"All statistics reset to neutral values.\" }", response);
  461. // Check statistic-remove
  462. sendUnixCommand("{ \"command\" : \"statistic-remove\", "
  463. " \"arguments\": {"
  464. " \"name\":\"bogus\" }}", response);
  465. EXPECT_EQ("{ \"result\": 1, \"text\": \"No 'bogus' statistic found\" }",
  466. response);
  467. // Check statistic-remove-all
  468. sendUnixCommand("{ \"command\" : \"statistic-remove-all\", "
  469. " \"arguments\": {}}", response);
  470. EXPECT_EQ("{ \"result\": 0, \"text\": \"All statistics removed.\" }",
  471. response);
  472. }
  473. } // End of anonymous namespace