sockcreator_tests.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright (C) 2011-2012 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 "../sockcreator.h"
  15. #include <util/unittests/fork.h>
  16. #include <util/io/fd.h>
  17. #include <boost/lexical_cast.hpp>
  18. #include <gtest/gtest.h>
  19. #include <sys/types.h>
  20. #include <sys/socket.h>
  21. #include <netinet/in.h>
  22. #include <arpa/inet.h>
  23. #include <unistd.h>
  24. #include <iostream>
  25. #include <cstring>
  26. #include <cerrno>
  27. using namespace isc::socket_creator;
  28. using namespace isc::util::unittests;
  29. using namespace isc::util::io;
  30. // The tests check both TCP and UDP sockets on IPv4 and IPv6.
  31. //
  32. // Essentially we need to check all four combinations of TCP/UDP and IPv4/IPv6.
  33. // The different address families (IPv4/IPv6) require different structures to
  34. // hold the address information, and so some common code is in the form of
  35. // templates (or overloads), parameterised on the structure type.
  36. //
  37. // The protocol is determined by an integer (SOCK_STREAM or SOCK_DGRAM) so
  38. // cannot be templated in the same way. Relevant check functions are
  39. // selected manually.
  40. namespace {
  41. // Set IP-version-specific fields.
  42. void
  43. setAddressFamilyFields(sockaddr_in* address) {
  44. address->sin_family = AF_INET;
  45. address->sin_addr.s_addr = INADDR_ANY;
  46. }
  47. void
  48. setAddressFamilyFields(sockaddr_in6* address) {
  49. address->sin6_family = AF_INET6;
  50. address->sin6_addr = in6addr_loopback;
  51. }
  52. // Socket has been opened, peform a check on it. The sole argument is the
  53. // socket descriptor. The TCP check is the same regardless of the address
  54. // family. The UDP check requires that the socket address be obtained so
  55. // is parameterised on the type of structure required to hold the address.
  56. void
  57. tcpCheck(const int socknum) {
  58. // Sufficient to be able to listen on the socket.
  59. EXPECT_EQ(0, listen(socknum, 1));
  60. }
  61. template <typename ADDRTYPE>
  62. void
  63. udpCheck(const int socknum) {
  64. // UDP testing is more complicated than TCP: send a packet to ourselves and
  65. // see if it arrives.
  66. // Get details of the socket so that we can use it as the target of the
  67. // sendto().
  68. ADDRTYPE addr;
  69. memset(&addr, 0, sizeof(addr));
  70. sockaddr* addr_ptr = reinterpret_cast<sockaddr*>(&addr);
  71. socklen_t len = sizeof(addr);
  72. ASSERT_EQ(0, getsockname(socknum, addr_ptr, &len));
  73. // Send the packet to ourselves and check we receive it.
  74. ASSERT_EQ(5, sendto(socknum, "test", 5, 0, addr_ptr, sizeof(addr))) <<
  75. "Send failed with error " << strerror(errno) << " on socket " <<
  76. socknum;
  77. char buffer[5];
  78. ASSERT_EQ(5, recv(socknum, buffer, 5, 0)) <<
  79. "Recv failed with error " << strerror(errno) << " on socket " <<
  80. socknum;
  81. EXPECT_STREQ("test", buffer);
  82. }
  83. // The check function (tcpCheck/udpCheck) is passed as a parameter to the test
  84. // code, so provide a conveniet typedef.
  85. typedef void (*socket_check_t)(const int);
  86. // Address-family-specific scoket checks.
  87. //
  88. // The first argument is used to select the overloaded check function.
  89. // The other argument is the socket descriptor number.
  90. // IPv4 check
  91. void addressFamilySpecificCheck(const sockaddr_in*, const int, const int) {
  92. }
  93. // IPv6 check
  94. void addressFamilySpecificCheck(const sockaddr_in6*, const int socknum,
  95. const int socket_type)
  96. {
  97. int options;
  98. socklen_t len = sizeof(options);
  99. EXPECT_EQ(0, getsockopt(socknum, IPPROTO_IPV6, IPV6_V6ONLY, &options,
  100. &len));
  101. EXPECT_NE(0, options);
  102. if (socket_type == SOCK_DGRAM) {
  103. // Some more checks for UDP - MTU
  104. #ifdef IPV6_USE_MIN_MTU /* RFC 3542, not too common yet*/
  105. // use minimum MTU
  106. EXPECT_EQ(0, getsockopt(socknum, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
  107. &options, &len)) << strerror(errno);
  108. EXPECT_NE(0, options);
  109. #else
  110. // We do not check for the IPV6_MTU, because while setting works (eg.
  111. // the packets are fragmented correctly), the getting does not. If
  112. // we try to getsockopt it, an error complaining it can't be accessed
  113. // on unconnected socket is returned. If we try to connect it, the
  114. // MTU of the interface is returned, not the one we set. So we live
  115. // in belief it works because we examined the packet dump.
  116. #if defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
  117. // Turned off Path MTU discovery on IPv6/UDP sockets?
  118. EXPECT_EQ(0, getsockopt(socknum, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
  119. &options, &len)) << strerror(errno);
  120. EXPECT_EQ(IPV6_PMTUDISC_DONT, options);
  121. #endif
  122. #endif
  123. }
  124. }
  125. // Just ignore the fd and pretend success. We close invalid fds in the tests.
  126. int
  127. closeIgnore(int) {
  128. return (0);
  129. }
  130. // Generic version of the socket test. It creates the socket and checks that
  131. // it is a valid descriptor. The family-specific check functions are called
  132. // to check that the socket is valid. The function is parameterised according
  133. // to the structure used to hold the address.
  134. //
  135. // Arguments:
  136. // socket_type Type of socket to create (SOCK_DGRAM or SOCK_STREAM)
  137. // socket_check Associated check function - udpCheck() or tcpCheck()
  138. template <typename ADDRTYPE>
  139. void testAnyCreate(int socket_type, socket_check_t socket_check) {
  140. // Create the socket.
  141. ADDRTYPE addr;
  142. memset(&addr, 0, sizeof(addr));
  143. setAddressFamilyFields(&addr);
  144. sockaddr* addr_ptr = reinterpret_cast<sockaddr*>(&addr);
  145. const int socket = getSock(socket_type, addr_ptr, sizeof(addr),
  146. closeIgnore);
  147. ASSERT_GE(socket, 0) << "Couldn't create socket: failed with " <<
  148. "return code " << socket << " and error " << strerror(errno);
  149. // Perform socket-type-specific testing.
  150. socket_check(socket);
  151. // Do address-family-independent
  152. int options;
  153. socklen_t len = sizeof(options);
  154. EXPECT_EQ(0, getsockopt(socket, SOL_SOCKET, SO_REUSEADDR, &options, &len));
  155. EXPECT_NE(0, options);
  156. // ...and the address-family specific tests.
  157. addressFamilySpecificCheck(&addr, socket, socket_type);
  158. // Tidy up and exit.
  159. EXPECT_EQ(0, close(socket));
  160. }
  161. // Several tests to ensure we can create the sockets.
  162. TEST(get_sock, udp4_create) {
  163. testAnyCreate<sockaddr_in>(SOCK_DGRAM, udpCheck<sockaddr_in>);
  164. }
  165. TEST(get_sock, tcp4_create) {
  166. testAnyCreate<sockaddr_in>(SOCK_STREAM, tcpCheck);
  167. }
  168. TEST(get_sock, udp6_create) {
  169. testAnyCreate<sockaddr_in6>(SOCK_DGRAM, udpCheck<sockaddr_in6>);
  170. }
  171. TEST(get_sock, tcp6_create) {
  172. testAnyCreate<sockaddr_in6>(SOCK_STREAM, tcpCheck);
  173. }
  174. bool close_called(false);
  175. // You can use it as a close mockup. If you care about checking if it was really
  176. // called, you can use the close_called variable. But set it to false before the
  177. // test.
  178. int closeCall(int socket) {
  179. close(socket);
  180. close_called = true;
  181. return (0);
  182. }
  183. // Ask the get_sock function for some nonsense and test if it is able to report
  184. // an error.
  185. TEST(get_sock, fail_with_nonsense) {
  186. sockaddr addr;
  187. memset(&addr, 0, sizeof(addr));
  188. close_called = false;
  189. ASSERT_EQ(-1, getSock(0, &addr, sizeof addr, closeCall));
  190. ASSERT_FALSE(close_called); // The "socket" call should have failed already
  191. }
  192. // Bind should have failed here
  193. TEST(get_sock, fail_with_bind) {
  194. sockaddr_in addr;
  195. memset(&addr, 0, sizeof(addr));
  196. addr.sin_family = AF_INET;
  197. addr.sin_port = 1;
  198. // No host should have this address on the interface, so it should not be
  199. // possible to bind it.
  200. addr.sin_addr.s_addr = inet_addr("192.0.2.1");
  201. close_called = false;
  202. ASSERT_EQ(-2, getSock(SOCK_STREAM, reinterpret_cast<sockaddr*>(&addr),
  203. sizeof addr, closeCall));
  204. ASSERT_TRUE(close_called); // The "socket" call should have failed already
  205. }
  206. // The main run() function in the socket creator takes three functions to
  207. // get the socket, send information to it, and close it. These allow for
  208. // alternatives to the system functions to be used for testing.
  209. // Replacement getSock() function.
  210. // The return value indicates the result of checks and is encoded. Using LSB
  211. // bit numbering (least-significant bit is bit 0) then:
  212. //
  213. // bit 0: 1 if "type" is known, 0 otherwise
  214. // bit 1: 1 for UDP, 0 for TCP
  215. // bit 2: 1 if address family is known, 0 otherwise
  216. // bit 3: 1 for IPv6, 0 for IPv4
  217. // bit 4: 1 if port passed was valid
  218. //
  219. // Other possible return values are:
  220. //
  221. // -1: The simulated bind() call has failed
  222. // -2: The simulated socket() call has failed
  223. int
  224. getSockDummy(const int type, struct sockaddr* addr, const socklen_t,
  225. const close_t) {
  226. int result = 0;
  227. int port = 0;
  228. // Validate type field
  229. switch (type) {
  230. case SOCK_STREAM:
  231. result |= 0x01;
  232. break;
  233. case SOCK_DGRAM:
  234. result |= 0x03;
  235. break;
  236. }
  237. // Validate address family
  238. switch (addr->sa_family) {
  239. case AF_INET:
  240. result |= 0x04;
  241. port = reinterpret_cast<sockaddr_in*>(addr)->sin_port;
  242. break;
  243. case AF_INET6:
  244. result |= 0x0C;
  245. port = reinterpret_cast<sockaddr_in6*>(addr)->sin6_port;
  246. break;
  247. }
  248. // The port should be 0xffff. If it's not, we change the result.
  249. // The port of 0xbbbb means bind should fail and 0xcccc means
  250. // socket should fail.
  251. if (port != 0xffff) {
  252. errno = 0;
  253. if (port == 0xbbbb) {
  254. return (-2);
  255. } else if (port == 0xcccc) {
  256. return (-1);
  257. } else {
  258. result |= 0x10;
  259. }
  260. }
  261. return (result);
  262. }
  263. // Dummy send function - return data (the result of getSock()) to the destination.
  264. int
  265. send_FdDummy(const int destination, const int what) {
  266. // Make sure it is 1 byte so we know the length. We do not use more during
  267. // the test anyway. And even with the LS bute, we can distinguish between
  268. // the different results.
  269. const char fd_data = what & 0xff;
  270. const bool status = write_data(destination, &fd_data, sizeof(fd_data));
  271. return (status ? 0 : -1);
  272. }
  273. // Generic test that it works, with various inputs and outputs.
  274. // It uses different functions to create the socket and send it and pass
  275. // data to it and check it returns correct data back, to see if the run()
  276. // parses the commands correctly.
  277. void runTest(const char* input_data, const size_t input_size,
  278. const char* output_data, const size_t output_size,
  279. bool should_succeed = true,
  280. const close_t test_close = closeIgnore,
  281. const send_fd_t send_fd = send_FdDummy)
  282. {
  283. // Prepare the input feeder and output checker processes. The feeder
  284. // process sends data from the client to run() and the checker process
  285. // reads the response and checks it against the expected response.
  286. int input_fd = 0;
  287. const pid_t input = provide_input(&input_fd, input_data, input_size);
  288. ASSERT_NE(-1, input) << "Couldn't start input feeder";
  289. int output_fd = 0;
  290. const pid_t output = check_output(&output_fd, output_data, output_size);
  291. ASSERT_NE(-1, output) << "Couldn't start output checker";
  292. // Run the body
  293. if (should_succeed) {
  294. EXPECT_NO_THROW(run(input_fd, output_fd, getSockDummy, send_fd,
  295. test_close));
  296. } else {
  297. EXPECT_THROW(run(input_fd, output_fd, getSockDummy, send_fd,
  298. test_close), isc::socket_creator::SocketCreatorError);
  299. }
  300. // Close the pipes
  301. close(input_fd);
  302. close(output_fd);
  303. // Check the subprocesses say everything is OK too
  304. EXPECT_TRUE(process_ok(input));
  305. EXPECT_TRUE(process_ok(output));
  306. }
  307. // Check it terminates successfully when asked to.
  308. TEST(run, terminate) {
  309. runTest("T", 1, NULL, 0);
  310. }
  311. // Check it rejects incorrect input.
  312. TEST(run, bad_input) {
  313. runTest("XXX", 3, "FI", 2, false);
  314. }
  315. // Check it correctly parses query stream to create sockets.
  316. TEST(run, sockets) {
  317. runTest(
  318. // Commands:
  319. "SU4\xff\xff\0\0\0\0" // IPv4 UDP socket, port 0xffffff, address 0.0.0.0
  320. "ST4\xff\xff\0\0\0\0" // IPv4 TCP socket, port 0xffffff, address 0.0.0.0
  321. "ST6\xff\xff\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
  322. // IPv6 UDP socket, port 0xffffff, address ::
  323. "SU6\xff\xff\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
  324. // IPv6 TCP socket, port 0xffffff, address ::
  325. "T", // ... and terminate
  326. 9 + 9 + 21 + 21 + 1, // Length of command string
  327. "S\x07S\x05S\x0dS\x0f", // Response ("S" + LS byte of getSock() return)
  328. 8); // Length of response
  329. }
  330. // Check if failures of get_socket are handled correctly.
  331. TEST(run, bad_sockets) {
  332. // We need to construct the answer, but it depends on int length. We expect
  333. // two failure answers in this test, each answer comprising two characters
  334. // followed by the (int) errno value.
  335. char result[2 * (2 + sizeof(int))];
  336. // We expect the errno parts to be zero but the characters to depend on the
  337. // exact failure.
  338. memset(result, 0, sizeof(result));
  339. strcpy(result, "EB");
  340. strcpy(result + 2 + sizeof(int), "ES");
  341. // Run the test
  342. runTest(
  343. "SU4\xbb\xbb\0\0\0\0" // Port number will trigger simulated bind() fail
  344. "SU4\xcc\xcc\0\0\0\0" // Port number will trigger simulated socket() fail
  345. "T", // Terminate
  346. 19, // Length of command string
  347. result, sizeof(result));
  348. }
  349. // A close that fails. (This causes an abort.)
  350. int
  351. closeFail(int) {
  352. return (-1);
  353. }
  354. TEST(run, cant_close) {
  355. runTest("SU4\xff\xff\0\0\0\0", 9,
  356. "S\x07", 2,
  357. false, closeFail);
  358. }
  359. // A send of the file descriptor that fails. In this case we expect the client
  360. // to receive the "S" indicating that the descriptor is being sent and nothing
  361. // else. This causes an abort.
  362. int
  363. sendFDFail(const int, const int) {
  364. return (FD_SYSTEM_ERROR);
  365. }
  366. TEST(run, cant_send_fd) {
  367. runTest("SU4\xff\xff\0\0\0\0", 9,
  368. "S", 1,
  369. false, closeIgnore, sendFDFail);
  370. }
  371. } // Anonymous namespace