]> git.meshlink.io Git - meshlink-tiny/blob - src/net_socket.c
Remove listening sockets.
[meshlink-tiny] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "conf.h"
23 #include "connection.h"
24 #include "list.h"
25 #include "logger.h"
26 #include "meshlink_internal.h"
27 #include "meta.h"
28 #include "net.h"
29 #include "netutl.h"
30 #include "protocol.h"
31 #include "utils.h"
32 #include "xalloc.h"
33
34 /* Needed on Mac OS/X */
35 #ifndef SOL_TCP
36 #define SOL_TCP IPPROTO_TCP
37 #endif
38
39 #ifndef MSG_NOSIGNAL
40 #define MSG_NOSIGNAL 0
41 #endif
42
43 /* Setup sockets */
44
45 static void configure_tcp(connection_t *c) {
46 #ifdef O_NONBLOCK
47         int flags = fcntl(c->socket, F_GETFL);
48
49         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
50                 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "fcntl", strerror(errno));
51         }
52
53 #elif defined(WIN32)
54         unsigned long arg = 1;
55
56         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
57                 logger(c->mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
58         }
59
60 #endif
61
62 #if defined(SOL_TCP) && defined(TCP_NODELAY)
63         int nodelay = 1;
64         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&nodelay, sizeof(nodelay));
65 #endif
66
67 #if defined(IP_TOS) && defined(IPTOS_LOWDELAY)
68         int lowdelay = IPTOS_LOWDELAY;
69         setsockopt(c->socket, IPPROTO_IP, IP_TOS, (void *)&lowdelay, sizeof(lowdelay));
70 #endif
71
72 #if defined(SO_NOSIGPIPE)
73         int nosigpipe = 1;
74         setsockopt(c->socket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&nosigpipe, sizeof(nosigpipe));
75 #endif
76 }
77
78 static void retry_outgoing_handler(event_loop_t *loop, void *data) {
79         assert(data);
80
81         meshlink_handle_t *mesh = loop->data;
82         outgoing_t *outgoing = data;
83         setup_outgoing_connection(mesh, outgoing);
84 }
85
86 void retry_outgoing(meshlink_handle_t *mesh, outgoing_t *outgoing) {
87         if(!mesh->reachable && mesh->loop.now.tv_sec < mesh->last_unreachable + mesh->dev_class_traits[outgoing->node->devclass].fast_retry_period) {
88                 outgoing->timeout = 1;
89         } else {
90                 outgoing->timeout += 5;
91         }
92
93         int maxtimeout = mesh->dev_class_traits[outgoing->node->devclass].maxtimeout;
94
95         if(outgoing->timeout > maxtimeout) {
96                 outgoing->timeout = maxtimeout;
97         }
98
99         timeout_add(&mesh->loop, &outgoing->ev, retry_outgoing_handler, outgoing, &(struct timespec) {
100                 outgoing->timeout, prng(mesh, TIMER_FUDGE)
101         });
102
103         logger(mesh, MESHLINK_INFO, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
104 }
105
106 void finish_connecting(meshlink_handle_t *mesh, connection_t *c) {
107         logger(mesh, MESHLINK_INFO, "Connected to %s", c->name);
108
109         c->last_ping_time = mesh->loop.now.tv_sec;
110         c->status.connecting = false;
111
112         send_id(mesh, c);
113 }
114
115 static void handle_meta_write(meshlink_handle_t *mesh, connection_t *c) {
116         if(c->outbuf.len <= c->outbuf.offset) {
117                 return;
118         }
119
120         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, MSG_NOSIGNAL);
121
122         if(outlen <= 0) {
123                 if(!errno || errno == EPIPE) {
124                         logger(mesh, MESHLINK_INFO, "Connection closed by %s", c->name);
125                 } else if(sockwouldblock(sockerrno)) {
126                         logger(mesh, MESHLINK_DEBUG, "Sending %lu bytes to %s would block", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name);
127                         return;
128                 } else {
129                         logger(mesh, MESHLINK_ERROR, "Could not send %lu bytes of data to %s: %s", (unsigned long)(c->outbuf.len - c->outbuf.offset), c->name, strerror(errno));
130                 }
131
132                 terminate_connection(mesh, c, c->status.active);
133                 return;
134         }
135
136         buffer_read(&c->outbuf, outlen);
137
138         if(!c->outbuf.len) {
139                 io_set(&mesh->loop, &c->io, IO_READ);
140         }
141 }
142
143 void flush_meta(meshlink_handle_t *mesh, connection_t *c) {
144         handle_meta_write(mesh, c);
145 }
146
147 static void handle_meta_io(event_loop_t *loop, void *data, int flags) {
148         meshlink_handle_t *mesh = loop->data;
149         connection_t *c = data;
150
151         if(c->status.connecting) {
152                 c->status.connecting = false;
153
154                 int result;
155                 socklen_t len = sizeof(result);
156                 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
157
158                 if(!result) {
159                         finish_connecting(mesh, c);
160                 } else {
161                         logger(mesh, MESHLINK_ERROR, "Error while connecting to %s: %s", c->name, sockstrerror(result));
162                         terminate_connection(mesh, c, false);
163                         return;
164                 }
165         }
166
167         if(flags & IO_WRITE) {
168                 handle_meta_write(mesh, c);
169         } else {
170                 handle_meta_connection_data(mesh, c);
171         }
172 }
173
174 // Build a list of recently seen addresses.
175 static struct addrinfo *get_recent_addresses(node_t *n) {
176         struct addrinfo *ai = NULL;
177         struct addrinfo *aip;
178
179         for(int i = 0; i < 5; i++) {
180                 if(!n->recent[i].sa.sa_family) {
181                         break;
182                 }
183
184                 // Create a new struct addrinfo, and put it at the end of the list.
185                 struct addrinfo *nai = xzalloc(sizeof(*nai) + SALEN(n->recent[i].sa));
186
187                 if(!ai) {
188                         ai = nai;
189                 } else {
190                         aip->ai_next = nai;
191                 }
192
193                 aip = nai;
194
195                 nai->ai_family = n->recent[i].sa.sa_family;
196                 nai->ai_socktype = SOCK_STREAM;
197                 nai->ai_protocol = IPPROTO_TCP;
198                 nai->ai_addrlen = SALEN(n->recent[i].sa);
199                 nai->ai_addr = (struct sockaddr *)(nai + 1);
200                 memcpy(nai->ai_addr, &n->recent[i], nai->ai_addrlen);
201         }
202
203         return ai;
204 }
205
206 // Free struct addrinfo list from get_known_addresses().
207 static void free_known_addresses(struct addrinfo *ai) {
208         for(struct addrinfo *aip = ai, *next; aip; aip = next) {
209                 next = aip->ai_next;
210                 free(aip);
211         }
212 }
213
214 static bool get_next_outgoing_address(meshlink_handle_t *mesh, outgoing_t *outgoing) {
215         (void)mesh;
216
217         bool start = false;
218
219         if(outgoing->state == OUTGOING_START) {
220                 start = true;
221                 outgoing->state = OUTGOING_CANONICAL_RESOLVE;
222         }
223
224         if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
225                 node_t *n = outgoing->node;
226
227                 if(n->canonical_address) {
228                         char *address = xstrdup(n->canonical_address);
229                         char *port = strchr(address, ' ');
230
231                         if(port) {
232                                 *port++ = 0;
233                                 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
234                                 outgoing->aip = NULL;
235                                 outgoing->state = OUTGOING_CANONICAL;
236                         } else {
237                                 logger(mesh, MESHLINK_ERROR, "Canonical address for %s is missing port number", n->name);
238                                 outgoing->state = OUTGOING_RECENT;
239                         }
240
241                         free(address);
242                 } else {
243                         outgoing->state = OUTGOING_RECENT;
244                 }
245         }
246
247         if(outgoing->state == OUTGOING_CANONICAL) {
248                 if(!outgoing->aip) {
249                         outgoing->aip = outgoing->ai;
250                 } else {
251                         outgoing->aip = outgoing->aip->ai_next;
252                 }
253
254                 if(outgoing->aip) {
255                         return true;
256                 }
257
258                 if(outgoing->ai) {
259                         freeaddrinfo(outgoing->ai);
260                 }
261
262                 outgoing->ai = NULL;
263                 outgoing->aip = NULL;
264                 outgoing->state = OUTGOING_END;
265         }
266
267         if(outgoing->state == OUTGOING_RECENT) {
268                 if(!outgoing->aip) {
269                         outgoing->ai = get_recent_addresses(outgoing->node);
270                         outgoing->aip = outgoing->ai;
271                 } else {
272                         outgoing->aip = outgoing->aip->ai_next;
273                 }
274
275                 if(outgoing->aip) {
276                         return true;
277                 }
278
279                 free_known_addresses(outgoing->ai);
280                 outgoing->ai = NULL;
281                 outgoing->aip = NULL;
282                 outgoing->state = OUTGOING_END;
283         }
284
285         if(start) {
286                 outgoing->state = OUTGOING_NO_KNOWN_ADDRESSES;
287         }
288
289         return false;
290 }
291
292 void do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
293 begin:
294
295         if(!get_next_outgoing_address(mesh, outgoing)) {
296                 if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
297                         /* We are waiting for a callback from the ADNS thread */
298                 } else if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
299                         logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->node->name);
300                         list_delete(mesh->outgoings, outgoing);
301                 } else {
302                         logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
303                         retry_outgoing(mesh, outgoing);
304                 }
305
306                 return;
307         }
308
309         connection_t *c = new_connection();
310         c->outgoing = outgoing;
311
312         memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
313
314         if(mesh->log_level <= MESHLINK_INFO) {
315                 char *hostname = sockaddr2hostname(&c->address);
316                 logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->node->name, hostname);
317                 free(hostname);
318         }
319
320         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
321
322         if(c->socket == -1) {
323                 if(mesh->log_level <= MESHLINK_ERROR) {
324                         char *hostname = sockaddr2hostname(&c->address);
325                         logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
326                         free(hostname);
327                 }
328
329                 free_connection(c);
330                 goto begin;
331         }
332
333         configure_tcp(c);
334
335 #ifdef FD_CLOEXEC
336         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
337 #endif
338
339 #if defined(IPV6_V6ONLY)
340
341         if(c->address.sa.sa_family == AF_INET6) {
342                 static const int option = 1;
343                 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
344         }
345
346 #endif
347
348         /* Connect */
349
350         int result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
351
352         if(result == -1 && !sockinprogress(sockerrno)) {
353                 if(mesh->log_level <= MESHLINK_ERROR) {
354                         char *hostname = sockaddr2hostname(&c->address);
355                         logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->node->name, sockstrerror(sockerrno));
356                         free(hostname);
357                 }
358
359                 free_connection(c);
360                 goto begin;
361         }
362
363         /* Now that there is a working socket, fill in the rest and register this connection. */
364
365         c->status.connecting = true;
366         c->status.initiator = true;
367         c->name = xstrdup(outgoing->node->name);
368         c->last_ping_time = mesh->loop.now.tv_sec;
369
370         connection_add(mesh, c);
371
372         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
373 }
374
375 void reset_outgoing(outgoing_t *outgoing) {
376         if(outgoing->ai) {
377                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
378                         free_known_addresses(outgoing->ai);
379                 } else {
380                         freeaddrinfo(outgoing->ai);
381                 }
382         }
383
384         outgoing->ai = NULL;
385         outgoing->aip = NULL;
386         outgoing->state = OUTGOING_START;
387 }
388
389 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
390         timeout_del(&mesh->loop, &outgoing->ev);
391
392         if(outgoing->node->connection) {
393                 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
394
395                 outgoing->node->connection->outgoing = outgoing;
396                 return;
397         }
398
399         reset_outgoing(outgoing);
400
401         if(outgoing->node->status.blacklisted) {
402                 return;
403         }
404
405         if(mesh->connection_try_cb) {
406                 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
407         }
408
409         do_outgoing_connection(mesh, outgoing);
410 }
411
412 static void free_outgoing(outgoing_t *outgoing) {
413         meshlink_handle_t *mesh = outgoing->node->mesh;
414
415         timeout_del(&mesh->loop, &outgoing->ev);
416
417         if(outgoing->ai) {
418                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
419                         free_known_addresses(outgoing->ai);
420                 } else {
421                         freeaddrinfo(outgoing->ai);
422                 }
423         }
424
425         free(outgoing);
426 }
427
428 void init_outgoings(meshlink_handle_t *mesh) {
429         mesh->outgoings = list_alloc((list_action_t)free_outgoing);
430 }
431
432 void exit_outgoings(meshlink_handle_t *mesh) {
433         if(mesh->outgoings) {
434                 list_delete_list(mesh->outgoings);
435                 mesh->outgoings = NULL;
436         }
437 }