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