ip.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. /*
  2. Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
  3. This file is part of libzmq, the ZeroMQ core engine in C++.
  4. libzmq is free software; you can redistribute it and/or modify it under
  5. the terms of the GNU Lesser General Public License (LGPL) as published
  6. by the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. As a special exception, the Contributors give you permission to link
  9. this library with independent modules to produce an executable,
  10. regardless of the license terms of these independent modules, and to
  11. copy and distribute the resulting executable under terms of your choice,
  12. provided that you also meet, for each linked independent module, the
  13. terms and conditions of the license of that module. An independent
  14. module is a module which is not derived from or based on this library.
  15. If you modify this library, you must extend this exception to your
  16. version of the library.
  17. libzmq is distributed in the hope that it will be useful, but WITHOUT
  18. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  19. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  20. License for more details.
  21. You should have received a copy of the GNU Lesser General Public License
  22. along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. #include "precompiled.hpp"
  25. #include "ip.hpp"
  26. #include "err.hpp"
  27. #include "macros.hpp"
  28. #include "config.hpp"
  29. #include "address.hpp"
  30. #if !defined ZMQ_HAVE_WINDOWS
  31. #include <fcntl.h>
  32. #include <sys/types.h>
  33. #include <sys/socket.h>
  34. #include <sys/stat.h>
  35. #include <netdb.h>
  36. #include <netinet/in.h>
  37. #include <netinet/tcp.h>
  38. #include <stdlib.h>
  39. #include <unistd.h>
  40. #include <vector>
  41. #else
  42. #include "tcp.hpp"
  43. #ifdef ZMQ_HAVE_IPC
  44. #include "ipc_address.hpp"
  45. #endif
  46. #include <direct.h>
  47. #endif
  48. #if defined ZMQ_HAVE_OPENVMS || defined ZMQ_HAVE_VXWORKS
  49. #include <ioctl.h>
  50. #endif
  51. #if defined ZMQ_HAVE_VXWORKS
  52. #include <unistd.h>
  53. #include <sockLib.h>
  54. #include <ioLib.h>
  55. #endif
  56. #if defined ZMQ_HAVE_EVENTFD
  57. #include <sys/eventfd.h>
  58. #endif
  59. #if defined ZMQ_HAVE_OPENPGM
  60. #ifdef ZMQ_HAVE_WINDOWS
  61. #define __PGM_WININT_H__
  62. #endif
  63. #include <pgm/pgm.h>
  64. #endif
  65. #ifdef __APPLE__
  66. #include <TargetConditionals.h>
  67. #endif
  68. #ifndef ZMQ_HAVE_WINDOWS
  69. // Acceptable temporary directory environment variables
  70. static const char *tmp_env_vars[] = {
  71. "TMPDIR", "TEMPDIR", "TMP",
  72. 0 // Sentinel
  73. };
  74. #endif
  75. zmq::fd_t zmq::open_socket (int domain_, int type_, int protocol_)
  76. {
  77. int rc;
  78. // Setting this option result in sane behaviour when exec() functions
  79. // are used. Old sockets are closed and don't block TCP ports etc.
  80. #if defined ZMQ_HAVE_SOCK_CLOEXEC
  81. type_ |= SOCK_CLOEXEC;
  82. #endif
  83. #if defined ZMQ_HAVE_WINDOWS && defined WSA_FLAG_NO_HANDLE_INHERIT
  84. // if supported, create socket with WSA_FLAG_NO_HANDLE_INHERIT, such that
  85. // the race condition in making it non-inheritable later is avoided
  86. const fd_t s = WSASocket (domain_, type_, protocol_, NULL, 0,
  87. WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
  88. #else
  89. const fd_t s = socket (domain_, type_, protocol_);
  90. #endif
  91. if (s == retired_fd) {
  92. #ifdef ZMQ_HAVE_WINDOWS
  93. errno = wsa_error_to_errno (WSAGetLastError ());
  94. #endif
  95. return retired_fd;
  96. }
  97. make_socket_noninheritable (s);
  98. // Socket is not yet connected so EINVAL is not a valid networking error
  99. rc = zmq::set_nosigpipe (s);
  100. errno_assert (rc == 0);
  101. return s;
  102. }
  103. void zmq::unblock_socket (fd_t s_)
  104. {
  105. #if defined ZMQ_HAVE_WINDOWS
  106. u_long nonblock = 1;
  107. const int rc = ioctlsocket (s_, FIONBIO, &nonblock);
  108. wsa_assert (rc != SOCKET_ERROR);
  109. #elif defined ZMQ_HAVE_OPENVMS || defined ZMQ_HAVE_VXWORKS
  110. int nonblock = 1;
  111. int rc = ioctl (s_, FIONBIO, &nonblock);
  112. errno_assert (rc != -1);
  113. #else
  114. int flags = fcntl (s_, F_GETFL, 0);
  115. if (flags == -1)
  116. flags = 0;
  117. int rc = fcntl (s_, F_SETFL, flags | O_NONBLOCK);
  118. errno_assert (rc != -1);
  119. #endif
  120. }
  121. void zmq::enable_ipv4_mapping (fd_t s_)
  122. {
  123. LIBZMQ_UNUSED (s_);
  124. #if defined IPV6_V6ONLY && !defined ZMQ_HAVE_OPENBSD \
  125. && !defined ZMQ_HAVE_DRAGONFLY
  126. #ifdef ZMQ_HAVE_WINDOWS
  127. DWORD flag = 0;
  128. #else
  129. int flag = 0;
  130. #endif
  131. const int rc = setsockopt (s_, IPPROTO_IPV6, IPV6_V6ONLY,
  132. reinterpret_cast<char *> (&flag), sizeof (flag));
  133. #ifdef ZMQ_HAVE_WINDOWS
  134. wsa_assert (rc != SOCKET_ERROR);
  135. #else
  136. errno_assert (rc == 0);
  137. #endif
  138. #endif
  139. }
  140. int zmq::get_peer_ip_address (fd_t sockfd_, std::string &ip_addr_)
  141. {
  142. struct sockaddr_storage ss;
  143. const zmq_socklen_t addrlen =
  144. get_socket_address (sockfd_, socket_end_remote, &ss);
  145. if (addrlen == 0) {
  146. #ifdef ZMQ_HAVE_WINDOWS
  147. const int last_error = WSAGetLastError ();
  148. wsa_assert (last_error != WSANOTINITIALISED && last_error != WSAEFAULT
  149. && last_error != WSAEINPROGRESS
  150. && last_error != WSAENOTSOCK);
  151. #elif !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE
  152. errno_assert (errno != EBADF && errno != EFAULT && errno != ENOTSOCK);
  153. #else
  154. errno_assert (errno != EFAULT && errno != ENOTSOCK);
  155. #endif
  156. return 0;
  157. }
  158. char host[NI_MAXHOST];
  159. const int rc =
  160. getnameinfo (reinterpret_cast<struct sockaddr *> (&ss), addrlen, host,
  161. sizeof host, NULL, 0, NI_NUMERICHOST);
  162. if (rc != 0)
  163. return 0;
  164. ip_addr_ = host;
  165. union
  166. {
  167. struct sockaddr sa;
  168. struct sockaddr_storage sa_stor;
  169. } u;
  170. u.sa_stor = ss;
  171. return static_cast<int> (u.sa.sa_family);
  172. }
  173. void zmq::set_ip_type_of_service (fd_t s_, int iptos_)
  174. {
  175. int rc = setsockopt (s_, IPPROTO_IP, IP_TOS,
  176. reinterpret_cast<char *> (&iptos_), sizeof (iptos_));
  177. #ifdef ZMQ_HAVE_WINDOWS
  178. wsa_assert (rc != SOCKET_ERROR);
  179. #else
  180. errno_assert (rc == 0);
  181. #endif
  182. // Windows and Hurd do not support IPV6_TCLASS
  183. #if !defined(ZMQ_HAVE_WINDOWS) && defined(IPV6_TCLASS)
  184. rc = setsockopt (s_, IPPROTO_IPV6, IPV6_TCLASS,
  185. reinterpret_cast<char *> (&iptos_), sizeof (iptos_));
  186. // If IPv6 is not enabled ENOPROTOOPT will be returned on Linux and
  187. // EINVAL on OSX
  188. if (rc == -1) {
  189. errno_assert (errno == ENOPROTOOPT || errno == EINVAL);
  190. }
  191. #endif
  192. }
  193. int zmq::set_nosigpipe (fd_t s_)
  194. {
  195. #ifdef SO_NOSIGPIPE
  196. // Make sure that SIGPIPE signal is not generated when writing to a
  197. // connection that was already closed by the peer.
  198. // As per POSIX spec, EINVAL will be returned if the socket was valid but
  199. // the connection has been reset by the peer. Return an error so that the
  200. // socket can be closed and the connection retried if necessary.
  201. int set = 1;
  202. int rc = setsockopt (s_, SOL_SOCKET, SO_NOSIGPIPE, &set, sizeof (int));
  203. if (rc != 0 && errno == EINVAL)
  204. return -1;
  205. errno_assert (rc == 0);
  206. #else
  207. LIBZMQ_UNUSED (s_);
  208. #endif
  209. return 0;
  210. }
  211. int zmq::bind_to_device (fd_t s_, const std::string &bound_device_)
  212. {
  213. #ifdef ZMQ_HAVE_SO_BINDTODEVICE
  214. int rc = setsockopt (s_, SOL_SOCKET, SO_BINDTODEVICE,
  215. bound_device_.c_str (), bound_device_.length ());
  216. if (rc != 0) {
  217. assert_success_or_recoverable (s_, rc);
  218. return -1;
  219. }
  220. return 0;
  221. #else
  222. LIBZMQ_UNUSED (s_);
  223. LIBZMQ_UNUSED (bound_device_);
  224. errno = ENOTSUP;
  225. return -1;
  226. #endif
  227. }
  228. bool zmq::initialize_network ()
  229. {
  230. #if defined ZMQ_HAVE_OPENPGM
  231. // Init PGM transport. Ensure threading and timer are enabled. Find PGM
  232. // protocol ID. Note that if you want to use gettimeofday and sleep for
  233. // openPGM timing, set environment variables PGM_TIMER to "GTOD" and
  234. // PGM_SLEEP to "USLEEP".
  235. pgm_error_t *pgm_error = NULL;
  236. const bool ok = pgm_init (&pgm_error);
  237. if (ok != TRUE) {
  238. // Invalid parameters don't set pgm_error_t
  239. zmq_assert (pgm_error != NULL);
  240. if (pgm_error->domain == PGM_ERROR_DOMAIN_TIME
  241. && (pgm_error->code == PGM_ERROR_FAILED)) {
  242. // Failed to access RTC or HPET device.
  243. pgm_error_free (pgm_error);
  244. errno = EINVAL;
  245. return false;
  246. }
  247. // PGM_ERROR_DOMAIN_ENGINE: WSAStartup errors or missing WSARecvMsg.
  248. zmq_assert (false);
  249. }
  250. #endif
  251. #ifdef ZMQ_HAVE_WINDOWS
  252. // Intialise Windows sockets. Note that WSAStartup can be called multiple
  253. // times given that WSACleanup will be called for each WSAStartup.
  254. const WORD version_requested = MAKEWORD (2, 2);
  255. WSADATA wsa_data;
  256. const int rc = WSAStartup (version_requested, &wsa_data);
  257. zmq_assert (rc == 0);
  258. zmq_assert (LOBYTE (wsa_data.wVersion) == 2
  259. && HIBYTE (wsa_data.wVersion) == 2);
  260. #endif
  261. return true;
  262. }
  263. void zmq::shutdown_network ()
  264. {
  265. #ifdef ZMQ_HAVE_WINDOWS
  266. // On Windows, uninitialise socket layer.
  267. const int rc = WSACleanup ();
  268. wsa_assert (rc != SOCKET_ERROR);
  269. #endif
  270. #if defined ZMQ_HAVE_OPENPGM
  271. // Shut down the OpenPGM library.
  272. if (pgm_shutdown () != TRUE)
  273. zmq_assert (false);
  274. #endif
  275. }
  276. #if defined ZMQ_HAVE_WINDOWS
  277. static void tune_socket (const SOCKET socket_)
  278. {
  279. BOOL tcp_nodelay = 1;
  280. const int rc =
  281. setsockopt (socket_, IPPROTO_TCP, TCP_NODELAY,
  282. reinterpret_cast<char *> (&tcp_nodelay), sizeof tcp_nodelay);
  283. wsa_assert (rc != SOCKET_ERROR);
  284. zmq::tcp_tune_loopback_fast_path (socket_);
  285. }
  286. static int make_fdpair_tcpip (zmq::fd_t *r_, zmq::fd_t *w_)
  287. {
  288. #if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP
  289. // Windows CE does not manage security attributes
  290. SECURITY_DESCRIPTOR sd;
  291. SECURITY_ATTRIBUTES sa;
  292. memset (&sd, 0, sizeof sd);
  293. memset (&sa, 0, sizeof sa);
  294. InitializeSecurityDescriptor (&sd, SECURITY_DESCRIPTOR_REVISION);
  295. SetSecurityDescriptorDacl (&sd, TRUE, 0, FALSE);
  296. sa.nLength = sizeof (SECURITY_ATTRIBUTES);
  297. sa.lpSecurityDescriptor = &sd;
  298. #endif
  299. // This function has to be in a system-wide critical section so that
  300. // two instances of the library don't accidentally create signaler
  301. // crossing the process boundary.
  302. // We'll use named event object to implement the critical section.
  303. // Note that if the event object already exists, the CreateEvent requests
  304. // EVENT_ALL_ACCESS access right. If this fails, we try to open
  305. // the event object asking for SYNCHRONIZE access only.
  306. HANDLE sync = NULL;
  307. // Create critical section only if using fixed signaler port
  308. // Use problematic Event implementation for compatibility if using old port 5905.
  309. // Otherwise use Mutex implementation.
  310. const int event_signaler_port = 5905;
  311. if (zmq::signaler_port == event_signaler_port) {
  312. #if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP
  313. sync =
  314. CreateEventW (&sa, FALSE, TRUE, L"Global\\zmq-signaler-port-sync");
  315. #else
  316. sync =
  317. CreateEventW (NULL, FALSE, TRUE, L"Global\\zmq-signaler-port-sync");
  318. #endif
  319. if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED)
  320. sync = OpenEventW (SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE,
  321. L"Global\\zmq-signaler-port-sync");
  322. win_assert (sync != NULL);
  323. } else if (zmq::signaler_port != 0) {
  324. wchar_t mutex_name[MAX_PATH];
  325. #ifdef __MINGW32__
  326. _snwprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d",
  327. zmq::signaler_port);
  328. #else
  329. swprintf (mutex_name, MAX_PATH, L"Global\\zmq-signaler-port-%d",
  330. zmq::signaler_port);
  331. #endif
  332. #if !defined _WIN32_WCE && !defined ZMQ_HAVE_WINDOWS_UWP
  333. sync = CreateMutexW (&sa, FALSE, mutex_name);
  334. #else
  335. sync = CreateMutexW (NULL, FALSE, mutex_name);
  336. #endif
  337. if (sync == NULL && GetLastError () == ERROR_ACCESS_DENIED)
  338. sync = OpenMutexW (SYNCHRONIZE, FALSE, mutex_name);
  339. win_assert (sync != NULL);
  340. }
  341. // Windows has no 'socketpair' function. CreatePipe is no good as pipe
  342. // handles cannot be polled on. Here we create the socketpair by hand.
  343. *w_ = INVALID_SOCKET;
  344. *r_ = INVALID_SOCKET;
  345. // Create listening socket.
  346. SOCKET listener;
  347. listener = zmq::open_socket (AF_INET, SOCK_STREAM, 0);
  348. wsa_assert (listener != INVALID_SOCKET);
  349. // Set SO_REUSEADDR and TCP_NODELAY on listening socket.
  350. BOOL so_reuseaddr = 1;
  351. int rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
  352. reinterpret_cast<char *> (&so_reuseaddr),
  353. sizeof so_reuseaddr);
  354. wsa_assert (rc != SOCKET_ERROR);
  355. tune_socket (listener);
  356. // Init sockaddr to signaler port.
  357. struct sockaddr_in addr;
  358. memset (&addr, 0, sizeof addr);
  359. addr.sin_family = AF_INET;
  360. addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  361. addr.sin_port = htons (zmq::signaler_port);
  362. // Create the writer socket.
  363. *w_ = zmq::open_socket (AF_INET, SOCK_STREAM, 0);
  364. wsa_assert (*w_ != INVALID_SOCKET);
  365. if (sync != NULL) {
  366. // Enter the critical section.
  367. const DWORD dwrc = WaitForSingleObject (sync, INFINITE);
  368. zmq_assert (dwrc == WAIT_OBJECT_0 || dwrc == WAIT_ABANDONED);
  369. }
  370. // Bind listening socket to signaler port.
  371. rc = bind (listener, reinterpret_cast<const struct sockaddr *> (&addr),
  372. sizeof addr);
  373. if (rc != SOCKET_ERROR && zmq::signaler_port == 0) {
  374. // Retrieve ephemeral port number
  375. int addrlen = sizeof addr;
  376. rc = getsockname (listener, reinterpret_cast<struct sockaddr *> (&addr),
  377. &addrlen);
  378. }
  379. // Listen for incoming connections.
  380. if (rc != SOCKET_ERROR) {
  381. rc = listen (listener, 1);
  382. }
  383. // Connect writer to the listener.
  384. if (rc != SOCKET_ERROR) {
  385. rc = connect (*w_, reinterpret_cast<struct sockaddr *> (&addr),
  386. sizeof addr);
  387. }
  388. // Accept connection from writer.
  389. if (rc != SOCKET_ERROR) {
  390. // Set TCP_NODELAY on writer socket.
  391. tune_socket (*w_);
  392. *r_ = accept (listener, NULL, NULL);
  393. }
  394. // Send/receive large chunk to work around TCP slow start
  395. // This code is a workaround for #1608
  396. if (*r_ != INVALID_SOCKET) {
  397. const size_t dummy_size =
  398. 1024 * 1024; // 1M to overload default receive buffer
  399. unsigned char *dummy =
  400. static_cast<unsigned char *> (malloc (dummy_size));
  401. wsa_assert (dummy);
  402. int still_to_send = static_cast<int> (dummy_size);
  403. int still_to_recv = static_cast<int> (dummy_size);
  404. while (still_to_send || still_to_recv) {
  405. int nbytes;
  406. if (still_to_send > 0) {
  407. nbytes = ::send (
  408. *w_,
  409. reinterpret_cast<char *> (dummy + dummy_size - still_to_send),
  410. still_to_send, 0);
  411. wsa_assert (nbytes != SOCKET_ERROR);
  412. still_to_send -= nbytes;
  413. }
  414. nbytes = ::recv (
  415. *r_,
  416. reinterpret_cast<char *> (dummy + dummy_size - still_to_recv),
  417. still_to_recv, 0);
  418. wsa_assert (nbytes != SOCKET_ERROR);
  419. still_to_recv -= nbytes;
  420. }
  421. free (dummy);
  422. }
  423. // Save errno if error occurred in bind/listen/connect/accept.
  424. int saved_errno = 0;
  425. if (*r_ == INVALID_SOCKET)
  426. saved_errno = WSAGetLastError ();
  427. // We don't need the listening socket anymore. Close it.
  428. rc = closesocket (listener);
  429. wsa_assert (rc != SOCKET_ERROR);
  430. if (sync != NULL) {
  431. // Exit the critical section.
  432. BOOL brc;
  433. if (zmq::signaler_port == event_signaler_port)
  434. brc = SetEvent (sync);
  435. else
  436. brc = ReleaseMutex (sync);
  437. win_assert (brc != 0);
  438. // Release the kernel object
  439. brc = CloseHandle (sync);
  440. win_assert (brc != 0);
  441. }
  442. if (*r_ != INVALID_SOCKET) {
  443. zmq::make_socket_noninheritable (*r_);
  444. return 0;
  445. }
  446. // Cleanup writer if connection failed
  447. if (*w_ != INVALID_SOCKET) {
  448. rc = closesocket (*w_);
  449. wsa_assert (rc != SOCKET_ERROR);
  450. *w_ = INVALID_SOCKET;
  451. }
  452. // Set errno from saved value
  453. errno = zmq::wsa_error_to_errno (saved_errno);
  454. return -1;
  455. }
  456. #endif
  457. int zmq::make_fdpair (fd_t *r_, fd_t *w_)
  458. {
  459. #if defined ZMQ_HAVE_EVENTFD
  460. int flags = 0;
  461. #if defined ZMQ_HAVE_EVENTFD_CLOEXEC
  462. // Setting this option result in sane behaviour when exec() functions
  463. // are used. Old sockets are closed and don't block TCP ports, avoid
  464. // leaks, etc.
  465. flags |= EFD_CLOEXEC;
  466. #endif
  467. fd_t fd = eventfd (0, flags);
  468. if (fd == -1) {
  469. errno_assert (errno == ENFILE || errno == EMFILE);
  470. *w_ = *r_ = -1;
  471. return -1;
  472. }
  473. *w_ = *r_ = fd;
  474. return 0;
  475. #elif defined ZMQ_HAVE_WINDOWS
  476. #ifdef ZMQ_HAVE_IPC
  477. ipc_address_t address;
  478. std::string dirname, filename;
  479. // Create a listening socket.
  480. const SOCKET listener = open_socket (AF_UNIX, SOCK_STREAM, 0);
  481. if (listener == retired_fd) {
  482. // This may happen if the library was built on a system supporting AF_UNIX, but the system running doesn't support it.
  483. goto try_tcpip;
  484. }
  485. create_ipc_wildcard_address (dirname, filename);
  486. // Initialise the address structure.
  487. int rc = address.resolve (filename.c_str ());
  488. if (rc != 0) {
  489. goto error_closelistener;
  490. }
  491. // Bind the socket to the file path.
  492. rc = bind (listener, const_cast<sockaddr *> (address.addr ()),
  493. address.addrlen ());
  494. if (rc != 0) {
  495. errno = wsa_error_to_errno (WSAGetLastError ());
  496. goto error_closelistener;
  497. }
  498. // Listen for incoming connections.
  499. rc = listen (listener, 1);
  500. if (rc != 0) {
  501. errno = wsa_error_to_errno (WSAGetLastError ());
  502. goto error_closelistener;
  503. }
  504. sockaddr_un lcladdr;
  505. socklen_t lcladdr_len = sizeof lcladdr;
  506. rc = getsockname (listener, reinterpret_cast<struct sockaddr *> (&lcladdr),
  507. &lcladdr_len);
  508. wsa_assert (rc != -1);
  509. // Create the client socket.
  510. *w_ = open_socket (AF_UNIX, SOCK_STREAM, 0);
  511. if (*w_ == -1) {
  512. errno = wsa_error_to_errno (WSAGetLastError ());
  513. goto error_closelistener;
  514. }
  515. // Connect to the remote peer.
  516. rc = ::connect (*w_, reinterpret_cast<const struct sockaddr *> (&lcladdr),
  517. lcladdr_len);
  518. if (rc == -1) {
  519. goto error_closeclient;
  520. }
  521. *r_ = accept (listener, NULL, NULL);
  522. errno_assert (*r_ != -1);
  523. // Close the listener socket, we don't need it anymore.
  524. rc = closesocket (listener);
  525. wsa_assert (rc == 0);
  526. return 0;
  527. error_closeclient:
  528. int saved_errno = errno;
  529. rc = closesocket (*w_);
  530. wsa_assert (rc == 0);
  531. errno = saved_errno;
  532. error_closelistener:
  533. saved_errno = errno;
  534. rc = closesocket (listener);
  535. wsa_assert (rc == 0);
  536. errno = saved_errno;
  537. return -1;
  538. try_tcpip:
  539. // try to fallback to TCP/IP
  540. // TODO: maybe remember this decision permanently?
  541. #endif
  542. return make_fdpair_tcpip (r_, w_);
  543. #elif defined ZMQ_HAVE_OPENVMS
  544. // Whilst OpenVMS supports socketpair - it maps to AF_INET only. Further,
  545. // it does not set the socket options TCP_NODELAY and TCP_NODELACK which
  546. // can lead to performance problems.
  547. //
  548. // The bug will be fixed in V5.6 ECO4 and beyond. In the meantime, we'll
  549. // create the socket pair manually.
  550. struct sockaddr_in lcladdr;
  551. memset (&lcladdr, 0, sizeof lcladdr);
  552. lcladdr.sin_family = AF_INET;
  553. lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  554. lcladdr.sin_port = 0;
  555. int listener = open_socket (AF_INET, SOCK_STREAM, 0);
  556. errno_assert (listener != -1);
  557. int on = 1;
  558. int rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
  559. errno_assert (rc != -1);
  560. rc = setsockopt (listener, IPPROTO_TCP, TCP_NODELACK, &on, sizeof on);
  561. errno_assert (rc != -1);
  562. rc = bind (listener, (struct sockaddr *) &lcladdr, sizeof lcladdr);
  563. errno_assert (rc != -1);
  564. socklen_t lcladdr_len = sizeof lcladdr;
  565. rc = getsockname (listener, (struct sockaddr *) &lcladdr, &lcladdr_len);
  566. errno_assert (rc != -1);
  567. rc = listen (listener, 1);
  568. errno_assert (rc != -1);
  569. *w_ = open_socket (AF_INET, SOCK_STREAM, 0);
  570. errno_assert (*w_ != -1);
  571. rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on);
  572. errno_assert (rc != -1);
  573. rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELACK, &on, sizeof on);
  574. errno_assert (rc != -1);
  575. rc = connect (*w_, (struct sockaddr *) &lcladdr, sizeof lcladdr);
  576. errno_assert (rc != -1);
  577. *r_ = accept (listener, NULL, NULL);
  578. errno_assert (*r_ != -1);
  579. close (listener);
  580. return 0;
  581. #elif defined ZMQ_HAVE_VXWORKS
  582. struct sockaddr_in lcladdr;
  583. memset (&lcladdr, 0, sizeof lcladdr);
  584. lcladdr.sin_family = AF_INET;
  585. lcladdr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  586. lcladdr.sin_port = 0;
  587. int listener = open_socket (AF_INET, SOCK_STREAM, 0);
  588. errno_assert (listener != -1);
  589. int on = 1;
  590. int rc =
  591. setsockopt (listener, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof on);
  592. errno_assert (rc != -1);
  593. rc = bind (listener, (struct sockaddr *) &lcladdr, sizeof lcladdr);
  594. errno_assert (rc != -1);
  595. socklen_t lcladdr_len = sizeof lcladdr;
  596. rc = getsockname (listener, (struct sockaddr *) &lcladdr,
  597. (int *) &lcladdr_len);
  598. errno_assert (rc != -1);
  599. rc = listen (listener, 1);
  600. errno_assert (rc != -1);
  601. *w_ = open_socket (AF_INET, SOCK_STREAM, 0);
  602. errno_assert (*w_ != -1);
  603. rc = setsockopt (*w_, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof on);
  604. errno_assert (rc != -1);
  605. rc = connect (*w_, (struct sockaddr *) &lcladdr, sizeof lcladdr);
  606. errno_assert (rc != -1);
  607. *r_ = accept (listener, NULL, NULL);
  608. errno_assert (*r_ != -1);
  609. close (listener);
  610. return 0;
  611. #else
  612. // All other implementations support socketpair()
  613. int sv[2];
  614. int type = SOCK_STREAM;
  615. // Setting this option result in sane behaviour when exec() functions
  616. // are used. Old sockets are closed and don't block TCP ports, avoid
  617. // leaks, etc.
  618. #if defined ZMQ_HAVE_SOCK_CLOEXEC
  619. type |= SOCK_CLOEXEC;
  620. #endif
  621. int rc = socketpair (AF_UNIX, type, 0, sv);
  622. if (rc == -1) {
  623. errno_assert (errno == ENFILE || errno == EMFILE);
  624. *w_ = *r_ = -1;
  625. return -1;
  626. } else {
  627. make_socket_noninheritable (sv[0]);
  628. make_socket_noninheritable (sv[1]);
  629. *w_ = sv[0];
  630. *r_ = sv[1];
  631. return 0;
  632. }
  633. #endif
  634. }
  635. void zmq::make_socket_noninheritable (fd_t sock_)
  636. {
  637. #if defined ZMQ_HAVE_WINDOWS && !defined _WIN32_WCE \
  638. && !defined ZMQ_HAVE_WINDOWS_UWP
  639. // On Windows, preventing sockets to be inherited by child processes.
  640. const BOOL brc = SetHandleInformation (reinterpret_cast<HANDLE> (sock_),
  641. HANDLE_FLAG_INHERIT, 0);
  642. win_assert (brc);
  643. #elif (!defined ZMQ_HAVE_SOCK_CLOEXEC || !defined HAVE_ACCEPT4) \
  644. && defined FD_CLOEXEC
  645. // If there 's no SOCK_CLOEXEC, let's try the second best option.
  646. // Race condition can cause socket not to be closed (if fork happens
  647. // between accept and this point).
  648. const int rc = fcntl (sock_, F_SETFD, FD_CLOEXEC);
  649. errno_assert (rc != -1);
  650. #else
  651. LIBZMQ_UNUSED (sock_);
  652. #endif
  653. }
  654. void zmq::assert_success_or_recoverable (zmq::fd_t s_, int rc_)
  655. {
  656. #ifdef ZMQ_HAVE_WINDOWS
  657. if (rc_ != SOCKET_ERROR) {
  658. return;
  659. }
  660. #else
  661. if (rc_ != -1) {
  662. return;
  663. }
  664. #endif
  665. // Check whether an error occurred
  666. int err = 0;
  667. #if defined ZMQ_HAVE_HPUX || defined ZMQ_HAVE_VXWORKS
  668. int len = sizeof err;
  669. #else
  670. socklen_t len = sizeof err;
  671. #endif
  672. const int rc = getsockopt (s_, SOL_SOCKET, SO_ERROR,
  673. reinterpret_cast<char *> (&err), &len);
  674. // Assert if the error was caused by 0MQ bug.
  675. // Networking problems are OK. No need to assert.
  676. #ifdef ZMQ_HAVE_WINDOWS
  677. zmq_assert (rc == 0);
  678. if (err != 0) {
  679. wsa_assert (err == WSAECONNREFUSED || err == WSAECONNRESET
  680. || err == WSAECONNABORTED || err == WSAEINTR
  681. || err == WSAETIMEDOUT || err == WSAEHOSTUNREACH
  682. || err == WSAENETUNREACH || err == WSAENETDOWN
  683. || err == WSAENETRESET || err == WSAEACCES
  684. || err == WSAEINVAL || err == WSAEADDRINUSE);
  685. }
  686. #else
  687. // Following code should handle both Berkeley-derived socket
  688. // implementations and Solaris.
  689. if (rc == -1)
  690. err = errno;
  691. if (err != 0) {
  692. errno = err;
  693. errno_assert (errno == ECONNREFUSED || errno == ECONNRESET
  694. || errno == ECONNABORTED || errno == EINTR
  695. || errno == ETIMEDOUT || errno == EHOSTUNREACH
  696. || errno == ENETUNREACH || errno == ENETDOWN
  697. || errno == ENETRESET || errno == EINVAL);
  698. }
  699. #endif
  700. }
  701. #ifdef ZMQ_HAVE_IPC
  702. int zmq::create_ipc_wildcard_address (std::string &path_, std::string &file_)
  703. {
  704. #if defined ZMQ_HAVE_WINDOWS
  705. char buffer[MAX_PATH];
  706. {
  707. const errno_t rc = tmpnam_s (buffer);
  708. errno_assert (rc == 0);
  709. }
  710. // TODO or use CreateDirectoryA and specify permissions?
  711. const int rc = _mkdir (buffer);
  712. if (rc != 0) {
  713. return -1;
  714. }
  715. path_.assign (buffer);
  716. file_ = path_ + "/socket";
  717. #else
  718. std::string tmp_path;
  719. // If TMPDIR, TEMPDIR, or TMP are available and are directories, create
  720. // the socket directory there.
  721. const char **tmp_env = tmp_env_vars;
  722. while (tmp_path.empty () && *tmp_env != 0) {
  723. const char *const tmpdir = getenv (*tmp_env);
  724. struct stat statbuf;
  725. // Confirm it is actually a directory before trying to use
  726. if (tmpdir != 0 && ::stat (tmpdir, &statbuf) == 0
  727. && S_ISDIR (statbuf.st_mode)) {
  728. tmp_path.assign (tmpdir);
  729. if (*(tmp_path.rbegin ()) != '/') {
  730. tmp_path.push_back ('/');
  731. }
  732. }
  733. // Try the next environment variable
  734. ++tmp_env;
  735. }
  736. // Append a directory name
  737. tmp_path.append ("tmpXXXXXX");
  738. // We need room for tmp_path + trailing NUL
  739. std::vector<char> buffer (tmp_path.length () + 1);
  740. memcpy (&buffer[0], tmp_path.c_str (), tmp_path.length () + 1);
  741. #if defined HAVE_MKDTEMP
  742. // Create the directory. POSIX requires that mkdtemp() creates the
  743. // directory with 0700 permissions, meaning the only possible race
  744. // with socket creation could be the same user. However, since
  745. // each socket is created in a directory created by mkdtemp(), and
  746. // mkdtemp() guarantees a unique directory name, there will be no
  747. // collision.
  748. if (mkdtemp (&buffer[0]) == 0) {
  749. return -1;
  750. }
  751. path_.assign (&buffer[0]);
  752. file_ = path_ + "/socket";
  753. #else
  754. LIBZMQ_UNUSED (path_);
  755. int fd = mkstemp (&buffer[0]);
  756. if (fd == -1)
  757. return -1;
  758. ::close (fd);
  759. file_.assign (&buffer[0]);
  760. #endif
  761. #endif
  762. return 0;
  763. }
  764. #endif