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