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