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