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