PageRenderTime 71ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/src/openvpn/socket.c

https://github.com/Papafox/openvpn
C | 3368 lines | 2764 code | 359 blank | 245 comment | 509 complexity | 14e5c0419f15fac569f68b62947d6310 MD5 | raw file
Possible License(s): LGPL-2.0, GPL-2.0
  1. /*
  2. * OpenVPN -- An application to securely tunnel IP networks
  3. * over a single TCP/UDP port, with support for SSL/TLS-based
  4. * session authentication and key exchange,
  5. * packet encryption, packet authentication, and
  6. * packet compression.
  7. *
  8. * Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License version 2
  12. * as published by the Free Software Foundation.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program (see the file COPYING included with this
  21. * distribution); if not, write to the Free Software Foundation, Inc.,
  22. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  23. */
  24. #ifdef HAVE_CONFIG_H
  25. #include "config.h"
  26. #elif defined(_MSC_VER)
  27. #include "config-msvc.h"
  28. #endif
  29. #include "syshead.h"
  30. #include "socket.h"
  31. #include "fdmisc.h"
  32. #include "misc.h"
  33. #include "gremlin.h"
  34. #include "plugin.h"
  35. #include "ps.h"
  36. #include "manage.h"
  37. #include "misc.h"
  38. #include "manage.h"
  39. #include "memdbg.h"
  40. const int proto_overhead[] = { /* indexed by PROTO_x */
  41. 0,
  42. IPv4_UDP_HEADER_SIZE, /* IPv4 */
  43. IPv4_TCP_HEADER_SIZE,
  44. IPv4_TCP_HEADER_SIZE,
  45. IPv6_UDP_HEADER_SIZE, /* IPv6 */
  46. IPv6_TCP_HEADER_SIZE,
  47. IPv6_TCP_HEADER_SIZE,
  48. IPv6_TCP_HEADER_SIZE,
  49. };
  50. /*
  51. * Convert sockflags/getaddr_flags into getaddr_flags
  52. */
  53. static unsigned int
  54. sf2gaf(const unsigned int getaddr_flags,
  55. const unsigned int sockflags)
  56. {
  57. if (sockflags & SF_HOST_RANDOMIZE)
  58. return getaddr_flags | GETADDR_RANDOMIZE;
  59. else
  60. return getaddr_flags;
  61. }
  62. /*
  63. * Functions related to the translation of DNS names to IP addresses.
  64. */
  65. static const char*
  66. h_errno_msg(int h_errno_err)
  67. {
  68. switch (h_errno_err)
  69. {
  70. case HOST_NOT_FOUND:
  71. return "[HOST_NOT_FOUND] The specified host is unknown.";
  72. case NO_DATA:
  73. return "[NO_DATA] The requested name is valid but does not have an IP address.";
  74. case NO_RECOVERY:
  75. return "[NO_RECOVERY] A non-recoverable name server error occurred.";
  76. case TRY_AGAIN:
  77. return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
  78. }
  79. return "[unknown h_errno value]";
  80. }
  81. /*
  82. * Translate IP addr or hostname to in_addr_t.
  83. * If resolve error, try again for
  84. * resolve_retry_seconds seconds.
  85. */
  86. in_addr_t
  87. getaddr (unsigned int flags,
  88. const char *hostname,
  89. int resolve_retry_seconds,
  90. bool *succeeded,
  91. volatile int *signal_received)
  92. {
  93. struct addrinfo *ai;
  94. int status;
  95. status = openvpn_getaddrinfo(flags, hostname, resolve_retry_seconds,
  96. signal_received, AF_INET, &ai);
  97. if(status==0) {
  98. struct in_addr ia;
  99. if(succeeded)
  100. *succeeded=true;
  101. ia = ((struct sockaddr_in*)ai->ai_addr)->sin_addr;
  102. freeaddrinfo(ai);
  103. return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
  104. } else {
  105. if(succeeded)
  106. *succeeded =false;
  107. return 0;
  108. }
  109. }
  110. /*
  111. * Translate IPv4/IPv6 addr or hostname into struct addrinfo
  112. * If resolve error, try again for resolve_retry_seconds seconds.
  113. */
  114. int
  115. openvpn_getaddrinfo (unsigned int flags,
  116. const char *hostname,
  117. int resolve_retry_seconds,
  118. volatile int *signal_received,
  119. int ai_family,
  120. struct addrinfo **res)
  121. {
  122. struct addrinfo hints;
  123. int status;
  124. int sigrec = 0;
  125. int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
  126. struct gc_arena gc = gc_new ();
  127. ASSERT(res);
  128. #if defined(HAVE_RES_INIT)
  129. res_init ();
  130. #endif
  131. if (!hostname)
  132. hostname = "::";
  133. if (flags & GETADDR_RANDOMIZE)
  134. hostname = hostname_randomize(hostname, &gc);
  135. if (flags & GETADDR_MSG_VIRT_OUT)
  136. msglevel |= M_MSG_VIRT_OUT;
  137. if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
  138. && !signal_received)
  139. signal_received = &sigrec;
  140. /* try numeric ipv6 addr first */
  141. CLEAR(hints);
  142. hints.ai_family = ai_family;
  143. hints.ai_flags = AI_NUMERICHOST;
  144. hints.ai_socktype = SOCK_STREAM;
  145. status = getaddrinfo(hostname, NULL, &hints, res);
  146. if (status != 0) /* parse as numeric address failed? */
  147. {
  148. const int fail_wait_interval = 5; /* seconds */
  149. int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
  150. const char *fmt;
  151. int level = 0;
  152. fmt = "RESOLVE: Cannot resolve host address: %s: %s";
  153. if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
  154. && !resolve_retry_seconds)
  155. fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
  156. if (!(flags & GETADDR_RESOLVE) || status == EAI_FAIL)
  157. {
  158. msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
  159. goto done;
  160. }
  161. #ifdef ENABLE_MANAGEMENT
  162. if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
  163. {
  164. if (management)
  165. management_set_state (management,
  166. OPENVPN_STATE_RESOLVE,
  167. NULL,
  168. (in_addr_t)0,
  169. (in_addr_t)0);
  170. }
  171. #endif
  172. /*
  173. * Resolve hostname
  174. */
  175. while (true)
  176. {
  177. /* try hostname lookup */
  178. hints.ai_flags = 0;
  179. dmsg (D_SOCKET_DEBUG, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
  180. flags, hints.ai_family, hints.ai_socktype);
  181. status = getaddrinfo(hostname, NULL, &hints, res);
  182. if (signal_received)
  183. {
  184. get_signal (signal_received);
  185. if (*signal_received) /* were we interrupted by a signal? */
  186. {
  187. if (0 == status) {
  188. ASSERT(res);
  189. freeaddrinfo(*res);
  190. res = NULL;
  191. }
  192. if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
  193. {
  194. msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
  195. *signal_received = 0;
  196. }
  197. else
  198. goto done;
  199. }
  200. }
  201. /* success? */
  202. if (0 == status)
  203. break;
  204. /* resolve lookup failed, should we
  205. continue or fail? */
  206. level = msglevel;
  207. if (resolve_retries > 0)
  208. level = D_RESOLVE_ERRORS;
  209. msg (level,
  210. fmt,
  211. hostname,
  212. gai_strerror(status));
  213. if (--resolve_retries <= 0)
  214. goto done;
  215. openvpn_sleep (fail_wait_interval);
  216. }
  217. ASSERT(res);
  218. /* hostname resolve succeeded */
  219. /* Do not chose an IP Addresse by random or change the order *
  220. * of IP addresses, doing so will break RFC 3484 address selection *
  221. */
  222. }
  223. else
  224. {
  225. /* IP address parse succeeded */
  226. }
  227. done:
  228. if (signal_received && *signal_received)
  229. {
  230. int level = 0;
  231. if (flags & GETADDR_FATAL_ON_SIGNAL)
  232. level = M_FATAL;
  233. else if (flags & GETADDR_WARN_ON_SIGNAL)
  234. level = M_WARN;
  235. msg (level, "RESOLVE: signal received during DNS resolution attempt");
  236. }
  237. gc_free (&gc);
  238. return status;
  239. }
  240. /*
  241. * We do our own inet_aton because the glibc function
  242. * isn't very good about error checking.
  243. */
  244. int
  245. openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
  246. {
  247. unsigned int a, b, c, d;
  248. CLEAR (*addr);
  249. if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
  250. {
  251. if (a < 256 && b < 256 && c < 256 && d < 256)
  252. {
  253. addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
  254. return OIA_IP; /* good dotted quad */
  255. }
  256. }
  257. if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
  258. return OIA_ERROR; /* probably a badly formatted dotted quad */
  259. else
  260. return OIA_HOSTNAME; /* probably a hostname */
  261. }
  262. bool
  263. ip_addr_dotted_quad_safe (const char *dotted_quad)
  264. {
  265. /* verify non-NULL */
  266. if (!dotted_quad)
  267. return false;
  268. /* verify length is within limits */
  269. if (strlen (dotted_quad) > 15)
  270. return false;
  271. /* verify that all chars are either numeric or '.' and that no numeric
  272. substring is greater than 3 chars */
  273. {
  274. int nnum = 0;
  275. const char *p = dotted_quad;
  276. int c;
  277. while ((c = *p++))
  278. {
  279. if (c >= '0' && c <= '9')
  280. {
  281. ++nnum;
  282. if (nnum > 3)
  283. return false;
  284. }
  285. else if (c == '.')
  286. {
  287. nnum = 0;
  288. }
  289. else
  290. return false;
  291. }
  292. }
  293. /* verify that string will convert to IP address */
  294. {
  295. struct in_addr a;
  296. return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
  297. }
  298. }
  299. bool
  300. ipv6_addr_safe (const char *ipv6_text_addr)
  301. {
  302. /* verify non-NULL */
  303. if (!ipv6_text_addr)
  304. return false;
  305. /* verify length is within limits */
  306. if (strlen (ipv6_text_addr) > INET6_ADDRSTRLEN )
  307. return false;
  308. /* verify that string will convert to IPv6 address */
  309. {
  310. struct in6_addr a6;
  311. return inet_pton( AF_INET6, ipv6_text_addr, &a6 ) == 1;
  312. }
  313. }
  314. static bool
  315. dns_addr_safe (const char *addr)
  316. {
  317. if (addr)
  318. {
  319. const size_t len = strlen (addr);
  320. return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
  321. }
  322. else
  323. return false;
  324. }
  325. bool
  326. ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
  327. {
  328. if (ip_addr_dotted_quad_safe (addr))
  329. return true;
  330. else if (allow_fqdn)
  331. return dns_addr_safe (addr);
  332. else
  333. return false;
  334. }
  335. bool
  336. mac_addr_safe (const char *mac_addr)
  337. {
  338. /* verify non-NULL */
  339. if (!mac_addr)
  340. return false;
  341. /* verify length is within limits */
  342. if (strlen (mac_addr) > 17)
  343. return false;
  344. /* verify that all chars are either alphanumeric or ':' and that no
  345. alphanumeric substring is greater than 2 chars */
  346. {
  347. int nnum = 0;
  348. const char *p = mac_addr;
  349. int c;
  350. while ((c = *p++))
  351. {
  352. if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
  353. {
  354. ++nnum;
  355. if (nnum > 2)
  356. return false;
  357. }
  358. else if (c == ':')
  359. {
  360. nnum = 0;
  361. }
  362. else
  363. return false;
  364. }
  365. }
  366. /* error-checking is left to script invoked in lladdr.c */
  367. return true;
  368. }
  369. static void
  370. update_remote (const char* host,
  371. struct openvpn_sockaddr *addr,
  372. bool *changed,
  373. const unsigned int sockflags)
  374. {
  375. switch(addr->addr.sa.sa_family)
  376. {
  377. case AF_INET:
  378. if (host && addr)
  379. {
  380. const in_addr_t new_addr = getaddr (
  381. sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
  382. host,
  383. 1,
  384. NULL,
  385. NULL);
  386. if (new_addr && addr->addr.in4.sin_addr.s_addr != new_addr)
  387. {
  388. addr->addr.in4.sin_addr.s_addr = new_addr;
  389. *changed = true;
  390. }
  391. }
  392. break;
  393. case AF_INET6:
  394. if (host && addr)
  395. {
  396. int status;
  397. struct addrinfo* ai;
  398. status = openvpn_getaddrinfo(sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags), host, 1, NULL, AF_INET6, &ai);
  399. if ( status ==0 )
  400. {
  401. struct sockaddr_in6 sin6;
  402. CLEAR(sin6);
  403. sin6 = *((struct sockaddr_in6*)ai->ai_addr);
  404. if (!IN6_ARE_ADDR_EQUAL(&sin6.sin6_addr, &addr->addr.in6.sin6_addr))
  405. {
  406. int port = addr->addr.in6.sin6_port;
  407. /* ipv6 requires also eg. sin6_scope_id => easier to fully copy and override port */
  408. addr->addr.in6 = sin6;
  409. addr->addr.in6.sin6_port = port;
  410. }
  411. freeaddrinfo(ai);
  412. }
  413. }
  414. break;
  415. default:
  416. ASSERT(0);
  417. }
  418. }
  419. static int
  420. socket_get_sndbuf (int sd)
  421. {
  422. #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
  423. int val;
  424. socklen_t len;
  425. len = sizeof (val);
  426. if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
  427. && len == sizeof (val))
  428. return val;
  429. #endif
  430. return 0;
  431. }
  432. static void
  433. socket_set_sndbuf (int sd, int size)
  434. {
  435. #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
  436. if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
  437. {
  438. if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
  439. {
  440. msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
  441. }
  442. }
  443. #endif
  444. }
  445. static int
  446. socket_get_rcvbuf (int sd)
  447. {
  448. #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
  449. int val;
  450. socklen_t len;
  451. len = sizeof (val);
  452. if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
  453. && len == sizeof (val))
  454. return val;
  455. #endif
  456. return 0;
  457. }
  458. static bool
  459. socket_set_rcvbuf (int sd, int size)
  460. {
  461. #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
  462. if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
  463. {
  464. if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
  465. {
  466. msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
  467. return false;
  468. }
  469. }
  470. return true;
  471. #endif
  472. }
  473. static void
  474. socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
  475. {
  476. if (sbs)
  477. {
  478. const int sndbuf_old = socket_get_sndbuf (fd);
  479. const int rcvbuf_old = socket_get_rcvbuf (fd);
  480. if (sbs->sndbuf)
  481. socket_set_sndbuf (fd, sbs->sndbuf);
  482. if (sbs->rcvbuf)
  483. socket_set_rcvbuf (fd, sbs->rcvbuf);
  484. msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
  485. rcvbuf_old,
  486. socket_get_rcvbuf (fd),
  487. sndbuf_old,
  488. socket_get_sndbuf (fd));
  489. }
  490. }
  491. /*
  492. * Set other socket options
  493. */
  494. static bool
  495. socket_set_tcp_nodelay (int sd, int state)
  496. {
  497. #if defined(WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
  498. if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
  499. {
  500. msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
  501. return false;
  502. }
  503. else
  504. {
  505. dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
  506. return true;
  507. }
  508. #else
  509. msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
  510. return false;
  511. #endif
  512. }
  513. static inline void
  514. socket_set_mark (int sd, int mark)
  515. {
  516. #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
  517. if (mark && setsockopt (sd, SOL_SOCKET, SO_MARK, &mark, sizeof (mark)) != 0)
  518. msg (M_WARN, "NOTE: setsockopt SO_MARK=%d failed", mark);
  519. #endif
  520. }
  521. static bool
  522. socket_set_flags (int sd, unsigned int sockflags)
  523. {
  524. if (sockflags & SF_TCP_NODELAY)
  525. return socket_set_tcp_nodelay (sd, 1);
  526. else
  527. return true;
  528. }
  529. bool
  530. link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
  531. {
  532. if (ls && socket_defined (ls->sd))
  533. return socket_set_flags (ls->sd, ls->sockflags = sockflags);
  534. else
  535. return false;
  536. }
  537. void
  538. link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
  539. {
  540. if (ls && socket_defined (ls->sd))
  541. {
  542. ls->socket_buffer_sizes.sndbuf = sndbuf;
  543. ls->socket_buffer_sizes.rcvbuf = rcvbuf;
  544. socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
  545. }
  546. }
  547. /*
  548. * SOCKET INITALIZATION CODE.
  549. * Create a TCP/UDP socket
  550. */
  551. socket_descriptor_t
  552. create_socket_tcp (int af)
  553. {
  554. socket_descriptor_t sd;
  555. if ((sd = socket (af, SOCK_STREAM, IPPROTO_TCP)) < 0)
  556. msg (M_ERR, "Cannot create TCP socket");
  557. #ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
  558. /* set SO_REUSEADDR on socket */
  559. {
  560. int on = 1;
  561. if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
  562. (void *) &on, sizeof (on)) < 0)
  563. msg (M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
  564. }
  565. #endif
  566. return sd;
  567. }
  568. static socket_descriptor_t
  569. create_socket_udp (const unsigned int flags)
  570. {
  571. socket_descriptor_t sd;
  572. if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
  573. msg (M_ERR, "UDP: Cannot create UDP socket");
  574. #if ENABLE_IP_PKTINFO
  575. else if (flags & SF_USE_IP_PKTINFO)
  576. {
  577. int pad = 1;
  578. #ifdef IP_PKTINFO
  579. if (setsockopt (sd, SOL_IP, IP_PKTINFO,
  580. (void*)&pad, sizeof(pad)) < 0)
  581. msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
  582. #elif defined(IP_RECVDSTADDR)
  583. if (setsockopt (sd, IPPROTO_IP, IP_RECVDSTADDR,
  584. (void*)&pad, sizeof(pad)) < 0)
  585. msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR");
  586. #else
  587. #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
  588. #endif
  589. }
  590. #endif
  591. return sd;
  592. }
  593. static socket_descriptor_t
  594. create_socket_udp6 (const unsigned int flags)
  595. {
  596. socket_descriptor_t sd;
  597. if ((sd = socket (PF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
  598. msg (M_ERR, "UDP: Cannot create UDP6 socket");
  599. #if ENABLE_IP_PKTINFO
  600. else if (flags & SF_USE_IP_PKTINFO)
  601. {
  602. int pad = 1;
  603. #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
  604. if (setsockopt (sd, IPPROTO_IPV6, IPV6_PKTINFO,
  605. (void*)&pad, sizeof(pad)) < 0)
  606. #else
  607. if (setsockopt (sd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
  608. (void*)&pad, sizeof(pad)) < 0)
  609. #endif
  610. msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");
  611. }
  612. #endif
  613. return sd;
  614. }
  615. static void
  616. create_socket (struct link_socket *sock)
  617. {
  618. /* create socket */
  619. if (sock->info.proto == PROTO_UDPv4)
  620. {
  621. sock->sd = create_socket_udp (sock->sockflags);
  622. sock->sockflags |= SF_GETADDRINFO_DGRAM;
  623. #ifdef ENABLE_SOCKS
  624. if (sock->socks_proxy)
  625. sock->ctrl_sd = create_socket_tcp (AF_INET);
  626. #endif
  627. }
  628. else if (sock->info.proto == PROTO_TCPv4_SERVER
  629. || sock->info.proto == PROTO_TCPv4_CLIENT)
  630. {
  631. sock->sd = create_socket_tcp (AF_INET);
  632. }
  633. else if (sock->info.proto == PROTO_TCPv6_SERVER
  634. || sock->info.proto == PROTO_TCPv6_CLIENT)
  635. {
  636. sock->sd = create_socket_tcp (AF_INET6);
  637. }
  638. else if (sock->info.proto == PROTO_UDPv6)
  639. {
  640. sock->sd = create_socket_udp6 (sock->sockflags);
  641. sock->sockflags |= SF_GETADDRINFO_DGRAM;
  642. }
  643. else
  644. {
  645. ASSERT (0);
  646. }
  647. #ifdef TARGET_ANDROID
  648. /* pass socket FD to management interface to pass on to VPNService API
  649. * as "protected socket" (exempt from being routed into tunnel)
  650. */
  651. management->connection.fdtosend = sock->sd;
  652. management_android_control (management, "PROTECTFD", __func__);
  653. #endif
  654. }
  655. /*
  656. * Functions used for establishing a TCP stream connection.
  657. */
  658. static void
  659. socket_do_listen (socket_descriptor_t sd,
  660. const struct openvpn_sockaddr *local,
  661. bool do_listen,
  662. bool do_set_nonblock)
  663. {
  664. struct gc_arena gc = gc_new ();
  665. if (do_listen)
  666. {
  667. msg (M_INFO, "Listening for incoming TCP connection on %s",
  668. print_sockaddr (local, &gc));
  669. if (listen (sd, 1))
  670. msg (M_ERR, "TCP: listen() failed");
  671. }
  672. /* set socket to non-blocking mode */
  673. if (do_set_nonblock)
  674. set_nonblock (sd);
  675. gc_free (&gc);
  676. }
  677. socket_descriptor_t
  678. socket_do_accept (socket_descriptor_t sd,
  679. struct link_socket_actual *act,
  680. const bool nowait)
  681. {
  682. /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
  683. * are compiled because act is empty here.
  684. * could use getsockname() to support later remote_len check
  685. */
  686. socklen_t remote_len_af = af_addr_size(act->dest.addr.sa.sa_family);
  687. socklen_t remote_len = sizeof(act->dest.addr);
  688. socket_descriptor_t new_sd = SOCKET_UNDEFINED;
  689. CLEAR (*act);
  690. #ifdef HAVE_GETPEERNAME
  691. if (nowait)
  692. {
  693. new_sd = getpeername (sd, &act->dest.addr.sa, &remote_len);
  694. if (!socket_defined (new_sd))
  695. msg (D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
  696. else
  697. new_sd = sd;
  698. }
  699. #else
  700. if (nowait)
  701. msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
  702. #endif
  703. else
  704. {
  705. new_sd = accept (sd, &act->dest.addr.sa, &remote_len);
  706. }
  707. #if 0 /* For debugging only, test the effect of accept() failures */
  708. {
  709. static int foo = 0;
  710. ++foo;
  711. if (foo & 1)
  712. new_sd = -1;
  713. }
  714. #endif
  715. if (!socket_defined (new_sd))
  716. {
  717. msg (D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", sd);
  718. }
  719. /* only valid if we have remote_len_af!=0 */
  720. else if (remote_len_af && remote_len != remote_len_af)
  721. {
  722. msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
  723. openvpn_close_socket (new_sd);
  724. new_sd = SOCKET_UNDEFINED;
  725. }
  726. return new_sd;
  727. }
  728. static void
  729. tcp_connection_established (const struct link_socket_actual *act)
  730. {
  731. struct gc_arena gc = gc_new ();
  732. msg (M_INFO, "TCP connection established with %s",
  733. print_link_socket_actual (act, &gc));
  734. gc_free (&gc);
  735. }
  736. static int
  737. socket_listen_accept (socket_descriptor_t sd,
  738. struct link_socket_actual *act,
  739. const char *remote_dynamic,
  740. bool *remote_changed,
  741. const struct openvpn_sockaddr *local,
  742. bool do_listen,
  743. bool nowait,
  744. volatile int *signal_received)
  745. {
  746. struct gc_arena gc = gc_new ();
  747. /* struct openvpn_sockaddr *remote = &act->dest; */
  748. struct openvpn_sockaddr remote_verify = act->dest;
  749. int new_sd = SOCKET_UNDEFINED;
  750. CLEAR (*act);
  751. socket_do_listen (sd, local, do_listen, true);
  752. while (true)
  753. {
  754. int status;
  755. fd_set reads;
  756. struct timeval tv;
  757. FD_ZERO (&reads);
  758. FD_SET (sd, &reads);
  759. tv.tv_sec = 0;
  760. tv.tv_usec = 0;
  761. status = select (sd + 1, &reads, NULL, NULL, &tv);
  762. get_signal (signal_received);
  763. if (*signal_received)
  764. {
  765. gc_free (&gc);
  766. return sd;
  767. }
  768. if (status < 0)
  769. msg (D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
  770. if (status <= 0)
  771. {
  772. openvpn_sleep (1);
  773. continue;
  774. }
  775. new_sd = socket_do_accept (sd, act, nowait);
  776. if (socket_defined (new_sd))
  777. {
  778. update_remote (remote_dynamic, &remote_verify, remote_changed, 0);
  779. if (addr_defined (&remote_verify)
  780. && !addr_match (&remote_verify, &act->dest))
  781. {
  782. msg (M_WARN,
  783. "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
  784. print_link_socket_actual (act, &gc));
  785. if (openvpn_close_socket (new_sd))
  786. msg (M_ERR, "TCP: close socket failed (new_sd)");
  787. }
  788. else
  789. break;
  790. }
  791. openvpn_sleep (1);
  792. }
  793. if (!nowait && openvpn_close_socket (sd))
  794. msg (M_ERR, "TCP: close socket failed (sd)");
  795. tcp_connection_established (act);
  796. gc_free (&gc);
  797. return new_sd;
  798. }
  799. void
  800. socket_bind (socket_descriptor_t sd,
  801. struct openvpn_sockaddr *local,
  802. const char *prefix)
  803. {
  804. struct gc_arena gc = gc_new ();
  805. if (bind (sd, &local->addr.sa, af_addr_size(local->addr.sa.sa_family)))
  806. {
  807. const int errnum = openvpn_errno ();
  808. msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
  809. prefix,
  810. print_sockaddr (local, &gc),
  811. strerror_ts (errnum, &gc));
  812. }
  813. gc_free (&gc);
  814. }
  815. int
  816. openvpn_connect (socket_descriptor_t sd,
  817. struct openvpn_sockaddr *remote,
  818. int connect_timeout,
  819. volatile int *signal_received)
  820. {
  821. int status = 0;
  822. #ifdef CONNECT_NONBLOCK
  823. set_nonblock (sd);
  824. status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
  825. if (status)
  826. status = openvpn_errno ();
  827. if (
  828. #ifdef WIN32
  829. status == WSAEWOULDBLOCK
  830. #else
  831. status == EINPROGRESS
  832. #endif
  833. )
  834. {
  835. while (true)
  836. {
  837. fd_set writes;
  838. struct timeval tv;
  839. FD_ZERO (&writes);
  840. FD_SET (sd, &writes);
  841. tv.tv_sec = 0;
  842. tv.tv_usec = 0;
  843. status = select (sd + 1, NULL, &writes, NULL, &tv);
  844. if (signal_received)
  845. {
  846. get_signal (signal_received);
  847. if (*signal_received)
  848. {
  849. status = 0;
  850. break;
  851. }
  852. }
  853. if (status < 0)
  854. {
  855. status = openvpn_errno ();
  856. break;
  857. }
  858. if (status <= 0)
  859. {
  860. if (--connect_timeout < 0)
  861. {
  862. status = ETIMEDOUT;
  863. break;
  864. }
  865. openvpn_sleep (1);
  866. continue;
  867. }
  868. /* got it */
  869. {
  870. int val = 0;
  871. socklen_t len;
  872. len = sizeof (val);
  873. if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
  874. && len == sizeof (val))
  875. status = val;
  876. else
  877. status = openvpn_errno ();
  878. break;
  879. }
  880. }
  881. }
  882. #else
  883. status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
  884. if (status)
  885. status = openvpn_errno ();
  886. #endif
  887. return status;
  888. }
  889. void
  890. socket_connect (socket_descriptor_t *sd,
  891. struct openvpn_sockaddr *local,
  892. bool bind_local,
  893. struct openvpn_sockaddr *remote,
  894. const bool connection_profiles_defined,
  895. const char *remote_dynamic,
  896. bool *remote_changed,
  897. const int connect_retry_seconds,
  898. const int connect_timeout,
  899. const int connect_retry_max,
  900. const unsigned int sockflags,
  901. volatile int *signal_received)
  902. {
  903. struct gc_arena gc = gc_new ();
  904. int retry = 0;
  905. #ifdef CONNECT_NONBLOCK
  906. msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
  907. print_sockaddr (remote, &gc));
  908. #else
  909. msg (M_INFO, "Attempting to establish TCP connection with %s",
  910. print_sockaddr (remote, &gc));
  911. #endif
  912. while (true)
  913. {
  914. int status;
  915. #ifdef ENABLE_MANAGEMENT
  916. if (management)
  917. management_set_state (management,
  918. OPENVPN_STATE_TCP_CONNECT,
  919. NULL,
  920. (in_addr_t)0,
  921. (in_addr_t)0);
  922. #endif
  923. status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
  924. get_signal (signal_received);
  925. if (*signal_received)
  926. goto done;
  927. if (!status)
  928. break;
  929. msg (D_LINK_ERRORS,
  930. "TCP: connect to %s failed, will try again in %d seconds: %s",
  931. print_sockaddr (remote, &gc),
  932. connect_retry_seconds,
  933. strerror_ts (status, &gc));
  934. gc_reset (&gc);
  935. openvpn_close_socket (*sd);
  936. *sd = SOCKET_UNDEFINED;
  937. if ((connect_retry_max > 0 && ++retry >= connect_retry_max) || connection_profiles_defined)
  938. {
  939. *signal_received = SIGUSR1;
  940. goto done;
  941. }
  942. openvpn_sleep (connect_retry_seconds);
  943. get_signal (signal_received);
  944. if (*signal_received)
  945. goto done;
  946. *sd = create_socket_tcp (local->addr.sa.sa_family);
  947. if (bind_local)
  948. socket_bind (*sd, local, "TCP Client");
  949. update_remote (remote_dynamic, remote, remote_changed, sockflags);
  950. }
  951. msg (M_INFO, "TCP connection established with %s",
  952. print_sockaddr (remote, &gc));
  953. done:
  954. gc_free (&gc);
  955. }
  956. /* For stream protocols, allocate a buffer to build up packet.
  957. Called after frame has been finalized. */
  958. static void
  959. socket_frame_init (const struct frame *frame, struct link_socket *sock)
  960. {
  961. #ifdef WIN32
  962. overlapped_io_init (&sock->reads, frame, FALSE, false);
  963. overlapped_io_init (&sock->writes, frame, TRUE, false);
  964. sock->rw_handle.read = sock->reads.overlapped.hEvent;
  965. sock->rw_handle.write = sock->writes.overlapped.hEvent;
  966. #endif
  967. if (link_socket_connection_oriented (sock))
  968. {
  969. #ifdef WIN32
  970. stream_buf_init (&sock->stream_buf,
  971. &sock->reads.buf_init,
  972. sock->sockflags,
  973. sock->info.proto);
  974. #else
  975. alloc_buf_sock_tun (&sock->stream_buf_data,
  976. frame,
  977. false,
  978. FRAME_HEADROOM_MARKER_READ_STREAM);
  979. stream_buf_init (&sock->stream_buf,
  980. &sock->stream_buf_data,
  981. sock->sockflags,
  982. sock->info.proto);
  983. #endif
  984. }
  985. }
  986. /*
  987. * Adjust frame structure based on a Path MTU value given
  988. * to us by the OS.
  989. */
  990. void
  991. frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
  992. {
  993. frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
  994. }
  995. static void
  996. resolve_bind_local (struct link_socket *sock)
  997. {
  998. struct gc_arena gc = gc_new ();
  999. /* resolve local address if undefined */
  1000. if (!addr_defined (&sock->info.lsa->local))
  1001. {
  1002. /* may return AF_{INET|INET6} guessed from local_host */
  1003. switch(addr_guess_family(sock->info.proto, sock->local_host))
  1004. {
  1005. case AF_INET:
  1006. sock->info.lsa->local.addr.in4.sin_family = AF_INET;
  1007. sock->info.lsa->local.addr.in4.sin_addr.s_addr =
  1008. (sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
  1009. sock->local_host,
  1010. 0,
  1011. NULL,
  1012. NULL)
  1013. : htonl (INADDR_ANY));
  1014. sock->info.lsa->local.addr.in4.sin_port = htons (sock->local_port);
  1015. break;
  1016. case AF_INET6:
  1017. {
  1018. int status;
  1019. int err;
  1020. CLEAR(sock->info.lsa->local.addr.in6);
  1021. if (sock->local_host)
  1022. {
  1023. struct addrinfo *ai;
  1024. status = openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
  1025. sock->local_host, 0, NULL, AF_INET6, &ai);
  1026. if(status ==0) {
  1027. sock->info.lsa->local.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
  1028. freeaddrinfo(ai);
  1029. }
  1030. }
  1031. else
  1032. {
  1033. sock->info.lsa->local.addr.in6.sin6_family = AF_INET6;
  1034. sock->info.lsa->local.addr.in6.sin6_addr = in6addr_any;
  1035. status = 0;
  1036. }
  1037. if (!status == 0)
  1038. {
  1039. msg (M_FATAL, "getaddr6() failed for local \"%s\": %s",
  1040. sock->local_host,
  1041. gai_strerror(err));
  1042. }
  1043. sock->info.lsa->local.addr.in6.sin6_port = htons (sock->local_port);
  1044. }
  1045. break;
  1046. }
  1047. }
  1048. /* bind to local address/port */
  1049. if (sock->bind_local)
  1050. {
  1051. #ifdef ENABLE_SOCKS
  1052. if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
  1053. socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
  1054. else
  1055. #endif
  1056. socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
  1057. }
  1058. gc_free (&gc);
  1059. }
  1060. static void
  1061. resolve_remote (struct link_socket *sock,
  1062. int phase,
  1063. const char **remote_dynamic,
  1064. volatile int *signal_received)
  1065. {
  1066. struct gc_arena gc = gc_new ();
  1067. int af;
  1068. if (!sock->did_resolve_remote)
  1069. {
  1070. /* resolve remote address if undefined */
  1071. if (!addr_defined (&sock->info.lsa->remote))
  1072. {
  1073. af = addr_guess_family(sock->info.proto, sock->remote_host);
  1074. switch(af)
  1075. {
  1076. case AF_INET:
  1077. sock->info.lsa->remote.addr.in4.sin_family = AF_INET;
  1078. sock->info.lsa->remote.addr.in4.sin_addr.s_addr = 0;
  1079. break;
  1080. case AF_INET6:
  1081. CLEAR(sock->info.lsa->remote.addr.in6);
  1082. sock->info.lsa->remote.addr.in6.sin6_family = AF_INET6;
  1083. sock->info.lsa->remote.addr.in6.sin6_addr = in6addr_any;
  1084. break;
  1085. }
  1086. if (sock->remote_host)
  1087. {
  1088. unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
  1089. int retry = 0;
  1090. int status = -1;
  1091. if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
  1092. {
  1093. if (phase == 2)
  1094. flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
  1095. retry = 0;
  1096. }
  1097. else if (phase == 1)
  1098. {
  1099. if (sock->resolve_retry_seconds)
  1100. {
  1101. retry = 0;
  1102. }
  1103. else
  1104. {
  1105. flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
  1106. retry = 0;
  1107. }
  1108. }
  1109. else if (phase == 2)
  1110. {
  1111. if (sock->resolve_retry_seconds)
  1112. {
  1113. flags |= GETADDR_FATAL;
  1114. retry = sock->resolve_retry_seconds;
  1115. }
  1116. else
  1117. {
  1118. ASSERT (0);
  1119. }
  1120. }
  1121. else
  1122. {
  1123. ASSERT (0);
  1124. }
  1125. struct addrinfo* ai;
  1126. /* Temporary fix, this need to be changed for dual stack */
  1127. status = openvpn_getaddrinfo(flags, sock->remote_host, retry,
  1128. signal_received, af, &ai);
  1129. if(status == 0) {
  1130. sock->info.lsa->remote.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
  1131. freeaddrinfo(ai);
  1132. dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
  1133. flags,
  1134. phase,
  1135. retry,
  1136. signal_received ? *signal_received : -1,
  1137. status);
  1138. }
  1139. if (signal_received)
  1140. {
  1141. if (*signal_received)
  1142. goto done;
  1143. }
  1144. if (status!=0)
  1145. {
  1146. if (signal_received)
  1147. *signal_received = SIGUSR1;
  1148. goto done;
  1149. }
  1150. }
  1151. switch(af)
  1152. {
  1153. case AF_INET:
  1154. sock->info.lsa->remote.addr.in4.sin_port = htons (sock->remote_port);
  1155. break;
  1156. case AF_INET6:
  1157. sock->info.lsa->remote.addr.in6.sin6_port = htons (sock->remote_port);
  1158. break;
  1159. }
  1160. }
  1161. /* should we re-use previous active remote address? */
  1162. if (link_socket_actual_defined (&sock->info.lsa->actual))
  1163. {
  1164. msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
  1165. print_link_socket_actual (&sock->info.lsa->actual, &gc));
  1166. if (remote_dynamic)
  1167. *remote_dynamic = NULL;
  1168. }
  1169. else
  1170. {
  1171. CLEAR (sock->info.lsa->actual);
  1172. sock->info.lsa->actual.dest = sock->info.lsa->remote;
  1173. }
  1174. /* remember that we finished */
  1175. sock->did_resolve_remote = true;
  1176. }
  1177. done:
  1178. gc_free (&gc);
  1179. }
  1180. struct link_socket *
  1181. link_socket_new (void)
  1182. {
  1183. struct link_socket *sock;
  1184. ALLOC_OBJ_CLEAR (sock, struct link_socket);
  1185. sock->sd = SOCKET_UNDEFINED;
  1186. #ifdef ENABLE_SOCKS
  1187. sock->ctrl_sd = SOCKET_UNDEFINED;
  1188. #endif
  1189. return sock;
  1190. }
  1191. /* bind socket if necessary */
  1192. void
  1193. link_socket_init_phase1 (struct link_socket *sock,
  1194. const bool connection_profiles_defined,
  1195. const char *local_host,
  1196. int local_port,
  1197. const char *remote_host,
  1198. int remote_port,
  1199. int proto,
  1200. int mode,
  1201. const struct link_socket *accept_from,
  1202. #ifdef ENABLE_HTTP_PROXY
  1203. struct http_proxy_info *http_proxy,
  1204. #endif
  1205. #ifdef ENABLE_SOCKS
  1206. struct socks_proxy_info *socks_proxy,
  1207. #endif
  1208. #ifdef ENABLE_DEBUG
  1209. int gremlin,
  1210. #endif
  1211. bool bind_local,
  1212. bool remote_float,
  1213. int inetd,
  1214. struct link_socket_addr *lsa,
  1215. const char *ipchange_command,
  1216. const struct plugin_list *plugins,
  1217. int resolve_retry_seconds,
  1218. int connect_retry_seconds,
  1219. int connect_timeout,
  1220. int connect_retry_max,
  1221. int mtu_discover_type,
  1222. int rcvbuf,
  1223. int sndbuf,
  1224. int mark,
  1225. unsigned int sockflags)
  1226. {
  1227. ASSERT (sock);
  1228. sock->connection_profiles_defined = connection_profiles_defined;
  1229. sock->local_host = local_host;
  1230. sock->local_port = local_port;
  1231. sock->remote_host = remote_host;
  1232. sock->remote_port = remote_port;
  1233. #ifdef ENABLE_HTTP_PROXY
  1234. sock->http_proxy = http_proxy;
  1235. #endif
  1236. #ifdef ENABLE_SOCKS
  1237. sock->socks_proxy = socks_proxy;
  1238. #endif
  1239. sock->bind_local = bind_local;
  1240. sock->inetd = inetd;
  1241. sock->resolve_retry_seconds = resolve_retry_seconds;
  1242. sock->connect_retry_seconds = connect_retry_seconds;
  1243. sock->connect_timeout = connect_timeout;
  1244. sock->connect_retry_max = connect_retry_max;
  1245. sock->mtu_discover_type = mtu_discover_type;
  1246. #ifdef ENABLE_DEBUG
  1247. sock->gremlin = gremlin;
  1248. #endif
  1249. sock->socket_buffer_sizes.rcvbuf = rcvbuf;
  1250. sock->socket_buffer_sizes.sndbuf = sndbuf;
  1251. sock->sockflags = sockflags;
  1252. sock->info.proto = proto;
  1253. sock->info.remote_float = remote_float;
  1254. sock->info.lsa = lsa;
  1255. sock->info.ipchange_command = ipchange_command;
  1256. sock->info.plugins = plugins;
  1257. sock->mode = mode;
  1258. if (mode == LS_MODE_TCP_ACCEPT_FROM)
  1259. {
  1260. ASSERT (accept_from);
  1261. ASSERT (sock->info.proto == PROTO_TCPv4_SERVER
  1262. || sock->info.proto == PROTO_TCPv6_SERVER
  1263. );
  1264. ASSERT (!sock->inetd);
  1265. sock->sd = accept_from->sd;
  1266. }
  1267. if (false)
  1268. ;
  1269. #ifdef ENABLE_HTTP_PROXY
  1270. /* are we running in HTTP proxy mode? */
  1271. else if (sock->http_proxy)
  1272. {
  1273. ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
  1274. ASSERT (!sock->inetd);
  1275. /* the proxy server */
  1276. sock->remote_host = http_proxy->options.server;
  1277. sock->remote_port = http_proxy->options.port;
  1278. /* the OpenVPN server we will use the proxy to connect to */
  1279. sock->proxy_dest_host = remote_host;
  1280. sock->proxy_dest_port = remote_port;
  1281. }
  1282. #endif
  1283. #ifdef ENABLE_SOCKS
  1284. /* or in Socks proxy mode? */
  1285. else if (sock->socks_proxy)
  1286. {
  1287. ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
  1288. ASSERT (!sock->inetd);
  1289. /* the proxy server */
  1290. sock->remote_host = socks_proxy->server;
  1291. sock->remote_port = socks_proxy->port;
  1292. /* the OpenVPN server we will use the proxy to connect to */
  1293. sock->proxy_dest_host = remote_host;
  1294. sock->proxy_dest_port = remote_port;
  1295. }
  1296. #endif
  1297. else
  1298. {
  1299. sock->remote_host = remote_host;
  1300. sock->remote_port = remote_port;
  1301. }
  1302. /* bind behavior for TCP server vs. client */
  1303. if (sock->info.proto == PROTO_TCPv4_SERVER)
  1304. {
  1305. if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
  1306. sock->bind_local = false;
  1307. else
  1308. sock->bind_local = true;
  1309. }
  1310. /* were we started by inetd or xinetd? */
  1311. if (sock->inetd)
  1312. {
  1313. ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT
  1314. && sock->info.proto != PROTO_TCPv6_CLIENT);
  1315. ASSERT (socket_defined (inetd_socket_descriptor));
  1316. sock->sd = inetd_socket_descriptor;
  1317. }
  1318. else if (mode != LS_MODE_TCP_ACCEPT_FROM)
  1319. {
  1320. create_socket (sock);
  1321. /* set socket buffers based on --sndbuf and --rcvbuf options */
  1322. socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
  1323. /* set socket to --mark packets with given value */
  1324. socket_set_mark (sock->sd, mark);
  1325. resolve_bind_local (sock);
  1326. resolve_remote (sock, 1, NULL, NULL);
  1327. }
  1328. }
  1329. /* finalize socket initialization */
  1330. void
  1331. link_socket_init_phase2 (struct link_socket *sock,
  1332. const struct frame *frame,
  1333. volatile int *signal_received)
  1334. {
  1335. struct gc_arena gc = gc_new ();
  1336. const char *remote_dynamic = NULL;
  1337. bool remote_changed = false;
  1338. int sig_save = 0;
  1339. ASSERT (sock);
  1340. if (signal_received && *signal_received)
  1341. {
  1342. sig_save = *signal_received;
  1343. *signal_received = 0;
  1344. }
  1345. /* initialize buffers */
  1346. socket_frame_init (frame, sock);
  1347. /*
  1348. * Pass a remote name to connect/accept so that
  1349. * they can test for dynamic IP address changes
  1350. * and throw a SIGUSR1 if appropriate.
  1351. */
  1352. if (sock->resolve_retry_seconds)
  1353. remote_dynamic = sock->remote_host;
  1354. /* were we started by inetd or xinetd? */
  1355. if (sock->inetd)
  1356. {
  1357. if (sock->info.proto == PROTO_TCPv4_SERVER
  1358. || sock->info.proto == PROTO_TCPv6_SERVER) {
  1359. /* AF_INET as default (and fallback) for inetd */
  1360. sock->info.lsa->actual.dest.addr.sa.sa_family = AF_INET;
  1361. #ifdef HAVE_GETSOCKNAME
  1362. {
  1363. /* inetd: hint family type for dest = local's */
  1364. struct openvpn_sockaddr local_addr;
  1365. socklen_t addrlen = sizeof(local_addr);
  1366. if (getsockname (sock->sd, (struct sockaddr *)&local_addr, &addrlen) == 0) {
  1367. sock->info.lsa->actual.dest.addr.sa.sa_family = local_addr.addr.sa.sa_family;
  1368. dmsg (D_SOCKET_DEBUG, "inetd(%s): using sa_family=%d from getsockname(%d)",
  1369. proto2ascii(sock->info.proto, false), local_addr.addr.sa.sa_family,
  1370. sock->sd);
  1371. } else
  1372. msg (M_WARN, "inetd(%s): getsockname(%d) failed, using AF_INET",
  1373. proto2ascii(sock->info.proto, false), sock->sd);
  1374. }
  1375. #else
  1376. msg (M_WARN, "inetd(%s): this OS does not provide the getsockname() "
  1377. "function, using AF_INET",
  1378. proto2ascii(sock->info.proto, false));
  1379. #endif
  1380. sock->sd =
  1381. socket_listen_accept (sock->sd,
  1382. &sock->info.lsa->actual,
  1383. remote_dynamic,
  1384. &remote_changed,
  1385. &sock->info.lsa->local,
  1386. false,
  1387. sock->inetd == INETD_NOWAIT,
  1388. signal_received);
  1389. }
  1390. ASSERT (!remote_changed);
  1391. if (*signal_received)
  1392. goto done;
  1393. }
  1394. else
  1395. {
  1396. resolve_remote (sock, 2, &remote_dynamic, signal_received);
  1397. if (*signal_received)
  1398. goto done;
  1399. /* TCP client/server */
  1400. if (sock->info.proto == PROTO_TCPv4_SERVER
  1401. ||sock->info.proto == PROTO_TCPv6_SERVER)
  1402. {
  1403. switch (sock->mode)
  1404. {
  1405. case LS_MODE_DEFAULT:
  1406. sock->sd = socket_listen_accept (sock->sd,
  1407. &sock->info.lsa->actual,
  1408. remote_dynamic,
  1409. &remote_changed,
  1410. &sock->info.lsa->local,
  1411. true,
  1412. false,
  1413. signal_received);
  1414. break;
  1415. case LS_MODE_TCP_LISTEN:
  1416. socket_do_listen (sock->sd,
  1417. &sock->info.lsa->local,
  1418. true,
  1419. false);
  1420. break;
  1421. case LS_MODE_TCP_ACCEPT_FROM:
  1422. sock->sd = socket_do_accept (sock->sd,
  1423. &sock->info.lsa->actual,
  1424. false);
  1425. if (!socket_defined (sock->sd))
  1426. {
  1427. *signal_received = SIGTERM;
  1428. goto done;
  1429. }
  1430. tcp_connection_established (&sock->info.lsa->actual);
  1431. break;
  1432. default:
  1433. ASSERT (0);
  1434. }
  1435. }
  1436. else if (sock->info.proto == PROTO_TCPv4_CLIENT
  1437. ||sock->info.proto == PROTO_TCPv6_CLIENT)
  1438. {
  1439. #ifdef GENERAL_PROXY_SUPPORT
  1440. bool proxy_retry = false;
  1441. #else
  1442. const bool proxy_retry = false;
  1443. #endif
  1444. do {
  1445. socket_connect (&sock->sd,
  1446. &sock->info.lsa->local,
  1447. sock->bind_local,
  1448. &sock->info.lsa->actual.dest,
  1449. sock->connection_profiles_defined,
  1450. remote_dynamic,
  1451. &remote_changed,
  1452. sock->connect_retry_seconds,
  1453. sock->connect_timeout,
  1454. sock->connect_retry_max,
  1455. sock->sockflags,
  1456. signal_received);
  1457. if (*signal_received)
  1458. goto done;
  1459. if (false)
  1460. ;
  1461. #ifdef ENABLE_HTTP_PROXY
  1462. else if (sock->http_proxy)
  1463. {
  1464. proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
  1465. sock->sd,
  1466. sock->proxy_dest_host,
  1467. sock->proxy_dest_port,
  1468. &sock->stream_buf.residual,
  1469. signal_received);
  1470. }
  1471. #endif
  1472. #ifdef ENABLE_SOCKS
  1473. else if (sock->socks_proxy)
  1474. {
  1475. establish_socks_proxy_passthru (sock->socks_proxy,
  1476. sock->sd,
  1477. sock->proxy_dest_host,
  1478. sock->proxy_dest_port,
  1479. signal_received);
  1480. }
  1481. #endif
  1482. if (proxy_retry)
  1483. {
  1484. openvpn_close_socket (sock->sd);
  1485. sock->sd = create_socket_tcp (AF_INET);
  1486. }
  1487. } while (proxy_retry);
  1488. }
  1489. #ifdef ENABLE_SOCKS
  1490. else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
  1491. {
  1492. socket_connect (&sock->ctrl_sd,
  1493. &sock->info.lsa->local,
  1494. sock->bind_local,
  1495. &sock->info.lsa->actual.dest,
  1496. sock->connection_profiles_defined,
  1497. remote_dynamic,
  1498. &remote_changed,
  1499. sock->connect_retry_seconds,
  1500. sock->connect_timeout,
  1501. sock->connect_retry_max,
  1502. sock->sockflags,
  1503. signal_received);
  1504. if (*signal_received)
  1505. goto done;
  1506. establish_socks_proxy_udpassoc (sock->socks_proxy,
  1507. sock->ctrl_sd,
  1508. sock->sd,
  1509. &sock->socks_relay.dest,
  1510. signal_received);
  1511. if (*signal_received)
  1512. goto done;
  1513. sock->remote_host = sock->proxy_dest_host;
  1514. sock->remote_port = sock->proxy_dest_port;
  1515. sock->did_resolve_remote = false;
  1516. addr_zero_host(&sock->info.lsa->actual.dest);
  1517. addr_zero_host(&sock->info.lsa->remote);
  1518. resolve_remote (sock, 1, NULL, signal_received);
  1519. if (*signal_received)
  1520. goto done;
  1521. }
  1522. #endif
  1523. if (*signal_received)
  1524. goto done;
  1525. if (remote_changed)
  1526. {
  1527. msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
  1528. addr_copy_host(&sock->info.lsa->remote, &sock->info.lsa->actual.dest);
  1529. }
  1530. }
  1531. /* set misc socket parameters */
  1532. socket_set_flags (sock->sd, sock->sockflags);
  1533. /* set socket to non-blocking mode */
  1534. set_nonblock (sock->sd);
  1535. /* set socket file descriptor to not pass across execs, so that
  1536. scripts don't have access to it */
  1537. set_cloexec (sock->sd);
  1538. #ifdef ENABLE_SOCKS
  1539. if (socket_defined (sock->ctrl_sd))
  1540. set_cloexec (sock->ctrl_sd);
  1541. #endif
  1542. /* set Path MTU discovery options on the socket */
  1543. set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
  1544. #if EXTENDED_SOCKET_ERROR_CAPABILITY
  1545. /* if the OS supports it, enable extended error passing on the socket */
  1546. set_sock_extended_error_passing (sock->sd);
  1547. #endif
  1548. /* print local address */
  1549. {
  1550. const int msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
  1551. if (sock->inetd)
  1552. msg (msglevel, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
  1553. else
  1554. msg (msglevel, "%s link local%s: %s",
  1555. proto2ascii (sock->info.proto, true),
  1556. (sock->bind_local ? " (bound)" : ""),
  1557. print_sockaddr_ex (&sock->info.lsa->local, ":", sock->bind_local ? PS_SHOW_PORT : 0, &gc));
  1558. /* print active remote address */
  1559. msg (msglevel, "%s link remote: %s",
  1560. proto2ascii (sock->info.proto, true),
  1561. print_link_socket_actual_ex (&sock->info.lsa->actual,
  1562. ":",
  1563. PS_SHOW_PORT_IF_DEFINED,
  1564. &gc));
  1565. }
  1566. done:
  1567. if (sig_save && signal_received)
  1568. {
  1569. if (!*signal_received)
  1570. *signal_received = sig_save;
  1571. }
  1572. gc_free (&gc);
  1573. }
  1574. void
  1575. link_socket_close (struct link_socket *sock)
  1576. {
  1577. if (sock)
  1578. {
  1579. #ifdef ENABLE_DEBUG
  1580. const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
  1581. #else
  1582. const int gremlin = 0;
  1583. #endif
  1584. if (socket_defined (sock->sd))
  1585. {
  1586. #ifdef WIN32
  1587. close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
  1588. #endif
  1589. if (!gremlin)
  1590. {
  1591. msg (D_LOW, "TCP/UDP: Closing socket");
  1592. if (openvpn_close_socket (sock->sd))
  1593. msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
  1594. }
  1595. sock->sd = SOCKET_UNDEFINED;
  1596. #ifdef WIN32
  1597. if (!gremlin)
  1598. {
  1599. overlapped_io_close (&sock->reads);
  1600. overlapped_io_close (&sock->writes);
  1601. }
  1602. #endif
  1603. }
  1604. #ifdef ENABLE_SOCKS
  1605. if (socket_defined (sock->ctrl_sd))
  1606. {
  1607. if (openvpn_close_socket (sock->ctrl_sd))
  1608. msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
  1609. sock->ctrl_sd = SOCKET_UNDEFINED;
  1610. }
  1611. #endif
  1612. stream_buf_close (&sock->stream_buf);
  1613. free_buf (&sock->stream_buf_data);
  1614. if (!gremlin)
  1615. free (sock);
  1616. }
  1617. }
  1618. /* for stream protocols, allow for packet length prefix */
  1619. void
  1620. socket_adjust_frame_parameters (struct frame *frame, int proto)
  1621. {
  1622. if (link_socket_proto_connection_oriented (proto))
  1623. frame_add_to_extra_frame (frame, sizeof (packet_size_type));
  1624. }
  1625. void
  1626. setenv_trusted (struct env_set *es, const struct link_socket_info *info)
  1627. {
  1628. setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
  1629. }
  1630. static void
  1631. ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
  1632. {
  1633. const char *ip = print_sockaddr_ex (&info->lsa->actual.dest, NULL, 0, gc);
  1634. const char *port = print_sockaddr_ex (&info->lsa->actual.dest, NULL, PS_DONT_SHOW_ADDR|PS_SHOW_PORT, gc);
  1635. if (include_cmd)
  1636. argv_printf (argv, "%sc %s %s",
  1637. info->ipchange_command,
  1638. ip,
  1639. port);
  1640. else
  1641. argv_printf (argv, "%s %s",
  1642. ip,
  1643. port);
  1644. }
  1645. void
  1646. link_socket_connection_initiated (const struct buffer *buf,
  1647. struct link_socket_info *info,
  1648. const struct link_socket_actual *act,
  1649. const char *common_name,
  1650. struct env_set *es)
  1651. {
  1652. struct gc_arena gc = gc_new ();
  1653. info->lsa->actual = *act; /* Note: skip this line for --force-dest */
  1654. setenv_trusted (es, info);
  1655. info->connection_established = true;
  1656. /* Print connection initiated message, with common name if available */
  1657. {
  1658. struct buffer out = alloc_buf_gc (256, &gc);
  1659. if (common_name)
  1660. buf_printf (&out, "[%s] ", common_name);
  1661. buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
  1662. msg (M_INFO, "%s", BSTR (&out));
  1663. }
  1664. /* set environmental vars */
  1665. setenv_str (es, "common_name", common_name);
  1666. /* Process --ipchange plugin */
  1667. if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
  1668. {
  1669. struct argv argv = argv_new ();
  1670. ipchange_fmt (false, &argv, info, &gc);
  1671. if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
  1672. msg (M_WARN, "WARNING: ipchange plugin call failed");
  1673. argv_reset (&argv);
  1674. }
  1675. /* Process --ipchange option */
  1676. if (info->ipchange_command)
  1677. {
  1678. struct argv argv = argv_new ();
  1679. setenv_str (es, "script_type", "ipchange");
  1680. ipchange_fmt (true, &argv, info, &gc);
  1681. openvpn_run_script (&argv, es, 0, "--ipchange");
  1682. argv_reset (&argv);
  1683. }
  1684. gc_free (&gc);
  1685. }
  1686. void
  1687. link_socket_bad_incoming_addr (struct buffer *buf,
  1688. const struct link_socket_info *info,
  1689. const struct link_socket_actual *from_addr)
  1690. {
  1691. struct gc_arena gc = gc_new ();
  1692. switch(from_addr->dest.addr.sa.sa_family)
  1693. {
  1694. case AF_INET:
  1695. case AF_INET6:
  1696. msg (D_LINK_ERRORS,
  1697. "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
  1698. print_link_socket_actual (from_addr, &gc),
  1699. (int)from_addr->dest.addr.sa.sa_family,
  1700. print_sockaddr (&info->lsa->remote, &gc));
  1701. break;
  1702. }
  1703. buf->len = 0;
  1704. gc_free (&gc);
  1705. }
  1706. void
  1707. link_socket_bad_outgoing_addr (void)
  1708. {
  1709. dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
  1710. }
  1711. in_addr_t
  1712. link_socket_current_remote (const struct link_socket_info *info)
  1713. {
  1714. const struct link_socket_addr *lsa = info->lsa;
  1715. /*
  1716. * This logic supports "redirect-gateway" semantic, which
  1717. * makes sense only for PF_INET routes over PF_INET endpoints
  1718. *
  1719. * Maybe in the future consider PF_INET6 endpoints also ...
  1720. * by now just ignore it
  1721. *
  1722. */
  1723. if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
  1724. return IPV4_INVALID_ADDR;
  1725. if (link_socket_actual_defined (&lsa->actual))
  1726. return ntohl (lsa->actual.dest.addr.in4.sin_addr.s_addr);
  1727. else if (addr_defined (&lsa->remote))
  1728. return ntohl (lsa->remote.addr.in4.sin_addr.s_addr);
  1729. else
  1730. return 0;
  1731. }
  1732. /*
  1733. * Return a status string describing socket state.
  1734. */
  1735. const char *
  1736. socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
  1737. {
  1738. struct buffer out = alloc_buf_gc (64, gc);
  1739. if (s)
  1740. {
  1741. if (rwflags & EVENT_READ)
  1742. {
  1743. buf_printf (&out, "S%s",
  1744. (s->rwflags_debug & EVENT_READ) ? "R" : "r");
  1745. #ifdef WIN32
  1746. buf_printf (&out, "%s",
  1747. overlapped_io_state_ascii (&s->reads));
  1748. #endif
  1749. }
  1750. if (rwflags & EVENT_WRITE)
  1751. {
  1752. buf_printf (&out, "S%s",
  1753. (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
  1754. #ifdef WIN32
  1755. buf_printf (&out, "%s",
  1756. overlapped_io_state_ascii (&s->writes));
  1757. #endif
  1758. }
  1759. }
  1760. else
  1761. {
  1762. buf_printf (&out, "S?");
  1763. }
  1764. return BSTR (&out);
  1765. }
  1766. /*
  1767. * Stream buffer functions, used to packetize a TCP
  1768. * stream connection.
  1769. */
  1770. static inline void
  1771. stream_buf_reset (struct stream_buf *sb)
  1772. {
  1773. dmsg (D_STREAM_DEBUG, "STREAM: RESET");
  1774. sb->residual_fully_formed = false;
  1775. sb->buf = sb->buf_init;
  1776. buf_reset (&sb->next);
  1777. sb->len = -1;
  1778. }
  1779. void
  1780. stream_buf_init (struct stream_buf *sb,
  1781. struct buffer *buf,
  1782. const unsigned int sockflags,
  1783. const int proto)
  1784. {
  1785. sb->buf_init = *buf;
  1786. sb->maxlen = sb->buf_init.len;
  1787. sb->buf_init.len = 0;
  1788. sb->residual = alloc_buf (sb->maxlen);
  1789. sb->error = false;
  1790. #if PORT_SHARE
  1791. sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCPv4_SERVER))
  1792. ? PS_ENABLED
  1793. : PS_DISABLED;
  1794. #endif
  1795. stream_buf_reset (sb);
  1796. dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
  1797. }
  1798. static inline void
  1799. stream_buf_set_next (struct stream_buf *sb)
  1800. {
  1801. /* set up 'next' for next i/o read */
  1802. sb->next = sb->buf;
  1803. sb->next.offset = sb->buf.offset + sb->buf.len;
  1804. sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
  1805. dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
  1806. sb->buf.offset, sb->buf.len,
  1807. sb->next.offset, sb->next.len,
  1808. sb->len, sb->maxlen);
  1809. ASSERT (sb->next.len > 0);
  1810. ASSERT (buf_safe (&sb->buf, sb->next.len));
  1811. }
  1812. static inline void
  1813. stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
  1814. {
  1815. dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
  1816. buf_defined (&sb->buf) ? sb->buf.len : -1);
  1817. ASSERT (buf_defined (&sb->buf));
  1818. *buf = sb->buf;
  1819. }
  1820. static inline void
  1821. stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
  1822. {
  1823. dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
  1824. buf_defined (&sb->next) ? sb->next.len : -1);
  1825. ASSERT (buf_defined (&sb->next));
  1826. *buf = sb->next;
  1827. }
  1828. bool
  1829. stream_buf_read_setup_dowork (struct link_socket* sock)
  1830. {
  1831. if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
  1832. {
  1833. ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
  1834. ASSERT (buf_init (&sock->stream_buf.residual, 0));
  1835. sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
  1836. dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
  1837. sock->stream_buf.residual_fully_formed ? "YES" : "NO",
  1838. sock->stream_buf.residual.len);
  1839. }
  1840. if (!sock->stream_buf.residual_fully_formed)
  1841. stream_buf_set_next (&sock->stream_buf);
  1842. return !sock->stream_buf.residual_fully_formed;
  1843. }
  1844. bool
  1845. stream_buf_added (struct stream_buf *sb,
  1846. int length_added)
  1847. {
  1848. dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
  1849. if (length_added > 0)
  1850. sb->buf.len += length_added;
  1851. /* if length unknown, see if we can get the length prefix from
  1852. the head of the buffer */
  1853. if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
  1854. {
  1855. packet_size_type net_size;
  1856. #if PORT_SHARE
  1857. if (sb->port_share_state == PS_ENABLED)
  1858. {
  1859. if (!is_openvpn_protocol (&sb->buf))
  1860. {
  1861. msg (D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
  1862. sb->port_share_state = PS_FOREIGN;
  1863. sb->error = true;
  1864. return false;
  1865. }
  1866. else
  1867. sb->port_share_state = PS_DISABLED;
  1868. }
  1869. #endif
  1870. ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
  1871. sb->len = ntohps (net_size);
  1872. if (sb->len < 1 || sb->len > sb->maxlen)
  1873. {
  1874. msg (M_WARN, "WARNING: Bad encapsulated packet length from peer (%d), which must be > 0 and <= %d -- please ensure that --tun-mtu or --link-mtu is equal on both peers -- this condition could also indicate a possible active attack on the TCP link -- [Attempting restart...]", sb->len, sb->maxlen);
  1875. stream_buf_reset (sb);
  1876. sb->error = true;
  1877. return false;
  1878. }
  1879. }
  1880. /* is our incoming packet fully read? */
  1881. if (sb->len > 0 && sb->buf.len >= sb->len)
  1882. {
  1883. /* save any residual data that's part of the next packet */
  1884. ASSERT (buf_init (&sb->residual, 0));
  1885. if (sb->buf.len > sb->len)
  1886. ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
  1887. dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
  1888. BLEN (&sb->buf),
  1889. BLEN (&sb->residual));
  1890. return true;
  1891. }
  1892. else
  1893. {
  1894. dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
  1895. stream_buf_set_next (sb);
  1896. return false;
  1897. }
  1898. }
  1899. void
  1900. stream_buf_close (struct stream_buf* sb)
  1901. {
  1902. free_buf (&sb->residual);
  1903. }
  1904. /*
  1905. * The listen event is a special event whose sole purpose is
  1906. * to tell us that there's a new incoming connection on a
  1907. * TCP socket, for use in server mode.
  1908. */
  1909. event_t
  1910. socket_listen_event_handle (struct link_socket *s)
  1911. {
  1912. #ifdef WIN32
  1913. if (!defined_net_event_win32 (&s->listen_handle))
  1914. init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
  1915. return &s->listen_handle;
  1916. #else
  1917. return s->sd;
  1918. #endif
  1919. }
  1920. /*
  1921. * Format IP addresses in ascii
  1922. */
  1923. const char *
  1924. print_sockaddr (const struct openvpn_sockaddr *addr, struct gc_arena *gc)
  1925. {
  1926. return print_sockaddr_ex (addr, ":", PS_SHOW_PORT, gc);
  1927. }
  1928. const char *
  1929. print_sockaddr_ex (const struct openvpn_sockaddr *addr,
  1930. const char* separator,
  1931. const unsigned int flags,
  1932. struct gc_arena *gc)
  1933. {
  1934. struct buffer out = alloc_buf_gc (128, gc);
  1935. bool addr_is_defined;
  1936. addr_is_defined = addr_defined (addr);
  1937. if (!addr_is_defined) {
  1938. return "[undef]";
  1939. }
  1940. switch(addr->addr.sa.sa_family)
  1941. {
  1942. case AF_INET:
  1943. {
  1944. const int port= ntohs (addr->addr.in4.sin_port);
  1945. buf_puts (&out, "[AF_INET]");
  1946. if (!(flags & PS_DONT_SHOW_ADDR))
  1947. buf_printf (&out, "%s", (addr_defined (addr) ? inet_ntoa (addr->addr.in4.sin_addr) : "[undef]"));
  1948. if (((flags & PS_SHOW_PORT) || (addr_defined (addr) && (flags & PS_SHOW_PORT_IF_DEFINED)))
  1949. && port)
  1950. {
  1951. if (separator)
  1952. buf_printf (&out, "%s", separator);
  1953. buf_printf (&out, "%d", port);
  1954. }
  1955. }
  1956. break;
  1957. case AF_INET6:
  1958. {
  1959. const int port= ntohs (addr->addr.in6.sin6_port);
  1960. char buf[INET6_ADDRSTRLEN] = "";
  1961. buf_puts (&out, "[AF_INET6]");
  1962. if (addr_is_defined)
  1963. {
  1964. getnameinfo(&addr->addr.sa, sizeof (struct sockaddr_in6),
  1965. buf, sizeof (buf), NULL, 0, NI_NUMERICHOST);
  1966. buf_puts (&out, buf);
  1967. }
  1968. if (((flags & PS_SHOW_PORT) || (addr_is_defined && (flags & PS_SHOW_PORT_IF_DEFINED)))
  1969. && port)
  1970. {
  1971. if (separator)
  1972. buf_puts (&out, separator);
  1973. buf_printf (&out, "%d", port);
  1974. }
  1975. }
  1976. break;
  1977. default:
  1978. ASSERT(0);
  1979. }
  1980. return BSTR (&out);
  1981. }
  1982. const char *
  1983. print_link_socket_actual (const struct link_socket_actual *act, struct gc_arena *gc)
  1984. {
  1985. return print_link_socket_actual_ex (act, ":", PS_SHOW_PORT|PS_SHOW_PKTINFO, gc);
  1986. }
  1987. #ifndef IF_NAMESIZE
  1988. #define IF_NAMESIZE 16
  1989. #endif
  1990. const char *
  1991. print_link_socket_actual_ex (const struct link_socket_actual *act,
  1992. const char *separator,
  1993. const unsigned int flags,
  1994. struct gc_arena *gc)
  1995. {
  1996. if (act)
  1997. {
  1998. char ifname[IF_NAMESIZE] = "[undef]";
  1999. struct buffer out = alloc_buf_gc (128, gc);
  2000. buf_printf (&out, "%s", print_sockaddr_ex (&act->dest, separator, flags, gc));
  2001. #if ENABLE_IP_PKTINFO
  2002. if ((flags & PS_SHOW_PKTINFO) && addr_defined_ipi(act))
  2003. {
  2004. switch(act->dest.addr.sa.sa_family)
  2005. {
  2006. case AF_INET:
  2007. {
  2008. struct openvpn_sockaddr sa;
  2009. CLEAR (sa);
  2010. sa.addr.in4.sin_family = AF_INET;
  2011. #ifdef IP_PKTINFO
  2012. sa.addr.in4.sin_addr = act->pi.in4.ipi_spec_dst;
  2013. if_indextoname(act->pi.in4.ipi_ifindex, ifname);
  2014. #elif defined(IP_RECVDSTADDR)
  2015. sa.addr.in4.sin_addr = act->pi.in4;
  2016. ifname[0]=0;
  2017. #else
  2018. #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
  2019. #endif
  2020. buf_printf (&out, " (via %s%%%s)",
  2021. print_sockaddr_ex (&sa, separator, 0, gc),
  2022. ifname);
  2023. }
  2024. break;
  2025. case AF_INET6:
  2026. {
  2027. struct sockaddr_in6 sin6;
  2028. char buf[INET6_ADDRSTRLEN] = "[undef]";
  2029. CLEAR(sin6);
  2030. sin6.sin6_family = AF_INET6;
  2031. sin6.sin6_addr = act->pi.in6.ipi6_addr;
  2032. if_indextoname(act->pi.in6.ipi6_ifindex, ifname);
  2033. if (getnameinfo((struct sockaddr *)&sin6, sizeof (struct sockaddr_in6),
  2034. buf, sizeof (buf), NULL, 0, NI_NUMERICHOST) == 0)
  2035. buf_printf (&out, " (via %s%%%s)", buf, ifname);
  2036. else
  2037. buf_printf (&out, " (via [getnameinfo() err]%%%s)", ifname);
  2038. }
  2039. break;
  2040. }
  2041. }
  2042. #endif
  2043. return BSTR (&out);
  2044. }
  2045. else
  2046. return "[NULL]";
  2047. }
  2048. /*
  2049. * Convert an in_addr_t in host byte order
  2050. * to an ascii dotted quad.
  2051. */
  2052. const char *
  2053. print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
  2054. {
  2055. struct in_addr ia;
  2056. struct buffer out = alloc_buf_gc (64, gc);
  2057. if (addr || !(flags & IA_EMPTY_IF_UNDEF))
  2058. {
  2059. CLEAR (ia);
  2060. ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
  2061. buf_printf (&out, "%s", inet_ntoa (ia));
  2062. }
  2063. return BSTR (&out);
  2064. }
  2065. /*
  2066. * Convert an in6_addr in host byte order
  2067. * to an ascii representation of an IPv6 address
  2068. */
  2069. const char *
  2070. print_in6_addr (struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
  2071. {
  2072. struct buffer out = alloc_buf_gc (64, gc);
  2073. char tmp_out_buf[64]; /* inet_ntop wants pointer to buffer */
  2074. if ( memcmp(&a6, &in6addr_any, sizeof(a6)) != 0 ||
  2075. !(flags & IA_EMPTY_IF_UNDEF))
  2076. {
  2077. inet_ntop (AF_INET6, &a6, tmp_out_buf, sizeof(tmp_out_buf)-1);
  2078. buf_printf (&out, "%s", tmp_out_buf );
  2079. }
  2080. return BSTR (&out);
  2081. }
  2082. #ifndef UINT8_MAX
  2083. # define UINT8_MAX 0xff
  2084. #endif
  2085. /* add some offset to an ipv6 address
  2086. * (add in steps of 8 bits, taking overflow into next round)
  2087. */
  2088. struct in6_addr add_in6_addr( struct in6_addr base, uint32_t add )
  2089. {
  2090. int i;
  2091. for( i=15; i>=0 && add > 0 ; i-- )
  2092. {
  2093. register int carry;
  2094. register uint32_t h;
  2095. h = (unsigned char) base.s6_addr[i];
  2096. base.s6_addr[i] = (h+add) & UINT8_MAX;
  2097. /* using explicit carry for the 8-bit additions will catch
  2098. * 8-bit and(!) 32-bit overruns nicely
  2099. */
  2100. carry = ((h & 0xff) + (add & 0xff)) >> 8;
  2101. add = (add>>8) + carry;
  2102. }
  2103. return base;
  2104. }
  2105. /* set environmental variables for ip/port in *addr */
  2106. void
  2107. setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
  2108. {
  2109. char name_buf[256];
  2110. char buf[128];
  2111. switch(addr->addr.sa.sa_family)
  2112. {
  2113. case AF_INET:
  2114. if (flags & SA_IP_PORT)
  2115. openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
  2116. else
  2117. openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
  2118. setenv_str (es, name_buf, inet_ntoa (addr->addr.in4.sin_addr));
  2119. if ((flags & SA_IP_PORT) && addr->addr.in4.sin_port)
  2120. {
  2121. openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
  2122. setenv_int (es, name_buf, ntohs (addr->addr.in4.sin_port));
  2123. }
  2124. break;
  2125. case AF_INET6:
  2126. openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip6", name_prefix);
  2127. getnameinfo(&addr->addr.sa, sizeof (struct sockaddr_in6),
  2128. buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
  2129. setenv_str (es, name_buf, buf);
  2130. if ((flags & SA_IP_PORT) && addr->addr.in6.sin6_port)
  2131. {
  2132. openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
  2133. setenv_int (es, name_buf, ntohs (addr->addr.in6.sin6_port));
  2134. }
  2135. break;
  2136. }
  2137. }
  2138. void
  2139. setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
  2140. {
  2141. if (addr || !(flags & SA_SET_IF_NONZERO))
  2142. {
  2143. struct openvpn_sockaddr si;
  2144. CLEAR (si);
  2145. si.addr.in4.sin_family = AF_INET;
  2146. si.addr.in4.sin_addr.s_addr = htonl (addr);
  2147. setenv_sockaddr (es, name_prefix, &si, flags);
  2148. }
  2149. }
  2150. void
  2151. setenv_link_socket_actual (struct env_set *es,
  2152. const char *name_prefix,
  2153. const struct link_socket_actual *act,
  2154. const unsigned int flags)
  2155. {
  2156. setenv_sockaddr (es, name_prefix, &act->dest, flags);
  2157. }
  2158. /*
  2159. * Convert protocol names between index and ascii form.
  2160. */
  2161. struct proto_names {
  2162. const char *short_form;
  2163. const char *display_form;
  2164. bool is_dgram;
  2165. bool is_net;
  2166. unsigned short proto_af;
  2167. };
  2168. /* Indexed by PROTO_x */
  2169. static const struct proto_names proto_names[PROTO_N] = {
  2170. {"proto-uninitialized", "proto-NONE",0,0, AF_UNSPEC},
  2171. {"udp", "UDPv4",1,1, AF_INET},
  2172. {"tcp-server", "TCPv4_SERVER",0,1, AF_INET},
  2173. {"tcp-client", "TCPv4_CLIENT",0,1, AF_INET},
  2174. {"tcp", "TCPv4",0,1, AF_INET},
  2175. {"udp6" ,"UDPv6",1,1, AF_INET6},
  2176. {"tcp6-server","TCPv6_SERVER",0,1, AF_INET6},
  2177. {"tcp6-client","TCPv6_CLIENT",0,1, AF_INET6},
  2178. {"tcp6" ,"TCPv6",0,1, AF_INET6},
  2179. };
  2180. bool
  2181. proto_is_net(int proto)
  2182. {
  2183. if (proto < 0 || proto >= PROTO_N)
  2184. ASSERT(0);
  2185. return proto_names[proto].is_net;
  2186. }
  2187. bool
  2188. proto_is_dgram(int proto)
  2189. {
  2190. if (proto < 0 || proto >= PROTO_N)
  2191. ASSERT(0);
  2192. return proto_names[proto].is_dgram;
  2193. }
  2194. bool
  2195. proto_is_udp(int proto)
  2196. {
  2197. if (proto < 0 || proto >= PROTO_N)
  2198. ASSERT(0);
  2199. return proto_names[proto].is_dgram&&proto_names[proto].is_net;
  2200. }
  2201. bool
  2202. proto_is_tcp(int proto)
  2203. {
  2204. if (proto < 0 || proto >= PROTO_N)
  2205. ASSERT(0);
  2206. return (!proto_names[proto].is_dgram)&&proto_names[proto].is_net;
  2207. }
  2208. unsigned short
  2209. proto_sa_family(int proto)
  2210. {
  2211. if (proto < 0 || proto >= PROTO_N)
  2212. ASSERT(0);
  2213. return proto_names[proto].proto_af;
  2214. }
  2215. int
  2216. ascii2proto (const char* proto_name)
  2217. {
  2218. int i;
  2219. ASSERT (PROTO_N == SIZE (proto_names));
  2220. for (i = 0; i < PROTO_N; ++i)
  2221. if (!strcmp (proto_name, proto_names[i].short_form))
  2222. return i;
  2223. return -1;
  2224. }
  2225. const char *
  2226. proto2ascii (int proto, bool display_form)
  2227. {
  2228. ASSERT (PROTO_N == SIZE (proto_names));
  2229. if (proto < 0 || proto >= PROTO_N)
  2230. return "[unknown protocol]";
  2231. else if (display_form)
  2232. return proto_names[proto].display_form;
  2233. else
  2234. return proto_names[proto].short_form;
  2235. }
  2236. const char *
  2237. proto2ascii_all (struct gc_arena *gc)
  2238. {
  2239. struct buffer out = alloc_buf_gc (256, gc);
  2240. int i;
  2241. ASSERT (PROTO_N == SIZE (proto_names));
  2242. for (i = 0; i < PROTO_N; ++i)
  2243. {
  2244. if (i)
  2245. buf_printf(&out, " ");
  2246. buf_printf(&out, "[%s]", proto2ascii(i, false));
  2247. }
  2248. return BSTR (&out);
  2249. }
  2250. int
  2251. addr_guess_family(int proto, const char *name)
  2252. {
  2253. unsigned short ret;
  2254. if (proto)
  2255. {
  2256. return proto_sa_family(proto); /* already stamped */
  2257. }
  2258. else
  2259. {
  2260. struct addrinfo hints , *ai;
  2261. int err;
  2262. CLEAR(hints);
  2263. hints.ai_flags = AI_NUMERICHOST;
  2264. err = getaddrinfo(name, NULL, &hints, &ai);
  2265. if ( 0 == err )
  2266. {
  2267. ret=ai->ai_family;
  2268. freeaddrinfo(ai);
  2269. return ret;
  2270. }
  2271. }
  2272. return AF_INET; /* default */
  2273. }
  2274. const char *
  2275. addr_family_name (int af)
  2276. {
  2277. switch (af)
  2278. {
  2279. case AF_INET: return "AF_INET";
  2280. case AF_INET6: return "AF_INET6";
  2281. }
  2282. return "AF_UNSPEC";
  2283. }
  2284. /*
  2285. * Given a local proto, return local proto
  2286. * if !remote, or compatible remote proto
  2287. * if remote.
  2288. *
  2289. * This is used for options compatibility
  2290. * checking.
  2291. *
  2292. * IPv6 and IPv4 protocols are comptabile but OpenVPN
  2293. * has always sent UDPv4, TCPv4 over the wire. Keep these
  2294. * strings for backward compatbility
  2295. */
  2296. int
  2297. proto_remote (int proto, bool remote)
  2298. {
  2299. ASSERT (proto >= 0 && proto < PROTO_N);
  2300. if (remote)
  2301. {
  2302. switch (proto)
  2303. {
  2304. case PROTO_TCPv4_SERVER: return PROTO_TCPv4_CLIENT;
  2305. case PROTO_TCPv4_CLIENT: return PROTO_TCPv4_SERVER;
  2306. case PROTO_TCPv6_SERVER: return PROTO_TCPv4_CLIENT;
  2307. case PROTO_TCPv6_CLIENT: return PROTO_TCPv4_SERVER;
  2308. case PROTO_UDPv6: return PROTO_UDPv4;
  2309. }
  2310. }
  2311. else
  2312. {
  2313. switch (proto)
  2314. {
  2315. case PROTO_TCPv6_SERVER: return PROTO_TCPv4_SERVER;
  2316. case PROTO_TCPv6_CLIENT: return PROTO_TCPv4_CLIENT;
  2317. case PROTO_UDPv6: return PROTO_UDPv4;
  2318. }
  2319. }
  2320. return proto;
  2321. }
  2322. /*
  2323. * Bad incoming address lengths that differ from what
  2324. * we expect are considered to be fatal errors.
  2325. */
  2326. void
  2327. bad_address_length (int actual, int expected)
  2328. {
  2329. msg (M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
  2330. actual,
  2331. expected);
  2332. }
  2333. /*
  2334. * Socket Read Routines
  2335. */
  2336. int
  2337. link_socket_read_tcp (struct link_socket *sock,
  2338. struct buffer *buf)
  2339. {
  2340. int len = 0;
  2341. if (!sock->stream_buf.residual_fully_formed)
  2342. {
  2343. #ifdef WIN32
  2344. len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
  2345. #else
  2346. struct buffer frag;
  2347. stream_buf_get_next (&sock->stream_buf, &frag);
  2348. len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
  2349. #endif
  2350. if (!len)
  2351. sock->stream_reset = true;
  2352. if (len <= 0)
  2353. return buf->len = len;
  2354. }
  2355. if (sock->stream_buf.residual_fully_formed
  2356. || stream_buf_added (&sock->stream_buf, len)) /* packet complete? */
  2357. {
  2358. stream_buf_get_final (&sock->stream_buf, buf);
  2359. stream_buf_reset (&sock->stream_buf);
  2360. return buf->len;
  2361. }
  2362. else
  2363. return buf->len = 0; /* no error, but packet is still incomplete */
  2364. }
  2365. #ifndef WIN32
  2366. #if ENABLE_IP_PKTINFO
  2367. #pragma pack(1) /* needed to keep structure size consistent for 32 vs. 64-bit architectures */
  2368. struct openvpn_in4_pktinfo
  2369. {
  2370. struct cmsghdr cmsghdr;
  2371. #ifdef HAVE_IN_PKTINFO
  2372. struct in_pktinfo pi4;
  2373. #elif defined(IP_RECVDSTADDR)
  2374. struct in_addr pi4;
  2375. #endif
  2376. };
  2377. struct openvpn_in6_pktinfo
  2378. {
  2379. struct cmsghdr cmsghdr;
  2380. struct in6_pktinfo pi6;
  2381. };
  2382. union openvpn_pktinfo {
  2383. struct openvpn_in4_pktinfo msgpi4;
  2384. struct openvpn_in6_pktinfo msgpi6;
  2385. };
  2386. #pragma pack()
  2387. static socklen_t
  2388. link_socket_read_udp_posix_recvmsg (struct link_socket *sock,
  2389. struct buffer *buf,
  2390. int maxsize,
  2391. struct link_socket_actual *from)
  2392. {
  2393. struct iovec iov;
  2394. union openvpn_pktinfo opi;
  2395. struct msghdr mesg;
  2396. socklen_t fromlen = sizeof (from->dest.addr);
  2397. iov.iov_base = BPTR (buf);
  2398. iov.iov_len = maxsize;
  2399. mesg.msg_iov = &iov;
  2400. mesg.msg_iovlen = 1;
  2401. mesg.msg_name = &from->dest.addr;
  2402. mesg.msg_namelen = fromlen;
  2403. mesg.msg_control = &opi;
  2404. mesg.msg_controllen = sizeof opi;
  2405. buf->len = recvmsg (sock->sd, &mesg, 0);
  2406. if (buf->len >= 0)
  2407. {
  2408. struct cmsghdr *cmsg;
  2409. fromlen = mesg.msg_namelen;
  2410. cmsg = CMSG_FIRSTHDR (&mesg);
  2411. if (cmsg != NULL
  2412. && CMSG_NXTHDR (&mesg, cmsg) == NULL
  2413. #ifdef IP_PKTINFO
  2414. && cmsg->cmsg_level == SOL_IP
  2415. && cmsg->cmsg_type == IP_PKTINFO
  2416. #elif defined(IP_RECVDSTADDR)
  2417. && cmsg->cmsg_level == IPPROTO_IP
  2418. && cmsg->cmsg_type == IP_RECVDSTADDR
  2419. #else
  2420. #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
  2421. #endif
  2422. && cmsg->cmsg_len >= sizeof (struct openvpn_in4_pktinfo))
  2423. {
  2424. #ifdef IP_PKTINFO
  2425. struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
  2426. from->pi.in4.ipi_ifindex = pkti->ipi_ifindex;
  2427. from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
  2428. #elif defined(IP_RECVDSTADDR)
  2429. from->pi.in4 = *(struct in_addr*) CMSG_DATA (cmsg);
  2430. #else
  2431. #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
  2432. #endif
  2433. }
  2434. else if (cmsg != NULL
  2435. && CMSG_NXTHDR (&mesg, cmsg) == NULL
  2436. && cmsg->cmsg_level == IPPROTO_IPV6
  2437. && cmsg->cmsg_type == IPV6_PKTINFO
  2438. && cmsg->cmsg_len >= sizeof (struct openvpn_in6_pktinfo))
  2439. {
  2440. struct in6_pktinfo *pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
  2441. from->pi.in6.ipi6_ifindex = pkti6->ipi6_ifindex;
  2442. from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
  2443. }
  2444. }
  2445. return fromlen;
  2446. }
  2447. #endif
  2448. int
  2449. link_socket_read_udp_posix (struct link_socket *sock,
  2450. struct buffer *buf,
  2451. int maxsize,
  2452. struct link_socket_actual *from)
  2453. {
  2454. socklen_t fromlen = sizeof (from->dest.addr);
  2455. socklen_t expectedlen = af_addr_size(proto_sa_family(sock->info.proto));
  2456. addr_zero_host(&from->dest);
  2457. ASSERT (buf_safe (buf, maxsize));
  2458. #if ENABLE_IP_PKTINFO
  2459. /* Both PROTO_UDPv4 and PROTO_UDPv6 */
  2460. if (proto_is_udp(sock->info.proto) && sock->sockflags & SF_USE_IP_PKTINFO)
  2461. fromlen = link_socket_read_udp_posix_recvmsg (sock, buf, maxsize, from);
  2462. else
  2463. #endif
  2464. buf->len = recvfrom (sock->sd, BPTR (buf), maxsize, 0,
  2465. &from->dest.addr.sa, &fromlen);
  2466. if (buf->len >= 0 && expectedlen && fromlen != expectedlen)
  2467. bad_address_length (fromlen, expectedlen);
  2468. return buf->len;
  2469. }
  2470. #endif
  2471. /*
  2472. * Socket Write Routines
  2473. */
  2474. int
  2475. link_socket_write_tcp (struct link_socket *sock,
  2476. struct buffer *buf,
  2477. struct link_socket_actual *to)
  2478. {
  2479. packet_size_type len = BLEN (buf);
  2480. dmsg (D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
  2481. ASSERT (len <= sock->stream_buf.maxlen);
  2482. len = htonps (len);
  2483. ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
  2484. #ifdef WIN32
  2485. return link_socket_write_win32 (sock, buf, to);
  2486. #else
  2487. return link_socket_write_tcp_posix (sock, buf, to);
  2488. #endif
  2489. }
  2490. #if ENABLE_IP_PKTINFO
  2491. int
  2492. link_socket_write_udp_posix_sendmsg (struct link_socket *sock,
  2493. struct buffer *buf,
  2494. struct link_socket_actual *to)
  2495. {
  2496. struct iovec iov;
  2497. struct msghdr mesg;
  2498. struct cmsghdr *cmsg;
  2499. union openvpn_pktinfo opi;
  2500. iov.iov_base = BPTR (buf);
  2501. iov.iov_len = BLEN (buf);
  2502. mesg.msg_iov = &iov;
  2503. mesg.msg_iovlen = 1;
  2504. switch (sock->info.lsa->remote.addr.sa.sa_family)
  2505. {
  2506. case AF_INET:
  2507. {
  2508. mesg.msg_name = &to->dest.addr.sa;
  2509. mesg.msg_namelen = sizeof (struct sockaddr_in);
  2510. mesg.msg_control = &opi;
  2511. mesg.msg_controllen = sizeof (struct openvpn_in4_pktinfo);
  2512. mesg.msg_flags = 0;
  2513. cmsg = CMSG_FIRSTHDR (&mesg);
  2514. cmsg->cmsg_len = sizeof (struct openvpn_in4_pktinfo);
  2515. #ifdef HAVE_IN_PKTINFO
  2516. cmsg->cmsg_level = SOL_IP;
  2517. cmsg->cmsg_type = IP_PKTINFO;
  2518. {
  2519. struct in_pktinfo *pkti;
  2520. pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
  2521. pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
  2522. pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
  2523. pkti->ipi_addr.s_addr = 0;
  2524. }
  2525. #elif defined(IP_RECVDSTADDR)
  2526. cmsg->cmsg_level = IPPROTO_IP;
  2527. cmsg->cmsg_type = IP_RECVDSTADDR;
  2528. *(struct in_addr *) CMSG_DATA (cmsg) = to->pi.in4;
  2529. #else
  2530. #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
  2531. #endif
  2532. break;
  2533. }
  2534. case AF_INET6:
  2535. {
  2536. struct in6_pktinfo *pkti6;
  2537. mesg.msg_name = &to->dest.addr.sa;
  2538. mesg.msg_namelen = sizeof (struct sockaddr_in6);
  2539. mesg.msg_control = &opi;
  2540. mesg.msg_controllen = sizeof (struct openvpn_in6_pktinfo);
  2541. mesg.msg_flags = 0;
  2542. cmsg = CMSG_FIRSTHDR (&mesg);
  2543. cmsg->cmsg_len = sizeof (struct openvpn_in6_pktinfo);
  2544. cmsg->cmsg_level = IPPROTO_IPV6;
  2545. cmsg->cmsg_type = IPV6_PKTINFO;
  2546. pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
  2547. pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
  2548. pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
  2549. break;
  2550. }
  2551. default: ASSERT(0);
  2552. }
  2553. return sendmsg (sock->sd, &mesg, 0);
  2554. }
  2555. #endif
  2556. /*
  2557. * Win32 overlapped socket I/O functions.
  2558. */
  2559. #ifdef WIN32
  2560. int
  2561. socket_recv_queue (struct link_socket *sock, int maxsize)
  2562. {
  2563. if (sock->reads.iostate == IOSTATE_INITIAL)
  2564. {
  2565. WSABUF wsabuf[1];
  2566. int status;
  2567. /* reset buf to its initial state */
  2568. if (proto_is_udp(sock->info.proto))
  2569. {
  2570. sock->reads.buf = sock->reads.buf_init;
  2571. }
  2572. else if (proto_is_tcp(sock->info.proto))
  2573. {
  2574. stream_buf_get_next (&sock->stream_buf, &sock->reads.buf);
  2575. }
  2576. else
  2577. {
  2578. ASSERT (0);
  2579. }
  2580. /* Win32 docs say it's okay to allocate the wsabuf on the stack */
  2581. wsabuf[0].buf = BPTR (&sock->reads.buf);
  2582. wsabuf[0].len = maxsize ? maxsize : BLEN (&sock->reads.buf);
  2583. /* check for buffer overflow */
  2584. ASSERT (wsabuf[0].len <= BLEN (&sock->reads.buf));
  2585. /* the overlapped read will signal this event on I/O completion */
  2586. ASSERT (ResetEvent (sock->reads.overlapped.hEvent));
  2587. sock->reads.flags = 0;
  2588. if (proto_is_udp(sock->info.proto))
  2589. {
  2590. sock->reads.addr_defined = true;
  2591. if (sock->info.proto == PROTO_UDPv6)
  2592. sock->reads.addrlen = sizeof (sock->reads.addr6);
  2593. else
  2594. sock->reads.addrlen = sizeof (sock->reads.addr);
  2595. status = WSARecvFrom(
  2596. sock->sd,
  2597. wsabuf,
  2598. 1,
  2599. &sock->reads.size,
  2600. &sock->reads.flags,
  2601. (struct sockaddr *) &sock->reads.addr,
  2602. &sock->reads.addrlen,
  2603. &sock->reads.overlapped,
  2604. NULL);
  2605. }
  2606. else if (proto_is_tcp(sock->info.proto))
  2607. {
  2608. sock->reads.addr_defined = false;
  2609. status = WSARecv(
  2610. sock->sd,
  2611. wsabuf,
  2612. 1,
  2613. &sock->reads.size,
  2614. &sock->reads.flags,
  2615. &sock->reads.overlapped,
  2616. NULL);
  2617. }
  2618. else
  2619. {
  2620. status = 0;
  2621. ASSERT (0);
  2622. }
  2623. if (!status) /* operation completed immediately? */
  2624. {
  2625. int addrlen = af_addr_size(sock->info.lsa->local.addr.sa.sa_family);
  2626. if (sock->reads.addr_defined && sock->reads.addrlen != addrlen)
  2627. bad_address_length (sock->reads.addrlen, addrlen);
  2628. sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
  2629. /* since we got an immediate return, we must signal the event object ourselves */
  2630. ASSERT (SetEvent (sock->reads.overlapped.hEvent));
  2631. sock->reads.status = 0;
  2632. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
  2633. (int) wsabuf[0].len,
  2634. (int) sock->reads.size);
  2635. }
  2636. else
  2637. {
  2638. status = WSAGetLastError ();
  2639. if (status == WSA_IO_PENDING) /* operation queued? */
  2640. {
  2641. sock->reads.iostate = IOSTATE_QUEUED;
  2642. sock->reads.status = status;
  2643. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
  2644. (int) wsabuf[0].len);
  2645. }
  2646. else /* error occurred */
  2647. {
  2648. struct gc_arena gc = gc_new ();
  2649. ASSERT (SetEvent (sock->reads.overlapped.hEvent));
  2650. sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
  2651. sock->reads.status = status;
  2652. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
  2653. (int) wsabuf[0].len,
  2654. strerror_win32 (status, &gc));
  2655. gc_free (&gc);
  2656. }
  2657. }
  2658. }
  2659. return sock->reads.iostate;
  2660. }
  2661. int
  2662. socket_send_queue (struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
  2663. {
  2664. if (sock->writes.iostate == IOSTATE_INITIAL)
  2665. {
  2666. WSABUF wsabuf[1];
  2667. int status;
  2668. /* make a private copy of buf */
  2669. sock->writes.buf = sock->writes.buf_init;
  2670. sock->writes.buf.len = 0;
  2671. ASSERT (buf_copy (&sock->writes.buf, buf));
  2672. /* Win32 docs say it's okay to allocate the wsabuf on the stack */
  2673. wsabuf[0].buf = BPTR (&sock->writes.buf);
  2674. wsabuf[0].len = BLEN (&sock->writes.buf);
  2675. /* the overlapped write will signal this event on I/O completion */
  2676. ASSERT (ResetEvent (sock->writes.overlapped.hEvent));
  2677. sock->writes.flags = 0;
  2678. if (proto_is_udp(sock->info.proto))
  2679. {
  2680. /* set destination address for UDP writes */
  2681. sock->writes.addr_defined = true;
  2682. if (sock->info.proto == PROTO_UDPv6)
  2683. {
  2684. sock->writes.addr6 = to->dest.addr.in6;
  2685. sock->writes.addrlen = sizeof (sock->writes.addr6);
  2686. }
  2687. else
  2688. {
  2689. sock->writes.addr = to->dest.addr.in4;
  2690. sock->writes.addrlen = sizeof (sock->writes.addr);
  2691. }
  2692. status = WSASendTo(
  2693. sock->sd,
  2694. wsabuf,
  2695. 1,
  2696. &sock->writes.size,
  2697. sock->writes.flags,
  2698. (struct sockaddr *) &sock->writes.addr,
  2699. sock->writes.addrlen,
  2700. &sock->writes.overlapped,
  2701. NULL);
  2702. }
  2703. else if (proto_is_tcp(sock->info.proto))
  2704. {
  2705. /* destination address for TCP writes was established on connection initiation */
  2706. sock->writes.addr_defined = false;
  2707. status = WSASend(
  2708. sock->sd,
  2709. wsabuf,
  2710. 1,
  2711. &sock->writes.size,
  2712. sock->writes.flags,
  2713. &sock->writes.overlapped,
  2714. NULL);
  2715. }
  2716. else
  2717. {
  2718. status = 0;
  2719. ASSERT (0);
  2720. }
  2721. if (!status) /* operation completed immediately? */
  2722. {
  2723. sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
  2724. /* since we got an immediate return, we must signal the event object ourselves */
  2725. ASSERT (SetEvent (sock->writes.overlapped.hEvent));
  2726. sock->writes.status = 0;
  2727. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
  2728. (int) wsabuf[0].len,
  2729. (int) sock->writes.size);
  2730. }
  2731. else
  2732. {
  2733. status = WSAGetLastError ();
  2734. if (status == WSA_IO_PENDING) /* operation queued? */
  2735. {
  2736. sock->writes.iostate = IOSTATE_QUEUED;
  2737. sock->writes.status = status;
  2738. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
  2739. (int) wsabuf[0].len);
  2740. }
  2741. else /* error occurred */
  2742. {
  2743. struct gc_arena gc = gc_new ();
  2744. ASSERT (SetEvent (sock->writes.overlapped.hEvent));
  2745. sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
  2746. sock->writes.status = status;
  2747. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
  2748. (int) wsabuf[0].len,
  2749. strerror_win32 (status, &gc));
  2750. gc_free (&gc);
  2751. }
  2752. }
  2753. }
  2754. return sock->writes.iostate;
  2755. }
  2756. int
  2757. socket_finalize (SOCKET s,
  2758. struct overlapped_io *io,
  2759. struct buffer *buf,
  2760. struct link_socket_actual *from)
  2761. {
  2762. int ret = -1;
  2763. BOOL status;
  2764. switch (io->iostate)
  2765. {
  2766. case IOSTATE_QUEUED:
  2767. status = WSAGetOverlappedResult(
  2768. s,
  2769. &io->overlapped,
  2770. &io->size,
  2771. FALSE,
  2772. &io->flags
  2773. );
  2774. if (status)
  2775. {
  2776. /* successful return for a queued operation */
  2777. if (buf)
  2778. *buf = io->buf;
  2779. ret = io->size;
  2780. io->iostate = IOSTATE_INITIAL;
  2781. ASSERT (ResetEvent (io->overlapped.hEvent));
  2782. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
  2783. }
  2784. else
  2785. {
  2786. /* error during a queued operation */
  2787. ret = -1;
  2788. if (WSAGetLastError() != WSA_IO_INCOMPLETE)
  2789. {
  2790. /* if no error (i.e. just not finished yet), then DON'T execute this code */
  2791. io->iostate = IOSTATE_INITIAL;
  2792. ASSERT (ResetEvent (io->overlapped.hEvent));
  2793. msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion error");
  2794. }
  2795. }
  2796. break;
  2797. case IOSTATE_IMMEDIATE_RETURN:
  2798. io->iostate = IOSTATE_INITIAL;
  2799. ASSERT (ResetEvent (io->overlapped.hEvent));
  2800. if (io->status)
  2801. {
  2802. /* error return for a non-queued operation */
  2803. WSASetLastError (io->status);
  2804. ret = -1;
  2805. msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion non-queued error");
  2806. }
  2807. else
  2808. {
  2809. /* successful return for a non-queued operation */
  2810. if (buf)
  2811. *buf = io->buf;
  2812. ret = io->size;
  2813. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
  2814. }
  2815. break;
  2816. case IOSTATE_INITIAL: /* were we called without proper queueing? */
  2817. WSASetLastError (WSAEINVAL);
  2818. ret = -1;
  2819. dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
  2820. break;
  2821. default:
  2822. ASSERT (0);
  2823. }
  2824. /* return from address if requested */
  2825. if (from)
  2826. {
  2827. if (ret >= 0 && io->addr_defined)
  2828. {
  2829. /* TODO(jjo): streamline this mess */
  2830. /* in this func we dont have relevant info about the PF_ of this
  2831. * endpoint, as link_socket_actual will be zero for the 1st received packet
  2832. *
  2833. * Test for inets PF_ possible sizes
  2834. */
  2835. switch (io->addrlen)
  2836. {
  2837. case sizeof(struct sockaddr_in):
  2838. case sizeof(struct sockaddr_in6):
  2839. /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
  2840. * under WIN32*/
  2841. case sizeof(struct sockaddr_in6)-4:
  2842. break;
  2843. default:
  2844. bad_address_length (io->addrlen, af_addr_size(io->addr.sin_family));
  2845. }
  2846. switch (io->addr.sin_family)
  2847. {
  2848. case AF_INET:
  2849. from->dest.addr.in4 = io->addr;
  2850. break;
  2851. case AF_INET6:
  2852. from->dest.addr.in6 = io->addr6;
  2853. break;
  2854. }
  2855. }
  2856. else
  2857. CLEAR (from->dest.addr);
  2858. }
  2859. if (buf)
  2860. buf->len = ret;
  2861. return ret;
  2862. }
  2863. #endif /* WIN32 */
  2864. /*
  2865. * Socket event notification
  2866. */
  2867. unsigned int
  2868. socket_set (struct link_socket *s,
  2869. struct event_set *es,
  2870. unsigned int rwflags,
  2871. void *arg,
  2872. unsigned int *persistent)
  2873. {
  2874. if (s)
  2875. {
  2876. if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
  2877. {
  2878. ASSERT (!persistent);
  2879. rwflags &= ~EVENT_READ;
  2880. }
  2881. #ifdef WIN32
  2882. if (rwflags & EVENT_READ)
  2883. socket_recv_queue (s, 0);
  2884. #endif
  2885. /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
  2886. if (!persistent || *persistent != rwflags)
  2887. {
  2888. event_ctl (es, socket_event_handle (s), rwflags, arg);
  2889. if (persistent)
  2890. *persistent = rwflags;
  2891. }
  2892. s->rwflags_debug = rwflags;
  2893. }
  2894. return rwflags;
  2895. }
  2896. void
  2897. sd_close (socket_descriptor_t *sd)
  2898. {
  2899. if (sd && socket_defined (*sd))
  2900. {
  2901. openvpn_close_socket (*sd);
  2902. *sd = SOCKET_UNDEFINED;
  2903. }
  2904. }
  2905. #if UNIX_SOCK_SUPPORT
  2906. /*
  2907. * code for unix domain sockets
  2908. */
  2909. const char *
  2910. sockaddr_unix_name (const struct sockaddr_un *local, const char *null)
  2911. {
  2912. if (local && local->sun_family == PF_UNIX)
  2913. return local->sun_path;
  2914. else
  2915. return null;
  2916. }
  2917. socket_descriptor_t
  2918. create_socket_unix (void)
  2919. {
  2920. socket_descriptor_t sd;
  2921. if ((sd = socket (PF_UNIX, SOCK_STREAM, 0)) < 0)
  2922. msg (M_ERR, "Cannot create unix domain socket");
  2923. return sd;
  2924. }
  2925. void
  2926. socket_bind_unix (socket_descriptor_t sd,
  2927. struct sockaddr_un *local,
  2928. const char *prefix)
  2929. {
  2930. struct gc_arena gc = gc_new ();
  2931. #ifdef HAVE_UMASK
  2932. const mode_t orig_umask = umask (0);
  2933. #endif
  2934. if (bind (sd, (struct sockaddr *) local, sizeof (struct sockaddr_un)))
  2935. {
  2936. const int errnum = openvpn_errno ();
  2937. msg (M_FATAL, "%s: Socket bind[%d] failed on unix domain socket %s: %s",
  2938. prefix,
  2939. (int)sd,
  2940. sockaddr_unix_name (local, "NULL"),
  2941. strerror_ts (errnum, &gc));
  2942. }
  2943. #ifdef HAVE_UMASK
  2944. umask (orig_umask);
  2945. #endif
  2946. gc_free (&gc);
  2947. }
  2948. socket_descriptor_t
  2949. socket_accept_unix (socket_descriptor_t sd,
  2950. struct sockaddr_un *remote)
  2951. {
  2952. socklen_t remote_len = sizeof (struct sockaddr_un);
  2953. socket_descriptor_t ret;
  2954. CLEAR (*remote);
  2955. ret = accept (sd, (struct sockaddr *) remote, &remote_len);
  2956. return ret;
  2957. }
  2958. int
  2959. socket_connect_unix (socket_descriptor_t sd,
  2960. struct sockaddr_un *remote)
  2961. {
  2962. int status = connect (sd, (struct sockaddr *) remote, sizeof (struct sockaddr_un));
  2963. if (status)
  2964. status = openvpn_errno ();
  2965. return status;
  2966. }
  2967. void
  2968. sockaddr_unix_init (struct sockaddr_un *local, const char *path)
  2969. {
  2970. local->sun_family = PF_UNIX;
  2971. strncpynt (local->sun_path, path, sizeof (local->sun_path));
  2972. }
  2973. void
  2974. socket_delete_unix (const struct sockaddr_un *local)
  2975. {
  2976. const char *name = sockaddr_unix_name (local, NULL);
  2977. #ifdef HAVE_UNLINK
  2978. if (name && strlen (name))
  2979. unlink (name);
  2980. #endif
  2981. }
  2982. bool
  2983. unix_socket_get_peer_uid_gid (const socket_descriptor_t sd, int *uid, int *gid)
  2984. {
  2985. #ifdef HAVE_GETPEEREID
  2986. uid_t u;
  2987. gid_t g;
  2988. if (getpeereid (sd, &u, &g) == -1)
  2989. return false;
  2990. if (uid)
  2991. *uid = u;
  2992. if (gid)
  2993. *gid = g;
  2994. return true;
  2995. #elif defined(SO_PEERCRED)
  2996. struct ucred peercred;
  2997. socklen_t so_len = sizeof(peercred);
  2998. if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
  2999. return false;
  3000. if (uid)
  3001. *uid = peercred.uid;
  3002. if (gid)
  3003. *gid = peercred.gid;
  3004. return true;
  3005. #else
  3006. return false;
  3007. #endif
  3008. }
  3009. #endif