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