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-2022 OpenVPN 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 along
20  *  with this program; if not, write to the Free Software Foundation, Inc.,
21  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #ifndef SOCKET_H
25 #define SOCKET_H
26 
27 #include "buffer.h"
28 #include "common.h"
29 #include "error.h"
30 #include "proto.h"
31 #include "mtu.h"
32 #include "win32.h"
33 #include "event.h"
34 #include "proxy.h"
35 #include "socks.h"
36 #include "misc.h"
37 
38 /*
39  * OpenVPN's default port number as assigned by IANA.
40  */
41 #define OPENVPN_PORT "1194"
42 
43 /*
44  * Number of seconds that "resolv-retry infinite"
45  * represents.
46  */
47 #define RESOLV_RETRY_INFINITE 1000000000
48 
49 /*
50  * packet_size_type is used to communicate packet size
51  * over the wire when stream oriented protocols are
52  * being used
53  */
54 
55 typedef uint16_t packet_size_type;
56 
57 /* convert a packet_size_type from host to network order */
58 #define htonps(x) htons(x)
59 
60 /* convert a packet_size_type from network to host order */
61 #define ntohps(x) ntohs(x)
62 
63 /* OpenVPN sockaddr struct */
64 struct openvpn_sockaddr
65 {
66     /*int dummy;*/ /* add offset to force a bug if sa not explicitly dereferenced */
67     union {
68         struct sockaddr sa;
69         struct sockaddr_in in4;
70         struct sockaddr_in6 in6;
71     } addr;
72 };
73 
74 /* struct to hold preresolved host names */
75 struct cached_dns_entry {
76     const char *hostname;
77     const char *servname;
78     int ai_family;
79     int flags;
80     struct addrinfo *ai;
81     struct cached_dns_entry *next;
82 };
83 
84 /* actual address of remote, based on source address of received packets */
85 struct link_socket_actual
86 {
87     /*int dummy;*/ /* add offset to force a bug if dest not explicitly dereferenced */
88 
89     struct openvpn_sockaddr dest;
90 #if ENABLE_IP_PKTINFO
91     union {
92 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
93         struct in_pktinfo in4;
94 #elif defined(IP_RECVDSTADDR)
95         struct in_addr in4;
96 #endif
97         struct in6_pktinfo in6;
98     } pi;
99 #endif
100 };
101 
102 /* IP addresses which are persistent across SIGUSR1s */
103 struct link_socket_addr
104 {
105     struct addrinfo *bind_local;
106     struct addrinfo *remote_list; /* complete remote list */
107     struct addrinfo *current_remote; /* remote used in the
108                                       * current connection attempt */
109     struct link_socket_actual actual; /* reply to this address */
110 };
111 
112 struct link_socket_info
113 {
114     struct link_socket_addr *lsa;
115     bool connection_established;
116     const char *ipchange_command;
117     const struct plugin_list *plugins;
118     bool remote_float;
119     int proto;                  /* Protocol (PROTO_x defined below) */
120     sa_family_t af;                     /* Address family like AF_INET, AF_INET6 or AF_UNSPEC*/
121     bool bind_ipv6_only;
122     int mtu_changed;            /* Set to true when mtu value is changed */
123 };
124 
125 /*
126  * Used to extract packets encapsulated in streams into a buffer,
127  * in this case IP packets embedded in a TCP stream.
128  */
129 struct stream_buf
130 {
131     struct buffer buf_init;
132     struct buffer residual;
133     int maxlen;
134     bool residual_fully_formed;
135 
136     struct buffer buf;
137     struct buffer next;
138     int len;   /* -1 if not yet known */
139 
140     bool error; /* if true, fatal TCP error has occurred,
141                  *  requiring that connection be restarted */
142 #if PORT_SHARE
143 #define PS_DISABLED 0
144 #define PS_ENABLED  1
145 #define PS_FOREIGN  2
146     int port_share_state;
147 #endif
148 };
149 
150 /*
151  * Used to set socket buffer sizes
152  */
153 struct socket_buffer_size
154 {
155     int rcvbuf;
156     int sndbuf;
157 };
158 
159 /*
160  * This is the main socket structure used by OpenVPN.  The SOCKET_
161  * defines try to abstract away our implementation differences between
162  * using sockets on Posix vs. Win32.
163  */
164 struct link_socket
165 {
166     struct link_socket_info info;
167 
168     socket_descriptor_t sd;
169     socket_descriptor_t ctrl_sd; /* only used for UDP over Socks */
170 
171 #ifdef _WIN32
172     struct overlapped_io reads;
173     struct overlapped_io writes;
174     struct rw_handle rw_handle;
175     struct rw_handle listen_handle; /* For listening on TCP socket in server mode */
176 #endif
177 
178     /* used for printing status info only */
179     unsigned int rwflags_debug;
180 
181     /* used for long-term queueing of pre-accepted socket listen */
182     bool listen_persistent_queued;
183 
184     const char *remote_host;
185     const char *remote_port;
186     const char *local_host;
187     const char *local_port;
188     struct cached_dns_entry *dns_cache;
189     bool bind_local;
190 
191 #define INETD_NONE   0
192 #define INETD_WAIT   1
193 #define INETD_NOWAIT 2
194     int inetd;
195 
196 #define LS_MODE_DEFAULT           0
197 #define LS_MODE_TCP_LISTEN        1
198 #define LS_MODE_TCP_ACCEPT_FROM   2
199     int mode;
200 
201     int resolve_retry_seconds;
202     int mtu_discover_type;
203 
204     struct socket_buffer_size socket_buffer_sizes;
205 
206     int mtu;                    /* OS discovered MTU, or 0 if unknown */
207 
208 #define SF_USE_IP_PKTINFO (1<<0)
209 #define SF_TCP_NODELAY (1<<1)
210 #define SF_PORT_SHARE (1<<2)
211 #define SF_HOST_RANDOMIZE (1<<3)
212 #define SF_GETADDRINFO_DGRAM (1<<4)
213     unsigned int sockflags;
214     int mark;
215     const char *bind_dev;
216 
217     /* for stream sockets */
218     struct stream_buf stream_buf;
219     struct buffer stream_buf_data;
220     bool stream_reset;
221 
222     /* HTTP proxy */
223     struct http_proxy_info *http_proxy;
224 
225     /* Socks proxy */
226     struct socks_proxy_info *socks_proxy;
227     struct link_socket_actual socks_relay; /* Socks UDP relay address */
228 
229     /* The OpenVPN server we will use the proxy to connect to */
230     const char *proxy_dest_host;
231     const char *proxy_dest_port;
232 
233     /* Pointer to the server-poll to trigger the timeout in function which have
234      * their own loop instead of using the main oop */
235     struct event_timeout *server_poll_timeout;
236 
237 #if PASSTOS_CAPABILITY
238     /* used to get/set TOS. */
239 #if defined(TARGET_LINUX)
240     uint8_t ptos;
241 #else /* all the BSDs, Solaris, MacOS use plain "int" -> see "man ip" there */
242     int ptos;
243 #endif
244     bool ptos_defined;
245 #endif
246 
247 #ifdef ENABLE_DEBUG
248     int gremlin; /* --gremlin bits */
249 #endif
250 };
251 
252 /*
253  * Some Posix/Win32 differences.
254  */
255 
256 #ifndef MSG_NOSIGNAL
257 #define MSG_NOSIGNAL 0
258 #endif
259 
260 #ifdef _WIN32
261 
262 #define openvpn_close_socket(s) closesocket(s)
263 
264 int socket_recv_queue(struct link_socket *sock, int maxsize);
265 
266 int socket_send_queue(struct link_socket *sock,
267                       struct buffer *buf,
268                       const struct link_socket_actual *to);
269 
270 int socket_finalize(
271     SOCKET s,
272     struct overlapped_io *io,
273     struct buffer *buf,
274     struct link_socket_actual *from);
275 
276 #else  /* ifdef _WIN32 */
277 
278 #define openvpn_close_socket(s) close(s)
279 
280 #endif
281 
282 struct link_socket *link_socket_new(void);
283 
284 void socket_bind(socket_descriptor_t sd,
285                  struct addrinfo *local,
286                  int af_family,
287                  const char *prefix,
288                  bool ipv6only);
289 
290 int openvpn_connect(socket_descriptor_t sd,
291                     const struct sockaddr *remote,
292                     int connect_timeout,
293                     volatile int *signal_received);
294 
295 
296 
297 /*
298  * Initialize link_socket object.
299  */
300 /* *INDENT-OFF* uncrustify misparses this function declarion because of
301  * embedded #if/#endif tell it to skip this section */
302 void
303 link_socket_init_phase1(struct link_socket *sock,
304                         const char *local_host,
305                         const char *local_port,
306                         const char *remote_host,
307                         const char *remote_port,
308                         struct cached_dns_entry *dns_cache,
309                         int proto,
310                         sa_family_t af,
311                         bool bind_ipv6_only,
312                         int mode,
313                         const struct link_socket *accept_from,
314                         struct http_proxy_info *http_proxy,
315                         struct socks_proxy_info *socks_proxy,
316 #ifdef ENABLE_DEBUG
317                         int gremlin,
318 #endif
319                         bool bind_local,
320                         bool remote_float,
321                         int inetd,
322                         struct link_socket_addr *lsa,
323                         const char *ipchange_command,
324                         const struct plugin_list *plugins,
325                         int resolve_retry_seconds,
326                         int mtu_discover_type,
327                         int rcvbuf,
328                         int sndbuf,
329                         int mark,
330                         const char *bind_dev,
331                         struct event_timeout *server_poll_timeout,
332                         unsigned int sockflags);
333 /* Reenable uncrustify *INDENT-ON* */
334 
335 void link_socket_init_phase2(struct link_socket *sock,
336                              const struct frame *frame,
337                              struct signal_info *sig_info);
338 
339 void do_preresolve(struct context *c);
340 
341 void socket_adjust_frame_parameters(struct frame *frame, int proto);
342 
343 void frame_adjust_path_mtu(struct frame *frame, int pmtu, int proto);
344 
345 void link_socket_close(struct link_socket *sock);
346 
347 void sd_close(socket_descriptor_t *sd);
348 
349 #define PS_SHOW_PORT_IF_DEFINED (1<<0)
350 #define PS_SHOW_PORT            (1<<1)
351 #define PS_SHOW_PKTINFO         (1<<2)
352 #define PS_DONT_SHOW_ADDR       (1<<3)
353 #define PS_DONT_SHOW_FAMILY     (1<<4)
354 
355 const char *print_sockaddr_ex(const struct sockaddr *addr,
356                               const char *separator,
357                               const unsigned int flags,
358                               struct gc_arena *gc);
359 
360 static inline
361 const char *
print_openvpn_sockaddr_ex(const struct openvpn_sockaddr * addr,const char * separator,const unsigned int flags,struct gc_arena * gc)362 print_openvpn_sockaddr_ex(const struct openvpn_sockaddr *addr,
363                           const char *separator,
364                           const unsigned int flags,
365                           struct gc_arena *gc)
366 {
367     return print_sockaddr_ex(&addr->addr.sa, separator, flags, gc);
368 }
369 
370 static inline
371 const char *
print_openvpn_sockaddr(const struct openvpn_sockaddr * addr,struct gc_arena * gc)372 print_openvpn_sockaddr(const struct openvpn_sockaddr *addr,
373                        struct gc_arena *gc)
374 {
375     return print_sockaddr_ex(&addr->addr.sa, ":", PS_SHOW_PORT, gc);
376 }
377 
378 static inline
379 const char *
print_sockaddr(const struct sockaddr * addr,struct gc_arena * gc)380 print_sockaddr(const struct sockaddr *addr,
381                struct gc_arena *gc)
382 {
383     return print_sockaddr_ex(addr, ":", PS_SHOW_PORT, gc);
384 }
385 
386 
387 
388 const char *print_link_socket_actual_ex(const struct link_socket_actual *act,
389                                         const char *separator,
390                                         const unsigned int flags,
391                                         struct gc_arena *gc);
392 
393 const char *print_link_socket_actual(const struct link_socket_actual *act,
394                                      struct gc_arena *gc);
395 
396 
397 #define IA_EMPTY_IF_UNDEF (1<<0)
398 #define IA_NET_ORDER      (1<<1)
399 const char *print_in_addr_t(in_addr_t addr, unsigned int flags, struct gc_arena *gc);
400 
401 const char *print_in6_addr(struct in6_addr addr6, unsigned int flags, struct gc_arena *gc);
402 
403 struct in6_addr add_in6_addr( struct in6_addr base, uint32_t add );
404 
405 #define SA_IP_PORT        (1<<0)
406 #define SA_SET_IF_NONZERO (1<<1)
407 void setenv_sockaddr(struct env_set *es,
408                      const char *name_prefix,
409                      const struct openvpn_sockaddr *addr,
410                      const unsigned int flags);
411 
412 void setenv_in_addr_t(struct env_set *es,
413                       const char *name_prefix,
414                       in_addr_t addr,
415                       const unsigned int flags);
416 
417 void setenv_in6_addr(struct env_set *es,
418                      const char *name_prefix,
419                      const struct in6_addr *addr,
420                      const unsigned int flags);
421 
422 void setenv_link_socket_actual(struct env_set *es,
423                                const char *name_prefix,
424                                const struct link_socket_actual *act,
425                                const unsigned int flags);
426 
427 void bad_address_length(int actual, int expected);
428 
429 /* IPV4_INVALID_ADDR: returned by link_socket_current_remote()
430  * to ease redirect-gateway logic for ipv4 tunnels on ipv6 endpoints
431  */
432 #define IPV4_INVALID_ADDR 0xffffffff
433 in_addr_t link_socket_current_remote(const struct link_socket_info *info);
434 
435 const struct in6_addr *link_socket_current_remote_ipv6
436     (const struct link_socket_info *info);
437 
438 void link_socket_connection_initiated(struct link_socket_info *info,
439                                       const struct link_socket_actual *addr,
440                                       const char *common_name,
441                                       struct env_set *es);
442 
443 void link_socket_bad_incoming_addr(struct buffer *buf,
444                                    const struct link_socket_info *info,
445                                    const struct link_socket_actual *from_addr);
446 
447 void set_actual_address(struct link_socket_actual *actual,
448                         struct addrinfo *ai);
449 
450 void link_socket_bad_outgoing_addr(void);
451 
452 void setenv_trusted(struct env_set *es, const struct link_socket_info *info);
453 
454 bool link_socket_update_flags(struct link_socket *ls, unsigned int sockflags);
455 
456 void link_socket_update_buffer_sizes(struct link_socket *ls, int rcvbuf, int sndbuf);
457 
458 /*
459  * Low-level functions
460  */
461 
462 /* return values of openvpn_inet_aton */
463 #define OIA_HOSTNAME   0
464 #define OIA_IP         1
465 #define OIA_ERROR     -1
466 int openvpn_inet_aton(const char *dotted_quad, struct in_addr *addr);
467 
468 /* integrity validation on pulled options */
469 bool ip_addr_dotted_quad_safe(const char *dotted_quad);
470 
471 bool ip_or_dns_addr_safe(const char *addr, const bool allow_fqdn);
472 
473 bool mac_addr_safe(const char *mac_addr);
474 
475 bool ipv6_addr_safe(const char *ipv6_text_addr);
476 
477 socket_descriptor_t create_socket_tcp(struct addrinfo *);
478 
479 socket_descriptor_t socket_do_accept(socket_descriptor_t sd,
480                                      struct link_socket_actual *act,
481                                      const bool nowait);
482 
483 /*
484  * proto related
485  */
486 bool proto_is_net(int proto);
487 
488 bool proto_is_dgram(int proto);
489 
490 bool proto_is_udp(int proto);
491 
492 bool proto_is_tcp(int proto);
493 
494 
495 #if UNIX_SOCK_SUPPORT
496 
497 socket_descriptor_t create_socket_unix(void);
498 
499 void socket_bind_unix(socket_descriptor_t sd,
500                       struct sockaddr_un *local,
501                       const char *prefix);
502 
503 socket_descriptor_t socket_accept_unix(socket_descriptor_t sd,
504                                        struct sockaddr_un *remote);
505 
506 int socket_connect_unix(socket_descriptor_t sd,
507                         struct sockaddr_un *remote);
508 
509 void sockaddr_unix_init(struct sockaddr_un *local, const char *path);
510 
511 const char *sockaddr_unix_name(const struct sockaddr_un *local, const char *null);
512 
513 void socket_delete_unix(const struct sockaddr_un *local);
514 
515 bool unix_socket_get_peer_uid_gid(const socket_descriptor_t sd, int *uid, int *gid);
516 
517 #endif /* if UNIX_SOCK_SUPPORT */
518 
519 /*
520  * DNS resolution
521  */
522 
523 #define GETADDR_RESOLVE               (1<<0)
524 #define GETADDR_FATAL                 (1<<1)
525 #define GETADDR_HOST_ORDER            (1<<2)
526 #define GETADDR_MENTION_RESOLVE_RETRY (1<<3)
527 #define GETADDR_FATAL_ON_SIGNAL       (1<<4)
528 #define GETADDR_WARN_ON_SIGNAL        (1<<5)
529 #define GETADDR_MSG_VIRT_OUT          (1<<6)
530 #define GETADDR_TRY_ONCE              (1<<7)
531 #define GETADDR_UPDATE_MANAGEMENT_STATE (1<<8)
532 #define GETADDR_RANDOMIZE             (1<<9)
533 #define GETADDR_PASSIVE               (1<<10)
534 #define GETADDR_DATAGRAM              (1<<11)
535 
536 #define GETADDR_CACHE_MASK              (GETADDR_DATAGRAM|GETADDR_PASSIVE)
537 
538 /**
539  * Translate an IPv4 addr or hostname from string form to in_addr_t
540  *
541  * In case of resolve error, it will try again for
542  * resolve_retry_seconds seconds.
543  */
544 in_addr_t getaddr(unsigned int flags,
545                   const char *hostname,
546                   int resolve_retry_seconds,
547                   bool *succeeded,
548                   volatile int *signal_received);
549 
550 /**
551  * Translate an IPv6 addr or hostname from string form to in6_addr
552  */
553 bool get_ipv6_addr(const char *hostname, struct in6_addr *network,
554                    unsigned int *netbits, int msglevel);
555 
556 int openvpn_getaddrinfo(unsigned int flags,
557                         const char *hostname,
558                         const char *servname,
559                         int resolve_retry_seconds,
560                         volatile int *signal_received,
561                         int ai_family,
562                         struct addrinfo **res);
563 
564 /*
565  * Transport protocol naming and other details.
566  */
567 
568 /*
569  * Use enum's instead of #define to allow for easier
570  * optional proto support
571  */
572 enum proto_num {
573     PROTO_NONE,     /* catch for uninitialized */
574     PROTO_UDP,
575     PROTO_TCP,
576     PROTO_TCP_SERVER,
577     PROTO_TCP_CLIENT,
578     PROTO_N
579 };
580 
581 int ascii2proto(const char *proto_name);
582 
583 sa_family_t ascii2af(const char *proto_name);
584 
585 const char *proto2ascii(int proto, sa_family_t af, bool display_form);
586 
587 const char *proto2ascii_all(struct gc_arena *gc);
588 
589 const char *proto_remote(int proto, bool remote);
590 
591 const char *addr_family_name(int af);
592 
593 /*
594  * Overhead added to packets by various protocols.
595  */
596 #define IPv4_UDP_HEADER_SIZE              28
597 #define IPv4_TCP_HEADER_SIZE              40
598 #define IPv6_UDP_HEADER_SIZE              48
599 #define IPv6_TCP_HEADER_SIZE              60
600 
601 extern const int proto_overhead[];
602 
603 static inline int
datagram_overhead(int proto)604 datagram_overhead(int proto)
605 {
606     ASSERT(proto >= 0 && proto < PROTO_N);
607     return proto_overhead [proto];
608 }
609 
610 /*
611  * Misc inline functions
612  */
613 
614 static inline bool
link_socket_proto_connection_oriented(int proto)615 link_socket_proto_connection_oriented(int proto)
616 {
617     return !proto_is_dgram(proto);
618 }
619 
620 static inline bool
link_socket_connection_oriented(const struct link_socket * sock)621 link_socket_connection_oriented(const struct link_socket *sock)
622 {
623     if (sock)
624     {
625         return link_socket_proto_connection_oriented(sock->info.proto);
626     }
627     else
628     {
629         return false;
630     }
631 }
632 
633 static inline bool
addr_defined(const struct openvpn_sockaddr * addr)634 addr_defined(const struct openvpn_sockaddr *addr)
635 {
636     if (!addr)
637     {
638         return 0;
639     }
640     switch (addr->addr.sa.sa_family)
641     {
642         case AF_INET: return addr->addr.in4.sin_addr.s_addr != 0;
643 
644         case AF_INET6: return !IN6_IS_ADDR_UNSPECIFIED(&addr->addr.in6.sin6_addr);
645 
646         default: return 0;
647     }
648 }
649 
650 static inline bool
addr_local(const struct sockaddr * addr)651 addr_local(const struct sockaddr *addr)
652 {
653     if (!addr)
654     {
655         return false;
656     }
657     switch (addr->sa_family)
658     {
659         case AF_INET:
660             return ((const struct sockaddr_in *)addr)->sin_addr.s_addr == htonl(INADDR_LOOPBACK);
661 
662         case AF_INET6:
663             return IN6_IS_ADDR_LOOPBACK(&((const struct sockaddr_in6 *)addr)->sin6_addr);
664 
665         default:
666             return false;
667     }
668 }
669 
670 
671 static inline bool
addr_defined_ipi(const struct link_socket_actual * lsa)672 addr_defined_ipi(const struct link_socket_actual *lsa)
673 {
674 #if ENABLE_IP_PKTINFO
675     if (!lsa)
676     {
677         return 0;
678     }
679     switch (lsa->dest.addr.sa.sa_family)
680     {
681 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
682         case AF_INET: return lsa->pi.in4.ipi_spec_dst.s_addr != 0;
683 
684 #elif defined(IP_RECVDSTADDR)
685         case AF_INET: return lsa->pi.in4.s_addr != 0;
686 
687 #endif
688         case AF_INET6: return !IN6_IS_ADDR_UNSPECIFIED(&lsa->pi.in6.ipi6_addr);
689 
690         default: return 0;
691     }
692 #else  /* if ENABLE_IP_PKTINFO */
693     ASSERT(0);
694 #endif
695     return false;
696 }
697 
698 static inline bool
link_socket_actual_defined(const struct link_socket_actual * act)699 link_socket_actual_defined(const struct link_socket_actual *act)
700 {
701     return act && addr_defined(&act->dest);
702 }
703 
704 static inline bool
addr_match(const struct openvpn_sockaddr * a1,const struct openvpn_sockaddr * a2)705 addr_match(const struct openvpn_sockaddr *a1, const struct openvpn_sockaddr *a2)
706 {
707     switch (a1->addr.sa.sa_family)
708     {
709         case AF_INET:
710             return a1->addr.in4.sin_addr.s_addr == a2->addr.in4.sin_addr.s_addr;
711 
712         case AF_INET6:
713             return IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &a2->addr.in6.sin6_addr);
714     }
715     ASSERT(0);
716     return false;
717 }
718 
719 static inline bool
addrlist_match(const struct openvpn_sockaddr * a1,const struct addrinfo * addrlist)720 addrlist_match(const struct openvpn_sockaddr *a1, const struct addrinfo *addrlist)
721 {
722     const struct addrinfo *curele;
723     for (curele = addrlist; curele; curele = curele->ai_next)
724     {
725         switch (a1->addr.sa.sa_family)
726         {
727             case AF_INET:
728                 if (a1->addr.in4.sin_addr.s_addr == ((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr)
729                 {
730                     return true;
731                 }
732                 break;
733 
734             case AF_INET6:
735                 if (IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &((struct sockaddr_in6 *) curele->ai_addr)->sin6_addr))
736                 {
737                     return true;
738                 }
739                 break;
740 
741             default:
742                 ASSERT(0);
743         }
744     }
745     return false;
746 }
747 
748 static inline in_addr_t
addr_host(const struct openvpn_sockaddr * addr)749 addr_host(const struct openvpn_sockaddr *addr)
750 {
751     /*
752      * "public" addr returned is checked against ifconfig for
753      * possible clash: non sense for now given
754      * that we do ifconfig only IPv4
755      */
756     if (addr->addr.sa.sa_family != AF_INET)
757     {
758         return 0;
759     }
760     return ntohl(addr->addr.in4.sin_addr.s_addr);
761 }
762 
763 
764 static inline bool
addrlist_port_match(const struct openvpn_sockaddr * a1,const struct addrinfo * a2)765 addrlist_port_match(const struct openvpn_sockaddr *a1, const struct addrinfo *a2)
766 {
767     const struct addrinfo *curele;
768     for (curele = a2; curele; curele = curele->ai_next)
769     {
770         switch (a1->addr.sa.sa_family)
771         {
772             case AF_INET:
773                 if (curele->ai_family == AF_INET
774                     && a1->addr.in4.sin_addr.s_addr == ((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr
775                     && a1->addr.in4.sin_port == ((struct sockaddr_in *)curele->ai_addr)->sin_port)
776                 {
777                     return true;
778                 }
779                 break;
780 
781             case AF_INET6:
782                 if (curele->ai_family == AF_INET6
783                     && IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &((struct sockaddr_in6 *) curele->ai_addr)->sin6_addr)
784                     && a1->addr.in6.sin6_port == ((struct sockaddr_in6 *) curele->ai_addr)->sin6_port)
785                 {
786                     return true;
787                 }
788                 break;
789 
790             default:
791                 ASSERT(0);
792         }
793     }
794     return false;
795 }
796 
797 
798 
799 static inline bool
addr_port_match(const struct openvpn_sockaddr * a1,const struct openvpn_sockaddr * a2)800 addr_port_match(const struct openvpn_sockaddr *a1, const struct openvpn_sockaddr *a2)
801 {
802     switch (a1->addr.sa.sa_family)
803     {
804         case AF_INET:
805             return a1->addr.in4.sin_addr.s_addr == a2->addr.in4.sin_addr.s_addr
806                    && a1->addr.in4.sin_port == a2->addr.in4.sin_port;
807 
808         case AF_INET6:
809             return IN6_ARE_ADDR_EQUAL(&a1->addr.in6.sin6_addr, &a2->addr.in6.sin6_addr)
810                    && a1->addr.in6.sin6_port == a2->addr.in6.sin6_port;
811     }
812     ASSERT(0);
813     return false;
814 }
815 
816 static inline bool
addr_match_proto(const struct openvpn_sockaddr * a1,const struct openvpn_sockaddr * a2,const int proto)817 addr_match_proto(const struct openvpn_sockaddr *a1,
818                  const struct openvpn_sockaddr *a2,
819                  const int proto)
820 {
821     return link_socket_proto_connection_oriented(proto)
822            ? addr_match(a1, a2)
823            : addr_port_match(a1, a2);
824 }
825 
826 
827 static inline bool
addrlist_match_proto(const struct openvpn_sockaddr * a1,struct addrinfo * addr_list,const int proto)828 addrlist_match_proto(const struct openvpn_sockaddr *a1,
829                      struct addrinfo *addr_list,
830                      const int proto)
831 {
832     return link_socket_proto_connection_oriented(proto)
833            ? addrlist_match(a1, addr_list)
834            : addrlist_port_match(a1, addr_list);
835 }
836 
837 static inline void
addr_zero_host(struct openvpn_sockaddr * addr)838 addr_zero_host(struct openvpn_sockaddr *addr)
839 {
840     switch (addr->addr.sa.sa_family)
841     {
842         case AF_INET:
843             addr->addr.in4.sin_addr.s_addr = 0;
844             break;
845 
846         case AF_INET6:
847             memset(&addr->addr.in6.sin6_addr, 0, sizeof(struct in6_addr));
848             break;
849     }
850 }
851 
852 static inline void
addr_copy_sa(struct openvpn_sockaddr * dst,const struct openvpn_sockaddr * src)853 addr_copy_sa(struct openvpn_sockaddr *dst, const struct openvpn_sockaddr *src)
854 {
855     dst->addr = src->addr;
856 }
857 
858 static inline bool
addr_inet4or6(struct sockaddr * addr)859 addr_inet4or6(struct sockaddr *addr)
860 {
861     return addr->sa_family == AF_INET || addr->sa_family == AF_INET6;
862 }
863 
864 int addr_guess_family(sa_family_t af,const char *name);
865 
866 static inline int
af_addr_size(sa_family_t af)867 af_addr_size(sa_family_t af)
868 {
869     switch (af)
870     {
871         case AF_INET: return sizeof(struct sockaddr_in);
872 
873         case AF_INET6: return sizeof(struct sockaddr_in6);
874 
875         default:
876 #if 0
877             /* could be called from socket_do_accept() with empty addr */
878             msg(M_ERR, "Bad address family: %d\n", af);
879             ASSERT(0);
880 #endif
881             return 0;
882     }
883 }
884 
885 static inline bool
link_socket_actual_match(const struct link_socket_actual * a1,const struct link_socket_actual * a2)886 link_socket_actual_match(const struct link_socket_actual *a1, const struct link_socket_actual *a2)
887 {
888     return addr_port_match(&a1->dest, &a2->dest);
889 }
890 
891 #if PORT_SHARE
892 
893 static inline bool
socket_foreign_protocol_detected(const struct link_socket * sock)894 socket_foreign_protocol_detected(const struct link_socket *sock)
895 {
896     return link_socket_connection_oriented(sock)
897            && sock->stream_buf.port_share_state == PS_FOREIGN;
898 }
899 
900 static inline const struct buffer *
socket_foreign_protocol_head(const struct link_socket * sock)901 socket_foreign_protocol_head(const struct link_socket *sock)
902 {
903     return &sock->stream_buf.buf;
904 }
905 
906 static inline int
socket_foreign_protocol_sd(const struct link_socket * sock)907 socket_foreign_protocol_sd(const struct link_socket *sock)
908 {
909     return sock->sd;
910 }
911 
912 #endif /* if PORT_SHARE */
913 
914 static inline bool
socket_connection_reset(const struct link_socket * sock,int status)915 socket_connection_reset(const struct link_socket *sock, int status)
916 {
917     if (link_socket_connection_oriented(sock))
918     {
919         if (sock->stream_reset || sock->stream_buf.error)
920         {
921             return true;
922         }
923         else if (status < 0)
924         {
925             const int err = openvpn_errno();
926 #ifdef _WIN32
927             return err == WSAECONNRESET || err == WSAECONNABORTED;
928 #else
929             return err == ECONNRESET;
930 #endif
931         }
932     }
933     return false;
934 }
935 
936 static inline bool
link_socket_verify_incoming_addr(struct buffer * buf,const struct link_socket_info * info,const struct link_socket_actual * from_addr)937 link_socket_verify_incoming_addr(struct buffer *buf,
938                                  const struct link_socket_info *info,
939                                  const struct link_socket_actual *from_addr)
940 {
941     if (buf->len > 0)
942     {
943         switch (from_addr->dest.addr.sa.sa_family)
944         {
945             case AF_INET6:
946             case AF_INET:
947                 if (!link_socket_actual_defined(from_addr))
948                 {
949                     return false;
950                 }
951                 if (info->remote_float || (!info->lsa->remote_list))
952                 {
953                     return true;
954                 }
955                 if (addrlist_match_proto(&from_addr->dest, info->lsa->remote_list, info->proto))
956                 {
957                     return true;
958                 }
959         }
960     }
961     return false;
962 }
963 
964 static inline void
link_socket_get_outgoing_addr(struct buffer * buf,const struct link_socket_info * info,struct link_socket_actual ** act)965 link_socket_get_outgoing_addr(struct buffer *buf,
966                               const struct link_socket_info *info,
967                               struct link_socket_actual **act)
968 {
969     if (buf->len > 0)
970     {
971         struct link_socket_addr *lsa = info->lsa;
972         if (link_socket_actual_defined(&lsa->actual))
973         {
974             *act = &lsa->actual;
975         }
976         else
977         {
978             link_socket_bad_outgoing_addr();
979             buf->len = 0;
980             *act = NULL;
981         }
982     }
983 }
984 
985 static inline void
link_socket_set_outgoing_addr(struct link_socket_info * info,const struct link_socket_actual * act,const char * common_name,struct env_set * es)986 link_socket_set_outgoing_addr(struct link_socket_info *info,
987                               const struct link_socket_actual *act,
988                               const char *common_name,
989                               struct env_set *es)
990 {
991     struct link_socket_addr *lsa = info->lsa;
992     if (
993         /* new or changed address? */
994         (!info->connection_established
995          || !addr_match_proto(&act->dest, &lsa->actual.dest, info->proto)
996         )
997         &&
998         /* address undef or address == remote or --float */
999         (info->remote_float
1000          || (!lsa->remote_list || addrlist_match_proto(&act->dest, lsa->remote_list, info->proto))
1001         )
1002         )
1003     {
1004         link_socket_connection_initiated(info, act, common_name, es);
1005     }
1006 }
1007 
1008 bool stream_buf_read_setup_dowork(struct link_socket *sock);
1009 
1010 static inline bool
stream_buf_read_setup(struct link_socket * sock)1011 stream_buf_read_setup(struct link_socket *sock)
1012 {
1013     if (link_socket_connection_oriented(sock))
1014     {
1015         return stream_buf_read_setup_dowork(sock);
1016     }
1017     else
1018     {
1019         return true;
1020     }
1021 }
1022 
1023 /*
1024  * Socket Read Routines
1025  */
1026 
1027 int link_socket_read_tcp(struct link_socket *sock,
1028                          struct buffer *buf);
1029 
1030 #ifdef _WIN32
1031 
1032 static inline int
link_socket_read_udp_win32(struct link_socket * sock,struct buffer * buf,struct link_socket_actual * from)1033 link_socket_read_udp_win32(struct link_socket *sock,
1034                            struct buffer *buf,
1035                            struct link_socket_actual *from)
1036 {
1037     return socket_finalize(sock->sd, &sock->reads, buf, from);
1038 }
1039 
1040 #else  /* ifdef _WIN32 */
1041 
1042 int link_socket_read_udp_posix(struct link_socket *sock,
1043                                struct buffer *buf,
1044                                struct link_socket_actual *from);
1045 
1046 #endif
1047 
1048 /* read a TCP or UDP packet from link */
1049 static inline int
link_socket_read(struct link_socket * sock,struct buffer * buf,struct link_socket_actual * from)1050 link_socket_read(struct link_socket *sock,
1051                  struct buffer *buf,
1052                  struct link_socket_actual *from)
1053 {
1054     if (proto_is_udp(sock->info.proto)) /* unified UDPv4 and UDPv6 */
1055     {
1056         int res;
1057 
1058 #ifdef _WIN32
1059         res = link_socket_read_udp_win32(sock, buf, from);
1060 #else
1061         res = link_socket_read_udp_posix(sock, buf, from);
1062 #endif
1063         return res;
1064     }
1065     else if (proto_is_tcp(sock->info.proto)) /* unified TCPv4 and TCPv6 */
1066     {
1067         /* from address was returned by accept */
1068         addr_copy_sa(&from->dest, &sock->info.lsa->actual.dest);
1069         return link_socket_read_tcp(sock, buf);
1070     }
1071     else
1072     {
1073         ASSERT(0);
1074         return -1; /* NOTREACHED */
1075     }
1076 }
1077 
1078 /*
1079  * Socket Write routines
1080  */
1081 
1082 int link_socket_write_tcp(struct link_socket *sock,
1083                           struct buffer *buf,
1084                           struct link_socket_actual *to);
1085 
1086 #ifdef _WIN32
1087 
1088 static inline int
link_socket_write_win32(struct link_socket * sock,struct buffer * buf,struct link_socket_actual * to)1089 link_socket_write_win32(struct link_socket *sock,
1090                         struct buffer *buf,
1091                         struct link_socket_actual *to)
1092 {
1093     int err = 0;
1094     int status = 0;
1095     if (overlapped_io_active(&sock->writes))
1096     {
1097         status = socket_finalize(sock->sd, &sock->writes, NULL, NULL);
1098         if (status < 0)
1099         {
1100             err = WSAGetLastError();
1101         }
1102     }
1103     socket_send_queue(sock, buf, to);
1104     if (status < 0)
1105     {
1106         WSASetLastError(err);
1107         return status;
1108     }
1109     else
1110     {
1111         return BLEN(buf);
1112     }
1113 }
1114 
1115 #else  /* ifdef _WIN32 */
1116 
1117 size_t link_socket_write_udp_posix_sendmsg(struct link_socket *sock,
1118                                            struct buffer *buf,
1119                                            struct link_socket_actual *to);
1120 
1121 
1122 static inline size_t
link_socket_write_udp_posix(struct link_socket * sock,struct buffer * buf,struct link_socket_actual * to)1123 link_socket_write_udp_posix(struct link_socket *sock,
1124                             struct buffer *buf,
1125                             struct link_socket_actual *to)
1126 {
1127 #if ENABLE_IP_PKTINFO
1128     if (proto_is_udp(sock->info.proto) && (sock->sockflags & SF_USE_IP_PKTINFO)
1129         && addr_defined_ipi(to))
1130     {
1131         return link_socket_write_udp_posix_sendmsg(sock, buf, to);
1132     }
1133     else
1134 #endif
1135     return sendto(sock->sd, BPTR(buf), BLEN(buf), 0,
1136                   (struct sockaddr *) &to->dest.addr.sa,
1137                   (socklen_t) af_addr_size(to->dest.addr.sa.sa_family));
1138 }
1139 
1140 static inline size_t
link_socket_write_tcp_posix(struct link_socket * sock,struct buffer * buf,struct link_socket_actual * to)1141 link_socket_write_tcp_posix(struct link_socket *sock,
1142                             struct buffer *buf,
1143                             struct link_socket_actual *to)
1144 {
1145     return send(sock->sd, BPTR(buf), BLEN(buf), MSG_NOSIGNAL);
1146 }
1147 
1148 #endif /* ifdef _WIN32 */
1149 
1150 static inline size_t
link_socket_write_udp(struct link_socket * sock,struct buffer * buf,struct link_socket_actual * to)1151 link_socket_write_udp(struct link_socket *sock,
1152                       struct buffer *buf,
1153                       struct link_socket_actual *to)
1154 {
1155 #ifdef _WIN32
1156     return link_socket_write_win32(sock, buf, to);
1157 #else
1158     return link_socket_write_udp_posix(sock, buf, to);
1159 #endif
1160 }
1161 
1162 /* write a TCP or UDP packet to link */
1163 static inline int
link_socket_write(struct link_socket * sock,struct buffer * buf,struct link_socket_actual * to)1164 link_socket_write(struct link_socket *sock,
1165                   struct buffer *buf,
1166                   struct link_socket_actual *to)
1167 {
1168     if (proto_is_udp(sock->info.proto)) /* unified UDPv4 and UDPv6 */
1169     {
1170         return link_socket_write_udp(sock, buf, to);
1171     }
1172     else if (proto_is_tcp(sock->info.proto)) /* unified TCPv4 and TCPv6 */
1173     {
1174         return link_socket_write_tcp(sock, buf, to);
1175     }
1176     else
1177     {
1178         ASSERT(0);
1179         return -1; /* NOTREACHED */
1180     }
1181 }
1182 
1183 #if PASSTOS_CAPABILITY
1184 
1185 /*
1186  * Extract TOS bits.  Assumes that ipbuf is a valid IPv4 packet.
1187  */
1188 static inline void
link_socket_extract_tos(struct link_socket * ls,const struct buffer * ipbuf)1189 link_socket_extract_tos(struct link_socket *ls, const struct buffer *ipbuf)
1190 {
1191     if (ls && ipbuf)
1192     {
1193         struct openvpn_iphdr *iph = (struct openvpn_iphdr *) BPTR(ipbuf);
1194         ls->ptos = iph->tos;
1195         ls->ptos_defined = true;
1196     }
1197 }
1198 
1199 /*
1200  * Set socket properties to reflect TOS bits which were extracted
1201  * from tunnel packet.
1202  */
1203 static inline void
link_socket_set_tos(struct link_socket * ls)1204 link_socket_set_tos(struct link_socket *ls)
1205 {
1206     if (ls && ls->ptos_defined)
1207     {
1208         setsockopt(ls->sd, IPPROTO_IP, IP_TOS, (const void *)&ls->ptos, sizeof(ls->ptos));
1209     }
1210 }
1211 
1212 #endif /* if PASSTOS_CAPABILITY */
1213 
1214 /*
1215  * Socket I/O wait functions
1216  */
1217 
1218 static inline bool
socket_read_residual(const struct link_socket * s)1219 socket_read_residual(const struct link_socket *s)
1220 {
1221     return s && s->stream_buf.residual_fully_formed;
1222 }
1223 
1224 static inline event_t
socket_event_handle(const struct link_socket * s)1225 socket_event_handle(const struct link_socket *s)
1226 {
1227 #ifdef _WIN32
1228     return &s->rw_handle;
1229 #else
1230     return s->sd;
1231 #endif
1232 }
1233 
1234 event_t socket_listen_event_handle(struct link_socket *s);
1235 
1236 unsigned int
1237 socket_set(struct link_socket *s,
1238            struct event_set *es,
1239            unsigned int rwflags,
1240            void *arg,
1241            unsigned int *persistent);
1242 
1243 static inline void
socket_set_listen_persistent(struct link_socket * s,struct event_set * es,void * arg)1244 socket_set_listen_persistent(struct link_socket *s,
1245                              struct event_set *es,
1246                              void *arg)
1247 {
1248     if (s && !s->listen_persistent_queued)
1249     {
1250         event_ctl(es, socket_listen_event_handle(s), EVENT_READ, arg);
1251         s->listen_persistent_queued = true;
1252     }
1253 }
1254 
1255 static inline void
socket_reset_listen_persistent(struct link_socket * s)1256 socket_reset_listen_persistent(struct link_socket *s)
1257 {
1258 #ifdef _WIN32
1259     reset_net_event_win32(&s->listen_handle, s->sd);
1260 #endif
1261 }
1262 
1263 const char *socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc);
1264 
1265 #endif /* SOCKET_H */
1266