socketsession_unittest.cc 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. // Copyright (C) 2011 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 <sys/types.h>
  16. #include <sys/socket.h>
  17. #include <sys/un.h>
  18. #include <netinet/in.h>
  19. #include <fcntl.h>
  20. #include <netdb.h>
  21. #include <unistd.h>
  22. #include <cerrno>
  23. #include <cstring>
  24. #include <cstdlib>
  25. #include <algorithm>
  26. #include <string>
  27. #include <utility>
  28. #include <vector>
  29. #include <boost/noncopyable.hpp>
  30. #include <boost/scoped_ptr.hpp>
  31. #include <gtest/gtest.h>
  32. #include <exceptions/exceptions.h>
  33. #include <util/buffer.h>
  34. #include <util/io/fd_share.h>
  35. #include <util/io/socketsession.h>
  36. #include <util/io/sockaddr_util.h>
  37. using namespace std;
  38. using namespace isc;
  39. using boost::scoped_ptr;
  40. using namespace isc::util::io;
  41. using namespace isc::util::io::internal;
  42. namespace {
  43. const char* const TEST_PORT = "53535";
  44. const char* const TEST_PORT2 = "53536"; // use this in case we need 2 ports
  45. const char TEST_DATA[] = "Kea test";
  46. // A simple helper structure to automatically close test sockets on return
  47. // or exception in a RAII manner. non copyable to prevent duplicate close.
  48. struct ScopedSocket : boost::noncopyable {
  49. ScopedSocket() : fd(-1) {}
  50. ScopedSocket(int sock) : fd(sock) {}
  51. ~ScopedSocket() {
  52. closeSocket();
  53. }
  54. void reset(int sock) {
  55. closeSocket();
  56. fd = sock;
  57. }
  58. int fd;
  59. private:
  60. void closeSocket() {
  61. if (fd >= 0) {
  62. close(fd);
  63. }
  64. }
  65. };
  66. // A helper function that makes a test socket non block so that a certain
  67. // kind of test failure (such as missing send) won't cause hangup.
  68. void
  69. setNonBlock(int s, bool on) {
  70. int fcntl_flags = fcntl(s, F_GETFL, 0);
  71. if (on) {
  72. fcntl_flags |= O_NONBLOCK;
  73. } else {
  74. fcntl_flags &= ~O_NONBLOCK;
  75. }
  76. if (fcntl(s, F_SETFL, fcntl_flags) == -1) {
  77. isc_throw(isc::Unexpected, "fcntl(O_NONBLOCK) failed: " <<
  78. strerror(errno));
  79. }
  80. }
  81. // A helper to impose some reasonable amount of wait on recv(from)
  82. // if possible. It returns an option flag to be set for the system call
  83. // (when necessary).
  84. int
  85. setRecvDelay(int s) {
  86. const struct timeval timeo = { 10, 0 };
  87. if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo)) == -1) {
  88. if (errno == ENOPROTOOPT) {
  89. // Workaround for Solaris: see recursive_query_unittest
  90. return (MSG_DONTWAIT);
  91. } else {
  92. isc_throw(isc::Unexpected, "set RCVTIMEO failed: " <<
  93. strerror(errno));
  94. }
  95. }
  96. return (0);
  97. }
  98. // A shortcut type that is convenient to be used for socket related
  99. // system calls, which generally require this pair
  100. typedef pair<const struct sockaddr*, socklen_t> SockAddrInfo;
  101. // A helper class to convert textual representation of IP address and port
  102. // to a pair of sockaddr and its length (in the form of a SockAddrInfo
  103. // pair). Its get method uses getaddrinfo(3) for the conversion and stores
  104. // the result in the addrinfo_list_ vector until the object is destroyed.
  105. // The allocated resources will be automatically freed in an RAII manner.
  106. class SockAddrCreator {
  107. public:
  108. ~SockAddrCreator() {
  109. vector<struct addrinfo*>::const_iterator it;
  110. for (it = addrinfo_list_.begin(); it != addrinfo_list_.end(); ++it) {
  111. freeaddrinfo(*it);
  112. }
  113. }
  114. SockAddrInfo get(const string& addr_str, const string& port_str) {
  115. struct addrinfo hints, *res;
  116. memset(&hints, 0, sizeof(hints));
  117. hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
  118. hints.ai_family = AF_UNSPEC;
  119. hints.ai_socktype = SOCK_DGRAM; // could be either DGRAM or STREAM here
  120. const int error = getaddrinfo(addr_str.c_str(), port_str.c_str(),
  121. &hints, &res);
  122. if (error != 0) {
  123. isc_throw(isc::Unexpected, "getaddrinfo failed for " <<
  124. addr_str << ", " << port_str << ": " <<
  125. gai_strerror(error));
  126. }
  127. // Technically, this is not entirely exception safe; if push_back
  128. // throws, the resources allocated for 'res' will leak. We prefer
  129. // brevity here and ignore the minor failure mode.
  130. addrinfo_list_.push_back(res);
  131. return (SockAddrInfo(res->ai_addr, res->ai_addrlen));
  132. }
  133. private:
  134. vector<struct addrinfo*> addrinfo_list_;
  135. };
  136. class ForwardTest : public ::testing::Test {
  137. protected:
  138. /// @brief Returns socket path (using either hardcoded path or env variable)
  139. /// @return path to the unix socket
  140. std::string getSocketPath() {
  141. std::string socket_path;
  142. const char* env = getenv("KEA_SOCKET_TEST_DIR");
  143. if (env) {
  144. socket_path = string(env) + "/test.unix";
  145. } else {
  146. socket_path = string(TEST_DATA_BUILDDIR) + "/test.unix";
  147. }
  148. return (socket_path);
  149. }
  150. ForwardTest() : listen_fd_(-1), forwarder_(getSocketPath()),
  151. large_text_(65535, 'a'),
  152. test_un_len_(2 + strlen(getSocketPath().c_str()))
  153. {
  154. std::string unix_file = getSocketPath();
  155. unlink(unix_file.c_str());
  156. test_un_.sun_family = AF_UNIX;
  157. strncpy(test_un_.sun_path, unix_file.c_str(), sizeof(test_un_.sun_path));
  158. #ifdef HAVE_SA_LEN
  159. test_un_.sun_len = test_un_len_;
  160. #endif
  161. }
  162. ~ForwardTest() {
  163. if (listen_fd_ != -1) {
  164. close(listen_fd_);
  165. }
  166. unlink(getSocketPath().c_str());
  167. }
  168. // Start an internal "socket session server".
  169. void startListen() {
  170. if (listen_fd_ != -1) {
  171. isc_throw(isc::Unexpected, "duplicate call to startListen()");
  172. }
  173. listen_fd_ = socket(AF_UNIX, SOCK_STREAM, 0);
  174. if (listen_fd_ == -1) {
  175. isc_throw(isc::Unexpected, "failed to create UNIX domain socket" <<
  176. strerror(errno));
  177. }
  178. if (bind(listen_fd_, convertSockAddr(&test_un_), test_un_len_) == -1) {
  179. isc_throw(isc::Unexpected, "failed to bind UNIX domain socket" <<
  180. strerror(errno));
  181. }
  182. // 10 is an arbitrary choice, should be sufficient for a single test
  183. if (listen(listen_fd_, 10) == -1) {
  184. isc_throw(isc::Unexpected, "failed to listen on UNIX domain socket"
  185. << strerror(errno));
  186. }
  187. }
  188. int dummyConnect() const {
  189. const int s = socket(AF_UNIX, SOCK_STREAM, 0);
  190. if (s == -1) {
  191. isc_throw(isc::Unexpected,
  192. "failed to create a test UNIX domain socket");
  193. }
  194. setNonBlock(s, true);
  195. if (connect(s, convertSockAddr(&test_un_), sizeof(test_un_)) == -1) {
  196. isc_throw(isc::Unexpected,
  197. "failed to connect to the test SocketSessionForwarder");
  198. }
  199. return (s);
  200. }
  201. // Accept a new connection from a SocketSessionForwarder and return
  202. // the socket FD of the new connection. This assumes startListen()
  203. // has been called.
  204. int acceptForwarder() {
  205. setNonBlock(listen_fd_, true); // prevent the test from hanging up
  206. struct sockaddr_un from;
  207. socklen_t from_len = sizeof(from);
  208. const int s = accept(listen_fd_, convertSockAddr(&from), &from_len);
  209. if (s == -1) {
  210. isc_throw(isc::Unexpected, "accept failed: " << strerror(errno));
  211. }
  212. // Make sure the socket is *blocking*. We may pass large data, through
  213. // it, and apparently non blocking read could cause some unexpected
  214. // partial read on some systems.
  215. setNonBlock(s, false);
  216. return (s);
  217. }
  218. // A convenient shortcut for the namespace-scope version of getSockAddr
  219. SockAddrInfo getSockAddr(const string& addr_str, const string& port_str) {
  220. return (addr_creator_.get(addr_str, port_str));
  221. }
  222. // A helper method that creates a specified type of socket that is
  223. // supposed to be passed via a SocketSessionForwarder. It will bound
  224. // to the specified address and port in sainfo. If do_listen is true
  225. // and it's a TCP socket, it will also start listening to new connection
  226. // requests.
  227. int createSocket(int family, int type, int protocol,
  228. const SockAddrInfo& sainfo, bool do_listen)
  229. {
  230. int s = socket(family, type, protocol);
  231. if (s < 0) {
  232. isc_throw(isc::Unexpected, "socket(2) failed: " <<
  233. strerror(errno));
  234. }
  235. const int on = 1;
  236. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
  237. isc_throw(isc::Unexpected, "setsockopt(SO_REUSEADDR) failed: " <<
  238. strerror(errno));
  239. }
  240. if (bind(s, sainfo.first, sainfo.second) < 0) {
  241. close(s);
  242. isc_throw(isc::Unexpected, "bind(2) failed: " <<
  243. strerror(errno));
  244. }
  245. if (do_listen && protocol == IPPROTO_TCP) {
  246. if (listen(s, 1) == -1) {
  247. isc_throw(isc::Unexpected, "listen(2) failed: " <<
  248. strerror(errno));
  249. }
  250. }
  251. return (s);
  252. }
  253. // A helper method to push some (normally bogus) socket session header
  254. // via a Unix domain socket that pretends to be a valid
  255. // SocketSessionForwarder. It first opens the Unix domain socket,
  256. // and connect to the test receiver server (startListen() is expected to
  257. // be called beforehand), forwards a valid file descriptor ("stdin" is
  258. // used for simplicity), the pushed a 2-byte header length field of the
  259. // session header. The internal receiver_ pointer will be set to a
  260. // newly created receiver object for the connection.
  261. //
  262. // \param hdrlen: The header length to be pushed. It may or may not be
  263. // valid.
  264. // \param hdrlen_len: The length of the actually pushed data as "header
  265. // length". Normally it should be 2 (the default), but
  266. // could be a bogus value for testing.
  267. // \param push_fd: Whether to forward the FD. Normally it should be true,
  268. // but can be false for testing.
  269. void pushSessionHeader(uint16_t hdrlen,
  270. size_t hdrlen_len = sizeof(uint16_t),
  271. bool push_fd = true,
  272. int fd = 0)
  273. {
  274. isc::util::OutputBuffer obuffer(0);
  275. obuffer.clear();
  276. dummy_forwarder_.reset(dummyConnect());
  277. if (push_fd && send_fd(dummy_forwarder_.fd, fd) != 0) {
  278. isc_throw(isc::Unexpected, "Failed to pass FD");
  279. }
  280. obuffer.writeUint16(hdrlen);
  281. if (hdrlen_len > 0) {
  282. if (send(dummy_forwarder_.fd, obuffer.getData(), hdrlen_len, 0) !=
  283. hdrlen_len) {
  284. isc_throw(isc::Unexpected,
  285. "Failed to pass session header len");
  286. }
  287. }
  288. accept_sock_.reset(acceptForwarder());
  289. receiver_.reset(new SocketSessionReceiver(accept_sock_.fd));
  290. }
  291. // A helper method to push some (normally bogus) socket session via a
  292. // Unix domain socket pretending to be a valid SocketSessionForwarder.
  293. // It internally calls pushSessionHeader() for setup and pushing the
  294. // header, and pass (often bogus) header data and session data based
  295. // on the function parameters. The parameters are generally compatible
  296. // to those for SocketSessionForwarder::push, but could be invalid for
  297. // testing purposes. For session data, we use TEST_DATA and its size
  298. // by default for simplicity, but the size can be tweaked for testing.
  299. void pushSession(int family, int type, int protocol, socklen_t local_len,
  300. const sockaddr& local, socklen_t remote_len,
  301. const sockaddr& remote,
  302. size_t data_len = sizeof(TEST_DATA))
  303. {
  304. isc::util::OutputBuffer obuffer(0);
  305. obuffer.writeUint32(static_cast<uint32_t>(family));
  306. obuffer.writeUint32(static_cast<uint32_t>(type));
  307. obuffer.writeUint32(static_cast<uint32_t>(protocol));
  308. obuffer.writeUint32(static_cast<uint32_t>(local_len));
  309. obuffer.writeData(&local, min(local_len, getSALength(local)));
  310. obuffer.writeUint32(static_cast<uint32_t>(remote_len));
  311. obuffer.writeData(&remote, min(remote_len, getSALength(remote)));
  312. obuffer.writeUint32(static_cast<uint32_t>(data_len));
  313. pushSessionHeader(obuffer.getLength());
  314. if (send(dummy_forwarder_.fd, obuffer.getData(), obuffer.getLength(),
  315. 0) != obuffer.getLength()) {
  316. isc_throw(isc::Unexpected, "Failed to pass session header");
  317. }
  318. if (send(dummy_forwarder_.fd, TEST_DATA, sizeof(TEST_DATA), 0) !=
  319. sizeof(TEST_DATA)) {
  320. isc_throw(isc::Unexpected, "Failed to pass session data");
  321. }
  322. }
  323. // See below
  324. void checkPushAndPop(int family, int type, int protocol,
  325. const SockAddrInfo& local,
  326. const SockAddrInfo& remote, const void* const data,
  327. size_t data_len, bool new_connection);
  328. protected:
  329. int listen_fd_;
  330. SocketSessionForwarder forwarder_;
  331. ScopedSocket dummy_forwarder_; // forwarder "like" socket to pass bad data
  332. scoped_ptr<SocketSessionReceiver> receiver_;
  333. ScopedSocket accept_sock_;
  334. const string large_text_;
  335. private:
  336. struct sockaddr_un test_un_;
  337. const socklen_t test_un_len_;
  338. SockAddrCreator addr_creator_;
  339. };
  340. TEST_F(ForwardTest, construct) {
  341. // On construction the existence of the file doesn't matter.
  342. SocketSessionForwarder("some_file");
  343. // But too long a path should be rejected
  344. struct sockaddr_un s; // can't be const; some compiler complains
  345. EXPECT_THROW(SocketSessionForwarder(string(sizeof(s.sun_path), 'x')),
  346. SocketSessionError);
  347. // If it's one byte shorter it should be okay
  348. SocketSessionForwarder(string(sizeof(s.sun_path) - 1, 'x'));
  349. }
  350. TEST_F(ForwardTest, connect) {
  351. // File doesn't exist (we assume the file "no_such_file" doesn't exist)
  352. SocketSessionForwarder forwarder("no_such_file");
  353. EXPECT_THROW(forwarder.connectToReceiver(), SocketSessionError);
  354. // The socket should be closed internally, so close() should result in
  355. // error.
  356. EXPECT_THROW(forwarder.close(), BadValue);
  357. // Set up the receiver and connect. It should succeed.
  358. SocketSessionForwarder forwarder2(getSocketPath().c_str());
  359. startListen();
  360. forwarder2.connectToReceiver();
  361. // And it can be closed successfully.
  362. forwarder2.close();
  363. // Duplicate close should fail
  364. EXPECT_THROW(forwarder2.close(), BadValue);
  365. // Once closed, reconnect is okay.
  366. forwarder2.connectToReceiver();
  367. forwarder2.close();
  368. // Duplicate connect should be rejected
  369. forwarder2.connectToReceiver();
  370. EXPECT_THROW(forwarder2.connectToReceiver(), BadValue);
  371. // Connect then destroy. Should be internally closed, but unfortunately
  372. // it's not easy to test it directly. We only check no disruption happens.
  373. SocketSessionForwarder* forwarderp =
  374. new SocketSessionForwarder(getSocketPath().c_str());
  375. forwarderp->connectToReceiver();
  376. delete forwarderp;
  377. }
  378. TEST_F(ForwardTest, close) {
  379. // can't close before connect
  380. EXPECT_THROW(SocketSessionForwarder(getSocketPath().c_str()).close(), BadValue);
  381. }
  382. void
  383. checkSockAddrs(const sockaddr& expected, const sockaddr& actual) {
  384. char hbuf_expected[NI_MAXHOST], sbuf_expected[NI_MAXSERV],
  385. hbuf_actual[NI_MAXHOST], sbuf_actual[NI_MAXSERV];
  386. EXPECT_EQ(0, getnameinfo(&expected, getSALength(expected),
  387. hbuf_expected, sizeof(hbuf_expected),
  388. sbuf_expected, sizeof(sbuf_expected),
  389. NI_NUMERICHOST | NI_NUMERICSERV));
  390. EXPECT_EQ(0, getnameinfo(&actual, getSALength(actual),
  391. hbuf_actual, sizeof(hbuf_actual),
  392. sbuf_actual, sizeof(sbuf_actual),
  393. NI_NUMERICHOST | NI_NUMERICSERV));
  394. EXPECT_EQ(string(hbuf_expected), string(hbuf_actual));
  395. EXPECT_EQ(string(sbuf_expected), string(sbuf_actual));
  396. }
  397. // This is a commonly used test case that confirms normal behavior of
  398. // session passing. It first creates a "local" socket (which is supposed
  399. // to act as a "server") bound to the 'local' parameter. It then forwards
  400. // the descriptor of the FD of the local socket along with given data.
  401. // Next, it creates an Receiver object to receive the forwarded FD itself,
  402. // receives the FD, and sends test data from the received FD. The
  403. // test finally checks if it can receive the test data from the local socket
  404. // at the Forwarder side. In the case of TCP it's a bit complicated because
  405. // it first needs to establish a new connection, but essentially the test
  406. // scenario is the same. See the diagram below for more details.
  407. //
  408. // UDP:
  409. // Forwarder Receiver
  410. // sock -- (pass) --> passed_sock
  411. // (check) <-------- send TEST_DATA
  412. //
  413. // TCP:
  414. // Forwarder Receiver
  415. // server_sock---(pass)--->passed_sock
  416. // ^ |
  417. // |(connect) |
  418. // client_sock |
  419. // (check)<---------send TEST_DATA
  420. void
  421. ForwardTest::checkPushAndPop(int family, int type, int protocol,
  422. const SockAddrInfo& local,
  423. const SockAddrInfo& remote,
  424. const void* const data,
  425. size_t data_len, bool new_connection)
  426. {
  427. // Create an original socket to be passed
  428. const ScopedSocket sock(createSocket(family, type, protocol, local, true));
  429. int fwd_fd = sock.fd; // default FD to be forwarded
  430. ScopedSocket client_sock; // for TCP test we need a separate "client"..
  431. ScopedSocket server_sock; // ..and a separate socket for the connection
  432. if (protocol == IPPROTO_TCP) {
  433. // Use unspecified port for the "client" to avoid bind(2) failure
  434. const SockAddrInfo client_addr = getSockAddr(family == AF_INET6 ?
  435. "::1" : "127.0.0.1", "0");
  436. client_sock.reset(createSocket(family, type, protocol, client_addr,
  437. false));
  438. setNonBlock(client_sock.fd, true);
  439. // This connect would "fail" due to EINPROGRESS. Ignore it for now.
  440. connect(client_sock.fd, local.first, local.second);
  441. sockaddr_storage ss;
  442. socklen_t salen = sizeof(ss);
  443. server_sock.reset(accept(sock.fd, convertSockAddr(&ss), &salen));
  444. if (server_sock.fd == -1) {
  445. isc_throw(isc::Unexpected, "internal accept failed: " <<
  446. strerror(errno));
  447. }
  448. fwd_fd = server_sock.fd;
  449. }
  450. // If a new connection is required, start the "server", have the
  451. // internal forwarder connect to it, and then internally accept it.
  452. if (new_connection) {
  453. startListen();
  454. forwarder_.connectToReceiver();
  455. accept_sock_.reset(acceptForwarder());
  456. }
  457. // Then push one socket session via the forwarder.
  458. forwarder_.push(fwd_fd, family, type, protocol, *local.first,
  459. *remote.first, data, data_len);
  460. // Pop the socket session we just pushed from a local receiver, and
  461. // check the content. Since we do blocking read on the receiver's socket,
  462. // we set up an alarm to prevent hangup in case there's a bug that really
  463. // makes the blocking happen.
  464. SocketSessionReceiver receiver(accept_sock_.fd);
  465. alarm(1); // set up 1-sec timer, an arbitrary choice.
  466. const SocketSession sock_session = receiver.pop();
  467. alarm(0); // then cancel it.
  468. const ScopedSocket passed_sock(sock_session.getSocket());
  469. EXPECT_LE(0, passed_sock.fd);
  470. // The passed FD should be different from the original FD
  471. EXPECT_NE(fwd_fd, passed_sock.fd);
  472. EXPECT_EQ(family, sock_session.getFamily());
  473. EXPECT_EQ(type, sock_session.getType());
  474. EXPECT_EQ(protocol, sock_session.getProtocol());
  475. checkSockAddrs(*local.first, sock_session.getLocalEndpoint());
  476. checkSockAddrs(*remote.first, sock_session.getRemoteEndpoint());
  477. ASSERT_EQ(data_len, sock_session.getDataLength());
  478. EXPECT_EQ(0, memcmp(data, sock_session.getData(), data_len));
  479. // Check if the passed FD is usable by sending some data from it.
  480. setNonBlock(passed_sock.fd, false);
  481. if (protocol == IPPROTO_UDP) {
  482. EXPECT_EQ(sizeof(TEST_DATA),
  483. sendto(passed_sock.fd, TEST_DATA, sizeof(TEST_DATA), 0,
  484. convertSockAddr(local.first), local.second));
  485. } else {
  486. server_sock.reset(-1);
  487. EXPECT_EQ(sizeof(TEST_DATA),
  488. send(passed_sock.fd, TEST_DATA, sizeof(TEST_DATA), 0));
  489. }
  490. // We don't use non blocking read below as it doesn't seem to be always
  491. // reliable. Instead we impose some reasonably large upper time limit of
  492. // blocking (normally it shouldn't even block at all; the limit is to
  493. // force the test to stop even if there's some bug and recv fails).
  494. char recvbuf[sizeof(TEST_DATA)];
  495. sockaddr_storage ss;
  496. socklen_t sa_len = sizeof(ss);
  497. if (protocol == IPPROTO_UDP) {
  498. EXPECT_EQ(sizeof(recvbuf),
  499. recvfrom(fwd_fd, recvbuf, sizeof(recvbuf),
  500. setRecvDelay(fwd_fd), convertSockAddr(&ss),
  501. &sa_len));
  502. } else {
  503. setNonBlock(client_sock.fd, false);
  504. EXPECT_EQ(sizeof(recvbuf),
  505. recv(client_sock.fd, recvbuf, sizeof(recvbuf),
  506. setRecvDelay(client_sock.fd)));
  507. }
  508. EXPECT_EQ(string(TEST_DATA), string(recvbuf));
  509. }
  510. TEST_F(ForwardTest, pushAndPop) {
  511. // Pass a UDP/IPv6 session. We use different ports for different UDP
  512. // tests because Solaris 11 seems to prohibit reusing the same port for
  513. // some short period once the socket FD is forwarded, even if the sockets
  514. // are closed. See Trac #2028.
  515. const SockAddrInfo sai_local6(getSockAddr("::1", TEST_PORT));
  516. const SockAddrInfo sai_local6_alt(getSockAddr("::1", TEST_PORT2));
  517. const SockAddrInfo sai_remote6(getSockAddr("2001:db8::1", "5300"));
  518. {
  519. SCOPED_TRACE("Passing UDP/IPv6 session");
  520. checkPushAndPop(AF_INET6, SOCK_DGRAM, IPPROTO_UDP, sai_local6,
  521. sai_remote6, TEST_DATA, sizeof(TEST_DATA), true);
  522. }
  523. // Pass a TCP/IPv6 session.
  524. {
  525. SCOPED_TRACE("Passing TCP/IPv6 session");
  526. checkPushAndPop(AF_INET6, SOCK_STREAM, IPPROTO_TCP, sai_local6,
  527. sai_remote6, TEST_DATA, sizeof(TEST_DATA), false);
  528. }
  529. // Pass a UDP/IPv4 session. This reuses the same pair of forwarder and
  530. // receiver, which should be usable for multiple attempts of passing,
  531. // regardless of family of the passed session
  532. const SockAddrInfo sai_local4(getSockAddr("127.0.0.1", TEST_PORT));
  533. const SockAddrInfo sai_local4_alt(getSockAddr("127.0.0.1", TEST_PORT2));
  534. const SockAddrInfo sai_remote4(getSockAddr("192.0.2.2", "5300"));
  535. {
  536. SCOPED_TRACE("Passing UDP/IPv4 session");
  537. checkPushAndPop(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai_local4,
  538. sai_remote4, TEST_DATA, sizeof(TEST_DATA), false);
  539. }
  540. // Pass a TCP/IPv4 session.
  541. {
  542. SCOPED_TRACE("Passing TCP/IPv4 session");
  543. checkPushAndPop(AF_INET, SOCK_STREAM, IPPROTO_TCP, sai_local4,
  544. sai_remote4, TEST_DATA, sizeof(TEST_DATA), false);
  545. }
  546. // Also try large data
  547. {
  548. SCOPED_TRACE("Passing UDP/IPv6 session with large data");
  549. checkPushAndPop(AF_INET6, SOCK_DGRAM, IPPROTO_UDP, sai_local6_alt,
  550. sai_remote6, large_text_.c_str(), large_text_.length(),
  551. false);
  552. }
  553. {
  554. SCOPED_TRACE("Passing TCP/IPv6 session with large data");
  555. checkPushAndPop(AF_INET6, SOCK_STREAM, IPPROTO_TCP, sai_local6,
  556. sai_remote6, large_text_.c_str(), large_text_.length(),
  557. false);
  558. }
  559. {
  560. SCOPED_TRACE("Passing UDP/IPv4 session with large data");
  561. checkPushAndPop(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai_local4_alt,
  562. sai_remote4, large_text_.c_str(), large_text_.length(),
  563. false);
  564. }
  565. {
  566. SCOPED_TRACE("Passing TCP/IPv4 session with large data");
  567. checkPushAndPop(AF_INET, SOCK_STREAM, IPPROTO_TCP, sai_local4,
  568. sai_remote4, large_text_.c_str(), large_text_.length(),
  569. false);
  570. }
  571. }
  572. TEST_F(ForwardTest, badPush) {
  573. // push before connect
  574. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  575. *getSockAddr("192.0.2.1", "53").first,
  576. *getSockAddr("192.0.2.2", "53").first,
  577. TEST_DATA, sizeof(TEST_DATA)),
  578. BadValue);
  579. // Now connect the forwarder for the rest of tests
  580. startListen();
  581. forwarder_.connectToReceiver();
  582. // Invalid address family
  583. struct sockaddr sockaddr_unspec;
  584. sockaddr_unspec.sa_family = AF_UNSPEC;
  585. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  586. sockaddr_unspec,
  587. *getSockAddr("192.0.2.2", "53").first,
  588. TEST_DATA, sizeof(TEST_DATA)),
  589. BadValue);
  590. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  591. *getSockAddr("192.0.2.2", "53").first,
  592. sockaddr_unspec, TEST_DATA,
  593. sizeof(TEST_DATA)),
  594. BadValue);
  595. // Inconsistent address family
  596. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  597. *getSockAddr("2001:db8::1", "53").first,
  598. *getSockAddr("192.0.2.2", "53").first,
  599. TEST_DATA, sizeof(TEST_DATA)),
  600. BadValue);
  601. EXPECT_THROW(forwarder_.push(1, AF_INET6, SOCK_DGRAM, IPPROTO_UDP,
  602. *getSockAddr("2001:db8::1", "53").first,
  603. *getSockAddr("192.0.2.2", "53").first,
  604. TEST_DATA, sizeof(TEST_DATA)),
  605. BadValue);
  606. // Empty data: we reject them at least for now
  607. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  608. *getSockAddr("192.0.2.1", "53").first,
  609. *getSockAddr("192.0.2.2", "53").first,
  610. TEST_DATA, 0),
  611. BadValue);
  612. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  613. *getSockAddr("192.0.2.1", "53").first,
  614. *getSockAddr("192.0.2.2", "53").first,
  615. NULL, sizeof(TEST_DATA)),
  616. BadValue);
  617. // Too big data: we reject them at least for now
  618. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  619. *getSockAddr("192.0.2.1", "53").first,
  620. *getSockAddr("192.0.2.2", "53").first,
  621. string(65536, 'd').c_str(), 65536),
  622. BadValue);
  623. // Close the receiver before push. It will result in SIGPIPE (should be
  624. // ignored) and EPIPE, which will be converted to SocketSessionError.
  625. const int receiver_fd = acceptForwarder();
  626. close(receiver_fd);
  627. EXPECT_THROW(forwarder_.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  628. *getSockAddr("192.0.2.1", "53").first,
  629. *getSockAddr("192.0.2.2", "53").first,
  630. TEST_DATA, sizeof(TEST_DATA)),
  631. SocketSessionError);
  632. }
  633. // A subroutine for pushTooFast, continuously pushing socket sessions
  634. // with full-size DNS messages (65535 bytes) without receiving them.
  635. // the push attempts will eventually fill the socket send buffer and trigger
  636. // an exception. Unfortunately exactly how many we can forward depends on
  637. // the internal system implementation; it should be close to 3, because
  638. // in our current implementation it sets the send buffer to a size that
  639. // is sufficiently large to hold 2 sessions (but not much larger than that),
  640. // but (for example) Linux internally doubles the specified upper limit.
  641. // Experimentally we know 10 is enough to produce a reliable result, but
  642. // if it turns out to be not the case, we should do it a bit harder, e.g.,
  643. // by probing the actual buffer size by getsockopt(SO_SNDBUF).
  644. void
  645. multiPush(SocketSessionForwarder& forwarder, const struct sockaddr& sa,
  646. const void* data, size_t data_len)
  647. {
  648. for (int i = 0; i < 10; ++i) {
  649. forwarder.push(1, AF_INET, SOCK_DGRAM, IPPROTO_UDP, sa, sa,
  650. data, data_len);
  651. }
  652. }
  653. TEST_F(ForwardTest, pushTooFast) {
  654. // Emulate the situation where the forwarder is pushing sessions too fast.
  655. // It should eventually fail without blocking.
  656. startListen();
  657. forwarder_.connectToReceiver();
  658. EXPECT_THROW(multiPush(forwarder_, *getSockAddr("192.0.2.1", "53").first,
  659. large_text_.c_str(), large_text_.length()),
  660. SocketSessionError);
  661. }
  662. TEST_F(ForwardTest, badPop) {
  663. startListen();
  664. // Close the forwarder socket before pop() without sending anything.
  665. pushSessionHeader(0, 0, false);
  666. dummy_forwarder_.reset(-1);
  667. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  668. // Pretending to be a forwarder but don't actually pass FD.
  669. pushSessionHeader(0, 1, false);
  670. dummy_forwarder_.reset(-1);
  671. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  672. // Pass a valid FD (stdin), but provide short data for the hdrlen
  673. pushSessionHeader(0, 1);
  674. dummy_forwarder_.reset(-1);
  675. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  676. // Pass a valid FD, but provides too large hdrlen
  677. pushSessionHeader(0xffff);
  678. dummy_forwarder_.reset(-1);
  679. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  680. // Don't provide full header
  681. pushSessionHeader(sizeof(uint32_t));
  682. dummy_forwarder_.reset(-1);
  683. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  684. // Pushed header is too short
  685. const uint8_t dummy_data = 0;
  686. pushSessionHeader(1);
  687. send(dummy_forwarder_.fd, &dummy_data, 1, 0);
  688. dummy_forwarder_.reset(-1);
  689. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  690. // socket addresses commonly used below (the values don't matter).
  691. const SockAddrInfo sai_local(getSockAddr("192.0.2.1", "53535"));
  692. const SockAddrInfo sai_remote(getSockAddr("192.0.2.2", "53536"));
  693. const SockAddrInfo sai6(getSockAddr("2001:db8::1", "53537"));
  694. // Pass invalid address family (AF_UNSPEC)
  695. pushSession(AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, sai_local.second,
  696. *sai_local.first, sai_remote.second, *sai_remote.first);
  697. dummy_forwarder_.reset(-1);
  698. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  699. // Pass inconsistent address family for local
  700. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai6.second,
  701. *sai6.first, sai_remote.second, *sai_remote.first);
  702. dummy_forwarder_.reset(-1);
  703. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  704. // Same for remote
  705. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai_local.second,
  706. *sai_local.first, sai6.second, *sai6.first);
  707. dummy_forwarder_.reset(-1);
  708. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  709. // Pass too big sa length for local
  710. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  711. sizeof(struct sockaddr_storage) + 1, *sai_local.first,
  712. sai_remote.second, *sai_remote.first);
  713. dummy_forwarder_.reset(-1);
  714. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  715. // Same for remote
  716. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai_local.second,
  717. *sai_local.first, sizeof(struct sockaddr_storage) + 1,
  718. *sai_remote.first);
  719. dummy_forwarder_.reset(-1);
  720. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  721. // Pass too small sa length for local
  722. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  723. sizeof(struct sockaddr_in) - 1, *sai_local.first,
  724. sai_remote.second, *sai_remote.first);
  725. dummy_forwarder_.reset(-1);
  726. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  727. // Same for remote
  728. pushSession(AF_INET6, SOCK_DGRAM, IPPROTO_UDP,
  729. sai6.second, *sai6.first, sizeof(struct sockaddr_in6) - 1,
  730. *sai6.first);
  731. dummy_forwarder_.reset(-1);
  732. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  733. // Data length is too large
  734. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai_local.second,
  735. *sai_local.first, sai_remote.second,
  736. *sai_remote.first, 65536);
  737. dummy_forwarder_.reset(-1);
  738. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  739. // Empty data
  740. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai_local.second,
  741. *sai_local.first, sai_remote.second,
  742. *sai_remote.first, 0);
  743. dummy_forwarder_.reset(-1);
  744. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  745. // Not full data are passed
  746. pushSession(AF_INET, SOCK_DGRAM, IPPROTO_UDP, sai_local.second,
  747. *sai_local.first, sai_remote.second,
  748. *sai_remote.first, sizeof(TEST_DATA) + 1);
  749. dummy_forwarder_.reset(-1);
  750. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  751. // Check the forwarded FD is closed on failure
  752. ScopedSocket sock(createSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  753. getSockAddr("127.0.0.1", TEST_PORT),
  754. false));
  755. pushSessionHeader(0, 1, true, sock.fd);
  756. dummy_forwarder_.reset(-1);
  757. EXPECT_THROW(receiver_->pop(), SocketSessionError);
  758. // Close the original socket
  759. sock.reset(-1);
  760. // The passed one should have been closed, too, so we should be able
  761. // to bind a new socket to the same port.
  762. sock.reset(createSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  763. getSockAddr("127.0.0.1", TEST_PORT),
  764. false));
  765. }
  766. TEST(SocketSessionTest, badValue) {
  767. // normal cases are confirmed in ForwardTest. We only check some
  768. // abnormal cases here.
  769. SockAddrCreator addr_creator;
  770. EXPECT_THROW(SocketSession(42, AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL,
  771. addr_creator.get("192.0.2.1", "53").first,
  772. TEST_DATA, sizeof(TEST_DATA)),
  773. BadValue);
  774. EXPECT_THROW(SocketSession(42, AF_INET6, SOCK_STREAM, IPPROTO_TCP,
  775. addr_creator.get("2001:db8::1", "53").first,
  776. NULL, TEST_DATA , sizeof(TEST_DATA)), BadValue);
  777. EXPECT_THROW(SocketSession(42, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  778. addr_creator.get("192.0.2.1", "53").first,
  779. addr_creator.get("192.0.2.2", "5300").first,
  780. TEST_DATA, 0), BadValue);
  781. EXPECT_THROW(SocketSession(42, AF_INET, SOCK_DGRAM, IPPROTO_UDP,
  782. addr_creator.get("192.0.2.1", "53").first,
  783. addr_creator.get("192.0.2.2", "5300").first,
  784. NULL, sizeof(TEST_DATA)), BadValue);
  785. }
  786. }