s3:idmap_tdb: implement allocate_id in idmap methods for tdb backend
[metze/samba/wip.git] / source3 / winbindd / idmap_tdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    idmap TDB backend
5
6    Copyright (C) Tim Potter 2000
7    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
8    Copyright (C) Jeremy Allison 2006
9    Copyright (C) Simo Sorce 2003-2006
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_IDMAP
30
31 /* idmap version determines auto-conversion - this is the database
32    structure version specifier. */
33
34 #define IDMAP_VERSION 2
35
36 /* High water mark keys */
37 #define HWM_GROUP  "GROUP HWM"
38 #define HWM_USER   "USER HWM"
39
40 static struct idmap_tdb_state {
41
42         /* User and group id pool */
43         uid_t low_uid, high_uid;               /* Range of uids to allocate */
44         gid_t low_gid, high_gid;               /* Range of gids to allocate */
45
46 } idmap_tdb_state;
47
48 struct convert_fn_state {
49         struct db_context *db;
50         bool failed;
51 };
52
53 /*****************************************************************************
54  For idmap conversion: convert one record to new format
55  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
56  instead of the SID.
57 *****************************************************************************/
58 static int convert_fn(struct db_record *rec, void *private_data)
59 {
60         struct winbindd_domain *domain;
61         char *p;
62         NTSTATUS status;
63         DOM_SID sid;
64         uint32 rid;
65         fstring keystr;
66         fstring dom_name;
67         TDB_DATA key2;
68         struct convert_fn_state *s = (struct convert_fn_state *)private_data;
69
70         DEBUG(10,("Converting %s\n", (const char *)rec->key.dptr));
71
72         p = strchr((const char *)rec->key.dptr, '/');
73         if (!p)
74                 return 0;
75
76         *p = 0;
77         fstrcpy(dom_name, (const char *)rec->key.dptr);
78         *p++ = '/';
79
80         domain = find_domain_from_name(dom_name);
81         if (domain == NULL) {
82                 /* We must delete the old record. */
83                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
84                 DEBUG(0,("deleting record %s\n", (const char *)rec->key.dptr ));
85
86                 status = rec->delete_rec(rec);
87                 if (!NT_STATUS_IS_OK(status)) {
88                         DEBUG(0, ("Unable to delete record %s:%s\n",
89                                 (const char *)rec->key.dptr,
90                                 nt_errstr(status)));
91                         s->failed = true;
92                         return -1;
93                 }
94
95                 return 0;
96         }
97
98         rid = atoi(p);
99
100         sid_copy(&sid, &domain->sid);
101         sid_append_rid(&sid, rid);
102
103         sid_to_fstring(keystr, &sid);
104         key2 = string_term_tdb_data(keystr);
105
106         status = dbwrap_store(s->db, key2, rec->value, TDB_INSERT);
107         if (!NT_STATUS_IS_OK(status)) {
108                 DEBUG(0,("Unable to add record %s:%s\n",
109                         (const char *)key2.dptr,
110                         nt_errstr(status)));
111                 s->failed = true;
112                 return -1;
113         }
114
115         status = dbwrap_store(s->db, rec->value, key2, TDB_REPLACE);
116         if (!NT_STATUS_IS_OK(status)) {
117                 DEBUG(0,("Unable to update record %s:%s\n",
118                         (const char *)rec->value.dptr,
119                         nt_errstr(status)));
120                 s->failed = true;
121                 return -1;
122         }
123
124         status = rec->delete_rec(rec);
125         if (!NT_STATUS_IS_OK(status)) {
126                 DEBUG(0,("Unable to delete record %s:%s\n",
127                         (const char *)rec->key.dptr,
128                         nt_errstr(status)));
129                 s->failed = true;
130                 return -1;
131         }
132
133         return 0;
134 }
135
136 /*****************************************************************************
137  Convert the idmap database from an older version.
138 *****************************************************************************/
139
140 static bool idmap_tdb_upgrade(struct db_context *db)
141 {
142         int32 vers;
143         bool bigendianheader;
144         struct convert_fn_state s;
145
146         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
147
148         bigendianheader = (db->get_flags(db) & TDB_BIGENDIAN) ? True : False;
149
150         vers = dbwrap_fetch_int32(db, "IDMAP_VERSION");
151
152         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
153                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
154                 /*
155                  * high and low records were created on a
156                  * big endian machine and will need byte-reversing.
157                  */
158
159                 int32 wm;
160
161                 wm = dbwrap_fetch_int32(db, HWM_USER);
162
163                 if (wm != -1) {
164                         wm = IREV(wm);
165                 }  else {
166                         wm = idmap_tdb_state.low_uid;
167                 }
168
169                 if (dbwrap_store_int32(db, HWM_USER, wm) == -1) {
170                         DEBUG(0, ("Unable to byteswap user hwm in idmap database\n"));
171                         return False;
172                 }
173
174                 wm = dbwrap_fetch_int32(db, HWM_GROUP);
175                 if (wm != -1) {
176                         wm = IREV(wm);
177                 } else {
178                         wm = idmap_tdb_state.low_gid;
179                 }
180
181                 if (dbwrap_store_int32(db, HWM_GROUP, wm) == -1) {
182                         DEBUG(0, ("Unable to byteswap group hwm in idmap database\n"));
183                         return False;
184                 }
185         }
186
187         s.db = db;
188         s.failed = false;
189
190         /* the old format stored as DOMAIN/rid - now we store the SID direct */
191         db->traverse(db, convert_fn, &s);
192
193         if (s.failed) {
194                 DEBUG(0, ("Problem during conversion\n"));
195                 return False;
196         }
197
198         if (dbwrap_store_int32(db, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
199                 DEBUG(0, ("Unable to store 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 struct idmap_tdb_allocate_id_context {
403         const char *hwmkey;
404         const char *hwmtype;
405         uint32_t high_hwm;
406         uint32_t hwm;
407 };
408
409 static NTSTATUS idmap_tdb_allocate_id_action(struct db_context *db,
410                                              void *private_data)
411 {
412         NTSTATUS ret;
413         struct idmap_tdb_allocate_id_context *state;
414         uint32_t hwm;
415
416         state = (struct idmap_tdb_allocate_id_context *)private_data;
417
418         hwm = dbwrap_fetch_int32(db, state->hwmkey);
419         if (hwm == -1) {
420                 ret = NT_STATUS_INTERNAL_DB_ERROR;
421                 goto done;
422         }
423
424         /* check it is in the range */
425         if (hwm > state->high_hwm) {
426                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
427                           state->hwmtype, (unsigned long)state->high_hwm));
428                 ret = NT_STATUS_UNSUCCESSFUL;
429                 goto done;
430         }
431
432         /* fetch a new id and increment it */
433         ret = dbwrap_trans_change_uint32_atomic(db, state->hwmkey, &hwm, 1);
434         if (!NT_STATUS_IS_OK(ret)) {
435                 DEBUG(0, ("Fatal error while fetching a new %s value: %s\n!",
436                           state->hwmtype, nt_errstr(ret)));
437                 goto done;
438         }
439
440         /* recheck it is in the range */
441         if (hwm > state->high_hwm) {
442                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
443                           state->hwmtype, (unsigned long)state->high_hwm));
444                 ret = NT_STATUS_UNSUCCESSFUL;
445                 goto done;
446         }
447
448         ret = NT_STATUS_OK;
449         state->hwm = hwm;
450
451 done:
452         return ret;
453 }
454
455 static NTSTATUS idmap_tdb_allocate_id(struct unixid *xid)
456 {
457         const char *hwmkey;
458         const char *hwmtype;
459         uint32_t high_hwm;
460         uint32_t hwm = 0;
461         NTSTATUS status;
462         struct idmap_tdb_allocate_id_context state;
463
464         /* Get current high water mark */
465         switch (xid->type) {
466
467         case ID_TYPE_UID:
468                 hwmkey = HWM_USER;
469                 hwmtype = "UID";
470                 high_hwm = idmap_tdb_state.high_uid;
471                 break;
472
473         case ID_TYPE_GID:
474                 hwmkey = HWM_GROUP;
475                 hwmtype = "GID";
476                 high_hwm = idmap_tdb_state.high_gid;
477                 break;
478
479         default:
480                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
481                 return NT_STATUS_INVALID_PARAMETER;
482         }
483
484         state.hwm = hwm;
485         state.high_hwm = high_hwm;
486         state.hwmtype = hwmtype;
487         state.hwmkey = hwmkey;
488
489         status = dbwrap_trans_do(idmap_alloc_db, idmap_tdb_allocate_id_action,
490                                  &state);
491
492         if (NT_STATUS_IS_OK(status)) {
493                 xid->id = state.hwm;
494                 DEBUG(10,("New %s = %d\n", hwmtype, state.hwm));
495         } else {
496                 DEBUG(1, ("Error allocating a new %s\n", hwmtype));
497         }
498
499         return status;
500 }
501
502 /**
503  * Allocate a new unix-ID.
504  * For now this is for the default idmap domain only.
505  * Should be extended later on.
506  */
507 static NTSTATUS idmap_tdb_get_new_id(struct idmap_domain *dom,
508                                      struct unixid *id)
509 {
510         NTSTATUS ret;
511
512         if (!strequal(dom->name, "*")) {
513                 DEBUG(3, ("idmap_tdb_get_new_id: "
514                           "Refusing allocation of a new unixid for domain'%s'. "
515                           "Currently only supported for the default "
516                           "domain \"*\".\n",
517                            dom->name));
518                 return NT_STATUS_NOT_IMPLEMENTED;
519         }
520
521         ret = idmap_tdb_allocate_id(id);
522
523         return ret;
524 }
525
526 /**********************************
527  Close the alloc tdb 
528 **********************************/
529
530 static NTSTATUS idmap_tdb_alloc_close(void)
531 {
532         TALLOC_FREE(idmap_alloc_db);
533         return NT_STATUS_OK;
534 }
535
536 /**********************************************************************
537  IDMAP MAPPING TDB BACKEND
538 **********************************************************************/
539  
540 struct idmap_tdb_context {
541         struct db_context *db;
542         uint32_t filter_low_id;
543         uint32_t filter_high_id;
544 };
545
546 /*****************************
547  Initialise idmap database. 
548 *****************************/
549
550 static NTSTATUS idmap_tdb_db_init(struct idmap_domain *dom, const char *params)
551 {
552         NTSTATUS ret;
553         struct idmap_tdb_context *ctx;
554
555         ctx = talloc(dom, struct idmap_tdb_context);
556         if ( ! ctx) {
557                 DEBUG(0, ("Out of memory!\n"));
558                 return NT_STATUS_NO_MEMORY;
559         }
560
561         if (strequal(dom->name, "*")) {
562                 uid_t low_uid = 0;
563                 uid_t high_uid = 0;
564                 gid_t low_gid = 0;
565                 gid_t high_gid = 0;
566
567                 ctx->filter_low_id = 0;
568                 ctx->filter_high_id = 0;
569
570                 if (lp_idmap_uid(&low_uid, &high_uid)) {
571                         ctx->filter_low_id = low_uid;
572                         ctx->filter_high_id = high_uid;
573                 } else {
574                         DEBUG(3, ("Warning: 'idmap uid' not set!\n"));
575                 }
576
577                 if (lp_idmap_gid(&low_gid, &high_gid)) {
578                         if ((low_gid != low_uid) || (high_gid != high_uid)) {
579                                 DEBUG(1, ("Warning: 'idmap uid' and 'idmap gid'"
580                                       " ranges do not agree -- building "
581                                       "intersection\n"));
582                                 ctx->filter_low_id = MAX(ctx->filter_low_id,
583                                                          low_gid);
584                                 ctx->filter_high_id = MIN(ctx->filter_high_id,
585                                                           high_gid);
586                         }
587                 } else {
588                         DEBUG(3, ("Warning: 'idmap gid' not set!\n"));
589                 }
590         } else {
591                 char *config_option = NULL;
592                 const char *range;
593
594                 config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
595                 if ( ! config_option) {
596                         DEBUG(0, ("Out of memory!\n"));
597                         ret = NT_STATUS_NO_MEMORY;
598                         goto failed;
599                 }
600
601                 range = lp_parm_const_string(-1, config_option, "range", NULL);
602                 if (( ! range) ||
603                     (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2))
604                 {
605                         ctx->filter_low_id = 0;
606                         ctx->filter_high_id = 0;
607                 }
608
609                 talloc_free(config_option);
610         }
611
612         if (ctx->filter_low_id > ctx->filter_high_id) {
613                 ctx->filter_low_id = 0;
614                 ctx->filter_high_id = 0;
615         }
616
617         DEBUG(10, ("idmap_tdb_db_init: filter range %u-%u loaded for domain "
618               "'%s'\n", ctx->filter_low_id, ctx->filter_high_id, dom->name));
619
620         ret = idmap_tdb_open_db(ctx, false, &ctx->db);
621         if ( ! NT_STATUS_IS_OK(ret)) {
622                 goto failed;
623         }
624
625         dom->private_data = ctx;
626
627         return NT_STATUS_OK;
628
629 failed:
630         talloc_free(ctx);
631         return ret;
632 }
633
634 /**********************************
635  Single id to sid lookup function. 
636 **********************************/
637
638 static NTSTATUS idmap_tdb_id_to_sid(struct idmap_tdb_context *ctx, struct id_map *map)
639 {
640         NTSTATUS ret;
641         TDB_DATA data;
642         char *keystr;
643
644         if (!ctx || !map) {
645                 return NT_STATUS_INVALID_PARAMETER;
646         }
647
648         /* apply filters before checking */
649         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
650             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
651                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
652                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
653                 return NT_STATUS_NONE_MAPPED;
654         }
655
656         switch (map->xid.type) {
657
658         case ID_TYPE_UID:
659                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
660                 break;
661                 
662         case ID_TYPE_GID:
663                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
664                 break;
665
666         default:
667                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
668                 return NT_STATUS_INVALID_PARAMETER;
669         }
670
671         /* final SAFE_FREE safe */
672         data.dptr = NULL;
673
674         if (keystr == NULL) {
675                 DEBUG(0, ("Out of memory!\n"));
676                 ret = NT_STATUS_NO_MEMORY;
677                 goto done;
678         }
679
680         DEBUG(10,("Fetching record %s\n", keystr));
681
682         /* Check if the mapping exists */
683         data = dbwrap_fetch_bystring(ctx->db, NULL, keystr);
684
685         if (!data.dptr) {
686                 DEBUG(10,("Record %s not found\n", keystr));
687                 ret = NT_STATUS_NONE_MAPPED;
688                 goto done;
689         }
690                 
691         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
692                 DEBUG(10,("INVALID SID (%s) in record %s\n",
693                         (const char *)data.dptr, keystr));
694                 ret = NT_STATUS_INTERNAL_DB_ERROR;
695                 goto done;
696         }
697
698         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
699         ret = NT_STATUS_OK;
700
701 done:
702         talloc_free(data.dptr);
703         talloc_free(keystr);
704         return ret;
705 }
706
707 /**********************************
708  Single sid to id lookup function. 
709 **********************************/
710
711 static NTSTATUS idmap_tdb_sid_to_id(struct idmap_tdb_context *ctx, struct id_map *map)
712 {
713         NTSTATUS ret;
714         TDB_DATA data;
715         char *keystr;
716         unsigned long rec_id = 0;
717         TALLOC_CTX *tmp_ctx = talloc_stackframe();
718
719         keystr = sid_string_talloc(tmp_ctx, map->sid);
720         if (keystr == NULL) {
721                 DEBUG(0, ("Out of memory!\n"));
722                 ret = NT_STATUS_NO_MEMORY;
723                 goto done;
724         }
725
726         DEBUG(10,("Fetching record %s\n", keystr));
727
728         /* Check if sid is present in database */
729         data = dbwrap_fetch_bystring(ctx->db, tmp_ctx, keystr);
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         /* What type of record is this ? */
737         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
738                 map->xid.id = rec_id;
739                 map->xid.type = ID_TYPE_UID;
740                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
741                 ret = NT_STATUS_OK;
742
743         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
744                 map->xid.id = rec_id;
745                 map->xid.type = ID_TYPE_GID;
746                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
747                 ret = NT_STATUS_OK;
748
749         } else { /* Unknown record type ! */
750                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
751                 ret = NT_STATUS_INTERNAL_DB_ERROR;
752                 goto done;
753         }
754
755         /* apply filters before returning result */
756         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
757             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
758                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
759                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
760                 ret = NT_STATUS_NONE_MAPPED;
761         }
762
763 done:
764         talloc_free(tmp_ctx);
765         return ret;
766 }
767
768 /**********************************
769  lookup a set of unix ids. 
770 **********************************/
771
772 static NTSTATUS idmap_tdb_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
773 {
774         struct idmap_tdb_context *ctx;
775         NTSTATUS ret;
776         int i;
777
778         /* initialize the status to avoid suprise */
779         for (i = 0; ids[i]; i++) {
780                 ids[i]->status = ID_UNKNOWN;
781         }
782         
783         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
784
785         for (i = 0; ids[i]; i++) {
786                 ret = idmap_tdb_id_to_sid(ctx, ids[i]);
787                 if ( ! NT_STATUS_IS_OK(ret)) {
788
789                         /* if it is just a failed mapping continue */
790                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
791
792                                 /* make sure it is marked as unmapped */
793                                 ids[i]->status = ID_UNMAPPED;
794                                 continue;
795                         }
796                         
797                         /* some fatal error occurred, return immediately */
798                         goto done;
799                 }
800
801                 /* all ok, id is mapped */
802                 ids[i]->status = ID_MAPPED;
803         }
804
805         ret = NT_STATUS_OK;
806
807 done:
808         return ret;
809 }
810
811 /**********************************
812  lookup a set of sids. 
813 **********************************/
814
815 static NTSTATUS idmap_tdb_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
816 {
817         struct idmap_tdb_context *ctx;
818         NTSTATUS ret;
819         int i;
820
821         /* initialize the status to avoid suprise */
822         for (i = 0; ids[i]; i++) {
823                 ids[i]->status = ID_UNKNOWN;
824         }
825         
826         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
827
828         for (i = 0; ids[i]; i++) {
829                 ret = idmap_tdb_sid_to_id(ctx, ids[i]);
830                 if ( ! NT_STATUS_IS_OK(ret)) {
831
832                         /* if it is just a failed mapping continue */
833                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
834
835                                 /* make sure it is marked as unmapped */
836                                 ids[i]->status = ID_UNMAPPED;
837                                 continue;
838                         }
839                         
840                         /* some fatal error occurred, return immediately */
841                         goto done;
842                 }
843
844                 /* all ok, id is mapped */
845                 ids[i]->status = ID_MAPPED;
846         }
847
848         ret = NT_STATUS_OK;
849
850 done:
851         return ret;
852 }
853
854 /**********************************
855  set a mapping.
856 **********************************/
857
858 static NTSTATUS idmap_tdb_set_mapping(struct idmap_domain *dom,
859                                       const struct id_map *map)
860 {
861         struct idmap_tdb_context *ctx;
862         NTSTATUS ret;
863         TDB_DATA ksid, kid;
864         char *ksidstr, *kidstr;
865         fstring tmp;
866
867         if (!map || !map->sid) {
868                 return NT_STATUS_INVALID_PARAMETER;
869         }
870
871         ksidstr = kidstr = NULL;
872
873         /* TODO: should we filter a set_mapping using low/high filters ? */
874
875         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
876
877         switch (map->xid.type) {
878
879         case ID_TYPE_UID:
880                 kidstr = talloc_asprintf(ctx, "UID %lu",
881                                          (unsigned long)map->xid.id);
882                 break;
883
884         case ID_TYPE_GID:
885                 kidstr = talloc_asprintf(ctx, "GID %lu",
886                                          (unsigned long)map->xid.id);
887                 break;
888
889         default:
890                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
891                 return NT_STATUS_INVALID_PARAMETER;
892         }
893
894         if (kidstr == NULL) {
895                 DEBUG(0, ("ERROR: Out of memory!\n"));
896                 ret = NT_STATUS_NO_MEMORY;
897                 goto done;
898         }
899
900         if ((ksidstr = talloc_asprintf(
901                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
902                 DEBUG(0, ("Out of memory!\n"));
903                 ret = NT_STATUS_NO_MEMORY;
904                 goto done;
905         }
906
907         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
908         kid = string_term_tdb_data(kidstr);
909         ksid = string_term_tdb_data(ksidstr);
910
911         if (ctx->db->transaction_start(ctx->db) != 0) {
912                 DEBUG(0, ("Failed to start transaction for %s\n",
913                           ksidstr));
914                 ret = NT_STATUS_INTERNAL_DB_ERROR;
915                 goto done;
916         }
917
918         ret = dbwrap_store(ctx->db, ksid, kid, TDB_REPLACE);
919         if (!NT_STATUS_IS_OK(ret)) {
920                 ctx->db->transaction_cancel(ctx->db);
921                 DEBUG(0, ("Error storing SID -> ID (%s -> %s): %s\n",
922                           ksidstr, kidstr, nt_errstr(ret)));
923                 goto done;
924         }
925         ret = dbwrap_store(ctx->db, kid, ksid, TDB_REPLACE);
926         if (!NT_STATUS_IS_OK(ret)) {
927                 ctx->db->transaction_cancel(ctx->db);
928                 DEBUG(0, ("Error storing ID -> SID (%s -> %s): %s\n",
929                           kidstr, ksidstr, nt_errstr(ret)));
930                 goto done;
931         }
932
933         if (ctx->db->transaction_commit(ctx->db) != 0) {
934                 DEBUG(0, ("Failed to commit transaction for (%s -> %s)\n",
935                           ksidstr, kidstr));
936                 ret = NT_STATUS_INTERNAL_DB_ERROR;
937                 goto done;
938         }
939
940         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
941         ret = NT_STATUS_OK;
942
943 done:
944         talloc_free(ksidstr);
945         talloc_free(kidstr);
946         return ret;
947 }
948
949 /**********************************
950  Close the idmap tdb instance
951 **********************************/
952
953 static NTSTATUS idmap_tdb_close(struct idmap_domain *dom)
954 {
955         struct idmap_tdb_context *ctx;
956
957         if (dom->private_data) {
958                 ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
959
960                 TALLOC_FREE(ctx->db);
961         }
962         return NT_STATUS_OK;
963 }
964
965 static struct idmap_methods db_methods = {
966         .init = idmap_tdb_db_init,
967         .unixids_to_sids = idmap_tdb_unixids_to_sids,
968         .sids_to_unixids = idmap_tdb_sids_to_unixids,
969         .allocate_id = idmap_tdb_get_new_id,
970         .close_fn = idmap_tdb_close
971 };
972
973 NTSTATUS idmap_tdb_init(void)
974 {
975         DEBUG(10, ("calling idmap_tdb_init\n"));
976
977         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_methods);
978 }