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