s3-ctdb: Add ctdb_processes_exist
[kai/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
24 #ifdef CLUSTER_SUPPORT
25
26 #include "ctdbd_conn.h"
27 #include "ctdb_packet.h"
28 #include "messages.h"
29
30 /*
31  * It is not possible to include ctdb.h and tdb_compat.h (included via
32  * some other include above) without warnings. This fixes those
33  * warnings.
34  */
35
36 #ifdef typesafe_cb
37 #undef typesafe_cb
38 #endif
39
40 #ifdef typesafe_cb_preargs
41 #undef typesafe_cb_preargs
42 #endif
43
44 #ifdef typesafe_cb_postargs
45 #undef typesafe_cb_postargs
46 #endif
47
48 /* paths to these include files come from --with-ctdb= in configure */
49
50 #include "ctdb.h"
51 #include "ctdb_private.h"
52
53 struct ctdbd_connection {
54         struct messaging_context *msg_ctx;
55         uint32 reqid;
56         uint32 our_vnn;
57         uint64 rand_srvid;
58         struct ctdb_packet_context *pkt;
59         struct fd_event *fde;
60
61         void (*release_ip_handler)(const char *ip_addr, void *private_data);
62         void *release_ip_priv;
63 };
64
65 static uint32_t ctdbd_next_reqid(struct ctdbd_connection *conn)
66 {
67         conn->reqid += 1;
68         if (conn->reqid == 0) {
69                 conn->reqid += 1;
70         }
71         return conn->reqid;
72 }
73
74 static NTSTATUS ctdbd_control(struct ctdbd_connection *conn,
75                               uint32_t vnn, uint32 opcode, 
76                               uint64_t srvid, uint32_t flags, TDB_DATA data, 
77                               TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
78                               int *cstatus);
79
80 /*
81  * exit on fatal communications errors with the ctdbd daemon
82  */
83 static void cluster_fatal(const char *why)
84 {
85         DEBUG(0,("cluster fatal event: %s - exiting immediately\n", why));
86         /* we don't use smb_panic() as we don't want to delay to write
87            a core file. We need to release this process id immediately
88            so that someone else can take over without getting sharing
89            violations */
90         _exit(1);
91 }
92
93 /*
94  *
95  */
96 static void ctdb_packet_dump(struct ctdb_req_header *hdr)
97 {
98         if (DEBUGLEVEL < 10) {
99                 return;
100         }
101         DEBUGADD(10, ("len=%d, magic=%x, vers=%d, gen=%d, op=%d, reqid=%d\n",
102                       (int)hdr->length, (int)hdr->ctdb_magic,
103                       (int)hdr->ctdb_version, (int)hdr->generation,
104                       (int)hdr->operation, (int)hdr->reqid));
105 }
106
107 /*
108  * Register a srvid with ctdbd
109  */
110 static NTSTATUS register_with_ctdbd(struct ctdbd_connection *conn,
111                                     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 *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 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;
205         int fd;
206
207         if (!sockname || !*sockname) {
208                 sockname = CTDB_PATH;
209         }
210
211         fd = socket(AF_UNIX, SOCK_STREAM, 0);
212         if (fd == -1) {
213                 DEBUG(3, ("Could not create socket: %s\n", strerror(errno)));
214                 return map_nt_error_from_unix(errno);
215         }
216
217         ZERO_STRUCT(addr);
218         addr.sun_family = AF_UNIX;
219         strncpy(addr.sun_path, sockname, sizeof(addr.sun_path));
220
221         if (sys_connect(fd, (struct sockaddr *)(void *)&addr) == -1) {
222                 DEBUG(1, ("connect(%s) failed: %s\n", sockname,
223                           strerror(errno)));
224                 close(fd);
225                 return map_nt_error_from_unix(errno);
226         }
227
228         if (!(result = ctdb_packet_init(mem_ctx, fd))) {
229                 close(fd);
230                 return NT_STATUS_NO_MEMORY;
231         }
232
233         *presult = result;
234         return NT_STATUS_OK;
235 }
236
237 /*
238  * Do we have a complete ctdb packet in the queue?
239  */
240
241 static bool ctdb_req_complete(const uint8_t *buf, size_t available,
242                               size_t *length,
243                               void *private_data)
244 {
245         uint32 msglen;
246
247         if (available < sizeof(msglen)) {
248                 return False;
249         }
250
251         msglen = *((uint32 *)buf);
252
253         DEBUG(10, ("msglen = %d\n", msglen));
254
255         if (msglen < sizeof(struct ctdb_req_header)) {
256                 DEBUG(0, ("Got invalid msglen: %d, expected at least %d for "
257                           "the req_header\n", (int)msglen,
258                           (int)sizeof(struct ctdb_req_header)));
259                 cluster_fatal("ctdbd protocol error\n");
260         }
261
262         if (available < msglen) {
263                 return false;
264         }
265
266         *length = msglen;
267         return true;
268 }
269
270 /*
271  * State necessary to defer an incoming message while we are waiting for a
272  * ctdb reply.
273  */
274
275 struct deferred_msg_state {
276         struct messaging_context *msg_ctx;
277         struct messaging_rec *rec;
278 };
279
280 /*
281  * Timed event handler for the deferred message
282  */
283
284 static void deferred_message_dispatch(struct event_context *event_ctx,
285                                       struct timed_event *te,
286                                       struct timeval now,
287                                       void *private_data)
288 {
289         struct deferred_msg_state *state = talloc_get_type_abort(
290                 private_data, struct deferred_msg_state);
291
292         messaging_dispatch_rec(state->msg_ctx, state->rec);
293         TALLOC_FREE(state);
294         TALLOC_FREE(te);
295 }
296
297 struct req_pull_state {
298         TALLOC_CTX *mem_ctx;
299         DATA_BLOB req;
300 };
301
302 /*
303  * Pull a ctdb request out of the incoming ctdb_packet queue
304  */
305
306 static NTSTATUS ctdb_req_pull(uint8_t *buf, size_t length,
307                               void *private_data)
308 {
309         struct req_pull_state *state = (struct req_pull_state *)private_data;
310
311         state->req.data = talloc_move(state->mem_ctx, &buf);
312         state->req.length = length;
313         return NT_STATUS_OK;
314 }
315
316 /*
317  * Fetch a messaging_rec from an incoming ctdb style message
318  */
319
320 static struct messaging_rec *ctdb_pull_messaging_rec(TALLOC_CTX *mem_ctx,
321                                                      size_t overall_length,
322                                                      struct ctdb_req_message *msg)
323 {
324         struct messaging_rec *result;
325         DATA_BLOB blob;
326         enum ndr_err_code ndr_err;
327
328         if ((overall_length < offsetof(struct ctdb_req_message, data))
329             || (overall_length
330                 < offsetof(struct ctdb_req_message, data) + msg->datalen)) {
331
332                 cluster_fatal("got invalid msg length");
333         }
334
335         if (!(result = talloc(mem_ctx, struct messaging_rec))) {
336                 DEBUG(0, ("talloc failed\n"));
337                 return NULL;
338         }
339
340         blob = data_blob_const(msg->data, msg->datalen);
341
342         ndr_err = ndr_pull_struct_blob(
343                 &blob, result, result,
344                 (ndr_pull_flags_fn_t)ndr_pull_messaging_rec);
345
346         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
347                 DEBUG(0, ("ndr_pull_struct_blob failed: %s\n",
348                           ndr_errstr(ndr_err)));
349                 TALLOC_FREE(result);
350                 return NULL;
351         }
352
353         if (DEBUGLEVEL >= 10) {
354                 DEBUG(10, ("ctdb_pull_messaging_rec:\n"));
355                 NDR_PRINT_DEBUG(messaging_rec, result);
356         }
357
358         return result;
359 }
360
361 static NTSTATUS ctdb_packet_fd_read_sync(struct ctdb_packet_context *ctx)
362 {
363         int timeout = lp_ctdb_timeout();
364
365         if (timeout == 0) {
366                 timeout = -1;
367         }
368         return ctdb_packet_fd_read_sync_timeout(ctx, timeout);
369 }
370
371 /*
372  * Read a full ctdbd request. If we have a messaging context, defer incoming
373  * messages that might come in between.
374  */
375
376 static NTSTATUS ctdb_read_req(struct ctdbd_connection *conn, uint32 reqid,
377                               TALLOC_CTX *mem_ctx, void *result)
378 {
379         struct ctdb_req_header *hdr;
380         struct req_pull_state state;
381         NTSTATUS status;
382
383  again:
384
385         status = ctdb_packet_fd_read_sync(conn->pkt);
386
387         if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_BUSY)) {
388                 /* EAGAIN */
389                 goto again;
390         } else if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
391                 /* EAGAIN */
392                 goto again;
393         }
394
395         if (!NT_STATUS_IS_OK(status)) {
396                 DEBUG(0, ("ctdb_packet_fd_read failed: %s\n", nt_errstr(status)));
397                 cluster_fatal("ctdbd died\n");
398         }
399
400  next_pkt:
401
402         ZERO_STRUCT(state);
403         state.mem_ctx = mem_ctx;
404
405         if (!ctdb_packet_handler(conn->pkt, ctdb_req_complete, ctdb_req_pull,
406                             &state, &status)) {
407                 /*
408                  * Not enough data
409                  */
410                 DEBUG(10, ("not enough data from ctdb socket, retrying\n"));
411                 goto again;
412         }
413
414         if (!NT_STATUS_IS_OK(status)) {
415                 DEBUG(0, ("Could not read ctdb_packet: %s\n", nt_errstr(status)));
416                 cluster_fatal("ctdbd died\n");
417         }
418
419         hdr = (struct ctdb_req_header *)state.req.data;
420
421         DEBUG(10, ("Received ctdb packet\n"));
422         ctdb_packet_dump(hdr);
423
424         if (hdr->operation == CTDB_REQ_MESSAGE) {
425                 struct timed_event *evt;
426                 struct deferred_msg_state *msg_state;
427                 struct ctdb_req_message *msg = (struct ctdb_req_message *)hdr;
428
429                 if (conn->msg_ctx == NULL) {
430                         DEBUG(1, ("Got a message without having a msg ctx, "
431                                   "dropping msg %llu\n",
432                                   (long long unsigned)msg->srvid));
433                         goto next_pkt;
434                 }
435
436                 if ((conn->release_ip_handler != NULL)
437                     && (msg->srvid == CTDB_SRVID_RELEASE_IP)) {
438                         /* must be dispatched immediately */
439                         DEBUG(10, ("received CTDB_SRVID_RELEASE_IP\n"));
440                         conn->release_ip_handler((const char *)msg->data,
441                                                  conn->release_ip_priv);
442                         TALLOC_FREE(hdr);
443                         goto next_pkt;
444                 }
445
446                 if ((msg->srvid == CTDB_SRVID_RECONFIGURE)
447                     || (msg->srvid == CTDB_SRVID_SAMBA_NOTIFY)) {
448
449                         DEBUG(1, ("ctdb_read_req: Got %s message\n",
450                                   (msg->srvid == CTDB_SRVID_RECONFIGURE)
451                                   ? "cluster reconfigure" : "SAMBA_NOTIFY"));
452
453                         messaging_send(conn->msg_ctx,
454                                        messaging_server_id(conn->msg_ctx),
455                                        MSG_SMB_BRL_VALIDATE, &data_blob_null);
456                         messaging_send(conn->msg_ctx,
457                                        messaging_server_id(conn->msg_ctx),
458                                        MSG_DBWRAP_G_LOCK_RETRY,
459                                        &data_blob_null);
460                         TALLOC_FREE(hdr);
461                         goto next_pkt;
462                 }
463
464                 msg_state = talloc(NULL, struct deferred_msg_state);
465                 if (msg_state == NULL) {
466                         DEBUG(0, ("talloc failed\n"));
467                         TALLOC_FREE(hdr);
468                         goto next_pkt;
469                 }
470
471                 if (!(msg_state->rec = ctdb_pull_messaging_rec(
472                               msg_state, state.req.length, msg))) {
473                         DEBUG(0, ("ctdbd_pull_messaging_rec failed\n"));
474                         TALLOC_FREE(msg_state);
475                         TALLOC_FREE(hdr);
476                         goto next_pkt;
477                 }
478
479                 TALLOC_FREE(hdr);
480
481                 msg_state->msg_ctx = conn->msg_ctx;
482
483                 /*
484                  * We're waiting for a call reply, but an async message has
485                  * crossed. Defer dispatching to the toplevel event loop.
486                  */
487                 evt = event_add_timed(conn->msg_ctx->event_ctx,
488                                       conn->msg_ctx->event_ctx,
489                                       timeval_zero(),
490                                       deferred_message_dispatch,
491                                       msg_state);
492                 if (evt == NULL) {
493                         DEBUG(0, ("event_add_timed failed\n"));
494                         TALLOC_FREE(msg_state);
495                         TALLOC_FREE(hdr);
496                         goto next_pkt;
497                 }
498
499                 goto next_pkt;
500         }
501
502         if ((reqid != 0) && (hdr->reqid != reqid)) {
503                 /* we got the wrong reply */
504                 DEBUG(0,("Discarding mismatched ctdb reqid %u should have "
505                          "been %u\n", hdr->reqid, reqid));
506                 TALLOC_FREE(hdr);
507                 goto again;
508         }
509
510         *((void **)result) = talloc_move(mem_ctx, &hdr);
511
512         return NT_STATUS_OK;
513 }
514
515 /*
516  * Get us a ctdbd connection
517  */
518
519 static NTSTATUS ctdbd_init_connection(TALLOC_CTX *mem_ctx,
520                                       struct ctdbd_connection **pconn)
521 {
522         struct ctdbd_connection *conn;
523         NTSTATUS status;
524
525         if (!(conn = talloc_zero(mem_ctx, struct ctdbd_connection))) {
526                 DEBUG(0, ("talloc failed\n"));
527                 return NT_STATUS_NO_MEMORY;
528         }
529
530         status = ctdbd_connect(conn, &conn->pkt);
531
532         if (!NT_STATUS_IS_OK(status)) {
533                 DEBUG(10, ("ctdbd_connect failed: %s\n", nt_errstr(status)));
534                 goto fail;
535         }
536
537         status = get_cluster_vnn(conn, &conn->our_vnn);
538
539         if (!NT_STATUS_IS_OK(status)) {
540                 DEBUG(10, ("get_cluster_vnn failed: %s\n", nt_errstr(status)));
541                 goto fail;
542         }
543
544         if (!ctdbd_working(conn, conn->our_vnn)) {
545                 DEBUG(2, ("Node is not working, can not connect\n"));
546                 status = NT_STATUS_INTERNAL_DB_ERROR;
547                 goto fail;
548         }
549
550         generate_random_buffer((unsigned char *)&conn->rand_srvid,
551                                sizeof(conn->rand_srvid));
552
553         status = register_with_ctdbd(conn, conn->rand_srvid);
554
555         if (!NT_STATUS_IS_OK(status)) {
556                 DEBUG(5, ("Could not register random srvid: %s\n",
557                           nt_errstr(status)));
558                 goto fail;
559         }
560
561         *pconn = conn;
562         return NT_STATUS_OK;
563
564  fail:
565         TALLOC_FREE(conn);
566         return status;
567 }
568
569 /*
570  * Get us a ctdbd connection and register us as a process
571  */
572
573 NTSTATUS ctdbd_messaging_connection(TALLOC_CTX *mem_ctx,
574                                     struct ctdbd_connection **pconn)
575 {
576         struct ctdbd_connection *conn;
577         NTSTATUS status;
578
579         status = ctdbd_init_connection(mem_ctx, &conn);
580
581         if (!NT_STATUS_IS_OK(status)) {
582                 return status;
583         }
584
585         status = register_with_ctdbd(conn, (uint64_t)sys_getpid());
586         if (!NT_STATUS_IS_OK(status)) {
587                 goto fail;
588         }
589
590         status = register_with_ctdbd(conn, MSG_SRVID_SAMBA);
591         if (!NT_STATUS_IS_OK(status)) {
592                 goto fail;
593         }
594
595         status = register_with_ctdbd(conn, CTDB_SRVID_SAMBA_NOTIFY);
596         if (!NT_STATUS_IS_OK(status)) {
597                 goto fail;
598         }
599
600         *pconn = conn;
601         return NT_STATUS_OK;
602
603  fail:
604         TALLOC_FREE(conn);
605         return status;
606 }
607
608 struct messaging_context *ctdb_conn_msg_ctx(struct ctdbd_connection *conn)
609 {
610         return conn->msg_ctx;
611 }
612
613 int ctdbd_conn_get_fd(struct ctdbd_connection *conn)
614 {
615         return ctdb_packet_get_fd(conn->pkt);
616 }
617
618 /*
619  * Packet handler to receive and handle a ctdb message
620  */
621 static NTSTATUS ctdb_handle_message(uint8_t *buf, size_t length,
622                                     void *private_data)
623 {
624         struct ctdbd_connection *conn = talloc_get_type_abort(
625                 private_data, struct ctdbd_connection);
626         struct ctdb_req_message *msg;
627         struct messaging_rec *msg_rec;
628
629         msg = (struct ctdb_req_message *)buf;
630
631         if (msg->hdr.operation != CTDB_REQ_MESSAGE) {
632                 DEBUG(0, ("Received async msg of type %u, discarding\n",
633                           msg->hdr.operation));
634                 TALLOC_FREE(buf);
635                 return NT_STATUS_INVALID_PARAMETER;
636         }
637
638         if ((conn->release_ip_handler != NULL)
639             && (msg->srvid == CTDB_SRVID_RELEASE_IP)) {
640                 /* must be dispatched immediately */
641                 DEBUG(10, ("received CTDB_SRVID_RELEASE_IP\n"));
642                 conn->release_ip_handler((const char *)msg->data,
643                                          conn->release_ip_priv);
644                 TALLOC_FREE(buf);
645                 return NT_STATUS_OK;
646         }
647
648         SMB_ASSERT(conn->msg_ctx != NULL);
649
650         if ((msg->srvid == CTDB_SRVID_RECONFIGURE)
651             || (msg->srvid == CTDB_SRVID_SAMBA_NOTIFY)){
652                 DEBUG(0,("Got cluster reconfigure message\n"));
653                 /*
654                  * when the cluster is reconfigured or someone of the
655                  * family has passed away (SAMBA_NOTIFY), we need to
656                  * clean the brl database
657                  */
658                 messaging_send(conn->msg_ctx,
659                                messaging_server_id(conn->msg_ctx),
660                                MSG_SMB_BRL_VALIDATE, &data_blob_null);
661
662                 messaging_send(conn->msg_ctx,
663                                messaging_server_id(conn->msg_ctx),
664                                MSG_DBWRAP_G_LOCK_RETRY,
665                                &data_blob_null);
666
667                 TALLOC_FREE(buf);
668                 return NT_STATUS_OK;
669         }
670
671         /* only messages to our pid or the broadcast are valid here */
672         if (msg->srvid != sys_getpid() && msg->srvid != MSG_SRVID_SAMBA) {
673                 DEBUG(0,("Got unexpected message with srvid=%llu\n", 
674                          (unsigned long long)msg->srvid));
675                 TALLOC_FREE(buf);
676                 return NT_STATUS_OK;
677         }
678
679         if (!(msg_rec = ctdb_pull_messaging_rec(NULL, length, msg))) {
680                 DEBUG(10, ("ctdb_pull_messaging_rec failed\n"));
681                 TALLOC_FREE(buf);
682                 return NT_STATUS_NO_MEMORY;
683         }
684
685         messaging_dispatch_rec(conn->msg_ctx, msg_rec);
686
687         TALLOC_FREE(msg_rec);
688         TALLOC_FREE(buf);
689         return NT_STATUS_OK;
690 }
691
692 /*
693  * The ctdbd socket is readable asynchronuously
694  */
695
696 static void ctdbd_socket_handler(struct event_context *event_ctx,
697                                  struct fd_event *event,
698                                  uint16 flags,
699                                  void *private_data)
700 {
701         struct ctdbd_connection *conn = talloc_get_type_abort(
702                 private_data, struct ctdbd_connection);
703
704         NTSTATUS status;
705
706         status = ctdb_packet_fd_read(conn->pkt);
707
708         if (!NT_STATUS_IS_OK(status)) {
709                 DEBUG(0, ("packet_fd_read failed: %s\n", nt_errstr(status)));
710                 cluster_fatal("ctdbd died\n");
711         }
712
713         while (ctdb_packet_handler(conn->pkt, ctdb_req_complete,
714                               ctdb_handle_message, conn, &status)) {
715                 if (!NT_STATUS_IS_OK(status)) {
716                         DEBUG(10, ("could not handle incoming message: %s\n",
717                                    nt_errstr(status)));
718                 }
719         }
720 }
721
722 /*
723  * Prepare a ctdbd connection to receive messages
724  */
725
726 NTSTATUS ctdbd_register_msg_ctx(struct ctdbd_connection *conn,
727                                 struct messaging_context *msg_ctx)
728 {
729         SMB_ASSERT(conn->msg_ctx == NULL);
730         SMB_ASSERT(conn->fde == NULL);
731
732         if (!(conn->fde = event_add_fd(msg_ctx->event_ctx, conn,
733                                        ctdb_packet_get_fd(conn->pkt),
734                                        EVENT_FD_READ,
735                                        ctdbd_socket_handler,
736                                        conn))) {
737                 DEBUG(0, ("event_add_fd failed\n"));
738                 return NT_STATUS_NO_MEMORY;
739         }
740
741         conn->msg_ctx = msg_ctx;
742
743         return NT_STATUS_OK;
744 }
745
746 /*
747  * Send a messaging message across a ctdbd
748  */
749
750 NTSTATUS ctdbd_messaging_send(struct ctdbd_connection *conn,
751                               uint32 dst_vnn, uint64 dst_srvid,
752                               struct messaging_rec *msg)
753 {
754         struct ctdb_req_message r;
755         TALLOC_CTX *mem_ctx;
756         DATA_BLOB blob;
757         NTSTATUS status;
758         enum ndr_err_code ndr_err;
759
760         if (!(mem_ctx = talloc_init("ctdbd_messaging_send"))) {
761                 DEBUG(0, ("talloc failed\n"));
762                 return NT_STATUS_NO_MEMORY;
763         }
764
765         ndr_err = ndr_push_struct_blob(
766                 &blob, mem_ctx, msg,
767                 (ndr_push_flags_fn_t)ndr_push_messaging_rec);
768
769         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
770                 DEBUG(0, ("ndr_push_struct_blob failed: %s\n",
771                           ndr_errstr(ndr_err)));
772                 status = ndr_map_error2ntstatus(ndr_err);
773                 goto fail;
774         }
775
776         r.hdr.length = offsetof(struct ctdb_req_message, data) + blob.length;
777         r.hdr.ctdb_magic = CTDB_MAGIC;
778         r.hdr.ctdb_version = CTDB_VERSION;
779         r.hdr.generation = 1;
780         r.hdr.operation  = CTDB_REQ_MESSAGE;
781         r.hdr.destnode   = dst_vnn;
782         r.hdr.srcnode    = conn->our_vnn;
783         r.hdr.reqid      = 0;
784         r.srvid          = dst_srvid;
785         r.datalen        = blob.length;
786
787         DEBUG(10, ("ctdbd_messaging_send: Sending ctdb packet\n"));
788         ctdb_packet_dump(&r.hdr);
789
790         status = ctdb_packet_send(
791                 conn->pkt, 2,
792                 data_blob_const(&r, offsetof(struct ctdb_req_message, data)),
793                 blob);
794
795         if (!NT_STATUS_IS_OK(status)) {
796                 DEBUG(0, ("ctdb_packet_send failed: %s\n", nt_errstr(status)));
797                 goto fail;
798         }
799
800         status = ctdb_packet_flush(conn->pkt);
801
802         if (!NT_STATUS_IS_OK(status)) {
803                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
804                 cluster_fatal("cluster dispatch daemon msg write error\n");
805         }
806
807         status = NT_STATUS_OK;
808  fail:
809         TALLOC_FREE(mem_ctx);
810         return status;
811 }
812
813 /*
814  * send/recv a generic ctdb control message
815  */
816 static NTSTATUS ctdbd_control(struct ctdbd_connection *conn,
817                               uint32_t vnn, uint32 opcode, 
818                               uint64_t srvid, uint32_t flags, 
819                               TDB_DATA data, 
820                               TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
821                               int *cstatus)
822 {
823         struct ctdb_req_control req;
824         struct ctdb_reply_control *reply = NULL;
825         struct ctdbd_connection *new_conn = NULL;
826         NTSTATUS status;
827
828         if (conn == NULL) {
829                 status = ctdbd_init_connection(NULL, &new_conn);
830
831                 if (!NT_STATUS_IS_OK(status)) {
832                         DEBUG(10, ("Could not init temp connection: %s\n",
833                                    nt_errstr(status)));
834                         goto fail;
835                 }
836
837                 conn = new_conn;
838         }
839
840         ZERO_STRUCT(req);
841         req.hdr.length = offsetof(struct ctdb_req_control, data) + data.dsize;
842         req.hdr.ctdb_magic   = CTDB_MAGIC;
843         req.hdr.ctdb_version = CTDB_VERSION;
844         req.hdr.operation    = CTDB_REQ_CONTROL;
845         req.hdr.reqid        = ctdbd_next_reqid(conn);
846         req.hdr.destnode     = vnn;
847         req.opcode           = opcode;
848         req.srvid            = srvid;
849         req.datalen          = data.dsize;
850         req.flags            = flags;
851
852         DEBUG(10, ("ctdbd_control: Sending ctdb packet\n"));
853         ctdb_packet_dump(&req.hdr);
854
855         status = ctdb_packet_send(
856                 conn->pkt, 2,
857                 data_blob_const(&req, offsetof(struct ctdb_req_control, data)),
858                 data_blob_const(data.dptr, data.dsize));
859
860         if (!NT_STATUS_IS_OK(status)) {
861                 DEBUG(3, ("ctdb_packet_send failed: %s\n", nt_errstr(status)));
862                 goto fail;
863         }
864
865         status = ctdb_packet_flush(conn->pkt);
866
867         if (!NT_STATUS_IS_OK(status)) {
868                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
869                 cluster_fatal("cluster dispatch daemon control write error\n");
870         }
871
872         if (flags & CTDB_CTRL_FLAG_NOREPLY) {
873                 TALLOC_FREE(new_conn);
874                 if (cstatus) {
875                         *cstatus = 0;
876                 }
877                 return NT_STATUS_OK;
878         }
879
880         status = ctdb_read_req(conn, req.hdr.reqid, NULL, (void *)&reply);
881
882         if (!NT_STATUS_IS_OK(status)) {
883                 DEBUG(10, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
884                 goto fail;
885         }
886
887         if (reply->hdr.operation != CTDB_REPLY_CONTROL) {
888                 DEBUG(0, ("received invalid reply\n"));
889                 goto fail;
890         }
891
892         if (outdata) {
893                 if (!(outdata->dptr = (uint8 *)talloc_memdup(
894                               mem_ctx, reply->data, reply->datalen))) {
895                         TALLOC_FREE(reply);
896                         return NT_STATUS_NO_MEMORY;
897                 }
898                 outdata->dsize = reply->datalen;
899         }
900         if (cstatus) {
901                 (*cstatus) = reply->status;
902         }
903
904         status = NT_STATUS_OK;
905
906  fail:
907         TALLOC_FREE(new_conn);
908         TALLOC_FREE(reply);
909         return status;
910 }
911
912 /*
913  * see if a remote process exists
914  */
915 bool ctdbd_process_exists(struct ctdbd_connection *conn, uint32 vnn, pid_t pid)
916 {
917         NTSTATUS status;
918         TDB_DATA data;
919         int32_t cstatus;
920
921         data.dptr = (uint8_t*)&pid;
922         data.dsize = sizeof(pid);
923
924         status = ctdbd_control(conn, vnn, CTDB_CONTROL_PROCESS_EXISTS, 0, 0,
925                                data, NULL, NULL, &cstatus);
926         if (!NT_STATUS_IS_OK(status)) {
927                 DEBUG(0, (__location__ " ctdb_control for process_exists "
928                           "failed\n"));
929                 return False;
930         }
931
932         return cstatus == 0;
933 }
934
935 bool ctdb_processes_exist(struct ctdbd_connection *conn,
936                           const struct server_id *pids, int num_pids,
937                           bool *results)
938 {
939         TALLOC_CTX *frame = talloc_stackframe();
940         int i, num_received;
941         NTSTATUS status;
942         uint32_t *reqids;
943         bool result = false;
944
945         reqids = talloc_array(talloc_tos(), uint32_t, num_pids);
946         if (reqids == NULL) {
947                 goto fail;
948         }
949
950         for (i=0; i<num_pids; i++) {
951                 struct ctdb_req_control req;
952
953                 results[i] = false;
954                 reqids[i] = ctdbd_next_reqid(conn);
955
956                 ZERO_STRUCT(req);
957
958                 req.hdr.length = offsetof(struct ctdb_req_control, data);
959                 req.hdr.length += sizeof(pid_t);
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(pids[i].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(&pids[i].pid, sizeof(pids[i].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                 for (i=0; i<num_pids; i++) {
1013                         if (reqid == reqids[i]) {
1014                                 break;
1015                         }
1016                 }
1017                 if (i == num_pids) {
1018                         DEBUG(10, ("Received unknown record number %u\n",
1019                                    (unsigned)reqid));
1020                         goto fail;
1021                 }
1022                 results[i] = ((reply->status) == 0);
1023                 TALLOC_FREE(reply);
1024                 num_received += 1;
1025         }
1026
1027         result = true;
1028 fail:
1029         TALLOC_FREE(frame);
1030         return result;
1031 }
1032
1033 /*
1034  * Get a db path
1035  */
1036 char *ctdbd_dbpath(struct ctdbd_connection *conn,
1037                    TALLOC_CTX *mem_ctx, uint32_t db_id)
1038 {
1039         NTSTATUS status;
1040         TDB_DATA data;
1041         int32_t cstatus;
1042
1043         data.dptr = (uint8_t*)&db_id;
1044         data.dsize = sizeof(db_id);
1045
1046         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1047                                CTDB_CONTROL_GETDBPATH, 0, 0, data, 
1048                                mem_ctx, &data, &cstatus);
1049         if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
1050                 DEBUG(0,(__location__ " ctdb_control for getdbpath failed\n"));
1051                 return NULL;
1052         }
1053
1054         return (char *)data.dptr;
1055 }
1056
1057 /*
1058  * attach to a ctdb database
1059  */
1060 NTSTATUS ctdbd_db_attach(struct ctdbd_connection *conn,
1061                          const char *name, uint32_t *db_id, int tdb_flags)
1062 {
1063         NTSTATUS status;
1064         TDB_DATA data;
1065         int32_t cstatus;
1066         bool persistent = (tdb_flags & TDB_CLEAR_IF_FIRST) == 0;
1067
1068         data.dptr = (uint8_t*)name;
1069         data.dsize = strlen(name)+1;
1070
1071         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1072                                persistent
1073                                ? CTDB_CONTROL_DB_ATTACH_PERSISTENT
1074                                : CTDB_CONTROL_DB_ATTACH,
1075                                tdb_flags, 0, data, NULL, &data, &cstatus);
1076         if (!NT_STATUS_IS_OK(status)) {
1077                 DEBUG(0, (__location__ " ctdb_control for db_attach "
1078                           "failed: %s\n", nt_errstr(status)));
1079                 return status;
1080         }
1081
1082         if (cstatus != 0 || data.dsize != sizeof(uint32_t)) {
1083                 DEBUG(0,(__location__ " ctdb_control for db_attach failed\n"));
1084                 return NT_STATUS_INTERNAL_ERROR;
1085         }
1086
1087         *db_id = *(uint32_t *)data.dptr;
1088         talloc_free(data.dptr);
1089
1090         if (!(tdb_flags & TDB_SEQNUM)) {
1091                 return NT_STATUS_OK;
1092         }
1093
1094         data.dptr = (uint8_t *)db_id;
1095         data.dsize = sizeof(*db_id);
1096
1097         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1098                                CTDB_CONTROL_ENABLE_SEQNUM, 0, 0, data, 
1099                                NULL, NULL, &cstatus);
1100         if (!NT_STATUS_IS_OK(status) || cstatus != 0) {
1101                 DEBUG(0,(__location__ " ctdb_control for enable seqnum "
1102                          "failed\n"));
1103                 return NT_STATUS_IS_OK(status) ? NT_STATUS_INTERNAL_ERROR :
1104                         status;
1105         }
1106
1107         return NT_STATUS_OK;
1108 }
1109
1110 /*
1111  * force the migration of a record to this node
1112  */
1113 NTSTATUS ctdbd_migrate(struct ctdbd_connection *conn, uint32 db_id,
1114                        TDB_DATA key)
1115 {
1116         struct ctdb_req_call req;
1117         struct ctdb_reply_call *reply;
1118         NTSTATUS status;
1119
1120         ZERO_STRUCT(req);
1121
1122         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
1123         req.hdr.ctdb_magic   = CTDB_MAGIC;
1124         req.hdr.ctdb_version = CTDB_VERSION;
1125         req.hdr.operation    = CTDB_REQ_CALL;
1126         req.hdr.reqid        = ctdbd_next_reqid(conn);
1127         req.flags            = CTDB_IMMEDIATE_MIGRATION;
1128         req.callid           = CTDB_NULL_FUNC;
1129         req.db_id            = db_id;
1130         req.keylen           = key.dsize;
1131
1132         DEBUG(10, ("ctdbd_migrate: Sending ctdb packet\n"));
1133         ctdb_packet_dump(&req.hdr);
1134
1135         status = ctdb_packet_send(
1136                 conn->pkt, 2,
1137                 data_blob_const(&req, offsetof(struct ctdb_req_call, data)),
1138                 data_blob_const(key.dptr, key.dsize));
1139
1140         if (!NT_STATUS_IS_OK(status)) {
1141                 DEBUG(3, ("ctdb_packet_send failed: %s\n", nt_errstr(status)));
1142                 return status;
1143         }
1144
1145         status = ctdb_packet_flush(conn->pkt);
1146
1147         if (!NT_STATUS_IS_OK(status)) {
1148                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
1149                 cluster_fatal("cluster dispatch daemon control write error\n");
1150         }
1151
1152         status = ctdb_read_req(conn, req.hdr.reqid, NULL, (void *)&reply);
1153
1154         if (!NT_STATUS_IS_OK(status)) {
1155                 DEBUG(0, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
1156                 goto fail;
1157         }
1158
1159         if (reply->hdr.operation != CTDB_REPLY_CALL) {
1160                 DEBUG(0, ("received invalid reply\n"));
1161                 status = NT_STATUS_INTERNAL_ERROR;
1162                 goto fail;
1163         }
1164
1165         status = NT_STATUS_OK;
1166  fail:
1167
1168         TALLOC_FREE(reply);
1169         return status;
1170 }
1171
1172 /*
1173  * remotely fetch a record without locking it or forcing a migration
1174  */
1175 NTSTATUS ctdbd_fetch(struct ctdbd_connection *conn, uint32 db_id,
1176                      TDB_DATA key, TALLOC_CTX *mem_ctx, TDB_DATA *data)
1177 {
1178         struct ctdb_req_call req;
1179         struct ctdb_reply_call *reply;
1180         NTSTATUS status;
1181
1182         ZERO_STRUCT(req);
1183
1184         req.hdr.length = offsetof(struct ctdb_req_call, data) + key.dsize;
1185         req.hdr.ctdb_magic   = CTDB_MAGIC;
1186         req.hdr.ctdb_version = CTDB_VERSION;
1187         req.hdr.operation    = CTDB_REQ_CALL;
1188         req.hdr.reqid        = ctdbd_next_reqid(conn);
1189         req.flags            = 0;
1190         req.callid           = CTDB_FETCH_FUNC;
1191         req.db_id            = db_id;
1192         req.keylen           = key.dsize;
1193
1194         status = ctdb_packet_send(
1195                 conn->pkt, 2,
1196                 data_blob_const(&req, offsetof(struct ctdb_req_call, data)),
1197                 data_blob_const(key.dptr, key.dsize));
1198
1199         if (!NT_STATUS_IS_OK(status)) {
1200                 DEBUG(3, ("ctdb_packet_send failed: %s\n", nt_errstr(status)));
1201                 return status;
1202         }
1203
1204         status = ctdb_packet_flush(conn->pkt);
1205
1206         if (!NT_STATUS_IS_OK(status)) {
1207                 DEBUG(3, ("write to ctdbd failed: %s\n", nt_errstr(status)));
1208                 cluster_fatal("cluster dispatch daemon control write error\n");
1209         }
1210
1211         status = ctdb_read_req(conn, req.hdr.reqid, NULL, (void *)&reply);
1212
1213         if (!NT_STATUS_IS_OK(status)) {
1214                 DEBUG(0, ("ctdb_read_req failed: %s\n", nt_errstr(status)));
1215                 goto fail;
1216         }
1217
1218         if (reply->hdr.operation != CTDB_REPLY_CALL) {
1219                 DEBUG(0, ("received invalid reply\n"));
1220                 status = NT_STATUS_INTERNAL_ERROR;
1221                 goto fail;
1222         }
1223
1224         data->dsize = reply->datalen;
1225         if (data->dsize == 0) {
1226                 data->dptr = NULL;
1227                 goto done;
1228         }
1229
1230         data->dptr = (uint8 *)talloc_memdup(mem_ctx, &reply->data[0],
1231                                             reply->datalen);
1232         if (data->dptr == NULL) {
1233                 DEBUG(0, ("talloc failed\n"));
1234                 status = NT_STATUS_NO_MEMORY;
1235                 goto fail;
1236         }
1237
1238  done:
1239         status = NT_STATUS_OK;
1240  fail:
1241         TALLOC_FREE(reply);
1242         return status;
1243 }
1244
1245 struct ctdbd_traverse_state {
1246         void (*fn)(TDB_DATA key, TDB_DATA data, void *private_data);
1247         void *private_data;
1248 };
1249
1250 /*
1251  * Handle a traverse record coming in on the ctdbd connection
1252  */
1253
1254 static NTSTATUS ctdb_traverse_handler(uint8_t *buf, size_t length,
1255                                       void *private_data)
1256 {
1257         struct ctdbd_traverse_state *state =
1258                 (struct ctdbd_traverse_state *)private_data;
1259
1260         struct ctdb_req_message *m;
1261         struct ctdb_rec_data *d;
1262         TDB_DATA key, data;
1263
1264         m = (struct ctdb_req_message *)buf;
1265
1266         if (length < sizeof(*m) || m->hdr.length != length) {
1267                 DEBUG(0, ("Got invalid message of length %d\n", (int)length));
1268                 TALLOC_FREE(buf);
1269                 return NT_STATUS_UNEXPECTED_IO_ERROR;
1270         }
1271
1272         d = (struct ctdb_rec_data *)&m->data[0];
1273         if (m->datalen < sizeof(uint32_t) || m->datalen != d->length) {
1274                 DEBUG(0, ("Got invalid traverse data of length %d\n",
1275                           (int)m->datalen));
1276                 TALLOC_FREE(buf);
1277                 return NT_STATUS_UNEXPECTED_IO_ERROR;
1278         }
1279
1280         key.dsize = d->keylen;
1281         key.dptr  = &d->data[0];
1282         data.dsize = d->datalen;
1283         data.dptr = &d->data[d->keylen];                
1284
1285         if (key.dsize == 0 && data.dsize == 0) {
1286                 /* end of traverse */
1287                 return NT_STATUS_END_OF_FILE;
1288         }
1289
1290         if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
1291                 DEBUG(0, ("Got invalid ltdb header length %d\n",
1292                           (int)data.dsize));
1293                 TALLOC_FREE(buf);
1294                 return NT_STATUS_UNEXPECTED_IO_ERROR;
1295         }
1296         data.dsize -= sizeof(struct ctdb_ltdb_header);
1297         data.dptr += sizeof(struct ctdb_ltdb_header);
1298
1299         if (state->fn) {
1300                 state->fn(key, data, state->private_data);
1301         }
1302
1303         TALLOC_FREE(buf);
1304         return NT_STATUS_OK;
1305 }
1306
1307 /*
1308   Traverse a ctdb database. This uses a kind-of hackish way to open a second
1309   connection to ctdbd to avoid the hairy recursive and async problems with
1310   everything in-line.
1311 */
1312
1313 NTSTATUS ctdbd_traverse(uint32 db_id,
1314                         void (*fn)(TDB_DATA key, TDB_DATA data,
1315                                    void *private_data),
1316                         void *private_data)
1317 {
1318         struct ctdbd_connection *conn;
1319         NTSTATUS status;
1320
1321         TDB_DATA data;
1322         struct ctdb_traverse_start t;
1323         int cstatus;
1324         struct ctdbd_traverse_state state;
1325
1326         status = ctdbd_init_connection(NULL, &conn);
1327         if (!NT_STATUS_IS_OK(status)) {
1328                 DEBUG(0, ("ctdbd_init_connection failed: %s\n",
1329                           nt_errstr(status)));
1330                 return status;
1331         }
1332
1333         t.db_id = db_id;
1334         t.srvid = conn->rand_srvid;
1335         t.reqid = ctdbd_next_reqid(conn);
1336
1337         data.dptr = (uint8_t *)&t;
1338         data.dsize = sizeof(t);
1339
1340         status = ctdbd_control(conn, CTDB_CURRENT_NODE,
1341                                CTDB_CONTROL_TRAVERSE_START, conn->rand_srvid, 0,
1342                                data, NULL, NULL, &cstatus);
1343
1344         if (!NT_STATUS_IS_OK(status) || (cstatus != 0)) {
1345
1346                 DEBUG(0,("ctdbd_control failed: %s, %d\n", nt_errstr(status),
1347                          cstatus));
1348
1349                 if (NT_STATUS_IS_OK(status)) {
1350                         /*
1351                          * We need a mapping here
1352                          */
1353                         status = NT_STATUS_UNSUCCESSFUL;
1354                 }
1355                 goto done;
1356         }
1357
1358         state.fn = fn;
1359         state.private_data = private_data;
1360
1361         while (True) {
1362
1363                 status = NT_STATUS_OK;
1364
1365                 if (ctdb_packet_handler(conn->pkt, ctdb_req_complete,
1366                                    ctdb_traverse_handler, &state, &status)) {
1367
1368                         if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
1369                                 status = NT_STATUS_OK;
1370                                 break;
1371                         }
1372
1373                         /*
1374                          * There might be more in the queue
1375                          */
1376                         continue;
1377                 }
1378
1379                 if (!NT_STATUS_IS_OK(status)) {
1380                         break;
1381                 }
1382
1383                 status = ctdb_packet_fd_read_sync(conn->pkt);
1384
1385                 if (NT_STATUS_EQUAL(status, NT_STATUS_RETRY)) {
1386                         /*
1387                          * There might be more in the queue
1388                          */
1389                         continue;
1390                 }
1391
1392                 if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
1393                         status = NT_STATUS_OK;
1394                         break;
1395                 }
1396
1397                 if (!NT_STATUS_IS_OK(status)) {
1398                         DEBUG(0, ("ctdb_packet_fd_read_sync failed: %s\n", nt_errstr(status)));
1399                         cluster_fatal("ctdbd died\n");
1400                 }
1401         }
1402
1403  done:
1404         TALLOC_FREE(conn);
1405         return status;
1406 }
1407
1408 /*
1409    This is used to canonicalize a ctdb_sock_addr structure.
1410 */
1411 static void smbd_ctdb_canonicalize_ip(const struct sockaddr_storage *in,
1412                                       struct sockaddr_storage *out)
1413 {
1414         memcpy(out, in, sizeof (*out));
1415
1416 #ifdef HAVE_IPV6
1417         if (in->ss_family == AF_INET6) {
1418                 const char prefix[12] = { 0,0,0,0,0,0,0,0,0,0,0xff,0xff };
1419                 const struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)in;
1420                 struct sockaddr_in *out4 = (struct sockaddr_in *)out;
1421                 if (memcmp(&in6->sin6_addr, prefix, 12) == 0) {
1422                         memset(out, 0, sizeof(*out));
1423 #ifdef HAVE_SOCK_SIN_LEN
1424                         out4->sin_len = sizeof(*out);
1425 #endif
1426                         out4->sin_family = AF_INET;
1427                         out4->sin_port   = in6->sin6_port;
1428                         memcpy(&out4->sin_addr, &in6->sin6_addr.s6_addr32[3], 4);
1429                 }
1430         }
1431 #endif
1432 }
1433
1434 /*
1435  * Register us as a server for a particular tcp connection
1436  */
1437
1438 NTSTATUS ctdbd_register_ips(struct ctdbd_connection *conn,
1439                             const struct sockaddr_storage *_server,
1440                             const struct sockaddr_storage *_client,
1441                             void (*release_ip_handler)(const char *ip_addr,
1442                                                        void *private_data),
1443                             void *private_data)
1444 {
1445         /*
1446          * we still use ctdb_control_tcp for ipv4
1447          * because we want to work against older ctdb
1448          * versions at runtime
1449          */
1450         struct ctdb_control_tcp p4;
1451 #ifdef HAVE_STRUCT_CTDB_CONTROL_TCP_ADDR
1452         struct ctdb_control_tcp_addr p;
1453 #endif
1454         TDB_DATA data;
1455         NTSTATUS status;
1456         struct sockaddr_storage client;
1457         struct sockaddr_storage server;
1458
1459         /*
1460          * Only one connection so far
1461          */
1462         SMB_ASSERT(conn->release_ip_handler == NULL);
1463
1464         smbd_ctdb_canonicalize_ip(_client, &client);
1465         smbd_ctdb_canonicalize_ip(_server, &server);
1466
1467         switch (client.ss_family) {
1468         case AF_INET:
1469                 memcpy(&p4.dest, &server, sizeof(p4.dest));
1470                 memcpy(&p4.src, &client, sizeof(p4.src));
1471                 data.dptr = (uint8_t *)&p4;
1472                 data.dsize = sizeof(p4);
1473                 break;
1474 #ifdef HAVE_STRUCT_CTDB_CONTROL_TCP_ADDR
1475         case AF_INET6:
1476                 memcpy(&p.dest.ip6, &server, sizeof(p.dest.ip6));
1477                 memcpy(&p.src.ip6, &client, sizeof(p.src.ip6));
1478                 data.dptr = (uint8_t *)&p;
1479                 data.dsize = sizeof(p);
1480                 break;
1481 #endif
1482         default:
1483                 return NT_STATUS_INTERNAL_ERROR;
1484         }
1485
1486         conn->release_ip_handler = release_ip_handler;
1487         conn->release_ip_priv = private_data;
1488
1489         /*
1490          * We want to be told about IP releases
1491          */
1492
1493         status = register_with_ctdbd(conn, CTDB_SRVID_RELEASE_IP);
1494         if (!NT_STATUS_IS_OK(status)) {
1495                 return status;
1496         }
1497
1498         /*
1499          * inform ctdb of our tcp connection, so if IP takeover happens ctdb
1500          * can send an extra ack to trigger a reset for our client, so it
1501          * immediately reconnects
1502          */
1503         return ctdbd_control(conn, CTDB_CURRENT_NODE, 
1504                              CTDB_CONTROL_TCP_CLIENT, 0,
1505                              CTDB_CTRL_FLAG_NOREPLY, data, NULL, NULL, NULL);
1506 }
1507
1508 /*
1509  * We want to handle reconfigure events
1510  */
1511 NTSTATUS ctdbd_register_reconfigure(struct ctdbd_connection *conn)
1512 {
1513         return register_with_ctdbd(conn, CTDB_SRVID_RECONFIGURE);
1514 }
1515
1516 /*
1517   call a control on the local node
1518  */
1519 NTSTATUS ctdbd_control_local(struct ctdbd_connection *conn, uint32 opcode, 
1520                              uint64_t srvid, uint32_t flags, TDB_DATA data, 
1521                              TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
1522                              int *cstatus)
1523 {
1524         return ctdbd_control(conn, CTDB_CURRENT_NODE, opcode, srvid, flags, data, mem_ctx, outdata, cstatus);
1525 }
1526
1527 NTSTATUS ctdb_watch_us(struct ctdbd_connection *conn)
1528 {
1529         struct ctdb_client_notify_register reg_data;
1530         size_t struct_len;
1531         NTSTATUS status;
1532         int cstatus;
1533
1534         reg_data.srvid = CTDB_SRVID_SAMBA_NOTIFY;
1535         reg_data.len = 1;
1536         reg_data.notify_data[0] = 0;
1537
1538         struct_len = offsetof(struct ctdb_client_notify_register,
1539                               notify_data) + reg_data.len;
1540
1541         status = ctdbd_control_local(
1542                 conn, CTDB_CONTROL_REGISTER_NOTIFY, conn->rand_srvid, 0,
1543                 make_tdb_data((uint8_t *)&reg_data, struct_len),
1544                 NULL, NULL, &cstatus);
1545         if (!NT_STATUS_IS_OK(status)) {
1546                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1547                           nt_errstr(status)));
1548         }
1549         return status;
1550 }
1551
1552 NTSTATUS ctdb_unwatch(struct ctdbd_connection *conn)
1553 {
1554         struct ctdb_client_notify_deregister dereg_data;
1555         NTSTATUS status;
1556         int cstatus;
1557
1558         dereg_data.srvid = CTDB_SRVID_SAMBA_NOTIFY;
1559
1560         status = ctdbd_control_local(
1561                 conn, CTDB_CONTROL_DEREGISTER_NOTIFY, conn->rand_srvid, 0,
1562                 make_tdb_data((uint8_t *)&dereg_data, sizeof(dereg_data)),
1563                 NULL, NULL, &cstatus);
1564         if (!NT_STATUS_IS_OK(status)) {
1565                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1566                           nt_errstr(status)));
1567         }
1568         return status;
1569 }
1570
1571 #endif