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