s3:dbwrap: move db_open() to a file dbwrap_open.c of its own.
[samba.git] / source3 / groupdb / mapping_tdb.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-2006,
5  *  Copyright (C) Jean Fran├žois Micouleau      1998-2001.
6  *  Copyright (C) Volker Lendecke              2006.
7  *  Copyright (C) Gerald Carter                2006.
8  *  
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 3 of the License, or
12  *  (at your option) any later version.
13  *  
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *  
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
21  */
22
23 #include "includes.h"
24 #include "system/filesys.h"
25 #include "passdb.h"
26 #include "groupdb/mapping.h"
27 #include "dbwrap.h"
28 #include "dbwrap/dbwrap_open.h"
29 #include "util_tdb.h"
30 #include "../libcli/security/security.h"
31
32 static struct db_context *db; /* used for driver files */
33
34 static bool enum_group_mapping(const struct dom_sid *domsid,
35                                enum lsa_SidType sid_name_use,
36                                GROUP_MAP **pp_rmap,
37                                size_t *p_num_entries,
38                                bool unix_only);
39 static bool group_map_remove(const struct dom_sid *sid);
40
41 static bool mapping_switch(const char *ldb_path);
42
43 /****************************************************************************
44  Open the group mapping tdb.
45 ****************************************************************************/
46 static bool init_group_mapping(void)
47 {
48         const char *ldb_path;
49
50         if (db != NULL) {
51                 return true;
52         }
53
54         db = db_open(NULL, state_path("group_mapping.tdb"), 0,
55                            TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
56         if (db == NULL) {
57                 DEBUG(0, ("Failed to open group mapping database: %s\n",
58                           strerror(errno)));
59                 return false;
60         }
61
62         ldb_path = state_path("group_mapping.ldb");
63         if (file_exist(ldb_path) && !mapping_switch(ldb_path)) {
64                 unlink(state_path("group_mapping.tdb"));
65                 return false;
66
67         } else {
68                 /* handle upgrade from old versions of the database */
69 #if 0 /* -- Needs conversion to dbwrap -- */
70                 const char *vstring = "INFO/version";
71                 int32 vers_id;
72                 GROUP_MAP *map_table = NULL;
73                 size_t num_entries = 0;
74
75                 /* handle a Samba upgrade */
76                 tdb_lock_bystring(tdb, vstring);
77
78                 /* Cope with byte-reversed older versions of the db. */
79                 vers_id = tdb_fetch_int32(tdb, vstring);
80                 if ((vers_id == DATABASE_VERSION_V1)
81                     || (IREV(vers_id) == DATABASE_VERSION_V1)) {
82                         /*
83                          * Written on a bigendian machine with old fetch_int
84                          * code. Save as le.
85                          */
86                         tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
87                         vers_id = DATABASE_VERSION_V2;
88                 }
89
90                 /* if its an unknown version we remove everthing in the db */
91
92                 if (vers_id != DATABASE_VERSION_V2) {
93                         tdb_wipe_all(tdb);
94                         tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
95                 }
96
97                 tdb_unlock_bystring(tdb, vstring);
98
99                 /* cleanup any map entries with a gid == -1 */
100
101                 if ( enum_group_mapping( NULL, SID_NAME_UNKNOWN, &map_table,
102                                          &num_entries, False ) ) {
103                         int i;
104
105                         for ( i=0; i<num_entries; i++ ) {
106                                 if ( map_table[i].gid == -1 ) {
107                                         group_map_remove( &map_table[i].sid );
108                                 }
109                         }
110
111                         SAFE_FREE( map_table );
112                 }
113 #endif
114         }
115         return true;
116 }
117
118 static char *group_mapping_key(TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
119 {
120         char *sidstr, *result;
121
122         sidstr = sid_string_talloc(talloc_tos(), sid);
123         if (sidstr == NULL) {
124                 return NULL;
125         }
126
127         result = talloc_asprintf(mem_ctx, "%s%s", GROUP_PREFIX, sidstr);
128
129         TALLOC_FREE(sidstr);
130         return result;
131 }
132
133 /****************************************************************************
134 ****************************************************************************/
135 static bool add_mapping_entry(GROUP_MAP *map, int flag)
136 {
137         char *key, *buf;
138         int len;
139         NTSTATUS status;
140
141         key = group_mapping_key(talloc_tos(), &map->sid);
142         if (key == NULL) {
143                 return false;
144         }
145
146         len = tdb_pack(NULL, 0, "ddff",
147                 map->gid, map->sid_name_use, map->nt_name, map->comment);
148
149         buf = talloc_array(key, char, len);
150         if (!buf) {
151                 TALLOC_FREE(key);
152                 return false;
153         }
154         len = tdb_pack((uint8 *)buf, len, "ddff", map->gid,
155                        map->sid_name_use, map->nt_name, map->comment);
156
157         status = dbwrap_trans_store(
158                 db, string_term_tdb_data(key),
159                 make_tdb_data((uint8_t *)buf, len), TDB_REPLACE);
160
161         TALLOC_FREE(key);
162
163         return NT_STATUS_IS_OK(status);
164 }
165
166
167 /****************************************************************************
168  Return the sid and the type of the unix group.
169 ****************************************************************************/
170
171 static bool get_group_map_from_sid(struct dom_sid sid, GROUP_MAP *map)
172 {
173         TDB_DATA dbuf;
174         char *key;
175         int ret = 0;
176
177         /* the key is the SID, retrieving is direct */
178
179         key = group_mapping_key(talloc_tos(), &sid);
180         if (key == NULL) {
181                 return false;
182         }
183
184         dbuf = dbwrap_fetch_bystring(db, key, key);
185         if (dbuf.dptr == NULL) {
186                 TALLOC_FREE(key);
187                 return false;
188         }
189
190         ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
191                         &map->gid, &map->sid_name_use,
192                         &map->nt_name, &map->comment);
193
194         TALLOC_FREE(key);
195
196         if ( ret == -1 ) {
197                 DEBUG(3,("get_group_map_from_sid: tdb_unpack failure\n"));
198                 return false;
199         }
200
201         sid_copy(&map->sid, &sid);
202
203         return true;
204 }
205
206 static bool dbrec2map(const struct db_record *rec, GROUP_MAP *map)
207 {
208         if ((rec->key.dsize < strlen(GROUP_PREFIX))
209             || (strncmp((char *)rec->key.dptr, GROUP_PREFIX,
210                         GROUP_PREFIX_LEN) != 0)) {
211                 return False;
212         }
213
214         if (!string_to_sid(&map->sid, (const char *)rec->key.dptr
215                            + GROUP_PREFIX_LEN)) {
216                 return False;
217         }
218
219         return tdb_unpack(rec->value.dptr, rec->value.dsize, "ddff",
220                           &map->gid, &map->sid_name_use, &map->nt_name,
221                           &map->comment) != -1;
222 }
223
224 struct find_map_state {
225         bool found;
226         const char *name;       /* If != NULL, look for name */
227         gid_t gid;              /* valid iff name == NULL */
228         GROUP_MAP *map;
229 };
230
231 static int find_map(struct db_record *rec, void *private_data)
232 {
233         struct find_map_state *state = (struct find_map_state *)private_data;
234
235         if (!dbrec2map(rec, state->map)) {
236                 DEBUG(10, ("failed to unpack map\n"));
237                 return 0;
238         }
239
240         if (state->name != NULL) {
241                 if (strequal(state->name, state->map->nt_name)) {
242                         state->found = true;
243                         return 1;
244                 }
245         }
246         else {
247                 if (state->map->gid == state->gid) {
248                         state->found = true;
249                         return 1;
250                 }
251         }
252
253         return 0;
254 }
255
256 /****************************************************************************
257  Return the sid and the type of the unix group.
258 ****************************************************************************/
259
260 static bool get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
261 {
262         struct find_map_state state;
263
264         state.found = false;
265         state.name = NULL;      /* Indicate we're looking for gid */
266         state.gid = gid;
267         state.map = map;
268
269         db->traverse_read(db, find_map, (void *)&state);
270
271         return state.found;
272 }
273
274 /****************************************************************************
275  Return the sid and the type of the unix group.
276 ****************************************************************************/
277
278 static bool get_group_map_from_ntname(const char *name, GROUP_MAP *map)
279 {
280         struct find_map_state state;
281
282         state.found = false;
283         state.name = name;
284         state.map = map;
285
286         db->traverse_read(db, find_map, (void *)&state);
287
288         return state.found;
289 }
290
291 /****************************************************************************
292  Remove a group mapping entry.
293 ****************************************************************************/
294
295 static bool group_map_remove(const struct dom_sid *sid)
296 {
297         char *key;
298         NTSTATUS status;
299
300         key = group_mapping_key(talloc_tos(), sid);
301         if (key == NULL) {
302                 return false;
303         }
304
305         status = dbwrap_trans_delete(db, string_term_tdb_data(key));
306
307         TALLOC_FREE(key);
308         return NT_STATUS_IS_OK(status);
309 }
310
311 /****************************************************************************
312  Enumerate the group mapping.
313 ****************************************************************************/
314
315 struct enum_map_state {
316         const struct dom_sid *domsid;
317         enum lsa_SidType sid_name_use;
318         bool unix_only;
319
320         size_t num_maps;
321         GROUP_MAP *maps;
322 };
323
324 static int collect_map(struct db_record *rec, void *private_data)
325 {
326         struct enum_map_state *state = (struct enum_map_state *)private_data;
327         GROUP_MAP map;
328         GROUP_MAP *tmp;
329
330         if (!dbrec2map(rec, &map)) {
331                 return 0;
332         }
333         /* list only the type or everything if UNKNOWN */
334         if (state->sid_name_use != SID_NAME_UNKNOWN
335             && state->sid_name_use != map.sid_name_use) {
336                 DEBUG(11,("enum_group_mapping: group %s is not of the "
337                           "requested type\n", map.nt_name));
338                 return 0;
339         }
340
341         if ((state->unix_only == ENUM_ONLY_MAPPED) && (map.gid == -1)) {
342                 DEBUG(11,("enum_group_mapping: group %s is non mapped\n",
343                           map.nt_name));
344                 return 0;
345         }
346
347         if ((state->domsid != NULL) &&
348             (dom_sid_compare_domain(state->domsid, &map.sid) != 0)) {
349                 DEBUG(11,("enum_group_mapping: group %s is not in domain\n",
350                           sid_string_dbg(&map.sid)));
351                 return 0;
352         }
353
354         if (!(tmp = SMB_REALLOC_ARRAY(state->maps, GROUP_MAP,
355                                       state->num_maps+1))) {
356                 DEBUG(0,("enum_group_mapping: Unable to enlarge group "
357                          "map!\n"));
358                 return 1;
359         }
360
361         state->maps = tmp;
362         state->maps[state->num_maps] = map;
363         state->num_maps++;
364         return 0;
365 }
366
367 static bool enum_group_mapping(const struct dom_sid *domsid,
368                                enum lsa_SidType sid_name_use,
369                                GROUP_MAP **pp_rmap,
370                                size_t *p_num_entries, bool unix_only)
371 {
372         struct enum_map_state state;
373
374         state.domsid = domsid;
375         state.sid_name_use = sid_name_use;
376         state.unix_only = unix_only;
377         state.num_maps = 0;
378         state.maps = NULL;
379
380         if (db->traverse_read(db, collect_map, (void *)&state) < 0) {
381                 return false;
382         }
383
384         *pp_rmap = state.maps;
385         *p_num_entries = state.num_maps;
386
387         return true;
388 }
389
390 /* This operation happens on session setup, so it should better be fast. We
391  * store a list of aliases a SID is member of hanging off MEMBEROF/SID. */
392
393 static NTSTATUS one_alias_membership(const struct dom_sid *member,
394                                struct dom_sid **sids, size_t *num)
395 {
396         fstring tmp;
397         fstring key;
398         char *string_sid;
399         TDB_DATA dbuf;
400         const char *p;
401         NTSTATUS status = NT_STATUS_OK;
402         TALLOC_CTX *frame = talloc_stackframe();
403
404         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX,
405                  sid_to_fstring(tmp, member));
406
407         dbuf = dbwrap_fetch_bystring(db, frame, key);
408         if (dbuf.dptr == NULL) {
409                 TALLOC_FREE(frame);
410                 return NT_STATUS_OK;
411         }
412
413         p = (const char *)dbuf.dptr;
414
415         while (next_token_talloc(frame, &p, &string_sid, " ")) {
416                 struct dom_sid alias;
417                 uint32_t num_sids;
418
419                 if (!string_to_sid(&alias, string_sid))
420                         continue;
421
422                 num_sids = *num;
423                 status= add_sid_to_array_unique(NULL, &alias, sids, &num_sids);
424                 if (!NT_STATUS_IS_OK(status)) {
425                         goto done;
426                 }
427                 *num = num_sids;
428         }
429
430 done:
431         TALLOC_FREE(frame);
432         return status;
433 }
434
435 static NTSTATUS alias_memberships(const struct dom_sid *members, size_t num_members,
436                                   struct dom_sid **sids, size_t *num)
437 {
438         size_t i;
439
440         *num = 0;
441         *sids = NULL;
442
443         for (i=0; i<num_members; i++) {
444                 NTSTATUS status = one_alias_membership(&members[i], sids, num);
445                 if (!NT_STATUS_IS_OK(status))
446                         return status;
447         }
448         return NT_STATUS_OK;
449 }
450
451 static bool is_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
452 {
453         struct dom_sid *sids;
454         size_t i;
455         size_t num;
456
457         /* This feels the wrong way round, but the on-disk data structure
458          * dictates it this way. */
459         if (!NT_STATUS_IS_OK(alias_memberships(member, 1, &sids, &num)))
460                 return False;
461
462         for (i=0; i<num; i++) {
463                 if (dom_sid_compare(alias, &sids[i]) == 0) {
464                         TALLOC_FREE(sids);
465                         return True;
466                 }
467         }
468         TALLOC_FREE(sids);
469         return False;
470 }
471
472
473 static NTSTATUS add_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
474 {
475         GROUP_MAP map;
476         char *key;
477         fstring string_sid;
478         char *new_memberstring;
479         struct db_record *rec;
480         NTSTATUS status;
481
482         if (!get_group_map_from_sid(*alias, &map))
483                 return NT_STATUS_NO_SUCH_ALIAS;
484
485         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
486              (map.sid_name_use != SID_NAME_WKN_GRP) )
487                 return NT_STATUS_NO_SUCH_ALIAS;
488
489         if (is_aliasmem(alias, member))
490                 return NT_STATUS_MEMBER_IN_ALIAS;
491
492         sid_to_fstring(string_sid, member);
493
494         key = talloc_asprintf(talloc_tos(), "%s%s", MEMBEROF_PREFIX,
495                               string_sid);
496         if (key == NULL) {
497                 return NT_STATUS_NO_MEMORY;
498         }
499
500         if (db->transaction_start(db) != 0) {
501                 DEBUG(0, ("transaction_start failed\n"));
502                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
503         }
504
505         rec = db->fetch_locked(db, key, string_term_tdb_data(key));
506
507         if (rec == NULL) {
508                 DEBUG(10, ("fetch_lock failed\n"));
509                 TALLOC_FREE(key);
510                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
511                 goto cancel;
512         }
513
514         sid_to_fstring(string_sid, alias);
515
516         if (rec->value.dptr != NULL) {
517                 new_memberstring = talloc_asprintf(
518                         key, "%s %s", (char *)(rec->value.dptr), string_sid);
519         } else {
520                 new_memberstring = talloc_strdup(key, string_sid);
521         }
522
523         if (new_memberstring == NULL) {
524                 TALLOC_FREE(key);
525                 status = NT_STATUS_NO_MEMORY;
526                 goto cancel;
527         }
528
529         status = rec->store(rec, string_term_tdb_data(new_memberstring), 0);
530
531         TALLOC_FREE(key);
532
533         if (!NT_STATUS_IS_OK(status)) {
534                 DEBUG(10, ("Could not store record: %s\n", nt_errstr(status)));
535                 goto cancel;
536         }
537
538         if (db->transaction_commit(db) != 0) {
539                 DEBUG(0, ("transaction_commit failed\n"));
540                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
541                 return status;
542         }
543
544         return NT_STATUS_OK;
545
546  cancel:
547         if (db->transaction_cancel(db) != 0) {
548                 smb_panic("transaction_cancel failed");
549         }
550
551         return status;
552 }
553
554 struct aliasmem_state {
555         TALLOC_CTX *mem_ctx;
556         const struct dom_sid *alias;
557         struct dom_sid **sids;
558         size_t *num;
559 };
560
561 static int collect_aliasmem(struct db_record *rec, void *priv)
562 {
563         struct aliasmem_state *state = (struct aliasmem_state *)priv;
564         const char *p;
565         char *alias_string;
566         TALLOC_CTX *frame;
567
568         if (strncmp((const char *)rec->key.dptr, MEMBEROF_PREFIX,
569                     MEMBEROF_PREFIX_LEN) != 0)
570                 return 0;
571
572         p = (const char *)rec->value.dptr;
573
574         frame = talloc_stackframe();
575
576         while (next_token_talloc(frame, &p, &alias_string, " ")) {
577                 struct dom_sid alias, member;
578                 const char *member_string;
579                 uint32_t num_sids;
580
581                 if (!string_to_sid(&alias, alias_string))
582                         continue;
583
584                 if (dom_sid_compare(state->alias, &alias) != 0)
585                         continue;
586
587                 /* Ok, we found the alias we're looking for in the membership
588                  * list currently scanned. The key represents the alias
589                  * member. Add that. */
590
591                 member_string = strchr((const char *)rec->key.dptr, '/');
592
593                 /* Above we tested for MEMBEROF_PREFIX which includes the
594                  * slash. */
595
596                 SMB_ASSERT(member_string != NULL);
597                 member_string += 1;
598
599                 if (!string_to_sid(&member, member_string))
600                         continue;
601
602                 num_sids = *state->num;
603                 if (!NT_STATUS_IS_OK(add_sid_to_array(state->mem_ctx, &member,
604                                                       state->sids,
605                                                       &num_sids)))
606                 {
607                         /* talloc fail. */
608                         break;
609                 }
610                 *state->num = num_sids;
611         }
612
613         TALLOC_FREE(frame);
614         return 0;
615 }
616
617 static NTSTATUS enum_aliasmem(const struct dom_sid *alias, TALLOC_CTX *mem_ctx,
618                               struct dom_sid **sids, size_t *num)
619 {
620         GROUP_MAP map;
621         struct aliasmem_state state;
622
623         if (!get_group_map_from_sid(*alias, &map))
624                 return NT_STATUS_NO_SUCH_ALIAS;
625
626         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
627              (map.sid_name_use != SID_NAME_WKN_GRP) )
628                 return NT_STATUS_NO_SUCH_ALIAS;
629
630         *sids = NULL;
631         *num = 0;
632
633         state.alias = alias;
634         state.sids = sids;
635         state.num = num;
636         state.mem_ctx = mem_ctx;
637
638         db->traverse_read(db, collect_aliasmem, &state);
639         return NT_STATUS_OK;
640 }
641
642 static NTSTATUS del_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
643 {
644         NTSTATUS status;
645         struct dom_sid *sids;
646         size_t i, num;
647         bool found = False;
648         char *member_string;
649         char *key;
650         fstring sid_string;
651
652         if (db->transaction_start(db) != 0) {
653                 DEBUG(0, ("transaction_start failed\n"));
654                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
655         }
656
657         status = alias_memberships(member, 1, &sids, &num);
658
659         if (!NT_STATUS_IS_OK(status)) {
660                 goto cancel;
661         }
662
663         for (i=0; i<num; i++) {
664                 if (dom_sid_compare(&sids[i], alias) == 0) {
665                         found = True;
666                         break;
667                 }
668         }
669
670         if (!found) {
671                 TALLOC_FREE(sids);
672                 status = NT_STATUS_MEMBER_NOT_IN_ALIAS;
673                 goto cancel;
674         }
675
676         if (i < num)
677                 sids[i] = sids[num-1];
678
679         num -= 1;
680
681         sid_to_fstring(sid_string, member);
682
683         key = talloc_asprintf(sids, "%s%s", MEMBEROF_PREFIX, sid_string);
684         if (key == NULL) {
685                 TALLOC_FREE(sids);
686                 status = NT_STATUS_NO_MEMORY;
687                 goto cancel;
688         }
689
690         if (num == 0) {
691                 status = dbwrap_delete_bystring(db, key);
692                 goto commit;
693         }
694
695         member_string = talloc_strdup(sids, "");
696         if (member_string == NULL) {
697                 TALLOC_FREE(sids);
698                 status = NT_STATUS_NO_MEMORY;
699                 goto cancel;
700         }
701
702         for (i=0; i<num; i++) {
703
704                 sid_to_fstring(sid_string, &sids[i]);
705
706                 member_string = talloc_asprintf_append_buffer(
707                         member_string, " %s", sid_string);
708
709                 if (member_string == NULL) {
710                         TALLOC_FREE(sids);
711                         status = NT_STATUS_NO_MEMORY;
712                         goto cancel;
713                 }
714         }
715
716         status = dbwrap_store_bystring(
717                 db, key, string_term_tdb_data(member_string), 0);
718  commit:
719         TALLOC_FREE(sids);
720
721         if (!NT_STATUS_IS_OK(status)) {
722                 DEBUG(10, ("dbwrap_store_bystring failed: %s\n",
723                            nt_errstr(status)));
724                 goto cancel;
725         }
726
727         if (db->transaction_commit(db) != 0) {
728                 DEBUG(0, ("transaction_commit failed\n"));
729                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
730                 return status;
731         }
732
733         return NT_STATUS_OK;
734
735  cancel:
736         if (db->transaction_cancel(db) != 0) {
737                 smb_panic("transaction_cancel failed");
738         }
739         return status;
740 }
741
742
743 /* -- ldb->tdb switching code -------------------------------------------- */
744
745 /* change this if the data format ever changes */
746 #define LTDB_PACKING_FORMAT 0x26011967
747
748 /* old packing formats (not supported for now,
749  * it was never used for group mapping AFAIK) */
750 #define LTDB_PACKING_FORMAT_NODN 0x26011966
751
752 static unsigned int pull_uint32(uint8_t *p, int ofs)
753 {
754         p += ofs;
755         return p[0] | (p[1]<<8) | (p[2]<<16) | (p[3]<<24);
756 }
757
758 /*
759   unpack a ldb message from a linear buffer in TDB_DATA
760 */
761 static int convert_ldb_record(TDB_CONTEXT *ltdb, TDB_DATA key,
762                               TDB_DATA data, void *ptr)
763 {
764         TALLOC_CTX *tmp_ctx = talloc_tos();
765         GROUP_MAP map;
766         uint8_t *p;
767         uint32_t format;
768         uint32_t num_el;
769         unsigned int remaining;
770         unsigned int i, j;
771         size_t len;
772         char *name;
773         char *val;
774         char *q;
775         uint32_t num_mem = 0;
776         struct dom_sid *members = NULL;
777
778         p = (uint8_t *)data.dptr;
779         if (data.dsize < 8) {
780                 errno = EIO;
781                 goto failed;
782         }
783
784         format = pull_uint32(p, 0);
785         num_el = pull_uint32(p, 4);
786         p += 8;
787
788         remaining = data.dsize - 8;
789
790         switch (format) {
791         case LTDB_PACKING_FORMAT:
792                 len = strnlen((char *)p, remaining);
793                 if (len == remaining) {
794                         errno = EIO;
795                         goto failed;
796                 }
797
798                 if (*p == '@') {
799                         /* ignore special LDB attributes */
800                         return 0;
801                 }
802
803                 if (strncmp((char *)p, "rid=", 4)) {
804                         /* unknown entry, ignore */
805                         DEBUG(3, ("Found unknown entry in group mapping "
806                                   "database named [%s]\n", (char *)p));
807                         return 0;
808                 }
809
810                 remaining -= len + 1;
811                 p += len + 1;
812                 break;
813
814         case LTDB_PACKING_FORMAT_NODN:
815         default:
816                 errno = EIO;
817                 goto failed;
818         }
819
820         if (num_el == 0) {
821                 /* bad entry, ignore */
822                 return 0;
823         }
824
825         if (num_el > remaining / 6) {
826                 errno = EIO;
827                 goto failed;
828         }
829
830         ZERO_STRUCT(map);
831
832         for (i = 0; i < num_el; i++) {
833                 uint32_t num_vals;
834
835                 if (remaining < 10) {
836                         errno = EIO;
837                         goto failed;
838                 }
839                 len = strnlen((char *)p, remaining - 6);
840                 if (len == remaining - 6) {
841                         errno = EIO;
842                         goto failed;
843                 }
844                 name = talloc_strndup(tmp_ctx, (char *)p, len);
845                 if (name == NULL) {
846                         errno = ENOMEM;
847                         goto failed;
848                 }
849                 remaining -= len + 1;
850                 p += len + 1;
851
852                 num_vals = pull_uint32(p, 0);
853                 if (strcasecmp_m(name, "member") == 0) {
854                         num_mem = num_vals;
855                         members = talloc_array(tmp_ctx, struct dom_sid, num_mem);
856                         if (members == NULL) {
857                                 errno = ENOMEM;
858                                 goto failed;
859                         }
860                 } else if (num_vals != 1) {
861                         errno = EIO;
862                         goto failed;
863                 }
864
865                 p += 4;
866                 remaining -= 4;
867
868                 for (j = 0; j < num_vals; j++) {
869                         len = pull_uint32(p, 0);
870                         if (len > remaining-5) {
871                                 errno = EIO;
872                                 goto failed;
873                         }
874
875                         val = talloc_strndup(tmp_ctx, (char *)(p + 4), len);
876                         if (val == NULL) {
877                                 errno = ENOMEM;
878                                 goto failed;
879                         }
880
881                         remaining -= len+4+1;
882                         p += len+4+1;
883
884                         /* we ignore unknown or uninteresting attributes
885                          * (objectclass, etc.) */
886                         if (strcasecmp_m(name, "gidNumber") == 0) {
887                                 map.gid = strtoul(val, &q, 10);
888                                 if (*q) {
889                                         errno = EIO;
890                                         goto failed;
891                                 }
892                         } else if (strcasecmp_m(name, "sid") == 0) {
893                                 if (!string_to_sid(&map.sid, val)) {
894                                         errno = EIO;
895                                         goto failed;
896                                 }
897                         } else if (strcasecmp_m(name, "sidNameUse") == 0) {
898                                 map.sid_name_use = strtoul(val, &q, 10);
899                                 if (*q) {
900                                         errno = EIO;
901                                         goto failed;
902                                 }
903                         } else if (strcasecmp_m(name, "ntname") == 0) {
904                                 strlcpy(map.nt_name, val,
905                                         sizeof(map.nt_name));
906                         } else if (strcasecmp_m(name, "comment") == 0) {
907                                 strlcpy(map.comment, val,
908                                         sizeof(map.comment));
909                         } else if (strcasecmp_m(name, "member") == 0) {
910                                 if (!string_to_sid(&members[j], val)) {
911                                         errno = EIO;
912                                         goto failed;
913                                 }
914                         }
915
916                         TALLOC_FREE(val);
917                 }
918
919                 TALLOC_FREE(name);
920         }
921
922         if (!add_mapping_entry(&map, 0)) {
923                 errno = EIO;
924                 goto failed;
925         }
926
927         if (num_mem) {
928                 for (j = 0; j < num_mem; j++) {
929                         NTSTATUS status;
930                         status = add_aliasmem(&map.sid, &members[j]);
931                         if (!NT_STATUS_IS_OK(status)) {
932                                 errno = EIO;
933                                 goto failed;
934                         }
935                 }
936         }
937
938         if (remaining != 0) {
939                 DEBUG(0, ("Errror: %d bytes unread in ltdb_unpack_data\n",
940                           remaining));
941         }
942
943         return 0;
944
945 failed:
946         return -1;
947 }
948
949 static bool mapping_switch(const char *ldb_path)
950 {
951         TDB_CONTEXT *ltdb;
952         TALLOC_CTX *frame;
953         char *new_path;
954         int ret;
955
956         frame = talloc_stackframe();
957
958         ltdb = tdb_open_log(ldb_path, 0, TDB_DEFAULT, O_RDONLY, 0600);
959         if (ltdb == NULL) goto failed;
960
961         /* ldb is just a very fancy tdb, read out raw data and perform
962          * conversion */
963         ret = tdb_traverse(ltdb, convert_ldb_record, NULL);
964         if (ret < 0) goto failed;
965
966         if (ltdb) {
967                 tdb_close(ltdb);
968                 ltdb = NULL;
969         }
970
971         /* now rename the old db out of the way */
972         new_path = state_path("group_mapping.ldb.replaced");
973         if (!new_path) {
974                 goto failed;
975         }
976         if (rename(ldb_path, new_path) != 0) {
977                 DEBUG(0,("Failed to rename old group mapping database\n"));
978                 goto failed;
979         }
980         TALLOC_FREE(frame);
981         return True;
982
983 failed:
984         DEBUG(0, ("Failed to switch to tdb group mapping database\n"));
985         if (ltdb) tdb_close(ltdb);
986         TALLOC_FREE(frame);
987         return False;
988 }
989
990 static const struct mapping_backend tdb_backend = {
991         .add_mapping_entry         = add_mapping_entry,
992         .get_group_map_from_sid    = get_group_map_from_sid,
993         .get_group_map_from_gid    = get_group_map_from_gid,
994         .get_group_map_from_ntname = get_group_map_from_ntname,
995         .group_map_remove          = group_map_remove,
996         .enum_group_mapping        = enum_group_mapping,
997         .one_alias_membership      = one_alias_membership,
998         .add_aliasmem              = add_aliasmem,
999         .del_aliasmem              = del_aliasmem,
1000         .enum_aliasmem             = enum_aliasmem      
1001 };
1002
1003 /*
1004   initialise the tdb mapping backend
1005  */
1006 const struct mapping_backend *groupdb_tdb_init(void)
1007 {
1008         if (!init_group_mapping()) {
1009                 DEBUG(0,("Failed to initialise tdb mapping backend\n"));
1010                 return NULL;
1011         }
1012
1013         return &tdb_backend;
1014 }