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