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