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