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