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