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