Use the new directory_create_or_exist_strict() function.
[nivanova/samba-autobuild/.git] / source3 / rpc_server / rpc_server.c
1 /*
2    Unix SMB/Netbios implementation.
3    Generic infrstructure for RPC Daemons
4    Copyright (C) Simo Sorce 2010
5    Copyright (C) Andrew Bartlett 2011
6    Copyright (C) Andreas Schneider 2011
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 "rpc_server/rpc_pipes.h"
24 #include "rpc_server/rpc_server.h"
25 #include "rpc_server/rpc_config.h"
26 #include "rpc_dce.h"
27 #include "librpc/gen_ndr/netlogon.h"
28 #include "librpc/gen_ndr/auth.h"
29 #include "lib/tsocket/tsocket.h"
30 #include "libcli/named_pipe_auth/npa_tstream.h"
31 #include "../auth/auth_sam_reply.h"
32 #include "auth.h"
33 #include "rpc_server/rpc_ncacn_np.h"
34 #include "rpc_server/srv_pipe_hnd.h"
35 #include "rpc_server/srv_pipe.h"
36
37 #define SERVER_TCP_LOW_PORT  1024
38 #define SERVER_TCP_HIGH_PORT 1300
39
40 static NTSTATUS auth_anonymous_session_info(TALLOC_CTX *mem_ctx,
41                                             struct auth_session_info **session_info)
42 {
43         NTSTATUS status;
44
45         status = make_session_info_guest(mem_ctx, session_info);
46         if (!NT_STATUS_IS_OK(status)) {
47                 return status;
48         }
49
50         return NT_STATUS_OK;
51 }
52
53 /* Creates a pipes_struct and initializes it with the information
54  * sent from the client */
55 static int make_server_pipes_struct(TALLOC_CTX *mem_ctx,
56                                     struct messaging_context *msg_ctx,
57                                     const char *pipe_name,
58                                     enum dcerpc_transport_t transport,
59                                     bool ncalrpc_as_system,
60                                     const struct tsocket_address *local_address,
61                                     const struct tsocket_address *remote_address,
62                                     struct auth_session_info *session_info,
63                                     struct pipes_struct **_p,
64                                     int *perrno)
65 {
66         struct pipes_struct *p;
67         int ret;
68
69         ret = make_base_pipes_struct(mem_ctx, msg_ctx, pipe_name,
70                                      transport, RPC_LITTLE_ENDIAN,
71                                      ncalrpc_as_system,
72                                      remote_address, local_address, &p);
73         if (ret) {
74                 *perrno = ret;
75                 return -1;
76         }
77
78         if (session_info->unix_token && session_info->unix_info && session_info->security_token) {
79                 /* Don't call create_local_token(), we already have the full details here */
80                 p->session_info = talloc_steal(p, session_info);
81
82         } else {
83                 DEBUG(0, ("Supplied session_info in make_server_pipes_struct was incomplete!"));
84                 *perrno = EINVAL;
85                 return -1;
86         }
87
88         *_p = p;
89         return 0;
90 }
91
92 /* Start listening on the appropriate unix socket and setup all is needed to
93  * dispatch requests to the pipes rpc implementation */
94
95 struct dcerpc_ncacn_listen_state {
96         struct ndr_syntax_id syntax_id;
97
98         int fd;
99         union {
100                 char *name;
101                 uint16_t port;
102         } ep;
103
104         struct tevent_context *ev_ctx;
105         struct messaging_context *msg_ctx;
106         dcerpc_ncacn_disconnect_fn disconnect_fn;
107 };
108
109 static void named_pipe_listener(struct tevent_context *ev,
110                                 struct tevent_fd *fde,
111                                 uint16_t flags,
112                                 void *private_data);
113
114 int create_named_pipe_socket(const char *pipe_name)
115 {
116         char *np_dir = NULL;
117         int fd = -1;
118
119         /*
120          * As lp_ncalrpc_dir() should have 0755, but
121          * lp_ncalrpc_dir()/np should have 0700, we need to
122          * create lp_ncalrpc_dir() first.
123          */
124         if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
125                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
126                           lp_ncalrpc_dir(), strerror(errno)));
127                 goto out;
128         }
129
130         np_dir = talloc_asprintf(talloc_tos(), "%s/np", lp_ncalrpc_dir());
131         if (!np_dir) {
132                 DEBUG(0, ("Out of memory\n"));
133                 goto out;
134         }
135
136         if (!directory_create_or_exist_strict(np_dir, geteuid(), 0700)) {
137                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
138                           np_dir, strerror(errno)));
139                 goto out;
140         }
141
142         fd = create_pipe_sock(np_dir, pipe_name, 0700);
143         if (fd == -1) {
144                 DEBUG(0, ("Failed to create pipe socket! [%s/%s]\n",
145                           np_dir, pipe_name));
146                 goto out;
147         }
148
149         DEBUG(10, ("Openened pipe socket fd %d for %s\n", fd, pipe_name));
150
151 out:
152         talloc_free(np_dir);
153         return fd;
154 }
155
156 bool setup_named_pipe_socket(const char *pipe_name,
157                              struct tevent_context *ev_ctx,
158                              struct messaging_context *msg_ctx)
159 {
160         struct dcerpc_ncacn_listen_state *state;
161         struct tevent_fd *fde;
162         int rc;
163
164         state = talloc(ev_ctx, struct dcerpc_ncacn_listen_state);
165         if (!state) {
166                 DEBUG(0, ("Out of memory\n"));
167                 return false;
168         }
169         state->ep.name = talloc_strdup(state, pipe_name);
170         if (state->ep.name == NULL) {
171                 DEBUG(0, ("Out of memory\n"));
172                 goto out;
173         }
174         state->fd = create_named_pipe_socket(pipe_name);
175         if (state->fd == -1) {
176                 goto out;
177         }
178
179         rc = listen(state->fd, 5);
180         if (rc < 0) {
181                 DEBUG(0, ("Failed to listen on pipe socket %s: %s\n",
182                           pipe_name, strerror(errno)));
183                 goto out;
184         }
185
186         state->ev_ctx = ev_ctx;
187         state->msg_ctx = msg_ctx;
188
189         DEBUG(10, ("Openened pipe socket fd %d for %s\n",
190                    state->fd, pipe_name));
191
192         fde = tevent_add_fd(ev_ctx,
193                             state, state->fd, TEVENT_FD_READ,
194                             named_pipe_listener, state);
195         if (!fde) {
196                 DEBUG(0, ("Failed to add event handler!\n"));
197                 goto out;
198         }
199
200         tevent_fd_set_auto_close(fde);
201         return true;
202
203 out:
204         if (state->fd != -1) {
205                 close(state->fd);
206         }
207         TALLOC_FREE(state);
208         return false;
209 }
210
211 static void named_pipe_listener(struct tevent_context *ev,
212                                 struct tevent_fd *fde,
213                                 uint16_t flags,
214                                 void *private_data)
215 {
216         struct dcerpc_ncacn_listen_state *state =
217                         talloc_get_type_abort(private_data,
218                                               struct dcerpc_ncacn_listen_state);
219         struct sockaddr_un sunaddr;
220         socklen_t len;
221         int sd = -1;
222
223         /* TODO: should we have a limit to the number of clients ? */
224
225         len = sizeof(sunaddr);
226
227         sd = accept(state->fd,
228                     (struct sockaddr *)(void *)&sunaddr, &len);
229
230         if (sd == -1) {
231                 if (errno != EINTR) {
232                         DEBUG(6, ("Failed to get a valid socket [%s]\n",
233                                   strerror(errno)));
234                 }
235                 return;
236         }
237
238         DEBUG(6, ("Accepted socket %d\n", sd));
239
240         named_pipe_accept_function(state->ev_ctx,
241                                    state->msg_ctx,
242                                    state->ep.name,
243                                    sd, NULL, 0);
244 }
245
246
247 /* This is the core of the rpc server.
248  * Accepts connections from clients and process requests using the appropriate
249  * dispatcher table. */
250
251 struct named_pipe_client {
252         const char *pipe_name;
253
254         struct tevent_context *ev;
255         struct messaging_context *msg_ctx;
256
257         uint16_t file_type;
258         uint16_t device_state;
259         uint64_t allocation_size;
260
261         struct tstream_context *tstream;
262
263         struct tsocket_address *client;
264         char *client_name;
265         struct tsocket_address *server;
266         char *server_name;
267
268         struct auth_session_info *session_info;
269
270         struct pipes_struct *p;
271
272         struct tevent_queue *write_queue;
273
274         struct iovec *iov;
275         size_t count;
276
277         named_pipe_termination_fn *term_fn;
278         void *private_data;
279 };
280
281 static int named_pipe_destructor(struct named_pipe_client *npc)
282 {
283         if (npc->term_fn) {
284                 npc->term_fn(npc->private_data);
285         }
286         return 0;
287 }
288
289 static void named_pipe_accept_done(struct tevent_req *subreq);
290
291 void named_pipe_accept_function(struct tevent_context *ev_ctx,
292                                 struct messaging_context *msg_ctx,
293                                 const char *pipe_name, int fd,
294                                 named_pipe_termination_fn *term_fn,
295                                 void *private_data)
296 {
297         struct named_pipe_client *npc;
298         struct tstream_context *plain;
299         struct tevent_req *subreq;
300         int ret;
301
302         npc = talloc_zero(ev_ctx, struct named_pipe_client);
303         if (!npc) {
304                 DEBUG(0, ("Out of memory!\n"));
305                 close(fd);
306                 return;
307         }
308
309         npc->pipe_name = talloc_strdup(npc, pipe_name);
310         if (npc->pipe_name == NULL) {
311                 DEBUG(0, ("Out of memory!\n"));
312                 TALLOC_FREE(npc);
313                 close(fd);
314                 return;
315         }
316         npc->ev = ev_ctx;
317         npc->msg_ctx = msg_ctx;
318         npc->term_fn = term_fn;
319         npc->private_data = private_data;
320
321         talloc_set_destructor(npc, named_pipe_destructor);
322
323         /* make sure socket is in NON blocking state */
324         ret = set_blocking(fd, false);
325         if (ret != 0) {
326                 DEBUG(2, ("Failed to make socket non-blocking\n"));
327                 TALLOC_FREE(npc);
328                 close(fd);
329                 return;
330         }
331
332         ret = tstream_bsd_existing_socket(npc, fd, &plain);
333         if (ret != 0) {
334                 DEBUG(2, ("Failed to create tstream socket\n"));
335                 TALLOC_FREE(npc);
336                 close(fd);
337                 return;
338         }
339
340         npc->file_type = FILE_TYPE_MESSAGE_MODE_PIPE;
341         npc->device_state = 0xff | 0x0400 | 0x0100;
342         npc->allocation_size = 4096;
343
344         subreq = tstream_npa_accept_existing_send(npc, npc->ev, plain,
345                                                   npc->file_type,
346                                                   npc->device_state,
347                                                   npc->allocation_size);
348         if (!subreq) {
349                 DEBUG(2, ("Failed to start async accept procedure\n"));
350                 TALLOC_FREE(npc);
351                 close(fd);
352                 return;
353         }
354         tevent_req_set_callback(subreq, named_pipe_accept_done, npc);
355 }
356
357 static void named_pipe_packet_process(struct tevent_req *subreq);
358 static void named_pipe_packet_done(struct tevent_req *subreq);
359
360 static void named_pipe_accept_done(struct tevent_req *subreq)
361 {
362         struct auth_session_info_transport *session_info_transport;
363         struct named_pipe_client *npc =
364                 tevent_req_callback_data(subreq, struct named_pipe_client);
365         int error;
366         int ret;
367
368         ret = tstream_npa_accept_existing_recv(subreq, &error, npc,
369                                                 &npc->tstream,
370                                                 &npc->client,
371                                                 &npc->client_name,
372                                                 &npc->server,
373                                                 &npc->server_name,
374                                                 &session_info_transport);
375
376         npc->session_info = talloc_move(npc, &session_info_transport->session_info);
377
378         TALLOC_FREE(subreq);
379         if (ret != 0) {
380                 DEBUG(2, ("Failed to accept named pipe connection! (%s)\n",
381                           strerror(error)));
382                 TALLOC_FREE(npc);
383                 return;
384         }
385
386         ret = make_server_pipes_struct(npc,
387                                        npc->msg_ctx,
388                                        npc->pipe_name, NCACN_NP,
389                                         false, npc->server, npc->client, npc->session_info,
390                                         &npc->p, &error);
391         if (ret != 0) {
392                 DEBUG(2, ("Failed to create pipes_struct! (%s)\n",
393                           strerror(error)));
394                 goto fail;
395         }
396
397         npc->write_queue = tevent_queue_create(npc, "np_server_write_queue");
398         if (!npc->write_queue) {
399                 DEBUG(2, ("Failed to set up write queue!\n"));
400                 goto fail;
401         }
402
403         /* And now start receiving and processing packets */
404         subreq = dcerpc_read_ncacn_packet_send(npc, npc->ev, npc->tstream);
405         if (!subreq) {
406                 DEBUG(2, ("Failed to start receving packets\n"));
407                 goto fail;
408         }
409         tevent_req_set_callback(subreq, named_pipe_packet_process, npc);
410         return;
411
412 fail:
413         DEBUG(2, ("Fatal error. Terminating client(%s) connection!\n",
414                   npc->client_name));
415         /* terminate client connection */
416         talloc_free(npc);
417         return;
418 }
419
420 static void named_pipe_packet_process(struct tevent_req *subreq)
421 {
422         struct named_pipe_client *npc =
423                 tevent_req_callback_data(subreq, struct named_pipe_client);
424         struct _output_data *out = &npc->p->out_data;
425         DATA_BLOB recv_buffer = data_blob_null;
426         struct ncacn_packet *pkt;
427         NTSTATUS status;
428         ssize_t data_left;
429         ssize_t data_used;
430         char *data;
431         uint32_t to_send;
432         size_t i;
433         bool ok;
434
435         status = dcerpc_read_ncacn_packet_recv(subreq, npc, &pkt, &recv_buffer);
436         TALLOC_FREE(subreq);
437         if (!NT_STATUS_IS_OK(status)) {
438                 goto fail;
439         }
440
441         data_left = recv_buffer.length;
442         data = (char *)recv_buffer.data;
443
444         while (data_left) {
445
446                 data_used = process_incoming_data(npc->p, data, data_left);
447                 if (data_used < 0) {
448                         DEBUG(3, ("Failed to process dceprc request!\n"));
449                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
450                         goto fail;
451                 }
452
453                 data_left -= data_used;
454                 data += data_used;
455         }
456
457         /* Do not leak this buffer, npc is a long lived context */
458         talloc_free(recv_buffer.data);
459         talloc_free(pkt);
460
461         /* this is needed because of the way DCERPC Binds work in
462          * the RPC marshalling code */
463         to_send = out->frag.length - out->current_pdu_sent;
464         if (to_send > 0) {
465
466                 npc->iov = talloc_zero(npc, struct iovec);
467                 if (!npc->iov) {
468                         status = NT_STATUS_NO_MEMORY;
469                         goto fail;
470                 }
471                 npc->count = 1;
472
473                 npc->iov[0].iov_base = out->frag.data
474                                         + out->current_pdu_sent;
475                 npc->iov[0].iov_len = to_send;
476
477                 out->current_pdu_sent += to_send;
478         }
479
480         /* this condition is false for bind packets, or when we haven't
481          * yet got a full request, and need to wait for more data from
482          * the client */
483         while (out->data_sent_length < out->rdata.length) {
484
485                 ok = create_next_pdu(npc->p);
486                 if (!ok) {
487                         DEBUG(3, ("Failed to create next PDU!\n"));
488                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
489                         goto fail;
490                 }
491
492                 npc->iov = talloc_realloc(npc, npc->iov,
493                                             struct iovec, npc->count + 1);
494                 if (!npc->iov) {
495                         status = NT_STATUS_NO_MEMORY;
496                         goto fail;
497                 }
498
499                 npc->iov[npc->count].iov_base = out->frag.data;
500                 npc->iov[npc->count].iov_len = out->frag.length;
501
502                 npc->count++;
503         }
504
505         /* we still don't have a complete request, go back and wait for more
506          * data */
507         if (npc->count == 0) {
508                 /* Wait for the next packet */
509                 subreq = dcerpc_read_ncacn_packet_send(npc, npc->ev, npc->tstream);
510                 if (!subreq) {
511                         DEBUG(2, ("Failed to start receving packets\n"));
512                         status = NT_STATUS_NO_MEMORY;
513                         goto fail;
514                 }
515                 tevent_req_set_callback(subreq, named_pipe_packet_process, npc);
516                 return;
517         }
518
519         DEBUG(10, ("Sending %u fragments in a total of %u bytes\n",
520                    (unsigned int)npc->count,
521                    (unsigned int)npc->p->out_data.data_sent_length));
522
523         for (i = 0; i < npc->count; i++) {
524                 DEBUG(10, ("Sending PDU number: %d, PDU Length: %u\n",
525                           (unsigned int)i,
526                           (unsigned int)npc->iov[i].iov_len));
527                 dump_data(11, (const uint8_t *)npc->iov[i].iov_base,
528                                 npc->iov[i].iov_len);
529
530                 subreq = tstream_writev_queue_send(npc,
531                                                    npc->ev,
532                                                    npc->tstream,
533                                                    npc->write_queue,
534                                                    (npc->iov + i),
535                                                    1);
536                 if (!subreq) {
537                         DEBUG(2, ("Failed to send packet\n"));
538                         status = NT_STATUS_NO_MEMORY;
539                         goto fail;
540                 }
541                 tevent_req_set_callback(subreq, named_pipe_packet_done, npc);
542         }
543
544         return;
545
546 fail:
547         DEBUG(2, ("Fatal error(%s). "
548                   "Terminating client(%s) connection!\n",
549                   nt_errstr(status), npc->client_name));
550         /* terminate client connection */
551         talloc_free(npc);
552         return;
553 }
554
555 static void named_pipe_packet_done(struct tevent_req *subreq)
556 {
557         struct named_pipe_client *npc =
558                 tevent_req_callback_data(subreq, struct named_pipe_client);
559         int sys_errno;
560         int ret;
561
562         ret = tstream_writev_queue_recv(subreq, &sys_errno);
563         TALLOC_FREE(subreq);
564         if (ret == -1) {
565                 DEBUG(2, ("Writev failed!\n"));
566                 goto fail;
567         }
568
569         if (tevent_queue_length(npc->write_queue) > 0) {
570                 return;
571         }
572
573         /* clear out any data that may have been left around */
574         npc->count = 0;
575         TALLOC_FREE(npc->iov);
576         data_blob_free(&npc->p->in_data.data);
577         data_blob_free(&npc->p->out_data.frag);
578         data_blob_free(&npc->p->out_data.rdata);
579
580         talloc_free_children(npc->p->mem_ctx);
581
582         /* Wait for the next packet */
583         subreq = dcerpc_read_ncacn_packet_send(npc, npc->ev, npc->tstream);
584         if (!subreq) {
585                 DEBUG(2, ("Failed to start receving packets\n"));
586                 sys_errno = ENOMEM;
587                 goto fail;
588         }
589         tevent_req_set_callback(subreq, named_pipe_packet_process, npc);
590         return;
591
592 fail:
593         DEBUG(2, ("Fatal error(%s). "
594                   "Terminating client(%s) connection!\n",
595                   strerror(sys_errno), npc->client_name));
596         /* terminate client connection */
597         talloc_free(npc);
598         return;
599 }
600
601 /********************************************************************
602  * Start listening on the tcp/ip socket
603  ********************************************************************/
604
605 static void dcerpc_ncacn_tcpip_listener(struct tevent_context *ev,
606                                         struct tevent_fd *fde,
607                                         uint16_t flags,
608                                         void *private_data);
609
610 int create_tcpip_socket(const struct sockaddr_storage *ifss, uint16_t *port)
611 {
612         int fd = -1;
613
614         if (*port == 0) {
615                 uint16_t i;
616
617                 for (i = SERVER_TCP_LOW_PORT; i <= SERVER_TCP_HIGH_PORT; i++) {
618                         fd = open_socket_in(SOCK_STREAM,
619                                             i,
620                                             0,
621                                             ifss,
622                                             false);
623                         if (fd > 0) {
624                                 *port = i;
625                                 break;
626                         }
627                 }
628         } else {
629                 fd = open_socket_in(SOCK_STREAM,
630                                     *port,
631                                     0,
632                                     ifss,
633                                     true);
634         }
635         if (fd == -1) {
636                 DEBUG(0, ("Failed to create socket on port %u!\n", *port));
637                 return -1;
638         }
639
640         DEBUG(10, ("Opened tcpip socket fd %d for port %u\n", fd, *port));
641
642         return fd;
643 }
644
645 uint16_t setup_dcerpc_ncacn_tcpip_socket(struct tevent_context *ev_ctx,
646                                          struct messaging_context *msg_ctx,
647                                          const struct sockaddr_storage *ifss,
648                                          uint16_t port)
649 {
650         struct dcerpc_ncacn_listen_state *state;
651         struct tevent_fd *fde;
652         int rc;
653
654         state = talloc(ev_ctx, struct dcerpc_ncacn_listen_state);
655         if (state == NULL) {
656                 DEBUG(0, ("setup_dcerpc_ncacn_tcpip_socket: Out of memory\n"));
657                 return 0;
658         }
659
660         state->fd = -1;
661         state->ep.port = port;
662         state->disconnect_fn = NULL;
663
664         state->fd = create_tcpip_socket(ifss, &state->ep.port);
665         if (state->fd == -1) {
666                 goto out;
667         }
668
669         state->ev_ctx = ev_ctx;
670         state->msg_ctx = msg_ctx;
671
672         /* ready to listen */
673         set_socket_options(state->fd, "SO_KEEPALIVE");
674         set_socket_options(state->fd, lp_socket_options());
675
676         /* Set server socket to non-blocking for the accept. */
677         set_blocking(state->fd, false);
678
679         rc = listen(state->fd, SMBD_LISTEN_BACKLOG);
680         if (rc == -1) {
681                 DEBUG(0,("setup_tcpip_socket: listen - %s\n", strerror(errno)));
682                 goto out;
683         }
684
685         DEBUG(10, ("setup_tcpip_socket: openened socket fd %d for port %u\n",
686                    state->fd, state->ep.port));
687
688         fde = tevent_add_fd(state->ev_ctx,
689                             state,
690                             state->fd,
691                             TEVENT_FD_READ,
692                             dcerpc_ncacn_tcpip_listener,
693                             state);
694         if (fde == NULL) {
695                 DEBUG(0, ("setup_tcpip_socket: Failed to add event handler!\n"));
696                 goto out;
697         }
698
699         tevent_fd_set_auto_close(fde);
700
701         return state->ep.port;
702 out:
703         if (state->fd != -1) {
704                 close(state->fd);
705         }
706         TALLOC_FREE(state);
707
708         return 0;
709 }
710
711 static void dcerpc_ncacn_tcpip_listener(struct tevent_context *ev,
712                                         struct tevent_fd *fde,
713                                         uint16_t flags,
714                                         void *private_data)
715 {
716         struct dcerpc_ncacn_listen_state *state =
717                         talloc_get_type_abort(private_data,
718                                               struct dcerpc_ncacn_listen_state);
719         struct tsocket_address *cli_addr = NULL;
720         struct tsocket_address *srv_addr = NULL;
721         struct sockaddr_storage addr;
722         socklen_t in_addrlen = sizeof(addr);
723         int s = -1;
724         int rc;
725
726         s = accept(state->fd, (struct sockaddr *)(void *) &addr, &in_addrlen);
727         if (s == -1) {
728                 if (errno != EINTR) {
729                         DEBUG(0,("tcpip_listener accept: %s\n",
730                                  strerror(errno)));
731                 }
732                 return;
733         }
734
735         rc = tsocket_address_bsd_from_sockaddr(state,
736                                                (struct sockaddr *)(void *) &addr,
737                                                in_addrlen,
738                                                &cli_addr);
739         if (rc < 0) {
740                 close(s);
741                 return;
742         }
743
744         rc = getsockname(s, (struct sockaddr *)(void *) &addr, &in_addrlen);
745         if (rc < 0) {
746                 close(s);
747                 return;
748         }
749
750         rc = tsocket_address_bsd_from_sockaddr(state,
751                                                (struct sockaddr *)(void *) &addr,
752                                                in_addrlen,
753                                                &srv_addr);
754         if (rc < 0) {
755                 close(s);
756                 return;
757         }
758
759         DEBUG(6, ("tcpip_listener: Accepted socket %d\n", s));
760
761         dcerpc_ncacn_accept(state->ev_ctx,
762                             state->msg_ctx,
763                             NCACN_IP_TCP,
764                             NULL,
765                             cli_addr,
766                             srv_addr,
767                             s,
768                             NULL);
769 }
770
771 /********************************************************************
772  * Start listening on the ncalrpc socket
773  ********************************************************************/
774
775 static void dcerpc_ncalrpc_listener(struct tevent_context *ev,
776                                     struct tevent_fd *fde,
777                                     uint16_t flags,
778                                     void *private_data);
779
780 int create_dcerpc_ncalrpc_socket(const char *name)
781 {
782         int fd = -1;
783
784         if (name == NULL) {
785                 name = "DEFAULT";
786         }
787
788         if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
789                 DEBUG(0, ("Failed to create ncalrpc directory %s - %s\n",
790                           lp_ncalrpc_dir(), strerror(errno)));
791                 return -1;
792         }
793
794         fd = create_pipe_sock(lp_ncalrpc_dir(), name, 0755);
795         if (fd == -1) {
796                 DEBUG(0, ("Failed to create ncalrpc socket! [%s/%s]\n",
797                           lp_ncalrpc_dir(), name));
798                 return -1;
799         }
800
801         DEBUG(10, ("Openened ncalrpc socket fd %d for %s\n", fd, name));
802
803         return fd;
804 }
805
806 bool setup_dcerpc_ncalrpc_socket(struct tevent_context *ev_ctx,
807                                  struct messaging_context *msg_ctx,
808                                  const char *name,
809                                  dcerpc_ncacn_disconnect_fn fn)
810 {
811         struct dcerpc_ncacn_listen_state *state;
812         struct tevent_fd *fde;
813         int rc;
814
815         state = talloc(ev_ctx, struct dcerpc_ncacn_listen_state);
816         if (state == NULL) {
817                 DEBUG(0, ("Out of memory\n"));
818                 return false;
819         }
820
821         state->fd = -1;
822         state->disconnect_fn = fn;
823
824         if (name == NULL) {
825                 name = "DEFAULT";
826         }
827
828         state->ep.name = talloc_strdup(state, name);
829         if (state->ep.name == NULL) {
830                 DEBUG(0, ("Out of memory\n"));
831                 talloc_free(state);
832                 return false;
833         }
834
835         state->fd = create_dcerpc_ncalrpc_socket(name);
836         if (state->fd == -1) {
837                 goto out;
838         }
839
840         rc = listen(state->fd, 5);
841         if (rc < 0) {
842                 DEBUG(0, ("Failed to listen on ncalrpc socket %s: %s\n",
843                           name, strerror(errno)));
844                 goto out;
845         }
846
847         state->ev_ctx = ev_ctx;
848         state->msg_ctx = msg_ctx;
849
850         /* Set server socket to non-blocking for the accept. */
851         set_blocking(state->fd, false);
852
853         fde = tevent_add_fd(state->ev_ctx,
854                             state,
855                             state->fd,
856                             TEVENT_FD_READ,
857                             dcerpc_ncalrpc_listener,
858                             state);
859         if (fde == NULL) {
860                 DEBUG(0, ("Failed to add event handler for ncalrpc!\n"));
861                 goto out;
862         }
863
864         tevent_fd_set_auto_close(fde);
865
866         return true;
867 out:
868         if (state->fd != -1) {
869                 close(state->fd);
870         }
871         TALLOC_FREE(state);
872
873         return 0;
874 }
875
876 static void dcerpc_ncalrpc_listener(struct tevent_context *ev,
877                                         struct tevent_fd *fde,
878                                         uint16_t flags,
879                                         void *private_data)
880 {
881         struct dcerpc_ncacn_listen_state *state =
882                         talloc_get_type_abort(private_data,
883                                               struct dcerpc_ncacn_listen_state);
884         struct tsocket_address *cli_addr = NULL;
885         struct sockaddr_un sunaddr;
886         struct sockaddr *addr = (struct sockaddr *)(void *)&sunaddr;
887         socklen_t len = sizeof(sunaddr);
888         int sd = -1;
889         int rc;
890
891         ZERO_STRUCT(sunaddr);
892
893         sd = accept(state->fd, addr, &len);
894         if (sd == -1) {
895                 if (errno != EINTR) {
896                         DEBUG(0, ("ncalrpc accept() failed: %s\n", strerror(errno)));
897                 }
898                 return;
899         }
900
901         rc = tsocket_address_bsd_from_sockaddr(state,
902                                                addr, len,
903                                                &cli_addr);
904         if (rc < 0) {
905                 close(sd);
906                 return;
907         }
908
909         DEBUG(10, ("Accepted ncalrpc socket %d\n", sd));
910
911         dcerpc_ncacn_accept(state->ev_ctx,
912                             state->msg_ctx,
913                             NCALRPC,
914                             state->ep.name,
915                             cli_addr, NULL, sd,
916                             state->disconnect_fn);
917 }
918
919 struct dcerpc_ncacn_conn {
920         enum dcerpc_transport_t transport;
921
922         int sock;
923
924         struct pipes_struct *p;
925         dcerpc_ncacn_disconnect_fn disconnect_fn;
926
927         struct tevent_context *ev_ctx;
928         struct messaging_context *msg_ctx;
929
930         struct tstream_context *tstream;
931         struct tevent_queue *send_queue;
932
933         struct tsocket_address *client;
934         char *client_name;
935         struct tsocket_address *server;
936         char *server_name;
937         struct auth_session_info *session_info;
938
939         struct iovec *iov;
940         size_t count;
941 };
942
943 static void dcerpc_ncacn_packet_process(struct tevent_req *subreq);
944 static void dcerpc_ncacn_packet_done(struct tevent_req *subreq);
945
946 void dcerpc_ncacn_accept(struct tevent_context *ev_ctx,
947                          struct messaging_context *msg_ctx,
948                          enum dcerpc_transport_t transport,
949                          const char *name,
950                          struct tsocket_address *cli_addr,
951                          struct tsocket_address *srv_addr,
952                          int s,
953                          dcerpc_ncacn_disconnect_fn fn) {
954         struct dcerpc_ncacn_conn *ncacn_conn;
955         struct tevent_req *subreq;
956         bool system_user = false;
957         char *pipe_name;
958         NTSTATUS status;
959         int sys_errno;
960         uid_t uid;
961         gid_t gid;
962         int rc;
963
964         DEBUG(10, ("dcerpc_ncacn_accept\n"));
965
966         ncacn_conn = talloc_zero(ev_ctx, struct dcerpc_ncacn_conn);
967         if (ncacn_conn == NULL) {
968                 DEBUG(0, ("Out of memory!\n"));
969                 close(s);
970                 return;
971         }
972
973         ncacn_conn->transport = transport;
974         ncacn_conn->ev_ctx = ev_ctx;
975         ncacn_conn->msg_ctx = msg_ctx;
976         ncacn_conn->sock = s;
977         ncacn_conn->disconnect_fn = fn;
978
979         ncacn_conn->client = talloc_move(ncacn_conn, &cli_addr);
980         if (tsocket_address_is_inet(ncacn_conn->client, "ip")) {
981                 ncacn_conn->client_name =
982                         tsocket_address_inet_addr_string(ncacn_conn->client,
983                                                          ncacn_conn);
984         } else {
985                 ncacn_conn->client_name =
986                         tsocket_address_unix_path(ncacn_conn->client,
987                                                   ncacn_conn);
988         }
989         if (ncacn_conn->client_name == NULL) {
990                 DEBUG(0, ("Out of memory!\n"));
991                 talloc_free(ncacn_conn);
992                 close(s);
993                 return;
994         }
995
996         if (srv_addr != NULL) {
997                 ncacn_conn->server = talloc_move(ncacn_conn, &srv_addr);
998
999                 ncacn_conn->server_name =
1000                         tsocket_address_inet_addr_string(ncacn_conn->server,
1001                                                          ncacn_conn);
1002                 if (ncacn_conn->server_name == NULL) {
1003                         DEBUG(0, ("Out of memory!\n"));
1004                         talloc_free(ncacn_conn);
1005                         close(s);
1006                         return;
1007                 }
1008         }
1009
1010         switch (transport) {
1011                 case NCACN_IP_TCP:
1012                         pipe_name = tsocket_address_string(ncacn_conn->client,
1013                                                            ncacn_conn);
1014                         if (pipe_name == NULL) {
1015                                 close(s);
1016                                 talloc_free(ncacn_conn);
1017                                 return;
1018                         }
1019
1020                         break;
1021                 case NCALRPC:
1022                         rc = getpeereid(s, &uid, &gid);
1023                         if (rc < 0) {
1024                                 DEBUG(2, ("Failed to get ncalrpc connecting "
1025                                           "uid - %s!\n", strerror(errno)));
1026                         } else {
1027                                 if (uid == sec_initial_uid()) {
1028                                         system_user = true;
1029                                 }
1030                         }
1031                         /* FALL TROUGH */
1032                 case NCACN_NP:
1033                         pipe_name = talloc_strdup(ncacn_conn,
1034                                                   name);
1035                         if (pipe_name == NULL) {
1036                                 close(s);
1037                                 talloc_free(ncacn_conn);
1038                                 return;
1039                         }
1040                         break;
1041                 default:
1042                         DEBUG(0, ("unknown dcerpc transport: %u!\n",
1043                                   transport));
1044                         talloc_free(ncacn_conn);
1045                         close(s);
1046                         return;
1047         }
1048
1049         rc = set_blocking(s, false);
1050         if (rc < 0) {
1051                 DEBUG(2, ("Failed to set dcerpc socket to non-blocking\n"));
1052                 talloc_free(ncacn_conn);
1053                 close(s);
1054                 return;
1055         }
1056
1057         /*
1058          * As soon as we have tstream_bsd_existing_socket set up it will
1059          * take care of closing the socket.
1060          */
1061         rc = tstream_bsd_existing_socket(ncacn_conn, s, &ncacn_conn->tstream);
1062         if (rc < 0) {
1063                 DEBUG(2, ("Failed to create tstream socket for dcerpc\n"));
1064                 talloc_free(ncacn_conn);
1065                 close(s);
1066                 return;
1067         }
1068
1069         if (ncacn_conn->session_info == NULL) {
1070                 status = auth_anonymous_session_info(ncacn_conn,
1071                                                      &ncacn_conn->session_info);
1072                 if (!NT_STATUS_IS_OK(status)) {
1073                         DEBUG(2, ("Failed to create "
1074                                   "auth_anonymous_session_info - %s\n",
1075                                   nt_errstr(status)));
1076                         talloc_free(ncacn_conn);
1077                         return;
1078                 }
1079         }
1080
1081         rc = make_server_pipes_struct(ncacn_conn,
1082                                       ncacn_conn->msg_ctx,
1083                                       pipe_name,
1084                                       ncacn_conn->transport,
1085                                       system_user,
1086                                       ncacn_conn->server,
1087                                       ncacn_conn->client,
1088                                       ncacn_conn->session_info,
1089                                       &ncacn_conn->p,
1090                                       &sys_errno);
1091         if (rc < 0) {
1092                 DEBUG(2, ("Failed to create pipe struct - %s",
1093                           strerror(sys_errno)));
1094                 talloc_free(ncacn_conn);
1095                 return;
1096         }
1097
1098         ncacn_conn->send_queue = tevent_queue_create(ncacn_conn,
1099                                                         "dcerpc send queue");
1100         if (ncacn_conn->send_queue == NULL) {
1101                 DEBUG(0, ("Out of memory!\n"));
1102                 talloc_free(ncacn_conn);
1103                 return;
1104         }
1105
1106         subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1107                                                ncacn_conn->ev_ctx,
1108                                                ncacn_conn->tstream);
1109         if (subreq == NULL) {
1110                 DEBUG(2, ("Failed to send ncacn packet\n"));
1111                 talloc_free(ncacn_conn);
1112                 return;
1113         }
1114
1115         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1116
1117         DEBUG(10, ("dcerpc_ncacn_accept done\n"));
1118
1119         return;
1120 }
1121
1122 static void dcerpc_ncacn_packet_process(struct tevent_req *subreq)
1123 {
1124         struct dcerpc_ncacn_conn *ncacn_conn =
1125                 tevent_req_callback_data(subreq, struct dcerpc_ncacn_conn);
1126
1127         struct _output_data *out = &ncacn_conn->p->out_data;
1128         DATA_BLOB recv_buffer = data_blob_null;
1129         struct ncacn_packet *pkt;
1130         ssize_t data_left;
1131         ssize_t data_used;
1132         uint32_t to_send;
1133         char *data;
1134         NTSTATUS status;
1135         bool ok;
1136
1137         status = dcerpc_read_ncacn_packet_recv(subreq, ncacn_conn, &pkt, &recv_buffer);
1138         TALLOC_FREE(subreq);
1139         if (!NT_STATUS_IS_OK(status)) {
1140                 if (ncacn_conn->disconnect_fn != NULL) {
1141                         ok = ncacn_conn->disconnect_fn(ncacn_conn->p);
1142                         if (!ok) {
1143                                 DEBUG(3, ("Failed to call disconnect function\n"));
1144                         }
1145                 }
1146                 goto fail;
1147         }
1148
1149         data_left = recv_buffer.length;
1150         data = (char *) recv_buffer.data;
1151
1152         while (data_left) {
1153                 data_used = process_incoming_data(ncacn_conn->p, data, data_left);
1154                 if (data_used < 0) {
1155                         DEBUG(3, ("Failed to process dcerpc request!\n"));
1156                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
1157                         goto fail;
1158                 }
1159
1160                 data_left -= data_used;
1161                 data += data_used;
1162         }
1163
1164         /* Do not leak this buffer */
1165         talloc_free(recv_buffer.data);
1166         talloc_free(pkt);
1167
1168         /*
1169          * This is needed because of the way DCERPC binds work in the RPC
1170          * marshalling code
1171          */
1172         to_send = out->frag.length - out->current_pdu_sent;
1173         if (to_send > 0) {
1174
1175                 DEBUG(10, ("Current_pdu_len = %u, "
1176                            "current_pdu_sent = %u "
1177                            "Returning %u bytes\n",
1178                            (unsigned int)out->frag.length,
1179                            (unsigned int)out->current_pdu_sent,
1180                            (unsigned int)to_send));
1181
1182                 ncacn_conn->iov = talloc_zero(ncacn_conn, struct iovec);
1183                 if (ncacn_conn->iov == NULL) {
1184                         status = NT_STATUS_NO_MEMORY;
1185                         DEBUG(3, ("Out of memory!\n"));
1186                         goto fail;
1187                 }
1188                 ncacn_conn->count = 1;
1189
1190                 ncacn_conn->iov[0].iov_base = out->frag.data
1191                                             + out->current_pdu_sent;
1192                 ncacn_conn->iov[0].iov_len = to_send;
1193
1194                 out->current_pdu_sent += to_send;
1195         }
1196
1197         /*
1198          * This condition is false for bind packets, or when we haven't yet got
1199          * a full request, and need to wait for more data from the client
1200          */
1201         while (out->data_sent_length < out->rdata.length) {
1202                 ok = create_next_pdu(ncacn_conn->p);
1203                 if (!ok) {
1204                         DEBUG(3, ("Failed to create next PDU!\n"));
1205                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
1206                         goto fail;
1207                 }
1208
1209                 ncacn_conn->iov = talloc_realloc(ncacn_conn,
1210                                                  ncacn_conn->iov,
1211                                                  struct iovec,
1212                                                  ncacn_conn->count + 1);
1213                 if (ncacn_conn->iov == NULL) {
1214                         DEBUG(3, ("Out of memory!\n"));
1215                         status = NT_STATUS_NO_MEMORY;
1216                         goto fail;
1217                 }
1218
1219                 ncacn_conn->iov[ncacn_conn->count].iov_base = out->frag.data;
1220                 ncacn_conn->iov[ncacn_conn->count].iov_len = out->frag.length;
1221
1222                 DEBUG(10, ("PDU number: %d, PDU Length: %u\n",
1223                            (unsigned int) ncacn_conn->count,
1224                            (unsigned int) ncacn_conn->iov[ncacn_conn->count].iov_len));
1225                 dump_data(11, (const uint8_t *) ncacn_conn->iov[ncacn_conn->count].iov_base,
1226                               ncacn_conn->iov[ncacn_conn->count].iov_len);
1227                 ncacn_conn->count++;
1228         }
1229
1230         /*
1231          * We still don't have a complete request, go back and wait for more
1232          * data.
1233          */
1234         if (ncacn_conn->count == 0) {
1235                 /* Wait for the next packet */
1236                 subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1237                                                        ncacn_conn->ev_ctx,
1238                                                        ncacn_conn->tstream);
1239                 if (subreq == NULL) {
1240                         DEBUG(2, ("Failed to start receving packets\n"));
1241                         status = NT_STATUS_NO_MEMORY;
1242                         goto fail;
1243                 }
1244                 tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1245                 return;
1246         }
1247
1248         DEBUG(10, ("Sending a total of %u bytes\n",
1249                    (unsigned int)ncacn_conn->p->out_data.data_sent_length));
1250
1251         subreq = tstream_writev_queue_send(ncacn_conn,
1252                                            ncacn_conn->ev_ctx,
1253                                            ncacn_conn->tstream,
1254                                            ncacn_conn->send_queue,
1255                                            ncacn_conn->iov,
1256                                            ncacn_conn->count);
1257         if (subreq == NULL) {
1258                 DEBUG(2, ("Failed to send packet\n"));
1259                 status = NT_STATUS_NO_MEMORY;
1260                 goto fail;
1261         }
1262
1263         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_done, ncacn_conn);
1264         return;
1265
1266 fail:
1267         DEBUG(3, ("Terminating client(%s) connection! - '%s'\n",
1268                   ncacn_conn->client_name, nt_errstr(status)));
1269
1270         /* Terminate client connection */
1271         talloc_free(ncacn_conn);
1272         return;
1273 }
1274
1275 static void dcerpc_ncacn_packet_done(struct tevent_req *subreq)
1276 {
1277         struct dcerpc_ncacn_conn *ncacn_conn =
1278                 tevent_req_callback_data(subreq, struct dcerpc_ncacn_conn);
1279         NTSTATUS status = NT_STATUS_OK;
1280         int sys_errno;
1281         int rc;
1282
1283         rc = tstream_writev_queue_recv(subreq, &sys_errno);
1284         TALLOC_FREE(subreq);
1285         if (rc < 0) {
1286                 DEBUG(2, ("Writev failed!\n"));
1287                 status = map_nt_error_from_unix(sys_errno);
1288                 goto fail;
1289         }
1290
1291         /* clear out any data that may have been left around */
1292         ncacn_conn->count = 0;
1293         TALLOC_FREE(ncacn_conn->iov);
1294         data_blob_free(&ncacn_conn->p->in_data.data);
1295         data_blob_free(&ncacn_conn->p->out_data.frag);
1296         data_blob_free(&ncacn_conn->p->out_data.rdata);
1297
1298         talloc_free_children(ncacn_conn->p->mem_ctx);
1299
1300         /* Wait for the next packet */
1301         subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1302                                                ncacn_conn->ev_ctx,
1303                                                ncacn_conn->tstream);
1304         if (subreq == NULL) {
1305                 DEBUG(2, ("Failed to start receving packets\n"));
1306                 status = NT_STATUS_NO_MEMORY;
1307                 goto fail;
1308         }
1309
1310         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1311         return;
1312
1313 fail:
1314         DEBUG(3, ("Terminating client(%s) connection! - '%s'\n",
1315                   ncacn_conn->client_name, nt_errstr(status)));
1316
1317         /* Terminate client connection */
1318         talloc_free(ncacn_conn);
1319         return;
1320 }
1321
1322 /* vim: set ts=8 sw=8 noet cindent syntax=c.doxygen: */