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