r13316: Let the carnage begin....
[sfrench/samba-autobuild/.git] / source / nsswitch / winbindd_ads.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Winbind ADS backend functions
5
6    Copyright (C) Andrew Tridgell 2001
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003
8    Copyright (C) Gerald (Jerry) Carter 2004
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #ifdef HAVE_ADS
29
30 #undef DBGC_CLASS
31 #define DBGC_CLASS DBGC_WINBIND
32
33 /*
34   return our ads connections structure for a domain. We keep the connection
35   open to make things faster
36 */
37 static ADS_STRUCT *ads_cached_connection(struct winbindd_domain *domain)
38 {
39         ADS_STRUCT *ads;
40         ADS_STATUS status;
41
42         if (domain->private_data) {
43                 ads = (ADS_STRUCT *)domain->private_data;
44
45                 /* check for a valid structure */
46
47                 DEBUG(7, ("Current tickets expire at %d, time is now %d\n",
48                           (uint32) ads->auth.expire, (uint32) time(NULL)));
49                 if ( ads->config.realm && (ads->auth.expire > time(NULL))) {
50                         return ads;
51                 }
52                 else {
53                         /* we own this ADS_STRUCT so make sure it goes away */
54                         ads->is_mine = True;
55                         ads_destroy( &ads );
56                         ads_kdestroy("MEMORY:winbind_ccache");
57                         domain->private_data = NULL;
58                 }       
59         }
60
61         /* we don't want this to affect the users ccache */
62         setenv("KRB5CCNAME", "MEMORY:winbind_ccache", 1);
63
64         ads = ads_init(domain->alt_name, domain->name, NULL);
65         if (!ads) {
66                 DEBUG(1,("ads_init for domain %s failed\n", domain->name));
67                 return NULL;
68         }
69
70         /* the machine acct password might have change - fetch it every time */
71
72         SAFE_FREE(ads->auth.password);
73         SAFE_FREE(ads->auth.realm);
74
75         if ( IS_DC ) {
76                 DOM_SID sid;
77                 time_t last_set_time;
78
79                 if ( !secrets_fetch_trusted_domain_password( domain->name, &ads->auth.password, &sid, &last_set_time ) ) {
80                         ads_destroy( &ads );
81                         return NULL;
82                 }
83                 ads->auth.realm = SMB_STRDUP( ads->server.realm );
84                 strupper_m( ads->auth.realm );
85         }
86         else {
87                 struct winbindd_domain *our_domain = domain;
88
89                 ads->auth.password = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
90
91                 /* always give preference to the alt_name in our 
92                    primary domain if possible */
93
94                 if ( !domain->primary )
95                         our_domain = find_our_domain();
96
97                 if ( our_domain->alt_name[0] != '\0' ) {
98                         ads->auth.realm = SMB_STRDUP( our_domain->alt_name );
99                         strupper_m( ads->auth.realm );
100                 }
101                 else
102                         ads->auth.realm = SMB_STRDUP( lp_realm() );
103         }
104
105         ads->auth.renewable = 1;
106
107         status = ads_connect(ads);
108         if (!ADS_ERR_OK(status) || !ads->config.realm) {
109                 extern struct winbindd_methods msrpc_methods, cache_methods;
110                 DEBUG(1,("ads_connect for domain %s failed: %s\n", 
111                          domain->name, ads_errstr(status)));
112                 ads_destroy(&ads);
113
114                 /* if we get ECONNREFUSED then it might be a NT4
115                    server, fall back to MSRPC */
116                 if (status.error_type == ENUM_ADS_ERROR_SYSTEM &&
117                     status.err.rc == ECONNREFUSED) {
118                         DEBUG(1,("Trying MSRPC methods\n"));
119                         if (domain->methods == &cache_methods) {
120                                 domain->backend = &msrpc_methods;
121                         } else {
122                                 domain->methods = &msrpc_methods;
123                         }
124                 }
125                 return NULL;
126         }
127
128         if (use_nss_info("sfu") && (!ads_check_sfu_mapping(ads))) {
129                 DEBUG(0,("ads_cached_connection: failed to check sfu attributes\n"));
130                 return NULL;
131         }
132         
133         /* set the flag that says we don't own the memory even 
134            though we do so that ads_destroy() won't destroy the 
135            structure we pass back by reference */
136
137         ads->is_mine = False;
138
139         domain->private_data = (void *)ads;
140         return ads;
141 }
142
143
144 /* Query display info for a realm. This is the basic user list fn */
145 static NTSTATUS query_user_list(struct winbindd_domain *domain,
146                                TALLOC_CTX *mem_ctx,
147                                uint32 *num_entries, 
148                                WINBIND_USERINFO **info)
149 {
150         ADS_STRUCT *ads = NULL;
151         const char *attrs[] = {"userPrincipalName",
152                                "sAMAccountName",
153                                "name", "objectSid", "primaryGroupID", 
154                                "sAMAccountType", 
155                                ADS_ATTR_SFU_HOMEDIR_OID, 
156                                ADS_ATTR_SFU_SHELL_OID, 
157                                NULL};
158         int i, count;
159         ADS_STATUS rc;
160         void *res = NULL;
161         void *msg = NULL;
162         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
163
164         *num_entries = 0;
165
166         DEBUG(3,("ads: query_user_list\n"));
167
168         ads = ads_cached_connection(domain);
169         
170         if (!ads) {
171                 domain->last_status = NT_STATUS_SERVER_DISABLED;
172                 goto done;
173         }
174
175         rc = ads_search_retry(ads, &res, "(objectClass=user)", attrs);
176         if (!ADS_ERR_OK(rc) || !res) {
177                 DEBUG(1,("query_user_list ads_search: %s\n", ads_errstr(rc)));
178                 goto done;
179         }
180
181         count = ads_count_replies(ads, res);
182         if (count == 0) {
183                 DEBUG(1,("query_user_list: No users found\n"));
184                 goto done;
185         }
186
187         (*info) = TALLOC_ZERO_ARRAY(mem_ctx, WINBIND_USERINFO, count);
188         if (!*info) {
189                 status = NT_STATUS_NO_MEMORY;
190                 goto done;
191         }
192
193         i = 0;
194
195         for (msg = ads_first_entry(ads, res); msg; msg = ads_next_entry(ads, msg)) {
196                 char *name, *gecos;
197                 char *homedir = NULL;
198                 char *shell = NULL;
199                 uint32 group;
200                 uint32 atype;
201
202                 if (!ads_pull_uint32(ads, msg, "sAMAccountType", &atype) ||
203                     ads_atype_map(atype) != SID_NAME_USER) {
204                         DEBUG(1,("Not a user account? atype=0x%x\n", atype));
205                         continue;
206                 }
207
208                 name = ads_pull_username(ads, mem_ctx, msg);
209                 gecos = ads_pull_string(ads, mem_ctx, msg, "name");
210                 if (use_nss_info("sfu")) {
211                         homedir = ads_pull_string(ads, mem_ctx, msg, 
212                                                   ads->schema.sfu_homedir_attr);
213                         shell = ads_pull_string(ads, mem_ctx, msg, 
214                                                 ads->schema.sfu_shell_attr);
215                 }
216         
217                 if (!ads_pull_sid(ads, msg, "objectSid",
218                                   &(*info)[i].user_sid)) {
219                         DEBUG(1,("No sid for %s !?\n", name));
220                         continue;
221                 }
222                 if (!ads_pull_uint32(ads, msg, "primaryGroupID", &group)) {
223                         DEBUG(1,("No primary group for %s !?\n", name));
224                         continue;
225                 }
226
227                 (*info)[i].acct_name = name;
228                 (*info)[i].full_name = gecos;
229                 (*info)[i].homedir = homedir;
230                 (*info)[i].shell = shell;
231                 sid_compose(&(*info)[i].group_sid, &domain->sid, group);
232                 i++;
233         }
234
235         (*num_entries) = i;
236         status = NT_STATUS_OK;
237
238         DEBUG(3,("ads query_user_list gave %d entries\n", (*num_entries)));
239
240 done:
241         if (res) 
242                 ads_msgfree(ads, res);
243
244         return status;
245 }
246
247 /* list all domain groups */
248 static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
249                                 TALLOC_CTX *mem_ctx,
250                                 uint32 *num_entries, 
251                                 struct acct_info **info)
252 {
253         ADS_STRUCT *ads = NULL;
254         const char *attrs[] = {"userPrincipalName", "sAMAccountName",
255                                "name", "objectSid", NULL};
256         int i, count;
257         ADS_STATUS rc;
258         void *res = NULL;
259         void *msg = NULL;
260         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
261         const char *filter;
262         BOOL enum_dom_local_groups = False;
263
264         *num_entries = 0;
265
266         DEBUG(3,("ads: enum_dom_groups\n"));
267
268         /* only grab domain local groups for our domain */
269         if ( domain->native_mode && strequal(lp_realm(), domain->alt_name)  ) {
270                 enum_dom_local_groups = True;
271         }
272
273         /* Workaround ADS LDAP bug present in MS W2K3 SP0 and W2K SP4 w/o
274          * rollup-fixes:
275          *
276          * According to Section 5.1(4) of RFC 2251 if a value of a type is it's
277          * default value, it MUST be absent. In case of extensible matching the
278          * "dnattr" boolean defaults to FALSE and so it must be only be present
279          * when set to TRUE. 
280          *
281          * When it is set to FALSE and the OpenLDAP lib (correctly) encodes a
282          * filter using bitwise matching rule then the buggy AD fails to decode
283          * the extensible match. As a workaround set it to TRUE and thereby add
284          * the dnAttributes "dn" field to cope with those older AD versions.
285          * It should not harm and won't put any additional load on the AD since
286          * none of the dn components have a bitmask-attribute.
287          *
288          * Thanks to Ralf Haferkamp for input and testing - Guenther */
289
290         filter = talloc_asprintf(mem_ctx, "(&(objectCategory=group)(&(groupType:dn:%s:=%d)(!(groupType:dn:%s:=%d))))", 
291                                  ADS_LDAP_MATCHING_RULE_BIT_AND, GROUP_TYPE_SECURITY_ENABLED,
292                                  ADS_LDAP_MATCHING_RULE_BIT_AND, 
293                                  enum_dom_local_groups ? GROUP_TYPE_BUILTIN_LOCAL_GROUP : GROUP_TYPE_RESOURCE_GROUP);
294
295         if (filter == NULL) {
296                 status = NT_STATUS_NO_MEMORY;
297                 goto done;
298         }
299
300         ads = ads_cached_connection(domain);
301
302         if (!ads) {
303                 domain->last_status = NT_STATUS_SERVER_DISABLED;
304                 goto done;
305         }
306
307         rc = ads_search_retry(ads, &res, filter, attrs);
308         if (!ADS_ERR_OK(rc) || !res) {
309                 DEBUG(1,("enum_dom_groups ads_search: %s\n", ads_errstr(rc)));
310                 goto done;
311         }
312
313         count = ads_count_replies(ads, res);
314         if (count == 0) {
315                 DEBUG(1,("enum_dom_groups: No groups found\n"));
316                 goto done;
317         }
318
319         (*info) = TALLOC_ZERO_ARRAY(mem_ctx, struct acct_info, count);
320         if (!*info) {
321                 status = NT_STATUS_NO_MEMORY;
322                 goto done;
323         }
324
325         i = 0;
326         
327         for (msg = ads_first_entry(ads, res); msg; msg = ads_next_entry(ads, msg)) {
328                 char *name, *gecos;
329                 DOM_SID sid;
330                 uint32 rid;
331
332                 name = ads_pull_username(ads, mem_ctx, msg);
333                 gecos = ads_pull_string(ads, mem_ctx, msg, "name");
334                 if (!ads_pull_sid(ads, msg, "objectSid", &sid)) {
335                         DEBUG(1,("No sid for %s !?\n", name));
336                         continue;
337                 }
338
339                 if (!sid_peek_check_rid(&domain->sid, &sid, &rid)) {
340                         DEBUG(1,("No rid for %s !?\n", name));
341                         continue;
342                 }
343
344                 fstrcpy((*info)[i].acct_name, name);
345                 fstrcpy((*info)[i].acct_desc, gecos);
346                 (*info)[i].rid = rid;
347                 i++;
348         }
349
350         (*num_entries) = i;
351
352         status = NT_STATUS_OK;
353
354         DEBUG(3,("ads enum_dom_groups gave %d entries\n", (*num_entries)));
355
356 done:
357         if (res) 
358                 ads_msgfree(ads, res);
359
360         return status;
361 }
362
363 /* list all domain local groups */
364 static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
365                                 TALLOC_CTX *mem_ctx,
366                                 uint32 *num_entries, 
367                                 struct acct_info **info)
368 {
369         /*
370          * This is a stub function only as we returned the domain 
371          * local groups in enum_dom_groups() if the domain->native field
372          * was true.  This is a simple performance optimization when
373          * using LDAP.
374          *
375          * if we ever need to enumerate domain local groups separately, 
376          * then this the optimization in enum_dom_groups() will need 
377          * to be split out
378          */
379         *num_entries = 0;
380         
381         return NT_STATUS_OK;
382 }
383
384 /* convert a DN to a name, SID and name type 
385    this might become a major speed bottleneck if groups have
386    lots of users, in which case we could cache the results
387 */
388 static BOOL dn_lookup(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
389                       const char *dn,
390                       char **name, uint32 *name_type, DOM_SID *sid)
391 {
392         void *res = NULL;
393         const char *attrs[] = {"userPrincipalName", "sAMAccountName",
394                                "objectSid", "sAMAccountType", NULL};
395         ADS_STATUS rc;
396         uint32 atype;
397         DEBUG(3,("ads: dn_lookup\n"));
398
399         rc = ads_search_retry_dn(ads, &res, dn, attrs);
400
401         if (!ADS_ERR_OK(rc) || !res) {
402                 goto failed;
403         }
404
405         (*name) = ads_pull_username(ads, mem_ctx, res);
406
407         if (!ads_pull_uint32(ads, res, "sAMAccountType", &atype)) {
408                 goto failed;
409         }
410         (*name_type) = ads_atype_map(atype);
411
412         if (!ads_pull_sid(ads, res, "objectSid", sid)) {
413                 goto failed;
414         }
415
416         if (res) 
417                 ads_msgfree(ads, res);
418
419         return True;
420
421 failed:
422         if (res) 
423                 ads_msgfree(ads, res);
424
425         return False;
426 }
427
428 /* Lookup user information from a rid */
429 static NTSTATUS query_user(struct winbindd_domain *domain, 
430                            TALLOC_CTX *mem_ctx, 
431                            const DOM_SID *sid, 
432                            WINBIND_USERINFO *info)
433 {
434         ADS_STRUCT *ads = NULL;
435         const char *attrs[] = {"userPrincipalName", 
436                                "sAMAccountName",
437                                "name", 
438                                "primaryGroupID", 
439                                ADS_ATTR_SFU_HOMEDIR_OID, 
440                                ADS_ATTR_SFU_SHELL_OID, 
441                                NULL};
442         ADS_STATUS rc;
443         int count;
444         void *msg = NULL;
445         char *ldap_exp;
446         char *sidstr;
447         uint32 group_rid;
448         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
449
450         DEBUG(3,("ads: query_user\n"));
451
452         ads = ads_cached_connection(domain);
453         
454         if (!ads) {
455                 domain->last_status = NT_STATUS_SERVER_DISABLED;
456                 goto done;
457         }
458
459         sidstr = sid_binstring(sid);
460         asprintf(&ldap_exp, "(objectSid=%s)", sidstr);
461         rc = ads_search_retry(ads, &msg, ldap_exp, attrs);
462         free(ldap_exp);
463         free(sidstr);
464         if (!ADS_ERR_OK(rc) || !msg) {
465                 DEBUG(1,("query_user(sid=%s) ads_search: %s\n",
466                          sid_string_static(sid), ads_errstr(rc)));
467                 goto done;
468         }
469
470         count = ads_count_replies(ads, msg);
471         if (count != 1) {
472                 DEBUG(1,("query_user(sid=%s): Not found\n",
473                          sid_string_static(sid)));
474                 goto done;
475         }
476
477         info->acct_name = ads_pull_username(ads, mem_ctx, msg);
478         info->full_name = ads_pull_string(ads, mem_ctx, msg, "name");
479
480         if (use_nss_info("sfu")) {
481                 info->homedir = ads_pull_string(ads, mem_ctx, msg, 
482                                                 ads->schema.sfu_homedir_attr);
483                 info->shell = ads_pull_string(ads, mem_ctx, msg, 
484                                               ads->schema.sfu_shell_attr);
485         }
486
487         if (!ads_pull_uint32(ads, msg, "primaryGroupID", &group_rid)) {
488                 DEBUG(1,("No primary group for %s !?\n",
489                          sid_string_static(sid)));
490                 goto done;
491         }
492
493         sid_copy(&info->user_sid, sid);
494         sid_compose(&info->group_sid, &domain->sid, group_rid);
495
496         status = NT_STATUS_OK;
497
498         DEBUG(3,("ads query_user gave %s\n", info->acct_name));
499 done:
500         if (msg) 
501                 ads_msgfree(ads, msg);
502
503         return status;
504 }
505
506 /* Lookup groups a user is a member of - alternate method, for when
507    tokenGroups are not available. */
508 static NTSTATUS lookup_usergroups_alt(struct winbindd_domain *domain,
509                                       TALLOC_CTX *mem_ctx,
510                                       const char *user_dn, 
511                                       DOM_SID *primary_group,
512                                       size_t *p_num_groups, DOM_SID **user_sids)
513 {
514         ADS_STATUS rc;
515         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
516         int count;
517         void *res = NULL;
518         void *msg = NULL;
519         char *ldap_exp;
520         ADS_STRUCT *ads;
521         const char *group_attrs[] = {"objectSid", NULL};
522         char *escaped_dn;
523         size_t num_groups = 0;
524
525         DEBUG(3,("ads: lookup_usergroups_alt\n"));
526
527         ads = ads_cached_connection(domain);
528
529         if (!ads) {
530                 domain->last_status = NT_STATUS_SERVER_DISABLED;
531                 goto done;
532         }
533
534         if (!(escaped_dn = escape_ldap_string_alloc(user_dn))) {
535                 status = NT_STATUS_NO_MEMORY;
536                 goto done;
537         }
538
539         /* buggy server, no tokenGroups.  Instead lookup what groups this user
540            is a member of by DN search on member*/
541
542         if (!(ldap_exp = talloc_asprintf(mem_ctx, "(&(member=%s)(objectClass=group))", escaped_dn))) {
543                 DEBUG(1,("lookup_usergroups(dn=%s) asprintf failed!\n", user_dn));
544                 SAFE_FREE(escaped_dn);
545                 status = NT_STATUS_NO_MEMORY;
546                 goto done;
547         }
548
549         SAFE_FREE(escaped_dn);
550
551         rc = ads_search_retry(ads, &res, ldap_exp, group_attrs);
552         
553         if (!ADS_ERR_OK(rc) || !res) {
554                 DEBUG(1,("lookup_usergroups ads_search member=%s: %s\n", user_dn, ads_errstr(rc)));
555                 return ads_ntstatus(rc);
556         }
557         
558         count = ads_count_replies(ads, res);
559         
560         *user_sids = NULL;
561         num_groups = 0;
562
563         /* always add the primary group to the sid array */
564         add_sid_to_array(mem_ctx, primary_group, user_sids, &num_groups);
565
566         if (count > 0) {
567                 for (msg = ads_first_entry(ads, res); msg;
568                      msg = ads_next_entry(ads, msg)) {
569                         DOM_SID group_sid;
570                 
571                         if (!ads_pull_sid(ads, msg, "objectSid", &group_sid)) {
572                                 DEBUG(1,("No sid for this group ?!?\n"));
573                                 continue;
574                         }
575
576                         add_sid_to_array(mem_ctx, &group_sid, user_sids,
577                                          &num_groups);
578                 }
579
580         }
581
582         *p_num_groups = num_groups;
583         status = (user_sids != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
584
585         DEBUG(3,("ads lookup_usergroups (alt) for dn=%s\n", user_dn));
586 done:
587         if (res) 
588                 ads_msgfree(ads, res);
589
590         return status;
591 }
592
593 /* Lookup groups a user is a member of. */
594 static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
595                                   TALLOC_CTX *mem_ctx,
596                                   const DOM_SID *sid, 
597                                   uint32 *p_num_groups, DOM_SID **user_sids)
598 {
599         ADS_STRUCT *ads = NULL;
600         const char *attrs[] = {"tokenGroups", "primaryGroupID", NULL};
601         ADS_STATUS rc;
602         int count;
603         LDAPMessage *msg = NULL;
604         char *user_dn;
605         DOM_SID *sids;
606         int i;
607         DOM_SID primary_group;
608         uint32 primary_group_rid;
609         fstring sid_string;
610         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
611         size_t num_groups = 0;
612
613         DEBUG(3,("ads: lookup_usergroups\n"));
614         *p_num_groups = 0;
615
616         ads = ads_cached_connection(domain);
617         
618         if (!ads) {
619                 domain->last_status = NT_STATUS_SERVER_DISABLED;
620                 status = NT_STATUS_SERVER_DISABLED;
621                 goto done;
622         }
623
624         rc = ads_sid_to_dn(ads, mem_ctx, sid, &user_dn);
625         if (!ADS_ERR_OK(rc)) {
626                 status = ads_ntstatus(rc);
627                 goto done;
628         }
629
630         rc = ads_search_retry_dn(ads, (void**)(void *)&msg, user_dn, attrs);
631         if (!ADS_ERR_OK(rc)) {
632                 status = ads_ntstatus(rc);
633                 DEBUG(1,("lookup_usergroups(sid=%s) ads_search tokenGroups: %s\n", 
634                          sid_to_string(sid_string, sid), ads_errstr(rc)));
635                 goto done;
636         }
637         
638         if (!msg) {
639                 DEBUG(1,("lookup_usergroups(sid=%s) ads_search tokenGroups: NULL msg\n", 
640                          sid_to_string(sid_string, sid)));
641                 status = NT_STATUS_UNSUCCESSFUL;
642                 goto done;
643         }
644
645         if (!ads_pull_uint32(ads, msg, "primaryGroupID", &primary_group_rid)) {
646                 DEBUG(1,("%s: No primary group for sid=%s !?\n", 
647                          domain->name, sid_to_string(sid_string, sid)));
648                 goto done;
649         }
650
651         sid_copy(&primary_group, &domain->sid);
652         sid_append_rid(&primary_group, primary_group_rid);
653
654         count = ads_pull_sids(ads, mem_ctx, msg, "tokenGroups", &sids);
655
656         if (msg) 
657                 ads_msgfree(ads, msg);
658
659         /* there must always be at least one group in the token, 
660            unless we are talking to a buggy Win2k server */
661         if (count == 0) {
662                 status = lookup_usergroups_alt(domain, mem_ctx, user_dn, 
663                                              &primary_group,
664                                              &num_groups, user_sids);
665                 *p_num_groups = (uint32)num_groups;
666                 return status;
667         }
668
669         *user_sids = NULL;
670         num_groups = 0;
671
672         add_sid_to_array(mem_ctx, &primary_group, user_sids, &num_groups);
673         
674         for (i=0;i<count;i++) {
675
676                 /* ignore Builtin groups from ADS - Guenther */
677                 if (sid_check_is_in_builtin(&sids[i])) {
678                         continue;
679                 }
680                                
681                 add_sid_to_array_unique(mem_ctx, &sids[i],
682                                         user_sids, &num_groups);
683         }
684
685         *p_num_groups = (uint32)num_groups;
686         status = (user_sids != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
687
688         DEBUG(3,("ads lookup_usergroups for sid=%s\n",
689                  sid_to_string(sid_string, sid)));
690 done:
691         return status;
692 }
693
694 /*
695   find the members of a group, given a group rid and domain
696  */
697 static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
698                                 TALLOC_CTX *mem_ctx,
699                                 const DOM_SID *group_sid, uint32 *num_names, 
700                                 DOM_SID **sid_mem, char ***names, 
701                                 uint32 **name_types)
702 {
703         ADS_STATUS rc;
704         int count;
705         void *res=NULL;
706         ADS_STRUCT *ads = NULL;
707         char *ldap_exp;
708         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
709         char *sidstr;
710         char **members;
711         int i;
712         size_t num_members;
713         fstring sid_string;
714         BOOL more_values;
715         const char **attrs;
716         uint32 first_usn;
717         uint32 current_usn;
718         int num_retries = 0;
719
720         DEBUG(10,("ads: lookup_groupmem %s sid=%s\n", domain->name, 
721                   sid_string_static(group_sid)));
722
723         *num_names = 0;
724
725         ads = ads_cached_connection(domain);
726         
727         if (!ads) {
728                 domain->last_status = NT_STATUS_SERVER_DISABLED;
729                 goto done;
730         }
731
732         sidstr = sid_binstring(group_sid);
733
734         /* search for all members of the group */
735         if (!(ldap_exp = talloc_asprintf(mem_ctx, "(objectSid=%s)",sidstr))) {
736                 SAFE_FREE(sidstr);
737                 DEBUG(1, ("ads: lookup_groupmem: tallloc_asprintf for ldap_exp failed!\n"));
738                 status = NT_STATUS_NO_MEMORY;
739                 goto done;
740         }
741         SAFE_FREE(sidstr);
742
743         members = NULL;
744         num_members = 0;
745
746         attrs = TALLOC_ARRAY(mem_ctx, const char *, 3);
747         attrs[1] = talloc_strdup(mem_ctx, "usnChanged");
748         attrs[2] = NULL;
749                 
750         do {
751                 if (num_members == 0) 
752                         attrs[0] = talloc_strdup(mem_ctx, "member");
753
754                 DEBUG(10, ("Searching for attrs[0] = %s, attrs[1] = %s\n", attrs[0], attrs[1]));
755
756                 rc = ads_search_retry(ads, &res, ldap_exp, attrs);
757
758                 if (!ADS_ERR_OK(rc) || !res) {
759                         DEBUG(1,("ads: lookup_groupmem ads_search: %s\n",
760                                  ads_errstr(rc)));
761                         status = ads_ntstatus(rc);
762                         goto done;
763                 }
764
765                 count = ads_count_replies(ads, res);
766                 if (count == 0)
767                         break;
768
769                 if (num_members == 0) {
770                         if (!ads_pull_uint32(ads, res, "usnChanged", &first_usn)) {
771                                 DEBUG(1, ("ads: lookup_groupmem could not pull usnChanged!\n"));
772                                 goto done;
773                         }
774                 }
775
776                 if (!ads_pull_uint32(ads, res, "usnChanged", &current_usn)) {
777                         DEBUG(1, ("ads: lookup_groupmem could not pull usnChanged!\n"));
778                         goto done;
779                 }
780
781                 if (first_usn != current_usn) {
782                         DEBUG(5, ("ads: lookup_groupmem USN on this record changed"
783                                   " - restarting search\n"));
784                         if (num_retries < 5) {
785                                 num_retries++;
786                                 num_members = 0;
787                                 continue;
788                         } else {
789                                 DEBUG(5, ("ads: lookup_groupmem USN on this record changed"
790                                           " - restarted search too many times, aborting!\n"));
791                                 status = NT_STATUS_UNSUCCESSFUL;
792                                 goto done;
793                         }
794                 }
795
796                 members = ads_pull_strings_range(ads, mem_ctx, res,
797                                                  "member",
798                                                  members,
799                                                  &attrs[0],
800                                                  &num_members,
801                                                  &more_values);
802
803                 if ((members == NULL) || (num_members == 0))
804                         break;
805
806         } while (more_values);
807                 
808         /* now we need to turn a list of members into rids, names and name types 
809            the problem is that the members are in the form of distinguised names
810         */
811
812         (*sid_mem) = TALLOC_ZERO_ARRAY(mem_ctx, DOM_SID, num_members);
813         (*name_types) = TALLOC_ZERO_ARRAY(mem_ctx, uint32, num_members);
814         (*names) = TALLOC_ZERO_ARRAY(mem_ctx, char *, num_members);
815
816         for (i=0;i<num_members;i++) {
817                 uint32 name_type;
818                 char *name;
819                 DOM_SID sid;
820
821                 if (dn_lookup(ads, mem_ctx, members[i], &name, &name_type, &sid)) {
822                     (*names)[*num_names] = name;
823                     (*name_types)[*num_names] = name_type;
824                     sid_copy(&(*sid_mem)[*num_names], &sid);
825                     (*num_names)++;
826                 }
827         }       
828
829         status = NT_STATUS_OK;
830         DEBUG(3,("ads lookup_groupmem for sid=%s\n", sid_to_string(sid_string, group_sid)));
831 done:
832
833         if (res) 
834                 ads_msgfree(ads, res);
835
836         return status;
837 }
838
839 /* find the sequence number for a domain */
840 static NTSTATUS sequence_number(struct winbindd_domain *domain, uint32 *seq)
841 {
842         ADS_STRUCT *ads = NULL;
843         ADS_STATUS rc;
844
845         DEBUG(3,("ads: fetch sequence_number for %s\n", domain->name));
846
847         *seq = DOM_SEQUENCE_NONE;
848
849         ads = ads_cached_connection(domain);
850         
851         if (!ads) {
852                 domain->last_status = NT_STATUS_SERVER_DISABLED;
853                 return NT_STATUS_UNSUCCESSFUL;
854         }
855
856         rc = ads_USN(ads, seq);
857         
858         if (!ADS_ERR_OK(rc)) {
859         
860                 /* its a dead connection ; don't destroy it 
861                    through since ads_USN() has already done 
862                    that indirectly */
863                    
864                 domain->private_data = NULL;
865         }
866         return ads_ntstatus(rc);
867 }
868
869 /* get a list of trusted domains */
870 static NTSTATUS trusted_domains(struct winbindd_domain *domain,
871                                 TALLOC_CTX *mem_ctx,
872                                 uint32 *num_domains,
873                                 char ***names,
874                                 char ***alt_names,
875                                 DOM_SID **dom_sids)
876 {
877         NTSTATUS                result = NT_STATUS_UNSUCCESSFUL;
878         struct ds_domain_trust  *domains = NULL;
879         int                     count = 0;
880         int                     i;
881         uint32                  flags = DS_DOMAIN_DIRECT_OUTBOUND;
882         struct rpc_pipe_client *cli;
883
884         DEBUG(3,("ads: trusted_domains\n"));
885
886         *num_domains = 0;
887         *alt_names   = NULL;
888         *names       = NULL;
889         *dom_sids    = NULL;
890
891         result = cm_connect_netlogon(domain, &cli);
892
893         if (!NT_STATUS_IS_OK(result)) {
894                 DEBUG(5, ("trusted_domains: Could not open a connection to %s "
895                           "for PIPE_NETLOGON (%s)\n", 
896                           domain->name, nt_errstr(result)));
897                 return NT_STATUS_UNSUCCESSFUL;
898         }
899         
900         if ( NT_STATUS_IS_OK(result) ) {
901                 result = rpccli_ds_enum_domain_trusts(cli, mem_ctx,
902                                                       cli->cli->desthost, 
903                                                       flags, &domains,
904                                                       (unsigned int *)&count);
905         }
906         
907         if ( NT_STATUS_IS_OK(result) && count) {
908         
909                 /* Allocate memory for trusted domain names and sids */
910
911                 if ( !(*names = TALLOC_ARRAY(mem_ctx, char *, count)) ) {
912                         DEBUG(0, ("trusted_domains: out of memory\n"));
913                         return NT_STATUS_NO_MEMORY;
914                 }
915
916                 if ( !(*alt_names = TALLOC_ARRAY(mem_ctx, char *, count)) ) {
917                         DEBUG(0, ("trusted_domains: out of memory\n"));
918                         return NT_STATUS_NO_MEMORY;
919                 }
920
921                 if ( !(*dom_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, count)) ) {
922                         DEBUG(0, ("trusted_domains: out of memory\n"));
923                         return NT_STATUS_NO_MEMORY;
924                 }
925
926                 /* Copy across names and sids */
927
928                 for (i = 0; i < count; i++) {
929                         (*names)[i] = domains[i].netbios_domain;
930                         (*alt_names)[i] = domains[i].dns_domain;
931
932                         sid_copy(&(*dom_sids)[i], &domains[i].sid);
933                 }
934
935                 *num_domains = count;   
936         }
937
938         return result;
939 }
940
941 /* the ADS backend methods are exposed via this structure */
942 struct winbindd_methods ads_methods = {
943         True,
944         query_user_list,
945         enum_dom_groups,
946         enum_local_groups,
947         msrpc_name_to_sid,
948         msrpc_sid_to_name,
949         query_user,
950         lookup_usergroups,
951         msrpc_lookup_useraliases,
952         lookup_groupmem,
953         sequence_number,
954         msrpc_lockout_policy,
955         msrpc_password_policy,
956         trusted_domains,
957 };
958
959 #endif