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