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