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