s3:idmap_tdb: have idmap_tdb_open_db take an idmap_domain struct as argument
[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 struct idmap_tdb_context {
37         struct db_context *db;
38 };
39
40 /* High water mark keys */
41 #define HWM_GROUP  "GROUP HWM"
42 #define HWM_USER   "USER HWM"
43
44 static struct idmap_tdb_state {
45
46         /* User and group id pool */
47         uid_t low_uid, high_uid;               /* Range of uids to allocate */
48         gid_t low_gid, high_gid;               /* Range of gids to allocate */
49
50 } idmap_tdb_state;
51
52 struct convert_fn_state {
53         struct db_context *db;
54         bool failed;
55 };
56
57 /*****************************************************************************
58  For idmap conversion: convert one record to new format
59  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
60  instead of the SID.
61 *****************************************************************************/
62 static int convert_fn(struct db_record *rec, void *private_data)
63 {
64         struct winbindd_domain *domain;
65         char *p;
66         NTSTATUS status;
67         struct dom_sid sid;
68         uint32 rid;
69         fstring keystr;
70         fstring dom_name;
71         TDB_DATA key2;
72         struct convert_fn_state *s = (struct convert_fn_state *)private_data;
73
74         DEBUG(10,("Converting %s\n", (const char *)rec->key.dptr));
75
76         p = strchr((const char *)rec->key.dptr, '/');
77         if (!p)
78                 return 0;
79
80         *p = 0;
81         fstrcpy(dom_name, (const char *)rec->key.dptr);
82         *p++ = '/';
83
84         domain = find_domain_from_name(dom_name);
85         if (domain == NULL) {
86                 /* We must delete the old record. */
87                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
88                 DEBUG(0,("deleting record %s\n", (const char *)rec->key.dptr ));
89
90                 status = rec->delete_rec(rec);
91                 if (!NT_STATUS_IS_OK(status)) {
92                         DEBUG(0, ("Unable to delete record %s:%s\n",
93                                 (const char *)rec->key.dptr,
94                                 nt_errstr(status)));
95                         s->failed = true;
96                         return -1;
97                 }
98
99                 return 0;
100         }
101
102         rid = atoi(p);
103
104         sid_compose(&sid, &domain->sid, rid);
105
106         sid_to_fstring(keystr, &sid);
107         key2 = string_term_tdb_data(keystr);
108
109         status = dbwrap_store(s->db, key2, rec->value, TDB_INSERT);
110         if (!NT_STATUS_IS_OK(status)) {
111                 DEBUG(0,("Unable to add record %s:%s\n",
112                         (const char *)key2.dptr,
113                         nt_errstr(status)));
114                 s->failed = true;
115                 return -1;
116         }
117
118         status = dbwrap_store(s->db, rec->value, key2, TDB_REPLACE);
119         if (!NT_STATUS_IS_OK(status)) {
120                 DEBUG(0,("Unable to update record %s:%s\n",
121                         (const char *)rec->value.dptr,
122                         nt_errstr(status)));
123                 s->failed = true;
124                 return -1;
125         }
126
127         status = rec->delete_rec(rec);
128         if (!NT_STATUS_IS_OK(status)) {
129                 DEBUG(0,("Unable to delete record %s:%s\n",
130                         (const char *)rec->key.dptr,
131                         nt_errstr(status)));
132                 s->failed = true;
133                 return -1;
134         }
135
136         return 0;
137 }
138
139 /*****************************************************************************
140  Convert the idmap database from an older version.
141 *****************************************************************************/
142
143 static bool idmap_tdb_upgrade(struct idmap_domain *dom, struct db_context *db)
144 {
145         int32 vers;
146         bool bigendianheader;
147         struct convert_fn_state s;
148
149         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
150
151         bigendianheader = (db->get_flags(db) & TDB_BIGENDIAN) ? True : False;
152
153         vers = dbwrap_fetch_int32(db, "IDMAP_VERSION");
154
155         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
156                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
157                 /*
158                  * high and low records were created on a
159                  * big endian machine and will need byte-reversing.
160                  */
161
162                 int32 wm;
163
164                 wm = dbwrap_fetch_int32(db, HWM_USER);
165
166                 if (wm != -1) {
167                         wm = IREV(wm);
168                 }  else {
169                         wm = dom->low_id;
170                 }
171
172                 if (dbwrap_store_int32(db, HWM_USER, wm) == -1) {
173                         DEBUG(0, ("Unable to byteswap user hwm in idmap database\n"));
174                         return False;
175                 }
176
177                 wm = dbwrap_fetch_int32(db, HWM_GROUP);
178                 if (wm != -1) {
179                         wm = IREV(wm);
180                 } else {
181                         wm = dom->low_id;
182                 }
183
184                 if (dbwrap_store_int32(db, HWM_GROUP, wm) == -1) {
185                         DEBUG(0, ("Unable to byteswap group hwm in idmap database\n"));
186                         return False;
187                 }
188         }
189
190         s.db = db;
191         s.failed = false;
192
193         /* the old format stored as DOMAIN/rid - now we store the SID direct */
194         db->traverse(db, convert_fn, &s);
195
196         if (s.failed) {
197                 DEBUG(0, ("Problem during conversion\n"));
198                 return False;
199         }
200
201         if (dbwrap_store_int32(db, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
202                 DEBUG(0, ("Unable to store idmap version in databse\n"));
203                 return False;
204         }
205
206         return True;
207 }
208
209 static NTSTATUS idmap_tdb_load_ranges(void)
210 {
211         uid_t low_uid = 0;
212         uid_t high_uid = 0;
213         gid_t low_gid = 0;
214         gid_t high_gid = 0;
215
216         if (!lp_idmap_uid(&low_uid, &high_uid)) {
217                 DEBUG(1, ("idmap uid missing\n"));
218                 return NT_STATUS_UNSUCCESSFUL;
219         }
220
221         if (!lp_idmap_gid(&low_gid, &high_gid)) {
222                 DEBUG(1, ("idmap gid missing\n"));
223                 return NT_STATUS_UNSUCCESSFUL;
224         }
225
226         idmap_tdb_state.low_uid = low_uid;
227         idmap_tdb_state.high_uid = high_uid;
228         idmap_tdb_state.low_gid = low_gid;
229         idmap_tdb_state.high_gid = high_gid;
230
231         if (idmap_tdb_state.high_uid <= idmap_tdb_state.low_uid) {
232                 DEBUG(1, ("idmap uid range missing or invalid\n"));
233                 return NT_STATUS_UNSUCCESSFUL;
234         }
235
236         if (idmap_tdb_state.high_gid <= idmap_tdb_state.low_gid) {
237                 DEBUG(1, ("idmap gid range missing or invalid\n"));
238                 return NT_STATUS_UNSUCCESSFUL;
239         }
240
241         return NT_STATUS_OK;
242 }
243
244 static NTSTATUS idmap_tdb_open_db(struct idmap_domain *dom)
245 {
246         NTSTATUS ret;
247         TALLOC_CTX *mem_ctx;
248         char *tdbfile = NULL;
249         struct db_context *db = NULL;
250         int32_t version;
251         bool config_error = false;
252         struct idmap_tdb_context *ctx;
253
254         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
255
256         /* use our own context here */
257         mem_ctx = talloc_stackframe();
258
259         /* use the old database if present */
260         tdbfile = state_path("winbindd_idmap.tdb");
261         if (!tdbfile) {
262                 DEBUG(0, ("Out of memory!\n"));
263                 ret = NT_STATUS_NO_MEMORY;
264                 goto done;
265         }
266
267         DEBUG(10,("Opening tdbfile %s\n", tdbfile ));
268
269         /* Open idmap repository */
270         db = db_open(mem_ctx, tdbfile, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
271         if (!db) {
272                 DEBUG(0, ("Unable to open idmap database\n"));
273                 ret = NT_STATUS_UNSUCCESSFUL;
274                 goto done;
275         }
276
277         /* check against earlier versions */
278         version = dbwrap_fetch_int32(db, "IDMAP_VERSION");
279         if (version != IDMAP_VERSION) {
280                 if (config_error) {
281                         DEBUG(0,("Upgrade of IDMAP_VERSION from %d to %d is not "
282                                  "possible with incomplete configuration\n",
283                                  version, IDMAP_VERSION));
284                         ret = NT_STATUS_UNSUCCESSFUL;
285                         goto done;
286                 }
287                 if (db->transaction_start(db) != 0) {
288                         DEBUG(0, ("Unable to start upgrade transaction!\n"));
289                         ret = NT_STATUS_INTERNAL_DB_ERROR;
290                         goto done;
291                 }
292
293                 if (!idmap_tdb_upgrade(dom, db)) {
294                         db->transaction_cancel(db);
295                         DEBUG(0, ("Unable to open idmap database, it's in an old format, and upgrade failed!\n"));
296                         ret = NT_STATUS_INTERNAL_DB_ERROR;
297                         goto done;
298                 }
299
300                 if (db->transaction_commit(db) != 0) {
301                         DEBUG(0, ("Unable to commit upgrade transaction!\n"));
302                         ret = NT_STATUS_INTERNAL_DB_ERROR;
303                         goto done;
304                 }
305         }
306
307         ctx->db = talloc_move(ctx, &db);
308         ret = NT_STATUS_OK;
309
310 done:
311         talloc_free(mem_ctx);
312         return ret;
313 }
314
315 /**********************************************************************
316  IDMAP ALLOC TDB BACKEND
317 **********************************************************************/
318  
319 static struct db_context *idmap_alloc_db;
320
321 /**********************************
322  Initialise idmap alloc database. 
323 **********************************/
324
325 static NTSTATUS idmap_tdb_init_hwm(struct idmap_domain *dom)
326 {
327         int ret;
328         uint32_t low_uid;
329         uint32_t low_gid;
330         bool update_uid = false;
331         bool update_gid = false;
332         struct idmap_tdb_context *ctx;
333
334         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
335
336         low_uid = dbwrap_fetch_int32(ctx->db, HWM_USER);
337         if (low_uid == -1 || low_uid < dom->low_id) {
338                 update_uid = true;
339         }
340
341         low_gid = dbwrap_fetch_int32(ctx->db, HWM_GROUP);
342         if (low_gid == -1 || low_gid < dom->low_id) {
343                 update_gid = true;
344         }
345
346         if (!update_uid && !update_gid) {
347                 return NT_STATUS_OK;
348         }
349
350         if (ctx->db->transaction_start(ctx->db) != 0) {
351                 DEBUG(0, ("Unable to start upgrade transaction!\n"));
352                 return NT_STATUS_INTERNAL_DB_ERROR;
353         }
354
355         if (update_uid) {
356                 ret = dbwrap_store_int32(ctx->db, HWM_USER, dom->low_id);
357                 if (ret == -1) {
358                         ctx->db->transaction_cancel(ctx->db);
359                         DEBUG(0, ("Unable to initialise user hwm in idmap "
360                                   "database\n"));
361                         return NT_STATUS_INTERNAL_DB_ERROR;
362                 }
363         }
364
365         if (update_gid) {
366                 ret = dbwrap_store_int32(ctx->db, HWM_GROUP, dom->low_id);
367                 if (ret == -1) {
368                         ctx->db->transaction_cancel(ctx->db);
369                         DEBUG(0, ("Unable to initialise group hwm in idmap "
370                                   "database\n"));
371                         return NT_STATUS_INTERNAL_DB_ERROR;
372                 }
373         }
374
375         if (ctx->db->transaction_commit(ctx->db) != 0) {
376                 DEBUG(0, ("Unable to commit upgrade transaction!\n"));
377                 return NT_STATUS_INTERNAL_DB_ERROR;
378         }
379
380         return NT_STATUS_OK;
381 }
382
383 /**********************************
384  Allocate a new id. 
385 **********************************/
386
387 struct idmap_tdb_allocate_id_context {
388         const char *hwmkey;
389         const char *hwmtype;
390         uint32_t high_hwm;
391         uint32_t hwm;
392 };
393
394 static NTSTATUS idmap_tdb_allocate_id_action(struct db_context *db,
395                                              void *private_data)
396 {
397         NTSTATUS ret;
398         struct idmap_tdb_allocate_id_context *state;
399         uint32_t hwm;
400
401         state = (struct idmap_tdb_allocate_id_context *)private_data;
402
403         hwm = dbwrap_fetch_int32(db, state->hwmkey);
404         if (hwm == -1) {
405                 ret = NT_STATUS_INTERNAL_DB_ERROR;
406                 goto done;
407         }
408
409         /* check it is in the range */
410         if (hwm > state->high_hwm) {
411                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
412                           state->hwmtype, (unsigned long)state->high_hwm));
413                 ret = NT_STATUS_UNSUCCESSFUL;
414                 goto done;
415         }
416
417         /* fetch a new id and increment it */
418         ret = dbwrap_trans_change_uint32_atomic(db, state->hwmkey, &hwm, 1);
419         if (!NT_STATUS_IS_OK(ret)) {
420                 DEBUG(0, ("Fatal error while fetching a new %s value: %s\n!",
421                           state->hwmtype, nt_errstr(ret)));
422                 goto done;
423         }
424
425         /* recheck it is in the range */
426         if (hwm > state->high_hwm) {
427                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
428                           state->hwmtype, (unsigned long)state->high_hwm));
429                 ret = NT_STATUS_UNSUCCESSFUL;
430                 goto done;
431         }
432
433         ret = NT_STATUS_OK;
434         state->hwm = hwm;
435
436 done:
437         return ret;
438 }
439
440 static NTSTATUS idmap_tdb_allocate_id(struct unixid *xid)
441 {
442         const char *hwmkey;
443         const char *hwmtype;
444         uint32_t high_hwm;
445         uint32_t hwm = 0;
446         NTSTATUS status;
447         struct idmap_tdb_allocate_id_context state;
448
449         /* Get current high water mark */
450         switch (xid->type) {
451
452         case ID_TYPE_UID:
453                 hwmkey = HWM_USER;
454                 hwmtype = "UID";
455                 high_hwm = idmap_tdb_state.high_uid;
456                 break;
457
458         case ID_TYPE_GID:
459                 hwmkey = HWM_GROUP;
460                 hwmtype = "GID";
461                 high_hwm = idmap_tdb_state.high_gid;
462                 break;
463
464         default:
465                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
466                 return NT_STATUS_INVALID_PARAMETER;
467         }
468
469         state.hwm = hwm;
470         state.high_hwm = high_hwm;
471         state.hwmtype = hwmtype;
472         state.hwmkey = hwmkey;
473
474         status = dbwrap_trans_do(idmap_alloc_db, idmap_tdb_allocate_id_action,
475                                  &state);
476
477         if (NT_STATUS_IS_OK(status)) {
478                 xid->id = state.hwm;
479                 DEBUG(10,("New %s = %d\n", hwmtype, state.hwm));
480         } else {
481                 DEBUG(1, ("Error allocating a new %s\n", hwmtype));
482         }
483
484         return status;
485 }
486
487 /**
488  * Allocate a new unix-ID.
489  * For now this is for the default idmap domain only.
490  * Should be extended later on.
491  */
492 static NTSTATUS idmap_tdb_get_new_id(struct idmap_domain *dom,
493                                      struct unixid *id)
494 {
495         NTSTATUS ret;
496
497         if (!strequal(dom->name, "*")) {
498                 DEBUG(3, ("idmap_tdb_get_new_id: "
499                           "Refusing allocation of a new unixid for domain'%s'. "
500                           "Currently only supported for the default "
501                           "domain \"*\".\n",
502                            dom->name));
503                 return NT_STATUS_NOT_IMPLEMENTED;
504         }
505
506         ret = idmap_tdb_allocate_id(id);
507
508         return ret;
509 }
510
511 /**********************************
512  Close the alloc tdb 
513 **********************************/
514
515 static NTSTATUS idmap_tdb_alloc_close(void)
516 {
517         TALLOC_FREE(idmap_alloc_db);
518         return NT_STATUS_OK;
519 }
520
521 /**********************************************************************
522  IDMAP MAPPING TDB BACKEND
523 **********************************************************************/
524
525 /*****************************
526  Initialise idmap database. 
527 *****************************/
528
529 static NTSTATUS idmap_tdb_db_init(struct idmap_domain *dom, const char *params)
530 {
531         NTSTATUS ret;
532         struct idmap_tdb_context *ctx;
533
534         DEBUG(10, ("idmap_tdb_db_init called for domain '%s'\n", dom->name));
535
536         ctx = talloc(dom, struct idmap_tdb_context);
537         if ( ! ctx) {
538                 DEBUG(0, ("Out of memory!\n"));
539                 return NT_STATUS_NO_MEMORY;
540         }
541
542         /* load backend specific configuration here: */
543 #if 0
544         if (strequal(dom->name, "*")) {
545         } else {
546         }
547 #endif
548
549         dom->private_data = ctx;
550
551         ret = idmap_tdb_open_db(dom);
552         if ( ! NT_STATUS_IS_OK(ret)) {
553                 goto failed;
554         }
555
556         return NT_STATUS_OK;
557
558 failed:
559         talloc_free(ctx);
560         return ret;
561 }
562
563 /**********************************
564  Single id to sid lookup function. 
565 **********************************/
566
567 static NTSTATUS idmap_tdb_id_to_sid(struct idmap_domain *dom, struct id_map *map)
568 {
569         NTSTATUS ret;
570         TDB_DATA data;
571         char *keystr;
572         struct idmap_tdb_context *ctx;
573
574         if (!dom || !map) {
575                 return NT_STATUS_INVALID_PARAMETER;
576         }
577
578         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
579
580         /* apply filters before checking */
581         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
582                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
583                                 map->xid.id, dom->low_id, dom->high_id));
584                 return NT_STATUS_NONE_MAPPED;
585         }
586
587         switch (map->xid.type) {
588
589         case ID_TYPE_UID:
590                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
591                 break;
592                 
593         case ID_TYPE_GID:
594                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
595                 break;
596
597         default:
598                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
599                 return NT_STATUS_INVALID_PARAMETER;
600         }
601
602         /* final SAFE_FREE safe */
603         data.dptr = NULL;
604
605         if (keystr == NULL) {
606                 DEBUG(0, ("Out of memory!\n"));
607                 ret = NT_STATUS_NO_MEMORY;
608                 goto done;
609         }
610
611         DEBUG(10,("Fetching record %s\n", keystr));
612
613         /* Check if the mapping exists */
614         data = dbwrap_fetch_bystring(ctx->db, NULL, keystr);
615
616         if (!data.dptr) {
617                 DEBUG(10,("Record %s not found\n", keystr));
618                 ret = NT_STATUS_NONE_MAPPED;
619                 goto done;
620         }
621                 
622         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
623                 DEBUG(10,("INVALID SID (%s) in record %s\n",
624                         (const char *)data.dptr, keystr));
625                 ret = NT_STATUS_INTERNAL_DB_ERROR;
626                 goto done;
627         }
628
629         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
630         ret = NT_STATUS_OK;
631
632 done:
633         talloc_free(data.dptr);
634         talloc_free(keystr);
635         return ret;
636 }
637
638 /**********************************
639  Single sid to id lookup function. 
640 **********************************/
641
642 static NTSTATUS idmap_tdb_sid_to_id(struct idmap_domain *dom, struct id_map *map)
643 {
644         NTSTATUS ret;
645         TDB_DATA data;
646         char *keystr;
647         unsigned long rec_id = 0;
648         struct idmap_tdb_context *ctx;
649         TALLOC_CTX *tmp_ctx = talloc_stackframe();
650
651         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
652
653         keystr = sid_string_talloc(tmp_ctx, map->sid);
654         if (keystr == NULL) {
655                 DEBUG(0, ("Out of memory!\n"));
656                 ret = NT_STATUS_NO_MEMORY;
657                 goto done;
658         }
659
660         DEBUG(10,("Fetching record %s\n", keystr));
661
662         /* Check if sid is present in database */
663         data = dbwrap_fetch_bystring(ctx->db, tmp_ctx, keystr);
664         if (!data.dptr) {
665                 DEBUG(10,("Record %s not found\n", keystr));
666                 ret = NT_STATUS_NONE_MAPPED;
667                 goto done;
668         }
669
670         /* What type of record is this ? */
671         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
672                 map->xid.id = rec_id;
673                 map->xid.type = ID_TYPE_UID;
674                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
675                 ret = NT_STATUS_OK;
676
677         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
678                 map->xid.id = rec_id;
679                 map->xid.type = ID_TYPE_GID;
680                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
681                 ret = NT_STATUS_OK;
682
683         } else { /* Unknown record type ! */
684                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
685                 ret = NT_STATUS_INTERNAL_DB_ERROR;
686                 goto done;
687         }
688
689         /* apply filters before returning result */
690         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
691                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
692                                 map->xid.id, dom->low_id, dom->high_id));
693                 ret = NT_STATUS_NONE_MAPPED;
694         }
695
696 done:
697         talloc_free(tmp_ctx);
698         return ret;
699 }
700
701 /**********************************
702  lookup a set of unix ids. 
703 **********************************/
704
705 static NTSTATUS idmap_tdb_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
706 {
707         struct idmap_tdb_context *ctx;
708         NTSTATUS ret;
709         int i;
710
711         /* initialize the status to avoid suprise */
712         for (i = 0; ids[i]; i++) {
713                 ids[i]->status = ID_UNKNOWN;
714         }
715         
716         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
717
718         for (i = 0; ids[i]; i++) {
719                 ret = idmap_tdb_id_to_sid(dom, ids[i]);
720                 if ( ! NT_STATUS_IS_OK(ret)) {
721
722                         /* if it is just a failed mapping continue */
723                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
724
725                                 /* make sure it is marked as unmapped */
726                                 ids[i]->status = ID_UNMAPPED;
727                                 continue;
728                         }
729                         
730                         /* some fatal error occurred, return immediately */
731                         goto done;
732                 }
733
734                 /* all ok, id is mapped */
735                 ids[i]->status = ID_MAPPED;
736         }
737
738         ret = NT_STATUS_OK;
739
740 done:
741         return ret;
742 }
743
744 /**********************************
745  lookup a set of sids. 
746 **********************************/
747
748 static NTSTATUS idmap_tdb_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
749 {
750         struct idmap_tdb_context *ctx;
751         NTSTATUS ret;
752         int i;
753
754         /* initialize the status to avoid suprise */
755         for (i = 0; ids[i]; i++) {
756                 ids[i]->status = ID_UNKNOWN;
757         }
758         
759         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
760
761         for (i = 0; ids[i]; i++) {
762                 ret = idmap_tdb_sid_to_id(dom, ids[i]);
763                 if ( ! NT_STATUS_IS_OK(ret)) {
764
765                         /* if it is just a failed mapping continue */
766                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
767
768                                 /* make sure it is marked as unmapped */
769                                 ids[i]->status = ID_UNMAPPED;
770                                 continue;
771                         }
772                         
773                         /* some fatal error occurred, return immediately */
774                         goto done;
775                 }
776
777                 /* all ok, id is mapped */
778                 ids[i]->status = ID_MAPPED;
779         }
780
781         ret = NT_STATUS_OK;
782
783 done:
784         return ret;
785 }
786
787 /**********************************
788  set a mapping.
789 **********************************/
790
791 static NTSTATUS idmap_tdb_set_mapping(struct idmap_domain *dom,
792                                       const struct id_map *map)
793 {
794         struct idmap_tdb_context *ctx;
795         NTSTATUS ret;
796         TDB_DATA ksid, kid;
797         char *ksidstr, *kidstr;
798         fstring tmp;
799
800         if (!map || !map->sid) {
801                 return NT_STATUS_INVALID_PARAMETER;
802         }
803
804         ksidstr = kidstr = NULL;
805
806         /* TODO: should we filter a set_mapping using low/high filters ? */
807
808         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
809
810         switch (map->xid.type) {
811
812         case ID_TYPE_UID:
813                 kidstr = talloc_asprintf(ctx, "UID %lu",
814                                          (unsigned long)map->xid.id);
815                 break;
816
817         case ID_TYPE_GID:
818                 kidstr = talloc_asprintf(ctx, "GID %lu",
819                                          (unsigned long)map->xid.id);
820                 break;
821
822         default:
823                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
824                 return NT_STATUS_INVALID_PARAMETER;
825         }
826
827         if (kidstr == NULL) {
828                 DEBUG(0, ("ERROR: Out of memory!\n"));
829                 ret = NT_STATUS_NO_MEMORY;
830                 goto done;
831         }
832
833         if ((ksidstr = talloc_asprintf(
834                      ctx, "%s", sid_to_fstring(tmp, map->sid))) == NULL) {
835                 DEBUG(0, ("Out of memory!\n"));
836                 ret = NT_STATUS_NO_MEMORY;
837                 goto done;
838         }
839
840         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
841         kid = string_term_tdb_data(kidstr);
842         ksid = string_term_tdb_data(ksidstr);
843
844         if (ctx->db->transaction_start(ctx->db) != 0) {
845                 DEBUG(0, ("Failed to start transaction for %s\n",
846                           ksidstr));
847                 ret = NT_STATUS_INTERNAL_DB_ERROR;
848                 goto done;
849         }
850
851         ret = dbwrap_store(ctx->db, ksid, kid, TDB_REPLACE);
852         if (!NT_STATUS_IS_OK(ret)) {
853                 ctx->db->transaction_cancel(ctx->db);
854                 DEBUG(0, ("Error storing SID -> ID (%s -> %s): %s\n",
855                           ksidstr, kidstr, nt_errstr(ret)));
856                 goto done;
857         }
858         ret = dbwrap_store(ctx->db, kid, ksid, TDB_REPLACE);
859         if (!NT_STATUS_IS_OK(ret)) {
860                 ctx->db->transaction_cancel(ctx->db);
861                 DEBUG(0, ("Error storing ID -> SID (%s -> %s): %s\n",
862                           kidstr, ksidstr, nt_errstr(ret)));
863                 goto done;
864         }
865
866         if (ctx->db->transaction_commit(ctx->db) != 0) {
867                 DEBUG(0, ("Failed to commit transaction for (%s -> %s)\n",
868                           ksidstr, kidstr));
869                 ret = NT_STATUS_INTERNAL_DB_ERROR;
870                 goto done;
871         }
872
873         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
874         ret = NT_STATUS_OK;
875
876 done:
877         talloc_free(ksidstr);
878         talloc_free(kidstr);
879         return ret;
880 }
881
882 /**********************************
883  Close the idmap tdb instance
884 **********************************/
885
886 static NTSTATUS idmap_tdb_close(struct idmap_domain *dom)
887 {
888         struct idmap_tdb_context *ctx;
889
890         if (dom->private_data) {
891                 ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
892
893                 TALLOC_FREE(ctx->db);
894         }
895         return NT_STATUS_OK;
896 }
897
898 static struct idmap_methods db_methods = {
899         .init = idmap_tdb_db_init,
900         .unixids_to_sids = idmap_tdb_unixids_to_sids,
901         .sids_to_unixids = idmap_tdb_sids_to_unixids,
902         .allocate_id = idmap_tdb_get_new_id,
903         .close_fn = idmap_tdb_close
904 };
905
906 NTSTATUS idmap_tdb_init(void)
907 {
908         DEBUG(10, ("calling idmap_tdb_init\n"));
909
910         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_methods);
911 }