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