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