963dfe4f0c4fb54a812210cc140b68fa07f5f373
[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 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 "db_wrap.h"
31 #include "lib/util/unix_privs.h"
32 #include "librpc/rpc/dcerpc.h"
33 #include "lib/tdb/include/tdb.h"
34 #include "lib/util/util_tdb.h"
35 #include "lib/util/util_tdb.h"
36 #include "cluster/cluster.h"
37 #include "param/param.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 messaging_rec *retry_queue;
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.%u.%u", msg->base_path, 
124                                (unsigned)server_id.node, (unsigned)server_id.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 %u to %u of type %u - %s\n", 
266                                  rec->header->from.id, rec->header->to.id, rec->header->msg_type, 
267                                  nt_errstr(status)));
268                 }
269                 DLIST_REMOVE(msg->pending, rec);
270                 talloc_free(rec);
271         }
272         if (msg->pending == NULL) {
273                 EVENT_FD_NOT_WRITEABLE(msg->event.fde);
274         }
275 }
276
277 /*
278   handle a new incoming packet
279 */
280 static void messaging_recv_handler(struct messaging_context *msg)
281 {
282         struct messaging_rec *rec;
283         NTSTATUS status;
284         DATA_BLOB packet;
285         size_t msize;
286
287         /* see how many bytes are in the next packet */
288         status = socket_pending(msg->sock, &msize);
289         if (!NT_STATUS_IS_OK(status)) {
290                 DEBUG(0,("socket_pending failed in messaging - %s\n", 
291                          nt_errstr(status)));
292                 return;
293         }
294         
295         packet = data_blob_talloc(msg, NULL, msize);
296         if (packet.data == NULL) {
297                 /* assume this is temporary and retry */
298                 return;
299         }
300             
301         status = socket_recv(msg->sock, packet.data, msize, &msize);
302         if (!NT_STATUS_IS_OK(status)) {
303                 data_blob_free(&packet);
304                 return;
305         }
306
307         if (msize < sizeof(*rec->header)) {
308                 DEBUG(0,("messaging: bad message of size %d\n", (int)msize));
309                 data_blob_free(&packet);
310                 return;
311         }
312
313         rec = talloc(msg, struct messaging_rec);
314         if (rec == NULL) {
315                 smb_panic("Unable to allocate messaging_rec");
316         }
317
318         talloc_steal(rec, packet.data);
319         rec->msg           = msg;
320         rec->path          = msg->path;
321         rec->header        = (struct messaging_header *)packet.data;
322         rec->packet        = packet;
323         rec->retries       = 0;
324
325         if (msize != sizeof(*rec->header) + rec->header->length) {
326                 DEBUG(0,("messaging: bad message header size %d should be %d\n", 
327                          rec->header->length, (int)(msize - sizeof(*rec->header))));
328                 talloc_free(rec);
329                 return;
330         }
331
332         messaging_dispatch(msg, rec);
333         talloc_free(rec);
334 }
335
336
337 /*
338   handle a socket event
339 */
340 static void messaging_handler(struct event_context *ev, struct fd_event *fde, 
341                               uint16_t flags, void *private)
342 {
343         struct messaging_context *msg = talloc_get_type(private, 
344                                                         struct messaging_context);
345         if (flags & EVENT_FD_WRITE) {
346                 messaging_send_handler(msg);
347         }
348         if (flags & EVENT_FD_READ) {
349                 messaging_recv_handler(msg);
350         }
351 }
352
353
354 /*
355   Register a dispatch function for a particular message type.
356 */
357 NTSTATUS messaging_register(struct messaging_context *msg, void *private,
358                             uint32_t msg_type, msg_callback_t fn)
359 {
360         struct dispatch_fn *d;
361
362         /* possibly expand dispatch array */
363         if (msg_type >= msg->num_types) {
364                 struct dispatch_fn **dp;
365                 int i;
366                 dp = talloc_realloc(msg, msg->dispatch, struct dispatch_fn *, msg_type+1);
367                 NT_STATUS_HAVE_NO_MEMORY(dp);
368                 msg->dispatch = dp;
369                 for (i=msg->num_types;i<=msg_type;i++) {
370                         msg->dispatch[i] = NULL;
371                 }
372                 msg->num_types = msg_type+1;
373         }
374
375         d = talloc_zero(msg->dispatch, struct dispatch_fn);
376         NT_STATUS_HAVE_NO_MEMORY(d);
377         d->msg_type = msg_type;
378         d->private = private;
379         d->fn = fn;
380
381         DLIST_ADD(msg->dispatch[msg_type], d);
382
383         return NT_STATUS_OK;
384 }
385
386 /*
387   register a temporary message handler. The msg_type is allocated
388   above MSG_TMP_BASE
389 */
390 NTSTATUS messaging_register_tmp(struct messaging_context *msg, void *private,
391                                 msg_callback_t fn, uint32_t *msg_type)
392 {
393         struct dispatch_fn *d;
394         int id;
395
396         d = talloc_zero(msg->dispatch, struct dispatch_fn);
397         NT_STATUS_HAVE_NO_MEMORY(d);
398         d->private = private;
399         d->fn = fn;
400
401         id = idr_get_new_above(msg->dispatch_tree, d, MSG_TMP_BASE, UINT16_MAX);
402         if (id == -1) {
403                 talloc_free(d);
404                 return NT_STATUS_TOO_MANY_CONTEXT_IDS;
405         }
406
407         d->msg_type = (uint32_t)id;
408         (*msg_type) = d->msg_type;
409
410         return NT_STATUS_OK;
411 }
412
413 /*
414   De-register the function for a particular message type.
415 */
416 void messaging_deregister(struct messaging_context *msg, uint32_t msg_type, void *private)
417 {
418         struct dispatch_fn *d, *next;
419
420         if (msg_type >= msg->num_types) {
421                 d = (struct dispatch_fn *)idr_find(msg->dispatch_tree, 
422                                                    msg_type);
423                 if (!d) return;
424                 idr_remove(msg->dispatch_tree, msg_type);
425                 talloc_free(d);
426                 return;
427         }
428
429         for (d = msg->dispatch[msg_type]; d; d = next) {
430                 next = d->next;
431                 if (d->private == private) {
432                         DLIST_REMOVE(msg->dispatch[msg_type], d);
433                         talloc_free(d);
434                 }
435         }
436 }
437
438 /*
439   Send a message to a particular server
440 */
441 NTSTATUS messaging_send(struct messaging_context *msg, struct server_id server, 
442                         uint32_t msg_type, DATA_BLOB *data)
443 {
444         struct messaging_rec *rec;
445         NTSTATUS status;
446         size_t dlength = data?data->length:0;
447
448         rec = talloc(msg, struct messaging_rec);
449         if (rec == NULL) {
450                 return NT_STATUS_NO_MEMORY;
451         }
452
453         rec->packet = data_blob_talloc(rec, NULL, sizeof(*rec->header) + dlength);
454         if (rec->packet.data == NULL) {
455                 talloc_free(rec);
456                 return NT_STATUS_NO_MEMORY;
457         }
458
459         rec->retries       = 0;
460         rec->msg              = msg;
461         rec->header           = (struct messaging_header *)rec->packet.data;
462         rec->header->version  = MESSAGING_VERSION;
463         rec->header->msg_type = msg_type;
464         rec->header->from     = msg->server_id;
465         rec->header->to       = server;
466         rec->header->length   = dlength;
467         if (dlength != 0) {
468                 memcpy(rec->packet.data + sizeof(*rec->header), 
469                        data->data, dlength);
470         }
471
472         if (!cluster_node_equal(&msg->server_id, &server)) {
473                 /* the destination is on another node - dispatch via
474                    the cluster layer */
475                 status = cluster_message_send(server, &rec->packet);
476                 talloc_free(rec);
477                 return status;
478         }
479
480         rec->path = messaging_path(msg, server);
481         talloc_steal(rec, rec->path);
482
483         if (msg->pending != NULL) {
484                 status = STATUS_MORE_ENTRIES;
485         } else {
486                 status = try_send(rec);
487         }
488
489         if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
490                 if (msg->pending == NULL) {
491                         EVENT_FD_WRITEABLE(msg->event.fde);
492                 }
493                 DLIST_ADD_END(msg->pending, rec, struct messaging_rec *);
494                 return NT_STATUS_OK;
495         }
496
497         talloc_free(rec);
498
499         return status;
500 }
501
502 /*
503   Send a message to a particular server, with the message containing a single pointer
504 */
505 NTSTATUS messaging_send_ptr(struct messaging_context *msg, struct server_id server, 
506                             uint32_t msg_type, void *ptr)
507 {
508         DATA_BLOB blob;
509
510         blob.data = (uint8_t *)&ptr;
511         blob.length = sizeof(void *);
512
513         return messaging_send(msg, server, msg_type, &blob);
514 }
515
516
517 /*
518   destroy the messaging context
519 */
520 static int messaging_destructor(struct messaging_context *msg)
521 {
522         unlink(msg->path);
523         while (msg->names && msg->names[0]) {
524                 irpc_remove_name(msg, msg->names[0]);
525         }
526         return 0;
527 }
528
529 /*
530   create the listening socket and setup the dispatcher
531 */
532 struct messaging_context *messaging_init(TALLOC_CTX *mem_ctx, 
533                                          const char *dir,
534                                          struct server_id server_id, 
535                                          struct event_context *ev)
536 {
537         struct messaging_context *msg;
538         NTSTATUS status;
539         struct socket_address *path;
540
541         msg = talloc_zero(mem_ctx, struct messaging_context);
542         if (msg == NULL) {
543                 return NULL;
544         }
545
546         /* setup a handler for messages from other cluster nodes, if appropriate */
547         status = cluster_message_init(msg, server_id, cluster_message_handler);
548         if (!NT_STATUS_IS_OK(status)) {
549                 talloc_free(msg);
550                 return NULL;
551         }
552
553         if (ev == NULL) {
554                 ev = event_context_init(msg);
555         }
556
557         /* create the messaging directory if needed */
558         mkdir(dir, 0700);
559
560         msg->base_path     = talloc_reference(msg, dir);
561         msg->path          = messaging_path(msg, server_id);
562         msg->server_id     = server_id;
563         msg->idr           = idr_init(msg);
564         msg->dispatch_tree = idr_init(msg);
565         msg->start_time    = timeval_current();
566
567         status = socket_create("unix", SOCKET_TYPE_DGRAM, &msg->sock, 0);
568         if (!NT_STATUS_IS_OK(status)) {
569                 talloc_free(msg);
570                 return NULL;
571         }
572
573         /* by stealing here we ensure that the socket is cleaned up (and even 
574            deleted) on exit */
575         talloc_steal(msg, msg->sock);
576
577         path = socket_address_from_strings(msg, msg->sock->backend_name, 
578                                            msg->path, 0);
579         if (!path) {
580                 talloc_free(msg);
581                 return NULL;
582         }
583
584         status = socket_listen(msg->sock, path, 50, 0);
585         if (!NT_STATUS_IS_OK(status)) {
586                 DEBUG(0,("Unable to setup messaging listener for '%s':%s\n", msg->path, nt_errstr(status)));
587                 talloc_free(msg);
588                 return NULL;
589         }
590
591         /* it needs to be non blocking for sends */
592         set_blocking(socket_get_fd(msg->sock), false);
593
594         msg->event.ev   = talloc_reference(msg, ev);
595         msg->event.fde  = event_add_fd(ev, msg, socket_get_fd(msg->sock), 
596                                        EVENT_FD_READ, messaging_handler, msg);
597
598         talloc_set_destructor(msg, messaging_destructor);
599         
600         messaging_register(msg, NULL, MSG_PING, ping_message);
601         messaging_register(msg, NULL, MSG_IRPC, irpc_handler);
602         IRPC_REGISTER(msg, irpc, IRPC_UPTIME, irpc_uptime, msg);
603
604         return msg;
605 }
606
607 /* 
608    A hack, for the short term until we get 'client only' messaging in place 
609 */
610 struct messaging_context *messaging_client_init(TALLOC_CTX *mem_ctx, 
611                                                 const char *dir,
612                                                 struct event_context *ev)
613 {
614         struct server_id id;
615         ZERO_STRUCT(id);
616         id.id = random() % 0x10000000;
617         return messaging_init(mem_ctx, dir, id, ev);
618 }
619 /*
620   a list of registered irpc server functions
621 */
622 struct irpc_list {
623         struct irpc_list *next, *prev;
624         struct GUID uuid;
625         const struct ndr_interface_table *table;
626         int callnum;
627         irpc_function_t fn;
628         void *private;
629 };
630
631
632 /*
633   register a irpc server function
634 */
635 NTSTATUS irpc_register(struct messaging_context *msg_ctx, 
636                        const struct ndr_interface_table *table, 
637                        int callnum, irpc_function_t fn, void *private)
638 {
639         struct irpc_list *irpc;
640
641         /* override an existing handler, if any */
642         for (irpc=msg_ctx->irpc; irpc; irpc=irpc->next) {
643                 if (irpc->table == table && irpc->callnum == callnum) {
644                         break;
645                 }
646         }
647         if (irpc == NULL) {
648                 irpc = talloc(msg_ctx, struct irpc_list);
649                 NT_STATUS_HAVE_NO_MEMORY(irpc);
650                 DLIST_ADD(msg_ctx->irpc, irpc);
651         }
652
653         irpc->table   = table;
654         irpc->callnum = callnum;
655         irpc->fn      = fn;
656         irpc->private = private;
657         irpc->uuid = irpc->table->syntax_id.uuid;
658
659         return NT_STATUS_OK;
660 }
661
662
663 /*
664   handle an incoming irpc reply message
665 */
666 static void irpc_handler_reply(struct messaging_context *msg_ctx, struct irpc_message *m)
667 {
668         struct irpc_request *irpc;
669         enum ndr_err_code ndr_err;
670
671         irpc = (struct irpc_request *)idr_find(msg_ctx->idr, m->header.callid);
672         if (irpc == NULL) return;
673
674         /* parse the reply data */
675         ndr_err = irpc->table->calls[irpc->callnum].ndr_pull(m->ndr, NDR_OUT, irpc->r);
676         if (NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
677                 irpc->status = m->header.status;
678                 talloc_steal(irpc->mem_ctx, m);
679         } else {
680                 irpc->status = ndr_map_error2ntstatus(ndr_err);
681                 talloc_steal(irpc, m);
682         }
683         irpc->done = true;
684         if (irpc->async.fn) {
685                 irpc->async.fn(irpc);
686         }
687 }
688
689 /*
690   send a irpc reply
691 */
692 NTSTATUS irpc_send_reply(struct irpc_message *m, NTSTATUS status)
693 {
694         struct ndr_push *push;
695         DATA_BLOB packet;
696         enum ndr_err_code ndr_err;
697
698         m->header.status = status;
699
700         /* setup the reply */
701         push = ndr_push_init_ctx(m->ndr);
702         if (push == NULL) {
703                 status = NT_STATUS_NO_MEMORY;
704                 goto failed;
705         }
706
707         m->header.flags |= IRPC_FLAG_REPLY;
708
709         /* construct the packet */
710         ndr_err = ndr_push_irpc_header(push, NDR_SCALARS|NDR_BUFFERS, &m->header);
711         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
712                 status = ndr_map_error2ntstatus(ndr_err);
713                 goto failed;
714         }
715
716         ndr_err = m->irpc->table->calls[m->irpc->callnum].ndr_push(push, NDR_OUT, m->data);
717         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
718                 status = ndr_map_error2ntstatus(ndr_err);
719                 goto failed;
720         }
721
722         /* send the reply message */
723         packet = ndr_push_blob(push);
724         status = messaging_send(m->msg_ctx, m->from, MSG_IRPC, &packet);
725         if (!NT_STATUS_IS_OK(status)) goto failed;
726
727 failed:
728         talloc_free(m);
729         return status;
730 }
731
732 /*
733   handle an incoming irpc request message
734 */
735 static void irpc_handler_request(struct messaging_context *msg_ctx, 
736                                  struct irpc_message *m)
737 {
738         struct irpc_list *i;
739         void *r;
740         enum ndr_err_code ndr_err;
741
742         for (i=msg_ctx->irpc; i; i=i->next) {
743                 if (GUID_equal(&i->uuid, &m->header.uuid) &&
744                     i->table->syntax_id.if_version == m->header.if_version &&
745                     i->callnum == m->header.callnum) {
746                         break;
747                 }
748         }
749
750         if (i == NULL) {
751                 /* no registered handler for this message */
752                 talloc_free(m);
753                 return;
754         }
755
756         /* allocate space for the structure */
757         r = talloc_zero_size(m->ndr, i->table->calls[m->header.callnum].struct_size);
758         if (r == NULL) goto failed;
759
760         /* parse the request data */
761         ndr_err = i->table->calls[i->callnum].ndr_pull(m->ndr, NDR_IN, r);
762         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
763
764         /* make the call */
765         m->private     = i->private;
766         m->defer_reply = false;
767         m->msg_ctx     = msg_ctx;
768         m->irpc        = i;
769         m->data        = r;
770         m->ev          = msg_ctx->event.ev;
771
772         m->header.status = i->fn(m, r);
773
774         if (m->defer_reply) {
775                 /* the server function has asked to defer the reply to later */
776                 talloc_steal(msg_ctx, m);
777                 return;
778         }
779
780         irpc_send_reply(m, m->header.status);
781         return;
782
783 failed:
784         talloc_free(m);
785 }
786
787 /*
788   handle an incoming irpc message
789 */
790 static void irpc_handler(struct messaging_context *msg_ctx, void *private, 
791                          uint32_t msg_type, struct server_id src, DATA_BLOB *packet)
792 {
793         struct irpc_message *m;
794         enum ndr_err_code ndr_err;
795
796         m = talloc(msg_ctx, struct irpc_message);
797         if (m == NULL) goto failed;
798
799         m->from = src;
800
801         m->ndr = ndr_pull_init_blob(packet, m);
802         if (m->ndr == NULL) goto failed;
803
804         m->ndr->flags |= LIBNDR_FLAG_REF_ALLOC;
805
806         ndr_err = ndr_pull_irpc_header(m->ndr, NDR_BUFFERS|NDR_SCALARS, &m->header);
807         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
808
809         if (m->header.flags & IRPC_FLAG_REPLY) {
810                 irpc_handler_reply(msg_ctx, m);
811         } else {
812                 irpc_handler_request(msg_ctx, m);
813         }
814         return;
815
816 failed:
817         talloc_free(m);
818 }
819
820
821 /*
822   destroy a irpc request
823 */
824 static int irpc_destructor(struct irpc_request *irpc)
825 {
826         if (irpc->callid != -1) {
827                 idr_remove(irpc->msg_ctx->idr, irpc->callid);
828                 irpc->callid = -1;
829         }
830
831         if (irpc->reject_free) {
832                 return -1;
833         }
834         return 0;
835 }
836
837 /*
838   timeout a irpc request
839 */
840 static void irpc_timeout(struct event_context *ev, struct timed_event *te, 
841                          struct timeval t, void *private)
842 {
843         struct irpc_request *irpc = talloc_get_type(private, struct irpc_request);
844         irpc->status = NT_STATUS_IO_TIMEOUT;
845         irpc->done = true;
846         if (irpc->async.fn) {
847                 irpc->async.fn(irpc);
848         }
849 }
850
851
852 /*
853   make a irpc call - async send
854 */
855 struct irpc_request *irpc_call_send(struct messaging_context *msg_ctx, 
856                                     struct server_id server_id, 
857                                     const struct ndr_interface_table *table, 
858                                     int callnum, void *r, TALLOC_CTX *ctx)
859 {
860         struct irpc_header header;
861         struct ndr_push *ndr;
862         NTSTATUS status;
863         DATA_BLOB packet;
864         struct irpc_request *irpc;
865         enum ndr_err_code ndr_err;
866
867         irpc = talloc(msg_ctx, struct irpc_request);
868         if (irpc == NULL) goto failed;
869
870         irpc->msg_ctx  = msg_ctx;
871         irpc->table    = table;
872         irpc->callnum  = callnum;
873         irpc->callid   = idr_get_new(msg_ctx->idr, irpc, UINT16_MAX);
874         if (irpc->callid == -1) goto failed;
875         irpc->r        = r;
876         irpc->done     = false;
877         irpc->async.fn = NULL;
878         irpc->mem_ctx  = ctx;
879         irpc->reject_free = false;
880
881         talloc_set_destructor(irpc, irpc_destructor);
882
883         /* setup the header */
884         header.uuid = table->syntax_id.uuid;
885
886         header.if_version = table->syntax_id.if_version;
887         header.callid     = irpc->callid;
888         header.callnum    = callnum;
889         header.flags      = 0;
890         header.status     = NT_STATUS_OK;
891
892         /* construct the irpc packet */
893         ndr = ndr_push_init_ctx(irpc);
894         if (ndr == NULL) goto failed;
895
896         ndr_err = ndr_push_irpc_header(ndr, NDR_SCALARS|NDR_BUFFERS, &header);
897         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
898
899         ndr_err = table->calls[callnum].ndr_push(ndr, NDR_IN, r);
900         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
901
902         /* and send it */
903         packet = ndr_push_blob(ndr);
904         status = messaging_send(msg_ctx, server_id, MSG_IRPC, &packet);
905         if (!NT_STATUS_IS_OK(status)) goto failed;
906
907         event_add_timed(msg_ctx->event.ev, irpc, 
908                         timeval_current_ofs(IRPC_CALL_TIMEOUT, 0), 
909                         irpc_timeout, irpc);
910
911         talloc_free(ndr);
912         return irpc;
913
914 failed:
915         talloc_free(irpc);
916         return NULL;
917 }
918
919 /*
920   wait for a irpc reply
921 */
922 NTSTATUS irpc_call_recv(struct irpc_request *irpc)
923 {
924         NTSTATUS status;
925
926         NT_STATUS_HAVE_NO_MEMORY(irpc);
927
928         irpc->reject_free = true;
929
930         while (!irpc->done) {
931                 if (event_loop_once(irpc->msg_ctx->event.ev) != 0) {
932                         return NT_STATUS_CONNECTION_DISCONNECTED;
933                 }
934         }
935
936         irpc->reject_free = false;
937
938         status = irpc->status;
939         talloc_free(irpc);
940         return status;
941 }
942
943 /*
944   perform a synchronous irpc request
945 */
946 NTSTATUS irpc_call(struct messaging_context *msg_ctx, 
947                    struct server_id server_id, 
948                    const struct ndr_interface_table *table, 
949                    int callnum, void *r,
950                    TALLOC_CTX *mem_ctx)
951 {
952         struct irpc_request *irpc = irpc_call_send(msg_ctx, server_id, 
953                                                    table, callnum, r, mem_ctx);
954         return irpc_call_recv(irpc);
955 }
956
957 /*
958   open the naming database
959 */
960 static struct tdb_wrap *irpc_namedb_open(struct messaging_context *msg_ctx)
961 {
962         struct tdb_wrap *t;
963         char *path = talloc_asprintf(msg_ctx, "%s/names.tdb", msg_ctx->base_path);
964         if (path == NULL) {
965                 return NULL;
966         }
967         t = tdb_wrap_open(msg_ctx, path, 0, 0, O_RDWR|O_CREAT, 0660);
968         talloc_free(path);
969         return t;
970 }
971         
972
973 /*
974   add a string name that this irpc server can be called on
975 */
976 NTSTATUS irpc_add_name(struct messaging_context *msg_ctx, const char *name)
977 {
978         struct tdb_wrap *t;
979         TDB_DATA rec;
980         int count;
981         NTSTATUS status = NT_STATUS_OK;
982
983         t = irpc_namedb_open(msg_ctx);
984         NT_STATUS_HAVE_NO_MEMORY(t);
985
986         if (tdb_lock_bystring(t->tdb, name) != 0) {
987                 talloc_free(t);
988                 return NT_STATUS_LOCK_NOT_GRANTED;
989         }
990         rec = tdb_fetch_bystring(t->tdb, name);
991         count = rec.dsize / sizeof(struct server_id);
992         rec.dptr = (unsigned char *)realloc_p(rec.dptr, struct server_id, count+1);
993         rec.dsize += sizeof(struct server_id);
994         if (rec.dptr == NULL) {
995                 tdb_unlock_bystring(t->tdb, name);
996                 talloc_free(t);
997                 return NT_STATUS_NO_MEMORY;
998         }
999         ((struct server_id *)rec.dptr)[count] = msg_ctx->server_id;
1000         if (tdb_store_bystring(t->tdb, name, rec, 0) != 0) {
1001                 status = NT_STATUS_INTERNAL_ERROR;
1002         }
1003         free(rec.dptr);
1004         tdb_unlock_bystring(t->tdb, name);
1005         talloc_free(t);
1006
1007         msg_ctx->names = str_list_add(msg_ctx->names, name);
1008         talloc_steal(msg_ctx, msg_ctx->names);
1009
1010         return status;
1011 }
1012
1013 /*
1014   return a list of server ids for a server name
1015 */
1016 struct server_id *irpc_servers_byname(struct messaging_context *msg_ctx,
1017                                       TALLOC_CTX *mem_ctx,
1018                                       const char *name)
1019 {
1020         struct tdb_wrap *t;
1021         TDB_DATA rec;
1022         int count, i;
1023         struct server_id *ret;
1024
1025         t = irpc_namedb_open(msg_ctx);
1026         if (t == NULL) {
1027                 return NULL;
1028         }
1029
1030         if (tdb_lock_bystring(t->tdb, name) != 0) {
1031                 talloc_free(t);
1032                 return NULL;
1033         }
1034         rec = tdb_fetch_bystring(t->tdb, name);
1035         if (rec.dptr == NULL) {
1036                 tdb_unlock_bystring(t->tdb, name);
1037                 talloc_free(t);
1038                 return NULL;
1039         }
1040         count = rec.dsize / sizeof(struct server_id);
1041         ret = talloc_array(mem_ctx, struct server_id, count+1);
1042         if (ret == NULL) {
1043                 tdb_unlock_bystring(t->tdb, name);
1044                 talloc_free(t);
1045                 return NULL;
1046         }
1047         for (i=0;i<count;i++) {
1048                 ret[i] = ((struct server_id *)rec.dptr)[i];
1049         }
1050         ret[i] = cluster_id(0);
1051         free(rec.dptr);
1052         tdb_unlock_bystring(t->tdb, name);
1053         talloc_free(t);
1054
1055         return ret;
1056 }
1057
1058 /*
1059   remove a name from a messaging context
1060 */
1061 void irpc_remove_name(struct messaging_context *msg_ctx, const char *name)
1062 {
1063         struct tdb_wrap *t;
1064         TDB_DATA rec;
1065         int count, i;
1066         struct server_id *ids;
1067
1068         str_list_remove(msg_ctx->names, name);
1069
1070         t = irpc_namedb_open(msg_ctx);
1071         if (t == NULL) {
1072                 return;
1073         }
1074
1075         if (tdb_lock_bystring(t->tdb, name) != 0) {
1076                 talloc_free(t);
1077                 return;
1078         }
1079         rec = tdb_fetch_bystring(t->tdb, name);
1080         count = rec.dsize / sizeof(struct server_id);
1081         if (count == 0) {
1082                 tdb_unlock_bystring(t->tdb, name);
1083                 talloc_free(t);
1084                 return;
1085         }
1086         ids = (struct server_id *)rec.dptr;
1087         for (i=0;i<count;i++) {
1088                 if (cluster_id_equal(&ids[i], &msg_ctx->server_id)) {
1089                         if (i < count-1) {
1090                                 memmove(ids+i, ids+i+1, 
1091                                         sizeof(struct server_id) * (count-(i+1)));
1092                         }
1093                         rec.dsize -= sizeof(struct server_id);
1094                         break;
1095                 }
1096         }
1097         tdb_store_bystring(t->tdb, name, rec, 0);
1098         free(rec.dptr);
1099         tdb_unlock_bystring(t->tdb, name);
1100         talloc_free(t);
1101 }