Merge branch 'ctdb-merge' into v3-2-test
[ira/wip.git] / source3 / winbindd / idmap_tdb2.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    idmap TDB2 backend, used for clustered Samba setups.
5
6    This uses 2 tdb files. One is permanent, and is in shared storage
7    on the cluster (using "tdb:idmap2.tdb =" in smb.conf). The other is a
8    temporary cache tdb on local storage.
9
10    Copyright (C) Andrew Tridgell 2007
11
12    This is heavily based upon idmap_tdb.c, which is:
13
14    Copyright (C) Tim Potter 2000
15    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
16    Copyright (C) Jeremy Allison 2006
17    Copyright (C) Simo Sorce 2003-2006
18    
19    This program is free software; you can redistribute it and/or modify
20    it under the terms of the GNU General Public License as published by
21    the Free Software Foundation; either version 2 of the License, or
22    (at your option) any later version.
23    
24    This program is distributed in the hope that it will be useful,
25    but WITHOUT ANY WARRANTY; without even the implied warranty of
26    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27    GNU General Public License for more details.
28    
29    You should have received a copy of the GNU General Public License
30    along with this program; if not, write to the Free Software
31    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 */
33
34 #include "includes.h"
35 #include "winbindd.h"
36
37 #undef DBGC_CLASS
38 #define DBGC_CLASS DBGC_IDMAP
39
40 /* High water mark keys */
41 #define HWM_GROUP  "GROUP HWM"
42 #define HWM_USER   "USER HWM"
43
44 static struct idmap_tdb2_state {
45         /* User and group id pool */
46         uid_t low_uid, high_uid;               /* Range of uids to allocate */
47         gid_t low_gid, high_gid;               /* Range of gids to allocate */
48         const char *idmap_script;
49 } idmap_tdb2_state;
50
51
52
53 /* tdb context for the local cache tdb */
54 static TDB_CONTEXT *idmap_tdb2_tmp;
55
56 /* handle to the permanent tdb */
57 static struct db_context *idmap_tdb2_perm;
58
59 /*
60   open the cache tdb
61  */
62 static NTSTATUS idmap_tdb2_open_cache_db(void)
63 {
64         const char *db_path;
65
66         if (idmap_tdb2_tmp) {
67                 /* its already open */
68                 return NT_STATUS_OK;
69         }
70
71         db_path = lock_path("idmap2_cache.tdb");
72
73         /* Open idmap repository */
74         if (!(idmap_tdb2_tmp = tdb_open_log(db_path, 0, TDB_CLEAR_IF_FIRST, O_RDWR|O_CREAT, 0644))) {
75                 DEBUG(0, ("Unable to open cache idmap database '%s'\n", db_path));
76                 return NT_STATUS_UNSUCCESSFUL;
77         }
78
79         return NT_STATUS_OK;
80 }
81
82
83 static NTSTATUS idmap_tdb2_alloc_load(void);
84
85 /*
86   open the permanent tdb
87  */
88 static NTSTATUS idmap_tdb2_open_perm_db(void)
89 {
90         char *db_path;
91         
92         if (idmap_tdb2_perm) {
93                 /* its already open */
94                 return NT_STATUS_OK;
95         }
96
97         db_path = lp_parm_talloc_string(-1, "tdb", "idmap2.tdb", NULL);
98         if (db_path == NULL) {
99                 /* fall back to the private directory, which, despite
100                    its name, is usually on shared storage */
101                 db_path = talloc_asprintf(NULL, "%s/idmap2.tdb", lp_private_dir());
102         }
103         NT_STATUS_HAVE_NO_MEMORY(db_path);
104
105         /* Open idmap repository */
106         idmap_tdb2_perm = db_open(NULL, db_path, 0, TDB_DEFAULT,
107                                   O_RDWR|O_CREAT, 0644);
108         TALLOC_FREE(db_path);
109
110         if (idmap_tdb2_perm == NULL) {
111                 DEBUG(0, ("Unable to open permanent idmap database '%s'\n",
112                           db_path));
113                 return NT_STATUS_UNSUCCESSFUL;
114         }
115
116         /* load the ranges and high/low water marks */
117         return idmap_tdb2_alloc_load();
118 }
119
120
121 /*
122   load the idmap allocation ranges and high/low water marks
123 */
124 static NTSTATUS idmap_tdb2_alloc_load(void)
125 {
126         const char *range;
127         uid_t low_uid = 0;
128         uid_t high_uid = 0;
129         gid_t low_gid = 0;
130         gid_t high_gid = 0;
131
132         /* load ranges */
133         idmap_tdb2_state.low_uid = 0;
134         idmap_tdb2_state.high_uid = 0;
135         idmap_tdb2_state.low_gid = 0;
136         idmap_tdb2_state.high_gid = 0;
137
138         /* see if a idmap script is configured */
139         idmap_tdb2_state.idmap_script = lp_parm_const_string(-1, "idmap", "script", NULL);
140
141         if (idmap_tdb2_state.idmap_script) {
142                 DEBUG(1, ("using idmap script '%s'\n", idmap_tdb2_state.idmap_script));
143         }
144
145         range = lp_parm_const_string(-1, "idmap alloc config", "range", NULL);
146         if (range && range[0]) {
147                 unsigned low_id, high_id;
148                 if (sscanf(range, "%u - %u", &low_id, &high_id) == 2) {
149                         if (low_id < high_id) {
150                                 idmap_tdb2_state.low_gid = idmap_tdb2_state.low_uid = low_id;
151                                 idmap_tdb2_state.high_gid = idmap_tdb2_state.high_uid = high_id;
152                         } else {
153                                 DEBUG(1, ("ERROR: invalid idmap alloc range [%s]", range));
154                         }
155                 } else {
156                         DEBUG(1, ("ERROR: invalid syntax for idmap alloc config:range [%s]", range));
157                 }
158         }
159
160         /* Create high water marks for group and user id */
161         if (lp_idmap_uid(&low_uid, &high_uid)) {
162                 idmap_tdb2_state.low_uid = low_uid;
163                 idmap_tdb2_state.high_uid = high_uid;
164         }
165
166         if (lp_idmap_gid(&low_gid, &high_gid)) {
167                 idmap_tdb2_state.low_gid = low_gid;
168                 idmap_tdb2_state.high_gid = high_gid;
169         }
170
171         if (idmap_tdb2_state.high_uid <= idmap_tdb2_state.low_uid) {
172                 DEBUG(1, ("idmap uid range missing or invalid\n"));
173                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
174                 return NT_STATUS_UNSUCCESSFUL;
175         } else {
176                 uint32 low_id;
177
178                 if (((low_id = dbwrap_fetch_int32(idmap_tdb2_perm,
179                                                   HWM_USER)) == -1) ||
180                     (low_id < idmap_tdb2_state.low_uid)) {
181                         if (dbwrap_store_int32(
182                                     idmap_tdb2_perm, HWM_USER,
183                                     idmap_tdb2_state.low_uid) == -1) {
184                                 DEBUG(0, ("Unable to initialise user hwm in idmap database\n"));
185                                 return NT_STATUS_INTERNAL_DB_ERROR;
186                         }
187                 }
188         }
189
190         if (idmap_tdb2_state.high_gid <= idmap_tdb2_state.low_gid) {
191                 DEBUG(1, ("idmap gid range missing or invalid\n"));
192                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
193                 return NT_STATUS_UNSUCCESSFUL;
194         } else {
195                 uint32 low_id;
196
197                 if (((low_id = dbwrap_fetch_int32(idmap_tdb2_perm,
198                                                   HWM_GROUP)) == -1) ||
199                     (low_id < idmap_tdb2_state.low_gid)) {
200                         if (dbwrap_store_int32(
201                                     idmap_tdb2_perm, HWM_GROUP,
202                                     idmap_tdb2_state.low_gid) == -1) {
203                                 DEBUG(0, ("Unable to initialise group hwm in idmap database\n"));
204                                 return NT_STATUS_INTERNAL_DB_ERROR;
205                         }
206                 }
207         }
208
209         return NT_STATUS_OK;
210 }
211
212
213 /*
214   Initialise idmap alloc database. 
215 */
216 static NTSTATUS idmap_tdb2_alloc_init(const char *params)
217 {
218         /* nothing to do - we want to avoid opening the permanent
219            database if possible. Instead we load the params when we
220            first need it. */
221         return NT_STATUS_OK;
222 }
223
224
225 /*
226   Allocate a new id. 
227 */
228 static NTSTATUS idmap_tdb2_allocate_id(struct unixid *xid)
229 {
230         bool ret;
231         const char *hwmkey;
232         const char *hwmtype;
233         uint32_t high_hwm;
234         uint32_t hwm;
235         NTSTATUS status;
236
237         status = idmap_tdb2_open_perm_db();
238         NT_STATUS_NOT_OK_RETURN(status);
239
240         /* Get current high water mark */
241         switch (xid->type) {
242
243         case ID_TYPE_UID:
244                 hwmkey = HWM_USER;
245                 hwmtype = "UID";
246                 high_hwm = idmap_tdb2_state.high_uid;
247                 break;
248
249         case ID_TYPE_GID:
250                 hwmkey = HWM_GROUP;
251                 hwmtype = "GID";
252                 high_hwm = idmap_tdb2_state.high_gid;
253                 break;
254
255         default:
256                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
257                 return NT_STATUS_INVALID_PARAMETER;
258         }
259
260         if ((hwm = dbwrap_fetch_int32(idmap_tdb2_perm, hwmkey)) == -1) {
261                 return NT_STATUS_INTERNAL_DB_ERROR;
262         }
263
264         /* check it is in the range */
265         if (hwm > high_hwm) {
266                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
267                           hwmtype, (unsigned long)high_hwm));
268                 return NT_STATUS_UNSUCCESSFUL;
269         }
270
271         /* fetch a new id and increment it */
272         ret = dbwrap_change_uint32_atomic(idmap_tdb2_perm, hwmkey, &hwm, 1);
273         if (ret == -1) {
274                 DEBUG(1, ("Fatal error while fetching a new %s value\n!", hwmtype));
275                 return NT_STATUS_UNSUCCESSFUL;
276         }
277
278         /* recheck it is in the range */
279         if (hwm > high_hwm) {
280                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
281                           hwmtype, (unsigned long)high_hwm));
282                 return NT_STATUS_UNSUCCESSFUL;
283         }
284         
285         xid->id = hwm;
286         DEBUG(10,("New %s = %d\n", hwmtype, hwm));
287
288         return NT_STATUS_OK;
289 }
290
291 /*
292   Get current highest id. 
293 */
294 static NTSTATUS idmap_tdb2_get_hwm(struct unixid *xid)
295 {
296         const char *hwmkey;
297         const char *hwmtype;
298         uint32_t hwm;
299         uint32_t high_hwm;
300
301         /* Get current high water mark */
302         switch (xid->type) {
303
304         case ID_TYPE_UID:
305                 hwmkey = HWM_USER;
306                 hwmtype = "UID";
307                 high_hwm = idmap_tdb2_state.high_uid;
308                 break;
309
310         case ID_TYPE_GID:
311                 hwmkey = HWM_GROUP;
312                 hwmtype = "GID";
313                 high_hwm = idmap_tdb2_state.high_gid;
314                 break;
315
316         default:
317                 return NT_STATUS_INVALID_PARAMETER;
318         }
319
320         if ((hwm = dbwrap_fetch_int32(idmap_tdb2_perm, hwmkey)) == -1) {
321                 return NT_STATUS_INTERNAL_DB_ERROR;
322         }
323
324         xid->id = hwm;
325
326         /* Warn if it is out of range */
327         if (hwm >= high_hwm) {
328                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
329                           hwmtype, (unsigned long)high_hwm));
330         }
331
332         return NT_STATUS_OK;
333 }
334
335 /*
336   Set high id. 
337 */
338 static NTSTATUS idmap_tdb2_set_hwm(struct unixid *xid)
339 {
340         /* not supported, or we would invalidate the cache tdb on
341            other nodes */
342         DEBUG(0,("idmap_tdb2_set_hwm not supported\n"));
343         return NT_STATUS_NOT_SUPPORTED;
344 }
345
346 /*
347   Close the alloc tdb 
348 */
349 static NTSTATUS idmap_tdb2_alloc_close(void)
350 {
351         /* don't actually close it */
352         return NT_STATUS_OK;
353 }
354
355 /*
356   IDMAP MAPPING TDB BACKEND
357 */
358 struct idmap_tdb2_context {
359         uint32_t filter_low_id;
360         uint32_t filter_high_id;
361 };
362
363 /*
364   try fetching from the cache tdb, and if that fails then
365   fetch from the permanent tdb
366  */
367 static TDB_DATA tdb2_fetch_bystring(TALLOC_CTX *mem_ctx, const char *keystr)
368 {
369         TDB_DATA ret;
370         NTSTATUS status;
371
372         ret = tdb_fetch_bystring(idmap_tdb2_tmp, keystr);
373         if (ret.dptr != NULL) {
374                 /* got it from cache */
375                 unsigned char *tmp;
376
377                 tmp = (unsigned char *)talloc_memdup(mem_ctx, ret.dptr,
378                                                      ret.dsize);
379                 SAFE_FREE(ret.dptr);
380                 ret.dptr = tmp;
381
382                 if (ret.dptr == NULL) {
383                         return make_tdb_data(NULL, 0);
384                 }
385                 return ret;
386         }
387         
388         status = idmap_tdb2_open_perm_db();
389         if (!NT_STATUS_IS_OK(status)) {
390                 return ret;
391         }
392
393         /* fetch from the permanent tdb */
394         return dbwrap_fetch_bystring(idmap_tdb2_perm, mem_ctx, keystr);
395 }
396
397 /*
398   store into both databases
399  */
400 static NTSTATUS tdb2_store_bystring(const char *keystr, TDB_DATA data, int flags)
401 {
402         NTSTATUS ret;
403         NTSTATUS status = idmap_tdb2_open_perm_db();
404         if (!NT_STATUS_IS_OK(status)) {
405                 return NT_STATUS_UNSUCCESSFUL;
406         }
407         ret = dbwrap_store_bystring(idmap_tdb2_perm, keystr, data, flags);
408         if (!NT_STATUS_IS_OK(ret)) {
409                 ret = tdb_store_bystring(idmap_tdb2_tmp, keystr, data, flags) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
410         }
411         return ret;
412 }
413
414 /*
415   delete from both databases
416  */
417 static NTSTATUS tdb2_delete_bystring(const char *keystr)
418 {
419         NTSTATUS ret;
420         NTSTATUS status = idmap_tdb2_open_perm_db();
421         if (!NT_STATUS_IS_OK(status)) {
422                 return NT_STATUS_UNSUCCESSFUL;
423         }
424         ret = dbwrap_delete_bystring(idmap_tdb2_perm, keystr);
425         if (!NT_STATUS_IS_OK(ret)) {
426                 ret = tdb_delete_bystring(idmap_tdb2_tmp, keystr)  ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
427         }
428         return ret;
429 }
430
431 /*
432   Initialise idmap database. 
433 */
434 static NTSTATUS idmap_tdb2_db_init(struct idmap_domain *dom)
435 {
436         NTSTATUS ret;
437         struct idmap_tdb2_context *ctx;
438         char *config_option = NULL;
439         const char *range;
440         NTSTATUS status;
441
442         status = idmap_tdb2_open_cache_db();
443         NT_STATUS_NOT_OK_RETURN(status);
444
445         ctx = talloc(dom, struct idmap_tdb2_context);
446         if ( ! ctx) {
447                 DEBUG(0, ("Out of memory!\n"));
448                 return NT_STATUS_NO_MEMORY;
449         }
450
451         config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
452         if ( ! config_option) {
453                 DEBUG(0, ("Out of memory!\n"));
454                 ret = NT_STATUS_NO_MEMORY;
455                 goto failed;
456         }
457
458         range = lp_parm_const_string(-1, config_option, "range", NULL);
459         if (( ! range) ||
460             (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2) ||
461             (ctx->filter_low_id > ctx->filter_high_id)) {
462                 ctx->filter_low_id = 0;
463                 ctx->filter_high_id = 0;
464         }
465
466         dom->private_data = ctx;
467         dom->initialized = True;
468
469         talloc_free(config_option);
470         return NT_STATUS_OK;
471
472 failed:
473         talloc_free(ctx);
474         return ret;
475 }
476
477
478 /*
479   run a script to perform a mapping
480
481   The script should the following command lines:
482
483       SIDTOID S-1-xxxx
484       IDTOSID UID xxxx
485       IDTOSID GID xxxx
486
487   and should return one of the following as a single line of text
488      UID:xxxx
489      GID:xxxx
490      SID:xxxx
491      ERR:xxxx
492  */
493 static NTSTATUS idmap_tdb2_script(struct idmap_tdb2_context *ctx, struct id_map *map,
494                                   const char *fmt, ...)
495 {
496         va_list ap;
497         char *cmd;
498         FILE *p;
499         char line[64];
500         unsigned long v;
501
502         cmd = talloc_asprintf(ctx, "%s ", idmap_tdb2_state.idmap_script);
503         NT_STATUS_HAVE_NO_MEMORY(cmd);  
504
505         va_start(ap, fmt);
506         cmd = talloc_vasprintf_append(cmd, fmt, ap);
507         va_end(ap);
508         NT_STATUS_HAVE_NO_MEMORY(cmd);
509
510         p = popen(cmd, "r");
511         talloc_free(cmd);
512         if (p == NULL) {
513                 return NT_STATUS_NONE_MAPPED;
514         }
515
516         if (fgets(line, sizeof(line)-1, p) == NULL) {
517                 pclose(p);
518                 return NT_STATUS_NONE_MAPPED;
519         }
520         pclose(p);
521
522         DEBUG(10,("idmap script gave: %s\n", line));
523
524         if (sscanf(line, "UID:%lu", &v) == 1) {
525                 map->xid.id   = v;
526                 map->xid.type = ID_TYPE_UID;
527         } else if (sscanf(line, "GID:%lu", &v) == 1) {
528                 map->xid.id   = v;
529                 map->xid.type = ID_TYPE_GID;            
530         } else if (strncmp(line, "SID:S-", 6) == 0) {
531                 if (!string_to_sid(map->sid, &line[4])) {
532                         DEBUG(0,("Bad SID in '%s' from idmap script %s\n",
533                                  line, idmap_tdb2_state.idmap_script));
534                         return NT_STATUS_NONE_MAPPED;                   
535                 }
536         } else {
537                 DEBUG(0,("Bad reply '%s' from idmap script %s\n",
538                          line, idmap_tdb2_state.idmap_script));
539                 return NT_STATUS_NONE_MAPPED;
540         }
541
542         return NT_STATUS_OK;
543 }
544
545
546
547 /*
548   Single id to sid lookup function. 
549 */
550 static NTSTATUS idmap_tdb2_id_to_sid(struct idmap_tdb2_context *ctx, struct id_map *map)
551 {
552         NTSTATUS ret;
553         TDB_DATA data;
554         char *keystr;
555
556         if (!ctx || !map) {
557                 return NT_STATUS_INVALID_PARAMETER;
558         }
559
560         /* apply filters before checking */
561         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
562             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
563                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
564                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
565                 return NT_STATUS_NONE_MAPPED;
566         }
567
568         switch (map->xid.type) {
569
570         case ID_TYPE_UID:
571                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
572                 break;
573                 
574         case ID_TYPE_GID:
575                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
576                 break;
577
578         default:
579                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
580                 return NT_STATUS_INVALID_PARAMETER;
581         }
582
583         /* final SAFE_FREE safe */
584         data.dptr = NULL;
585
586         if (keystr == NULL) {
587                 DEBUG(0, ("Out of memory!\n"));
588                 ret = NT_STATUS_NO_MEMORY;
589                 goto done;
590         }
591
592         DEBUG(10,("Fetching record %s\n", keystr));
593
594         /* Check if the mapping exists */
595         data = tdb2_fetch_bystring(keystr, keystr);
596
597         if (!data.dptr) {
598                 fstring sidstr;
599
600                 DEBUG(10,("Record %s not found\n", keystr));
601                 if (idmap_tdb2_state.idmap_script == NULL) {
602                         ret = NT_STATUS_NONE_MAPPED;
603                         goto done;
604                 }
605
606                 ret = idmap_tdb2_script(ctx, map, "IDTOSID %s", keystr);
607
608                 /* store it on shared storage */
609                 if (!NT_STATUS_IS_OK(ret)) {
610                         goto done;
611                 }
612
613                 if (sid_to_fstring(sidstr, map->sid)) {
614                         /* both forward and reverse mappings */
615                         tdb2_store_bystring(keystr,
616                                             string_term_tdb_data(sidstr), 
617                                             TDB_REPLACE);
618                         tdb2_store_bystring(sidstr,
619                                             string_term_tdb_data(keystr), 
620                                             TDB_REPLACE);
621                 }
622                 goto done;
623         }
624                 
625         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
626                 DEBUG(10,("INVALID SID (%s) in record %s\n",
627                         (const char *)data.dptr, keystr));
628                 ret = NT_STATUS_INTERNAL_DB_ERROR;
629                 goto done;
630         }
631
632         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
633         ret = NT_STATUS_OK;
634
635 done:
636         talloc_free(keystr);
637         return ret;
638 }
639
640
641 /*
642  Single sid to id lookup function. 
643 */
644 static NTSTATUS idmap_tdb2_sid_to_id(struct idmap_tdb2_context *ctx, struct id_map *map)
645 {
646         NTSTATUS ret;
647         TDB_DATA data;
648         char *keystr;
649         unsigned long rec_id = 0;
650
651         if ((keystr = sid_string_talloc(ctx, map->sid)) == NULL) {
652                 DEBUG(0, ("Out of memory!\n"));
653                 ret = NT_STATUS_NO_MEMORY;
654                 goto done;
655         }
656
657         DEBUG(10,("Fetching record %s\n", keystr));
658
659         /* Check if sid is present in database */
660         data = tdb2_fetch_bystring(keystr, keystr);
661         if (!data.dptr) {
662                 fstring idstr;
663
664                 DEBUG(10,(__location__ " Record %s not found\n", keystr));
665
666                 if (idmap_tdb2_state.idmap_script == NULL) {
667                         ret = NT_STATUS_NONE_MAPPED;
668                         goto done;
669                 }
670                         
671                 ret = idmap_tdb2_script(ctx, map, "SIDTOID %s", keystr);
672                 /* store it on shared storage */
673                 if (!NT_STATUS_IS_OK(ret)) {
674                         goto done;
675                 }
676
677                 snprintf(idstr, sizeof(idstr), "%cID %lu", 
678                          map->xid.type == ID_TYPE_UID?'U':'G',
679                          (unsigned long)map->xid.id);
680                 /* store both forward and reverse mappings */
681                 tdb2_store_bystring(keystr, string_term_tdb_data(idstr),
682                                     TDB_REPLACE);
683                 tdb2_store_bystring(idstr, string_term_tdb_data(keystr),
684                                     TDB_REPLACE);
685                 goto done;
686         }
687
688         /* What type of record is this ? */
689         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
690                 map->xid.id = rec_id;
691                 map->xid.type = ID_TYPE_UID;
692                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
693                 ret = NT_STATUS_OK;
694
695         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
696                 map->xid.id = rec_id;
697                 map->xid.type = ID_TYPE_GID;
698                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
699                 ret = NT_STATUS_OK;
700
701         } else { /* Unknown record type ! */
702                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
703                 ret = NT_STATUS_INTERNAL_DB_ERROR;
704         }
705         
706         /* apply filters before returning result */
707         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
708             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
709                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
710                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
711                 ret = NT_STATUS_NONE_MAPPED;
712         }
713
714 done:
715         talloc_free(keystr);
716         return ret;
717 }
718
719 /*
720   lookup a set of unix ids. 
721 */
722 static NTSTATUS idmap_tdb2_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
723 {
724         struct idmap_tdb2_context *ctx;
725         NTSTATUS ret;
726         int i;
727
728         /* make sure we initialized */
729         if ( ! dom->initialized) {
730                 ret = idmap_tdb2_db_init(dom);
731                 if ( ! NT_STATUS_IS_OK(ret)) {
732                         return ret;
733                 }
734         }
735
736         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
737
738         for (i = 0; ids[i]; i++) {
739                 ret = idmap_tdb2_id_to_sid(ctx, ids[i]);
740                 if ( ! NT_STATUS_IS_OK(ret)) {
741
742                         /* if it is just a failed mapping continue */
743                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
744
745                                 /* make sure it is marked as unmapped */
746                                 ids[i]->status = ID_UNMAPPED;
747                                 continue;
748                         }
749                         
750                         /* some fatal error occurred, return immediately */
751                         goto done;
752                 }
753
754                 /* all ok, id is mapped */
755                 ids[i]->status = ID_MAPPED;
756         }
757
758         ret = NT_STATUS_OK;
759
760 done:
761         return ret;
762 }
763
764 /*
765   lookup a set of sids. 
766 */
767 static NTSTATUS idmap_tdb2_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
768 {
769         struct idmap_tdb2_context *ctx;
770         NTSTATUS ret;
771         int i;
772
773         /* make sure we initialized */
774         if ( ! dom->initialized) {
775                 ret = idmap_tdb2_db_init(dom);
776                 if ( ! NT_STATUS_IS_OK(ret)) {
777                         return ret;
778                 }
779         }
780
781         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
782
783         for (i = 0; ids[i]; i++) {
784                 ret = idmap_tdb2_sid_to_id(ctx, ids[i]);
785                 if ( ! NT_STATUS_IS_OK(ret)) {
786
787                         /* if it is just a failed mapping continue */
788                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
789
790                                 /* make sure it is marked as unmapped */
791                                 ids[i]->status = ID_UNMAPPED;
792                                 continue;
793                         }
794                         
795                         /* some fatal error occurred, return immediately */
796                         goto done;
797                 }
798
799                 /* all ok, id is mapped */
800                 ids[i]->status = ID_MAPPED;
801         }
802
803         ret = NT_STATUS_OK;
804
805 done:
806         return ret;
807 }
808
809
810 /*
811   set a mapping. 
812 */
813 static NTSTATUS idmap_tdb2_set_mapping(struct idmap_domain *dom, const struct id_map *map)
814 {
815         struct idmap_tdb2_context *ctx;
816         NTSTATUS ret;
817         TDB_DATA data;
818         char *ksidstr, *kidstr;
819         struct db_record *update_lock = NULL;
820         struct db_record *rec = NULL;
821
822         /* make sure we initialized */
823         if ( ! dom->initialized) {
824                 ret = idmap_tdb2_db_init(dom);
825                 if ( ! NT_STATUS_IS_OK(ret)) {
826                         return ret;
827                 }
828         }
829
830         if (!map || !map->sid) {
831                 return NT_STATUS_INVALID_PARAMETER;
832         }
833
834         ksidstr = kidstr = NULL;
835         data.dptr = NULL;
836
837         /* TODO: should we filter a set_mapping using low/high filters ? */
838         
839         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
840
841         switch (map->xid.type) {
842
843         case ID_TYPE_UID:
844                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
845                 break;
846                 
847         case ID_TYPE_GID:
848                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
849                 break;
850
851         default:
852                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
853                 return NT_STATUS_INVALID_PARAMETER;
854         }
855
856         if (kidstr == NULL) {
857                 DEBUG(0, ("ERROR: Out of memory!\n"));
858                 ret = NT_STATUS_NO_MEMORY;
859                 goto done;
860         }
861
862         if (!(ksidstr = sid_string_talloc(ctx, map->sid))) {
863                 DEBUG(0, ("Out of memory!\n"));
864                 ret = NT_STATUS_NO_MEMORY;
865                 goto done;
866         }
867
868         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
869
870         /*
871          * Get us the update lock. This is necessary to get the lock orders
872          * right, we need to deal with two records under a lock.
873          */
874
875         if (!(update_lock = idmap_tdb2_perm->fetch_locked(
876                       idmap_tdb2_perm, ctx,
877                       string_term_tdb_data("UPDATELOCK")))) {
878                 DEBUG(10,("Failed to lock record %s\n", ksidstr));
879                 ret = NT_STATUS_UNSUCCESSFUL;
880                 goto done;
881         }
882
883         /*
884          * *DELETE* previous mappings if any. *
885          */
886
887         /* First delete indexed on SID */
888
889         if (((rec = idmap_tdb2_perm->fetch_locked(
890                      idmap_tdb2_perm, update_lock,
891                      string_term_tdb_data(ksidstr))) != NULL)
892             && (rec->value.dsize != 0)) {
893                 struct db_record *rec2;
894
895                 if ((rec2 = idmap_tdb2_perm->fetch_locked(
896                              idmap_tdb2_perm, update_lock, rec->value))
897                     != NULL) {
898                         rec2->delete_rec(rec2);
899                         TALLOC_FREE(rec2);
900                 }
901
902                 rec->delete_rec(rec);
903
904                 tdb_delete(idmap_tdb2_tmp, rec->key);
905                 tdb_delete(idmap_tdb2_tmp, rec->value);
906         }
907         TALLOC_FREE(rec);
908
909         /* Now delete indexed on unix ID */
910
911         if (((rec = idmap_tdb2_perm->fetch_locked(
912                      idmap_tdb2_perm, update_lock,
913                      string_term_tdb_data(kidstr))) != NULL)
914             && (rec->value.dsize != 0)) {
915                 struct db_record *rec2;
916
917                 if ((rec2 = idmap_tdb2_perm->fetch_locked(
918                              idmap_tdb2_perm, update_lock, rec->value))
919                     != NULL) {
920                         rec2->delete_rec(rec2);
921                         TALLOC_FREE(rec2);
922                 }
923
924                 rec->delete_rec(rec);
925
926                 tdb_delete(idmap_tdb2_tmp, rec->key);
927                 tdb_delete(idmap_tdb2_tmp, rec->value);
928         }
929         TALLOC_FREE(rec);
930
931         if (!NT_STATUS_IS_OK(tdb2_store_bystring(ksidstr, string_term_tdb_data(kidstr),
932                                 TDB_INSERT))) {
933                 DEBUG(0, ("Error storing SID -> ID\n"));
934                 ret = NT_STATUS_UNSUCCESSFUL;
935                 goto done;
936         }
937         if (!NT_STATUS_IS_OK(tdb2_store_bystring(kidstr, string_term_tdb_data(ksidstr),
938                                 TDB_INSERT))) {
939                 DEBUG(0, ("Error storing ID -> SID\n"));
940                 /* try to remove the previous stored SID -> ID map */
941                 tdb2_delete_bystring(ksidstr);
942                 ret = NT_STATUS_UNSUCCESSFUL;
943                 goto done;
944         }
945
946         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
947         ret = NT_STATUS_OK;
948
949 done:
950         talloc_free(ksidstr);
951         talloc_free(kidstr);
952         SAFE_FREE(data.dptr);
953         TALLOC_FREE(update_lock);
954         return ret;
955 }
956
957 /*
958   remove a mapping. 
959 */
960 static NTSTATUS idmap_tdb2_remove_mapping(struct idmap_domain *dom, const struct id_map *map)
961 {
962         /* not supported as it would invalidate the cache tdb on other
963            nodes */
964         DEBUG(0,("idmap_tdb2_remove_mapping not supported\n"));
965         return NT_STATUS_NOT_SUPPORTED;
966 }
967
968 /*
969   Close the idmap tdb instance
970 */
971 static NTSTATUS idmap_tdb2_close(struct idmap_domain *dom)
972 {
973         /* don't do anything */
974         return NT_STATUS_OK;
975 }
976
977
978 /*
979   Dump all mappings out
980 */
981 static NTSTATUS idmap_tdb2_dump_data(struct idmap_domain *dom, struct id_map **maps, int *num_maps)
982 {
983         DEBUG(0,("idmap_tdb2_dump_data not supported\n"));
984         return NT_STATUS_NOT_SUPPORTED;
985 }
986
987 static struct idmap_methods db_methods = {
988         .init            = idmap_tdb2_db_init,
989         .unixids_to_sids = idmap_tdb2_unixids_to_sids,
990         .sids_to_unixids = idmap_tdb2_sids_to_unixids,
991         .set_mapping     = idmap_tdb2_set_mapping,
992         .remove_mapping  = idmap_tdb2_remove_mapping,
993         .dump_data       = idmap_tdb2_dump_data,
994         .close_fn        = idmap_tdb2_close
995 };
996
997 static struct idmap_alloc_methods db_alloc_methods = {
998         .init        = idmap_tdb2_alloc_init,
999         .allocate_id = idmap_tdb2_allocate_id,
1000         .get_id_hwm  = idmap_tdb2_get_hwm,
1001         .set_id_hwm  = idmap_tdb2_set_hwm,
1002         .close_fn    = idmap_tdb2_alloc_close
1003 };
1004
1005 NTSTATUS idmap_tdb2_init(void)
1006 {
1007         NTSTATUS ret;
1008
1009         /* register both backends */
1010         ret = smb_register_idmap_alloc(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_alloc_methods);
1011         if (! NT_STATUS_IS_OK(ret)) {
1012                 DEBUG(0, ("Unable to register idmap alloc tdb2 module: %s\n", get_friendly_nt_error_msg(ret)));
1013                 return ret;
1014         }
1015
1016         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_methods);
1017 }