d69fd68e1031f27589ae9f8140caf8cdf63fa9be
[samba.git] / source3 / nsswitch / 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
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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #include "winbindd.h"
26
27 #undef DBGC_CLASS
28 #define DBGC_CLASS DBGC_IDMAP
29
30 static_decl_idmap;
31
32 struct idmap_backend {
33         const char *name;
34         struct idmap_methods *methods;
35         struct idmap_backend *prev, *next;
36 };
37
38 struct idmap_alloc_backend {
39         const char *name;
40         struct idmap_alloc_methods *methods;
41         struct idmap_alloc_backend *prev, *next;
42 };
43
44 struct idmap_cache_ctx;
45
46 static TALLOC_CTX *idmap_ctx = NULL;
47 static struct idmap_cache_ctx *idmap_cache;
48
49 static struct idmap_backend *backends = NULL;
50 static struct idmap_domain **idmap_domains = NULL;
51 static int num_domains = 0;
52 static int pdb_dom_num = -1;
53 static int def_dom_num = -1;
54
55 static struct idmap_alloc_backend *alloc_backends = NULL;
56 static struct idmap_alloc_methods *alloc_methods = NULL;
57
58 #define IDMAP_CHECK_RET(ret) do { if ( ! NT_STATUS_IS_OK(ret)) { DEBUG(2, ("ERROR: NTSTATUS = 0x%08x\n", NT_STATUS_V(ret))); goto done; } } while(0)
59 #define IDMAP_CHECK_ALLOC(mem) do { if (!mem) { DEBUG(0, ("Out of memory!\n")); ret = NT_STATUS_NO_MEMORY; goto done; } } while(0)
60
61 static struct idmap_methods *get_methods(struct idmap_backend *be, const char *name)
62 {
63         struct idmap_backend *b;
64
65         for (b = be; b; b = b->next) {
66                 if (strequal(b->name, name)) {
67                         return b->methods;
68                 }
69         }
70
71         return NULL;
72 }
73
74 static struct idmap_alloc_methods *get_alloc_methods(struct idmap_alloc_backend *be, const char *name)
75 {
76         struct idmap_alloc_backend *b;
77
78         for (b = be; b; b = b->next) {
79                 if (strequal(b->name, name)) {
80                         return b->methods;
81                 }
82         }
83
84         return NULL;
85 }
86
87 /**********************************************************************
88  Allow a module to register itself as a method.
89 **********************************************************************/
90
91 NTSTATUS smb_register_idmap(int version, const char *name, struct idmap_methods *methods)
92 {
93         struct idmap_methods *test;
94         struct idmap_backend *entry;
95
96         if (!idmap_ctx) {
97                 return NT_STATUS_INTERNAL_DB_ERROR;
98         }
99
100         if ((version != SMB_IDMAP_INTERFACE_VERSION)) {
101                 DEBUG(0, ("Failed to register idmap module.\n"
102                           "The module was compiled against SMB_IDMAP_INTERFACE_VERSION %d,\n"
103                           "current SMB_IDMAP_INTERFACE_VERSION is %d.\n"
104                           "Please recompile against the current version of samba!\n",  
105                           version, SMB_IDMAP_INTERFACE_VERSION));
106                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
107         }
108
109         if (!name || !name[0] || !methods) {
110                 DEBUG(0,("Called with NULL pointer or empty name!\n"));
111                 return NT_STATUS_INVALID_PARAMETER;
112         }
113
114         test = get_methods(backends, name);
115         if (test) {
116                 DEBUG(0,("Idmap module %s already registered!\n", name));
117                 return NT_STATUS_OBJECT_NAME_COLLISION;
118         }
119
120         entry = talloc(idmap_ctx, struct idmap_backend);
121         if ( ! entry) {
122                 DEBUG(0,("Out of memory!\n"));
123                 return NT_STATUS_NO_MEMORY;
124         }
125         entry->name = talloc_strdup(idmap_ctx, name);
126         if ( ! entry->name) {
127                 DEBUG(0,("Out of memory!\n"));
128                 return NT_STATUS_NO_MEMORY;
129         }
130         entry->methods = methods;
131
132         DLIST_ADD(backends, entry);
133         DEBUG(5, ("Successfully added idmap backend '%s'\n", name));
134         return NT_STATUS_OK;
135 }
136
137 /**********************************************************************
138  Allow a module to register itself as a method.
139 **********************************************************************/
140
141 NTSTATUS smb_register_idmap_alloc(int version, const char *name, struct idmap_alloc_methods *methods)
142 {
143         struct idmap_alloc_methods *test;
144         struct idmap_alloc_backend *entry;
145
146         if (!idmap_ctx) {
147                 return NT_STATUS_INTERNAL_DB_ERROR;
148         }
149
150         if ((version != SMB_IDMAP_INTERFACE_VERSION)) {
151                 DEBUG(0, ("Failed to register idmap alloc module.\n"
152                           "The module was compiled against SMB_IDMAP_INTERFACE_VERSION %d,\n"
153                           "current SMB_IDMAP_INTERFACE_VERSION is %d.\n"
154                           "Please recompile against the current version of samba!\n",  
155                           version, SMB_IDMAP_INTERFACE_VERSION));
156                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
157         }
158
159         if (!name || !name[0] || !methods) {
160                 DEBUG(0,("Called with NULL pointer or empty name!\n"));
161                 return NT_STATUS_INVALID_PARAMETER;
162         }
163
164         test = get_alloc_methods(alloc_backends, name);
165         if (test) {
166                 DEBUG(0,("idmap_alloc module %s already registered!\n", name));
167                 return NT_STATUS_OBJECT_NAME_COLLISION;
168         }
169
170         entry = talloc(idmap_ctx, struct idmap_alloc_backend);
171         if ( ! entry) {
172                 DEBUG(0,("Out of memory!\n"));
173                 return NT_STATUS_NO_MEMORY;
174         }
175         entry->name = talloc_strdup(idmap_ctx, name);
176         if ( ! entry->name) {
177                 DEBUG(0,("Out of memory!\n"));
178                 return NT_STATUS_NO_MEMORY;
179         }
180         entry->methods = methods;
181
182         DLIST_ADD(alloc_backends, entry);
183         DEBUG(5, ("Successfully added idmap alloc backend '%s'\n", name));
184         return NT_STATUS_OK;
185 }
186
187 static int close_domain_destructor(struct idmap_domain *dom)
188 {
189         NTSTATUS ret;
190
191         ret = dom->methods->close_fn(dom);
192         if (!NT_STATUS_IS_OK(ret)) {
193                 DEBUG(3, ("Failed to close idmap domain [%s]!\n", dom->name));
194         }
195
196         return 0;
197 }
198
199 /**************************************************************************
200  Shutdown.
201 **************************************************************************/
202
203 NTSTATUS idmap_close(void)
204 {
205         /* close the alloc backend first before freeing idmap_ctx */
206         if (alloc_methods) {
207                 alloc_methods->close_fn();
208                 alloc_methods = NULL;
209         }
210         alloc_backends = NULL;
211
212         /* this talloc_free call will fire the talloc destructors
213          * that will free all active backends resources */
214         TALLOC_FREE(idmap_ctx);
215         idmap_cache = NULL;
216         idmap_domains = NULL;
217         backends = NULL;
218
219         return NT_STATUS_OK;
220 }
221
222 /**********************************************************************
223  Initialise idmap cache and a remote backend (if configured).
224 **********************************************************************/
225
226 static const char *idmap_default_domain[] = { "default domain", NULL };
227
228 NTSTATUS idmap_init(void)
229 {       
230         NTSTATUS ret;
231         struct idmap_domain *dom;
232         char *compat_backend = NULL;
233         char *compat_params = NULL;
234         const char **dom_list = NULL;
235         char *alloc_backend;
236         BOOL default_already_defined = False;
237         BOOL pri_dom_is_in_list = False;
238         int compat = 0;
239         int i;
240
241         if (idmap_ctx) {
242                 return NT_STATUS_OK;
243         }
244
245         if ( (idmap_ctx = talloc_named_const(NULL, 0, "idmap_ctx")) == NULL ) {
246                 return NT_STATUS_NO_MEMORY;
247         }
248
249         if ( (idmap_cache = idmap_cache_init(idmap_ctx)) == NULL ) {
250                 return NT_STATUS_UNSUCCESSFUL;
251         }
252
253         static_init_idmap;
254
255         dom_list = lp_idmap_domains();
256         
257         if ( dom_list && lp_idmap_backend() ) {
258                 DEBUG(0, ("WARNING: idmap backend and idmap domains are "
259                           "mutually excusive!\n"));
260                 DEBUGADD(0,("idmap backend option will be IGNORED!\n"));
261         } else if ( lp_idmap_backend() ) {
262                 const char **compat_list = lp_idmap_backend();
263                 char *p = NULL;
264                 const char *q = NULL;           
265
266                 DEBUG(0, ("WARNING: idmap backend is deprecated!\n"));
267                 compat = 1;
268
269                 if ( (compat_backend = talloc_strdup( idmap_ctx, *compat_list )) == NULL ) {
270                         ret = NT_STATUS_NO_MEMORY;
271                         goto done;                      
272                 }
273                 
274                 /* strip any leading idmap_ prefix of */
275                 if (strncmp(*compat_list, "idmap_", 6) == 0 ) {
276                         q = *compat_list += 6;
277                         DEBUG(0, ("WARNING: idmap backend uses obsolete and "
278                                   "deprecated 'idmap_' prefix.\n"
279                                   "Please replace 'idmap_%s' by '%s' in %s\n", 
280                                   q, q, dyn_CONFIGFILE));
281                         compat_backend = talloc_strdup( idmap_ctx, q);
282                 } else {
283                         compat_backend = talloc_strdup( idmap_ctx, *compat_list);
284                 }
285                         
286                 /* separate the backend and module arguements */
287                 if ((p = strchr(compat_backend, ':')) != NULL) {
288                         *p = '\0';                      
289                         compat_params = p + 1;
290                 }
291         }
292
293         if ( ! dom_list) {
294                 dom_list = idmap_default_domain;
295         }
296         
297         /***************************
298          * initialize idmap domains
299          */
300         DEBUG(1, ("Initializing idmap domains\n"));
301
302         for (i = 0; dom_list[i]; i++) {
303                 const char *parm_backend;
304                 char *config_option;
305
306                 if (strequal(dom_list[i], lp_workgroup())) {
307                         pri_dom_is_in_list = True;
308                 }
309                 /* init domain */
310                 
311                 dom = talloc_zero(idmap_ctx, struct idmap_domain);
312                 IDMAP_CHECK_ALLOC(dom);
313
314                 dom->name = talloc_strdup(dom, dom_list[i]);
315                 IDMAP_CHECK_ALLOC(dom->name);
316
317                 config_option = talloc_asprintf(dom, "idmap config %s", dom->name);
318                 IDMAP_CHECK_ALLOC(config_option);
319
320                 /* default or specific ? */
321
322                 dom->default_domain = lp_parm_bool(-1, config_option, "default", False);
323
324                 if (dom->default_domain ||
325                     strequal(dom_list[i], idmap_default_domain[0])) {
326
327                         /* make sure this is set even when we match idmap_default_domain[0] */
328                         dom->default_domain = True;
329
330                         if (default_already_defined) {
331                                 DEBUG(1, ("ERROR: Multiple domains defined as default!\n"));
332                                 ret = NT_STATUS_INVALID_PARAMETER;
333                                 goto done;
334                         }
335
336                         default_already_defined = True;
337
338                 } 
339
340                 dom->readonly = lp_parm_bool(-1, config_option, "readonly", False);
341
342                 /* find associated backend (default: tdb) */
343                 if (compat) {
344                         parm_backend = talloc_strdup(idmap_ctx, compat_backend);
345                 } else {
346                         parm_backend = talloc_strdup(idmap_ctx,
347                                                      lp_parm_const_string(-1, config_option, "backend", "tdb"));
348                 }
349                 IDMAP_CHECK_ALLOC(parm_backend);
350
351                 /* get the backend methods for this domain */
352                 dom->methods = get_methods(backends, parm_backend);
353
354                 if ( ! dom->methods) {
355                         ret = smb_probe_module("idmap", parm_backend);
356                         if (NT_STATUS_IS_OK(ret)) {
357                                 dom->methods = get_methods(backends, parm_backend);
358                         }
359                 }
360                 if ( ! dom->methods) {
361                         DEBUG(0, ("ERROR: Could not get methods for backend %s\n", parm_backend));
362                         ret = NT_STATUS_UNSUCCESSFUL;
363                         goto done;
364                 }
365
366                 /* check the set_mapping function exists otherwise mark the module as readonly */
367                 if ( ! dom->methods->set_mapping) {
368                         dom->readonly = True;
369                 }
370
371                 /* now that we have methods, set the destructor for this domain */
372                 talloc_set_destructor(dom, close_domain_destructor);
373
374                 /* Finally instance a backend copy for this domain */
375                 ret = dom->methods->init(dom, compat_params);
376                 if ( ! NT_STATUS_IS_OK(ret)) {
377                         DEBUG(0, ("ERROR: Initialization failed for backend %s (domain %s)\n",
378                                                 parm_backend, dom->name));
379                         ret = NT_STATUS_UNSUCCESSFUL;
380                         goto done;
381                 }
382                 idmap_domains = talloc_realloc(idmap_ctx, idmap_domains, struct idmap_domain *, i+1);
383                 if ( ! idmap_domains) {
384                         DEBUG(0, ("Out of memory!\n"));
385                         ret = NT_STATUS_NO_MEMORY;
386                         goto done;
387                 }
388                 idmap_domains[i] = dom;
389
390                 if (dom->default_domain) { /* save default domain position for future uses */
391                         def_dom_num = i;
392                 }
393
394                 DEBUG(10, ("Domain %s - Backend %s - %sdefault - %sreadonly\n",
395                                 dom->name, parm_backend,
396                                 dom->default_domain?"":"not ", dom->readonly?"":"not "));
397
398                 talloc_free(config_option);
399         }
400
401         /* save the number of domains we have */
402         num_domains = i;
403
404         /* automatically add idmap_nss backend if needed */
405         if ((lp_server_role() == ROLE_DOMAIN_MEMBER) &&
406             ( ! pri_dom_is_in_list) &&
407             lp_winbind_trusted_domains_only()) {
408
409                 dom = talloc_zero(idmap_ctx, struct idmap_domain);
410                 IDMAP_CHECK_ALLOC(dom);
411
412                 dom->name = talloc_strdup(dom, lp_workgroup());
413                 IDMAP_CHECK_ALLOC(dom->name);
414
415                 dom->default_domain = False;
416                 dom->readonly = True;
417
418                 /* get the backend methods for passdb */
419                 dom->methods = get_methods(backends, "nss");
420
421                 /* (the nss module is always statically linked) */
422                 if ( ! dom->methods) {
423                         DEBUG(0, ("ERROR: Could not get methods for idmap_nss ?!\n"));
424                         ret = NT_STATUS_UNSUCCESSFUL;
425                         goto done;
426                 }
427
428                 /* now that we have methods, set the destructor for this domain */
429                 talloc_set_destructor(dom, close_domain_destructor);
430
431                 /* Finally instance a backend copy for this domain */
432                 ret = dom->methods->init(dom, compat_params);
433                 if ( ! NT_STATUS_IS_OK(ret)) {
434                         DEBUG(0, ("ERROR: Initialization failed for idmap_nss ?!\n"));
435                         ret = NT_STATUS_UNSUCCESSFUL;
436                         goto done;
437                 }
438
439                 idmap_domains = talloc_realloc(idmap_ctx, idmap_domains, struct idmap_domain *, num_domains+1);
440                 if ( ! idmap_domains) {
441                         DEBUG(0, ("Out of memory!\n"));
442                         ret = NT_STATUS_NO_MEMORY;
443                         goto done;
444                 }
445                 idmap_domains[num_domains] = dom;
446
447                 DEBUG(10, ("Domain %s - Backend nss - not default - readonly\n", dom->name ));
448
449                 num_domains++;
450         }
451
452         /**** automatically add idmap_passdb backend ****/
453         dom = talloc_zero(idmap_ctx, struct idmap_domain);
454         IDMAP_CHECK_ALLOC(dom);
455
456         dom->name = talloc_strdup(dom, get_global_sam_name());
457         IDMAP_CHECK_ALLOC(dom->name);
458
459         dom->default_domain = False;
460         dom->readonly = True;
461
462         /* get the backend methods for passdb */
463         dom->methods = get_methods(backends, "passdb");
464
465         /* (the passdb module is always statically linked) */
466         if ( ! dom->methods) {
467                 DEBUG(0, ("ERROR: Could not get methods for idmap_passdb ?!\n"));
468                 ret = NT_STATUS_UNSUCCESSFUL;
469                 goto done;
470         }
471
472         /* now that we have methods, set the destructor for this domain */
473         talloc_set_destructor(dom, close_domain_destructor);
474
475         /* Finally instance a backend copy for this domain */
476         ret = dom->methods->init(dom, compat_params);
477         if ( ! NT_STATUS_IS_OK(ret)) {
478                 DEBUG(0, ("ERROR: Initialization failed for idmap_passdb ?!\n"));
479                 ret = NT_STATUS_UNSUCCESSFUL;
480                 goto done;
481         }
482
483         idmap_domains = talloc_realloc(idmap_ctx, idmap_domains, struct idmap_domain *, num_domains+1);
484         if ( ! idmap_domains) {
485                 DEBUG(0, ("Out of memory!\n"));
486                 ret = NT_STATUS_NO_MEMORY;
487                 goto done;
488         }
489         idmap_domains[num_domains] = dom;
490
491         /* needed to handle special BUILTIN and wellknown SIDs cases */
492         pdb_dom_num = num_domains;
493
494         DEBUG(10, ("Domain %s - Backend passdb - not default - readonly\n", dom->name));
495
496         num_domains++;
497         /**** finished adding idmap_passdb backend ****/
498
499         /* sort domains so that the default is the last one */
500         /* don't sort if no default domain defined */
501         if (def_dom_num != -1 && def_dom_num != num_domains-1) { /* default is not last, move it */
502                 struct idmap_domain *tmp;
503
504                 if (pdb_dom_num > def_dom_num) {
505                         pdb_dom_num --;
506
507                 } else if (pdb_dom_num == def_dom_num) { /* ?? */
508                         pdb_dom_num = num_domains - 1;
509                 }
510
511                 tmp = idmap_domains[def_dom_num];
512
513                 for (i = def_dom_num; i < num_domains-1; i++) {
514                         idmap_domains[i] = idmap_domains[i+1];
515                 }
516                 idmap_domains[i] = tmp;
517                 def_dom_num = i;
518         }
519
520
521         /***************************
522          * initialize alloc module
523          */
524         DEBUG(1, ("Initializing idmap alloc module\n"));
525
526         if (compat) {
527                 alloc_backend = talloc_strdup(idmap_ctx, compat_backend);
528         } else {
529                 char *ab = lp_idmap_alloc_backend();
530                 
531                 if (ab && (ab[0] != '\0')) {
532                         alloc_backend = talloc_strdup(idmap_ctx, lp_idmap_alloc_backend());
533                 } else {
534                         alloc_backend = talloc_strdup(idmap_ctx, "tdb");
535                 }
536         }
537         IDMAP_CHECK_ALLOC(alloc_backend);
538
539         alloc_methods = get_alloc_methods(alloc_backends, alloc_backend);
540         if ( ! alloc_methods) {
541                 ret = smb_probe_module("idmap", alloc_backend);
542                 if (NT_STATUS_IS_OK(ret)) {
543                         alloc_methods = get_alloc_methods(alloc_backends, alloc_backend);
544                 }
545         }
546         if ( ! alloc_methods) {
547                 DEBUG(0, ("ERROR: Could not get methods for alloc backend %s\n", alloc_backend));
548                 ret = NT_STATUS_UNSUCCESSFUL;
549                 goto done;
550         }
551
552         ret = alloc_methods->init(compat_params);
553         if ( ! NT_STATUS_IS_OK(ret)) {
554                 DEBUG(0, ("ERROR: Initialization failed for alloc backend %s\n", alloc_backend));
555                 ret = NT_STATUS_UNSUCCESSFUL;
556                 goto done;
557         }
558
559         /* cleanpu temporary strings */
560         TALLOC_FREE( compat_backend );
561         
562         return NT_STATUS_OK;
563
564 done:
565         DEBUG(0, ("Aborting IDMAP Initialization ...\n"));
566         idmap_close();
567         return ret;
568 }
569
570 /**************************************************************************
571  idmap allocator interface functions
572 **************************************************************************/
573
574 NTSTATUS idmap_allocate_uid(struct unixid *id)
575 {
576         NTSTATUS ret;
577
578         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
579                 return ret;
580         }
581
582         id->type = ID_TYPE_UID;
583         return alloc_methods->allocate_id(id);
584 }
585
586 NTSTATUS idmap_allocate_gid(struct unixid *id)
587 {
588         NTSTATUS ret;
589
590         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
591                 return ret;
592         }
593
594         id->type = ID_TYPE_GID;
595         return alloc_methods->allocate_id(id);
596 }
597
598 NTSTATUS idmap_set_uid_hwm(struct unixid *id)
599 {
600         NTSTATUS ret;
601
602         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
603                 return ret;
604         }
605
606         id->type = ID_TYPE_UID;
607         return alloc_methods->set_id_hwm(id);
608 }
609
610 NTSTATUS idmap_set_gid_hwm(struct unixid *id)
611 {
612         NTSTATUS ret;
613
614         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
615                 return ret;
616         }
617
618         id->type = ID_TYPE_GID;
619         return alloc_methods->set_id_hwm(id);
620 }
621
622 /******************************************************************************
623  Lookup an idmap_domain give a full user or group SID
624  ******************************************************************************/
625
626 static struct idmap_domain* find_idmap_domain_from_sid( DOM_SID *account_sid )
627 {
628         DOM_SID domain_sid;
629         uint32 rid;
630         struct winbindd_domain *domain = NULL;
631         int i;
632         
633         /* 1. Handle BUILTIN or Special SIDs and prevent them from
634            falling into the default domain space (if we have a
635            configured passdb backend. */
636
637         if ( (pdb_dom_num != -1) && 
638              (sid_check_is_in_builtin(account_sid) ||
639               sid_check_is_in_wellknown_domain(account_sid)) ) 
640         {
641                 return idmap_domains[pdb_dom_num];
642         }
643
644         /* 2. Lookup the winbindd_domain from the account_sid */
645
646         sid_copy( &domain_sid, account_sid );
647         sid_split_rid( &domain_sid, &rid );     
648         domain = find_domain_from_sid_noinit( &domain_sid );    
649
650         for (i = 0; domain && i < num_domains; i++) {
651                 if ( strequal( idmap_domains[i]->name, domain->name ) ) {
652                         return idmap_domains[i];
653                 }
654         }
655
656         /* 3. Fall back to the default domain */
657
658         if ( def_dom_num != -1 ) {
659                 return idmap_domains[def_dom_num];
660         }
661
662         return NULL;
663 }
664
665 /******************************************************************************
666  Lookup an index given an idmap_domain pointer
667  ******************************************************************************/
668
669 static uint32 find_idmap_domain_index( struct idmap_domain *id_domain)
670 {
671         int i;
672         
673         for (i = 0; i < num_domains; i++) {
674                 if ( idmap_domains[i] == id_domain )
675                         return i;               
676         }
677
678         return -1;      
679 }
680
681
682 /*********************************************************
683  Check if creating a mapping is permitted for the domain
684 *********************************************************/
685
686 static NTSTATUS idmap_can_map(const struct id_map *map, struct idmap_domain **ret_dom)
687 {
688         struct idmap_domain *dom;
689
690         /* Check we do not create mappings for our own local domain, or BUILTIN or special SIDs */
691         if ((sid_compare_domain(map->sid, get_global_sam_sid()) == 0) ||
692             sid_check_is_in_builtin(map->sid) ||
693             sid_check_is_in_wellknown_domain(map->sid)) {
694                 DEBUG(10, ("We are not supposed to create mappings for our own domains (local, builtin, specials)\n"));
695                 return NT_STATUS_UNSUCCESSFUL;
696         }
697
698         /* Special check for trusted domain only = Yes */
699         if (lp_winbind_trusted_domains_only()) {
700                 struct winbindd_domain *wdom = find_our_domain();
701                 if (wdom && (sid_compare_domain(map->sid, &wdom->sid) == 0)) {
702                         DEBUG(10, ("We are not supposed to create mappings for our primary domain when <trusted domain only> is True\n"));
703                         DEBUGADD(10, ("Leave [%s] unmapped\n", sid_string_static(map->sid)));
704                         return NT_STATUS_UNSUCCESSFUL;
705                 }
706         }
707
708         if ( (dom = find_idmap_domain_from_sid( map->sid )) == NULL ) {
709                 /* huh, couldn't find a suitable domain, let's just leave it unmapped */
710                 DEBUG(10, ("Could not find idmap backend for SID %s", sid_string_static(map->sid)));
711                 return NT_STATUS_NO_SUCH_DOMAIN;
712         }
713
714         if (dom->readonly) {
715                 /* ouch the domain is read only, let's just leave it unmapped */
716                 DEBUG(10, ("idmap backend for SID %s is READONLY!\n", sid_string_static(map->sid)));
717                 return NT_STATUS_UNSUCCESSFUL;
718         }
719
720         *ret_dom = dom;
721         return NT_STATUS_OK;
722 }
723
724 static NTSTATUS idmap_new_mapping(TALLOC_CTX *ctx, struct id_map *map)
725 {
726         NTSTATUS ret;
727         struct idmap_domain *dom;
728         const char *domname, *name;
729         enum lsa_SidType sid_type;
730         BOOL wbret;
731
732         ret = idmap_can_map(map, &dom);
733         if ( ! NT_STATUS_IS_OK(ret)) {
734                 return NT_STATUS_NONE_MAPPED;
735         }
736         
737         /* by default calls to winbindd are disabled
738            the following call will not recurse so this is safe */
739         winbind_on();
740         wbret = winbind_lookup_sid(ctx, map->sid, &domname, &name, &sid_type);
741         winbind_off();
742
743         /* check if this is a valid SID and then map it */
744         if (wbret) {
745                 switch (sid_type) {
746                 case SID_NAME_USER:
747                         ret = idmap_allocate_uid(&map->xid);
748                         if ( ! NT_STATUS_IS_OK(ret)) {
749                                 /* can't allocate id, let's just leave it unmapped */
750                                 DEBUG(2, ("uid allocation failed! Can't create mapping\n"));
751                                 return NT_STATUS_NONE_MAPPED;
752                         }
753                         break;
754                 case SID_NAME_DOM_GRP:
755                 case SID_NAME_ALIAS:
756                 case SID_NAME_WKN_GRP:
757                         ret = idmap_allocate_gid(&map->xid);
758                         if ( ! NT_STATUS_IS_OK(ret)) {
759                                 /* can't allocate id, let's just leave it unmapped */
760                                 DEBUG(2, ("gid allocation failed! Can't create mapping\n"));
761                                 return NT_STATUS_NONE_MAPPED;
762                         }
763                         break;
764                 default:
765                         /* invalid sid, let's just leave it unmapped */
766                         DEBUG(10, ("SID %s is UNKNOWN, skip mapping\n", sid_string_static(map->sid)));
767                         return NT_STATUS_NONE_MAPPED;
768                 }
769
770                 /* ok, got a new id, let's set a mapping */
771                 map->status = ID_MAPPED;
772
773                 DEBUG(10, ("Setting mapping: %s <-> %s %lu\n",
774                            sid_string_static(map->sid),
775                            (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
776                            (unsigned long)map->xid.id));
777                 ret = dom->methods->set_mapping(dom, map);
778
779                 if ( ! NT_STATUS_IS_OK(ret)) {
780                         /* something wrong here :-( */
781                         DEBUG(2, ("Failed to commit mapping\n!"));
782
783                         /* TODO: would it make sense to have an "unalloc_id function?" */
784
785                         return NT_STATUS_NONE_MAPPED;
786                 }
787         } else {
788                 DEBUG(2,("Invalid SID, not mapping %s (type %d)\n",
789                                 sid_string_static(map->sid), sid_type));
790                 return NT_STATUS_NONE_MAPPED;
791         }
792
793         return NT_STATUS_OK;
794 }
795
796 static NTSTATUS idmap_backends_set_mapping(const struct id_map *map)
797 {
798         struct idmap_domain *dom;
799         NTSTATUS ret;
800
801         DEBUG(10, ("Setting mapping %s <-> %s %lu\n",
802                    sid_string_static(map->sid),
803                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
804                    (unsigned long)map->xid.id));
805
806         ret = idmap_can_map(map, &dom);
807         if ( ! NT_STATUS_IS_OK(ret)) {
808                 return ret;
809         }
810
811         DEBUG(10,("set_mapping for domain %s\n", dom->name ));  
812
813         return dom->methods->set_mapping(dom, map);
814 }
815
816 static NTSTATUS idmap_backends_unixids_to_sids(struct id_map **ids)
817 {
818         struct idmap_domain *dom;
819         struct id_map **unmapped;
820         struct id_map **_ids;
821         TALLOC_CTX *ctx;
822         NTSTATUS ret;
823         int i, u, n;
824
825         if (!ids || !*ids) {
826                 DEBUG(1, ("Invalid list of maps\n"));
827                 return NT_STATUS_INVALID_PARAMETER;
828         }
829
830         ctx = talloc_named_const(NULL, 0, "idmap_backends_unixids_to_sids ctx");
831         if ( ! ctx) {
832                 DEBUG(0, ("Out of memory!\n"));
833                 return NT_STATUS_NO_MEMORY;
834         }
835
836         DEBUG(10, ("Query backends to map ids->sids\n"));
837
838         /* start from the default (the last one) and then if there are still
839          * unmapped entries cycle through the others */
840
841         _ids = ids;
842
843         /* make sure all maps are marked as in UNKNOWN status */
844         for (i = 0; _ids[i]; i++) {
845                 _ids[i]->status = ID_UNKNOWN;
846         }
847
848         unmapped = NULL;
849         for (n = num_domains-1; n >= 0; n--) { /* cycle backwards */
850
851                 dom = idmap_domains[n];
852
853                 DEBUG(10, ("Query sids from domain %s\n", dom->name));
854                 
855                 ret = dom->methods->unixids_to_sids(dom, _ids);
856                 IDMAP_CHECK_RET(ret);
857
858                 unmapped = NULL;
859
860                 for (i = 0, u = 0; _ids[i]; i++) {
861                         if (_ids[i]->status == ID_UNKNOWN || _ids[i]->status == ID_UNMAPPED) {
862                                 unmapped = talloc_realloc(ctx, unmapped, struct id_map *, u + 2);
863                                 IDMAP_CHECK_ALLOC(unmapped);
864                                 unmapped[u] = _ids[i];
865                                 u++;
866                         }
867                 }
868                 if (unmapped) {
869                         /* terminate the unmapped list */
870                         unmapped[u] = NULL;
871                 } else { /* no more entries, get out */
872                         break;
873                 }
874
875                 _ids = unmapped;
876                 
877         }
878
879         if (unmapped) {
880                 /* there are still unmapped ids, map them to the unix users/groups domains */
881                 for (i = 0; unmapped[i]; i++) {
882                         switch (unmapped[i]->xid.type) {
883                         case ID_TYPE_UID:
884                                 uid_to_unix_users_sid((uid_t)unmapped[i]->xid.id, unmapped[i]->sid);
885                                 unmapped[i]->status = ID_MAPPED;
886                                 break;
887                         case ID_TYPE_GID:
888                                 gid_to_unix_groups_sid((gid_t)unmapped[i]->xid.id, unmapped[i]->sid);
889                                 unmapped[i]->status = ID_MAPPED;
890                                 break;
891                         default: /* what?! */
892                                 unmapped[i]->status = ID_UNKNOWN;
893                                 break;
894                         }
895                 }
896         }
897
898         ret = NT_STATUS_OK;
899
900 done:
901         talloc_free(ctx);
902         return ret;
903 }       
904
905 static NTSTATUS idmap_backends_sids_to_unixids(struct id_map **ids)
906 {
907         struct id_map ***dom_ids;
908         struct idmap_domain *dom;
909         TALLOC_CTX *ctx;
910         NTSTATUS ret;
911         int i, *counters;
912
913         if ( (ctx = talloc_named_const(NULL, 0, "be_sids_to_ids")) == NULL ) {
914                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
915                 return NT_STATUS_NO_MEMORY;
916         }
917
918         DEBUG(10, ("Query backends to map sids->ids\n"));
919
920         /* split list per domain */
921
922         dom_ids = talloc_zero_array(ctx, struct id_map **, num_domains);
923         IDMAP_CHECK_ALLOC(dom_ids);
924         counters = talloc_zero_array(ctx, int, num_domains);
925
926         /* partition the requests by domain */
927
928         for (i = 0; ids[i]; i++) {
929                 uint32 idx;             
930
931                 /* make sure they are unknown to start off */
932                 ids[i]->status = ID_UNKNOWN;
933
934                 if ( (dom = find_idmap_domain_from_sid( ids[i]->sid )) == NULL ) {
935                         /* no vailable idmap_domain.  Move on */
936                         continue;
937                 }
938
939                 DEBUG(10,("SID %s is being handled by %s\n", 
940                           sid_string_static(ids[i]->sid),  
941                           dom ? dom->name : "none" ));
942
943                 idx = find_idmap_domain_index( dom );
944                 SMB_ASSERT( idx != -1 );
945                 
946                 dom_ids[idx] = talloc_realloc(ctx, dom_ids[idx], 
947                                               struct id_map *, counters[idx] + 2);
948                 IDMAP_CHECK_ALLOC(dom_ids[idx]);
949
950                 dom_ids[idx][counters[idx]] = ids[i];
951                 counters[idx]++;
952                 dom_ids[idx][counters[idx]] = NULL;
953         }
954
955         /* All the ids have been dispatched in the right queues.
956            Let's cycle through the filled ones */
957
958         for (i = 0; i < num_domains; i++) {
959                 if (dom_ids[i]) {
960                         dom = idmap_domains[i];
961                         DEBUG(10, ("Query ids from domain %s\n", dom->name));
962                         ret = dom->methods->sids_to_unixids(dom, dom_ids[i]);
963                         IDMAP_CHECK_RET(ret);
964                 }
965         }
966
967         /* ok all the backends have been contacted at this point */
968         /* let's see if we have any unmapped SID left and act accordingly */
969
970         for (i = 0; ids[i]; i++) {
971                 if (ids[i]->status == ID_UNKNOWN || ids[i]->status == ID_UNMAPPED) {
972                         /* ok this is an unmapped one, see if we can map it */
973                         ret = idmap_new_mapping(ctx, ids[i]);
974                         if (NT_STATUS_IS_OK(ret)) {
975                                 /* successfully mapped */
976                                 ids[i]->status = ID_MAPPED;
977                         } else if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
978                                 /* could not map it */
979                                 ids[i]->status = ID_UNMAPPED;
980                         } else {
981                                 /* Something very bad happened down there */
982                                 ids[i]->status = ID_UNKNOWN;
983                         }
984                 }
985         }
986
987         ret = NT_STATUS_OK;
988
989 done:
990         talloc_free(ctx);
991         return ret;
992 }       
993
994 /**************************************************************************
995  idmap interface functions
996 **************************************************************************/
997
998 NTSTATUS idmap_unixids_to_sids(struct id_map **ids)
999 {
1000         TALLOC_CTX *ctx;
1001         NTSTATUS ret;
1002         struct id_map **bids;
1003         int i, bi;
1004         int bn = 0;
1005
1006         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1007                 return ret;
1008         }
1009
1010         if (!ids || !*ids) {
1011                 DEBUG(1, ("Invalid list of maps\n"));
1012                 return NT_STATUS_INVALID_PARAMETER;
1013         }
1014
1015         ctx = talloc_named_const(NULL, 0, "idmap_unixids_to_sids ctx");
1016         if ( ! ctx) {
1017                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1018                 return NT_STATUS_NO_MEMORY;
1019         }
1020
1021         /* no ids to be asked to the backends by default */
1022         bids = NULL;
1023         bi = 0;
1024         
1025         for (i = 0; ids[i]; i++) {
1026
1027                 if ( ! ids[i]->sid) {
1028                         DEBUG(1, ("invalid null SID in id_map array"));
1029                         talloc_free(ctx);
1030                         return NT_STATUS_INVALID_PARAMETER;
1031                 }
1032
1033                 ret = idmap_cache_map_id(idmap_cache, ids[i]);
1034
1035                 if ( ! NT_STATUS_IS_OK(ret)) {
1036
1037                         if ( ! bids) {
1038                                 /* alloc space for ids to be resolved by backends (realloc ten by ten) */
1039                                 bids = talloc_array(ctx, struct id_map *, 10);
1040                                 if ( ! bids) {
1041                                         DEBUG(1, ("Out of memory!\n"));
1042                                         talloc_free(ctx);
1043                                         return NT_STATUS_NO_MEMORY;
1044                                 }
1045                                 bn = 10;
1046                         }
1047
1048                         /* add this id to the ones to be retrieved from the backends */
1049                         bids[bi] = ids[i];
1050                         bi++;
1051         
1052                         /* check if we need to allocate new space on the rids array */
1053                         if (bi == bn) {
1054                                 bn += 10;
1055                                 bids = talloc_realloc(ctx, bids, struct id_map *, bn);
1056                                 if ( ! bids) {
1057                                         DEBUG(1, ("Out of memory!\n"));
1058                                         talloc_free(ctx);
1059                                         return NT_STATUS_NO_MEMORY;
1060                                 }
1061                         }
1062
1063                         /* make sure the last element is NULL */
1064                         bids[bi] = NULL;
1065                 }
1066         }
1067
1068         /* let's see if there is any id mapping to be retieved from the backends */
1069         if (bi) {
1070                 ret = idmap_backends_unixids_to_sids(bids);
1071                 IDMAP_CHECK_RET(ret);
1072
1073                 /* update the cache */
1074                 for (i = 0; i < bi; i++) {
1075                         if (bids[i]->status == ID_MAPPED) {
1076                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1077                         } else if (bids[i]->status == ID_UNKNOWN) {
1078                                 /* return an expired entry in the cache or an unknown */
1079                                 /* this handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
1080                                  * for disconnected mode */
1081                                 idmap_cache_map_id(idmap_cache, ids[i]);
1082                         } else { /* unmapped */
1083                                 ret = idmap_cache_set_negative_id(idmap_cache, bids[i]);
1084                         }
1085                         IDMAP_CHECK_RET(ret);
1086                 }
1087         }
1088
1089         ret = NT_STATUS_OK;
1090 done:
1091         talloc_free(ctx);
1092         return ret;
1093 }
1094
1095 NTSTATUS idmap_sids_to_unixids(struct id_map **ids)
1096 {
1097         TALLOC_CTX *ctx;
1098         NTSTATUS ret;
1099         struct id_map **bids;
1100         int i, bi;
1101         int bn = 0;
1102
1103         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1104                 return ret;
1105         }
1106
1107         if (!ids || !*ids) {
1108                 DEBUG(1, ("Invalid list of maps\n"));
1109                 return NT_STATUS_INVALID_PARAMETER;
1110         }
1111
1112         ctx = talloc_named_const(NULL, 0, "idmap_sids_to_unixids ctx");
1113         if ( ! ctx) {
1114                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1115                 return NT_STATUS_NO_MEMORY;
1116         }
1117
1118         /* no ids to be asked to the backends by default */
1119         bids = NULL;
1120         bi = 0;
1121         
1122         for (i = 0; ids[i]; i++) {
1123
1124                 if ( ! ids[i]->sid) {
1125                         DEBUG(1, ("invalid null SID in id_map array\n"));
1126                         talloc_free(ctx);
1127                         return NT_STATUS_INVALID_PARAMETER;
1128                 }
1129
1130                 ret = idmap_cache_map_sid(idmap_cache, ids[i]);
1131
1132                 if ( ! NT_STATUS_IS_OK(ret)) {
1133
1134                         if ( ! bids) {
1135                                 /* alloc space for ids to be resolved by backends (realloc ten by ten) */
1136                                 bids = talloc_array(ctx, struct id_map *, 10);
1137                                 if ( ! bids) {
1138                                         DEBUG(1, ("Out of memory!\n"));
1139                                         talloc_free(ctx);
1140                                         return NT_STATUS_NO_MEMORY;
1141                                 }
1142                                 bn = 10;
1143                         }
1144
1145                         /* add this id to the ones to be retrieved from the backends */
1146                         bids[bi] = ids[i];
1147                         bi++;
1148
1149                         /* check if we need to allocate new space on the ids array */
1150                         if (bi == bn) {
1151                                 bn += 10;
1152                                 bids = talloc_realloc(ctx, bids, struct id_map *, bn);
1153                                 if ( ! bids) {
1154                                         DEBUG(1, ("Out of memory!\n"));
1155                                         talloc_free(ctx);
1156                                         return NT_STATUS_NO_MEMORY;
1157                                 }
1158                         }
1159
1160                         /* make sure the last element is NULL */
1161                         bids[bi] = NULL;
1162                 }
1163         }
1164
1165         /* let's see if there is any id mapping to be retieved from the backends */
1166         if (bids) {
1167                 ret = idmap_backends_sids_to_unixids(bids);
1168                 IDMAP_CHECK_RET(ret);
1169
1170                 /* update the cache */
1171                 for (i = 0; bids[i]; i++) {
1172                         if (bids[i]->status == ID_MAPPED) {
1173                                 ret = idmap_cache_set(idmap_cache, bids[i]);
1174                         } else if (bids[i]->status == ID_UNKNOWN) {
1175                                 /* return an expired entry in the cache or an unknown */
1176                                 /* this handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
1177                                  * for disconnected mode */
1178                                 idmap_cache_map_id(idmap_cache, ids[i]);
1179                         } else {
1180                                 ret = idmap_cache_set_negative_sid(idmap_cache, bids[i]);
1181                         }
1182                         IDMAP_CHECK_RET(ret);
1183                 }
1184         }
1185
1186         ret = NT_STATUS_OK;
1187 done:
1188         talloc_free(ctx);
1189         return ret;
1190 }
1191
1192 NTSTATUS idmap_set_mapping(const struct id_map *id)
1193 {
1194         TALLOC_CTX *ctx;
1195         NTSTATUS ret;
1196
1197         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1198                 return ret;
1199         }
1200
1201         /* sanity checks */
1202         if ((id->sid == NULL) || (id->status != ID_MAPPED)) {
1203                 DEBUG(1, ("NULL SID or unmapped entry\n"));
1204                 return NT_STATUS_INVALID_PARAMETER;
1205         }
1206
1207         /* TODO: check uid/gid range ? */
1208
1209         ctx = talloc_named_const(NULL, 0, "idmap_set_mapping ctx");
1210         if ( ! ctx) {
1211                 DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
1212                 return NT_STATUS_NO_MEMORY;
1213         }
1214
1215         /* set the new mapping */
1216         ret = idmap_backends_set_mapping(id);
1217         IDMAP_CHECK_RET(ret);
1218
1219         /* set the mapping in the cache */
1220         ret = idmap_cache_set(idmap_cache, id);
1221         IDMAP_CHECK_RET(ret);
1222
1223 done:
1224         talloc_free(ctx);
1225         return ret;
1226 }
1227
1228 /**************************************************************************
1229  Dump backend status.
1230 **************************************************************************/
1231
1232 void idmap_dump_maps(char *logfile)
1233 {
1234         NTSTATUS ret;
1235         struct unixid allid;
1236         struct id_map *maps;
1237         int num_maps;
1238         FILE *dump;
1239         int i;
1240
1241         if (! NT_STATUS_IS_OK(ret = idmap_init())) {
1242                 return;
1243         }
1244
1245         dump = fopen(logfile, "w");
1246         if ( ! dump) {
1247                 DEBUG(0, ("Unable to open open stream for file [%s], errno: %d\n", logfile, errno));
1248                 return;
1249         }
1250
1251         allid.type = ID_TYPE_UID;
1252         allid.id = 0;
1253         alloc_methods->get_id_hwm(&allid);
1254         fprintf(dump, "USER HWM %lu\n", (unsigned long)allid.id);
1255
1256         allid.type = ID_TYPE_GID;
1257         allid.id = 0;
1258         alloc_methods->get_id_hwm(&allid);
1259         fprintf(dump, "GROUP HWM %lu\n", (unsigned long)allid.id);
1260
1261         maps = talloc(idmap_ctx, struct id_map);
1262         num_maps = 0;
1263
1264         for (i = 0; i < num_domains; i++) {
1265                 if (idmap_domains[i]->methods->dump_data) {
1266                         idmap_domains[i]->methods->dump_data(idmap_domains[i], &maps, &num_maps);
1267                 }
1268         }
1269
1270         for (i = 0; i < num_maps; i++) {
1271                 switch (maps[i].xid.type) {
1272                 case ID_TYPE_UID:
1273                         fprintf(dump, "UID %lu %s\n",
1274                                 (unsigned long)maps[i].xid.id,
1275                                 sid_string_static(maps[i].sid));
1276                         break;
1277                 case ID_TYPE_GID:
1278                         fprintf(dump, "GID %lu %s\n",
1279                                 (unsigned long)maps[i].xid.id,
1280                                 sid_string_static(maps[i].sid));
1281                         break;
1282                 }
1283         }
1284
1285         fflush(dump);
1286         fclose(dump);
1287 }
1288
1289 char *idmap_fetch_secret(const char *backend, bool alloc,
1290                                const char *domain, const char *identity)
1291 {
1292         char *tmp, *ret;
1293         int r;
1294
1295         if (alloc) {
1296                 r = asprintf(&tmp, "IDMAP_ALLOC_%s", backend);
1297         } else {
1298                 r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
1299         }
1300
1301         if (r < 0) 
1302                 return NULL;
1303
1304         strupper_m(tmp); /* make sure the key is case insensitive */
1305         ret = secrets_fetch_generic(tmp, identity);
1306
1307         SAFE_FREE( tmp );       
1308
1309         return ret;
1310 }