socketsession_unittest.cc 35 KB

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