7f1c917e6d4cee05e6a486a9046c9fcee6f85cc9
[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 #include <poll.h> // for nfds_t
40
41 #include <tr_debug.h>
42 #include <tr_socket.h>
43
44 /**
45  * Open sockets on all interface addresses
46  *
47  * Uses getaddrinfo() to find all TCP addresses and opens sockets in
48  * non-blocking modes. Binds to most max_fd sockets and stores file descriptors
49  * in fd_out. Unused entries in fd_out are not modified. Returns the actual
50  * number of sockets opened.
51  *
52  * @param port port to listen on
53  * @param fd_out output array, at least max_fd long
54  * @param max_fd maximum number of file descriptors to write
55  * @return number of file descriptors written into the output array
56  */
57 nfds_t tr_sock_listen_all(unsigned int port, int *fd_out, nfds_t max_fd)
58 {
59   int rc = 0;
60   int conn = -1;
61   int optval = 1;
62   int gai_retval = 0;
63   struct addrinfo *ai=NULL;
64   struct addrinfo *ai_head=NULL;
65   struct addrinfo hints={
66       .ai_flags=AI_PASSIVE,
67       .ai_family=AF_UNSPEC,
68       .ai_socktype=SOCK_STREAM,
69       .ai_protocol=IPPROTO_TCP
70   };
71   char *port_str=NULL;
72   nfds_t n_opened=0;
73
74   port_str=talloc_asprintf(NULL, "%d", port);
75   if (port_str==NULL) {
76     tr_err("tr_sock_listen_all: unable to allocate port");
77     return 0;
78   }
79
80   gai_retval = getaddrinfo(NULL, port_str, &hints, &ai_head);
81   talloc_free(port_str);
82   if (gai_retval != 0) {
83     tr_err("tr_sock_listen_all: getaddrinfo() failed (%s)", gai_strerror(gai_retval));
84     return 0;
85   }
86   tr_debug("tr_sock_listen_all: got address info");
87
88   /* TODO: listen on all ports - I don't recall what this means (jlr, 4/11/2018) */
89   for (ai=ai_head,n_opened=0; (ai!=NULL)&&(n_opened<max_fd); ai=ai->ai_next) {
90     if (0 > (conn = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))) {
91       tr_debug("tr_sock_listen_all: unable to open socket");
92       continue;
93     }
94
95     optval=1;
96     if (0!=setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
97       tr_debug("tids_listen: unable to set SO_REUSEADDR"); /* not fatal? */
98
99     if (ai->ai_family==AF_INET6) {
100       /* don't allow IPv4-mapped IPv6 addresses (per RFC4942, not sure
101        * if still relevant) */
102       if (0!=setsockopt(conn, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval))) {
103         tr_debug("tr_sock_listen_all: unable to set IPV6_V6ONLY, skipping interface");
104         close(conn);
105         continue;
106       }
107     }
108
109     rc=bind(conn, ai->ai_addr, ai->ai_addrlen);
110     if (rc<0) {
111       tr_debug("tr_sock_listen_all: unable to bind to socket");
112       close(conn);
113       continue;
114     }
115
116     if (0>listen(conn, 512)) {
117       tr_debug("tr_sock_listen_all: unable to listen on bound socket");
118       close(conn);
119       continue;
120     }
121
122     /* ok, this one worked. Save it */
123     fd_out[n_opened++]=conn;
124   }
125   freeaddrinfo(ai_head);
126
127   if (n_opened==0) {
128     tr_debug("tr_sock_listen_all: no addresses available for listening.");
129     return 0;
130   }
131
132   tr_debug("tr_sock_listen_all: listening on port %d on %d socket%s",
133            port,
134            n_opened,
135            (n_opened==1)?"":"s");
136
137   return n_opened;
138 }
139