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