s3:idmap: remove unused alloc method get_id_hwm from idmap API
[obnox/samba/samba-obnox.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         struct 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_compose(&sid, &domain->sid, rid);
101
102         sid_to_fstring(keystr, &sid);
103         key2 = string_term_tdb_data(keystr);
104
105         status = dbwrap_store(s->db, key2, rec->value, TDB_INSERT);
106         if (!NT_STATUS_IS_OK(status)) {
107                 DEBUG(0,("Unable to add record %s:%s\n",
108                         (const char *)key2.dptr,
109                         nt_errstr(status)));
110                 s->failed = true;
111                 return -1;
112         }
113
114         status = dbwrap_store(s->db, rec->value, key2, TDB_REPLACE);
115         if (!NT_STATUS_IS_OK(status)) {
116                 DEBUG(0,("Unable to update record %s:%s\n",
117                         (const char *)rec->value.dptr,
118                         nt_errstr(status)));
119                 s->failed = true;
120                 return -1;
121         }
122
123         status = rec->delete_rec(rec);
124         if (!NT_STATUS_IS_OK(status)) {
125                 DEBUG(0,("Unable to delete record %s:%s\n",
126                         (const char *)rec->key.dptr,
127                         nt_errstr(status)));
128                 s->failed = true;
129                 return -1;
130         }
131
132         return 0;
133 }
134
135 /*****************************************************************************
136  Convert the idmap database from an older version.
137 *****************************************************************************/
138
139 static bool idmap_tdb_upgrade(struct db_context *db)
140 {
141         int32 vers;
142         bool bigendianheader;
143         struct convert_fn_state s;
144
145         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
146
147         bigendianheader = (db->get_flags(db) & TDB_BIGENDIAN) ? True : False;
148
149         vers = dbwrap_fetch_int32(db, "IDMAP_VERSION");
150
151         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
152                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
153                 /*
154                  * high and low records were created on a
155                  * big endian machine and will need byte-reversing.
156                  */
157
158                 int32 wm;
159
160                 wm = dbwrap_fetch_int32(db, HWM_USER);
161
162                 if (wm != -1) {
163                         wm = IREV(wm);
164                 }  else {
165                         wm = idmap_tdb_state.low_uid;
166                 }
167
168                 if (dbwrap_store_int32(db, HWM_USER, wm) == -1) {
169                         DEBUG(0, ("Unable to byteswap user hwm in idmap database\n"));
170                         return False;
171                 }
172
173                 wm = dbwrap_fetch_int32(db, HWM_GROUP);
174                 if (wm != -1) {
175                         wm = IREV(wm);
176                 } else {
177                         wm = idmap_tdb_state.low_gid;
178                 }
179
180                 if (dbwrap_store_int32(db, HWM_GROUP, wm) == -1) {
181                         DEBUG(0, ("Unable to byteswap group hwm in idmap database\n"));
182                         return False;
183                 }
184         }
185
186         s.db = db;
187         s.failed = false;
188
189         /* the old format stored as DOMAIN/rid - now we store the SID direct */
190         db->traverse(db, convert_fn, &s);
191
192         if (s.failed) {
193                 DEBUG(0, ("Problem during conversion\n"));
194                 return False;
195         }
196
197         if (dbwrap_store_int32(db, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
198                 DEBUG(0, ("Unable to store idmap version in databse\n"));
199                 return False;
200         }
201
202         return True;
203 }
204
205 static NTSTATUS idmap_tdb_load_ranges(void)
206 {
207         uid_t low_uid = 0;
208         uid_t high_uid = 0;
209         gid_t low_gid = 0;
210         gid_t high_gid = 0;
211
212         if (!lp_idmap_uid(&low_uid, &high_uid)) {
213                 DEBUG(1, ("idmap uid missing\n"));
214                 return NT_STATUS_UNSUCCESSFUL;
215         }
216
217         if (!lp_idmap_gid(&low_gid, &high_gid)) {
218                 DEBUG(1, ("idmap gid missing\n"));
219                 return NT_STATUS_UNSUCCESSFUL;
220         }
221
222         idmap_tdb_state.low_uid = low_uid;
223         idmap_tdb_state.high_uid = high_uid;
224         idmap_tdb_state.low_gid = low_gid;
225         idmap_tdb_state.high_gid = high_gid;
226
227         if (idmap_tdb_state.high_uid <= idmap_tdb_state.low_uid) {
228                 DEBUG(1, ("idmap uid range missing or invalid\n"));
229                 return NT_STATUS_UNSUCCESSFUL;
230         }
231
232         if (idmap_tdb_state.high_gid <= idmap_tdb_state.low_gid) {
233                 DEBUG(1, ("idmap gid range missing or invalid\n"));
234                 return NT_STATUS_UNSUCCESSFUL;
235         }
236
237         return NT_STATUS_OK;
238 }
239
240 static NTSTATUS idmap_tdb_open_db(TALLOC_CTX *memctx,
241                                   bool check_config,
242                                   struct db_context **dbctx)
243 {
244         NTSTATUS ret;
245         TALLOC_CTX *ctx;
246         char *tdbfile = NULL;
247         struct db_context *db = NULL;
248         int32_t version;
249         bool config_error = false;
250
251         ret = idmap_tdb_load_ranges();
252         if (!NT_STATUS_IS_OK(ret)) {
253                 config_error = true;
254                 if (check_config) {
255                         return ret;
256                 }
257         }
258
259         /* use our own context here */
260         ctx = talloc_stackframe();
261
262         /* use the old database if present */
263         tdbfile = state_path("winbindd_idmap.tdb");
264         if (!tdbfile) {
265                 DEBUG(0, ("Out of memory!\n"));
266                 ret = NT_STATUS_NO_MEMORY;
267                 goto done;
268         }
269
270         DEBUG(10,("Opening tdbfile %s\n", tdbfile ));
271
272         /* Open idmap repository */
273         db = db_open(ctx, tdbfile, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
274         if (!db) {
275                 DEBUG(0, ("Unable to open idmap database\n"));
276                 ret = NT_STATUS_UNSUCCESSFUL;
277                 goto done;
278         }
279
280         /* check against earlier versions */
281         version = dbwrap_fetch_int32(db, "IDMAP_VERSION");
282         if (version != IDMAP_VERSION) {
283                 if (config_error) {
284                         DEBUG(0,("Upgrade of IDMAP_VERSION from %d to %d is not "
285                                  "possible with incomplete configuration\n",
286                                  version, IDMAP_VERSION));
287                         ret = NT_STATUS_UNSUCCESSFUL;
288                         goto done;
289                 }
290                 if (db->transaction_start(db) != 0) {
291                         DEBUG(0, ("Unable to start upgrade transaction!\n"));
292                         ret = NT_STATUS_INTERNAL_DB_ERROR;
293                         goto done;
294                 }
295
296                 if (!idmap_tdb_upgrade(db)) {
297                         db->transaction_cancel(db);
298                         DEBUG(0, ("Unable to open idmap database, it's in an old format, and upgrade failed!\n"));
299                         ret = NT_STATUS_INTERNAL_DB_ERROR;
300                         goto done;
301                 }
302
303                 if (db->transaction_commit(db) != 0) {
304                         DEBUG(0, ("Unable to commit upgrade transaction!\n"));
305                         ret = NT_STATUS_INTERNAL_DB_ERROR;
306                         goto done;
307                 }
308         }
309
310         *dbctx = talloc_move(memctx, &db);
311         ret = NT_STATUS_OK;
312
313 done:
314         talloc_free(ctx);
315         return ret;
316 }
317
318 /**********************************************************************
319  IDMAP ALLOC TDB BACKEND
320 **********************************************************************/
321  
322 static struct db_context *idmap_alloc_db;
323
324 /**********************************
325  Initialise idmap alloc database. 
326 **********************************/
327
328 static NTSTATUS idmap_tdb_alloc_init( const char *params )
329 {
330         int ret;
331         NTSTATUS status;
332         uint32_t low_uid;
333         uint32_t low_gid;
334         bool update_uid = false;
335         bool update_gid = false;
336
337         status = idmap_tdb_open_db(NULL, true, &idmap_alloc_db);
338         if (!NT_STATUS_IS_OK(status)) {
339                 DEBUG(0, ("idmap will be unable to map foreign SIDs: %s\n",
340                           nt_errstr(status)));
341                 return status;
342         }
343
344         low_uid = dbwrap_fetch_int32(idmap_alloc_db, HWM_USER);
345         if (low_uid == -1 || low_uid < idmap_tdb_state.low_uid) {
346                 update_uid = true;
347         }
348
349         low_gid = dbwrap_fetch_int32(idmap_alloc_db, HWM_GROUP);
350         if (low_gid == -1 || low_gid < idmap_tdb_state.low_gid) {
351                 update_gid = true;
352         }
353
354         if (!update_uid && !update_gid) {
355                 return NT_STATUS_OK;
356         }
357
358         if (idmap_alloc_db->transaction_start(idmap_alloc_db) != 0) {
359                 TALLOC_FREE(idmap_alloc_db);
360                 DEBUG(0, ("Unable to start upgrade transaction!\n"));
361                 return NT_STATUS_INTERNAL_DB_ERROR;
362         }
363
364         if (update_uid) {
365                 ret = dbwrap_store_int32(idmap_alloc_db, HWM_USER,
366                                          idmap_tdb_state.low_uid);
367                 if (ret == -1) {
368                         idmap_alloc_db->transaction_cancel(idmap_alloc_db);
369                         TALLOC_FREE(idmap_alloc_db);
370                         DEBUG(0, ("Unable to initialise user hwm in idmap "
371                                   "database\n"));
372                         return NT_STATUS_INTERNAL_DB_ERROR;
373                 }
374         }
375
376         if (update_gid) {
377                 ret = dbwrap_store_int32(idmap_alloc_db, HWM_GROUP,
378                                          idmap_tdb_state.low_gid);
379                 if (ret == -1) {
380                         idmap_alloc_db->transaction_cancel(idmap_alloc_db);
381                         TALLOC_FREE(idmap_alloc_db);
382                         DEBUG(0, ("Unable to initialise group hwm in idmap "
383                                   "database\n"));
384                         return NT_STATUS_INTERNAL_DB_ERROR;
385                 }
386         }
387
388         if (idmap_alloc_db->transaction_commit(idmap_alloc_db) != 0) {
389                 TALLOC_FREE(idmap_alloc_db);
390                 DEBUG(0, ("Unable to commit upgrade transaction!\n"));
391                 return NT_STATUS_INTERNAL_DB_ERROR;
392         }
393
394         return NT_STATUS_OK;
395 }
396
397 /**********************************
398  Allocate a new id. 
399 **********************************/
400
401 static NTSTATUS idmap_tdb_allocate_id(struct unixid *xid)
402 {
403         NTSTATUS ret;
404         const char *hwmkey;
405         const char *hwmtype;
406         uint32_t high_hwm;
407         uint32_t hwm;
408         int res;
409
410         /* Get current high water mark */
411         switch (xid->type) {
412
413         case ID_TYPE_UID:
414                 hwmkey = HWM_USER;
415                 hwmtype = "UID";
416                 high_hwm = idmap_tdb_state.high_uid;
417                 break;
418
419         case ID_TYPE_GID:
420                 hwmkey = HWM_GROUP;
421                 hwmtype = "GID";
422                 high_hwm = idmap_tdb_state.high_gid;
423                 break;
424
425         default:
426                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
427                 return NT_STATUS_INVALID_PARAMETER;
428         }
429
430         res = idmap_alloc_db->transaction_start(idmap_alloc_db);
431         if (res != 0) {
432                 DEBUG(1, (__location__ " Failed to start transaction.\n"));
433                 return NT_STATUS_UNSUCCESSFUL;
434         }
435
436         if ((hwm = dbwrap_fetch_int32(idmap_alloc_db, hwmkey)) == -1) {
437                 idmap_alloc_db->transaction_cancel(idmap_alloc_db);
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                 idmap_alloc_db->transaction_cancel(idmap_alloc_db);
446                 return NT_STATUS_UNSUCCESSFUL;
447         }
448
449         /* fetch a new id and increment it */
450         ret = dbwrap_change_uint32_atomic(idmap_alloc_db, hwmkey, &hwm, 1);
451         if (!NT_STATUS_IS_OK(ret)) {
452                 DEBUG(0, ("Fatal error while fetching a new %s value: %s\n!",
453                           hwmtype, nt_errstr(ret)));
454                 idmap_alloc_db->transaction_cancel(idmap_alloc_db);
455                 return ret;
456         }
457
458         /* recheck it is in the range */
459         if (hwm > high_hwm) {
460                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
461                           hwmtype, (unsigned long)high_hwm));
462                 idmap_alloc_db->transaction_cancel(idmap_alloc_db);
463                 return NT_STATUS_UNSUCCESSFUL;
464         }
465
466         res = idmap_alloc_db->transaction_commit(idmap_alloc_db);
467         if (res != 0) {
468                 DEBUG(1, (__location__ " Failed to commit transaction.\n"));
469                 return NT_STATUS_UNSUCCESSFUL;
470         }
471
472         xid->id = hwm;
473         DEBUG(10,("New %s = %d\n", hwmtype, hwm));
474
475         return NT_STATUS_OK;
476 }
477
478 /**********************************
479  Set high id. 
480 **********************************/
481
482 static NTSTATUS idmap_tdb_set_hwm(struct unixid *xid)
483 {
484         const char *hwmkey;
485         const char *hwmtype;
486         uint32_t hwm;
487         uint32_t high_hwm;
488         NTSTATUS ret;
489
490         /* Get current high water mark */
491         switch (xid->type) {
492
493         case ID_TYPE_UID:
494                 hwmkey = HWM_USER;
495                 hwmtype = "UID";
496                 high_hwm = idmap_tdb_state.high_uid;
497                 break;
498
499         case ID_TYPE_GID:
500                 hwmkey = HWM_GROUP;
501                 hwmtype = "GID";
502                 high_hwm = idmap_tdb_state.high_gid;
503                 break;
504
505         default:
506                 return NT_STATUS_INVALID_PARAMETER;
507         }
508
509         hwm = xid->id;
510
511         /* Warn if it is out of range */
512         if (hwm >= high_hwm) {
513                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
514                           hwmtype, (unsigned long)high_hwm));
515         }
516
517         ret = dbwrap_trans_store_uint32(idmap_alloc_db, hwmkey, hwm);
518
519         return ret;
520 }
521
522 /**********************************
523  Close the alloc tdb 
524 **********************************/
525
526 static NTSTATUS idmap_tdb_alloc_close(void)
527 {
528         TALLOC_FREE(idmap_alloc_db);
529         return NT_STATUS_OK;
530 }
531
532 /**********************************************************************
533  IDMAP MAPPING TDB BACKEND
534 **********************************************************************/
535  
536 struct idmap_tdb_context {
537         struct db_context *db;
538         uint32_t filter_low_id;
539         uint32_t filter_high_id;
540 };
541
542 /*****************************
543  Initialise idmap database. 
544 *****************************/
545
546 static NTSTATUS idmap_tdb_db_init(struct idmap_domain *dom, const char *params)
547 {
548         NTSTATUS ret;
549         struct idmap_tdb_context *ctx;
550
551         DEBUG(10, ("idmap_tdb_db_init called for domain '%s'\n", dom->name));
552
553         ctx = talloc(dom, struct idmap_tdb_context);
554         if ( ! ctx) {
555                 DEBUG(0, ("Out of memory!\n"));
556                 return NT_STATUS_NO_MEMORY;
557         }
558
559         if (strequal(dom->name, "*")) {
560                 uid_t low_uid = 0;
561                 uid_t high_uid = 0;
562                 gid_t low_gid = 0;
563                 gid_t high_gid = 0;
564
565                 ctx->filter_low_id = 0;
566                 ctx->filter_high_id = 0;
567
568                 if (lp_idmap_uid(&low_uid, &high_uid)) {
569                         ctx->filter_low_id = low_uid;
570                         ctx->filter_high_id = high_uid;
571                 } else {
572                         DEBUG(3, ("Warning: 'idmap uid' not set!\n"));
573                 }
574
575                 if (lp_idmap_gid(&low_gid, &high_gid)) {
576                         if ((low_gid != low_uid) || (high_gid != high_uid)) {
577                                 DEBUG(1, ("Warning: 'idmap uid' and 'idmap gid'"
578                                       " ranges do not agree -- building "
579                                       "intersection\n"));
580                                 ctx->filter_low_id = MAX(ctx->filter_low_id,
581                                                          low_gid);
582                                 ctx->filter_high_id = MIN(ctx->filter_high_id,
583                                                           high_gid);
584                         }
585                 } else {
586                         DEBUG(3, ("Warning: 'idmap gid' not set!\n"));
587                 }
588         } else {
589                 char *config_option = NULL;
590                 const char *range;
591
592                 config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
593                 if ( ! config_option) {
594                         DEBUG(0, ("Out of memory!\n"));
595                         ret = NT_STATUS_NO_MEMORY;
596                         goto failed;
597                 }
598
599                 range = lp_parm_const_string(-1, config_option, "range", NULL);
600                 if (( ! range) ||
601                     (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2))
602                 {
603                         ctx->filter_low_id = 0;
604                         ctx->filter_high_id = 0;
605                 }
606
607                 talloc_free(config_option);
608         }
609
610         if (ctx->filter_low_id > ctx->filter_high_id) {
611                 ctx->filter_low_id = 0;
612                 ctx->filter_high_id = 0;
613         }
614
615         DEBUG(10, ("idmap_tdb_db_init: filter range %u-%u loaded for domain "
616               "'%s'\n", ctx->filter_low_id, ctx->filter_high_id, dom->name));
617
618         ret = idmap_tdb_open_db(ctx, false, &ctx->db);
619         if ( ! NT_STATUS_IS_OK(ret)) {
620                 goto failed;
621         }
622
623         dom->private_data = ctx;
624
625         return NT_STATUS_OK;
626
627 failed:
628         talloc_free(ctx);
629         return ret;
630 }
631
632 /**********************************
633  Single id to sid lookup function. 
634 **********************************/
635
636 static NTSTATUS idmap_tdb_id_to_sid(struct idmap_tdb_context *ctx, struct id_map *map)
637 {
638         NTSTATUS ret;
639         TDB_DATA data;
640         char *keystr;
641
642         if (!ctx || !map) {
643                 return NT_STATUS_INVALID_PARAMETER;
644         }
645
646         /* apply filters before checking */
647         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
648             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
649                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
650                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
651                 return NT_STATUS_NONE_MAPPED;
652         }
653
654         switch (map->xid.type) {
655
656         case ID_TYPE_UID:
657                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
658                 break;
659                 
660         case ID_TYPE_GID:
661                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
662                 break;
663
664         default:
665                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
666                 return NT_STATUS_INVALID_PARAMETER;
667         }
668
669         /* final SAFE_FREE safe */
670         data.dptr = NULL;
671
672         if (keystr == NULL) {
673                 DEBUG(0, ("Out of memory!\n"));
674                 ret = NT_STATUS_NO_MEMORY;
675                 goto done;
676         }
677
678         DEBUG(10,("Fetching record %s\n", keystr));
679
680         /* Check if the mapping exists */
681         data = dbwrap_fetch_bystring(ctx->db, NULL, keystr);
682
683         if (!data.dptr) {
684                 DEBUG(10,("Record %s not found\n", keystr));
685                 ret = NT_STATUS_NONE_MAPPED;
686                 goto done;
687         }
688                 
689         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
690                 DEBUG(10,("INVALID SID (%s) in record %s\n",
691                         (const char *)data.dptr, keystr));
692                 ret = NT_STATUS_INTERNAL_DB_ERROR;
693                 goto done;
694         }
695
696         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
697         ret = NT_STATUS_OK;
698
699 done:
700         talloc_free(data.dptr);
701         talloc_free(keystr);
702         return ret;
703 }
704
705 /**********************************
706  Single sid to id lookup function. 
707 **********************************/
708
709 static NTSTATUS idmap_tdb_sid_to_id(struct idmap_tdb_context *ctx, struct id_map *map)
710 {
711         NTSTATUS ret;
712         TDB_DATA data;
713         char *keystr;
714         unsigned long rec_id = 0;
715         TALLOC_CTX *tmp_ctx = talloc_stackframe();
716
717         keystr = sid_string_talloc(tmp_ctx, map->sid);
718         if (keystr == NULL) {
719                 DEBUG(0, ("Out of memory!\n"));
720                 ret = NT_STATUS_NO_MEMORY;
721                 goto done;
722         }
723
724         DEBUG(10,("Fetching record %s\n", keystr));
725
726         /* Check if sid is present in database */
727         data = dbwrap_fetch_bystring(ctx->db, tmp_ctx, keystr);
728         if (!data.dptr) {
729                 DEBUG(10,("Record %s not found\n", keystr));
730                 ret = NT_STATUS_NONE_MAPPED;
731                 goto done;
732         }
733
734         /* What type of record is this ? */
735         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
736                 map->xid.id = rec_id;
737                 map->xid.type = ID_TYPE_UID;
738                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
739                 ret = NT_STATUS_OK;
740
741         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
742                 map->xid.id = rec_id;
743                 map->xid.type = ID_TYPE_GID;
744                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
745                 ret = NT_STATUS_OK;
746
747         } else { /* Unknown record type ! */
748                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
749                 ret = NT_STATUS_INTERNAL_DB_ERROR;
750                 goto done;
751         }
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(tmp_ctx);
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         /* initialize the status to avoid suprise */
777         for (i = 0; ids[i]; i++) {
778                 ids[i]->status = ID_UNKNOWN;
779         }
780         
781         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
782
783         for (i = 0; ids[i]; i++) {
784                 ret = idmap_tdb_id_to_sid(ctx, ids[i]);
785                 if ( ! NT_STATUS_IS_OK(ret)) {
786
787                         /* if it is just a failed mapping continue */
788                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
789
790                                 /* make sure it is marked as unmapped */
791                                 ids[i]->status = ID_UNMAPPED;
792                                 continue;
793                         }
794                         
795                         /* some fatal error occurred, return immediately */
796                         goto done;
797                 }
798
799                 /* all ok, id is mapped */
800                 ids[i]->status = ID_MAPPED;
801         }
802
803         ret = NT_STATUS_OK;
804
805 done:
806         return ret;
807 }
808
809 /**********************************
810  lookup a set of sids. 
811 **********************************/
812
813 static NTSTATUS idmap_tdb_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
814 {
815         struct idmap_tdb_context *ctx;
816         NTSTATUS ret;
817         int i;
818
819         /* initialize the status to avoid suprise */
820         for (i = 0; ids[i]; i++) {
821                 ids[i]->status = ID_UNKNOWN;
822         }
823         
824         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
825
826         for (i = 0; ids[i]; i++) {
827                 ret = idmap_tdb_sid_to_id(ctx, ids[i]);
828                 if ( ! NT_STATUS_IS_OK(ret)) {
829
830                         /* if it is just a failed mapping continue */
831                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
832
833                                 /* make sure it is marked as unmapped */
834                                 ids[i]->status = ID_UNMAPPED;
835                                 continue;
836                         }
837                         
838                         /* some fatal error occurred, return immediately */
839                         goto done;
840                 }
841
842                 /* all ok, id is mapped */
843                 ids[i]->status = ID_MAPPED;
844         }
845
846         ret = NT_STATUS_OK;
847
848 done:
849         return ret;
850 }
851
852 /**********************************
853  set a mapping.
854 **********************************/
855
856 static NTSTATUS idmap_tdb_set_mapping(struct idmap_domain *dom,
857                                       const struct id_map *map)
858 {
859         struct idmap_tdb_context *ctx;
860         NTSTATUS ret;
861         TDB_DATA ksid, kid;
862         char *ksidstr, *kidstr;
863         fstring tmp;
864
865         if (!map || !map->sid) {
866                 return NT_STATUS_INVALID_PARAMETER;
867         }
868
869         ksidstr = kidstr = NULL;
870
871         /* TODO: should we filter a set_mapping using low/high filters ? */
872
873         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
874
875         switch (map->xid.type) {
876
877         case ID_TYPE_UID:
878                 kidstr = talloc_asprintf(ctx, "UID %lu",
879                                          (unsigned long)map->xid.id);
880                 break;
881
882         case ID_TYPE_GID:
883                 kidstr = talloc_asprintf(ctx, "GID %lu",
884                                          (unsigned long)map->xid.id);
885                 break;
886
887         default:
888                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
889                 return NT_STATUS_INVALID_PARAMETER;
890         }
891
892         if (kidstr == NULL) {
893                 DEBUG(0, ("ERROR: Out of memory!\n"));
894                 ret = NT_STATUS_NO_MEMORY;
895                 goto done;
896         }
897
898         if ((ksidstr = talloc_asprintf(
899                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
900                 DEBUG(0, ("Out of memory!\n"));
901                 ret = NT_STATUS_NO_MEMORY;
902                 goto done;
903         }
904
905         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
906         kid = string_term_tdb_data(kidstr);
907         ksid = string_term_tdb_data(ksidstr);
908
909         if (ctx->db->transaction_start(ctx->db) != 0) {
910                 DEBUG(0, ("Failed to start transaction for %s\n",
911                           ksidstr));
912                 ret = NT_STATUS_INTERNAL_DB_ERROR;
913                 goto done;
914         }
915
916         ret = dbwrap_store(ctx->db, ksid, kid, TDB_REPLACE);
917         if (!NT_STATUS_IS_OK(ret)) {
918                 ctx->db->transaction_cancel(ctx->db);
919                 DEBUG(0, ("Error storing SID -> ID (%s -> %s): %s\n",
920                           ksidstr, kidstr, nt_errstr(ret)));
921                 goto done;
922         }
923         ret = dbwrap_store(ctx->db, kid, ksid, TDB_REPLACE);
924         if (!NT_STATUS_IS_OK(ret)) {
925                 ctx->db->transaction_cancel(ctx->db);
926                 DEBUG(0, ("Error storing ID -> SID (%s -> %s): %s\n",
927                           kidstr, ksidstr, nt_errstr(ret)));
928                 goto done;
929         }
930
931         if (ctx->db->transaction_commit(ctx->db) != 0) {
932                 DEBUG(0, ("Failed to commit transaction for (%s -> %s)\n",
933                           ksidstr, kidstr));
934                 ret = NT_STATUS_INTERNAL_DB_ERROR;
935                 goto done;
936         }
937
938         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
939         ret = NT_STATUS_OK;
940
941 done:
942         talloc_free(ksidstr);
943         talloc_free(kidstr);
944         return ret;
945 }
946
947 /**********************************
948  Close the idmap tdb instance
949 **********************************/
950
951 static NTSTATUS idmap_tdb_close(struct idmap_domain *dom)
952 {
953         struct idmap_tdb_context *ctx;
954
955         if (dom->private_data) {
956                 ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
957
958                 TALLOC_FREE(ctx->db);
959         }
960         return NT_STATUS_OK;
961 }
962
963 static struct idmap_methods db_methods = {
964
965         .init = idmap_tdb_db_init,
966         .unixids_to_sids = idmap_tdb_unixids_to_sids,
967         .sids_to_unixids = idmap_tdb_sids_to_unixids,
968         .set_mapping = idmap_tdb_set_mapping,
969         .close_fn = idmap_tdb_close
970 };
971
972 static struct idmap_alloc_methods db_alloc_methods = {
973
974         .init = idmap_tdb_alloc_init,
975         .allocate_id = idmap_tdb_allocate_id,
976         .set_id_hwm = idmap_tdb_set_hwm,
977         .close_fn = idmap_tdb_alloc_close
978 };
979
980 NTSTATUS idmap_alloc_tdb_init(void)
981 {
982         return smb_register_idmap_alloc(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_alloc_methods);
983 }
984
985 NTSTATUS idmap_tdb_init(void)
986 {
987         NTSTATUS ret;
988
989         DEBUG(10, ("calling idmap_tdb_init\n"));
990
991         /* FIXME: bad hack to actually register also the alloc_tdb module without changining configure.in */
992         ret = idmap_alloc_tdb_init();
993         if (! NT_STATUS_IS_OK(ret)) {
994                 return ret;
995         }
996         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_methods);
997 }