f05003aff2ee5661ce9876230ac50380d2748b32
[trust_router.git] / common / tr_socket.c
1 /*
2  * Copyright (c) 2016-2018, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <talloc.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <netdb.h>
39
40 #include <tr_debug.h>
41 #include <tr_socket.h>
42
43 /**
44  * Open sockets on all interface addresses
45  *
46  * Uses getaddrinfo() to find all TCP addresses and opens sockets in
47  * non-blocking modes. Binds to most max_fd sockets and stores file descriptors
48  * in fd_out. Unused entries in fd_out are not modified. Returns the actual
49  * number of sockets opened.
50  *
51  * @param port port to listen on
52  * @param fd_out output array, at least max_fd long
53  * @param max_fd maximum number of file descriptors to write
54  * @return number of file descriptors written into the output array
55  */
56 ssize_t listen_on_all_addrs(unsigned int port, int *fd_out, size_t max_fd)
57 {
58   int rc = 0;
59   int conn = -1;
60   int optval = 1;
61   int gai_retval = 0;
62   struct addrinfo *ai=NULL;
63   struct addrinfo *ai_head=NULL;
64   struct addrinfo hints={
65       .ai_flags=AI_PASSIVE,
66       .ai_family=AF_UNSPEC,
67       .ai_socktype=SOCK_STREAM,
68       .ai_protocol=IPPROTO_TCP
69   };
70   char *port_str=NULL;
71   size_t n_opened=0;
72
73   port_str=talloc_asprintf(NULL, "%d", port);
74   if (port_str==NULL) {
75     tr_err("listen_on_all_addrs: unable to allocate port");
76     return -1;
77   }
78
79   gai_retval = getaddrinfo(NULL, port_str, &hints, &ai_head);
80   talloc_free(port_str);
81   if (gai_retval != 0) {
82     tr_err("listen_on_all_addrs: getaddrinfo() failed (%s)", gai_strerror(gai_retval));
83     return -1;
84   }
85   tr_debug("listen_on_all_addrs: got address info");
86
87   /* TODO: listen on all ports - I don't recall what this means (jlr, 4/11/2018) */
88   for (ai=ai_head,n_opened=0; (ai!=NULL)&&(n_opened<max_fd); ai=ai->ai_next) {
89     if (0 > (conn = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))) {
90       tr_debug("listen_on_all_addrs: unable to open socket");
91       continue;
92     }
93
94     optval=1;
95     if (0!=setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
96       tr_debug("tids_listen: unable to set SO_REUSEADDR"); /* not fatal? */
97
98     if (ai->ai_family==AF_INET6) {
99       /* don't allow IPv4-mapped IPv6 addresses (per RFC4942, not sure
100        * if still relevant) */
101       if (0!=setsockopt(conn, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval))) {
102         tr_debug("listen_on_all_addrs: unable to set IPV6_V6ONLY, skipping interface");
103         close(conn);
104         continue;
105       }
106     }
107
108     rc=bind(conn, ai->ai_addr, ai->ai_addrlen);
109     if (rc<0) {
110       tr_debug("listen_on_all_addrs: unable to bind to socket");
111       close(conn);
112       continue;
113     }
114
115     if (0>listen(conn, 512)) {
116       tr_debug("listen_on_all_addrs: unable to listen on bound socket");
117       close(conn);
118       continue;
119     }
120
121     /* ok, this one worked. Save it */
122     fd_out[n_opened++]=conn;
123   }
124   freeaddrinfo(ai_head);
125
126   if (n_opened==0) {
127     tr_debug("listen_on_all_addrs: no addresses available for listening.");
128     return -1;
129   }
130
131   tr_debug("listen_on_all_addrs: monitoring interface listening on port %d on %d socket%s",
132            port,
133            n_opened,
134            (n_opened==1)?"":"s");
135
136   return n_opened;
137 }