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