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