socketsession_unittest.cc 35 KB

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