3f6cccd35adaae6ecb8aff7182275ba135571791
[amitay/samba.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
322         /* use our own context here */
323         ctx = talloc_new(NULL);
324         if (!ctx) {
325                 DEBUG(0, ("Out of memory!\n"));
326                 return NT_STATUS_NO_MEMORY;
327         }
328
329         ret = idmap_tdb_open_db(ctx, &idmap_alloc_tdb);
330         if ( ! NT_STATUS_IS_OK(ret)) {
331                 talloc_free(ctx);
332                 return ret;
333         }
334
335         talloc_free(ctx);
336
337         /* load ranges */
338         idmap_tdb_state.low_uid = 0;
339         idmap_tdb_state.high_uid = 0;
340         idmap_tdb_state.low_gid = 0;
341         idmap_tdb_state.high_gid = 0;
342
343         range = lp_parm_const_string(-1, "idmap alloc config", "range", NULL);
344         if (range && range[0]) {
345                 unsigned low_id, high_id;
346
347                 if (sscanf(range, "%u - %u", &low_id, &high_id) == 2) {
348                         if (low_id < high_id) {
349                                 idmap_tdb_state.low_gid = idmap_tdb_state.low_uid = low_id;
350                                 idmap_tdb_state.high_gid = idmap_tdb_state.high_uid = high_id;
351                         } else {
352                                 DEBUG(1, ("ERROR: invalid idmap alloc range [%s]", range));
353                         }
354                 } else {
355                         DEBUG(1, ("ERROR: invalid syntax for idmap alloc config:range [%s]", range));
356                 }
357         }
358
359         /* Create high water marks for group and user id */
360         if (lp_idmap_uid(&low_uid, &high_uid)) {
361                 idmap_tdb_state.low_uid = low_uid;
362                 idmap_tdb_state.high_uid = high_uid;
363         }
364
365         if (lp_idmap_gid(&low_gid, &high_gid)) {
366                 idmap_tdb_state.low_gid = low_gid;
367                 idmap_tdb_state.high_gid = high_gid;
368         }
369
370         if (idmap_tdb_state.high_uid <= idmap_tdb_state.low_uid) {
371                 DEBUG(1, ("idmap uid range missing or invalid\n"));
372                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
373                 return NT_STATUS_UNSUCCESSFUL;
374         } else {
375                 uint32 low_id;
376
377                 if (((low_id = tdb_fetch_int32(idmap_alloc_tdb, HWM_USER)) == -1) ||
378                     (low_id < idmap_tdb_state.low_uid)) {
379                         if (tdb_store_int32(idmap_alloc_tdb, HWM_USER, idmap_tdb_state.low_uid) == -1) {
380                                 DEBUG(0, ("Unable to initialise user hwm in idmap database\n"));
381                                 return NT_STATUS_INTERNAL_DB_ERROR;
382                         }
383                 }
384         }
385
386         if (idmap_tdb_state.high_gid <= idmap_tdb_state.low_gid) {
387                 DEBUG(1, ("idmap gid range missing or invalid\n"));
388                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
389                 return NT_STATUS_UNSUCCESSFUL;
390         } else {
391                 uint32 low_id;
392
393                 if (((low_id = tdb_fetch_int32(idmap_alloc_tdb, HWM_GROUP)) == -1) ||
394                     (low_id < idmap_tdb_state.low_gid)) {
395                         if (tdb_store_int32(idmap_alloc_tdb, HWM_GROUP, idmap_tdb_state.low_gid) == -1) {
396                                 DEBUG(0, ("Unable to initialise group hwm in idmap database\n"));
397                                 return NT_STATUS_INTERNAL_DB_ERROR;
398                         }
399                 }
400         }
401
402         return NT_STATUS_OK;
403 }
404
405 /**********************************
406  Allocate a new id. 
407 **********************************/
408
409 static NTSTATUS idmap_tdb_allocate_id(struct unixid *xid)
410 {
411         bool ret;
412         const char *hwmkey;
413         const char *hwmtype;
414         uint32_t high_hwm;
415         uint32_t hwm;
416
417         /* Get current high water mark */
418         switch (xid->type) {
419
420         case ID_TYPE_UID:
421                 hwmkey = HWM_USER;
422                 hwmtype = "UID";
423                 high_hwm = idmap_tdb_state.high_uid;
424                 break;
425
426         case ID_TYPE_GID:
427                 hwmkey = HWM_GROUP;
428                 hwmtype = "GID";
429                 high_hwm = idmap_tdb_state.high_gid;
430                 break;
431
432         default:
433                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
434                 return NT_STATUS_INVALID_PARAMETER;
435         }
436
437         if ((hwm = tdb_fetch_int32(idmap_alloc_tdb, hwmkey)) == -1) {
438                 return NT_STATUS_INTERNAL_DB_ERROR;
439         }
440
441         /* check it is in the range */
442         if (hwm > high_hwm) {
443                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
444                           hwmtype, (unsigned long)high_hwm));
445                 return NT_STATUS_UNSUCCESSFUL;
446         }
447
448         /* fetch a new id and increment it */
449         ret = tdb_change_uint32_atomic(idmap_alloc_tdb, hwmkey, &hwm, 1);
450         if (!ret) {
451                 DEBUG(1, ("Fatal error while fetching a new %s value\n!", hwmtype));
452                 return NT_STATUS_UNSUCCESSFUL;
453         }
454
455         /* recheck it is in the range */
456         if (hwm > high_hwm) {
457                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
458                           hwmtype, (unsigned long)high_hwm));
459                 return NT_STATUS_UNSUCCESSFUL;
460         }
461         
462         xid->id = hwm;
463         DEBUG(10,("New %s = %d\n", hwmtype, hwm));
464
465         return NT_STATUS_OK;
466 }
467
468 /**********************************
469  Get current highest id. 
470 **********************************/
471
472 static NTSTATUS idmap_tdb_get_hwm(struct unixid *xid)
473 {
474         const char *hwmkey;
475         const char *hwmtype;
476         uint32_t hwm;
477         uint32_t high_hwm;
478
479         /* Get current high water mark */
480         switch (xid->type) {
481
482         case ID_TYPE_UID:
483                 hwmkey = HWM_USER;
484                 hwmtype = "UID";
485                 high_hwm = idmap_tdb_state.high_uid;
486                 break;
487
488         case ID_TYPE_GID:
489                 hwmkey = HWM_GROUP;
490                 hwmtype = "GID";
491                 high_hwm = idmap_tdb_state.high_gid;
492                 break;
493
494         default:
495                 return NT_STATUS_INVALID_PARAMETER;
496         }
497
498         if ((hwm = tdb_fetch_int32(idmap_alloc_tdb, hwmkey)) == -1) {
499                 return NT_STATUS_INTERNAL_DB_ERROR;
500         }
501
502         xid->id = hwm;
503
504         /* Warn if it is out of range */
505         if (hwm >= high_hwm) {
506                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
507                           hwmtype, (unsigned long)high_hwm));
508         }
509
510         return NT_STATUS_OK;
511 }
512
513 /**********************************
514  Set high id. 
515 **********************************/
516
517 static NTSTATUS idmap_tdb_set_hwm(struct unixid *xid)
518 {
519         const char *hwmkey;
520         const char *hwmtype;
521         uint32_t hwm;
522         uint32_t high_hwm;
523
524         /* Get current high water mark */
525         switch (xid->type) {
526
527         case ID_TYPE_UID:
528                 hwmkey = HWM_USER;
529                 hwmtype = "UID";
530                 high_hwm = idmap_tdb_state.high_uid;
531                 break;
532
533         case ID_TYPE_GID:
534                 hwmkey = HWM_GROUP;
535                 hwmtype = "GID";
536                 high_hwm = idmap_tdb_state.high_gid;
537                 break;
538
539         default:
540                 return NT_STATUS_INVALID_PARAMETER;
541         }
542
543         hwm = xid->id;
544
545         if ((hwm = tdb_store_int32(idmap_alloc_tdb, hwmkey, hwm)) == -1) {
546                 return NT_STATUS_INTERNAL_DB_ERROR;
547         }
548
549         /* Warn if it is out of range */
550         if (hwm >= high_hwm) {
551                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
552                           hwmtype, (unsigned long)high_hwm));
553         }
554
555         return NT_STATUS_OK;
556 }
557
558 /**********************************
559  Close the alloc tdb 
560 **********************************/
561
562 static NTSTATUS idmap_tdb_alloc_close(void)
563 {
564         if (idmap_alloc_tdb) {
565                 if (idmap_tdb_tdb_close(idmap_alloc_tdb) == 0) {
566                         return NT_STATUS_OK;
567                 } else {
568                         return NT_STATUS_UNSUCCESSFUL;
569                 }
570         }
571         return NT_STATUS_OK;
572 }
573
574 /**********************************************************************
575  IDMAP MAPPING TDB BACKEND
576 **********************************************************************/
577  
578 struct idmap_tdb_context {
579         TDB_CONTEXT *tdb;
580         uint32_t filter_low_id;
581         uint32_t filter_high_id;
582 };
583
584 /*****************************
585  Initialise idmap database. 
586 *****************************/
587
588 static NTSTATUS idmap_tdb_db_init(struct idmap_domain *dom, const char *params)
589 {
590         NTSTATUS ret;
591         struct idmap_tdb_context *ctx;
592         char *config_option = NULL;
593         const char *range;
594
595         ctx = talloc(dom, struct idmap_tdb_context);
596         if ( ! ctx) {
597                 DEBUG(0, ("Out of memory!\n"));
598                 return NT_STATUS_NO_MEMORY;
599         }
600
601         config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
602         if ( ! config_option) {
603                 DEBUG(0, ("Out of memory!\n"));
604                 ret = NT_STATUS_NO_MEMORY;
605                 goto failed;
606         }
607
608         ret = idmap_tdb_open_db(ctx, &ctx->tdb);
609         if ( ! NT_STATUS_IS_OK(ret)) {
610                 goto failed;
611         }
612
613         range = lp_parm_const_string(-1, config_option, "range", NULL);
614         if (( ! range) ||
615             (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2) ||
616             (ctx->filter_low_id > ctx->filter_high_id)) {
617                 ctx->filter_low_id = 0;
618                 ctx->filter_high_id = 0;
619         }
620
621         dom->private_data = ctx;
622
623         talloc_free(config_option);
624         return NT_STATUS_OK;
625
626 failed:
627         talloc_free(ctx);
628         return ret;
629 }
630
631 /**********************************
632  Single id to sid lookup function. 
633 **********************************/
634
635 static NTSTATUS idmap_tdb_id_to_sid(struct idmap_tdb_context *ctx, struct id_map *map)
636 {
637         NTSTATUS ret;
638         TDB_DATA data;
639         char *keystr;
640
641         if (!ctx || !map) {
642                 return NT_STATUS_INVALID_PARAMETER;
643         }
644
645         /* apply filters before checking */
646         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
647             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
648                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
649                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
650                 return NT_STATUS_NONE_MAPPED;
651         }
652
653         switch (map->xid.type) {
654
655         case ID_TYPE_UID:
656                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
657                 break;
658                 
659         case ID_TYPE_GID:
660                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
661                 break;
662
663         default:
664                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
665                 return NT_STATUS_INVALID_PARAMETER;
666         }
667
668         /* final SAFE_FREE safe */
669         data.dptr = NULL;
670
671         if (keystr == NULL) {
672                 DEBUG(0, ("Out of memory!\n"));
673                 ret = NT_STATUS_NO_MEMORY;
674                 goto done;
675         }
676
677         DEBUG(10,("Fetching record %s\n", keystr));
678
679         /* Check if the mapping exists */
680         data = tdb_fetch_bystring(ctx->tdb, keystr);
681
682         if (!data.dptr) {
683                 DEBUG(10,("Record %s not found\n", keystr));
684                 ret = NT_STATUS_NONE_MAPPED;
685                 goto done;
686         }
687                 
688         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
689                 DEBUG(10,("INVALID SID (%s) in record %s\n",
690                         (const char *)data.dptr, keystr));
691                 ret = NT_STATUS_INTERNAL_DB_ERROR;
692                 goto done;
693         }
694
695         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
696         ret = NT_STATUS_OK;
697
698 done:
699         SAFE_FREE(data.dptr);
700         talloc_free(keystr);
701         return ret;
702 }
703
704 /**********************************
705  Single sid to id lookup function. 
706 **********************************/
707
708 static NTSTATUS idmap_tdb_sid_to_id(struct idmap_tdb_context *ctx, struct id_map *map)
709 {
710         NTSTATUS ret;
711         TDB_DATA data;
712         char *keystr;
713         unsigned long rec_id = 0;
714         fstring tmp;
715
716         if ((keystr = talloc_asprintf(
717                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
718                 DEBUG(0, ("Out of memory!\n"));
719                 ret = NT_STATUS_NO_MEMORY;
720                 goto done;
721         }
722
723         DEBUG(10,("Fetching record %s\n", keystr));
724
725         /* Check if sid is present in database */
726         data = tdb_fetch_bystring(ctx->tdb, keystr);
727         if (!data.dptr) {
728                 DEBUG(10,("Record %s not found\n", keystr));
729                 ret = NT_STATUS_NONE_MAPPED;
730                 goto done;
731         }
732
733         /* What type of record is this ? */
734         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
735                 map->xid.id = rec_id;
736                 map->xid.type = ID_TYPE_UID;
737                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
738                 ret = NT_STATUS_OK;
739
740         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
741                 map->xid.id = rec_id;
742                 map->xid.type = ID_TYPE_GID;
743                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
744                 ret = NT_STATUS_OK;
745
746         } else { /* Unknown record type ! */
747                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
748                 ret = NT_STATUS_INTERNAL_DB_ERROR;
749         }
750         
751         SAFE_FREE(data.dptr);
752
753         /* apply filters before returning result */
754         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
755             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
756                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
757                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
758                 ret = NT_STATUS_NONE_MAPPED;
759         }
760
761 done:
762         talloc_free(keystr);
763         return ret;
764 }
765
766 /**********************************
767  lookup a set of unix ids. 
768 **********************************/
769
770 static NTSTATUS idmap_tdb_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
771 {
772         struct idmap_tdb_context *ctx;
773         NTSTATUS ret;
774         int i;
775
776         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
777
778         for (i = 0; ids[i]; i++) {
779                 ret = idmap_tdb_id_to_sid(ctx, ids[i]);
780                 if ( ! NT_STATUS_IS_OK(ret)) {
781
782                         /* if it is just a failed mapping continue */
783                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
784
785                                 /* make sure it is marked as unmapped */
786                                 ids[i]->status = ID_UNMAPPED;
787                                 continue;
788                         }
789                         
790                         /* some fatal error occurred, return immediately */
791                         goto done;
792                 }
793
794                 /* all ok, id is mapped */
795                 ids[i]->status = ID_MAPPED;
796         }
797
798         ret = NT_STATUS_OK;
799
800 done:
801         return ret;
802 }
803
804 /**********************************
805  lookup a set of sids. 
806 **********************************/
807
808 static NTSTATUS idmap_tdb_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
809 {
810         struct idmap_tdb_context *ctx;
811         NTSTATUS ret;
812         int i;
813
814         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
815
816         for (i = 0; ids[i]; i++) {
817                 ret = idmap_tdb_sid_to_id(ctx, ids[i]);
818                 if ( ! NT_STATUS_IS_OK(ret)) {
819
820                         /* if it is just a failed mapping continue */
821                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
822
823                                 /* make sure it is marked as unmapped */
824                                 ids[i]->status = ID_UNMAPPED;
825                                 continue;
826                         }
827                         
828                         /* some fatal error occurred, return immediately */
829                         goto done;
830                 }
831
832                 /* all ok, id is mapped */
833                 ids[i]->status = ID_MAPPED;
834         }
835
836         ret = NT_STATUS_OK;
837
838 done:
839         return ret;
840 }
841
842 /**********************************
843  set a mapping. 
844 **********************************/
845
846 static NTSTATUS idmap_tdb_set_mapping(struct idmap_domain *dom, const struct id_map *map)
847 {
848         struct idmap_tdb_context *ctx;
849         NTSTATUS ret;
850         TDB_DATA ksid, kid, data;
851         char *ksidstr, *kidstr;
852         fstring tmp;
853
854         if (!map || !map->sid) {
855                 return NT_STATUS_INVALID_PARAMETER;
856         }
857
858         ksidstr = kidstr = NULL;
859         data.dptr = NULL;
860
861         /* TODO: should we filter a set_mapping using low/high filters ? */
862         
863         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
864
865         switch (map->xid.type) {
866
867         case ID_TYPE_UID:
868                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
869                 break;
870                 
871         case ID_TYPE_GID:
872                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
873                 break;
874
875         default:
876                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
877                 return NT_STATUS_INVALID_PARAMETER;
878         }
879
880         if (kidstr == NULL) {
881                 DEBUG(0, ("ERROR: Out of memory!\n"));
882                 ret = NT_STATUS_NO_MEMORY;
883                 goto done;
884         }
885
886         if ((ksidstr = talloc_asprintf(
887                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
888                 DEBUG(0, ("Out of memory!\n"));
889                 ret = NT_STATUS_NO_MEMORY;
890                 goto done;
891         }
892
893         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
894         kid = string_term_tdb_data(kidstr);
895         ksid = string_term_tdb_data(ksidstr);
896
897         /* *DELETE* previous mappings if any.
898          * This is done both SID and [U|G]ID passed in */
899         
900         /* Lock the record for this SID. */
901         if (tdb_chainlock(ctx->tdb, ksid) != 0) {
902                 DEBUG(10,("Failed to lock record %s. Error %s\n",
903                                 ksidstr, tdb_errorstr(ctx->tdb) ));
904                 return NT_STATUS_UNSUCCESSFUL;
905         }
906
907         data = tdb_fetch(ctx->tdb, ksid);
908         if (data.dptr) {
909                 DEBUG(10, ("Deleting existing mapping %s <-> %s\n", (const char *)data.dptr, ksidstr ));
910                 tdb_delete(ctx->tdb, data);
911                 tdb_delete(ctx->tdb, ksid);
912                 SAFE_FREE(data.dptr);
913         }
914
915         data = tdb_fetch(ctx->tdb, kid);
916         if (data.dptr) {
917                 DEBUG(10,("Deleting existing mapping %s <-> %s\n", (const char *)data.dptr, kidstr ));
918                 tdb_delete(ctx->tdb, data);
919                 tdb_delete(ctx->tdb, kid);
920                 SAFE_FREE(data.dptr);
921         }
922
923         if (tdb_store(ctx->tdb, ksid, kid, TDB_INSERT) == -1) {
924                 DEBUG(0, ("Error storing SID -> ID: %s\n", tdb_errorstr(ctx->tdb)));
925                 tdb_chainunlock(ctx->tdb, ksid);
926                 ret = NT_STATUS_UNSUCCESSFUL;
927                 goto done;
928         }
929         if (tdb_store(ctx->tdb, kid, ksid, TDB_INSERT) == -1) {
930                 DEBUG(0, ("Error stroing ID -> SID: %s\n", tdb_errorstr(ctx->tdb)));
931                 /* try to remove the previous stored SID -> ID map */
932                 tdb_delete(ctx->tdb, ksid);
933                 tdb_chainunlock(ctx->tdb, ksid);
934                 ret = NT_STATUS_UNSUCCESSFUL;
935                 goto done;
936         }
937
938         tdb_chainunlock(ctx->tdb, ksid);
939         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
940         ret = NT_STATUS_OK;
941
942 done:
943         talloc_free(ksidstr);
944         talloc_free(kidstr);
945         SAFE_FREE(data.dptr);
946         return ret;
947 }
948
949 /**********************************
950  remove a mapping. 
951 **********************************/
952
953 static NTSTATUS idmap_tdb_remove_mapping(struct idmap_domain *dom, const struct id_map *map)
954 {
955         struct idmap_tdb_context *ctx;
956         NTSTATUS ret;
957         TDB_DATA ksid, kid, data;
958         char *ksidstr, *kidstr;
959         fstring tmp;
960
961         if (!map || !map->sid) {
962                 return NT_STATUS_INVALID_PARAMETER;
963         }
964
965         ksidstr = kidstr = NULL;
966         data.dptr = NULL;
967
968         /* TODO: should we filter a remove_mapping using low/high filters ? */
969         
970         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
971
972         switch (map->xid.type) {
973
974         case ID_TYPE_UID:
975                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
976                 break;
977                 
978         case ID_TYPE_GID:
979                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
980                 break;
981
982         default:
983                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
984                 return NT_STATUS_INVALID_PARAMETER;
985         }
986
987         if (kidstr == NULL) {
988                 DEBUG(0, ("ERROR: Out of memory!\n"));
989                 ret = NT_STATUS_NO_MEMORY;
990                 goto done;
991         }
992
993         if ((ksidstr = talloc_asprintf(
994                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
995                 DEBUG(0, ("Out of memory!\n"));
996                 ret = NT_STATUS_NO_MEMORY;
997                 goto done;
998         }
999
1000         DEBUG(10, ("Checking %s <-> %s map\n", ksidstr, kidstr));
1001         ksid = string_term_tdb_data(ksidstr);
1002         kid = string_term_tdb_data(kidstr);
1003
1004         /* Lock the record for this SID. */
1005         if (tdb_chainlock(ctx->tdb, ksid) != 0) {
1006                 DEBUG(10,("Failed to lock record %s. Error %s\n",
1007                                 ksidstr, tdb_errorstr(ctx->tdb) ));
1008                 return NT_STATUS_UNSUCCESSFUL;
1009         }
1010
1011         /* Check if sid is present in database */
1012         data = tdb_fetch(ctx->tdb, ksid);
1013         if (!data.dptr) {
1014                 DEBUG(10,("Record %s not found\n", ksidstr));
1015                 tdb_chainunlock(ctx->tdb, ksid);
1016                 ret = NT_STATUS_NONE_MAPPED;
1017                 goto done;
1018         }
1019
1020         /* Check if sid is mapped to the specified ID */
1021         if ((data.dsize != kid.dsize) ||
1022             (memcmp(data.dptr, kid.dptr, data.dsize) != 0)) {
1023                 DEBUG(10,("Specified SID does not map to specified ID\n"));
1024                 DEBUGADD(10,("Actual mapping is %s -> %s\n", ksidstr, (const char *)data.dptr));
1025                 tdb_chainunlock(ctx->tdb, ksid);
1026                 ret = NT_STATUS_NONE_MAPPED;
1027                 goto done;
1028         }
1029         
1030         DEBUG(10, ("Removing %s <-> %s map\n", ksidstr, kidstr));
1031
1032         /* Delete previous mappings. */
1033         
1034         DEBUG(10, ("Deleting existing mapping %s -> %s\n", ksidstr, kidstr ));
1035         tdb_delete(ctx->tdb, ksid);
1036
1037         DEBUG(10,("Deleting existing mapping %s -> %s\n", kidstr, ksidstr ));
1038         tdb_delete(ctx->tdb, kid);
1039
1040         tdb_chainunlock(ctx->tdb, ksid);
1041         ret = NT_STATUS_OK;
1042
1043 done:
1044         talloc_free(ksidstr);
1045         talloc_free(kidstr);
1046         SAFE_FREE(data.dptr);
1047         return ret;
1048 }
1049
1050 /**********************************
1051  Close the idmap tdb instance
1052 **********************************/
1053
1054 static NTSTATUS idmap_tdb_close(struct idmap_domain *dom)
1055 {
1056         struct idmap_tdb_context *ctx;
1057
1058         if (dom->private_data) {
1059                 ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
1060
1061                 if (idmap_tdb_tdb_close(ctx->tdb) == 0) {
1062                         return NT_STATUS_OK;
1063                 } else {
1064                         return NT_STATUS_UNSUCCESSFUL;
1065                 }
1066         }
1067         return NT_STATUS_OK;
1068 }
1069
1070 struct dump_data {
1071         TALLOC_CTX *memctx;
1072         struct id_map **maps;
1073         int *num_maps;
1074         NTSTATUS ret;
1075 };
1076
1077 static int idmap_tdb_dump_one_entry(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA value, void *pdata)
1078 {
1079         struct dump_data *data = talloc_get_type(pdata, struct dump_data);
1080         struct id_map *maps;
1081         int num_maps = *data->num_maps;
1082
1083         /* ignore any record but the ones with a SID as key */
1084         if (strncmp((const char *)key.dptr, "S-", 2) == 0) {
1085
1086                 maps = talloc_realloc(NULL, *data->maps, struct id_map, num_maps+1);
1087                 if ( ! maps) {
1088                         DEBUG(0, ("Out of memory!\n"));
1089                         data->ret = NT_STATUS_NO_MEMORY;
1090                         return -1;
1091                 }
1092                 *data->maps = maps;
1093                 maps[num_maps].sid = talloc(maps, DOM_SID);
1094                 if ( ! maps[num_maps].sid) {
1095                         DEBUG(0, ("Out of memory!\n"));
1096                         data->ret = NT_STATUS_NO_MEMORY;
1097                         return -1;
1098                 }
1099
1100                 if (!string_to_sid(maps[num_maps].sid, (const char *)key.dptr)) {
1101                         DEBUG(10,("INVALID record %s\n", (const char *)key.dptr));
1102                         /* continue even with errors */
1103                         return 0;
1104                 }
1105
1106                 /* Try a UID record. */
1107                 if (sscanf((const char *)value.dptr, "UID %u", &(maps[num_maps].xid.id)) == 1) {
1108                         maps[num_maps].xid.type = ID_TYPE_UID;
1109                         maps[num_maps].status = ID_MAPPED;
1110                         *data->num_maps = num_maps + 1;
1111
1112                 /* Try a GID record. */
1113                 } else
1114                 if (sscanf((const char *)value.dptr, "GID %u", &(maps[num_maps].xid.id)) == 1) {
1115                         maps[num_maps].xid.type = ID_TYPE_GID;
1116                         maps[num_maps].status = ID_MAPPED;
1117                         *data->num_maps = num_maps + 1;
1118
1119                 /* Unknown record type ! */
1120                 } else {
1121                         maps[num_maps].status = ID_UNKNOWN;
1122                         DEBUG(2, ("Found INVALID record %s -> %s\n",
1123                                 (const char *)key.dptr, (const char *)value.dptr));
1124                         /* do not increment num_maps */
1125                 }
1126         }
1127
1128         return 0;
1129 }
1130
1131 /**********************************
1132  Dump all mappings out
1133 **********************************/
1134
1135 static NTSTATUS idmap_tdb_dump_data(struct idmap_domain *dom, struct id_map **maps, int *num_maps)
1136 {
1137         struct idmap_tdb_context *ctx;
1138         struct dump_data *data;
1139         NTSTATUS ret = NT_STATUS_OK;
1140
1141         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
1142
1143         data = TALLOC_ZERO_P(ctx, struct dump_data);
1144         if ( ! data) {
1145                 DEBUG(0, ("Out of memory!\n"));
1146                 return NT_STATUS_NO_MEMORY;
1147         }
1148         data->maps = maps;
1149         data->num_maps = num_maps;
1150         data->ret = NT_STATUS_OK;
1151
1152         tdb_traverse(ctx->tdb, idmap_tdb_dump_one_entry, data);
1153
1154         if ( ! NT_STATUS_IS_OK(data->ret)) {
1155                 ret = data->ret;
1156         }
1157
1158         talloc_free(data);
1159         return ret;
1160 }
1161
1162 static struct idmap_methods db_methods = {
1163
1164         .init = idmap_tdb_db_init,
1165         .unixids_to_sids = idmap_tdb_unixids_to_sids,
1166         .sids_to_unixids = idmap_tdb_sids_to_unixids,
1167         .set_mapping = idmap_tdb_set_mapping,
1168         .remove_mapping = idmap_tdb_remove_mapping,
1169         .dump_data = idmap_tdb_dump_data,
1170         .close_fn = idmap_tdb_close
1171 };
1172
1173 static struct idmap_alloc_methods db_alloc_methods = {
1174
1175         .init = idmap_tdb_alloc_init,
1176         .allocate_id = idmap_tdb_allocate_id,
1177         .get_id_hwm = idmap_tdb_get_hwm,
1178         .set_id_hwm = idmap_tdb_set_hwm,
1179         .close_fn = idmap_tdb_alloc_close
1180 };
1181
1182 NTSTATUS idmap_alloc_tdb_init(void)
1183 {
1184         return smb_register_idmap_alloc(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_alloc_methods);
1185 }
1186
1187 NTSTATUS idmap_tdb_init(void)
1188 {
1189         NTSTATUS ret;
1190
1191         DEBUG(10, ("calling idmap_tdb_init\n"));
1192
1193         /* FIXME: bad hack to actually register also the alloc_tdb module without changining configure.in */
1194         ret = idmap_alloc_tdb_init();
1195         if (! NT_STATUS_IS_OK(ret)) {
1196                 return ret;
1197         }
1198         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_methods);
1199 }