Merge Samba3 and Samba4 together
[amitay/samba.git] / source3 / winbindd / idmap_tdb2.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    idmap TDB2 backend, used for clustered Samba setups.
5
6    This uses dbwrap to access tdb files. The location can be set
7    using tdb:idmap2.tdb =" in smb.conf
8
9    Copyright (C) Andrew Tridgell 2007
10
11    This is heavily based upon idmap_tdb.c, which is:
12
13    Copyright (C) Tim Potter 2000
14    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
15    Copyright (C) Jeremy Allison 2006
16    Copyright (C) Simo Sorce 2003-2006
17    
18    This program is free software; you can redistribute it and/or modify
19    it under the terms of the GNU General Public License as published by
20    the Free Software Foundation; either version 2 of the License, or
21    (at your option) any later version.
22    
23    This program is distributed in the hope that it will be useful,
24    but WITHOUT ANY WARRANTY; without even the implied warranty of
25    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26    GNU General Public License for more details.
27    
28    You should have received a copy of the GNU General Public License
29    along with this program; if not, write to the Free Software
30    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 */
32
33 #include "includes.h"
34 #include "winbindd.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_IDMAP
38
39 /* 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
52 /* handle to the permanent tdb */
53 static struct db_context *idmap_tdb2;
54
55 static NTSTATUS idmap_tdb2_alloc_load(void);
56
57 /*
58   open the permanent tdb
59  */
60 static NTSTATUS idmap_tdb2_open_db(void)
61 {
62         char *db_path;
63         
64         if (idmap_tdb2) {
65                 /* its already open */
66                 return NT_STATUS_OK;
67         }
68
69         db_path = lp_parm_talloc_string(-1, "tdb", "idmap2.tdb", NULL);
70         if (db_path == NULL) {
71                 /* fall back to the private directory, which, despite
72                    its name, is usually on shared storage */
73                 db_path = talloc_asprintf(NULL, "%s/idmap2.tdb", lp_private_dir());
74         }
75         NT_STATUS_HAVE_NO_MEMORY(db_path);
76
77         /* Open idmap repository */
78         idmap_tdb2 = db_open(NULL, db_path, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644);
79         TALLOC_FREE(db_path);
80
81         if (idmap_tdb2 == NULL) {
82                 DEBUG(0, ("Unable to open idmap_tdb2 database '%s'\n",
83                           db_path));
84                 return NT_STATUS_UNSUCCESSFUL;
85         }
86
87         /* load the ranges and high/low water marks */
88         return idmap_tdb2_alloc_load();
89 }
90
91
92 /*
93   load the idmap allocation ranges and high/low water marks
94 */
95 static NTSTATUS idmap_tdb2_alloc_load(void)
96 {
97         const char *range;
98         uid_t low_uid = 0;
99         uid_t high_uid = 0;
100         gid_t low_gid = 0;
101         gid_t high_gid = 0;
102         uint32 low_id, high_id;
103
104         /* see if a idmap script is configured */
105         idmap_tdb2_state.idmap_script = lp_parm_const_string(-1, "idmap",
106                                                              "script", NULL);
107
108         if (idmap_tdb2_state.idmap_script) {
109                 DEBUG(1, ("using idmap script '%s'\n",
110                           idmap_tdb2_state.idmap_script));
111         }
112
113         /* load ranges */
114
115         /* Create high water marks for group and user id */
116         if (!lp_idmap_uid(&low_uid, &high_uid)
117             || !lp_idmap_gid(&low_gid, &high_gid)) {
118                 DEBUG(1, ("idmap uid or idmap gid missing\n"));
119                 return NT_STATUS_UNSUCCESSFUL;
120         }
121
122         idmap_tdb2_state.low_uid = low_uid;
123         idmap_tdb2_state.high_uid = high_uid;
124         idmap_tdb2_state.low_gid = low_gid;
125         idmap_tdb2_state.high_gid = high_gid;
126
127         if (idmap_tdb2_state.high_uid <= idmap_tdb2_state.low_uid) {
128                 DEBUG(1, ("idmap uid range missing or invalid\n"));
129                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
130                 return NT_STATUS_UNSUCCESSFUL;
131         }
132
133         if (((low_id = dbwrap_fetch_int32(idmap_tdb2,
134                                           HWM_USER)) == -1) ||
135             (low_id < idmap_tdb2_state.low_uid)) {
136                 if (!NT_STATUS_IS_OK(dbwrap_trans_store_int32(
137                                              idmap_tdb2, HWM_USER,
138                                              idmap_tdb2_state.low_uid))) {
139                         DEBUG(0, ("Unable to initialise user hwm in idmap "
140                                   "database\n"));
141                         return NT_STATUS_INTERNAL_DB_ERROR;
142                 }
143         }
144
145         if (idmap_tdb2_state.high_gid <= idmap_tdb2_state.low_gid) {
146                 DEBUG(1, ("idmap gid range missing or invalid\n"));
147                 DEBUGADD(1, ("idmap will be unable to map foreign SIDs\n"));
148                 return NT_STATUS_UNSUCCESSFUL;
149         }
150
151         if (((low_id = dbwrap_fetch_int32(idmap_tdb2,
152                                           HWM_GROUP)) == -1) ||
153             (low_id < idmap_tdb2_state.low_gid)) {
154                 if (!NT_STATUS_IS_OK(dbwrap_trans_store_int32(
155                                              idmap_tdb2, HWM_GROUP,
156                                              idmap_tdb2_state.low_gid))) {
157                         DEBUG(0, ("Unable to initialise group hwm in idmap "
158                                   "database\n"));
159                         return NT_STATUS_INTERNAL_DB_ERROR;
160                 }
161         }
162
163         return NT_STATUS_OK;
164 }
165
166
167 /*
168   Initialise idmap alloc database. 
169 */
170 static NTSTATUS idmap_tdb2_alloc_init(const char *params)
171 {
172         /* nothing to do - we want to avoid opening the permanent
173            database if possible. Instead we load the params when we
174            first need it. */
175         return NT_STATUS_OK;
176 }
177
178
179 /*
180   Allocate a new id. 
181 */
182 static NTSTATUS idmap_tdb2_allocate_id(struct unixid *xid)
183 {
184         bool ret;
185         const char *hwmkey;
186         const char *hwmtype;
187         uint32_t high_hwm;
188         uint32_t hwm;
189         int res;
190
191         /* Get current high water mark */
192         switch (xid->type) {
193
194         case ID_TYPE_UID:
195                 hwmkey = HWM_USER;
196                 hwmtype = "UID";
197                 high_hwm = idmap_tdb2_state.high_uid;
198                 break;
199
200         case ID_TYPE_GID:
201                 hwmkey = HWM_GROUP;
202                 hwmtype = "GID";
203                 high_hwm = idmap_tdb2_state.high_gid;
204                 break;
205
206         default:
207                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
208                 return NT_STATUS_INVALID_PARAMETER;
209         }
210
211         res = idmap_tdb2->transaction_start(idmap_tdb2);
212         if (res != 0) {
213                 DEBUG(1,(__location__ " Failed to start transaction\n"));
214                 return NT_STATUS_UNSUCCESSFUL;
215         }
216
217         if ((hwm = dbwrap_fetch_int32(idmap_tdb2, hwmkey)) == -1) {
218                 idmap_tdb2->transaction_cancel(idmap_tdb2);
219                 return NT_STATUS_INTERNAL_DB_ERROR;
220         }
221
222         /* check it is in the range */
223         if (hwm > high_hwm) {
224                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
225                           hwmtype, (unsigned long)high_hwm));
226                 idmap_tdb2->transaction_cancel(idmap_tdb2);
227                 return NT_STATUS_UNSUCCESSFUL;
228         }
229
230         /* fetch a new id and increment it */
231         ret = dbwrap_change_uint32_atomic(idmap_tdb2, hwmkey, &hwm, 1);
232         if (ret == -1) {
233                 DEBUG(1, ("Fatal error while fetching a new %s value\n!", hwmtype));
234                 idmap_tdb2->transaction_cancel(idmap_tdb2);
235                 return NT_STATUS_UNSUCCESSFUL;
236         }
237
238         /* recheck it is in the range */
239         if (hwm > high_hwm) {
240                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n", 
241                           hwmtype, (unsigned long)high_hwm));
242                 idmap_tdb2->transaction_cancel(idmap_tdb2);
243                 return NT_STATUS_UNSUCCESSFUL;
244         }
245
246         res = idmap_tdb2->transaction_commit(idmap_tdb2);
247         if (res != 0) {
248                 DEBUG(1,(__location__ " Failed to commit transaction\n"));
249                 return NT_STATUS_UNSUCCESSFUL;
250         }
251         
252         xid->id = hwm;
253         DEBUG(10,("New %s = %d\n", hwmtype, hwm));
254
255         return NT_STATUS_OK;
256 }
257
258 /*
259   Get current highest id. 
260 */
261 static NTSTATUS idmap_tdb2_get_hwm(struct unixid *xid)
262 {
263         const char *hwmkey;
264         const char *hwmtype;
265         uint32_t hwm;
266         uint32_t high_hwm;
267
268         /* Get current high water mark */
269         switch (xid->type) {
270
271         case ID_TYPE_UID:
272                 hwmkey = HWM_USER;
273                 hwmtype = "UID";
274                 high_hwm = idmap_tdb2_state.high_uid;
275                 break;
276
277         case ID_TYPE_GID:
278                 hwmkey = HWM_GROUP;
279                 hwmtype = "GID";
280                 high_hwm = idmap_tdb2_state.high_gid;
281                 break;
282
283         default:
284                 return NT_STATUS_INVALID_PARAMETER;
285         }
286
287         if ((hwm = dbwrap_fetch_int32(idmap_tdb2, hwmkey)) == -1) {
288                 return NT_STATUS_INTERNAL_DB_ERROR;
289         }
290
291         xid->id = hwm;
292
293         /* Warn if it is out of range */
294         if (hwm >= high_hwm) {
295                 DEBUG(0, ("Warning: %s range full!! (max: %lu)\n", 
296                           hwmtype, (unsigned long)high_hwm));
297         }
298
299         return NT_STATUS_OK;
300 }
301
302 /*
303   Set high id. 
304 */
305 static NTSTATUS idmap_tdb2_set_hwm(struct unixid *xid)
306 {
307         /* not supported, or we would invalidate the cache tdb on
308            other nodes */
309         DEBUG(0,("idmap_tdb2_set_hwm not supported\n"));
310         return NT_STATUS_NOT_SUPPORTED;
311 }
312
313 /*
314   Close the alloc tdb 
315 */
316 static NTSTATUS idmap_tdb2_alloc_close(void)
317 {
318         /* don't actually close it */
319         return NT_STATUS_OK;
320 }
321
322 /*
323   IDMAP MAPPING TDB BACKEND
324 */
325 struct idmap_tdb2_context {
326         uint32_t filter_low_id;
327         uint32_t filter_high_id;
328 };
329
330 /*
331   Initialise idmap database. 
332 */
333 static NTSTATUS idmap_tdb2_db_init(struct idmap_domain *dom,
334                                    const char *params)
335 {
336         NTSTATUS ret;
337         struct idmap_tdb2_context *ctx;
338         char *config_option = NULL;
339         const char *range;
340         NTSTATUS status;
341
342         status = idmap_tdb2_open_db();
343         NT_STATUS_NOT_OK_RETURN(status);
344
345         ctx = talloc(dom, struct idmap_tdb2_context);
346         if ( ! ctx) {
347                 DEBUG(0, ("Out of memory!\n"));
348                 return NT_STATUS_NO_MEMORY;
349         }
350
351         config_option = talloc_asprintf(ctx, "idmap config %s", dom->name);
352         if ( ! config_option) {
353                 DEBUG(0, ("Out of memory!\n"));
354                 ret = NT_STATUS_NO_MEMORY;
355                 goto failed;
356         }
357
358         range = lp_parm_const_string(-1, config_option, "range", NULL);
359         if (( ! range) ||
360             (sscanf(range, "%u - %u", &ctx->filter_low_id, &ctx->filter_high_id) != 2) ||
361             (ctx->filter_low_id > ctx->filter_high_id)) {
362                 ctx->filter_low_id = 0;
363                 ctx->filter_high_id = 0;
364         }
365
366         dom->private_data = ctx;
367
368         talloc_free(config_option);
369         return NT_STATUS_OK;
370
371 failed:
372         talloc_free(ctx);
373         return ret;
374 }
375
376
377 /*
378   run a script to perform a mapping
379
380   The script should the following command lines:
381
382       SIDTOID S-1-xxxx
383       IDTOSID UID xxxx
384       IDTOSID GID xxxx
385
386   and should return one of the following as a single line of text
387      UID:xxxx
388      GID:xxxx
389      SID:xxxx
390      ERR:xxxx
391  */
392 static NTSTATUS idmap_tdb2_script(struct idmap_tdb2_context *ctx, struct id_map *map,
393                                   const char *fmt, ...)
394 {
395         va_list ap;
396         char *cmd;
397         FILE *p;
398         char line[64];
399         unsigned long v;
400
401         cmd = talloc_asprintf(ctx, "%s ", idmap_tdb2_state.idmap_script);
402         NT_STATUS_HAVE_NO_MEMORY(cmd);  
403
404         va_start(ap, fmt);
405         cmd = talloc_vasprintf_append(cmd, fmt, ap);
406         va_end(ap);
407         NT_STATUS_HAVE_NO_MEMORY(cmd);
408
409         p = popen(cmd, "r");
410         talloc_free(cmd);
411         if (p == NULL) {
412                 return NT_STATUS_NONE_MAPPED;
413         }
414
415         if (fgets(line, sizeof(line)-1, p) == NULL) {
416                 pclose(p);
417                 return NT_STATUS_NONE_MAPPED;
418         }
419         pclose(p);
420
421         DEBUG(10,("idmap script gave: %s\n", line));
422
423         if (sscanf(line, "UID:%lu", &v) == 1) {
424                 map->xid.id   = v;
425                 map->xid.type = ID_TYPE_UID;
426         } else if (sscanf(line, "GID:%lu", &v) == 1) {
427                 map->xid.id   = v;
428                 map->xid.type = ID_TYPE_GID;            
429         } else if (strncmp(line, "SID:S-", 6) == 0) {
430                 if (!string_to_sid(map->sid, &line[4])) {
431                         DEBUG(0,("Bad SID in '%s' from idmap script %s\n",
432                                  line, idmap_tdb2_state.idmap_script));
433                         return NT_STATUS_NONE_MAPPED;                   
434                 }
435         } else {
436                 DEBUG(0,("Bad reply '%s' from idmap script %s\n",
437                          line, idmap_tdb2_state.idmap_script));
438                 return NT_STATUS_NONE_MAPPED;
439         }
440
441         return NT_STATUS_OK;
442 }
443
444
445
446 /*
447   Single id to sid lookup function. 
448 */
449 static NTSTATUS idmap_tdb2_id_to_sid(struct idmap_tdb2_context *ctx, struct id_map *map)
450 {
451         NTSTATUS ret;
452         TDB_DATA data;
453         char *keystr;
454
455         if (!ctx || !map) {
456                 return NT_STATUS_INVALID_PARAMETER;
457         }
458
459         /* apply filters before checking */
460         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
461             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
462                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
463                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
464                 return NT_STATUS_NONE_MAPPED;
465         }
466
467         switch (map->xid.type) {
468
469         case ID_TYPE_UID:
470                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
471                 break;
472                 
473         case ID_TYPE_GID:
474                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
475                 break;
476
477         default:
478                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
479                 return NT_STATUS_INVALID_PARAMETER;
480         }
481
482         /* final SAFE_FREE safe */
483         data.dptr = NULL;
484
485         if (keystr == NULL) {
486                 DEBUG(0, ("Out of memory!\n"));
487                 ret = NT_STATUS_NO_MEMORY;
488                 goto done;
489         }
490
491         DEBUG(10,("Fetching record %s\n", keystr));
492
493         /* Check if the mapping exists */
494         data = dbwrap_fetch_bystring(idmap_tdb2, keystr, keystr);
495
496         if (!data.dptr) {
497                 fstring sidstr;
498
499                 DEBUG(10,("Record %s not found\n", keystr));
500                 if (idmap_tdb2_state.idmap_script == NULL) {
501                         ret = NT_STATUS_NONE_MAPPED;
502                         goto done;
503                 }
504
505                 ret = idmap_tdb2_script(ctx, map, "IDTOSID %s", keystr);
506
507                 /* store it on shared storage */
508                 if (!NT_STATUS_IS_OK(ret)) {
509                         goto done;
510                 }
511
512                 if (sid_to_fstring(sidstr, map->sid)) {
513                         /* both forward and reverse mappings */
514                         dbwrap_store_bystring(idmap_tdb2, keystr,
515                                             string_term_tdb_data(sidstr), 
516                                             TDB_REPLACE);
517                         dbwrap_store_bystring(idmap_tdb2, sidstr,
518                                             string_term_tdb_data(keystr), 
519                                             TDB_REPLACE);
520                 }
521                 goto done;
522         }
523                 
524         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
525                 DEBUG(10,("INVALID SID (%s) in record %s\n",
526                         (const char *)data.dptr, keystr));
527                 ret = NT_STATUS_INTERNAL_DB_ERROR;
528                 goto done;
529         }
530
531         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
532         ret = NT_STATUS_OK;
533
534 done:
535         talloc_free(keystr);
536         return ret;
537 }
538
539
540 /*
541  Single sid to id lookup function. 
542 */
543 static NTSTATUS idmap_tdb2_sid_to_id(struct idmap_tdb2_context *ctx, struct id_map *map)
544 {
545         NTSTATUS ret;
546         TDB_DATA data;
547         char *keystr;
548         unsigned long rec_id = 0;
549
550         if ((keystr = sid_string_talloc(ctx, map->sid)) == NULL) {
551                 DEBUG(0, ("Out of memory!\n"));
552                 ret = NT_STATUS_NO_MEMORY;
553                 goto done;
554         }
555
556         DEBUG(10,("Fetching record %s\n", keystr));
557
558         /* Check if sid is present in database */
559         data = dbwrap_fetch_bystring(idmap_tdb2, keystr, keystr);
560         if (!data.dptr) {
561                 fstring idstr;
562
563                 DEBUG(10,(__location__ " Record %s not found\n", keystr));
564
565                 if (idmap_tdb2_state.idmap_script == NULL) {
566                         ret = NT_STATUS_NONE_MAPPED;
567                         goto done;
568                 }
569                         
570                 ret = idmap_tdb2_script(ctx, map, "SIDTOID %s", keystr);
571                 /* store it on shared storage */
572                 if (!NT_STATUS_IS_OK(ret)) {
573                         goto done;
574                 }
575
576                 snprintf(idstr, sizeof(idstr), "%cID %lu", 
577                          map->xid.type == ID_TYPE_UID?'U':'G',
578                          (unsigned long)map->xid.id);
579                 /* store both forward and reverse mappings */
580                 dbwrap_store_bystring(idmap_tdb2, keystr, string_term_tdb_data(idstr),
581                                     TDB_REPLACE);
582                 dbwrap_store_bystring(idmap_tdb2, idstr, string_term_tdb_data(keystr),
583                                     TDB_REPLACE);
584                 goto done;
585         }
586
587         /* What type of record is this ? */
588         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
589                 map->xid.id = rec_id;
590                 map->xid.type = ID_TYPE_UID;
591                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
592                 ret = NT_STATUS_OK;
593
594         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
595                 map->xid.id = rec_id;
596                 map->xid.type = ID_TYPE_GID;
597                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
598                 ret = NT_STATUS_OK;
599
600         } else { /* Unknown record type ! */
601                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
602                 ret = NT_STATUS_INTERNAL_DB_ERROR;
603         }
604         
605         /* apply filters before returning result */
606         if ((ctx->filter_low_id && (map->xid.id < ctx->filter_low_id)) ||
607             (ctx->filter_high_id && (map->xid.id > ctx->filter_high_id))) {
608                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
609                                 map->xid.id, ctx->filter_low_id, ctx->filter_high_id));
610                 ret = NT_STATUS_NONE_MAPPED;
611         }
612
613 done:
614         talloc_free(keystr);
615         return ret;
616 }
617
618 /*
619   lookup a set of unix ids. 
620 */
621 static NTSTATUS idmap_tdb2_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
622 {
623         struct idmap_tdb2_context *ctx;
624         NTSTATUS ret;
625         int i;
626
627         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
628
629         for (i = 0; ids[i]; i++) {
630                 ret = idmap_tdb2_id_to_sid(ctx, ids[i]);
631                 if ( ! NT_STATUS_IS_OK(ret)) {
632
633                         /* if it is just a failed mapping continue */
634                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
635
636                                 /* make sure it is marked as unmapped */
637                                 ids[i]->status = ID_UNMAPPED;
638                                 continue;
639                         }
640                         
641                         /* some fatal error occurred, return immediately */
642                         goto done;
643                 }
644
645                 /* all ok, id is mapped */
646                 ids[i]->status = ID_MAPPED;
647         }
648
649         ret = NT_STATUS_OK;
650
651 done:
652         return ret;
653 }
654
655 /*
656   lookup a set of sids. 
657 */
658 static NTSTATUS idmap_tdb2_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
659 {
660         struct idmap_tdb2_context *ctx;
661         NTSTATUS ret;
662         int i;
663
664         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
665
666         for (i = 0; ids[i]; i++) {
667                 ret = idmap_tdb2_sid_to_id(ctx, ids[i]);
668                 if ( ! NT_STATUS_IS_OK(ret)) {
669
670                         /* if it is just a failed mapping continue */
671                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
672
673                                 /* make sure it is marked as unmapped */
674                                 ids[i]->status = ID_UNMAPPED;
675                                 continue;
676                         }
677                         
678                         /* some fatal error occurred, return immediately */
679                         goto done;
680                 }
681
682                 /* all ok, id is mapped */
683                 ids[i]->status = ID_MAPPED;
684         }
685
686         ret = NT_STATUS_OK;
687
688 done:
689         return ret;
690 }
691
692
693 /*
694   set a mapping. 
695 */
696 static NTSTATUS idmap_tdb2_set_mapping(struct idmap_domain *dom, const struct id_map *map)
697 {
698         struct idmap_tdb2_context *ctx;
699         NTSTATUS ret;
700         TDB_DATA data;
701         char *ksidstr, *kidstr;
702         int res;
703         bool started_transaction = false;
704
705         if (!map || !map->sid) {
706                 return NT_STATUS_INVALID_PARAMETER;
707         }
708
709         ksidstr = kidstr = NULL;
710
711         /* TODO: should we filter a set_mapping using low/high filters ? */
712         
713         ctx = talloc_get_type(dom->private_data, struct idmap_tdb2_context);
714
715         switch (map->xid.type) {
716
717         case ID_TYPE_UID:
718                 kidstr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
719                 break;
720                 
721         case ID_TYPE_GID:
722                 kidstr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
723                 break;
724
725         default:
726                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
727                 return NT_STATUS_INVALID_PARAMETER;
728         }
729
730         if (kidstr == NULL) {
731                 DEBUG(0, ("ERROR: Out of memory!\n"));
732                 ret = NT_STATUS_NO_MEMORY;
733                 goto done;
734         }
735
736         if (!(ksidstr = sid_string_talloc(ctx, map->sid))) {
737                 DEBUG(0, ("Out of memory!\n"));
738                 ret = NT_STATUS_NO_MEMORY;
739                 goto done;
740         }
741
742         DEBUG(10, ("Storing %s <-> %s map\n", ksidstr, kidstr));
743
744         res = idmap_tdb2->transaction_start(idmap_tdb2);
745         if (res != 0) {
746                 DEBUG(1,(__location__ " Failed to start transaction\n"));
747                 ret = NT_STATUS_UNSUCCESSFUL;
748                 goto done;
749         }
750
751         started_transaction = true;
752         
753         /* check wheter sid mapping is already present in db */
754         data = dbwrap_fetch_bystring(idmap_tdb2, ksidstr, ksidstr);
755         if (data.dptr) {
756                 ret = NT_STATUS_OBJECT_NAME_COLLISION;
757                 goto done;
758         }
759
760         ret = dbwrap_store_bystring(idmap_tdb2, ksidstr, string_term_tdb_data(kidstr),
761                                   TDB_INSERT);
762         if (!NT_STATUS_IS_OK(ret)) {
763                 DEBUG(0, ("Error storing SID -> ID: %s\n", nt_errstr(ret)));
764                 goto done;
765         }
766         ret = dbwrap_store_bystring(idmap_tdb2, kidstr, string_term_tdb_data(ksidstr),
767                                   TDB_INSERT);
768         if (!NT_STATUS_IS_OK(ret)) {
769                 DEBUG(0, ("Error storing ID -> SID: %s\n", nt_errstr(ret)));
770                 /* try to remove the previous stored SID -> ID map */
771                 dbwrap_delete_bystring(idmap_tdb2, ksidstr);
772                 goto done;
773         }
774
775         started_transaction = false;
776
777         res = idmap_tdb2->transaction_commit(idmap_tdb2);
778         if (res != 0) {
779                 DEBUG(1,(__location__ " Failed to commit transaction\n"));
780                 ret = NT_STATUS_UNSUCCESSFUL;
781                 goto done;
782         }
783
784         DEBUG(10,("Stored %s <-> %s\n", ksidstr, kidstr));
785         ret = NT_STATUS_OK;
786
787 done:
788         if (started_transaction) {
789                 idmap_tdb2->transaction_cancel(idmap_tdb2);
790         }
791         talloc_free(ksidstr);
792         talloc_free(kidstr);
793         return ret;
794 }
795
796 /*
797   remove a mapping. 
798 */
799 static NTSTATUS idmap_tdb2_remove_mapping(struct idmap_domain *dom, const struct id_map *map)
800 {
801         /* not supported as it would invalidate the cache tdb on other
802            nodes */
803         DEBUG(0,("idmap_tdb2_remove_mapping not supported\n"));
804         return NT_STATUS_NOT_SUPPORTED;
805 }
806
807 /*
808   Close the idmap tdb instance
809 */
810 static NTSTATUS idmap_tdb2_close(struct idmap_domain *dom)
811 {
812         /* don't do anything */
813         return NT_STATUS_OK;
814 }
815
816
817 /*
818   Dump all mappings out
819 */
820 static NTSTATUS idmap_tdb2_dump_data(struct idmap_domain *dom, struct id_map **maps, int *num_maps)
821 {
822         DEBUG(0,("idmap_tdb2_dump_data not supported\n"));
823         return NT_STATUS_NOT_SUPPORTED;
824 }
825
826 static struct idmap_methods db_methods = {
827         .init            = idmap_tdb2_db_init,
828         .unixids_to_sids = idmap_tdb2_unixids_to_sids,
829         .sids_to_unixids = idmap_tdb2_sids_to_unixids,
830         .set_mapping     = idmap_tdb2_set_mapping,
831         .remove_mapping  = idmap_tdb2_remove_mapping,
832         .dump_data       = idmap_tdb2_dump_data,
833         .close_fn        = idmap_tdb2_close
834 };
835
836 static struct idmap_alloc_methods db_alloc_methods = {
837         .init        = idmap_tdb2_alloc_init,
838         .allocate_id = idmap_tdb2_allocate_id,
839         .get_id_hwm  = idmap_tdb2_get_hwm,
840         .set_id_hwm  = idmap_tdb2_set_hwm,
841         .close_fn    = idmap_tdb2_alloc_close
842 };
843
844 NTSTATUS idmap_tdb2_init(void)
845 {
846         NTSTATUS ret;
847
848         /* register both backends */
849         ret = smb_register_idmap_alloc(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_alloc_methods);
850         if (! NT_STATUS_IS_OK(ret)) {
851                 DEBUG(0, ("Unable to register idmap alloc tdb2 module: %s\n", get_friendly_nt_error_msg(ret)));
852                 return ret;
853         }
854
855         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb2", &db_methods);
856 }