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