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