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