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