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