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