8f3e7c465e46c3889ef2adab725fec649ffd255a
[sfrench/samba-autobuild/.git] / source / nsswitch / idmap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    ID Mapping
4    Copyright (C) Tim Potter 2000
5    Copyright (C) Jim McDonough <jmcd@us.ibm.com>        2003
6    Copyright (C) Simo Sorce 2003
7    Copyright (C) Jeremy Allison 2006
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 #undef DBGC_CLASS
28 #define DBGC_CLASS DBGC_IDMAP
29
30 static_decl_idmap;
31
32 struct idmap_backend {
33         const char *name;
34         struct idmap_methods *methods;
35         struct idmap_backend *prev, *next;
36 };
37
38 struct idmap_alloc_backend {
39         const char *name;
40         struct idmap_alloc_methods *methods;
41         struct idmap_alloc_backend *prev, *next;
42 };
43
44 struct idmap_cache_ctx;
45
46 struct idmap_alloc_context {
47         const char *params;
48         struct idmap_alloc_methods *methods;
49         BOOL initialized;
50 };
51
52 static TALLOC_CTX *idmap_ctx = NULL;
53 static struct idmap_cache_ctx *idmap_cache;
54
55 static struct idmap_backend *backends = NULL;
56 static struct idmap_domain **idmap_domains = NULL;
57 static int num_domains = 0;
58 static int pdb_dom_num = -1;
59 static int def_dom_num = -1;
60
61 static struct idmap_alloc_backend *alloc_backends = NULL;
62 static struct idmap_alloc_context *idmap_alloc_ctx = NULL;
63
64 #define IDMAP_CHECK_RET(ret) do { if ( ! NT_STATUS_IS_OK(ret)) { DEBUG(2, ("ERROR: NTSTATUS = 0x%08x\n", NT_STATUS_V(ret))); goto done; } } while(0)
65 #define IDMAP_REPORT_RET(ret) do { if ( ! NT_STATUS_IS_OK(ret)) { DEBUG(2, ("ERROR: NTSTATUS = 0x%08x\n", NT_STATUS_V(ret))); } } while(0)
66 #define IDMAP_CHECK_ALLOC(mem) do { if (!mem) { DEBUG(0, ("Out of memory!\n")); ret = NT_STATUS_NO_MEMORY; goto done; } } while(0)
67
68 static struct idmap_methods *get_methods(struct idmap_backend *be, const char *name)
69 {
70         struct idmap_backend *b;
71
72         for (b = be; b; b = b->next) {
73                 if (strequal(b->name, name)) {
74                         return b->methods;
75                 }
76         }
77
78         return NULL;
79 }
80
81 static struct idmap_alloc_methods *get_alloc_methods(struct idmap_alloc_backend *be, const char *name)
82 {
83         struct idmap_alloc_backend *b;
84
85         for (b = be; b; b = b->next) {
86                 if (strequal(b->name, name)) {
87                         return b->methods;
88                 }
89         }
90
91         return NULL;
92 }
93
94 BOOL idmap_is_offline(void)
95 {
96         return ( lp_winbind_offline_logon() &&
97              get_global_winbindd_state_offline() );
98 }
99
100 /**********************************************************************
101  Allow a module to register itself as a method.
102 **********************************************************************/
103
104 NTSTATUS smb_register_idmap(int version, const char *name, struct idmap_methods *methods)
105 {
106         struct idmap_methods *test;
107         struct idmap_backend *entry;
108
109         if (!idmap_ctx) {
110                 return NT_STATUS_INTERNAL_DB_ERROR;
111         }
112
113         if ((version != SMB_IDMAP_INTERFACE_VERSION)) {
114                 DEBUG(0, ("Failed to register idmap module.\n"
115                           "The module was compiled against SMB_IDMAP_INTERFACE_VERSION %d,\n"
116                           "current SMB_IDMAP_INTERFACE_VERSION is %d.\n"
117                           "Please recompile against the current version of samba!\n",  
118                           version, SMB_IDMAP_INTERFACE_VERSION));
119                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
120         }
121
122         if (!name || !name[0] || !methods) {
123                 DEBUG(0,("Called with NULL pointer or empty name!\n"));
124                 return NT_STATUS_INVALID_PARAMETER;
125         }
126
127         test = get_methods(backends, name);
128         if (test) {
129                 DEBUG(0,("Idmap module %s already registered!\n", name));
130                 return NT_STATUS_OBJECT_NAME_COLLISION;
131         }
132
133         entry = talloc(idmap_ctx, struct idmap_backend);
134         if ( ! entry) {
135                 DEBUG(0,("Out of memory!\n"));
136                 return NT_STATUS_NO_MEMORY;
137         }
138         entry->name = talloc_strdup(idmap_ctx, name);
139         if ( ! entry->name) {
140                 DEBUG(0,("Out of memory!\n"));
141                 return NT_STATUS_NO_MEMORY;
142         }
143         entry->methods = methods;
144
145         DLIST_ADD(backends, entry);
146         DEBUG(5, ("Successfully added idmap backend '%s'\n", name));
147         return NT_STATUS_OK;
148 }
149
150 /**********************************************************************
151  Allow a module to register itself as a method.
152 **********************************************************************/
153
154 NTSTATUS smb_register_idmap_alloc(int version, const char *name, struct idmap_alloc_methods *methods)
155 {
156         struct idmap_alloc_methods *test;
157         struct idmap_alloc_backend *entry;
158
159         if (!idmap_ctx) {
160                 return NT_STATUS_INTERNAL_DB_ERROR;
161         }
162
163         if ((version != SMB_IDMAP_INTERFACE_VERSION)) {
164                 DEBUG(0, ("Failed to register idmap alloc module.\n"
165                           "The module was compiled against SMB_IDMAP_INTERFACE_VERSION %d,\n"
166                           "current SMB_IDMAP_INTERFACE_VERSION is %d.\n"
167                           "Please recompile against the current version of samba!\n",  
168                           version, SMB_IDMAP_INTERFACE_VERSION));
169                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
170         }
171
172         if (!name || !name[0] || !methods) {
173                 DEBUG(0,("Called with NULL pointer or empty name!\n"));
174                 return NT_STATUS_INVALID_PARAMETER;
175         }
176
177         test = get_alloc_methods(alloc_backends, name);
178         if (test) {
179                 DEBUG(0,("idmap_alloc module %s already registered!\n", name));
180                 return NT_STATUS_OBJECT_NAME_COLLISION;
181         }
182
183         entry = talloc(idmap_ctx, struct idmap_alloc_backend);
184         if ( ! entry) {
185                 DEBUG(0,("Out of memory!\n"));
186                 return NT_STATUS_NO_MEMORY;
187         }
188         entry->name = talloc_strdup(idmap_ctx, name);
189         if ( ! entry->name) {
190                 DEBUG(0,("Out of memory!\n"));
191                 return NT_STATUS_NO_MEMORY;
192         }
193         entry->methods = methods;
194
195         DLIST_ADD(alloc_backends, entry);
196         DEBUG(5, ("Successfully added idmap alloc backend '%s'\n", name));
197         return NT_STATUS_OK;
198 }
199
200 static int close_domain_destructor(struct idmap_domain *dom)
201 {
202         NTSTATUS ret;
203
204         ret = dom->methods->close_fn(dom);
205         if (!NT_STATUS_IS_OK(ret)) {
206                 DEBUG(3, ("Failed to close idmap domain [%s]!\n", dom->name));
207         }
208
209         return 0;
210 }
211
212 /**************************************************************************
213  Shutdown.
214 **************************************************************************/
215
216 NTSTATUS idmap_close(void)
217 {
218         /* close the alloc backend first before freeing idmap_ctx */
219         if (idmap_alloc_ctx) {
220                 idmap_alloc_ctx->methods->close_fn();
221                 idmap_alloc_ctx->methods = NULL;
222         }
223         alloc_backends = NULL;
224
225         /* this talloc_free call will fire the talloc destructors
226          * that will free all active backends resources */
227         TALLOC_FREE(idmap_ctx);
228         idmap_cache = NULL;
229         idmap_domains = NULL;
230         backends = NULL;
231
232         return NT_STATUS_OK;
233 }
234
235 /**********************************************************************
236  Initialise idmap cache and a remote backend (if configured).
237 **********************************************************************/
238
239 static const char *idmap_default_domain[] = { "default domain", NULL };
240
241 /****************************************************************************
242  ****************************************************************************/
243
244 NTSTATUS idmap_init_cache(void)
245 {       
246         /* Always initialize the cache.  We'll have to delay initialization
247            of backends if we are offline */
248
249         if ( idmap_ctx ) {
250                 return NT_STATUS_OK;
251         }       
252         
253         if ( (idmap_ctx = talloc_named_const(NULL, 0, "idmap_ctx")) == NULL ) {
254                 return NT_STATUS_NO_MEMORY;
255         }
256
257         if ( (idmap_cache = idmap_cache_init(idmap_ctx)) == NULL ) {
258                 return NT_STATUS_UNSUCCESSFUL;
259         }
260
261         return NT_STATUS_OK;
262 }
263
264 /****************************************************************************
265  ****************************************************************************/
266
267 NTSTATUS idmap_init(void)
268 {       
269         NTSTATUS ret;
270         static NTSTATUS idmap_init_status = NT_STATUS_UNSUCCESSFUL;
271         struct idmap_domain *dom;
272         char *compat_backend = NULL;
273         char *compat_params = NULL;
274         const char **dom_list = NULL;
275         char *alloc_backend = NULL;
276         BOOL default_already_defined = False;
277         BOOL pri_dom_is_in_list = False;
278         int compat = 0;
279         int i;
280
281         ret = idmap_init_cache();
282         if ( !NT_STATUS_IS_OK(ret) )
283                 return ret;
284
285         if (NT_STATUS_IS_OK(idmap_init_status)) {               
286                 return NT_STATUS_OK;
287         }
288         
289         /* We can't reliably call intialization code here unless 
290            we are online.  But return NT_STATUS_OK so the upper 
291            level code doesn't abort idmap lookups. */
292
293         if ( get_global_winbindd_state_offline() ) {
294                 idmap_init_status = NT_STATUS_FILE_IS_OFFLINE;
295                 return NT_STATUS_OK;
296         }
297
298         static_init_idmap;
299
300         dom_list = lp_idmap_domains();
301         
302         if ( lp_idmap_backend() ) {
303                 const char **compat_list = lp_idmap_backend();
304                 char *p = NULL;
305                 const char *q = NULL;           
306
307                 if ( dom_list ) {                       
308                         DEBUG(0, ("WARNING: idmap backend and idmap domains are "
309                                   "mutually excusive!\n"));
310                         DEBUGADD(0,("idmap backend option will be IGNORED!\n"));
311                 } else {
312                         compat = 1;
313
314                         if ( (compat_backend = talloc_strdup( idmap_ctx, *compat_list )) == NULL ) {
315                                 ret = NT_STATUS_NO_MEMORY;
316                                 goto done;
317                         }
318                 
319                         /* strip any leading idmap_ prefix of */
320                         if (strncmp(*compat_list, "idmap_", 6) == 0 ) {
321                                 q = *compat_list += 6;
322                                 DEBUG(0, ("WARNING: idmap backend uses obsolete and "
323                                           "deprecated 'idmap_' prefix.\n"
324                                           "Please replace 'idmap_%s' by '%s' in %s\n", 
325                                           q, q, dyn_CONFIGFILE));
326                                 compat_backend = talloc_strdup( idmap_ctx, q);
327                         } else {
328                                 compat_backend = talloc_strdup( idmap_ctx, *compat_list);
329                         }
330                         
331                         /* separate the backend and module arguements */
332                         if ((p = strchr(compat_backend, ':')) != NULL) {
333                                 *p = '\0';                      
334                                 compat_params = p + 1;
335                         }
336                 }               
337         } else if ( !dom_list ) {
338                 /* Back compatible: without idmap domains and explicit
339                    idmap backend.  Taking default idmap backend: tdb */
340                 
341                 compat = 1;
342                 compat_backend = talloc_strdup( idmap_ctx, "tdb");
343                 compat_params = compat_backend;
344         }
345
346         if ( ! dom_list) {
347                 dom_list = idmap_default_domain;
348         }
349         
350         /***************************
351          * initialize idmap domains
352          */
353         DEBUG(1, ("Initializing idmap domains\n"));
354
355         for (i = 0; dom_list[i]; i++) {
356                 const char *parm_backend;
357                 char *config_option;
358
359                 /* ignore BUILTIN and local MACHINE domains */
360                 if ( strequal(dom_list[i], "BUILTIN") 
361                      || strequal(dom_list[i], get_global_sam_name() ) ) 
362                 {
363                         DEBUG(0,("idmap_init: Ignoring invalid domain %s\n", 
364                                  dom_list[i]));
365                         continue;
366                 }
367
368                 if (strequal(dom_list[i], lp_workgroup())) {
369                         pri_dom_is_in_list = True;
370                 }
371                 /* init domain */
372                 
373                 dom = TALLOC_ZERO_P(idmap_ctx, struct idmap_domain);
374                 IDMAP_CHECK_ALLOC(dom);
375
376                 dom->name = talloc_strdup(dom, dom_list[i]);
377                 IDMAP_CHECK_ALLOC(dom->name);
378
379                 config_option = talloc_asprintf(dom, "idmap config %s", dom->name);
380                 IDMAP_CHECK_ALLOC(config_option);
381
382                 /* default or specific ? */
383
384                 dom->default_domain = lp_parm_bool(-1, config_option, "default", False);
385
386                 if (dom->default_domain ||
387                     strequal(dom_list[i], idmap_default_domain[0])) {
388
389                         /* make sure this is set even when we match idmap_default_domain[0] */
390                         dom->default_domain = True;
391
392                         if (default_already_defined) {
393                                 DEBUG(1, ("ERROR: Multiple domains defined as default!\n"));
394                                 ret = NT_STATUS_INVALID_PARAMETER;
395                                 goto done;
396                         }
397
398                         default_already_defined = True;
399
400                 } 
401
402                 dom->readonly = lp_parm_bool(-1, config_option, "readonly", False);
403
404                 /* find associated backend (default: tdb) */
405                 if (compat) {
406                         parm_backend = talloc_strdup(idmap_ctx, compat_backend);
407                 } else {
408                         parm_backend = talloc_strdup(idmap_ctx,
409                                                      lp_parm_const_string(-1, config_option, "backend", "tdb"));
410                 }
411                 IDMAP_CHECK_ALLOC(parm_backend);
412
413                 /* get the backend methods for this domain */
414                 dom->methods = get_methods(backends, parm_backend);
415
416                 if ( ! dom->methods) {
417                         ret = smb_probe_module("idmap", parm_backend);
418                         if (NT_STATUS_IS_OK(ret)) {
419                                 dom->methods = get_methods(backends, parm_backend);
420                         }
421                 }
422                 if ( ! dom->methods) {
423                         DEBUG(0, ("ERROR: Could not get methods for backend %s\n", parm_backend));
424                         ret = NT_STATUS_UNSUCCESSFUL;
425                         goto done;
426                 }
427
428                 /* check the set_mapping function exists otherwise mark the module as readonly */
429                 if ( ! dom->methods->set_mapping) {
430                         DEBUG(5, ("Forcing to readonly, as ithis module can't store arbitrary mappings.\n"));
431                         dom->readonly = True;
432                 }
433
434                 /* now that we have methods, set the destructor for this domain */
435                 talloc_set_destructor(dom, close_domain_destructor);
436
437                 if (compat_params) {
438                         dom->params = talloc_strdup(dom, compat_params);
439                         IDMAP_CHECK_ALLOC(dom->params);
440                 } else {
441                         dom->params = NULL;
442                 }
443
444                 /* Finally instance a backend copy for this domain */
445                 ret = dom->methods->init(dom);
446                 if ( ! NT_STATUS_IS_OK(ret)) {
447                         DEBUG(0, ("ERROR: Initialization failed for backend %s (domain %s), deferred!\n",
448                                                 parm_backend, dom->name));
449                 }
450                 idmap_domains = talloc_realloc(idmap_ctx, idmap_domains, struct idmap_domain *, i+1);
451                 if ( ! idmap_domains) {
452                         DEBUG(0, ("Out of memory!\n"));
453                         ret = NT_STATUS_NO_MEMORY;
454                         goto done;
455                 }
456                 idmap_domains[i] = dom;
457
458                 if (dom->default_domain) { /* save default domain position for future uses */
459                         def_dom_num = i;
460                 }
461
462                 DEBUG(10, ("Domain %s - Backend %s - %sdefault - %sreadonly\n",
463                                 dom->name, parm_backend,
464                                 dom->default_domain?"":"not ", dom->readonly?"":"not "));
465
466                 talloc_free(config_option);
467         }
468
469         /* save the number of domains we have */
470         num_domains = i;
471
472         /* automatically add idmap_nss backend if needed */
473         if ((lp_server_role() == ROLE_DOMAIN_MEMBER) &&
474             ( ! pri_dom_is_in_list) &&
475             lp_winbind_trusted_domains_only()) {
476
477                 dom = TALLOC_ZERO_P(idmap_ctx, struct idmap_domain);
478                 IDMAP_CHECK_ALLOC(dom);
479
480                 dom->name = talloc_strdup(dom, lp_workgroup());
481                 IDMAP_CHECK_ALLOC(dom->name);
482
483                 dom->default_domain = False;
484                 dom->readonly = True;
485
486                 /* get the backend methods for passdb */
487                 dom->methods = get_methods(backends, "nss");
488
489                 /* (the nss module is always statically linked) */
490                 if ( ! dom->methods) {
491                         DEBUG(0, ("ERROR: Could not get methods for idmap_nss ?!\n"));
492                         ret = NT_STATUS_UNSUCCESSFUL;
493                         goto done;
494                 }
495
496                 /* now that we have methods, set the destructor for this domain */
497                 talloc_set_destructor(dom, close_domain_destructor);
498
499                 if (compat_params) {
500                         dom->params = talloc_strdup(dom, compat_params);
501                         IDMAP_CHECK_ALLOC(dom->params);
502                 } else {
503                         dom->params = NULL;
504                 }
505
506                 /* Finally instance a backend copy for this domain */
507                 ret = dom->methods->init(dom);
508                 if ( ! NT_STATUS_IS_OK(ret)) {
509                         DEBUG(0, ("ERROR: Initialization failed for idmap_nss ?!\n"));
510                         ret = NT_STATUS_UNSUCCESSFUL;
511                         goto done;
512                 }
513
514                 idmap_domains = talloc_realloc(idmap_ctx, idmap_domains, struct idmap_domain *, num_domains+1);
515                 if ( ! idmap_domains) {
516                         DEBUG(0, ("Out of memory!\n"));
517                         ret = NT_STATUS_NO_MEMORY;
518                         goto done;
519                 }
520                 idmap_domains[num_domains] = dom;
521
522                 DEBUG(10, ("Domain %s - Backend nss - not default - readonly\n", dom->name ));
523
524                 num_domains++;
525         }
526
527         /**** automatically add idmap_passdb backend ****/
528         dom = TALLOC_ZERO_P(idmap_ctx, struct idmap_domain);
529         IDMAP_CHECK_ALLOC(dom);
530
531         dom->name = talloc_strdup(dom, get_global_sam_name());
532         IDMAP_CHECK_ALLOC(dom->name);
533
534         dom->default_domain = False;
535         dom->readonly = True;
536
537         /* get the backend methods for passdb */
538         dom->methods = get_methods(backends, "passdb");
539
540         /* (the passdb module is always statically linked) */
541         if ( ! dom->methods) {
542                 DEBUG(0, ("ERROR: Could not get methods for idmap_passdb ?!\n"));
543                 ret = NT_STATUS_UNSUCCESSFUL;
544                 goto done;
545         }
546
547         /* now that we have methods, set the destructor for this domain */
548         talloc_set_destructor(dom, close_domain_destructor);
549
550         if (compat_params) {
551                 dom->params = talloc_strdup(dom, compat_params);
552                 IDMAP_CHECK_ALLOC(dom->params);
553         } else {
554                 dom->params = NULL;
555         }
556
557         /* Finally instance a backend copy for this domain */
558         ret = dom->methods->init(dom);
559         if ( ! NT_STATUS_IS_OK(ret)) {
560                 DEBUG(0, ("ERROR: Initialization failed for idmap_passdb ?!\n"));
561                 ret = NT_STATUS_UNSUCCESSFUL;
562                 goto done;
563         }
564
565         idmap_domains = talloc_realloc(idmap_ctx, idmap_domains, struct idmap_domain *, num_domains+1);
566         if ( ! idmap_domains) {
567                 DEBUG(0, ("Out of memory!\n"));
568                 ret = NT_STATUS_NO_MEMORY;
569                 goto done;
570         }
571         idmap_domains[num_domains] = dom;
572
573         /* needed to handle special BUILTIN and wellknown SIDs cases */
574         pdb_dom_num = num_domains;
575
576         DEBUG(10, ("Domain %s - Backend passdb - not default - readonly\n", dom->name));
577
578         num_domains++;
579         /**** finished adding idmap_passdb backend ****/
580
581         /* sort domains so that the default is the last one */
582         /* don't sort if no default domain defined */
583         if (def_dom_num != -1 && def_dom_num != num_domains-1) { /* default is not last, move it */
584                 struct idmap_domain *tmp;
585
586                 if (pdb_dom_num > def_dom_num) {
587                         pdb_dom_num --;
588
589                 } else if (pdb_dom_num == def_dom_num) { /* ?? */
590                         pdb_dom_num = num_domains - 1;
591                 }
592
593                 tmp = idmap_domains[def_dom_num];
594
595                 for (i = def_dom_num; i < num_domains-1; i++) {
596                         idmap_domains[i] = idmap_domains[i+1];
597                 }
598                 idmap_domains[i] = tmp;
599                 def_dom_num = i;
600         }
601
602
603         /* Initialize alloc module */
604
605         DEBUG(3, ("Initializing idmap alloc module\n"));
606
607         alloc_backend = NULL;
608         if (compat) {
609                 alloc_backend = talloc_strdup(idmap_ctx, compat_backend);
610         } else {
611                 char *ab = lp_idmap_alloc_backend();
612                 
613                 if (ab && (ab[0] != '\0')) {
614                         alloc_backend = talloc_strdup(idmap_ctx, lp_idmap_alloc_backend());
615                 }
616         }
617
618         if ( alloc_backend ) {
619                 
620                 idmap_alloc_ctx = TALLOC_ZERO_P(idmap_ctx, struct idmap_alloc_context);
621                 IDMAP_CHECK_ALLOC(idmap_alloc_ctx);
622
623                 idmap_alloc_ctx->methods = get_alloc_methods(alloc_backends, alloc_backend);
624                 if ( ! idmap_alloc_ctx->methods) {
625                         ret = smb_probe_module("idmap", alloc_backend);
626                         if (NT_STATUS_IS_OK(ret)) {
627                                 idmap_alloc_ctx->methods = get_alloc_methods(alloc_backends, alloc_backend);
628                         }
629                 }
630                 if (idmap_alloc_ctx->methods) {
631
632                         if (compat_params) {
633                                 idmap_alloc_ctx->params = talloc_strdup(idmap_alloc_ctx, compat_params);
634                                 IDMAP_CHECK_ALLOC(idmap_alloc_ctx->params);
635                         } else {
636                                 idmap_alloc_ctx->params = NULL;
637                         }
638
639                         ret = idmap_alloc_ctx->methods->init(idmap_alloc_ctx->params);
640                         if ( ! NT_STATUS_IS_OK(ret)) {
641                                 DEBUG(0, ("ERROR: Initialization failed for alloc "
642                                           "backend %s, deferred!\n", alloc_backend));
643                         } else {
644                                 idmap_alloc_ctx->initialized = True;
645                         }
646                 } else {
647                         DEBUG(2, ("idmap_init: Unable to get methods for alloc backend %s\n", 
648                                   alloc_backend));
649                         /* certain compat backends are just readonly */
650                         if ( compat ) {
651                                 TALLOC_FREE(idmap_alloc_ctx);
652                                 ret = NT_STATUS_OK;
653                         } else {
654                                 ret = NT_STATUS_UNSUCCESSFUL;
655                         }
656                 }
657         }
658         
659         /* cleanpu temporary strings */
660         TALLOC_FREE( compat_backend );
661
662         idmap_init_status = NT_STATUS_OK;
663         
664         return ret;
665
666 done:
667         DEBUG(0, ("Aborting IDMAP Initialization ...\n"));
668         idmap_close();
669
670         return ret;
671 }
672
673 static NTSTATUS idmap_alloc_init(void)
674 {
675         NTSTATUS ret;
676
677         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
678                 return ret;
679         }
680
681         if ( ! idmap_alloc_ctx) {
682                 return NT_STATUS_NOT_SUPPORTED;
683         }
684
685         if ( ! idmap_alloc_ctx->initialized) {
686                 ret = idmap_alloc_ctx->methods->init(idmap_alloc_ctx->params);
687                 if ( ! NT_STATUS_IS_OK(ret)) {
688                         DEBUG(0, ("ERROR: Initialization failed for alloc "
689                                   "backend, deferred!\n"));
690                         return ret;
691                 } else {
692                         idmap_alloc_ctx->initialized = True;
693                 }
694         }
695
696         return NT_STATUS_OK;
697 }
698
699 /**************************************************************************
700  idmap allocator interface functions
701 **************************************************************************/
702
703 NTSTATUS idmap_allocate_uid(struct unixid *id)
704 {
705         NTSTATUS ret;
706
707         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
708                 return ret;
709         }
710
711         id->type = ID_TYPE_UID;
712         return idmap_alloc_ctx->methods->allocate_id(id);
713 }
714
715 NTSTATUS idmap_allocate_gid(struct unixid *id)
716 {
717         NTSTATUS ret;
718
719         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
720                 return ret;
721         }
722
723         id->type = ID_TYPE_GID;
724         return idmap_alloc_ctx->methods->allocate_id(id);
725 }
726
727 NTSTATUS idmap_set_uid_hwm(struct unixid *id)
728 {
729         NTSTATUS ret;
730
731         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
732                 return ret;
733         }
734
735         id->type = ID_TYPE_UID;
736         return idmap_alloc_ctx->methods->set_id_hwm(id);
737 }
738
739 NTSTATUS idmap_set_gid_hwm(struct unixid *id)
740 {
741         NTSTATUS ret;
742
743         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
744                 return ret;
745         }
746
747         id->type = ID_TYPE_GID;
748         return idmap_alloc_ctx->methods->set_id_hwm(id);
749 }
750
751 /******************************************************************************
752  Lookup an idmap_domain give a full user or group SID
753  ******************************************************************************/
754
755 static struct idmap_domain* find_idmap_domain_from_sid( DOM_SID *account_sid )
756 {
757         DOM_SID domain_sid;
758         uint32 rid;
759         struct winbindd_domain *domain = NULL;
760         int i;
761         
762         /* 1. Handle BUILTIN or Special SIDs and prevent them from
763            falling into the default domain space (if we have a
764            configured passdb backend. */
765
766         if ( (pdb_dom_num != -1) && 
767              (sid_check_is_in_builtin(account_sid) ||
768               sid_check_is_in_wellknown_domain(account_sid) ||
769               sid_check_is_in_unix_groups(account_sid) ||
770               sid_check_is_in_unix_users(account_sid)) ) 
771         {
772                 return idmap_domains[pdb_dom_num];
773         }
774
775         /* 2. Lookup the winbindd_domain from the account_sid */
776
777         sid_copy( &domain_sid, account_sid );
778         sid_split_rid( &domain_sid, &rid );     
779         domain = find_domain_from_sid_noinit( &domain_sid );    
780
781         for (i = 0; domain && i < num_domains; i++) {
782                 if ( strequal( idmap_domains[i]->name, domain->name ) ) {
783                         return idmap_domains[i];
784                 }
785         }
786
787         /* 3. Fall back to the default domain */
788
789         if ( def_dom_num != -1 ) {
790                 return idmap_domains[def_dom_num];
791         }
792
793         return NULL;
794 }
795
796 /******************************************************************************
797  Lookup an index given an idmap_domain pointer
798  ******************************************************************************/
799
800 static uint32 find_idmap_domain_index( struct idmap_domain *id_domain)
801 {
802         int i;
803         
804         for (i = 0; i < num_domains; i++) {
805                 if ( idmap_domains[i] == id_domain )
806                         return i;               
807         }
808
809         return -1;      
810 }
811
812
813 /*********************************************************
814  Check if creating a mapping is permitted for the domain
815 *********************************************************/
816
817 static NTSTATUS idmap_can_map(const struct id_map *map, struct idmap_domain **ret_dom)
818 {
819         struct idmap_domain *dom;
820
821         /* Check we do not create mappings for our own local domain, or BUILTIN or special SIDs */
822         if ((sid_compare_domain(map->sid, get_global_sam_sid()) == 0) ||
823             sid_check_is_in_builtin(map->sid) ||
824             sid_check_is_in_wellknown_domain(map->sid) ||
825             sid_check_is_in_unix_users(map->sid) ||
826             sid_check_is_in_unix_groups(map->sid) ) 
827         {
828                 DEBUG(10, ("We are not supposed to create mappings for our own domains (local, builtin, specials)\n"));
829                 return NT_STATUS_UNSUCCESSFUL;
830         }
831
832         /* Special check for trusted domain only = Yes */
833         if (lp_winbind_trusted_domains_only()) {
834                 struct winbindd_domain *wdom = find_our_domain();
835                 if (wdom && (sid_compare_domain(map->sid, &wdom->sid) == 0)) {
836                         DEBUG(10, ("We are not supposed to create mappings for our primary domain when <trusted domain only> is True\n"));
837                         DEBUGADD(10, ("Leave [%s] unmapped\n", sid_string_static(map->sid)));
838                         return NT_STATUS_UNSUCCESSFUL;
839                 }
840         }
841
842         if ( (dom = find_idmap_domain_from_sid( map->sid )) == NULL ) {
843                 /* huh, couldn't find a suitable domain, let's just leave it unmapped */
844                 DEBUG(10, ("Could not find idmap backend for SID %s", sid_string_static(map->sid)));
845                 return NT_STATUS_NO_SUCH_DOMAIN;
846         }
847
848         if (dom->readonly) {
849                 /* ouch the domain is read only, let's just leave it unmapped */
850                 DEBUG(10, ("idmap backend for SID %s is READONLY!\n", sid_string_static(map->sid)));
851                 return NT_STATUS_UNSUCCESSFUL;
852         }
853
854         *ret_dom = dom;
855         return NT_STATUS_OK;
856 }
857
858 static NTSTATUS idmap_new_mapping(TALLOC_CTX *ctx, struct id_map *map)
859 {
860         NTSTATUS ret;
861         struct idmap_domain *dom;
862
863         /* If we are offline we cannot lookup SIDs, deny mapping */
864         if (idmap_is_offline()) {
865                 return NT_STATUS_FILE_IS_OFFLINE;
866         }
867
868         ret = idmap_can_map(map, &dom);
869         if ( ! NT_STATUS_IS_OK(ret)) {
870                 return NT_STATUS_NONE_MAPPED;
871         }
872
873         /* check if this is a valid SID and then map it */
874         switch (map->xid.type) {
875         case ID_TYPE_UID:
876                 ret = idmap_allocate_uid(&map->xid);
877                 if ( ! NT_STATUS_IS_OK(ret)) {
878                         /* can't allocate id, let's just leave it unmapped */
879                         DEBUG(2, ("uid allocation failed! Can't create mapping\n"));
880                         return NT_STATUS_NONE_MAPPED;
881                 }
882                 break;
883         case ID_TYPE_GID:
884                 ret = idmap_allocate_gid(&map->xid);
885                 if ( ! NT_STATUS_IS_OK(ret)) {
886                         /* can't allocate id, let's just leave it unmapped */
887                         DEBUG(2, ("gid allocation failed! Can't create mapping\n"));
888                         return NT_STATUS_NONE_MAPPED;
889                 }
890                 break;
891         default:
892                 /* invalid sid, let's just leave it unmapped */
893                 DEBUG(3,("idmap_new_mapping: Refusing to create a "
894                          "mapping for an unspecified ID type.\n"));             
895                 return NT_STATUS_NONE_MAPPED;
896         }
897
898         /* ok, got a new id, let's set a mapping */
899         map->status = ID_MAPPED;
900
901         DEBUG(10, ("Setting mapping: %s <-> %s %lu\n",
902                    sid_string_static(map->sid),
903                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
904                    (unsigned long)map->xid.id));
905         ret = dom->methods->set_mapping(dom, map);
906
907         if ( ! NT_STATUS_IS_OK(ret)) {
908                 /* something wrong here :-( */
909                 DEBUG(2, ("Failed to commit mapping\n!"));
910
911                 /* TODO: would it make sense to have an "unalloc_id function?" */
912
913                 return NT_STATUS_NONE_MAPPED;
914         }
915
916         return NT_STATUS_OK;
917 }
918
919 static NTSTATUS idmap_backends_set_mapping(const struct id_map *map)
920 {
921         struct idmap_domain *dom;
922         NTSTATUS ret;
923
924         DEBUG(10, ("Setting mapping %s <-> %s %lu\n",
925                    sid_string_static(map->sid),
926                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
927                    (unsigned long)map->xid.id));
928
929         ret = idmap_can_map(map, &dom);
930         if ( ! NT_STATUS_IS_OK(ret)) {
931                 return ret;
932         }
933
934         DEBUG(10,("set_mapping for domain %s\n", dom->name ));  
935
936         return dom->methods->set_mapping(dom, map);
937 }
938
939 static NTSTATUS idmap_backends_unixids_to_sids(struct id_map **ids)
940 {
941         struct idmap_domain *dom;
942         struct id_map **unmapped;
943         struct id_map **_ids;
944         TALLOC_CTX *ctx;
945         NTSTATUS ret;
946         int i, u, n;
947
948         if (!ids || !*ids) {
949                 DEBUG(1, ("Invalid list of maps\n"));
950                 return NT_STATUS_INVALID_PARAMETER;
951         }
952
953         ctx = talloc_named_const(NULL, 0, "idmap_backends_unixids_to_sids ctx");
954         if ( ! ctx) {
955                 DEBUG(0, ("Out of memory!\n"));
956                 return NT_STATUS_NO_MEMORY;
957         }
958
959         DEBUG(10, ("Query backends to map ids->sids\n"));
960
961         /* start from the default (the last one) and then if there are still
962          * unmapped entries cycle through the others */
963
964         _ids = ids;
965
966         unmapped = NULL;
967         for (n = num_domains-1; n >= 0; n--) { /* cycle backwards */
968
969                 dom = idmap_domains[n];
970
971                 DEBUG(10, ("Query sids from domain %s\n", dom->name));
972                 
973                 ret = dom->methods->unixids_to_sids(dom, _ids);
974                 IDMAP_REPORT_RET(ret);
975
976                 unmapped = NULL;
977
978                 for (i = 0, u = 0; _ids[i]; i++) {
979                         if (_ids[i]->status != ID_MAPPED) {
980                                 unmapped = talloc_realloc(ctx, unmapped, struct id_map *, u + 2);
981                                 IDMAP_CHECK_ALLOC(unmapped);
982                                 unmapped[u] = _ids[i];
983                                 u++;
984                         }
985                 }
986                 if (unmapped) {
987                         /* terminate the unmapped list */
988                         unmapped[u] = NULL;
989                 } else { /* no more entries, get out */
990                         break;
991                 }
992
993                 _ids = unmapped;
994                 
995         }
996
997         if (unmapped) {
998                 /* there are still unmapped ids, map them to the unix users/groups domains */
999                 /* except for expired entries, these will be returned as valid (offline mode) */
1000                 for (i = 0; unmapped[i]; i++) {
1001                         if (unmapped[i]->status == ID_EXPIRED) continue;
1002                         switch (unmapped[i]->xid.type) {
1003                         case ID_TYPE_UID:
1004                                 uid_to_unix_users_sid((uid_t)unmapped[i]->xid.id, unmapped[i]->sid);
1005                                 unmapped[i]->status = ID_MAPPED;
1006                                 break;
1007                         case ID_TYPE_GID:
1008                                 gid_to_unix_groups_sid((gid_t)unmapped[i]->xid.id, unmapped[i]->sid);
1009                                 unmapped[i]->status = ID_MAPPED;
1010                                 break;
1011                         default: /* what?! */
1012                                 unmapped[i]->status = ID_UNKNOWN;
1013                                 break;
1014                         }
1015                 }
1016         }
1017
1018         ret = NT_STATUS_OK;
1019
1020 done:
1021         talloc_free(ctx);
1022         return ret;
1023 }       
1024
1025 static NTSTATUS idmap_backends_sids_to_unixids(struct id_map **ids)
1026 {
1027         struct id_map ***dom_ids;
1028         struct idmap_domain *dom;
1029         TALLOC_CTX *ctx;
1030         NTSTATUS ret;
1031         int i, *counters;
1032
1033         if ( (ctx = talloc_named_const(NULL, 0, "be_sids_to_ids")) == NULL ) {
1034                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1035                 return NT_STATUS_NO_MEMORY;
1036         }
1037
1038         DEBUG(10, ("Query backends to map sids->ids\n"));
1039
1040         /* split list per domain */
1041         if (num_domains == 0) {
1042                 DEBUG(1, ("No domains available?\n"));
1043                 return NT_STATUS_UNSUCCESSFUL;
1044         }
1045
1046         dom_ids = TALLOC_ZERO_ARRAY(ctx, struct id_map **, num_domains);
1047         IDMAP_CHECK_ALLOC(dom_ids);
1048         counters = TALLOC_ZERO_ARRAY(ctx, int, num_domains);
1049         IDMAP_CHECK_ALLOC(counters);
1050
1051         /* partition the requests by domain */
1052
1053         for (i = 0; ids[i]; i++) {
1054                 uint32 idx;             
1055
1056                 if ( (dom = find_idmap_domain_from_sid( ids[i]->sid )) == NULL ) {
1057                         /* no available idmap_domain.  Move on */
1058                         continue;
1059                 }
1060
1061                 DEBUG(10,("SID %s is being handled by %s\n", 
1062                           sid_string_static(ids[i]->sid),  
1063                           dom ? dom->name : "none" ));
1064
1065                 idx = find_idmap_domain_index( dom );
1066                 SMB_ASSERT( idx != -1 );
1067                 
1068                 dom_ids[idx] = talloc_realloc(ctx, dom_ids[idx], 
1069                                               struct id_map *, counters[idx] + 2);
1070                 IDMAP_CHECK_ALLOC(dom_ids[idx]);
1071
1072                 dom_ids[idx][counters[idx]] = ids[i];
1073                 counters[idx]++;
1074                 dom_ids[idx][counters[idx]] = NULL;
1075         }
1076
1077         /* All the ids have been dispatched in the right queues.
1078            Let's cycle through the filled ones */
1079
1080         for (i = 0; i < num_domains; i++) {
1081                 if (dom_ids[i]) {
1082                         dom = idmap_domains[i];
1083                         DEBUG(10, ("Query ids from domain %s\n", dom->name));
1084                         ret = dom->methods->sids_to_unixids(dom, dom_ids[i]);
1085                         IDMAP_REPORT_RET(ret);
1086                 }
1087         }
1088
1089         /* ok all the backends have been contacted at this point */
1090         /* let's see if we have any unmapped SID left and act accordingly */
1091
1092         for (i = 0; ids[i]; i++) {
1093                 /* NOTE: this will NOT touch ID_EXPIRED entries that the backend
1094                  * was not able to confirm/deny (offline mode) */
1095                 if (ids[i]->status == ID_UNKNOWN || ids[i]->status == ID_UNMAPPED) {
1096                         /* ok this is an unmapped one, see if we can map it */
1097                         ret = idmap_new_mapping(ctx, ids[i]);
1098                         if (NT_STATUS_IS_OK(ret)) {
1099                                 /* successfully mapped */
1100                                 ids[i]->status = ID_MAPPED;
1101                         } else if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
1102                                 /* could not map it */
1103                                 ids[i]->status = ID_UNMAPPED;
1104                         } else {
1105                                 /* Something very bad happened down there
1106                                  * OR we are offline */
1107                                 ids[i]->status = ID_UNKNOWN;
1108                         }
1109                 }
1110         }
1111
1112         ret = NT_STATUS_OK;
1113
1114 done:
1115         talloc_free(ctx);
1116         return ret;
1117 }       
1118
1119 /**************************************************************************
1120  idmap interface functions
1121 **************************************************************************/
1122
1123 NTSTATUS idmap_unixids_to_sids(struct id_map **ids)
1124 {
1125         TALLOC_CTX *ctx;
1126         NTSTATUS ret;
1127         struct id_map **bids;
1128         int i, bi;
1129         int bn = 0;
1130         struct winbindd_domain *our_domain = find_our_domain(); 
1131
1132         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1133                 return ret;
1134         }
1135
1136         if (!ids || !*ids) {
1137                 DEBUG(1, ("Invalid list of maps\n"));
1138                 return NT_STATUS_INVALID_PARAMETER;
1139         }
1140
1141         ctx = talloc_named_const(NULL, 0, "idmap_unixids_to_sids ctx");
1142         if ( ! ctx) {
1143                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1144                 return NT_STATUS_NO_MEMORY;
1145         }
1146
1147         /* no ids to be asked to the backends by default */
1148         bids = NULL;
1149         bi = 0;
1150         
1151         for (i = 0; ids[i]; i++) {
1152
1153                 if ( ! ids[i]->sid) {
1154                         DEBUG(1, ("invalid null SID in id_map array"));
1155                         talloc_free(ctx);
1156                         return NT_STATUS_INVALID_PARAMETER;
1157                 }
1158
1159                 ret = idmap_cache_map_id(idmap_cache, ids[i]);
1160
1161                 if ( ! NT_STATUS_IS_OK(ret)) {
1162
1163                         if ( ! bids) {
1164                                 /* alloc space for ids to be resolved by backends (realloc ten by ten) */
1165                                 bids = TALLOC_ARRAY(ctx, struct id_map *, 10);
1166                                 if ( ! bids) {
1167                                         DEBUG(1, ("Out of memory!\n"));
1168                                         talloc_free(ctx);
1169                                         return NT_STATUS_NO_MEMORY;
1170                                 }
1171                                 bn = 10;
1172                         }
1173
1174                         /* add this id to the ones to be retrieved from the backends */
1175                         bids[bi] = ids[i];
1176                         bi++;
1177         
1178                         /* check if we need to allocate new space on the rids array */
1179                         if (bi == bn) {
1180                                 bn += 10;
1181                                 bids = talloc_realloc(ctx, bids, struct id_map *, bn);
1182                                 if ( ! bids) {
1183                                         DEBUG(1, ("Out of memory!\n"));
1184                                         talloc_free(ctx);
1185                                         return NT_STATUS_NO_MEMORY;
1186                                 }
1187                         }
1188
1189                         /* make sure the last element is NULL */
1190                         bids[bi] = NULL;
1191                 }
1192         }
1193
1194         /* let's see if there is any id mapping to be retieved from the backends */
1195         if (bi) {
1196                 /* Only do query if we are online */
1197                 if ( IS_DOMAIN_OFFLINE(our_domain) ) {
1198                         ret = NT_STATUS_FILE_IS_OFFLINE;
1199                         goto done;
1200                 }
1201
1202                 ret = idmap_backends_unixids_to_sids(bids);
1203                 IDMAP_CHECK_RET(ret);
1204
1205                 /* update the cache */
1206                 for (i = 0; i < bi; i++) {
1207                         if (bids[i]->status == ID_MAPPED) {
1208                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1209                         } else if (bids[i]->status == ID_EXPIRED) {
1210                                 /* the cache returned an expired entry and the backend was
1211                                  * was not able to clear the situation (offline).
1212                                  * This handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
1213                                  * for disconnected mode, */
1214                                 bids[i]->status = ID_MAPPED;
1215                         } else if (bids[i]->status == ID_UNKNOWN) {
1216                                 /* something bad here. We were not able to handle this for some
1217                                  * reason, mark it as unmapped and hope next time things will
1218                                  * settle down. */
1219                                 bids[i]->status = ID_UNMAPPED;
1220                         } else { /* unmapped */
1221                                 ret = idmap_cache_set_negative_id(idmap_cache, bids[i]);
1222                         }
1223                         IDMAP_CHECK_RET(ret);
1224                 }
1225         }
1226
1227         ret = NT_STATUS_OK;
1228 done:
1229         talloc_free(ctx);
1230         return ret;
1231 }
1232
1233 NTSTATUS idmap_sids_to_unixids(struct id_map **ids)
1234 {
1235         TALLOC_CTX *ctx;
1236         NTSTATUS ret;
1237         struct id_map **bids;
1238         int i, bi;
1239         int bn = 0;
1240         struct winbindd_domain *our_domain = find_our_domain(); 
1241
1242         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1243                 return ret;
1244         }
1245
1246         if (!ids || !*ids) {
1247                 DEBUG(1, ("Invalid list of maps\n"));
1248                 return NT_STATUS_INVALID_PARAMETER;
1249         }
1250
1251         ctx = talloc_named_const(NULL, 0, "idmap_sids_to_unixids ctx");
1252         if ( ! ctx) {
1253                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1254                 return NT_STATUS_NO_MEMORY;
1255         }
1256
1257         /* no ids to be asked to the backends by default */
1258         bids = NULL;
1259         bi = 0;
1260         
1261         for (i = 0; ids[i]; i++) {
1262
1263                 if ( ! ids[i]->sid) {
1264                         DEBUG(1, ("invalid null SID in id_map array\n"));
1265                         talloc_free(ctx);
1266                         return NT_STATUS_INVALID_PARAMETER;
1267                 }
1268
1269                 ret = idmap_cache_map_sid(idmap_cache, ids[i]);
1270
1271                 if ( ! NT_STATUS_IS_OK(ret)) {
1272
1273                         if ( ! bids) {
1274                                 /* alloc space for ids to be resolved
1275                                    by backends (realloc ten by ten) */
1276                                 bids = TALLOC_ARRAY(ctx, struct id_map *, 10);
1277                                 if ( ! bids) {
1278                                         DEBUG(1, ("Out of memory!\n"));
1279                                         talloc_free(ctx);
1280                                         return NT_STATUS_NO_MEMORY;
1281                                 }
1282                                 bn = 10;
1283                         }
1284
1285                         /* add this id to the ones to be retrieved from the backends */
1286                         bids[bi] = ids[i];
1287                         bi++;
1288
1289                         /* check if we need to allocate new space on the ids array */
1290                         if (bi == bn) {
1291                                 bn += 10;
1292                                 bids = talloc_realloc(ctx, bids, struct id_map *, bn);
1293                                 if ( ! bids) {
1294                                         DEBUG(1, ("Out of memory!\n"));
1295                                         talloc_free(ctx);
1296                                         return NT_STATUS_NO_MEMORY;
1297                                 }
1298                         }
1299
1300                         /* make sure the last element is NULL */
1301                         bids[bi] = NULL;
1302                 }
1303         }
1304
1305         /* let's see if there is any id mapping to be retieved from the backends */
1306         if (bids) {
1307                 /* Only do query if we are online */
1308                 if ( IS_DOMAIN_OFFLINE(our_domain) ) {
1309                         ret = NT_STATUS_FILE_IS_OFFLINE;
1310                         goto done;
1311                 }
1312                 
1313                 ret = idmap_backends_sids_to_unixids(bids);
1314                 IDMAP_CHECK_RET(ret);
1315
1316                 /* update the cache */
1317                 for (i = 0; bids[i]; i++) {
1318                         if (bids[i]->status == ID_MAPPED) {
1319                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1320                         } else if (bids[i]->status == ID_EXPIRED) {
1321                                 /* the cache returned an expired entry and the backend was
1322                                  * was not able to clear the situation (offline).
1323                                  * This handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
1324                                  * for disconnected mode, */
1325                                 bids[i]->status = ID_MAPPED;
1326                         } else if (bids[i]->status == ID_UNKNOWN) {
1327                                 /* something bad here. We were not able to handle this for some
1328                                  * reason, mark it as unmapped and hope next time things will
1329                                  * settle down. */
1330                                 bids[i]->status = ID_UNMAPPED;
1331                         } else { /* unmapped */
1332                                 ret = idmap_cache_set_negative_sid(idmap_cache, bids[i]);
1333                         }
1334                         IDMAP_CHECK_RET(ret);
1335                 }
1336         }
1337
1338         ret = NT_STATUS_OK;
1339 done:
1340         talloc_free(ctx);
1341         return ret;
1342 }
1343
1344 NTSTATUS idmap_set_mapping(const struct id_map *id)
1345 {
1346         TALLOC_CTX *ctx;
1347         NTSTATUS ret;
1348
1349         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1350                 return ret;
1351         }
1352
1353         /* sanity checks */
1354         if ((id->sid == NULL) || (id->status != ID_MAPPED)) {
1355                 DEBUG(1, ("NULL SID or unmapped entry\n"));
1356                 return NT_STATUS_INVALID_PARAMETER;
1357         }
1358
1359         /* TODO: check uid/gid range ? */
1360
1361         ctx = talloc_named_const(NULL, 0, "idmap_set_mapping ctx");
1362         if ( ! ctx) {
1363                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1364                 return NT_STATUS_NO_MEMORY;
1365         }
1366
1367         /* set the new mapping */
1368         ret = idmap_backends_set_mapping(id);
1369         IDMAP_CHECK_RET(ret);
1370
1371         /* set the mapping in the cache */
1372         ret = idmap_cache_set(idmap_cache, id);
1373         IDMAP_CHECK_RET(ret);
1374
1375 done:
1376         talloc_free(ctx);
1377         return ret;
1378 }
1379
1380 /**************************************************************************
1381  Dump backend status.
1382 **************************************************************************/
1383
1384 void idmap_dump_maps(char *logfile)
1385 {
1386         NTSTATUS ret;
1387         struct unixid allid;
1388         struct id_map *maps;
1389         int num_maps;
1390         FILE *dump;
1391         int i;
1392
1393         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1394                 return;
1395         }
1396
1397         dump = fopen(logfile, "w");
1398         if ( ! dump) {
1399                 DEBUG(0, ("Unable to open open stream for file [%s], errno: %d\n", logfile, errno));
1400                 return;
1401         }
1402
1403         if (NT_STATUS_IS_OK(ret = idmap_alloc_init())) {                
1404                 allid.type = ID_TYPE_UID;
1405                 allid.id = 0;
1406                 idmap_alloc_ctx->methods->get_id_hwm(&allid);
1407                 fprintf(dump, "USER HWM %lu\n", (unsigned long)allid.id);
1408                 
1409                 allid.type = ID_TYPE_GID;
1410                 allid.id = 0;
1411                 idmap_alloc_ctx->methods->get_id_hwm(&allid);
1412                 fprintf(dump, "GROUP HWM %lu\n", (unsigned long)allid.id);
1413         }
1414         
1415         maps = talloc(idmap_ctx, struct id_map);
1416         num_maps = 0;
1417
1418         for (i = 0; i < num_domains; i++) {
1419                 if (idmap_domains[i]->methods->dump_data) {
1420                         idmap_domains[i]->methods->dump_data(idmap_domains[i], &maps, &num_maps);
1421                 }
1422         }
1423
1424         for (i = 0; i < num_maps; i++) {
1425                 switch (maps[i].xid.type) {
1426                 case ID_TYPE_UID:
1427                         fprintf(dump, "UID %lu %s\n",
1428                                 (unsigned long)maps[i].xid.id,
1429                                 sid_string_static(maps[i].sid));
1430                         break;
1431                 case ID_TYPE_GID:
1432                         fprintf(dump, "GID %lu %s\n",
1433                                 (unsigned long)maps[i].xid.id,
1434                                 sid_string_static(maps[i].sid));
1435                         break;
1436                 case ID_TYPE_NOT_SPECIFIED:
1437                         break;
1438                 }
1439         }
1440
1441         fflush(dump);
1442         fclose(dump);
1443 }
1444
1445 char *idmap_fetch_secret(const char *backend, bool alloc,
1446                                const char *domain, const char *identity)
1447 {
1448         char *tmp, *ret;
1449         int r;
1450
1451         if (alloc) {
1452                 r = asprintf(&tmp, "IDMAP_ALLOC_%s", backend);
1453         } else {
1454                 r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
1455         }
1456
1457         if (r < 0) 
1458                 return NULL;
1459
1460         strupper_m(tmp); /* make sure the key is case insensitive */
1461         ret = secrets_fetch_generic(tmp, identity);
1462
1463         SAFE_FREE( tmp );       
1464
1465         return ret;
1466 }
1467