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