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