385547e0e78936c7de06aa6380292b51d9bec6b9
[samba.git] / ctdb / tcp / tcp_connect.c
1 /* 
2    ctdb over TCP
3
4    Copyright (C) Andrew Tridgell  2006
5    Copyright (C) Ronnie Sahlberg  2008
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "replace.h"
22 #include "system/network.h"
23 #include "system/filesys.h"
24
25 #include <talloc.h>
26 #include <tevent.h>
27
28 #include "lib/util/debug.h"
29 #include "lib/util/time.h"
30 #include "lib/util/blocking.h"
31
32 #include "ctdb_private.h"
33
34 #include "common/system.h"
35 #include "common/common.h"
36 #include "common/logging.h"
37
38 #include "ctdb_tcp.h"
39
40 /*
41   stop any connecting (established or pending) to a node
42  */
43 void ctdb_tcp_stop_connection(struct ctdb_node *node)
44 {
45         struct ctdb_tcp_node *tnode = talloc_get_type(
46                 node->private_data, struct ctdb_tcp_node);
47         
48         ctdb_queue_set_fd(tnode->out_queue, -1);
49         talloc_free(tnode->connect_te);
50         talloc_free(tnode->connect_fde);
51         tnode->connect_fde = NULL;
52         tnode->connect_te = NULL;
53         if (tnode->fd != -1) {
54                 close(tnode->fd);
55                 tnode->fd = -1;
56         }
57 }
58
59
60 /*
61   called when a complete packet has come in - should not happen on this socket
62   unless the other side closes the connection with RST or FIN
63  */
64 void ctdb_tcp_tnode_cb(uint8_t *data, size_t cnt, void *private_data)
65 {
66         struct ctdb_node *node = talloc_get_type(private_data, struct ctdb_node);
67         struct ctdb_tcp_node *tnode = talloc_get_type(
68                 node->private_data, struct ctdb_tcp_node);
69
70         if (data == NULL) {
71                 node->ctdb->upcalls->node_dead(node);
72         }
73
74         ctdb_tcp_stop_connection(node);
75         tnode->connect_te = tevent_add_timer(node->ctdb->ev, tnode,
76                                              timeval_current_ofs(3, 0),
77                                              ctdb_tcp_node_connect, node);
78         TALLOC_FREE(data);
79 }
80
81 /*
82   called when socket becomes writeable on connect
83 */
84 static void ctdb_node_connect_write(struct tevent_context *ev,
85                                     struct tevent_fd *fde,
86                                     uint16_t flags, void *private_data)
87 {
88         struct ctdb_node *node = talloc_get_type(private_data,
89                                                  struct ctdb_node);
90         struct ctdb_tcp_node *tnode = talloc_get_type(node->private_data,
91                                                       struct ctdb_tcp_node);
92         struct ctdb_context *ctdb = node->ctdb;
93         int error = 0;
94         socklen_t len = sizeof(error);
95         int one = 1;
96
97         talloc_free(tnode->connect_te);
98         tnode->connect_te = NULL;
99
100         if (getsockopt(tnode->fd, SOL_SOCKET, SO_ERROR, &error, &len) != 0 ||
101             error != 0) {
102                 ctdb_tcp_stop_connection(node);
103                 tnode->connect_te = tevent_add_timer(ctdb->ev, tnode,
104                                                     timeval_current_ofs(1, 0),
105                                                     ctdb_tcp_node_connect, node);
106                 return;
107         }
108
109         talloc_free(tnode->connect_fde);
110         tnode->connect_fde = NULL;
111
112         if (setsockopt(tnode->fd,IPPROTO_TCP,TCP_NODELAY,(char *)&one,sizeof(one)) == -1) {
113                 DEBUG(DEBUG_WARNING, ("Failed to set TCP_NODELAY on fd - %s\n",
114                                       strerror(errno)));
115         }
116         if (setsockopt(tnode->fd,SOL_SOCKET,SO_KEEPALIVE,(char *)&one,sizeof(one)) == -1) {
117                 DEBUG(DEBUG_WARNING, ("Failed to set KEEPALIVE on fd - %s\n",
118                                       strerror(errno)));
119         }
120
121         ctdb_queue_set_fd(tnode->out_queue, tnode->fd);
122
123         /* the queue subsystem now owns this fd */
124         tnode->fd = -1;
125
126         /* tell the ctdb layer we are connected */
127         node->ctdb->upcalls->node_connected(node);
128 }
129
130
131 /*
132   called when we should try and establish a tcp connection to a node
133 */
134 void ctdb_tcp_node_connect(struct tevent_context *ev, struct tevent_timer *te,
135                            struct timeval t, void *private_data)
136 {
137         struct ctdb_node *node = talloc_get_type(private_data,
138                                                  struct ctdb_node);
139         struct ctdb_tcp_node *tnode = talloc_get_type(node->private_data, 
140                                                       struct ctdb_tcp_node);
141         struct ctdb_context *ctdb = node->ctdb;
142         ctdb_sock_addr sock_in;
143         int sockin_size;
144         int sockout_size;
145         ctdb_sock_addr sock_out;
146         int ret;
147
148         ctdb_tcp_stop_connection(node);
149
150         sock_out = node->address;
151
152         tnode->fd = socket(sock_out.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
153         if (tnode->fd == -1) {
154                 DEBUG(DEBUG_ERR, (__location__ " Failed to create socket\n"));
155                 return;
156         }
157
158         ret = set_blocking(tnode->fd, false);
159         if (ret != 0) {
160                 DEBUG(DEBUG_ERR,
161                       (__location__
162                        " failed to set socket non-blocking (%s)\n",
163                        strerror(errno)));
164                 close(tnode->fd);
165                 tnode->fd = -1;
166                 return;
167         }
168
169         set_close_on_exec(tnode->fd);
170
171         DEBUG(DEBUG_DEBUG, (__location__ " Created TCP SOCKET FD:%d\n", tnode->fd));
172
173         /* Bind our side of the socketpair to the same address we use to listen
174          * on incoming CTDB traffic.
175          * We must specify this address to make sure that the address we expose to
176          * the remote side is actually routable in case CTDB traffic will run on
177          * a dedicated non-routeable network.
178          */
179         sock_in = *ctdb->address;
180
181         /* AIX libs check to see if the socket address and length
182            arguments are consistent with each other on calls like
183            connect().   Can not get by with just sizeof(sock_in),
184            need sizeof(sock_in.ip).
185         */
186         switch (sock_in.sa.sa_family) {
187         case AF_INET:
188                 sock_in.ip.sin_port = 0 /* Any port */;
189                 sockin_size = sizeof(sock_in.ip);
190                 sockout_size = sizeof(sock_out.ip);
191                 break;
192         case AF_INET6:
193                 sock_in.ip6.sin6_port = 0 /* Any port */;
194                 sockin_size = sizeof(sock_in.ip6);
195                 sockout_size = sizeof(sock_out.ip6);
196                 break;
197         default:
198                 DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n",
199                         sock_in.sa.sa_family));
200                 close(tnode->fd);
201                 tnode->fd = -1;
202                 return;
203         }
204
205         if (bind(tnode->fd, (struct sockaddr *)&sock_in, sockin_size) == -1) {
206                 DEBUG(DEBUG_ERR, (__location__ " Failed to bind socket %s(%d)\n",
207                                   strerror(errno), errno));
208                 close(tnode->fd);
209                 tnode->fd = -1;
210                 return;
211         }
212
213         if (connect(tnode->fd, (struct sockaddr *)&sock_out, sockout_size) != 0 &&
214             errno != EINPROGRESS) {
215                 ctdb_tcp_stop_connection(node);
216                 tnode->connect_te = tevent_add_timer(ctdb->ev, tnode,
217                                                      timeval_current_ofs(1, 0),
218                                                      ctdb_tcp_node_connect, node);
219                 return;
220         }
221
222         /* non-blocking connect - wait for write event */
223         tnode->connect_fde = tevent_add_fd(node->ctdb->ev, tnode, tnode->fd,
224                                            TEVENT_FD_WRITE|TEVENT_FD_READ,
225                                            ctdb_node_connect_write, node);
226
227         /* don't give it long to connect - retry in one second. This ensures
228            that we find a node is up quickly (tcp normally backs off a syn reply
229            delay by quite a lot) */
230         tnode->connect_te = tevent_add_timer(ctdb->ev, tnode,
231                                              timeval_current_ofs(1, 0),
232                                              ctdb_tcp_node_connect, node);
233 }
234
235 /*
236   called when we get contacted by another node
237   currently makes no attempt to check if the connection is really from a ctdb
238   node in our cluster
239 */
240 static void ctdb_listen_event(struct tevent_context *ev, struct tevent_fd *fde,
241                               uint16_t flags, void *private_data)
242 {
243         struct ctdb_context *ctdb = talloc_get_type(private_data, struct ctdb_context);
244         struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data, struct ctdb_tcp);
245         ctdb_sock_addr addr;
246         socklen_t len;
247         int fd, nodeid;
248         struct ctdb_incoming *in;
249         int one = 1;
250         int ret;
251
252         memset(&addr, 0, sizeof(addr));
253         len = sizeof(addr);
254         fd = accept(ctcp->listen_fd, (struct sockaddr *)&addr, &len);
255         if (fd == -1) return;
256         smb_set_close_on_exec(fd);
257
258         nodeid = ctdb_ip_to_nodeid(ctdb, &addr);
259
260         if (nodeid == -1) {
261                 DEBUG(DEBUG_ERR, ("Refused connection from unknown node %s\n", ctdb_addr_to_str(&addr)));
262                 close(fd);
263                 return;
264         }
265
266         in = talloc_zero(ctcp, struct ctdb_incoming);
267         in->fd = fd;
268         in->ctdb = ctdb;
269
270         ret = set_blocking(in->fd, false);
271         if (ret != 0) {
272                 DEBUG(DEBUG_ERR,
273                       (__location__
274                        " failed to set socket non-blocking (%s)\n",
275                        strerror(errno)));
276                 close(in->fd);
277                 in->fd = -1;
278                 return;
279         }
280
281         set_close_on_exec(in->fd);
282
283         DEBUG(DEBUG_DEBUG, (__location__ " Created SOCKET FD:%d to incoming ctdb connection\n", fd));
284
285         if (setsockopt(in->fd,SOL_SOCKET,SO_KEEPALIVE,(char *)&one,sizeof(one)) == -1) {
286                 DEBUG(DEBUG_WARNING, ("Failed to set KEEPALIVE on fd - %s\n",
287                                       strerror(errno)));
288         }
289
290         in->queue = ctdb_queue_setup(ctdb, in, in->fd, CTDB_TCP_ALIGNMENT,
291                                      ctdb_tcp_read_cb, in, "ctdbd-%s", ctdb_addr_to_str(&addr));
292 }
293
294
295 /*
296   automatically find which address to listen on
297 */
298 static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb)
299 {
300         struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data,
301                                                 struct ctdb_tcp);
302         ctdb_sock_addr sock;
303         int lock_fd, i;
304         const char *lock_path = CTDB_RUNDIR "/.socket_lock";
305         struct flock lock;
306         int one = 1;
307         int sock_size;
308         struct tevent_fd *fde;
309
310         /* If there are no nodes, then it won't be possible to find
311          * the first one.  Log a failure and short circuit the whole
312          * process.
313          */
314         if (ctdb->num_nodes == 0) {
315                 DEBUG(DEBUG_CRIT,("No nodes available to attempt bind to - is the nodes file empty?\n"));
316                 return -1;
317         }
318
319         /* in order to ensure that we don't get two nodes with the
320            same adddress, we must make the bind() and listen() calls
321            atomic. The SO_REUSEADDR setsockopt only prevents double
322            binds if the first socket is in LISTEN state  */
323         lock_fd = open(lock_path, O_RDWR|O_CREAT, 0666);
324         if (lock_fd == -1) {
325                 DEBUG(DEBUG_CRIT,("Unable to open %s\n", lock_path));
326                 return -1;
327         }
328
329         lock.l_type = F_WRLCK;
330         lock.l_whence = SEEK_SET;
331         lock.l_start = 0;
332         lock.l_len = 1;
333         lock.l_pid = 0;
334
335         if (fcntl(lock_fd, F_SETLKW, &lock) != 0) {
336                 DEBUG(DEBUG_CRIT,("Unable to lock %s\n", lock_path));
337                 close(lock_fd);
338                 return -1;
339         }
340
341         for (i=0; i < ctdb->num_nodes; i++) {
342                 if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) {
343                         continue;
344                 }
345                 sock = ctdb->nodes[i]->address;
346
347                 switch (sock.sa.sa_family) {
348                 case AF_INET:
349                         sock_size = sizeof(sock.ip);
350                         break;
351                 case AF_INET6:
352                         sock_size = sizeof(sock.ip6);
353                         break;
354                 default:
355                         DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n",
356                                 sock.sa.sa_family));
357                         continue;
358                 }
359
360                 ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
361                 if (ctcp->listen_fd == -1) {
362                         ctdb_set_error(ctdb, "socket failed\n");
363                         continue;
364                 }
365
366                 set_close_on_exec(ctcp->listen_fd);
367
368                 if (setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,
369                                (char *)&one,sizeof(one)) == -1) {
370                         DEBUG(DEBUG_WARNING, ("Failed to set REUSEADDR on fd - %s\n",
371                                               strerror(errno)));
372                 }
373
374                 if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) == 0) {
375                         break;
376                 }
377
378                 if (errno == EADDRNOTAVAIL) {
379                         DEBUG(DEBUG_DEBUG,(__location__ " Failed to bind() to socket. %s(%d)\n",
380                                         strerror(errno), errno));
381                 } else {
382                         DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n",
383                                         strerror(errno), errno));
384                 }
385
386                 close(ctcp->listen_fd);
387                 ctcp->listen_fd = -1;
388         }
389
390         if (i == ctdb->num_nodes) {
391                 DEBUG(DEBUG_CRIT,("Unable to bind to any of the node addresses - giving up\n"));
392                 goto failed;
393         }
394         ctdb->address = talloc_memdup(ctdb,
395                                       &ctdb->nodes[i]->address,
396                                       sizeof(ctdb_sock_addr));
397         if (ctdb->address == NULL) {
398                 ctdb_set_error(ctdb, "Out of memory at %s:%d",
399                                __FILE__, __LINE__);
400                 goto failed;
401         }
402
403         ctdb->name = talloc_asprintf(ctdb, "%s:%u",
404                                      ctdb_addr_to_str(ctdb->address),
405                                      ctdb_addr_to_port(ctdb->address));
406         if (ctdb->name == NULL) {
407                 ctdb_set_error(ctdb, "Out of memory at %s:%d",
408                                __FILE__, __LINE__);
409                 goto failed;
410         }
411         DEBUG(DEBUG_INFO,("ctdb chose network address %s\n", ctdb->name));
412
413         if (listen(ctcp->listen_fd, 10) == -1) {
414                 goto failed;
415         }
416
417         fde = tevent_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, TEVENT_FD_READ,
418                             ctdb_listen_event, ctdb);
419         tevent_fd_set_auto_close(fde);
420
421         close(lock_fd);
422
423         return 0;
424
425 failed:
426         close(lock_fd);
427         if (ctcp->listen_fd != -1) {
428                 close(ctcp->listen_fd);
429                 ctcp->listen_fd = -1;
430         }
431         return -1;
432 }
433
434
435 /*
436   listen on our own address
437 */
438 int ctdb_tcp_listen(struct ctdb_context *ctdb)
439 {
440         struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data,
441                                                 struct ctdb_tcp);
442         ctdb_sock_addr sock;
443         int sock_size;
444         int one = 1;
445         struct tevent_fd *fde;
446
447         /* we can either auto-bind to the first available address, or we can
448            use a specified address */
449         if (!ctdb->address) {
450                 return ctdb_tcp_listen_automatic(ctdb);
451         }
452
453         sock = *ctdb->address;
454
455         switch (sock.sa.sa_family) {
456         case AF_INET:
457                 sock_size = sizeof(sock.ip);
458                 break;
459         case AF_INET6:
460                 sock_size = sizeof(sock.ip6);
461                 break;
462         default:
463                 DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n",
464                         sock.sa.sa_family));
465                 goto failed;
466         }
467
468         ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
469         if (ctcp->listen_fd == -1) {
470                 ctdb_set_error(ctdb, "socket failed\n");
471                 return -1;
472         }
473
474         set_close_on_exec(ctcp->listen_fd);
475
476         if (setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one)) == -1) {
477                 DEBUG(DEBUG_WARNING, ("Failed to set REUSEADDR on fd - %s\n",
478                                       strerror(errno)));
479         }
480
481         if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) != 0) {
482                 DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno));
483                 goto failed;
484         }
485
486         if (listen(ctcp->listen_fd, 10) == -1) {
487                 goto failed;
488         }
489
490         fde = tevent_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, TEVENT_FD_READ,
491                             ctdb_listen_event, ctdb);
492         tevent_fd_set_auto_close(fde);
493
494         return 0;
495
496 failed:
497         if (ctcp->listen_fd != -1) {
498                 close(ctcp->listen_fd);
499         }
500         ctcp->listen_fd = -1;
501         return -1;
502 }
503