b8255ba4dd8e3a25ea516c3eeca423b2f095e26b
[samba.git] / source4 / rpc_server / dcerpc_server.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    server side dcerpc core code
5
6    Copyright (C) Andrew Tridgell 2003-2005
7    Copyright (C) Stefan (metze) Metzmacher 2004-2005
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "auth/auth.h"
25 #include "auth/gensec/gensec.h"
26 #include "../lib/util/dlinklist.h"
27 #include "rpc_server/dcerpc_server.h"
28 #include "rpc_server/dcerpc_server_proto.h"
29 #include "rpc_server/common/proto.h"
30 #include "librpc/rpc/dcerpc_proto.h"
31 #include "system/filesys.h"
32 #include "libcli/security/security.h"
33 #include "param/param.h"
34 #include "../lib/tsocket/tsocket.h"
35 #include "../libcli/named_pipe_auth/npa_tstream.h"
36 #include "smbd/service_stream.h"
37 #include "../lib/tsocket/tsocket.h"
38 #include "lib/socket/socket.h"
39 #include "smbd/process_model.h"
40 #include "lib/messaging/irpc.h"
41 #include "librpc/rpc/rpc_common.h"
42 #include "lib/util/samba_modules.h"
43 #include "librpc/gen_ndr/ndr_dcerpc.h"
44 #include "../lib/util/tevent_ntstatus.h"
45
46 static NTSTATUS dcesrv_negotiate_contexts(struct dcesrv_call_state *call,
47                                 const struct dcerpc_bind *b,
48                                 struct dcerpc_ack_ctx *ack_ctx_list);
49
50 /*
51   find an association group given a assoc_group_id
52  */
53 static struct dcesrv_assoc_group *dcesrv_assoc_group_find(struct dcesrv_context *dce_ctx,
54                                                           uint32_t id)
55 {
56         void *id_ptr;
57
58         id_ptr = idr_find(dce_ctx->assoc_groups_idr, id);
59         if (id_ptr == NULL) {
60                 return NULL;
61         }
62         return talloc_get_type_abort(id_ptr, struct dcesrv_assoc_group);
63 }
64
65 /*
66   take a reference to an existing association group
67  */
68 static struct dcesrv_assoc_group *dcesrv_assoc_group_reference(TALLOC_CTX *mem_ctx,
69                                                                struct dcesrv_context *dce_ctx,
70                                                                uint32_t id)
71 {
72         struct dcesrv_assoc_group *assoc_group;
73
74         assoc_group = dcesrv_assoc_group_find(dce_ctx, id);
75         if (assoc_group == NULL) {
76                 DEBUG(2,(__location__ ": Failed to find assoc_group 0x%08x\n", id));
77                 return NULL;
78         }
79         return talloc_reference(mem_ctx, assoc_group);
80 }
81
82 static int dcesrv_assoc_group_destructor(struct dcesrv_assoc_group *assoc_group)
83 {
84         int ret;
85         ret = idr_remove(assoc_group->dce_ctx->assoc_groups_idr, assoc_group->id);
86         if (ret != 0) {
87                 DEBUG(0,(__location__ ": Failed to remove assoc_group 0x%08x\n",
88                          assoc_group->id));
89         }
90         return 0;
91 }
92
93 /*
94   allocate a new association group
95  */
96 static struct dcesrv_assoc_group *dcesrv_assoc_group_new(TALLOC_CTX *mem_ctx,
97                                                          struct dcesrv_context *dce_ctx)
98 {
99         struct dcesrv_assoc_group *assoc_group;
100         int id;
101
102         assoc_group = talloc_zero(mem_ctx, struct dcesrv_assoc_group);
103         if (assoc_group == NULL) {
104                 return NULL;
105         }
106         
107         id = idr_get_new_random(dce_ctx->assoc_groups_idr, assoc_group, UINT16_MAX);
108         if (id == -1) {
109                 talloc_free(assoc_group);
110                 DEBUG(0,(__location__ ": Out of association groups!\n"));
111                 return NULL;
112         }
113
114         assoc_group->id = id;
115         assoc_group->dce_ctx = dce_ctx;
116
117         talloc_set_destructor(assoc_group, dcesrv_assoc_group_destructor);
118
119         return assoc_group;
120 }
121
122
123 /*
124   see if two endpoints match
125 */
126 static bool endpoints_match(const struct dcerpc_binding *ep1,
127                             const struct dcerpc_binding *ep2)
128 {
129         enum dcerpc_transport_t t1;
130         enum dcerpc_transport_t t2;
131         const char *e1;
132         const char *e2;
133
134         t1 = dcerpc_binding_get_transport(ep1);
135         t2 = dcerpc_binding_get_transport(ep2);
136
137         e1 = dcerpc_binding_get_string_option(ep1, "endpoint");
138         e2 = dcerpc_binding_get_string_option(ep2, "endpoint");
139
140         if (t1 != t2) {
141                 return false;
142         }
143
144         if (!e1 || !e2) {
145                 return e1 == e2;
146         }
147
148         if (strcasecmp(e1, e2) != 0) {
149                 return false;
150         }
151
152         return true;
153 }
154
155 /*
156   find an endpoint in the dcesrv_context
157 */
158 static struct dcesrv_endpoint *find_endpoint(struct dcesrv_context *dce_ctx,
159                                              const struct dcerpc_binding *ep_description)
160 {
161         struct dcesrv_endpoint *ep;
162         for (ep=dce_ctx->endpoint_list; ep; ep=ep->next) {
163                 if (endpoints_match(ep->ep_description, ep_description)) {
164                         return ep;
165                 }
166         }
167         return NULL;
168 }
169
170 /*
171   find a registered context_id from a bind or alter_context
172 */
173 static struct dcesrv_connection_context *dcesrv_find_context(struct dcesrv_connection *conn, 
174                                                              uint16_t context_id)
175 {
176         struct dcesrv_connection_context *c;
177         for (c=conn->contexts;c;c=c->next) {
178                 if (c->context_id == context_id) return c;
179         }
180         return NULL;
181 }
182
183 /*
184   see if a uuid and if_version match to an interface
185 */
186 static bool interface_match(const struct dcesrv_interface *if1,
187                                                         const struct dcesrv_interface *if2)
188 {
189         return (if1->syntax_id.if_version == if2->syntax_id.if_version && 
190                         GUID_equal(&if1->syntax_id.uuid, &if2->syntax_id.uuid));
191 }
192
193 /*
194   find the interface operations on any endpoint with this binding
195 */
196 static const struct dcesrv_interface *find_interface_by_binding(struct dcesrv_context *dce_ctx,
197                                                                 struct dcerpc_binding *binding,
198                                                                 const struct dcesrv_interface *iface)
199 {
200         struct dcesrv_endpoint *ep;
201         for (ep=dce_ctx->endpoint_list; ep; ep=ep->next) {
202                 if (endpoints_match(ep->ep_description, binding)) {
203                         struct dcesrv_if_list *ifl;
204                         for (ifl=ep->interface_list; ifl; ifl=ifl->next) {
205                                 if (interface_match(&(ifl->iface), iface)) {
206                                         return &(ifl->iface);
207                                 }
208                         }
209                 }
210         }
211         return NULL;
212 }
213
214 /*
215   see if a uuid and if_version match to an interface
216 */
217 static bool interface_match_by_uuid(const struct dcesrv_interface *iface,
218                                     const struct GUID *uuid, uint32_t if_version)
219 {
220         return (iface->syntax_id.if_version == if_version && 
221                         GUID_equal(&iface->syntax_id.uuid, uuid));
222 }
223
224 /*
225   find the interface operations on an endpoint by uuid
226 */
227 const struct dcesrv_interface *find_interface_by_uuid(const struct dcesrv_endpoint *endpoint,
228                                                       const struct GUID *uuid, uint32_t if_version)
229 {
230         struct dcesrv_if_list *ifl;
231         for (ifl=endpoint->interface_list; ifl; ifl=ifl->next) {
232                 if (interface_match_by_uuid(&(ifl->iface), uuid, if_version)) {
233                         return &(ifl->iface);
234                 }
235         }
236         return NULL;
237 }
238
239 /*
240   find the earlier parts of a fragmented call awaiting reassembily
241 */
242 static struct dcesrv_call_state *dcesrv_find_fragmented_call(struct dcesrv_connection *dce_conn, uint32_t call_id)
243 {
244         struct dcesrv_call_state *c;
245         for (c=dce_conn->incoming_fragmented_call_list;c;c=c->next) {
246                 if (c->pkt.call_id == call_id) {
247                         return c;
248                 }
249         }
250         return NULL;
251 }
252
253 /*
254   register an interface on an endpoint
255
256   An endpoint is one unix domain socket (for ncalrpc), one TCP port
257   (for ncacn_ip_tcp) or one (forwarded) named pipe (for ncacn_np).
258
259   Each endpoint can have many interfaces such as netlogon, lsa or
260   samr.  Some have essentially the full set.
261
262   This is driven from the set of interfaces listed in each IDL file
263   via the PIDL generated *__op_init_server() functions.
264 */
265 _PUBLIC_ NTSTATUS dcesrv_interface_register(struct dcesrv_context *dce_ctx,
266                                    const char *ep_name,
267                                    const struct dcesrv_interface *iface,
268                                    const struct security_descriptor *sd)
269 {
270         struct dcesrv_endpoint *ep;
271         struct dcesrv_if_list *ifl;
272         struct dcerpc_binding *binding;
273         bool add_ep = false;
274         NTSTATUS status;
275         enum dcerpc_transport_t transport;
276         char *ep_string = NULL;
277         bool use_single_process = true;
278         const char *ep_process_string;
279
280         /*
281          * If we are not using handles, there is no need for force
282          * this service into using a single process.
283          *
284          * However, due to the way we listen for RPC packets, we can
285          * only do this if we have a single service per pipe or TCP
286          * port, so we still force a single combined process for
287          * ncalrpc.
288          */
289         if (iface->flags & DCESRV_INTERFACE_FLAGS_HANDLES_NOT_USED) {
290                 use_single_process = false;
291         }
292
293         status = dcerpc_parse_binding(dce_ctx, ep_name, &binding);
294
295         if (NT_STATUS_IS_ERR(status)) {
296                 DEBUG(0, ("Trouble parsing binding string '%s'\n", ep_name));
297                 return status;
298         }
299
300         transport = dcerpc_binding_get_transport(binding);
301         if (transport == NCACN_IP_TCP) {
302                 int port;
303                 char port_str[6];
304
305                 /* 
306                  * First check if there is already a port specified, eg
307                  * for epmapper on ncacn_ip_tcp:[135]
308                  */
309                 const char *endpoint
310                         = dcerpc_binding_get_string_option(binding,
311                                                            "endpoint");
312                 if (endpoint == NULL) {
313                         port = lpcfg_parm_int(dce_ctx->lp_ctx, NULL,
314                                               "rpc server port", iface->name, 0);
315                         
316                         /*
317                          * For RPC services that are not set to use a single
318                          * process, we do not default to using the 'rpc server
319                          * port' because that would cause a double-bind on
320                          * that port.
321                          */
322                         if (port == 0 && !use_single_process) {
323                                 port = lpcfg_rpc_server_port(dce_ctx->lp_ctx);
324                         }
325                         if (port != 0) {
326                                 snprintf(port_str, sizeof(port_str), "%u", port);
327                                 status = dcerpc_binding_set_string_option(binding,
328                                                                           "endpoint",
329                                                                           port_str);
330                                 if (!NT_STATUS_IS_OK(status)) {
331                                         return status;
332                                 }
333                         }
334                 }
335         }
336
337         /* see if the interface is already registered on the endpoint */
338         if (find_interface_by_binding(dce_ctx, binding, iface)!=NULL) {
339                 DEBUG(0,("dcesrv_interface_register: interface '%s' already registered on endpoint '%s'\n",
340                          iface->name, ep_name));
341                 return NT_STATUS_OBJECT_NAME_COLLISION;
342         }
343
344         /* check if this endpoint exists
345          */
346         ep = find_endpoint(dce_ctx, binding);
347
348         if (ep != NULL) {
349                 /*
350                  * We want a new port on ncacn_ip_tcp for NETLOGON, so
351                  * it can be multi-process.  Other processes can also
352                  * listen on distinct ports, if they have one forced
353                  * in the code above with eg 'rpc server port:drsuapi = 1027'
354                  *
355                  * If we have mulitiple endpoints on port 0, they each
356                  * get an epemeral port (currently by walking up from
357                  * 1024).
358                  *
359                  * Because one endpoint can only have one process
360                  * model, we add a new IP_TCP endpoint for each model.
361                  *
362                  * This works in conjunction with the forced overwrite
363                  * of ep->use_single_process below.
364                  */
365                 if (ep->use_single_process != use_single_process
366                     && transport == NCACN_IP_TCP) {
367                         add_ep = true;
368                 }
369         }
370
371         if (ep == NULL || add_ep) {
372                 ep = talloc_zero(dce_ctx, struct dcesrv_endpoint);
373                 if (!ep) {
374                         return NT_STATUS_NO_MEMORY;
375                 }
376                 ZERO_STRUCTP(ep);
377                 ep->ep_description = talloc_move(ep, &binding);
378                 add_ep = true;
379
380                 /* add mgmt interface */
381                 ifl = talloc_zero(ep, struct dcesrv_if_list);
382                 if (!ifl) {
383                         return NT_STATUS_NO_MEMORY;
384                 }
385
386                 ifl->iface = dcesrv_get_mgmt_interface();
387
388                 DLIST_ADD(ep->interface_list, ifl);
389         }
390
391         /*
392          * By default don't force into a single process, but if any
393          * interface on this endpoint on this service uses handles
394          * (most do), then we must force into single process mode
395          *
396          * By overwriting this each time a new interface is added to
397          * this endpoint, we end up with the most restrictive setting.
398          */
399         if (use_single_process) {
400                 ep->use_single_process = true;
401         }
402
403         /* talloc a new interface list element */
404         ifl = talloc_zero(ep, struct dcesrv_if_list);
405         if (!ifl) {
406                 return NT_STATUS_NO_MEMORY;
407         }
408
409         /* copy the given interface struct to the one on the endpoints interface list */
410         memcpy(&(ifl->iface),iface, sizeof(struct dcesrv_interface));
411
412         /* if we have a security descriptor given,
413          * we should see if we can set it up on the endpoint
414          */
415         if (sd != NULL) {
416                 /* if there's currently no security descriptor given on the endpoint
417                  * we try to set it
418                  */
419                 if (ep->sd == NULL) {
420                         ep->sd = security_descriptor_copy(ep, sd);
421                 }
422
423                 /* if now there's no security descriptor given on the endpoint
424                  * something goes wrong, either we failed to copy the security descriptor
425                  * or there was already one on the endpoint
426                  */
427                 if (ep->sd != NULL) {
428                         DEBUG(0,("dcesrv_interface_register: interface '%s' failed to setup a security descriptor\n"
429                                  "                           on endpoint '%s'\n",
430                                 iface->name, ep_name));
431                         if (add_ep) free(ep);
432                         free(ifl);
433                         return NT_STATUS_OBJECT_NAME_COLLISION;
434                 }
435         }
436
437         /* finally add the interface on the endpoint */
438         DLIST_ADD(ep->interface_list, ifl);
439
440         /* if it's a new endpoint add it to the dcesrv_context */
441         if (add_ep) {
442                 DLIST_ADD(dce_ctx->endpoint_list, ep);
443         }
444
445         /* Re-get the string as we may have set a port */
446         ep_string = dcerpc_binding_string(dce_ctx, ep->ep_description);
447
448         if (use_single_process) {
449                 ep_process_string = "single process required";
450         } else {
451                 ep_process_string = "multi process compatible";
452         }
453
454         DBG_INFO("dcesrv_interface_register: interface '%s' "
455                  "registered on endpoint '%s' (%s)\n",
456                  iface->name, ep_string, ep_process_string);
457         TALLOC_FREE(ep_string);
458
459         return NT_STATUS_OK;
460 }
461
462 NTSTATUS dcesrv_inherited_session_key(struct dcesrv_connection *p,
463                                       DATA_BLOB *session_key)
464 {
465         if (p->auth_state.session_info->session_key.length) {
466                 *session_key = p->auth_state.session_info->session_key;
467                 return NT_STATUS_OK;
468         }
469         return NT_STATUS_NO_USER_SESSION_KEY;
470 }
471
472 /*
473  * Fetch the authentication session key if available.
474  *
475  * This is the key generated by a gensec authentication.
476  *
477  */
478 _PUBLIC_ NTSTATUS dcesrv_auth_session_key(struct dcesrv_call_state *call,
479                                           DATA_BLOB *session_key)
480 {
481         return dcesrv_inherited_session_key(call->conn, session_key);
482 }
483
484 /*
485   fetch the user session key - may be default (above) or the SMB session key
486
487   The key is always truncated to 16 bytes 
488 */
489 _PUBLIC_ NTSTATUS dcesrv_fetch_session_key(struct dcesrv_connection *p,
490                                   DATA_BLOB *session_key)
491 {
492         struct dcesrv_auth *auth = &p->auth_state;
493         NTSTATUS status;
494
495         if (auth->session_key == NULL) {
496                 return NT_STATUS_NO_USER_SESSION_KEY;
497         }
498
499         status = auth->session_key(p, session_key);
500         if (!NT_STATUS_IS_OK(status)) {
501                 return status;
502         }
503
504         session_key->length = MIN(session_key->length, 16);
505
506         return NT_STATUS_OK;
507 }
508
509 /*
510  * Fetch the transport session key if available.
511  * Typically this is the SMB session key
512  * or a fixed key for local transports.
513  *
514  * The key is always truncated to 16 bytes.
515 */
516 _PUBLIC_ NTSTATUS dcesrv_transport_session_key(struct dcesrv_call_state *call,
517                                                DATA_BLOB *session_key)
518 {
519         return dcesrv_fetch_session_key(call->conn, session_key);
520 }
521
522 /*
523   connect to a dcerpc endpoint
524 */
525 _PUBLIC_ NTSTATUS dcesrv_endpoint_connect(struct dcesrv_context *dce_ctx,
526                                  TALLOC_CTX *mem_ctx,
527                                  const struct dcesrv_endpoint *ep,
528                                  struct auth_session_info *session_info,
529                                  struct tevent_context *event_ctx,
530                                  struct imessaging_context *msg_ctx,
531                                  struct server_id server_id,
532                                  uint32_t state_flags,
533                                  struct dcesrv_connection **_p)
534 {
535         struct dcesrv_connection *p;
536
537         if (!session_info) {
538                 return NT_STATUS_ACCESS_DENIED;
539         }
540
541         p = talloc_zero(mem_ctx, struct dcesrv_connection);
542         NT_STATUS_HAVE_NO_MEMORY(p);
543
544         if (!talloc_reference(p, session_info)) {
545                 talloc_free(p);
546                 return NT_STATUS_NO_MEMORY;
547         }
548
549         p->dce_ctx = dce_ctx;
550         p->endpoint = ep;
551         p->packet_log_dir = lpcfg_lock_directory(dce_ctx->lp_ctx);
552         p->auth_state.session_info = session_info;
553         p->auth_state.session_key = dcesrv_generic_session_key;
554         p->event_ctx = event_ctx;
555         p->msg_ctx = msg_ctx;
556         p->server_id = server_id;
557         p->state_flags = state_flags;
558         p->allow_bind = true;
559         p->max_recv_frag = 5840;
560         p->max_xmit_frag = 5840;
561         p->max_total_request_size = DCERPC_NCACN_REQUEST_DEFAULT_MAX_SIZE;
562
563         /*
564          * For now we only support NDR32.
565          */
566         p->preferred_transfer = &ndr_transfer_syntax_ndr;
567
568         *_p = p;
569         return NT_STATUS_OK;
570 }
571
572 /*
573   move a call from an existing linked list to the specified list. This
574   prevents bugs where we forget to remove the call from a previous
575   list when moving it.
576  */
577 static void dcesrv_call_set_list(struct dcesrv_call_state *call, 
578                                  enum dcesrv_call_list list)
579 {
580         switch (call->list) {
581         case DCESRV_LIST_NONE:
582                 break;
583         case DCESRV_LIST_CALL_LIST:
584                 DLIST_REMOVE(call->conn->call_list, call);
585                 break;
586         case DCESRV_LIST_FRAGMENTED_CALL_LIST:
587                 DLIST_REMOVE(call->conn->incoming_fragmented_call_list, call);
588                 break;
589         case DCESRV_LIST_PENDING_CALL_LIST:
590                 DLIST_REMOVE(call->conn->pending_call_list, call);
591                 break;
592         }
593         call->list = list;
594         switch (list) {
595         case DCESRV_LIST_NONE:
596                 break;
597         case DCESRV_LIST_CALL_LIST:
598                 DLIST_ADD_END(call->conn->call_list, call);
599                 break;
600         case DCESRV_LIST_FRAGMENTED_CALL_LIST:
601                 DLIST_ADD_END(call->conn->incoming_fragmented_call_list, call);
602                 break;
603         case DCESRV_LIST_PENDING_CALL_LIST:
604                 DLIST_ADD_END(call->conn->pending_call_list, call);
605                 break;
606         }
607 }
608
609 static void dcesrv_call_disconnect_after(struct dcesrv_call_state *call,
610                                          const char *reason)
611 {
612         if (call->conn->terminate != NULL) {
613                 return;
614         }
615
616         call->conn->allow_bind = false;
617         call->conn->allow_alter = false;
618         call->conn->allow_auth3 = false;
619         call->conn->allow_request = false;
620
621         call->terminate_reason = talloc_strdup(call, reason);
622         if (call->terminate_reason == NULL) {
623                 call->terminate_reason = __location__;
624         }
625 }
626
627 /*
628   return a dcerpc bind_nak
629 */
630 static NTSTATUS dcesrv_bind_nak(struct dcesrv_call_state *call, uint32_t reason)
631 {
632         struct ncacn_packet pkt;
633         struct dcerpc_bind_nak_version version;
634         struct data_blob_list_item *rep;
635         NTSTATUS status;
636         static const uint8_t _pad[3] = { 0, };
637
638         /*
639          * We add the call to the pending_call_list
640          * in order to defer the termination.
641          */
642         dcesrv_call_disconnect_after(call, "dcesrv_bind_nak");
643
644         /* setup a bind_nak */
645         dcesrv_init_hdr(&pkt, lpcfg_rpc_big_endian(call->conn->dce_ctx->lp_ctx));
646         pkt.auth_length = 0;
647         pkt.call_id = call->pkt.call_id;
648         pkt.ptype = DCERPC_PKT_BIND_NAK;
649         pkt.pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST;
650         pkt.u.bind_nak.reject_reason = reason;
651         version.rpc_vers = 5;
652         version.rpc_vers_minor = 0;
653         pkt.u.bind_nak.num_versions = 1;
654         pkt.u.bind_nak.versions = &version;
655         pkt.u.bind_nak._pad = data_blob_const(_pad, sizeof(_pad));
656
657         rep = talloc_zero(call, struct data_blob_list_item);
658         if (!rep) {
659                 return NT_STATUS_NO_MEMORY;
660         }
661
662         status = ncacn_push_auth(&rep->blob, call, &pkt, NULL);
663         if (!NT_STATUS_IS_OK(status)) {
664                 return status;
665         }
666
667         dcerpc_set_frag_length(&rep->blob, rep->blob.length);
668
669         DLIST_ADD_END(call->replies, rep);
670         dcesrv_call_set_list(call, DCESRV_LIST_CALL_LIST);
671
672         if (call->conn->call_list && call->conn->call_list->replies) {
673                 if (call->conn->transport.report_output_data) {
674                         call->conn->transport.report_output_data(call->conn);
675                 }
676         }
677
678         return NT_STATUS_OK;    
679 }
680
681 static NTSTATUS dcesrv_fault_disconnect(struct dcesrv_call_state *call,
682                                  uint32_t fault_code)
683 {
684         /*
685          * We add the call to the pending_call_list
686          * in order to defer the termination.
687          */
688         dcesrv_call_disconnect_after(call, "dcesrv_fault_disconnect");
689
690         return dcesrv_fault_with_flags(call, fault_code,
691                                        DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
692 }
693
694 static int dcesrv_connection_context_destructor(struct dcesrv_connection_context *c)
695 {
696         DLIST_REMOVE(c->conn->contexts, c);
697
698         if (c->iface && c->iface->unbind) {
699                 c->iface->unbind(c, c->iface);
700                 c->iface = NULL;
701         }
702
703         return 0;
704 }
705
706 static void dcesrv_prepare_context_auth(struct dcesrv_call_state *dce_call)
707 {
708         struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
709         const struct dcesrv_endpoint *endpoint = dce_call->conn->endpoint;
710         enum dcerpc_transport_t transport =
711                 dcerpc_binding_get_transport(endpoint->ep_description);
712         struct dcesrv_connection_context *context = dce_call->context;
713         const struct dcesrv_interface *iface = context->iface;
714
715         context->min_auth_level = DCERPC_AUTH_LEVEL_NONE;
716
717         if (transport == NCALRPC) {
718                 context->allow_connect = true;
719                 return;
720         }
721
722         /*
723          * allow overwrite per interface
724          * allow dcerpc auth level connect:<interface>
725          */
726         context->allow_connect = lpcfg_allow_dcerpc_auth_level_connect(lp_ctx);
727         context->allow_connect = lpcfg_parm_bool(lp_ctx, NULL,
728                                         "allow dcerpc auth level connect",
729                                         iface->name,
730                                         context->allow_connect);
731 }
732
733 NTSTATUS dcesrv_interface_bind_require_integrity(struct dcesrv_call_state *dce_call,
734                                                  const struct dcesrv_interface *iface)
735 {
736         if (dce_call->context == NULL) {
737                 return NT_STATUS_INTERNAL_ERROR;
738         }
739
740         /*
741          * For connection oriented DCERPC DCERPC_AUTH_LEVEL_PACKET (4)
742          * has the same behavior as DCERPC_AUTH_LEVEL_INTEGRITY (5).
743          */
744         dce_call->context->min_auth_level = DCERPC_AUTH_LEVEL_PACKET;
745         return NT_STATUS_OK;
746 }
747
748 NTSTATUS dcesrv_interface_bind_require_privacy(struct dcesrv_call_state *dce_call,
749                                                const struct dcesrv_interface *iface)
750 {
751         if (dce_call->context == NULL) {
752                 return NT_STATUS_INTERNAL_ERROR;
753         }
754
755         dce_call->context->min_auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
756         return NT_STATUS_OK;
757 }
758
759 _PUBLIC_ NTSTATUS dcesrv_interface_bind_reject_connect(struct dcesrv_call_state *dce_call,
760                                                        const struct dcesrv_interface *iface)
761 {
762         struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
763         const struct dcesrv_endpoint *endpoint = dce_call->conn->endpoint;
764         enum dcerpc_transport_t transport =
765                 dcerpc_binding_get_transport(endpoint->ep_description);
766         struct dcesrv_connection_context *context = dce_call->context;
767
768         if (context == NULL) {
769                 return NT_STATUS_INTERNAL_ERROR;
770         }
771
772         if (transport == NCALRPC) {
773                 context->allow_connect = true;
774                 return NT_STATUS_OK;
775         }
776
777         /*
778          * allow overwrite per interface
779          * allow dcerpc auth level connect:<interface>
780          */
781         context->allow_connect = false;
782         context->allow_connect = lpcfg_parm_bool(lp_ctx, NULL,
783                                         "allow dcerpc auth level connect",
784                                         iface->name,
785                                         context->allow_connect);
786         return NT_STATUS_OK;
787 }
788
789 _PUBLIC_ NTSTATUS dcesrv_interface_bind_allow_connect(struct dcesrv_call_state *dce_call,
790                                                       const struct dcesrv_interface *iface)
791 {
792         struct loadparm_context *lp_ctx = dce_call->conn->dce_ctx->lp_ctx;
793         const struct dcesrv_endpoint *endpoint = dce_call->conn->endpoint;
794         enum dcerpc_transport_t transport =
795                 dcerpc_binding_get_transport(endpoint->ep_description);
796         struct dcesrv_connection_context *context = dce_call->context;
797
798         if (context == NULL) {
799                 return NT_STATUS_INTERNAL_ERROR;
800         }
801
802         if (transport == NCALRPC) {
803                 context->allow_connect = true;
804                 return NT_STATUS_OK;
805         }
806
807         /*
808          * allow overwrite per interface
809          * allow dcerpc auth level connect:<interface>
810          */
811         context->allow_connect = true;
812         context->allow_connect = lpcfg_parm_bool(lp_ctx, NULL,
813                                         "allow dcerpc auth level connect",
814                                         iface->name,
815                                         context->allow_connect);
816         return NT_STATUS_OK;
817 }
818
819 struct dcesrv_conn_auth_wait_context {
820         struct tevent_req *req;
821         bool done;
822         NTSTATUS status;
823 };
824
825 struct dcesrv_conn_auth_wait_state {
826         uint8_t dummy;
827 };
828
829 static struct tevent_req *dcesrv_conn_auth_wait_send(TALLOC_CTX *mem_ctx,
830                                                      struct tevent_context *ev,
831                                                      void *private_data)
832 {
833         struct dcesrv_conn_auth_wait_context *auth_wait =
834                 talloc_get_type_abort(private_data,
835                 struct dcesrv_conn_auth_wait_context);
836         struct tevent_req *req = NULL;
837         struct dcesrv_conn_auth_wait_state *state = NULL;
838
839         req = tevent_req_create(mem_ctx, &state,
840                                 struct dcesrv_conn_auth_wait_state);
841         if (req == NULL) {
842                 return NULL;
843         }
844         auth_wait->req = req;
845
846         tevent_req_defer_callback(req, ev);
847
848         if (!auth_wait->done) {
849                 return req;
850         }
851
852         if (tevent_req_nterror(req, auth_wait->status)) {
853                 return tevent_req_post(req, ev);
854         }
855
856         tevent_req_done(req);
857         return tevent_req_post(req, ev);
858 }
859
860 static NTSTATUS dcesrv_conn_auth_wait_recv(struct tevent_req *req)
861 {
862         return tevent_req_simple_recv_ntstatus(req);
863 }
864
865 static NTSTATUS dcesrv_conn_auth_wait_setup(struct dcesrv_connection *conn)
866 {
867         struct dcesrv_conn_auth_wait_context *auth_wait = NULL;
868
869         if (conn->wait_send != NULL) {
870                 return NT_STATUS_INTERNAL_ERROR;
871         }
872
873         auth_wait = talloc_zero(conn, struct dcesrv_conn_auth_wait_context);
874         if (auth_wait == NULL) {
875                 return NT_STATUS_NO_MEMORY;
876         }
877
878         conn->wait_private = auth_wait;
879         conn->wait_send = dcesrv_conn_auth_wait_send;
880         conn->wait_recv = dcesrv_conn_auth_wait_recv;
881         return NT_STATUS_OK;
882 }
883
884 static void dcesrv_conn_auth_wait_finished(struct dcesrv_connection *conn,
885                                            NTSTATUS status)
886 {
887         struct dcesrv_conn_auth_wait_context *auth_wait =
888                 talloc_get_type_abort(conn->wait_private,
889                 struct dcesrv_conn_auth_wait_context);
890
891         auth_wait->done = true;
892         auth_wait->status = status;
893
894         if (auth_wait->req == NULL) {
895                 return;
896         }
897
898         if (tevent_req_nterror(auth_wait->req, status)) {
899                 return;
900         }
901
902         tevent_req_done(auth_wait->req);
903 }
904
905 static NTSTATUS dcesrv_auth_reply(struct dcesrv_call_state *call);
906
907 static void dcesrv_bind_done(struct tevent_req *subreq);
908
909 /*
910   handle a bind request
911 */
912 static NTSTATUS dcesrv_bind(struct dcesrv_call_state *call)
913 {
914         struct dcesrv_connection *conn = call->conn;
915         struct ncacn_packet *pkt = &call->ack_pkt;
916         NTSTATUS status;
917         uint32_t extra_flags = 0;
918         uint16_t max_req = 0;
919         uint16_t max_rep = 0;
920         const char *ep_prefix = "";
921         const char *endpoint = NULL;
922         struct dcesrv_auth *auth = &call->conn->auth_state;
923         struct dcerpc_ack_ctx *ack_ctx_list = NULL;
924         struct dcerpc_ack_ctx *ack_features = NULL;
925         struct tevent_req *subreq = NULL;
926         size_t i;
927
928         status = dcerpc_verify_ncacn_packet_header(&call->pkt,
929                         DCERPC_PKT_BIND,
930                         call->pkt.u.bind.auth_info.length,
931                         0, /* required flags */
932                         DCERPC_PFC_FLAG_FIRST |
933                         DCERPC_PFC_FLAG_LAST |
934                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
935                         0x08 | /* this is not defined, but should be ignored */
936                         DCERPC_PFC_FLAG_CONC_MPX |
937                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
938                         DCERPC_PFC_FLAG_MAYBE |
939                         DCERPC_PFC_FLAG_OBJECT_UUID);
940         if (!NT_STATUS_IS_OK(status)) {
941                 return dcesrv_bind_nak(call,
942                         DCERPC_BIND_NAK_REASON_PROTOCOL_VERSION_NOT_SUPPORTED);
943         }
944
945         /* max_recv_frag and max_xmit_frag result always in the same value! */
946         max_req = MIN(call->pkt.u.bind.max_xmit_frag,
947                       call->pkt.u.bind.max_recv_frag);
948         /*
949          * The values are between 2048 and 5840 tested against Windows 2012R2
950          * via ncacn_ip_tcp on port 135.
951          */
952         max_req = MAX(2048, max_req);
953         max_rep = MIN(max_req, call->conn->max_recv_frag);
954         /* They are truncated to an 8 byte boundary. */
955         max_rep &= 0xFFF8;
956
957         /* max_recv_frag and max_xmit_frag result always in the same value! */
958         call->conn->max_recv_frag = max_rep;
959         call->conn->max_xmit_frag = max_rep;
960
961         /*
962           if provided, check the assoc_group is valid
963          */
964         if (call->pkt.u.bind.assoc_group_id != 0) {
965                 call->conn->assoc_group = dcesrv_assoc_group_reference(call->conn,
966                                                                        call->conn->dce_ctx,
967                                                                        call->pkt.u.bind.assoc_group_id);
968         } else {
969                 call->conn->assoc_group = dcesrv_assoc_group_new(call->conn,
970                                                                  call->conn->dce_ctx);
971         }
972
973         /*
974          * The NETLOGON server does not use handles and so
975          * there is no need to support association groups, but
976          * we need to give back a number regardless.
977          *
978          * We have to do this when it is not run as a single process,
979          * because then it can't see the other valid association
980          * groups.  We handle this genericly for all endpoints not
981          * running in single process mode.
982          *
983          * We know which endpoint we are on even before checking the
984          * iface UUID, so for simplicity we enforce the same policy
985          * for all interfaces on the endpoint.
986          *
987          * This means that where NETLOGON
988          * shares an endpoint (such as ncalrpc or of 'lsa over
989          * netlogon' is set) we will still check association groups.
990          *
991          */
992
993         if (call->conn->assoc_group == NULL &&
994             !call->conn->endpoint->use_single_process) {
995                 call->conn->assoc_group
996                         = dcesrv_assoc_group_new(call->conn,
997                                                  call->conn->dce_ctx);
998         }
999         if (call->conn->assoc_group == NULL) {
1000                 return dcesrv_bind_nak(call, 0);
1001         }
1002
1003         if (call->pkt.u.bind.num_contexts < 1) {
1004                 return dcesrv_bind_nak(call, 0);
1005         }
1006
1007         ack_ctx_list = talloc_zero_array(call, struct dcerpc_ack_ctx,
1008                                          call->pkt.u.bind.num_contexts);
1009         if (ack_ctx_list == NULL) {
1010                 return dcesrv_bind_nak(call, 0);
1011         }
1012
1013         /*
1014          * Set some sane defaults (required by dcesrv_negotiate_contexts()/
1015          * dcesrv_check_or_create_context()) and do some protocol validation
1016          * and set sane defaults.
1017          */
1018         for (i = 0; i < call->pkt.u.bind.num_contexts; i++) {
1019                 const struct dcerpc_ctx_list *c = &call->pkt.u.bind.ctx_list[i];
1020                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1021                 bool is_feature = false;
1022                 uint64_t features = 0;
1023
1024                 if (c->num_transfer_syntaxes == 0) {
1025                         return dcesrv_bind_nak(call, 0);
1026                 }
1027
1028                 a->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1029                 a->reason.value = DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
1030
1031                 /*
1032                  * It's only treated as bind time feature request, if the first
1033                  * transfer_syntax matches, all others are ignored.
1034                  */
1035                 is_feature = dcerpc_extract_bind_time_features(c->transfer_syntaxes[0],
1036                                                                &features);
1037                 if (!is_feature) {
1038                         continue;
1039                 }
1040
1041                 if (ack_features != NULL) {
1042                         /*
1043                          * Only one bind time feature context is allowed.
1044                          */
1045                         return dcesrv_bind_nak(call, 0);
1046                 }
1047                 ack_features = a;
1048
1049                 a->result = DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK;
1050                 a->reason.negotiate = 0;
1051                 if (features & DCERPC_BIND_TIME_SECURITY_CONTEXT_MULTIPLEXING) {
1052                         /* not supported yet */
1053                 }
1054                 if (features & DCERPC_BIND_TIME_KEEP_CONNECTION_ON_ORPHAN) {
1055                         a->reason.negotiate |=
1056                                 DCERPC_BIND_TIME_KEEP_CONNECTION_ON_ORPHAN;
1057                 }
1058
1059                 call->conn->bind_time_features = a->reason.negotiate;
1060         }
1061
1062         /*
1063          * Try to negotiate one new presentation context.
1064          *
1065          * Deep in here we locate the iface (by uuid) that the client
1066          * requested, from the list of interfaces on the
1067          * call->conn->endpoint, and call iface->bind() on that iface.
1068          *
1069          * call->conn was set up at the accept() of the socket, and
1070          * call->conn->endpoint has a list of interfaces restricted to
1071          * this port or pipe.
1072          */
1073         status = dcesrv_negotiate_contexts(call, &call->pkt.u.bind, ack_ctx_list);
1074         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROTOCOL_ERROR)) {
1075                 return dcesrv_bind_nak(call, 0);
1076         }
1077         if (!NT_STATUS_IS_OK(status)) {
1078                 return status;
1079         }
1080
1081         /*
1082          * At this point we still don't know which interface (eg
1083          * netlogon, lsa, drsuapi) the caller requested in this bind!
1084          * The most recently added context is available as the first
1085          * element in the linked list at call->conn->contexts, that is
1086          * call->conn->contexts->iface, but they may not have
1087          * requested one at all!
1088          */
1089
1090         if ((call->pkt.pfc_flags & DCERPC_PFC_FLAG_CONC_MPX) &&
1091             (call->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
1092                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_MULTIPLEXED;
1093                 extra_flags |= DCERPC_PFC_FLAG_CONC_MPX;
1094         }
1095
1096         if (call->state_flags & DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL) {
1097                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL;
1098         }
1099
1100         /*
1101          * After finding the interface and setting up the NDR
1102          * transport negotiation etc, handle any authentication that
1103          * is being requested.
1104          */
1105         if (!dcesrv_auth_bind(call)) {
1106
1107                 if (auth->auth_level == DCERPC_AUTH_LEVEL_NONE) {
1108                         /*
1109                          * With DCERPC_AUTH_LEVEL_NONE, we get the
1110                          * reject_reason in auth->auth_context_id.
1111                          */
1112                         return dcesrv_bind_nak(call, auth->auth_context_id);
1113                 }
1114
1115                 /*
1116                  * This must a be a temporary failure e.g. talloc or invalid
1117                  * configuration, e.g. no machine account.
1118                  */
1119                 return dcesrv_bind_nak(call,
1120                                 DCERPC_BIND_NAK_REASON_TEMPORARY_CONGESTION);
1121         }
1122
1123         /* setup a bind_ack */
1124         dcesrv_init_hdr(pkt, lpcfg_rpc_big_endian(call->conn->dce_ctx->lp_ctx));
1125         pkt->auth_length = 0;
1126         pkt->call_id = call->pkt.call_id;
1127         pkt->ptype = DCERPC_PKT_BIND_ACK;
1128         pkt->pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST | extra_flags;
1129         pkt->u.bind_ack.max_xmit_frag = call->conn->max_xmit_frag;
1130         pkt->u.bind_ack.max_recv_frag = call->conn->max_recv_frag;
1131         pkt->u.bind_ack.assoc_group_id = call->conn->assoc_group->id;
1132
1133         endpoint = dcerpc_binding_get_string_option(
1134                                 call->conn->endpoint->ep_description,
1135                                 "endpoint");
1136         if (endpoint == NULL) {
1137                 endpoint = "";
1138         }
1139
1140         if (strncasecmp(endpoint, "\\pipe\\", 6) == 0) {
1141                 /*
1142                  * TODO: check if this is really needed
1143                  *
1144                  * Or if we should fix this in our idl files.
1145                  */
1146                 ep_prefix = "\\PIPE\\";
1147                 endpoint += 6;
1148         }
1149
1150         pkt->u.bind_ack.secondary_address = talloc_asprintf(call, "%s%s",
1151                                                            ep_prefix,
1152                                                            endpoint);
1153         if (pkt->u.bind_ack.secondary_address == NULL) {
1154                 return NT_STATUS_NO_MEMORY;
1155         }
1156         pkt->u.bind_ack.num_results = call->pkt.u.bind.num_contexts;
1157         pkt->u.bind_ack.ctx_list = ack_ctx_list;
1158         pkt->u.bind_ack.auth_info = data_blob_null;
1159
1160         status = dcesrv_auth_prepare_bind_ack(call, pkt);
1161         if (!NT_STATUS_IS_OK(status)) {
1162                 return dcesrv_bind_nak(call, 0);
1163         }
1164
1165         if (auth->auth_finished) {
1166                 return dcesrv_auth_reply(call);
1167         }
1168
1169         subreq = gensec_update_send(call, call->event_ctx,
1170                                     auth->gensec_security,
1171                                     call->in_auth_info.credentials);
1172         if (subreq == NULL) {
1173                 return NT_STATUS_NO_MEMORY;
1174         }
1175         tevent_req_set_callback(subreq, dcesrv_bind_done, call);
1176
1177         return dcesrv_conn_auth_wait_setup(conn);
1178 }
1179
1180 static void dcesrv_bind_done(struct tevent_req *subreq)
1181 {
1182         struct dcesrv_call_state *call =
1183                 tevent_req_callback_data(subreq,
1184                 struct dcesrv_call_state);
1185         struct dcesrv_connection *conn = call->conn;
1186         NTSTATUS status;
1187
1188         status = gensec_update_recv(subreq, call,
1189                                     &call->out_auth_info->credentials);
1190         TALLOC_FREE(subreq);
1191
1192         status = dcesrv_auth_complete(call, status);
1193         if (!NT_STATUS_IS_OK(status)) {
1194                 status = dcesrv_bind_nak(call, 0);
1195                 dcesrv_conn_auth_wait_finished(conn, status);
1196                 return;
1197         }
1198
1199         status = dcesrv_auth_reply(call);
1200         dcesrv_conn_auth_wait_finished(conn, status);
1201         return;
1202 }
1203
1204 static NTSTATUS dcesrv_auth_reply(struct dcesrv_call_state *call)
1205 {
1206         struct ncacn_packet *pkt = &call->ack_pkt;
1207         struct data_blob_list_item *rep = NULL;
1208         NTSTATUS status;
1209
1210         rep = talloc_zero(call, struct data_blob_list_item);
1211         if (!rep) {
1212                 return NT_STATUS_NO_MEMORY;
1213         }
1214
1215         status = ncacn_push_auth(&rep->blob, call, pkt,
1216                                  call->out_auth_info);
1217         if (!NT_STATUS_IS_OK(status)) {
1218                 return status;
1219         }
1220
1221         dcerpc_set_frag_length(&rep->blob, rep->blob.length);
1222
1223         DLIST_ADD_END(call->replies, rep);
1224         dcesrv_call_set_list(call, DCESRV_LIST_CALL_LIST);
1225
1226         if (call->conn->call_list && call->conn->call_list->replies) {
1227                 if (call->conn->transport.report_output_data) {
1228                         call->conn->transport.report_output_data(call->conn);
1229                 }
1230         }
1231
1232         return NT_STATUS_OK;
1233 }
1234
1235
1236 static void dcesrv_auth3_done(struct tevent_req *subreq);
1237
1238 /*
1239   handle a auth3 request
1240 */
1241 static NTSTATUS dcesrv_auth3(struct dcesrv_call_state *call)
1242 {
1243         struct dcesrv_connection *conn = call->conn;
1244         struct dcesrv_auth *auth = &call->conn->auth_state;
1245         struct tevent_req *subreq = NULL;
1246         NTSTATUS status;
1247
1248         if (!call->conn->allow_auth3) {
1249                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1250         }
1251
1252         if (call->conn->auth_state.auth_finished) {
1253                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1254         }
1255
1256         status = dcerpc_verify_ncacn_packet_header(&call->pkt,
1257                         DCERPC_PKT_AUTH3,
1258                         call->pkt.u.auth3.auth_info.length,
1259                         0, /* required flags */
1260                         DCERPC_PFC_FLAG_FIRST |
1261                         DCERPC_PFC_FLAG_LAST |
1262                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1263                         0x08 | /* this is not defined, but should be ignored */
1264                         DCERPC_PFC_FLAG_CONC_MPX |
1265                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1266                         DCERPC_PFC_FLAG_MAYBE |
1267                         DCERPC_PFC_FLAG_OBJECT_UUID);
1268         if (!NT_STATUS_IS_OK(status)) {
1269                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1270         }
1271
1272         /* handle the auth3 in the auth code */
1273         if (!dcesrv_auth_prepare_auth3(call)) {
1274                 /*
1275                  * we don't send a reply to a auth3 request,
1276                  * except by a fault.
1277                  *
1278                  * In anycase we mark the connection as
1279                  * invalid.
1280                  */
1281                 call->conn->auth_state.auth_invalid = true;
1282                 if (call->fault_code != 0) {
1283                         return dcesrv_fault_disconnect(call, call->fault_code);
1284                 }
1285                 TALLOC_FREE(call);
1286                 return NT_STATUS_OK;
1287         }
1288
1289         subreq = gensec_update_send(call, call->event_ctx,
1290                                     auth->gensec_security,
1291                                     call->in_auth_info.credentials);
1292         if (subreq == NULL) {
1293                 return NT_STATUS_NO_MEMORY;
1294         }
1295         tevent_req_set_callback(subreq, dcesrv_auth3_done, call);
1296
1297         return dcesrv_conn_auth_wait_setup(conn);
1298 }
1299
1300 static void dcesrv_auth3_done(struct tevent_req *subreq)
1301 {
1302         struct dcesrv_call_state *call =
1303                 tevent_req_callback_data(subreq,
1304                 struct dcesrv_call_state);
1305         struct dcesrv_connection *conn = call->conn;
1306         NTSTATUS status;
1307
1308         status = gensec_update_recv(subreq, call,
1309                                     &call->out_auth_info->credentials);
1310         TALLOC_FREE(subreq);
1311
1312         status = dcesrv_auth_complete(call, status);
1313         if (!NT_STATUS_IS_OK(status)) {
1314                 /*
1315                  * we don't send a reply to a auth3 request,
1316                  * except by a fault.
1317                  *
1318                  * In anycase we mark the connection as
1319                  * invalid.
1320                  */
1321                 call->conn->auth_state.auth_invalid = true;
1322                 if (call->fault_code != 0) {
1323                         status = dcesrv_fault_disconnect(call, call->fault_code);
1324                         dcesrv_conn_auth_wait_finished(conn, status);
1325                         return;
1326                 }
1327                 TALLOC_FREE(call);
1328                 dcesrv_conn_auth_wait_finished(conn, NT_STATUS_OK);
1329                 return;
1330         }
1331
1332         /*
1333          * we don't send a reply to a auth3 request.
1334          */
1335         TALLOC_FREE(call);
1336         dcesrv_conn_auth_wait_finished(conn, NT_STATUS_OK);
1337         return;
1338 }
1339
1340
1341 static NTSTATUS dcesrv_check_or_create_context(struct dcesrv_call_state *call,
1342                                 const struct dcerpc_bind *b,
1343                                 const struct dcerpc_ctx_list *ctx,
1344                                 struct dcerpc_ack_ctx *ack,
1345                                 bool validate_only,
1346                                 const struct ndr_syntax_id *supported_transfer)
1347 {
1348         uint32_t if_version;
1349         struct dcesrv_connection_context *context;
1350         const struct dcesrv_interface *iface;
1351         struct GUID uuid;
1352         NTSTATUS status;
1353         const struct ndr_syntax_id *selected_transfer = NULL;
1354         size_t i;
1355         bool ok;
1356
1357         if (b == NULL) {
1358                 return NT_STATUS_INTERNAL_ERROR;
1359         }
1360         if (ctx == NULL) {
1361                 return NT_STATUS_INTERNAL_ERROR;
1362         }
1363         if (ctx->num_transfer_syntaxes < 1) {
1364                 return NT_STATUS_INTERNAL_ERROR;
1365         }
1366         if (ack == NULL) {
1367                 return NT_STATUS_INTERNAL_ERROR;
1368         }
1369         if (supported_transfer == NULL) {
1370                 return NT_STATUS_INTERNAL_ERROR;
1371         }
1372
1373         switch (ack->result) {
1374         case DCERPC_BIND_ACK_RESULT_ACCEPTANCE:
1375         case DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK:
1376                 /*
1377                  * We is already completed.
1378                  */
1379                 return NT_STATUS_OK;
1380         default:
1381                 break;
1382         }
1383
1384         ack->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1385         ack->reason.value = DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
1386
1387         if_version = ctx->abstract_syntax.if_version;
1388         uuid = ctx->abstract_syntax.uuid;
1389
1390         iface = find_interface_by_uuid(call->conn->endpoint, &uuid, if_version);
1391         if (iface == NULL) {
1392                 char *uuid_str = GUID_string(call, &uuid);
1393                 DEBUG(2,("Request for unknown dcerpc interface %s/%d\n", uuid_str, if_version));
1394                 talloc_free(uuid_str);
1395                 /*
1396                  * We report this only via ack->result
1397                  */
1398                 return NT_STATUS_OK;
1399         }
1400
1401         ack->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1402         ack->reason.value = DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED;
1403
1404         if (validate_only) {
1405                 /*
1406                  * We report this only via ack->result
1407                  */
1408                 return NT_STATUS_OK;
1409         }
1410
1411         for (i = 0; i < ctx->num_transfer_syntaxes; i++) {
1412                 /*
1413                  * we only do NDR encoded dcerpc for now.
1414                  */
1415                 ok = ndr_syntax_id_equal(&ctx->transfer_syntaxes[i],
1416                                          supported_transfer);
1417                 if (ok) {
1418                         selected_transfer = supported_transfer;
1419                         break;
1420                 }
1421         }
1422
1423         context = dcesrv_find_context(call->conn, ctx->context_id);
1424         if (context != NULL) {
1425                 ok = ndr_syntax_id_equal(&context->iface->syntax_id,
1426                                          &ctx->abstract_syntax);
1427                 if (!ok) {
1428                         return NT_STATUS_RPC_PROTOCOL_ERROR;
1429                 }
1430
1431                 if (selected_transfer != NULL) {
1432                         ok = ndr_syntax_id_equal(&context->transfer_syntax,
1433                                                  selected_transfer);
1434                         if (!ok) {
1435                                 return NT_STATUS_RPC_PROTOCOL_ERROR;
1436                         }
1437
1438                         ack->result = DCERPC_BIND_ACK_RESULT_ACCEPTANCE;
1439                         ack->reason.value = DCERPC_BIND_ACK_REASON_NOT_SPECIFIED;
1440                         ack->syntax = context->transfer_syntax;
1441                 }
1442
1443                 /*
1444                  * We report this only via ack->result
1445                  */
1446                 return NT_STATUS_OK;
1447         }
1448
1449         if (selected_transfer == NULL) {
1450                 /*
1451                  * We report this only via ack->result
1452                  */
1453                 return NT_STATUS_OK;
1454         }
1455
1456         ack->result = DCERPC_BIND_ACK_RESULT_USER_REJECTION;
1457         ack->reason.value = DCERPC_BIND_ACK_REASON_LOCAL_LIMIT_EXCEEDED;
1458
1459         /* add this context to the list of available context_ids */
1460         context = talloc_zero(call->conn, struct dcesrv_connection_context);
1461         if (context == NULL) {
1462                 return NT_STATUS_NO_MEMORY;
1463         }
1464         context->conn = call->conn;
1465         context->context_id = ctx->context_id;
1466         context->iface = iface;
1467         context->transfer_syntax = *selected_transfer;
1468         context->private_data = NULL;
1469         DLIST_ADD(call->conn->contexts, context);
1470         call->context = context;
1471         talloc_set_destructor(context, dcesrv_connection_context_destructor);
1472
1473         dcesrv_prepare_context_auth(call);
1474
1475         /*
1476          * Multiplex is supported by default
1477          */
1478         call->state_flags |= DCESRV_CALL_STATE_FLAG_MULTIPLEXED;
1479
1480         status = iface->bind(call, iface, if_version);
1481         call->context = NULL;
1482         if (!NT_STATUS_IS_OK(status)) {
1483                 /* we don't want to trigger the iface->unbind() hook */
1484                 context->iface = NULL;
1485                 talloc_free(context);
1486                 /*
1487                  * We report this only via ack->result
1488                  */
1489                 return NT_STATUS_OK;
1490         }
1491
1492         ack->result = DCERPC_BIND_ACK_RESULT_ACCEPTANCE;
1493         ack->reason.value = DCERPC_BIND_ACK_REASON_NOT_SPECIFIED;
1494         ack->syntax = context->transfer_syntax;
1495         return NT_STATUS_OK;
1496 }
1497
1498 static NTSTATUS dcesrv_negotiate_contexts(struct dcesrv_call_state *call,
1499                                 const struct dcerpc_bind *b,
1500                                 struct dcerpc_ack_ctx *ack_ctx_list)
1501 {
1502         NTSTATUS status;
1503         size_t i;
1504         bool validate_only = false;
1505         bool preferred_ndr32;
1506
1507         /*
1508          * Try to negotiate one new presentation context,
1509          * using our preferred transfer syntax.
1510          */
1511         for (i = 0; i < b->num_contexts; i++) {
1512                 const struct dcerpc_ctx_list *c = &b->ctx_list[i];
1513                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1514
1515                 status = dcesrv_check_or_create_context(call, b, c, a,
1516                                                 validate_only,
1517                                                 call->conn->preferred_transfer);
1518                 if (!NT_STATUS_IS_OK(status)) {
1519                         return status;
1520                 }
1521
1522                 if (a->result == DCERPC_BIND_ACK_RESULT_ACCEPTANCE) {
1523                         /*
1524                          * We managed to negotiate one context.
1525                          *
1526                          * => we're done.
1527                          */
1528                         validate_only = true;
1529                 }
1530         }
1531
1532         preferred_ndr32 = ndr_syntax_id_equal(&ndr_transfer_syntax_ndr,
1533                                         call->conn->preferred_transfer);
1534         if (preferred_ndr32) {
1535                 /*
1536                  * We're done.
1537                  */
1538                 return NT_STATUS_OK;
1539         }
1540
1541         /*
1542          * Try to negotiate one new presentation context,
1543          * using NDR 32 as fallback.
1544          */
1545         for (i = 0; i < b->num_contexts; i++) {
1546                 const struct dcerpc_ctx_list *c = &b->ctx_list[i];
1547                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1548
1549                 status = dcesrv_check_or_create_context(call, b, c, a,
1550                                                 validate_only,
1551                                                 &ndr_transfer_syntax_ndr);
1552                 if (!NT_STATUS_IS_OK(status)) {
1553                         return status;
1554                 }
1555
1556                 if (a->result == DCERPC_BIND_ACK_RESULT_ACCEPTANCE) {
1557                         /*
1558                          * We managed to negotiate one context.
1559                          *
1560                          * => we're done.
1561                          */
1562                         validate_only = true;
1563                 }
1564         }
1565
1566         return NT_STATUS_OK;
1567 }
1568
1569 static void dcesrv_alter_done(struct tevent_req *subreq);
1570
1571 /*
1572   handle a alter context request
1573 */
1574 static NTSTATUS dcesrv_alter(struct dcesrv_call_state *call)
1575 {
1576         struct dcesrv_connection *conn = call->conn;
1577         NTSTATUS status;
1578         bool auth_ok = false;
1579         struct ncacn_packet *pkt = &call->ack_pkt;
1580         uint32_t extra_flags = 0;
1581         struct dcesrv_auth *auth = &call->conn->auth_state;
1582         struct dcerpc_ack_ctx *ack_ctx_list = NULL;
1583         struct tevent_req *subreq = NULL;
1584         size_t i;
1585
1586         if (!call->conn->allow_alter) {
1587                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1588         }
1589
1590         status = dcerpc_verify_ncacn_packet_header(&call->pkt,
1591                         DCERPC_PKT_ALTER,
1592                         call->pkt.u.alter.auth_info.length,
1593                         0, /* required flags */
1594                         DCERPC_PFC_FLAG_FIRST |
1595                         DCERPC_PFC_FLAG_LAST |
1596                         DCERPC_PFC_FLAG_SUPPORT_HEADER_SIGN |
1597                         0x08 | /* this is not defined, but should be ignored */
1598                         DCERPC_PFC_FLAG_CONC_MPX |
1599                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
1600                         DCERPC_PFC_FLAG_MAYBE |
1601                         DCERPC_PFC_FLAG_OBJECT_UUID);
1602         if (!NT_STATUS_IS_OK(status)) {
1603                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1604         }
1605
1606         auth_ok = dcesrv_auth_alter(call);
1607         if (!auth_ok) {
1608                 if (call->fault_code != 0) {
1609                         return dcesrv_fault_disconnect(call, call->fault_code);
1610                 }
1611         }
1612
1613         if (call->pkt.u.alter.num_contexts < 1) {
1614                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1615         }
1616
1617         ack_ctx_list = talloc_zero_array(call, struct dcerpc_ack_ctx,
1618                                          call->pkt.u.alter.num_contexts);
1619         if (ack_ctx_list == NULL) {
1620                 return NT_STATUS_NO_MEMORY;
1621         }
1622
1623         /*
1624          * Set some sane defaults (required by dcesrv_negotiate_contexts()/
1625          * dcesrv_check_or_create_context()) and do some protocol validation
1626          * and set sane defaults.
1627          */
1628         for (i = 0; i < call->pkt.u.alter.num_contexts; i++) {
1629                 const struct dcerpc_ctx_list *c = &call->pkt.u.alter.ctx_list[i];
1630                 struct dcerpc_ack_ctx *a = &ack_ctx_list[i];
1631
1632                 if (c->num_transfer_syntaxes == 0) {
1633                         return dcesrv_fault_disconnect(call,
1634                                         DCERPC_NCA_S_PROTO_ERROR);
1635                 }
1636
1637                 a->result = DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION;
1638                 a->reason.value = DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED;
1639         }
1640
1641         /*
1642          * Try to negotiate one new presentation context.
1643          */
1644         status = dcesrv_negotiate_contexts(call, &call->pkt.u.alter, ack_ctx_list);
1645         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROTOCOL_ERROR)) {
1646                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1647         }
1648         if (!NT_STATUS_IS_OK(status)) {
1649                 return status;
1650         }
1651
1652         if ((call->pkt.pfc_flags & DCERPC_PFC_FLAG_CONC_MPX) &&
1653             (call->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
1654                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_MULTIPLEXED;
1655                 extra_flags |= DCERPC_PFC_FLAG_CONC_MPX;
1656         }
1657
1658         if (call->state_flags & DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL) {
1659                 call->conn->state_flags |= DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL;
1660         }
1661
1662         /* handle any authentication that is being requested */
1663         if (!auth_ok) {
1664                 if (call->in_auth_info.auth_type !=
1665                     call->conn->auth_state.auth_type)
1666                 {
1667                         return dcesrv_fault_disconnect(call,
1668                                         DCERPC_FAULT_SEC_PKG_ERROR);
1669                 }
1670                 return dcesrv_fault_disconnect(call, DCERPC_FAULT_ACCESS_DENIED);
1671         }
1672
1673         dcesrv_init_hdr(pkt, lpcfg_rpc_big_endian(call->conn->dce_ctx->lp_ctx));
1674         pkt->auth_length = 0;
1675         pkt->call_id = call->pkt.call_id;
1676         pkt->ptype = DCERPC_PKT_ALTER_RESP;
1677         pkt->pfc_flags = DCERPC_PFC_FLAG_FIRST | DCERPC_PFC_FLAG_LAST | extra_flags;
1678         pkt->u.alter_resp.max_xmit_frag = call->conn->max_xmit_frag;
1679         pkt->u.alter_resp.max_recv_frag = call->conn->max_recv_frag;
1680         pkt->u.alter_resp.assoc_group_id = call->conn->assoc_group->id;
1681         pkt->u.alter_resp.secondary_address = "";
1682         pkt->u.alter_resp.num_results = call->pkt.u.alter.num_contexts;
1683         pkt->u.alter_resp.ctx_list = ack_ctx_list;
1684         pkt->u.alter_resp.auth_info = data_blob_null;
1685
1686         status = dcesrv_auth_prepare_alter_ack(call, pkt);
1687         if (!NT_STATUS_IS_OK(status)) {
1688                 return dcesrv_fault_disconnect(call, DCERPC_FAULT_SEC_PKG_ERROR);
1689         }
1690
1691         if (auth->auth_finished) {
1692                 return dcesrv_auth_reply(call);
1693         }
1694
1695         subreq = gensec_update_send(call, call->event_ctx,
1696                                     auth->gensec_security,
1697                                     call->in_auth_info.credentials);
1698         if (subreq == NULL) {
1699                 return NT_STATUS_NO_MEMORY;
1700         }
1701         tevent_req_set_callback(subreq, dcesrv_alter_done, call);
1702
1703         return dcesrv_conn_auth_wait_setup(conn);
1704 }
1705
1706 static void dcesrv_alter_done(struct tevent_req *subreq)
1707 {
1708         struct dcesrv_call_state *call =
1709                 tevent_req_callback_data(subreq,
1710                 struct dcesrv_call_state);
1711         struct dcesrv_connection *conn = call->conn;
1712         NTSTATUS status;
1713
1714         status = gensec_update_recv(subreq, call,
1715                                     &call->out_auth_info->credentials);
1716         TALLOC_FREE(subreq);
1717
1718         status = dcesrv_auth_complete(call, status);
1719         if (!NT_STATUS_IS_OK(status)) {
1720                 status = dcesrv_fault_disconnect(call, DCERPC_FAULT_SEC_PKG_ERROR);
1721                 dcesrv_conn_auth_wait_finished(conn, status);
1722                 return;
1723         }
1724
1725         status = dcesrv_auth_reply(call);
1726         dcesrv_conn_auth_wait_finished(conn, status);
1727         return;
1728 }
1729
1730 /*
1731   possibly save the call for inspection with ndrdump
1732  */
1733 static void dcesrv_save_call(struct dcesrv_call_state *call, const char *why)
1734 {
1735 #ifdef DEVELOPER
1736         char *fname;
1737         const char *dump_dir;
1738         dump_dir = lpcfg_parm_string(call->conn->dce_ctx->lp_ctx, NULL, "dcesrv", "stubs directory");
1739         if (!dump_dir) {
1740                 return;
1741         }
1742         fname = talloc_asprintf(call, "%s/RPC-%s-%u-%s.dat",
1743                                 dump_dir,
1744                                 call->context->iface->name,
1745                                 call->pkt.u.request.opnum,
1746                                 why);
1747         if (file_save(fname, call->pkt.u.request.stub_and_verifier.data, call->pkt.u.request.stub_and_verifier.length)) {
1748                 DEBUG(0,("RPC SAVED %s\n", fname));
1749         }
1750         talloc_free(fname);
1751 #endif
1752 }
1753
1754 static NTSTATUS dcesrv_check_verification_trailer(struct dcesrv_call_state *call)
1755 {
1756         TALLOC_CTX *frame = talloc_stackframe();
1757         const uint32_t bitmask1 = call->conn->auth_state.client_hdr_signing ?
1758                 DCERPC_SEC_VT_CLIENT_SUPPORTS_HEADER_SIGNING : 0;
1759         const struct dcerpc_sec_vt_pcontext pcontext = {
1760                 .abstract_syntax = call->context->iface->syntax_id,
1761                 .transfer_syntax = call->context->transfer_syntax,
1762         };
1763         const struct dcerpc_sec_vt_header2 header2 =
1764                 dcerpc_sec_vt_header2_from_ncacn_packet(&call->pkt);
1765         enum ndr_err_code ndr_err;
1766         struct dcerpc_sec_verification_trailer *vt = NULL;
1767         NTSTATUS status = NT_STATUS_OK;
1768         bool ok;
1769
1770         SMB_ASSERT(call->pkt.ptype == DCERPC_PKT_REQUEST);
1771
1772         ndr_err = ndr_pop_dcerpc_sec_verification_trailer(call->ndr_pull,
1773                                                           frame, &vt);
1774         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1775                 status = ndr_map_error2ntstatus(ndr_err);
1776                 goto done;
1777         }
1778
1779         ok = dcerpc_sec_verification_trailer_check(vt, &bitmask1,
1780                                                    &pcontext, &header2);
1781         if (!ok) {
1782                 status = NT_STATUS_ACCESS_DENIED;
1783                 goto done;
1784         }
1785 done:
1786         TALLOC_FREE(frame);
1787         return status;
1788 }
1789
1790 /*
1791   handle a dcerpc request packet
1792 */
1793 static NTSTATUS dcesrv_request(struct dcesrv_call_state *call)
1794 {
1795         const struct dcesrv_endpoint *endpoint = call->conn->endpoint;
1796         enum dcerpc_transport_t transport =
1797                 dcerpc_binding_get_transport(endpoint->ep_description);
1798         struct ndr_pull *pull;
1799         NTSTATUS status;
1800
1801         if (!call->conn->allow_request) {
1802                 return dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
1803         }
1804
1805         /* if authenticated, and the mech we use can't do async replies, don't use them... */
1806         if (call->conn->auth_state.gensec_security && 
1807             !gensec_have_feature(call->conn->auth_state.gensec_security, GENSEC_FEATURE_ASYNC_REPLIES)) {
1808                 call->state_flags &= ~DCESRV_CALL_STATE_FLAG_MAY_ASYNC;
1809         }
1810
1811         if (call->context == NULL) {
1812                 return dcesrv_fault_with_flags(call, DCERPC_NCA_S_UNKNOWN_IF,
1813                                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
1814         }
1815
1816         switch (call->conn->auth_state.auth_level) {
1817         case DCERPC_AUTH_LEVEL_NONE:
1818         case DCERPC_AUTH_LEVEL_PACKET:
1819         case DCERPC_AUTH_LEVEL_INTEGRITY:
1820         case DCERPC_AUTH_LEVEL_PRIVACY:
1821                 break;
1822         default:
1823                 if (!call->context->allow_connect) {
1824                         char *addr;
1825
1826                         addr = tsocket_address_string(call->conn->remote_address,
1827                                                       call);
1828
1829                         DEBUG(2, ("%s: restrict auth_level_connect access "
1830                                   "to [%s] with auth[type=0x%x,level=0x%x] "
1831                                   "on [%s] from [%s]\n",
1832                                   __func__, call->context->iface->name,
1833                                   call->conn->auth_state.auth_type,
1834                                   call->conn->auth_state.auth_level,
1835                                   derpc_transport_string_by_transport(transport),
1836                                   addr));
1837                         return dcesrv_fault(call, DCERPC_FAULT_ACCESS_DENIED);
1838                 }
1839                 break;
1840         }
1841
1842         if (call->conn->auth_state.auth_level < call->context->min_auth_level) {
1843                 char *addr;
1844
1845                 addr = tsocket_address_string(call->conn->remote_address, call);
1846
1847                 DEBUG(2, ("%s: restrict access by min_auth_level[0x%x] "
1848                           "to [%s] with auth[type=0x%x,level=0x%x] "
1849                           "on [%s] from [%s]\n",
1850                           __func__,
1851                           call->context->min_auth_level,
1852                           call->context->iface->name,
1853                           call->conn->auth_state.auth_type,
1854                           call->conn->auth_state.auth_level,
1855                           derpc_transport_string_by_transport(transport),
1856                           addr));
1857                 return dcesrv_fault(call, DCERPC_FAULT_ACCESS_DENIED);
1858         }
1859
1860         pull = ndr_pull_init_blob(&call->pkt.u.request.stub_and_verifier, call);
1861         NT_STATUS_HAVE_NO_MEMORY(pull);
1862
1863         pull->flags |= LIBNDR_FLAG_REF_ALLOC;
1864
1865         call->ndr_pull  = pull;
1866
1867         if (!(call->pkt.drep[0] & DCERPC_DREP_LE)) {
1868                 pull->flags |= LIBNDR_FLAG_BIGENDIAN;
1869         }
1870
1871         status = dcesrv_check_verification_trailer(call);
1872         if (!NT_STATUS_IS_OK(status)) {
1873                 uint32_t faultcode = DCERPC_FAULT_OTHER;
1874                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1875                         faultcode = DCERPC_FAULT_ACCESS_DENIED;
1876                 }
1877                 DEBUG(10, ("dcesrv_check_verification_trailer failed: %s\n",
1878                            nt_errstr(status)));
1879                 return dcesrv_fault(call, faultcode);
1880         }
1881
1882         /* unravel the NDR for the packet */
1883         status = call->context->iface->ndr_pull(call, call, pull, &call->r);
1884         if (!NT_STATUS_IS_OK(status)) {
1885                 uint8_t extra_flags = 0;
1886                 if (call->fault_code == DCERPC_FAULT_OP_RNG_ERROR) {
1887                         /* we got an unknown call */
1888                         DEBUG(3,(__location__ ": Unknown RPC call %u on %s\n",
1889                                  call->pkt.u.request.opnum,
1890                                  call->context->iface->name));
1891                         dcesrv_save_call(call, "unknown");
1892                         extra_flags |= DCERPC_PFC_FLAG_DID_NOT_EXECUTE;
1893                 } else {
1894                         dcesrv_save_call(call, "pullfail");
1895                 }
1896                 return dcesrv_fault_with_flags(call, call->fault_code, extra_flags);
1897         }
1898
1899         if (pull->offset != pull->data_size) {
1900                 dcesrv_save_call(call, "extrabytes");
1901                 DEBUG(3,("Warning: %d extra bytes in incoming RPC request\n", 
1902                          pull->data_size - pull->offset));
1903         }
1904
1905         /* call the dispatch function */
1906         status = call->context->iface->dispatch(call, call, call->r);
1907         if (!NT_STATUS_IS_OK(status)) {
1908                 DEBUG(5,("dcerpc fault in call %s:%02x - %s\n",
1909                          call->context->iface->name,
1910                          call->pkt.u.request.opnum,
1911                          dcerpc_errstr(pull, call->fault_code)));
1912                 return dcesrv_fault(call, call->fault_code);
1913         }
1914
1915         /* add the call to the pending list */
1916         dcesrv_call_set_list(call, DCESRV_LIST_PENDING_CALL_LIST);
1917
1918         if (call->state_flags & DCESRV_CALL_STATE_FLAG_ASYNC) {
1919                 return NT_STATUS_OK;
1920         }
1921
1922         return dcesrv_reply(call);
1923 }
1924
1925
1926 /*
1927   remove the call from the right list when freed
1928  */
1929 static int dcesrv_call_dequeue(struct dcesrv_call_state *call)
1930 {
1931         dcesrv_call_set_list(call, DCESRV_LIST_NONE);
1932         return 0;
1933 }
1934
1935 _PUBLIC_ const struct tsocket_address *dcesrv_connection_get_local_address(struct dcesrv_connection *conn)
1936 {
1937         return conn->local_address;
1938 }
1939
1940 _PUBLIC_ const struct tsocket_address *dcesrv_connection_get_remote_address(struct dcesrv_connection *conn)
1941 {
1942         return conn->remote_address;
1943 }
1944
1945 /*
1946   process some input to a dcerpc endpoint server.
1947 */
1948 static NTSTATUS dcesrv_process_ncacn_packet(struct dcesrv_connection *dce_conn,
1949                                             struct ncacn_packet *pkt,
1950                                             DATA_BLOB blob)
1951 {
1952         NTSTATUS status;
1953         struct dcesrv_call_state *call;
1954         struct dcesrv_call_state *existing = NULL;
1955
1956         call = talloc_zero(dce_conn, struct dcesrv_call_state);
1957         if (!call) {
1958                 data_blob_free(&blob);
1959                 talloc_free(pkt);
1960                 return NT_STATUS_NO_MEMORY;
1961         }
1962         call->conn              = dce_conn;
1963         call->event_ctx         = dce_conn->event_ctx;
1964         call->msg_ctx           = dce_conn->msg_ctx;
1965         call->state_flags       = call->conn->state_flags;
1966         call->time              = timeval_current();
1967         call->list              = DCESRV_LIST_NONE;
1968
1969         talloc_steal(call, pkt);
1970         talloc_steal(call, blob.data);
1971         call->pkt = *pkt;
1972
1973         talloc_set_destructor(call, dcesrv_call_dequeue);
1974
1975         if (call->conn->allow_bind) {
1976                 /*
1977                  * Only one bind is possible per connection
1978                  */
1979                 call->conn->allow_bind = false;
1980                 return dcesrv_bind(call);
1981         }
1982
1983         /* we have to check the signing here, before combining the
1984            pdus */
1985         if (call->pkt.ptype == DCERPC_PKT_REQUEST) {
1986                 if (!call->conn->allow_request) {
1987                         return dcesrv_fault_disconnect(call,
1988                                         DCERPC_NCA_S_PROTO_ERROR);
1989                 }
1990
1991                 status = dcerpc_verify_ncacn_packet_header(&call->pkt,
1992                                 DCERPC_PKT_REQUEST,
1993                                 call->pkt.u.request.stub_and_verifier.length,
1994                                 0, /* required_flags */
1995                                 DCERPC_PFC_FLAG_FIRST |
1996                                 DCERPC_PFC_FLAG_LAST |
1997                                 DCERPC_PFC_FLAG_PENDING_CANCEL |
1998                                 0x08 | /* this is not defined, but should be ignored */
1999                                 DCERPC_PFC_FLAG_CONC_MPX |
2000                                 DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
2001                                 DCERPC_PFC_FLAG_MAYBE |
2002                                 DCERPC_PFC_FLAG_OBJECT_UUID);
2003                 if (!NT_STATUS_IS_OK(status)) {
2004                         return dcesrv_fault_disconnect(call,
2005                                         DCERPC_NCA_S_PROTO_ERROR);
2006                 }
2007
2008                 if (call->pkt.frag_length > DCERPC_FRAG_MAX_SIZE) {
2009                         /*
2010                          * We don't use dcesrv_fault_disconnect()
2011                          * here, because we don't want to set
2012                          * DCERPC_PFC_FLAG_DID_NOT_EXECUTE
2013                          *
2014                          * Note that we don't check against the negotiated
2015                          * max_recv_frag, but a hard coded value.
2016                          */
2017                         dcesrv_call_disconnect_after(call,
2018                                 "dcesrv_auth_request - frag_length too large");
2019                         return dcesrv_fault(call,
2020                                         DCERPC_NCA_S_PROTO_ERROR);
2021                 }
2022
2023                 if (call->pkt.pfc_flags & DCERPC_PFC_FLAG_FIRST) {
2024                         if (dce_conn->pending_call_list != NULL) {
2025                                 /*
2026                                  * concurrent requests are only allowed
2027                                  * if DCERPC_PFC_FLAG_CONC_MPX was negotiated.
2028                                  */
2029                                 if (!(dce_conn->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
2030                                         dcesrv_call_disconnect_after(call,
2031                                                 "dcesrv_auth_request - "
2032                                                 "existing pending call without CONN_MPX");
2033                                         return dcesrv_fault(call,
2034                                                 DCERPC_NCA_S_PROTO_ERROR);
2035                                 }
2036                         }
2037                         /* only one request is possible in the fragmented list */
2038                         if (dce_conn->incoming_fragmented_call_list != NULL) {
2039                                 if (!(dce_conn->state_flags & DCESRV_CALL_STATE_FLAG_MULTIPLEXED)) {
2040                                         /*
2041                                          * Without DCERPC_PFC_FLAG_CONC_MPX
2042                                          * we need to return the FAULT on the
2043                                          * already existing call.
2044                                          *
2045                                          * This is important to get the
2046                                          * call_id and context_id right.
2047                                          */
2048                                         TALLOC_FREE(call);
2049                                         call = dce_conn->incoming_fragmented_call_list;
2050                                 }
2051                                 dcesrv_call_disconnect_after(call,
2052                                         "dcesrv_auth_request - "
2053                                         "existing fragmented call");
2054                                 return dcesrv_fault(call,
2055                                                 DCERPC_NCA_S_PROTO_ERROR);
2056                         }
2057                         if (call->pkt.pfc_flags & DCERPC_PFC_FLAG_PENDING_CANCEL) {
2058                                 return dcesrv_fault_disconnect(call,
2059                                                 DCERPC_FAULT_NO_CALL_ACTIVE);
2060                         }
2061                         call->context = dcesrv_find_context(call->conn,
2062                                                 call->pkt.u.request.context_id);
2063                         if (call->context == NULL) {
2064                                 return dcesrv_fault_with_flags(call, DCERPC_NCA_S_UNKNOWN_IF,
2065                                         DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
2066                         }
2067                 } else {
2068                         const struct dcerpc_request *nr = &call->pkt.u.request;
2069                         const struct dcerpc_request *er = NULL;
2070                         int cmp;
2071
2072                         existing = dcesrv_find_fragmented_call(dce_conn,
2073                                                         call->pkt.call_id);
2074                         if (existing == NULL) {
2075                                 dcesrv_call_disconnect_after(call,
2076                                         "dcesrv_auth_request - "
2077                                         "no existing fragmented call");
2078                                 return dcesrv_fault(call,
2079                                                 DCERPC_NCA_S_PROTO_ERROR);
2080                         }
2081                         er = &existing->pkt.u.request;
2082
2083                         if (call->pkt.ptype != existing->pkt.ptype) {
2084                                 /* trying to play silly buggers are we? */
2085                                 return dcesrv_fault_disconnect(existing,
2086                                                 DCERPC_NCA_S_PROTO_ERROR);
2087                         }
2088                         cmp = memcmp(call->pkt.drep, existing->pkt.drep,
2089                                      sizeof(pkt->drep));
2090                         if (cmp != 0) {
2091                                 return dcesrv_fault_disconnect(existing,
2092                                                 DCERPC_NCA_S_PROTO_ERROR);
2093                         }
2094                         if (nr->context_id != er->context_id)  {
2095                                 return dcesrv_fault_disconnect(existing,
2096                                                 DCERPC_NCA_S_PROTO_ERROR);
2097                         }
2098                         if (nr->opnum != er->opnum)  {
2099                                 return dcesrv_fault_disconnect(existing,
2100                                                 DCERPC_NCA_S_PROTO_ERROR);
2101                         }
2102                 }
2103         }
2104
2105         if (call->pkt.ptype == DCERPC_PKT_REQUEST) {
2106                 bool ok;
2107                 uint8_t payload_offset = DCERPC_REQUEST_LENGTH;
2108
2109                 if (call->pkt.pfc_flags & DCERPC_PFC_FLAG_OBJECT_UUID) {
2110                         payload_offset += 16;
2111                 }
2112
2113                 ok = dcesrv_auth_pkt_pull(call, &blob,
2114                                           0, /* required_flags */
2115                                           DCERPC_PFC_FLAG_FIRST |
2116                                           DCERPC_PFC_FLAG_LAST |
2117                                           DCERPC_PFC_FLAG_PENDING_CANCEL |
2118                                           0x08 | /* this is not defined, but should be ignored */
2119                                           DCERPC_PFC_FLAG_CONC_MPX |
2120                                           DCERPC_PFC_FLAG_DID_NOT_EXECUTE |
2121                                           DCERPC_PFC_FLAG_MAYBE |
2122                                           DCERPC_PFC_FLAG_OBJECT_UUID,
2123                                           payload_offset,
2124                                           &call->pkt.u.request.stub_and_verifier);
2125                 if (!ok) {
2126                         /*
2127                          * We don't use dcesrv_fault_disconnect()
2128                          * here, because we don't want to set
2129                          * DCERPC_PFC_FLAG_DID_NOT_EXECUTE
2130                          */
2131                         dcesrv_call_disconnect_after(call,
2132                                                 "dcesrv_auth_request - failed");
2133                         if (call->fault_code == 0) {
2134                                 call->fault_code = DCERPC_FAULT_ACCESS_DENIED;
2135                         }
2136                         return dcesrv_fault(call, call->fault_code);
2137                 }
2138         }
2139
2140         /* see if this is a continued packet */
2141         if (existing != NULL) {
2142                 struct dcerpc_request *er = &existing->pkt.u.request;
2143                 const struct dcerpc_request *nr = &call->pkt.u.request;
2144                 size_t available;
2145                 size_t alloc_size;
2146                 size_t alloc_hint;
2147
2148                 /*
2149                  * Up to 4 MByte are allowed by all fragments
2150                  */
2151                 available = dce_conn->max_total_request_size;
2152                 if (er->stub_and_verifier.length > available) {
2153                         dcesrv_call_disconnect_after(existing,
2154                                 "dcesrv_auth_request - existing payload too large");
2155                         return dcesrv_fault(existing, DCERPC_FAULT_ACCESS_DENIED);
2156                 }
2157                 available -= er->stub_and_verifier.length;
2158                 if (nr->alloc_hint > available) {
2159                         dcesrv_call_disconnect_after(existing,
2160                                 "dcesrv_auth_request - alloc hint too large");
2161                         return dcesrv_fault(existing, DCERPC_FAULT_ACCESS_DENIED);
2162                 }
2163                 if (nr->stub_and_verifier.length > available) {
2164                         dcesrv_call_disconnect_after(existing,
2165                                 "dcesrv_auth_request - new payload too large");
2166                         return dcesrv_fault(existing, DCERPC_FAULT_ACCESS_DENIED);
2167                 }
2168                 alloc_hint = er->stub_and_verifier.length + nr->alloc_hint;
2169                 /* allocate at least 1 byte */
2170                 alloc_hint = MAX(alloc_hint, 1);
2171                 alloc_size = er->stub_and_verifier.length +
2172                              nr->stub_and_verifier.length;
2173                 alloc_size = MAX(alloc_size, alloc_hint);
2174
2175                 er->stub_and_verifier.data =
2176                         talloc_realloc(existing,
2177                                        er->stub_and_verifier.data,
2178                                        uint8_t, alloc_size);
2179                 if (er->stub_and_verifier.data == NULL) {
2180                         TALLOC_FREE(call);
2181                         return dcesrv_fault_with_flags(existing,
2182                                                        DCERPC_FAULT_OUT_OF_RESOURCES,
2183                                                        DCERPC_PFC_FLAG_DID_NOT_EXECUTE);
2184                 }
2185                 memcpy(er->stub_and_verifier.data +
2186                        er->stub_and_verifier.length,
2187                        nr->stub_and_verifier.data,
2188                        nr->stub_and_verifier.length);
2189                 er->stub_and_verifier.length += nr->stub_and_verifier.length;
2190
2191                 existing->pkt.pfc_flags |= (call->pkt.pfc_flags & DCERPC_PFC_FLAG_LAST);
2192
2193                 TALLOC_FREE(call);
2194                 call = existing;
2195         }
2196
2197         /* this may not be the last pdu in the chain - if its isn't then
2198            just put it on the incoming_fragmented_call_list and wait for the rest */
2199         if (call->pkt.ptype == DCERPC_PKT_REQUEST &&
2200             !(call->pkt.pfc_flags & DCERPC_PFC_FLAG_LAST)) {
2201                 /*
2202                  * Up to 4 MByte are allowed by all fragments
2203                  */
2204                 if (call->pkt.u.request.alloc_hint > dce_conn->max_total_request_size) {
2205                         dcesrv_call_disconnect_after(call,
2206                                 "dcesrv_auth_request - initial alloc hint too large");
2207                         return dcesrv_fault(call, DCERPC_FAULT_ACCESS_DENIED);
2208                 }
2209                 dcesrv_call_set_list(call, DCESRV_LIST_FRAGMENTED_CALL_LIST);
2210                 return NT_STATUS_OK;
2211         } 
2212         
2213         /* This removes any fragments we may have had stashed away */
2214         dcesrv_call_set_list(call, DCESRV_LIST_NONE);
2215
2216         switch (call->pkt.ptype) {
2217         case DCERPC_PKT_BIND:
2218                 status = dcesrv_bind_nak(call,
2219                         DCERPC_BIND_NAK_REASON_NOT_SPECIFIED);
2220                 break;
2221         case DCERPC_PKT_AUTH3:
2222                 status = dcesrv_auth3(call);
2223                 break;
2224         case DCERPC_PKT_ALTER:
2225                 status = dcesrv_alter(call);
2226                 break;
2227         case DCERPC_PKT_REQUEST:
2228                 status = dcesrv_request(call);
2229                 break;
2230         case DCERPC_PKT_CO_CANCEL:
2231         case DCERPC_PKT_ORPHANED:
2232                 /*
2233                  * Window just ignores CO_CANCEL and ORPHANED,
2234                  * so we do...
2235                  */
2236                 status = NT_STATUS_OK;
2237                 TALLOC_FREE(call);
2238                 break;
2239         case DCERPC_PKT_BIND_ACK:
2240         case DCERPC_PKT_BIND_NAK:
2241         case DCERPC_PKT_ALTER_RESP:
2242         case DCERPC_PKT_RESPONSE:
2243         case DCERPC_PKT_FAULT:
2244         case DCERPC_PKT_SHUTDOWN:
2245         default:
2246                 status = dcesrv_fault_disconnect(call, DCERPC_NCA_S_PROTO_ERROR);
2247                 break;
2248         }
2249
2250         /* if we are going to be sending a reply then add
2251            it to the list of pending calls. We add it to the end to keep the call
2252            list in the order we will answer */
2253         if (!NT_STATUS_IS_OK(status)) {
2254                 talloc_free(call);
2255         }
2256
2257         return status;
2258 }
2259
2260 _PUBLIC_ NTSTATUS dcesrv_init_context(TALLOC_CTX *mem_ctx, 
2261                                       struct loadparm_context *lp_ctx,
2262                                       const char **endpoint_servers, struct dcesrv_context **_dce_ctx)
2263 {
2264         NTSTATUS status;
2265         struct dcesrv_context *dce_ctx;
2266         int i;
2267
2268         if (!endpoint_servers) {
2269                 DEBUG(0,("dcesrv_init_context: no endpoint servers configured\n"));
2270                 return NT_STATUS_INTERNAL_ERROR;
2271         }
2272
2273         dce_ctx = talloc_zero(mem_ctx, struct dcesrv_context);
2274         NT_STATUS_HAVE_NO_MEMORY(dce_ctx);
2275
2276         if (uid_wrapper_enabled()) {
2277                 setenv("UID_WRAPPER_MYUID", "1", 1);
2278         }
2279         dce_ctx->initial_euid = geteuid();
2280         if (uid_wrapper_enabled()) {
2281                 unsetenv("UID_WRAPPER_MYUID");
2282         }
2283
2284         dce_ctx->endpoint_list  = NULL;
2285         dce_ctx->lp_ctx = lp_ctx;
2286         dce_ctx->assoc_groups_idr = idr_init(dce_ctx);
2287         NT_STATUS_HAVE_NO_MEMORY(dce_ctx->assoc_groups_idr);
2288         dce_ctx->broken_connections = NULL;
2289
2290         for (i=0;endpoint_servers[i];i++) {
2291                 const struct dcesrv_endpoint_server *ep_server;
2292
2293                 ep_server = dcesrv_ep_server_byname(endpoint_servers[i]);
2294                 if (!ep_server) {
2295                         DEBUG(0,("dcesrv_init_context: failed to find endpoint server = '%s'\n", endpoint_servers[i]));
2296                         return NT_STATUS_INTERNAL_ERROR;
2297                 }
2298
2299                 status = ep_server->init_server(dce_ctx, ep_server);
2300                 if (!NT_STATUS_IS_OK(status)) {
2301                         DEBUG(0,("dcesrv_init_context: failed to init endpoint server = '%s': %s\n", endpoint_servers[i],
2302                                 nt_errstr(status)));
2303                         return status;
2304                 }
2305         }
2306
2307         *_dce_ctx = dce_ctx;
2308         return NT_STATUS_OK;
2309 }
2310
2311 /* the list of currently registered DCERPC endpoint servers.
2312  */
2313 static struct ep_server {
2314         struct dcesrv_endpoint_server *ep_server;
2315 } *ep_servers = NULL;
2316 static int num_ep_servers;
2317
2318 /*
2319   register a DCERPC endpoint server. 
2320
2321   The 'name' can be later used by other backends to find the operations
2322   structure for this backend.  
2323
2324 */
2325 _PUBLIC_ NTSTATUS dcerpc_register_ep_server(const struct dcesrv_endpoint_server *ep_server)
2326 {
2327         
2328         if (dcesrv_ep_server_byname(ep_server->name) != NULL) {
2329                 /* its already registered! */
2330                 DEBUG(0,("DCERPC endpoint server '%s' already registered\n", 
2331                          ep_server->name));
2332                 return NT_STATUS_OBJECT_NAME_COLLISION;
2333         }
2334
2335         ep_servers = realloc_p(ep_servers, struct ep_server, num_ep_servers+1);
2336         if (!ep_servers) {
2337                 smb_panic("out of memory in dcerpc_register");
2338         }
2339
2340         ep_servers[num_ep_servers].ep_server = smb_xmemdup(ep_server, sizeof(*ep_server));
2341         ep_servers[num_ep_servers].ep_server->name = smb_xstrdup(ep_server->name);
2342
2343         num_ep_servers++;
2344
2345         DEBUG(3,("DCERPC endpoint server '%s' registered\n", 
2346                  ep_server->name));
2347
2348         return NT_STATUS_OK;
2349 }
2350
2351 /*
2352   return the operations structure for a named backend of the specified type
2353 */
2354 const struct dcesrv_endpoint_server *dcesrv_ep_server_byname(const char *name)
2355 {
2356         int i;
2357
2358         for (i=0;i<num_ep_servers;i++) {
2359                 if (strcmp(ep_servers[i].ep_server->name, name) == 0) {
2360                         return ep_servers[i].ep_server;
2361                 }
2362         }
2363
2364         return NULL;
2365 }
2366
2367 void dcerpc_server_init(struct loadparm_context *lp_ctx)
2368 {
2369         static bool initialized;
2370 #define _MODULE_PROTO(init) extern NTSTATUS init(TALLOC_CTX *);
2371         STATIC_dcerpc_server_MODULES_PROTO;
2372         init_module_fn static_init[] = { STATIC_dcerpc_server_MODULES };
2373         init_module_fn *shared_init;
2374
2375         if (initialized) {
2376                 return;
2377         }
2378         initialized = true;
2379
2380         shared_init = load_samba_modules(NULL, "dcerpc_server");
2381
2382         run_init_functions(NULL, static_init);
2383         run_init_functions(NULL, shared_init);
2384
2385         talloc_free(shared_init);
2386 }
2387
2388 /*
2389   return the DCERPC module version, and the size of some critical types
2390   This can be used by endpoint server modules to either detect compilation errors, or provide
2391   multiple implementations for different smbd compilation options in one module
2392 */
2393 const struct dcesrv_critical_sizes *dcerpc_module_version(void)
2394 {
2395         static const struct dcesrv_critical_sizes critical_sizes = {
2396                 DCERPC_MODULE_VERSION,
2397                 sizeof(struct dcesrv_context),
2398                 sizeof(struct dcesrv_endpoint),
2399                 sizeof(struct dcesrv_endpoint_server),
2400                 sizeof(struct dcesrv_interface),
2401                 sizeof(struct dcesrv_if_list),
2402                 sizeof(struct dcesrv_connection),
2403                 sizeof(struct dcesrv_call_state),
2404                 sizeof(struct dcesrv_auth),
2405                 sizeof(struct dcesrv_handle)
2406         };
2407
2408         return &critical_sizes;
2409 }
2410
2411 static void dcesrv_terminate_connection(struct dcesrv_connection *dce_conn, const char *reason)
2412 {
2413         struct dcesrv_context *dce_ctx = dce_conn->dce_ctx;
2414         struct stream_connection *srv_conn;
2415         srv_conn = talloc_get_type(dce_conn->transport.private_data,
2416                                    struct stream_connection);
2417
2418         dce_conn->wait_send = NULL;
2419         dce_conn->wait_recv = NULL;
2420         dce_conn->wait_private = NULL;
2421
2422         dce_conn->allow_bind = false;
2423         dce_conn->allow_auth3 = false;
2424         dce_conn->allow_alter = false;
2425         dce_conn->allow_request = false;
2426
2427         if (dce_conn->pending_call_list == NULL) {
2428                 char *full_reason = talloc_asprintf(dce_conn, "dcesrv: %s", reason);
2429
2430                 DLIST_REMOVE(dce_ctx->broken_connections, dce_conn);
2431                 stream_terminate_connection(srv_conn, full_reason ? full_reason : reason);
2432                 return;
2433         }
2434
2435         if (dce_conn->terminate != NULL) {
2436                 return;
2437         }
2438
2439         DEBUG(3,("dcesrv: terminating connection due to '%s' deferred due to pending calls\n",
2440                  reason));
2441         dce_conn->terminate = talloc_strdup(dce_conn, reason);
2442         if (dce_conn->terminate == NULL) {
2443                 dce_conn->terminate = "dcesrv: deferred terminating connection - no memory";
2444         }
2445         DLIST_ADD_END(dce_ctx->broken_connections, dce_conn);
2446 }
2447
2448 static void dcesrv_cleanup_broken_connections(struct dcesrv_context *dce_ctx)
2449 {
2450         struct dcesrv_connection *cur, *next;
2451
2452         next = dce_ctx->broken_connections;
2453         while (next != NULL) {
2454                 cur = next;
2455                 next = cur->next;
2456
2457                 if (cur->state_flags & DCESRV_CALL_STATE_FLAG_PROCESS_PENDING_CALL) {
2458                         struct dcesrv_connection_context *context_cur, *context_next;
2459
2460                         context_next = cur->contexts;
2461                         while (context_next != NULL) {
2462                                 context_cur = context_next;
2463                                 context_next = context_cur->next;
2464
2465                                 dcesrv_connection_context_destructor(context_cur);
2466                         }
2467                 }
2468
2469                 dcesrv_terminate_connection(cur, cur->terminate);
2470         }
2471 }
2472
2473 /* We need this include to be able to compile on some plateforms
2474  * (ie. freebsd 7.2) as it seems that <sys/uio.h> is not included
2475  * correctly.
2476  * It has to be that deep because otherwise we have a conflict on
2477  * const struct dcesrv_interface declaration.
2478  * This is mostly due to socket_wrapper defining #define bind swrap_bind
2479  * which conflict with the bind used before.
2480  */
2481 #include "system/network.h"
2482
2483 struct dcesrv_sock_reply_state {
2484         struct dcesrv_connection *dce_conn;
2485         struct dcesrv_call_state *call;
2486         struct iovec iov;
2487 };
2488
2489 static void dcesrv_sock_reply_done(struct tevent_req *subreq);
2490 static void dcesrv_call_terminate_step1(struct tevent_req *subreq);
2491
2492 static void dcesrv_sock_report_output_data(struct dcesrv_connection *dce_conn)
2493 {
2494         struct dcesrv_call_state *call;
2495
2496         call = dce_conn->call_list;
2497         if (!call || !call->replies) {
2498                 return;
2499         }
2500
2501         while (call->replies) {
2502                 struct data_blob_list_item *rep = call->replies;
2503                 struct dcesrv_sock_reply_state *substate;
2504                 struct tevent_req *subreq;
2505
2506                 substate = talloc_zero(call, struct dcesrv_sock_reply_state);
2507                 if (!substate) {
2508                         dcesrv_terminate_connection(dce_conn, "no memory");
2509                         return;
2510                 }
2511
2512                 substate->dce_conn = dce_conn;
2513                 substate->call = NULL;
2514
2515                 DLIST_REMOVE(call->replies, rep);
2516
2517                 if (call->replies == NULL && call->terminate_reason == NULL) {
2518                         substate->call = call;
2519                 }
2520
2521                 substate->iov.iov_base = (void *) rep->blob.data;
2522                 substate->iov.iov_len = rep->blob.length;
2523
2524                 subreq = tstream_writev_queue_send(substate,
2525                                                    dce_conn->event_ctx,
2526                                                    dce_conn->stream,
2527                                                    dce_conn->send_queue,
2528                                                    &substate->iov, 1);
2529                 if (!subreq) {
2530                         dcesrv_terminate_connection(dce_conn, "no memory");
2531                         return;
2532                 }
2533                 tevent_req_set_callback(subreq, dcesrv_sock_reply_done,
2534                                         substate);
2535         }
2536
2537         if (call->terminate_reason != NULL) {
2538                 struct tevent_req *subreq;
2539
2540                 subreq = tevent_queue_wait_send(call,
2541                                                 dce_conn->event_ctx,
2542                                                 dce_conn->send_queue);
2543                 if (!subreq) {
2544                         dcesrv_terminate_connection(dce_conn, __location__);
2545                         return;
2546                 }
2547                 tevent_req_set_callback(subreq, dcesrv_call_terminate_step1,
2548                                         call);
2549         }
2550
2551         DLIST_REMOVE(call->conn->call_list, call);
2552         call->list = DCESRV_LIST_NONE;
2553 }
2554
2555 static void dcesrv_sock_reply_done(struct tevent_req *subreq)
2556 {
2557         struct dcesrv_sock_reply_state *substate = tevent_req_callback_data(subreq,
2558                                                 struct dcesrv_sock_reply_state);
2559         int ret;
2560         int sys_errno;
2561         NTSTATUS status;
2562         struct dcesrv_call_state *call = substate->call;
2563
2564         ret = tstream_writev_queue_recv(subreq, &sys_errno);
2565         TALLOC_FREE(subreq);
2566         if (ret == -1) {
2567                 status = map_nt_error_from_unix_common(sys_errno);
2568                 dcesrv_terminate_connection(substate->dce_conn, nt_errstr(status));
2569                 return;
2570         }
2571
2572         talloc_free(substate);
2573         if (call) {
2574                 talloc_free(call);
2575         }
2576 }
2577
2578 static void dcesrv_call_terminate_step2(struct tevent_req *subreq);
2579
2580 static void dcesrv_call_terminate_step1(struct tevent_req *subreq)
2581 {
2582         struct dcesrv_call_state *call = tevent_req_callback_data(subreq,
2583                                                 struct dcesrv_call_state);
2584         bool ok;
2585         struct timeval tv;
2586
2587         /* make sure we stop send queue before removing subreq */
2588         tevent_queue_stop(call->conn->send_queue);
2589
2590         ok = tevent_queue_wait_recv(subreq);
2591         TALLOC_FREE(subreq);
2592         if (!ok) {
2593                 dcesrv_terminate_connection(call->conn, __location__);
2594                 return;
2595         }
2596
2597         /* disconnect after 200 usecs */
2598         tv = timeval_current_ofs_usec(200);
2599         subreq = tevent_wakeup_send(call, call->conn->event_ctx, tv);
2600         if (subreq == NULL) {
2601                 dcesrv_terminate_connection(call->conn, __location__);
2602                 return;
2603         }
2604         tevent_req_set_callback(subreq, dcesrv_call_terminate_step2,
2605                                 call);
2606 }
2607
2608 static void dcesrv_call_terminate_step2(struct tevent_req *subreq)
2609 {
2610         struct dcesrv_call_state *call = tevent_req_callback_data(subreq,
2611                                                 struct dcesrv_call_state);
2612         bool ok;
2613
2614         ok = tevent_wakeup_recv(subreq);
2615         TALLOC_FREE(subreq);
2616         if (!ok) {
2617                 dcesrv_terminate_connection(call->conn, __location__);
2618                 return;
2619         }
2620
2621         dcesrv_terminate_connection(call->conn, call->terminate_reason);
2622 }
2623
2624 struct dcesrv_socket_context {
2625         const struct dcesrv_endpoint *endpoint;
2626         struct dcesrv_context *dcesrv_ctx;
2627 };
2628
2629
2630 static void dcesrv_read_fragment_done(struct tevent_req *subreq);
2631
2632 static void dcesrv_sock_accept(struct stream_connection *srv_conn)
2633 {
2634         NTSTATUS status;
2635         struct dcesrv_socket_context *dcesrv_sock = 
2636                 talloc_get_type(srv_conn->private_data, struct dcesrv_socket_context);
2637         enum dcerpc_transport_t transport =
2638                 dcerpc_binding_get_transport(dcesrv_sock->endpoint->ep_description);
2639         struct dcesrv_connection *dcesrv_conn = NULL;
2640         int ret;
2641         struct tevent_req *subreq;
2642         struct loadparm_context *lp_ctx = dcesrv_sock->dcesrv_ctx->lp_ctx;
2643
2644         dcesrv_cleanup_broken_connections(dcesrv_sock->dcesrv_ctx);
2645
2646         if (!srv_conn->session_info) {
2647                 status = auth_anonymous_session_info(srv_conn,
2648                                                      lp_ctx,
2649                                                      &srv_conn->session_info);
2650                 if (!NT_STATUS_IS_OK(status)) {
2651                         DEBUG(0,("dcesrv_sock_accept: auth_anonymous_session_info failed: %s\n",
2652                                 nt_errstr(status)));
2653                         stream_terminate_connection(srv_conn, nt_errstr(status));
2654                         return;
2655                 }
2656         }
2657
2658         /*
2659          * This fills in dcesrv_conn->endpoint with the endpoint
2660          * associated with the socket.  From this point on we know
2661          * which (group of) services we are handling, but not the
2662          * specific interface.
2663          */
2664
2665         status = dcesrv_endpoint_connect(dcesrv_sock->dcesrv_ctx,
2666                                          srv_conn,
2667                                          dcesrv_sock->endpoint,
2668                                          srv_conn->session_info,
2669                                          srv_conn->event.ctx,
2670                                          srv_conn->msg_ctx,
2671                                          srv_conn->server_id,
2672                                          DCESRV_CALL_STATE_FLAG_MAY_ASYNC,
2673                                          &dcesrv_conn);
2674         if (!NT_STATUS_IS_OK(status)) {
2675                 DEBUG(0,("dcesrv_sock_accept: dcesrv_endpoint_connect failed: %s\n", 
2676                         nt_errstr(status)));
2677                 stream_terminate_connection(srv_conn, nt_errstr(status));
2678                 return;
2679         }
2680
2681         dcesrv_conn->transport.private_data             = srv_conn;
2682         dcesrv_conn->transport.report_output_data       = dcesrv_sock_report_output_data;
2683
2684         TALLOC_FREE(srv_conn->event.fde);
2685
2686         dcesrv_conn->send_queue = tevent_queue_create(dcesrv_conn, "dcesrv send queue");
2687         if (!dcesrv_conn->send_queue) {
2688                 status = NT_STATUS_NO_MEMORY;
2689                 DEBUG(0,("dcesrv_sock_accept: tevent_queue_create(%s)\n",
2690                         nt_errstr(status)));
2691                 stream_terminate_connection(srv_conn, nt_errstr(status));
2692                 return;
2693         }
2694
2695         if (transport == NCACN_NP) {
2696                 dcesrv_conn->auth_state.session_key = dcesrv_inherited_session_key;
2697                 dcesrv_conn->stream = talloc_move(dcesrv_conn,
2698                                                   &srv_conn->tstream);
2699         } else {
2700                 ret = tstream_bsd_existing_socket(dcesrv_conn,
2701                                                   socket_get_fd(srv_conn->socket),
2702                                                   &dcesrv_conn->stream);
2703                 if (ret == -1) {
2704                         status = map_nt_error_from_unix_common(errno);
2705                         DEBUG(0, ("dcesrv_sock_accept: "
2706                                   "failed to setup tstream: %s\n",
2707                                   nt_errstr(status)));
2708                         stream_terminate_connection(srv_conn, nt_errstr(status));
2709                         return;
2710                 }
2711                 socket_set_flags(srv_conn->socket, SOCKET_FLAG_NOCLOSE);
2712         }
2713
2714         dcesrv_conn->local_address = srv_conn->local_address;
2715         dcesrv_conn->remote_address = srv_conn->remote_address;
2716
2717         if (transport == NCALRPC) {
2718                 uid_t uid;
2719                 gid_t gid;
2720                 int sock_fd;
2721
2722                 sock_fd = socket_get_fd(srv_conn->socket);
2723                 if (sock_fd == -1) {
2724                         stream_terminate_connection(
2725                                 srv_conn, "socket_get_fd failed\n");
2726                         return;
2727                 }
2728
2729                 ret = getpeereid(sock_fd, &uid, &gid);
2730                 if (ret == -1) {
2731                         status = map_nt_error_from_unix_common(errno);
2732                         DEBUG(0, ("dcesrv_sock_accept: "
2733                                   "getpeereid() failed for NCALRPC: %s\n",
2734                                   nt_errstr(status)));
2735                         stream_terminate_connection(srv_conn, nt_errstr(status));
2736                         return;
2737                 }
2738                 if (uid == dcesrv_conn->dce_ctx->initial_euid) {
2739                         struct tsocket_address *r = NULL;
2740
2741                         ret = tsocket_address_unix_from_path(dcesrv_conn,
2742                                                              AS_SYSTEM_MAGIC_PATH_TOKEN,
2743                                                              &r);
2744                         if (ret == -1) {
2745                                 status = map_nt_error_from_unix_common(errno);
2746                                 DEBUG(0, ("dcesrv_sock_accept: "
2747                                           "tsocket_address_unix_from_path() failed for NCALRPC: %s\n",
2748                                           nt_errstr(status)));
2749                                 stream_terminate_connection(srv_conn, nt_errstr(status));
2750                                 return;
2751                         }
2752                         dcesrv_conn->remote_address = r;
2753                 }
2754         }
2755
2756         srv_conn->private_data = dcesrv_conn;
2757
2758         subreq = dcerpc_read_ncacn_packet_send(dcesrv_conn,
2759                                                dcesrv_conn->event_ctx,
2760                                                dcesrv_conn->stream);
2761         if (!subreq) {
2762                 status = NT_STATUS_NO_MEMORY;
2763                 DEBUG(0,("dcesrv_sock_accept: dcerpc_read_fragment_buffer_send(%s)\n",
2764                         nt_errstr(status)));
2765                 stream_terminate_connection(srv_conn, nt_errstr(status));
2766                 return;
2767         }
2768         tevent_req_set_callback(subreq, dcesrv_read_fragment_done, dcesrv_conn);
2769
2770         return;
2771 }
2772
2773 static void dcesrv_conn_wait_done(struct tevent_req *subreq);
2774
2775 static void dcesrv_read_fragment_done(struct tevent_req *subreq)
2776 {
2777         struct dcesrv_connection *dce_conn = tevent_req_callback_data(subreq,
2778                                              struct dcesrv_connection);
2779         struct dcesrv_context *dce_ctx = dce_conn->dce_ctx;
2780         struct ncacn_packet *pkt;
2781         DATA_BLOB buffer;
2782         NTSTATUS status;
2783
2784         if (dce_conn->terminate) {
2785                 /*
2786                  * if the current connection is broken
2787                  * we need to clean it up before any other connection
2788                  */
2789                 dcesrv_terminate_connection(dce_conn, dce_conn->terminate);
2790                 dcesrv_cleanup_broken_connections(dce_ctx);
2791                 return;
2792         }
2793
2794         dcesrv_cleanup_broken_connections(dce_ctx);
2795
2796         status = dcerpc_read_ncacn_packet_recv(subreq, dce_conn,
2797                                                &pkt, &buffer);
2798         TALLOC_FREE(subreq);
2799         if (!NT_STATUS_IS_OK(status)) {
2800                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2801                 return;
2802         }
2803
2804         status = dcesrv_process_ncacn_packet(dce_conn, pkt, buffer);
2805         if (!NT_STATUS_IS_OK(status)) {
2806                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2807                 return;
2808         }
2809
2810         /*
2811          * This is used to block the connection during
2812          * pending authentication.
2813          */
2814         if (dce_conn->wait_send != NULL) {
2815                 subreq = dce_conn->wait_send(dce_conn,
2816                                              dce_conn->event_ctx,
2817                                              dce_conn->wait_private);
2818                 if (!subreq) {
2819                         status = NT_STATUS_NO_MEMORY;
2820                         dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2821                         return;
2822                 }
2823                 tevent_req_set_callback(subreq, dcesrv_conn_wait_done, dce_conn);
2824                 return;
2825         }
2826
2827         subreq = dcerpc_read_ncacn_packet_send(dce_conn,
2828                                                dce_conn->event_ctx,
2829                                                dce_conn->stream);
2830         if (!subreq) {
2831                 status = NT_STATUS_NO_MEMORY;
2832                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2833                 return;
2834         }
2835         tevent_req_set_callback(subreq, dcesrv_read_fragment_done, dce_conn);
2836 }
2837
2838 static void dcesrv_conn_wait_done(struct tevent_req *subreq)
2839 {
2840         struct dcesrv_connection *dce_conn = tevent_req_callback_data(subreq,
2841                                              struct dcesrv_connection);
2842         struct dcesrv_context *dce_ctx = dce_conn->dce_ctx;
2843         NTSTATUS status;
2844
2845         if (dce_conn->terminate) {
2846                 /*
2847                  * if the current connection is broken
2848                  * we need to clean it up before any other connection
2849                  */
2850                 dcesrv_terminate_connection(dce_conn, dce_conn->terminate);
2851                 dcesrv_cleanup_broken_connections(dce_ctx);
2852                 return;
2853         }
2854
2855         dcesrv_cleanup_broken_connections(dce_ctx);
2856
2857         status = dce_conn->wait_recv(subreq);
2858         dce_conn->wait_send = NULL;
2859         dce_conn->wait_recv = NULL;
2860         dce_conn->wait_private = NULL;
2861         TALLOC_FREE(subreq);
2862         if (!NT_STATUS_IS_OK(status)) {
2863                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2864                 return;
2865         }
2866
2867         subreq = dcerpc_read_ncacn_packet_send(dce_conn,
2868                                                dce_conn->event_ctx,
2869                                                dce_conn->stream);
2870         if (!subreq) {
2871                 status = NT_STATUS_NO_MEMORY;
2872                 dcesrv_terminate_connection(dce_conn, nt_errstr(status));
2873                 return;
2874         }
2875         tevent_req_set_callback(subreq, dcesrv_read_fragment_done, dce_conn);
2876 }
2877
2878 static void dcesrv_sock_recv(struct stream_connection *conn, uint16_t flags)
2879 {
2880         struct dcesrv_connection *dce_conn = talloc_get_type(conn->private_data,
2881                                              struct dcesrv_connection);
2882         dcesrv_terminate_connection(dce_conn, "dcesrv_sock_recv triggered");
2883 }
2884
2885 static void dcesrv_sock_send(struct stream_connection *conn, uint16_t flags)
2886 {
2887         struct dcesrv_connection *dce_conn = talloc_get_type(conn->private_data,
2888                                              struct dcesrv_connection);
2889         dcesrv_terminate_connection(dce_conn, "dcesrv_sock_send triggered");
2890 }
2891
2892
2893 static const struct stream_server_ops dcesrv_stream_ops = {
2894         .name                   = "rpc",
2895         .accept_connection      = dcesrv_sock_accept,
2896         .recv_handler           = dcesrv_sock_recv,
2897         .send_handler           = dcesrv_sock_send,
2898 };
2899
2900 static NTSTATUS dcesrv_add_ep_unix(struct dcesrv_context *dce_ctx, 
2901                                    struct loadparm_context *lp_ctx,
2902                                    struct dcesrv_endpoint *e,
2903                                    struct tevent_context *event_ctx,
2904                                    const struct model_ops *model_ops,
2905                                    void *process_context)
2906 {
2907         struct dcesrv_socket_context *dcesrv_sock;
2908         uint16_t port = 1;
2909         NTSTATUS status;
2910         const char *endpoint;
2911
2912         dcesrv_sock = talloc_zero(event_ctx, struct dcesrv_socket_context);
2913         NT_STATUS_HAVE_NO_MEMORY(dcesrv_sock);
2914
2915         /* remember the endpoint of this socket */
2916         dcesrv_sock->endpoint           = e;
2917         dcesrv_sock->dcesrv_ctx         = talloc_reference(dcesrv_sock, dce_ctx);
2918
2919         endpoint = dcerpc_binding_get_string_option(e->ep_description, "endpoint");
2920
2921         status = stream_setup_socket(dcesrv_sock, event_ctx, lp_ctx,
2922                                      model_ops, &dcesrv_stream_ops, 
2923                                      "unix", endpoint, &port,
2924                                      lpcfg_socket_options(lp_ctx),
2925                                      dcesrv_sock, process_context);
2926         if (!NT_STATUS_IS_OK(status)) {
2927                 DEBUG(0,("service_setup_stream_socket(path=%s) failed - %s\n",
2928                          endpoint, nt_errstr(status)));
2929         }
2930
2931         return status;
2932 }
2933
2934 static NTSTATUS dcesrv_add_ep_ncalrpc(struct dcesrv_context *dce_ctx, 
2935                                       struct loadparm_context *lp_ctx,
2936                                       struct dcesrv_endpoint *e,
2937                                       struct tevent_context *event_ctx,
2938                                       const struct model_ops *model_ops,
2939                                       void *process_context)
2940 {
2941         struct dcesrv_socket_context *dcesrv_sock;
2942         uint16_t port = 1;
2943         char *full_path;
2944         NTSTATUS status;
2945         const char *endpoint;
2946
2947         endpoint = dcerpc_binding_get_string_option(e->ep_description, "endpoint");
2948
2949         if (endpoint == NULL) {
2950                 /*
2951                  * No identifier specified: use DEFAULT.
2952                  *
2953                  * TODO: DO NOT hardcode this value anywhere else. Rather, specify
2954                  * no endpoint and let the epmapper worry about it.
2955                  */
2956                 endpoint = "DEFAULT";
2957                 status = dcerpc_binding_set_string_option(e->ep_description,
2958                                                           "endpoint",
2959                                                           endpoint);
2960                 if (!NT_STATUS_IS_OK(status)) {
2961                         DEBUG(0,("dcerpc_binding_set_string_option() failed - %s\n",
2962                                   nt_errstr(status)));
2963                         return status;
2964                 }
2965         }
2966
2967         full_path = talloc_asprintf(dce_ctx, "%s/%s", lpcfg_ncalrpc_dir(lp_ctx),
2968                                     endpoint);
2969
2970         dcesrv_sock = talloc_zero(event_ctx, struct dcesrv_socket_context);
2971         NT_STATUS_HAVE_NO_MEMORY(dcesrv_sock);
2972
2973         /* remember the endpoint of this socket */
2974         dcesrv_sock->endpoint           = e;
2975         dcesrv_sock->dcesrv_ctx         = talloc_reference(dcesrv_sock, dce_ctx);
2976
2977         status = stream_setup_socket(dcesrv_sock, event_ctx, lp_ctx,
2978                                      model_ops, &dcesrv_stream_ops, 
2979                                      "unix", full_path, &port, 
2980                                      lpcfg_socket_options(lp_ctx),
2981                                      dcesrv_sock, process_context);
2982         if (!NT_STATUS_IS_OK(status)) {
2983                 DEBUG(0,("service_setup_stream_socket(identifier=%s,path=%s) failed - %s\n",
2984                          endpoint, full_path, nt_errstr(status)));
2985         }
2986         return status;
2987 }
2988
2989 static NTSTATUS dcesrv_add_ep_np(struct dcesrv_context *dce_ctx,
2990                                  struct loadparm_context *lp_ctx,
2991                                  struct dcesrv_endpoint *e,
2992                                  struct tevent_context *event_ctx,
2993                                  const struct model_ops *model_ops,
2994                                  void *process_context)
2995 {
2996         struct dcesrv_socket_context *dcesrv_sock;
2997         NTSTATUS status;
2998         const char *endpoint;
2999
3000         endpoint = dcerpc_binding_get_string_option(e->ep_description, "endpoint");
3001         if (endpoint == NULL) {
3002                 DEBUG(0, ("Endpoint mandatory for named pipes\n"));
3003                 return NT_STATUS_INVALID_PARAMETER;
3004         }
3005
3006         dcesrv_sock = talloc_zero(event_ctx, struct dcesrv_socket_context);
3007         NT_STATUS_HAVE_NO_MEMORY(dcesrv_sock);
3008
3009         /* remember the endpoint of this socket */
3010         dcesrv_sock->endpoint           = e;
3011         dcesrv_sock->dcesrv_ctx         = talloc_reference(dcesrv_sock, dce_ctx);
3012
3013         status = tstream_setup_named_pipe(dce_ctx, event_ctx, lp_ctx,
3014                                           model_ops, &dcesrv_stream_ops,
3015                                           endpoint,
3016                                           dcesrv_sock, process_context);
3017         if (!NT_STATUS_IS_OK(status)) {
3018                 DEBUG(0,("stream_setup_named_pipe(pipe=%s) failed - %s\n",
3019                          endpoint, nt_errstr(status)));
3020                 return status;
3021         }
3022
3023         return NT_STATUS_OK;
3024 }
3025
3026 /*
3027   add a socket address to the list of events, one event per dcerpc endpoint
3028 */
3029 static NTSTATUS add_socket_rpc_tcp_iface(struct dcesrv_context *dce_ctx,
3030                                          struct dcesrv_endpoint *e,
3031                                          struct tevent_context *event_ctx,
3032                                          const struct model_ops *model_ops,
3033                                          const char *address,
3034                                          void *process_context)
3035 {
3036         struct dcesrv_socket_context *dcesrv_sock;
3037         uint16_t port = 0;
3038         NTSTATUS status;
3039         const char *endpoint;
3040         char port_str[6];
3041
3042         endpoint = dcerpc_binding_get_string_option(e->ep_description, "endpoint");
3043         if (endpoint != NULL) {
3044                 port = atoi(endpoint);
3045         }
3046
3047         dcesrv_sock = talloc_zero(event_ctx, struct dcesrv_socket_context);
3048         NT_STATUS_HAVE_NO_MEMORY(dcesrv_sock);
3049
3050         /* remember the endpoint of this socket */
3051         dcesrv_sock->endpoint           = e;
3052         dcesrv_sock->dcesrv_ctx         = talloc_reference(dcesrv_sock, dce_ctx);
3053
3054         status = stream_setup_socket(dcesrv_sock, event_ctx, dce_ctx->lp_ctx,
3055                                      model_ops, &dcesrv_stream_ops, 
3056                                      "ip", address, &port,
3057                                      lpcfg_socket_options(dce_ctx->lp_ctx),
3058                                      dcesrv_sock, process_context);
3059         if (!NT_STATUS_IS_OK(status)) {
3060                 struct dcesrv_if_list *iface;
3061                 DEBUG(0,("service_setup_stream_socket(address=%s,port=%u) for ",
3062                          address, port));
3063                 for (iface = e->interface_list; iface; iface = iface->next) {
3064                         DEBUGADD(0, ("%s ", iface->iface.name));
3065                 }
3066                 DEBUGADD(0, ("failed - %s",
3067                              nt_errstr(status)));
3068                 return status;
3069         }
3070
3071         snprintf(port_str, sizeof(port_str), "%u", port);
3072
3073         status = dcerpc_binding_set_string_option(e->ep_description,
3074                                                   "endpoint", port_str);
3075         if (!NT_STATUS_IS_OK(status)) {
3076                 DEBUG(0,("dcerpc_binding_set_string_option(endpoint, %s) failed - %s\n",
3077                          port_str, nt_errstr(status)));
3078                 return status;
3079         } else {
3080                 struct dcesrv_if_list *iface;
3081                 DEBUG(4,("Successfully listening on ncacn_ip_tcp endpoint [%s]:[%s] for ",
3082                          address, port_str));
3083                 for (iface = e->interface_list; iface; iface = iface->next) {
3084                         DEBUGADD(4, ("%s ", iface->iface.name));
3085                 }
3086                 DEBUGADD(4, ("\n"));
3087         }
3088
3089         return NT_STATUS_OK;
3090 }
3091
3092 #include "lib/socket/netif.h" /* Included here to work around the fact that socket_wrapper redefines bind() */
3093
3094 static NTSTATUS dcesrv_add_ep_tcp(struct dcesrv_context *dce_ctx, 
3095                                   struct loadparm_context *lp_ctx,
3096                                   struct dcesrv_endpoint *e,
3097                                   struct tevent_context *event_ctx,
3098                                   const struct model_ops *model_ops,
3099                                   void *process_context)
3100 {
3101         NTSTATUS status;
3102
3103         /* Add TCP/IP sockets */
3104         if (lpcfg_interfaces(lp_ctx) && lpcfg_bind_interfaces_only(lp_ctx)) {
3105                 int num_interfaces;
3106                 int i;
3107                 struct interface *ifaces;
3108
3109                 load_interface_list(dce_ctx, lp_ctx, &ifaces);
3110
3111                 num_interfaces = iface_list_count(ifaces);
3112                 for(i = 0; i < num_interfaces; i++) {
3113                         const char *address = iface_list_n_ip(ifaces, i);
3114                         status = add_socket_rpc_tcp_iface(dce_ctx, e, event_ctx,
3115                                                           model_ops, address,
3116                                                           process_context);
3117                         NT_STATUS_NOT_OK_RETURN(status);
3118                 }
3119         } else {
3120                 char **wcard;
3121                 size_t i;
3122                 size_t num_binds = 0;
3123                 wcard = iface_list_wildcard(dce_ctx);
3124                 NT_STATUS_HAVE_NO_MEMORY(wcard);
3125                 for (i=0; wcard[i]; i++) {
3126                         status = add_socket_rpc_tcp_iface(dce_ctx, e, event_ctx,
3127                                                           model_ops, wcard[i],
3128                                                           process_context);
3129                         if (NT_STATUS_IS_OK(status)) {
3130                                 num_binds++;
3131                         }
3132                 }
3133                 talloc_free(wcard);
3134                 if (num_binds == 0) {
3135                         return NT_STATUS_INVALID_PARAMETER_MIX;
3136                 }
3137         }
3138
3139         return NT_STATUS_OK;
3140 }
3141
3142 NTSTATUS dcesrv_add_ep(struct dcesrv_context *dce_ctx,
3143                        struct loadparm_context *lp_ctx,
3144                        struct dcesrv_endpoint *e,
3145                        struct tevent_context *event_ctx,
3146                        const struct model_ops *model_ops,
3147                        void *process_context)
3148 {
3149         enum dcerpc_transport_t transport =
3150                 dcerpc_binding_get_transport(e->ep_description);
3151
3152         switch (transport) {
3153         case NCACN_UNIX_STREAM:
3154                 return dcesrv_add_ep_unix(dce_ctx, lp_ctx, e, event_ctx,
3155                                           model_ops, process_context);
3156
3157         case NCALRPC:
3158                 return dcesrv_add_ep_ncalrpc(dce_ctx, lp_ctx, e, event_ctx,
3159                                              model_ops, process_context);
3160
3161         case NCACN_IP_TCP:
3162                 return dcesrv_add_ep_tcp(dce_ctx, lp_ctx, e, event_ctx,
3163                                          model_ops, process_context);
3164
3165         case NCACN_NP:
3166                 return dcesrv_add_ep_np(dce_ctx, lp_ctx, e, event_ctx,
3167                                         model_ops, process_context);
3168
3169         default:
3170                 return NT_STATUS_NOT_SUPPORTED;
3171         }
3172 }
3173
3174
3175 /**
3176  * retrieve credentials from a dce_call
3177  */
3178 _PUBLIC_ struct cli_credentials *dcesrv_call_credentials(struct dcesrv_call_state *dce_call)
3179 {
3180         return dce_call->conn->auth_state.session_info->credentials;
3181 }
3182
3183 /**
3184  * returns true if this is an authenticated call
3185  */
3186 _PUBLIC_ bool dcesrv_call_authenticated(struct dcesrv_call_state *dce_call)
3187 {
3188         enum security_user_level level;
3189         level = security_session_user_level(dce_call->conn->auth_state.session_info, NULL);
3190         return level >= SECURITY_USER;
3191 }
3192
3193 /**
3194  * retrieve account_name for a dce_call
3195  */
3196 _PUBLIC_ const char *dcesrv_call_account_name(struct dcesrv_call_state *dce_call)
3197 {
3198         return dce_call->context->conn->auth_state.session_info->info->account_name;
3199 }
3200
3201 /**
3202  * retrieve session_info from a dce_call
3203  */
3204 _PUBLIC_ struct auth_session_info *dcesrv_call_session_info(struct dcesrv_call_state *dce_call)
3205 {
3206         return dce_call->context->conn->auth_state.session_info;
3207 }