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