PageRenderTime 51ms CodeModel.GetById 16ms 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

Large files files are truncated, but you can click here to view the full file

  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. overl

Large files files are truncated, but you can click here to view the full file