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