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