s3-includes: only include system/filesys.h when needed.
[obnox/samba/samba-obnox.git] / source3 / winbindd / idmap_tdb.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    idmap TDB backend
5
6    Copyright (C) Tim Potter 2000
7    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
8    Copyright (C) Jeremy Allison 2006
9    Copyright (C) Simo Sorce 2003-2006
10    Copyright (C) Michael Adam 2009-2010
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 #include "includes.h"
27 #include "system/filesys.h"
28 #include "winbindd.h"
29 #include "idmap.h"
30 #include "idmap_rw.h"
31 #include "dbwrap.h"
32 #include "../libcli/security/security.h"
33
34 #undef DBGC_CLASS
35 #define DBGC_CLASS DBGC_IDMAP
36
37 /* idmap version determines auto-conversion - this is the database
38    structure version specifier. */
39
40 #define IDMAP_VERSION 2
41
42 struct idmap_tdb_context {
43         struct db_context *db;
44         struct idmap_rw_ops *rw_ops;
45 };
46
47 /* High water mark keys */
48 #define HWM_GROUP  "GROUP HWM"
49 #define HWM_USER   "USER HWM"
50
51 struct convert_fn_state {
52         struct db_context *db;
53         bool failed;
54 };
55
56 /*****************************************************************************
57  For idmap conversion: convert one record to new format
58  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
59  instead of the SID.
60 *****************************************************************************/
61 static int convert_fn(struct db_record *rec, void *private_data)
62 {
63         struct winbindd_domain *domain;
64         char *p;
65         NTSTATUS status;
66         struct dom_sid sid;
67         uint32 rid;
68         fstring keystr;
69         fstring dom_name;
70         TDB_DATA key2;
71         struct convert_fn_state *s = (struct convert_fn_state *)private_data;
72
73         DEBUG(10,("Converting %s\n", (const char *)rec->key.dptr));
74
75         p = strchr((const char *)rec->key.dptr, '/');
76         if (!p)
77                 return 0;
78
79         *p = 0;
80         fstrcpy(dom_name, (const char *)rec->key.dptr);
81         *p++ = '/';
82
83         domain = find_domain_from_name(dom_name);
84         if (domain == NULL) {
85                 /* We must delete the old record. */
86                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
87                 DEBUG(0,("deleting record %s\n", (const char *)rec->key.dptr ));
88
89                 status = rec->delete_rec(rec);
90                 if (!NT_STATUS_IS_OK(status)) {
91                         DEBUG(0, ("Unable to delete record %s:%s\n",
92                                 (const char *)rec->key.dptr,
93                                 nt_errstr(status)));
94                         s->failed = true;
95                         return -1;
96                 }
97
98                 return 0;
99         }
100
101         rid = atoi(p);
102
103         sid_compose(&sid, &domain->sid, rid);
104
105         sid_to_fstring(keystr, &sid);
106         key2 = string_term_tdb_data(keystr);
107
108         status = dbwrap_store(s->db, key2, rec->value, TDB_INSERT);
109         if (!NT_STATUS_IS_OK(status)) {
110                 DEBUG(0,("Unable to add record %s:%s\n",
111                         (const char *)key2.dptr,
112                         nt_errstr(status)));
113                 s->failed = true;
114                 return -1;
115         }
116
117         status = dbwrap_store(s->db, rec->value, key2, TDB_REPLACE);
118         if (!NT_STATUS_IS_OK(status)) {
119                 DEBUG(0,("Unable to update record %s:%s\n",
120                         (const char *)rec->value.dptr,
121                         nt_errstr(status)));
122                 s->failed = true;
123                 return -1;
124         }
125
126         status = rec->delete_rec(rec);
127         if (!NT_STATUS_IS_OK(status)) {
128                 DEBUG(0,("Unable to delete record %s:%s\n",
129                         (const char *)rec->key.dptr,
130                         nt_errstr(status)));
131                 s->failed = true;
132                 return -1;
133         }
134
135         return 0;
136 }
137
138 /*****************************************************************************
139  Convert the idmap database from an older version.
140 *****************************************************************************/
141
142 static bool idmap_tdb_upgrade(struct idmap_domain *dom, struct db_context *db)
143 {
144         int32 vers;
145         bool bigendianheader;
146         struct convert_fn_state s;
147
148         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
149
150         bigendianheader = (db->get_flags(db) & TDB_BIGENDIAN) ? True : False;
151
152         vers = dbwrap_fetch_int32(db, "IDMAP_VERSION");
153
154         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
155                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
156                 /*
157                  * high and low records were created on a
158                  * big endian machine and will need byte-reversing.
159                  */
160
161                 int32 wm;
162
163                 wm = dbwrap_fetch_int32(db, HWM_USER);
164
165                 if (wm != -1) {
166                         wm = IREV(wm);
167                 }  else {
168                         wm = dom->low_id;
169                 }
170
171                 if (dbwrap_store_int32(db, HWM_USER, wm) == -1) {
172                         DEBUG(0, ("Unable to byteswap user hwm in idmap database\n"));
173                         return False;
174                 }
175
176                 wm = dbwrap_fetch_int32(db, HWM_GROUP);
177                 if (wm != -1) {
178                         wm = IREV(wm);
179                 } else {
180                         wm = dom->low_id;
181                 }
182
183                 if (dbwrap_store_int32(db, HWM_GROUP, wm) == -1) {
184                         DEBUG(0, ("Unable to byteswap group hwm in idmap database\n"));
185                         return False;
186                 }
187         }
188
189         s.db = db;
190         s.failed = false;
191
192         /* the old format stored as DOMAIN/rid - now we store the SID direct */
193         db->traverse(db, convert_fn, &s);
194
195         if (s.failed) {
196                 DEBUG(0, ("Problem during conversion\n"));
197                 return False;
198         }
199
200         if (dbwrap_store_int32(db, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
201                 DEBUG(0, ("Unable to store idmap version in database\n"));
202                 return False;
203         }
204
205         return True;
206 }
207
208 static NTSTATUS idmap_tdb_init_hwm(struct idmap_domain *dom)
209 {
210         int ret;
211         uint32_t low_uid;
212         uint32_t low_gid;
213         bool update_uid = false;
214         bool update_gid = false;
215         struct idmap_tdb_context *ctx;
216
217         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
218
219         low_uid = dbwrap_fetch_int32(ctx->db, HWM_USER);
220         if (low_uid == -1 || low_uid < dom->low_id) {
221                 update_uid = true;
222         }
223
224         low_gid = dbwrap_fetch_int32(ctx->db, HWM_GROUP);
225         if (low_gid == -1 || low_gid < dom->low_id) {
226                 update_gid = true;
227         }
228
229         if (!update_uid && !update_gid) {
230                 return NT_STATUS_OK;
231         }
232
233         if (ctx->db->transaction_start(ctx->db) != 0) {
234                 DEBUG(0, ("Unable to start upgrade transaction!\n"));
235                 return NT_STATUS_INTERNAL_DB_ERROR;
236         }
237
238         if (update_uid) {
239                 ret = dbwrap_store_int32(ctx->db, HWM_USER, dom->low_id);
240                 if (ret == -1) {
241                         ctx->db->transaction_cancel(ctx->db);
242                         DEBUG(0, ("Unable to initialise user hwm in idmap "
243                                   "database\n"));
244                         return NT_STATUS_INTERNAL_DB_ERROR;
245                 }
246         }
247
248         if (update_gid) {
249                 ret = dbwrap_store_int32(ctx->db, HWM_GROUP, dom->low_id);
250                 if (ret == -1) {
251                         ctx->db->transaction_cancel(ctx->db);
252                         DEBUG(0, ("Unable to initialise group hwm in idmap "
253                                   "database\n"));
254                         return NT_STATUS_INTERNAL_DB_ERROR;
255                 }
256         }
257
258         if (ctx->db->transaction_commit(ctx->db) != 0) {
259                 DEBUG(0, ("Unable to commit upgrade transaction!\n"));
260                 return NT_STATUS_INTERNAL_DB_ERROR;
261         }
262
263         return NT_STATUS_OK;
264 }
265
266 static NTSTATUS idmap_tdb_open_db(struct idmap_domain *dom)
267 {
268         NTSTATUS ret;
269         TALLOC_CTX *mem_ctx;
270         char *tdbfile = NULL;
271         struct db_context *db = NULL;
272         int32_t version;
273         bool config_error = false;
274         struct idmap_tdb_context *ctx;
275
276         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
277
278         if (ctx->db) {
279                 /* it is already open */
280                 return NT_STATUS_OK;
281         }
282
283         /* use our own context here */
284         mem_ctx = talloc_stackframe();
285
286         /* use the old database if present */
287         tdbfile = state_path("winbindd_idmap.tdb");
288         if (!tdbfile) {
289                 DEBUG(0, ("Out of memory!\n"));
290                 ret = NT_STATUS_NO_MEMORY;
291                 goto done;
292         }
293
294         DEBUG(10,("Opening tdbfile %s\n", tdbfile ));
295
296         /* Open idmap repository */
297         db = db_open(mem_ctx, tdbfile, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
298         if (!db) {
299                 DEBUG(0, ("Unable to open idmap database\n"));
300                 ret = NT_STATUS_UNSUCCESSFUL;
301                 goto done;
302         }
303
304         /* check against earlier versions */
305         version = dbwrap_fetch_int32(db, "IDMAP_VERSION");
306         if (version != IDMAP_VERSION) {
307                 if (config_error) {
308                         DEBUG(0,("Upgrade of IDMAP_VERSION from %d to %d is not "
309                                  "possible with incomplete configuration\n",
310                                  version, IDMAP_VERSION));
311                         ret = NT_STATUS_UNSUCCESSFUL;
312                         goto done;
313                 }
314                 if (db->transaction_start(db) != 0) {
315                         DEBUG(0, ("Unable to start upgrade transaction!\n"));
316                         ret = NT_STATUS_INTERNAL_DB_ERROR;
317                         goto done;
318                 }
319
320                 if (!idmap_tdb_upgrade(dom, db)) {
321                         db->transaction_cancel(db);
322                         DEBUG(0, ("Unable to open idmap database, it's in an old format, and upgrade failed!\n"));
323                         ret = NT_STATUS_INTERNAL_DB_ERROR;
324                         goto done;
325                 }
326
327                 if (db->transaction_commit(db) != 0) {
328                         DEBUG(0, ("Unable to commit upgrade transaction!\n"));
329                         ret = NT_STATUS_INTERNAL_DB_ERROR;
330                         goto done;
331                 }
332         }
333
334         ctx->db = talloc_move(ctx, &db);
335
336         ret = idmap_tdb_init_hwm(dom);
337
338 done:
339         talloc_free(mem_ctx);
340         return ret;
341 }
342
343 /**********************************************************************
344  IDMAP ALLOC TDB BACKEND
345 **********************************************************************/
346
347 /**********************************
348  Allocate a new id. 
349 **********************************/
350
351 struct idmap_tdb_allocate_id_context {
352         const char *hwmkey;
353         const char *hwmtype;
354         uint32_t high_hwm;
355         uint32_t hwm;
356 };
357
358 static NTSTATUS idmap_tdb_allocate_id_action(struct db_context *db,
359                                              void *private_data)
360 {
361         NTSTATUS ret;
362         struct idmap_tdb_allocate_id_context *state;
363         uint32_t hwm;
364
365         state = (struct idmap_tdb_allocate_id_context *)private_data;
366
367         hwm = dbwrap_fetch_int32(db, state->hwmkey);
368         if (hwm == -1) {
369                 ret = NT_STATUS_INTERNAL_DB_ERROR;
370                 goto done;
371         }
372
373         /* check it is in the range */
374         if (hwm > state->high_hwm) {
375                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
376                           state->hwmtype, (unsigned long)state->high_hwm));
377                 ret = NT_STATUS_UNSUCCESSFUL;
378                 goto done;
379         }
380
381         /* fetch a new id and increment it */
382         ret = dbwrap_trans_change_uint32_atomic(db, state->hwmkey, &hwm, 1);
383         if (!NT_STATUS_IS_OK(ret)) {
384                 DEBUG(0, ("Fatal error while fetching a new %s value: %s\n!",
385                           state->hwmtype, nt_errstr(ret)));
386                 goto done;
387         }
388
389         /* recheck it is in the range */
390         if (hwm > state->high_hwm) {
391                 DEBUG(1, ("Fatal Error: %s range full!! (max: %lu)\n",
392                           state->hwmtype, (unsigned long)state->high_hwm));
393                 ret = NT_STATUS_UNSUCCESSFUL;
394                 goto done;
395         }
396
397         ret = NT_STATUS_OK;
398         state->hwm = hwm;
399
400 done:
401         return ret;
402 }
403
404 static NTSTATUS idmap_tdb_allocate_id(struct idmap_domain *dom,
405                                       struct unixid *xid)
406 {
407         const char *hwmkey;
408         const char *hwmtype;
409         uint32_t high_hwm;
410         uint32_t hwm = 0;
411         NTSTATUS status;
412         struct idmap_tdb_allocate_id_context state;
413         struct idmap_tdb_context *ctx;
414
415         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
416
417         /* Get current high water mark */
418         switch (xid->type) {
419
420         case ID_TYPE_UID:
421                 hwmkey = HWM_USER;
422                 hwmtype = "UID";
423                 break;
424
425         case ID_TYPE_GID:
426                 hwmkey = HWM_GROUP;
427                 hwmtype = "GID";
428                 break;
429
430         default:
431                 DEBUG(2, ("Invalid ID type (0x%x)\n", xid->type));
432                 return NT_STATUS_INVALID_PARAMETER;
433         }
434
435         high_hwm = dom->high_id;
436
437         state.hwm = hwm;
438         state.high_hwm = high_hwm;
439         state.hwmtype = hwmtype;
440         state.hwmkey = hwmkey;
441
442         status = dbwrap_trans_do(ctx->db, idmap_tdb_allocate_id_action,
443                                  &state);
444
445         if (NT_STATUS_IS_OK(status)) {
446                 xid->id = state.hwm;
447                 DEBUG(10,("New %s = %d\n", hwmtype, state.hwm));
448         } else {
449                 DEBUG(1, ("Error allocating a new %s\n", hwmtype));
450         }
451
452         return status;
453 }
454
455 /**
456  * Allocate a new unix-ID.
457  * For now this is for the default idmap domain only.
458  * Should be extended later on.
459  */
460 static NTSTATUS idmap_tdb_get_new_id(struct idmap_domain *dom,
461                                      struct unixid *id)
462 {
463         NTSTATUS ret;
464
465         if (!strequal(dom->name, "*")) {
466                 DEBUG(3, ("idmap_tdb_get_new_id: "
467                           "Refusing allocation of a new unixid for domain'%s'. "
468                           "Currently only supported for the default "
469                           "domain \"*\".\n",
470                            dom->name));
471                 return NT_STATUS_NOT_IMPLEMENTED;
472         }
473
474         ret = idmap_tdb_allocate_id(dom, id);
475
476         return ret;
477 }
478
479 /**********************************************************************
480  IDMAP MAPPING TDB BACKEND
481 **********************************************************************/
482
483 /*****************************
484  Initialise idmap database. 
485 *****************************/
486
487 static NTSTATUS idmap_tdb_set_mapping(struct idmap_domain *dom,
488                                       const struct id_map *map);
489
490 static NTSTATUS idmap_tdb_db_init(struct idmap_domain *dom)
491 {
492         NTSTATUS ret;
493         struct idmap_tdb_context *ctx;
494
495         DEBUG(10, ("idmap_tdb_db_init called for domain '%s'\n", dom->name));
496
497         ctx = talloc_zero(dom, struct idmap_tdb_context);
498         if ( ! ctx) {
499                 DEBUG(0, ("Out of memory!\n"));
500                 return NT_STATUS_NO_MEMORY;
501         }
502
503         /* load backend specific configuration here: */
504 #if 0
505         if (strequal(dom->name, "*")) {
506         } else {
507         }
508 #endif
509
510         ctx->rw_ops = talloc_zero(ctx, struct idmap_rw_ops);
511         if (ctx->rw_ops == NULL) {
512                 DEBUG(0, ("Out of memory!\n"));
513                 ret = NT_STATUS_NO_MEMORY;
514                 goto failed;
515         }
516
517         ctx->rw_ops->get_new_id = idmap_tdb_get_new_id;
518         ctx->rw_ops->set_mapping = idmap_tdb_set_mapping;
519
520         dom->private_data = ctx;
521
522         ret = idmap_tdb_open_db(dom);
523         if ( ! NT_STATUS_IS_OK(ret)) {
524                 goto failed;
525         }
526
527         return NT_STATUS_OK;
528
529 failed:
530         talloc_free(ctx);
531         return ret;
532 }
533
534
535 /**
536  * store a mapping in the database
537  */
538
539 struct idmap_tdb_set_mapping_context {
540         const char *ksidstr;
541         const char *kidstr;
542 };
543
544 static NTSTATUS idmap_tdb_set_mapping_action(struct db_context *db,
545                                              void *private_data)
546 {
547         NTSTATUS ret;
548         struct idmap_tdb_set_mapping_context *state;
549
550         state = (struct idmap_tdb_set_mapping_context *)private_data;
551
552         DEBUG(10, ("Storing %s <-> %s map\n", state->ksidstr, state->kidstr));
553
554         ret = dbwrap_store_bystring(db, state->ksidstr,
555                                     string_term_tdb_data(state->kidstr),
556                                     TDB_REPLACE);
557         if (!NT_STATUS_IS_OK(ret)) {
558                 DEBUG(0, ("Error storing SID -> ID (%s -> %s): %s\n",
559                           state->ksidstr, state->kidstr, nt_errstr(ret)));
560                 goto done;
561         }
562
563         ret = dbwrap_store_bystring(db, state->kidstr,
564                                     string_term_tdb_data(state->ksidstr),
565                                     TDB_REPLACE);
566         if (!NT_STATUS_IS_OK(ret)) {
567                 DEBUG(0, ("Error storing ID -> SID (%s -> %s): %s\n",
568                           state->kidstr, state->ksidstr, nt_errstr(ret)));
569                 goto done;
570         }
571
572         DEBUG(10,("Stored %s <-> %s\n", state->ksidstr, state->kidstr));
573         ret = NT_STATUS_OK;
574
575 done:
576         return ret;
577 }
578
579 static NTSTATUS idmap_tdb_set_mapping(struct idmap_domain *dom,
580                                       const struct id_map *map)
581 {
582         struct idmap_tdb_context *ctx;
583         NTSTATUS ret;
584         char *ksidstr, *kidstr;
585         struct idmap_tdb_set_mapping_context state;
586
587         if (!map || !map->sid) {
588                 return NT_STATUS_INVALID_PARAMETER;
589         }
590
591         ksidstr = kidstr = NULL;
592
593         /* TODO: should we filter a set_mapping using low/high filters ? */
594
595         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
596
597         switch (map->xid.type) {
598
599         case ID_TYPE_UID:
600                 kidstr = talloc_asprintf(ctx, "UID %lu",
601                                          (unsigned long)map->xid.id);
602                 break;
603
604         case ID_TYPE_GID:
605                 kidstr = talloc_asprintf(ctx, "GID %lu",
606                                          (unsigned long)map->xid.id);
607                 break;
608
609         default:
610                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
611                 return NT_STATUS_INVALID_PARAMETER;
612         }
613
614         if (kidstr == NULL) {
615                 DEBUG(0, ("ERROR: Out of memory!\n"));
616                 ret = NT_STATUS_NO_MEMORY;
617                 goto done;
618         }
619
620         ksidstr = sid_string_talloc(ctx, map->sid);
621         if (ksidstr == NULL) {
622                 DEBUG(0, ("Out of memory!\n"));
623                 ret = NT_STATUS_NO_MEMORY;
624                 goto done;
625         }
626
627         state.ksidstr = ksidstr;
628         state.kidstr = kidstr;
629
630         ret = dbwrap_trans_do(ctx->db, idmap_tdb_set_mapping_action, &state);
631
632 done:
633         talloc_free(ksidstr);
634         talloc_free(kidstr);
635         return ret;
636 }
637
638 /**
639  * Create a new mapping for an unmapped SID, also allocating a new ID.
640  * This should be run inside a transaction.
641  *
642  * TODO:
643  * Properly integrate this with multi domain idmap config:
644  * Currently, the allocator is default-config only.
645  */
646 static NTSTATUS idmap_tdb_new_mapping(struct idmap_domain *dom, struct id_map *map)
647 {
648         NTSTATUS ret;
649         struct idmap_tdb_context *ctx;
650
651         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
652
653         ret = idmap_rw_new_mapping(dom, ctx->rw_ops, map);
654
655         return ret;
656 }
657
658
659 /**********************************
660  Single id to sid lookup function. 
661 **********************************/
662
663 static NTSTATUS idmap_tdb_id_to_sid(struct idmap_domain *dom, struct id_map *map)
664 {
665         NTSTATUS ret;
666         TDB_DATA data;
667         char *keystr;
668         struct idmap_tdb_context *ctx;
669
670         if (!dom || !map) {
671                 return NT_STATUS_INVALID_PARAMETER;
672         }
673
674         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
675
676         /* apply filters before checking */
677         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
678                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
679                                 map->xid.id, dom->low_id, dom->high_id));
680                 return NT_STATUS_NONE_MAPPED;
681         }
682
683         switch (map->xid.type) {
684
685         case ID_TYPE_UID:
686                 keystr = talloc_asprintf(ctx, "UID %lu", (unsigned long)map->xid.id);
687                 break;
688
689         case ID_TYPE_GID:
690                 keystr = talloc_asprintf(ctx, "GID %lu", (unsigned long)map->xid.id);
691                 break;
692
693         default:
694                 DEBUG(2, ("INVALID unix ID type: 0x02%x\n", map->xid.type));
695                 return NT_STATUS_INVALID_PARAMETER;
696         }
697
698         /* final SAFE_FREE safe */
699         data.dptr = NULL;
700
701         if (keystr == NULL) {
702                 DEBUG(0, ("Out of memory!\n"));
703                 ret = NT_STATUS_NO_MEMORY;
704                 goto done;
705         }
706
707         DEBUG(10,("Fetching record %s\n", keystr));
708
709         /* Check if the mapping exists */
710         data = dbwrap_fetch_bystring(ctx->db, NULL, keystr);
711
712         if (!data.dptr) {
713                 DEBUG(10,("Record %s not found\n", keystr));
714                 ret = NT_STATUS_NONE_MAPPED;
715                 goto done;
716         }
717
718         if (!string_to_sid(map->sid, (const char *)data.dptr)) {
719                 DEBUG(10,("INVALID SID (%s) in record %s\n",
720                         (const char *)data.dptr, keystr));
721                 ret = NT_STATUS_INTERNAL_DB_ERROR;
722                 goto done;
723         }
724
725         DEBUG(10,("Found record %s -> %s\n", keystr, (const char *)data.dptr));
726         ret = NT_STATUS_OK;
727
728 done:
729         talloc_free(data.dptr);
730         talloc_free(keystr);
731         return ret;
732 }
733
734 /**********************************
735  Single sid to id lookup function. 
736 **********************************/
737
738 static NTSTATUS idmap_tdb_sid_to_id(struct idmap_domain *dom, struct id_map *map)
739 {
740         NTSTATUS ret;
741         TDB_DATA data;
742         char *keystr;
743         unsigned long rec_id = 0;
744         struct idmap_tdb_context *ctx;
745         TALLOC_CTX *tmp_ctx = talloc_stackframe();
746
747         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
748
749         keystr = sid_string_talloc(tmp_ctx, map->sid);
750         if (keystr == NULL) {
751                 DEBUG(0, ("Out of memory!\n"));
752                 ret = NT_STATUS_NO_MEMORY;
753                 goto done;
754         }
755
756         DEBUG(10,("Fetching record %s\n", keystr));
757
758         /* Check if sid is present in database */
759         data = dbwrap_fetch_bystring(ctx->db, tmp_ctx, keystr);
760         if (!data.dptr) {
761                 DEBUG(10,("Record %s not found\n", keystr));
762                 ret = NT_STATUS_NONE_MAPPED;
763                 goto done;
764         }
765
766         /* What type of record is this ? */
767         if (sscanf((const char *)data.dptr, "UID %lu", &rec_id) == 1) { /* Try a UID record. */
768                 map->xid.id = rec_id;
769                 map->xid.type = ID_TYPE_UID;
770                 DEBUG(10,("Found uid record %s -> %s \n", keystr, (const char *)data.dptr ));
771                 ret = NT_STATUS_OK;
772
773         } else if (sscanf((const char *)data.dptr, "GID %lu", &rec_id) == 1) { /* Try a GID record. */
774                 map->xid.id = rec_id;
775                 map->xid.type = ID_TYPE_GID;
776                 DEBUG(10,("Found gid record %s -> %s \n", keystr, (const char *)data.dptr ));
777                 ret = NT_STATUS_OK;
778
779         } else { /* Unknown record type ! */
780                 DEBUG(2, ("Found INVALID record %s -> %s\n", keystr, (const char *)data.dptr));
781                 ret = NT_STATUS_INTERNAL_DB_ERROR;
782                 goto done;
783         }
784
785         /* apply filters before returning result */
786         if (!idmap_unix_id_is_in_range(map->xid.id, dom)) {
787                 DEBUG(5, ("Requested id (%u) out of range (%u - %u). Filtered!\n",
788                                 map->xid.id, dom->low_id, dom->high_id));
789                 ret = NT_STATUS_NONE_MAPPED;
790         }
791
792 done:
793         talloc_free(tmp_ctx);
794         return ret;
795 }
796
797 /**********************************
798  lookup a set of unix ids. 
799 **********************************/
800
801 static NTSTATUS idmap_tdb_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids)
802 {
803         NTSTATUS ret;
804         int i;
805
806         /* initialize the status to avoid suprise */
807         for (i = 0; ids[i]; i++) {
808                 ids[i]->status = ID_UNKNOWN;
809         }
810
811         for (i = 0; ids[i]; i++) {
812                 ret = idmap_tdb_id_to_sid(dom, ids[i]);
813                 if ( ! NT_STATUS_IS_OK(ret)) {
814
815                         /* if it is just a failed mapping continue */
816                         if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
817
818                                 /* make sure it is marked as unmapped */
819                                 ids[i]->status = ID_UNMAPPED;
820                                 continue;
821                         }
822
823                         /* some fatal error occurred, return immediately */
824                         goto done;
825                 }
826
827                 /* all ok, id is mapped */
828                 ids[i]->status = ID_MAPPED;
829         }
830
831         ret = NT_STATUS_OK;
832
833 done:
834         return ret;
835 }
836
837 /**********************************
838  lookup a set of sids. 
839 **********************************/
840
841 struct idmap_tdb_sids_to_unixids_context {
842         struct idmap_domain *dom;
843         struct id_map **ids;
844         bool allocate_unmapped;
845 };
846
847 static NTSTATUS idmap_tdb_sids_to_unixids_action(struct db_context *db,
848                                                  void *private_data)
849 {
850         struct idmap_tdb_sids_to_unixids_context *state;
851         int i;
852         NTSTATUS ret = NT_STATUS_OK;
853
854         state = (struct idmap_tdb_sids_to_unixids_context *)private_data;
855
856         DEBUG(10, ("idmap_tdb_sids_to_unixids_action: "
857                    " domain: [%s], allocate: %s\n",
858                    state->dom->name,
859                    state->allocate_unmapped ? "yes" : "no"));
860
861         for (i = 0; state->ids[i]; i++) {
862                 if ((state->ids[i]->status == ID_UNKNOWN) ||
863                     /* retry if we could not map in previous run: */
864                     (state->ids[i]->status == ID_UNMAPPED))
865                 {
866                         NTSTATUS ret2;
867
868                         ret2 = idmap_tdb_sid_to_id(state->dom, state->ids[i]);
869                         if (!NT_STATUS_IS_OK(ret2)) {
870
871                                 /* if it is just a failed mapping, continue */
872                                 if (NT_STATUS_EQUAL(ret2, NT_STATUS_NONE_MAPPED)) {
873
874                                         /* make sure it is marked as unmapped */
875                                         state->ids[i]->status = ID_UNMAPPED;
876                                         ret = STATUS_SOME_UNMAPPED;
877                                 } else {
878                                         /* some fatal error occurred, return immediately */
879                                         ret = ret2;
880                                         goto done;
881                                 }
882                         } else {
883                                 /* all ok, id is mapped */
884                                 state->ids[i]->status = ID_MAPPED;
885                         }
886                 }
887
888                 if ((state->ids[i]->status == ID_UNMAPPED) &&
889                     state->allocate_unmapped)
890                 {
891                         ret = idmap_tdb_new_mapping(state->dom, state->ids[i]);
892                         if (!NT_STATUS_IS_OK(ret)) {
893                                 goto done;
894                         }
895                 }
896         }
897
898 done:
899         return ret;
900 }
901
902 static NTSTATUS idmap_tdb_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids)
903 {
904         struct idmap_tdb_context *ctx;
905         NTSTATUS ret;
906         int i;
907         struct idmap_tdb_sids_to_unixids_context state;
908
909         /* initialize the status to avoid suprise */
910         for (i = 0; ids[i]; i++) {
911                 ids[i]->status = ID_UNKNOWN;
912         }
913
914         ctx = talloc_get_type(dom->private_data, struct idmap_tdb_context);
915
916         state.dom = dom;
917         state.ids = ids;
918         state.allocate_unmapped = false;
919
920         ret = idmap_tdb_sids_to_unixids_action(ctx->db, &state);
921
922         if (NT_STATUS_EQUAL(ret, STATUS_SOME_UNMAPPED) && !dom->read_only) {
923                 state.allocate_unmapped = true;
924                 ret = dbwrap_trans_do(ctx->db,
925                                       idmap_tdb_sids_to_unixids_action,
926                                       &state);
927         }
928
929         return ret;
930 }
931
932
933 /**********************************
934  Close the idmap tdb instance
935 **********************************/
936
937 static struct idmap_methods db_methods = {
938         .init = idmap_tdb_db_init,
939         .unixids_to_sids = idmap_tdb_unixids_to_sids,
940         .sids_to_unixids = idmap_tdb_sids_to_unixids,
941         .allocate_id = idmap_tdb_get_new_id,
942 };
943
944 NTSTATUS idmap_tdb_init(void)
945 {
946         DEBUG(10, ("calling idmap_tdb_init\n"));
947
948         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "tdb", &db_methods);
949 }