winbindd: fix predefined domains routing in find_lookup_domain_from_sid()
[amitay/samba.git] / source3 / winbindd / winbindd_util.c
index fb1793d250a7e162afd34ae2659cefed0f7bd61c..4d8fdb74472daaf0c6caa4f284053e8f63ba7544 100644 (file)
@@ -43,6 +43,7 @@
  * Winbind daemon for NT domain authentication nss module.
  **/
 
+static bool add_trusted_domains_dc(void);
 
 /* The list of trusted domains.  Note that the list can be deleted and
    recreated using the init_domain_list() function so pointers to
@@ -107,15 +108,6 @@ static bool is_internal_domain(const struct dom_sid *sid)
        return (sid_check_is_our_sam(sid) || sid_check_is_builtin(sid));
 }
 
-static bool is_in_internal_domain(const struct dom_sid *sid)
-{
-       if (sid == NULL)
-               return False;
-
-       return (sid_check_is_in_our_sam(sid) || sid_check_is_in_builtin(sid));
-}
-
-
 /* Add a trusted domain to our list of domains.
    If the domain already exists in the list,
    return it and don't re-initialize.  */
@@ -127,6 +119,7 @@ static NTSTATUS add_trusted_domain(const char *domain_name,
                                   uint32_t trust_flags,
                                   uint32_t trust_attribs,
                                   enum netr_SchannelType secure_channel_type,
+                                  struct winbindd_domain *routing_domain,
                                   struct winbindd_domain **_d)
 {
        struct winbindd_domain *domain = NULL;
@@ -226,6 +219,18 @@ static NTSTATUS add_trusted_domain(const char *domain_name,
                return NT_STATUS_NO_MEMORY;
        }
 
+       domain->queue = tevent_queue_create(domain, "winbind_domain");
+       if (domain->queue == NULL) {
+               TALLOC_FREE(domain);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       domain->binding_handle = wbint_binding_handle(domain, domain, NULL);
+       if (domain->binding_handle == NULL) {
+               TALLOC_FREE(domain);
+               return NT_STATUS_NO_MEMORY;
+       }
+
        domain->name = talloc_strdup(domain, domain_name);
        if (domain->name == NULL) {
                TALLOC_FREE(domain);
@@ -253,6 +258,7 @@ static NTSTATUS add_trusted_domain(const char *domain_name,
        domain->domain_type = trust_type;
        domain->domain_trust_attribs = trust_attribs;
        domain->secure_channel_type = secure_channel_type;
+       domain->routing_domain = routing_domain;
        sid_copy(&domain->sid, sid);
 
        /* Is this our primary domain ? */
@@ -275,6 +281,8 @@ static NTSTATUS add_trusted_domain(const char *domain_name,
                }
        }
 
+       domain->can_do_ncacn_ip_tcp = domain->active_directory;
+
        /* Link to domain list */
        DLIST_ADD_END(_domain_list, domain);
 
@@ -291,7 +299,7 @@ static NTSTATUS add_trusted_domain(const char *domain_name,
 }
 
 bool set_routing_domain(struct winbindd_domain *domain,
-                       const struct winbindd_domain *routing_domain)
+                       struct winbindd_domain *routing_domain)
 {
        if (domain->routing_domain == NULL) {
                domain->routing_domain = routing_domain;
@@ -303,6 +311,59 @@ bool set_routing_domain(struct winbindd_domain *domain,
        return true;
 }
 
+bool add_trusted_domain_from_auth(uint16_t validation_level,
+                                 struct info3_text *info3,
+                                 struct info6_text *info6)
+{
+       struct winbindd_domain *domain = NULL;
+       struct dom_sid domain_sid;
+       const char *dns_domainname = NULL;
+       NTSTATUS status;
+       bool ok;
+
+       /*
+        * We got a successfull auth from a domain that might not yet be in our
+        * domain list. If we're a member we trust our DC who authenticated the
+        * user from that domain and add the domain to our list on-the-fly. If
+        * we're a DC we rely on configured trusts and don't add on-the-fly.
+        */
+
+       if (IS_DC) {
+               return true;
+       }
+
+       ok = dom_sid_parse(info3->dom_sid, &domain_sid);
+       if (!ok) {
+               DBG_NOTICE("dom_sid_parse [%s] failed\n", info3->dom_sid);
+               return false;
+       }
+
+       if (validation_level == 6) {
+               if (!strequal(info6->dns_domainname, "")) {
+                       dns_domainname = info6->dns_domainname;
+               }
+       }
+
+       status = add_trusted_domain(info3->logon_dom,
+                                   dns_domainname,
+                                   &domain_sid,
+                                   0,
+                                   NETR_TRUST_FLAG_OUTBOUND,
+                                   0,
+                                   SEC_CHAN_NULL,
+                                   find_default_route_domain(),
+                                   &domain);
+       if (!NT_STATUS_IS_OK(status) &&
+           !NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_DOMAIN))
+       {
+               DBG_DEBUG("Adding domain [%s] with sid [%s] failed\n",
+                         info3->logon_dom, info3->dom_sid);
+               return false;
+       }
+
+       return true;
+}
+
 bool domain_is_forest_root(const struct winbindd_domain *domain)
 {
        const uint32_t fr_flags =
@@ -339,7 +400,7 @@ static void add_trusted_domains( struct winbindd_domain *domain )
        state->request.length = sizeof(state->request);
        state->request.cmd = WINBINDD_LIST_TRUSTDOM;
 
-       req = wb_domain_request_send(state, server_event_context(),
+       req = wb_domain_request_send(state, global_event_context(),
                                     domain, &state->request);
        if (req == NULL) {
                DEBUG(1, ("wb_domain_request_send failed\n"));
@@ -482,6 +543,7 @@ static void trustdom_list_done(struct tevent_req *req)
                                            trust_flags,
                                            trust_attribs,
                                            SEC_CHAN_NULL,
+                                           find_default_route_domain(),
                                            &domain);
                if (!NT_STATUS_IS_OK(status) &&
                    !NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_DOMAIN))
@@ -531,7 +593,7 @@ static void rescan_forest_root_trusts( void )
 {
        struct winbindd_tdc_domain *dom_list = NULL;
         size_t num_trusts = 0;
-       int i;
+       size_t i;
        NTSTATUS status;
 
        /* The only transitive trusts supported by Windows 2003 AD are
@@ -565,6 +627,7 @@ static void rescan_forest_root_trusts( void )
                                                    dom_list[i].trust_flags,
                                                    dom_list[i].trust_attribs,
                                                    SEC_CHAN_NULL,
+                                                   find_default_route_domain(),
                                                    &d);
 
                        if (!NT_STATUS_IS_OK(status) &&
@@ -607,7 +670,7 @@ static void rescan_forest_trusts( void )
        struct winbindd_domain *d = NULL;
        struct winbindd_tdc_domain *dom_list = NULL;
         size_t num_trusts = 0;
-       int i;
+       size_t i;
        NTSTATUS status;
 
        /* The only transitive trusts supported by Windows 2003 AD are
@@ -647,6 +710,7 @@ static void rescan_forest_trusts( void )
                                        flags,
                                        attribs,
                                        SEC_CHAN_NULL,
+                                       find_default_route_domain(),
                                        &d);
                                if (!NT_STATUS_IS_OK(status) &&
                                    NT_STATUS_EQUAL(status,
@@ -720,7 +784,12 @@ enum winbindd_result winbindd_dual_init_connection(struct winbindd_domain *domai
                [sizeof(state->request->data.init_conn.dcname)-1]='\0';
 
        if (strlen(state->request->data.init_conn.dcname) > 0) {
-               fstrcpy(domain->dcname, state->request->data.init_conn.dcname);
+               TALLOC_FREE(domain->dcname);
+               domain->dcname = talloc_strdup(domain,
+                               state->request->data.init_conn.dcname);
+               if (domain->dcname == NULL) {
+                       return WINBINDD_ERROR;
+               }
        }
 
        init_dc_connection(domain, false);
@@ -755,64 +824,14 @@ static void wb_imsg_new_trusted_domain(struct imessaging_context *msg,
                                       struct server_id server_id,
                                       DATA_BLOB *data)
 {
-       TALLOC_CTX *frame = talloc_stackframe();
-       enum netr_SchannelType secure_channel_type = SEC_CHAN_DOMAIN;
-       struct lsa_TrustDomainInfoInfoEx info;
-       enum ndr_err_code ndr_err;
-       struct winbindd_domain *d = NULL;
-       uint32_t trust_flags = 0;
-       NTSTATUS status;
-
-       DEBUG(5, ("wb_imsg_new_trusted_domain\n"));
-
-       if (data == NULL) {
-               TALLOC_FREE(frame);
-               return;
-       }
-
-       ndr_err = ndr_pull_struct_blob_all(data, frame, &info,
-                       (ndr_pull_flags_fn_t)ndr_pull_lsa_TrustDomainInfoInfoEx);
-       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-               TALLOC_FREE(frame);
-               return;
-       }
-
-       d = find_domain_from_name_noinit(info.netbios_name.string);
-       if (d != NULL) {
-               TALLOC_FREE(frame);
-               return;
-       }
+       bool ok;
 
-       if (info.trust_type == LSA_TRUST_TYPE_UPLEVEL) {
-               secure_channel_type = SEC_CHAN_DNS_DOMAIN;
-       }
-       if (info.trust_direction & LSA_TRUST_DIRECTION_INBOUND) {
-               trust_flags |= NETR_TRUST_FLAG_INBOUND;
-       }
-       if (info.trust_direction & LSA_TRUST_DIRECTION_OUTBOUND) {
-               trust_flags |= NETR_TRUST_FLAG_OUTBOUND;
-       }
-       if (info.trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
-               trust_flags |= NETR_TRUST_FLAG_IN_FOREST;
-       }
+       DBG_NOTICE("Rescanning trusted domains\n");
 
-       status = add_trusted_domain(info.netbios_name.string,
-                                   info.domain_name.string,
-                                   info.sid,
-                                   info.trust_type,
-                                   trust_flags,
-                                   info.trust_attributes,
-                                   secure_channel_type,
-                                   &d);
-       if (!NT_STATUS_IS_OK(status) &&
-           !NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_DOMAIN))
-       {
-               DBG_NOTICE("add_trusted_domain returned %s\n",
-                          nt_errstr(status));
-               TALLOC_FREE(frame);
-               return;
+       ok = add_trusted_domains_dc();
+       if (!ok) {
+               DBG_ERR("Failed to reload trusted domains\n");
        }
-       TALLOC_FREE(frame);
 }
 
 /*
@@ -858,6 +877,214 @@ static bool migrate_secrets_tdb_to_ldb(struct winbindd_domain *domain)
        return true;
 }
 
+static bool add_trusted_domains_dc(void)
+{
+       struct winbindd_domain *domain =  NULL;
+       struct pdb_trusted_domain **domains = NULL;
+       uint32_t num_domains = 0;
+       uint32_t i;
+       NTSTATUS status;
+
+       if (!(pdb_capabilities() & PDB_CAP_TRUSTED_DOMAINS_EX)) {
+               struct trustdom_info **ti = NULL;
+
+               status = pdb_enum_trusteddoms(talloc_tos(), &num_domains, &ti);
+               if (!NT_STATUS_IS_OK(status)) {
+                       DBG_ERR("pdb_enum_trusteddoms() failed - %s\n",
+                               nt_errstr(status));
+                       return false;
+               }
+
+               for (i = 0; i < num_domains; i++) {
+                       status = add_trusted_domain(ti[i]->name,
+                                                   NULL,
+                                                   &ti[i]->sid,
+                                                   LSA_TRUST_TYPE_DOWNLEVEL,
+                                                   NETR_TRUST_FLAG_OUTBOUND,
+                                                   0,
+                                                   SEC_CHAN_DOMAIN,
+                                                   NULL,
+                                                   &domain);
+                       if (!NT_STATUS_IS_OK(status)) {
+                               DBG_NOTICE("add_trusted_domain returned %s\n",
+                                          nt_errstr(status));
+                               return false;
+                       }
+
+                       /* Even in the parent winbindd we'll need to
+                          talk to the DC, so try and see if we can
+                          contact it. Theoretically this isn't neccessary
+                          as the init_dc_connection() in init_child_recv()
+                          will do this, but we can start detecting the DC
+                          early here. */
+                       set_domain_online_request(domain);
+               }
+
+               return true;
+       }
+
+       status = pdb_enum_trusted_domains(talloc_tos(), &num_domains, &domains);
+       if (!NT_STATUS_IS_OK(status)) {
+               DBG_ERR("pdb_enum_trusted_domains() failed - %s\n",
+                       nt_errstr(status));
+               return false;
+       }
+
+       for (i = 0; i < num_domains; i++) {
+               enum netr_SchannelType sec_chan_type = SEC_CHAN_DOMAIN;
+               uint32_t trust_flags = 0;
+
+               if (domains[i]->trust_type == LSA_TRUST_TYPE_UPLEVEL) {
+                       sec_chan_type = SEC_CHAN_DNS_DOMAIN;
+               }
+
+               if (!(domains[i]->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND)) {
+                       sec_chan_type = SEC_CHAN_NULL;
+               }
+
+               if (domains[i]->trust_direction & LSA_TRUST_DIRECTION_INBOUND) {
+                       trust_flags |= NETR_TRUST_FLAG_INBOUND;
+               }
+               if (domains[i]->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND) {
+                       trust_flags |= NETR_TRUST_FLAG_OUTBOUND;
+               }
+               if (domains[i]->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
+                       trust_flags |= NETR_TRUST_FLAG_IN_FOREST;
+               }
+
+               if (domains[i]->trust_attributes & LSA_TRUST_ATTRIBUTE_CROSS_ORGANIZATION) {
+                       /*
+                        * We don't support selective authentication yet.
+                        */
+                       DBG_WARNING("Ignoring CROSS_ORGANIZATION trust to "
+                                   "domain[%s/%s]\n",
+                                   domains[i]->netbios_name,
+                                   domains[i]->domain_name);
+                       continue;
+               }
+
+               status = add_trusted_domain(domains[i]->netbios_name,
+                                           domains[i]->domain_name,
+                                           &domains[i]->security_identifier,
+                                           domains[i]->trust_type,
+                                           trust_flags,
+                                           domains[i]->trust_attributes,
+                                           sec_chan_type,
+                                           NULL,
+                                           &domain);
+               if (!NT_STATUS_IS_OK(status)) {
+                       DBG_NOTICE("add_trusted_domain returned %s\n",
+                                  nt_errstr(status));
+                       return false;
+               }
+
+               if (domains[i]->trust_type == LSA_TRUST_TYPE_UPLEVEL) {
+                       domain->active_directory = true;
+               }
+               domain->domain_type = domains[i]->trust_type;
+               domain->domain_trust_attribs = domains[i]->trust_attributes;
+
+               if (sec_chan_type != SEC_CHAN_NULL) {
+                       /* Even in the parent winbindd we'll need to
+                          talk to the DC, so try and see if we can
+                          contact it. Theoretically this isn't neccessary
+                          as the init_dc_connection() in init_child_recv()
+                          will do this, but we can start detecting the DC
+                          early here. */
+                       set_domain_online_request(domain);
+               }
+       }
+
+       for (i = 0; i < num_domains; i++) {
+               struct ForestTrustInfo fti;
+               uint32_t fi;
+               enum ndr_err_code ndr_err;
+               struct winbindd_domain *routing_domain = NULL;
+
+               if (domains[i]->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
+                       continue;
+               }
+
+               if (!(domains[i]->trust_attributes & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE)) {
+                       continue;
+               }
+
+               if (domains[i]->trust_forest_trust_info.length == 0) {
+                       continue;
+               }
+
+               routing_domain = find_domain_from_name_noinit(
+                       domains[i]->netbios_name);
+               if (routing_domain == NULL) {
+                       DBG_ERR("Can't find winbindd domain [%s]\n",
+                               domains[i]->netbios_name);
+                       return false;
+               }
+
+               ndr_err = ndr_pull_struct_blob_all(
+                       &domains[i]->trust_forest_trust_info,
+                       talloc_tos(), &fti,
+                       (ndr_pull_flags_fn_t)ndr_pull_ForestTrustInfo);
+               if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
+                       DBG_ERR("ndr_pull_ForestTrustInfo(%s) - %s\n",
+                               domains[i]->netbios_name,
+                               ndr_map_error2string(ndr_err));
+                       return false;
+               }
+
+               for (fi = 0; fi < fti.count; fi++) {
+                       struct ForestTrustInfoRecord *rec =
+                               &fti.records[fi].record;
+                       struct ForestTrustDataDomainInfo *drec = NULL;
+
+                       if (rec->type != FOREST_TRUST_DOMAIN_INFO) {
+                               continue;
+                       }
+                       drec = &rec->data.info;
+
+                       if (rec->flags & LSA_NB_DISABLED_MASK) {
+                               continue;
+                       }
+
+                       if (rec->flags & LSA_SID_DISABLED_MASK) {
+                               continue;
+                       }
+
+                       /*
+                        * TODO:
+                        * also try to find a matching
+                        * LSA_TLN_DISABLED_MASK ???
+                        */
+
+                       domain = find_domain_from_name_noinit(drec->netbios_name.string);
+                       if (domain != NULL) {
+                               continue;
+                       }
+
+                       status = add_trusted_domain(drec->netbios_name.string,
+                                                   drec->dns_name.string,
+                                                   &drec->sid,
+                                                   LSA_TRUST_TYPE_UPLEVEL,
+                                                   NETR_TRUST_FLAG_OUTBOUND,
+                                                   0,
+                                                   SEC_CHAN_NULL,
+                                                   routing_domain,
+                                                   &domain);
+                       if (!NT_STATUS_IS_OK(status)) {
+                               DBG_NOTICE("add_trusted_domain returned %s\n",
+                                          nt_errstr(status));
+                               return false;
+                       }
+                       if (domain == NULL) {
+                               continue;
+                       }
+               }
+       }
+
+       return true;
+}
+
+
 /* Look up global info for the winbind daemon */
 bool init_domain_list(void)
 {
@@ -865,6 +1092,7 @@ bool init_domain_list(void)
        struct pdb_domain_info *pdb_domain_info = NULL;
        struct winbindd_domain *domain =  NULL;
        NTSTATUS status;
+       bool ok;
 
        /* Free existing list */
        free_domain_list();
@@ -878,6 +1106,7 @@ bool init_domain_list(void)
                                    0, /* trust_flags */
                                    0, /* trust_attribs */
                                    SEC_CHAN_LOCAL,
+                                   NULL,
                                    &domain);
        if (!NT_STATUS_IS_OK(status)) {
                DBG_ERR("add_trusted_domain BUILTIN returned %s\n",
@@ -904,7 +1133,6 @@ bool init_domain_list(void)
                enum netr_SchannelType sec_chan_type;
                const char *account_name;
                struct samr_Password current_nt_hash;
-               bool ok;
 
                if (pdb_domain_info == NULL) {
                        DEBUG(0, ("Failed to fetch our own, local AD "
@@ -930,6 +1158,7 @@ bool init_domain_list(void)
                                            trust_flags,
                                            LSA_TRUST_ATTRIBUTE_WITHIN_FOREST,
                                            SEC_CHAN_BDC,
+                                           NULL,
                                            &domain);
                TALLOC_FREE(pdb_domain_info);
                if (!NT_STATUS_IS_OK(status)) {
@@ -1001,6 +1230,7 @@ bool init_domain_list(void)
                                            trust_flags,
                                            0, /* trust_attribs */
                                            secure_channel_type,
+                                           NULL,
                                            &domain);
                if (!NT_STATUS_IS_OK(status)) {
                        DBG_ERR("Failed to add local SAM to "
@@ -1008,7 +1238,14 @@ bool init_domain_list(void)
                        return false;
                }
        }
-       /* Add ourselves as the first entry. */
+
+       if (IS_DC) {
+               ok = add_trusted_domains_dc();
+               if (!ok) {
+                       DBG_ERR("init_domain_list_dc failed\n");
+                       return false;
+               }
+       }
 
        if ( role == ROLE_DOMAIN_MEMBER ) {
                struct dom_sid our_sid;
@@ -1033,6 +1270,7 @@ bool init_domain_list(void)
                                            NETR_TRUST_FLAG_OUTBOUND,
                                            0, /* trust_attribs */
                                            SEC_CHAN_WKSTA,
+                                           NULL,
                                            &domain);
                if (!NT_STATUS_IS_OK(status)) {
                        DBG_ERR("Failed to add local SAM to "
@@ -1049,207 +1287,11 @@ bool init_domain_list(void)
 
        }
 
-       if (IS_DC && (pdb_capabilities() & PDB_CAP_TRUSTED_DOMAINS_EX)) {
-               uint32_t num_domains = 0;
-               struct pdb_trusted_domain **domains = NULL;
-               uint32_t i;
-
-               status = pdb_enum_trusted_domains(talloc_tos(), &num_domains, &domains);
-               if (!NT_STATUS_IS_OK(status)) {
-                       DBG_ERR("pdb_enum_trusted_domains() failed - %s\n",
-                               nt_errstr(status));
-                       return false;
-               }
-
-               for (i = 0; i < num_domains; i++) {
-                       enum netr_SchannelType sec_chan_type = SEC_CHAN_DOMAIN;
-                       uint32_t trust_flags = 0;
-
-                       if (domains[i]->trust_type == LSA_TRUST_TYPE_UPLEVEL) {
-                               sec_chan_type = SEC_CHAN_DNS_DOMAIN;
-                       }
-
-                       if (!(domains[i]->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND)) {
-                               sec_chan_type = SEC_CHAN_NULL;
-                       }
-
-                       if (domains[i]->trust_direction & LSA_TRUST_DIRECTION_INBOUND) {
-                               trust_flags |= NETR_TRUST_FLAG_INBOUND;
-                       }
-                       if (domains[i]->trust_direction & LSA_TRUST_DIRECTION_OUTBOUND) {
-                               trust_flags |= NETR_TRUST_FLAG_OUTBOUND;
-                       }
-                       if (domains[i]->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
-                               trust_flags |= NETR_TRUST_FLAG_IN_FOREST;
-                       }
-
-                       status = add_trusted_domain(domains[i]->netbios_name,
-                                                   domains[i]->domain_name,
-                                                   &domains[i]->security_identifier,
-                                                   domains[i]->trust_type,
-                                                   trust_flags,
-                                                   domains[i]->trust_attributes,
-                                                   sec_chan_type,
-                                                   &domain);
-                       if (!NT_STATUS_IS_OK(status)) {
-                               DBG_NOTICE("add_trusted_domain returned %s\n",
-                                          nt_errstr(status));
-                               return false;
-                       }
-
-                       if (domains[i]->trust_type == LSA_TRUST_TYPE_UPLEVEL) {
-                               domain->active_directory = true;
-                       }
-                       domain->domain_type = domains[i]->trust_type;
-                       domain->domain_trust_attribs = domains[i]->trust_attributes;
-
-                       if (sec_chan_type != SEC_CHAN_NULL) {
-                               /* Even in the parent winbindd we'll need to
-                                  talk to the DC, so try and see if we can
-                                  contact it. Theoretically this isn't neccessary
-                                  as the init_dc_connection() in init_child_recv()
-                                  will do this, but we can start detecting the DC
-                                  early here. */
-                               set_domain_online_request(domain);
-                       }
-               }
-
-               for (i = 0; i < num_domains; i++) {
-                       struct ForestTrustInfo fti;
-                       uint32_t fi;
-                       enum ndr_err_code ndr_err;
-                       struct winbindd_domain *routing_domain = NULL;
-                       bool ok;
-
-                       if (domains[i]->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
-                               continue;
-                       }
-
-                       if (!(domains[i]->trust_attributes & LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE)) {
-                               continue;
-                       }
-
-                       if (domains[i]->trust_forest_trust_info.length == 0) {
-                               continue;
-                       }
-
-                       routing_domain = find_domain_from_name_noinit(
-                               domains[i]->netbios_name);
-                       if (routing_domain == NULL) {
-                               DBG_ERR("Can't find winbindd domain [%s]\n",
-                                       domains[i]->netbios_name);
-                               return false;
-                       }
-
-                       ndr_err = ndr_pull_struct_blob_all(
-                                       &domains[i]->trust_forest_trust_info,
-                                       talloc_tos(), &fti,
-                                       (ndr_pull_flags_fn_t)ndr_pull_ForestTrustInfo);
-                       if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
-                               DBG_ERR("ndr_pull_ForestTrustInfo(%s) - %s\n",
-                                       domains[i]->netbios_name,
-                                       ndr_map_error2string(ndr_err));
-                               return false;
-                       }
-
-                       for (fi = 0; fi < fti.count; fi++) {
-                               struct ForestTrustInfoRecord *rec =
-                                       &fti.records[fi].record;
-                               struct ForestTrustDataDomainInfo *drec = NULL;
-
-                               if (rec->type != FOREST_TRUST_DOMAIN_INFO) {
-                                       continue;
-                               }
-                               drec = &rec->data.info;
-
-                               if (rec->flags & LSA_NB_DISABLED_MASK) {
-                                       continue;
-                               }
-
-                               if (rec->flags & LSA_SID_DISABLED_MASK) {
-                                       continue;
-                               }
-
-                               /*
-                                * TODO:
-                                * also try to find a matching
-                                * LSA_TLN_DISABLED_MASK ???
-                                */
-
-                               domain = find_domain_from_name_noinit(drec->netbios_name.string);
-                               if (domain != NULL) {
-                                       continue;
-                               }
-
-                               status = add_trusted_domain(drec->netbios_name.string,
-                                                           drec->dns_name.string,
-                                                           &drec->sid,
-                                                           LSA_TRUST_TYPE_UPLEVEL,
-                                                           NETR_TRUST_FLAG_OUTBOUND,
-                                                           0,
-                                                           SEC_CHAN_NULL,
-                                                           &domain);
-                               if (!NT_STATUS_IS_OK(status)) {
-                                       DBG_NOTICE("add_trusted_domain returned %s\n",
-                                                  nt_errstr(status));
-                                       return false;
-                               }
-                               if (domain == NULL) {
-                                       continue;
-                               }
-                               ok = set_routing_domain(domain, routing_domain);
-                               if (!ok) {
-                                       DBG_ERR("set_routing_domain on [%s] to "
-                                               "[%s] failed\n",
-                                               domain->name,
-                                               routing_domain->name);
-                                       return false;
-                               }
-                       }
-               }
-       } else if (IS_DC) {
-               uint32_t num_domains = 0;
-               struct trustdom_info **domains = NULL;
-               uint32_t i;
-
-               status = pdb_enum_trusteddoms(talloc_tos(), &num_domains, &domains);
-               if (!NT_STATUS_IS_OK(status)) {
-                       DBG_ERR("pdb_enum_trusteddoms() failed - %s\n",
-                               nt_errstr(status));
-                       return false;
-               }
-
-               for (i = 0; i < num_domains; i++) {
-                       status = add_trusted_domain(domains[i]->name,
-                                                   NULL,
-                                                   &domains[i]->sid,
-                                                   LSA_TRUST_TYPE_DOWNLEVEL,
-                                                   NETR_TRUST_FLAG_OUTBOUND,
-                                                   0,
-                                                   SEC_CHAN_DOMAIN,
-                                                   &domain);
-                       if (!NT_STATUS_IS_OK(status)) {
-                               DBG_NOTICE("add_trusted_domain returned %s\n",
-                                          nt_errstr(status));
-                               return false;
-                       }
-
-                       /* Even in the parent winbindd we'll need to
-                          talk to the DC, so try and see if we can
-                          contact it. Theoretically this isn't neccessary
-                          as the init_dc_connection() in init_child_recv()
-                          will do this, but we can start detecting the DC
-                          early here. */
-                       set_domain_online_request(domain);
-               }
-       }
-
        status = imessaging_register(winbind_imessaging_context(), NULL,
-                                    MSG_WINBIND_NEW_TRUSTED_DOMAIN,
+                                    MSG_WINBIND_RELOAD_TRUSTED_DOMAINS,
                                     wb_imsg_new_trusted_domain);
        if (!NT_STATUS_IS_OK(status)) {
-               DEBUG(0, ("imessaging_register(MSG_WINBIND_NEW_TRUSTED_DOMAIN) - %s\n",
-                         nt_errstr(status)));
+               DBG_ERR("imessaging_register failed %s\n", nt_errstr(status));
                return false;
        }
 
@@ -1405,7 +1447,7 @@ struct winbindd_domain *find_default_route_domain(void)
        if (!IS_DC) {
                return find_our_domain();
        }
-       DBG_ERR("Routing logic not yet implemented on a DC");
+       DBG_DEBUG("Routing logic not yet implemented on a DC\n");
        return NULL;
 }
 
@@ -1424,19 +1466,33 @@ struct winbindd_domain *find_lookup_domain_from_sid(const struct dom_sid *sid)
             sid_check_is_unix_groups(sid) ||
             sid_check_is_in_unix_users(sid) ||
             sid_check_is_unix_users(sid) ||
+            sid_check_is_our_sam(sid) ||
+             sid_check_is_in_our_sam(sid) )
+       {
+               return find_domain_from_sid(get_global_sam_sid());
+       }
+
+       if ( sid_check_is_builtin(sid) ||
+            sid_check_is_in_builtin(sid) ||
             sid_check_is_wellknown_domain(sid, NULL) ||
             sid_check_is_in_wellknown_domain(sid) )
        {
-               return find_domain_from_sid(get_global_sam_sid());
+               return find_domain_from_sid(&global_sid_Builtin);
        }
 
-       /* A DC can't ask the local smbd for remote SIDs, here winbindd is the
-        * one to contact the external DC's. On member servers the internal
-        * domains are different: These are part of the local SAM. */
+       if (IS_DC) {
+               struct winbindd_domain *domain = NULL;
+
+               domain = find_domain_from_sid_noinit(sid);
+               if (domain == NULL) {
+                       return NULL;
+               }
+
+               if (domain->secure_channel_type != SEC_CHAN_NULL) {
+                       return domain;
+               }
 
-       if (IS_DC || is_internal_domain(sid) || is_in_internal_domain(sid)) {
-               DEBUG(10, ("calling find_domain_from_sid\n"));
-               return find_domain_from_sid(sid);
+               return domain->routing_domain;
        }
 
        /* On a member server a query for SID or name can always go to our
@@ -1458,10 +1514,25 @@ struct winbindd_domain *find_lookup_domain_from_name(const char *domain_name)
                return find_domain_from_name_noinit( get_global_sam_name() );
        }
 
-       if (IS_DC || strequal(domain_name, "BUILTIN") ||
-           strequal(domain_name, get_global_sam_name()))
+       if (strequal(domain_name, "BUILTIN") ||
+           strequal(domain_name, get_global_sam_name())) {
                return find_domain_from_name_noinit(domain_name);
+       }
 
+       if (IS_DC) {
+               struct winbindd_domain *domain = NULL;
+
+               domain = find_domain_from_name_noinit(domain_name);
+               if (domain == NULL) {
+                       return NULL;
+               }
+
+               if (domain->secure_channel_type != SEC_CHAN_NULL) {
+                       return domain;
+               }
+
+               return domain->routing_domain;
+       }
 
        return find_our_domain();
 }
@@ -1494,45 +1565,44 @@ static bool assume_domain(const char *domain)
        return False;
 }
 
-/* Parse a string of the form DOMAIN\user into a domain and a user */
-
-bool parse_domain_user(const char *domuser, fstring domain, fstring user)
+/* Parse a DOMAIN\user or UPN string into a domain, namespace and a user */
+bool parse_domain_user(const char *domuser,
+                      fstring namespace,
+                      fstring domain,
+                      fstring user)
 {
-       char *p = strchr(domuser,*lp_winbind_separator());
+       char *p = NULL;
 
-       if ( !p ) {
+       if (strlen(domuser) == 0) {
+               return false;
+       }
+
+       p = strchr(domuser, *lp_winbind_separator());
+       if (p != NULL) {
+               fstrcpy(user, p + 1);
+               fstrcpy(domain, domuser);
+               domain[PTR_DIFF(p, domuser)] = '\0';
+               fstrcpy(namespace, domain);
+       } else {
                fstrcpy(user, domuser);
-               p = strchr(domuser, '@');
 
-               if ( assume_domain(lp_workgroup()) && p == NULL) {
+               domain[0] = '\0';
+               namespace[0] = '\0';
+               p = strchr(domuser, '@');
+               if (p != NULL) {
+                       /* upn */
+                       fstrcpy(namespace, p + 1);
+               } else if (assume_domain(lp_workgroup())) {
                        fstrcpy(domain, lp_workgroup());
-               } else if (p != NULL) {
-                       fstrcpy(domain, p + 1);
-                       user[PTR_DIFF(p, domuser)] = 0;
+                       fstrcpy(namespace, domain);
                } else {
-                       return False;
+                       fstrcpy(namespace, lp_netbios_name());
                }
-       } else {
-               fstrcpy(user, p+1);
-               fstrcpy(domain, domuser);
-               domain[PTR_DIFF(p, domuser)] = 0;
        }
 
        return strupper_m(domain);
 }
 
-bool parse_domain_user_talloc(TALLOC_CTX *mem_ctx, const char *domuser,
-                             char **domain, char **user)
-{
-       fstring fstr_domain, fstr_user;
-       if (!parse_domain_user(domuser, fstr_domain, fstr_user)) {
-               return False;
-       }
-       *domain = talloc_strdup(mem_ctx, fstr_domain);
-       *user = talloc_strdup(mem_ctx, fstr_user);
-       return ((*domain != NULL) && (*user != NULL));
-}
-
 /* Ensure an incoming username from NSS is fully qualified. Replace the
    incoming fstring with DOMAIN <separator> user. Returns the same
    values as parse_domain_user() but also replaces the incoming username.
@@ -1542,9 +1612,15 @@ bool parse_domain_user_talloc(TALLOC_CTX *mem_ctx, const char *domuser,
    really should be changed to use this instead of doing things
    by hand. JRA. */
 
-bool canonicalize_username(fstring username_inout, fstring domain, fstring user)
+bool canonicalize_username(fstring username_inout,
+                          fstring namespace,
+                          fstring domain,
+                          fstring user)
 {
-       if (!parse_domain_user(username_inout, domain, user)) {
+       bool ok;
+
+       ok = parse_domain_user(username_inout, namespace, domain, user);
+       if (!ok) {
                return False;
        }
        slprintf(username_inout, sizeof(fstring) - 1, "%s%c%s",
@@ -1566,26 +1642,6 @@ bool canonicalize_username(fstring username_inout, fstring domain, fstring user)
 
     We always canonicalize as UPPERCASE DOMAIN, lowercase username.
 */
-void fill_domain_username(fstring name, const char *domain, const char *user, bool can_assume)
-{
-       fstring tmp_user;
-
-       if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
-               can_assume = false;
-       }
-
-       fstrcpy(tmp_user, user);
-       (void)strlower_m(tmp_user);
-
-       if (can_assume && assume_domain(domain)) {
-               strlcpy(name, tmp_user, sizeof(fstring));
-       } else {
-               slprintf(name, sizeof(fstring) - 1, "%s%c%s",
-                        domain, *lp_winbind_separator(),
-                        tmp_user);
-       }
-}
-
 /**
  * talloc version of fill_domain_username()
  * return NULL on talloc failure.
@@ -1898,18 +1954,6 @@ done:
        return ret;
 }
 
-/*********************************************************************
- ********************************************************************/
-
-bool winbindd_internal_child(struct winbindd_child *child)
-{
-       if ((child == idmap_child()) || (child == locator_child())) {
-               return True;
-       }
-
-       return False;
-}
-
 #ifdef HAVE_KRB5_LOCATE_PLUGIN_H
 
 /*********************************************************************