s3:idmap_ad: untangle two assignments from checks
[metze/samba/wip.git] / source3 / winbindd / idmap_ad.c
1 /*
2  *  idmap_ad: map between Active Directory and RFC 2307 or "Services for Unix" (SFU) Accounts
3  *
4  * Unix SMB/CIFS implementation.
5  *
6  * Winbind ADS backend functions
7  *
8  * Copyright (C) Andrew Tridgell 2001
9  * Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003
10  * Copyright (C) Gerald (Jerry) Carter 2004-2007
11  * Copyright (C) Luke Howard 2001-2004
12  * Copyright (C) Michael Adam 2008
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, see <http://www.gnu.org/licenses/>.
26  */
27
28 #include "includes.h"
29 #include "winbindd.h"
30
31 #undef DBGC_CLASS
32 #define DBGC_CLASS DBGC_IDMAP
33
34 #define WINBIND_CCACHE_NAME "MEMORY:winbind_ccache"
35
36 #define IDMAP_AD_MAX_IDS 30
37 #define CHECK_ALLOC_DONE(mem) do { \
38      if (!mem) { \
39            DEBUG(0, ("Out of memory!\n")); \
40            ret = NT_STATUS_NO_MEMORY; \
41            goto done; \
42       } \
43 } while (0)
44
45 struct idmap_ad_context {
46         ADS_STRUCT *ads;
47         struct posix_schema *ad_schema;
48         enum wb_posix_mapping ad_map_type; /* WB_POSIX_MAP_UNKNOWN */
49 };
50
51 NTSTATUS init_module(void);
52
53 /************************************************************************
54  ***********************************************************************/
55
56 static ADS_STATUS ad_idmap_cached_connection_internal(struct idmap_domain *dom)
57 {
58         ADS_STRUCT *ads;
59         ADS_STATUS status;
60         bool local = False;
61         fstring dc_name;
62         struct sockaddr_storage dc_ip;
63         struct idmap_ad_context *ctx;
64         char *ldap_server = NULL;
65         char *realm = NULL;
66         struct winbindd_domain *wb_dom;
67
68         DEBUG(10, ("ad_idmap_cached_connection: called for domain '%s'\n",
69                    dom->name));
70
71         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
72
73         if (ctx->ads != NULL) {
74
75                 time_t expire;
76                 time_t now = time(NULL);
77
78                 ads = ctx->ads;
79
80                 expire = MIN(ads->auth.tgt_expire, ads->auth.tgs_expire);
81
82                 /* check for a valid structure */
83                 DEBUG(7, ("Current tickets expire in %d seconds (at %d, time is now %d)\n",
84                           (uint32)expire-(uint32)now, (uint32) expire, (uint32) now));
85
86                 if ( ads->config.realm && (expire > time(NULL))) {
87                         return ADS_SUCCESS;
88                 } else {
89                         /* we own this ADS_STRUCT so make sure it goes away */
90                         DEBUG(7,("Deleting expired krb5 credential cache\n"));
91                         ads->is_mine = True;
92                         ads_destroy( &ads );
93                         ads_kdestroy(WINBIND_CCACHE_NAME);
94                         ctx->ads = NULL;
95                         TALLOC_FREE( ctx->ad_schema );
96                 }
97         }
98
99         if (!local) {
100                 /* we don't want this to affect the users ccache */
101                 setenv("KRB5CCNAME", WINBIND_CCACHE_NAME, 1);
102         }
103
104         /*
105          * At this point we only have the NetBIOS domain name.
106          * Check if we can get server nam and realm from SAF cache
107          * and the domain list.
108          */
109         ldap_server = saf_fetch(dom->name);
110         DEBUG(10, ("ldap_server from saf cache: '%s'\n", ldap_server?ldap_server:""));
111
112         wb_dom = find_domain_from_name_noinit(dom->name);
113         if (wb_dom == NULL) {
114                 DEBUG(10, ("find_domain_from_name_noinit did not find domain '%s'\n",
115                            dom->name));
116                 realm = NULL;
117         } else {
118                 DEBUG(10, ("find_domain_from_name_noinit found realm '%s' for "
119                           " domain '%s'\n", wb_dom->alt_name, dom->name));
120                 realm = wb_dom->alt_name;
121         }
122
123         if ( (ads = ads_init(realm, dom->name, ldap_server)) == NULL ) {
124                 DEBUG(1,("ads_init failed\n"));
125                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
126         }
127
128         /* the machine acct password might have change - fetch it every time */
129         SAFE_FREE(ads->auth.password);
130         ads->auth.password = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
131
132         SAFE_FREE(ads->auth.realm);
133         ads->auth.realm = SMB_STRDUP(lp_realm());
134
135         /* setup server affinity */
136
137         get_dc_name(dom->name, realm, dc_name, &dc_ip );
138         
139         status = ads_connect(ads);
140         if (!ADS_ERR_OK(status)) {
141                 DEBUG(1, ("ad_idmap_init: failed to connect to AD\n"));
142                 ads_destroy(&ads);
143                 return status;
144         }
145
146         ads->is_mine = False;
147
148         ctx->ads = ads;
149
150         return ADS_SUCCESS;
151 }
152
153 /************************************************************************
154  ***********************************************************************/
155
156 static ADS_STATUS ad_idmap_cached_connection(struct idmap_domain *dom)
157 {
158         ADS_STATUS status;
159         struct idmap_ad_context * ctx;
160
161         status = ad_idmap_cached_connection_internal(dom);
162         if (!ADS_ERR_OK(status)) {
163                 return status;
164         }
165
166         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
167
168         /* if we have a valid ADS_STRUCT and the schema model is
169            defined, then we can return here. */
170
171         if ( ctx->ad_schema ) {
172                 return ADS_SUCCESS;
173         }
174
175         /* Otherwise, set the schema model */
176
177         if ( (ctx->ad_map_type ==  WB_POSIX_MAP_SFU) ||
178              (ctx->ad_map_type ==  WB_POSIX_MAP_SFU20) ||
179              (ctx->ad_map_type ==  WB_POSIX_MAP_RFC2307) )
180         {
181                 status = ads_check_posix_schema_mapping(NULL, ctx->ads, ctx->ad_map_type, &ctx->ad_schema);
182                 if ( !ADS_ERR_OK(status) ) {
183                         DEBUG(2,("ad_idmap_cached_connection: Failed to obtain schema details!\n"));
184                 }
185         }
186         
187         return status;
188 }
189
190 /************************************************************************
191  ***********************************************************************/
192
193 static NTSTATUS idmap_ad_initialize(struct idmap_domain *dom,
194                                     const char *params)
195 {
196         struct idmap_ad_context *ctx;
197         char *config_option;
198         const char *schema_mode = NULL; 
199
200         ctx = TALLOC_ZERO_P(dom, struct idmap_ad_context);
201         if (ctx == NULL) {
202                 DEBUG(0, ("Out of memory!\n"));
203                 return NT_STATUS_NO_MEMORY;
204         }
205
206         config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
207         if (config_option == NULL) {
208                 DEBUG(0, ("Out of memory!\n"));
209                 talloc_free(ctx);
210                 return NT_STATUS_NO_MEMORY;
211         }
212
213         /* default map type */
214         ctx->ad_map_type = WB_POSIX_MAP_RFC2307;
215
216         /* schema mode */
217         schema_mode = lp_parm_const_string(-1, config_option, "schema_mode", NULL);
218         if ( schema_mode && schema_mode[0] ) {
219                 if ( strequal(schema_mode, "sfu") )
220                         ctx->ad_map_type = WB_POSIX_MAP_SFU;
221                 else if ( strequal(schema_mode, "sfu20" ) )
222                         ctx->ad_map_type = WB_POSIX_MAP_SFU20;
223                 else if ( strequal(schema_mode, "rfc2307" ) )
224                         ctx->ad_map_type = WB_POSIX_MAP_RFC2307;
225                 else
226                         DEBUG(0,("idmap_ad_initialize: Unknown schema_mode (%s)\n",
227                                  schema_mode));
228         }
229
230         dom->private_data = ctx;
231
232         talloc_free(config_option);
233
234         return NT_STATUS_OK;
235 }
236
237 /************************************************************************
238  Search up to IDMAP_AD_MAX_IDS entries in maps for a match.
239  ***********************************************************************/
240
241 static struct id_map *find_map_by_id(struct id_map **maps, enum id_type type, uint32_t id)
242 {
243         int i;
244
245         for (i = 0; maps[i] && i<IDMAP_AD_MAX_IDS; i++) {
246                 if ((maps[i]->xid.type == type) && (maps[i]->xid.id == id)) {
247                         return maps[i];
248                 }
249         }
250
251         return NULL;    
252 }
253
254 /************************************************************************
255  Search up to IDMAP_AD_MAX_IDS entries in maps for a match
256  ***********************************************************************/
257
258 static struct id_map *find_map_by_sid(struct id_map **maps, DOM_SID *sid)
259 {
260         int i;
261
262         for (i = 0; maps[i] && i<IDMAP_AD_MAX_IDS; i++) {
263                 if (sid_equal(maps[i]->sid, sid)) {
264                         return maps[i];
265                 }
266         }
267
268         return NULL;    
269 }
270
271 /************************************************************************
272  ***********************************************************************/
273
274 static NTSTATUS idmap_ad_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
275 {
276         NTSTATUS ret;
277         TALLOC_CTX *memctx;
278         struct idmap_ad_context *ctx;
279         ADS_STATUS rc;
280         const char *attrs[] = { "sAMAccountType", 
281                                 "objectSid",
282                                 NULL, /* uidnumber */
283                                 NULL, /* gidnumber */
284                                 NULL };
285         LDAPMessage *res = NULL;
286         LDAPMessage *entry = NULL;
287         char *filter = NULL;
288         int idx = 0;
289         int bidx = 0;
290         int count;
291         int i;
292         char *u_filter = NULL;
293         char *g_filter = NULL;
294
295         /* initialize the status to avoid suprise */
296         for (i = 0; ids[i]; i++) {
297                 ids[i]->status = ID_UNKNOWN;
298         }
299         
300         /* Only do query if we are online */
301         if (idmap_is_offline()) {
302                 return NT_STATUS_FILE_IS_OFFLINE;
303         }
304
305         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
306
307         if ( (memctx = talloc_new(ctx)) == NULL ) {
308                 DEBUG(0, ("Out of memory!\n"));
309                 return NT_STATUS_NO_MEMORY;
310         }
311
312         rc = ad_idmap_cached_connection(dom);
313         if (!ADS_ERR_OK(rc)) {
314                 DEBUG(1, ("ADS uninitialized: %s\n", ads_errstr(rc)));
315                 ret = NT_STATUS_UNSUCCESSFUL;
316                 /* ret = ads_ntstatus(rc); */
317                 goto done;
318         }
319
320         attrs[2] = ctx->ad_schema->posix_uidnumber_attr;
321         attrs[3] = ctx->ad_schema->posix_gidnumber_attr;
322
323 again:
324         bidx = idx;
325         for (i = 0; (i < IDMAP_AD_MAX_IDS) && ids[idx]; i++, idx++) {
326                 switch (ids[idx]->xid.type) {
327                 case ID_TYPE_UID:     
328                         if ( ! u_filter) {
329                                 u_filter = talloc_asprintf(memctx, "(&(|"
330                                                            "(sAMAccountType=%d)"
331                                                            "(sAMAccountType=%d)"
332                                                            "(sAMAccountType=%d))(|",
333                                                            ATYPE_NORMAL_ACCOUNT,
334                                                            ATYPE_WORKSTATION_TRUST,
335                                                            ATYPE_INTERDOMAIN_TRUST);
336                         }
337                         u_filter = talloc_asprintf_append_buffer(u_filter, "(%s=%lu)",
338                                                           ctx->ad_schema->posix_uidnumber_attr,
339                                                           (unsigned long)ids[idx]->xid.id);
340                         CHECK_ALLOC_DONE(u_filter);
341                         break;
342                                 
343                 case ID_TYPE_GID:
344                         if ( ! g_filter) {
345                                 g_filter = talloc_asprintf(memctx, "(&(|"
346                                                            "(sAMAccountType=%d)"
347                                                            "(sAMAccountType=%d))(|",
348                                                            ATYPE_SECURITY_GLOBAL_GROUP,
349                                                            ATYPE_SECURITY_LOCAL_GROUP);
350                         }
351                         g_filter = talloc_asprintf_append_buffer(g_filter, "(%s=%lu)",
352                                                           ctx->ad_schema->posix_gidnumber_attr,
353                                                           (unsigned long)ids[idx]->xid.id);
354                         CHECK_ALLOC_DONE(g_filter);
355                         break;
356
357                 default:
358                         DEBUG(3, ("Error: mapping requested but Unknown ID type\n"));
359                         ids[idx]->status = ID_UNKNOWN;
360                         continue;
361                 }
362         }
363         filter = talloc_asprintf(memctx, "(|");
364         CHECK_ALLOC_DONE(filter);
365         if ( u_filter) {
366                 filter = talloc_asprintf_append_buffer(filter, "%s))", u_filter);
367                 CHECK_ALLOC_DONE(filter);
368                         TALLOC_FREE(u_filter);
369         }
370         if ( g_filter) {
371                 filter = talloc_asprintf_append_buffer(filter, "%s))", g_filter);
372                 CHECK_ALLOC_DONE(filter);
373                 TALLOC_FREE(g_filter);
374         }
375         filter = talloc_asprintf_append_buffer(filter, ")");
376         CHECK_ALLOC_DONE(filter);
377
378         rc = ads_search_retry(ctx->ads, &res, filter, attrs);
379         if (!ADS_ERR_OK(rc)) {
380                 DEBUG(1, ("ERROR: ads search returned: %s\n", ads_errstr(rc)));
381                 ret = NT_STATUS_UNSUCCESSFUL;
382                 goto done;
383         }
384
385         if ( (count = ads_count_replies(ctx->ads, res)) == 0 ) {
386                 DEBUG(10, ("No IDs found\n"));
387         }
388
389         entry = res;
390         for (i = 0; (i < count) && entry; i++) {
391                 DOM_SID sid;
392                 enum id_type type;
393                 struct id_map *map;
394                 uint32_t id;
395                 uint32_t atype;
396
397                 if (i == 0) { /* first entry */
398                         entry = ads_first_entry(ctx->ads, entry);
399                 } else { /* following ones */
400                         entry = ads_next_entry(ctx->ads, entry);
401                 }
402
403                 if ( !entry ) {
404                         DEBUG(2, ("ERROR: Unable to fetch ldap entries from results\n"));
405                         break;
406                 }
407
408                 /* first check if the SID is present */
409                 if (!ads_pull_sid(ctx->ads, entry, "objectSid", &sid)) {
410                         DEBUG(2, ("Could not retrieve SID from entry\n"));
411                         continue;
412                 }
413
414                 /* get type */
415                 if (!ads_pull_uint32(ctx->ads, entry, "sAMAccountType", &atype)) {
416                         DEBUG(1, ("could not get SAM account type\n"));
417                         continue;
418                 }
419
420                 switch (atype & 0xF0000000) {
421                 case ATYPE_SECURITY_GLOBAL_GROUP:
422                 case ATYPE_SECURITY_LOCAL_GROUP:
423                         type = ID_TYPE_GID;
424                         break;
425                 case ATYPE_NORMAL_ACCOUNT:
426                 case ATYPE_WORKSTATION_TRUST:
427                 case ATYPE_INTERDOMAIN_TRUST:
428                         type = ID_TYPE_UID;
429                         break;
430                 default:
431                         DEBUG(1, ("unrecognized SAM account type %08x\n", atype));
432                         continue;
433                 }
434
435                 if (!ads_pull_uint32(ctx->ads, entry, (type==ID_TYPE_UID) ?
436                                                  ctx->ad_schema->posix_uidnumber_attr :
437                                                  ctx->ad_schema->posix_gidnumber_attr,
438                                      &id)) 
439                 {
440                         DEBUG(1, ("Could not get unix ID\n"));
441                         continue;
442                 }
443
444                 if (!idmap_unix_id_is_in_range(id, dom)) {
445                         DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
446                                 id, dom->low_id, dom->high_id));
447                         continue;
448                 }
449
450                 map = find_map_by_id(&ids[bidx], type, id);
451                 if (!map) {
452                         DEBUG(2, ("WARNING: couldn't match result with requested ID\n"));
453                         continue;
454                 }
455
456                 sid_copy(map->sid, &sid);
457
458                 /* mapped */
459                 map->status = ID_MAPPED;
460
461                 DEBUG(10, ("Mapped %s -> %lu (%d)\n", sid_string_dbg(map->sid),
462                            (unsigned long)map->xid.id,
463                            map->xid.type));
464         }
465
466         if (res) {
467                 ads_msgfree(ctx->ads, res);
468         }
469
470         if (ids[idx]) { /* still some values to map */
471                 goto again;
472         }
473
474         ret = NT_STATUS_OK;
475
476         /* mark all unknown/expired ones as unmapped */
477         for (i = 0; ids[i]; i++) {
478                 if (ids[i]->status != ID_MAPPED) 
479                         ids[i]->status = ID_UNMAPPED;
480         }
481
482 done:
483         talloc_free(memctx);
484         return ret;
485 }
486
487 /************************************************************************
488  ***********************************************************************/
489
490 static NTSTATUS idmap_ad_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
491 {
492         NTSTATUS ret;
493         TALLOC_CTX *memctx;
494         struct idmap_ad_context *ctx;
495         ADS_STATUS rc;
496         const char *attrs[] = { "sAMAccountType", 
497                                 "objectSid",
498                                 NULL, /* attr_uidnumber */
499                                 NULL, /* attr_gidnumber */
500                                 NULL };
501         LDAPMessage *res = NULL;
502         LDAPMessage *entry = NULL;
503         char *filter = NULL;
504         int idx = 0;
505         int bidx = 0;
506         int count;
507         int i;
508         char *sidstr;
509
510         /* initialize the status to avoid suprise */
511         for (i = 0; ids[i]; i++) {
512                 ids[i]->status = ID_UNKNOWN;
513         }
514
515         /* Only do query if we are online */
516         if (idmap_is_offline()) {
517                 return NT_STATUS_FILE_IS_OFFLINE;
518         }
519
520         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);      
521
522         if ( (memctx = talloc_new(ctx)) == NULL ) {             
523                 DEBUG(0, ("Out of memory!\n"));
524                 return NT_STATUS_NO_MEMORY;
525         }
526
527         rc = ad_idmap_cached_connection(dom);
528         if (!ADS_ERR_OK(rc)) {
529                 DEBUG(1, ("ADS uninitialized: %s\n", ads_errstr(rc)));
530                 ret = NT_STATUS_UNSUCCESSFUL;
531                 /* ret = ads_ntstatus(rc); */
532                 goto done;
533         }
534
535         if (ctx->ad_schema == NULL) {
536                 DEBUG(0, ("haven't got ctx->ad_schema ! \n"));
537                 ret = NT_STATUS_UNSUCCESSFUL;
538                 goto done;
539         }
540
541         attrs[2] = ctx->ad_schema->posix_uidnumber_attr;
542         attrs[3] = ctx->ad_schema->posix_gidnumber_attr;
543
544 again:
545         filter = talloc_asprintf(memctx, "(&(|"
546                                  "(sAMAccountType=%d)(sAMAccountType=%d)(sAMAccountType=%d)" /* user account types */
547                                  "(sAMAccountType=%d)(sAMAccountType=%d)" /* group account types */
548                                  ")(|",
549                                  ATYPE_NORMAL_ACCOUNT, ATYPE_WORKSTATION_TRUST, ATYPE_INTERDOMAIN_TRUST,
550                                  ATYPE_SECURITY_GLOBAL_GROUP, ATYPE_SECURITY_LOCAL_GROUP);
551                 
552         CHECK_ALLOC_DONE(filter);
553
554         bidx = idx;
555         for (i = 0; (i < IDMAP_AD_MAX_IDS) && ids[idx]; i++, idx++) {
556
557                 ids[idx]->status = ID_UNKNOWN;
558
559                 sidstr = sid_binstring(ids[idx]->sid);
560                 filter = talloc_asprintf_append_buffer(filter, "(objectSid=%s)", sidstr);
561                         
562                 free(sidstr);
563                 CHECK_ALLOC_DONE(filter);
564         }
565         filter = talloc_asprintf_append_buffer(filter, "))");
566         CHECK_ALLOC_DONE(filter);
567         DEBUG(10, ("Filter: [%s]\n", filter));
568
569         rc = ads_search_retry(ctx->ads, &res, filter, attrs);
570         if (!ADS_ERR_OK(rc)) {
571                 DEBUG(1, ("ERROR: ads search returned: %s\n", ads_errstr(rc)));
572                 ret = NT_STATUS_UNSUCCESSFUL;
573                 goto done;
574         }
575
576         if ( (count = ads_count_replies(ctx->ads, res)) == 0 ) {
577                 DEBUG(10, ("No IDs found\n"));
578         }
579
580         entry = res;    
581         for (i = 0; (i < count) && entry; i++) {
582                 DOM_SID sid;
583                 enum id_type type;
584                 struct id_map *map;
585                 uint32_t id;
586                 uint32_t atype;
587
588                 if (i == 0) { /* first entry */
589                         entry = ads_first_entry(ctx->ads, entry);
590                 } else { /* following ones */
591                         entry = ads_next_entry(ctx->ads, entry);
592                 }
593
594                 if ( !entry ) {
595                         DEBUG(2, ("ERROR: Unable to fetch ldap entries from results\n"));
596                         break;
597                 }
598
599                 /* first check if the SID is present */
600                 if (!ads_pull_sid(ctx->ads, entry, "objectSid", &sid)) {
601                         DEBUG(2, ("Could not retrieve SID from entry\n"));
602                         continue;
603                 }
604
605                 map = find_map_by_sid(&ids[bidx], &sid);
606                 if (!map) {
607                         DEBUG(2, ("WARNING: couldn't match result with requested SID\n"));
608                         continue;
609                 }
610
611                 /* get type */
612                 if (!ads_pull_uint32(ctx->ads, entry, "sAMAccountType", &atype)) {
613                         DEBUG(1, ("could not get SAM account type\n"));
614                         continue;
615                 }
616
617                 switch (atype & 0xF0000000) {
618                 case ATYPE_SECURITY_GLOBAL_GROUP:
619                 case ATYPE_SECURITY_LOCAL_GROUP:
620                         type = ID_TYPE_GID;
621                         break;
622                 case ATYPE_NORMAL_ACCOUNT:
623                 case ATYPE_WORKSTATION_TRUST:
624                 case ATYPE_INTERDOMAIN_TRUST:
625                         type = ID_TYPE_UID;
626                         break;
627                 default:
628                         DEBUG(1, ("unrecognized SAM account type %08x\n", atype));
629                         continue;
630                 }
631
632                 if (!ads_pull_uint32(ctx->ads, entry, (type==ID_TYPE_UID) ?
633                                                  ctx->ad_schema->posix_uidnumber_attr :
634                                                  ctx->ad_schema->posix_gidnumber_attr,
635                                      &id)) 
636                 {
637                         DEBUG(1, ("Could not get unix ID\n"));
638                         continue;
639                 }
640                 if (!idmap_unix_id_is_in_range(id, dom)) {
641                         DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
642                                 id, dom->low_id, dom->high_id));
643                         continue;
644                 }
645
646                 /* mapped */
647                 map->xid.type = type;
648                 map->xid.id = id;
649                 map->status = ID_MAPPED;
650
651                 DEBUG(10, ("Mapped %s -> %lu (%d)\n", sid_string_dbg(map->sid),
652                            (unsigned long)map->xid.id,
653                            map->xid.type));
654         }
655
656         if (res) {
657                 ads_msgfree(ctx->ads, res);
658         }
659
660         if (ids[idx]) { /* still some values to map */
661                 goto again;
662         }
663
664         ret = NT_STATUS_OK;
665
666         /* mark all unknwoni/expired ones as unmapped */
667         for (i = 0; ids[i]; i++) {
668                 if (ids[i]->status != ID_MAPPED) 
669                         ids[i]->status = ID_UNMAPPED;
670         }
671
672 done:
673         talloc_free(memctx);
674         return ret;
675 }
676
677 /************************************************************************
678  ***********************************************************************/
679
680 static NTSTATUS idmap_ad_close(struct idmap_domain *dom)
681 {
682         struct idmap_ad_context * ctx;
683
684         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
685
686         if (ctx->ads != NULL) {
687                 /* we own this ADS_STRUCT so make sure it goes away */
688                 ctx->ads->is_mine = True;
689                 ads_destroy( &ctx->ads );
690                 ctx->ads = NULL;
691         }
692
693         TALLOC_FREE( ctx->ad_schema );
694         
695         return NT_STATUS_OK;
696 }
697
698 /*
699  * nss_info_{sfu,sfu20,rfc2307}
700  */
701
702 /************************************************************************
703  Initialize the {sfu,sfu20,rfc2307} state
704  ***********************************************************************/
705
706 static const char *wb_posix_map_unknown_string = "WB_POSIX_MAP_UNKNOWN";
707 static const char *wb_posix_map_template_string = "WB_POSIX_MAP_TEMPLATE";
708 static const char *wb_posix_map_sfu_string = "WB_POSIX_MAP_SFU";
709 static const char *wb_posix_map_sfu20_string = "WB_POSIX_MAP_SFU20";
710 static const char *wb_posix_map_rfc2307_string = "WB_POSIX_MAP_RFC2307";
711 static const char *wb_posix_map_unixinfo_string = "WB_POSIX_MAP_UNIXINFO";
712
713 static const char *ad_map_type_string(enum wb_posix_mapping map_type)
714 {
715         switch (map_type) {
716                 case WB_POSIX_MAP_TEMPLATE:
717                         return wb_posix_map_template_string;
718                 case WB_POSIX_MAP_SFU:
719                         return wb_posix_map_sfu_string;
720                 case WB_POSIX_MAP_SFU20:
721                         return wb_posix_map_sfu20_string;
722                 case WB_POSIX_MAP_RFC2307:
723                         return wb_posix_map_rfc2307_string;
724                 case WB_POSIX_MAP_UNIXINFO:
725                         return wb_posix_map_unixinfo_string;
726                 default:
727                         return wb_posix_map_unknown_string;
728         }
729 }
730
731 static NTSTATUS nss_ad_generic_init(struct nss_domain_entry *e,
732                                     enum wb_posix_mapping new_ad_map_type)
733 {
734         struct idmap_domain *dom;
735         struct idmap_ad_context *ctx;
736
737         if (e->state != NULL) {
738                 dom = talloc_get_type(e->state, struct idmap_domain);
739         } else {
740                 dom = TALLOC_ZERO_P(e, struct idmap_domain);
741                 if (dom == NULL) {
742                         DEBUG(0, ("Out of memory!\n"));
743                         return NT_STATUS_NO_MEMORY;
744                 }
745                 e->state = dom;
746         }
747
748         if (e->domain != NULL) {
749                 dom->name = talloc_strdup(dom, e->domain);
750                 if (dom->name == NULL) {
751                         DEBUG(0, ("Out of memory!\n"));
752                         return NT_STATUS_NO_MEMORY;
753                 }
754         }
755
756         if (dom->private_data != NULL) {
757                 ctx = talloc_get_type(dom->private_data,
758                                       struct idmap_ad_context);
759         } else {
760                 ctx = TALLOC_ZERO_P(dom, struct idmap_ad_context);
761                 if (ctx == NULL) {
762                         DEBUG(0, ("Out of memory!\n"));
763                         return NT_STATUS_NO_MEMORY;
764                 }
765                 ctx->ad_map_type = WB_POSIX_MAP_RFC2307;
766                 dom->private_data = ctx;
767         }
768
769         if ((ctx->ad_map_type != WB_POSIX_MAP_UNKNOWN) &&
770             (ctx->ad_map_type != new_ad_map_type))
771         {
772                 DEBUG(2, ("nss_ad_generic_init: "
773                           "Warning: overriding previously set posix map type "
774                           "%s for domain %s with map type %s.\n",
775                           ad_map_type_string(ctx->ad_map_type),
776                           dom->name,
777                           ad_map_type_string(new_ad_map_type)));
778         }
779
780         ctx->ad_map_type = new_ad_map_type;
781
782         return NT_STATUS_OK;
783 }
784
785 static NTSTATUS nss_sfu_init( struct nss_domain_entry *e )
786 {
787         return nss_ad_generic_init(e, WB_POSIX_MAP_SFU);
788 }
789
790 static NTSTATUS nss_sfu20_init( struct nss_domain_entry *e )
791 {
792         return nss_ad_generic_init(e, WB_POSIX_MAP_SFU20);
793 }
794
795 static NTSTATUS nss_rfc2307_init( struct nss_domain_entry *e )
796 {
797         return nss_ad_generic_init(e, WB_POSIX_MAP_RFC2307);
798 }
799
800
801 /************************************************************************
802  ***********************************************************************/
803
804 static NTSTATUS nss_ad_get_info( struct nss_domain_entry *e, 
805                                   const DOM_SID *sid, 
806                                   TALLOC_CTX *mem_ctx,
807                                   ADS_STRUCT *ads, 
808                                   LDAPMessage *msg,
809                                   char **homedir,
810                                   char **shell, 
811                                   char **gecos,
812                                   uint32 *gid )
813 {
814         const char *attrs[] = {NULL, /* attr_homedir */
815                                NULL, /* attr_shell */
816                                NULL, /* attr_gecos */
817                                NULL, /* attr_gidnumber */
818                                NULL };
819         char *filter = NULL;
820         LDAPMessage *msg_internal = NULL;
821         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
822         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
823         char *sidstr = NULL;
824         struct idmap_domain *dom;
825         struct idmap_ad_context *ctx;
826
827         DEBUG(10, ("nss_ad_get_info called for sid [%s] in domain '%s'\n",
828                    sid_string_dbg(sid), e->domain?e->domain:"NULL"));
829
830         /* Only do query if we are online */
831         if (idmap_is_offline()) {
832                 return NT_STATUS_FILE_IS_OFFLINE;
833         }
834
835         dom = talloc_get_type(e->state, struct idmap_domain);
836         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
837
838         ads_status = ad_idmap_cached_connection(dom);
839         if (!ADS_ERR_OK(ads_status)) {
840                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
841         }
842
843         if (!ctx->ad_schema) {
844                 DEBUG(10, ("nss_ad_get_info: no ad_schema configured!\n"));
845                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
846         }
847
848         if (!sid || !homedir || !shell || !gecos) {
849                 return NT_STATUS_INVALID_PARAMETER;
850         }
851
852         /* See if we can use the ADS connection struct swe were given */
853
854         if (ads) {
855                 DEBUG(10, ("nss_ad_get_info: using given ads connection and "
856                            "LDAP message (%p)\n", msg));
857
858                 *homedir = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_homedir_attr );
859                 *shell   = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_shell_attr );
860                 *gecos   = ads_pull_string( ads, mem_ctx, msg, ctx->ad_schema->posix_gecos_attr );
861
862                 if (gid) {
863                         if ( !ads_pull_uint32(ads, msg, ctx->ad_schema->posix_gidnumber_attr, gid ) )
864                                 *gid = (uint32)-1;
865                 }
866
867                 nt_status = NT_STATUS_OK;
868                 goto done;
869         }
870
871         /* Have to do our own query */
872
873         DEBUG(10, ("nss_ad_get_info: no ads connection given, doing our "
874                    "own query\n"));
875
876         attrs[0] = ctx->ad_schema->posix_homedir_attr;
877         attrs[1] = ctx->ad_schema->posix_shell_attr;
878         attrs[2] = ctx->ad_schema->posix_gecos_attr;
879         attrs[3] = ctx->ad_schema->posix_gidnumber_attr;
880
881         sidstr = sid_binstring(sid);
882         filter = talloc_asprintf(mem_ctx, "(objectSid=%s)", sidstr);
883         SAFE_FREE(sidstr);
884
885         if (!filter) {
886                 nt_status = NT_STATUS_NO_MEMORY;
887                 goto done;
888         }
889
890         ads_status = ads_search_retry(ctx->ads, &msg_internal, filter, attrs);
891         if (!ADS_ERR_OK(ads_status)) {
892                 nt_status = ads_ntstatus(ads_status);
893                 goto done;
894         }
895
896         *homedir = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_homedir_attr);
897         *shell   = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_shell_attr);
898         *gecos   = ads_pull_string(ctx->ads, mem_ctx, msg_internal, ctx->ad_schema->posix_gecos_attr);
899
900         if (gid) {
901                 if (!ads_pull_uint32(ctx->ads, msg_internal, ctx->ad_schema->posix_gidnumber_attr, gid))
902                         *gid = (uint32)-1;
903         }
904
905         nt_status = NT_STATUS_OK;
906
907 done:
908         if (msg_internal) {
909                 ads_msgfree(ctx->ads, msg_internal);
910         }
911
912         return nt_status;
913 }
914
915 /**********************************************************************
916  *********************************************************************/
917
918 static NTSTATUS nss_ad_map_to_alias(TALLOC_CTX *mem_ctx,
919                                     struct nss_domain_entry *e,
920                                     const char *name,
921                                     char **alias)
922 {
923         const char *attrs[] = {NULL, /* attr_uid */
924                                NULL };
925         char *filter = NULL;
926         LDAPMessage *msg = NULL;
927         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
928         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
929         struct idmap_domain *dom;
930         struct idmap_ad_context *ctx = NULL;
931
932         /* Check incoming parameters */
933
934         if ( !e || !e->domain || !name || !*alias) {
935                 nt_status = NT_STATUS_INVALID_PARAMETER;
936                 goto done;
937         }
938
939         /* Only do query if we are online */
940
941         if (idmap_is_offline()) {
942                 nt_status = NT_STATUS_FILE_IS_OFFLINE;
943                 goto done;
944         }
945
946         dom = talloc_get_type(e->state, struct idmap_domain);
947         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
948
949         ads_status = ad_idmap_cached_connection(dom);
950         if (!ADS_ERR_OK(ads_status)) {
951                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
952         }
953
954         if (!ctx->ad_schema) {
955                 nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
956                 goto done;
957         }
958
959         attrs[0] = ctx->ad_schema->posix_uid_attr;
960
961         filter = talloc_asprintf(mem_ctx,
962                                  "(sAMAccountName=%s)",
963                                  name);
964         if (!filter) {
965                 nt_status = NT_STATUS_NO_MEMORY;
966                 goto done;
967         }
968
969         ads_status = ads_search_retry(ctx->ads, &msg, filter, attrs);
970         if (!ADS_ERR_OK(ads_status)) {
971                 nt_status = ads_ntstatus(ads_status);
972                 goto done;
973         }
974
975         *alias = ads_pull_string(ctx->ads, mem_ctx, msg, ctx->ad_schema->posix_uid_attr);
976
977         if (!*alias) {
978                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
979         }
980
981         nt_status = NT_STATUS_OK;
982
983 done:
984         if (filter) {
985                 talloc_destroy(filter);
986         }
987         if (msg) {
988                 ads_msgfree(ctx->ads, msg);
989         }
990
991         return nt_status;
992 }
993
994 /**********************************************************************
995  *********************************************************************/
996
997 static NTSTATUS nss_ad_map_from_alias( TALLOC_CTX *mem_ctx,
998                                              struct nss_domain_entry *e,
999                                              const char *alias,
1000                                              char **name )
1001 {
1002         const char *attrs[] = {"sAMAccountName",
1003                                NULL };
1004         char *filter = NULL;
1005         LDAPMessage *msg = NULL;
1006         ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
1007         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
1008         char *username;
1009         struct idmap_domain *dom;
1010         struct idmap_ad_context *ctx = NULL;
1011
1012         /* Check incoming parameters */
1013
1014         if ( !alias || !name) {
1015                 nt_status = NT_STATUS_INVALID_PARAMETER;
1016                 goto done;
1017         }
1018
1019         /* Only do query if we are online */
1020
1021         if (idmap_is_offline()) {
1022                 nt_status = NT_STATUS_FILE_IS_OFFLINE;
1023                 goto done;
1024         }
1025
1026         dom = talloc_get_type(e->state, struct idmap_domain);
1027         ctx = talloc_get_type(dom->private_data, struct idmap_ad_context);
1028
1029         ads_status = ad_idmap_cached_connection(dom);
1030         if (!ADS_ERR_OK(ads_status)) {
1031                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1032         }
1033
1034         if (!ctx->ad_schema) {
1035                 nt_status = NT_STATUS_OBJECT_PATH_NOT_FOUND;
1036                 goto done;
1037         }
1038
1039         filter = talloc_asprintf(mem_ctx,
1040                                  "(%s=%s)",
1041                                  ctx->ad_schema->posix_uid_attr,
1042                                  alias);
1043         if (!filter) {
1044                 nt_status = NT_STATUS_NO_MEMORY;
1045                 goto done;
1046         }
1047
1048         ads_status = ads_search_retry(ctx->ads, &msg, filter, attrs);
1049         if (!ADS_ERR_OK(ads_status)) {
1050                 nt_status = ads_ntstatus(ads_status);
1051                 goto done;
1052         }
1053
1054         username = ads_pull_string(ctx->ads, mem_ctx, msg,
1055                                    "sAMAccountName");
1056         if (!username) {
1057                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
1058         }
1059
1060         *name = talloc_asprintf(mem_ctx, "%s\\%s",
1061                                 lp_workgroup(),
1062                                 username);
1063         if (!*name) {
1064                 nt_status = NT_STATUS_NO_MEMORY;
1065                 goto done;
1066         }
1067
1068         nt_status = NT_STATUS_OK;
1069
1070 done:
1071         if (filter) {
1072                 talloc_destroy(filter);
1073         }
1074         if (msg) {
1075                 ads_msgfree(ctx->ads, msg);
1076         }
1077
1078         return nt_status;
1079 }
1080
1081
1082 /************************************************************************
1083  ***********************************************************************/
1084
1085 static NTSTATUS nss_ad_close( void )
1086 {
1087         /* nothing to do.  All memory is free()'d by the idmap close_fn() */
1088
1089         return NT_STATUS_OK;
1090 }
1091
1092 /************************************************************************
1093  Function dispatch tables for the idmap and nss plugins
1094  ***********************************************************************/
1095
1096 static struct idmap_methods ad_methods = {
1097         .init            = idmap_ad_initialize,
1098         .unixids_to_sids = idmap_ad_unixids_to_sids,
1099         .sids_to_unixids = idmap_ad_sids_to_unixids,
1100         .close_fn        = idmap_ad_close
1101 };
1102
1103 /* The SFU and RFC2307 NSS plugins share everything but the init
1104    function which sets the intended schema model to use */
1105   
1106 static struct nss_info_methods nss_rfc2307_methods = {
1107         .init           = nss_rfc2307_init,
1108         .get_nss_info   = nss_ad_get_info,
1109         .map_to_alias   = nss_ad_map_to_alias,
1110         .map_from_alias = nss_ad_map_from_alias,
1111         .close_fn       = nss_ad_close
1112 };
1113
1114 static struct nss_info_methods nss_sfu_methods = {
1115         .init           = nss_sfu_init,
1116         .get_nss_info   = nss_ad_get_info,
1117         .map_to_alias   = nss_ad_map_to_alias,
1118         .map_from_alias = nss_ad_map_from_alias,
1119         .close_fn       = nss_ad_close
1120 };
1121
1122 static struct nss_info_methods nss_sfu20_methods = {
1123         .init           = nss_sfu20_init,
1124         .get_nss_info   = nss_ad_get_info,
1125         .map_to_alias   = nss_ad_map_to_alias,
1126         .map_from_alias = nss_ad_map_from_alias,
1127         .close_fn       = nss_ad_close
1128 };
1129
1130
1131
1132 /************************************************************************
1133  Initialize the plugins
1134  ***********************************************************************/
1135
1136 NTSTATUS idmap_ad_init(void)
1137 {
1138         static NTSTATUS status_idmap_ad = NT_STATUS_UNSUCCESSFUL;
1139         static NTSTATUS status_nss_rfc2307 = NT_STATUS_UNSUCCESSFUL;
1140         static NTSTATUS status_nss_sfu = NT_STATUS_UNSUCCESSFUL;
1141         static NTSTATUS status_nss_sfu20 = NT_STATUS_UNSUCCESSFUL;
1142
1143         /* Always register the AD method first in order to get the
1144            idmap_domain interface called */
1145
1146         if ( !NT_STATUS_IS_OK(status_idmap_ad) ) {
1147                 status_idmap_ad = smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, 
1148                                                      "ad", &ad_methods);
1149                 if ( !NT_STATUS_IS_OK(status_idmap_ad) )
1150                         return status_idmap_ad;         
1151         }
1152         
1153         if ( !NT_STATUS_IS_OK( status_nss_rfc2307 ) ) {
1154                 status_nss_rfc2307 = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1155                                                             "rfc2307",  &nss_rfc2307_methods );         
1156                 if ( !NT_STATUS_IS_OK(status_nss_rfc2307) )
1157                         return status_nss_rfc2307;
1158         }
1159
1160         if ( !NT_STATUS_IS_OK( status_nss_sfu ) ) {
1161                 status_nss_sfu = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1162                                                         "sfu",  &nss_sfu_methods );             
1163                 if ( !NT_STATUS_IS_OK(status_nss_sfu) )
1164                         return status_nss_sfu;          
1165         }
1166
1167         if ( !NT_STATUS_IS_OK( status_nss_sfu20 ) ) {
1168                 status_nss_sfu20 = smb_register_idmap_nss(SMB_NSS_INFO_INTERFACE_VERSION,
1169                                                         "sfu20",  &nss_sfu20_methods );         
1170                 if ( !NT_STATUS_IS_OK(status_nss_sfu20) )
1171                         return status_nss_sfu20;                
1172         }
1173
1174         return NT_STATUS_OK;    
1175 }
1176