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