build: Remove checks for ctdb features
[jlayton/samba.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
27 #include "messages.h"
28
29 /*
30  * It is not possible to include ctdb.h and tdb_compat.h (included via
31  * some other include above) without warnings. This fixes those
32  * warnings.
33  */
34
35 #ifdef typesafe_cb
36 #undef typesafe_cb
37 #endif
38
39 #ifdef typesafe_cb_preargs
40 #undef typesafe_cb_preargs
41 #endif
42
43 #ifdef typesafe_cb_postargs
44 #undef typesafe_cb_postargs
45 #endif
46
47 /* paths to these include files come from --with-ctdb= in configure */
48
49 #include "ctdb.h"
50 #include "ctdb_private.h"
51
52 struct ctdbd_connection {
53         struct messaging_context *msg_ctx;
54         uint32_t reqid;
55         uint32_t our_vnn;
56         uint64_t rand_srvid;
57         int fd;
58         struct tevent_fd *fde;
59
60         bool (*release_ip_handler)(const char *ip_addr, void *private_data);
61         void *release_ip_priv;
62 };
63
64 static uint32_t ctdbd_next_reqid(struct ctdbd_connection *conn)
65 {
66         conn->reqid += 1;
67         if (conn->reqid == 0) {
68                 conn->reqid += 1;
69         }
70         return conn->reqid;
71 }
72
73 static NTSTATUS ctdbd_control(struct ctdbd_connection *conn,
74                               uint32_t vnn, uint32_t opcode,
75                               uint64_t srvid, uint32_t flags, TDB_DATA data,
76                               TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
77                               int *cstatus);
78
79 /*
80  * exit on fatal communications errors with the ctdbd daemon
81  */
82 static void cluster_fatal(const char *why)
83 {
84         DEBUG(0,("cluster fatal event: %s - exiting immediately\n", why));
85         /* we don't use smb_panic() as we don't want to delay to write
86            a core file. We need to release this process id immediately
87            so that someone else can take over without getting sharing
88            violations */
89         _exit(1);
90 }
91
92 /*
93  *
94  */
95 static void ctdb_packet_dump(struct ctdb_req_header *hdr)
96 {
97         if (DEBUGLEVEL < 11) {
98                 return;
99         }
100         DEBUGADD(11, ("len=%d, magic=%x, vers=%d, gen=%d, op=%d, reqid=%d\n",
101                       (int)hdr->length, (int)hdr->ctdb_magic,
102                       (int)hdr->ctdb_version, (int)hdr->generation,
103                       (int)hdr->operation, (int)hdr->reqid));
104 }
105
106 /*
107  * Register a srvid with ctdbd
108  */
109 NTSTATUS register_with_ctdbd(struct ctdbd_connection *conn, uint64_t srvid)
110 {
111
112         int cstatus;
113         return ctdbd_control(conn, CTDB_CURRENT_NODE,
114                              CTDB_CONTROL_REGISTER_SRVID, srvid, 0,
115                              tdb_null, NULL, NULL, &cstatus);
116 }
117
118 /*
119  * get our vnn from the cluster
120  */
121 static NTSTATUS get_cluster_vnn(struct ctdbd_connection *conn, uint32_t *vnn)
122 {
123         int32_t cstatus=-1;
124         NTSTATUS status;
125         status = ctdbd_control(conn,
126                                CTDB_CURRENT_NODE, CTDB_CONTROL_GET_PNN, 0, 0,
127                                tdb_null, NULL, NULL, &cstatus);
128         if (!NT_STATUS_IS_OK(status)) {
129                 DEBUG(1, ("ctdbd_control failed: %s\n", nt_errstr(status)));
130                 return status;
131         }
132         *vnn = (uint32_t)cstatus;
133         return status;
134 }
135
136 /*
137  * Are we active (i.e. not banned or stopped?)
138  */
139 static bool ctdbd_working(struct ctdbd_connection *conn, uint32_t vnn)
140 {
141         int32_t cstatus=-1;
142         NTSTATUS status;
143         TDB_DATA outdata;
144         struct ctdb_node_map *m;
145         uint32_t failure_flags;
146         bool ret = false;
147         int i;
148
149         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
150                                CTDB_CONTROL_GET_NODEMAP, 0, 0,
151                                tdb_null, talloc_tos(), &outdata, &cstatus);
152         if (!NT_STATUS_IS_OK(status)) {
153                 DEBUG(1, ("ctdbd_control failed: %s\n", nt_errstr(status)));
154                 return false;
155         }
156         if ((cstatus != 0) || (outdata.dptr == NULL)) {
157                 DEBUG(2, ("Received invalid ctdb data\n"));
158                 return false;
159         }
160
161         m = (struct ctdb_node_map *)outdata.dptr;
162
163         for (i=0; i<m->num; i++) {
164                 if (vnn == m->nodes[i].pnn) {
165                         break;
166                 }
167         }
168
169         if (i == m->num) {
170                 DEBUG(2, ("Did not find ourselves (node %d) in nodemap\n",
171                           (int)vnn));
172                 goto fail;
173         }
174
175         failure_flags = NODE_FLAGS_BANNED | NODE_FLAGS_DISCONNECTED
176                 | NODE_FLAGS_PERMANENTLY_DISABLED | NODE_FLAGS_STOPPED;
177
178         if ((m->nodes[i].flags & failure_flags) != 0) {
179                 DEBUG(2, ("Node has status %x, not active\n",
180                           (int)m->nodes[i].flags));
181                 goto fail;
182         }
183
184         ret = true;
185 fail:
186         TALLOC_FREE(outdata.dptr);
187         return ret;
188 }
189
190 uint32_t ctdbd_vnn(const struct ctdbd_connection *conn)
191 {
192         return conn->our_vnn;
193 }
194
195 const char *lp_ctdbd_socket(void)
196 {
197         const char *ret;
198
199         ret = lp__ctdbd_socket();
200         if (ret != NULL && strlen(ret) > 0) {
201                 return ret;
202         }
203
204         return CTDB_PATH;
205 }
206
207 /*
208  * Get us a ctdb connection
209  */
210
211 static int ctdbd_connect(int *pfd)
212 {
213         const char *sockname = lp_ctdbd_socket();
214         struct sockaddr_un addr = { 0, };
215         int fd;
216         socklen_t salen;
217         size_t namelen;
218
219         fd = socket(AF_UNIX, SOCK_STREAM, 0);
220         if (fd == -1) {
221                 int err = errno;
222                 DEBUG(3, ("Could not create socket: %s\n", strerror(err)));
223                 return err;
224         }
225
226         addr.sun_family = AF_UNIX;
227
228         namelen = strlcpy(addr.sun_path, sockname, sizeof(addr.sun_path));
229         if (namelen >= sizeof(addr.sun_path)) {
230                 DEBUG(3, ("%s: Socket name too long: %s\n", __func__,
231                           sockname));
232                 close(fd);
233                 return ENAMETOOLONG;
234         }
235
236         salen = sizeof(struct sockaddr_un);
237
238         if (connect(fd, (struct sockaddr *)(void *)&addr, salen) == -1) {
239                 int err = errno;
240                 DEBUG(1, ("connect(%s) failed: %s\n", sockname,
241                           strerror(err)));
242                 close(fd);
243                 return err;
244         }
245
246         *pfd = fd;
247         return 0;
248 }
249
250 /*
251  * State necessary to defer an incoming message while we are waiting for a
252  * ctdb reply.
253  */
254
255 struct deferred_msg_state {
256         struct messaging_context *msg_ctx;
257         struct messaging_rec *rec;
258 };
259
260 /*
261  * Timed event handler for the deferred message
262  */
263
264 static void deferred_message_dispatch(struct tevent_context *event_ctx,
265                                       struct tevent_timer *te,
266                                       struct timeval now,
267                                       void *private_data)
268 {
269         struct deferred_msg_state *state = talloc_get_type_abort(
270                 private_data, struct deferred_msg_state);
271
272         messaging_dispatch_rec(state->msg_ctx, state->rec);
273         TALLOC_FREE(state);
274         TALLOC_FREE(te);
275 }
276
277 /*
278  * Fetch a messaging_rec from an incoming ctdb style message
279  */
280
281 static struct messaging_rec *ctdb_pull_messaging_rec(TALLOC_CTX *mem_ctx,
282                                                      size_t overall_length,
283                                                      struct ctdb_req_message *msg)
284 {
285         struct messaging_rec *result;
286         DATA_BLOB blob;
287         enum ndr_err_code ndr_err;
288
289         if ((overall_length < offsetof(struct ctdb_req_message, data))
290             || (overall_length
291                 < offsetof(struct ctdb_req_message, data) + msg->datalen)) {
292
293                 cluster_fatal("got invalid msg length");
294         }
295
296         if (!(result = talloc(mem_ctx, struct messaging_rec))) {
297                 DEBUG(0, ("talloc failed\n"));
298                 return NULL;
299         }
300
301         blob = data_blob_const(msg->data, msg->datalen);
302
303         ndr_err = ndr_pull_struct_blob(
304                 &blob, result, result,
305                 (ndr_pull_flags_fn_t)ndr_pull_messaging_rec);
306
307         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
308                 DEBUG(0, ("ndr_pull_struct_blob failed: %s\n",
309                           ndr_errstr(ndr_err)));
310                 TALLOC_FREE(result);
311                 return NULL;
312         }
313
314         if (DEBUGLEVEL >= 11) {
315                 DEBUG(11, ("ctdb_pull_messaging_rec:\n"));
316                 NDR_PRINT_DEBUG(messaging_rec, result);
317         }
318
319         return result;
320 }
321
322 static NTSTATUS ctdb_read_packet(int fd, TALLOC_CTX *mem_ctx,
323                                  struct ctdb_req_header **result)
324 {
325         int timeout = lp_ctdb_timeout();
326         struct ctdb_req_header *req;
327         int ret, revents;
328         uint32_t msglen;
329         NTSTATUS status;
330
331         if (timeout == 0) {
332                 timeout = -1;
333         }
334
335         if (timeout != -1) {
336                 ret = poll_one_fd(fd, POLLIN, timeout, &revents);
337                 if (ret == -1) {
338                         return map_nt_error_from_unix(errno);
339                 }
340                 if (ret == 0) {
341                         return NT_STATUS_IO_TIMEOUT;
342                 }
343                 if (ret != 1) {
344                         return NT_STATUS_UNEXPECTED_IO_ERROR;
345                 }
346         }
347
348         status = read_data(fd, (char *)&msglen, sizeof(msglen));
349         if (!NT_STATUS_IS_OK(status)) {
350                 return status;
351         }
352
353         if (msglen < sizeof(struct ctdb_req_header)) {
354                 return NT_STATUS_UNEXPECTED_IO_ERROR;
355         }
356
357         req = talloc_size(mem_ctx, msglen);
358         if (req == NULL) {
359                 return NT_STATUS_NO_MEMORY;
360         }
361         talloc_set_name_const(req, "struct ctdb_req_header");
362
363         req->length = msglen;
364
365         status = read_data(fd, ((char *)req) + sizeof(msglen),
366                            msglen - sizeof(msglen));
367         if (!NT_STATUS_IS_OK(status)) {
368                 return status;
369         }
370
371         *result = req;
372         return NT_STATUS_OK;
373 }
374
375 /*
376  * Read a full ctdbd request. If we have a messaging context, defer incoming
377  * messages that might come in between.
378  */
379
380 static NTSTATUS ctdb_read_req(struct ctdbd_connection *conn, uint32_t reqid,
381                               TALLOC_CTX *mem_ctx,
382                               struct ctdb_req_header **result)
383 {
384         struct ctdb_req_header *hdr;
385         NTSTATUS status;
386
387  next_pkt:
388
389         status = ctdb_read_packet(conn->fd, mem_ctx, &hdr);
390         if (!NT_STATUS_IS_OK(status)) {
391                 DEBUG(0, ("ctdb_read_packet failed: %s\n", nt_errstr(status)));
392                 cluster_fatal("ctdbd died\n");
393         }
394
395         DEBUG(11, ("Received ctdb packet\n"));
396         ctdb_packet_dump(hdr);
397
398         if (hdr->operation == CTDB_REQ_MESSAGE) {
399                 struct tevent_timer *evt;
400                 struct deferred_msg_state *msg_state;
401                 struct ctdb_req_message *msg = (struct ctdb_req_message *)hdr;
402
403                 if (conn->msg_ctx == NULL) {
404                         DEBUG(1, ("Got a message without having a msg ctx, "
405                                   "dropping msg %llu\n",
406                                   (long long unsigned)msg->srvid));
407                         goto next_pkt;
408                 }
409
410                 if ((conn->release_ip_handler != NULL)
411                     && (msg->srvid == CTDB_SRVID_RELEASE_IP)) {
412                         bool ret;
413
414                         /* must be dispatched immediately */
415                         DEBUG(10, ("received CTDB_SRVID_RELEASE_IP\n"));
416                         ret = conn->release_ip_handler((const char *)msg->data,
417                                                        conn->release_ip_priv);
418                         TALLOC_FREE(hdr);
419
420                         if (ret) {
421                                 /*
422                                  * We need to release the ip,
423                                  * so return an error to the upper layers.
424                                  *
425                                  * We make sure we don't trigger this again.
426                                  */
427                                 conn->release_ip_handler = NULL;
428                                 conn->release_ip_priv = NULL;
429                                 return NT_STATUS_ADDRESS_CLOSED;
430                         }
431                         goto next_pkt;
432                 }
433
434                 if ((msg->srvid == CTDB_SRVID_RECONFIGURE)
435                     || (msg->srvid == CTDB_SRVID_SAMBA_NOTIFY)) {
436
437                         DEBUG(1, ("ctdb_read_req: Got %s message\n",
438                                   (msg->srvid == CTDB_SRVID_RECONFIGURE)
439                                   ? "cluster reconfigure" : "SAMBA_NOTIFY"));
440
441                         messaging_send(conn->msg_ctx,
442                                        messaging_server_id(conn->msg_ctx),
443                                        MSG_SMB_BRL_VALIDATE, &data_blob_null);
444                         TALLOC_FREE(hdr);
445                         goto next_pkt;
446                 }
447
448                 msg_state = talloc(NULL, struct deferred_msg_state);
449                 if (msg_state == NULL) {
450                         DEBUG(0, ("talloc failed\n"));
451                         TALLOC_FREE(hdr);
452                         goto next_pkt;
453                 }
454
455                 if (!(msg_state->rec = ctdb_pull_messaging_rec(
456                               msg_state, msg->hdr.length, msg))) {
457                         DEBUG(0, ("ctdbd_pull_messaging_rec failed\n"));
458                         TALLOC_FREE(msg_state);
459                         TALLOC_FREE(hdr);
460                         goto next_pkt;
461                 }
462
463                 TALLOC_FREE(hdr);
464
465                 msg_state->msg_ctx = conn->msg_ctx;
466
467                 /*
468                  * We're waiting for a call reply, but an async message has
469                  * crossed. Defer dispatching to the toplevel event loop.
470                  */
471                 evt = tevent_add_timer(messaging_tevent_context(conn->msg_ctx),
472                                       messaging_tevent_context(conn->msg_ctx),
473                                       timeval_zero(),
474                                       deferred_message_dispatch,
475                                       msg_state);
476                 if (evt == NULL) {
477                         DEBUG(0, ("event_add_timed failed\n"));
478                         TALLOC_FREE(msg_state);
479                         TALLOC_FREE(hdr);
480                         goto next_pkt;
481                 }
482
483                 goto next_pkt;
484         }
485
486         if ((reqid != 0) && (hdr->reqid != reqid)) {
487                 /* we got the wrong reply */
488                 DEBUG(0,("Discarding mismatched ctdb reqid %u should have "
489                          "been %u\n", hdr->reqid, reqid));
490                 TALLOC_FREE(hdr);
491                 goto next_pkt;
492         }
493
494         *result = talloc_move(mem_ctx, &hdr);
495
496         return NT_STATUS_OK;
497 }
498
499 static int ctdbd_connection_destructor(struct ctdbd_connection *c)
500 {
501         close(c->fd);
502         return 0;
503 }
504 /*
505  * Get us a ctdbd connection
506  */
507
508 static NTSTATUS ctdbd_init_connection(TALLOC_CTX *mem_ctx,
509                                       struct ctdbd_connection **pconn)
510 {
511         struct ctdbd_connection *conn;
512         int ret;
513         NTSTATUS status;
514
515         if (!(conn = talloc_zero(mem_ctx, struct ctdbd_connection))) {
516                 DEBUG(0, ("talloc failed\n"));
517                 return NT_STATUS_NO_MEMORY;
518         }
519
520         ret = ctdbd_connect(&conn->fd);
521         if (ret != 0) {
522                 status = map_nt_error_from_unix(errno);
523                 DEBUG(10, ("ctdbd_connect failed: %s\n", strerror(errno)));
524                 goto fail;
525         }
526         talloc_set_destructor(conn, ctdbd_connection_destructor);
527
528         status = get_cluster_vnn(conn, &conn->our_vnn);
529
530         if (!NT_STATUS_IS_OK(status)) {
531                 DEBUG(10, ("get_cluster_vnn failed: %s\n", nt_errstr(status)));
532                 goto fail;
533         }
534
535         if (!ctdbd_working(conn, conn->our_vnn)) {
536                 DEBUG(2, ("Node is not working, can not connect\n"));
537                 status = NT_STATUS_INTERNAL_DB_ERROR;
538                 goto fail;
539         }
540
541         generate_random_buffer((unsigned char *)&conn->rand_srvid,
542                                sizeof(conn->rand_srvid));
543
544         status = register_with_ctdbd(conn, conn->rand_srvid);
545
546         if (!NT_STATUS_IS_OK(status)) {
547                 DEBUG(5, ("Could not register random srvid: %s\n",
548                           nt_errstr(status)));
549                 goto fail;
550         }
551
552         *pconn = conn;
553         return NT_STATUS_OK;
554
555  fail:
556         TALLOC_FREE(conn);
557         return status;
558 }
559
560 /*
561  * Get us a ctdbd connection and register us as a process
562  */
563
564 NTSTATUS ctdbd_messaging_connection(TALLOC_CTX *mem_ctx,
565                                     struct ctdbd_connection **pconn)
566 {
567         struct ctdbd_connection *conn;
568         NTSTATUS status;
569
570         status = ctdbd_init_connection(mem_ctx, &conn);
571
572         if (!NT_STATUS_IS_OK(status)) {
573                 return status;
574         }
575
576         status = register_with_ctdbd(conn, (uint64_t)getpid());
577         if (!NT_STATUS_IS_OK(status)) {
578                 goto fail;
579         }
580
581         status = register_with_ctdbd(conn, MSG_SRVID_SAMBA);
582         if (!NT_STATUS_IS_OK(status)) {
583                 goto fail;
584         }
585
586         status = register_with_ctdbd(conn, CTDB_SRVID_SAMBA_NOTIFY);
587         if (!NT_STATUS_IS_OK(status)) {
588                 goto fail;
589         }
590
591         *pconn = conn;
592         return NT_STATUS_OK;
593
594  fail:
595         TALLOC_FREE(conn);
596         return status;
597 }
598
599 struct messaging_context *ctdb_conn_msg_ctx(struct ctdbd_connection *conn)
600 {
601         return conn->msg_ctx;
602 }
603
604 int ctdbd_conn_get_fd(struct ctdbd_connection *conn)
605 {
606         return conn->fd;
607 }
608
609 /*
610  * Packet handler to receive and handle a ctdb message
611  */
612 static NTSTATUS ctdb_handle_message(struct messaging_context *msg_ctx,
613                                     struct ctdbd_connection *conn,
614                                     struct ctdb_req_header *hdr)
615 {
616         struct ctdb_req_message *msg;
617         struct messaging_rec *msg_rec;
618
619         if (hdr->operation != CTDB_REQ_MESSAGE) {
620                 DEBUG(0, ("Received async msg of type %u, discarding\n",
621                           hdr->operation));
622                 return NT_STATUS_INVALID_PARAMETER;
623         }
624
625         msg = (struct ctdb_req_message *)hdr;
626
627         if ((conn->release_ip_handler != NULL)
628             && (msg->srvid == CTDB_SRVID_RELEASE_IP)) {
629                 bool ret;
630
631                 /* must be dispatched immediately */
632                 DEBUG(10, ("received CTDB_SRVID_RELEASE_IP\n"));
633                 ret = conn->release_ip_handler((const char *)msg->data,
634                                                conn->release_ip_priv);
635                 if (ret) {
636                         /*
637                          * We need to release the ip.
638                          *
639                          * We make sure we don't trigger this again.
640                          */
641                         conn->release_ip_handler = NULL;
642                         conn->release_ip_priv = NULL;
643                 }
644                 return NT_STATUS_OK;
645         }
646
647         SMB_ASSERT(conn->msg_ctx != NULL);
648
649         if ((msg->srvid == CTDB_SRVID_RECONFIGURE)
650             || (msg->srvid == CTDB_SRVID_SAMBA_NOTIFY)){
651                 DEBUG(0,("Got cluster reconfigure message\n"));
652                 /*
653                  * when the cluster is reconfigured or someone of the
654                  * family has passed away (SAMBA_NOTIFY), we need to
655                  * clean the brl database
656                  */
657                 messaging_send(conn->msg_ctx,
658                                messaging_server_id(conn->msg_ctx),
659                                MSG_SMB_BRL_VALIDATE, &data_blob_null);
660
661                 return NT_STATUS_OK;
662         }
663
664         /* only messages to our pid or the broadcast are valid here */
665         if (msg->srvid != getpid() && msg->srvid != MSG_SRVID_SAMBA) {
666                 DEBUG(0,("Got unexpected message with srvid=%llu\n", 
667                          (unsigned long long)msg->srvid));
668                 return NT_STATUS_OK;
669         }
670
671         msg_rec = ctdb_pull_messaging_rec(talloc_tos(), msg->hdr.length, msg);
672         if (msg_rec == NULL) {
673                 DEBUG(10, ("ctdb_pull_messaging_rec failed\n"));
674                 return NT_STATUS_NO_MEMORY;
675         }
676         messaging_dispatch_rec(conn->msg_ctx, msg_rec);
677         return NT_STATUS_OK;
678 }
679
680 /*
681  * The ctdbd socket is readable asynchronuously
682  */
683
684 static void ctdbd_socket_handler(struct tevent_context *event_ctx,
685                                  struct tevent_fd *event,
686                                  uint16 flags,
687                                  void *private_data)
688 {
689         struct ctdbd_connection *conn = talloc_get_type_abort(
690                 private_data, struct ctdbd_connection);
691         struct ctdb_req_header *hdr;
692         NTSTATUS status;
693
694         status = ctdb_read_packet(conn->fd, talloc_tos(), &hdr);
695         if (!NT_STATUS_IS_OK(status)) {
696                 DEBUG(0, ("ctdb_read_packet failed: %s\n", nt_errstr(status)));
697                 cluster_fatal("ctdbd died\n");
698         }
699
700         status = ctdb_handle_message(conn->msg_ctx, conn, hdr);
701         if (!NT_STATUS_IS_OK(status)) {
702                 DEBUG(10, ("could not handle incoming message: %s\n",
703                            nt_errstr(status)));
704         }
705 }
706
707 /*
708  * Prepare a ctdbd connection to receive messages
709  */
710
711 NTSTATUS ctdbd_register_msg_ctx(struct ctdbd_connection *conn,
712                                 struct messaging_context *msg_ctx)
713 {
714         SMB_ASSERT(conn->msg_ctx == NULL);
715         SMB_ASSERT(conn->fde == NULL);
716
717         if (!(conn->fde = tevent_add_fd(messaging_tevent_context(msg_ctx),
718                                        conn,
719                                        conn->fd,
720                                        TEVENT_FD_READ,
721                                        ctdbd_socket_handler,
722                                        conn))) {
723                 DEBUG(0, ("event_add_fd failed\n"));
724                 return NT_STATUS_NO_MEMORY;
725         }
726
727         conn->msg_ctx = msg_ctx;
728
729         return NT_STATUS_OK;
730 }
731
732 /*
733  * Send a messaging message across a ctdbd
734  */
735
736 NTSTATUS ctdbd_messaging_send(struct ctdbd_connection *conn,
737                               uint32_t dst_vnn, uint64_t dst_srvid,
738                               struct messaging_rec *msg)
739 {
740         DATA_BLOB blob;
741         NTSTATUS status;
742         enum ndr_err_code ndr_err;
743
744         ndr_err = ndr_push_struct_blob(
745                 &blob, talloc_tos(), msg,
746                 (ndr_push_flags_fn_t)ndr_push_messaging_rec);
747
748         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
749                 DEBUG(0, ("ndr_push_struct_blob failed: %s\n",
750                           ndr_errstr(ndr_err)));
751                 return ndr_map_error2ntstatus(ndr_err);
752         }
753
754         status = ctdbd_messaging_send_blob(conn, dst_vnn, dst_srvid,
755                                            blob.data, blob.length);
756         TALLOC_FREE(blob.data);
757         return status;
758 }
759
760 NTSTATUS ctdbd_messaging_send_blob(struct ctdbd_connection *conn,
761                                    uint32_t dst_vnn, uint64_t dst_srvid,
762                                    const uint8_t *buf, size_t buflen)
763 {
764         struct ctdb_req_message r;
765         struct iovec iov[2];
766         ssize_t nwritten;
767
768         r.hdr.length = offsetof(struct ctdb_req_message, data) + buflen;
769         r.hdr.ctdb_magic = CTDB_MAGIC;
770         r.hdr.ctdb_version = CTDB_VERSION;
771         r.hdr.generation = 1;
772         r.hdr.operation  = CTDB_REQ_MESSAGE;
773         r.hdr.destnode   = dst_vnn;
774         r.hdr.srcnode    = conn->our_vnn;
775         r.hdr.reqid      = 0;
776         r.srvid          = dst_srvid;
777         r.datalen        = buflen;
778
779         DEBUG(10, ("ctdbd_messaging_send: Sending ctdb packet\n"));
780         ctdb_packet_dump(&r.hdr);
781
782         iov[0].iov_base = &r;
783         iov[0].iov_len = offsetof(struct ctdb_req_message, data);
784         iov[1].iov_base = discard_const_p(uint8_t, buf);
785         iov[1].iov_len = buflen;
786
787         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
788         if (nwritten == -1) {
789                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
790                 cluster_fatal("cluster dispatch daemon msg write error\n");
791         }
792
793         return NT_STATUS_OK;
794 }
795
796 /*
797  * send/recv a generic ctdb control message
798  */
799 static NTSTATUS ctdbd_control(struct ctdbd_connection *conn,
800                               uint32_t vnn, uint32_t opcode,
801                               uint64_t srvid, uint32_t flags,
802                               TDB_DATA data,
803                               TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
804                               int *cstatus)
805 {
806         struct ctdb_req_control req;
807         struct ctdb_req_header *hdr;
808         struct ctdb_reply_control *reply = NULL;
809         struct ctdbd_connection *new_conn = NULL;
810         struct iovec iov[2];
811         ssize_t nwritten;
812         NTSTATUS status;
813
814         if (conn == NULL) {
815                 status = ctdbd_init_connection(NULL, &new_conn);
816
817                 if (!NT_STATUS_IS_OK(status)) {
818                         DEBUG(10, ("Could not init temp connection: %s\n",
819                                    nt_errstr(status)));
820                         goto fail;
821                 }
822
823                 conn = new_conn;
824         }
825
826         ZERO_STRUCT(req);
827         req.hdr.length = offsetof(struct ctdb_req_control, data) + data.dsize;
828         req.hdr.ctdb_magic   = CTDB_MAGIC;
829         req.hdr.ctdb_version = CTDB_VERSION;
830         req.hdr.operation    = CTDB_REQ_CONTROL;
831         req.hdr.reqid        = ctdbd_next_reqid(conn);
832         req.hdr.destnode     = vnn;
833         req.opcode           = opcode;
834         req.srvid            = srvid;
835         req.datalen          = data.dsize;
836         req.flags            = flags;
837
838         DEBUG(10, ("ctdbd_control: Sending ctdb packet\n"));
839         ctdb_packet_dump(&req.hdr);
840
841         iov[0].iov_base = &req;
842         iov[0].iov_len = offsetof(struct ctdb_req_control, data);
843         iov[1].iov_base = data.dptr;
844         iov[1].iov_len = data.dsize;
845
846         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
847         if (nwritten == -1) {
848                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
849                 cluster_fatal("cluster dispatch daemon msg write error\n");
850         }
851
852         if (flags & CTDB_CTRL_FLAG_NOREPLY) {
853                 TALLOC_FREE(new_conn);
854                 if (cstatus) {
855                         *cstatus = 0;
856                 }
857                 return NT_STATUS_OK;
858         }
859
860         status = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
861
862         if (!NT_STATUS_IS_OK(status)) {
863                 DEBUG(10, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
864                 goto fail;
865         }
866
867         if (hdr->operation != CTDB_REPLY_CONTROL) {
868                 DEBUG(0, ("received invalid reply\n"));
869                 goto fail;
870         }
871         reply = (struct ctdb_reply_control *)hdr;
872
873         if (outdata) {
874                 if (!(outdata->dptr = (uint8 *)talloc_memdup(
875                               mem_ctx, reply->data, reply->datalen))) {
876                         TALLOC_FREE(reply);
877                         return NT_STATUS_NO_MEMORY;
878                 }
879                 outdata->dsize = reply->datalen;
880         }
881         if (cstatus) {
882                 (*cstatus) = reply->status;
883         }
884
885         status = NT_STATUS_OK;
886
887  fail:
888         TALLOC_FREE(new_conn);
889         TALLOC_FREE(reply);
890         return status;
891 }
892
893 /*
894  * see if a remote process exists
895  */
896 bool ctdbd_process_exists(struct ctdbd_connection *conn, uint32_t vnn, pid_t pid)
897 {
898         struct server_id id;
899         bool result;
900
901         id.pid = pid;
902         id.vnn = vnn;
903
904         if (!ctdb_processes_exist(conn, &id, 1, &result)) {
905                 DEBUG(10, ("ctdb_processes_exist failed\n"));
906                 return false;
907         }
908         return result;
909 }
910
911 bool ctdb_processes_exist(struct ctdbd_connection *conn,
912                           const struct server_id *pids, int num_pids,
913                           bool *results)
914 {
915         TALLOC_CTX *frame = talloc_stackframe();
916         int i, num_received;
917         NTSTATUS status;
918         uint32_t *reqids;
919         bool result = false;
920
921         reqids = talloc_array(talloc_tos(), uint32_t, num_pids);
922         if (reqids == NULL) {
923                 goto fail;
924         }
925
926         for (i=0; i<num_pids; i++) {
927                 struct ctdb_req_control req;
928                 pid_t pid;
929                 struct iovec iov[2];
930                 ssize_t nwritten;
931
932                 results[i] = false;
933                 reqids[i] = ctdbd_next_reqid(conn);
934
935                 ZERO_STRUCT(req);
936
937                 /*
938                  * pids[i].pid is uint64_t, scale down to pid_t which
939                  * is the wire protocol towards ctdb.
940                  */
941                 pid = pids[i].pid;
942
943                 DEBUG(10, ("Requesting PID %d/%d, reqid=%d\n",
944                            (int)pids[i].vnn, (int)pid,
945                            (int)reqids[i]));
946
947                 req.hdr.length = offsetof(struct ctdb_req_control, data);
948                 req.hdr.length += sizeof(pid);
949                 req.hdr.ctdb_magic   = CTDB_MAGIC;
950                 req.hdr.ctdb_version = CTDB_VERSION;
951                 req.hdr.operation    = CTDB_REQ_CONTROL;
952                 req.hdr.reqid        = reqids[i];
953                 req.hdr.destnode     = pids[i].vnn;
954                 req.opcode           = CTDB_CONTROL_PROCESS_EXISTS;
955                 req.srvid            = 0;
956                 req.datalen          = sizeof(pid);
957                 req.flags            = 0;
958
959                 DEBUG(10, ("ctdbd_control: Sending ctdb packet\n"));
960                 ctdb_packet_dump(&req.hdr);
961
962                 iov[0].iov_base = &req;
963                 iov[0].iov_len = offsetof(struct ctdb_req_control, data);
964                 iov[1].iov_base = &pid;
965                 iov[1].iov_len = sizeof(pid);
966
967                 nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
968                 if (nwritten == -1) {
969                         status = map_nt_error_from_unix(errno);
970                         DEBUG(10, ("write_data_iov failed: %s\n",
971                                    strerror(errno)));
972                         goto fail;
973                 }
974         }
975
976         num_received = 0;
977
978         while (num_received < num_pids) {
979                 struct ctdb_req_header *hdr;
980                 struct ctdb_reply_control *reply;
981                 uint32_t reqid;
982
983                 status = ctdb_read_req(conn, 0, talloc_tos(), &hdr);
984                 if (!NT_STATUS_IS_OK(status)) {
985                         DEBUG(10, ("ctdb_read_req failed: %s\n",
986                                    nt_errstr(status)));
987                         goto fail;
988                 }
989
990                 if (hdr->operation != CTDB_REPLY_CONTROL) {
991                         DEBUG(10, ("Received invalid reply\n"));
992                         goto fail;
993                 }
994                 reply = (struct ctdb_reply_control *)hdr;
995
996                 reqid = reply->hdr.reqid;
997
998                 DEBUG(10, ("Received reqid %d\n", (int)reqid));
999
1000                 for (i=0; i<num_pids; i++) {
1001                         if (reqid == reqids[i]) {
1002                                 break;
1003                         }
1004                 }
1005                 if (i == num_pids) {
1006                         DEBUG(10, ("Received unknown record number %u\n",
1007                                    (unsigned)reqid));
1008                         goto fail;
1009                 }
1010                 results[i] = ((reply->status) == 0);
1011                 TALLOC_FREE(reply);
1012                 num_received += 1;
1013         }
1014
1015         result = true;
1016 fail:
1017         TALLOC_FREE(frame);
1018         return result;
1019 }
1020
1021 struct ctdb_vnn_list {
1022         uint32_t vnn;
1023         uint32_t reqid;
1024         unsigned num_srvids;
1025         unsigned num_filled;
1026         uint64_t *srvids;
1027         unsigned *pid_indexes;
1028 };
1029
1030 /*
1031  * Get a list of all vnns mentioned in a list of
1032  * server_ids. vnn_indexes tells where in the vnns array we have to
1033  * place the pids.
1034  */
1035 static bool ctdb_collect_vnns(TALLOC_CTX *mem_ctx,
1036                               const struct server_id *pids, unsigned num_pids,
1037                               struct ctdb_vnn_list **pvnns,
1038                               unsigned *pnum_vnns)
1039 {
1040         struct ctdb_vnn_list *vnns = NULL;
1041         unsigned *vnn_indexes = NULL;
1042         unsigned i, num_vnns = 0;
1043
1044         vnn_indexes = talloc_array(mem_ctx, unsigned, num_pids);
1045         if (vnn_indexes == NULL) {
1046                 DEBUG(1, ("talloc_array failed\n"));
1047                 goto fail;
1048         }
1049
1050         for (i=0; i<num_pids; i++) {
1051                 unsigned j;
1052                 uint32_t vnn = pids[i].vnn;
1053
1054                 for (j=0; j<num_vnns; j++) {
1055                         if (vnn == vnns[j].vnn) {
1056                                 break;
1057                         }
1058                 }
1059                 vnn_indexes[i] = j;
1060
1061                 if (j < num_vnns) {
1062                         /*
1063                          * Already in the array
1064                          */
1065                         vnns[j].num_srvids += 1;
1066                         continue;
1067                 }
1068                 vnns = talloc_realloc(mem_ctx, vnns, struct ctdb_vnn_list,
1069                                       num_vnns+1);
1070                 if (vnns == NULL) {
1071                         DEBUG(1, ("talloc_realloc failed\n"));
1072                         goto fail;
1073                 }
1074                 vnns[num_vnns].vnn = vnn;
1075                 vnns[num_vnns].num_srvids = 1;
1076                 vnns[num_vnns].num_filled = 0;
1077                 num_vnns += 1;
1078         }
1079         for (i=0; i<num_vnns; i++) {
1080                 struct ctdb_vnn_list *vnn = &vnns[i];
1081
1082                 vnn->srvids = talloc_array(vnns, uint64_t, vnn->num_srvids);
1083                 if (vnn->srvids == NULL) {
1084                         DEBUG(1, ("talloc_array failed\n"));
1085                         goto fail;
1086                 }
1087                 vnn->pid_indexes = talloc_array(vnns, unsigned,
1088                                                 vnn->num_srvids);
1089                 if (vnn->pid_indexes == NULL) {
1090                         DEBUG(1, ("talloc_array failed\n"));
1091                         goto fail;
1092                 }
1093         }
1094         for (i=0; i<num_pids; i++) {
1095                 struct ctdb_vnn_list *vnn = &vnns[vnn_indexes[i]];
1096                 vnn->srvids[vnn->num_filled] = pids[i].unique_id;
1097                 vnn->pid_indexes[vnn->num_filled] = i;
1098                 vnn->num_filled += 1;
1099         }
1100
1101         TALLOC_FREE(vnn_indexes);
1102         *pvnns = vnns;
1103         *pnum_vnns = num_vnns;
1104         return true;
1105 fail:
1106         TALLOC_FREE(vnns);
1107         TALLOC_FREE(vnn_indexes);
1108         return false;
1109 }
1110
1111 bool ctdb_serverids_exist_supported(struct ctdbd_connection *conn)
1112 {
1113         return true;
1114 }
1115
1116 bool ctdb_serverids_exist(struct ctdbd_connection *conn,
1117                           const struct server_id *pids, unsigned num_pids,
1118                           bool *results)
1119 {
1120         unsigned i, num_received;
1121         NTSTATUS status;
1122         struct ctdb_vnn_list *vnns = NULL;
1123         unsigned num_vnns;
1124
1125         if (!ctdb_collect_vnns(talloc_tos(), pids, num_pids,
1126                                &vnns, &num_vnns)) {
1127                 DEBUG(1, ("ctdb_collect_vnns failed\n"));
1128                 goto fail;
1129         }
1130
1131         for (i=0; i<num_vnns; i++) {
1132                 struct ctdb_vnn_list *vnn = &vnns[i];
1133                 struct ctdb_req_control req;
1134                 struct iovec iov[2];
1135                 ssize_t nwritten;
1136
1137                 vnn->reqid = ctdbd_next_reqid(conn);
1138
1139                 ZERO_STRUCT(req);
1140
1141                 DEBUG(10, ("Requesting VNN %d, reqid=%d, num_srvids=%u\n",
1142                            (int)vnn->vnn, (int)vnn->reqid, vnn->num_srvids));
1143
1144                 req.hdr.length = offsetof(struct ctdb_req_control, data);
1145                 req.hdr.ctdb_magic   = CTDB_MAGIC;
1146                 req.hdr.ctdb_version = CTDB_VERSION;
1147                 req.hdr.operation    = CTDB_REQ_CONTROL;
1148                 req.hdr.reqid        = vnn->reqid;
1149                 req.hdr.destnode     = vnn->vnn;
1150                 req.opcode           = CTDB_CONTROL_CHECK_SRVIDS;
1151                 req.srvid            = 0;
1152                 req.datalen          = sizeof(uint64_t) * vnn->num_srvids;
1153                 req.hdr.length      += req.datalen;
1154                 req.flags            = 0;
1155
1156                 DEBUG(10, ("ctdbd_control: Sending ctdb packet\n"));
1157                 ctdb_packet_dump(&req.hdr);
1158
1159                 iov[0].iov_base = &req;
1160                 iov[0].iov_len = offsetof(struct ctdb_req_control, data);
1161                 iov[1].iov_base = vnn->srvids;
1162                 iov[1].iov_len = req.datalen;
1163
1164                 nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
1165                 if (nwritten == -1) {
1166                         status = map_nt_error_from_unix(errno);
1167                         DEBUG(10, ("write_data_iov failed: %s\n",
1168                                    strerror(errno)));
1169                         goto fail;
1170                 }
1171         }
1172
1173         num_received = 0;
1174
1175         while (num_received < num_vnns) {
1176                 struct ctdb_req_header *hdr;
1177                 struct ctdb_reply_control *reply;
1178                 struct ctdb_vnn_list *vnn;
1179                 uint32_t reqid;
1180                 uint8_t *reply_data;
1181
1182                 status = ctdb_read_req(conn, 0, talloc_tos(), &hdr);
1183                 if (!NT_STATUS_IS_OK(status)) {
1184                         DEBUG(1, ("ctdb_read_req failed: %s\n",
1185                                   nt_errstr(status)));
1186                         goto fail;
1187                 }
1188
1189                 if (hdr->operation != CTDB_REPLY_CONTROL) {
1190                         DEBUG(1, ("Received invalid reply %u\n",
1191                                   (unsigned)reply->hdr.operation));
1192                         goto fail;
1193                 }
1194                 reply = (struct ctdb_reply_control *)hdr;
1195
1196                 reqid = reply->hdr.reqid;
1197
1198                 DEBUG(10, ("Received reqid %d\n", (int)reqid));
1199
1200                 for (i=0; i<num_vnns; i++) {
1201                         if (reqid == vnns[i].reqid) {
1202                                 break;
1203                         }
1204                 }
1205                 if (i == num_vnns) {
1206                         DEBUG(1, ("Received unknown reqid number %u\n",
1207                                   (unsigned)reqid));
1208                         goto fail;
1209                 }
1210
1211                 DEBUG(10, ("Found index %u\n", i));
1212
1213                 vnn = &vnns[i];
1214
1215                 DEBUG(10, ("Received vnn %u, vnn->num_srvids %u, datalen %u\n",
1216                            (unsigned)vnn->vnn, vnn->num_srvids,
1217                            (unsigned)reply->datalen));
1218
1219                 if (reply->datalen >= ((vnn->num_srvids+7)/8)) {
1220                         /*
1221                          * Got a real reply
1222                          */
1223                         reply_data = reply->data;
1224                 } else {
1225                         /*
1226                          * Got an error reply
1227                          */
1228                         DEBUG(5, ("Received short reply len %d, status %u, "
1229                                   "errorlen %u\n",
1230                                   (unsigned)reply->datalen,
1231                                   (unsigned)reply->status,
1232                                   (unsigned)reply->errorlen));
1233                         dump_data(5, reply->data, reply->errorlen);
1234
1235                         /*
1236                          * This will trigger everything set to false
1237                          */
1238                         reply_data = NULL;
1239                 }
1240
1241                 for (i=0; i<vnn->num_srvids; i++) {
1242                         int idx = vnn->pid_indexes[i];
1243
1244                         if (pids[i].unique_id ==
1245                             SERVERID_UNIQUE_ID_NOT_TO_VERIFY) {
1246                                 results[idx] = true;
1247                                 continue;
1248                         }
1249                         results[idx] =
1250                                 (reply_data != NULL) &&
1251                                 ((reply_data[i/8] & (1<<(i%8))) != 0);
1252                 }
1253
1254                 TALLOC_FREE(reply);
1255                 num_received += 1;
1256         }
1257
1258         TALLOC_FREE(vnns);
1259         return true;
1260 fail:
1261         cluster_fatal("serverids_exist failed");
1262         return false;
1263 }
1264
1265 /*
1266  * Get a db path
1267  */
1268 char *ctdbd_dbpath(struct ctdbd_connection *conn,
1269                    TALLOC_CTX *mem_ctx, uint32_t db_id)
1270 {
1271         NTSTATUS status;
1272         TDB_DATA data;
1273         int32_t cstatus;
1274
1275         data.dptr = (uint8_t*)&db_id;
1276         data.dsize = sizeof(db_id);
1277
1278         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1279                                CTDB_CONTROL_GETDBPATH, 0, 0, data, 
1280                                mem_ctx, &data, &cstatus);
1281         if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
1282                 DEBUG(0,(__location__ " ctdb_control for getdbpath failed\n"));
1283                 return NULL;
1284         }
1285
1286         return (char *)data.dptr;
1287 }
1288
1289 /*
1290  * attach to a ctdb database
1291  */
1292 NTSTATUS ctdbd_db_attach(struct ctdbd_connection *conn,
1293                          const char *name, uint32_t *db_id, int tdb_flags)
1294 {
1295         NTSTATUS status;
1296         TDB_DATA data;
1297         int32_t cstatus;
1298         bool persistent = (tdb_flags & TDB_CLEAR_IF_FIRST) == 0;
1299
1300         data = string_term_tdb_data(name);
1301
1302         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1303                                persistent
1304                                ? CTDB_CONTROL_DB_ATTACH_PERSISTENT
1305                                : CTDB_CONTROL_DB_ATTACH,
1306                                tdb_flags, 0, data, NULL, &data, &cstatus);
1307         if (!NT_STATUS_IS_OK(status)) {
1308                 DEBUG(0, (__location__ " ctdb_control for db_attach "
1309                           "failed: %s\n", nt_errstr(status)));
1310                 return status;
1311         }
1312
1313         if (cstatus != 0 || data.dsize != sizeof(uint32_t)) {
1314                 DEBUG(0,(__location__ " ctdb_control for db_attach failed\n"));
1315                 return NT_STATUS_INTERNAL_ERROR;
1316         }
1317
1318         *db_id = *(uint32_t *)data.dptr;
1319         talloc_free(data.dptr);
1320
1321         if (!(tdb_flags & TDB_SEQNUM)) {
1322                 return NT_STATUS_OK;
1323         }
1324
1325         data.dptr = (uint8_t *)db_id;
1326         data.dsize = sizeof(*db_id);
1327
1328         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1329                                CTDB_CONTROL_ENABLE_SEQNUM, 0, 0, data, 
1330                                NULL, NULL, &cstatus);
1331         if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
1332                 DEBUG(0,(__location__ " ctdb_control for enable seqnum "
1333                          "failed\n"));
1334                 return NT_STATUS_IS_OK(status) ? NT_STATUS_INTERNAL_ERROR :
1335                         status;
1336         }
1337
1338         return NT_STATUS_OK;
1339 }
1340
1341 /*
1342  * force the migration of a record to this node
1343  */
1344 NTSTATUS ctdbd_migrate(struct ctdbd_connection *conn, uint32_t db_id,
1345                        TDB_DATA key)
1346 {
1347         struct ctdb_req_call req;
1348         struct ctdb_req_header *hdr;
1349         struct iovec iov[2];
1350         ssize_t nwritten;
1351         NTSTATUS status;
1352
1353         ZERO_STRUCT(req);
1354
1355         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
1356         req.hdr.ctdb_magic   = CTDB_MAGIC;
1357         req.hdr.ctdb_version = CTDB_VERSION;
1358         req.hdr.operation    = CTDB_REQ_CALL;
1359         req.hdr.reqid        = ctdbd_next_reqid(conn);
1360         req.flags            = CTDB_IMMEDIATE_MIGRATION;
1361         req.callid           = CTDB_NULL_FUNC;
1362         req.db_id            = db_id;
1363         req.keylen           = key.dsize;
1364
1365         DEBUG(10, ("ctdbd_migrate: Sending ctdb packet\n"));
1366         ctdb_packet_dump(&req.hdr);
1367
1368         iov[0].iov_base = &req;
1369         iov[0].iov_len = offsetof(struct ctdb_req_call, data);
1370         iov[1].iov_base = key.dptr;
1371         iov[1].iov_len = key.dsize;
1372
1373         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
1374         if (nwritten == -1) {
1375                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
1376                 cluster_fatal("cluster dispatch daemon msg write error\n");
1377         }
1378
1379         status = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
1380
1381         if (!NT_STATUS_IS_OK(status)) {
1382                 DEBUG(0, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
1383                 goto fail;
1384         }
1385
1386         if (hdr->operation != CTDB_REPLY_CALL) {
1387                 DEBUG(0, ("received invalid reply\n"));
1388                 status = NT_STATUS_INTERNAL_ERROR;
1389                 goto fail;
1390         }
1391
1392         status = NT_STATUS_OK;
1393  fail:
1394
1395         TALLOC_FREE(hdr);
1396         return status;
1397 }
1398
1399 /*
1400  * Fetch a record and parse it
1401  */
1402 NTSTATUS ctdbd_parse(struct ctdbd_connection *conn, uint32_t db_id,
1403                      TDB_DATA key, bool local_copy,
1404                      void (*parser)(TDB_DATA key, TDB_DATA data,
1405                                     void *private_data),
1406                      void *private_data)
1407 {
1408         struct ctdb_req_call req;
1409         struct ctdb_req_header *hdr = NULL;
1410         struct ctdb_reply_call *reply;
1411         struct iovec iov[2];
1412         ssize_t nwritten;
1413         NTSTATUS status;
1414         uint32_t flags;
1415
1416         flags = local_copy ? CTDB_WANT_READONLY : 0;
1417
1418         ZERO_STRUCT(req);
1419
1420         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
1421         req.hdr.ctdb_magic   = CTDB_MAGIC;
1422         req.hdr.ctdb_version = CTDB_VERSION;
1423         req.hdr.operation    = CTDB_REQ_CALL;
1424         req.hdr.reqid        = ctdbd_next_reqid(conn);
1425         req.flags            = flags;
1426         req.callid           = CTDB_FETCH_FUNC;
1427         req.db_id            = db_id;
1428         req.keylen           = key.dsize;
1429
1430         iov[0].iov_base = &req;
1431         iov[0].iov_len = offsetof(struct ctdb_req_call, data);
1432         iov[1].iov_base = key.dptr;
1433         iov[1].iov_len = key.dsize;
1434
1435         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
1436         if (nwritten == -1) {
1437                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
1438                 cluster_fatal("cluster dispatch daemon msg write error\n");
1439         }
1440
1441         status = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
1442
1443         if (!NT_STATUS_IS_OK(status)) {
1444                 DEBUG(0, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
1445                 goto fail;
1446         }
1447
1448         if (hdr->operation != CTDB_REPLY_CALL) {
1449                 DEBUG(0, ("received invalid reply\n"));
1450                 status = NT_STATUS_INTERNAL_ERROR;
1451                 goto fail;
1452         }
1453         reply = (struct ctdb_reply_call *)hdr;
1454
1455         if (reply->datalen == 0) {
1456                 /*
1457                  * Treat an empty record as non-existing
1458                  */
1459                 status = NT_STATUS_NOT_FOUND;
1460                 goto fail;
1461         }
1462
1463         parser(key, make_tdb_data(&reply->data[0], reply->datalen),
1464                private_data);
1465
1466         status = NT_STATUS_OK;
1467  fail:
1468         TALLOC_FREE(hdr);
1469         return status;
1470 }
1471
1472 /*
1473   Traverse a ctdb database. This uses a kind-of hackish way to open a second
1474   connection to ctdbd to avoid the hairy recursive and async problems with
1475   everything in-line.
1476 */
1477
1478 NTSTATUS ctdbd_traverse(uint32_t db_id,
1479                         void (*fn)(TDB_DATA key, TDB_DATA data,
1480                                    void *private_data),
1481                         void *private_data)
1482 {
1483         struct ctdbd_connection *conn;
1484         NTSTATUS status;
1485
1486         TDB_DATA key, data;
1487         struct ctdb_traverse_start t;
1488         int cstatus;
1489
1490         become_root();
1491         status = ctdbd_init_connection(NULL, &conn);
1492         unbecome_root();
1493         if (!NT_STATUS_IS_OK(status)) {
1494                 DEBUG(0, ("ctdbd_init_connection failed: %s\n",
1495                           nt_errstr(status)));
1496                 return status;
1497         }
1498
1499         t.db_id = db_id;
1500         t.srvid = conn->rand_srvid;
1501         t.reqid = ctdbd_next_reqid(conn);
1502
1503         data.dptr = (uint8_t *)&t;
1504         data.dsize = sizeof(t);
1505
1506         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1507                                CTDB_CONTROL_TRAVERSE_START, conn->rand_srvid, 0,
1508                                data, NULL, NULL, &cstatus);
1509
1510         if (!NT_STATUS_IS_OK(status) || (cstatus != 0)) {
1511
1512                 DEBUG(0,("ctdbd_control failed: %s, %d\n", nt_errstr(status),
1513                          cstatus));
1514
1515                 if (NT_STATUS_IS_OK(status)) {
1516                         /*
1517                          * We need a mapping here
1518                          */
1519                         status = NT_STATUS_UNSUCCESSFUL;
1520                 }
1521                 TALLOC_FREE(conn);
1522                 return status;
1523         }
1524
1525         while (True) {
1526                 struct ctdb_req_header *hdr;
1527                 struct ctdb_req_message *m;
1528                 struct ctdb_rec_data *d;
1529
1530                 status = ctdb_read_packet(conn->fd, conn, &hdr);
1531                 if (!NT_STATUS_IS_OK(status)) {
1532                         DEBUG(0, ("ctdb_read_packet failed: %s\n",
1533                                   nt_errstr(status)));
1534                         cluster_fatal("ctdbd died\n");
1535                 }
1536
1537                 if (hdr->operation != CTDB_REQ_MESSAGE) {
1538                         DEBUG(0, ("Got operation %u, expected a message\n",
1539                                   (unsigned)hdr->operation));
1540                         TALLOC_FREE(conn);
1541                         return NT_STATUS_UNEXPECTED_IO_ERROR;
1542                 }
1543
1544                 m = (struct ctdb_req_message *)hdr;
1545                 d = (struct ctdb_rec_data *)&m->data[0];
1546                 if (m->datalen < sizeof(uint32_t) || m->datalen != d->length) {
1547                         DEBUG(0, ("Got invalid traverse data of length %d\n",
1548                                   (int)m->datalen));
1549                         TALLOC_FREE(conn);
1550                         return NT_STATUS_UNEXPECTED_IO_ERROR;
1551                 }
1552
1553                 key.dsize = d->keylen;
1554                 key.dptr  = &d->data[0];
1555                 data.dsize = d->datalen;
1556                 data.dptr = &d->data[d->keylen];
1557
1558                 if (key.dsize == 0 && data.dsize == 0) {
1559                         /* end of traverse */
1560                         TALLOC_FREE(conn);
1561                         return NT_STATUS_OK;
1562                 }
1563
1564                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
1565                         DEBUG(0, ("Got invalid ltdb header length %d\n",
1566                                   (int)data.dsize));
1567                         TALLOC_FREE(conn);
1568                         return NT_STATUS_UNEXPECTED_IO_ERROR;
1569                 }
1570                 data.dsize -= sizeof(struct ctdb_ltdb_header);
1571                 data.dptr += sizeof(struct ctdb_ltdb_header);
1572
1573                 if (fn != NULL) {
1574                         fn(key, data, private_data);
1575                 }
1576         }
1577         return NT_STATUS_OK;
1578 }
1579
1580 /*
1581    This is used to canonicalize a ctdb_sock_addr structure.
1582 */
1583 static void smbd_ctdb_canonicalize_ip(const struct sockaddr_storage *in,
1584                                       struct sockaddr_storage *out)
1585 {
1586         memcpy(out, in, sizeof (*out));
1587
1588 #ifdef HAVE_IPV6
1589         if (in->ss_family == AF_INET6) {
1590                 const char prefix[12] = { 0,0,0,0,0,0,0,0,0,0,0xff,0xff };
1591                 const struct sockaddr_in6 *in6 =
1592                         (const struct sockaddr_in6 *)in;
1593                 struct sockaddr_in *out4 = (struct sockaddr_in *)out;
1594                 if (memcmp(&in6->sin6_addr, prefix, 12) == 0) {
1595                         memset(out, 0, sizeof(*out));
1596 #ifdef HAVE_SOCK_SIN_LEN
1597                         out4->sin_len = sizeof(*out);
1598 #endif
1599                         out4->sin_family = AF_INET;
1600                         out4->sin_port   = in6->sin6_port;
1601                         memcpy(&out4->sin_addr, &in6->sin6_addr.s6_addr[12], 4);
1602                 }
1603         }
1604 #endif
1605 }
1606
1607 /*
1608  * Register us as a server for a particular tcp connection
1609  */
1610
1611 NTSTATUS ctdbd_register_ips(struct ctdbd_connection *conn,
1612                             const struct sockaddr_storage *_server,
1613                             const struct sockaddr_storage *_client,
1614                             bool (*release_ip_handler)(const char *ip_addr,
1615                                                        void *private_data),
1616                             void *private_data)
1617 {
1618         /*
1619          * we still use ctdb_control_tcp for ipv4
1620          * because we want to work against older ctdb
1621          * versions at runtime
1622          */
1623         struct ctdb_control_tcp p4;
1624         struct ctdb_control_tcp_addr p;
1625         TDB_DATA data;
1626         NTSTATUS status;
1627         struct sockaddr_storage client;
1628         struct sockaddr_storage server;
1629
1630         /*
1631          * Only one connection so far
1632          */
1633         SMB_ASSERT(conn->release_ip_handler == NULL);
1634
1635         smbd_ctdb_canonicalize_ip(_client, &client);
1636         smbd_ctdb_canonicalize_ip(_server, &server);
1637
1638         switch (client.ss_family) {
1639         case AF_INET:
1640                 memcpy(&p4.dest, &server, sizeof(p4.dest));
1641                 memcpy(&p4.src, &client, sizeof(p4.src));
1642                 data.dptr = (uint8_t *)&p4;
1643                 data.dsize = sizeof(p4);
1644                 break;
1645         case AF_INET6:
1646                 memcpy(&p.dest.ip6, &server, sizeof(p.dest.ip6));
1647                 memcpy(&p.src.ip6, &client, sizeof(p.src.ip6));
1648                 data.dptr = (uint8_t *)&p;
1649                 data.dsize = sizeof(p);
1650                 break;
1651         default:
1652                 return NT_STATUS_INTERNAL_ERROR;
1653         }
1654
1655         conn->release_ip_handler = release_ip_handler;
1656         conn->release_ip_priv = private_data;
1657
1658         /*
1659          * We want to be told about IP releases
1660          */
1661
1662         status = register_with_ctdbd(conn, CTDB_SRVID_RELEASE_IP);
1663         if (!NT_STATUS_IS_OK(status)) {
1664                 return status;
1665         }
1666
1667         /*
1668          * inform ctdb of our tcp connection, so if IP takeover happens ctdb
1669          * can send an extra ack to trigger a reset for our client, so it
1670          * immediately reconnects
1671          */
1672         return ctdbd_control(conn, CTDB_CURRENT_NODE, 
1673                              CTDB_CONTROL_TCP_CLIENT, 0,
1674                              CTDB_CTRL_FLAG_NOREPLY, data, NULL, NULL, NULL);
1675 }
1676
1677 /*
1678  * We want to handle reconfigure events
1679  */
1680 NTSTATUS ctdbd_register_reconfigure(struct ctdbd_connection *conn)
1681 {
1682         return register_with_ctdbd(conn, CTDB_SRVID_RECONFIGURE);
1683 }
1684
1685 /*
1686   call a control on the local node
1687  */
1688 NTSTATUS ctdbd_control_local(struct ctdbd_connection *conn, uint32_t opcode,
1689                              uint64_t srvid, uint32_t flags, TDB_DATA data,
1690                              TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
1691                              int *cstatus)
1692 {
1693         return ctdbd_control(conn, CTDB_CURRENT_NODE, opcode, srvid, flags, data, mem_ctx, outdata, cstatus);
1694 }
1695
1696 NTSTATUS ctdb_watch_us(struct ctdbd_connection *conn)
1697 {
1698         struct ctdb_client_notify_register reg_data;
1699         size_t struct_len;
1700         NTSTATUS status;
1701         int cstatus;
1702
1703         reg_data.srvid = CTDB_SRVID_SAMBA_NOTIFY;
1704         reg_data.len = 1;
1705         reg_data.notify_data[0] = 0;
1706
1707         struct_len = offsetof(struct ctdb_client_notify_register,
1708                               notify_data) + reg_data.len;
1709
1710         status = ctdbd_control_local(
1711                 conn, CTDB_CONTROL_REGISTER_NOTIFY, conn->rand_srvid, 0,
1712                 make_tdb_data((uint8_t *)&reg_data, struct_len),
1713                 NULL, NULL, &cstatus);
1714         if (!NT_STATUS_IS_OK(status)) {
1715                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1716                           nt_errstr(status)));
1717         }
1718         return status;
1719 }
1720
1721 NTSTATUS ctdb_unwatch(struct ctdbd_connection *conn)
1722 {
1723         struct ctdb_client_notify_deregister dereg_data;
1724         NTSTATUS status;
1725         int cstatus;
1726
1727         dereg_data.srvid = CTDB_SRVID_SAMBA_NOTIFY;
1728
1729         status = ctdbd_control_local(
1730                 conn, CTDB_CONTROL_DEREGISTER_NOTIFY, conn->rand_srvid, 0,
1731                 make_tdb_data((uint8_t *)&dereg_data, sizeof(dereg_data)),
1732                 NULL, NULL, &cstatus);
1733         if (!NT_STATUS_IS_OK(status)) {
1734                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1735                           nt_errstr(status)));
1736         }
1737         return status;
1738 }
1739
1740 NTSTATUS ctdbd_probe(void)
1741 {
1742         /*
1743          * Do a very early check if ctdbd is around to avoid an abort and core
1744          * later
1745          */
1746         struct ctdbd_connection *conn = NULL;
1747         NTSTATUS status;
1748
1749         status = ctdbd_messaging_connection(talloc_tos(), &conn);
1750
1751         /*
1752          * We only care if we can connect.
1753          */
1754         TALLOC_FREE(conn);
1755
1756         return status;
1757 }