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