s4:irpc: use LIBNDR_FLAG_REF_ALLOC for the server side when pulling
[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 "tdb_wrap.h"
31 #include "../lib/util/unix_privs.h"
32 #include "librpc/rpc/dcerpc.h"
33 #include "../tdb/include/tdb.h"
34 #include "../lib/util/util_tdb.h"
35 #include "cluster/cluster.h"
36 #include "../lib/util/tevent_ntstatus.h"
37
38 /* change the message version with any incompatible changes in the protocol */
39 #define MESSAGING_VERSION 1
40
41 /*
42   a pending irpc call
43 */
44 struct irpc_request {
45         struct messaging_context *msg_ctx;
46         int callid;
47         struct {
48                 void (*handler)(struct irpc_request *irpc, struct irpc_message *m);
49                 void *private_data;
50         } incoming;
51 };
52
53 struct messaging_context {
54         struct server_id server_id;
55         struct socket_context *sock;
56         const char *base_path;
57         const char *path;
58         struct dispatch_fn **dispatch;
59         uint32_t num_types;
60         struct idr_context *dispatch_tree;
61         struct messaging_rec *pending;
62         struct messaging_rec *retry_queue;
63         struct irpc_list *irpc;
64         struct idr_context *idr;
65         const char **names;
66         struct timeval start_time;
67         struct tevent_timer *retry_te;
68         struct {
69                 struct tevent_context *ev;
70                 struct tevent_fd *fde;
71         } event;
72 };
73
74 /* we have a linked list of dispatch handlers for each msg_type that
75    this messaging server can deal with */
76 struct dispatch_fn {
77         struct dispatch_fn *next, *prev;
78         uint32_t msg_type;
79         void *private_data;
80         msg_callback_t fn;
81 };
82
83 /* an individual message */
84 struct messaging_rec {
85         struct messaging_rec *next, *prev;
86         struct messaging_context *msg;
87         const char *path;
88
89         struct messaging_header {
90                 uint32_t version;
91                 uint32_t msg_type;
92                 struct server_id from;
93                 struct server_id to;
94                 uint32_t length;
95         } *header;
96
97         DATA_BLOB packet;
98         uint32_t retries;
99 };
100
101
102 static void irpc_handler(struct messaging_context *, void *, 
103                          uint32_t, struct server_id, DATA_BLOB *);
104
105
106 /*
107  A useful function for testing the message system.
108 */
109 static void ping_message(struct messaging_context *msg, void *private_data,
110                          uint32_t msg_type, struct server_id src, DATA_BLOB *data)
111 {
112         DEBUG(1,("INFO: Received PING message from server %u.%u [%.*s]\n",
113                  (unsigned int)src.node, (unsigned int)src.id, (int)data->length,
114                  data->data?(const char *)data->data:""));
115         messaging_send(msg, src, MSG_PONG, data);
116 }
117
118 /*
119   return uptime of messaging server via irpc
120 */
121 static NTSTATUS irpc_uptime(struct irpc_message *msg, 
122                             struct irpc_uptime *r)
123 {
124         struct messaging_context *ctx = talloc_get_type(msg->private_data, struct messaging_context);
125         *r->out.start_time = timeval_to_nttime(&ctx->start_time);
126         return NT_STATUS_OK;
127 }
128
129 /* 
130    return the path to a messaging socket
131 */
132 static char *messaging_path(struct messaging_context *msg, struct server_id server_id)
133 {
134         TALLOC_CTX *tmp_ctx = talloc_new(msg);
135         const char *id = cluster_id_string(tmp_ctx, server_id);
136         char *s;
137         if (id == NULL) {
138                 return NULL;
139         }
140         s = talloc_asprintf(msg, "%s/msg.%s", msg->base_path, id);
141         talloc_steal(s, tmp_ctx);
142         return s;
143 }
144
145 /*
146   dispatch a fully received message
147
148   note that this deliberately can match more than one message handler
149   per message. That allows a single messasging context to register
150   (for example) a debug handler for more than one piece of code
151 */
152 static void messaging_dispatch(struct messaging_context *msg, struct messaging_rec *rec)
153 {
154         struct dispatch_fn *d, *next;
155
156         /* temporary IDs use an idtree, the rest use a array of pointers */
157         if (rec->header->msg_type >= MSG_TMP_BASE) {
158                 d = (struct dispatch_fn *)idr_find(msg->dispatch_tree, 
159                                                    rec->header->msg_type);
160         } else if (rec->header->msg_type < msg->num_types) {
161                 d = msg->dispatch[rec->header->msg_type];
162         } else {
163                 d = NULL;
164         }
165
166         for (; d; d = next) {
167                 DATA_BLOB data;
168                 next = d->next;
169                 data.data = rec->packet.data + sizeof(*rec->header);
170                 data.length = rec->header->length;
171                 d->fn(msg, d->private_data, d->msg_type, rec->header->from, &data);
172         }
173         rec->header->length = 0;
174 }
175
176 /*
177   handler for messages that arrive from other nodes in the cluster
178 */
179 static void cluster_message_handler(struct messaging_context *msg, DATA_BLOB packet)
180 {
181         struct messaging_rec *rec;
182
183         rec = talloc(msg, struct messaging_rec);
184         if (rec == NULL) {
185                 smb_panic("Unable to allocate messaging_rec");
186         }
187
188         rec->msg           = msg;
189         rec->path          = msg->path;
190         rec->header        = (struct messaging_header *)packet.data;
191         rec->packet        = packet;
192         rec->retries       = 0;
193
194         if (packet.length != sizeof(*rec->header) + rec->header->length) {
195                 DEBUG(0,("messaging: bad message header size %d should be %d\n", 
196                          rec->header->length, (int)(packet.length - sizeof(*rec->header))));
197                 talloc_free(rec);
198                 return;
199         }
200
201         messaging_dispatch(msg, rec);
202         talloc_free(rec);
203 }
204
205
206
207 /*
208   try to send the message
209 */
210 static NTSTATUS try_send(struct messaging_rec *rec)
211 {
212         struct messaging_context *msg = rec->msg;
213         size_t nsent;
214         void *priv;
215         NTSTATUS status;
216         struct socket_address *path;
217
218         /* rec->path is the path of the *other* socket, where we want
219          * this to end up */
220         path = socket_address_from_strings(msg, msg->sock->backend_name, 
221                                            rec->path, 0);
222         if (!path) {
223                 return NT_STATUS_NO_MEMORY;
224         }
225
226         /* we send with privileges so messages work from any context */
227         priv = root_privileges();
228         status = socket_sendto(msg->sock, &rec->packet, &nsent, path);
229         talloc_free(path);
230         talloc_free(priv);
231
232         return status;
233 }
234
235 /*
236   retry backed off messages
237 */
238 static void msg_retry_timer(struct tevent_context *ev, struct tevent_timer *te, 
239                             struct timeval t, void *private_data)
240 {
241         struct messaging_context *msg = talloc_get_type(private_data,
242                                                         struct messaging_context);
243         msg->retry_te = NULL;
244
245         /* put the messages back on the main queue */
246         while (msg->retry_queue) {
247                 struct messaging_rec *rec = msg->retry_queue;
248                 DLIST_REMOVE(msg->retry_queue, rec);
249                 DLIST_ADD_END(msg->pending, rec, struct messaging_rec *);
250         }
251
252         EVENT_FD_WRITEABLE(msg->event.fde);     
253 }
254
255 /*
256   handle a socket write event
257 */
258 static void messaging_send_handler(struct messaging_context *msg)
259 {
260         while (msg->pending) {
261                 struct messaging_rec *rec = msg->pending;
262                 NTSTATUS status;
263                 status = try_send(rec);
264                 if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
265                         rec->retries++;
266                         if (rec->retries > 3) {
267                                 /* we're getting continuous write errors -
268                                    backoff this record */
269                                 DLIST_REMOVE(msg->pending, rec);
270                                 DLIST_ADD_END(msg->retry_queue, rec, 
271                                               struct messaging_rec *);
272                                 if (msg->retry_te == NULL) {
273                                         msg->retry_te = 
274                                                 event_add_timed(msg->event.ev, msg, 
275                                                                 timeval_current_ofs(1, 0), 
276                                                                 msg_retry_timer, msg);
277                                 }
278                         }
279                         break;
280                 }
281                 rec->retries = 0;
282                 if (!NT_STATUS_IS_OK(status)) {
283                         TALLOC_CTX *tmp_ctx = talloc_new(msg);
284                         DEBUG(1,("messaging: Lost message from %s to %s of type %u - %s\n", 
285                                  cluster_id_string(tmp_ctx, rec->header->from),
286                                  cluster_id_string(tmp_ctx, rec->header->to),
287                                  rec->header->msg_type, 
288                                  nt_errstr(status)));
289                         talloc_free(tmp_ctx);
290                 }
291                 DLIST_REMOVE(msg->pending, rec);
292                 talloc_free(rec);
293         }
294         if (msg->pending == NULL) {
295                 EVENT_FD_NOT_WRITEABLE(msg->event.fde);
296         }
297 }
298
299 /*
300   handle a new incoming packet
301 */
302 static void messaging_recv_handler(struct messaging_context *msg)
303 {
304         struct messaging_rec *rec;
305         NTSTATUS status;
306         DATA_BLOB packet;
307         size_t msize;
308
309         /* see how many bytes are in the next packet */
310         status = socket_pending(msg->sock, &msize);
311         if (!NT_STATUS_IS_OK(status)) {
312                 DEBUG(0,("socket_pending failed in messaging - %s\n", 
313                          nt_errstr(status)));
314                 return;
315         }
316         
317         packet = data_blob_talloc(msg, NULL, msize);
318         if (packet.data == NULL) {
319                 /* assume this is temporary and retry */
320                 return;
321         }
322             
323         status = socket_recv(msg->sock, packet.data, msize, &msize);
324         if (!NT_STATUS_IS_OK(status)) {
325                 data_blob_free(&packet);
326                 return;
327         }
328
329         if (msize < sizeof(*rec->header)) {
330                 DEBUG(0,("messaging: bad message of size %d\n", (int)msize));
331                 data_blob_free(&packet);
332                 return;
333         }
334
335         rec = talloc(msg, struct messaging_rec);
336         if (rec == NULL) {
337                 smb_panic("Unable to allocate messaging_rec");
338         }
339
340         talloc_steal(rec, packet.data);
341         rec->msg           = msg;
342         rec->path          = msg->path;
343         rec->header        = (struct messaging_header *)packet.data;
344         rec->packet        = packet;
345         rec->retries       = 0;
346
347         if (msize != sizeof(*rec->header) + rec->header->length) {
348                 DEBUG(0,("messaging: bad message header size %d should be %d\n", 
349                          rec->header->length, (int)(msize - sizeof(*rec->header))));
350                 talloc_free(rec);
351                 return;
352         }
353
354         messaging_dispatch(msg, rec);
355         talloc_free(rec);
356 }
357
358
359 /*
360   handle a socket event
361 */
362 static void messaging_handler(struct tevent_context *ev, struct tevent_fd *fde, 
363                               uint16_t flags, void *private_data)
364 {
365         struct messaging_context *msg = talloc_get_type(private_data,
366                                                         struct messaging_context);
367         if (flags & EVENT_FD_WRITE) {
368                 messaging_send_handler(msg);
369         }
370         if (flags & EVENT_FD_READ) {
371                 messaging_recv_handler(msg);
372         }
373 }
374
375
376 /*
377   Register a dispatch function for a particular message type.
378 */
379 NTSTATUS messaging_register(struct messaging_context *msg, void *private_data,
380                             uint32_t msg_type, msg_callback_t fn)
381 {
382         struct dispatch_fn *d;
383
384         /* possibly expand dispatch array */
385         if (msg_type >= msg->num_types) {
386                 struct dispatch_fn **dp;
387                 int i;
388                 dp = talloc_realloc(msg, msg->dispatch, struct dispatch_fn *, msg_type+1);
389                 NT_STATUS_HAVE_NO_MEMORY(dp);
390                 msg->dispatch = dp;
391                 for (i=msg->num_types;i<=msg_type;i++) {
392                         msg->dispatch[i] = NULL;
393                 }
394                 msg->num_types = msg_type+1;
395         }
396
397         d = talloc_zero(msg->dispatch, struct dispatch_fn);
398         NT_STATUS_HAVE_NO_MEMORY(d);
399         d->msg_type = msg_type;
400         d->private_data = private_data;
401         d->fn = fn;
402
403         DLIST_ADD(msg->dispatch[msg_type], d);
404
405         return NT_STATUS_OK;
406 }
407
408 /*
409   register a temporary message handler. The msg_type is allocated
410   above MSG_TMP_BASE
411 */
412 NTSTATUS messaging_register_tmp(struct messaging_context *msg, void *private_data,
413                                 msg_callback_t fn, uint32_t *msg_type)
414 {
415         struct dispatch_fn *d;
416         int id;
417
418         d = talloc_zero(msg->dispatch, struct dispatch_fn);
419         NT_STATUS_HAVE_NO_MEMORY(d);
420         d->private_data = private_data;
421         d->fn = fn;
422
423         id = idr_get_new_above(msg->dispatch_tree, d, MSG_TMP_BASE, UINT16_MAX);
424         if (id == -1) {
425                 talloc_free(d);
426                 return NT_STATUS_TOO_MANY_CONTEXT_IDS;
427         }
428
429         d->msg_type = (uint32_t)id;
430         (*msg_type) = d->msg_type;
431
432         return NT_STATUS_OK;
433 }
434
435 /*
436   De-register the function for a particular message type.
437 */
438 void messaging_deregister(struct messaging_context *msg, uint32_t msg_type, void *private_data)
439 {
440         struct dispatch_fn *d, *next;
441
442         if (msg_type >= msg->num_types) {
443                 d = (struct dispatch_fn *)idr_find(msg->dispatch_tree, 
444                                                    msg_type);
445                 if (!d) return;
446                 idr_remove(msg->dispatch_tree, msg_type);
447                 talloc_free(d);
448                 return;
449         }
450
451         for (d = msg->dispatch[msg_type]; d; d = next) {
452                 next = d->next;
453                 if (d->private_data == private_data) {
454                         DLIST_REMOVE(msg->dispatch[msg_type], d);
455                         talloc_free(d);
456                 }
457         }
458 }
459
460 /*
461   Send a message to a particular server
462 */
463 NTSTATUS messaging_send(struct messaging_context *msg, struct server_id server, 
464                         uint32_t msg_type, const DATA_BLOB *data)
465 {
466         struct messaging_rec *rec;
467         NTSTATUS status;
468         size_t dlength = data?data->length:0;
469
470         rec = talloc(msg, struct messaging_rec);
471         if (rec == NULL) {
472                 return NT_STATUS_NO_MEMORY;
473         }
474
475         rec->packet = data_blob_talloc(rec, NULL, sizeof(*rec->header) + dlength);
476         if (rec->packet.data == NULL) {
477                 talloc_free(rec);
478                 return NT_STATUS_NO_MEMORY;
479         }
480
481         rec->retries       = 0;
482         rec->msg              = msg;
483         rec->header           = (struct messaging_header *)rec->packet.data;
484         /* zero padding */
485         ZERO_STRUCTP(rec->header);
486         rec->header->version  = MESSAGING_VERSION;
487         rec->header->msg_type = msg_type;
488         rec->header->from     = msg->server_id;
489         rec->header->to       = server;
490         rec->header->length   = dlength;
491         if (dlength != 0) {
492                 memcpy(rec->packet.data + sizeof(*rec->header), 
493                        data->data, dlength);
494         }
495
496         if (!cluster_node_equal(&msg->server_id, &server)) {
497                 /* the destination is on another node - dispatch via
498                    the cluster layer */
499                 status = cluster_message_send(server, &rec->packet);
500                 talloc_free(rec);
501                 return status;
502         }
503
504         rec->path = messaging_path(msg, server);
505         talloc_steal(rec, rec->path);
506
507         if (msg->pending != NULL) {
508                 status = STATUS_MORE_ENTRIES;
509         } else {
510                 status = try_send(rec);
511         }
512
513         if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
514                 if (msg->pending == NULL) {
515                         EVENT_FD_WRITEABLE(msg->event.fde);
516                 }
517                 DLIST_ADD_END(msg->pending, rec, struct messaging_rec *);
518                 return NT_STATUS_OK;
519         }
520
521         talloc_free(rec);
522
523         return status;
524 }
525
526 /*
527   Send a message to a particular server, with the message containing a single pointer
528 */
529 NTSTATUS messaging_send_ptr(struct messaging_context *msg, struct server_id server, 
530                             uint32_t msg_type, void *ptr)
531 {
532         DATA_BLOB blob;
533
534         blob.data = (uint8_t *)&ptr;
535         blob.length = sizeof(void *);
536
537         return messaging_send(msg, server, msg_type, &blob);
538 }
539
540
541 /*
542   destroy the messaging context
543 */
544 static int messaging_destructor(struct messaging_context *msg)
545 {
546         unlink(msg->path);
547         while (msg->names && msg->names[0]) {
548                 irpc_remove_name(msg, msg->names[0]);
549         }
550         return 0;
551 }
552
553 /*
554   create the listening socket and setup the dispatcher
555 */
556 struct messaging_context *messaging_init(TALLOC_CTX *mem_ctx, 
557                                          const char *dir,
558                                          struct server_id server_id, 
559                                          struct tevent_context *ev)
560 {
561         struct messaging_context *msg;
562         NTSTATUS status;
563         struct socket_address *path;
564
565         if (ev == NULL) {
566                 return NULL;
567         }
568
569         msg = talloc_zero(mem_ctx, struct messaging_context);
570         if (msg == NULL) {
571                 return NULL;
572         }
573
574         /* setup a handler for messages from other cluster nodes, if appropriate */
575         status = cluster_message_init(msg, server_id, cluster_message_handler);
576         if (!NT_STATUS_IS_OK(status)) {
577                 talloc_free(msg);
578                 return NULL;
579         }
580
581         /* create the messaging directory if needed */
582         mkdir(dir, 0700);
583
584         msg->base_path     = talloc_reference(msg, dir);
585         msg->path          = messaging_path(msg, server_id);
586         msg->server_id     = server_id;
587         msg->idr           = idr_init(msg);
588         msg->dispatch_tree = idr_init(msg);
589         msg->start_time    = timeval_current();
590
591         status = socket_create("unix", SOCKET_TYPE_DGRAM, &msg->sock, 0);
592         if (!NT_STATUS_IS_OK(status)) {
593                 talloc_free(msg);
594                 return NULL;
595         }
596
597         /* by stealing here we ensure that the socket is cleaned up (and even 
598            deleted) on exit */
599         talloc_steal(msg, msg->sock);
600
601         path = socket_address_from_strings(msg, msg->sock->backend_name, 
602                                            msg->path, 0);
603         if (!path) {
604                 talloc_free(msg);
605                 return NULL;
606         }
607
608         status = socket_listen(msg->sock, path, 50, 0);
609         if (!NT_STATUS_IS_OK(status)) {
610                 DEBUG(0,("Unable to setup messaging listener for '%s':%s\n", msg->path, nt_errstr(status)));
611                 talloc_free(msg);
612                 return NULL;
613         }
614
615         /* it needs to be non blocking for sends */
616         set_blocking(socket_get_fd(msg->sock), false);
617
618         msg->event.ev   = ev;
619         msg->event.fde  = event_add_fd(ev, msg, socket_get_fd(msg->sock), 
620                                        EVENT_FD_READ, messaging_handler, msg);
621         tevent_fd_set_auto_close(msg->event.fde);
622
623         talloc_set_destructor(msg, messaging_destructor);
624         
625         messaging_register(msg, NULL, MSG_PING, ping_message);
626         messaging_register(msg, NULL, MSG_IRPC, irpc_handler);
627         IRPC_REGISTER(msg, irpc, IRPC_UPTIME, irpc_uptime, msg);
628
629         return msg;
630 }
631
632 /* 
633    A hack, for the short term until we get 'client only' messaging in place 
634 */
635 struct messaging_context *messaging_client_init(TALLOC_CTX *mem_ctx, 
636                                                 const char *dir,
637                                                 struct tevent_context *ev)
638 {
639         struct server_id id;
640         ZERO_STRUCT(id);
641         id.id = random() % 0x10000000;
642         return messaging_init(mem_ctx, dir, id, ev);
643 }
644 /*
645   a list of registered irpc server functions
646 */
647 struct irpc_list {
648         struct irpc_list *next, *prev;
649         struct GUID uuid;
650         const struct ndr_interface_table *table;
651         int callnum;
652         irpc_function_t fn;
653         void *private_data;
654 };
655
656
657 /*
658   register a irpc server function
659 */
660 NTSTATUS irpc_register(struct messaging_context *msg_ctx, 
661                        const struct ndr_interface_table *table, 
662                        int callnum, irpc_function_t fn, void *private_data)
663 {
664         struct irpc_list *irpc;
665
666         /* override an existing handler, if any */
667         for (irpc=msg_ctx->irpc; irpc; irpc=irpc->next) {
668                 if (irpc->table == table && irpc->callnum == callnum) {
669                         break;
670                 }
671         }
672         if (irpc == NULL) {
673                 irpc = talloc(msg_ctx, struct irpc_list);
674                 NT_STATUS_HAVE_NO_MEMORY(irpc);
675                 DLIST_ADD(msg_ctx->irpc, irpc);
676         }
677
678         irpc->table   = table;
679         irpc->callnum = callnum;
680         irpc->fn      = fn;
681         irpc->private_data = private_data;
682         irpc->uuid = irpc->table->syntax_id.uuid;
683
684         return NT_STATUS_OK;
685 }
686
687
688 /*
689   handle an incoming irpc reply message
690 */
691 static void irpc_handler_reply(struct messaging_context *msg_ctx, struct irpc_message *m)
692 {
693         struct irpc_request *irpc;
694
695         irpc = (struct irpc_request *)idr_find(msg_ctx->idr, m->header.callid);
696         if (irpc == NULL) return;
697
698         irpc->incoming.handler(irpc, m);
699 }
700
701 /*
702   send a irpc reply
703 */
704 NTSTATUS irpc_send_reply(struct irpc_message *m, NTSTATUS status)
705 {
706         struct ndr_push *push;
707         DATA_BLOB packet;
708         enum ndr_err_code ndr_err;
709
710         m->header.status = status;
711
712         /* setup the reply */
713         push = ndr_push_init_ctx(m->ndr);
714         if (push == NULL) {
715                 status = NT_STATUS_NO_MEMORY;
716                 goto failed;
717         }
718
719         m->header.flags |= IRPC_FLAG_REPLY;
720
721         /* construct the packet */
722         ndr_err = ndr_push_irpc_header(push, NDR_SCALARS|NDR_BUFFERS, &m->header);
723         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
724                 status = ndr_map_error2ntstatus(ndr_err);
725                 goto failed;
726         }
727
728         ndr_err = m->irpc->table->calls[m->irpc->callnum].ndr_push(push, NDR_OUT, m->data);
729         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
730                 status = ndr_map_error2ntstatus(ndr_err);
731                 goto failed;
732         }
733
734         /* send the reply message */
735         packet = ndr_push_blob(push);
736         status = messaging_send(m->msg_ctx, m->from, MSG_IRPC, &packet);
737         if (!NT_STATUS_IS_OK(status)) goto failed;
738
739 failed:
740         talloc_free(m);
741         return status;
742 }
743
744 /*
745   handle an incoming irpc request message
746 */
747 static void irpc_handler_request(struct messaging_context *msg_ctx, 
748                                  struct irpc_message *m)
749 {
750         struct irpc_list *i;
751         void *r;
752         enum ndr_err_code ndr_err;
753
754         for (i=msg_ctx->irpc; i; i=i->next) {
755                 if (GUID_equal(&i->uuid, &m->header.uuid) &&
756                     i->table->syntax_id.if_version == m->header.if_version &&
757                     i->callnum == m->header.callnum) {
758                         break;
759                 }
760         }
761
762         if (i == NULL) {
763                 /* no registered handler for this message */
764                 talloc_free(m);
765                 return;
766         }
767
768         /* allocate space for the structure */
769         r = talloc_zero_size(m->ndr, i->table->calls[m->header.callnum].struct_size);
770         if (r == NULL) goto failed;
771
772         m->ndr->flags |= LIBNDR_FLAG_REF_ALLOC;
773
774         /* parse the request data */
775         ndr_err = i->table->calls[i->callnum].ndr_pull(m->ndr, NDR_IN, r);
776         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
777
778         /* make the call */
779         m->private_data= i->private_data;
780         m->defer_reply = false;
781         m->no_reply    = false;
782         m->msg_ctx     = msg_ctx;
783         m->irpc        = i;
784         m->data        = r;
785         m->ev          = msg_ctx->event.ev;
786
787         m->header.status = i->fn(m, r);
788
789         if (m->no_reply) {
790                 /* the server function won't ever be replying to this request */
791                 talloc_free(m);
792                 return;
793         }
794
795         if (m->defer_reply) {
796                 /* the server function has asked to defer the reply to later */
797                 talloc_steal(msg_ctx, m);
798                 return;
799         }
800
801         irpc_send_reply(m, m->header.status);
802         return;
803
804 failed:
805         talloc_free(m);
806 }
807
808 /*
809   handle an incoming irpc message
810 */
811 static void irpc_handler(struct messaging_context *msg_ctx, void *private_data,
812                          uint32_t msg_type, struct server_id src, DATA_BLOB *packet)
813 {
814         struct irpc_message *m;
815         enum ndr_err_code ndr_err;
816
817         m = talloc(msg_ctx, struct irpc_message);
818         if (m == NULL) goto failed;
819
820         m->from = src;
821
822         m->ndr = ndr_pull_init_blob(packet, m);
823         if (m->ndr == NULL) goto failed;
824
825         m->ndr->flags |= LIBNDR_FLAG_REF_ALLOC;
826
827         ndr_err = ndr_pull_irpc_header(m->ndr, NDR_BUFFERS|NDR_SCALARS, &m->header);
828         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) goto failed;
829
830         if (m->header.flags & IRPC_FLAG_REPLY) {
831                 irpc_handler_reply(msg_ctx, m);
832         } else {
833                 irpc_handler_request(msg_ctx, m);
834         }
835         return;
836
837 failed:
838         talloc_free(m);
839 }
840
841
842 /*
843   destroy a irpc request
844 */
845 static int irpc_destructor(struct irpc_request *irpc)
846 {
847         if (irpc->callid != -1) {
848                 idr_remove(irpc->msg_ctx->idr, irpc->callid);
849                 irpc->callid = -1;
850         }
851
852         return 0;
853 }
854
855 /*
856   open the naming database
857 */
858 static struct tdb_wrap *irpc_namedb_open(struct messaging_context *msg_ctx)
859 {
860         struct tdb_wrap *t;
861         char *path = talloc_asprintf(msg_ctx, "%s/names.tdb", msg_ctx->base_path);
862         if (path == NULL) {
863                 return NULL;
864         }
865         t = tdb_wrap_open(msg_ctx, path, 0, 0, O_RDWR|O_CREAT, 0660);
866         talloc_free(path);
867         return t;
868 }
869         
870
871 /*
872   add a string name that this irpc server can be called on
873 */
874 NTSTATUS irpc_add_name(struct messaging_context *msg_ctx, const char *name)
875 {
876         struct tdb_wrap *t;
877         TDB_DATA rec;
878         int count;
879         NTSTATUS status = NT_STATUS_OK;
880
881         t = irpc_namedb_open(msg_ctx);
882         NT_STATUS_HAVE_NO_MEMORY(t);
883
884         if (tdb_lock_bystring(t->tdb, name) != 0) {
885                 talloc_free(t);
886                 return NT_STATUS_LOCK_NOT_GRANTED;
887         }
888         rec = tdb_fetch_bystring(t->tdb, name);
889         count = rec.dsize / sizeof(struct server_id);
890         rec.dptr = (unsigned char *)realloc_p(rec.dptr, struct server_id, count+1);
891         rec.dsize += sizeof(struct server_id);
892         if (rec.dptr == NULL) {
893                 tdb_unlock_bystring(t->tdb, name);
894                 talloc_free(t);
895                 return NT_STATUS_NO_MEMORY;
896         }
897         ((struct server_id *)rec.dptr)[count] = msg_ctx->server_id;
898         if (tdb_store_bystring(t->tdb, name, rec, 0) != 0) {
899                 status = NT_STATUS_INTERNAL_ERROR;
900         }
901         free(rec.dptr);
902         tdb_unlock_bystring(t->tdb, name);
903         talloc_free(t);
904
905         msg_ctx->names = str_list_add(msg_ctx->names, name);
906         talloc_steal(msg_ctx, msg_ctx->names);
907
908         return status;
909 }
910
911 /*
912   return a list of server ids for a server name
913 */
914 struct server_id *irpc_servers_byname(struct messaging_context *msg_ctx,
915                                       TALLOC_CTX *mem_ctx,
916                                       const char *name)
917 {
918         struct tdb_wrap *t;
919         TDB_DATA rec;
920         int count, i;
921         struct server_id *ret;
922
923         t = irpc_namedb_open(msg_ctx);
924         if (t == NULL) {
925                 return NULL;
926         }
927
928         if (tdb_lock_bystring(t->tdb, name) != 0) {
929                 talloc_free(t);
930                 return NULL;
931         }
932         rec = tdb_fetch_bystring(t->tdb, name);
933         if (rec.dptr == NULL) {
934                 tdb_unlock_bystring(t->tdb, name);
935                 talloc_free(t);
936                 return NULL;
937         }
938         count = rec.dsize / sizeof(struct server_id);
939         ret = talloc_array(mem_ctx, struct server_id, count+1);
940         if (ret == NULL) {
941                 tdb_unlock_bystring(t->tdb, name);
942                 talloc_free(t);
943                 return NULL;
944         }
945         for (i=0;i<count;i++) {
946                 ret[i] = ((struct server_id *)rec.dptr)[i];
947         }
948         ret[i] = cluster_id(0, 0);
949         free(rec.dptr);
950         tdb_unlock_bystring(t->tdb, name);
951         talloc_free(t);
952
953         return ret;
954 }
955
956 /*
957   remove a name from a messaging context
958 */
959 void irpc_remove_name(struct messaging_context *msg_ctx, const char *name)
960 {
961         struct tdb_wrap *t;
962         TDB_DATA rec;
963         int count, i;
964         struct server_id *ids;
965
966         str_list_remove(msg_ctx->names, name);
967
968         t = irpc_namedb_open(msg_ctx);
969         if (t == NULL) {
970                 return;
971         }
972
973         if (tdb_lock_bystring(t->tdb, name) != 0) {
974                 talloc_free(t);
975                 return;
976         }
977         rec = tdb_fetch_bystring(t->tdb, name);
978         if (rec.dptr == NULL) {
979                 tdb_unlock_bystring(t->tdb, name);
980                 talloc_free(t);
981                 return;
982         }
983         count = rec.dsize / sizeof(struct server_id);
984         if (count == 0) {
985                 free(rec.dptr);
986                 tdb_unlock_bystring(t->tdb, name);
987                 talloc_free(t);
988                 return;
989         }
990         ids = (struct server_id *)rec.dptr;
991         for (i=0;i<count;i++) {
992                 if (cluster_id_equal(&ids[i], &msg_ctx->server_id)) {
993                         if (i < count-1) {
994                                 memmove(ids+i, ids+i+1, 
995                                         sizeof(struct server_id) * (count-(i+1)));
996                         }
997                         rec.dsize -= sizeof(struct server_id);
998                         break;
999                 }
1000         }
1001         tdb_store_bystring(t->tdb, name, rec, 0);
1002         free(rec.dptr);
1003         tdb_unlock_bystring(t->tdb, name);
1004         talloc_free(t);
1005 }
1006
1007 struct server_id messaging_get_server_id(struct messaging_context *msg_ctx)
1008 {
1009         return msg_ctx->server_id;
1010 }
1011
1012 struct irpc_bh_state {
1013         struct messaging_context *msg_ctx;
1014         struct server_id server_id;
1015         const struct ndr_interface_table *table;
1016         uint32_t timeout;
1017 };
1018
1019 static bool irpc_bh_is_connected(struct dcerpc_binding_handle *h)
1020 {
1021         struct irpc_bh_state *hs = dcerpc_binding_handle_data(h,
1022                                    struct irpc_bh_state);
1023
1024         if (!hs->msg_ctx) {
1025                 return false;
1026         }
1027
1028         return true;
1029 }
1030
1031 static uint32_t irpc_bh_set_timeout(struct dcerpc_binding_handle *h,
1032                                     uint32_t timeout)
1033 {
1034         struct irpc_bh_state *hs = dcerpc_binding_handle_data(h,
1035                                    struct irpc_bh_state);
1036         uint32_t old = hs->timeout;
1037
1038         hs->timeout = timeout;
1039
1040         return old;
1041 }
1042
1043 struct irpc_bh_raw_call_state {
1044         struct irpc_request *irpc;
1045         uint32_t opnum;
1046         DATA_BLOB in_data;
1047         DATA_BLOB in_packet;
1048         DATA_BLOB out_data;
1049 };
1050
1051 static void irpc_bh_raw_call_incoming_handler(struct irpc_request *irpc,
1052                                               struct irpc_message *m);
1053
1054 static struct tevent_req *irpc_bh_raw_call_send(TALLOC_CTX *mem_ctx,
1055                                                 struct tevent_context *ev,
1056                                                 struct dcerpc_binding_handle *h,
1057                                                 const struct GUID *object,
1058                                                 uint32_t opnum,
1059                                                 uint32_t in_flags,
1060                                                 const uint8_t *in_data,
1061                                                 size_t in_length)
1062 {
1063         struct irpc_bh_state *hs =
1064                 dcerpc_binding_handle_data(h,
1065                 struct irpc_bh_state);
1066         struct tevent_req *req;
1067         struct irpc_bh_raw_call_state *state;
1068         bool ok;
1069         struct irpc_header header;
1070         struct ndr_push *ndr;
1071         NTSTATUS status;
1072         enum ndr_err_code ndr_err;
1073
1074         req = tevent_req_create(mem_ctx, &state,
1075                                 struct irpc_bh_raw_call_state);
1076         if (req == NULL) {
1077                 return NULL;
1078         }
1079         state->opnum = opnum;
1080         state->in_data.data = discard_const_p(uint8_t, in_data);
1081         state->in_data.length = in_length;
1082
1083         ok = irpc_bh_is_connected(h);
1084         if (!ok) {
1085                 tevent_req_nterror(req, NT_STATUS_INVALID_CONNECTION);
1086                 return tevent_req_post(req, ev);
1087         }
1088
1089         state->irpc = talloc_zero(state, struct irpc_request);
1090         if (tevent_req_nomem(state->irpc, req)) {
1091                 return tevent_req_post(req, ev);
1092         }
1093
1094         state->irpc->msg_ctx  = hs->msg_ctx;
1095         state->irpc->callid   = idr_get_new(hs->msg_ctx->idr,
1096                                             state->irpc, UINT16_MAX);
1097         if (state->irpc->callid == -1) {
1098                 tevent_req_nterror(req, NT_STATUS_INSUFFICIENT_RESOURCES);
1099                 return tevent_req_post(req, ev);
1100         }
1101         state->irpc->incoming.handler = irpc_bh_raw_call_incoming_handler;
1102         state->irpc->incoming.private_data = req;
1103
1104         talloc_set_destructor(state->irpc, irpc_destructor);
1105
1106         /* setup the header */
1107         header.uuid = hs->table->syntax_id.uuid;
1108
1109         header.if_version = hs->table->syntax_id.if_version;
1110         header.callid     = state->irpc->callid;
1111         header.callnum    = state->opnum;
1112         header.flags      = 0;
1113         header.status     = NT_STATUS_OK;
1114
1115         /* construct the irpc packet */
1116         ndr = ndr_push_init_ctx(state->irpc);
1117         if (tevent_req_nomem(ndr, req)) {
1118                 return tevent_req_post(req, ev);
1119         }
1120
1121         ndr_err = ndr_push_irpc_header(ndr, NDR_SCALARS|NDR_BUFFERS, &header);
1122         status = ndr_map_error2ntstatus(ndr_err);
1123         if (!NT_STATUS_IS_OK(status)) {
1124                 tevent_req_nterror(req, status);
1125                 return tevent_req_post(req, ev);
1126         }
1127
1128         ndr_err = ndr_push_bytes(ndr, in_data, in_length);
1129         status = ndr_map_error2ntstatus(ndr_err);
1130         if (!NT_STATUS_IS_OK(status)) {
1131                 tevent_req_nterror(req, status);
1132                 return tevent_req_post(req, ev);
1133         }
1134
1135         /* and send it */
1136         state->in_packet = ndr_push_blob(ndr);
1137         status = messaging_send(hs->msg_ctx, hs->server_id,
1138                                 MSG_IRPC, &state->in_packet);
1139         if (!NT_STATUS_IS_OK(status)) {
1140                 tevent_req_nterror(req, status);
1141                 return tevent_req_post(req, ev);
1142         }
1143
1144         if (hs->timeout != IRPC_CALL_TIMEOUT_INF) {
1145                 /* set timeout-callback in case caller wants that */
1146                 ok = tevent_req_set_endtime(req, ev, timeval_current_ofs(hs->timeout, 0));
1147                 if (!ok) {
1148                         return tevent_req_post(req, ev);
1149                 }
1150         }
1151
1152         return req;
1153 }
1154
1155 static void irpc_bh_raw_call_incoming_handler(struct irpc_request *irpc,
1156                                               struct irpc_message *m)
1157 {
1158         struct tevent_req *req =
1159                 talloc_get_type_abort(irpc->incoming.private_data,
1160                 struct tevent_req);
1161         struct irpc_bh_raw_call_state *state =
1162                 tevent_req_data(req,
1163                 struct irpc_bh_raw_call_state);
1164
1165         talloc_steal(state, m);
1166
1167         if (!NT_STATUS_IS_OK(m->header.status)) {
1168                 tevent_req_nterror(req, m->header.status);
1169                 return;
1170         }
1171
1172         state->out_data = data_blob_talloc(state,
1173                 m->ndr->data + m->ndr->offset,
1174                 m->ndr->data_size - m->ndr->offset);
1175         if ((m->ndr->data_size - m->ndr->offset) > 0 && !state->out_data.data) {
1176                 tevent_req_nomem(NULL, req);
1177                 return;
1178         }
1179
1180         tevent_req_done(req);
1181 }
1182
1183 static NTSTATUS irpc_bh_raw_call_recv(struct tevent_req *req,
1184                                         TALLOC_CTX *mem_ctx,
1185                                         uint8_t **out_data,
1186                                         size_t *out_length,
1187                                         uint32_t *out_flags)
1188 {
1189         struct irpc_bh_raw_call_state *state =
1190                 tevent_req_data(req,
1191                 struct irpc_bh_raw_call_state);
1192         NTSTATUS status;
1193
1194         if (tevent_req_is_nterror(req, &status)) {
1195                 tevent_req_received(req);
1196                 return status;
1197         }
1198
1199         *out_data = talloc_move(mem_ctx, &state->out_data.data);
1200         *out_length = state->out_data.length;
1201         *out_flags = 0;
1202         tevent_req_received(req);
1203         return NT_STATUS_OK;
1204 }
1205
1206 struct irpc_bh_disconnect_state {
1207         uint8_t _dummy;
1208 };
1209
1210 static struct tevent_req *irpc_bh_disconnect_send(TALLOC_CTX *mem_ctx,
1211                                                 struct tevent_context *ev,
1212                                                 struct dcerpc_binding_handle *h)
1213 {
1214         struct irpc_bh_state *hs = dcerpc_binding_handle_data(h,
1215                                      struct irpc_bh_state);
1216         struct tevent_req *req;
1217         struct irpc_bh_disconnect_state *state;
1218         bool ok;
1219
1220         req = tevent_req_create(mem_ctx, &state,
1221                                 struct irpc_bh_disconnect_state);
1222         if (req == NULL) {
1223                 return NULL;
1224         }
1225
1226         ok = irpc_bh_is_connected(h);
1227         if (!ok) {
1228                 tevent_req_nterror(req, NT_STATUS_INVALID_CONNECTION);
1229                 return tevent_req_post(req, ev);
1230         }
1231
1232         hs->msg_ctx = NULL;
1233
1234         tevent_req_done(req);
1235         return tevent_req_post(req, ev);
1236 }
1237
1238 static NTSTATUS irpc_bh_disconnect_recv(struct tevent_req *req)
1239 {
1240         NTSTATUS status;
1241
1242         if (tevent_req_is_nterror(req, &status)) {
1243                 tevent_req_received(req);
1244                 return status;
1245         }
1246
1247         tevent_req_received(req);
1248         return NT_STATUS_OK;
1249 }
1250
1251 static bool irpc_bh_ref_alloc(struct dcerpc_binding_handle *h)
1252 {
1253         return true;
1254 }
1255
1256 static const struct dcerpc_binding_handle_ops irpc_bh_ops = {
1257         .name                   = "wbint",
1258         .is_connected           = irpc_bh_is_connected,
1259         .set_timeout            = irpc_bh_set_timeout,
1260         .raw_call_send          = irpc_bh_raw_call_send,
1261         .raw_call_recv          = irpc_bh_raw_call_recv,
1262         .disconnect_send        = irpc_bh_disconnect_send,
1263         .disconnect_recv        = irpc_bh_disconnect_recv,
1264
1265         .ref_alloc              = irpc_bh_ref_alloc,
1266 };
1267
1268 /* initialise a irpc binding handle */
1269 struct dcerpc_binding_handle *irpc_binding_handle(TALLOC_CTX *mem_ctx,
1270                                         struct messaging_context *msg_ctx,
1271                                         struct server_id server_id,
1272                                         const struct ndr_interface_table *table)
1273 {
1274         struct dcerpc_binding_handle *h;
1275         struct irpc_bh_state *hs;
1276
1277         h = dcerpc_binding_handle_create(mem_ctx,
1278                                          &irpc_bh_ops,
1279                                          NULL,
1280                                          table,
1281                                          &hs,
1282                                          struct irpc_bh_state,
1283                                          __location__);
1284         if (h == NULL) {
1285                 return NULL;
1286         }
1287         hs->msg_ctx = msg_ctx;
1288         hs->server_id = server_id;
1289         hs->table = table;
1290         hs->timeout = IRPC_CALL_TIMEOUT;
1291
1292         dcerpc_binding_handle_set_sync_ev(h, msg_ctx->event.ev);
1293
1294         return h;
1295 }
1296
1297 struct dcerpc_binding_handle *irpc_binding_handle_by_name(TALLOC_CTX *mem_ctx,
1298                                         struct messaging_context *msg_ctx,
1299                                         const char *dest_task,
1300                                         const struct ndr_interface_table *table)
1301 {
1302         struct dcerpc_binding_handle *h;
1303         struct server_id *sids;
1304         struct server_id sid;
1305
1306         /* find the server task */
1307         sids = irpc_servers_byname(msg_ctx, mem_ctx, dest_task);
1308         if (sids == NULL) {
1309                 errno = EADDRNOTAVAIL;
1310                 return NULL;
1311         }
1312         if (sids[0].id == 0) {
1313                 talloc_free(sids);
1314                 errno = EADDRNOTAVAIL;
1315                 return NULL;
1316         }
1317         sid = sids[0];
1318         talloc_free(sids);
1319
1320         h = irpc_binding_handle(mem_ctx, msg_ctx,
1321                                 sid, table);
1322         if (h == NULL) {
1323                 return NULL;
1324         }
1325
1326         return h;
1327 }