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