s3-rpc_server: Fixed the accept() for named_pipe_listener.
[nivanova/samba-autobuild/.git] / source3 / rpc_server / rpc_server.c
1 /*
2    Unix SMB/Netbios implementation.
3    Generic infrstructure for RPC Daemons
4    Copyright (C) Simo Sorce 2010
5
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 "registry/reg_parse_prs.h"
26 #include "lib/tsocket/tsocket.h"
27 #include "libcli/named_pipe_auth/npa_tstream.h"
28 #include "../auth/auth_sam_reply.h"
29
30 #define SERVER_TCP_LOW_PORT  1024
31 #define SERVER_TCP_HIGH_PORT 1300
32
33 static NTSTATUS auth_anonymous_session_info(TALLOC_CTX *mem_ctx,
34                                             struct auth_session_info_transport **session_info)
35 {
36         struct auth_session_info_transport *i;
37         struct auth_serversupplied_info *s;
38         struct auth_user_info_dc *u;
39         union netr_Validation val;
40         NTSTATUS status;
41
42         i = talloc_zero(mem_ctx, struct auth_session_info_transport);
43         if (i == NULL) {
44                 return NT_STATUS_NO_MEMORY;
45         }
46
47         status = make_server_info_guest(i, &s);
48         if (!NT_STATUS_IS_OK(status)) {
49                 return status;
50         }
51
52         i->security_token = s->security_token;
53         i->session_key    = s->user_session_key;
54
55         val.sam3 = s->info3;
56
57         status = make_user_info_dc_netlogon_validation(mem_ctx,
58                                                        "",
59                                                        3,
60                                                        &val,
61                                                        &u);
62         if (!NT_STATUS_IS_OK(status)) {
63                 DEBUG(0, ("conversion of info3 into user_info_dc failed!\n"));
64                 return status;
65         }
66         i->info = talloc_move(i, &u->info);
67         talloc_free(u);
68
69         *session_info = i;
70
71         return NT_STATUS_OK;
72 }
73
74 /* Creates a pipes_struct and initializes it with the information
75  * sent from the client */
76 static int make_server_pipes_struct(TALLOC_CTX *mem_ctx,
77                                     const char *pipe_name,
78                                     const struct ndr_syntax_id id,
79                                     enum dcerpc_transport_t transport,
80                                     bool system_user,
81                                     const char *client_address,
82                                     const char *server_address,
83                                     struct auth_session_info_transport *session_info,
84                                     struct pipes_struct **_p,
85                                     int *perrno)
86 {
87         struct netr_SamInfo3 *info3;
88         struct auth_user_info_dc *auth_user_info_dc;
89         struct pipes_struct *p;
90         NTSTATUS status;
91         bool ok;
92
93         p = talloc_zero(mem_ctx, struct pipes_struct);
94         if (!p) {
95                 *perrno = ENOMEM;
96                 return -1;
97         }
98         p->syntax = id;
99         p->transport = transport;
100         p->system_user = system_user;
101
102         p->mem_ctx = talloc_named(p, 0, "pipe %s %p", pipe_name, p);
103         if (!p->mem_ctx) {
104                 TALLOC_FREE(p);
105                 *perrno = ENOMEM;
106                 return -1;
107         }
108
109         ok = init_pipe_handles(p, &id);
110         if (!ok) {
111                 DEBUG(1, ("Failed to init handles\n"));
112                 TALLOC_FREE(p);
113                 *perrno = EINVAL;
114                 return -1;
115         }
116
117
118         data_blob_free(&p->in_data.data);
119         data_blob_free(&p->in_data.pdu);
120
121         p->endian = RPC_LITTLE_ENDIAN;
122
123         /* Fake up an auth_user_info_dc for now, to make an info3, to make the session_info structure */
124         auth_user_info_dc = talloc_zero(p, struct auth_user_info_dc);
125         if (!auth_user_info_dc) {
126                 TALLOC_FREE(p);
127                 *perrno = ENOMEM;
128                 return -1;
129         }
130
131         auth_user_info_dc->num_sids = session_info->security_token->num_sids;
132         auth_user_info_dc->sids = session_info->security_token->sids;
133         auth_user_info_dc->info = session_info->info;
134         auth_user_info_dc->user_session_key = session_info->session_key;
135
136         /* This creates the input structure that make_server_info_info3 is looking for */
137         status = auth_convert_user_info_dc_saminfo3(p, auth_user_info_dc,
138                                                     &info3);
139
140         if (!NT_STATUS_IS_OK(status)) {
141                 DEBUG(1, ("Failed to convert auth_user_info_dc into netr_SamInfo3\n"));
142                 TALLOC_FREE(p);
143                 *perrno = EINVAL;
144                 return -1;
145         }
146
147         status = make_server_info_info3(p,
148                                         info3->base.account_name.string,
149                                         info3->base.domain.string,
150                                         &p->session_info, info3);
151         if (!NT_STATUS_IS_OK(status)) {
152                 DEBUG(1, ("Failed to init server info\n"));
153                 TALLOC_FREE(p);
154                 *perrno = EINVAL;
155                 return -1;
156         }
157
158         /*
159          * Some internal functions need a local token to determine access to
160          * resoutrces.
161          */
162         status = create_local_token(p->session_info);
163         if (!NT_STATUS_IS_OK(status)) {
164                 DEBUG(1, ("Failed to init local auth token\n"));
165                 TALLOC_FREE(p);
166                 *perrno = EINVAL;
167                 return -1;
168         }
169
170         /* Now override the session_info->security_token with the exact
171          * security_token we were given from the other side,
172          * regardless of what we just calculated */
173         p->session_info->security_token = talloc_move(p->session_info, &session_info->security_token);
174
175         /* Also set the session key to the correct value */
176         p->session_info->user_session_key = session_info->session_key;
177         p->session_info->user_session_key.data = talloc_move(p->session_info, &session_info->session_key.data);
178
179         p->client_id = talloc_zero(p, struct client_address);
180         if (!p->client_id) {
181                 TALLOC_FREE(p);
182                 *perrno = ENOMEM;
183                 return -1;
184         }
185         strlcpy(p->client_id->addr,
186                 client_address, sizeof(p->client_id->addr));
187         p->client_id->name = talloc_strdup(p->client_id, client_address);
188         if (p->client_id->name == NULL) {
189                 TALLOC_FREE(p);
190                 *perrno = ENOMEM;
191                 return -1;
192         }
193
194         if (server_address != NULL) {
195                 p->server_id = talloc_zero(p, struct client_address);
196                 if (p->client_id == NULL) {
197                         TALLOC_FREE(p);
198                         *perrno = ENOMEM;
199                         return -1;
200                 }
201
202                 strlcpy(p->server_id->addr,
203                         server_address,
204                         sizeof(p->server_id->addr));
205
206                 p->server_id->name = talloc_strdup(p->server_id,
207                                                    server_address);
208                 if (p->server_id->name == NULL) {
209                         TALLOC_FREE(p);
210                         *perrno = ENOMEM;
211                         return -1;
212                 }
213         }
214
215         talloc_set_destructor(p, close_internal_rpc_pipe_hnd);
216
217         *_p = p;
218         return 0;
219 }
220
221 /* Start listening on the appropriate unix socket and setup all is needed to
222  * dispatch requests to the pipes rpc implementation */
223
224 struct dcerpc_ncacn_listen_state {
225         struct ndr_syntax_id syntax_id;
226
227         int fd;
228         union {
229                 char *name;
230                 uint16_t port;
231         } ep;
232
233         struct tevent_context *ev_ctx;
234         struct messaging_context *msg_ctx;
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 receaving 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
686 /********************************************************************
687  * Start listening on the tcp/ip socket
688  ********************************************************************/
689
690 static void dcerpc_ncacn_tcpip_listener(struct tevent_context *ev,
691                                         struct tevent_fd *fde,
692                                         uint16_t flags,
693                                         void *private_data);
694
695 uint16_t setup_dcerpc_ncacn_tcpip_socket(struct tevent_context *ev_ctx,
696                                          struct messaging_context *msg_ctx,
697                                          struct ndr_syntax_id syntax_id,
698                                          const struct sockaddr_storage *ifss,
699                                          uint16_t port)
700 {
701         struct dcerpc_ncacn_listen_state *state;
702         struct tevent_fd *fde;
703         int rc;
704
705         state = talloc(ev_ctx, struct dcerpc_ncacn_listen_state);
706         if (state == NULL) {
707                 DEBUG(0, ("setup_dcerpc_ncacn_tcpip_socket: Out of memory\n"));
708                 return 0;
709         }
710
711         state->syntax_id = syntax_id;
712         state->fd = -1;
713         state->ep.port = port;
714
715         if (state->ep.port == 0) {
716                 uint16_t i;
717
718                 for (i = SERVER_TCP_LOW_PORT; i <= SERVER_TCP_HIGH_PORT; i++) {
719                         state->fd = open_socket_in(SOCK_STREAM,
720                                                    i,
721                                                    0,
722                                                    ifss,
723                                                    false);
724                         if (state->fd > 0) {
725                                 state->ep.port = i;
726                                 break;
727                         }
728                 }
729         } else {
730                 state->fd = open_socket_in(SOCK_STREAM,
731                                            state->ep.port,
732                                            0,
733                                            ifss,
734                                            true);
735         }
736         if (state->fd == -1) {
737                 DEBUG(0, ("setup_dcerpc_ncacn_tcpip_socket: Failed to create "
738                           "socket on port %u!\n", state->ep.port));
739                 goto out;
740         }
741
742         state->ev_ctx = ev_ctx;
743         state->msg_ctx = msg_ctx;
744
745         /* ready to listen */
746         set_socket_options(state->fd, "SO_KEEPALIVE");
747         set_socket_options(state->fd, lp_socket_options());
748
749         /* Set server socket to non-blocking for the accept. */
750         set_blocking(state->fd, false);
751
752         rc = listen(state->fd, SMBD_LISTEN_BACKLOG);
753         if (rc == -1) {
754                 DEBUG(0,("setup_tcpip_socket: listen - %s\n", strerror(errno)));
755                 goto out;
756         }
757
758         DEBUG(10, ("setup_tcpip_socket: openened socket fd %d for port %u\n",
759                    state->fd, state->ep.port));
760
761         fde = tevent_add_fd(state->ev_ctx,
762                             state,
763                             state->fd,
764                             TEVENT_FD_READ,
765                             dcerpc_ncacn_tcpip_listener,
766                             state);
767         if (fde == NULL) {
768                 DEBUG(0, ("setup_tcpip_socket: Failed to add event handler!\n"));
769                 goto out;
770         }
771
772         tevent_fd_set_auto_close(fde);
773
774         return state->ep.port;
775 out:
776         if (state->fd != -1) {
777                 close(state->fd);
778         }
779         TALLOC_FREE(state);
780
781         return 0;
782 }
783
784 static void dcerpc_ncacn_tcpip_listener(struct tevent_context *ev,
785                                         struct tevent_fd *fde,
786                                         uint16_t flags,
787                                         void *private_data)
788 {
789         struct dcerpc_ncacn_listen_state *state =
790                         talloc_get_type_abort(private_data,
791                                               struct dcerpc_ncacn_listen_state);
792         struct tsocket_address *cli_addr = NULL;
793         struct tsocket_address *srv_addr = NULL;
794         struct sockaddr_storage addr;
795         socklen_t in_addrlen = sizeof(addr);
796         int s = -1;
797         int rc;
798
799         while (s == -1) {
800                 s = accept(state->fd, (struct sockaddr *)(void *) &addr, &in_addrlen);
801                 if (s == -1 && errno != EINTR) {
802                         break;
803                 }
804         }
805
806         if (s == -1) {
807                 DEBUG(0,("tcpip_listener accept: %s\n",
808                          strerror(errno)));
809                 return;
810         }
811
812         rc = tsocket_address_bsd_from_sockaddr(state,
813                                                (struct sockaddr *)(void *) &addr,
814                                                in_addrlen,
815                                                &cli_addr);
816         if (rc < 0) {
817                 close(s);
818                 return;
819         }
820
821         rc = getsockname(s, (struct sockaddr *)(void *) &addr, &in_addrlen);
822         if (rc < 0) {
823                 close(s);
824                 return;
825         }
826
827         rc = tsocket_address_bsd_from_sockaddr(state,
828                                                (struct sockaddr *)(void *) &addr,
829                                                in_addrlen,
830                                                &srv_addr);
831         if (rc < 0) {
832                 close(s);
833                 return;
834         }
835
836         DEBUG(6, ("tcpip_listener: Accepted socket %d\n", s));
837
838         dcerpc_ncacn_accept(state->ev_ctx,
839                             state->msg_ctx,
840                             state->syntax_id,
841                             NCACN_IP_TCP,
842                             NULL,
843                             state->ep.port,
844                             cli_addr,
845                             srv_addr,
846                             s);
847 }
848
849 /********************************************************************
850  * Start listening on the ncalrpc socket
851  ********************************************************************/
852
853 static void dcerpc_ncalrpc_listener(struct tevent_context *ev,
854                                     struct tevent_fd *fde,
855                                     uint16_t flags,
856                                     void *private_data);
857
858 bool setup_dcerpc_ncalrpc_socket(struct tevent_context *ev_ctx,
859                                  struct messaging_context *msg_ctx,
860                                  struct ndr_syntax_id syntax_id,
861                                  const char *name)
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
875         if (name == NULL) {
876                 name = "DEFAULT";
877         }
878         state->ep.name = talloc_strdup(state, name);
879
880         if (state->ep.name == NULL) {
881                 DEBUG(0, ("Out of memory\n"));
882                 talloc_free(state);
883                 return false;
884         }
885
886         if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0700)) {
887                 DEBUG(0, ("Failed to create pipe directory %s - %s\n",
888                           lp_ncalrpc_dir(), strerror(errno)));
889                 goto out;
890         }
891
892         state->fd = create_pipe_sock(lp_ncalrpc_dir(), name, 0700);
893         if (state->fd == -1) {
894                 DEBUG(0, ("Failed to create pipe socket! [%s/%s]\n",
895                           lp_ncalrpc_dir(), name));
896                 goto out;
897         }
898
899         DEBUG(10, ("Openened pipe socket fd %d for %s\n", state->fd, name));
900
901         state->ev_ctx = ev_ctx;
902         state->msg_ctx = msg_ctx;
903
904         /* Set server socket to non-blocking for the accept. */
905         set_blocking(state->fd, false);
906
907         fde = tevent_add_fd(state->ev_ctx,
908                             state,
909                             state->fd,
910                             TEVENT_FD_READ,
911                             dcerpc_ncalrpc_listener,
912                             state);
913         if (fde == NULL) {
914                 DEBUG(0, ("Failed to add event handler for ncalrpc!\n"));
915                 goto out;
916         }
917
918         tevent_fd_set_auto_close(fde);
919
920         return true;
921 out:
922         if (state->fd != -1) {
923                 close(state->fd);
924         }
925         TALLOC_FREE(state);
926
927         return 0;
928 }
929
930 static void dcerpc_ncalrpc_listener(struct tevent_context *ev,
931                                         struct tevent_fd *fde,
932                                         uint16_t flags,
933                                         void *private_data)
934 {
935         struct dcerpc_ncacn_listen_state *state =
936                         talloc_get_type_abort(private_data,
937                                               struct dcerpc_ncacn_listen_state);
938         struct tsocket_address *cli_addr = NULL;
939         struct sockaddr_un sunaddr;
940         struct sockaddr *addr = (struct sockaddr *)(void *)&sunaddr;
941         socklen_t len = sizeof(sunaddr);
942         int sd = -1;
943         int rc;
944
945         ZERO_STRUCT(sunaddr);
946
947         while (sd == -1) {
948                 sd = accept(state->fd, addr, &len);
949                 if (sd == -1 && errno != EINTR) {
950                         break;
951                 }
952         }
953
954         if (sd == -1) {
955                 DEBUG(0, ("ncalrpc accept() failed: %s\n", strerror(errno)));
956                 return;
957         }
958
959         rc = tsocket_address_bsd_from_sockaddr(state,
960                                                addr, len,
961                                                &cli_addr);
962         if (rc < 0) {
963                 close(sd);
964                 return;
965         }
966
967         DEBUG(10, ("Accepted ncalrpc socket %d\n", sd));
968
969         dcerpc_ncacn_accept(state->ev_ctx,
970                             state->msg_ctx,
971                             state->syntax_id, NCALRPC,
972                             state->ep.name, 0,
973                             cli_addr, NULL, sd);
974 }
975
976 struct dcerpc_ncacn_conn {
977         struct ndr_syntax_id syntax_id;
978
979         enum dcerpc_transport_t transport;
980
981         union {
982                 const char *name;
983                 uint16_t port;
984         } ep;
985
986         int sock;
987
988         struct pipes_struct *p;
989
990         struct tevent_context *ev_ctx;
991         struct messaging_context *msg_ctx;
992
993         struct tstream_context *tstream;
994         struct tevent_queue *send_queue;
995
996         struct tsocket_address *client;
997         char *client_name;
998         struct tsocket_address *server;
999         char *server_name;
1000         struct auth_session_info_transport *session_info;
1001
1002         struct iovec *iov;
1003         size_t count;
1004 };
1005
1006 static void dcerpc_ncacn_packet_process(struct tevent_req *subreq);
1007 static void dcerpc_ncacn_packet_done(struct tevent_req *subreq);
1008
1009 static void dcerpc_ncacn_accept(struct tevent_context *ev_ctx,
1010                                 struct messaging_context *msg_ctx,
1011                                 struct ndr_syntax_id syntax_id,
1012                                 enum dcerpc_transport_t transport,
1013                                 const char *name,
1014                                 uint16_t port,
1015                                 struct tsocket_address *cli_addr,
1016                                 struct tsocket_address *srv_addr,
1017                                 int s) {
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
1044         ncacn_conn->client = talloc_move(ncacn_conn, &cli_addr);
1045         if (tsocket_address_is_inet(ncacn_conn->client, "ip")) {
1046                 ncacn_conn->client_name =
1047                         tsocket_address_inet_addr_string(ncacn_conn->client,
1048                                                          ncacn_conn);
1049         } else {
1050                 ncacn_conn->client_name =
1051                         tsocket_address_unix_path(ncacn_conn->client,
1052                                                   ncacn_conn);
1053         }
1054         if (ncacn_conn->client_name == NULL) {
1055                 DEBUG(0, ("Out of memory!\n"));
1056                 talloc_free(ncacn_conn);
1057                 close(s);
1058                 return;
1059         }
1060
1061         if (srv_addr != NULL) {
1062                 ncacn_conn->server = talloc_move(ncacn_conn, &srv_addr);
1063
1064                 ncacn_conn->server_name =
1065                         tsocket_address_inet_addr_string(ncacn_conn->server,
1066                                                          ncacn_conn);
1067                 if (ncacn_conn->server_name == NULL) {
1068                         DEBUG(0, ("Out of memory!\n"));
1069                         talloc_free(ncacn_conn);
1070                         close(s);
1071                         return;
1072                 }
1073         }
1074
1075         switch (transport) {
1076                 case NCACN_IP_TCP:
1077                         ncacn_conn->ep.port = port;
1078
1079                         pipe_name = tsocket_address_string(ncacn_conn->client,
1080                                                            ncacn_conn);
1081                         if (pipe_name == NULL) {
1082                                 close(s);
1083                                 talloc_free(ncacn_conn);
1084                                 return;
1085                         }
1086
1087                         break;
1088                 case NCALRPC:
1089                         rc = sys_getpeereid(s, &uid);
1090                         if (rc < 0) {
1091                                 DEBUG(2, ("Failed to get ncalrpc connecting uid!"));
1092                         } else {
1093                                 if (uid == sec_initial_uid()) {
1094                                         system_user = true;
1095                                 }
1096                         }
1097                 case NCACN_NP:
1098                         ncacn_conn->ep.name = talloc_strdup(ncacn_conn, name);
1099                         if (ncacn_conn->ep.name == NULL) {
1100                                 close(s);
1101                                 talloc_free(ncacn_conn);
1102                                 return;
1103                         }
1104
1105                         pipe_name = talloc_strdup(ncacn_conn,
1106                                                   name);
1107                         if (pipe_name == NULL) {
1108                                 close(s);
1109                                 talloc_free(ncacn_conn);
1110                                 return;
1111                         }
1112                         break;
1113                 default:
1114                         DEBUG(0, ("unknown dcerpc transport: %u!\n",
1115                                   transport));
1116                         talloc_free(ncacn_conn);
1117                         close(s);
1118                         return;
1119         }
1120
1121         rc = set_blocking(s, false);
1122         if (rc < 0) {
1123                 DEBUG(2, ("Failed to set dcerpc socket to non-blocking\n"));
1124                 talloc_free(ncacn_conn);
1125                 close(s);
1126                 return;
1127         }
1128
1129         /*
1130          * As soon as we have tstream_bsd_existing_socket set up it will
1131          * take care of closing the socket.
1132          */
1133         rc = tstream_bsd_existing_socket(ncacn_conn, s, &ncacn_conn->tstream);
1134         if (rc < 0) {
1135                 DEBUG(2, ("Failed to create tstream socket for dcerpc\n"));
1136                 talloc_free(ncacn_conn);
1137                 close(s);
1138                 return;
1139         }
1140
1141         if (tsocket_address_is_inet(ncacn_conn->client, "ip")) {
1142                 cli_str = ncacn_conn->client_name;
1143         } else {
1144                 cli_str = "";
1145         }
1146
1147         if (ncacn_conn->server != NULL) {
1148                 if (tsocket_address_is_inet(ncacn_conn->server, "ip")) {
1149                         srv_str = ncacn_conn->server_name;
1150                 } else {
1151                         srv_str = NULL;
1152                 }
1153         }
1154
1155         if (ncacn_conn->session_info == NULL) {
1156                 status = auth_anonymous_session_info(ncacn_conn,
1157                                                      &ncacn_conn->session_info);
1158                 if (!NT_STATUS_IS_OK(status)) {
1159                         DEBUG(2, ("Failed to create "
1160                                   "auth_anonymous_session_info - %s\n",
1161                                   nt_errstr(status)));
1162                         talloc_free(ncacn_conn);
1163                         return;
1164                 }
1165         }
1166
1167         rc = make_server_pipes_struct(ncacn_conn,
1168                                       pipe_name,
1169                                       ncacn_conn->syntax_id,
1170                                       ncacn_conn->transport,
1171                                       system_user,
1172                                       cli_str,
1173                                       srv_str,
1174                                       ncacn_conn->session_info,
1175                                       &ncacn_conn->p,
1176                                       &sys_errno);
1177         if (rc < 0) {
1178                 DEBUG(2, ("Failed to create pipe struct - %s",
1179                           strerror(sys_errno)));
1180                 talloc_free(ncacn_conn);
1181                 return;
1182         }
1183
1184         ncacn_conn->send_queue = tevent_queue_create(ncacn_conn,
1185                                                         "dcerpc send queue");
1186         if (ncacn_conn->send_queue == NULL) {
1187                 DEBUG(0, ("Out of memory!\n"));
1188                 talloc_free(ncacn_conn);
1189                 return;
1190         }
1191
1192         subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1193                                                ncacn_conn->ev_ctx,
1194                                                ncacn_conn->tstream);
1195         if (subreq == NULL) {
1196                 DEBUG(2, ("Failed to send ncacn packet\n"));
1197                 talloc_free(ncacn_conn);
1198                 return;
1199         }
1200
1201         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1202
1203         DEBUG(10, ("dcerpc_ncacn_accept done\n"));
1204
1205         return;
1206 }
1207
1208 static void dcerpc_ncacn_packet_process(struct tevent_req *subreq)
1209 {
1210         struct dcerpc_ncacn_conn *ncacn_conn =
1211                 tevent_req_callback_data(subreq, struct dcerpc_ncacn_conn);
1212
1213         struct _output_data *out = &ncacn_conn->p->out_data;
1214         DATA_BLOB recv_buffer = data_blob_null;
1215         struct ncacn_packet *pkt;
1216         ssize_t data_left;
1217         ssize_t data_used;
1218         uint32_t to_send;
1219         char *data;
1220         NTSTATUS status;
1221         bool ok;
1222
1223         status = dcerpc_read_ncacn_packet_recv(subreq, ncacn_conn, &pkt, &recv_buffer);
1224         TALLOC_FREE(subreq);
1225         if (!NT_STATUS_IS_OK(status)) {
1226                 DEBUG(3, ("Failed to receive ncacn packet!\n"));
1227                 goto fail;
1228         }
1229
1230         data_left = recv_buffer.length;
1231         data = (char *) recv_buffer.data;
1232
1233         while (data_left) {
1234                 data_used = process_incoming_data(ncacn_conn->p, data, data_left);
1235                 if (data_used < 0) {
1236                         DEBUG(3, ("Failed to process dcerpc request!\n"));
1237                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
1238                         goto fail;
1239                 }
1240
1241                 data_left -= data_used;
1242                 data += data_used;
1243         }
1244
1245         /* Do not leak this buffer */
1246         talloc_free(recv_buffer.data);
1247         talloc_free(pkt);
1248
1249         /*
1250          * This is needed because of the way DCERPC binds work in the RPC
1251          * marshalling code
1252          */
1253         to_send = out->frag.length - out->current_pdu_sent;
1254         if (to_send > 0) {
1255
1256                 DEBUG(10, ("Current_pdu_len = %u, "
1257                            "current_pdu_sent = %u "
1258                            "Returning %u bytes\n",
1259                            (unsigned int)out->frag.length,
1260                            (unsigned int)out->current_pdu_sent,
1261                            (unsigned int)to_send));
1262
1263                 ncacn_conn->iov = talloc_zero(ncacn_conn, struct iovec);
1264                 if (ncacn_conn->iov == NULL) {
1265                         status = NT_STATUS_NO_MEMORY;
1266                         DEBUG(3, ("Out of memory!\n"));
1267                         goto fail;
1268                 }
1269                 ncacn_conn->count = 1;
1270
1271                 ncacn_conn->iov[0].iov_base = out->frag.data
1272                                             + out->current_pdu_sent;
1273                 ncacn_conn->iov[0].iov_len = to_send;
1274
1275                 out->current_pdu_sent += to_send;
1276         }
1277
1278         /*
1279          * This condition is false for bind packets, or when we haven't yet got
1280          * a full request, and need to wait for more data from the client
1281          */
1282         while (out->data_sent_length < out->rdata.length) {
1283                 ok = create_next_pdu(ncacn_conn->p);
1284                 if (!ok) {
1285                         DEBUG(3, ("Failed to create next PDU!\n"));
1286                         status = NT_STATUS_UNEXPECTED_IO_ERROR;
1287                         goto fail;
1288                 }
1289
1290                 ncacn_conn->iov = talloc_realloc(ncacn_conn,
1291                                                  ncacn_conn->iov,
1292                                                  struct iovec,
1293                                                  ncacn_conn->count + 1);
1294                 if (ncacn_conn->iov == NULL) {
1295                         DEBUG(3, ("Out of memory!\n"));
1296                         status = NT_STATUS_NO_MEMORY;
1297                         goto fail;
1298                 }
1299
1300                 ncacn_conn->iov[ncacn_conn->count].iov_base = out->frag.data;
1301                 ncacn_conn->iov[ncacn_conn->count].iov_len = out->frag.length;
1302
1303                 DEBUG(10, ("PDU number: %d, PDU Length: %u\n",
1304                            (unsigned int) ncacn_conn->count,
1305                            (unsigned int) ncacn_conn->iov[ncacn_conn->count].iov_len));
1306                 dump_data(11, (const uint8_t *) ncacn_conn->iov[ncacn_conn->count].iov_base,
1307                               ncacn_conn->iov[ncacn_conn->count].iov_len);
1308                 ncacn_conn->count++;
1309         }
1310
1311         /*
1312          * We still don't have a complete request, go back and wait for more
1313          * data.
1314          */
1315         if (ncacn_conn->count == 0) {
1316                 /* Wait for the next packet */
1317                 subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1318                                                        ncacn_conn->ev_ctx,
1319                                                        ncacn_conn->tstream);
1320                 if (subreq == NULL) {
1321                         DEBUG(2, ("Failed to start receving packets\n"));
1322                         status = NT_STATUS_NO_MEMORY;
1323                         goto fail;
1324                 }
1325                 tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1326                 return;
1327         }
1328
1329         DEBUG(10, ("Sending a total of %u bytes\n",
1330                    (unsigned int)ncacn_conn->p->out_data.data_sent_length));
1331
1332         subreq = tstream_writev_queue_send(ncacn_conn,
1333                                            ncacn_conn->ev_ctx,
1334                                            ncacn_conn->tstream,
1335                                            ncacn_conn->send_queue,
1336                                            ncacn_conn->iov,
1337                                            ncacn_conn->count);
1338         if (subreq == NULL) {
1339                 DEBUG(2, ("Failed to send packet\n"));
1340                 status = NT_STATUS_NO_MEMORY;
1341                 goto fail;
1342         }
1343
1344         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_done, ncacn_conn);
1345         return;
1346
1347 fail:
1348         DEBUG(2, ("Fatal error(%s). "
1349                   "Terminating client(%s) connection!\n",
1350                   nt_errstr(status), ncacn_conn->client_name));
1351
1352         /* Terminate client connection */
1353         talloc_free(ncacn_conn);
1354         return;
1355 }
1356
1357 static void dcerpc_ncacn_packet_done(struct tevent_req *subreq)
1358 {
1359         struct dcerpc_ncacn_conn *ncacn_conn =
1360                 tevent_req_callback_data(subreq, struct dcerpc_ncacn_conn);
1361         int sys_errno;
1362         int rc;
1363
1364         rc = tstream_writev_queue_recv(subreq, &sys_errno);
1365         TALLOC_FREE(subreq);
1366         if (rc < 0) {
1367                 DEBUG(2, ("Writev failed!\n"));
1368                 goto fail;
1369         }
1370
1371         /* clear out any data that may have been left around */
1372         ncacn_conn->count = 0;
1373         TALLOC_FREE(ncacn_conn->iov);
1374         data_blob_free(&ncacn_conn->p->in_data.data);
1375         data_blob_free(&ncacn_conn->p->out_data.frag);
1376         data_blob_free(&ncacn_conn->p->out_data.rdata);
1377
1378         /* Wait for the next packet */
1379         subreq = dcerpc_read_ncacn_packet_send(ncacn_conn,
1380                                                ncacn_conn->ev_ctx,
1381                                                ncacn_conn->tstream);
1382         if (subreq == NULL) {
1383                 DEBUG(2, ("Failed to start receving packets\n"));
1384                 sys_errno = ENOMEM;
1385                 goto fail;
1386         }
1387
1388         tevent_req_set_callback(subreq, dcerpc_ncacn_packet_process, ncacn_conn);
1389         return;
1390
1391 fail:
1392         DEBUG(2, ("Fatal error(%s). Terminating client(%s) connection!\n",
1393                   strerror(sys_errno), ncacn_conn->client_name));
1394
1395         /* Terminate client connection */
1396         talloc_free(ncacn_conn);
1397         return;
1398 }
1399
1400 /* vim: set ts=8 sw=8 noet cindent syntax=c.doxygen: */