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