s3:idmap_tdb2: remove special treatment of NULL sid from idmap_tdb2_sids_to_unixids
[metze/samba/wip.git] / source3 / winbindd / idmap_tdb2.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    idmap TDB2 backend, used for clustered Samba setups.
5
6    This uses dbwrap to access tdb files. The location can be set
7    using tdb:idmap2.tdb =" in smb.conf
8
9    Copyright (C) Andrew Tridgell 2007
10
11    This is heavily based upon idmap_tdb.c, which is:
12
13    Copyright (C) Tim Potter 2000
14    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
15    Copyright (C) Jeremy Allison 2006
16    Copyright (C) Simo Sorce 2003-2006
17
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         bool read_only;
321 };
322
323 /*
324   Initialise idmap database. 
325 */
326 static NTSTATUS idmap_tdb2_db_init(struct idmap_domain *dom,
327                                    const char *params)
328 {
329         NTSTATUS ret;
330         struct idmap_tdb2_context *ctx;
331         NTSTATUS status;
332
333         status = idmap_tdb2_open_db();
334         NT_STATUS_NOT_OK_RETURN(status);
335
336         ctx = talloc(dom, struct idmap_tdb2_context);
337         if ( ! ctx) {
338                 DEBUG(0, ("Out of memory!\n"));
339                 return NT_STATUS_NO_MEMORY;
340         }
341
342         if (strequal(dom->name, "*")) {
343                 uid_t low_uid = 0;
344                 uid_t high_uid = 0;
345                 gid_t low_gid = 0;
346                 gid_t high_gid = 0;
347
348                 ctx->filter_low_id = 0;
349                 ctx->filter_high_id = 0;
350
351                 if (lp_idmap_uid(&low_uid, &high_uid)) {
352                         ctx->filter_low_id = low_uid;
353                         ctx->filter_high_id = high_uid;
354                 } else {
355                         DEBUG(3, ("Warning: 'idmap uid' not set!\n"));
356                 }
357
358                 if (lp_idmap_gid(&low_gid, &high_gid)) {
359                         if ((low_gid != low_uid) || (high_gid != high_uid)) {
360                                 DEBUG(1, ("Warning: 'idmap uid' and 'idmap gid'"
361                                       " ranges do not agree -- building "
362                                       "intersection\n"));
363                                 ctx->filter_low_id = MAX(ctx->filter_low_id,
364                                                          low_gid);
365                                 ctx->filter_high_id = MIN(ctx->filter_high_id,
366                                                           high_gid);
367                         }
368                 } else {
369                         DEBUG(3, ("Warning: 'idmap gid' not set!\n"));
370                 }
371
372                 ctx->read_only = lp_idmap_read_only();
373         } else {
374                 char *config_option = NULL;
375                 const char *range;
376                 config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
377                 if ( ! config_option) {
378                         DEBUG(0, ("Out of memory!\n"));
379                         ret = NT_STATUS_NO_MEMORY;
380                         goto failed;
381                 }
382
383                 range = lp_parm_const_string(-1, config_option, "range", NULL);
384                 if (( ! range) ||
385                     (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2))
386                 {
387                         ctx->filter_low_id = 0;
388                         ctx->filter_high_id = 0;
389                 }
390
391                 ctx->read_only = lp_parm_bool(-1, config_option, "read only",
392                                               false);
393
394                 talloc_free(config_option);
395         }
396
397         if (ctx->filter_low_id > ctx->filter_high_id) {
398                 ctx->filter_low_id = 0;
399                 ctx->filter_high_id = 0;
400         }
401
402         dom->private_data = ctx;
403
404         return NT_STATUS_OK;
405
406 failed:
407         talloc_free(ctx);
408         return ret;
409 }
410
411 struct idmap_tdb2_set_mapping_context {
412         const char *ksidstr;
413         const char *kidstr;
414 };
415
416 static NTSTATUS idmap_tdb2_set_mapping_action(struct db_context *db,
417                                               void *private_data)
418 {
419         TDB_DATA data;
420         NTSTATUS ret;
421         struct idmap_tdb2_set_mapping_context *state;
422         TALLOC_CTX *tmp_ctx = talloc_stackframe();
423
424         state = (struct idmap_tdb2_set_mapping_context *)private_data;
425
426         DEBUG(10, ("Storing %s <-> %s map\n", state->ksidstr, state->kidstr));
427
428         /* check wheter sid mapping is already present in db */
429         data = dbwrap_fetch_bystring(db, tmp_ctx, state->ksidstr);
430         if (data.dptr) {
431                 ret = NT_STATUS_OBJECT_NAME_COLLISION;
432                 goto done;
433         }
434
435         ret = dbwrap_store_bystring(db, state->ksidstr,
436                                     string_term_tdb_data(state->kidstr),
437                                     TDB_INSERT);
438         if (!NT_STATUS_IS_OK(ret)) {
439                 DEBUG(0, ("Error storing SID -> ID: %s\n", nt_errstr(ret)));
440                 goto done;
441         }
442
443         ret = dbwrap_store_bystring(db, state->kidstr,
444                                     string_term_tdb_data(state->ksidstr),
445                                     TDB_INSERT);
446         if (!NT_STATUS_IS_OK(ret)) {
447                 DEBUG(0, ("Error storing ID -> SID: %s\n", nt_errstr(ret)));
448                 /* try to remove the previous stored SID -> ID map */
449                 dbwrap_delete_bystring(db, state->ksidstr);
450                 goto done;
451         }
452
453         DEBUG(10,("Stored %s <-> %s\n", state->ksidstr, state->kidstr));
454
455 done:
456         talloc_free(tmp_ctx);
457         return ret;
458 }
459
460
461 /*
462   run a script to perform a mapping
463
464   The script should the following command lines:
465
466       SIDTOID S-1-xxxx
467       IDTOSID UID xxxx
468       IDTOSID GID xxxx
469
470   and should return one of the following as a single line of text
471      UID:xxxx
472      GID:xxxx
473      SID:xxxx
474      ERR:xxxx
475  */
476 static NTSTATUS idmap_tdb2_script(struct idmap_tdb2_context *ctx, struct id_map *map,
477                                   const char *fmt, ...)
478 {
479         va_list ap;
480         char *cmd;
481         FILE *p;
482         char line[64];
483         unsigned long v;
484
485         cmd = talloc_asprintf(ctx, "%s ", idmap_tdb2_state.idmap_script);
486         NT_STATUS_HAVE_NO_MEMORY(cmd);  
487
488         va_start(ap, fmt);
489         cmd = talloc_vasprintf_append(cmd, fmt, ap);
490         va_end(ap);
491         NT_STATUS_HAVE_NO_MEMORY(cmd);
492
493         p = popen(cmd, "r");
494         talloc_free(cmd);
495         if (p == NULL) {
496                 return NT_STATUS_NONE_MAPPED;
497         }
498
499         if (fgets(line, sizeof(line)-1, p) == NULL) {
500                 pclose(p);
501                 return NT_STATUS_NONE_MAPPED;
502         }
503         pclose(p);
504
505         DEBUG(10,("idmap script gave: %s\n", line));
506
507         if (sscanf(line, "UID:%lu", &v) == 1) {
508                 map->xid.id   = v;
509                 map->xid.type = ID_TYPE_UID;
510         } else if (sscanf(line, "GID:%lu", &v) == 1) {
511                 map->xid.id   = v;
512                 map->xid.type = ID_TYPE_GID;            
513         } else if (strncmp(line, "SID:S-", 6) == 0) {
514                 if (!string_to_sid(map->sid, &line[4])) {
515                         DEBUG(0,("Bad SID in '%s' from idmap script %s\n",
516                                  line, idmap_tdb2_state.idmap_script));
517                         return NT_STATUS_NONE_MAPPED;                   
518                 }
519         } else {
520                 DEBUG(0,("Bad reply '%s' from idmap script %s\n",
521                          line, idmap_tdb2_state.idmap_script));
522                 return NT_STATUS_NONE_MAPPED;
523         }
524
525         return NT_STATUS_OK;
526 }
527
528
529
530 /*
531   Single id to sid lookup function. 
532 */
533 static NTSTATUS idmap_tdb2_id_to_sid(struct idmap_tdb2_context *ctx, struct id_map *map)
534 {
535         NTSTATUS ret;
536         TDB_DATA data;
537         char *keystr;
538         NTSTATUS status;
539
540         status = idmap_tdb2_open_db();
541         NT_STATUS_NOT_OK_RETURN(status);
542
543         if (!ctx || !map) {
544                 return NT_STATUS_INVALID_PARAMETER;
545         }
546
547         /* apply filters before checking */
548         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
549             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
550                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
551                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
552                 return NT_STATUS_NONE_MAPPED;
553         }
554
555         switch (map->xid.type) {
556
557         case ID_TYPE_UID:
558                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
559                 break;
560
561         case ID_TYPE_GID:
562                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
563                 break;
564
565         default:
566                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
567                 return NT_STATUS_INVALID_PARAMETER;
568         }
569
570         /* final SAFE_FREE safe */
571         data.dptr = NULL;
572
573         if (keystr == NULL) {
574                 DEBUG(0, ("Out of memory!\n"));
575                 ret = NT_STATUS_NO_MEMORY;
576                 goto done;
577         }
578
579         DEBUG(10,("Fetching record %s\n", keystr));
580
581         /* Check if the mapping exists */
582         data = dbwrap_fetch_bystring(idmap_tdb2, keystr, keystr);
583
584         if (!data.dptr) {
585                 char *sidstr;
586                 struct idmap_tdb2_set_mapping_context store_state;
587
588                 DEBUG(10,("Record %s not found\n", keystr));
589                 if (idmap_tdb2_state.idmap_script == NULL) {
590                         ret = NT_STATUS_NONE_MAPPED;
591                         goto done;
592                 }
593
594                 ret = idmap_tdb2_script(ctx, map, "IDTOSID %s", keystr);
595
596                 /* store it on shared storage */
597                 if (!NT_STATUS_IS_OK(ret)) {
598                         goto done;
599                 }
600
601                 sidstr = sid_string_talloc(keystr, map->sid);
602                 if (!sidstr) {
603                         ret = NT_STATUS_NO_MEMORY;
604                         goto done;
605                 }
606
607                 store_state.ksidstr = sidstr;
608                 store_state.kidstr = keystr;
609
610                 ret = dbwrap_trans_do(idmap_tdb2, idmap_tdb2_set_mapping_action,
611                                       &store_state);
612                 goto done;
613         }
614
615         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
616                 DEBUG(10,("INVALID SID (%s) in record %s\n",
617                         (const char *)data.dptr, keystr));
618                 ret = NT_STATUS_INTERNAL_DB_ERROR;
619                 goto done;
620         }
621
622         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
623         ret = NT_STATUS_OK;
624
625 done:
626         talloc_free(keystr);
627         return ret;
628 }
629
630
631 /*
632  Single sid to id lookup function. 
633 */
634 static NTSTATUS idmap_tdb2_sid_to_id(struct idmap_tdb2_context *ctx, struct id_map *map)
635 {
636         NTSTATUS ret;
637         TDB_DATA data;
638         char *keystr;
639         unsigned long rec_id = 0;
640         TALLOC_CTX *tmp_ctx = talloc_stackframe();
641
642         ret = idmap_tdb2_open_db();
643         NT_STATUS_NOT_OK_RETURN(ret);
644
645         keystr = sid_string_talloc(tmp_ctx, map->sid);
646         if (keystr == NULL) {
647                 DEBUG(0, ("Out of memory!\n"));
648                 ret = NT_STATUS_NO_MEMORY;
649                 goto done;
650         }
651
652         DEBUG(10,("Fetching record %s\n", keystr));
653
654         /* Check if sid is present in database */
655         data = dbwrap_fetch_bystring(idmap_tdb2, tmp_ctx, keystr);
656         if (!data.dptr) {
657                 char *idstr;
658                 struct idmap_tdb2_set_mapping_context store_state;
659
660                 DEBUG(10,(__location__ " Record %s not found\n", keystr));
661
662                 if (idmap_tdb2_state.idmap_script == NULL) {
663                         ret = NT_STATUS_NONE_MAPPED;
664                         goto done;
665                 }
666
667                 ret = idmap_tdb2_script(ctx, map, "SIDTOID %s", keystr);
668                 /* store it on shared storage */
669                 if (!NT_STATUS_IS_OK(ret)) {
670                         goto done;
671                 }
672
673                 /* apply filters before returning result */
674                 if ((ctx->filter_low_id
675                      && (map->xid.id < ctx->filter_low_id)) ||
676                     (ctx->filter_high_id
677                      && (map->xid.id > ctx->filter_high_id))) {
678                         DEBUG(5, ("Script returned id (%u) out of range "
679                                   "(%u - %u). Filtered!\n",
680                                   map->xid.id,
681                                   ctx->filter_low_id, ctx->filter_high_id));
682                         ret = NT_STATUS_NONE_MAPPED;
683                         goto done;
684                 }
685
686                 idstr = talloc_asprintf(tmp_ctx, "%cID %lu",
687                                         map->xid.type == ID_TYPE_UID?'U':'G',
688                                         (unsigned long)map->xid.id);
689                 if (idstr == NULL) {
690                         ret = NT_STATUS_NO_MEMORY;
691                         goto done;
692                 }
693
694                 store_state.ksidstr = keystr;
695                 store_state.kidstr = idstr;
696
697                 ret = dbwrap_trans_do(idmap_tdb2, idmap_tdb2_set_mapping_action,
698                                       &store_state);
699                 goto done;
700         }
701
702         /* What type of record is this ? */
703         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
704                 map->xid.id = rec_id;
705                 map->xid.type = ID_TYPE_UID;
706                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
707                 ret = NT_STATUS_OK;
708
709         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
710                 map->xid.id = rec_id;
711                 map->xid.type = ID_TYPE_GID;
712                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
713                 ret = NT_STATUS_OK;
714
715         } else { /* Unknown record type ! */
716                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
717                 ret = NT_STATUS_INTERNAL_DB_ERROR;
718                 goto done;
719         }
720
721         /* apply filters before returning result */
722         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
723             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
724                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
725                                 map->xid.id, ctx->filter_low_id, ctx->filter_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         struct idmap_tdb2_context *ctx;
740         NTSTATUS ret;
741         int i;
742
743         /* initialize the status to avoid suprise */
744         for (i = 0; ids[i]; i++) {
745                 ids[i]->status = ID_UNKNOWN;
746         }
747
748         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
749
750         for (i = 0; ids[i]; i++) {
751                 ret = idmap_tdb2_id_to_sid(ctx, ids[i]);
752                 if ( ! NT_STATUS_IS_OK(ret)) {
753
754                         /* if it is just a failed mapping continue */
755                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
756
757                                 /* make sure it is marked as unmapped */
758                                 ids[i]->status = ID_UNMAPPED;
759                                 continue;
760                         }
761
762                         /* some fatal error occurred, return immediately */
763                         goto done;
764                 }
765
766                 /* all ok, id is mapped */
767                 ids[i]->status = ID_MAPPED;
768         }
769
770         ret = NT_STATUS_OK;
771
772 done:
773         return ret;
774 }
775
776 /*
777   lookup a set of sids. 
778 */
779
780 struct idmap_tdb2_sids_to_unixids_context {
781         struct idmap_domain *dom;
782         struct id_map **ids;
783         bool allocate_unmapped;
784 };
785
786 static NTSTATUS idmap_tdb2_sids_to_unixids_action(struct db_context *db,
787                                                   void *private_data)
788 {
789         struct idmap_tdb2_sids_to_unixids_context *state;
790         int i;
791         struct idmap_tdb2_context *ctx;
792         NTSTATUS ret = NT_STATUS_OK;
793
794         state = (struct idmap_tdb2_sids_to_unixids_context *)private_data;
795
796         DEBUG(10, ("idmap_tdb2_sids_to_unixids_action: "
797                    " domain: [%s], allocate: %s\n",
798                    state->dom->name,
799                    state->allocate_unmapped ? "yes" : "no"));
800
801         ctx = talloc_get_type(state->dom->private_data,
802                               struct idmap_tdb2_context);
803
804
805         for (i = 0; state->ids[i]; i++) {
806                 if ((state->ids[i]->status == ID_UNKNOWN) ||
807                     /* retry if we could not map in previous run: */
808                     (state->ids[i]->status == ID_UNMAPPED))
809                 {
810                         NTSTATUS ret2;
811
812                         ret2 = idmap_tdb2_sid_to_id(ctx, state->ids[i]);
813                         if (!NT_STATUS_IS_OK(ret2)) {
814
815                                 /* if it is just a failed mapping, continue */
816                                 if (NT_STATUS_EQUAL(ret2, NT_STATUS_NONE_MAPPED)) {
817
818                                         /* make sure it is marked as unmapped */
819                                         state->ids[i]->status = ID_UNMAPPED;
820                                         ret = STATUS_SOME_UNMAPPED;
821                                 } else {
822                                         /* some fatal error occurred, return immediately */
823                                         ret = ret2;
824                                         goto done;
825                                 }
826                         } else {
827                                 /* all ok, id is mapped */
828                                 state->ids[i]->status = ID_MAPPED;
829                         }
830                 }
831
832                 if ((state->ids[i]->status == ID_UNMAPPED) &&
833                     state->allocate_unmapped)
834                 {
835                         ret = idmap_tdb2_new_mapping(state->dom, state->ids[i]);
836                         if (!NT_STATUS_IS_OK(ret)) {
837                                 goto done;
838                         }
839                 }
840         }
841
842 done:
843         return ret;
844 }
845
846 static NTSTATUS idmap_tdb2_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
847 {
848         NTSTATUS ret;
849         int i;
850         struct idmap_tdb2_sids_to_unixids_context state;
851         struct idmap_tdb2_context *ctx;
852
853         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
854
855         /* initialize the status to avoid suprise */
856         for (i = 0; ids[i]; i++) {
857                 ids[i]->status = ID_UNKNOWN;
858         }
859
860         state.dom = dom;
861         state.ids = ids;
862         state.allocate_unmapped = false;
863
864         ret = idmap_tdb2_sids_to_unixids_action(idmap_tdb2, &state);
865
866         if (NT_STATUS_EQUAL(ret, STATUS_SOME_UNMAPPED) && !ctx->read_only) {
867                 state.allocate_unmapped = true;
868                 ret = dbwrap_trans_do(idmap_tdb2,
869                                       idmap_tdb2_sids_to_unixids_action,
870                                       &state);
871         }
872
873         return ret;
874 }
875
876
877 /*
878   set a mapping. 
879 */
880
881 static NTSTATUS idmap_tdb2_set_mapping(struct idmap_domain *dom, const struct id_map *map)
882 {
883         struct idmap_tdb2_context *ctx;
884         NTSTATUS ret;
885         char *ksidstr, *kidstr;
886         struct idmap_tdb2_set_mapping_context state;
887
888         if (!map || !map->sid) {
889                 return NT_STATUS_INVALID_PARAMETER;
890         }
891
892         ksidstr = kidstr = NULL;
893
894         /* TODO: should we filter a set_mapping using low/high filters ? */
895
896         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
897
898         switch (map->xid.type) {
899
900         case ID_TYPE_UID:
901                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
902                 break;
903
904         case ID_TYPE_GID:
905                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
906                 break;
907
908         default:
909                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
910                 return NT_STATUS_INVALID_PARAMETER;
911         }
912
913         if (kidstr == NULL) {
914                 DEBUG(0, ("ERROR: Out of memory!\n"));
915                 ret = NT_STATUS_NO_MEMORY;
916                 goto done;
917         }
918
919         ksidstr = sid_string_talloc(ctx, map->sid);
920         if (ksidstr == NULL) {
921                 DEBUG(0, ("Out of memory!\n"));
922                 ret = NT_STATUS_NO_MEMORY;
923                 goto done;
924         }
925
926         state.ksidstr = ksidstr;
927         state.kidstr = kidstr;
928
929         ret = dbwrap_trans_do(idmap_tdb2, idmap_tdb2_set_mapping_action,
930                               &state);
931
932 done:
933         talloc_free(ksidstr);
934         talloc_free(kidstr);
935         return ret;
936 }
937
938 /**
939  * Create a new mapping for an unmapped SID, also allocating a new ID.
940  * This should be run inside a transaction.
941  *
942  * TODO:
943 *  Properly integrate this with multi domain idmap config:
944  * Currently, the allocator is default-config only.
945  */
946 static NTSTATUS idmap_tdb2_new_mapping(struct idmap_domain *dom, struct id_map *map)
947 {
948         NTSTATUS ret;
949         char *sidstr;
950         TDB_DATA data;
951         TALLOC_CTX *mem_ctx = talloc_stackframe();
952
953         if (map == NULL) {
954                 ret = NT_STATUS_INVALID_PARAMETER;
955                 goto done;
956         }
957
958         if ((map->xid.type != ID_TYPE_UID) && (map->xid.type != ID_TYPE_GID)) {
959                 ret = NT_STATUS_INVALID_PARAMETER;
960                 goto done;
961         }
962
963         if (map->sid == NULL) {
964                 ret = NT_STATUS_INVALID_PARAMETER;
965                 goto done;
966         }
967
968         /* check wheter the SID is already mapped in the db */
969         sidstr = sid_string_talloc(mem_ctx, map->sid);
970         if (sidstr == NULL) {
971                 DEBUG(0, ("Out of memory!\n"));
972                 ret = NT_STATUS_NO_MEMORY;
973                 goto done;
974         }
975
976         data = dbwrap_fetch_bystring(idmap_tdb2, mem_ctx, sidstr);
977         if (data.dptr) {
978                 ret = NT_STATUS_OBJECT_NAME_COLLISION;
979                 goto done;
980         }
981
982         /* unmapped - get a new id */
983         ret = idmap_tdb2_get_new_id(dom, &map->xid);
984         if (!NT_STATUS_IS_OK(ret)) {
985                 DEBUG(3, ("Could not allocate id: %s\n", nt_errstr(ret)));
986                 goto done;
987         }
988
989         DEBUG(10, ("Setting mapping: %s <-> %s %lu\n",
990                    sid_string_dbg(map->sid),
991                    (map->xid.type == ID_TYPE_UID) ? "UID" : "GID",
992                    (unsigned long)map->xid.id));
993
994         map->status = ID_MAPPED;
995
996         /* store the mapping */
997         ret = idmap_tdb2_set_mapping(dom, map);
998         if (!NT_STATUS_IS_OK(ret)) {
999                 DEBUG(3, ("Could not store the new mapping: %s\n",
1000                           nt_errstr(ret)));
1001         }
1002
1003 done:
1004         talloc_free(mem_ctx);
1005         return ret;
1006 }
1007
1008 /*
1009   Close the idmap tdb instance
1010 */
1011 static NTSTATUS idmap_tdb2_close(struct idmap_domain *dom)
1012 {
1013         /* don't do anything */
1014         return NT_STATUS_OK;
1015 }
1016
1017 static struct idmap_methods db_methods = {
1018         .init            = idmap_tdb2_db_init,
1019         .unixids_to_sids = idmap_tdb2_unixids_to_sids,
1020         .sids_to_unixids = idmap_tdb2_sids_to_unixids,
1021         .allocate_id     = idmap_tdb2_get_new_id,
1022         .close_fn        = idmap_tdb2_close
1023 };
1024
1025 NTSTATUS idmap_tdb2_init(void)
1026 {
1027         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_methods);
1028 }