s3:idmap_tdb2: use range from idmap_domain in idmap_tdb2_allocate_id
[sfrench/samba-autobuild/.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_allocate_id_context state;
245
246         status = idmap_tdb2_open_db();
247         NT_STATUS_NOT_OK_RETURN(status);
248
249         /* Get current high water mark */
250         switch (xid->type) {
251
252         case ID_TYPE_UID:
253                 hwmkey = HWM_USER;
254                 hwmtype = "UID";
255                 break;
256
257         case ID_TYPE_GID:
258                 hwmkey = HWM_GROUP;
259                 hwmtype = "GID";
260                 break;
261
262         default:
263                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
264                 return NT_STATUS_INVALID_PARAMETER;
265         }
266
267         high_hwm = dom->high_id;
268
269         state.hwm = hwm;
270         state.high_hwm = high_hwm;
271         state.hwmtype = hwmtype;
272         state.hwmkey = hwmkey;
273
274         status = dbwrap_trans_do(idmap_tdb2, idmap_tdb2_allocate_id_action,
275                                  &state);
276
277         if (NT_STATUS_IS_OK(status)) {
278                 xid->id = state.hwm;
279                 DEBUG(10,("New %s = %d\n", hwmtype, state.hwm));
280         } else {
281                 DEBUG(1, ("Error allocating a new %s\n", hwmtype));
282         }
283
284         return status;
285 }
286
287 /**
288  * Allocate a new unix-ID.
289  * For now this is for the default idmap domain only.
290  * Should be extended later on.
291  */
292 static NTSTATUS idmap_tdb2_get_new_id(struct idmap_domain *dom,
293                                       struct unixid *id)
294 {
295         NTSTATUS ret;
296
297         if (!strequal(dom->name, "*")) {
298                 DEBUG(3, ("idmap_tdb2_get_new_id: "
299                           "Refusing creation of mapping for domain'%s'. "
300                           "Currently only supported for the default "
301                           "domain \"*\".\n",
302                            dom->name));
303                 return NT_STATUS_NOT_IMPLEMENTED;
304         }
305
306         ret = idmap_tdb2_allocate_id(dom, id);
307
308         return ret;
309 }
310
311 /*
312   IDMAP MAPPING TDB BACKEND
313 */
314
315 /*
316   Initialise idmap database. 
317 */
318 static NTSTATUS idmap_tdb2_db_init(struct idmap_domain *dom,
319                                    const char *params)
320 {
321         NTSTATUS ret;
322         struct idmap_tdb2_context *ctx;
323         NTSTATUS status;
324
325         ctx = talloc(dom, struct idmap_tdb2_context);
326         if ( ! ctx) {
327                 DEBUG(0, ("Out of memory!\n"));
328                 return NT_STATUS_NO_MEMORY;
329         }
330
331         if (strequal(dom->name, "*")) {
332                 uid_t low_uid = 0;
333                 uid_t high_uid = 0;
334                 gid_t low_gid = 0;
335                 gid_t high_gid = 0;
336
337                 ctx->filter_low_id = 0;
338                 ctx->filter_high_id = 0;
339
340                 if (lp_idmap_uid(&low_uid, &high_uid)) {
341                         ctx->filter_low_id = low_uid;
342                         ctx->filter_high_id = high_uid;
343                 } else {
344                         DEBUG(3, ("Warning: 'idmap uid' not set!\n"));
345                 }
346
347                 if (lp_idmap_gid(&low_gid, &high_gid)) {
348                         if ((low_gid != low_uid) || (high_gid != high_uid)) {
349                                 DEBUG(1, ("Warning: 'idmap uid' and 'idmap gid'"
350                                       " ranges do not agree -- building "
351                                       "intersection\n"));
352                                 ctx->filter_low_id = MAX(ctx->filter_low_id,
353                                                          low_gid);
354                                 ctx->filter_high_id = MIN(ctx->filter_high_id,
355                                                           high_gid);
356                         }
357                 } else {
358                         DEBUG(3, ("Warning: 'idmap gid' not set!\n"));
359                 }
360
361                 ctx->script = lp_parm_const_string(-1, "idmap", "script", NULL);
362                 if (ctx->script) {
363                         DEBUG(1, ("using idmap script '%s'\n", ctx->script));
364                 }
365         } else {
366                 char *config_option = NULL;
367                 const char *range;
368                 config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
369                 if ( ! config_option) {
370                         DEBUG(0, ("Out of memory!\n"));
371                         ret = NT_STATUS_NO_MEMORY;
372                         goto failed;
373                 }
374
375                 range = lp_parm_const_string(-1, config_option, "range", NULL);
376                 if (( ! range) ||
377                     (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2))
378                 {
379                         ctx->filter_low_id = 0;
380                         ctx->filter_high_id = 0;
381                 }
382
383                 ctx->script = lp_parm_const_string(-1, config_option, "script", NULL);
384                 if (ctx->script) {
385                         DEBUG(1, ("using idmap script '%s'\n", ctx->script));
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         ret = idmap_tdb2_open_db();
397         if (!NT_STATUS_IS_OK(ret)) {
398                 goto failed;
399         }
400
401         dom->private_data = ctx;
402
403         return NT_STATUS_OK;
404
405 failed:
406         talloc_free(ctx);
407         return ret;
408 }
409
410 struct idmap_tdb2_set_mapping_context {
411         const char *ksidstr;
412         const char *kidstr;
413 };
414
415 static NTSTATUS idmap_tdb2_set_mapping_action(struct db_context *db,
416                                               void *private_data)
417 {
418         TDB_DATA data;
419         NTSTATUS ret;
420         struct idmap_tdb2_set_mapping_context *state;
421         TALLOC_CTX *tmp_ctx = talloc_stackframe();
422
423         state = (struct idmap_tdb2_set_mapping_context *)private_data;
424
425         DEBUG(10, ("Storing %s <-> %s map\n", state->ksidstr, state->kidstr));
426
427         /* check wheter sid mapping is already present in db */
428         data = dbwrap_fetch_bystring(db, tmp_ctx, state->ksidstr);
429         if (data.dptr) {
430                 ret = NT_STATUS_OBJECT_NAME_COLLISION;
431                 goto done;
432         }
433
434         ret = dbwrap_store_bystring(db, state->ksidstr,
435                                     string_term_tdb_data(state->kidstr),
436                                     TDB_INSERT);
437         if (!NT_STATUS_IS_OK(ret)) {
438                 DEBUG(0, ("Error storing SID -> ID: %s\n", nt_errstr(ret)));
439                 goto done;
440         }
441
442         ret = dbwrap_store_bystring(db, state->kidstr,
443                                     string_term_tdb_data(state->ksidstr),
444                                     TDB_INSERT);
445         if (!NT_STATUS_IS_OK(ret)) {
446                 DEBUG(0, ("Error storing ID -> SID: %s\n", nt_errstr(ret)));
447                 /* try to remove the previous stored SID -> ID map */
448                 dbwrap_delete_bystring(db, state->ksidstr);
449                 goto done;
450         }
451
452         DEBUG(10,("Stored %s <-> %s\n", state->ksidstr, state->kidstr));
453
454 done:
455         talloc_free(tmp_ctx);
456         return ret;
457 }
458
459
460 /*
461   run a script to perform a mapping
462
463   The script should the following command lines:
464
465       SIDTOID S-1-xxxx
466       IDTOSID UID xxxx
467       IDTOSID GID xxxx
468
469   and should return one of the following as a single line of text
470      UID:xxxx
471      GID:xxxx
472      SID:xxxx
473      ERR:xxxx
474  */
475 static NTSTATUS idmap_tdb2_script(struct idmap_tdb2_context *ctx, struct id_map *map,
476                                   const char *fmt, ...)
477 {
478         va_list ap;
479         char *cmd;
480         FILE *p;
481         char line[64];
482         unsigned long v;
483
484         cmd = talloc_asprintf(ctx, "%s ", ctx->script);
485         NT_STATUS_HAVE_NO_MEMORY(cmd);  
486
487         va_start(ap, fmt);
488         cmd = talloc_vasprintf_append(cmd, fmt, ap);
489         va_end(ap);
490         NT_STATUS_HAVE_NO_MEMORY(cmd);
491
492         p = popen(cmd, "r");
493         talloc_free(cmd);
494         if (p == NULL) {
495                 return NT_STATUS_NONE_MAPPED;
496         }
497
498         if (fgets(line, sizeof(line)-1, p) == NULL) {
499                 pclose(p);
500                 return NT_STATUS_NONE_MAPPED;
501         }
502         pclose(p);
503
504         DEBUG(10,("idmap script gave: %s\n", line));
505
506         if (sscanf(line, "UID:%lu", &v) == 1) {
507                 map->xid.id   = v;
508                 map->xid.type = ID_TYPE_UID;
509         } else if (sscanf(line, "GID:%lu", &v) == 1) {
510                 map->xid.id   = v;
511                 map->xid.type = ID_TYPE_GID;            
512         } else if (strncmp(line, "SID:S-", 6) == 0) {
513                 if (!string_to_sid(map->sid, &line[4])) {
514                         DEBUG(0,("Bad SID in '%s' from idmap script %s\n",
515                                  line, ctx->script));
516                         return NT_STATUS_NONE_MAPPED;                   
517                 }
518         } else {
519                 DEBUG(0,("Bad reply '%s' from idmap script %s\n",
520                          line, ctx->script));
521                 return NT_STATUS_NONE_MAPPED;
522         }
523
524         return NT_STATUS_OK;
525 }
526
527
528
529 /*
530   Single id to sid lookup function. 
531 */
532 static NTSTATUS idmap_tdb2_id_to_sid(struct idmap_domain *dom, struct id_map *map)
533 {
534         NTSTATUS ret;
535         TDB_DATA data;
536         char *keystr;
537         NTSTATUS status;
538         struct idmap_tdb2_context *ctx;
539
540
541         status = idmap_tdb2_open_db();
542         NT_STATUS_NOT_OK_RETURN(status);
543
544         if (!dom || !map) {
545                 return NT_STATUS_INVALID_PARAMETER;
546         }
547
548         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
549
550         /* apply filters before checking */
551         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
552                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
553                                 map->xid.id, dom->low_id, dom->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_domain *dom, struct id_map *map)
637 {
638         NTSTATUS ret;
639         TDB_DATA data;
640         char *keystr;
641         unsigned long rec_id = 0;
642         struct idmap_tdb2_context *ctx;
643         TALLOC_CTX *tmp_ctx = talloc_stackframe();
644
645         ret = idmap_tdb2_open_db();
646         NT_STATUS_NOT_OK_RETURN(ret);
647
648         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
649
650         keystr = sid_string_talloc(tmp_ctx, map->sid);
651         if (keystr == NULL) {
652                 DEBUG(0, ("Out of memory!\n"));
653                 ret = NT_STATUS_NO_MEMORY;
654                 goto done;
655         }
656
657         DEBUG(10,("Fetching record %s\n", keystr));
658
659         /* Check if sid is present in database */
660         data = dbwrap_fetch_bystring(idmap_tdb2, tmp_ctx, keystr);
661         if (!data.dptr) {
662                 char *idstr;
663                 struct idmap_tdb2_set_mapping_context store_state;
664
665                 DEBUG(10,(__location__ " Record %s not found\n", keystr));
666
667                 if (ctx->script == NULL) {
668                         ret = NT_STATUS_NONE_MAPPED;
669                         goto done;
670                 }
671
672                 ret = idmap_tdb2_script(ctx, map, "SIDTOID %s", keystr);
673                 /* store it on shared storage */
674                 if (!NT_STATUS_IS_OK(ret)) {
675                         goto done;
676                 }
677
678                 /* apply filters before returning result */
679                 if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
680                         DEBUG(5, ("Script returned id (%u) out of range "
681                                   "(%u - %u). Filtered!\n",
682                                   map->xid.id, dom->low_id, dom->high_id));
683                         ret = NT_STATUS_NONE_MAPPED;
684                         goto done;
685                 }
686
687                 idstr = talloc_asprintf(tmp_ctx, "%cID %lu",
688                                         map->xid.type == ID_TYPE_UID?'U':'G',
689                                         (unsigned long)map->xid.id);
690                 if (idstr == NULL) {
691                         ret = NT_STATUS_NO_MEMORY;
692                         goto done;
693                 }
694
695                 store_state.ksidstr = keystr;
696                 store_state.kidstr = idstr;
697
698                 ret = dbwrap_trans_do(idmap_tdb2, idmap_tdb2_set_mapping_action,
699                                       &store_state);
700                 goto done;
701         }
702
703         /* What type of record is this ? */
704         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
705                 map->xid.id = rec_id;
706                 map->xid.type = ID_TYPE_UID;
707                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
708                 ret = NT_STATUS_OK;
709
710         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
711                 map->xid.id = rec_id;
712                 map->xid.type = ID_TYPE_GID;
713                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
714                 ret = NT_STATUS_OK;
715
716         } else { /* Unknown record type ! */
717                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
718                 ret = NT_STATUS_INTERNAL_DB_ERROR;
719                 goto done;
720         }
721
722         /* apply filters before returning result */
723         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
724                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
725                                 map->xid.id, dom->low_id, dom->high_id));
726                 ret = NT_STATUS_NONE_MAPPED;
727         }
728
729 done:
730         talloc_free(tmp_ctx);
731         return ret;
732 }
733
734 /*
735   lookup a set of unix ids. 
736 */
737 static NTSTATUS idmap_tdb2_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
738 {
739         NTSTATUS ret;
740         int i;
741
742         /* initialize the status to avoid suprise */
743         for (i = 0; ids[i]; i++) {
744                 ids[i]->status = ID_UNKNOWN;
745         }
746
747         for (i = 0; ids[i]; i++) {
748                 ret = idmap_tdb2_id_to_sid(dom, ids[i]);
749                 if ( ! NT_STATUS_IS_OK(ret)) {
750
751                         /* if it is just a failed mapping continue */
752                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
753
754                                 /* make sure it is marked as unmapped */
755                                 ids[i]->status = ID_UNMAPPED;
756                                 continue;
757                         }
758
759                         /* some fatal error occurred, return immediately */
760                         goto done;
761                 }
762
763                 /* all ok, id is mapped */
764                 ids[i]->status = ID_MAPPED;
765         }
766
767         ret = NT_STATUS_OK;
768
769 done:
770         return ret;
771 }
772
773 /*
774   lookup a set of sids. 
775 */
776
777 struct idmap_tdb2_sids_to_unixids_context {
778         struct idmap_domain *dom;
779         struct id_map **ids;
780         bool allocate_unmapped;
781 };
782
783 static NTSTATUS idmap_tdb2_sids_to_unixids_action(struct db_context *db,
784                                                   void *private_data)
785 {
786         struct idmap_tdb2_sids_to_unixids_context *state;
787         int i;
788         NTSTATUS ret = NT_STATUS_OK;
789
790         state = (struct idmap_tdb2_sids_to_unixids_context *)private_data;
791
792         DEBUG(10, ("idmap_tdb2_sids_to_unixids_action: "
793                    " domain: [%s], allocate: %s\n",
794                    state->dom->name,
795                    state->allocate_unmapped ? "yes" : "no"));
796
797         for (i = 0; state->ids[i]; i++) {
798                 if ((state->ids[i]->status == ID_UNKNOWN) ||
799                     /* retry if we could not map in previous run: */
800                     (state->ids[i]->status == ID_UNMAPPED))
801                 {
802                         NTSTATUS ret2;
803
804                         ret2 = idmap_tdb2_sid_to_id(state->dom, state->ids[i]);
805                         if (!NT_STATUS_IS_OK(ret2)) {
806
807                                 /* if it is just a failed mapping, continue */
808                                 if (NT_STATUS_EQUAL(ret2, NT_STATUS_NONE_MAPPED)) {
809
810                                         /* make sure it is marked as unmapped */
811                                         state->ids[i]->status = ID_UNMAPPED;
812                                         ret = STATUS_SOME_UNMAPPED;
813                                 } else {
814                                         /* some fatal error occurred, return immediately */
815                                         ret = ret2;
816                                         goto done;
817                                 }
818                         } else {
819                                 /* all ok, id is mapped */
820                                 state->ids[i]->status = ID_MAPPED;
821                         }
822                 }
823
824                 if ((state->ids[i]->status == ID_UNMAPPED) &&
825                     state->allocate_unmapped)
826                 {
827                         ret = idmap_tdb2_new_mapping(state->dom, state->ids[i]);
828                         if (!NT_STATUS_IS_OK(ret)) {
829                                 goto done;
830                         }
831                 }
832         }
833
834 done:
835         return ret;
836 }
837
838 static NTSTATUS idmap_tdb2_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
839 {
840         NTSTATUS ret;
841         int i;
842         struct idmap_tdb2_sids_to_unixids_context state;
843
844         /* initialize the status to avoid suprise */
845         for (i = 0; ids[i]; i++) {
846                 ids[i]->status = ID_UNKNOWN;
847         }
848
849         state.dom = dom;
850         state.ids = ids;
851         state.allocate_unmapped = false;
852
853         ret = idmap_tdb2_sids_to_unixids_action(idmap_tdb2, &state);
854
855         if (NT_STATUS_EQUAL(ret, STATUS_SOME_UNMAPPED)) {
856                 state.allocate_unmapped = true;
857                 ret = dbwrap_trans_do(idmap_tdb2,
858                                       idmap_tdb2_sids_to_unixids_action,
859                                       &state);
860         }
861
862         return ret;
863 }
864
865
866 /*
867   set a mapping. 
868 */
869
870 static NTSTATUS idmap_tdb2_set_mapping(struct idmap_domain *dom, const struct id_map *map)
871 {
872         struct idmap_tdb2_context *ctx;
873         NTSTATUS ret;
874         char *ksidstr, *kidstr;
875         struct idmap_tdb2_set_mapping_context state;
876
877         if (!map || !map->sid) {
878                 return NT_STATUS_INVALID_PARAMETER;
879         }
880
881         ksidstr = kidstr = NULL;
882
883         /* TODO: should we filter a set_mapping using low/high filters ? */
884
885         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
886
887         switch (map->xid.type) {
888
889         case ID_TYPE_UID:
890                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
891                 break;
892
893         case ID_TYPE_GID:
894                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
895                 break;
896
897         default:
898                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
899                 return NT_STATUS_INVALID_PARAMETER;
900         }
901
902         if (kidstr == NULL) {
903                 DEBUG(0, ("ERROR: Out of memory!\n"));
904                 ret = NT_STATUS_NO_MEMORY;
905                 goto done;
906         }
907
908         ksidstr = sid_string_talloc(ctx, map->sid);
909         if (ksidstr == NULL) {
910                 DEBUG(0, ("Out of memory!\n"));
911                 ret = NT_STATUS_NO_MEMORY;
912                 goto done;
913         }
914
915         state.ksidstr = ksidstr;
916         state.kidstr = kidstr;
917
918         ret = dbwrap_trans_do(idmap_tdb2, idmap_tdb2_set_mapping_action,
919                               &state);
920
921 done:
922         talloc_free(ksidstr);
923         talloc_free(kidstr);
924         return ret;
925 }
926
927 /**
928  * Create a new mapping for an unmapped SID, also allocating a new ID.
929  * This should be run inside a transaction.
930  *
931  * TODO:
932 *  Properly integrate this with multi domain idmap config:
933  * Currently, the allocator is default-config only.
934  */
935 static NTSTATUS idmap_tdb2_new_mapping(struct idmap_domain *dom, struct id_map *map)
936 {
937         NTSTATUS ret;
938         char *sidstr;
939         TDB_DATA data;
940         TALLOC_CTX *mem_ctx = talloc_stackframe();
941
942         if (map == NULL) {
943                 ret = NT_STATUS_INVALID_PARAMETER;
944                 goto done;
945         }
946
947         if ((map->xid.type != ID_TYPE_UID) && (map->xid.type != ID_TYPE_GID)) {
948                 ret = NT_STATUS_INVALID_PARAMETER;
949                 goto done;
950         }
951
952         if (map->sid == NULL) {
953                 ret = NT_STATUS_INVALID_PARAMETER;
954                 goto done;
955         }
956
957         /* check wheter the SID is already mapped in the db */
958         sidstr = sid_string_talloc(mem_ctx, map->sid);
959         if (sidstr == NULL) {
960                 DEBUG(0, ("Out of memory!\n"));
961                 ret = NT_STATUS_NO_MEMORY;
962                 goto done;
963         }
964
965         data = dbwrap_fetch_bystring(idmap_tdb2, mem_ctx, sidstr);
966         if (data.dptr) {
967                 ret = NT_STATUS_OBJECT_NAME_COLLISION;
968                 goto done;
969         }
970
971         /* unmapped - get a new id */
972         ret = idmap_tdb2_get_new_id(dom, &map->xid);
973         if (!NT_STATUS_IS_OK(ret)) {
974                 DEBUG(3, ("Could not allocate id: %s\n", nt_errstr(ret)));
975                 goto done;
976         }
977
978         DEBUG(10, ("Setting mapping: %s <-> %s %lu\n",
979                    sid_string_dbg(map->sid),
980                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
981                    (unsigned long)map->xid.id));
982
983         map->status = ID_MAPPED;
984
985         /* store the mapping */
986         ret = idmap_tdb2_set_mapping(dom, map);
987         if (!NT_STATUS_IS_OK(ret)) {
988                 DEBUG(3, ("Could not store the new mapping: %s\n",
989                           nt_errstr(ret)));
990         }
991
992 done:
993         talloc_free(mem_ctx);
994         return ret;
995 }
996
997 /*
998   Close the idmap tdb instance
999 */
1000 static NTSTATUS idmap_tdb2_close(struct idmap_domain *dom)
1001 {
1002         /* don't do anything */
1003         return NT_STATUS_OK;
1004 }
1005
1006 static struct idmap_methods db_methods = {
1007         .init            = idmap_tdb2_db_init,
1008         .unixids_to_sids = idmap_tdb2_unixids_to_sids,
1009         .sids_to_unixids = idmap_tdb2_sids_to_unixids,
1010         .allocate_id     = idmap_tdb2_get_new_id,
1011         .close_fn        = idmap_tdb2_close
1012 };
1013
1014 NTSTATUS idmap_tdb2_init(void)
1015 {
1016         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_methods);
1017 }