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