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