Remove "idmap alloc config : range" parameter
[metze/samba/wip.git] / source3 / winbindd / idmap_tdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    idmap TDB backend
5
6    Copyright (C) Tim Potter 2000
7    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
8    Copyright (C) Jeremy Allison 2006
9    Copyright (C) Simo Sorce 2003-2006
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_IDMAP
30
31 /* High water mark keys */
32 #define HWM_GROUP  "GROUP HWM"
33 #define HWM_USER   "USER HWM"
34
35 static struct idmap_tdb_state {
36
37         /* User and group id pool */
38         uid_t low_uid, high_uid;               /* Range of uids to allocate */
39         gid_t low_gid, high_gid;               /* Range of gids to allocate */
40
41 } idmap_tdb_state;
42
43 /*****************************************************************************
44  For idmap conversion: convert one record to new format
45  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
46  instead of the SID.
47 *****************************************************************************/
48 static int convert_fn(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA data, void *state)
49 {
50         struct winbindd_domain *domain;
51         char *p;
52         DOM_SID sid;
53         uint32 rid;
54         fstring keystr;
55         fstring dom_name;
56         TDB_DATA key2;
57         bool *failed = (bool *)state;
58
59         DEBUG(10,("Converting %s\n", (const char *)key.dptr));
60
61         p = strchr((const char *)key.dptr, '/');
62         if (!p)
63                 return 0;
64
65         *p = 0;
66         fstrcpy(dom_name, (const char *)key.dptr);
67         *p++ = '/';
68
69         domain = find_domain_from_name(dom_name);
70         if (domain == NULL) {
71                 /* We must delete the old record. */
72                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
73                 DEBUG(0,("deleting record %s\n", (const char *)key.dptr ));
74
75                 if (tdb_delete(tdb, key) != 0) {
76                         DEBUG(0, ("Unable to delete record %s\n", (const char *)key.dptr));
77                         *failed = True;
78                         return -1;
79                 }
80
81                 return 0;
82         }
83
84         rid = atoi(p);
85
86         sid_copy(&sid, &domain->sid);
87         sid_append_rid(&sid, rid);
88
89         sid_to_fstring(keystr, &sid);
90         key2 = string_term_tdb_data(keystr);
91
92         if (tdb_store(tdb, key2, data, TDB_INSERT) != 0) {
93                 DEBUG(0,("Unable to add record %s\n", (const char *)key2.dptr ));
94                 *failed = True;
95                 return -1;
96         }
97
98         if (tdb_store(tdb, data, key2, TDB_REPLACE) != 0) {
99                 DEBUG(0,("Unable to update record %s\n", (const char *)data.dptr ));
100                 *failed = True;
101                 return -1;
102         }
103
104         if (tdb_delete(tdb, key) != 0) {
105                 DEBUG(0,("Unable to delete record %s\n", (const char *)key.dptr ));
106                 *failed = True;
107                 return -1;
108         }
109
110         return 0;
111 }
112
113 /*****************************************************************************
114  Convert the idmap database from an older version.
115 *****************************************************************************/
116
117 static bool idmap_tdb_upgrade(const char *idmap_name)
118 {
119         int32 vers;
120         bool bigendianheader;
121         bool failed = False;
122         TDB_CONTEXT *idmap_tdb;
123
124         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
125
126         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
127                                         TDB_DEFAULT, O_RDWR,
128                                         0600))) {
129                 DEBUG(0, ("Unable to open idmap database\n"));
130                 return False;
131         }
132
133         bigendianheader = (tdb_get_flags(idmap_tdb) & TDB_BIGENDIAN) ? True : False;
134
135         vers = tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION");
136
137         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
138                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
139                 /*
140                  * high and low records were created on a
141                  * big endian machine and will need byte-reversing.
142                  */
143
144                 int32 wm;
145
146                 wm = tdb_fetch_int32(idmap_tdb, HWM_USER);
147
148                 if (wm != -1) {
149                         wm = IREV(wm);
150                 }  else {
151                         wm = idmap_tdb_state.low_uid;
152                 }
153
154                 if (tdb_store_int32(idmap_tdb, HWM_USER, wm) == -1) {
155                         DEBUG(0, ("Unable to byteswap user hwm in idmap database\n"));
156                         tdb_close(idmap_tdb);
157                         return False;
158                 }
159
160                 wm = tdb_fetch_int32(idmap_tdb, HWM_GROUP);
161                 if (wm != -1) {
162                         wm = IREV(wm);
163                 } else {
164                         wm = idmap_tdb_state.low_gid;
165                 }
166
167                 if (tdb_store_int32(idmap_tdb, HWM_GROUP, wm) == -1) {
168                         DEBUG(0, ("Unable to byteswap group hwm in idmap database\n"));
169                         tdb_close(idmap_tdb);
170                         return False;
171                 }
172         }
173
174         /* the old format stored as DOMAIN/rid - now we store the SID direct */
175         tdb_traverse(idmap_tdb, convert_fn, &failed);
176
177         if (failed) {
178                 DEBUG(0, ("Problem during conversion\n"));
179                 tdb_close(idmap_tdb);
180                 return False;
181         }
182
183         if (tdb_store_int32(idmap_tdb, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
184                 DEBUG(0, ("Unable to dtore idmap version in databse\n"));
185                 tdb_close(idmap_tdb);
186                 return False;
187         }
188
189         tdb_close(idmap_tdb);
190         return True;
191 }
192
193 /* WARNING: We can't open a tdb twice inthe same process, for that reason
194  * I'm going to use a hack with open ref counts to open the winbindd_idmap.tdb
195  * only once. We will later decide whether to split the db in multiple files
196  * or come up with a better solution to share them. */
197
198 static TDB_CONTEXT *idmap_tdb_common_ctx;
199 static int idmap_tdb_open_ref_count = 0;
200
201 static NTSTATUS idmap_tdb_open_db(TALLOC_CTX *memctx, TDB_CONTEXT **tdbctx)
202 {
203         NTSTATUS ret;
204         TALLOC_CTX *ctx;
205         SMB_STRUCT_STAT stbuf;
206         char *tdbfile = NULL;
207         int32 version;
208         bool tdb_is_new = False;
209
210         if (idmap_tdb_open_ref_count) { /* the tdb has already been opened */
211                 idmap_tdb_open_ref_count++;
212                 *tdbctx = idmap_tdb_common_ctx;
213                 return NT_STATUS_OK;
214         }
215
216         /* use our own context here */
217         ctx = talloc_new(memctx);
218         if (!ctx) {
219                 DEBUG(0, ("Out of memory!\n"));
220                 return NT_STATUS_NO_MEMORY;
221         }
222
223         /* use the old database if present */
224         tdbfile = talloc_strdup(ctx, state_path("winbindd_idmap.tdb"));
225         if (!tdbfile) {
226                 DEBUG(0, ("Out of memory!\n"));
227                 ret = NT_STATUS_NO_MEMORY;
228                 goto done;
229         }
230
231         if (!file_exist(tdbfile, &stbuf)) {
232                 tdb_is_new = True;
233         }
234
235         DEBUG(10,("Opening tdbfile %s\n", tdbfile ));
236
237         /* Open idmap repository */
238         if (!(idmap_tdb_common_ctx = tdb_open_log(tdbfile, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644))) {
239                 DEBUG(0, ("Unable to open idmap database\n"));
240                 ret = NT_STATUS_UNSUCCESSFUL;
241                 goto done;
242         }
243
244         if (tdb_is_new) {
245                 /* the file didn't existed before opening it, let's
246                  * store idmap version as nobody else yet opened and
247                  * stored it. I do not like this method but didn't
248                  * found a way to understand if an opened tdb have
249                  * been just created or not --- SSS */
250                 tdb_store_int32(idmap_tdb_common_ctx, "IDMAP_VERSION", IDMAP_VERSION);
251         }
252
253         /* check against earlier versions */
254         version = tdb_fetch_int32(idmap_tdb_common_ctx, "IDMAP_VERSION");
255         if (version != IDMAP_VERSION) {
256                 
257                 /* backup_tdb expects the tdb not to be open */
258                 tdb_close(idmap_tdb_common_ctx);
259
260                 if ( ! idmap_tdb_upgrade(tdbfile)) {
261                 
262                         DEBUG(0, ("Unable to open idmap database, it's in an old formati, and upgrade failed!\n"));
263                         ret = NT_STATUS_INTERNAL_DB_ERROR;
264                         goto done;
265                 }
266
267                 /* Re-Open idmap repository */
268                 if (!(idmap_tdb_common_ctx = tdb_open_log(tdbfile, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644))) {
269                         DEBUG(0, ("Unable to open idmap database\n"));
270                         ret = NT_STATUS_UNSUCCESSFUL;
271                         goto done;
272                 }
273         }
274
275         *tdbctx = idmap_tdb_common_ctx;
276         idmap_tdb_open_ref_count++;
277         ret = NT_STATUS_OK;
278
279 done:
280         talloc_free(ctx);
281         return ret;
282 }
283
284  /* NEVER use tdb_close() except for the conversion routines that are guaranteed
285  * to run only when the database is opened the first time, always use this function. */ 
286
287 bool idmap_tdb_tdb_close(TDB_CONTEXT *tdbctx)
288 {
289         if (tdbctx != idmap_tdb_common_ctx) {
290                 DEBUG(0, ("ERROR: Invalid tdb context!"));
291                 return False;
292         }
293
294         idmap_tdb_open_ref_count--;
295         if (idmap_tdb_open_ref_count) {
296                 return True;
297         }
298
299         return tdb_close(idmap_tdb_common_ctx);
300 }
301
302 /**********************************************************************
303  IDMAP ALLOC TDB BACKEND
304 **********************************************************************/
305  
306 static TDB_CONTEXT *idmap_alloc_tdb;
307
308 /**********************************
309  Initialise idmap alloc database. 
310 **********************************/
311
312 static NTSTATUS idmap_tdb_alloc_init( const char *params )
313 {
314         NTSTATUS ret;
315         TALLOC_CTX *ctx;
316         const char *range;
317         uid_t low_uid = 0;
318         uid_t high_uid = 0;
319         gid_t low_gid = 0;
320         gid_t high_gid = 0;
321         uint32_t low_id, high_id;
322
323         /* use our own context here */
324         ctx = talloc_new(NULL);
325         if (!ctx) {
326                 DEBUG(0, ("Out of memory!\n"));
327                 return NT_STATUS_NO_MEMORY;
328         }
329
330         ret = idmap_tdb_open_db(ctx, &idmap_alloc_tdb);
331         if ( ! NT_STATUS_IS_OK(ret)) {
332                 talloc_free(ctx);
333                 return ret;
334         }
335
336         talloc_free(ctx);
337
338         /* load ranges */
339
340         if (!lp_idmap_uid(&low_uid, &high_uid)
341             || !lp_idmap_gid(&low_gid, &high_gid)) {
342                 DEBUG(1, ("idmap uid or idmap gid missing\n"));
343                 return NT_STATUS_UNSUCCESSFUL;
344         }
345
346         idmap_tdb_state.low_uid = low_uid;
347         idmap_tdb_state.high_uid = high_uid;
348         idmap_tdb_state.low_gid = low_gid;
349         idmap_tdb_state.high_gid = high_gid;
350
351         if (idmap_tdb_state.high_uid <= idmap_tdb_state.low_uid) {
352                 DEBUG(1, ("idmap uid range missing or invalid\n"));
353                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
354                 return NT_STATUS_UNSUCCESSFUL;
355         }
356
357         if (idmap_tdb_state.high_gid <= idmap_tdb_state.low_gid) {
358                 DEBUG(1, ("idmap gid range missing or invalid\n"));
359                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
360                 return NT_STATUS_UNSUCCESSFUL;
361         }
362
363         if (((low_id = tdb_fetch_int32(idmap_alloc_tdb, HWM_USER)) == -1) ||
364             (low_id < idmap_tdb_state.low_uid)) {
365                 if (tdb_store_int32(idmap_alloc_tdb, HWM_USER,
366                                     idmap_tdb_state.low_uid) == -1) {
367                         DEBUG(0, ("Unable to initialise user hwm in idmap "
368                                   "database\n"));
369                         return NT_STATUS_INTERNAL_DB_ERROR;
370                 }
371         }
372
373         if (((low_id = tdb_fetch_int32(idmap_alloc_tdb, HWM_GROUP)) == -1) ||
374             (low_id < idmap_tdb_state.low_gid)) {
375                 if (tdb_store_int32(idmap_alloc_tdb, HWM_GROUP,
376                                     idmap_tdb_state.low_gid) == -1) {
377                         DEBUG(0, ("Unable to initialise group hwm in idmap "
378                                   "database\n"));
379                         return NT_STATUS_INTERNAL_DB_ERROR;
380                 }
381         }
382
383         return NT_STATUS_OK;
384 }
385
386 /**********************************
387  Allocate a new id. 
388 **********************************/
389
390 static NTSTATUS idmap_tdb_allocate_id(struct unixid *xid)
391 {
392         bool ret;
393         const char *hwmkey;
394         const char *hwmtype;
395         uint32_t high_hwm;
396         uint32_t hwm;
397
398         /* Get current high water mark */
399         switch (xid->type) {
400
401         case ID_TYPE_UID:
402                 hwmkey = HWM_USER;
403                 hwmtype = "UID";
404                 high_hwm = idmap_tdb_state.high_uid;
405                 break;
406
407         case ID_TYPE_GID:
408                 hwmkey = HWM_GROUP;
409                 hwmtype = "GID";
410                 high_hwm = idmap_tdb_state.high_gid;
411                 break;
412
413         default:
414                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
415                 return NT_STATUS_INVALID_PARAMETER;
416         }
417
418         if ((hwm = tdb_fetch_int32(idmap_alloc_tdb, hwmkey)) == -1) {
419                 return NT_STATUS_INTERNAL_DB_ERROR;
420         }
421
422         /* check it is in the range */
423         if (hwm > high_hwm) {
424                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
425                           hwmtype, (unsigned long)high_hwm));
426                 return NT_STATUS_UNSUCCESSFUL;
427         }
428
429         /* fetch a new id and increment it */
430         ret = tdb_change_uint32_atomic(idmap_alloc_tdb, hwmkey, &hwm, 1);
431         if (!ret) {
432                 DEBUG(1, ("Fatal error while fetching a new %s value\n!", hwmtype));
433                 return NT_STATUS_UNSUCCESSFUL;
434         }
435
436         /* recheck it is in the range */
437         if (hwm > high_hwm) {
438                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
439                           hwmtype, (unsigned long)high_hwm));
440                 return NT_STATUS_UNSUCCESSFUL;
441         }
442         
443         xid->id = hwm;
444         DEBUG(10,("New %s = %d\n", hwmtype, hwm));
445
446         return NT_STATUS_OK;
447 }
448
449 /**********************************
450  Get current highest id. 
451 **********************************/
452
453 static NTSTATUS idmap_tdb_get_hwm(struct unixid *xid)
454 {
455         const char *hwmkey;
456         const char *hwmtype;
457         uint32_t hwm;
458         uint32_t high_hwm;
459
460         /* Get current high water mark */
461         switch (xid->type) {
462
463         case ID_TYPE_UID:
464                 hwmkey = HWM_USER;
465                 hwmtype = "UID";
466                 high_hwm = idmap_tdb_state.high_uid;
467                 break;
468
469         case ID_TYPE_GID:
470                 hwmkey = HWM_GROUP;
471                 hwmtype = "GID";
472                 high_hwm = idmap_tdb_state.high_gid;
473                 break;
474
475         default:
476                 return NT_STATUS_INVALID_PARAMETER;
477         }
478
479         if ((hwm = tdb_fetch_int32(idmap_alloc_tdb, hwmkey)) == -1) {
480                 return NT_STATUS_INTERNAL_DB_ERROR;
481         }
482
483         xid->id = hwm;
484
485         /* Warn if it is out of range */
486         if (hwm >= high_hwm) {
487                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
488                           hwmtype, (unsigned long)high_hwm));
489         }
490
491         return NT_STATUS_OK;
492 }
493
494 /**********************************
495  Set high id. 
496 **********************************/
497
498 static NTSTATUS idmap_tdb_set_hwm(struct unixid *xid)
499 {
500         const char *hwmkey;
501         const char *hwmtype;
502         uint32_t hwm;
503         uint32_t high_hwm;
504
505         /* Get current high water mark */
506         switch (xid->type) {
507
508         case ID_TYPE_UID:
509                 hwmkey = HWM_USER;
510                 hwmtype = "UID";
511                 high_hwm = idmap_tdb_state.high_uid;
512                 break;
513
514         case ID_TYPE_GID:
515                 hwmkey = HWM_GROUP;
516                 hwmtype = "GID";
517                 high_hwm = idmap_tdb_state.high_gid;
518                 break;
519
520         default:
521                 return NT_STATUS_INVALID_PARAMETER;
522         }
523
524         hwm = xid->id;
525
526         if ((hwm = tdb_store_int32(idmap_alloc_tdb, hwmkey, hwm)) == -1) {
527                 return NT_STATUS_INTERNAL_DB_ERROR;
528         }
529
530         /* Warn if it is out of range */
531         if (hwm >= high_hwm) {
532                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
533                           hwmtype, (unsigned long)high_hwm));
534         }
535
536         return NT_STATUS_OK;
537 }
538
539 /**********************************
540  Close the alloc tdb 
541 **********************************/
542
543 static NTSTATUS idmap_tdb_alloc_close(void)
544 {
545         if (idmap_alloc_tdb) {
546                 if (idmap_tdb_tdb_close(idmap_alloc_tdb) == 0) {
547                         return NT_STATUS_OK;
548                 } else {
549                         return NT_STATUS_UNSUCCESSFUL;
550                 }
551         }
552         return NT_STATUS_OK;
553 }
554
555 /**********************************************************************
556  IDMAP MAPPING TDB BACKEND
557 **********************************************************************/
558  
559 struct idmap_tdb_context {
560         TDB_CONTEXT *tdb;
561         uint32_t filter_low_id;
562         uint32_t filter_high_id;
563 };
564
565 /*****************************
566  Initialise idmap database. 
567 *****************************/
568
569 static NTSTATUS idmap_tdb_db_init(struct idmap_domain *dom, const char *params)
570 {
571         NTSTATUS ret;
572         struct idmap_tdb_context *ctx;
573         char *config_option = NULL;
574         const char *range;
575
576         ctx = talloc(dom, struct idmap_tdb_context);
577         if ( ! ctx) {
578                 DEBUG(0, ("Out of memory!\n"));
579                 return NT_STATUS_NO_MEMORY;
580         }
581
582         config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
583         if ( ! config_option) {
584                 DEBUG(0, ("Out of memory!\n"));
585                 ret = NT_STATUS_NO_MEMORY;
586                 goto failed;
587         }
588
589         ret = idmap_tdb_open_db(ctx, &ctx->tdb);
590         if ( ! NT_STATUS_IS_OK(ret)) {
591                 goto failed;
592         }
593
594         range = lp_parm_const_string(-1, config_option, "range", NULL);
595         if (( ! range) ||
596             (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2) ||
597             (ctx->filter_low_id > ctx->filter_high_id)) {
598                 ctx->filter_low_id = 0;
599                 ctx->filter_high_id = 0;
600         }
601
602         dom->private_data = ctx;
603
604         talloc_free(config_option);
605         return NT_STATUS_OK;
606
607 failed:
608         talloc_free(ctx);
609         return ret;
610 }
611
612 /**********************************
613  Single id to sid lookup function. 
614 **********************************/
615
616 static NTSTATUS idmap_tdb_id_to_sid(struct idmap_tdb_context *ctx, struct id_map *map)
617 {
618         NTSTATUS ret;
619         TDB_DATA data;
620         char *keystr;
621
622         if (!ctx || !map) {
623                 return NT_STATUS_INVALID_PARAMETER;
624         }
625
626         /* apply filters before checking */
627         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
628             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
629                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
630                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
631                 return NT_STATUS_NONE_MAPPED;
632         }
633
634         switch (map->xid.type) {
635
636         case ID_TYPE_UID:
637                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
638                 break;
639                 
640         case ID_TYPE_GID:
641                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
642                 break;
643
644         default:
645                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
646                 return NT_STATUS_INVALID_PARAMETER;
647         }
648
649         /* final SAFE_FREE safe */
650         data.dptr = NULL;
651
652         if (keystr == NULL) {
653                 DEBUG(0, ("Out of memory!\n"));
654                 ret = NT_STATUS_NO_MEMORY;
655                 goto done;
656         }
657
658         DEBUG(10,("Fetching record %s\n", keystr));
659
660         /* Check if the mapping exists */
661         data = tdb_fetch_bystring(ctx->tdb, keystr);
662
663         if (!data.dptr) {
664                 DEBUG(10,("Record %s not found\n", keystr));
665                 ret = NT_STATUS_NONE_MAPPED;
666                 goto done;
667         }
668                 
669         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
670                 DEBUG(10,("INVALID SID (%s) in record %s\n",
671                         (const char *)data.dptr, keystr));
672                 ret = NT_STATUS_INTERNAL_DB_ERROR;
673                 goto done;
674         }
675
676         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
677         ret = NT_STATUS_OK;
678
679 done:
680         SAFE_FREE(data.dptr);
681         talloc_free(keystr);
682         return ret;
683 }
684
685 /**********************************
686  Single sid to id lookup function. 
687 **********************************/
688
689 static NTSTATUS idmap_tdb_sid_to_id(struct idmap_tdb_context *ctx, struct id_map *map)
690 {
691         NTSTATUS ret;
692         TDB_DATA data;
693         char *keystr;
694         unsigned long rec_id = 0;
695         fstring tmp;
696
697         if ((keystr = talloc_asprintf(
698                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
699                 DEBUG(0, ("Out of memory!\n"));
700                 ret = NT_STATUS_NO_MEMORY;
701                 goto done;
702         }
703
704         DEBUG(10,("Fetching record %s\n", keystr));
705
706         /* Check if sid is present in database */
707         data = tdb_fetch_bystring(ctx->tdb, keystr);
708         if (!data.dptr) {
709                 DEBUG(10,("Record %s not found\n", keystr));
710                 ret = NT_STATUS_NONE_MAPPED;
711                 goto done;
712         }
713
714         /* What type of record is this ? */
715         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
716                 map->xid.id = rec_id;
717                 map->xid.type = ID_TYPE_UID;
718                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
719                 ret = NT_STATUS_OK;
720
721         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
722                 map->xid.id = rec_id;
723                 map->xid.type = ID_TYPE_GID;
724                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
725                 ret = NT_STATUS_OK;
726
727         } else { /* Unknown record type ! */
728                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
729                 ret = NT_STATUS_INTERNAL_DB_ERROR;
730         }
731         
732         SAFE_FREE(data.dptr);
733
734         /* apply filters before returning result */
735         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
736             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
737                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
738                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
739                 ret = NT_STATUS_NONE_MAPPED;
740         }
741
742 done:
743         talloc_free(keystr);
744         return ret;
745 }
746
747 /**********************************
748  lookup a set of unix ids. 
749 **********************************/
750
751 static NTSTATUS idmap_tdb_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
752 {
753         struct idmap_tdb_context *ctx;
754         NTSTATUS ret;
755         int i;
756
757         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
758
759         for (i = 0; ids[i]; i++) {
760                 ret = idmap_tdb_id_to_sid(ctx, ids[i]);
761                 if ( ! NT_STATUS_IS_OK(ret)) {
762
763                         /* if it is just a failed mapping continue */
764                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
765
766                                 /* make sure it is marked as unmapped */
767                                 ids[i]->status = ID_UNMAPPED;
768                                 continue;
769                         }
770                         
771                         /* some fatal error occurred, return immediately */
772                         goto done;
773                 }
774
775                 /* all ok, id is mapped */
776                 ids[i]->status = ID_MAPPED;
777         }
778
779         ret = NT_STATUS_OK;
780
781 done:
782         return ret;
783 }
784
785 /**********************************
786  lookup a set of sids. 
787 **********************************/
788
789 static NTSTATUS idmap_tdb_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
790 {
791         struct idmap_tdb_context *ctx;
792         NTSTATUS ret;
793         int i;
794
795         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
796
797         for (i = 0; ids[i]; i++) {
798                 ret = idmap_tdb_sid_to_id(ctx, ids[i]);
799                 if ( ! NT_STATUS_IS_OK(ret)) {
800
801                         /* if it is just a failed mapping continue */
802                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
803
804                                 /* make sure it is marked as unmapped */
805                                 ids[i]->status = ID_UNMAPPED;
806                                 continue;
807                         }
808                         
809                         /* some fatal error occurred, return immediately */
810                         goto done;
811                 }
812
813                 /* all ok, id is mapped */
814                 ids[i]->status = ID_MAPPED;
815         }
816
817         ret = NT_STATUS_OK;
818
819 done:
820         return ret;
821 }
822
823 /**********************************
824  set a mapping. 
825 **********************************/
826
827 static NTSTATUS idmap_tdb_set_mapping(struct idmap_domain *dom, const struct id_map *map)
828 {
829         struct idmap_tdb_context *ctx;
830         NTSTATUS ret;
831         TDB_DATA ksid, kid, data;
832         char *ksidstr, *kidstr;
833         fstring tmp;
834
835         if (!map || !map->sid) {
836                 return NT_STATUS_INVALID_PARAMETER;
837         }
838
839         ksidstr = kidstr = NULL;
840         data.dptr = NULL;
841
842         /* TODO: should we filter a set_mapping using low/high filters ? */
843         
844         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
845
846         switch (map->xid.type) {
847
848         case ID_TYPE_UID:
849                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
850                 break;
851                 
852         case ID_TYPE_GID:
853                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
854                 break;
855
856         default:
857                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
858                 return NT_STATUS_INVALID_PARAMETER;
859         }
860
861         if (kidstr == NULL) {
862                 DEBUG(0, ("ERROR: Out of memory!\n"));
863                 ret = NT_STATUS_NO_MEMORY;
864                 goto done;
865         }
866
867         if ((ksidstr = talloc_asprintf(
868                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
869                 DEBUG(0, ("Out of memory!\n"));
870                 ret = NT_STATUS_NO_MEMORY;
871                 goto done;
872         }
873
874         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
875         kid = string_term_tdb_data(kidstr);
876         ksid = string_term_tdb_data(ksidstr);
877
878         /* *DELETE* previous mappings if any.
879          * This is done both SID and [U|G]ID passed in */
880         
881         /* Lock the record for this SID. */
882         if (tdb_chainlock(ctx->tdb, ksid) != 0) {
883                 DEBUG(10,("Failed to lock record %s. Error %s\n",
884                                 ksidstr, tdb_errorstr(ctx->tdb) ));
885                 return NT_STATUS_UNSUCCESSFUL;
886         }
887
888         data = tdb_fetch(ctx->tdb, ksid);
889         if (data.dptr) {
890                 DEBUG(10, ("Deleting existing mapping %s <-> %s\n", (const char *)data.dptr, ksidstr ));
891                 tdb_delete(ctx->tdb, data);
892                 tdb_delete(ctx->tdb, ksid);
893                 SAFE_FREE(data.dptr);
894         }
895
896         data = tdb_fetch(ctx->tdb, kid);
897         if (data.dptr) {
898                 DEBUG(10,("Deleting existing mapping %s <-> %s\n", (const char *)data.dptr, kidstr ));
899                 tdb_delete(ctx->tdb, data);
900                 tdb_delete(ctx->tdb, kid);
901                 SAFE_FREE(data.dptr);
902         }
903
904         if (tdb_store(ctx->tdb, ksid, kid, TDB_INSERT) == -1) {
905                 DEBUG(0, ("Error storing SID -> ID: %s\n", tdb_errorstr(ctx->tdb)));
906                 tdb_chainunlock(ctx->tdb, ksid);
907                 ret = NT_STATUS_UNSUCCESSFUL;
908                 goto done;
909         }
910         if (tdb_store(ctx->tdb, kid, ksid, TDB_INSERT) == -1) {
911                 DEBUG(0, ("Error stroing ID -> SID: %s\n", tdb_errorstr(ctx->tdb)));
912                 /* try to remove the previous stored SID -> ID map */
913                 tdb_delete(ctx->tdb, ksid);
914                 tdb_chainunlock(ctx->tdb, ksid);
915                 ret = NT_STATUS_UNSUCCESSFUL;
916                 goto done;
917         }
918
919         tdb_chainunlock(ctx->tdb, ksid);
920         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
921         ret = NT_STATUS_OK;
922
923 done:
924         talloc_free(ksidstr);
925         talloc_free(kidstr);
926         SAFE_FREE(data.dptr);
927         return ret;
928 }
929
930 /**********************************
931  remove a mapping. 
932 **********************************/
933
934 static NTSTATUS idmap_tdb_remove_mapping(struct idmap_domain *dom, const struct id_map *map)
935 {
936         struct idmap_tdb_context *ctx;
937         NTSTATUS ret;
938         TDB_DATA ksid, kid, data;
939         char *ksidstr, *kidstr;
940         fstring tmp;
941
942         if (!map || !map->sid) {
943                 return NT_STATUS_INVALID_PARAMETER;
944         }
945
946         ksidstr = kidstr = NULL;
947         data.dptr = NULL;
948
949         /* TODO: should we filter a remove_mapping using low/high filters ? */
950         
951         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
952
953         switch (map->xid.type) {
954
955         case ID_TYPE_UID:
956                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
957                 break;
958                 
959         case ID_TYPE_GID:
960                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
961                 break;
962
963         default:
964                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
965                 return NT_STATUS_INVALID_PARAMETER;
966         }
967
968         if (kidstr == NULL) {
969                 DEBUG(0, ("ERROR: Out of memory!\n"));
970                 ret = NT_STATUS_NO_MEMORY;
971                 goto done;
972         }
973
974         if ((ksidstr = talloc_asprintf(
975                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
976                 DEBUG(0, ("Out of memory!\n"));
977                 ret = NT_STATUS_NO_MEMORY;
978                 goto done;
979         }
980
981         DEBUG(10, ("Checking %s <-> %s map\n", ksidstr, kidstr));
982         ksid = string_term_tdb_data(ksidstr);
983         kid = string_term_tdb_data(kidstr);
984
985         /* Lock the record for this SID. */
986         if (tdb_chainlock(ctx->tdb, ksid) != 0) {
987                 DEBUG(10,("Failed to lock record %s. Error %s\n",
988                                 ksidstr, tdb_errorstr(ctx->tdb) ));
989                 return NT_STATUS_UNSUCCESSFUL;
990         }
991
992         /* Check if sid is present in database */
993         data = tdb_fetch(ctx->tdb, ksid);
994         if (!data.dptr) {
995                 DEBUG(10,("Record %s not found\n", ksidstr));
996                 tdb_chainunlock(ctx->tdb, ksid);
997                 ret = NT_STATUS_NONE_MAPPED;
998                 goto done;
999         }
1000
1001         /* Check if sid is mapped to the specified ID */
1002         if ((data.dsize != kid.dsize) ||
1003             (memcmp(data.dptr, kid.dptr, data.dsize) != 0)) {
1004                 DEBUG(10,("Specified SID does not map to specified ID\n"));
1005                 DEBUGADD(10,("Actual mapping is %s -> %s\n", ksidstr, (const char *)data.dptr));
1006                 tdb_chainunlock(ctx->tdb, ksid);
1007                 ret = NT_STATUS_NONE_MAPPED;
1008                 goto done;
1009         }
1010         
1011         DEBUG(10, ("Removing %s <-> %s map\n", ksidstr, kidstr));
1012
1013         /* Delete previous mappings. */
1014         
1015         DEBUG(10, ("Deleting existing mapping %s -> %s\n", ksidstr, kidstr ));
1016         tdb_delete(ctx->tdb, ksid);
1017
1018         DEBUG(10,("Deleting existing mapping %s -> %s\n", kidstr, ksidstr ));
1019         tdb_delete(ctx->tdb, kid);
1020
1021         tdb_chainunlock(ctx->tdb, ksid);
1022         ret = NT_STATUS_OK;
1023
1024 done:
1025         talloc_free(ksidstr);
1026         talloc_free(kidstr);
1027         SAFE_FREE(data.dptr);
1028         return ret;
1029 }
1030
1031 /**********************************
1032  Close the idmap tdb instance
1033 **********************************/
1034
1035 static NTSTATUS idmap_tdb_close(struct idmap_domain *dom)
1036 {
1037         struct idmap_tdb_context *ctx;
1038
1039         if (dom->private_data) {
1040                 ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
1041
1042                 if (idmap_tdb_tdb_close(ctx->tdb) == 0) {
1043                         return NT_STATUS_OK;
1044                 } else {
1045                         return NT_STATUS_UNSUCCESSFUL;
1046                 }
1047         }
1048         return NT_STATUS_OK;
1049 }
1050
1051 struct dump_data {
1052         TALLOC_CTX *memctx;
1053         struct id_map **maps;
1054         int *num_maps;
1055         NTSTATUS ret;
1056 };
1057
1058 static int idmap_tdb_dump_one_entry(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA value, void *pdata)
1059 {
1060         struct dump_data *data = talloc_get_type(pdata, struct dump_data);
1061         struct id_map *maps;
1062         int num_maps = *data->num_maps;
1063
1064         /* ignore any record but the ones with a SID as key */
1065         if (strncmp((const char *)key.dptr, "S-", 2) == 0) {
1066
1067                 maps = talloc_realloc(NULL, *data->maps, struct id_map, num_maps+1);
1068                 if ( ! maps) {
1069                         DEBUG(0, ("Out of memory!\n"));
1070                         data->ret = NT_STATUS_NO_MEMORY;
1071                         return -1;
1072                 }
1073                 *data->maps = maps;
1074                 maps[num_maps].sid = talloc(maps, DOM_SID);
1075                 if ( ! maps[num_maps].sid) {
1076                         DEBUG(0, ("Out of memory!\n"));
1077                         data->ret = NT_STATUS_NO_MEMORY;
1078                         return -1;
1079                 }
1080
1081                 if (!string_to_sid(maps[num_maps].sid, (const char *)key.dptr)) {
1082                         DEBUG(10,("INVALID record %s\n", (const char *)key.dptr));
1083                         /* continue even with errors */
1084                         return 0;
1085                 }
1086
1087                 /* Try a UID record. */
1088                 if (sscanf((const char *)value.dptr, "UID %u", &(maps[num_maps].xid.id)) == 1) {
1089                         maps[num_maps].xid.type = ID_TYPE_UID;
1090                         maps[num_maps].status = ID_MAPPED;
1091                         *data->num_maps = num_maps + 1;
1092
1093                 /* Try a GID record. */
1094                 } else
1095                 if (sscanf((const char *)value.dptr, "GID %u", &(maps[num_maps].xid.id)) == 1) {
1096                         maps[num_maps].xid.type = ID_TYPE_GID;
1097                         maps[num_maps].status = ID_MAPPED;
1098                         *data->num_maps = num_maps + 1;
1099
1100                 /* Unknown record type ! */
1101                 } else {
1102                         maps[num_maps].status = ID_UNKNOWN;
1103                         DEBUG(2, ("Found INVALID record %s -> %s\n",
1104                                 (const char *)key.dptr, (const char *)value.dptr));
1105                         /* do not increment num_maps */
1106                 }
1107         }
1108
1109         return 0;
1110 }
1111
1112 /**********************************
1113  Dump all mappings out
1114 **********************************/
1115
1116 static NTSTATUS idmap_tdb_dump_data(struct idmap_domain *dom, struct id_map **maps, int *num_maps)
1117 {
1118         struct idmap_tdb_context *ctx;
1119         struct dump_data *data;
1120         NTSTATUS ret = NT_STATUS_OK;
1121
1122         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
1123
1124         data = TALLOC_ZERO_P(ctx, struct dump_data);
1125         if ( ! data) {
1126                 DEBUG(0, ("Out of memory!\n"));
1127                 return NT_STATUS_NO_MEMORY;
1128         }
1129         data->maps = maps;
1130         data->num_maps = num_maps;
1131         data->ret = NT_STATUS_OK;
1132
1133         tdb_traverse(ctx->tdb, idmap_tdb_dump_one_entry, data);
1134
1135         if ( ! NT_STATUS_IS_OK(data->ret)) {
1136                 ret = data->ret;
1137         }
1138
1139         talloc_free(data);
1140         return ret;
1141 }
1142
1143 static struct idmap_methods db_methods = {
1144
1145         .init = idmap_tdb_db_init,
1146         .unixids_to_sids = idmap_tdb_unixids_to_sids,
1147         .sids_to_unixids = idmap_tdb_sids_to_unixids,
1148         .set_mapping = idmap_tdb_set_mapping,
1149         .remove_mapping = idmap_tdb_remove_mapping,
1150         .dump_data = idmap_tdb_dump_data,
1151         .close_fn = idmap_tdb_close
1152 };
1153
1154 static struct idmap_alloc_methods db_alloc_methods = {
1155
1156         .init = idmap_tdb_alloc_init,
1157         .allocate_id = idmap_tdb_allocate_id,
1158         .get_id_hwm = idmap_tdb_get_hwm,
1159         .set_id_hwm = idmap_tdb_set_hwm,
1160         .close_fn = idmap_tdb_alloc_close
1161 };
1162
1163 NTSTATUS idmap_alloc_tdb_init(void)
1164 {
1165         return smb_register_idmap_alloc(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_alloc_methods);
1166 }
1167
1168 NTSTATUS idmap_tdb_init(void)
1169 {
1170         NTSTATUS ret;
1171
1172         DEBUG(10, ("calling idmap_tdb_init\n"));
1173
1174         /* FIXME: bad hack to actually register also the alloc_tdb module without changining configure.in */
1175         ret = idmap_alloc_tdb_init();
1176         if (! NT_STATUS_IS_OK(ret)) {
1177                 return ret;
1178         }
1179         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_methods);
1180 }