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