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