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