Log incoming IP address when accepting a connection
[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 #include <errno.h>
44
45 /**
46  * Open sockets on all interface addresses
47  *
48  * Uses getaddrinfo() to find all TCP addresses and opens sockets in
49  * non-blocking modes. Binds to most max_fd sockets and stores file descriptors
50  * in fd_out. Unused entries in fd_out are not modified. Returns the actual
51  * number of sockets opened.
52  *
53  * @param port port to listen on
54  * @param fd_out output array, at least max_fd long
55  * @param max_fd maximum number of file descriptors to write
56  * @return number of file descriptors written into the output array
57  */
58 nfds_t tr_sock_listen_all(unsigned int port, int *fd_out, nfds_t max_fd)
59 {
60   int rc = 0;
61   int conn = -1;
62   int optval = 1;
63   int gai_retval = 0;
64   struct addrinfo *ai=NULL;
65   struct addrinfo *ai_head=NULL;
66   struct addrinfo hints={
67       .ai_flags=AI_PASSIVE,
68       .ai_family=AF_UNSPEC,
69       .ai_socktype=SOCK_STREAM,
70       .ai_protocol=IPPROTO_TCP
71   };
72   char *port_str=NULL;
73   nfds_t n_opened=0;
74
75   port_str=talloc_asprintf(NULL, "%d", port);
76   if (port_str==NULL) {
77     tr_err("tr_sock_listen_all: unable to allocate port");
78     return 0;
79   }
80
81   gai_retval = getaddrinfo(NULL, port_str, &hints, &ai_head);
82   talloc_free(port_str);
83   if (gai_retval != 0) {
84     tr_err("tr_sock_listen_all: getaddrinfo() failed (%s)", gai_strerror(gai_retval));
85     return 0;
86   }
87   tr_debug("tr_sock_listen_all: got address info");
88
89   /* TODO: listen on all ports - I don't recall what this means (jlr, 4/11/2018) */
90   for (ai=ai_head,n_opened=0; (ai!=NULL)&&(n_opened<max_fd); ai=ai->ai_next) {
91     if (0 > (conn = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol))) {
92       tr_debug("tr_sock_listen_all: unable to open socket");
93       continue;
94     }
95
96     optval=1;
97     if (0!=setsockopt(conn, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)))
98       tr_debug("tids_listen: unable to set SO_REUSEADDR"); /* not fatal? */
99
100     if (ai->ai_family==AF_INET6) {
101       /* don't allow IPv4-mapped IPv6 addresses (per RFC4942, not sure
102        * if still relevant) */
103       if (0!=setsockopt(conn, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval))) {
104         tr_debug("tr_sock_listen_all: unable to set IPV6_V6ONLY, skipping interface");
105         close(conn);
106         continue;
107       }
108     }
109
110     rc=bind(conn, ai->ai_addr, ai->ai_addrlen);
111     if (rc<0) {
112       tr_debug("tr_sock_listen_all: unable to bind to socket");
113       close(conn);
114       continue;
115     }
116
117     if (0>listen(conn, 512)) {
118       tr_debug("tr_sock_listen_all: unable to listen on bound socket");
119       close(conn);
120       continue;
121     }
122
123     /* ok, this one worked. Save it */
124     fd_out[n_opened++]=conn;
125   }
126   freeaddrinfo(ai_head);
127
128   if (n_opened==0) {
129     tr_debug("tr_sock_listen_all: no addresses available for listening.");
130     return 0;
131   }
132
133   tr_debug("tr_sock_listen_all: listening on port %d on %d socket%s",
134            port,
135            n_opened,
136            (n_opened==1)?"":"s");
137
138   return n_opened;
139 }
140
141 /**
142  * Extract a string-formatted socket address from a struct sockaddr
143  *
144  * @param s
145  * @param dst pointer to allocated space of at least INET6_ADDRSLEN bytes
146  * @param dst_len size of space allocated at dst
147  * @return pointer to dst or null on error
148  */
149 static const char *tr_sock_ip_address(struct sockaddr *s, char *dst, size_t dst_len)
150 {
151   switch (s->sa_family) {
152     case AF_INET:
153       inet_ntop(AF_INET,
154                 &(((struct sockaddr_in *)s)->sin_addr),
155                 dst,
156                 (socklen_t) dst_len);
157       break;
158
159     case AF_INET6:
160       inet_ntop(AF_INET6,
161                 &(((struct sockaddr_in6 *)s)->sin6_addr),
162                 dst,
163                 (socklen_t) dst_len);
164       break;
165
166     default:
167       snprintf(dst, dst_len, "addr family %u", s->sa_family);
168       break;
169   }
170
171   return dst;
172 }
173
174 /**
175  * Accept a socket connection
176  *
177  * @param sock
178  * @return -1 on error, connection fd on success
179  */
180 int tr_sock_accept(int sock)
181 {
182   int conn = -1;
183   struct sockaddr_storage peeraddr;
184   socklen_t addr_len = sizeof(peeraddr);
185   char peeraddr_string[INET6_ADDRSTRLEN];
186   char err[80];
187
188   if (0 > (conn = accept(sock, (struct sockaddr *)&(peeraddr), &addr_len))) {
189     if (strerror_r(errno, err, sizeof(err)))
190       snprintf(err, sizeof(err), "errno = %d", errno);
191     tr_err("tr_sock_accept: Unable to accept connection: %s", err);
192   } else {
193     tr_notice("tr_sock_accept: Incoming connection on fd %d from %s",
194               conn,
195               tr_sock_ip_address((struct sockaddr *)&peeraddr,
196                                  peeraddr_string,
197                                  sizeof(peeraddr_string)));
198   }
199   return conn;
200 }