PageRenderTime 75ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/socket.c

https://github.com/gonzopancho/android-external-openvpn
C | 2784 lines | 2259 code | 333 blank | 192 comment | 427 complexity | 44f324e1ccb6bd778bc2e67431f4b7ef 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-2009 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. #include "syshead.h"
  25. #include "socket.h"
  26. #include "fdmisc.h"
  27. #include "thread.h"
  28. #include "misc.h"
  29. #include "gremlin.h"
  30. #include "plugin.h"
  31. #include "ps.h"
  32. #include "manage.h"
  33. #include "misc.h"
  34. #include "memdbg.h"
  35. const int proto_overhead[] = { /* indexed by PROTO_x */
  36. IPv4_UDP_HEADER_SIZE,
  37. IPv4_TCP_HEADER_SIZE,
  38. IPv4_TCP_HEADER_SIZE,
  39. IPv4_TCP_HEADER_SIZE
  40. };
  41. /*
  42. * Convert sockflags/getaddr_flags into getaddr_flags
  43. */
  44. static unsigned int
  45. sf2gaf(const unsigned int getaddr_flags,
  46. const unsigned int sockflags)
  47. {
  48. if (sockflags & SF_HOST_RANDOMIZE)
  49. return getaddr_flags | GETADDR_RANDOMIZE;
  50. else
  51. return getaddr_flags;
  52. }
  53. /*
  54. * Functions related to the translation of DNS names to IP addresses.
  55. */
  56. static const char*
  57. h_errno_msg(int h_errno_err)
  58. {
  59. switch (h_errno_err)
  60. {
  61. case HOST_NOT_FOUND:
  62. return "[HOST_NOT_FOUND] The specified host is unknown.";
  63. case NO_DATA:
  64. return "[NO_DATA] The requested name is valid but does not have an IP address.";
  65. case NO_RECOVERY:
  66. return "[NO_RECOVERY] A non-recoverable name server error occurred.";
  67. case TRY_AGAIN:
  68. return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
  69. }
  70. return "[unknown h_errno value]";
  71. }
  72. /*
  73. * Translate IP addr or hostname to in_addr_t.
  74. * If resolve error, try again for
  75. * resolve_retry_seconds seconds.
  76. */
  77. in_addr_t
  78. getaddr (unsigned int flags,
  79. const char *hostname,
  80. int resolve_retry_seconds,
  81. bool *succeeded,
  82. volatile int *signal_received)
  83. {
  84. struct in_addr ia;
  85. int status;
  86. int sigrec = 0;
  87. int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
  88. struct gc_arena gc = gc_new ();
  89. if (flags & GETADDR_RANDOMIZE)
  90. hostname = hostname_randomize(hostname, &gc);
  91. if (flags & GETADDR_MSG_VIRT_OUT)
  92. msglevel |= M_MSG_VIRT_OUT;
  93. CLEAR (ia);
  94. if (succeeded)
  95. *succeeded = false;
  96. if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
  97. && !signal_received)
  98. signal_received = &sigrec;
  99. status = openvpn_inet_aton (hostname, &ia); /* parse ascii IP address */
  100. if (status != OIA_IP) /* parse as IP address failed? */
  101. {
  102. const int fail_wait_interval = 5; /* seconds */
  103. int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
  104. struct hostent *h;
  105. const char *fmt;
  106. int level = 0;
  107. CLEAR (ia);
  108. fmt = "RESOLVE: Cannot resolve host address: %s: %s";
  109. if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
  110. && !resolve_retry_seconds)
  111. fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
  112. if (!(flags & GETADDR_RESOLVE) || status == OIA_ERROR)
  113. {
  114. msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
  115. goto done;
  116. }
  117. #ifdef ENABLE_MANAGEMENT
  118. if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
  119. {
  120. if (management)
  121. management_set_state (management,
  122. OPENVPN_STATE_RESOLVE,
  123. NULL,
  124. (in_addr_t)0,
  125. (in_addr_t)0);
  126. }
  127. #endif
  128. /*
  129. * Resolve hostname
  130. */
  131. while (true)
  132. {
  133. /* try hostname lookup */
  134. #if defined(HAVE_RES_INIT)
  135. res_init ();
  136. #endif
  137. h = gethostbyname (hostname);
  138. if (signal_received)
  139. {
  140. get_signal (signal_received);
  141. if (*signal_received) /* were we interrupted by a signal? */
  142. {
  143. h = NULL;
  144. if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
  145. {
  146. msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
  147. *signal_received = 0;
  148. }
  149. else
  150. goto done;
  151. }
  152. }
  153. /* success? */
  154. if (h)
  155. break;
  156. /* resolve lookup failed, should we
  157. continue or fail? */
  158. level = msglevel;
  159. if (resolve_retries > 0)
  160. level = D_RESOLVE_ERRORS;
  161. msg (level,
  162. fmt,
  163. hostname,
  164. h_errno_msg (h_errno));
  165. if (--resolve_retries <= 0)
  166. goto done;
  167. openvpn_sleep (fail_wait_interval);
  168. }
  169. if (h->h_addrtype != AF_INET || h->h_length != 4)
  170. {
  171. msg (msglevel, "RESOLVE: Sorry, but we only accept IPv4 DNS names: %s", hostname);
  172. goto done;
  173. }
  174. ia.s_addr = *(in_addr_t *) (h->h_addr_list[0]);
  175. if (ia.s_addr)
  176. {
  177. if (h->h_addr_list[1]) /* more than one address returned */
  178. {
  179. int n = 0;
  180. /* count address list */
  181. while (h->h_addr_list[n])
  182. ++n;
  183. ASSERT (n >= 2);
  184. msg (D_RESOLVE_ERRORS, "RESOLVE: NOTE: %s resolves to %d addresses, choosing one by random",
  185. hostname,
  186. n);
  187. /* choose address randomly, for basic load-balancing capability */
  188. ia.s_addr = *(in_addr_t *) (h->h_addr_list[get_random () % n]);
  189. }
  190. }
  191. /* hostname resolve succeeded */
  192. if (succeeded)
  193. *succeeded = true;
  194. }
  195. else
  196. {
  197. /* IP address parse succeeded */
  198. if (succeeded)
  199. *succeeded = true;
  200. }
  201. done:
  202. if (signal_received && *signal_received)
  203. {
  204. int level = 0;
  205. if (flags & GETADDR_FATAL_ON_SIGNAL)
  206. level = M_FATAL;
  207. else if (flags & GETADDR_WARN_ON_SIGNAL)
  208. level = M_WARN;
  209. msg (level, "RESOLVE: signal received during DNS resolution attempt");
  210. }
  211. gc_free (&gc);
  212. return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
  213. }
  214. /*
  215. * We do our own inet_aton because the glibc function
  216. * isn't very good about error checking.
  217. */
  218. int
  219. openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
  220. {
  221. unsigned int a, b, c, d;
  222. CLEAR (*addr);
  223. if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
  224. {
  225. if (a < 256 && b < 256 && c < 256 && d < 256)
  226. {
  227. addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
  228. return OIA_IP; /* good dotted quad */
  229. }
  230. }
  231. if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
  232. return OIA_ERROR; /* probably a badly formatted dotted quad */
  233. else
  234. return OIA_HOSTNAME; /* probably a hostname */
  235. }
  236. bool
  237. ip_addr_dotted_quad_safe (const char *dotted_quad)
  238. {
  239. /* verify non-NULL */
  240. if (!dotted_quad)
  241. return false;
  242. /* verify length is within limits */
  243. if (strlen (dotted_quad) > 15)
  244. return false;
  245. /* verify that all chars are either numeric or '.' and that no numeric
  246. substring is greater than 3 chars */
  247. {
  248. int nnum = 0;
  249. const char *p = dotted_quad;
  250. int c;
  251. while ((c = *p++))
  252. {
  253. if (c >= '0' && c <= '9')
  254. {
  255. ++nnum;
  256. if (nnum > 3)
  257. return false;
  258. }
  259. else if (c == '.')
  260. {
  261. nnum = 0;
  262. }
  263. else
  264. return false;
  265. }
  266. }
  267. /* verify that string will convert to IP address */
  268. {
  269. struct in_addr a;
  270. return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
  271. }
  272. }
  273. static bool
  274. dns_addr_safe (const char *addr)
  275. {
  276. if (addr)
  277. {
  278. const size_t len = strlen (addr);
  279. return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
  280. }
  281. else
  282. return false;
  283. }
  284. bool
  285. ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
  286. {
  287. if (ip_addr_dotted_quad_safe (addr))
  288. return true;
  289. else if (allow_fqdn)
  290. return dns_addr_safe (addr);
  291. else
  292. return false;
  293. }
  294. bool
  295. mac_addr_safe (const char *mac_addr)
  296. {
  297. /* verify non-NULL */
  298. if (!mac_addr)
  299. return false;
  300. /* verify length is within limits */
  301. if (strlen (mac_addr) > 17)
  302. return false;
  303. /* verify that all chars are either alphanumeric or ':' and that no
  304. alphanumeric substring is greater than 2 chars */
  305. {
  306. int nnum = 0;
  307. const char *p = mac_addr;
  308. int c;
  309. while ((c = *p++))
  310. {
  311. if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
  312. {
  313. ++nnum;
  314. if (nnum > 2)
  315. return false;
  316. }
  317. else if (c == ':')
  318. {
  319. nnum = 0;
  320. }
  321. else
  322. return false;
  323. }
  324. }
  325. /* error-checking is left to script invoked in lladdr.c */
  326. return true;
  327. }
  328. static void
  329. update_remote (const char* host,
  330. struct openvpn_sockaddr *addr,
  331. bool *changed,
  332. const unsigned int sockflags)
  333. {
  334. if (host && addr)
  335. {
  336. const in_addr_t new_addr = getaddr (
  337. sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
  338. host,
  339. 1,
  340. NULL,
  341. NULL);
  342. if (new_addr && addr->sa.sin_addr.s_addr != new_addr)
  343. {
  344. addr->sa.sin_addr.s_addr = new_addr;
  345. *changed = true;
  346. }
  347. }
  348. }
  349. static int
  350. socket_get_sndbuf (int sd)
  351. {
  352. #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
  353. int val;
  354. socklen_t len;
  355. len = sizeof (val);
  356. if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
  357. && len == sizeof (val))
  358. return val;
  359. #endif
  360. return 0;
  361. }
  362. static void
  363. socket_set_sndbuf (int sd, int size)
  364. {
  365. #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
  366. if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
  367. {
  368. if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
  369. {
  370. msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
  371. }
  372. }
  373. #endif
  374. }
  375. static int
  376. socket_get_rcvbuf (int sd)
  377. {
  378. #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
  379. int val;
  380. socklen_t len;
  381. len = sizeof (val);
  382. if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
  383. && len == sizeof (val))
  384. return val;
  385. #endif
  386. return 0;
  387. }
  388. static bool
  389. socket_set_rcvbuf (int sd, int size)
  390. {
  391. #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
  392. if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
  393. {
  394. if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
  395. {
  396. msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
  397. return false;
  398. }
  399. }
  400. return true;
  401. #endif
  402. }
  403. static void
  404. socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
  405. {
  406. if (sbs)
  407. {
  408. const int sndbuf_old = socket_get_sndbuf (fd);
  409. const int rcvbuf_old = socket_get_rcvbuf (fd);
  410. if (sbs->sndbuf)
  411. socket_set_sndbuf (fd, sbs->sndbuf);
  412. if (sbs->rcvbuf)
  413. socket_set_rcvbuf (fd, sbs->rcvbuf);
  414. msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
  415. rcvbuf_old,
  416. socket_get_rcvbuf (fd),
  417. sndbuf_old,
  418. socket_get_sndbuf (fd));
  419. }
  420. }
  421. /*
  422. * Set other socket options
  423. */
  424. static bool
  425. socket_set_tcp_nodelay (int sd, int state)
  426. {
  427. #if defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY)
  428. if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
  429. {
  430. msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
  431. return false;
  432. }
  433. else
  434. {
  435. dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
  436. return true;
  437. }
  438. #else
  439. msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
  440. return false;
  441. #endif
  442. }
  443. static bool
  444. socket_set_flags (int sd, unsigned int sockflags)
  445. {
  446. if (sockflags & SF_TCP_NODELAY)
  447. return socket_set_tcp_nodelay (sd, 1);
  448. else
  449. return true;
  450. }
  451. bool
  452. link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
  453. {
  454. if (ls && socket_defined (ls->sd))
  455. return socket_set_flags (ls->sd, ls->sockflags = sockflags);
  456. else
  457. return false;
  458. }
  459. void
  460. link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
  461. {
  462. if (ls && socket_defined (ls->sd))
  463. {
  464. ls->socket_buffer_sizes.sndbuf = sndbuf;
  465. ls->socket_buffer_sizes.rcvbuf = rcvbuf;
  466. socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
  467. }
  468. }
  469. /*
  470. * SOCKET INITALIZATION CODE.
  471. * Create a TCP/UDP socket
  472. */
  473. socket_descriptor_t
  474. create_socket_tcp (void)
  475. {
  476. socket_descriptor_t sd;
  477. if ((sd = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
  478. msg (M_SOCKERR, "Cannot create TCP socket");
  479. #ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
  480. /* set SO_REUSEADDR on socket */
  481. {
  482. int on = 1;
  483. if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
  484. (void *) &on, sizeof (on)) < 0)
  485. msg (M_SOCKERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
  486. }
  487. #endif
  488. #if 0
  489. /* set socket linger options */
  490. {
  491. struct linger linger;
  492. linger.l_onoff = 1;
  493. linger.l_linger = 2;
  494. if (setsockopt (sd, SOL_SOCKET, SO_LINGER,
  495. (void *) &linger, sizeof (linger)) < 0)
  496. msg (M_SOCKERR, "TCP: Cannot setsockopt SO_LINGER on TCP socket");
  497. }
  498. #endif
  499. return sd;
  500. }
  501. static socket_descriptor_t
  502. create_socket_udp (const unsigned int flags)
  503. {
  504. socket_descriptor_t sd;
  505. if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
  506. msg (M_SOCKERR, "UDP: Cannot create UDP socket");
  507. #if ENABLE_IP_PKTINFO
  508. else if (flags & SF_USE_IP_PKTINFO)
  509. {
  510. int pad = 1;
  511. setsockopt (sd, SOL_IP, IP_PKTINFO, (void*)&pad, sizeof(pad));
  512. }
  513. #endif
  514. return sd;
  515. }
  516. static void
  517. create_socket (struct link_socket *sock)
  518. {
  519. /* create socket */
  520. if (sock->info.proto == PROTO_UDPv4)
  521. {
  522. sock->sd = create_socket_udp (sock->sockflags);
  523. #ifdef ENABLE_SOCKS
  524. if (sock->socks_proxy)
  525. sock->ctrl_sd = create_socket_tcp ();
  526. #endif
  527. }
  528. else if (sock->info.proto == PROTO_TCPv4_SERVER
  529. || sock->info.proto == PROTO_TCPv4_CLIENT)
  530. {
  531. sock->sd = create_socket_tcp ();
  532. }
  533. else
  534. {
  535. ASSERT (0);
  536. }
  537. }
  538. /*
  539. * Functions used for establishing a TCP stream connection.
  540. */
  541. static void
  542. socket_do_listen (socket_descriptor_t sd,
  543. const struct openvpn_sockaddr *local,
  544. bool do_listen,
  545. bool do_set_nonblock)
  546. {
  547. struct gc_arena gc = gc_new ();
  548. if (do_listen)
  549. {
  550. msg (M_INFO, "Listening for incoming TCP connection on %s",
  551. print_sockaddr (local, &gc));
  552. if (listen (sd, 1))
  553. msg (M_SOCKERR, "TCP: listen() failed");
  554. }
  555. /* set socket to non-blocking mode */
  556. if (do_set_nonblock)
  557. set_nonblock (sd);
  558. gc_free (&gc);
  559. }
  560. socket_descriptor_t
  561. socket_do_accept (socket_descriptor_t sd,
  562. struct link_socket_actual *act,
  563. const bool nowait)
  564. {
  565. socklen_t remote_len = sizeof (act->dest.sa);
  566. socket_descriptor_t new_sd = SOCKET_UNDEFINED;
  567. CLEAR (*act);
  568. #ifdef HAVE_GETPEERNAME
  569. if (nowait)
  570. {
  571. new_sd = getpeername (sd, (struct sockaddr *) &act->dest.sa, &remote_len);
  572. if (!socket_defined (new_sd))
  573. msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: getpeername() failed");
  574. else
  575. new_sd = sd;
  576. }
  577. #else
  578. if (nowait)
  579. msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
  580. #endif
  581. else
  582. {
  583. new_sd = accept (sd, (struct sockaddr *) &act->dest.sa, &remote_len);
  584. }
  585. #if 0 /* For debugging only, test the effect of accept() failures */
  586. {
  587. static int foo = 0;
  588. ++foo;
  589. if (foo & 1)
  590. new_sd = -1;
  591. }
  592. #endif
  593. if (!socket_defined (new_sd))
  594. {
  595. msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: accept(%d) failed", sd);
  596. }
  597. else if (remote_len != sizeof (act->dest.sa))
  598. {
  599. msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
  600. openvpn_close_socket (new_sd);
  601. new_sd = SOCKET_UNDEFINED;
  602. }
  603. return new_sd;
  604. }
  605. static void
  606. tcp_connection_established (const struct link_socket_actual *act)
  607. {
  608. struct gc_arena gc = gc_new ();
  609. msg (M_INFO, "TCP connection established with %s",
  610. print_link_socket_actual (act, &gc));
  611. gc_free (&gc);
  612. }
  613. static int
  614. socket_listen_accept (socket_descriptor_t sd,
  615. struct link_socket_actual *act,
  616. const char *remote_dynamic,
  617. bool *remote_changed,
  618. const struct openvpn_sockaddr *local,
  619. bool do_listen,
  620. bool nowait,
  621. volatile int *signal_received)
  622. {
  623. struct gc_arena gc = gc_new ();
  624. /* struct openvpn_sockaddr *remote = &act->dest; */
  625. struct openvpn_sockaddr remote_verify = act->dest;
  626. int new_sd = SOCKET_UNDEFINED;
  627. CLEAR (*act);
  628. socket_do_listen (sd, local, do_listen, true);
  629. while (true)
  630. {
  631. int status;
  632. fd_set reads;
  633. struct timeval tv;
  634. FD_ZERO (&reads);
  635. FD_SET (sd, &reads);
  636. tv.tv_sec = 0;
  637. tv.tv_usec = 0;
  638. status = select (sd + 1, &reads, NULL, NULL, &tv);
  639. get_signal (signal_received);
  640. if (*signal_received)
  641. {
  642. gc_free (&gc);
  643. return sd;
  644. }
  645. if (status < 0)
  646. msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: select() failed");
  647. if (status <= 0)
  648. {
  649. openvpn_sleep (1);
  650. continue;
  651. }
  652. new_sd = socket_do_accept (sd, act, nowait);
  653. if (socket_defined (new_sd))
  654. {
  655. update_remote (remote_dynamic, &remote_verify, remote_changed, 0);
  656. if (addr_defined (&remote_verify)
  657. && !addr_match (&remote_verify, &act->dest))
  658. {
  659. msg (M_WARN,
  660. "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
  661. print_link_socket_actual (act, &gc));
  662. if (openvpn_close_socket (new_sd))
  663. msg (M_SOCKERR, "TCP: close socket failed (new_sd)");
  664. }
  665. else
  666. break;
  667. }
  668. openvpn_sleep (1);
  669. }
  670. if (!nowait && openvpn_close_socket (sd))
  671. msg (M_SOCKERR, "TCP: close socket failed (sd)");
  672. tcp_connection_established (act);
  673. gc_free (&gc);
  674. return new_sd;
  675. }
  676. void
  677. socket_bind (socket_descriptor_t sd,
  678. struct openvpn_sockaddr *local,
  679. const char *prefix)
  680. {
  681. struct gc_arena gc = gc_new ();
  682. if (bind (sd, (struct sockaddr *) &local->sa, sizeof (local->sa)))
  683. {
  684. const int errnum = openvpn_errno_socket ();
  685. msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
  686. prefix,
  687. print_sockaddr (local, &gc),
  688. strerror_ts (errnum, &gc));
  689. }
  690. gc_free (&gc);
  691. }
  692. int
  693. openvpn_connect (socket_descriptor_t sd,
  694. struct openvpn_sockaddr *remote,
  695. int connect_timeout,
  696. volatile int *signal_received)
  697. {
  698. int status = 0;
  699. #ifdef CONNECT_NONBLOCK
  700. set_nonblock (sd);
  701. status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
  702. if (status)
  703. status = openvpn_errno_socket ();
  704. if (status == EINPROGRESS)
  705. {
  706. while (true)
  707. {
  708. fd_set writes;
  709. struct timeval tv;
  710. FD_ZERO (&writes);
  711. FD_SET (sd, &writes);
  712. tv.tv_sec = 0;
  713. tv.tv_usec = 0;
  714. status = select (sd + 1, NULL, &writes, NULL, &tv);
  715. if (signal_received)
  716. {
  717. get_signal (signal_received);
  718. if (*signal_received)
  719. {
  720. status = 0;
  721. break;
  722. }
  723. }
  724. if (status < 0)
  725. {
  726. status = openvpn_errno_socket ();
  727. break;
  728. }
  729. if (status <= 0)
  730. {
  731. if (--connect_timeout < 0)
  732. {
  733. status = ETIMEDOUT;
  734. break;
  735. }
  736. openvpn_sleep (1);
  737. continue;
  738. }
  739. /* got it */
  740. {
  741. int val = 0;
  742. socklen_t len;
  743. len = sizeof (val);
  744. if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
  745. && len == sizeof (val))
  746. status = val;
  747. else
  748. status = openvpn_errno_socket ();
  749. break;
  750. }
  751. }
  752. }
  753. #else
  754. status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
  755. if (status)
  756. status = openvpn_errno_socket ();
  757. #endif
  758. return status;
  759. }
  760. void
  761. socket_connect (socket_descriptor_t *sd,
  762. struct openvpn_sockaddr *local,
  763. bool bind_local,
  764. struct openvpn_sockaddr *remote,
  765. const bool connection_profiles_defined,
  766. const char *remote_dynamic,
  767. bool *remote_changed,
  768. const int connect_retry_seconds,
  769. const int connect_timeout,
  770. const int connect_retry_max,
  771. const unsigned int sockflags,
  772. volatile int *signal_received)
  773. {
  774. struct gc_arena gc = gc_new ();
  775. int retry = 0;
  776. #ifdef CONNECT_NONBLOCK
  777. msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
  778. print_sockaddr (remote, &gc));
  779. #else
  780. msg (M_INFO, "Attempting to establish TCP connection with %s",
  781. print_sockaddr (remote, &gc));
  782. #endif
  783. while (true)
  784. {
  785. int status;
  786. #ifdef ENABLE_MANAGEMENT
  787. if (management)
  788. management_set_state (management,
  789. OPENVPN_STATE_TCP_CONNECT,
  790. NULL,
  791. (in_addr_t)0,
  792. (in_addr_t)0);
  793. #endif
  794. status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
  795. get_signal (signal_received);
  796. if (*signal_received)
  797. goto done;
  798. if (!status)
  799. break;
  800. msg (D_LINK_ERRORS,
  801. "TCP: connect to %s failed, will try again in %d seconds: %s",
  802. print_sockaddr (remote, &gc),
  803. connect_retry_seconds,
  804. strerror_ts (status, &gc));
  805. gc_reset (&gc);
  806. openvpn_close_socket (*sd);
  807. *sd = SOCKET_UNDEFINED;
  808. if ((connect_retry_max > 0 && ++retry >= connect_retry_max) || connection_profiles_defined)
  809. {
  810. *signal_received = SIGUSR1;
  811. goto done;
  812. }
  813. openvpn_sleep (connect_retry_seconds);
  814. get_signal (signal_received);
  815. if (*signal_received)
  816. goto done;
  817. *sd = create_socket_tcp ();
  818. if (bind_local)
  819. socket_bind (*sd, local, "TCP Client");
  820. update_remote (remote_dynamic, remote, remote_changed, sockflags);
  821. }
  822. msg (M_INFO, "TCP connection established with %s",
  823. print_sockaddr (remote, &gc));
  824. done:
  825. gc_free (&gc);
  826. }
  827. /* For stream protocols, allocate a buffer to build up packet.
  828. Called after frame has been finalized. */
  829. static void
  830. socket_frame_init (const struct frame *frame, struct link_socket *sock)
  831. {
  832. #ifdef WIN32
  833. overlapped_io_init (&sock->reads, frame, FALSE, false);
  834. overlapped_io_init (&sock->writes, frame, TRUE, false);
  835. sock->rw_handle.read = sock->reads.overlapped.hEvent;
  836. sock->rw_handle.write = sock->writes.overlapped.hEvent;
  837. #endif
  838. if (link_socket_connection_oriented (sock))
  839. {
  840. #ifdef WIN32
  841. stream_buf_init (&sock->stream_buf,
  842. &sock->reads.buf_init,
  843. sock->sockflags,
  844. sock->info.proto);
  845. #else
  846. alloc_buf_sock_tun (&sock->stream_buf_data,
  847. frame,
  848. false,
  849. FRAME_HEADROOM_MARKER_READ_STREAM);
  850. stream_buf_init (&sock->stream_buf,
  851. &sock->stream_buf_data,
  852. sock->sockflags,
  853. sock->info.proto);
  854. #endif
  855. }
  856. }
  857. /*
  858. * Adjust frame structure based on a Path MTU value given
  859. * to us by the OS.
  860. */
  861. void
  862. frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
  863. {
  864. frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
  865. }
  866. static void
  867. resolve_bind_local (struct link_socket *sock)
  868. {
  869. struct gc_arena gc = gc_new ();
  870. /* resolve local address if undefined */
  871. if (!addr_defined (&sock->info.lsa->local))
  872. {
  873. sock->info.lsa->local.sa.sin_family = AF_INET;
  874. sock->info.lsa->local.sa.sin_addr.s_addr =
  875. (sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
  876. sock->local_host,
  877. 0,
  878. NULL,
  879. NULL)
  880. : htonl (INADDR_ANY));
  881. sock->info.lsa->local.sa.sin_port = htons (sock->local_port);
  882. }
  883. /* bind to local address/port */
  884. if (sock->bind_local)
  885. {
  886. #ifdef ENABLE_SOCKS
  887. if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
  888. socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
  889. else
  890. #endif
  891. socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
  892. }
  893. gc_free (&gc);
  894. }
  895. static void
  896. resolve_remote (struct link_socket *sock,
  897. int phase,
  898. const char **remote_dynamic,
  899. volatile int *signal_received)
  900. {
  901. struct gc_arena gc = gc_new ();
  902. if (!sock->did_resolve_remote)
  903. {
  904. /* resolve remote address if undefined */
  905. if (!addr_defined (&sock->info.lsa->remote))
  906. {
  907. sock->info.lsa->remote.sa.sin_family = AF_INET;
  908. sock->info.lsa->remote.sa.sin_addr.s_addr = 0;
  909. if (sock->remote_host)
  910. {
  911. unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
  912. int retry = 0;
  913. bool status = false;
  914. if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
  915. {
  916. if (phase == 2)
  917. flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
  918. retry = 0;
  919. }
  920. else if (phase == 1)
  921. {
  922. if (sock->resolve_retry_seconds)
  923. {
  924. retry = 0;
  925. }
  926. else
  927. {
  928. flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
  929. retry = 0;
  930. }
  931. }
  932. else if (phase == 2)
  933. {
  934. if (sock->resolve_retry_seconds)
  935. {
  936. flags |= GETADDR_FATAL;
  937. retry = sock->resolve_retry_seconds;
  938. }
  939. else
  940. {
  941. ASSERT (0);
  942. }
  943. }
  944. else
  945. {
  946. ASSERT (0);
  947. }
  948. sock->info.lsa->remote.sa.sin_addr.s_addr = getaddr (
  949. flags,
  950. sock->remote_host,
  951. retry,
  952. &status,
  953. signal_received);
  954. dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
  955. flags,
  956. phase,
  957. retry,
  958. signal_received ? *signal_received : -1,
  959. status);
  960. if (signal_received)
  961. {
  962. if (*signal_received)
  963. goto done;
  964. }
  965. if (!status)
  966. {
  967. if (signal_received)
  968. *signal_received = SIGUSR1;
  969. goto done;
  970. }
  971. }
  972. sock->info.lsa->remote.sa.sin_port = htons (sock->remote_port);
  973. }
  974. /* should we re-use previous active remote address? */
  975. if (link_socket_actual_defined (&sock->info.lsa->actual))
  976. {
  977. msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
  978. print_link_socket_actual (&sock->info.lsa->actual, &gc));
  979. if (remote_dynamic)
  980. *remote_dynamic = NULL;
  981. }
  982. else
  983. {
  984. CLEAR (sock->info.lsa->actual);
  985. sock->info.lsa->actual.dest = sock->info.lsa->remote;
  986. }
  987. /* remember that we finished */
  988. sock->did_resolve_remote = true;
  989. }
  990. done:
  991. gc_free (&gc);
  992. }
  993. struct link_socket *
  994. link_socket_new (void)
  995. {
  996. struct link_socket *sock;
  997. ALLOC_OBJ_CLEAR (sock, struct link_socket);
  998. sock->sd = SOCKET_UNDEFINED;
  999. #ifdef ENABLE_SOCKS
  1000. sock->ctrl_sd = SOCKET_UNDEFINED;
  1001. #endif
  1002. return sock;
  1003. }
  1004. /* bind socket if necessary */
  1005. void
  1006. link_socket_init_phase1 (struct link_socket *sock,
  1007. const bool connection_profiles_defined,
  1008. const char *local_host,
  1009. int local_port,
  1010. const char *remote_host,
  1011. int remote_port,
  1012. int proto,
  1013. int mode,
  1014. const struct link_socket *accept_from,
  1015. #ifdef ENABLE_HTTP_PROXY
  1016. struct http_proxy_info *http_proxy,
  1017. #endif
  1018. #ifdef ENABLE_SOCKS
  1019. struct socks_proxy_info *socks_proxy,
  1020. #endif
  1021. #ifdef ENABLE_DEBUG
  1022. int gremlin,
  1023. #endif
  1024. bool bind_local,
  1025. bool remote_float,
  1026. int inetd,
  1027. struct link_socket_addr *lsa,
  1028. const char *ipchange_command,
  1029. const struct plugin_list *plugins,
  1030. int resolve_retry_seconds,
  1031. int connect_retry_seconds,
  1032. int connect_timeout,
  1033. int connect_retry_max,
  1034. int mtu_discover_type,
  1035. int rcvbuf,
  1036. int sndbuf,
  1037. unsigned int sockflags)
  1038. {
  1039. ASSERT (sock);
  1040. sock->connection_profiles_defined = connection_profiles_defined;
  1041. sock->local_host = local_host;
  1042. sock->local_port = local_port;
  1043. sock->remote_host = remote_host;
  1044. sock->remote_port = remote_port;
  1045. #ifdef ENABLE_HTTP_PROXY
  1046. sock->http_proxy = http_proxy;
  1047. #endif
  1048. #ifdef ENABLE_SOCKS
  1049. sock->socks_proxy = socks_proxy;
  1050. #endif
  1051. sock->bind_local = bind_local;
  1052. sock->inetd = inetd;
  1053. sock->resolve_retry_seconds = resolve_retry_seconds;
  1054. sock->connect_retry_seconds = connect_retry_seconds;
  1055. sock->connect_timeout = connect_timeout;
  1056. sock->connect_retry_max = connect_retry_max;
  1057. sock->mtu_discover_type = mtu_discover_type;
  1058. #ifdef ENABLE_DEBUG
  1059. sock->gremlin = gremlin;
  1060. #endif
  1061. sock->socket_buffer_sizes.rcvbuf = rcvbuf;
  1062. sock->socket_buffer_sizes.sndbuf = sndbuf;
  1063. sock->sockflags = sockflags;
  1064. sock->info.proto = proto;
  1065. sock->info.remote_float = remote_float;
  1066. sock->info.lsa = lsa;
  1067. sock->info.ipchange_command = ipchange_command;
  1068. sock->info.plugins = plugins;
  1069. sock->mode = mode;
  1070. if (mode == LS_MODE_TCP_ACCEPT_FROM)
  1071. {
  1072. ASSERT (accept_from);
  1073. ASSERT (sock->info.proto == PROTO_TCPv4_SERVER);
  1074. ASSERT (!sock->inetd);
  1075. sock->sd = accept_from->sd;
  1076. }
  1077. if (false)
  1078. ;
  1079. #ifdef ENABLE_HTTP_PROXY
  1080. /* are we running in HTTP proxy mode? */
  1081. else if (sock->http_proxy)
  1082. {
  1083. ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
  1084. ASSERT (!sock->inetd);
  1085. /* the proxy server */
  1086. sock->remote_host = http_proxy->options.server;
  1087. sock->remote_port = http_proxy->options.port;
  1088. /* the OpenVPN server we will use the proxy to connect to */
  1089. sock->proxy_dest_host = remote_host;
  1090. sock->proxy_dest_port = remote_port;
  1091. }
  1092. #endif
  1093. #ifdef ENABLE_SOCKS
  1094. /* or in Socks proxy mode? */
  1095. else if (sock->socks_proxy)
  1096. {
  1097. ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
  1098. ASSERT (!sock->inetd);
  1099. /* the proxy server */
  1100. sock->remote_host = socks_proxy->server;
  1101. sock->remote_port = socks_proxy->port;
  1102. /* the OpenVPN server we will use the proxy to connect to */
  1103. sock->proxy_dest_host = remote_host;
  1104. sock->proxy_dest_port = remote_port;
  1105. }
  1106. #endif
  1107. else
  1108. {
  1109. sock->remote_host = remote_host;
  1110. sock->remote_port = remote_port;
  1111. }
  1112. /* bind behavior for TCP server vs. client */
  1113. if (sock->info.proto == PROTO_TCPv4_SERVER)
  1114. {
  1115. if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
  1116. sock->bind_local = false;
  1117. else
  1118. sock->bind_local = true;
  1119. }
  1120. /* were we started by inetd or xinetd? */
  1121. if (sock->inetd)
  1122. {
  1123. ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT);
  1124. ASSERT (socket_defined (inetd_socket_descriptor));
  1125. sock->sd = inetd_socket_descriptor;
  1126. }
  1127. else if (mode != LS_MODE_TCP_ACCEPT_FROM)
  1128. {
  1129. create_socket (sock);
  1130. resolve_bind_local (sock);
  1131. resolve_remote (sock, 1, NULL, NULL);
  1132. }
  1133. }
  1134. /* finalize socket initialization */
  1135. void
  1136. link_socket_init_phase2 (struct link_socket *sock,
  1137. const struct frame *frame,
  1138. volatile int *signal_received)
  1139. {
  1140. struct gc_arena gc = gc_new ();
  1141. const char *remote_dynamic = NULL;
  1142. bool remote_changed = false;
  1143. int sig_save = 0;
  1144. ASSERT (sock);
  1145. if (signal_received && *signal_received)
  1146. {
  1147. sig_save = *signal_received;
  1148. *signal_received = 0;
  1149. }
  1150. /* initialize buffers */
  1151. socket_frame_init (frame, sock);
  1152. /*
  1153. * Pass a remote name to connect/accept so that
  1154. * they can test for dynamic IP address changes
  1155. * and throw a SIGUSR1 if appropriate.
  1156. */
  1157. if (sock->resolve_retry_seconds)
  1158. remote_dynamic = sock->remote_host;
  1159. /* were we started by inetd or xinetd? */
  1160. if (sock->inetd)
  1161. {
  1162. if (sock->info.proto == PROTO_TCPv4_SERVER)
  1163. sock->sd =
  1164. socket_listen_accept (sock->sd,
  1165. &sock->info.lsa->actual,
  1166. remote_dynamic,
  1167. &remote_changed,
  1168. &sock->info.lsa->local,
  1169. false,
  1170. sock->inetd == INETD_NOWAIT,
  1171. signal_received);
  1172. ASSERT (!remote_changed);
  1173. if (*signal_received)
  1174. goto done;
  1175. }
  1176. else
  1177. {
  1178. resolve_remote (sock, 2, &remote_dynamic, signal_received);
  1179. if (*signal_received)
  1180. goto done;
  1181. /* TCP client/server */
  1182. if (sock->info.proto == PROTO_TCPv4_SERVER)
  1183. {
  1184. switch (sock->mode)
  1185. {
  1186. case LS_MODE_DEFAULT:
  1187. sock->sd = socket_listen_accept (sock->sd,
  1188. &sock->info.lsa->actual,
  1189. remote_dynamic,
  1190. &remote_changed,
  1191. &sock->info.lsa->local,
  1192. true,
  1193. false,
  1194. signal_received);
  1195. break;
  1196. case LS_MODE_TCP_LISTEN:
  1197. socket_do_listen (sock->sd,
  1198. &sock->info.lsa->local,
  1199. true,
  1200. false);
  1201. break;
  1202. case LS_MODE_TCP_ACCEPT_FROM:
  1203. sock->sd = socket_do_accept (sock->sd,
  1204. &sock->info.lsa->actual,
  1205. false);
  1206. if (!socket_defined (sock->sd))
  1207. {
  1208. *signal_received = SIGTERM;
  1209. goto done;
  1210. }
  1211. tcp_connection_established (&sock->info.lsa->actual);
  1212. break;
  1213. default:
  1214. ASSERT (0);
  1215. }
  1216. }
  1217. else if (sock->info.proto == PROTO_TCPv4_CLIENT)
  1218. {
  1219. #ifdef GENERAL_PROXY_SUPPORT
  1220. bool proxy_retry = false;
  1221. #else
  1222. const bool proxy_retry = false;
  1223. #endif
  1224. do {
  1225. socket_connect (&sock->sd,
  1226. &sock->info.lsa->local,
  1227. sock->bind_local,
  1228. &sock->info.lsa->actual.dest,
  1229. sock->connection_profiles_defined,
  1230. remote_dynamic,
  1231. &remote_changed,
  1232. sock->connect_retry_seconds,
  1233. sock->connect_timeout,
  1234. sock->connect_retry_max,
  1235. sock->sockflags,
  1236. signal_received);
  1237. if (*signal_received)
  1238. goto done;
  1239. if (false)
  1240. ;
  1241. #ifdef ENABLE_HTTP_PROXY
  1242. else if (sock->http_proxy)
  1243. {
  1244. proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
  1245. sock->sd,
  1246. sock->proxy_dest_host,
  1247. sock->proxy_dest_port,
  1248. &sock->stream_buf.residual,
  1249. signal_received);
  1250. }
  1251. #endif
  1252. #ifdef ENABLE_SOCKS
  1253. else if (sock->socks_proxy)
  1254. {
  1255. establish_socks_proxy_passthru (sock->socks_proxy,
  1256. sock->sd,
  1257. sock->proxy_dest_host,
  1258. sock->proxy_dest_port,
  1259. signal_received);
  1260. }
  1261. #endif
  1262. if (proxy_retry)
  1263. {
  1264. openvpn_close_socket (sock->sd);
  1265. sock->sd = create_socket_tcp ();
  1266. }
  1267. } while (proxy_retry);
  1268. }
  1269. #ifdef ENABLE_SOCKS
  1270. else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
  1271. {
  1272. socket_connect (&sock->ctrl_sd,
  1273. &sock->info.lsa->local,
  1274. sock->bind_local,
  1275. &sock->info.lsa->actual.dest,
  1276. sock->connection_profiles_defined,
  1277. remote_dynamic,
  1278. &remote_changed,
  1279. sock->connect_retry_seconds,
  1280. sock->connect_timeout,
  1281. sock->connect_retry_max,
  1282. sock->sockflags,
  1283. signal_received);
  1284. if (*signal_received)
  1285. goto done;
  1286. establish_socks_proxy_udpassoc (sock->socks_proxy,
  1287. sock->ctrl_sd,
  1288. sock->sd,
  1289. &sock->socks_relay.dest,
  1290. signal_received);
  1291. if (*signal_received)
  1292. goto done;
  1293. sock->remote_host = sock->proxy_dest_host;
  1294. sock->remote_port = sock->proxy_dest_port;
  1295. sock->did_resolve_remote = false;
  1296. sock->info.lsa->actual.dest.sa.sin_addr.s_addr = 0;
  1297. sock->info.lsa->remote.sa.sin_addr.s_addr = 0;
  1298. resolve_remote (sock, 1, NULL, signal_received);
  1299. if (*signal_received)
  1300. goto done;
  1301. }
  1302. #endif
  1303. if (*signal_received)
  1304. goto done;
  1305. if (remote_changed)
  1306. {
  1307. msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
  1308. sock->info.lsa->remote.sa.sin_addr.s_addr = sock->info.lsa->actual.dest.sa.sin_addr.s_addr;
  1309. }
  1310. }
  1311. /* set socket buffers based on --sndbuf and --rcvbuf options */
  1312. socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
  1313. /* set misc socket parameters */
  1314. socket_set_flags (sock->sd, sock->sockflags);
  1315. /* set socket to non-blocking mode */
  1316. set_nonblock (sock->sd);
  1317. /* set socket file descriptor to not pass across execs, so that
  1318. scripts don't have access to it */
  1319. set_cloexec (sock->sd);
  1320. #ifdef ENABLE_SOCKS
  1321. if (socket_defined (sock->ctrl_sd))
  1322. set_cloexec (sock->ctrl_sd);
  1323. #endif
  1324. /* set Path MTU discovery options on the socket */
  1325. set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
  1326. #if EXTENDED_SOCKET_ERROR_CAPABILITY
  1327. /* if the OS supports it, enable extended error passing on the socket */
  1328. set_sock_extended_error_passing (sock->sd);
  1329. #endif
  1330. /* print local address */
  1331. if (sock->inetd)
  1332. msg (M_INFO, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
  1333. else
  1334. msg (M_INFO, "%s link local%s: %s",
  1335. proto2ascii (sock->info.proto, true),
  1336. (sock->bind_local ? " (bound)" : ""),
  1337. print_sockaddr_ex (&sock->info.lsa->local, ":", sock->bind_local ? PS_SHOW_PORT : 0, &gc));
  1338. /* print active remote address */
  1339. msg (M_INFO, "%s link remote: %s",
  1340. proto2ascii (sock->info.proto, true),
  1341. print_link_socket_actual_ex (&sock->info.lsa->actual,
  1342. ":",
  1343. PS_SHOW_PORT_IF_DEFINED,
  1344. &gc));
  1345. done:
  1346. if (sig_save && signal_received)
  1347. {
  1348. if (!*signal_received)
  1349. *signal_received = sig_save;
  1350. }
  1351. gc_free (&gc);
  1352. }
  1353. void
  1354. link_socket_close (struct link_socket *sock)
  1355. {
  1356. if (sock)
  1357. {
  1358. #ifdef ENABLE_DEBUG
  1359. const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
  1360. #else
  1361. const int gremlin = 0;
  1362. #endif
  1363. if (socket_defined (sock->sd))
  1364. {
  1365. #ifdef WIN32
  1366. close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
  1367. #endif
  1368. if (!gremlin)
  1369. {
  1370. msg (D_CLOSE, "TCP/UDP: Closing socket");
  1371. if (openvpn_close_socket (sock->sd))
  1372. msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket failed");
  1373. }
  1374. sock->sd = SOCKET_UNDEFINED;
  1375. #ifdef WIN32
  1376. if (!gremlin)
  1377. {
  1378. overlapped_io_close (&sock->reads);
  1379. overlapped_io_close (&sock->writes);
  1380. }
  1381. #endif
  1382. }
  1383. #ifdef ENABLE_SOCKS
  1384. if (socket_defined (sock->ctrl_sd))
  1385. {
  1386. if (openvpn_close_socket (sock->ctrl_sd))
  1387. msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket (ctrl_sd) failed");
  1388. sock->ctrl_sd = SOCKET_UNDEFINED;
  1389. }
  1390. #endif
  1391. stream_buf_close (&sock->stream_buf);
  1392. free_buf (&sock->stream_buf_data);
  1393. if (!gremlin)
  1394. free (sock);
  1395. }
  1396. }
  1397. /* for stream protocols, allow for packet length prefix */
  1398. void
  1399. socket_adjust_frame_parameters (struct frame *frame, int proto)
  1400. {
  1401. if (link_socket_proto_connection_oriented (proto))
  1402. frame_add_to_extra_frame (frame, sizeof (packet_size_type));
  1403. }
  1404. void
  1405. setenv_trusted (struct env_set *es, const struct link_socket_info *info)
  1406. {
  1407. setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
  1408. }
  1409. static void
  1410. ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
  1411. {
  1412. const char *ip = print_sockaddr_ex (&info->lsa->actual.dest, NULL, 0, gc);
  1413. const char *port = print_sockaddr_ex (&info->lsa->actual.dest, NULL, PS_DONT_SHOW_ADDR|PS_SHOW_PORT, gc);
  1414. if (include_cmd)
  1415. argv_printf (argv, "%sc %s %s",
  1416. info->ipchange_command,
  1417. ip,
  1418. port);
  1419. else
  1420. argv_printf (argv, "%s %s",
  1421. ip,
  1422. port);
  1423. }
  1424. void
  1425. link_socket_connection_initiated (const struct buffer *buf,
  1426. struct link_socket_info *info,
  1427. const struct link_socket_actual *act,
  1428. const char *common_name,
  1429. struct env_set *es)
  1430. {
  1431. struct gc_arena gc = gc_new ();
  1432. info->lsa->actual = *act; /* Note: skip this line for --force-dest */
  1433. setenv_trusted (es, info);
  1434. info->connection_established = true;
  1435. /* Print connection initiated message, with common name if available */
  1436. {
  1437. struct buffer out = alloc_buf_gc (256, &gc);
  1438. if (common_name)
  1439. buf_printf (&out, "[%s] ", common_name);
  1440. buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
  1441. msg (M_INFO, "%s", BSTR (&out));
  1442. }
  1443. /* set environmental vars */
  1444. setenv_str (es, "common_name", common_name);
  1445. /* Process --ipchange plugin */
  1446. if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
  1447. {
  1448. struct argv argv = argv_new ();
  1449. ipchange_fmt (false, &argv, info, &gc);
  1450. if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
  1451. msg (M_WARN, "WARNING: ipchange plugin call failed");
  1452. argv_reset (&argv);
  1453. }
  1454. /* Process --ipchange option */
  1455. if (info->ipchange_command)
  1456. {
  1457. struct argv argv = argv_new ();
  1458. setenv_str (es, "script_type", "ipchange");
  1459. ipchange_fmt (true, &argv, info, &gc);
  1460. openvpn_execve_check (&argv, es, S_SCRIPT, "ip-change command failed");
  1461. argv_reset (&argv);
  1462. }
  1463. gc_free (&gc);
  1464. }
  1465. void
  1466. link_socket_bad_incoming_addr (struct buffer *buf,
  1467. const struct link_socket_info *info,
  1468. const struct link_socket_actual *from_addr)
  1469. {
  1470. struct gc_arena gc = gc_new ();
  1471. msg (D_LINK_ERRORS,
  1472. "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
  1473. print_link_socket_actual (from_addr, &gc),
  1474. (int)from_addr->dest.sa.sin_family,
  1475. print_sockaddr (&info->lsa->remote, &gc));
  1476. buf->len = 0;
  1477. gc_free (&gc);
  1478. }
  1479. void
  1480. link_socket_bad_outgoing_addr (void)
  1481. {
  1482. dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
  1483. }
  1484. in_addr_t
  1485. link_socket_current_remote (const struct link_socket_info *info)
  1486. {
  1487. const struct link_socket_addr *lsa = info->lsa;
  1488. if (link_socket_actual_defined (&lsa->actual))
  1489. return ntohl (lsa->actual.dest.sa.sin_addr.s_addr);
  1490. else if (addr_defined (&lsa->remote))
  1491. return ntohl (lsa->remote.sa.sin_addr.s_addr);
  1492. else
  1493. return 0;
  1494. }
  1495. /*
  1496. * Return a status string describing socket state.
  1497. */
  1498. const char *
  1499. socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
  1500. {
  1501. struct buffer out = alloc_buf_gc (64, gc);
  1502. if (s)
  1503. {
  1504. if (rwflags & EVENT_READ)
  1505. {
  1506. buf_printf (&out, "S%s",
  1507. (s->rwflags_debug & EVENT_READ) ? "R" : "r");
  1508. #ifdef WIN32
  1509. buf_printf (&out, "%s",
  1510. overlapped_io_state_ascii (&s->reads));
  1511. #endif
  1512. }
  1513. if (rwflags & EVENT_WRITE)
  1514. {
  1515. buf_printf (&out, "S%s",
  1516. (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
  1517. #ifdef WIN32
  1518. buf_printf (&out, "%s",
  1519. overlapped_io_state_ascii (&s->writes));
  1520. #endif
  1521. }
  1522. }
  1523. else
  1524. {
  1525. buf_printf (&out, "S?");
  1526. }
  1527. return BSTR (&out);
  1528. }
  1529. /*
  1530. * Stream buffer functions, used to packetize a TCP
  1531. * stream connection.
  1532. */
  1533. static inline void
  1534. stream_buf_reset (struct stream_buf *sb)
  1535. {
  1536. dmsg (D_STREAM_DEBUG, "STREAM: RESET");
  1537. sb->residual_fully_formed = false;
  1538. sb->buf = sb->buf_init;
  1539. buf_reset (&sb->next);
  1540. sb->len = -1;
  1541. }
  1542. void
  1543. stream_buf_init (struct stream_buf *sb,
  1544. struct buffer *buf,
  1545. const unsigned int sockflags,
  1546. const int proto)
  1547. {
  1548. sb->buf_init = *buf;
  1549. sb->maxlen = sb->buf_init.len;
  1550. sb->buf_init.len = 0;
  1551. sb->residual = alloc_buf (sb->maxlen);
  1552. sb->error = false;
  1553. #if PORT_SHARE
  1554. sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCPv4_SERVER))
  1555. ? PS_ENABLED
  1556. : PS_DISABLED;
  1557. #endif
  1558. stream_buf_reset (sb);
  1559. dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
  1560. }
  1561. static inline void
  1562. stream_buf_set_next (struct stream_buf *sb)
  1563. {
  1564. /* set up 'next' for next i/o read */
  1565. sb->next = sb->buf;
  1566. sb->next.offset = sb->buf.offset + sb->buf.len;
  1567. sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
  1568. dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
  1569. sb->buf.offset, sb->buf.len,
  1570. sb->next.offset, sb->next.len,
  1571. sb->len, sb->maxlen);
  1572. ASSERT (sb->next.len > 0);
  1573. ASSERT (buf_safe (&sb->buf, sb->next.len));
  1574. }
  1575. static inline void
  1576. stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
  1577. {
  1578. dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
  1579. buf_defined (&sb->buf) ? sb->buf.len : -1);
  1580. ASSERT (buf_defined (&sb->buf));
  1581. *buf = sb->buf;
  1582. }
  1583. static inline void
  1584. stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
  1585. {
  1586. dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
  1587. buf_defined (&sb->next) ? sb->next.len : -1);
  1588. ASSERT (buf_defined (&sb->next));
  1589. *buf = sb->next;
  1590. }
  1591. bool
  1592. stream_buf_read_setup_dowork (struct link_socket* sock)
  1593. {
  1594. if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
  1595. {
  1596. ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
  1597. ASSERT (buf_init (&sock->stream_buf.residual, 0));
  1598. sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
  1599. dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
  1600. sock->stream_buf.residual_fully_formed ? "YES" : "NO",
  1601. sock->stream_buf.residual.len);
  1602. }
  1603. if (!sock->stream_buf.residual_fully_formed)
  1604. stream_buf_set_next (&sock->stream_buf);
  1605. return !sock->stream_buf.residual_fully_formed;
  1606. }
  1607. bool
  1608. stream_buf_added (struct stream_buf *sb,
  1609. int length_added)
  1610. {
  1611. dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
  1612. if (length_added > 0)
  1613. sb->buf.len += length_added;
  1614. /* if length unknown, see if we can get the length prefix from
  1615. the head of the buffer */
  1616. if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
  1617. {
  1618. packet_size_type net_size;
  1619. #if PORT_SHARE
  1620. if (sb->port_share_state == PS_ENABLED)
  1621. {
  1622. if (!is_openvpn_protocol (&sb->buf))
  1623. {
  1624. msg (D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
  1625. sb->port_share_state = PS_FOREIGN;
  1626. sb->error = true;
  1627. return false;
  1628. }
  1629. else
  1630. sb->port_share_state = PS_DISABLED;
  1631. }
  1632. #endif
  1633. ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
  1634. sb->len = ntohps (net_size);
  1635. if (sb->len < 1 || sb->len > sb->maxlen)
  1636. {
  1637. 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 -- [Attemping restart...]", sb->len, sb->maxlen);
  1638. stream_buf_reset (sb);
  1639. sb->error = true;
  1640. return false;
  1641. }
  1642. }
  1643. /* is our incoming packet fully read? */
  1644. if (sb->len > 0 && sb->buf.len >= sb->len)
  1645. {
  1646. /* save any residual data that's part of the next packet */
  1647. ASSERT (buf_init (&sb->residual, 0));
  1648. if (sb->buf.len > sb->len)
  1649. ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
  1650. dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
  1651. BLEN (&sb->buf),
  1652. BLEN (&sb->residual));
  1653. return true;
  1654. }
  1655. else
  1656. {
  1657. dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
  1658. stream_buf_set_next (sb);
  1659. return false;
  1660. }
  1661. }
  1662. void
  1663. stream_buf_close (struct stream_buf* sb)
  1664. {
  1665. free_buf (&sb->residual);
  1666. }
  1667. /*
  1668. * The listen event is a special event whose sole purpose is
  1669. * to tell us that there's a new incoming connection on a
  1670. * TCP socket, for use in server mode.
  1671. */
  1672. event_t
  1673. socket_listen_event_handle (struct link_socket *s)
  1674. {
  1675. #ifdef WIN32
  1676. if (!defined_net_event_win32 (&s->listen_handle))
  1677. init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
  1678. return &s->listen_handle;
  1679. #else
  1680. return s->sd;
  1681. #endif
  1682. }
  1683. /*
  1684. * Format IP addresses in ascii
  1685. */
  1686. const char *
  1687. print_sockaddr (const struct openvpn_sockaddr *addr, struct gc_arena *gc)
  1688. {
  1689. return print_sockaddr_ex (addr, ":", PS_SHOW_PORT, gc);
  1690. }
  1691. const char *
  1692. print_sockaddr_ex (const struct openvpn_sockaddr *addr,
  1693. const char* separator,
  1694. const unsigned int flags,
  1695. struct gc_arena *gc)
  1696. {
  1697. if (addr)
  1698. {
  1699. struct buffer out = alloc_buf_gc (64, gc);
  1700. const int port = ntohs (addr->sa.sin_port);
  1701. mutex_lock_static (L_INET_NTOA);
  1702. if (!(flags & PS_DONT_SHOW_ADDR))
  1703. buf_printf (&out, "%s", (addr_defined (addr) ? inet_ntoa (addr->sa.sin_addr) : "[undef]"));
  1704. mutex_unlock_static (L_INET_NTOA);
  1705. if (((flags & PS_SHOW_PORT) || (addr_defined (addr) && (flags & PS_SHOW_PORT_IF_DEFINED)))
  1706. && port)
  1707. {
  1708. if (separator)
  1709. buf_printf (&out, "%s", separator);
  1710. buf_printf (&out, "%d", port);
  1711. }
  1712. return BSTR (&out);
  1713. }
  1714. else
  1715. return "[NULL]";
  1716. }
  1717. const char *
  1718. print_link_socket_actual (const struct link_socket_actual *act, struct gc_arena *gc)
  1719. {
  1720. return print_link_socket_actual_ex (act, ":", PS_SHOW_PORT|PS_SHOW_PKTINFO, gc);
  1721. }
  1722. const char *
  1723. print_link_socket_actual_ex (const struct link_socket_actual *act,
  1724. const char *separator,
  1725. const unsigned int flags,
  1726. struct gc_arena *gc)
  1727. {
  1728. if (act)
  1729. {
  1730. struct buffer out = alloc_buf_gc (128, gc);
  1731. buf_printf (&out, "%s", print_sockaddr_ex (&act->dest, separator, flags, gc));
  1732. #if ENABLE_IP_PKTINFO
  1733. if ((flags & PS_SHOW_PKTINFO) && act->pi.ipi_spec_dst.s_addr)
  1734. {
  1735. struct openvpn_sockaddr sa;
  1736. CLEAR (sa);
  1737. sa.sa.sin_addr = act->pi.ipi_spec_dst;
  1738. buf_printf (&out, " (via %s)", print_sockaddr_ex (&sa, separator, 0, gc));
  1739. }
  1740. #endif
  1741. return BSTR (&out);
  1742. }
  1743. else
  1744. return "[NULL]";
  1745. }
  1746. /*
  1747. * Convert an in_addr_t in host byte order
  1748. * to an ascii dotted quad.
  1749. */
  1750. const char *
  1751. print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
  1752. {
  1753. struct in_addr ia;
  1754. struct buffer out = alloc_buf_gc (64, gc);
  1755. if (addr || !(flags & IA_EMPTY_IF_UNDEF))
  1756. {
  1757. CLEAR (ia);
  1758. ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
  1759. mutex_lock_static (L_INET_NTOA);
  1760. buf_printf (&out, "%s", inet_ntoa (ia));
  1761. mutex_unlock_static (L_INET_NTOA);
  1762. }
  1763. return BSTR (&out);
  1764. }
  1765. /* set environmental variables for ip/port in *addr */
  1766. void
  1767. setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const bool flags)
  1768. {
  1769. char name_buf[256];
  1770. if (flags & SA_IP_PORT)
  1771. openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
  1772. else
  1773. openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
  1774. mutex_lock_static (L_INET_NTOA);
  1775. setenv_str (es, name_buf, inet_ntoa (addr->sa.sin_addr));
  1776. mutex_unlock_static (L_INET_NTOA);
  1777. if ((flags & SA_IP_PORT) && addr->sa.sin_port)
  1778. {
  1779. openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
  1780. setenv_int (es, name_buf, ntohs (addr->sa.sin_port));
  1781. }
  1782. }
  1783. void
  1784. setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const bool flags)
  1785. {
  1786. if (addr || !(flags & SA_SET_IF_NONZERO))
  1787. {
  1788. struct openvpn_sockaddr si;
  1789. CLEAR (si);
  1790. si.sa.sin_addr.s_addr = htonl (addr);
  1791. setenv_sockaddr (es, na

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