lib: Make ctdbd_register_ips return 0/errno
[bbaumbach/samba-autobuild/.git] / source3 / lib / ctdbd_conn.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba internal messaging functions
4    Copyright (C) 2007 by Volker Lendecke
5    Copyright (C) 2007 by Andrew Tridgell
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 "includes.h"
22 #include "util_tdb.h"
23 #include "serverid.h"
24 #include "ctdbd_conn.h"
25 #include "system/select.h"
26 #include "lib/sys_rw_data.h"
27 #include "lib/util/iov_buf.h"
28
29 #include "messages.h"
30
31 /* paths to these include files come from --with-ctdb= in configure */
32
33 #include "ctdb.h"
34 #include "ctdb_private.h"
35
36 struct ctdbd_srvid_cb {
37         uint64_t srvid;
38         int (*cb)(uint32_t src_vnn, uint32_t dst_vnn,
39                   uint64_t dst_srvid,
40                   const uint8_t *msg, size_t msglen,
41                   void *private_data);
42         void *private_data;
43 };
44
45 struct ctdbd_connection {
46         const char *sockname;   /* Needed in ctdbd_traverse */
47         struct messaging_context *msg_ctx;
48         uint32_t reqid;
49         uint32_t our_vnn;
50         uint64_t rand_srvid;
51         struct ctdbd_srvid_cb *callbacks;
52         int fd;
53         struct tevent_fd *fde;
54         int timeout;
55 };
56
57 static uint32_t ctdbd_next_reqid(struct ctdbd_connection *conn)
58 {
59         conn->reqid += 1;
60         if (conn->reqid == 0) {
61                 conn->reqid += 1;
62         }
63         return conn->reqid;
64 }
65
66 static int ctdbd_control(struct ctdbd_connection *conn,
67                          uint32_t vnn, uint32_t opcode,
68                          uint64_t srvid, uint32_t flags,
69                          TDB_DATA data,
70                          TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
71                          int *cstatus);
72
73 /*
74  * exit on fatal communications errors with the ctdbd daemon
75  */
76 static void cluster_fatal(const char *why)
77 {
78         DEBUG(0,("cluster fatal event: %s - exiting immediately\n", why));
79         /* we don't use smb_panic() as we don't want to delay to write
80            a core file. We need to release this process id immediately
81            so that someone else can take over without getting sharing
82            violations */
83         _exit(1);
84 }
85
86 /*
87  *
88  */
89 static void ctdb_packet_dump(struct ctdb_req_header *hdr)
90 {
91         if (DEBUGLEVEL < 11) {
92                 return;
93         }
94         DEBUGADD(11, ("len=%d, magic=%x, vers=%d, gen=%d, op=%d, reqid=%d\n",
95                       (int)hdr->length, (int)hdr->ctdb_magic,
96                       (int)hdr->ctdb_version, (int)hdr->generation,
97                       (int)hdr->operation, (int)hdr->reqid));
98 }
99
100 /*
101  * Register a srvid with ctdbd
102  */
103 int register_with_ctdbd(struct ctdbd_connection *conn, uint64_t srvid,
104                         int (*cb)(uint32_t src_vnn, uint32_t dst_vnn,
105                                   uint64_t dst_srvid,
106                                   const uint8_t *msg, size_t msglen,
107                                   void *private_data),
108                         void *private_data)
109 {
110
111         int ret, cstatus;
112         size_t num_callbacks;
113         struct ctdbd_srvid_cb *tmp;
114
115         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
116                             CTDB_CONTROL_REGISTER_SRVID, srvid, 0,
117                             tdb_null, NULL, NULL, &cstatus);
118         if (ret != 0) {
119                 return ret;
120         }
121
122         num_callbacks = talloc_array_length(conn->callbacks);
123
124         tmp = talloc_realloc(conn, conn->callbacks, struct ctdbd_srvid_cb,
125                              num_callbacks + 1);
126         if (tmp == NULL) {
127                 return ENOMEM;
128         }
129         conn->callbacks = tmp;
130
131         conn->callbacks[num_callbacks] = (struct ctdbd_srvid_cb) {
132                 .srvid = srvid, .cb = cb, .private_data = private_data
133         };
134
135         return 0;
136 }
137
138 static int ctdbd_msg_call_back(struct ctdbd_connection *conn,
139                                struct ctdb_req_message *msg)
140 {
141         size_t msg_len;
142         size_t i, num_callbacks;
143
144         msg_len = msg->hdr.length;
145         if (msg_len < offsetof(struct ctdb_req_message, data)) {
146                 DEBUG(10, ("%s: len %u too small\n", __func__,
147                            (unsigned)msg_len));
148                 return 0;
149         }
150         msg_len -= offsetof(struct ctdb_req_message, data);
151
152         if (msg_len < msg->datalen) {
153                 DEBUG(10, ("%s: msg_len=%u < msg->datalen=%u\n", __func__,
154                            (unsigned)msg_len, (unsigned)msg->datalen));
155                 return 0;
156         }
157
158         num_callbacks = talloc_array_length(conn->callbacks);
159
160         for (i=0; i<num_callbacks; i++) {
161                 struct ctdbd_srvid_cb *cb = &conn->callbacks[i];
162
163                 if ((cb->srvid == msg->srvid) && (cb->cb != NULL)) {
164                         int ret;
165
166                         ret = cb->cb(msg->hdr.srcnode, msg->hdr.destnode,
167                                      msg->srvid, msg->data, msg->datalen,
168                                      cb->private_data);
169                         if (ret != 0) {
170                                 return ret;
171                         }
172                 }
173         }
174         return 0;
175 }
176
177 /*
178  * get our vnn from the cluster
179  */
180 static int get_cluster_vnn(struct ctdbd_connection *conn, uint32_t *vnn)
181 {
182         int32_t cstatus=-1;
183         int ret;
184         ret = ctdbd_control(conn,
185                             CTDB_CURRENT_NODE, CTDB_CONTROL_GET_PNN, 0, 0,
186                             tdb_null, NULL, NULL, &cstatus);
187         if (ret != 0) {
188                 DEBUG(1, ("ctdbd_control failed: %s\n", strerror(ret)));
189                 return ret;
190         }
191         *vnn = (uint32_t)cstatus;
192         return ret;
193 }
194
195 /*
196  * Are we active (i.e. not banned or stopped?)
197  */
198 static bool ctdbd_working(struct ctdbd_connection *conn, uint32_t vnn)
199 {
200         int32_t cstatus=-1;
201         TDB_DATA outdata;
202         struct ctdb_node_map *m;
203         uint32_t failure_flags;
204         bool ok = false;
205         int i, ret;
206
207         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
208                             CTDB_CONTROL_GET_NODEMAP, 0, 0,
209                             tdb_null, talloc_tos(), &outdata, &cstatus);
210         if (ret != 0) {
211                 DEBUG(1, ("ctdbd_control failed: %s\n", strerror(ret)));
212                 return false;
213         }
214         if ((cstatus != 0) || (outdata.dptr == NULL)) {
215                 DEBUG(2, ("Received invalid ctdb data\n"));
216                 return false;
217         }
218
219         m = (struct ctdb_node_map *)outdata.dptr;
220
221         for (i=0; i<m->num; i++) {
222                 if (vnn == m->nodes[i].pnn) {
223                         break;
224                 }
225         }
226
227         if (i == m->num) {
228                 DEBUG(2, ("Did not find ourselves (node %d) in nodemap\n",
229                           (int)vnn));
230                 goto fail;
231         }
232
233         failure_flags = NODE_FLAGS_BANNED | NODE_FLAGS_DISCONNECTED
234                 | NODE_FLAGS_PERMANENTLY_DISABLED | NODE_FLAGS_STOPPED;
235
236         if ((m->nodes[i].flags & failure_flags) != 0) {
237                 DEBUG(2, ("Node has status %x, not active\n",
238                           (int)m->nodes[i].flags));
239                 goto fail;
240         }
241
242         ok = true;
243 fail:
244         TALLOC_FREE(outdata.dptr);
245         return ok;
246 }
247
248 uint32_t ctdbd_vnn(const struct ctdbd_connection *conn)
249 {
250         return conn->our_vnn;
251 }
252
253 /*
254  * Get us a ctdb connection
255  */
256
257 static int ctdbd_connect(const char *sockname, int *pfd)
258 {
259         struct sockaddr_un addr = { 0, };
260         int fd;
261         socklen_t salen;
262         size_t namelen;
263
264         fd = socket(AF_UNIX, SOCK_STREAM, 0);
265         if (fd == -1) {
266                 int err = errno;
267                 DEBUG(3, ("Could not create socket: %s\n", strerror(err)));
268                 return err;
269         }
270
271         addr.sun_family = AF_UNIX;
272
273         namelen = strlcpy(addr.sun_path, sockname, sizeof(addr.sun_path));
274         if (namelen >= sizeof(addr.sun_path)) {
275                 DEBUG(3, ("%s: Socket name too long: %s\n", __func__,
276                           sockname));
277                 close(fd);
278                 return ENAMETOOLONG;
279         }
280
281         salen = sizeof(struct sockaddr_un);
282
283         if (connect(fd, (struct sockaddr *)(void *)&addr, salen) == -1) {
284                 int err = errno;
285                 DEBUG(1, ("connect(%s) failed: %s\n", sockname,
286                           strerror(err)));
287                 close(fd);
288                 return err;
289         }
290
291         *pfd = fd;
292         return 0;
293 }
294
295 static int ctdb_read_packet(int fd, int timeout, TALLOC_CTX *mem_ctx,
296                             struct ctdb_req_header **result)
297 {
298         struct ctdb_req_header *req;
299         int ret, revents;
300         uint32_t msglen;
301         ssize_t nread;
302
303         if (timeout != -1) {
304                 ret = poll_one_fd(fd, POLLIN, timeout, &revents);
305                 if (ret == -1) {
306                         return errno;
307                 }
308                 if (ret == 0) {
309                         return ETIMEDOUT;
310                 }
311                 if (ret != 1) {
312                         return EIO;
313                 }
314         }
315
316         nread = read_data(fd, &msglen, sizeof(msglen));
317         if (nread == -1) {
318                 return errno;
319         }
320         if (nread == 0) {
321                 return EIO;
322         }
323
324         if (msglen < sizeof(struct ctdb_req_header)) {
325                 return EIO;
326         }
327
328         req = talloc_size(mem_ctx, msglen);
329         if (req == NULL) {
330                 return ENOMEM;
331         }
332         talloc_set_name_const(req, "struct ctdb_req_header");
333
334         req->length = msglen;
335
336         nread = read_data(fd, ((char *)req) + sizeof(msglen),
337                           msglen - sizeof(msglen));
338         if (nread == -1) {
339                 TALLOC_FREE(req);
340                 return errno;
341         }
342         if (nread == 0) {
343                 TALLOC_FREE(req);
344                 return EIO;
345         }
346
347         *result = req;
348         return 0;
349 }
350
351 /*
352  * Read a full ctdbd request. If we have a messaging context, defer incoming
353  * messages that might come in between.
354  */
355
356 static int ctdb_read_req(struct ctdbd_connection *conn, uint32_t reqid,
357                          TALLOC_CTX *mem_ctx, struct ctdb_req_header **result)
358 {
359         struct ctdb_req_header *hdr;
360         int ret;
361
362  next_pkt:
363
364         ret = ctdb_read_packet(conn->fd, conn->timeout, mem_ctx, &hdr);
365         if (ret != 0) {
366                 DEBUG(0, ("ctdb_read_packet failed: %s\n", strerror(ret)));
367                 cluster_fatal("ctdbd died\n");
368         }
369
370         DEBUG(11, ("Received ctdb packet\n"));
371         ctdb_packet_dump(hdr);
372
373         if (hdr->operation == CTDB_REQ_MESSAGE) {
374                 struct ctdb_req_message *msg = (struct ctdb_req_message *)hdr;
375
376                 if (conn->msg_ctx == NULL) {
377                         DEBUG(1, ("Got a message without having a msg ctx, "
378                                   "dropping msg %llu\n",
379                                   (long long unsigned)msg->srvid));
380                         TALLOC_FREE(hdr);
381                         goto next_pkt;
382                 }
383
384                 ret = ctdbd_msg_call_back(conn, msg);
385                 if (ret != 0) {
386                         TALLOC_FREE(hdr);
387                         return ret;
388                 }
389
390                 TALLOC_FREE(hdr);
391                 goto next_pkt;
392         }
393
394         if ((reqid != 0) && (hdr->reqid != reqid)) {
395                 /* we got the wrong reply */
396                 DEBUG(0,("Discarding mismatched ctdb reqid %u should have "
397                          "been %u\n", hdr->reqid, reqid));
398                 TALLOC_FREE(hdr);
399                 goto next_pkt;
400         }
401
402         *result = talloc_move(mem_ctx, &hdr);
403
404         return 0;
405 }
406
407 static int ctdbd_connection_destructor(struct ctdbd_connection *c)
408 {
409         TALLOC_FREE(c->fde);
410         if (c->fd != -1) {
411                 close(c->fd);
412                 c->fd = -1;
413         }
414         return 0;
415 }
416 /*
417  * Get us a ctdbd connection
418  */
419
420 static int ctdbd_init_connection(TALLOC_CTX *mem_ctx,
421                                  const char *sockname, int timeout,
422                                  struct ctdbd_connection **pconn)
423 {
424         struct ctdbd_connection *conn;
425         int ret;
426
427         if (!(conn = talloc_zero(mem_ctx, struct ctdbd_connection))) {
428                 DEBUG(0, ("talloc failed\n"));
429                 return ENOMEM;
430         }
431
432         conn->sockname = talloc_strdup(conn, sockname);
433         if (conn->sockname == NULL) {
434                 DBG_ERR("%s: talloc failed\n", __func__);
435                 ret = ENOMEM;
436                 goto fail;
437         }
438
439         conn->timeout = timeout;
440
441         if (conn->timeout == 0) {
442                 conn->timeout = -1;
443         }
444
445         ret = ctdbd_connect(conn->sockname, &conn->fd);
446         if (ret != 0) {
447                 DEBUG(1, ("ctdbd_connect failed: %s\n", strerror(ret)));
448                 goto fail;
449         }
450         talloc_set_destructor(conn, ctdbd_connection_destructor);
451
452         ret = get_cluster_vnn(conn, &conn->our_vnn);
453
454         if (ret != 0) {
455                 DEBUG(10, ("get_cluster_vnn failed: %s\n", strerror(ret)));
456                 goto fail;
457         }
458
459         if (!ctdbd_working(conn, conn->our_vnn)) {
460                 DEBUG(2, ("Node is not working, can not connect\n"));
461                 ret = EIO;
462                 goto fail;
463         }
464
465         generate_random_buffer((unsigned char *)&conn->rand_srvid,
466                                sizeof(conn->rand_srvid));
467
468         ret = register_with_ctdbd(conn, conn->rand_srvid, NULL, NULL);
469
470         if (ret != 0) {
471                 DEBUG(5, ("Could not register random srvid: %s\n",
472                           strerror(ret)));
473                 goto fail;
474         }
475
476         *pconn = conn;
477         return 0;
478
479  fail:
480         TALLOC_FREE(conn);
481         return ret;
482 }
483
484 /*
485  * Get us a ctdbd connection and register us as a process
486  */
487
488 int ctdbd_messaging_connection(TALLOC_CTX *mem_ctx,
489                                const char *sockname, int timeout,
490                                struct ctdbd_connection **pconn)
491 {
492         struct ctdbd_connection *conn;
493         int ret;
494
495         ret = ctdbd_init_connection(mem_ctx, sockname, timeout, &conn);
496
497         if (ret != 0) {
498                 return ret;
499         }
500
501         ret = register_with_ctdbd(conn, MSG_SRVID_SAMBA, NULL, NULL);
502         if (ret != 0) {
503                 goto fail;
504         }
505
506         *pconn = conn;
507         return 0;
508
509  fail:
510         TALLOC_FREE(conn);
511         return ret;
512 }
513
514 struct messaging_context *ctdb_conn_msg_ctx(struct ctdbd_connection *conn)
515 {
516         return conn->msg_ctx;
517 }
518
519 int ctdbd_conn_get_fd(struct ctdbd_connection *conn)
520 {
521         return conn->fd;
522 }
523
524 /*
525  * Packet handler to receive and handle a ctdb message
526  */
527 static int ctdb_handle_message(struct ctdbd_connection *conn,
528                                struct ctdb_req_header *hdr)
529 {
530         struct ctdb_req_message *msg;
531
532         if (hdr->operation != CTDB_REQ_MESSAGE) {
533                 DEBUG(0, ("Received async msg of type %u, discarding\n",
534                           hdr->operation));
535                 return EINVAL;
536         }
537
538         msg = (struct ctdb_req_message *)hdr;
539
540         ctdbd_msg_call_back(conn, msg);
541
542         return 0;
543 }
544
545 /*
546  * The ctdbd socket is readable asynchronuously
547  */
548
549 static void ctdbd_socket_handler(struct tevent_context *event_ctx,
550                                  struct tevent_fd *event,
551                                  uint16_t flags,
552                                  void *private_data)
553 {
554         struct ctdbd_connection *conn = talloc_get_type_abort(
555                 private_data, struct ctdbd_connection);
556         struct ctdb_req_header *hdr = NULL;
557         int ret;
558
559         ret = ctdb_read_packet(conn->fd, conn->timeout, talloc_tos(), &hdr);
560         if (ret != 0) {
561                 DEBUG(0, ("ctdb_read_packet failed: %s\n", strerror(ret)));
562                 cluster_fatal("ctdbd died\n");
563         }
564
565         ret = ctdb_handle_message(conn, hdr);
566
567         TALLOC_FREE(hdr);
568
569         if (ret != 0) {
570                 DEBUG(10, ("could not handle incoming message: %s\n",
571                            strerror(ret)));
572         }
573 }
574
575 /*
576  * Prepare a ctdbd connection to receive messages
577  */
578
579 int ctdbd_register_msg_ctx(struct ctdbd_connection *conn,
580                            struct messaging_context *msg_ctx)
581 {
582         SMB_ASSERT(conn->msg_ctx == NULL);
583         SMB_ASSERT(conn->fde == NULL);
584
585         if (!(conn->fde = tevent_add_fd(messaging_tevent_context(msg_ctx),
586                                        conn,
587                                        conn->fd,
588                                        TEVENT_FD_READ,
589                                        ctdbd_socket_handler,
590                                        conn))) {
591                 DEBUG(0, ("event_add_fd failed\n"));
592                 return ENOMEM;
593         }
594
595         conn->msg_ctx = msg_ctx;
596
597         return 0;
598 }
599
600 int ctdbd_messaging_send_iov(struct ctdbd_connection *conn,
601                              uint32_t dst_vnn, uint64_t dst_srvid,
602                              const struct iovec *iov, int iovlen)
603 {
604         struct ctdb_req_message r;
605         struct iovec iov2[iovlen+1];
606         size_t buflen = iov_buflen(iov, iovlen);
607         ssize_t nwritten;
608
609         r.hdr.length = offsetof(struct ctdb_req_message, data) + buflen;
610         r.hdr.ctdb_magic = CTDB_MAGIC;
611         r.hdr.ctdb_version = CTDB_PROTOCOL;
612         r.hdr.generation = 1;
613         r.hdr.operation  = CTDB_REQ_MESSAGE;
614         r.hdr.destnode   = dst_vnn;
615         r.hdr.srcnode    = conn->our_vnn;
616         r.hdr.reqid      = 0;
617         r.srvid          = dst_srvid;
618         r.datalen        = buflen;
619
620         DEBUG(10, ("ctdbd_messaging_send: Sending ctdb packet\n"));
621         ctdb_packet_dump(&r.hdr);
622
623         iov2[0].iov_base = &r;
624         iov2[0].iov_len = offsetof(struct ctdb_req_message, data);
625         memcpy(&iov2[1], iov, iovlen * sizeof(struct iovec));
626
627         nwritten = write_data_iov(conn->fd, iov2, iovlen+1);
628         if (nwritten == -1) {
629                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
630                 cluster_fatal("cluster dispatch daemon msg write error\n");
631         }
632
633         return 0;
634 }
635
636 /*
637  * send/recv a generic ctdb control message
638  */
639 static int ctdbd_control(struct ctdbd_connection *conn,
640                          uint32_t vnn, uint32_t opcode,
641                          uint64_t srvid, uint32_t flags,
642                          TDB_DATA data,
643                          TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
644                          int *cstatus)
645 {
646         struct ctdb_req_control req;
647         struct ctdb_req_header *hdr;
648         struct ctdb_reply_control *reply = NULL;
649         struct iovec iov[2];
650         ssize_t nwritten;
651         int ret;
652
653         ZERO_STRUCT(req);
654         req.hdr.length = offsetof(struct ctdb_req_control, data) + data.dsize;
655         req.hdr.ctdb_magic   = CTDB_MAGIC;
656         req.hdr.ctdb_version = CTDB_PROTOCOL;
657         req.hdr.operation    = CTDB_REQ_CONTROL;
658         req.hdr.reqid        = ctdbd_next_reqid(conn);
659         req.hdr.destnode     = vnn;
660         req.opcode           = opcode;
661         req.srvid            = srvid;
662         req.datalen          = data.dsize;
663         req.flags            = flags;
664
665         DEBUG(10, ("ctdbd_control: Sending ctdb packet\n"));
666         ctdb_packet_dump(&req.hdr);
667
668         iov[0].iov_base = &req;
669         iov[0].iov_len = offsetof(struct ctdb_req_control, data);
670         iov[1].iov_base = data.dptr;
671         iov[1].iov_len = data.dsize;
672
673         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
674         if (nwritten == -1) {
675                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
676                 cluster_fatal("cluster dispatch daemon msg write error\n");
677         }
678
679         if (flags & CTDB_CTRL_FLAG_NOREPLY) {
680                 if (cstatus) {
681                         *cstatus = 0;
682                 }
683                 return 0;
684         }
685
686         ret = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
687         if (ret != 0) {
688                 DEBUG(10, ("ctdb_read_req failed: %s\n", strerror(ret)));
689                 return ret;
690         }
691
692         if (hdr->operation != CTDB_REPLY_CONTROL) {
693                 DEBUG(0, ("received invalid reply\n"));
694                 TALLOC_FREE(hdr);
695                 return EIO;
696         }
697         reply = (struct ctdb_reply_control *)hdr;
698
699         if (outdata) {
700                 if (!(outdata->dptr = (uint8_t *)talloc_memdup(
701                               mem_ctx, reply->data, reply->datalen))) {
702                         TALLOC_FREE(reply);
703                         return ENOMEM;
704                 }
705                 outdata->dsize = reply->datalen;
706         }
707         if (cstatus) {
708                 (*cstatus) = reply->status;
709         }
710
711         TALLOC_FREE(reply);
712         return ret;
713 }
714
715 /*
716  * see if a remote process exists
717  */
718 bool ctdbd_process_exists(struct ctdbd_connection *conn, uint32_t vnn, pid_t pid)
719 {
720         struct server_id id;
721         bool result;
722
723         id.pid = pid;
724         id.vnn = vnn;
725
726         if (!ctdb_processes_exist(conn, &id, 1, &result)) {
727                 DEBUG(10, ("ctdb_processes_exist failed\n"));
728                 return false;
729         }
730         return result;
731 }
732
733 bool ctdb_processes_exist(struct ctdbd_connection *conn,
734                           const struct server_id *pids, int num_pids,
735                           bool *results)
736 {
737         TALLOC_CTX *frame = talloc_stackframe();
738         int i, num_received;
739         uint32_t *reqids;
740         bool result = false;
741
742         reqids = talloc_array(talloc_tos(), uint32_t, num_pids);
743         if (reqids == NULL) {
744                 goto fail;
745         }
746
747         for (i=0; i<num_pids; i++) {
748                 struct ctdb_req_control req;
749                 pid_t pid;
750                 struct iovec iov[2];
751                 ssize_t nwritten;
752
753                 results[i] = false;
754                 reqids[i] = ctdbd_next_reqid(conn);
755
756                 ZERO_STRUCT(req);
757
758                 /*
759                  * pids[i].pid is uint64_t, scale down to pid_t which
760                  * is the wire protocol towards ctdb.
761                  */
762                 pid = pids[i].pid;
763
764                 DEBUG(10, ("Requesting PID %d/%d, reqid=%d\n",
765                            (int)pids[i].vnn, (int)pid,
766                            (int)reqids[i]));
767
768                 req.hdr.length = offsetof(struct ctdb_req_control, data);
769                 req.hdr.length += sizeof(pid);
770                 req.hdr.ctdb_magic   = CTDB_MAGIC;
771                 req.hdr.ctdb_version = CTDB_PROTOCOL;
772                 req.hdr.operation    = CTDB_REQ_CONTROL;
773                 req.hdr.reqid        = reqids[i];
774                 req.hdr.destnode     = pids[i].vnn;
775                 req.opcode           = CTDB_CONTROL_PROCESS_EXISTS;
776                 req.srvid            = 0;
777                 req.datalen          = sizeof(pid);
778                 req.flags            = 0;
779
780                 DEBUG(10, ("ctdbd_control: Sending ctdb packet\n"));
781                 ctdb_packet_dump(&req.hdr);
782
783                 iov[0].iov_base = &req;
784                 iov[0].iov_len = offsetof(struct ctdb_req_control, data);
785                 iov[1].iov_base = &pid;
786                 iov[1].iov_len = sizeof(pid);
787
788                 nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
789                 if (nwritten == -1) {
790                         DEBUG(10, ("write_data_iov failed: %s\n",
791                                    strerror(errno)));
792                         goto fail;
793                 }
794         }
795
796         num_received = 0;
797
798         while (num_received < num_pids) {
799                 struct ctdb_req_header *hdr;
800                 struct ctdb_reply_control *reply;
801                 uint32_t reqid;
802                 int ret;
803
804                 ret = ctdb_read_req(conn, 0, talloc_tos(), &hdr);
805                 if (ret != 0) {
806                         DEBUG(10, ("ctdb_read_req failed: %s\n",
807                                    strerror(ret)));
808                         goto fail;
809                 }
810
811                 if (hdr->operation != CTDB_REPLY_CONTROL) {
812                         DEBUG(10, ("Received invalid reply\n"));
813                         goto fail;
814                 }
815                 reply = (struct ctdb_reply_control *)hdr;
816
817                 reqid = reply->hdr.reqid;
818
819                 DEBUG(10, ("Received reqid %d\n", (int)reqid));
820
821                 for (i=0; i<num_pids; i++) {
822                         if (reqid == reqids[i]) {
823                                 break;
824                         }
825                 }
826                 if (i == num_pids) {
827                         DEBUG(10, ("Received unknown record number %u\n",
828                                    (unsigned)reqid));
829                         goto fail;
830                 }
831                 results[i] = ((reply->status) == 0);
832                 TALLOC_FREE(reply);
833                 num_received += 1;
834         }
835
836         result = true;
837 fail:
838         TALLOC_FREE(frame);
839         return result;
840 }
841
842 /*
843  * Get a db path
844  */
845 char *ctdbd_dbpath(struct ctdbd_connection *conn,
846                    TALLOC_CTX *mem_ctx, uint32_t db_id)
847 {
848         int ret;
849         TDB_DATA data;
850         TDB_DATA rdata = {0};
851         int32_t cstatus = 0;
852
853         data.dptr = (uint8_t*)&db_id;
854         data.dsize = sizeof(db_id);
855
856         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
857                             CTDB_CONTROL_GETDBPATH, 0, 0, data,
858                             mem_ctx, &rdata, &cstatus);
859         if ((ret != 0) || cstatus != 0) {
860                 DEBUG(0, (__location__ " ctdb_control for getdbpath failed: %s\n",
861                           strerror(ret)));
862                 return NULL;
863         }
864
865         return (char *)rdata.dptr;
866 }
867
868 /*
869  * attach to a ctdb database
870  */
871 int ctdbd_db_attach(struct ctdbd_connection *conn,
872                     const char *name, uint32_t *db_id, int tdb_flags)
873 {
874         int ret;
875         TDB_DATA data;
876         int32_t cstatus;
877         bool persistent = (tdb_flags & TDB_CLEAR_IF_FIRST) == 0;
878
879         data = string_term_tdb_data(name);
880
881         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
882                             persistent
883                             ? CTDB_CONTROL_DB_ATTACH_PERSISTENT
884                             : CTDB_CONTROL_DB_ATTACH,
885                             tdb_flags, 0, data, NULL, &data, &cstatus);
886         if (ret != 0) {
887                 DEBUG(0, (__location__ " ctdb_control for db_attach "
888                           "failed: %s\n", strerror(ret)));
889                 return ret;
890         }
891
892         if (cstatus != 0 || data.dsize != sizeof(uint32_t)) {
893                 DEBUG(0,(__location__ " ctdb_control for db_attach failed\n"));
894                 return EIO;
895         }
896
897         *db_id = *(uint32_t *)data.dptr;
898         talloc_free(data.dptr);
899
900         if (!(tdb_flags & TDB_SEQNUM)) {
901                 return 0;
902         }
903
904         data.dptr = (uint8_t *)db_id;
905         data.dsize = sizeof(*db_id);
906
907         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
908                             CTDB_CONTROL_ENABLE_SEQNUM, 0, 0, data,
909                             NULL, NULL, &cstatus);
910         if ((ret != 0) || cstatus != 0) {
911                 DEBUG(0, (__location__ " ctdb_control for enable seqnum "
912                           "failed: %s\n", strerror(ret)));
913                 return (ret == 0) ? EIO : ret;
914         }
915
916         return 0;
917 }
918
919 /*
920  * force the migration of a record to this node
921  */
922 int ctdbd_migrate(struct ctdbd_connection *conn, uint32_t db_id, TDB_DATA key)
923 {
924         struct ctdb_req_call req;
925         struct ctdb_req_header *hdr;
926         struct iovec iov[2];
927         ssize_t nwritten;
928         int ret;
929
930         ZERO_STRUCT(req);
931
932         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
933         req.hdr.ctdb_magic   = CTDB_MAGIC;
934         req.hdr.ctdb_version = CTDB_PROTOCOL;
935         req.hdr.operation    = CTDB_REQ_CALL;
936         req.hdr.reqid        = ctdbd_next_reqid(conn);
937         req.flags            = CTDB_IMMEDIATE_MIGRATION;
938         req.callid           = CTDB_NULL_FUNC;
939         req.db_id            = db_id;
940         req.keylen           = key.dsize;
941
942         DEBUG(10, ("ctdbd_migrate: Sending ctdb packet\n"));
943         ctdb_packet_dump(&req.hdr);
944
945         iov[0].iov_base = &req;
946         iov[0].iov_len = offsetof(struct ctdb_req_call, data);
947         iov[1].iov_base = key.dptr;
948         iov[1].iov_len = key.dsize;
949
950         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
951         if (nwritten == -1) {
952                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
953                 cluster_fatal("cluster dispatch daemon msg write error\n");
954         }
955
956         ret = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
957         if (ret != 0) {
958                 DEBUG(10, ("ctdb_read_req failed: %s\n", strerror(ret)));
959                 goto fail;
960         }
961
962         if (hdr->operation != CTDB_REPLY_CALL) {
963                 DEBUG(0, ("received invalid reply\n"));
964                 goto fail;
965         }
966
967  fail:
968
969         TALLOC_FREE(hdr);
970         return ret;
971 }
972
973 /*
974  * Fetch a record and parse it
975  */
976 int ctdbd_parse(struct ctdbd_connection *conn, uint32_t db_id,
977                 TDB_DATA key, bool local_copy,
978                 void (*parser)(TDB_DATA key, TDB_DATA data,
979                                void *private_data),
980                 void *private_data)
981 {
982         struct ctdb_req_call req;
983         struct ctdb_req_header *hdr = NULL;
984         struct ctdb_reply_call *reply;
985         struct iovec iov[2];
986         ssize_t nwritten;
987         uint32_t flags;
988         int ret;
989
990         flags = local_copy ? CTDB_WANT_READONLY : 0;
991
992         ZERO_STRUCT(req);
993
994         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
995         req.hdr.ctdb_magic   = CTDB_MAGIC;
996         req.hdr.ctdb_version = CTDB_PROTOCOL;
997         req.hdr.operation    = CTDB_REQ_CALL;
998         req.hdr.reqid        = ctdbd_next_reqid(conn);
999         req.flags            = flags;
1000         req.callid           = CTDB_FETCH_FUNC;
1001         req.db_id            = db_id;
1002         req.keylen           = key.dsize;
1003
1004         iov[0].iov_base = &req;
1005         iov[0].iov_len = offsetof(struct ctdb_req_call, data);
1006         iov[1].iov_base = key.dptr;
1007         iov[1].iov_len = key.dsize;
1008
1009         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
1010         if (nwritten == -1) {
1011                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
1012                 cluster_fatal("cluster dispatch daemon msg write error\n");
1013         }
1014
1015         ret = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
1016         if (ret != 0) {
1017                 DEBUG(10, ("ctdb_read_req failed: %s\n", strerror(ret)));
1018                 goto fail;
1019         }
1020
1021         if ((hdr == NULL) || (hdr->operation != CTDB_REPLY_CALL)) {
1022                 DEBUG(0, ("received invalid reply\n"));
1023                 ret = EIO;
1024                 goto fail;
1025         }
1026         reply = (struct ctdb_reply_call *)hdr;
1027
1028         if (reply->datalen == 0) {
1029                 /*
1030                  * Treat an empty record as non-existing
1031                  */
1032                 ret = ENOENT;
1033                 goto fail;
1034         }
1035
1036         parser(key, make_tdb_data(&reply->data[0], reply->datalen),
1037                private_data);
1038
1039         ret = 0;
1040  fail:
1041         TALLOC_FREE(hdr);
1042         return ret;
1043 }
1044
1045 /*
1046   Traverse a ctdb database. This uses a kind-of hackish way to open a second
1047   connection to ctdbd to avoid the hairy recursive and async problems with
1048   everything in-line.
1049 */
1050
1051 int ctdbd_traverse(struct ctdbd_connection *master, uint32_t db_id,
1052                         void (*fn)(TDB_DATA key, TDB_DATA data,
1053                                    void *private_data),
1054                         void *private_data)
1055 {
1056         struct ctdbd_connection *conn;
1057         int ret;
1058         TDB_DATA key, data;
1059         struct ctdb_traverse_start t;
1060         int cstatus;
1061
1062         become_root();
1063         ret = ctdbd_init_connection(NULL, master->sockname, master->timeout,
1064                                     &conn);
1065         unbecome_root();
1066         if (ret != 0) {
1067                 DEBUG(0, ("ctdbd_init_connection failed: %s\n",
1068                           strerror(ret)));
1069                 return ret;
1070         }
1071
1072         t.db_id = db_id;
1073         t.srvid = conn->rand_srvid;
1074         t.reqid = ctdbd_next_reqid(conn);
1075
1076         data.dptr = (uint8_t *)&t;
1077         data.dsize = sizeof(t);
1078
1079         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
1080                             CTDB_CONTROL_TRAVERSE_START, conn->rand_srvid,
1081                             0, data, NULL, NULL, &cstatus);
1082
1083         if ((ret != 0) || (cstatus != 0)) {
1084                 DEBUG(0,("ctdbd_control failed: %s, %d\n", strerror(ret),
1085                          cstatus));
1086
1087                 if (ret == 0) {
1088                         /*
1089                          * We need a mapping here
1090                          */
1091                         ret = EIO;
1092                 }
1093                 TALLOC_FREE(conn);
1094                 return ret;
1095         }
1096
1097         while (True) {
1098                 struct ctdb_req_header *hdr = NULL;
1099                 struct ctdb_req_message *m;
1100                 struct ctdb_rec_data *d;
1101
1102                 ret = ctdb_read_packet(conn->fd, conn->timeout, conn, &hdr);
1103                 if (ret != 0) {
1104                         DEBUG(0, ("ctdb_read_packet failed: %s\n",
1105                                   strerror(ret)));
1106                         cluster_fatal("ctdbd died\n");
1107                 }
1108
1109                 if (hdr->operation != CTDB_REQ_MESSAGE) {
1110                         DEBUG(0, ("Got operation %u, expected a message\n",
1111                                   (unsigned)hdr->operation));
1112                         TALLOC_FREE(conn);
1113                         return EIO;
1114                 }
1115
1116                 m = (struct ctdb_req_message *)hdr;
1117                 d = (struct ctdb_rec_data *)&m->data[0];
1118                 if (m->datalen < sizeof(uint32_t) || m->datalen != d->length) {
1119                         DEBUG(0, ("Got invalid traverse data of length %d\n",
1120                                   (int)m->datalen));
1121                         TALLOC_FREE(conn);
1122                         return EIO;
1123                 }
1124
1125                 key.dsize = d->keylen;
1126                 key.dptr  = &d->data[0];
1127                 data.dsize = d->datalen;
1128                 data.dptr = &d->data[d->keylen];
1129
1130                 if (key.dsize == 0 && data.dsize == 0) {
1131                         /* end of traverse */
1132                         TALLOC_FREE(conn);
1133                         return 0;
1134                 }
1135
1136                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
1137                         DEBUG(0, ("Got invalid ltdb header length %d\n",
1138                                   (int)data.dsize));
1139                         TALLOC_FREE(conn);
1140                         return EIO;
1141                 }
1142                 data.dsize -= sizeof(struct ctdb_ltdb_header);
1143                 data.dptr += sizeof(struct ctdb_ltdb_header);
1144
1145                 if (fn != NULL) {
1146                         fn(key, data, private_data);
1147                 }
1148         }
1149         return 0;
1150 }
1151
1152 /*
1153    This is used to canonicalize a ctdb_sock_addr structure.
1154 */
1155 static void smbd_ctdb_canonicalize_ip(const struct sockaddr_storage *in,
1156                                       struct sockaddr_storage *out)
1157 {
1158         memcpy(out, in, sizeof (*out));
1159
1160 #ifdef HAVE_IPV6
1161         if (in->ss_family == AF_INET6) {
1162                 const char prefix[12] = { 0,0,0,0,0,0,0,0,0,0,0xff,0xff };
1163                 const struct sockaddr_in6 *in6 =
1164                         (const struct sockaddr_in6 *)in;
1165                 struct sockaddr_in *out4 = (struct sockaddr_in *)out;
1166                 if (memcmp(&in6->sin6_addr, prefix, 12) == 0) {
1167                         memset(out, 0, sizeof(*out));
1168 #ifdef HAVE_SOCK_SIN_LEN
1169                         out4->sin_len = sizeof(*out);
1170 #endif
1171                         out4->sin_family = AF_INET;
1172                         out4->sin_port   = in6->sin6_port;
1173                         memcpy(&out4->sin_addr, &in6->sin6_addr.s6_addr[12], 4);
1174                 }
1175         }
1176 #endif
1177 }
1178
1179 /*
1180  * Register us as a server for a particular tcp connection
1181  */
1182
1183 int ctdbd_register_ips(struct ctdbd_connection *conn,
1184                        const struct sockaddr_storage *_server,
1185                        const struct sockaddr_storage *_client,
1186                        int (*cb)(uint32_t src_vnn, uint32_t dst_vnn,
1187                                  uint64_t dst_srvid,
1188                                  const uint8_t *msg, size_t msglen,
1189                                  void *private_data),
1190                        void *private_data)
1191 {
1192         struct ctdb_control_tcp_addr p;
1193         TDB_DATA data = { .dptr = (uint8_t *)&p, .dsize = sizeof(p) };
1194         int ret;
1195         struct sockaddr_storage client;
1196         struct sockaddr_storage server;
1197
1198         /*
1199          * Only one connection so far
1200          */
1201
1202         smbd_ctdb_canonicalize_ip(_client, &client);
1203         smbd_ctdb_canonicalize_ip(_server, &server);
1204
1205         switch (client.ss_family) {
1206         case AF_INET:
1207                 memcpy(&p.dest.ip, &server, sizeof(p.dest.ip));
1208                 memcpy(&p.src.ip, &client, sizeof(p.src.ip));
1209                 break;
1210         case AF_INET6:
1211                 memcpy(&p.dest.ip6, &server, sizeof(p.dest.ip6));
1212                 memcpy(&p.src.ip6, &client, sizeof(p.src.ip6));
1213                 break;
1214         default:
1215                 return EIO;
1216         }
1217
1218         /*
1219          * We want to be told about IP releases
1220          */
1221
1222         ret = register_with_ctdbd(conn, CTDB_SRVID_RELEASE_IP,
1223                                   cb, private_data);
1224         if (ret != 0) {
1225                 return ret;
1226         }
1227
1228         /*
1229          * inform ctdb of our tcp connection, so if IP takeover happens ctdb
1230          * can send an extra ack to trigger a reset for our client, so it
1231          * immediately reconnects
1232          */
1233         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
1234                             CTDB_CONTROL_TCP_CLIENT, 0,
1235                             CTDB_CTRL_FLAG_NOREPLY, data, NULL, NULL,
1236                             NULL);
1237         if (ret != 0) {
1238                 return ret;
1239         }
1240         return 0;
1241 }
1242
1243 /*
1244   call a control on the local node
1245  */
1246 NTSTATUS ctdbd_control_local(struct ctdbd_connection *conn, uint32_t opcode,
1247                              uint64_t srvid, uint32_t flags, TDB_DATA data,
1248                              TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
1249                              int *cstatus)
1250 {
1251         int ret;
1252
1253         ret = ctdbd_control(conn, CTDB_CURRENT_NODE, opcode, srvid, flags, data,
1254                             mem_ctx, outdata, cstatus);
1255         if (ret != 0) {
1256                 return map_nt_error_from_unix(ret);
1257         }
1258         return NT_STATUS_OK;
1259 }
1260
1261 NTSTATUS ctdb_watch_us(struct ctdbd_connection *conn)
1262 {
1263         struct ctdb_client_notify_register reg_data;
1264         size_t struct_len;
1265         NTSTATUS status;
1266         int cstatus;
1267
1268         reg_data.srvid = CTDB_SRVID_SAMBA_NOTIFY;
1269         reg_data.len = 1;
1270         reg_data.notify_data[0] = 0;
1271
1272         struct_len = offsetof(struct ctdb_client_notify_register,
1273                               notify_data) + reg_data.len;
1274
1275         status = ctdbd_control_local(
1276                 conn, CTDB_CONTROL_REGISTER_NOTIFY, conn->rand_srvid, 0,
1277                 make_tdb_data((uint8_t *)&reg_data, struct_len),
1278                 NULL, NULL, &cstatus);
1279         if (!NT_STATUS_IS_OK(status)) {
1280                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1281                           nt_errstr(status)));
1282         }
1283         return status;
1284 }
1285
1286 NTSTATUS ctdb_unwatch(struct ctdbd_connection *conn)
1287 {
1288         struct ctdb_client_notify_deregister dereg_data;
1289         NTSTATUS status;
1290         int cstatus;
1291
1292         dereg_data.srvid = CTDB_SRVID_SAMBA_NOTIFY;
1293
1294         status = ctdbd_control_local(
1295                 conn, CTDB_CONTROL_DEREGISTER_NOTIFY, conn->rand_srvid, 0,
1296                 make_tdb_data((uint8_t *)&dereg_data, sizeof(dereg_data)),
1297                 NULL, NULL, &cstatus);
1298         if (!NT_STATUS_IS_OK(status)) {
1299                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1300                           nt_errstr(status)));
1301         }
1302         return status;
1303 }
1304
1305 NTSTATUS ctdbd_probe(const char *sockname, int timeout)
1306 {
1307         /*
1308          * Do a very early check if ctdbd is around to avoid an abort and core
1309          * later
1310          */
1311         struct ctdbd_connection *conn = NULL;
1312         int ret;
1313
1314         ret = ctdbd_messaging_connection(talloc_tos(), sockname, timeout,
1315                                          &conn);
1316
1317         /*
1318          * We only care if we can connect.
1319          */
1320         TALLOC_FREE(conn);
1321
1322         return map_nt_error_from_unix(ret);
1323 }