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