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