Remove "idmap alloc config : range" parameter
[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         uint32 low_id, high_id;
132
133         /* see if a idmap script is configured */
134         idmap_tdb2_state.idmap_script = lp_parm_const_string(-1, "idmap",
135                                                              "script", NULL);
136
137         if (idmap_tdb2_state.idmap_script) {
138                 DEBUG(1, ("using idmap script '%s'\n",
139                           idmap_tdb2_state.idmap_script));
140         }
141
142         /* load ranges */
143
144         /* Create high water marks for group and user id */
145         if (!lp_idmap_uid(&low_uid, &high_uid)
146             || !lp_idmap_gid(&low_gid, &high_gid)) {
147                 DEBUG(1, ("idmap uid or idmap gid missing\n"));
148                 return NT_STATUS_UNSUCCESSFUL;
149         }
150
151         idmap_tdb2_state.low_uid = low_uid;
152         idmap_tdb2_state.high_uid = high_uid;
153         idmap_tdb2_state.low_gid = low_gid;
154         idmap_tdb2_state.high_gid = high_gid;
155
156         if (idmap_tdb2_state.high_uid <= idmap_tdb2_state.low_uid) {
157                 DEBUG(1, ("idmap uid range missing or invalid\n"));
158                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
159                 return NT_STATUS_UNSUCCESSFUL;
160         }
161
162         if (((low_id = dbwrap_fetch_int32(idmap_tdb2_perm,
163                                           HWM_USER)) == -1) ||
164             (low_id < idmap_tdb2_state.low_uid)) {
165                 if (dbwrap_store_int32(
166                             idmap_tdb2_perm, HWM_USER,
167                             idmap_tdb2_state.low_uid) == -1) {
168                         DEBUG(0, ("Unable to initialise user hwm in idmap "
169                                   "database\n"));
170                         return NT_STATUS_INTERNAL_DB_ERROR;
171                 }
172         }
173
174         if (idmap_tdb2_state.high_gid <= idmap_tdb2_state.low_gid) {
175                 DEBUG(1, ("idmap gid range missing or invalid\n"));
176                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
177                 return NT_STATUS_UNSUCCESSFUL;
178         }
179
180         if (((low_id = dbwrap_fetch_int32(idmap_tdb2_perm,
181                                           HWM_GROUP)) == -1) ||
182             (low_id < idmap_tdb2_state.low_gid)) {
183                 if (dbwrap_store_int32(
184                             idmap_tdb2_perm, HWM_GROUP,
185                             idmap_tdb2_state.low_gid) == -1) {
186                         DEBUG(0, ("Unable to initialise group hwm in idmap "
187                                   "database\n"));
188                         return NT_STATUS_INTERNAL_DB_ERROR;
189                 }
190         }
191
192         return NT_STATUS_OK;
193 }
194
195
196 /*
197   Initialise idmap alloc database. 
198 */
199 static NTSTATUS idmap_tdb2_alloc_init(const char *params)
200 {
201         /* nothing to do - we want to avoid opening the permanent
202            database if possible. Instead we load the params when we
203            first need it. */
204         return NT_STATUS_OK;
205 }
206
207
208 /*
209   Allocate a new id. 
210 */
211 static NTSTATUS idmap_tdb2_allocate_id(struct unixid *xid)
212 {
213         bool ret;
214         const char *hwmkey;
215         const char *hwmtype;
216         uint32_t high_hwm;
217         uint32_t hwm;
218         NTSTATUS status;
219
220         status = idmap_tdb2_open_perm_db();
221         NT_STATUS_NOT_OK_RETURN(status);
222
223         /* Get current high water mark */
224         switch (xid->type) {
225
226         case ID_TYPE_UID:
227                 hwmkey = HWM_USER;
228                 hwmtype = "UID";
229                 high_hwm = idmap_tdb2_state.high_uid;
230                 break;
231
232         case ID_TYPE_GID:
233                 hwmkey = HWM_GROUP;
234                 hwmtype = "GID";
235                 high_hwm = idmap_tdb2_state.high_gid;
236                 break;
237
238         default:
239                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
240                 return NT_STATUS_INVALID_PARAMETER;
241         }
242
243         if ((hwm = dbwrap_fetch_int32(idmap_tdb2_perm, hwmkey)) == -1) {
244                 return NT_STATUS_INTERNAL_DB_ERROR;
245         }
246
247         /* check it is in the range */
248         if (hwm > high_hwm) {
249                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
250                           hwmtype, (unsigned long)high_hwm));
251                 return NT_STATUS_UNSUCCESSFUL;
252         }
253
254         /* fetch a new id and increment it */
255         ret = dbwrap_change_uint32_atomic(idmap_tdb2_perm, hwmkey, &hwm, 1);
256         if (ret == -1) {
257                 DEBUG(1, ("Fatal error while fetching a new %s value\n!", hwmtype));
258                 return NT_STATUS_UNSUCCESSFUL;
259         }
260
261         /* recheck it is in the range */
262         if (hwm > high_hwm) {
263                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
264                           hwmtype, (unsigned long)high_hwm));
265                 return NT_STATUS_UNSUCCESSFUL;
266         }
267         
268         xid->id = hwm;
269         DEBUG(10,("New %s = %d\n", hwmtype, hwm));
270
271         return NT_STATUS_OK;
272 }
273
274 /*
275   Get current highest id. 
276 */
277 static NTSTATUS idmap_tdb2_get_hwm(struct unixid *xid)
278 {
279         const char *hwmkey;
280         const char *hwmtype;
281         uint32_t hwm;
282         uint32_t high_hwm;
283
284         /* Get current high water mark */
285         switch (xid->type) {
286
287         case ID_TYPE_UID:
288                 hwmkey = HWM_USER;
289                 hwmtype = "UID";
290                 high_hwm = idmap_tdb2_state.high_uid;
291                 break;
292
293         case ID_TYPE_GID:
294                 hwmkey = HWM_GROUP;
295                 hwmtype = "GID";
296                 high_hwm = idmap_tdb2_state.high_gid;
297                 break;
298
299         default:
300                 return NT_STATUS_INVALID_PARAMETER;
301         }
302
303         if ((hwm = dbwrap_fetch_int32(idmap_tdb2_perm, hwmkey)) == -1) {
304                 return NT_STATUS_INTERNAL_DB_ERROR;
305         }
306
307         xid->id = hwm;
308
309         /* Warn if it is out of range */
310         if (hwm >= high_hwm) {
311                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
312                           hwmtype, (unsigned long)high_hwm));
313         }
314
315         return NT_STATUS_OK;
316 }
317
318 /*
319   Set high id. 
320 */
321 static NTSTATUS idmap_tdb2_set_hwm(struct unixid *xid)
322 {
323         /* not supported, or we would invalidate the cache tdb on
324            other nodes */
325         DEBUG(0,("idmap_tdb2_set_hwm not supported\n"));
326         return NT_STATUS_NOT_SUPPORTED;
327 }
328
329 /*
330   Close the alloc tdb 
331 */
332 static NTSTATUS idmap_tdb2_alloc_close(void)
333 {
334         /* don't actually close it */
335         return NT_STATUS_OK;
336 }
337
338 /*
339   IDMAP MAPPING TDB BACKEND
340 */
341 struct idmap_tdb2_context {
342         uint32_t filter_low_id;
343         uint32_t filter_high_id;
344 };
345
346 /*
347   try fetching from the cache tdb, and if that fails then
348   fetch from the permanent tdb
349  */
350 static TDB_DATA tdb2_fetch_bystring(TALLOC_CTX *mem_ctx, const char *keystr)
351 {
352         TDB_DATA ret;
353         NTSTATUS status;
354
355         ret = tdb_fetch_bystring(idmap_tdb2_tmp, keystr);
356         if (ret.dptr != NULL) {
357                 /* got it from cache */
358                 unsigned char *tmp;
359
360                 tmp = (unsigned char *)talloc_memdup(mem_ctx, ret.dptr,
361                                                      ret.dsize);
362                 SAFE_FREE(ret.dptr);
363                 ret.dptr = tmp;
364
365                 if (ret.dptr == NULL) {
366                         return make_tdb_data(NULL, 0);
367                 }
368                 return ret;
369         }
370         
371         status = idmap_tdb2_open_perm_db();
372         if (!NT_STATUS_IS_OK(status)) {
373                 return ret;
374         }
375
376         /* fetch from the permanent tdb */
377         return dbwrap_fetch_bystring(idmap_tdb2_perm, mem_ctx, keystr);
378 }
379
380 /*
381   store into both databases
382  */
383 static NTSTATUS tdb2_store_bystring(const char *keystr, TDB_DATA data, int flags)
384 {
385         NTSTATUS ret;
386         NTSTATUS status = idmap_tdb2_open_perm_db();
387         if (!NT_STATUS_IS_OK(status)) {
388                 return NT_STATUS_UNSUCCESSFUL;
389         }
390         ret = dbwrap_store_bystring(idmap_tdb2_perm, keystr, data, flags);
391         if (!NT_STATUS_IS_OK(ret)) {
392                 ret = tdb_store_bystring(idmap_tdb2_tmp, keystr, data, flags) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
393         }
394         return ret;
395 }
396
397 /*
398   delete from both databases
399  */
400 static NTSTATUS tdb2_delete_bystring(const char *keystr)
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_delete_bystring(idmap_tdb2_perm, keystr);
408         if (!NT_STATUS_IS_OK(ret)) {
409                 ret = tdb_delete_bystring(idmap_tdb2_tmp, keystr)  ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
410         }
411         return ret;
412 }
413
414 /*
415   Initialise idmap database. 
416 */
417 static NTSTATUS idmap_tdb2_db_init(struct idmap_domain *dom,
418                                    const char *params)
419 {
420         NTSTATUS ret;
421         struct idmap_tdb2_context *ctx;
422         char *config_option = NULL;
423         const char *range;
424         NTSTATUS status;
425
426         status = idmap_tdb2_open_cache_db();
427         NT_STATUS_NOT_OK_RETURN(status);
428
429         ctx = talloc(dom, struct idmap_tdb2_context);
430         if ( ! ctx) {
431                 DEBUG(0, ("Out of memory!\n"));
432                 return NT_STATUS_NO_MEMORY;
433         }
434
435         config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
436         if ( ! config_option) {
437                 DEBUG(0, ("Out of memory!\n"));
438                 ret = NT_STATUS_NO_MEMORY;
439                 goto failed;
440         }
441
442         range = lp_parm_const_string(-1, config_option, "range", NULL);
443         if (( ! range) ||
444             (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2) ||
445             (ctx->filter_low_id > ctx->filter_high_id)) {
446                 ctx->filter_low_id = 0;
447                 ctx->filter_high_id = 0;
448         }
449
450         dom->private_data = ctx;
451
452         talloc_free(config_option);
453         return NT_STATUS_OK;
454
455 failed:
456         talloc_free(ctx);
457         return ret;
458 }
459
460
461 /*
462   run a script to perform a mapping
463
464   The script should the following command lines:
465
466       SIDTOID S-1-xxxx
467       IDTOSID UID xxxx
468       IDTOSID GID xxxx
469
470   and should return one of the following as a single line of text
471      UID:xxxx
472      GID:xxxx
473      SID:xxxx
474      ERR:xxxx
475  */
476 static NTSTATUS idmap_tdb2_script(struct idmap_tdb2_context *ctx, struct id_map *map,
477                                   const char *fmt, ...)
478 {
479         va_list ap;
480         char *cmd;
481         FILE *p;
482         char line[64];
483         unsigned long v;
484
485         cmd = talloc_asprintf(ctx, "%s ", idmap_tdb2_state.idmap_script);
486         NT_STATUS_HAVE_NO_MEMORY(cmd);  
487
488         va_start(ap, fmt);
489         cmd = talloc_vasprintf_append(cmd, fmt, ap);
490         va_end(ap);
491         NT_STATUS_HAVE_NO_MEMORY(cmd);
492
493         p = popen(cmd, "r");
494         talloc_free(cmd);
495         if (p == NULL) {
496                 return NT_STATUS_NONE_MAPPED;
497         }
498
499         if (fgets(line, sizeof(line)-1, p) == NULL) {
500                 pclose(p);
501                 return NT_STATUS_NONE_MAPPED;
502         }
503         pclose(p);
504
505         DEBUG(10,("idmap script gave: %s\n", line));
506
507         if (sscanf(line, "UID:%lu", &v) == 1) {
508                 map->xid.id   = v;
509                 map->xid.type = ID_TYPE_UID;
510         } else if (sscanf(line, "GID:%lu", &v) == 1) {
511                 map->xid.id   = v;
512                 map->xid.type = ID_TYPE_GID;            
513         } else if (strncmp(line, "SID:S-", 6) == 0) {
514                 if (!string_to_sid(map->sid, &line[4])) {
515                         DEBUG(0,("Bad SID in '%s' from idmap script %s\n",
516                                  line, idmap_tdb2_state.idmap_script));
517                         return NT_STATUS_NONE_MAPPED;                   
518                 }
519         } else {
520                 DEBUG(0,("Bad reply '%s' from idmap script %s\n",
521                          line, idmap_tdb2_state.idmap_script));
522                 return NT_STATUS_NONE_MAPPED;
523         }
524
525         return NT_STATUS_OK;
526 }
527
528
529
530 /*
531   Single id to sid lookup function. 
532 */
533 static NTSTATUS idmap_tdb2_id_to_sid(struct idmap_tdb2_context *ctx, struct id_map *map)
534 {
535         NTSTATUS ret;
536         TDB_DATA data;
537         char *keystr;
538
539         if (!ctx || !map) {
540                 return NT_STATUS_INVALID_PARAMETER;
541         }
542
543         /* apply filters before checking */
544         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
545             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
546                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
547                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
548                 return NT_STATUS_NONE_MAPPED;
549         }
550
551         switch (map->xid.type) {
552
553         case ID_TYPE_UID:
554                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
555                 break;
556                 
557         case ID_TYPE_GID:
558                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
559                 break;
560
561         default:
562                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
563                 return NT_STATUS_INVALID_PARAMETER;
564         }
565
566         /* final SAFE_FREE safe */
567         data.dptr = NULL;
568
569         if (keystr == NULL) {
570                 DEBUG(0, ("Out of memory!\n"));
571                 ret = NT_STATUS_NO_MEMORY;
572                 goto done;
573         }
574
575         DEBUG(10,("Fetching record %s\n", keystr));
576
577         /* Check if the mapping exists */
578         data = tdb2_fetch_bystring(keystr, keystr);
579
580         if (!data.dptr) {
581                 fstring sidstr;
582
583                 DEBUG(10,("Record %s not found\n", keystr));
584                 if (idmap_tdb2_state.idmap_script == NULL) {
585                         ret = NT_STATUS_NONE_MAPPED;
586                         goto done;
587                 }
588
589                 ret = idmap_tdb2_script(ctx, map, "IDTOSID %s", keystr);
590
591                 /* store it on shared storage */
592                 if (!NT_STATUS_IS_OK(ret)) {
593                         goto done;
594                 }
595
596                 if (sid_to_fstring(sidstr, map->sid)) {
597                         /* both forward and reverse mappings */
598                         tdb2_store_bystring(keystr,
599                                             string_term_tdb_data(sidstr), 
600                                             TDB_REPLACE);
601                         tdb2_store_bystring(sidstr,
602                                             string_term_tdb_data(keystr), 
603                                             TDB_REPLACE);
604                 }
605                 goto done;
606         }
607                 
608         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
609                 DEBUG(10,("INVALID SID (%s) in record %s\n",
610                         (const char *)data.dptr, keystr));
611                 ret = NT_STATUS_INTERNAL_DB_ERROR;
612                 goto done;
613         }
614
615         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
616         ret = NT_STATUS_OK;
617
618 done:
619         talloc_free(keystr);
620         return ret;
621 }
622
623
624 /*
625  Single sid to id lookup function. 
626 */
627 static NTSTATUS idmap_tdb2_sid_to_id(struct idmap_tdb2_context *ctx, struct id_map *map)
628 {
629         NTSTATUS ret;
630         TDB_DATA data;
631         char *keystr;
632         unsigned long rec_id = 0;
633
634         if ((keystr = sid_string_talloc(ctx, map->sid)) == NULL) {
635                 DEBUG(0, ("Out of memory!\n"));
636                 ret = NT_STATUS_NO_MEMORY;
637                 goto done;
638         }
639
640         DEBUG(10,("Fetching record %s\n", keystr));
641
642         /* Check if sid is present in database */
643         data = tdb2_fetch_bystring(keystr, keystr);
644         if (!data.dptr) {
645                 fstring idstr;
646
647                 DEBUG(10,(__location__ " Record %s not found\n", keystr));
648
649                 if (idmap_tdb2_state.idmap_script == NULL) {
650                         ret = NT_STATUS_NONE_MAPPED;
651                         goto done;
652                 }
653                         
654                 ret = idmap_tdb2_script(ctx, map, "SIDTOID %s", keystr);
655                 /* store it on shared storage */
656                 if (!NT_STATUS_IS_OK(ret)) {
657                         goto done;
658                 }
659
660                 snprintf(idstr, sizeof(idstr), "%cID %lu", 
661                          map->xid.type == ID_TYPE_UID?'U':'G',
662                          (unsigned long)map->xid.id);
663                 /* store both forward and reverse mappings */
664                 tdb2_store_bystring(keystr, string_term_tdb_data(idstr),
665                                     TDB_REPLACE);
666                 tdb2_store_bystring(idstr, string_term_tdb_data(keystr),
667                                     TDB_REPLACE);
668                 goto done;
669         }
670
671         /* What type of record is this ? */
672         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
673                 map->xid.id = rec_id;
674                 map->xid.type = ID_TYPE_UID;
675                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
676                 ret = NT_STATUS_OK;
677
678         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
679                 map->xid.id = rec_id;
680                 map->xid.type = ID_TYPE_GID;
681                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
682                 ret = NT_STATUS_OK;
683
684         } else { /* Unknown record type ! */
685                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
686                 ret = NT_STATUS_INTERNAL_DB_ERROR;
687         }
688         
689         /* apply filters before returning result */
690         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
691             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
692                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
693                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
694                 ret = NT_STATUS_NONE_MAPPED;
695         }
696
697 done:
698         talloc_free(keystr);
699         return ret;
700 }
701
702 /*
703   lookup a set of unix ids. 
704 */
705 static NTSTATUS idmap_tdb2_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
706 {
707         struct idmap_tdb2_context *ctx;
708         NTSTATUS ret;
709         int i;
710
711         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
712
713         for (i = 0; ids[i]; i++) {
714                 ret = idmap_tdb2_id_to_sid(ctx, ids[i]);
715                 if ( ! NT_STATUS_IS_OK(ret)) {
716
717                         /* if it is just a failed mapping continue */
718                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
719
720                                 /* make sure it is marked as unmapped */
721                                 ids[i]->status = ID_UNMAPPED;
722                                 continue;
723                         }
724                         
725                         /* some fatal error occurred, return immediately */
726                         goto done;
727                 }
728
729                 /* all ok, id is mapped */
730                 ids[i]->status = ID_MAPPED;
731         }
732
733         ret = NT_STATUS_OK;
734
735 done:
736         return ret;
737 }
738
739 /*
740   lookup a set of sids. 
741 */
742 static NTSTATUS idmap_tdb2_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
743 {
744         struct idmap_tdb2_context *ctx;
745         NTSTATUS ret;
746         int i;
747
748         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
749
750         for (i = 0; ids[i]; i++) {
751                 ret = idmap_tdb2_sid_to_id(ctx, ids[i]);
752                 if ( ! NT_STATUS_IS_OK(ret)) {
753
754                         /* if it is just a failed mapping continue */
755                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
756
757                                 /* make sure it is marked as unmapped */
758                                 ids[i]->status = ID_UNMAPPED;
759                                 continue;
760                         }
761                         
762                         /* some fatal error occurred, return immediately */
763                         goto done;
764                 }
765
766                 /* all ok, id is mapped */
767                 ids[i]->status = ID_MAPPED;
768         }
769
770         ret = NT_STATUS_OK;
771
772 done:
773         return ret;
774 }
775
776
777 /*
778   set a mapping. 
779 */
780 static NTSTATUS idmap_tdb2_set_mapping(struct idmap_domain *dom, const struct id_map *map)
781 {
782         struct idmap_tdb2_context *ctx;
783         NTSTATUS ret;
784         TDB_DATA data;
785         char *ksidstr, *kidstr;
786         struct db_record *update_lock = NULL;
787         struct db_record *rec = NULL;
788
789         if (!map || !map->sid) {
790                 return NT_STATUS_INVALID_PARAMETER;
791         }
792
793         ksidstr = kidstr = NULL;
794         data.dptr = NULL;
795
796         /* TODO: should we filter a set_mapping using low/high filters ? */
797         
798         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
799
800         switch (map->xid.type) {
801
802         case ID_TYPE_UID:
803                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
804                 break;
805                 
806         case ID_TYPE_GID:
807                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
808                 break;
809
810         default:
811                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
812                 return NT_STATUS_INVALID_PARAMETER;
813         }
814
815         if (kidstr == NULL) {
816                 DEBUG(0, ("ERROR: Out of memory!\n"));
817                 ret = NT_STATUS_NO_MEMORY;
818                 goto done;
819         }
820
821         if (!(ksidstr = sid_string_talloc(ctx, map->sid))) {
822                 DEBUG(0, ("Out of memory!\n"));
823                 ret = NT_STATUS_NO_MEMORY;
824                 goto done;
825         }
826
827         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
828
829         /*
830          * Get us the update lock. This is necessary to get the lock orders
831          * right, we need to deal with two records under a lock.
832          */
833
834         if (!(update_lock = idmap_tdb2_perm->fetch_locked(
835                       idmap_tdb2_perm, ctx,
836                       string_term_tdb_data("UPDATELOCK")))) {
837                 DEBUG(10,("Failed to lock record %s\n", ksidstr));
838                 ret = NT_STATUS_UNSUCCESSFUL;
839                 goto done;
840         }
841
842         /*
843          * *DELETE* previous mappings if any. *
844          */
845
846         /* First delete indexed on SID */
847
848         if (((rec = idmap_tdb2_perm->fetch_locked(
849                      idmap_tdb2_perm, update_lock,
850                      string_term_tdb_data(ksidstr))) != NULL)
851             && (rec->value.dsize != 0)) {
852                 struct db_record *rec2;
853
854                 if ((rec2 = idmap_tdb2_perm->fetch_locked(
855                              idmap_tdb2_perm, update_lock, rec->value))
856                     != NULL) {
857                         rec2->delete_rec(rec2);
858                         TALLOC_FREE(rec2);
859                 }
860
861                 rec->delete_rec(rec);
862
863                 tdb_delete(idmap_tdb2_tmp, rec->key);
864                 tdb_delete(idmap_tdb2_tmp, rec->value);
865         }
866         TALLOC_FREE(rec);
867
868         /* Now delete indexed on unix ID */
869
870         if (((rec = idmap_tdb2_perm->fetch_locked(
871                      idmap_tdb2_perm, update_lock,
872                      string_term_tdb_data(kidstr))) != NULL)
873             && (rec->value.dsize != 0)) {
874                 struct db_record *rec2;
875
876                 if ((rec2 = idmap_tdb2_perm->fetch_locked(
877                              idmap_tdb2_perm, update_lock, rec->value))
878                     != NULL) {
879                         rec2->delete_rec(rec2);
880                         TALLOC_FREE(rec2);
881                 }
882
883                 rec->delete_rec(rec);
884
885                 tdb_delete(idmap_tdb2_tmp, rec->key);
886                 tdb_delete(idmap_tdb2_tmp, rec->value);
887         }
888         TALLOC_FREE(rec);
889
890         if (!NT_STATUS_IS_OK(tdb2_store_bystring(ksidstr, string_term_tdb_data(kidstr),
891                                 TDB_INSERT))) {
892                 DEBUG(0, ("Error storing SID -> ID\n"));
893                 ret = NT_STATUS_UNSUCCESSFUL;
894                 goto done;
895         }
896         if (!NT_STATUS_IS_OK(tdb2_store_bystring(kidstr, string_term_tdb_data(ksidstr),
897                                 TDB_INSERT))) {
898                 DEBUG(0, ("Error storing ID -> SID\n"));
899                 /* try to remove the previous stored SID -> ID map */
900                 tdb2_delete_bystring(ksidstr);
901                 ret = NT_STATUS_UNSUCCESSFUL;
902                 goto done;
903         }
904
905         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
906         ret = NT_STATUS_OK;
907
908 done:
909         talloc_free(ksidstr);
910         talloc_free(kidstr);
911         SAFE_FREE(data.dptr);
912         TALLOC_FREE(update_lock);
913         return ret;
914 }
915
916 /*
917   remove a mapping. 
918 */
919 static NTSTATUS idmap_tdb2_remove_mapping(struct idmap_domain *dom, const struct id_map *map)
920 {
921         /* not supported as it would invalidate the cache tdb on other
922            nodes */
923         DEBUG(0,("idmap_tdb2_remove_mapping not supported\n"));
924         return NT_STATUS_NOT_SUPPORTED;
925 }
926
927 /*
928   Close the idmap tdb instance
929 */
930 static NTSTATUS idmap_tdb2_close(struct idmap_domain *dom)
931 {
932         /* don't do anything */
933         return NT_STATUS_OK;
934 }
935
936
937 /*
938   Dump all mappings out
939 */
940 static NTSTATUS idmap_tdb2_dump_data(struct idmap_domain *dom, struct id_map **maps, int *num_maps)
941 {
942         DEBUG(0,("idmap_tdb2_dump_data not supported\n"));
943         return NT_STATUS_NOT_SUPPORTED;
944 }
945
946 static struct idmap_methods db_methods = {
947         .init            = idmap_tdb2_db_init,
948         .unixids_to_sids = idmap_tdb2_unixids_to_sids,
949         .sids_to_unixids = idmap_tdb2_sids_to_unixids,
950         .set_mapping     = idmap_tdb2_set_mapping,
951         .remove_mapping  = idmap_tdb2_remove_mapping,
952         .dump_data       = idmap_tdb2_dump_data,
953         .close_fn        = idmap_tdb2_close
954 };
955
956 static struct idmap_alloc_methods db_alloc_methods = {
957         .init        = idmap_tdb2_alloc_init,
958         .allocate_id = idmap_tdb2_allocate_id,
959         .get_id_hwm  = idmap_tdb2_get_hwm,
960         .set_id_hwm  = idmap_tdb2_set_hwm,
961         .close_fn    = idmap_tdb2_alloc_close
962 };
963
964 NTSTATUS idmap_tdb2_init(void)
965 {
966         NTSTATUS ret;
967
968         /* register both backends */
969         ret = smb_register_idmap_alloc(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_alloc_methods);
970         if (! NT_STATUS_IS_OK(ret)) {
971                 DEBUG(0, ("Unable to register idmap alloc tdb2 module: %s\n", get_friendly_nt_error_msg(ret)));
972                 return ret;
973         }
974
975         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_methods);
976 }