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