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