Use single copy of tdb in both samba3 and samba4.
[ira/wip.git] / source4 / lib / messaging / messaging.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Samba internal messaging functions
5
6    Copyright (C) Andrew Tridgell 2004
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "lib/events/events.h"
24 #include "system/filesys.h"
25 #include "messaging/messaging.h"
26 #include "lib/util/dlinklist.h"
27 #include "lib/socket/socket.h"
28 #include "librpc/gen_ndr/ndr_irpc.h"
29 #include "lib/messaging/irpc.h"
30 #include "tdb_wrap.h"
31 #include "lib/util/unix_privs.h"
32 #include "librpc/rpc/dcerpc.h"
33 #include "../tdb/include/tdb.h"
34 #include "lib/util/util_tdb.h"
35 #include "cluster/cluster.h"
36 #include "param/param.h"
37
38 /* change the message version with any incompatible changes in the protocol */
39 #define MESSAGING_VERSION 1
40
41 struct messaging_context {
42         struct server_id server_id;
43         struct socket_context *sock;
44         const char *base_path;
45         const char *path;
46         struct dispatch_fn **dispatch;
47         uint32_t num_types;
48         struct idr_context *dispatch_tree;
49         struct messaging_rec *pending;
50         struct messaging_rec *retry_queue;
51         struct smb_iconv_convenience *iconv_convenience;
52         struct irpc_list *irpc;
53         struct idr_context *idr;
54         const char **names;
55         struct timeval start_time;
56         struct timed_event *retry_te;
57         struct {
58                 struct event_context *ev;
59                 struct fd_event *fde;
60         } event;
61 };
62
63 /* we have a linked list of dispatch handlers for each msg_type that
64    this messaging server can deal with */
65 struct dispatch_fn {
66         struct dispatch_fn *next, *prev;
67         uint32_t msg_type;
68         void *private;
69         msg_callback_t fn;
70 };
71
72 /* an individual message */
73 struct messaging_rec {
74         struct messaging_rec *next, *prev;
75         struct messaging_context *msg;
76         const char *path;
77
78         struct messaging_header {
79                 uint32_t version;
80                 uint32_t msg_type;
81                 struct server_id from;
82                 struct server_id to;
83                 uint32_t length;
84         } *header;
85
86         DATA_BLOB packet;
87         uint32_t retries;
88 };
89
90
91 static void irpc_handler(struct messaging_context *, void *, 
92                          uint32_t, struct server_id, DATA_BLOB *);
93
94
95 /*
96  A useful function for testing the message system.
97 */
98 static void ping_message(struct messaging_context *msg, void *private, 
99                          uint32_t msg_type, struct server_id src, DATA_BLOB *data)
100 {
101         DEBUG(1,("INFO: Received PING message from server %u.%u [%.*s]\n",
102                  (uint_t)src.node, (uint_t)src.id, (int)data->length, 
103                  data->data?(const char *)data->data:""));
104         messaging_send(msg, src, MSG_PONG, data);
105 }
106
107 /*
108   return uptime of messaging server via irpc
109 */
110 static NTSTATUS irpc_uptime(struct irpc_message *msg, 
111                             struct irpc_uptime *r)
112 {
113         struct messaging_context *ctx = talloc_get_type(msg->private, struct messaging_context);
114         *r->out.start_time = timeval_to_nttime(&ctx->start_time);
115         return NT_STATUS_OK;
116 }
117
118 /* 
119    return the path to a messaging socket
120 */
121 static char *messaging_path(struct messaging_context *msg, struct server_id server_id)
122 {
123         return talloc_asprintf(msg, "%s/msg.%s", msg->base_path, 
124                                cluster_id_string(msg, server_id));
125 }
126
127 /*
128   dispatch a fully received message
129
130   note that this deliberately can match more than one message handler
131   per message. That allows a single messasging context to register
132   (for example) a debug handler for more than one piece of code
133 */
134 static void messaging_dispatch(struct messaging_context *msg, struct messaging_rec *rec)
135 {
136         struct dispatch_fn *d, *next;
137
138         /* temporary IDs use an idtree, the rest use a array of pointers */
139         if (rec->header->msg_type >= MSG_TMP_BASE) {
140                 d = (struct dispatch_fn *)idr_find(msg->dispatch_tree, 
141                                                    rec->header->msg_type);
142         } else if (rec->header->msg_type < msg->num_types) {
143                 d = msg->dispatch[rec->header->msg_type];
144         } else {
145                 d = NULL;
146         }
147
148         for (; d; d = next) {
149                 DATA_BLOB data;
150                 next = d->next;
151                 data.data = rec->packet.data + sizeof(*rec->header);
152                 data.length = rec->header->length;
153                 d->fn(msg, d->private, d->msg_type, rec->header->from, &data);
154         }
155         rec->header->length = 0;
156 }
157
158 /*
159   handler for messages that arrive from other nodes in the cluster
160 */
161 static void cluster_message_handler(struct messaging_context *msg, DATA_BLOB packet)
162 {
163         struct messaging_rec *rec;
164
165         rec = talloc(msg, struct messaging_rec);
166         if (rec == NULL) {
167                 smb_panic("Unable to allocate messaging_rec");
168         }
169
170         rec->msg           = msg;
171         rec->path          = msg->path;
172         rec->header        = (struct messaging_header *)packet.data;
173         rec->packet        = packet;
174         rec->retries       = 0;
175
176         if (packet.length != sizeof(*rec->header) + rec->header->length) {
177                 DEBUG(0,("messaging: bad message header size %d should be %d\n", 
178                          rec->header->length, (int)(packet.length - sizeof(*rec->header))));
179                 talloc_free(rec);
180                 return;
181         }
182
183         messaging_dispatch(msg, rec);
184         talloc_free(rec);
185 }
186
187
188
189 /*
190   try to send the message
191 */
192 static NTSTATUS try_send(struct messaging_rec *rec)
193 {
194         struct messaging_context *msg = rec->msg;
195         size_t nsent;
196         void *priv;
197         NTSTATUS status;
198         struct socket_address *path;
199
200         /* rec->path is the path of the *other* socket, where we want
201          * this to end up */
202         path = socket_address_from_strings(msg, msg->sock->backend_name, 
203                                            rec->path, 0);
204         if (!path) {
205                 return NT_STATUS_NO_MEMORY;
206         }
207
208         /* we send with privileges so messages work from any context */
209         priv = root_privileges();
210         status = socket_sendto(msg->sock, &rec->packet, &nsent, path);
211         talloc_free(path);
212         talloc_free(priv);
213
214         return status;
215 }
216
217 /*
218   retry backed off messages
219 */
220 static void msg_retry_timer(struct event_context *ev, struct timed_event *te, 
221                             struct timeval t, void *private)
222 {
223         struct messaging_context *msg = talloc_get_type(private, 
224                                                         struct messaging_context);
225         msg->retry_te = NULL;
226
227         /* put the messages back on the main queue */
228         while (msg->retry_queue) {
229                 struct messaging_rec *rec = msg->retry_queue;
230                 DLIST_REMOVE(msg->retry_queue, rec);
231                 DLIST_ADD_END(msg->pending, rec, struct messaging_rec *);
232         }
233
234         EVENT_FD_WRITEABLE(msg->event.fde);     
235 }
236
237 /*
238   handle a socket write event
239 */
240 static void messaging_send_handler(struct messaging_context *msg)
241 {
242         while (msg->pending) {
243                 struct messaging_rec *rec = msg->pending;
244                 NTSTATUS status;
245                 status = try_send(rec);
246                 if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
247                         rec->retries++;
248                         if (rec->retries > 3) {
249                                 /* we're getting continuous write errors -
250                                    backoff this record */
251                                 DLIST_REMOVE(msg->pending, rec);
252                                 DLIST_ADD_END(msg->retry_queue, rec, 
253                                               struct messaging_rec *);
254                                 if (msg->retry_te == NULL) {
255                                         msg->retry_te = 
256                                                 event_add_timed(msg->event.ev, msg, 
257                                                                 timeval_current_ofs(1, 0), 
258                                                                 msg_retry_timer, msg);
259                                 }
260                         }
261                         break;
262                 }
263                 rec->retries = 0;
264                 if (!NT_STATUS_IS_OK(status)) {
265                         DEBUG(1,("messaging: Lost message from %s to %s of type %u - %s\n", 
266                                  cluster_id_string(debug_ctx(), rec->header->from), 
267                                  cluster_id_string(debug_ctx(), rec->header->to), 
268                                  rec->header->msg_type, 
269                                  nt_errstr(status)));
270                 }
271                 DLIST_REMOVE(msg->pending, rec);
272                 talloc_free(rec);
273         }
274         if (msg->pending == NULL) {
275                 EVENT_FD_NOT_WRITEABLE(msg->event.fde);
276         }
277 }
278
279 /*
280   handle a new incoming packet
281 */
282 static void messaging_recv_handler(struct messaging_context *msg)
283 {
284         struct messaging_rec *rec;
285         NTSTATUS status;
286         DATA_BLOB packet;
287         size_t msize;
288
289         /* see how many bytes are in the next packet */
290         status = socket_pending(msg->sock, &msize);
291         if (!NT_STATUS_IS_OK(status)) {
292                 DEBUG(0,("socket_pending failed in messaging - %s\n", 
293                          nt_errstr(status)));
294                 return;
295         }
296         
297         packet = data_blob_talloc(msg, NULL, msize);
298         if (packet.data == NULL) {
299                 /* assume this is temporary and retry */
300                 return;
301         }
302             
303         status = socket_recv(msg->sock, packet.data, msize, &msize);
304         if (!NT_STATUS_IS_OK(status)) {
305                 data_blob_free(&packet);
306                 return;
307         }
308
309         if (msize < sizeof(*rec->header)) {
310                 DEBUG(0,("messaging: bad message of size %d\n", (int)msize));
311                 data_blob_free(&packet);
312                 return;
313         }
314
315         rec = talloc(msg, struct messaging_rec);
316         if (rec == NULL) {
317                 smb_panic("Unable to allocate messaging_rec");
318         }
319
320         talloc_steal(rec, packet.data);
321         rec->msg           = msg;
322         rec->path          = msg->path;
323         rec->header        = (struct messaging_header *)packet.data;
324         rec->packet        = packet;
325         rec->retries       = 0;
326
327         if (msize != sizeof(*rec->header) + rec->header->length) {
328                 DEBUG(0,("messaging: bad message header size %d should be %d\n", 
329                          rec->header->length, (int)(msize - sizeof(*rec->header))));
330                 talloc_free(rec);
331                 return;
332         }
333
334         messaging_dispatch(msg, rec);
335         talloc_free(rec);
336 }
337
338
339 /*
340   handle a socket event
341 */
342 static void messaging_handler(struct event_context *ev, struct fd_event *fde, 
343                               uint16_t flags, void *private)
344 {
345         struct messaging_context *msg = talloc_get_type(private, 
346                                                         struct messaging_context);
347         if (flags & EVENT_FD_WRITE) {
348                 messaging_send_handler(msg);
349         }
350         if (flags & EVENT_FD_READ) {
351                 messaging_recv_handler(msg);
352         }
353 }
354
355
356 /*
357   Register a dispatch function for a particular message type.
358 */
359 NTSTATUS messaging_register(struct messaging_context *msg, void *private,
360                             uint32_t msg_type, msg_callback_t fn)
361 {
362         struct dispatch_fn *d;
363
364         /* possibly expand dispatch array */
365         if (msg_type >= msg->num_types) {
366                 struct dispatch_fn **dp;
367                 int i;
368                 dp = talloc_realloc(msg, msg->dispatch, struct dispatch_fn *, msg_type+1);
369                 NT_STATUS_HAVE_NO_MEMORY(dp);
370                 msg->dispatch = dp;
371                 for (i=msg->num_types;i<=msg_type;i++) {
372                         msg->dispatch[i] = NULL;
373                 }
374                 msg->num_types = msg_type+1;
375         }
376
377         d = talloc_zero(msg->dispatch, struct dispatch_fn);
378         NT_STATUS_HAVE_NO_MEMORY(d);
379         d->msg_type = msg_type;
380         d->private = private;
381         d->fn = fn;
382
383         DLIST_ADD(msg->dispatch[msg_type], d);
384
385         return NT_STATUS_OK;
386 }
387
388 /*
389   register a temporary message handler. The msg_type is allocated
390   above MSG_TMP_BASE
391 */
392 NTSTATUS messaging_register_tmp(struct messaging_context *msg, void *private,
393                                 msg_callback_t fn, uint32_t *msg_type)
394 {
395         struct dispatch_fn *d;
396         int id;
397
398         d = talloc_zero(msg->dispatch, struct dispatch_fn);
399         NT_STATUS_HAVE_NO_MEMORY(d);
400         d->private = private;
401         d->fn = fn;
402
403         id = idr_get_new_above(msg->dispatch_tree, d, MSG_TMP_BASE, UINT16_MAX);
404         if (id == -1) {
405                 talloc_free(d);
406                 return NT_STATUS_TOO_MANY_CONTEXT_IDS;
407         }
408
409         d->msg_type = (uint32_t)id;
410         (*msg_type) = d->msg_type;
411
412         return NT_STATUS_OK;
413 }
414
415 /*
416   De-register the function for a particular message type.
417 */
418 void messaging_deregister(struct messaging_context *msg, uint32_t msg_type, void *private)
419 {
420         struct dispatch_fn *d, *next;
421
422         if (msg_type >= msg->num_types) {
423                 d = (struct dispatch_fn *)idr_find(msg->dispatch_tree, 
424                                                    msg_type);
425                 if (!d) return;
426                 idr_remove(msg->dispatch_tree, msg_type);
427                 talloc_free(d);
428                 return;
429         }
430
431         for (d = msg->dispatch[msg_type]; d; d = next) {
432                 next = d->next;
433                 if (d->private == private) {
434                         DLIST_REMOVE(msg->dispatch[msg_type], d);
435                         talloc_free(d);
436                 }
437         }
438 }
439
440 /*
441   Send a message to a particular server
442 */
443 NTSTATUS messaging_send(struct messaging_context *msg, struct server_id server, 
444                         uint32_t msg_type, DATA_BLOB *data)
445 {
446         struct messaging_rec *rec;
447         NTSTATUS status;
448         size_t dlength = data?data->length:0;
449
450         rec = talloc(msg, struct messaging_rec);
451         if (rec == NULL) {
452                 return NT_STATUS_NO_MEMORY;
453         }
454
455         rec->packet = data_blob_talloc(rec, NULL, sizeof(*rec->header) + dlength);
456         if (rec->packet.data == NULL) {
457                 talloc_free(rec);
458                 return NT_STATUS_NO_MEMORY;
459         }
460
461         rec->retries       = 0;
462         rec->msg              = msg;
463         rec->header           = (struct messaging_header *)rec->packet.data;
464         /* zero padding */
465         ZERO_STRUCTP(rec->header);
466         rec->header->version  = MESSAGING_VERSION;
467         rec->header->msg_type = msg_type;
468         rec->header->from     = msg->server_id;
469         rec->header->to       = server;
470         rec->header->length   = dlength;
471         if (dlength != 0) {
472                 memcpy(rec->packet.data + sizeof(*rec->header), 
473                        data->data, dlength);
474         }
475
476         if (!cluster_node_equal(&msg->server_id, &server)) {
477                 /* the destination is on another node - dispatch via
478                    the cluster layer */
479                 status = cluster_message_send(server, &rec->packet);
480                 talloc_free(rec);
481                 return status;
482         }
483
484         rec->path = messaging_path(msg, server);
485         talloc_steal(rec, rec->path);
486
487         if (msg->pending != NULL) {
488                 status = STATUS_MORE_ENTRIES;
489         } else {
490                 status = try_send(rec);
491         }
492
493         if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
494                 if (msg->pending == NULL) {
495                         EVENT_FD_WRITEABLE(msg->event.fde);
496                 }
497                 DLIST_ADD_END(msg->pending, rec, struct messaging_rec *);
498                 return NT_STATUS_OK;
499         }
500
501         talloc_free(rec);
502
503         return status;
504 }
505
506 /*
507   Send a message to a particular server, with the message containing a single pointer
508 */
509 NTSTATUS messaging_send_ptr(struct messaging_context *msg, struct server_id server, 
510                             uint32_t msg_type, void *ptr)
511 {
512         DATA_BLOB blob;
513
514         blob.data = (uint8_t *)&ptr;
515         blob.length = sizeof(void *);
516
517         return messaging_send(msg, server, msg_type, &blob);
518 }
519
520
521 /*
522   destroy the messaging context
523 */
524 static int messaging_destructor(struct messaging_context *msg)
525 {
526         unlink(msg->path);
527         while (msg->names && msg->names[0]) {
528                 irpc_remove_name(msg, msg->names[0]);
529         }
530         return 0;
531 }
532
533 /*
534   create the listening socket and setup the dispatcher
535 */
536 struct messaging_context *messaging_init(TALLOC_CTX *mem_ctx, 
537                                          const char *dir,
538                                          struct server_id server_id, 
539                                          struct smb_iconv_convenience *iconv_convenience,
540                                          struct event_context *ev)
541 {
542         struct messaging_context *msg;
543         NTSTATUS status;
544         struct socket_address *path;
545
546         if (ev == NULL) {
547                 return NULL;
548         }
549
550         msg = talloc_zero(mem_ctx, struct messaging_context);
551         if (msg == NULL) {
552                 return NULL;
553         }
554
555         /* setup a handler for messages from other cluster nodes, if appropriate */
556         status = cluster_message_init(msg, server_id, cluster_message_handler);
557         if (!NT_STATUS_IS_OK(status)) {
558                 talloc_free(msg);
559                 return NULL;
560         }
561
562         /* create the messaging directory if needed */
563         mkdir(dir, 0700);
564
565         msg->base_path     = talloc_reference(msg, dir);
566         msg->path          = messaging_path(msg, server_id);
567         msg->server_id     = server_id;
568         msg->iconv_convenience = iconv_convenience;
569         msg->idr           = idr_init(msg);
570         msg->dispatch_tree = idr_init(msg);
571         msg->start_time    = timeval_current();
572
573         status = socket_create("unix", SOCKET_TYPE_DGRAM, &msg->sock, 0);
574         if (!NT_STATUS_IS_OK(status)) {
575                 talloc_free(msg);
576                 return NULL;
577         }
578
579         /* by stealing here we ensure that the socket is cleaned up (and even 
580            deleted) on exit */
581         talloc_steal(msg, msg->sock);
582
583         path = socket_address_from_strings(msg, msg->sock->backend_name, 
584                                            msg->path, 0);
585         if (!path) {
586                 talloc_free(msg);
587                 return NULL;
588         }
589
590         status = socket_listen(msg->sock, path, 50, 0);
591         if (!NT_STATUS_IS_OK(status)) {
592                 DEBUG(0,("Unable to setup messaging listener for '%s':%s\n", msg->path, nt_errstr(status)));
593                 talloc_free(msg);
594                 return NULL;
595         }
596
597         /* it needs to be non blocking for sends */
598         set_blocking(socket_get_fd(msg->sock), false);
599
600         msg->event.ev   = talloc_reference(msg, ev);
601         msg->event.fde  = event_add_fd(ev, msg, socket_get_fd(msg->sock), 
602                                        EVENT_FD_READ, messaging_handler, msg);
603
604         talloc_set_destructor(msg, messaging_destructor);
605         
606         messaging_register(msg, NULL, MSG_PING, ping_message);
607         messaging_register(msg, NULL, MSG_IRPC, irpc_handler);
608         IRPC_REGISTER(msg, irpc, IRPC_UPTIME, irpc_uptime, msg);
609
610         return msg;
611 }
612
613 /* 
614    A hack, for the short term until we get 'client only' messaging in place 
615 */
616 struct messaging_context *messaging_client_init(TALLOC_CTX *mem_ctx, 
617                                                 const char *dir,
618                                                 struct smb_iconv_convenience *iconv_convenience,
619                                                 struct event_context *ev)
620 {
621         struct server_id id;
622         ZERO_STRUCT(id);
623         id.id = random() % 0x10000000;
624         return messaging_init(mem_ctx, dir, id, iconv_convenience, ev);
625 }
626 /*
627   a list of registered irpc server functions
628 */
629 struct irpc_list {
630         struct irpc_list *next, *prev;
631         struct GUID uuid;
632         const struct ndr_interface_table *table;
633         int callnum;
634         irpc_function_t fn;
635         void *private;
636 };
637
638
639 /*
640   register a irpc server function
641 */
642 NTSTATUS irpc_register(struct messaging_context *msg_ctx, 
643                        const struct ndr_interface_table *table, 
644                        int callnum, irpc_function_t fn, void *private)
645 {
646         struct irpc_list *irpc;
647
648         /* override an existing handler, if any */
649         for (irpc=msg_ctx->irpc; irpc; irpc=irpc->next) {
650                 if (irpc->table == table && irpc->callnum == callnum) {
651                         break;
652                 }
653         }
654         if (irpc == NULL) {
655                 irpc = talloc(msg_ctx, struct irpc_list);
656                 NT_STATUS_HAVE_NO_MEMORY(irpc);
657                 DLIST_ADD(msg_ctx->irpc, irpc);
658         }
659
660         irpc->table   = table;
661         irpc->callnum = callnum;
662         irpc->fn      = fn;
663         irpc->private = private;
664         irpc->uuid = irpc->table->syntax_id.uuid;
665
666         return NT_STATUS_OK;
667 }
668
669
670 /*
671   handle an incoming irpc reply message
672 */
673 static void irpc_handler_reply(struct messaging_context *msg_ctx, struct irpc_message *m)
674 {
675         struct irpc_request *irpc;
676         enum ndr_err_code ndr_err;
677
678         irpc = (struct irpc_request *)idr_find(msg_ctx->idr, m->header.callid);
679         if (irpc == NULL) return;
680
681         /* parse the reply data */
682         ndr_err = irpc->table->calls[irpc->callnum].ndr_pull(m->ndr, NDR_OUT, irpc->r);
683         if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
684                 irpc->status = m->header.status;
685                 talloc_steal(irpc->mem_ctx, m);
686         } else {
687                 irpc->status = ndr_map_error2ntstatus(ndr_err);
688                 talloc_steal(irpc, m);
689         }
690         irpc->done = true;
691         if (irpc->async.fn) {
692                 irpc->async.fn(irpc);
693         }
694 }
695
696 /*
697   send a irpc reply
698 */
699 NTSTATUS irpc_send_reply(struct irpc_message *m, NTSTATUS status)
700 {
701         struct ndr_push *push;
702         DATA_BLOB packet;
703         enum ndr_err_code ndr_err;
704
705         m->header.status = status;
706
707         /* setup the reply */
708         push = ndr_push_init_ctx(m->ndr, m->msg_ctx->iconv_convenience);
709         if (push == NULL) {
710                 status = NT_STATUS_NO_MEMORY;
711                 goto failed;
712         }
713
714         m->header.flags |= IRPC_FLAG_REPLY;
715
716         /* construct the packet */
717         ndr_err = ndr_push_irpc_header(push, NDR_SCALARS|NDR_BUFFERS, &m->header);
718         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
719                 status = ndr_map_error2ntstatus(ndr_err);
720                 goto failed;
721         }
722
723         ndr_err = m->irpc->table->calls[m->irpc->callnum].ndr_push(push, NDR_OUT, m->data);
724         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
725                 status = ndr_map_error2ntstatus(ndr_err);
726                 goto failed;
727         }
728
729         /* send the reply message */
730         packet = ndr_push_blob(push);
731         status = messaging_send(m->msg_ctx, m->from, MSG_IRPC, &packet);
732         if (!NT_STATUS_IS_OK(status)) goto failed;
733
734 failed:
735         talloc_free(m);
736         return status;
737 }
738
739 /*
740   handle an incoming irpc request message
741 */
742 static void irpc_handler_request(struct messaging_context *msg_ctx, 
743                                  struct irpc_message *m)
744 {
745         struct irpc_list *i;
746         void *r;
747         enum ndr_err_code ndr_err;
748
749         for (i=msg_ctx->irpc; i; i=i->next) {
750                 if (GUID_equal(&i->uuid, &m->header.uuid) &&
751                     i->table->syntax_id.if_version == m->header.if_version &&
752                     i->callnum == m->header.callnum) {
753                         break;
754                 }
755         }
756
757         if (i == NULL) {
758                 /* no registered handler for this message */
759                 talloc_free(m);
760                 return;
761         }
762
763         /* allocate space for the structure */
764         r = talloc_zero_size(m->ndr, i->table->calls[m->header.callnum].struct_size);
765         if (r == NULL) goto failed;
766
767         /* parse the request data */
768         ndr_err = i->table->calls[i->callnum].ndr_pull(m->ndr, NDR_IN, r);
769         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
770
771         /* make the call */
772         m->private     = i->private;
773         m->defer_reply = false;
774         m->msg_ctx     = msg_ctx;
775         m->irpc        = i;
776         m->data        = r;
777         m->ev          = msg_ctx->event.ev;
778
779         m->header.status = i->fn(m, r);
780
781         if (m->defer_reply) {
782                 /* the server function has asked to defer the reply to later */
783                 talloc_steal(msg_ctx, m);
784                 return;
785         }
786
787         irpc_send_reply(m, m->header.status);
788         return;
789
790 failed:
791         talloc_free(m);
792 }
793
794 /*
795   handle an incoming irpc message
796 */
797 static void irpc_handler(struct messaging_context *msg_ctx, void *private, 
798                          uint32_t msg_type, struct server_id src, DATA_BLOB *packet)
799 {
800         struct irpc_message *m;
801         enum ndr_err_code ndr_err;
802
803         m = talloc(msg_ctx, struct irpc_message);
804         if (m == NULL) goto failed;
805
806         m->from = src;
807
808         m->ndr = ndr_pull_init_blob(packet, m, msg_ctx->iconv_convenience);
809         if (m->ndr == NULL) goto failed;
810
811         m->ndr->flags |= LIBNDR_FLAG_REF_ALLOC;
812
813         ndr_err = ndr_pull_irpc_header(m->ndr, NDR_BUFFERS|NDR_SCALARS, &m->header);
814         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
815
816         if (m->header.flags & IRPC_FLAG_REPLY) {
817                 irpc_handler_reply(msg_ctx, m);
818         } else {
819                 irpc_handler_request(msg_ctx, m);
820         }
821         return;
822
823 failed:
824         talloc_free(m);
825 }
826
827
828 /*
829   destroy a irpc request
830 */
831 static int irpc_destructor(struct irpc_request *irpc)
832 {
833         if (irpc->callid != -1) {
834                 idr_remove(irpc->msg_ctx->idr, irpc->callid);
835                 irpc->callid = -1;
836         }
837
838         if (irpc->reject_free) {
839                 return -1;
840         }
841         return 0;
842 }
843
844 /*
845   timeout a irpc request
846 */
847 static void irpc_timeout(struct event_context *ev, struct timed_event *te, 
848                          struct timeval t, void *private)
849 {
850         struct irpc_request *irpc = talloc_get_type(private, struct irpc_request);
851         irpc->status = NT_STATUS_IO_TIMEOUT;
852         irpc->done = true;
853         if (irpc->async.fn) {
854                 irpc->async.fn(irpc);
855         }
856 }
857
858
859 /*
860   make a irpc call - async send
861 */
862 struct irpc_request *irpc_call_send(struct messaging_context *msg_ctx, 
863                                     struct server_id server_id, 
864                                     const struct ndr_interface_table *table, 
865                                     int callnum, void *r, TALLOC_CTX *ctx)
866 {
867         struct irpc_header header;
868         struct ndr_push *ndr;
869         NTSTATUS status;
870         DATA_BLOB packet;
871         struct irpc_request *irpc;
872         enum ndr_err_code ndr_err;
873
874         irpc = talloc(msg_ctx, struct irpc_request);
875         if (irpc == NULL) goto failed;
876
877         irpc->msg_ctx  = msg_ctx;
878         irpc->table    = table;
879         irpc->callnum  = callnum;
880         irpc->callid   = idr_get_new(msg_ctx->idr, irpc, UINT16_MAX);
881         if (irpc->callid == -1) goto failed;
882         irpc->r        = r;
883         irpc->done     = false;
884         irpc->async.fn = NULL;
885         irpc->mem_ctx  = ctx;
886         irpc->reject_free = false;
887
888         talloc_set_destructor(irpc, irpc_destructor);
889
890         /* setup the header */
891         header.uuid = table->syntax_id.uuid;
892
893         header.if_version = table->syntax_id.if_version;
894         header.callid     = irpc->callid;
895         header.callnum    = callnum;
896         header.flags      = 0;
897         header.status     = NT_STATUS_OK;
898
899         /* construct the irpc packet */
900         ndr = ndr_push_init_ctx(irpc, msg_ctx->iconv_convenience);
901         if (ndr == NULL) goto failed;
902
903         ndr_err = ndr_push_irpc_header(ndr, NDR_SCALARS|NDR_BUFFERS, &header);
904         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
905
906         ndr_err = table->calls[callnum].ndr_push(ndr, NDR_IN, r);
907         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
908
909         /* and send it */
910         packet = ndr_push_blob(ndr);
911         status = messaging_send(msg_ctx, server_id, MSG_IRPC, &packet);
912         if (!NT_STATUS_IS_OK(status)) goto failed;
913
914         event_add_timed(msg_ctx->event.ev, irpc, 
915                         timeval_current_ofs(IRPC_CALL_TIMEOUT, 0), 
916                         irpc_timeout, irpc);
917
918         talloc_free(ndr);
919         return irpc;
920
921 failed:
922         talloc_free(irpc);
923         return NULL;
924 }
925
926 /*
927   wait for a irpc reply
928 */
929 NTSTATUS irpc_call_recv(struct irpc_request *irpc)
930 {
931         NTSTATUS status;
932
933         NT_STATUS_HAVE_NO_MEMORY(irpc);
934
935         irpc->reject_free = true;
936
937         while (!irpc->done) {
938                 if (event_loop_once(irpc->msg_ctx->event.ev) != 0) {
939                         return NT_STATUS_CONNECTION_DISCONNECTED;
940                 }
941         }
942
943         irpc->reject_free = false;
944
945         status = irpc->status;
946         talloc_free(irpc);
947         return status;
948 }
949
950 /*
951   perform a synchronous irpc request
952 */
953 NTSTATUS irpc_call(struct messaging_context *msg_ctx, 
954                    struct server_id server_id, 
955                    const struct ndr_interface_table *table, 
956                    int callnum, void *r,
957                    TALLOC_CTX *mem_ctx)
958 {
959         struct irpc_request *irpc = irpc_call_send(msg_ctx, server_id, 
960                                                    table, callnum, r, mem_ctx);
961         return irpc_call_recv(irpc);
962 }
963
964 /*
965   open the naming database
966 */
967 static struct tdb_wrap *irpc_namedb_open(struct messaging_context *msg_ctx)
968 {
969         struct tdb_wrap *t;
970         char *path = talloc_asprintf(msg_ctx, "%s/names.tdb", msg_ctx->base_path);
971         if (path == NULL) {
972                 return NULL;
973         }
974         t = tdb_wrap_open(msg_ctx, path, 0, 0, O_RDWR|O_CREAT, 0660);
975         talloc_free(path);
976         return t;
977 }
978         
979
980 /*
981   add a string name that this irpc server can be called on
982 */
983 NTSTATUS irpc_add_name(struct messaging_context *msg_ctx, const char *name)
984 {
985         struct tdb_wrap *t;
986         TDB_DATA rec;
987         int count;
988         NTSTATUS status = NT_STATUS_OK;
989
990         t = irpc_namedb_open(msg_ctx);
991         NT_STATUS_HAVE_NO_MEMORY(t);
992
993         if (tdb_lock_bystring(t->tdb, name) != 0) {
994                 talloc_free(t);
995                 return NT_STATUS_LOCK_NOT_GRANTED;
996         }
997         rec = tdb_fetch_bystring(t->tdb, name);
998         count = rec.dsize / sizeof(struct server_id);
999         rec.dptr = (unsigned char *)realloc_p(rec.dptr, struct server_id, count+1);
1000         rec.dsize += sizeof(struct server_id);
1001         if (rec.dptr == NULL) {
1002                 tdb_unlock_bystring(t->tdb, name);
1003                 talloc_free(t);
1004                 return NT_STATUS_NO_MEMORY;
1005         }
1006         ((struct server_id *)rec.dptr)[count] = msg_ctx->server_id;
1007         if (tdb_store_bystring(t->tdb, name, rec, 0) != 0) {
1008                 status = NT_STATUS_INTERNAL_ERROR;
1009         }
1010         free(rec.dptr);
1011         tdb_unlock_bystring(t->tdb, name);
1012         talloc_free(t);
1013
1014         msg_ctx->names = str_list_add(msg_ctx->names, name);
1015         talloc_steal(msg_ctx, msg_ctx->names);
1016
1017         return status;
1018 }
1019
1020 /*
1021   return a list of server ids for a server name
1022 */
1023 struct server_id *irpc_servers_byname(struct messaging_context *msg_ctx,
1024                                       TALLOC_CTX *mem_ctx,
1025                                       const char *name)
1026 {
1027         struct tdb_wrap *t;
1028         TDB_DATA rec;
1029         int count, i;
1030         struct server_id *ret;
1031
1032         t = irpc_namedb_open(msg_ctx);
1033         if (t == NULL) {
1034                 return NULL;
1035         }
1036
1037         if (tdb_lock_bystring(t->tdb, name) != 0) {
1038                 talloc_free(t);
1039                 return NULL;
1040         }
1041         rec = tdb_fetch_bystring(t->tdb, name);
1042         if (rec.dptr == NULL) {
1043                 tdb_unlock_bystring(t->tdb, name);
1044                 talloc_free(t);
1045                 return NULL;
1046         }
1047         count = rec.dsize / sizeof(struct server_id);
1048         ret = talloc_array(mem_ctx, struct server_id, count+1);
1049         if (ret == NULL) {
1050                 tdb_unlock_bystring(t->tdb, name);
1051                 talloc_free(t);
1052                 return NULL;
1053         }
1054         for (i=0;i<count;i++) {
1055                 ret[i] = ((struct server_id *)rec.dptr)[i];
1056         }
1057         ret[i] = cluster_id(0, 0);
1058         free(rec.dptr);
1059         tdb_unlock_bystring(t->tdb, name);
1060         talloc_free(t);
1061
1062         return ret;
1063 }
1064
1065 /*
1066   remove a name from a messaging context
1067 */
1068 void irpc_remove_name(struct messaging_context *msg_ctx, const char *name)
1069 {
1070         struct tdb_wrap *t;
1071         TDB_DATA rec;
1072         int count, i;
1073         struct server_id *ids;
1074
1075         str_list_remove(msg_ctx->names, name);
1076
1077         t = irpc_namedb_open(msg_ctx);
1078         if (t == NULL) {
1079                 return;
1080         }
1081
1082         if (tdb_lock_bystring(t->tdb, name) != 0) {
1083                 talloc_free(t);
1084                 return;
1085         }
1086         rec = tdb_fetch_bystring(t->tdb, name);
1087         if (rec.dptr == NULL) {
1088                 tdb_unlock_bystring(t->tdb, name);
1089                 talloc_free(t);
1090                 return;
1091         }
1092         count = rec.dsize / sizeof(struct server_id);
1093         if (count == 0) {
1094                 free(rec.dptr);
1095                 tdb_unlock_bystring(t->tdb, name);
1096                 talloc_free(t);
1097                 return;
1098         }
1099         ids = (struct server_id *)rec.dptr;
1100         for (i=0;i<count;i++) {
1101                 if (cluster_id_equal(&ids[i], &msg_ctx->server_id)) {
1102                         if (i < count-1) {
1103                                 memmove(ids+i, ids+i+1, 
1104                                         sizeof(struct server_id) * (count-(i+1)));
1105                         }
1106                         rec.dsize -= sizeof(struct server_id);
1107                         break;
1108                 }
1109         }
1110         tdb_store_bystring(t->tdb, name, rec, 0);
1111         free(rec.dptr);
1112         tdb_unlock_bystring(t->tdb, name);
1113         talloc_free(t);
1114 }
1115
1116 struct server_id messaging_get_server_id(struct messaging_context *msg_ctx)
1117 {
1118         return msg_ctx->server_id;
1119 }