Merge 2610c05b5b95cc7036b3d6dfb894c6cfbdb68483 as Samba-4.0alpha16
[ira/wip.git] / source3 / winbindd / idmap_tdb2.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    idmap TDB2 backend, used for clustered Samba setups.
5
6    This uses dbwrap to access tdb files. The location can be set
7    using tdb:idmap2.tdb =" in smb.conf
8
9    Copyright (C) Andrew Tridgell 2007
10
11    This is heavily based upon idmap_tdb.c, which is:
12
13    Copyright (C) Tim Potter 2000
14    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
15    Copyright (C) Jeremy Allison 2006
16    Copyright (C) Simo Sorce 2003-2006
17    Copyright (C) Michael Adam 2009-2010
18
19    This program is free software; you can redistribute it and/or modify
20    it under the terms of the GNU General Public License as published by
21    the Free Software Foundation; either version 2 of the License, or
22    (at your option) any later version.
23
24    This program is distributed in the hope that it will be useful,
25    but WITHOUT ANY WARRANTY; without even the implied warranty of
26    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27    GNU General Public License for more details.
28
29    You should have received a copy of the GNU General Public License
30    along with this program; if not, write to the Free Software
31    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 */
33
34 #include "includes.h"
35 #include "system/filesys.h"
36 #include "winbindd.h"
37 #include "idmap.h"
38 #include "idmap_rw.h"
39 #include "dbwrap.h"
40 #include "../libcli/security/dom_sid.h"
41 #include "util_tdb.h"
42
43 #undef DBGC_CLASS
44 #define DBGC_CLASS DBGC_IDMAP
45
46 struct idmap_tdb2_context {
47         struct db_context *db;
48         const char *script; /* script to provide idmaps */
49         struct idmap_rw_ops *rw_ops;
50 };
51
52 /* High water mark keys */
53 #define HWM_GROUP  "GROUP HWM"
54 #define HWM_USER   "USER HWM"
55
56
57 /*
58  * check and initialize high/low water marks in the db
59  */
60 static NTSTATUS idmap_tdb2_init_hwm(struct idmap_domain *dom)
61 {
62         NTSTATUS status;
63         uint32 low_id;
64         struct idmap_tdb2_context *ctx;
65
66         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
67
68         /* Create high water marks for group and user id */
69
70         low_id = dbwrap_fetch_int32(ctx->db, HWM_USER);
71         if ((low_id == -1) || (low_id < dom->low_id)) {
72                 status = dbwrap_trans_store_int32(ctx->db, HWM_USER,
73                                                   dom->low_id);
74                 if (!NT_STATUS_IS_OK(status)) {
75                         DEBUG(0, ("Unable to initialise user hwm in idmap "
76                                   "database: %s\n", nt_errstr(status)));
77                         return NT_STATUS_INTERNAL_DB_ERROR;
78                 }
79         }
80
81         low_id = dbwrap_fetch_int32(ctx->db, HWM_GROUP);
82         if ((low_id == -1) || (low_id < dom->low_id)) {
83                 status = dbwrap_trans_store_int32(ctx->db, HWM_GROUP,
84                                                   dom->low_id);
85                 if (!NT_STATUS_IS_OK(status)) {
86                         DEBUG(0, ("Unable to initialise group hwm in idmap "
87                                   "database: %s\n", nt_errstr(status)));
88                         return NT_STATUS_INTERNAL_DB_ERROR;
89                 }
90         }
91
92         return NT_STATUS_OK;
93 }
94
95
96 /*
97   open the permanent tdb
98  */
99 static NTSTATUS idmap_tdb2_open_db(struct idmap_domain *dom)
100 {
101         char *db_path;
102         struct idmap_tdb2_context *ctx;
103
104         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
105
106         if (ctx->db) {
107                 /* its already open */
108                 return NT_STATUS_OK;
109         }
110
111         db_path = lp_parm_talloc_string(-1, "tdb", "idmap2.tdb", NULL);
112         if (db_path == NULL) {
113                 /* fall back to the private directory, which, despite
114                    its name, is usually on shared storage */
115                 db_path = talloc_asprintf(NULL, "%s/idmap2.tdb", lp_private_dir());
116         }
117         NT_STATUS_HAVE_NO_MEMORY(db_path);
118
119         /* Open idmap repository */
120         ctx->db = db_open(ctx, db_path, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644);
121         TALLOC_FREE(db_path);
122
123         if (ctx->db == NULL) {
124                 DEBUG(0, ("Unable to open idmap_tdb2 database '%s'\n",
125                           db_path));
126                 return NT_STATUS_UNSUCCESSFUL;
127         }
128
129         return idmap_tdb2_init_hwm(dom);
130 }
131
132
133 /*
134   Allocate a new id. 
135 */
136
137 struct idmap_tdb2_allocate_id_context {
138         const char *hwmkey;
139         const char *hwmtype;
140         uint32_t high_hwm;
141         uint32_t hwm;
142 };
143
144 static NTSTATUS idmap_tdb2_allocate_id_action(struct db_context *db,
145                                               void *private_data)
146 {
147         NTSTATUS ret;
148         struct idmap_tdb2_allocate_id_context *state;
149         uint32_t hwm;
150
151         state = (struct idmap_tdb2_allocate_id_context *)private_data;
152
153         hwm = dbwrap_fetch_int32(db, state->hwmkey);
154         if (hwm == -1) {
155                 ret = NT_STATUS_INTERNAL_DB_ERROR;
156                 goto done;
157         }
158
159         /* check it is in the range */
160         if (hwm > state->high_hwm) {
161                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
162                           state->hwmtype, (unsigned long)state->high_hwm));
163                 ret = NT_STATUS_UNSUCCESSFUL;
164                 goto done;
165         }
166
167         /* fetch a new id and increment it */
168         ret = dbwrap_trans_change_uint32_atomic(db, state->hwmkey, &hwm, 1);
169         if (!NT_STATUS_IS_OK(ret)) {
170                 DEBUG(1, ("Fatal error while fetching a new %s value\n!",
171                           state->hwmtype));
172                 goto done;
173         }
174
175         /* recheck it is in the range */
176         if (hwm > state->high_hwm) {
177                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
178                           state->hwmtype, (unsigned long)state->high_hwm));
179                 ret = NT_STATUS_UNSUCCESSFUL;
180                 goto done;
181         }
182
183         ret = NT_STATUS_OK;
184         state->hwm = hwm;
185
186 done:
187         return ret;
188 }
189
190 static NTSTATUS idmap_tdb2_allocate_id(struct idmap_domain *dom,
191                                        struct unixid *xid)
192 {
193         const char *hwmkey;
194         const char *hwmtype;
195         uint32_t high_hwm;
196         uint32_t hwm = 0;
197         NTSTATUS status;
198         struct idmap_tdb2_allocate_id_context state;
199         struct idmap_tdb2_context *ctx;
200
201         status = idmap_tdb2_open_db(dom);
202         NT_STATUS_NOT_OK_RETURN(status);
203
204         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
205
206         /* Get current high water mark */
207         switch (xid->type) {
208
209         case ID_TYPE_UID:
210                 hwmkey = HWM_USER;
211                 hwmtype = "UID";
212                 break;
213
214         case ID_TYPE_GID:
215                 hwmkey = HWM_GROUP;
216                 hwmtype = "GID";
217                 break;
218
219         default:
220                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
221                 return NT_STATUS_INVALID_PARAMETER;
222         }
223
224         high_hwm = dom->high_id;
225
226         state.hwm = hwm;
227         state.high_hwm = high_hwm;
228         state.hwmtype = hwmtype;
229         state.hwmkey = hwmkey;
230
231         status = dbwrap_trans_do(ctx->db, idmap_tdb2_allocate_id_action,
232                                  &state);
233
234         if (NT_STATUS_IS_OK(status)) {
235                 xid->id = state.hwm;
236                 DEBUG(10,("New %s = %d\n", hwmtype, state.hwm));
237         } else {
238                 DEBUG(1, ("Error allocating a new %s\n", hwmtype));
239         }
240
241         return status;
242 }
243
244 /**
245  * Allocate a new unix-ID.
246  * For now this is for the default idmap domain only.
247  * Should be extended later on.
248  */
249 static NTSTATUS idmap_tdb2_get_new_id(struct idmap_domain *dom,
250                                       struct unixid *id)
251 {
252         NTSTATUS ret;
253
254         if (!strequal(dom->name, "*")) {
255                 DEBUG(3, ("idmap_tdb2_get_new_id: "
256                           "Refusing creation of mapping for domain'%s'. "
257                           "Currently only supported for the default "
258                           "domain \"*\".\n",
259                            dom->name));
260                 return NT_STATUS_NOT_IMPLEMENTED;
261         }
262
263         ret = idmap_tdb2_allocate_id(dom, id);
264
265         return ret;
266 }
267
268 /*
269   IDMAP MAPPING TDB BACKEND
270 */
271
272 static NTSTATUS idmap_tdb2_set_mapping(struct idmap_domain *dom,
273                                        const struct id_map *map);
274
275 /*
276   Initialise idmap database. 
277 */
278 static NTSTATUS idmap_tdb2_db_init(struct idmap_domain *dom)
279 {
280         NTSTATUS ret;
281         struct idmap_tdb2_context *ctx;
282
283         ctx = talloc_zero(dom, struct idmap_tdb2_context);
284         if ( ! ctx) {
285                 DEBUG(0, ("Out of memory!\n"));
286                 return NT_STATUS_NO_MEMORY;
287         }
288
289         if (strequal(dom->name, "*")) {
290                 ctx->script = lp_parm_const_string(-1, "idmap", "script", NULL);
291                 if (ctx->script) {
292                         DEBUG(1, ("using idmap script '%s'\n", ctx->script));
293                 }
294         } else {
295                 char *config_option = NULL;
296
297                 config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
298                 if ( ! config_option) {
299                         DEBUG(0, ("Out of memory!\n"));
300                         ret = NT_STATUS_NO_MEMORY;
301                         goto failed;
302                 }
303
304                 ctx->script = lp_parm_const_string(-1, config_option, "script", NULL);
305                 if (ctx->script) {
306                         DEBUG(1, ("using idmap script '%s'\n", ctx->script));
307                 }
308
309                 talloc_free(config_option);
310         }
311
312         ctx->rw_ops = talloc_zero(ctx, struct idmap_rw_ops);
313         if (ctx->rw_ops == NULL) {
314                 DEBUG(0, ("Out of memory!\n"));
315                 ret = NT_STATUS_NO_MEMORY;
316                 goto failed;
317         }
318
319         ctx->rw_ops->get_new_id = idmap_tdb2_get_new_id;
320         ctx->rw_ops->set_mapping = idmap_tdb2_set_mapping;
321
322         dom->private_data = ctx;
323
324         ret = idmap_tdb2_open_db(dom);
325         if (!NT_STATUS_IS_OK(ret)) {
326                 goto failed;
327         }
328
329         return NT_STATUS_OK;
330
331 failed:
332         talloc_free(ctx);
333         return ret;
334 }
335
336
337 /**
338  * store a mapping in the database.
339  */
340
341 struct idmap_tdb2_set_mapping_context {
342         const char *ksidstr;
343         const char *kidstr;
344 };
345
346 static NTSTATUS idmap_tdb2_set_mapping_action(struct db_context *db,
347                                               void *private_data)
348 {
349         TDB_DATA data;
350         NTSTATUS ret;
351         struct idmap_tdb2_set_mapping_context *state;
352         TALLOC_CTX *tmp_ctx = talloc_stackframe();
353
354         state = (struct idmap_tdb2_set_mapping_context *)private_data;
355
356         DEBUG(10, ("Storing %s <-> %s map\n", state->ksidstr, state->kidstr));
357
358         /* check wheter sid mapping is already present in db */
359         data = dbwrap_fetch_bystring(db, tmp_ctx, state->ksidstr);
360         if (data.dptr) {
361                 ret = NT_STATUS_OBJECT_NAME_COLLISION;
362                 goto done;
363         }
364
365         ret = dbwrap_store_bystring(db, state->ksidstr,
366                                     string_term_tdb_data(state->kidstr),
367                                     TDB_INSERT);
368         if (!NT_STATUS_IS_OK(ret)) {
369                 DEBUG(0, ("Error storing SID -> ID: %s\n", nt_errstr(ret)));
370                 goto done;
371         }
372
373         ret = dbwrap_store_bystring(db, state->kidstr,
374                                     string_term_tdb_data(state->ksidstr),
375                                     TDB_INSERT);
376         if (!NT_STATUS_IS_OK(ret)) {
377                 DEBUG(0, ("Error storing ID -> SID: %s\n", nt_errstr(ret)));
378                 /* try to remove the previous stored SID -> ID map */
379                 dbwrap_delete_bystring(db, state->ksidstr);
380                 goto done;
381         }
382
383         DEBUG(10,("Stored %s <-> %s\n", state->ksidstr, state->kidstr));
384
385 done:
386         talloc_free(tmp_ctx);
387         return ret;
388 }
389
390 static NTSTATUS idmap_tdb2_set_mapping(struct idmap_domain *dom, const struct id_map *map)
391 {
392         struct idmap_tdb2_context *ctx;
393         NTSTATUS ret;
394         char *ksidstr, *kidstr;
395         struct idmap_tdb2_set_mapping_context state;
396
397         if (!map || !map->sid) {
398                 return NT_STATUS_INVALID_PARAMETER;
399         }
400
401         ksidstr = kidstr = NULL;
402
403         /* TODO: should we filter a set_mapping using low/high filters ? */
404
405         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
406
407         switch (map->xid.type) {
408
409         case ID_TYPE_UID:
410                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
411                 break;
412
413         case ID_TYPE_GID:
414                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
415                 break;
416
417         default:
418                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
419                 return NT_STATUS_INVALID_PARAMETER;
420         }
421
422         if (kidstr == NULL) {
423                 DEBUG(0, ("ERROR: Out of memory!\n"));
424                 ret = NT_STATUS_NO_MEMORY;
425                 goto done;
426         }
427
428         ksidstr = sid_string_talloc(ctx, map->sid);
429         if (ksidstr == NULL) {
430                 DEBUG(0, ("Out of memory!\n"));
431                 ret = NT_STATUS_NO_MEMORY;
432                 goto done;
433         }
434
435         state.ksidstr = ksidstr;
436         state.kidstr = kidstr;
437
438         ret = dbwrap_trans_do(ctx->db, idmap_tdb2_set_mapping_action,
439                               &state);
440
441 done:
442         talloc_free(ksidstr);
443         talloc_free(kidstr);
444         return ret;
445 }
446
447 /**
448  * Create a new mapping for an unmapped SID, also allocating a new ID.
449  * This should be run inside a transaction.
450  *
451  * TODO:
452 *  Properly integrate this with multi domain idmap config:
453  * Currently, the allocator is default-config only.
454  */
455 static NTSTATUS idmap_tdb2_new_mapping(struct idmap_domain *dom, struct id_map *map)
456 {
457         NTSTATUS ret;
458         struct idmap_tdb2_context *ctx;
459
460         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
461
462         ret = idmap_rw_new_mapping(dom, ctx->rw_ops, map);
463
464         return ret;
465 }
466
467
468 /*
469   run a script to perform a mapping
470
471   The script should the following command lines:
472
473       SIDTOID S-1-xxxx
474       IDTOSID UID xxxx
475       IDTOSID GID xxxx
476
477   and should return one of the following as a single line of text
478      UID:xxxx
479      GID:xxxx
480      SID:xxxx
481      ERR:xxxx
482  */
483 static NTSTATUS idmap_tdb2_script(struct idmap_tdb2_context *ctx, struct id_map *map,
484                                   const char *fmt, ...)
485 {
486         va_list ap;
487         char *cmd;
488         FILE *p;
489         char line[64];
490         unsigned long v;
491
492         cmd = talloc_asprintf(ctx, "%s ", ctx->script);
493         NT_STATUS_HAVE_NO_MEMORY(cmd);  
494
495         va_start(ap, fmt);
496         cmd = talloc_vasprintf_append(cmd, fmt, ap);
497         va_end(ap);
498         NT_STATUS_HAVE_NO_MEMORY(cmd);
499
500         p = popen(cmd, "r");
501         talloc_free(cmd);
502         if (p == NULL) {
503                 return NT_STATUS_NONE_MAPPED;
504         }
505
506         if (fgets(line, sizeof(line)-1, p) == NULL) {
507                 pclose(p);
508                 return NT_STATUS_NONE_MAPPED;
509         }
510         pclose(p);
511
512         DEBUG(10,("idmap script gave: %s\n", line));
513
514         if (sscanf(line, "UID:%lu", &v) == 1) {
515                 map->xid.id   = v;
516                 map->xid.type = ID_TYPE_UID;
517         } else if (sscanf(line, "GID:%lu", &v) == 1) {
518                 map->xid.id   = v;
519                 map->xid.type = ID_TYPE_GID;            
520         } else if (strncmp(line, "SID:S-", 6) == 0) {
521                 if (!string_to_sid(map->sid, &line[4])) {
522                         DEBUG(0,("Bad SID in '%s' from idmap script %s\n",
523                                  line, ctx->script));
524                         return NT_STATUS_NONE_MAPPED;                   
525                 }
526         } else {
527                 DEBUG(0,("Bad reply '%s' from idmap script %s\n",
528                          line, ctx->script));
529                 return NT_STATUS_NONE_MAPPED;
530         }
531
532         return NT_STATUS_OK;
533 }
534
535
536
537 /*
538   Single id to sid lookup function. 
539 */
540 static NTSTATUS idmap_tdb2_id_to_sid(struct idmap_domain *dom, struct id_map *map)
541 {
542         NTSTATUS ret;
543         TDB_DATA data;
544         char *keystr;
545         NTSTATUS status;
546         struct idmap_tdb2_context *ctx;
547
548
549         if (!dom || !map) {
550                 return NT_STATUS_INVALID_PARAMETER;
551         }
552
553         status = idmap_tdb2_open_db(dom);
554         NT_STATUS_NOT_OK_RETURN(status);
555
556         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
557
558         /* apply filters before checking */
559         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
560                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
561                                 map->xid.id, dom->low_id, dom->high_id));
562                 return NT_STATUS_NONE_MAPPED;
563         }
564
565         switch (map->xid.type) {
566
567         case ID_TYPE_UID:
568                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
569                 break;
570
571         case ID_TYPE_GID:
572                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
573                 break;
574
575         default:
576                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
577                 return NT_STATUS_INVALID_PARAMETER;
578         }
579
580         /* final SAFE_FREE safe */
581         data.dptr = NULL;
582
583         if (keystr == NULL) {
584                 DEBUG(0, ("Out of memory!\n"));
585                 ret = NT_STATUS_NO_MEMORY;
586                 goto done;
587         }
588
589         DEBUG(10,("Fetching record %s\n", keystr));
590
591         /* Check if the mapping exists */
592         data = dbwrap_fetch_bystring(ctx->db, keystr, keystr);
593
594         if (!data.dptr) {
595                 char *sidstr;
596                 struct idmap_tdb2_set_mapping_context store_state;
597
598                 DEBUG(10,("Record %s not found\n", keystr));
599                 if (ctx->script == NULL) {
600                         ret = NT_STATUS_NONE_MAPPED;
601                         goto done;
602                 }
603
604                 ret = idmap_tdb2_script(ctx, map, "IDTOSID %s", keystr);
605
606                 /* store it on shared storage */
607                 if (!NT_STATUS_IS_OK(ret)) {
608                         goto done;
609                 }
610
611                 sidstr = sid_string_talloc(keystr, map->sid);
612                 if (!sidstr) {
613                         ret = NT_STATUS_NO_MEMORY;
614                         goto done;
615                 }
616
617                 store_state.ksidstr = sidstr;
618                 store_state.kidstr = keystr;
619
620                 ret = dbwrap_trans_do(ctx->db, idmap_tdb2_set_mapping_action,
621                                       &store_state);
622                 goto done;
623         }
624
625         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
626                 DEBUG(10,("INVALID SID (%s) in record %s\n",
627                         (const char *)data.dptr, keystr));
628                 ret = NT_STATUS_INTERNAL_DB_ERROR;
629                 goto done;
630         }
631
632         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
633         ret = NT_STATUS_OK;
634
635 done:
636         talloc_free(keystr);
637         return ret;
638 }
639
640
641 /*
642  Single sid to id lookup function. 
643 */
644 static NTSTATUS idmap_tdb2_sid_to_id(struct idmap_domain *dom, struct id_map *map)
645 {
646         NTSTATUS ret;
647         TDB_DATA data;
648         char *keystr;
649         unsigned long rec_id = 0;
650         struct idmap_tdb2_context *ctx;
651         TALLOC_CTX *tmp_ctx = talloc_stackframe();
652
653         ret = idmap_tdb2_open_db(dom);
654         NT_STATUS_NOT_OK_RETURN(ret);
655
656         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
657
658         keystr = sid_string_talloc(tmp_ctx, map->sid);
659         if (keystr == NULL) {
660                 DEBUG(0, ("Out of memory!\n"));
661                 ret = NT_STATUS_NO_MEMORY;
662                 goto done;
663         }
664
665         DEBUG(10,("Fetching record %s\n", keystr));
666
667         /* Check if sid is present in database */
668         data = dbwrap_fetch_bystring(ctx->db, tmp_ctx, keystr);
669         if (!data.dptr) {
670                 char *idstr;
671                 struct idmap_tdb2_set_mapping_context store_state;
672
673                 DEBUG(10,(__location__ " Record %s not found\n", keystr));
674
675                 if (ctx->script == NULL) {
676                         ret = NT_STATUS_NONE_MAPPED;
677                         goto done;
678                 }
679
680                 ret = idmap_tdb2_script(ctx, map, "SIDTOID %s", keystr);
681                 /* store it on shared storage */
682                 if (!NT_STATUS_IS_OK(ret)) {
683                         goto done;
684                 }
685
686                 /* apply filters before returning result */
687                 if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
688                         DEBUG(5, ("Script returned id (%u) out of range "
689                                   "(%u - %u). Filtered!\n",
690                                   map->xid.id, dom->low_id, dom->high_id));
691                         ret = NT_STATUS_NONE_MAPPED;
692                         goto done;
693                 }
694
695                 idstr = talloc_asprintf(tmp_ctx, "%cID %lu",
696                                         map->xid.type == ID_TYPE_UID?'U':'G',
697                                         (unsigned long)map->xid.id);
698                 if (idstr == NULL) {
699                         ret = NT_STATUS_NO_MEMORY;
700                         goto done;
701                 }
702
703                 store_state.ksidstr = keystr;
704                 store_state.kidstr = idstr;
705
706                 ret = dbwrap_trans_do(ctx->db, idmap_tdb2_set_mapping_action,
707                                       &store_state);
708                 goto done;
709         }
710
711         /* What type of record is this ? */
712         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
713                 map->xid.id = rec_id;
714                 map->xid.type = ID_TYPE_UID;
715                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
716                 ret = NT_STATUS_OK;
717
718         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
719                 map->xid.id = rec_id;
720                 map->xid.type = ID_TYPE_GID;
721                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
722                 ret = NT_STATUS_OK;
723
724         } else { /* Unknown record type ! */
725                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
726                 ret = NT_STATUS_INTERNAL_DB_ERROR;
727                 goto done;
728         }
729
730         /* apply filters before returning result */
731         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
732                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
733                                 map->xid.id, dom->low_id, dom->high_id));
734                 ret = NT_STATUS_NONE_MAPPED;
735         }
736
737 done:
738         talloc_free(tmp_ctx);
739         return ret;
740 }
741
742 /*
743   lookup a set of unix ids. 
744 */
745 static NTSTATUS idmap_tdb2_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
746 {
747         NTSTATUS ret;
748         int i;
749
750         /* initialize the status to avoid suprise */
751         for (i = 0; ids[i]; i++) {
752                 ids[i]->status = ID_UNKNOWN;
753         }
754
755         for (i = 0; ids[i]; i++) {
756                 ret = idmap_tdb2_id_to_sid(dom, ids[i]);
757                 if ( ! NT_STATUS_IS_OK(ret)) {
758
759                         /* if it is just a failed mapping continue */
760                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
761
762                                 /* make sure it is marked as unmapped */
763                                 ids[i]->status = ID_UNMAPPED;
764                                 continue;
765                         }
766
767                         /* some fatal error occurred, return immediately */
768                         goto done;
769                 }
770
771                 /* all ok, id is mapped */
772                 ids[i]->status = ID_MAPPED;
773         }
774
775         ret = NT_STATUS_OK;
776
777 done:
778         return ret;
779 }
780
781 /*
782   lookup a set of sids. 
783 */
784
785 struct idmap_tdb2_sids_to_unixids_context {
786         struct idmap_domain *dom;
787         struct id_map **ids;
788         bool allocate_unmapped;
789 };
790
791 static NTSTATUS idmap_tdb2_sids_to_unixids_action(struct db_context *db,
792                                                   void *private_data)
793 {
794         struct idmap_tdb2_sids_to_unixids_context *state;
795         int i;
796         NTSTATUS ret = NT_STATUS_OK;
797
798         state = (struct idmap_tdb2_sids_to_unixids_context *)private_data;
799
800         DEBUG(10, ("idmap_tdb2_sids_to_unixids_action: "
801                    " domain: [%s], allocate: %s\n",
802                    state->dom->name,
803                    state->allocate_unmapped ? "yes" : "no"));
804
805         for (i = 0; state->ids[i]; i++) {
806                 if ((state->ids[i]->status == ID_UNKNOWN) ||
807                     /* retry if we could not map in previous run: */
808                     (state->ids[i]->status == ID_UNMAPPED))
809                 {
810                         NTSTATUS ret2;
811
812                         ret2 = idmap_tdb2_sid_to_id(state->dom, state->ids[i]);
813                         if (!NT_STATUS_IS_OK(ret2)) {
814
815                                 /* if it is just a failed mapping, continue */
816                                 if (NT_STATUS_EQUAL(ret2, NT_STATUS_NONE_MAPPED)) {
817
818                                         /* make sure it is marked as unmapped */
819                                         state->ids[i]->status = ID_UNMAPPED;
820                                         ret = STATUS_SOME_UNMAPPED;
821                                 } else {
822                                         /* some fatal error occurred, return immediately */
823                                         ret = ret2;
824                                         goto done;
825                                 }
826                         } else {
827                                 /* all ok, id is mapped */
828                                 state->ids[i]->status = ID_MAPPED;
829                         }
830                 }
831
832                 if ((state->ids[i]->status == ID_UNMAPPED) &&
833                     state->allocate_unmapped)
834                 {
835                         ret = idmap_tdb2_new_mapping(state->dom, state->ids[i]);
836                         if (!NT_STATUS_IS_OK(ret)) {
837                                 goto done;
838                         }
839                 }
840         }
841
842 done:
843         return ret;
844 }
845
846 static NTSTATUS idmap_tdb2_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
847 {
848         NTSTATUS ret;
849         int i;
850         struct idmap_tdb2_sids_to_unixids_context state;
851         struct idmap_tdb2_context *ctx;
852
853         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
854
855         /* initialize the status to avoid suprise */
856         for (i = 0; ids[i]; i++) {
857                 ids[i]->status = ID_UNKNOWN;
858         }
859
860         state.dom = dom;
861         state.ids = ids;
862         state.allocate_unmapped = false;
863
864         ret = idmap_tdb2_sids_to_unixids_action(ctx->db, &state);
865
866         if (NT_STATUS_EQUAL(ret, STATUS_SOME_UNMAPPED) && !dom->read_only) {
867                 state.allocate_unmapped = true;
868                 ret = dbwrap_trans_do(ctx->db,
869                                       idmap_tdb2_sids_to_unixids_action,
870                                       &state);
871         }
872
873         return ret;
874 }
875
876
877 static struct idmap_methods db_methods = {
878         .init            = idmap_tdb2_db_init,
879         .unixids_to_sids = idmap_tdb2_unixids_to_sids,
880         .sids_to_unixids = idmap_tdb2_sids_to_unixids,
881         .allocate_id     = idmap_tdb2_get_new_id
882 };
883
884 NTSTATUS idmap_tdb2_init(void)
885 {
886         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_methods);
887 }