lib: Use tdb_storev in gencache
[kai/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 "replace.h"
22 #include "util_tdb.h"
23 #include "serverid.h"
24 #include "ctdbd_conn.h"
25 #include "system/select.h"
26 #include "lib/util/sys_rw_data.h"
27 #include "lib/util/iov_buf.h"
28 #include "lib/util/select.h"
29 #include "lib/util/debug.h"
30 #include "lib/util/talloc_stack.h"
31 #include "lib/util/genrand.h"
32 #include "lib/util/fault.h"
33
34 /* paths to these include files come from --with-ctdb= in configure */
35
36 #include "ctdb_private.h"
37
38 struct ctdbd_srvid_cb {
39         uint64_t srvid;
40         int (*cb)(uint32_t src_vnn, uint32_t dst_vnn,
41                   uint64_t dst_srvid,
42                   const uint8_t *msg, size_t msglen,
43                   void *private_data);
44         void *private_data;
45 };
46
47 struct ctdbd_connection {
48         uint32_t reqid;
49         uint32_t our_vnn;
50         uint64_t rand_srvid;
51         struct ctdbd_srvid_cb *callbacks;
52         int fd;
53         struct tevent_fd *fde;
54         int timeout;
55 };
56
57 static uint32_t ctdbd_next_reqid(struct ctdbd_connection *conn)
58 {
59         conn->reqid += 1;
60         if (conn->reqid == 0) {
61                 conn->reqid += 1;
62         }
63         return conn->reqid;
64 }
65
66 static int ctdbd_control(struct ctdbd_connection *conn,
67                          uint32_t vnn, uint32_t opcode,
68                          uint64_t srvid, uint32_t flags,
69                          TDB_DATA data,
70                          TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
71                          int32_t *cstatus);
72
73 /*
74  * exit on fatal communications errors with the ctdbd daemon
75  */
76 static void cluster_fatal(const char *why)
77 {
78         DEBUG(0,("cluster fatal event: %s - exiting immediately\n", why));
79         /* we don't use smb_panic() as we don't want to delay to write
80            a core file. We need to release this process id immediately
81            so that someone else can take over without getting sharing
82            violations */
83         _exit(1);
84 }
85
86 /*
87  *
88  */
89 static void ctdb_packet_dump(struct ctdb_req_header *hdr)
90 {
91         if (DEBUGLEVEL < 11) {
92                 return;
93         }
94         DEBUGADD(11, ("len=%d, magic=%x, vers=%d, gen=%d, op=%d, reqid=%d\n",
95                       (int)hdr->length, (int)hdr->ctdb_magic,
96                       (int)hdr->ctdb_version, (int)hdr->generation,
97                       (int)hdr->operation, (int)hdr->reqid));
98 }
99
100 /*
101  * Register a srvid with ctdbd
102  */
103 int register_with_ctdbd(struct ctdbd_connection *conn, uint64_t srvid,
104                         int (*cb)(uint32_t src_vnn, uint32_t dst_vnn,
105                                   uint64_t dst_srvid,
106                                   const uint8_t *msg, size_t msglen,
107                                   void *private_data),
108                         void *private_data)
109 {
110
111         int ret;
112         int32_t cstatus;
113         size_t num_callbacks;
114         struct ctdbd_srvid_cb *tmp;
115
116         ret = ctdbd_control_local(conn, CTDB_CONTROL_REGISTER_SRVID, srvid, 0,
117                                   tdb_null, NULL, NULL, &cstatus);
118         if (ret != 0) {
119                 return ret;
120         }
121
122         num_callbacks = talloc_array_length(conn->callbacks);
123
124         tmp = talloc_realloc(conn, conn->callbacks, struct ctdbd_srvid_cb,
125                              num_callbacks + 1);
126         if (tmp == NULL) {
127                 return ENOMEM;
128         }
129         conn->callbacks = tmp;
130
131         conn->callbacks[num_callbacks] = (struct ctdbd_srvid_cb) {
132                 .srvid = srvid, .cb = cb, .private_data = private_data
133         };
134
135         return 0;
136 }
137
138 static int ctdbd_msg_call_back(struct ctdbd_connection *conn,
139                                struct ctdb_req_message_old *msg)
140 {
141         uint32_t msg_len;
142         size_t i, num_callbacks;
143
144         msg_len = msg->hdr.length;
145         if (msg_len < offsetof(struct ctdb_req_message_old, data)) {
146                 DBG_DEBUG("len %"PRIu32" too small\n", msg_len);
147                 return 0;
148         }
149         msg_len -= offsetof(struct ctdb_req_message_old, data);
150
151         if (msg_len < msg->datalen) {
152                 DBG_DEBUG("msg_len=%"PRIu32" < msg->datalen=%"PRIu32"\n",
153                           msg_len, msg->datalen);
154                 return 0;
155         }
156
157         num_callbacks = talloc_array_length(conn->callbacks);
158
159         for (i=0; i<num_callbacks; i++) {
160                 struct ctdbd_srvid_cb *cb = &conn->callbacks[i];
161
162                 if ((cb->srvid == msg->srvid) && (cb->cb != NULL)) {
163                         int ret;
164
165                         ret = cb->cb(msg->hdr.srcnode, msg->hdr.destnode,
166                                      msg->srvid, msg->data, msg->datalen,
167                                      cb->private_data);
168                         if (ret != 0) {
169                                 return ret;
170                         }
171                 }
172         }
173         return 0;
174 }
175
176 /*
177  * get our vnn from the cluster
178  */
179 static int get_cluster_vnn(struct ctdbd_connection *conn, uint32_t *vnn)
180 {
181         int32_t cstatus=-1;
182         int ret;
183         ret = ctdbd_control_local(conn, CTDB_CONTROL_GET_PNN, 0, 0,
184                                   tdb_null, NULL, NULL, &cstatus);
185         if (ret != 0) {
186                 DEBUG(1, ("ctdbd_control failed: %s\n", strerror(ret)));
187                 return ret;
188         }
189         *vnn = (uint32_t)cstatus;
190         return ret;
191 }
192
193 /*
194  * Are we active (i.e. not banned or stopped?)
195  */
196 static bool ctdbd_working(struct ctdbd_connection *conn, uint32_t vnn)
197 {
198         int32_t cstatus=-1;
199         TDB_DATA outdata;
200         struct ctdb_node_map_old *m;
201         bool ok = false;
202         uint32_t i;
203         int ret;
204
205         ret = ctdbd_control_local(conn, CTDB_CONTROL_GET_NODEMAP, 0, 0,
206                                   tdb_null, talloc_tos(), &outdata, &cstatus);
207         if (ret != 0) {
208                 DEBUG(1, ("ctdbd_control failed: %s\n", strerror(ret)));
209                 return false;
210         }
211         if ((cstatus != 0) || (outdata.dptr == NULL)) {
212                 DEBUG(2, ("Received invalid ctdb data\n"));
213                 return false;
214         }
215
216         m = (struct ctdb_node_map_old *)outdata.dptr;
217
218         for (i=0; i<m->num; i++) {
219                 if (vnn == m->nodes[i].pnn) {
220                         break;
221                 }
222         }
223
224         if (i == m->num) {
225                 DEBUG(2, ("Did not find ourselves (node %d) in nodemap\n",
226                           (int)vnn));
227                 goto fail;
228         }
229
230         if ((m->nodes[i].flags & NODE_FLAGS_INACTIVE) != 0) {
231                 DEBUG(2, ("Node has status %x, not active\n",
232                           (int)m->nodes[i].flags));
233                 goto fail;
234         }
235
236         ok = true;
237 fail:
238         TALLOC_FREE(outdata.dptr);
239         return ok;
240 }
241
242 uint32_t ctdbd_vnn(const struct ctdbd_connection *conn)
243 {
244         return conn->our_vnn;
245 }
246
247 /*
248  * Get us a ctdb connection
249  */
250
251 static int ctdbd_connect(const char *sockname, int *pfd)
252 {
253         struct sockaddr_un addr = { 0, };
254         int fd;
255         socklen_t salen;
256         size_t namelen;
257
258         fd = socket(AF_UNIX, SOCK_STREAM, 0);
259         if (fd == -1) {
260                 int err = errno;
261                 DEBUG(3, ("Could not create socket: %s\n", strerror(err)));
262                 return err;
263         }
264
265         addr.sun_family = AF_UNIX;
266
267         namelen = strlcpy(addr.sun_path, sockname, sizeof(addr.sun_path));
268         if (namelen >= sizeof(addr.sun_path)) {
269                 DEBUG(3, ("%s: Socket name too long: %s\n", __func__,
270                           sockname));
271                 close(fd);
272                 return ENAMETOOLONG;
273         }
274
275         salen = sizeof(struct sockaddr_un);
276
277         if (connect(fd, (struct sockaddr *)(void *)&addr, salen) == -1) {
278                 int err = errno;
279                 DEBUG(1, ("connect(%s) failed: %s\n", sockname,
280                           strerror(err)));
281                 close(fd);
282                 return err;
283         }
284
285         *pfd = fd;
286         return 0;
287 }
288
289 static int ctdb_read_packet(int fd, int timeout, TALLOC_CTX *mem_ctx,
290                             struct ctdb_req_header **result)
291 {
292         struct ctdb_req_header *req;
293         uint32_t msglen;
294         ssize_t nread;
295
296         if (timeout != -1) {
297                 struct pollfd pfd = { .fd = fd, .events = POLLIN };
298                 int ret;
299
300                 ret = sys_poll_intr(&pfd, 1, timeout);
301                 if (ret == -1) {
302                         return errno;
303                 }
304                 if (ret == 0) {
305                         return ETIMEDOUT;
306                 }
307                 if (ret != 1) {
308                         return EIO;
309                 }
310         }
311
312         nread = read_data(fd, &msglen, sizeof(msglen));
313         if (nread == -1) {
314                 return errno;
315         }
316         if (nread == 0) {
317                 return EIO;
318         }
319
320         if (msglen < sizeof(struct ctdb_req_header)) {
321                 return EIO;
322         }
323
324         req = talloc_size(mem_ctx, msglen);
325         if (req == NULL) {
326                 return ENOMEM;
327         }
328         talloc_set_name_const(req, "struct ctdb_req_header");
329
330         req->length = msglen;
331
332         nread = read_data(fd, ((char *)req) + sizeof(msglen),
333                           msglen - sizeof(msglen));
334         if (nread == -1) {
335                 TALLOC_FREE(req);
336                 return errno;
337         }
338         if (nread == 0) {
339                 TALLOC_FREE(req);
340                 return EIO;
341         }
342
343         *result = req;
344         return 0;
345 }
346
347 /*
348  * Read a full ctdbd request. If we have a messaging context, defer incoming
349  * messages that might come in between.
350  */
351
352 static int ctdb_read_req(struct ctdbd_connection *conn, uint32_t reqid,
353                          TALLOC_CTX *mem_ctx, struct ctdb_req_header **result)
354 {
355         struct ctdb_req_header *hdr;
356         int ret;
357
358  next_pkt:
359
360         ret = ctdb_read_packet(conn->fd, conn->timeout, mem_ctx, &hdr);
361         if (ret != 0) {
362                 DEBUG(0, ("ctdb_read_packet failed: %s\n", strerror(ret)));
363                 cluster_fatal("ctdbd died\n");
364         }
365
366         DEBUG(11, ("Received ctdb packet\n"));
367         ctdb_packet_dump(hdr);
368
369         if (hdr->operation == CTDB_REQ_MESSAGE) {
370                 struct ctdb_req_message_old *msg = (struct ctdb_req_message_old *)hdr;
371
372                 ret = ctdbd_msg_call_back(conn, msg);
373                 if (ret != 0) {
374                         TALLOC_FREE(hdr);
375                         return ret;
376                 }
377
378                 TALLOC_FREE(hdr);
379                 goto next_pkt;
380         }
381
382         if ((reqid != 0) && (hdr->reqid != reqid)) {
383                 /* we got the wrong reply */
384                 DEBUG(0,("Discarding mismatched ctdb reqid %u should have "
385                          "been %u\n", hdr->reqid, reqid));
386                 TALLOC_FREE(hdr);
387                 goto next_pkt;
388         }
389
390         *result = talloc_move(mem_ctx, &hdr);
391
392         return 0;
393 }
394
395 static int ctdbd_connection_destructor(struct ctdbd_connection *c)
396 {
397         TALLOC_FREE(c->fde);
398         if (c->fd != -1) {
399                 close(c->fd);
400                 c->fd = -1;
401         }
402         return 0;
403 }
404 /*
405  * Get us a ctdbd connection
406  */
407
408 static int ctdbd_init_connection_internal(TALLOC_CTX *mem_ctx,
409                                           const char *sockname, int timeout,
410                                           struct ctdbd_connection *conn)
411 {
412         int ret;
413
414         conn->timeout = timeout;
415         if (conn->timeout == 0) {
416                 conn->timeout = -1;
417         }
418
419         ret = ctdbd_connect(sockname, &conn->fd);
420         if (ret != 0) {
421                 DEBUG(1, ("ctdbd_connect failed: %s\n", strerror(ret)));
422                 return ret;
423         }
424         talloc_set_destructor(conn, ctdbd_connection_destructor);
425
426         ret = get_cluster_vnn(conn, &conn->our_vnn);
427         if (ret != 0) {
428                 DEBUG(10, ("get_cluster_vnn failed: %s\n", strerror(ret)));
429                 return ret;
430         }
431
432         if (!ctdbd_working(conn, conn->our_vnn)) {
433                 DEBUG(2, ("Node is not working, can not connect\n"));
434                 return EIO;
435         }
436
437         generate_random_buffer((unsigned char *)&conn->rand_srvid,
438                                sizeof(conn->rand_srvid));
439
440         ret = register_with_ctdbd(conn, conn->rand_srvid, NULL, NULL);
441         if (ret != 0) {
442                 DEBUG(5, ("Could not register random srvid: %s\n",
443                           strerror(ret)));
444                 return ret;
445         }
446
447         return 0;
448 }
449
450 int ctdbd_init_connection(TALLOC_CTX *mem_ctx,
451                           const char *sockname, int timeout,
452                           struct ctdbd_connection **pconn)
453 {
454         struct ctdbd_connection *conn;
455         int ret;
456
457         if (!(conn = talloc_zero(mem_ctx, struct ctdbd_connection))) {
458                 DEBUG(0, ("talloc failed\n"));
459                 return ENOMEM;
460         }
461
462         ret = ctdbd_init_connection_internal(mem_ctx,
463                                              sockname,
464                                              timeout,
465                                              conn);
466         if (ret != 0) {
467                 DBG_ERR("ctdbd_init_connection_internal failed (%s)\n",
468                         strerror(ret));
469                 goto fail;
470         }
471
472         *pconn = conn;
473         return 0;
474
475  fail:
476         TALLOC_FREE(conn);
477         return ret;
478 }
479
480 int ctdbd_reinit_connection(TALLOC_CTX *mem_ctx,
481                             const char *sockname, int timeout,
482                             struct ctdbd_connection *conn)
483 {
484         int ret;
485
486         ret = ctdbd_connection_destructor(conn);
487         if (ret != 0) {
488                 DBG_ERR("ctdbd_connection_destructor failed\n");
489                 return ret;
490         }
491
492         ret = ctdbd_init_connection_internal(mem_ctx,
493                                              sockname,
494                                              timeout,
495                                              conn);
496         if (ret != 0) {
497                 DBG_ERR("ctdbd_init_connection_internal failed (%s)\n",
498                         strerror(ret));
499                 return ret;
500         }
501
502         return 0;
503 }
504
505 int ctdbd_conn_get_fd(struct ctdbd_connection *conn)
506 {
507         return conn->fd;
508 }
509
510 /*
511  * Packet handler to receive and handle a ctdb message
512  */
513 static int ctdb_handle_message(struct ctdbd_connection *conn,
514                                struct ctdb_req_header *hdr)
515 {
516         struct ctdb_req_message_old *msg;
517
518         if (hdr->operation != CTDB_REQ_MESSAGE) {
519                 DEBUG(0, ("Received async msg of type %u, discarding\n",
520                           hdr->operation));
521                 return EINVAL;
522         }
523
524         msg = (struct ctdb_req_message_old *)hdr;
525
526         ctdbd_msg_call_back(conn, msg);
527
528         return 0;
529 }
530
531 void ctdbd_socket_readable(struct ctdbd_connection *conn)
532 {
533         struct ctdb_req_header *hdr = NULL;
534         int ret;
535
536         ret = ctdb_read_packet(conn->fd, conn->timeout, talloc_tos(), &hdr);
537         if (ret != 0) {
538                 DEBUG(0, ("ctdb_read_packet failed: %s\n", strerror(ret)));
539                 cluster_fatal("ctdbd died\n");
540         }
541
542         ret = ctdb_handle_message(conn, hdr);
543
544         TALLOC_FREE(hdr);
545
546         if (ret != 0) {
547                 DEBUG(10, ("could not handle incoming message: %s\n",
548                            strerror(ret)));
549         }
550 }
551
552 int ctdbd_messaging_send_iov(struct ctdbd_connection *conn,
553                              uint32_t dst_vnn, uint64_t dst_srvid,
554                              const struct iovec *iov, int iovlen)
555 {
556         struct ctdb_req_message_old r;
557         struct iovec iov2[iovlen+1];
558         size_t buflen = iov_buflen(iov, iovlen);
559         ssize_t nwritten;
560
561         r.hdr.length = offsetof(struct ctdb_req_message_old, data) + buflen;
562         r.hdr.ctdb_magic = CTDB_MAGIC;
563         r.hdr.ctdb_version = CTDB_PROTOCOL;
564         r.hdr.generation = 1;
565         r.hdr.operation  = CTDB_REQ_MESSAGE;
566         r.hdr.destnode   = dst_vnn;
567         r.hdr.srcnode    = conn->our_vnn;
568         r.hdr.reqid      = 0;
569         r.srvid          = dst_srvid;
570         r.datalen        = buflen;
571
572         DEBUG(10, ("ctdbd_messaging_send: Sending ctdb packet\n"));
573         ctdb_packet_dump(&r.hdr);
574
575         iov2[0].iov_base = &r;
576         iov2[0].iov_len = offsetof(struct ctdb_req_message_old, data);
577         memcpy(&iov2[1], iov, iovlen * sizeof(struct iovec));
578
579         nwritten = write_data_iov(conn->fd, iov2, iovlen+1);
580         if (nwritten == -1) {
581                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
582                 cluster_fatal("cluster dispatch daemon msg write error\n");
583         }
584
585         return 0;
586 }
587
588 /*
589  * send/recv a generic ctdb control message
590  */
591 static int ctdbd_control(struct ctdbd_connection *conn,
592                          uint32_t vnn, uint32_t opcode,
593                          uint64_t srvid, uint32_t flags,
594                          TDB_DATA data,
595                          TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
596                          int32_t *cstatus)
597 {
598         struct ctdb_req_control_old req;
599         struct ctdb_req_header *hdr;
600         struct ctdb_reply_control_old *reply = NULL;
601         struct iovec iov[2];
602         ssize_t nwritten;
603         int ret;
604
605         ZERO_STRUCT(req);
606         req.hdr.length = offsetof(struct ctdb_req_control_old, data) + data.dsize;
607         req.hdr.ctdb_magic   = CTDB_MAGIC;
608         req.hdr.ctdb_version = CTDB_PROTOCOL;
609         req.hdr.operation    = CTDB_REQ_CONTROL;
610         req.hdr.reqid        = ctdbd_next_reqid(conn);
611         req.hdr.destnode     = vnn;
612         req.opcode           = opcode;
613         req.srvid            = srvid;
614         req.datalen          = data.dsize;
615         req.flags            = flags;
616
617         DBG_DEBUG("Sending ctdb packet reqid=%"PRIu32", vnn=%"PRIu32", "
618                   "opcode=%"PRIu32", srvid=%"PRIu64"\n", req.hdr.reqid,
619                   req.hdr.destnode, req.opcode, req.srvid);
620         ctdb_packet_dump(&req.hdr);
621
622         iov[0].iov_base = &req;
623         iov[0].iov_len = offsetof(struct ctdb_req_control_old, data);
624         iov[1].iov_base = data.dptr;
625         iov[1].iov_len = data.dsize;
626
627         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
628         if (nwritten == -1) {
629                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
630                 cluster_fatal("cluster dispatch daemon msg write error\n");
631         }
632
633         if (flags & CTDB_CTRL_FLAG_NOREPLY) {
634                 if (cstatus) {
635                         *cstatus = 0;
636                 }
637                 return 0;
638         }
639
640         ret = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
641         if (ret != 0) {
642                 DEBUG(10, ("ctdb_read_req failed: %s\n", strerror(ret)));
643                 return ret;
644         }
645
646         if (hdr->operation != CTDB_REPLY_CONTROL) {
647                 DEBUG(0, ("received invalid reply\n"));
648                 TALLOC_FREE(hdr);
649                 return EIO;
650         }
651         reply = (struct ctdb_reply_control_old *)hdr;
652
653         if (outdata) {
654                 if (!(outdata->dptr = (uint8_t *)talloc_memdup(
655                               mem_ctx, reply->data, reply->datalen))) {
656                         TALLOC_FREE(reply);
657                         return ENOMEM;
658                 }
659                 outdata->dsize = reply->datalen;
660         }
661         if (cstatus) {
662                 (*cstatus) = reply->status;
663         }
664
665         TALLOC_FREE(reply);
666         return ret;
667 }
668
669 /*
670  * see if a remote process exists
671  */
672 bool ctdbd_process_exists(struct ctdbd_connection *conn, uint32_t vnn, pid_t pid)
673 {
674         int32_t cstatus = 0;
675         int ret;
676
677         ret = ctdbd_control(conn, vnn, CTDB_CONTROL_PROCESS_EXISTS, 0, 0,
678                             (TDB_DATA) { .dptr = (uint8_t *)&pid,
679                                          .dsize = sizeof(pid) },
680                             NULL, NULL, &cstatus);
681         if (ret != 0) {
682                 return false;
683         }
684         return (cstatus == 0);
685 }
686
687 /*
688  * Get a db path
689  */
690 char *ctdbd_dbpath(struct ctdbd_connection *conn,
691                    TALLOC_CTX *mem_ctx, uint32_t db_id)
692 {
693         int ret;
694         TDB_DATA data;
695         TDB_DATA rdata = {0};
696         int32_t cstatus = 0;
697
698         data.dptr = (uint8_t*)&db_id;
699         data.dsize = sizeof(db_id);
700
701         ret = ctdbd_control_local(conn, CTDB_CONTROL_GETDBPATH, 0, 0, data,
702                                   mem_ctx, &rdata, &cstatus);
703         if ((ret != 0) || cstatus != 0) {
704                 DEBUG(0, (__location__ " ctdb_control for getdbpath failed: %s\n",
705                           strerror(ret)));
706                 return NULL;
707         }
708
709         return (char *)rdata.dptr;
710 }
711
712 /*
713  * attach to a ctdb database
714  */
715 int ctdbd_db_attach(struct ctdbd_connection *conn,
716                     const char *name, uint32_t *db_id, int tdb_flags)
717 {
718         int ret;
719         TDB_DATA data;
720         int32_t cstatus;
721         bool persistent = (tdb_flags & TDB_CLEAR_IF_FIRST) == 0;
722
723         data = string_term_tdb_data(name);
724
725         ret = ctdbd_control_local(conn,
726                                   persistent
727                                   ? CTDB_CONTROL_DB_ATTACH_PERSISTENT
728                                   : CTDB_CONTROL_DB_ATTACH,
729                                   tdb_flags, 0, data, NULL, &data, &cstatus);
730         if (ret != 0) {
731                 DEBUG(0, (__location__ " ctdb_control for db_attach "
732                           "failed: %s\n", strerror(ret)));
733                 return ret;
734         }
735
736         if (cstatus != 0 || data.dsize != sizeof(uint32_t)) {
737                 DEBUG(0,(__location__ " ctdb_control for db_attach failed\n"));
738                 return EIO;
739         }
740
741         *db_id = *(uint32_t *)data.dptr;
742         talloc_free(data.dptr);
743
744         if (!(tdb_flags & TDB_SEQNUM)) {
745                 return 0;
746         }
747
748         data.dptr = (uint8_t *)db_id;
749         data.dsize = sizeof(*db_id);
750
751         ret = ctdbd_control_local(conn, CTDB_CONTROL_ENABLE_SEQNUM, 0, 0, data,
752                                   NULL, NULL, &cstatus);
753         if ((ret != 0) || cstatus != 0) {
754                 DEBUG(0, (__location__ " ctdb_control for enable seqnum "
755                           "failed: %s\n", strerror(ret)));
756                 return (ret == 0) ? EIO : ret;
757         }
758
759         return 0;
760 }
761
762 /*
763  * force the migration of a record to this node
764  */
765 int ctdbd_migrate(struct ctdbd_connection *conn, uint32_t db_id, TDB_DATA key)
766 {
767         struct ctdb_req_call_old req;
768         struct ctdb_req_header *hdr;
769         struct iovec iov[2];
770         ssize_t nwritten;
771         int ret;
772
773         ZERO_STRUCT(req);
774
775         req.hdr.length = offsetof(struct ctdb_req_call_old, data) + key.dsize;
776         req.hdr.ctdb_magic   = CTDB_MAGIC;
777         req.hdr.ctdb_version = CTDB_PROTOCOL;
778         req.hdr.operation    = CTDB_REQ_CALL;
779         req.hdr.reqid        = ctdbd_next_reqid(conn);
780         req.flags            = CTDB_IMMEDIATE_MIGRATION;
781         req.callid           = CTDB_NULL_FUNC;
782         req.db_id            = db_id;
783         req.keylen           = key.dsize;
784
785         DEBUG(10, ("ctdbd_migrate: Sending ctdb packet\n"));
786         ctdb_packet_dump(&req.hdr);
787
788         iov[0].iov_base = &req;
789         iov[0].iov_len = offsetof(struct ctdb_req_call_old, data);
790         iov[1].iov_base = key.dptr;
791         iov[1].iov_len = key.dsize;
792
793         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
794         if (nwritten == -1) {
795                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
796                 cluster_fatal("cluster dispatch daemon msg write error\n");
797         }
798
799         ret = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
800         if (ret != 0) {
801                 DEBUG(10, ("ctdb_read_req failed: %s\n", strerror(ret)));
802                 goto fail;
803         }
804
805         if (hdr->operation != CTDB_REPLY_CALL) {
806                 if (hdr->operation == CTDB_REPLY_ERROR) {
807                         DBG_ERR("received error from ctdb\n");
808                 } else {
809                         DBG_ERR("received invalid reply\n");
810                 }
811                 ret = EIO;
812                 goto fail;
813         }
814
815  fail:
816
817         TALLOC_FREE(hdr);
818         return ret;
819 }
820
821 /*
822  * Fetch a record and parse it
823  */
824 int ctdbd_parse(struct ctdbd_connection *conn, uint32_t db_id,
825                 TDB_DATA key, bool local_copy,
826                 void (*parser)(TDB_DATA key, TDB_DATA data,
827                                void *private_data),
828                 void *private_data)
829 {
830         struct ctdb_req_call_old req;
831         struct ctdb_req_header *hdr = NULL;
832         struct ctdb_reply_call_old *reply;
833         struct iovec iov[2];
834         ssize_t nwritten;
835         uint32_t flags;
836         int ret;
837
838         flags = local_copy ? CTDB_WANT_READONLY : 0;
839
840         ZERO_STRUCT(req);
841
842         req.hdr.length = offsetof(struct ctdb_req_call_old, data) + key.dsize;
843         req.hdr.ctdb_magic   = CTDB_MAGIC;
844         req.hdr.ctdb_version = CTDB_PROTOCOL;
845         req.hdr.operation    = CTDB_REQ_CALL;
846         req.hdr.reqid        = ctdbd_next_reqid(conn);
847         req.flags            = flags;
848         req.callid           = CTDB_FETCH_FUNC;
849         req.db_id            = db_id;
850         req.keylen           = key.dsize;
851
852         iov[0].iov_base = &req;
853         iov[0].iov_len = offsetof(struct ctdb_req_call_old, data);
854         iov[1].iov_base = key.dptr;
855         iov[1].iov_len = key.dsize;
856
857         nwritten = write_data_iov(conn->fd, iov, ARRAY_SIZE(iov));
858         if (nwritten == -1) {
859                 DEBUG(3, ("write_data_iov failed: %s\n", strerror(errno)));
860                 cluster_fatal("cluster dispatch daemon msg write error\n");
861         }
862
863         ret = ctdb_read_req(conn, req.hdr.reqid, NULL, &hdr);
864         if (ret != 0) {
865                 DEBUG(10, ("ctdb_read_req failed: %s\n", strerror(ret)));
866                 goto fail;
867         }
868
869         if ((hdr == NULL) || (hdr->operation != CTDB_REPLY_CALL)) {
870                 DEBUG(0, ("received invalid reply\n"));
871                 ret = EIO;
872                 goto fail;
873         }
874         reply = (struct ctdb_reply_call_old *)hdr;
875
876         if (reply->datalen == 0) {
877                 /*
878                  * Treat an empty record as non-existing
879                  */
880                 ret = ENOENT;
881                 goto fail;
882         }
883
884         parser(key, make_tdb_data(&reply->data[0], reply->datalen),
885                private_data);
886
887         ret = 0;
888  fail:
889         TALLOC_FREE(hdr);
890         return ret;
891 }
892
893 /*
894   Traverse a ctdb database. "conn" must be an otherwise unused
895   ctdb_connection where no other messages but the traverse ones are
896   expected.
897 */
898
899 int ctdbd_traverse(struct ctdbd_connection *conn, uint32_t db_id,
900                         void (*fn)(TDB_DATA key, TDB_DATA data,
901                                    void *private_data),
902                         void *private_data)
903 {
904         int ret;
905         TDB_DATA key, data;
906         struct ctdb_traverse_start t;
907         int32_t cstatus;
908
909         t.db_id = db_id;
910         t.srvid = conn->rand_srvid;
911         t.reqid = ctdbd_next_reqid(conn);
912
913         data.dptr = (uint8_t *)&t;
914         data.dsize = sizeof(t);
915
916         ret = ctdbd_control_local(conn, CTDB_CONTROL_TRAVERSE_START,
917                                   conn->rand_srvid,
918                                   0, data, NULL, NULL, &cstatus);
919
920         if ((ret != 0) || (cstatus != 0)) {
921                 DEBUG(0,("ctdbd_control failed: %s, %d\n", strerror(ret),
922                          cstatus));
923
924                 if (ret == 0) {
925                         /*
926                          * We need a mapping here
927                          */
928                         ret = EIO;
929                 }
930                 return ret;
931         }
932
933         while (true) {
934                 struct ctdb_req_header *hdr = NULL;
935                 struct ctdb_req_message_old *m;
936                 struct ctdb_rec_data_old *d;
937
938                 ret = ctdb_read_packet(conn->fd, conn->timeout, conn, &hdr);
939                 if (ret != 0) {
940                         DEBUG(0, ("ctdb_read_packet failed: %s\n",
941                                   strerror(ret)));
942                         cluster_fatal("ctdbd died\n");
943                 }
944
945                 if (hdr->operation != CTDB_REQ_MESSAGE) {
946                         DEBUG(0, ("Got operation %u, expected a message\n",
947                                   (unsigned)hdr->operation));
948                         return EIO;
949                 }
950
951                 m = (struct ctdb_req_message_old *)hdr;
952                 d = (struct ctdb_rec_data_old *)&m->data[0];
953                 if (m->datalen < sizeof(uint32_t) || m->datalen != d->length) {
954                         DEBUG(0, ("Got invalid traverse data of length %d\n",
955                                   (int)m->datalen));
956                         return EIO;
957                 }
958
959                 key.dsize = d->keylen;
960                 key.dptr  = &d->data[0];
961                 data.dsize = d->datalen;
962                 data.dptr = &d->data[d->keylen];
963
964                 if (key.dsize == 0 && data.dsize == 0) {
965                         /* end of traverse */
966                         return 0;
967                 }
968
969                 if (data.dsize < sizeof(struct ctdb_ltdb_header)) {
970                         DEBUG(0, ("Got invalid ltdb header length %d\n",
971                                   (int)data.dsize));
972                         return EIO;
973                 }
974                 data.dsize -= sizeof(struct ctdb_ltdb_header);
975                 data.dptr += sizeof(struct ctdb_ltdb_header);
976
977                 if (fn != NULL) {
978                         fn(key, data, private_data);
979                 }
980         }
981         return 0;
982 }
983
984 /*
985    This is used to canonicalize a ctdb_sock_addr structure.
986 */
987 static void smbd_ctdb_canonicalize_ip(const struct sockaddr_storage *in,
988                                       struct sockaddr_storage *out)
989 {
990         memcpy(out, in, sizeof (*out));
991
992 #ifdef HAVE_IPV6
993         if (in->ss_family == AF_INET6) {
994                 const char prefix[12] = { 0,0,0,0,0,0,0,0,0,0,0xff,0xff };
995                 const struct sockaddr_in6 *in6 =
996                         (const struct sockaddr_in6 *)in;
997                 struct sockaddr_in *out4 = (struct sockaddr_in *)out;
998                 if (memcmp(&in6->sin6_addr, prefix, 12) == 0) {
999                         memset(out, 0, sizeof(*out));
1000 #ifdef HAVE_SOCK_SIN_LEN
1001                         out4->sin_len = sizeof(*out);
1002 #endif
1003                         out4->sin_family = AF_INET;
1004                         out4->sin_port   = in6->sin6_port;
1005                         memcpy(&out4->sin_addr, &in6->sin6_addr.s6_addr[12], 4);
1006                 }
1007         }
1008 #endif
1009 }
1010
1011 /*
1012  * Register us as a server for a particular tcp connection
1013  */
1014
1015 int ctdbd_register_ips(struct ctdbd_connection *conn,
1016                        const struct sockaddr_storage *_server,
1017                        const struct sockaddr_storage *_client,
1018                        int (*cb)(uint32_t src_vnn, uint32_t dst_vnn,
1019                                  uint64_t dst_srvid,
1020                                  const uint8_t *msg, size_t msglen,
1021                                  void *private_data),
1022                        void *private_data)
1023 {
1024         struct ctdb_connection p;
1025         TDB_DATA data = { .dptr = (uint8_t *)&p, .dsize = sizeof(p) };
1026         int ret;
1027         struct sockaddr_storage client;
1028         struct sockaddr_storage server;
1029
1030         /*
1031          * Only one connection so far
1032          */
1033
1034         smbd_ctdb_canonicalize_ip(_client, &client);
1035         smbd_ctdb_canonicalize_ip(_server, &server);
1036
1037         switch (client.ss_family) {
1038         case AF_INET:
1039                 memcpy(&p.dst.ip, &server, sizeof(p.dst.ip));
1040                 memcpy(&p.src.ip, &client, sizeof(p.src.ip));
1041                 break;
1042         case AF_INET6:
1043                 memcpy(&p.dst.ip6, &server, sizeof(p.dst.ip6));
1044                 memcpy(&p.src.ip6, &client, sizeof(p.src.ip6));
1045                 break;
1046         default:
1047                 return EIO;
1048         }
1049
1050         /*
1051          * We want to be told about IP releases
1052          */
1053
1054         ret = register_with_ctdbd(conn, CTDB_SRVID_RELEASE_IP,
1055                                   cb, private_data);
1056         if (ret != 0) {
1057                 return ret;
1058         }
1059
1060         /*
1061          * inform ctdb of our tcp connection, so if IP takeover happens ctdb
1062          * can send an extra ack to trigger a reset for our client, so it
1063          * immediately reconnects
1064          */
1065         ret = ctdbd_control(conn, CTDB_CURRENT_NODE,
1066                             CTDB_CONTROL_TCP_CLIENT, 0,
1067                             CTDB_CTRL_FLAG_NOREPLY, data, NULL, NULL,
1068                             NULL);
1069         if (ret != 0) {
1070                 return ret;
1071         }
1072         return 0;
1073 }
1074
1075 /*
1076   call a control on the local node
1077  */
1078 int ctdbd_control_local(struct ctdbd_connection *conn, uint32_t opcode,
1079                         uint64_t srvid, uint32_t flags, TDB_DATA data,
1080                         TALLOC_CTX *mem_ctx, TDB_DATA *outdata,
1081                         int32_t *cstatus)
1082 {
1083         return ctdbd_control(conn, CTDB_CURRENT_NODE, opcode, srvid, flags, data,
1084                              mem_ctx, outdata, cstatus);
1085 }
1086
1087 int ctdb_watch_us(struct ctdbd_connection *conn)
1088 {
1089         struct ctdb_notify_data_old reg_data;
1090         size_t struct_len;
1091         int ret;
1092         int32_t cstatus;
1093
1094         reg_data.srvid = CTDB_SRVID_SAMBA_NOTIFY;
1095         reg_data.len = 1;
1096         reg_data.notify_data[0] = 0;
1097
1098         struct_len = offsetof(struct ctdb_notify_data_old,
1099                               notify_data) + reg_data.len;
1100
1101         ret = ctdbd_control_local(
1102                 conn, CTDB_CONTROL_REGISTER_NOTIFY, conn->rand_srvid, 0,
1103                 make_tdb_data((uint8_t *)&reg_data, struct_len),
1104                 NULL, NULL, &cstatus);
1105         if (ret != 0) {
1106                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1107                           strerror(ret)));
1108         }
1109         return ret;
1110 }
1111
1112 int ctdb_unwatch(struct ctdbd_connection *conn)
1113 {
1114         uint64_t srvid = CTDB_SRVID_SAMBA_NOTIFY;
1115         int ret;
1116         int32_t cstatus;
1117
1118         ret = ctdbd_control_local(
1119                 conn, CTDB_CONTROL_DEREGISTER_NOTIFY, conn->rand_srvid, 0,
1120                 make_tdb_data((uint8_t *)&srvid, sizeof(srvid)),
1121                 NULL, NULL, &cstatus);
1122         if (ret != 0) {
1123                 DEBUG(1, ("ctdbd_control_local failed: %s\n",
1124                           strerror(ret)));
1125         }
1126         return ret;
1127 }
1128
1129 int ctdbd_probe(const char *sockname, int timeout)
1130 {
1131         /*
1132          * Do a very early check if ctdbd is around to avoid an abort and core
1133          * later
1134          */
1135         struct ctdbd_connection *conn = NULL;
1136         int ret;
1137
1138         ret = ctdbd_init_connection(talloc_tos(), sockname, timeout,
1139                                     &conn);
1140
1141         /*
1142          * We only care if we can connect.
1143          */
1144         TALLOC_FREE(conn);
1145
1146         return ret;
1147 }