]> git.meshlink.io Git - meshlink-tiny/blob - src/net_socket.c
Remove support for multiple connections.
[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 static void free_outgoing(outgoing_t *outgoing) {
293         meshlink_handle_t *mesh = outgoing->node->mesh;
294
295         timeout_del(&mesh->loop, &outgoing->ev);
296
297         if(outgoing->ai) {
298                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
299                         free_known_addresses(outgoing->ai);
300                 } else {
301                         freeaddrinfo(outgoing->ai);
302                 }
303         }
304
305         free(outgoing);
306 }
307
308 void do_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
309 begin:
310
311         if(!get_next_outgoing_address(mesh, outgoing)) {
312                 if(outgoing->state == OUTGOING_CANONICAL_RESOLVE) {
313                         /* We are waiting for a callback from the ADNS thread */
314                 } else if(outgoing->state == OUTGOING_NO_KNOWN_ADDRESSES) {
315                         logger(mesh, MESHLINK_ERROR, "No known addresses for %s", outgoing->node->name);
316                         free_outgoing(outgoing);
317                         mesh->outgoing = NULL;
318                 } else {
319                         logger(mesh, MESHLINK_ERROR, "Could not set up a meta connection to %s", outgoing->node->name);
320                         retry_outgoing(mesh, outgoing);
321                 }
322
323                 return;
324         }
325
326         connection_t *c = new_connection();
327         c->outgoing = outgoing;
328
329         memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
330
331         if(mesh->log_level <= MESHLINK_INFO) {
332                 char *hostname = sockaddr2hostname(&c->address);
333                 logger(mesh, MESHLINK_INFO, "Trying to connect to %s at %s", outgoing->node->name, hostname);
334                 free(hostname);
335         }
336
337         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
338
339         if(c->socket == -1) {
340                 if(mesh->log_level <= MESHLINK_ERROR) {
341                         char *hostname = sockaddr2hostname(&c->address);
342                         logger(mesh, MESHLINK_ERROR, "Creating socket for %s at %s failed: %s", c->name, hostname, sockstrerror(sockerrno));
343                         free(hostname);
344                 }
345
346                 free_connection(c);
347                 goto begin;
348         }
349
350         configure_tcp(c);
351
352 #ifdef FD_CLOEXEC
353         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
354 #endif
355
356 #if defined(IPV6_V6ONLY)
357
358         if(c->address.sa.sa_family == AF_INET6) {
359                 static const int option = 1;
360                 setsockopt(c->socket, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof(option));
361         }
362
363 #endif
364
365         /* Connect */
366
367         int result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
368
369         if(result == -1 && !sockinprogress(sockerrno)) {
370                 if(mesh->log_level <= MESHLINK_ERROR) {
371                         char *hostname = sockaddr2hostname(&c->address);
372                         logger(mesh, MESHLINK_ERROR, "Could not connect to %s: %s", outgoing->node->name, sockstrerror(sockerrno));
373                         free(hostname);
374                 }
375
376                 free_connection(c);
377                 goto begin;
378         }
379
380         /* Now that there is a working socket, fill in the rest and register this connection. */
381
382         c->status.connecting = true;
383         c->status.initiator = true;
384         c->name = xstrdup(outgoing->node->name);
385         c->last_ping_time = mesh->loop.now.tv_sec;
386
387         connection_add(mesh, c);
388
389         io_add(&mesh->loop, &c->io, handle_meta_io, c, c->socket, IO_READ | IO_WRITE);
390 }
391
392 void reset_outgoing(outgoing_t *outgoing) {
393         if(outgoing->ai) {
394                 if(outgoing->state == OUTGOING_RECENT || outgoing->state == OUTGOING_KNOWN) {
395                         free_known_addresses(outgoing->ai);
396                 } else {
397                         freeaddrinfo(outgoing->ai);
398                 }
399         }
400
401         outgoing->ai = NULL;
402         outgoing->aip = NULL;
403         outgoing->state = OUTGOING_START;
404 }
405
406 void setup_outgoing_connection(meshlink_handle_t *mesh, outgoing_t *outgoing) {
407         timeout_del(&mesh->loop, &outgoing->ev);
408
409         if(outgoing->node->connection) {
410                 logger(mesh, MESHLINK_INFO, "Already connected to %s", outgoing->node->name);
411
412                 outgoing->node->connection->outgoing = outgoing;
413                 return;
414         }
415
416         reset_outgoing(outgoing);
417
418         if(outgoing->node->status.blacklisted) {
419                 return;
420         }
421
422         if(mesh->connection_try_cb) {
423                 mesh->connection_try_cb(mesh, (meshlink_node_t *)outgoing->node);
424         }
425
426         do_outgoing_connection(mesh, outgoing);
427 }
428
429 void init_outgoings(meshlink_handle_t *mesh) {
430         mesh->outgoing = NULL;
431 }
432
433 void exit_outgoings(meshlink_handle_t *mesh) {
434         if(mesh->outgoing) {
435                 free_outgoing(mesh->outgoing);
436                 mesh->outgoing = NULL;
437         }
438 }