r22713: Offline logon fixes for idmap manager:
[samba.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         
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                 DEBUG(10, ("We are not supposed to create mappings for our own domains (local, builtin, specials)\n"));
826                 return NT_STATUS_UNSUCCESSFUL;
827         }
828
829         /* Special check for trusted domain only = Yes */
830         if (lp_winbind_trusted_domains_only()) {
831                 struct winbindd_domain *wdom = find_our_domain();
832                 if (wdom && (sid_compare_domain(map->sid, &wdom->sid) == 0)) {
833                         DEBUG(10, ("We are not supposed to create mappings for our primary domain when <trusted domain only> is True\n"));
834                         DEBUGADD(10, ("Leave [%s] unmapped\n", sid_string_static(map->sid)));
835                         return NT_STATUS_UNSUCCESSFUL;
836                 }
837         }
838
839         if ( (dom = find_idmap_domain_from_sid( map->sid )) == NULL ) {
840                 /* huh, couldn't find a suitable domain, let's just leave it unmapped */
841                 DEBUG(10, ("Could not find idmap backend for SID %s", sid_string_static(map->sid)));
842                 return NT_STATUS_NO_SUCH_DOMAIN;
843         }
844
845         if (dom->readonly) {
846                 /* ouch the domain is read only, let's just leave it unmapped */
847                 DEBUG(10, ("idmap backend for SID %s is READONLY!\n", sid_string_static(map->sid)));
848                 return NT_STATUS_UNSUCCESSFUL;
849         }
850
851         *ret_dom = dom;
852         return NT_STATUS_OK;
853 }
854
855 static NTSTATUS idmap_new_mapping(TALLOC_CTX *ctx, struct id_map *map)
856 {
857         NTSTATUS ret;
858         struct idmap_domain *dom;
859
860         /* If we are offline we cannot lookup SIDs, deny mapping */
861         if (idmap_is_offline()) {
862                 return NT_STATUS_FILE_IS_OFFLINE;
863         }
864
865         ret = idmap_can_map(map, &dom);
866         if ( ! NT_STATUS_IS_OK(ret)) {
867                 return NT_STATUS_NONE_MAPPED;
868         }
869
870         /* check if this is a valid SID and then map it */
871         switch (map->xid.type) {
872         case ID_TYPE_UID:
873                 ret = idmap_allocate_uid(&map->xid);
874                 if ( ! NT_STATUS_IS_OK(ret)) {
875                         /* can't allocate id, let's just leave it unmapped */
876                         DEBUG(2, ("uid allocation failed! Can't create mapping\n"));
877                         return NT_STATUS_NONE_MAPPED;
878                 }
879                 break;
880         case ID_TYPE_GID:
881                 ret = idmap_allocate_gid(&map->xid);
882                 if ( ! NT_STATUS_IS_OK(ret)) {
883                         /* can't allocate id, let's just leave it unmapped */
884                         DEBUG(2, ("gid allocation failed! Can't create mapping\n"));
885                         return NT_STATUS_NONE_MAPPED;
886                 }
887                 break;
888         default:
889                 /* invalid sid, let's just leave it unmapped */
890                 DEBUG(3,("idmap_new_mapping: Refusing to create a "
891                          "mapping for an unspecified ID type.\n"));             
892                 return NT_STATUS_NONE_MAPPED;
893         }
894
895         /* ok, got a new id, let's set a mapping */
896         map->status = ID_MAPPED;
897
898         DEBUG(10, ("Setting mapping: %s <-> %s %lu\n",
899                    sid_string_static(map->sid),
900                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
901                    (unsigned long)map->xid.id));
902         ret = dom->methods->set_mapping(dom, map);
903
904         if ( ! NT_STATUS_IS_OK(ret)) {
905                 /* something wrong here :-( */
906                 DEBUG(2, ("Failed to commit mapping\n!"));
907
908                 /* TODO: would it make sense to have an "unalloc_id function?" */
909
910                 return NT_STATUS_NONE_MAPPED;
911         }
912
913         return NT_STATUS_OK;
914 }
915
916 static NTSTATUS idmap_backends_set_mapping(const struct id_map *map)
917 {
918         struct idmap_domain *dom;
919         NTSTATUS ret;
920
921         DEBUG(10, ("Setting mapping %s <-> %s %lu\n",
922                    sid_string_static(map->sid),
923                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
924                    (unsigned long)map->xid.id));
925
926         ret = idmap_can_map(map, &dom);
927         if ( ! NT_STATUS_IS_OK(ret)) {
928                 return ret;
929         }
930
931         DEBUG(10,("set_mapping for domain %s\n", dom->name ));  
932
933         return dom->methods->set_mapping(dom, map);
934 }
935
936 static NTSTATUS idmap_backends_unixids_to_sids(struct id_map **ids)
937 {
938         struct idmap_domain *dom;
939         struct id_map **unmapped;
940         struct id_map **_ids;
941         TALLOC_CTX *ctx;
942         NTSTATUS ret;
943         int i, u, n;
944
945         if (!ids || !*ids) {
946                 DEBUG(1, ("Invalid list of maps\n"));
947                 return NT_STATUS_INVALID_PARAMETER;
948         }
949
950         ctx = talloc_named_const(NULL, 0, "idmap_backends_unixids_to_sids ctx");
951         if ( ! ctx) {
952                 DEBUG(0, ("Out of memory!\n"));
953                 return NT_STATUS_NO_MEMORY;
954         }
955
956         DEBUG(10, ("Query backends to map ids->sids\n"));
957
958         /* start from the default (the last one) and then if there are still
959          * unmapped entries cycle through the others */
960
961         _ids = ids;
962
963         unmapped = NULL;
964         for (n = num_domains-1; n >= 0; n--) { /* cycle backwards */
965
966                 dom = idmap_domains[n];
967
968                 DEBUG(10, ("Query sids from domain %s\n", dom->name));
969                 
970                 ret = dom->methods->unixids_to_sids(dom, _ids);
971                 IDMAP_REPORT_RET(ret);
972
973                 unmapped = NULL;
974
975                 for (i = 0, u = 0; _ids[i]; i++) {
976                         if (_ids[i]->status != ID_MAPPED) {
977                                 unmapped = talloc_realloc(ctx, unmapped, struct id_map *, u + 2);
978                                 IDMAP_CHECK_ALLOC(unmapped);
979                                 unmapped[u] = _ids[i];
980                                 u++;
981                         }
982                 }
983                 if (unmapped) {
984                         /* terminate the unmapped list */
985                         unmapped[u] = NULL;
986                 } else { /* no more entries, get out */
987                         break;
988                 }
989
990                 _ids = unmapped;
991                 
992         }
993
994         if (unmapped) {
995                 /* there are still unmapped ids, map them to the unix users/groups domains */
996                 /* except for expired entries, these will be returned as valid (offline mode) */
997                 for (i = 0; unmapped[i]; i++) {
998                         if (unmapped[i]->status == ID_EXPIRED) continue;
999                         switch (unmapped[i]->xid.type) {
1000                         case ID_TYPE_UID:
1001                                 uid_to_unix_users_sid((uid_t)unmapped[i]->xid.id, unmapped[i]->sid);
1002                                 unmapped[i]->status = ID_MAPPED;
1003                                 break;
1004                         case ID_TYPE_GID:
1005                                 gid_to_unix_groups_sid((gid_t)unmapped[i]->xid.id, unmapped[i]->sid);
1006                                 unmapped[i]->status = ID_MAPPED;
1007                                 break;
1008                         default: /* what?! */
1009                                 unmapped[i]->status = ID_UNKNOWN;
1010                                 break;
1011                         }
1012                 }
1013         }
1014
1015         ret = NT_STATUS_OK;
1016
1017 done:
1018         talloc_free(ctx);
1019         return ret;
1020 }       
1021
1022 static NTSTATUS idmap_backends_sids_to_unixids(struct id_map **ids)
1023 {
1024         struct id_map ***dom_ids;
1025         struct idmap_domain *dom;
1026         TALLOC_CTX *ctx;
1027         NTSTATUS ret;
1028         int i, *counters;
1029
1030         if ( (ctx = talloc_named_const(NULL, 0, "be_sids_to_ids")) == NULL ) {
1031                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1032                 return NT_STATUS_NO_MEMORY;
1033         }
1034
1035         DEBUG(10, ("Query backends to map sids->ids\n"));
1036
1037         /* split list per domain */
1038         if (num_domains == 0) {
1039                 DEBUG(1, ("No domains available?\n"));
1040                 return NT_STATUS_UNSUCCESSFUL;
1041         }
1042
1043         dom_ids = TALLOC_ZERO_ARRAY(ctx, struct id_map **, num_domains);
1044         IDMAP_CHECK_ALLOC(dom_ids);
1045         counters = TALLOC_ZERO_ARRAY(ctx, int, num_domains);
1046         IDMAP_CHECK_ALLOC(counters);
1047
1048         /* partition the requests by domain */
1049
1050         for (i = 0; ids[i]; i++) {
1051                 uint32 idx;             
1052
1053                 if ( (dom = find_idmap_domain_from_sid( ids[i]->sid )) == NULL ) {
1054                         /* no available idmap_domain.  Move on */
1055                         continue;
1056                 }
1057
1058                 DEBUG(10,("SID %s is being handled by %s\n", 
1059                           sid_string_static(ids[i]->sid),  
1060                           dom ? dom->name : "none" ));
1061
1062                 idx = find_idmap_domain_index( dom );
1063                 SMB_ASSERT( idx != -1 );
1064                 
1065                 dom_ids[idx] = talloc_realloc(ctx, dom_ids[idx], 
1066                                               struct id_map *, counters[idx] + 2);
1067                 IDMAP_CHECK_ALLOC(dom_ids[idx]);
1068
1069                 dom_ids[idx][counters[idx]] = ids[i];
1070                 counters[idx]++;
1071                 dom_ids[idx][counters[idx]] = NULL;
1072         }
1073
1074         /* All the ids have been dispatched in the right queues.
1075            Let's cycle through the filled ones */
1076
1077         for (i = 0; i < num_domains; i++) {
1078                 if (dom_ids[i]) {
1079                         dom = idmap_domains[i];
1080                         DEBUG(10, ("Query ids from domain %s\n", dom->name));
1081                         ret = dom->methods->sids_to_unixids(dom, dom_ids[i]);
1082                         IDMAP_REPORT_RET(ret);
1083                 }
1084         }
1085
1086         /* ok all the backends have been contacted at this point */
1087         /* let's see if we have any unmapped SID left and act accordingly */
1088
1089         for (i = 0; ids[i]; i++) {
1090                 /* NOTE: this will NOT touch ID_EXPIRED entries that the backend
1091                  * was not able to confirm/deny (offline mode) */
1092                 if (ids[i]->status == ID_UNKNOWN || ids[i]->status == ID_UNMAPPED) {
1093                         /* ok this is an unmapped one, see if we can map it */
1094                         ret = idmap_new_mapping(ctx, ids[i]);
1095                         if (NT_STATUS_IS_OK(ret)) {
1096                                 /* successfully mapped */
1097                                 ids[i]->status = ID_MAPPED;
1098                         } else if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
1099                                 /* could not map it */
1100                                 ids[i]->status = ID_UNMAPPED;
1101                         } else {
1102                                 /* Something very bad happened down there
1103                                  * OR we are offline */
1104                                 ids[i]->status = ID_UNKNOWN;
1105                         }
1106                 }
1107         }
1108
1109         ret = NT_STATUS_OK;
1110
1111 done:
1112         talloc_free(ctx);
1113         return ret;
1114 }       
1115
1116 /**************************************************************************
1117  idmap interface functions
1118 **************************************************************************/
1119
1120 NTSTATUS idmap_unixids_to_sids(struct id_map **ids)
1121 {
1122         TALLOC_CTX *ctx;
1123         NTSTATUS ret;
1124         struct id_map **bids;
1125         int i, bi;
1126         int bn = 0;
1127         struct winbindd_domain *our_domain = find_our_domain(); 
1128
1129         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1130                 return ret;
1131         }
1132
1133         if (!ids || !*ids) {
1134                 DEBUG(1, ("Invalid list of maps\n"));
1135                 return NT_STATUS_INVALID_PARAMETER;
1136         }
1137
1138         ctx = talloc_named_const(NULL, 0, "idmap_unixids_to_sids ctx");
1139         if ( ! ctx) {
1140                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1141                 return NT_STATUS_NO_MEMORY;
1142         }
1143
1144         /* no ids to be asked to the backends by default */
1145         bids = NULL;
1146         bi = 0;
1147         
1148         for (i = 0; ids[i]; i++) {
1149
1150                 if ( ! ids[i]->sid) {
1151                         DEBUG(1, ("invalid null SID in id_map array"));
1152                         talloc_free(ctx);
1153                         return NT_STATUS_INVALID_PARAMETER;
1154                 }
1155
1156                 ret = idmap_cache_map_id(idmap_cache, ids[i]);
1157
1158                 if ( ! NT_STATUS_IS_OK(ret)) {
1159
1160                         if ( ! bids) {
1161                                 /* alloc space for ids to be resolved by backends (realloc ten by ten) */
1162                                 bids = TALLOC_ARRAY(ctx, struct id_map *, 10);
1163                                 if ( ! bids) {
1164                                         DEBUG(1, ("Out of memory!\n"));
1165                                         talloc_free(ctx);
1166                                         return NT_STATUS_NO_MEMORY;
1167                                 }
1168                                 bn = 10;
1169                         }
1170
1171                         /* add this id to the ones to be retrieved from the backends */
1172                         bids[bi] = ids[i];
1173                         bi++;
1174         
1175                         /* check if we need to allocate new space on the rids array */
1176                         if (bi == bn) {
1177                                 bn += 10;
1178                                 bids = talloc_realloc(ctx, bids, struct id_map *, bn);
1179                                 if ( ! bids) {
1180                                         DEBUG(1, ("Out of memory!\n"));
1181                                         talloc_free(ctx);
1182                                         return NT_STATUS_NO_MEMORY;
1183                                 }
1184                         }
1185
1186                         /* make sure the last element is NULL */
1187                         bids[bi] = NULL;
1188                 }
1189         }
1190
1191         /* let's see if there is any id mapping to be retieved from the backends */
1192         if (bi) {
1193                 /* Only do query if we are online */
1194                 if ( IS_DOMAIN_OFFLINE(our_domain) ) {
1195                         ret = NT_STATUS_FILE_IS_OFFLINE;
1196                         goto done;
1197                 }
1198
1199                 ret = idmap_backends_unixids_to_sids(bids);
1200                 IDMAP_CHECK_RET(ret);
1201
1202                 /* update the cache */
1203                 for (i = 0; i < bi; i++) {
1204                         if (bids[i]->status == ID_MAPPED) {
1205                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1206                         } else if (bids[i]->status == ID_EXPIRED) {
1207                                 /* the cache returned an expired entry and the backend was
1208                                  * was not able to clear the situation (offline).
1209                                  * This handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
1210                                  * for disconnected mode, */
1211                                 bids[i]->status = ID_MAPPED;
1212                         } else if (bids[i]->status == ID_UNKNOWN) {
1213                                 /* something bad here. We were not able to handle this for some
1214                                  * reason, mark it as unmapped and hope next time things will
1215                                  * settle down. */
1216                                 bids[i]->status = ID_UNMAPPED;
1217                         } else { /* unmapped */
1218                                 ret = idmap_cache_set_negative_id(idmap_cache, bids[i]);
1219                         }
1220                         IDMAP_CHECK_RET(ret);
1221                 }
1222         }
1223
1224         ret = NT_STATUS_OK;
1225 done:
1226         talloc_free(ctx);
1227         return ret;
1228 }
1229
1230 NTSTATUS idmap_sids_to_unixids(struct id_map **ids)
1231 {
1232         TALLOC_CTX *ctx;
1233         NTSTATUS ret;
1234         struct id_map **bids;
1235         int i, bi;
1236         int bn = 0;
1237         struct winbindd_domain *our_domain = find_our_domain(); 
1238
1239         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1240                 return ret;
1241         }
1242
1243         if (!ids || !*ids) {
1244                 DEBUG(1, ("Invalid list of maps\n"));
1245                 return NT_STATUS_INVALID_PARAMETER;
1246         }
1247
1248         ctx = talloc_named_const(NULL, 0, "idmap_sids_to_unixids ctx");
1249         if ( ! ctx) {
1250                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1251                 return NT_STATUS_NO_MEMORY;
1252         }
1253
1254         /* no ids to be asked to the backends by default */
1255         bids = NULL;
1256         bi = 0;
1257         
1258         for (i = 0; ids[i]; i++) {
1259
1260                 if ( ! ids[i]->sid) {
1261                         DEBUG(1, ("invalid null SID in id_map array\n"));
1262                         talloc_free(ctx);
1263                         return NT_STATUS_INVALID_PARAMETER;
1264                 }
1265
1266                 ret = idmap_cache_map_sid(idmap_cache, ids[i]);
1267
1268                 if ( ! NT_STATUS_IS_OK(ret)) {
1269
1270                         if ( ! bids) {
1271                                 /* alloc space for ids to be resolved
1272                                    by backends (realloc ten by ten) */
1273                                 bids = TALLOC_ARRAY(ctx, struct id_map *, 10);
1274                                 if ( ! bids) {
1275                                         DEBUG(1, ("Out of memory!\n"));
1276                                         talloc_free(ctx);
1277                                         return NT_STATUS_NO_MEMORY;
1278                                 }
1279                                 bn = 10;
1280                         }
1281
1282                         /* add this id to the ones to be retrieved from the backends */
1283                         bids[bi] = ids[i];
1284                         bi++;
1285
1286                         /* check if we need to allocate new space on the ids array */
1287                         if (bi == bn) {
1288                                 bn += 10;
1289                                 bids = talloc_realloc(ctx, bids, struct id_map *, bn);
1290                                 if ( ! bids) {
1291                                         DEBUG(1, ("Out of memory!\n"));
1292                                         talloc_free(ctx);
1293                                         return NT_STATUS_NO_MEMORY;
1294                                 }
1295                         }
1296
1297                         /* make sure the last element is NULL */
1298                         bids[bi] = NULL;
1299                 }
1300         }
1301
1302         /* let's see if there is any id mapping to be retieved from the backends */
1303         if (bids) {
1304                 /* Only do query if we are online */
1305                 if ( IS_DOMAIN_OFFLINE(our_domain) ) {
1306                         ret = NT_STATUS_FILE_IS_OFFLINE;
1307                         goto done;
1308                 }
1309                 
1310                 ret = idmap_backends_sids_to_unixids(bids);
1311                 IDMAP_CHECK_RET(ret);
1312
1313                 /* update the cache */
1314                 for (i = 0; bids[i]; i++) {
1315                         if (bids[i]->status == ID_MAPPED) {
1316                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1317                         } else if (bids[i]->status == ID_EXPIRED) {
1318                                 /* the cache returned an expired entry and the backend was
1319                                  * was not able to clear the situation (offline).
1320                                  * This handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
1321                                  * for disconnected mode, */
1322                                 bids[i]->status = ID_MAPPED;
1323                         } else if (bids[i]->status == ID_UNKNOWN) {
1324                                 /* something bad here. We were not able to handle this for some
1325                                  * reason, mark it as unmapped and hope next time things will
1326                                  * settle down. */
1327                                 bids[i]->status = ID_UNMAPPED;
1328                         } else { /* unmapped */
1329                                 ret = idmap_cache_set_negative_sid(idmap_cache, bids[i]);
1330                         }
1331                         IDMAP_CHECK_RET(ret);
1332                 }
1333         }
1334
1335         ret = NT_STATUS_OK;
1336 done:
1337         talloc_free(ctx);
1338         return ret;
1339 }
1340
1341 NTSTATUS idmap_set_mapping(const struct id_map *id)
1342 {
1343         TALLOC_CTX *ctx;
1344         NTSTATUS ret;
1345
1346         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1347                 return ret;
1348         }
1349
1350         /* sanity checks */
1351         if ((id->sid == NULL) || (id->status != ID_MAPPED)) {
1352                 DEBUG(1, ("NULL SID or unmapped entry\n"));
1353                 return NT_STATUS_INVALID_PARAMETER;
1354         }
1355
1356         /* TODO: check uid/gid range ? */
1357
1358         ctx = talloc_named_const(NULL, 0, "idmap_set_mapping ctx");
1359         if ( ! ctx) {
1360                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1361                 return NT_STATUS_NO_MEMORY;
1362         }
1363
1364         /* set the new mapping */
1365         ret = idmap_backends_set_mapping(id);
1366         IDMAP_CHECK_RET(ret);
1367
1368         /* set the mapping in the cache */
1369         ret = idmap_cache_set(idmap_cache, id);
1370         IDMAP_CHECK_RET(ret);
1371
1372 done:
1373         talloc_free(ctx);
1374         return ret;
1375 }
1376
1377 /**************************************************************************
1378  Dump backend status.
1379 **************************************************************************/
1380
1381 void idmap_dump_maps(char *logfile)
1382 {
1383         NTSTATUS ret;
1384         struct unixid allid;
1385         struct id_map *maps;
1386         int num_maps;
1387         FILE *dump;
1388         int i;
1389
1390         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1391                 return;
1392         }
1393
1394         dump = fopen(logfile, "w");
1395         if ( ! dump) {
1396                 DEBUG(0, ("Unable to open open stream for file [%s], errno: %d\n", logfile, errno));
1397                 return;
1398         }
1399
1400         if (NT_STATUS_IS_OK(ret = idmap_alloc_init())) {                
1401                 allid.type = ID_TYPE_UID;
1402                 allid.id = 0;
1403                 idmap_alloc_ctx->methods->get_id_hwm(&allid);
1404                 fprintf(dump, "USER HWM %lu\n", (unsigned long)allid.id);
1405                 
1406                 allid.type = ID_TYPE_GID;
1407                 allid.id = 0;
1408                 idmap_alloc_ctx->methods->get_id_hwm(&allid);
1409                 fprintf(dump, "GROUP HWM %lu\n", (unsigned long)allid.id);
1410         }
1411         
1412         maps = talloc(idmap_ctx, struct id_map);
1413         num_maps = 0;
1414
1415         for (i = 0; i < num_domains; i++) {
1416                 if (idmap_domains[i]->methods->dump_data) {
1417                         idmap_domains[i]->methods->dump_data(idmap_domains[i], &maps, &num_maps);
1418                 }
1419         }
1420
1421         for (i = 0; i < num_maps; i++) {
1422                 switch (maps[i].xid.type) {
1423                 case ID_TYPE_UID:
1424                         fprintf(dump, "UID %lu %s\n",
1425                                 (unsigned long)maps[i].xid.id,
1426                                 sid_string_static(maps[i].sid));
1427                         break;
1428                 case ID_TYPE_GID:
1429                         fprintf(dump, "GID %lu %s\n",
1430                                 (unsigned long)maps[i].xid.id,
1431                                 sid_string_static(maps[i].sid));
1432                         break;
1433                 case ID_TYPE_NOT_SPECIFIED:
1434                         break;
1435                 }
1436         }
1437
1438         fflush(dump);
1439         fclose(dump);
1440 }
1441
1442 char *idmap_fetch_secret(const char *backend, bool alloc,
1443                                const char *domain, const char *identity)
1444 {
1445         char *tmp, *ret;
1446         int r;
1447
1448         if (alloc) {
1449                 r = asprintf(&tmp, "IDMAP_ALLOC_%s", backend);
1450         } else {
1451                 r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
1452         }
1453
1454         if (r < 0) 
1455                 return NULL;
1456
1457         strupper_m(tmp); /* make sure the key is case insensitive */
1458         ret = secrets_fetch_generic(tmp, identity);
1459
1460         SAFE_FREE( tmp );       
1461
1462         return ret;
1463 }
1464