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