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