r23153: a first cut at a fix for the dgram flood problem that volker
[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 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 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 = idr_find(msg->dispatch_tree, rec->header->msg_type);
141         } else if (rec->header->msg_type < msg->num_types) {
142                 d = msg->dispatch[rec->header->msg_type];
143         } else {
144                 d = NULL;
145         }
146
147         for (; d; d = next) {
148                 DATA_BLOB data;
149                 next = d->next;
150                 data.data = rec->packet.data + sizeof(*rec->header);
151                 data.length = rec->header->length;
152                 d->fn(msg, d->private, d->msg_type, rec->header->from, &data);
153         }
154         rec->header->length = 0;
155 }
156
157 /*
158   handler for messages that arrive from other nodes in the cluster
159 */
160 static void cluster_message_handler(struct messaging_context *msg, DATA_BLOB packet)
161 {
162         struct messaging_rec *rec;
163
164         rec = talloc(msg, struct messaging_rec);
165         if (rec == NULL) {
166                 smb_panic("Unable to allocate messaging_rec");
167         }
168
169         rec->msg           = msg;
170         rec->path          = msg->path;
171         rec->header        = (struct messaging_header *)packet.data;
172         rec->packet        = packet;
173         rec->retries       = 0;
174
175         if (packet.length != sizeof(*rec->header) + rec->header->length) {
176                 DEBUG(0,("messaging: bad message header size %d should be %d\n", 
177                          rec->header->length, (int)(packet.length - sizeof(*rec->header))));
178                 talloc_free(rec);
179                 return;
180         }
181
182         messaging_dispatch(msg, rec);
183         talloc_free(rec);
184 }
185
186
187
188 /*
189   try to send the message
190 */
191 static NTSTATUS try_send(struct messaging_rec *rec)
192 {
193         struct messaging_context *msg = rec->msg;
194         size_t nsent;
195         void *priv;
196         NTSTATUS status;
197         struct socket_address *path;
198
199         /* rec->path is the path of the *other* socket, where we want
200          * this to end up */
201         path = socket_address_from_strings(msg, msg->sock->backend_name, 
202                                            rec->path, 0);
203         if (!path) {
204                 return NT_STATUS_NO_MEMORY;
205         }
206
207         /* we send with privileges so messages work from any context */
208         priv = root_privileges();
209         status = socket_sendto(msg->sock, &rec->packet, &nsent, path);
210         talloc_free(path);
211         talloc_free(priv);
212
213         return status;
214 }
215
216 /*
217   retry backed off messages
218 */
219 static void msg_retry_timer(struct event_context *ev, struct timed_event *te, 
220                             struct timeval t, void *private)
221 {
222         struct messaging_context *msg = talloc_get_type(private, 
223                                                         struct messaging_context);
224         msg->retry_te = NULL;
225
226         /* put the messages back on the main queue */
227         while (msg->retry_queue) {
228                 struct messaging_rec *rec = msg->retry_queue;
229                 DLIST_REMOVE(msg->retry_queue, rec);
230                 DLIST_ADD_END(msg->pending, rec, struct messaging_rec *);
231         }
232
233         EVENT_FD_WRITEABLE(msg->event.fde);     
234 }
235
236 /*
237   handle a socket write event
238 */
239 static void messaging_send_handler(struct messaging_context *msg)
240 {
241         while (msg->pending) {
242                 struct messaging_rec *rec = msg->pending;
243                 NTSTATUS status;
244                 status = try_send(rec);
245                 if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
246                         rec->retries++;
247                         if (rec->retries > 3) {
248                                 /* we're getting continuous write errors -
249                                    backoff this record */
250                                 DLIST_REMOVE(msg->pending, rec);
251                                 DLIST_ADD_END(msg->retry_queue, rec, 
252                                               struct messaging_rec *);
253                                 if (msg->retry_te == NULL) {
254                                         msg->retry_te = 
255                                                 event_add_timed(msg->event.ev, msg, 
256                                                                 timeval_current_ofs(1, 0), 
257                                                                 msg_retry_timer, msg);
258                                 }
259                         }
260                         break;
261                 }
262                 rec->retries = 0;
263                 if (!NT_STATUS_IS_OK(status)) {
264                         DEBUG(1,("messaging: Lost message from %u to %u of type %u - %s\n", 
265                                  rec->header->from.id, rec->header->to.id, rec->header->msg_type, 
266                                  nt_errstr(status)));
267                 }
268                 DLIST_REMOVE(msg->pending, rec);
269                 talloc_free(rec);
270         }
271         if (msg->pending == NULL) {
272                 EVENT_FD_NOT_WRITEABLE(msg->event.fde);
273         }
274 }
275
276 /*
277   handle a new incoming packet
278 */
279 static void messaging_recv_handler(struct messaging_context *msg)
280 {
281         struct messaging_rec *rec;
282         NTSTATUS status;
283         DATA_BLOB packet;
284         size_t msize;
285
286         /* see how many bytes are in the next packet */
287         status = socket_pending(msg->sock, &msize);
288         if (!NT_STATUS_IS_OK(status)) {
289                 DEBUG(0,("socket_pending failed in messaging - %s\n", 
290                          nt_errstr(status)));
291                 return;
292         }
293         
294         packet = data_blob_talloc(msg, NULL, msize);
295         if (packet.data == NULL) {
296                 /* assume this is temporary and retry */
297                 return;
298         }
299             
300         status = socket_recv(msg->sock, packet.data, msize, &msize);
301         if (!NT_STATUS_IS_OK(status)) {
302                 data_blob_free(&packet);
303                 return;
304         }
305
306         if (msize < sizeof(*rec->header)) {
307                 DEBUG(0,("messaging: bad message of size %d\n", (int)msize));
308                 data_blob_free(&packet);
309                 return;
310         }
311
312         rec = talloc(msg, struct messaging_rec);
313         if (rec == NULL) {
314                 smb_panic("Unable to allocate messaging_rec");
315         }
316
317         talloc_steal(rec, packet.data);
318         rec->msg           = msg;
319         rec->path          = msg->path;
320         rec->header        = (struct messaging_header *)packet.data;
321         rec->packet        = packet;
322         rec->retries       = 0;
323
324         if (msize != sizeof(*rec->header) + rec->header->length) {
325                 DEBUG(0,("messaging: bad message header size %d should be %d\n", 
326                          rec->header->length, (int)(msize - sizeof(*rec->header))));
327                 talloc_free(rec);
328                 return;
329         }
330
331         messaging_dispatch(msg, rec);
332         talloc_free(rec);
333 }
334
335
336 /*
337   handle a socket event
338 */
339 static void messaging_handler(struct event_context *ev, struct fd_event *fde, 
340                               uint16_t flags, void *private)
341 {
342         struct messaging_context *msg = talloc_get_type(private, 
343                                                         struct messaging_context);
344         if (flags & EVENT_FD_WRITE) {
345                 messaging_send_handler(msg);
346         }
347         if (flags & EVENT_FD_READ) {
348                 messaging_recv_handler(msg);
349         }
350 }
351
352
353 /*
354   Register a dispatch function for a particular message type.
355 */
356 NTSTATUS messaging_register(struct messaging_context *msg, void *private,
357                             uint32_t msg_type, msg_callback_t fn)
358 {
359         struct dispatch_fn *d;
360
361         /* possibly expand dispatch array */
362         if (msg_type >= msg->num_types) {
363                 struct dispatch_fn **dp;
364                 int i;
365                 dp = talloc_realloc(msg, msg->dispatch, struct dispatch_fn *, msg_type+1);
366                 NT_STATUS_HAVE_NO_MEMORY(dp);
367                 msg->dispatch = dp;
368                 for (i=msg->num_types;i<=msg_type;i++) {
369                         msg->dispatch[i] = NULL;
370                 }
371                 msg->num_types = msg_type+1;
372         }
373
374         d = talloc_zero(msg->dispatch, struct dispatch_fn);
375         NT_STATUS_HAVE_NO_MEMORY(d);
376         d->msg_type = msg_type;
377         d->private = private;
378         d->fn = fn;
379
380         DLIST_ADD(msg->dispatch[msg_type], d);
381
382         return NT_STATUS_OK;
383 }
384
385 /*
386   register a temporary message handler. The msg_type is allocated
387   above MSG_TMP_BASE
388 */
389 NTSTATUS messaging_register_tmp(struct messaging_context *msg, void *private,
390                                 msg_callback_t fn, uint32_t *msg_type)
391 {
392         struct dispatch_fn *d;
393         int id;
394
395         d = talloc_zero(msg->dispatch, struct dispatch_fn);
396         NT_STATUS_HAVE_NO_MEMORY(d);
397         d->private = private;
398         d->fn = fn;
399
400         id = idr_get_new_above(msg->dispatch_tree, d, MSG_TMP_BASE, UINT16_MAX);
401         if (id == -1) {
402                 talloc_free(d);
403                 return NT_STATUS_TOO_MANY_CONTEXT_IDS;
404         }
405
406         d->msg_type = (uint32_t)id;
407         (*msg_type) = d->msg_type;
408
409         return NT_STATUS_OK;
410 }
411
412 /*
413   De-register the function for a particular message type.
414 */
415 void messaging_deregister(struct messaging_context *msg, uint32_t msg_type, void *private)
416 {
417         struct dispatch_fn *d, *next;
418
419         if (msg_type >= msg->num_types) {
420                 d = idr_find(msg->dispatch_tree, msg_type);
421                 if (!d) return;
422                 idr_remove(msg->dispatch_tree, msg_type);
423                 talloc_free(d);
424                 return;
425         }
426
427         for (d = msg->dispatch[msg_type]; d; d = next) {
428                 next = d->next;
429                 if (d->private == private) {
430                         DLIST_REMOVE(msg->dispatch[msg_type], d);
431                         talloc_free(d);
432                 }
433         }
434 }
435
436 /*
437   Send a message to a particular server
438 */
439 NTSTATUS messaging_send(struct messaging_context *msg, struct server_id server, 
440                         uint32_t msg_type, DATA_BLOB *data)
441 {
442         struct messaging_rec *rec;
443         NTSTATUS status;
444         size_t dlength = data?data->length:0;
445
446         rec = talloc(msg, struct messaging_rec);
447         if (rec == NULL) {
448                 return NT_STATUS_NO_MEMORY;
449         }
450
451         rec->packet = data_blob_talloc(rec, NULL, sizeof(*rec->header) + dlength);
452         if (rec->packet.data == NULL) {
453                 talloc_free(rec);
454                 return NT_STATUS_NO_MEMORY;
455         }
456
457         rec->retries       = 0;
458         rec->msg              = msg;
459         rec->header           = (struct messaging_header *)rec->packet.data;
460         rec->header->version  = MESSAGING_VERSION;
461         rec->header->msg_type = msg_type;
462         rec->header->from     = msg->server_id;
463         rec->header->to       = server;
464         rec->header->length   = dlength;
465         if (dlength != 0) {
466                 memcpy(rec->packet.data + sizeof(*rec->header), 
467                        data->data, dlength);
468         }
469
470         if (!cluster_node_equal(&msg->server_id, &server)) {
471                 /* the destination is on another node - dispatch via
472                    the cluster layer */
473                 status = cluster_message_send(server, &rec->packet);
474                 talloc_free(rec);
475                 return status;
476         }
477
478         rec->path = messaging_path(msg, server);
479         talloc_steal(rec, rec->path);
480
481         if (msg->pending != NULL) {
482                 status = STATUS_MORE_ENTRIES;
483         } else {
484                 status = try_send(rec);
485         }
486
487         if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
488                 if (msg->pending == NULL) {
489                         EVENT_FD_WRITEABLE(msg->event.fde);
490                 }
491                 DLIST_ADD_END(msg->pending, rec, struct messaging_rec *);
492                 return NT_STATUS_OK;
493         }
494
495         talloc_free(rec);
496
497         return status;
498 }
499
500 /*
501   Send a message to a particular server, with the message containing a single pointer
502 */
503 NTSTATUS messaging_send_ptr(struct messaging_context *msg, struct server_id server, 
504                             uint32_t msg_type, void *ptr)
505 {
506         DATA_BLOB blob;
507
508         blob.data = (void *)&ptr;
509         blob.length = sizeof(void *);
510
511         return messaging_send(msg, server, msg_type, &blob);
512 }
513
514
515 /*
516   destroy the messaging context
517 */
518 static int messaging_destructor(struct messaging_context *msg)
519 {
520         unlink(msg->path);
521         while (msg->names && msg->names[0]) {
522                 irpc_remove_name(msg, msg->names[0]);
523         }
524         return 0;
525 }
526
527 /*
528   create the listening socket and setup the dispatcher
529 */
530 struct messaging_context *messaging_init(TALLOC_CTX *mem_ctx, 
531                                          struct server_id server_id, 
532                                          struct event_context *ev)
533 {
534         struct messaging_context *msg;
535         NTSTATUS status;
536         struct socket_address *path;
537         char *dir;
538
539         msg = talloc_zero(mem_ctx, struct messaging_context);
540         if (msg == NULL) {
541                 return NULL;
542         }
543
544         /* setup a handler for messages from other cluster nodes, if appropriate */
545         status = cluster_message_init(msg, server_id, cluster_message_handler);
546         if (!NT_STATUS_IS_OK(status)) {
547                 talloc_free(msg);
548                 return NULL;
549         }
550
551         if (ev == NULL) {
552                 ev = event_context_init(msg);
553         }
554
555         /* create the messaging directory if needed */
556         dir = smbd_tmp_path(msg, "messaging");
557         mkdir(dir, 0700);
558         talloc_free(dir);
559
560         msg->base_path     = smbd_tmp_path(msg, "messaging");
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                                                 struct event_context *ev)
612 {
613         struct server_id id;
614         ZERO_STRUCT(id);
615         id.id = random() % 0x10000000;
616         return messaging_init(mem_ctx, id, ev);
617 }
618 /*
619   a list of registered irpc server functions
620 */
621 struct irpc_list {
622         struct irpc_list *next, *prev;
623         struct GUID uuid;
624         const struct dcerpc_interface_table *table;
625         int callnum;
626         irpc_function_t fn;
627         void *private;
628 };
629
630
631 /*
632   register a irpc server function
633 */
634 NTSTATUS irpc_register(struct messaging_context *msg_ctx, 
635                        const struct dcerpc_interface_table *table, 
636                        int callnum, irpc_function_t fn, void *private)
637 {
638         struct irpc_list *irpc;
639
640         /* override an existing handler, if any */
641         for (irpc=msg_ctx->irpc; irpc; irpc=irpc->next) {
642                 if (irpc->table == table && irpc->callnum == callnum) {
643                         break;
644                 }
645         }
646         if (irpc == NULL) {
647                 irpc = talloc(msg_ctx, struct irpc_list);
648                 NT_STATUS_HAVE_NO_MEMORY(irpc);
649                 DLIST_ADD(msg_ctx->irpc, irpc);
650         }
651
652         irpc->table   = table;
653         irpc->callnum = callnum;
654         irpc->fn      = fn;
655         irpc->private = private;
656         irpc->uuid = irpc->table->syntax_id.uuid;
657
658         return NT_STATUS_OK;
659 }
660
661
662 /*
663   handle an incoming irpc reply message
664 */
665 static void irpc_handler_reply(struct messaging_context *msg_ctx, struct irpc_message *m)
666 {
667         struct irpc_request *irpc;
668
669         irpc = idr_find(msg_ctx->idr, m->header.callid);
670         if (irpc == NULL) return;
671
672         /* parse the reply data */
673         irpc->status = irpc->table->calls[irpc->callnum].ndr_pull(m->ndr, NDR_OUT, irpc->r);
674         if (NT_STATUS_IS_OK(irpc->status)) {
675                 irpc->status = m->header.status;
676                 talloc_steal(irpc->mem_ctx, m);
677         } else {
678                 talloc_steal(irpc, m);
679         }
680         irpc->done = True;
681         if (irpc->async.fn) {
682                 irpc->async.fn(irpc);
683         }
684 }
685
686 /*
687   send a irpc reply
688 */
689 NTSTATUS irpc_send_reply(struct irpc_message *m, NTSTATUS status)
690 {
691         struct ndr_push *push;
692         DATA_BLOB packet;
693
694         m->header.status = status;
695
696         /* setup the reply */
697         push = ndr_push_init_ctx(m->ndr);
698         if (push == NULL) {
699                 status = NT_STATUS_NO_MEMORY;
700                 goto failed;
701         }
702
703         m->header.flags |= IRPC_FLAG_REPLY;
704
705         /* construct the packet */
706         status = ndr_push_irpc_header(push, NDR_SCALARS|NDR_BUFFERS, &m->header);
707         if (!NT_STATUS_IS_OK(status)) goto failed;
708
709         status = m->irpc->table->calls[m->irpc->callnum].ndr_push(push, NDR_OUT, m->data);
710         if (!NT_STATUS_IS_OK(status)) goto failed;
711
712         /* send the reply message */
713         packet = ndr_push_blob(push);
714         status = messaging_send(m->msg_ctx, m->from, MSG_IRPC, &packet);
715         if (!NT_STATUS_IS_OK(status)) goto failed;
716
717 failed:
718         talloc_free(m);
719         return status;
720 }
721
722 /*
723   handle an incoming irpc request message
724 */
725 static void irpc_handler_request(struct messaging_context *msg_ctx, 
726                                  struct irpc_message *m)
727 {
728         struct irpc_list *i;
729         void *r;
730         NTSTATUS status;
731
732         for (i=msg_ctx->irpc; i; i=i->next) {
733                 if (GUID_equal(&i->uuid, &m->header.uuid) &&
734                     i->table->syntax_id.if_version == m->header.if_version &&
735                     i->callnum == m->header.callnum) {
736                         break;
737                 }
738         }
739
740         if (i == NULL) {
741                 /* no registered handler for this message */
742                 talloc_free(m);
743                 return;
744         }
745
746         /* allocate space for the structure */
747         r = talloc_zero_size(m->ndr, i->table->calls[m->header.callnum].struct_size);
748         if (r == NULL) goto failed;
749
750         /* parse the request data */
751         status = i->table->calls[i->callnum].ndr_pull(m->ndr, NDR_IN, r);
752         if (!NT_STATUS_IS_OK(status)) goto failed;
753
754         /* make the call */
755         m->private     = i->private;
756         m->defer_reply = False;
757         m->msg_ctx     = msg_ctx;
758         m->irpc        = i;
759         m->data        = r;
760         m->ev          = msg_ctx->event.ev;
761
762         m->header.status = i->fn(m, r);
763
764         if (m->defer_reply) {
765                 /* the server function has asked to defer the reply to later */
766                 talloc_steal(msg_ctx, m);
767                 return;
768         }
769
770         irpc_send_reply(m, m->header.status);
771         return;
772
773 failed:
774         talloc_free(m);
775 }
776
777 /*
778   handle an incoming irpc message
779 */
780 static void irpc_handler(struct messaging_context *msg_ctx, void *private, 
781                          uint32_t msg_type, struct server_id src, DATA_BLOB *packet)
782 {
783         struct irpc_message *m;
784         NTSTATUS status;
785
786         m = talloc(msg_ctx, struct irpc_message);
787         if (m == NULL) goto failed;
788
789         m->from = src;
790
791         m->ndr = ndr_pull_init_blob(packet, m);
792         if (m->ndr == NULL) goto failed;
793
794         m->ndr->flags |= LIBNDR_FLAG_REF_ALLOC;
795
796         status = ndr_pull_irpc_header(m->ndr, NDR_BUFFERS|NDR_SCALARS, &m->header);
797         if (!NT_STATUS_IS_OK(status)) goto failed;
798
799         if (m->header.flags & IRPC_FLAG_REPLY) {
800                 irpc_handler_reply(msg_ctx, m);
801         } else {
802                 irpc_handler_request(msg_ctx, m);
803         }
804         return;
805
806 failed:
807         talloc_free(m);
808 }
809
810
811 /*
812   destroy a irpc request
813 */
814 static int irpc_destructor(struct irpc_request *irpc)
815 {
816         if (irpc->callid != -1) {
817                 idr_remove(irpc->msg_ctx->idr, irpc->callid);
818                 irpc->callid = -1;
819         }
820
821         if (irpc->reject_free) {
822                 return -1;
823         }
824         return 0;
825 }
826
827 /*
828   timeout a irpc request
829 */
830 static void irpc_timeout(struct event_context *ev, struct timed_event *te, 
831                          struct timeval t, void *private)
832 {
833         struct irpc_request *irpc = talloc_get_type(private, struct irpc_request);
834         irpc->status = NT_STATUS_IO_TIMEOUT;
835         irpc->done = True;
836         if (irpc->async.fn) {
837                 irpc->async.fn(irpc);
838         }
839 }
840
841
842 /*
843   make a irpc call - async send
844 */
845 struct irpc_request *irpc_call_send(struct messaging_context *msg_ctx, 
846                                     struct server_id server_id, 
847                                     const struct dcerpc_interface_table *table, 
848                                     int callnum, void *r, TALLOC_CTX *ctx)
849 {
850         struct irpc_header header;
851         struct ndr_push *ndr;
852         NTSTATUS status;
853         DATA_BLOB packet;
854         struct irpc_request *irpc;
855
856         irpc = talloc(msg_ctx, struct irpc_request);
857         if (irpc == NULL) goto failed;
858
859         irpc->msg_ctx  = msg_ctx;
860         irpc->table    = table;
861         irpc->callnum  = callnum;
862         irpc->callid   = idr_get_new(msg_ctx->idr, irpc, UINT16_MAX);
863         if (irpc->callid == -1) goto failed;
864         irpc->r        = r;
865         irpc->done     = False;
866         irpc->async.fn = NULL;
867         irpc->mem_ctx  = ctx;
868         irpc->reject_free = False;
869
870         talloc_set_destructor(irpc, irpc_destructor);
871
872         /* setup the header */
873         header.uuid = table->syntax_id.uuid;
874
875         header.if_version = table->syntax_id.if_version;
876         header.callid     = irpc->callid;
877         header.callnum    = callnum;
878         header.flags      = 0;
879         header.status     = NT_STATUS_OK;
880
881         /* construct the irpc packet */
882         ndr = ndr_push_init_ctx(irpc);
883         if (ndr == NULL) goto failed;
884
885         status = ndr_push_irpc_header(ndr, NDR_SCALARS|NDR_BUFFERS, &header);
886         if (!NT_STATUS_IS_OK(status)) goto failed;
887
888         status = table->calls[callnum].ndr_push(ndr, NDR_IN, r);
889         if (!NT_STATUS_IS_OK(status)) goto failed;
890
891         /* and send it */
892         packet = ndr_push_blob(ndr);
893         status = messaging_send(msg_ctx, server_id, MSG_IRPC, &packet);
894         if (!NT_STATUS_IS_OK(status)) goto failed;
895
896         event_add_timed(msg_ctx->event.ev, irpc, 
897                         timeval_current_ofs(IRPC_CALL_TIMEOUT, 0), 
898                         irpc_timeout, irpc);
899
900         talloc_free(ndr);
901         return irpc;
902
903 failed:
904         talloc_free(irpc);
905         return NULL;
906 }
907
908 /*
909   wait for a irpc reply
910 */
911 NTSTATUS irpc_call_recv(struct irpc_request *irpc)
912 {
913         NTSTATUS status;
914
915         NT_STATUS_HAVE_NO_MEMORY(irpc);
916
917         irpc->reject_free = true;
918
919         while (!irpc->done) {
920                 if (event_loop_once(irpc->msg_ctx->event.ev) != 0) {
921                         return NT_STATUS_CONNECTION_DISCONNECTED;
922                 }
923         }
924
925         irpc->reject_free = false;
926
927         status = irpc->status;
928         talloc_free(irpc);
929         return status;
930 }
931
932 /*
933   perform a synchronous irpc request
934 */
935 NTSTATUS irpc_call(struct messaging_context *msg_ctx, 
936                    struct server_id server_id, 
937                    const struct dcerpc_interface_table *table, 
938                    int callnum, void *r,
939                    TALLOC_CTX *mem_ctx)
940 {
941         struct irpc_request *irpc = irpc_call_send(msg_ctx, server_id, 
942                                                    table, callnum, r, mem_ctx);
943         return irpc_call_recv(irpc);
944 }
945
946 /*
947   open the naming database
948 */
949 static struct tdb_wrap *irpc_namedb_open(struct messaging_context *msg_ctx)
950 {
951         struct tdb_wrap *t;
952         char *path = talloc_asprintf(msg_ctx, "%s/names.tdb", msg_ctx->base_path);
953         if (path == NULL) {
954                 return NULL;
955         }
956         t = tdb_wrap_open(msg_ctx, path, 0, 0, O_RDWR|O_CREAT, 0660);
957         talloc_free(path);
958         return t;
959 }
960         
961
962 /*
963   add a string name that this irpc server can be called on
964 */
965 NTSTATUS irpc_add_name(struct messaging_context *msg_ctx, const char *name)
966 {
967         struct tdb_wrap *t;
968         TDB_DATA rec;
969         int count;
970         NTSTATUS status = NT_STATUS_OK;
971
972         t = irpc_namedb_open(msg_ctx);
973         NT_STATUS_HAVE_NO_MEMORY(t);
974
975         if (tdb_lock_bystring(t->tdb, name) != 0) {
976                 talloc_free(t);
977                 return NT_STATUS_LOCK_NOT_GRANTED;
978         }
979         rec = tdb_fetch_bystring(t->tdb, name);
980         count = rec.dsize / sizeof(struct server_id);
981         rec.dptr = (unsigned char *)realloc_p(rec.dptr, struct server_id, count+1);
982         rec.dsize += sizeof(struct server_id);
983         if (rec.dptr == NULL) {
984                 tdb_unlock_bystring(t->tdb, name);
985                 talloc_free(t);
986                 return NT_STATUS_NO_MEMORY;
987         }
988         ((struct server_id *)rec.dptr)[count] = msg_ctx->server_id;
989         if (tdb_store_bystring(t->tdb, name, rec, 0) != 0) {
990                 status = NT_STATUS_INTERNAL_ERROR;
991         }
992         free(rec.dptr);
993         tdb_unlock_bystring(t->tdb, name);
994         talloc_free(t);
995
996         msg_ctx->names = str_list_add(msg_ctx->names, name);
997         talloc_steal(msg_ctx, msg_ctx->names);
998
999         return status;
1000 }
1001
1002 /*
1003   return a list of server ids for a server name
1004 */
1005 struct server_id *irpc_servers_byname(struct messaging_context *msg_ctx,
1006                                       TALLOC_CTX *mem_ctx,
1007                                       const char *name)
1008 {
1009         struct tdb_wrap *t;
1010         TDB_DATA rec;
1011         int count, i;
1012         struct server_id *ret;
1013
1014         t = irpc_namedb_open(msg_ctx);
1015         if (t == NULL) {
1016                 return NULL;
1017         }
1018
1019         if (tdb_lock_bystring(t->tdb, name) != 0) {
1020                 talloc_free(t);
1021                 return NULL;
1022         }
1023         rec = tdb_fetch_bystring(t->tdb, name);
1024         if (rec.dptr == NULL) {
1025                 tdb_unlock_bystring(t->tdb, name);
1026                 talloc_free(t);
1027                 return NULL;
1028         }
1029         count = rec.dsize / sizeof(struct server_id);
1030         ret = talloc_array(mem_ctx, struct server_id, count+1);
1031         if (ret == NULL) {
1032                 tdb_unlock_bystring(t->tdb, name);
1033                 talloc_free(t);
1034                 return NULL;
1035         }
1036         for (i=0;i<count;i++) {
1037                 ret[i] = ((struct server_id *)rec.dptr)[i];
1038         }
1039         ret[i] = cluster_id(0);
1040         free(rec.dptr);
1041         tdb_unlock_bystring(t->tdb, name);
1042         talloc_free(t);
1043
1044         return ret;
1045 }
1046
1047 /*
1048   remove a name from a messaging context
1049 */
1050 void irpc_remove_name(struct messaging_context *msg_ctx, const char *name)
1051 {
1052         struct tdb_wrap *t;
1053         TDB_DATA rec;
1054         int count, i;
1055         struct server_id *ids;
1056
1057         str_list_remove(msg_ctx->names, name);
1058
1059         t = irpc_namedb_open(msg_ctx);
1060         if (t == NULL) {
1061                 return;
1062         }
1063
1064         if (tdb_lock_bystring(t->tdb, name) != 0) {
1065                 talloc_free(t);
1066                 return;
1067         }
1068         rec = tdb_fetch_bystring(t->tdb, name);
1069         count = rec.dsize / sizeof(struct server_id);
1070         if (count == 0) {
1071                 tdb_unlock_bystring(t->tdb, name);
1072                 talloc_free(t);
1073                 return;
1074         }
1075         ids = (struct server_id *)rec.dptr;
1076         for (i=0;i<count;i++) {
1077                 if (cluster_id_equal(&ids[i], &msg_ctx->server_id)) {
1078                         if (i < count-1) {
1079                                 memmove(ids+i, ids+i+1, 
1080                                         sizeof(struct server_id) * (count-(i+1)));
1081                         }
1082                         rec.dsize -= sizeof(struct server_id);
1083                         break;
1084                 }
1085         }
1086         tdb_store_bystring(t->tdb, name, rec, 0);
1087         free(rec.dptr);
1088         tdb_unlock_bystring(t->tdb, name);
1089         talloc_free(t);
1090 }