8b16f27f7dac147d36f8a118e37f5abab7aaed25
[metze/samba/wip.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 arguments */
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         /* on DCs we need to add idmap_tdb as the default backend if compat is
526          * defined (when the old implicit configuration is used)
527          * This is not done in the previous loop a on member server we exclude
528          * the local domain. But on a DC the local domain is the only domain
529          * available therefore we are left with no default domain */
530         if (((lp_server_role() == ROLE_DOMAIN_PDC) ||
531              (lp_server_role() == ROLE_DOMAIN_BDC)) &&
532             ((num_domains == 0) && (compat == 1))) {
533
534                 dom = TALLOC_ZERO_P(idmap_ctx, struct idmap_domain);
535                 IDMAP_CHECK_ALLOC(dom);
536
537                 dom->name = talloc_strdup(dom, "__default__");
538                 IDMAP_CHECK_ALLOC(dom->name);
539
540                 dom->default_domain = True;
541                 dom->readonly = False;
542
543                 /* get the backend methods for this domain */
544                 dom->methods = get_methods(backends, compat_backend);
545
546                 if ( ! dom->methods) {
547                         ret = smb_probe_module("idmap", compat_backend);
548                         if (NT_STATUS_IS_OK(ret)) {
549                                 dom->methods = get_methods(backends,
550                                                            compat_backend);
551                         }
552                 }
553                 if ( ! dom->methods) {
554                         DEBUG(0, ("ERROR: Could not get methods for "
555                                   "backend %s\n", compat_backend));
556                         ret = NT_STATUS_UNSUCCESSFUL;
557                         goto done;
558                 }
559
560                 /* now that we have methods,
561                  * set the destructor for this domain */
562                 talloc_set_destructor(dom, close_domain_destructor);
563
564                 dom->params = talloc_strdup(dom, compat_params);
565                 IDMAP_CHECK_ALLOC(dom->params);
566
567                 /* Finally instance a backend copy for this domain */
568                 ret = dom->methods->init(dom);
569                 if ( ! NT_STATUS_IS_OK(ret)) {
570                         DEBUG(0, ("ERROR: Initialization failed for backend "
571                                   "%s (domain %s), deferred!\n",
572                                   compat_backend, dom->name));
573                 }
574                 idmap_domains = talloc_realloc(idmap_ctx, idmap_domains,
575                                                 struct idmap_domain *, 2);
576                 if ( ! idmap_domains) {
577                         DEBUG(0, ("Out of memory!\n"));
578                         ret = NT_STATUS_NO_MEMORY;
579                         goto done;
580                 }
581                 idmap_domains[num_domains] = dom;
582
583                 def_dom_num = num_domains;
584
585                 /* Bump counter to next available slot */
586
587                 num_domains++;
588
589                 DEBUG(10, ("Domain %s - Backend %s - %sdefault - %sreadonly\n",
590                                 dom->name, compat_backend,
591                                 dom->default_domain?"":"not ",
592                                 dom->readonly?"":"not "));
593         }
594
595         /* automatically add idmap_nss backend if needed */
596         if ((lp_server_role() == ROLE_DOMAIN_MEMBER) &&
597             ( ! pri_dom_is_in_list) &&
598             lp_winbind_trusted_domains_only()) {
599
600                 dom = TALLOC_ZERO_P(idmap_ctx, struct idmap_domain);
601                 IDMAP_CHECK_ALLOC(dom);
602
603                 dom->name = talloc_strdup(dom, lp_workgroup());
604                 IDMAP_CHECK_ALLOC(dom->name);
605
606                 dom->default_domain = False;
607                 dom->readonly = True;
608
609                 /* get the backend methods for passdb */
610                 dom->methods = get_methods(backends, "nss");
611
612                 /* (the nss module is always statically linked) */
613                 if ( ! dom->methods) {
614                         DEBUG(0, ("ERROR: No methods for idmap_nss ?!\n"));
615                         ret = NT_STATUS_UNSUCCESSFUL;
616                         goto done;
617                 }
618
619                 /* now that we have methods,
620                  * set the destructor for this domain */
621                 talloc_set_destructor(dom, close_domain_destructor);
622
623                 if (compat_params) {
624                         dom->params = talloc_strdup(dom, compat_params);
625                         IDMAP_CHECK_ALLOC(dom->params);
626                 } else {
627                         dom->params = NULL;
628                 }
629
630                 /* Finally instance a backend copy for this domain */
631                 ret = dom->methods->init(dom);
632                 if ( ! NT_STATUS_IS_OK(ret)) {
633                         DEBUG(0, ("ERROR: Init. failed for idmap_nss ?!\n"));
634                         ret = NT_STATUS_UNSUCCESSFUL;
635                         goto done;
636                 }
637
638                 idmap_domains = talloc_realloc(idmap_ctx,
639                                                 idmap_domains,
640                                                 struct idmap_domain *,
641                                                 num_domains+1);
642                 if ( ! idmap_domains) {
643                         DEBUG(0, ("Out of memory!\n"));
644                         ret = NT_STATUS_NO_MEMORY;
645                         goto done;
646                 }
647                 idmap_domains[num_domains] = dom;
648
649                 DEBUG(10, ("Domain %s - Backend nss - not default - readonly\n",
650                            dom->name ));
651
652                 num_domains++;
653         }
654
655         /**** automatically add idmap_passdb backend ****/
656         dom = TALLOC_ZERO_P(idmap_ctx, struct idmap_domain);
657         IDMAP_CHECK_ALLOC(dom);
658
659         dom->name = talloc_strdup(dom, get_global_sam_name());
660         IDMAP_CHECK_ALLOC(dom->name);
661
662         dom->default_domain = False;
663         dom->readonly = True;
664
665         /* get the backend methods for passdb */
666         dom->methods = get_methods(backends, "passdb");
667
668         /* (the passdb module is always statically linked) */
669         if ( ! dom->methods) {
670                 DEBUG(0, ("ERROR: No methods for idmap_passdb ?!\n"));
671                 ret = NT_STATUS_UNSUCCESSFUL;
672                 goto done;
673         }
674
675         /* now that we have methods, set the destructor for this domain */
676         talloc_set_destructor(dom, close_domain_destructor);
677
678         if (compat_params) {
679                 dom->params = talloc_strdup(dom, compat_params);
680                 IDMAP_CHECK_ALLOC(dom->params);
681         } else {
682                 dom->params = NULL;
683         }
684
685         /* Finally instance a backend copy for this domain */
686         ret = dom->methods->init(dom);
687         if ( ! NT_STATUS_IS_OK(ret)) {
688                 DEBUG(0, ("ERROR: Init. failed for idmap_passdb ?!\n"));
689                 ret = NT_STATUS_UNSUCCESSFUL;
690                 goto done;
691         }
692
693         idmap_domains = talloc_realloc(idmap_ctx,
694                                         idmap_domains,
695                                         struct idmap_domain *,
696                                         num_domains+1);
697         if ( ! idmap_domains) {
698                 DEBUG(0, ("Out of memory!\n"));
699                 ret = NT_STATUS_NO_MEMORY;
700                 goto done;
701         }
702         idmap_domains[num_domains] = dom;
703
704         /* needed to handle special BUILTIN and wellknown SIDs cases */
705         pdb_dom_num = num_domains;
706
707         DEBUG(10, ("Domain %s - Backend passdb - not default - readonly\n",
708                    dom->name));
709
710         num_domains++;
711         /**** finished adding idmap_passdb backend ****/
712
713         /* sort domains so that the default is the last one */
714         /* don't sort if no default domain defined */
715         if (def_dom_num != -1 && def_dom_num != num_domains-1) {
716                 /* default is not last, move it */
717                 struct idmap_domain *tmp;
718
719                 if (pdb_dom_num > def_dom_num) {
720                         pdb_dom_num --;
721
722                 } else if (pdb_dom_num == def_dom_num) { /* ?? */
723                         pdb_dom_num = num_domains - 1;
724                 }
725
726                 tmp = idmap_domains[def_dom_num];
727
728                 for (i = def_dom_num; i < num_domains-1; i++) {
729                         idmap_domains[i] = idmap_domains[i+1];
730                 }
731                 idmap_domains[i] = tmp;
732                 def_dom_num = i;
733         }
734
735
736         /* Initialize alloc module */
737
738         DEBUG(3, ("Initializing idmap alloc module\n"));
739
740         alloc_backend = NULL;
741         if (compat) {
742                 alloc_backend = talloc_strdup(idmap_ctx, compat_backend);
743         } else {
744                 char *ab = lp_idmap_alloc_backend();
745
746                 if (ab && (ab[0] != '\0')) {
747                         alloc_backend = talloc_strdup(idmap_ctx,
748                                                       lp_idmap_alloc_backend());
749                 }
750         }
751
752         if ( alloc_backend ) {
753
754                 idmap_alloc_ctx = TALLOC_ZERO_P(idmap_ctx,
755                                                 struct idmap_alloc_context);
756                 IDMAP_CHECK_ALLOC(idmap_alloc_ctx);
757
758                 idmap_alloc_ctx->methods = get_alloc_methods(alloc_backends,
759                                                              alloc_backend);
760                 if ( ! idmap_alloc_ctx->methods) {
761                         ret = smb_probe_module("idmap", alloc_backend);
762                         if (NT_STATUS_IS_OK(ret)) {
763                                 idmap_alloc_ctx->methods =
764                                         get_alloc_methods(alloc_backends,
765                                                           alloc_backend);
766                         }
767                 }
768                 if (idmap_alloc_ctx->methods) {
769
770                         if (compat_params) {
771                                 idmap_alloc_ctx->params =
772                                         talloc_strdup(idmap_alloc_ctx,
773                                                       compat_params);
774                                 IDMAP_CHECK_ALLOC(idmap_alloc_ctx->params);
775                         } else {
776                                 idmap_alloc_ctx->params = NULL;
777                         }
778
779                         ret = idmap_alloc_ctx->methods->init(idmap_alloc_ctx->params);
780                         if ( ! NT_STATUS_IS_OK(ret)) {
781                                 DEBUG(0, ("ERROR: Initialization failed for "
782                                           "alloc backend %s, deferred!\n",
783                                           alloc_backend));
784                         } else {
785                                 idmap_alloc_ctx->initialized = True;
786                         }
787                 } else {
788                         DEBUG(2, ("idmap_init: Unable to get methods for "
789                                   "alloc backend %s\n",
790                                   alloc_backend));
791                         /* certain compat backends are just readonly */
792                         if ( compat ) {
793                                 TALLOC_FREE(idmap_alloc_ctx);
794                                 ret = NT_STATUS_OK;
795                         } else {
796                                 ret = NT_STATUS_UNSUCCESSFUL;
797                         }
798                 }
799         }
800
801         /* cleanup temporary strings */
802         TALLOC_FREE( compat_backend );
803
804         idmap_init_status = NT_STATUS_OK;
805
806         return ret;
807
808 done:
809         DEBUG(0, ("Aborting IDMAP Initialization ...\n"));
810         idmap_close();
811
812         return ret;
813 }
814
815 static NTSTATUS idmap_alloc_init(void)
816 {
817         NTSTATUS ret;
818
819         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
820                 return ret;
821         }
822
823         if ( ! idmap_alloc_ctx) {
824                 return NT_STATUS_NOT_SUPPORTED;
825         }
826
827         if ( ! idmap_alloc_ctx->initialized) {
828                 ret = idmap_alloc_ctx->methods->init(idmap_alloc_ctx->params);
829                 if ( ! NT_STATUS_IS_OK(ret)) {
830                         DEBUG(0, ("ERROR: Initialization failed for alloc "
831                                   "backend, deferred!\n"));
832                         return ret;
833                 } else {
834                         idmap_alloc_ctx->initialized = True;
835                 }
836         }
837
838         return NT_STATUS_OK;
839 }
840
841 /**************************************************************************
842  idmap allocator interface functions
843 **************************************************************************/
844
845 NTSTATUS idmap_allocate_uid(struct unixid *id)
846 {
847         NTSTATUS ret;
848
849         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
850                 return ret;
851         }
852
853         id->type = ID_TYPE_UID;
854         return idmap_alloc_ctx->methods->allocate_id(id);
855 }
856
857 NTSTATUS idmap_allocate_gid(struct unixid *id)
858 {
859         NTSTATUS ret;
860
861         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
862                 return ret;
863         }
864
865         id->type = ID_TYPE_GID;
866         return idmap_alloc_ctx->methods->allocate_id(id);
867 }
868
869 NTSTATUS idmap_set_uid_hwm(struct unixid *id)
870 {
871         NTSTATUS ret;
872
873         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
874                 return ret;
875         }
876
877         id->type = ID_TYPE_UID;
878         return idmap_alloc_ctx->methods->set_id_hwm(id);
879 }
880
881 NTSTATUS idmap_set_gid_hwm(struct unixid *id)
882 {
883         NTSTATUS ret;
884
885         if (! NT_STATUS_IS_OK(ret = idmap_alloc_init())) {
886                 return ret;
887         }
888
889         id->type = ID_TYPE_GID;
890         return idmap_alloc_ctx->methods->set_id_hwm(id);
891 }
892
893 /******************************************************************************
894  Lookup an idmap_domain give a full user or group SID
895  ******************************************************************************/
896
897 static struct idmap_domain* find_idmap_domain_from_sid( DOM_SID *account_sid )
898 {
899         DOM_SID domain_sid;
900         uint32 rid;
901         struct winbindd_domain *domain = NULL;
902         int i;
903
904         /* 1. Handle BUILTIN or Special SIDs and prevent them from
905            falling into the default domain space (if we have a
906            configured passdb backend. */
907
908         if ( (pdb_dom_num != -1) &&
909              (sid_check_is_in_builtin(account_sid) ||
910               sid_check_is_in_wellknown_domain(account_sid) ||
911               sid_check_is_in_unix_groups(account_sid) ||
912               sid_check_is_in_unix_users(account_sid)) )
913         {
914                 return idmap_domains[pdb_dom_num];
915         }
916
917         /* 2. Lookup the winbindd_domain from the account_sid */
918
919         sid_copy( &domain_sid, account_sid );
920         sid_split_rid( &domain_sid, &rid );
921         domain = find_domain_from_sid_noinit( &domain_sid );
922
923         for (i = 0; domain && i < num_domains; i++) {
924                 if ( strequal( idmap_domains[i]->name, domain->name ) ) {
925                         return idmap_domains[i];
926                 }
927         }
928
929         /* 3. Fall back to the default domain */
930
931         if ( def_dom_num != -1 ) {
932                 return idmap_domains[def_dom_num];
933         }
934
935         return NULL;
936 }
937
938 /******************************************************************************
939  Lookup an index given an idmap_domain pointer
940  ******************************************************************************/
941
942 static uint32 find_idmap_domain_index( struct idmap_domain *id_domain)
943 {
944         int i;
945
946         for (i = 0; i < num_domains; i++) {
947                 if ( idmap_domains[i] == id_domain )
948                         return i;
949         }
950
951         return -1;
952 }
953
954
955 /*********************************************************
956  Check if creating a mapping is permitted for the domain
957 *********************************************************/
958
959 static NTSTATUS idmap_can_map(const struct id_map *map,
960                               struct idmap_domain **ret_dom)
961 {
962         struct idmap_domain *dom;
963
964         /* Check we do not create mappings for our own local domain,
965          * or BUILTIN or special SIDs */
966         if ((sid_compare_domain(map->sid, get_global_sam_sid()) == 0) ||
967             sid_check_is_in_builtin(map->sid) ||
968             sid_check_is_in_wellknown_domain(map->sid) ||
969             sid_check_is_in_unix_users(map->sid) ||
970             sid_check_is_in_unix_groups(map->sid) )
971         {
972                 DEBUG(10, ("We are not supposed to create mappings for our own "
973                            "domains (local, builtin, specials)\n"));
974                 return NT_STATUS_UNSUCCESSFUL;
975         }
976
977         /* Special check for trusted domain only = Yes */
978         if (lp_winbind_trusted_domains_only()) {
979                 struct winbindd_domain *wdom = find_our_domain();
980                 if (wdom && (sid_compare_domain(map->sid, &wdom->sid) == 0)) {
981                         DEBUG(10, ("We are not supposed to create mappings for "
982                                    "our primary domain when <trusted domain "
983                                    "only> is True\n"));
984                         DEBUGADD(10, ("Leave [%s] unmapped\n",
985                                       sid_string_dbg(map->sid)));
986                         return NT_STATUS_UNSUCCESSFUL;
987                 }
988         }
989
990         if ( (dom = find_idmap_domain_from_sid( map->sid )) == NULL ) {
991                 /* huh, couldn't find a suitable domain,
992                  *  let's just leave it unmapped */
993                 DEBUG(10, ("Could not find idmap backend for SID %s\n",
994                            sid_string_dbg(map->sid)));
995                 return NT_STATUS_NO_SUCH_DOMAIN;
996         }
997
998         if (dom->readonly) {
999                 /* ouch the domain is read only,
1000                  *  let's just leave it unmapped */
1001                 DEBUG(10, ("idmap backend for SID %s is READONLY!\n",
1002                            sid_string_dbg(map->sid)));
1003                 return NT_STATUS_UNSUCCESSFUL;
1004         }
1005
1006         *ret_dom = dom;
1007         return NT_STATUS_OK;
1008 }
1009
1010 static NTSTATUS idmap_new_mapping(TALLOC_CTX *ctx, struct id_map *map)
1011 {
1012         NTSTATUS ret;
1013         struct idmap_domain *dom;
1014
1015         /* If we are offline we cannot lookup SIDs, deny mapping */
1016         if (idmap_is_offline()) {
1017                 return NT_STATUS_FILE_IS_OFFLINE;
1018         }
1019
1020         ret = idmap_can_map(map, &dom);
1021         if ( ! NT_STATUS_IS_OK(ret)) {
1022                 return NT_STATUS_NONE_MAPPED;
1023         }
1024
1025         /* check if this is a valid SID and then map it */
1026         switch (map->xid.type) {
1027         case ID_TYPE_UID:
1028                 ret = idmap_allocate_uid(&map->xid);
1029                 if ( ! NT_STATUS_IS_OK(ret)) {
1030                         /* can't allocate id, let's just leave it unmapped */
1031                         DEBUG(2, ("uid allocation failed! "
1032                                   "Can't create mapping\n"));
1033                         return NT_STATUS_NONE_MAPPED;
1034                 }
1035                 break;
1036         case ID_TYPE_GID:
1037                 ret = idmap_allocate_gid(&map->xid);
1038                 if ( ! NT_STATUS_IS_OK(ret)) {
1039                         /* can't allocate id, let's just leave it unmapped */
1040                         DEBUG(2, ("gid allocation failed! "
1041                                   "Can't create mapping\n"));
1042                         return NT_STATUS_NONE_MAPPED;
1043                 }
1044                 break;
1045         default:
1046                 /* invalid sid, let's just leave it unmapped */
1047                 DEBUG(3,("idmap_new_mapping: Refusing to create a "
1048                          "mapping for an unspecified ID type.\n"));
1049                 return NT_STATUS_NONE_MAPPED;
1050         }
1051
1052         /* ok, got a new id, let's set a mapping */
1053         map->status = ID_MAPPED;
1054
1055         DEBUG(10, ("Setting mapping: %s <-> %s %lu\n",
1056                    sid_string_dbg(map->sid),
1057                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
1058                    (unsigned long)map->xid.id));
1059         ret = dom->methods->set_mapping(dom, map);
1060
1061         if ( ! NT_STATUS_IS_OK(ret)) {
1062                 /* something wrong here :-( */
1063                 DEBUG(2, ("Failed to commit mapping\n!"));
1064
1065         /* TODO: would it make sense to have an "unalloc_id function?" */
1066
1067                 return NT_STATUS_NONE_MAPPED;
1068         }
1069
1070         return NT_STATUS_OK;
1071 }
1072
1073 static NTSTATUS idmap_backends_set_mapping(const struct id_map *map)
1074 {
1075         struct idmap_domain *dom;
1076         NTSTATUS ret;
1077
1078         DEBUG(10, ("Setting mapping %s <-> %s %lu\n",
1079                    sid_string_dbg(map->sid),
1080                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
1081                    (unsigned long)map->xid.id));
1082
1083         ret = idmap_can_map(map, &dom);
1084         if ( ! NT_STATUS_IS_OK(ret)) {
1085                 return ret;
1086         }
1087
1088         DEBUG(10,("set_mapping for domain %s\n", dom->name ));
1089
1090         return dom->methods->set_mapping(dom, map);
1091 }
1092
1093 static NTSTATUS idmap_backends_unixids_to_sids(struct id_map **ids)
1094 {
1095         struct idmap_domain *dom;
1096         struct id_map **unmapped;
1097         struct id_map **_ids;
1098         TALLOC_CTX *ctx;
1099         NTSTATUS ret;
1100         int i, u, n;
1101
1102         if (!ids || !*ids) {
1103                 DEBUG(1, ("Invalid list of maps\n"));
1104                 return NT_STATUS_INVALID_PARAMETER;
1105         }
1106
1107         ctx = talloc_named_const(NULL, 0, "idmap_backends_unixids_to_sids ctx");
1108         if ( ! ctx) {
1109                 DEBUG(0, ("Out of memory!\n"));
1110                 return NT_STATUS_NO_MEMORY;
1111         }
1112
1113         DEBUG(10, ("Query backends to map ids->sids\n"));
1114
1115         /* start from the default (the last one) and then if there are still
1116          * unmapped entries cycle through the others */
1117
1118         _ids = ids;
1119
1120         unmapped = NULL;
1121         for (n = num_domains-1; n >= 0; n--) { /* cycle backwards */
1122
1123                 dom = idmap_domains[n];
1124
1125                 DEBUG(10, ("Query sids from domain %s\n", dom->name));
1126
1127                 ret = dom->methods->unixids_to_sids(dom, _ids);
1128                 IDMAP_REPORT_RET(ret);
1129
1130                 unmapped = NULL;
1131
1132                 for (i = 0, u = 0; _ids[i]; i++) {
1133                         if (_ids[i]->status != ID_MAPPED) {
1134                                 unmapped = talloc_realloc(ctx, unmapped,
1135                                                         struct id_map *, u + 2);
1136                                 IDMAP_CHECK_ALLOC(unmapped);
1137                                 unmapped[u] = _ids[i];
1138                                 u++;
1139                         }
1140                 }
1141                 if (unmapped) {
1142                         /* terminate the unmapped list */
1143                         unmapped[u] = NULL;
1144                 } else { /* no more entries, get out */
1145                         break;
1146                 }
1147
1148                 _ids = unmapped;
1149
1150         }
1151
1152         if (unmapped) {
1153                 /* there are still unmapped ids,
1154                  * map them to the unix users/groups domains */
1155                 /* except for expired entries,
1156                  * these will be returned as valid (offline mode) */
1157                 for (i = 0; unmapped[i]; i++) {
1158                         if (unmapped[i]->status == ID_EXPIRED) continue;
1159                         switch (unmapped[i]->xid.type) {
1160                         case ID_TYPE_UID:
1161                                 uid_to_unix_users_sid(
1162                                                 (uid_t)unmapped[i]->xid.id,
1163                                                 unmapped[i]->sid);
1164                                 unmapped[i]->status = ID_MAPPED;
1165                                 break;
1166                         case ID_TYPE_GID:
1167                                 gid_to_unix_groups_sid(
1168                                                 (gid_t)unmapped[i]->xid.id,
1169                                                 unmapped[i]->sid);
1170                                 unmapped[i]->status = ID_MAPPED;
1171                                 break;
1172                         default: /* what?! */
1173                                 unmapped[i]->status = ID_UNKNOWN;
1174                                 break;
1175                         }
1176                 }
1177         }
1178
1179         ret = NT_STATUS_OK;
1180
1181 done:
1182         talloc_free(ctx);
1183         return ret;
1184 }
1185
1186 static NTSTATUS idmap_backends_sids_to_unixids(struct id_map **ids)
1187 {
1188         struct id_map ***dom_ids;
1189         struct idmap_domain *dom;
1190         TALLOC_CTX *ctx;
1191         NTSTATUS ret;
1192         int i, *counters;
1193
1194         if ( (ctx = talloc_named_const(NULL, 0, "be_sids_to_ids")) == NULL ) {
1195                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1196                 return NT_STATUS_NO_MEMORY;
1197         }
1198
1199         DEBUG(10, ("Query backends to map sids->ids\n"));
1200
1201         /* split list per domain */
1202         if (num_domains == 0) {
1203                 DEBUG(1, ("No domains available?\n"));
1204                 return NT_STATUS_UNSUCCESSFUL;
1205         }
1206
1207         dom_ids = TALLOC_ZERO_ARRAY(ctx, struct id_map **, num_domains);
1208         IDMAP_CHECK_ALLOC(dom_ids);
1209         counters = TALLOC_ZERO_ARRAY(ctx, int, num_domains);
1210         IDMAP_CHECK_ALLOC(counters);
1211
1212         /* partition the requests by domain */
1213
1214         for (i = 0; ids[i]; i++) {
1215                 uint32 idx;
1216
1217                 if ((dom = find_idmap_domain_from_sid(ids[i]->sid)) == NULL) {
1218                         /* no available idmap_domain.  Move on */
1219                         continue;
1220                 }
1221
1222                 DEBUG(10,("SID %s is being handled by %s\n",
1223                           sid_string_dbg(ids[i]->sid),
1224                           dom ? dom->name : "none" ));
1225
1226                 idx = find_idmap_domain_index( dom );
1227                 SMB_ASSERT( idx != -1 );
1228
1229                 dom_ids[idx] = talloc_realloc(ctx, dom_ids[idx],
1230                                               struct id_map *,
1231                                               counters[idx] + 2);
1232                 IDMAP_CHECK_ALLOC(dom_ids[idx]);
1233
1234                 dom_ids[idx][counters[idx]] = ids[i];
1235                 counters[idx]++;
1236                 dom_ids[idx][counters[idx]] = NULL;
1237         }
1238
1239         /* All the ids have been dispatched in the right queues.
1240            Let's cycle through the filled ones */
1241
1242         for (i = 0; i < num_domains; i++) {
1243                 if (dom_ids[i]) {
1244                         dom = idmap_domains[i];
1245                         DEBUG(10, ("Query ids from domain %s\n", dom->name));
1246                         ret = dom->methods->sids_to_unixids(dom, dom_ids[i]);
1247                         IDMAP_REPORT_RET(ret);
1248                 }
1249         }
1250
1251         /* ok all the backends have been contacted at this point */
1252         /* let's see if we have any unmapped SID left and act accordingly */
1253
1254         for (i = 0; ids[i]; i++) {
1255                 /* NOTE: this will NOT touch ID_EXPIRED entries that the backend
1256                  * was not able to confirm/deny (offline mode) */
1257                 if (ids[i]->status == ID_UNKNOWN ||
1258                         ids[i]->status == ID_UNMAPPED) {
1259                         /* ok this is an unmapped one, see if we can map it */
1260                         ret = idmap_new_mapping(ctx, ids[i]);
1261                         if (NT_STATUS_IS_OK(ret)) {
1262                                 /* successfully mapped */
1263                                 ids[i]->status = ID_MAPPED;
1264                         } else
1265                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
1266                                 /* could not map it */
1267                                 ids[i]->status = ID_UNMAPPED;
1268                         } else {
1269                                 /* Something very bad happened down there
1270                                  * OR we are offline */
1271                                 ids[i]->status = ID_UNKNOWN;
1272                         }
1273                 }
1274         }
1275
1276         ret = NT_STATUS_OK;
1277
1278 done:
1279         talloc_free(ctx);
1280         return ret;
1281 }
1282
1283 /**************************************************************************
1284  idmap interface functions
1285 **************************************************************************/
1286
1287 NTSTATUS idmap_unixids_to_sids(struct id_map **ids)
1288 {
1289         TALLOC_CTX *ctx;
1290         NTSTATUS ret;
1291         struct id_map **bids;
1292         int i, bi;
1293         int bn = 0;
1294         struct winbindd_domain *our_domain = find_our_domain();
1295
1296         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1297                 return ret;
1298         }
1299
1300         if (!ids || !*ids) {
1301                 DEBUG(1, ("Invalid list of maps\n"));
1302                 return NT_STATUS_INVALID_PARAMETER;
1303         }
1304
1305         ctx = talloc_named_const(NULL, 0, "idmap_unixids_to_sids ctx");
1306         if ( ! ctx) {
1307                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1308                 return NT_STATUS_NO_MEMORY;
1309         }
1310
1311         /* no ids to be asked to the backends by default */
1312         bids = NULL;
1313         bi = 0;
1314
1315         for (i = 0; ids[i]; i++) {
1316
1317                 if ( ! ids[i]->sid) {
1318                         DEBUG(1, ("invalid null SID in id_map array"));
1319                         talloc_free(ctx);
1320                         return NT_STATUS_INVALID_PARAMETER;
1321                 }
1322
1323                 ret = idmap_cache_map_id(idmap_cache, ids[i]);
1324
1325                 if ( ! NT_STATUS_IS_OK(ret)) {
1326
1327                         if ( ! bids) {
1328                                 /* alloc space for ids to be resolved by
1329                                  * backends (realloc ten by ten) */
1330                                 bids = TALLOC_ARRAY(ctx, struct id_map *, 10);
1331                                 if ( ! bids) {
1332                                         DEBUG(1, ("Out of memory!\n"));
1333                                         talloc_free(ctx);
1334                                         return NT_STATUS_NO_MEMORY;
1335                                 }
1336                                 bn = 10;
1337                         }
1338
1339                         /* add this id to the ones to be retrieved
1340                          * from the backends */
1341                         bids[bi] = ids[i];
1342                         bi++;
1343
1344                         /* check if we need to allocate new space
1345                          *  on the rids array */
1346                         if (bi == bn) {
1347                                 bn += 10;
1348                                 bids = talloc_realloc(ctx, bids,
1349                                                       struct id_map *, bn);
1350                                 if ( ! bids) {
1351                                         DEBUG(1, ("Out of memory!\n"));
1352                                         talloc_free(ctx);
1353                                         return NT_STATUS_NO_MEMORY;
1354                                 }
1355                         }
1356
1357                         /* make sure the last element is NULL */
1358                         bids[bi] = NULL;
1359                 }
1360         }
1361
1362         /* let's see if there is any id mapping to be retrieved
1363          * from the backends */
1364         if (bi) {
1365                 /* Only do query if we are online */
1366                 if ( IS_DOMAIN_OFFLINE(our_domain) ) {
1367                         ret = NT_STATUS_FILE_IS_OFFLINE;
1368                         goto done;
1369                 }
1370
1371                 ret = idmap_backends_unixids_to_sids(bids);
1372                 IDMAP_CHECK_RET(ret);
1373
1374                 /* update the cache */
1375                 for (i = 0; i < bi; i++) {
1376                         if (bids[i]->status == ID_MAPPED) {
1377                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1378                         } else if (bids[i]->status == ID_EXPIRED) {
1379                                 /* the cache returned an expired entry and the
1380                                  * backend was not able to clear the situation
1381                                  * (offline). This handles a previous
1382                                  * NT_STATUS_SYNCHRONIZATION_REQUIRED
1383                                  * for disconnected mode, */
1384                                 bids[i]->status = ID_MAPPED;
1385                         } else if (bids[i]->status == ID_UNKNOWN) {
1386                                 /* something bad here. We were not able to
1387                                  * handle this for some reason, mark it as
1388                                  * unmapped and hope next time things will
1389                                  * settle down. */
1390                                 bids[i]->status = ID_UNMAPPED;
1391                         } else { /* unmapped */
1392                                 ret = idmap_cache_set_negative_id(idmap_cache,
1393                                                                   bids[i]);
1394                         }
1395                         IDMAP_CHECK_RET(ret);
1396                 }
1397         }
1398
1399         ret = NT_STATUS_OK;
1400 done:
1401         talloc_free(ctx);
1402         return ret;
1403 }
1404
1405 NTSTATUS idmap_sids_to_unixids(struct id_map **ids)
1406 {
1407         TALLOC_CTX *ctx;
1408         NTSTATUS ret;
1409         struct id_map **bids;
1410         int i, bi;
1411         int bn = 0;
1412         struct winbindd_domain *our_domain = find_our_domain();
1413
1414         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1415                 return ret;
1416         }
1417
1418         if (!ids || !*ids) {
1419                 DEBUG(1, ("Invalid list of maps\n"));
1420                 return NT_STATUS_INVALID_PARAMETER;
1421         }
1422
1423         ctx = talloc_named_const(NULL, 0, "idmap_sids_to_unixids ctx");
1424         if ( ! ctx) {
1425                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1426                 return NT_STATUS_NO_MEMORY;
1427         }
1428
1429         /* no ids to be asked to the backends by default */
1430         bids = NULL;
1431         bi = 0;
1432
1433         for (i = 0; ids[i]; i++) {
1434
1435                 if ( ! ids[i]->sid) {
1436                         DEBUG(1, ("invalid null SID in id_map array\n"));
1437                         talloc_free(ctx);
1438                         return NT_STATUS_INVALID_PARAMETER;
1439                 }
1440
1441                 ret = idmap_cache_map_sid(idmap_cache, ids[i]);
1442
1443                 if ( ! NT_STATUS_IS_OK(ret)) {
1444
1445                         if ( ! bids) {
1446                                 /* alloc space for ids to be resolved
1447                                    by backends (realloc ten by ten) */
1448                                 bids = TALLOC_ARRAY(ctx, struct id_map *, 10);
1449                                 if ( ! bids) {
1450                                         DEBUG(1, ("Out of memory!\n"));
1451                                         talloc_free(ctx);
1452                                         return NT_STATUS_NO_MEMORY;
1453                                 }
1454                                 bn = 10;
1455                         }
1456
1457                         /* add this id to the ones to be retrieved
1458                          * from the backends */
1459                         bids[bi] = ids[i];
1460                         bi++;
1461
1462                         /* check if we need to allocate new space
1463                          * on the ids array */
1464                         if (bi == bn) {
1465                                 bn += 10;
1466                                 bids = talloc_realloc(ctx, bids,
1467                                                       struct id_map *, bn);
1468                                 if ( ! bids) {
1469                                         DEBUG(1, ("Out of memory!\n"));
1470                                         talloc_free(ctx);
1471                                         return NT_STATUS_NO_MEMORY;
1472                                 }
1473                         }
1474
1475                         /* make sure the last element is NULL */
1476                         bids[bi] = NULL;
1477                 }
1478         }
1479
1480         /* let's see if there is any id mapping to be retrieved
1481          * from the backends */
1482         if (bids) {
1483                 /* Only do query if we are online */
1484                 if ( IS_DOMAIN_OFFLINE(our_domain) ) {
1485                         ret = NT_STATUS_FILE_IS_OFFLINE;
1486                         goto done;
1487                 }
1488
1489                 ret = idmap_backends_sids_to_unixids(bids);
1490                 IDMAP_CHECK_RET(ret);
1491
1492                 /* update the cache */
1493                 for (i = 0; bids[i]; i++) {
1494                         if (bids[i]->status == ID_MAPPED) {
1495                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1496                         } else if (bids[i]->status == ID_EXPIRED) {
1497                                 /* the cache returned an expired entry and the
1498                                  * backend was not able to clear the situation
1499                                  * (offline). This handles a previous
1500                                  * NT_STATUS_SYNCHRONIZATION_REQUIRED
1501                                  * for disconnected mode, */
1502                                 bids[i]->status = ID_MAPPED;
1503                         } else if (bids[i]->status == ID_UNKNOWN) {
1504                                 /* something bad here. We were not able to
1505                                  * handle this for some reason, mark it as
1506                                  * unmapped and hope next time things will
1507                                  * settle down. */
1508                                 bids[i]->status = ID_UNMAPPED;
1509                         } else { /* unmapped */
1510                                 ret = idmap_cache_set_negative_sid(idmap_cache,
1511                                                                    bids[i]);
1512                         }
1513                         IDMAP_CHECK_RET(ret);
1514                 }
1515         }
1516
1517         ret = NT_STATUS_OK;
1518 done:
1519         talloc_free(ctx);
1520         return ret;
1521 }
1522
1523 NTSTATUS idmap_set_mapping(const struct id_map *id)
1524 {
1525         TALLOC_CTX *ctx;
1526         NTSTATUS ret;
1527
1528         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1529                 return ret;
1530         }
1531
1532         /* sanity checks */
1533         if ((id->sid == NULL) || (id->status != ID_MAPPED)) {
1534                 DEBUG(1, ("NULL SID or unmapped entry\n"));
1535                 return NT_STATUS_INVALID_PARAMETER;
1536         }
1537
1538         /* TODO: check uid/gid range ? */
1539
1540         ctx = talloc_named_const(NULL, 0, "idmap_set_mapping ctx");
1541         if ( ! ctx) {
1542                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1543                 return NT_STATUS_NO_MEMORY;
1544         }
1545
1546         /* set the new mapping */
1547         ret = idmap_backends_set_mapping(id);
1548         IDMAP_CHECK_RET(ret);
1549
1550         /* set the mapping in the cache */
1551         ret = idmap_cache_set(idmap_cache, id);
1552         IDMAP_CHECK_RET(ret);
1553
1554 done:
1555         talloc_free(ctx);
1556         return ret;
1557 }
1558
1559 char *idmap_fetch_secret(const char *backend, bool alloc,
1560                                const char *domain, const char *identity)
1561 {
1562         char *tmp, *ret;
1563         int r;
1564
1565         if (alloc) {
1566                 r = asprintf(&tmp, "IDMAP_ALLOC_%s", backend);
1567         } else {
1568                 r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
1569         }
1570
1571         if (r < 0)
1572                 return NULL;
1573
1574         strupper_m(tmp); /* make sure the key is case insensitive */
1575         ret = secrets_fetch_generic(tmp, identity);
1576
1577         SAFE_FREE(tmp);
1578
1579         return ret;
1580 }
1581