passdb: Use dom_sid_str_buf
[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         struct dom_sid_buf 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                  dom_sid_str_buf(member, &tmp));
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         struct dom_sid_buf 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         key = talloc_asprintf(talloc_tos(), "%s%s", MEMBEROF_PREFIX,
563                               dom_sid_str_buf(member, &string_sid));
564         if (key == NULL) {
565                 return NT_STATUS_NO_MEMORY;
566         }
567
568         if (dbwrap_transaction_start(db) != 0) {
569                 DEBUG(0, ("transaction_start failed\n"));
570                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
571         }
572
573         rec = dbwrap_fetch_locked(db, key, string_term_tdb_data(key));
574
575         if (rec == NULL) {
576                 DEBUG(10, ("fetch_lock failed\n"));
577                 TALLOC_FREE(key);
578                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
579                 goto cancel;
580         }
581
582         value = dbwrap_record_get_value(rec);
583
584         dom_sid_str_buf(alias, &string_sid);
585
586         if (value.dptr != NULL) {
587                 new_memberstring = talloc_asprintf(
588                         key, "%s %s", (char *)(value.dptr), string_sid.buf);
589         } else {
590                 new_memberstring = talloc_strdup(key, string_sid.buf);
591         }
592
593         if (new_memberstring == NULL) {
594                 TALLOC_FREE(key);
595                 status = NT_STATUS_NO_MEMORY;
596                 goto cancel;
597         }
598
599         status = dbwrap_record_store(rec, string_term_tdb_data(new_memberstring), 0);
600
601         TALLOC_FREE(key);
602
603         if (!NT_STATUS_IS_OK(status)) {
604                 DEBUG(10, ("Could not store record: %s\n", nt_errstr(status)));
605                 goto cancel;
606         }
607
608         if (dbwrap_transaction_commit(db) != 0) {
609                 DEBUG(0, ("transaction_commit failed\n"));
610                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
611                 return status;
612         }
613
614         return NT_STATUS_OK;
615
616  cancel:
617         if (dbwrap_transaction_cancel(db) != 0) {
618                 smb_panic("transaction_cancel failed");
619         }
620
621         return status;
622 }
623
624 struct aliasmem_state {
625         TALLOC_CTX *mem_ctx;
626         const struct dom_sid *alias;
627         struct dom_sid **sids;
628         size_t *num;
629 };
630
631 static int collect_aliasmem(struct db_record *rec, void *priv)
632 {
633         struct aliasmem_state *state = (struct aliasmem_state *)priv;
634         const char *p;
635         char *alias_string;
636         TALLOC_CTX *frame;
637         TDB_DATA key = dbwrap_record_get_key(rec);
638         TDB_DATA value = dbwrap_record_get_value(rec);
639
640         if (strncmp((const char *)key.dptr, MEMBEROF_PREFIX,
641                     MEMBEROF_PREFIX_LEN) != 0)
642                 return 0;
643
644         p = (const char *)value.dptr;
645
646         frame = talloc_stackframe();
647
648         while (next_token_talloc(frame, &p, &alias_string, " ")) {
649                 struct dom_sid alias, member;
650                 const char *member_string;
651                 uint32_t num_sids;
652
653                 if (!string_to_sid(&alias, alias_string))
654                         continue;
655
656                 if (dom_sid_compare(state->alias, &alias) != 0)
657                         continue;
658
659                 /* Ok, we found the alias we're looking for in the membership
660                  * list currently scanned. The key represents the alias
661                  * member. Add that. */
662
663                 member_string = strchr((const char *)key.dptr, '/');
664
665                 /* Above we tested for MEMBEROF_PREFIX which includes the
666                  * slash. */
667
668                 SMB_ASSERT(member_string != NULL);
669                 member_string += 1;
670
671                 if (!string_to_sid(&member, member_string))
672                         continue;
673
674                 num_sids = *state->num;
675                 if (!NT_STATUS_IS_OK(add_sid_to_array(state->mem_ctx, &member,
676                                                       state->sids,
677                                                       &num_sids)))
678                 {
679                         /* talloc fail. */
680                         break;
681                 }
682                 *state->num = num_sids;
683         }
684
685         TALLOC_FREE(frame);
686         return 0;
687 }
688
689 static NTSTATUS enum_aliasmem(const struct dom_sid *alias, TALLOC_CTX *mem_ctx,
690                               struct dom_sid **sids, size_t *num)
691 {
692         GROUP_MAP *map;
693         struct aliasmem_state state;
694
695         map = talloc_zero(talloc_tos(), GROUP_MAP);
696         if (!map) {
697                 return NT_STATUS_NO_MEMORY;
698         }
699
700         if (!get_group_map_from_sid(*alias, map)) {
701                 TALLOC_FREE(map);
702                 return NT_STATUS_NO_SUCH_ALIAS;
703         }
704
705         if ((map->sid_name_use != SID_NAME_ALIAS) &&
706             (map->sid_name_use != SID_NAME_WKN_GRP)) {
707                 TALLOC_FREE(map);
708                 return NT_STATUS_NO_SUCH_ALIAS;
709         }
710
711         TALLOC_FREE(map);
712
713         *sids = NULL;
714         *num = 0;
715
716         state.alias = alias;
717         state.sids = sids;
718         state.num = num;
719         state.mem_ctx = mem_ctx;
720
721         dbwrap_traverse_read(db, collect_aliasmem, &state, NULL);
722         return NT_STATUS_OK;
723 }
724
725 static NTSTATUS del_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
726 {
727         NTSTATUS status;
728         struct dom_sid *sids;
729         size_t i, num;
730         bool found = False;
731         char *member_string;
732         char *key;
733         struct dom_sid_buf sid_string;
734
735         if (dbwrap_transaction_start(db) != 0) {
736                 DEBUG(0, ("transaction_start failed\n"));
737                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
738         }
739
740         status = alias_memberships(member, 1, &sids, &num);
741
742         if (!NT_STATUS_IS_OK(status)) {
743                 goto cancel;
744         }
745
746         for (i=0; i<num; i++) {
747                 if (dom_sid_compare(&sids[i], alias) == 0) {
748                         found = True;
749                         break;
750                 }
751         }
752
753         if (!found) {
754                 TALLOC_FREE(sids);
755                 status = NT_STATUS_MEMBER_NOT_IN_ALIAS;
756                 goto cancel;
757         }
758
759         if (i < num)
760                 sids[i] = sids[num-1];
761
762         num -= 1;
763
764         key = talloc_asprintf(
765                 sids,
766                 "%s%s",
767                 MEMBEROF_PREFIX,
768                 dom_sid_str_buf(member, &sid_string));
769         if (key == NULL) {
770                 TALLOC_FREE(sids);
771                 status = NT_STATUS_NO_MEMORY;
772                 goto cancel;
773         }
774
775         if (num == 0) {
776                 status = dbwrap_delete_bystring(db, key);
777                 goto commit;
778         }
779
780         member_string = talloc_strdup(sids, "");
781         if (member_string == NULL) {
782                 TALLOC_FREE(sids);
783                 status = NT_STATUS_NO_MEMORY;
784                 goto cancel;
785         }
786
787         for (i=0; i<num; i++) {
788
789                 member_string = talloc_asprintf_append_buffer(
790                         member_string,
791                         " %s",
792                         dom_sid_str_buf(&sids[i], &sid_string));
793
794                 if (member_string == NULL) {
795                         TALLOC_FREE(sids);
796                         status = NT_STATUS_NO_MEMORY;
797                         goto cancel;
798                 }
799         }
800
801         status = dbwrap_store_bystring(
802                 db, key, string_term_tdb_data(member_string), 0);
803  commit:
804         TALLOC_FREE(sids);
805
806         if (!NT_STATUS_IS_OK(status)) {
807                 DEBUG(10, ("dbwrap_store_bystring failed: %s\n",
808                            nt_errstr(status)));
809                 goto cancel;
810         }
811
812         if (dbwrap_transaction_commit(db) != 0) {
813                 DEBUG(0, ("transaction_commit failed\n"));
814                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
815                 return status;
816         }
817
818         return NT_STATUS_OK;
819
820  cancel:
821         if (dbwrap_transaction_cancel(db) != 0) {
822                 smb_panic("transaction_cancel failed");
823         }
824         return status;
825 }
826
827
828 /* -- ldb->tdb switching code -------------------------------------------- */
829
830 /* change this if the data format ever changes */
831 #define LTDB_PACKING_FORMAT 0x26011967
832
833 /* old packing formats (not supported for now,
834  * it was never used for group mapping AFAIK) */
835 #define LTDB_PACKING_FORMAT_NODN 0x26011966
836
837 static unsigned int pull_uint32(uint8_t *p, int ofs)
838 {
839         p += ofs;
840         return p[0] | (p[1]<<8) | (p[2]<<16) | (p[3]<<24);
841 }
842
843 /*
844   unpack a ldb message from a linear buffer in TDB_DATA
845 */
846 static int convert_ldb_record(TDB_CONTEXT *ltdb, TDB_DATA key,
847                               TDB_DATA data, void *ptr)
848 {
849         TALLOC_CTX *tmp_ctx = talloc_tos();
850         GROUP_MAP *map = NULL;
851         uint8_t *p;
852         uint32_t format;
853         uint32_t num_el;
854         unsigned int remaining;
855         unsigned int i, j;
856         size_t len;
857         char *name;
858         char *val;
859         char *q;
860         uint32_t num_mem = 0;
861         struct dom_sid *members = NULL;
862
863         p = (uint8_t *)data.dptr;
864         if (data.dsize < 8) {
865                 errno = EIO;
866                 goto failed;
867         }
868
869         format = pull_uint32(p, 0);
870         num_el = pull_uint32(p, 4);
871         p += 8;
872
873         remaining = data.dsize - 8;
874
875         switch (format) {
876         case LTDB_PACKING_FORMAT:
877                 len = strnlen((char *)p, remaining);
878                 if (len == remaining) {
879                         errno = EIO;
880                         goto failed;
881                 }
882
883                 if (*p == '@') {
884                         /* ignore special LDB attributes */
885                         return 0;
886                 }
887
888                 if (strncmp((char *)p, "rid=", 4)) {
889                         /* unknown entry, ignore */
890                         DEBUG(3, ("Found unknown entry in group mapping "
891                                   "database named [%s]\n", (char *)p));
892                         return 0;
893                 }
894
895                 remaining -= len + 1;
896                 p += len + 1;
897                 break;
898
899         case LTDB_PACKING_FORMAT_NODN:
900         default:
901                 errno = EIO;
902                 goto failed;
903         }
904
905         if (num_el == 0) {
906                 /* bad entry, ignore */
907                 return 0;
908         }
909
910         if (num_el > remaining / 6) {
911                 errno = EIO;
912                 goto failed;
913         }
914
915         map = talloc_zero(NULL, GROUP_MAP);
916         if (!map) {
917                 errno = ENOMEM;
918                 goto failed;
919         }
920
921         for (i = 0; i < num_el; i++) {
922                 uint32_t num_vals;
923
924                 if (remaining < 10) {
925                         errno = EIO;
926                         goto failed;
927                 }
928                 len = strnlen((char *)p, remaining - 6);
929                 if (len == remaining - 6) {
930                         errno = EIO;
931                         goto failed;
932                 }
933                 name = talloc_strndup(tmp_ctx, (char *)p, len);
934                 if (name == NULL) {
935                         errno = ENOMEM;
936                         goto failed;
937                 }
938                 remaining -= len + 1;
939                 p += len + 1;
940
941                 num_vals = pull_uint32(p, 0);
942                 if (strcasecmp_m(name, "member") == 0) {
943                         num_mem = num_vals;
944                         members = talloc_array(tmp_ctx, struct dom_sid, num_mem);
945                         if (members == NULL) {
946                                 errno = ENOMEM;
947                                 goto failed;
948                         }
949                 } else if (num_vals != 1) {
950                         errno = EIO;
951                         goto failed;
952                 }
953
954                 p += 4;
955                 remaining -= 4;
956
957                 for (j = 0; j < num_vals; j++) {
958                         len = pull_uint32(p, 0);
959                         if (len > remaining-5) {
960                                 errno = EIO;
961                                 goto failed;
962                         }
963
964                         val = talloc_strndup(tmp_ctx, (char *)(p + 4), len);
965                         if (val == NULL) {
966                                 errno = ENOMEM;
967                                 goto failed;
968                         }
969
970                         remaining -= len+4+1;
971                         p += len+4+1;
972
973                         /* we ignore unknown or uninteresting attributes
974                          * (objectclass, etc.) */
975                         if (strcasecmp_m(name, "gidNumber") == 0) {
976                                 map->gid = strtoul(val, &q, 10);
977                                 if (*q) {
978                                         errno = EIO;
979                                         goto failed;
980                                 }
981                         } else if (strcasecmp_m(name, "sid") == 0) {
982                                 if (!string_to_sid(&map->sid, val)) {
983                                         errno = EIO;
984                                         goto failed;
985                                 }
986                         } else if (strcasecmp_m(name, "sidNameUse") == 0) {
987                                 map->sid_name_use = strtoul(val, &q, 10);
988                                 if (*q) {
989                                         errno = EIO;
990                                         goto failed;
991                                 }
992                         } else if (strcasecmp_m(name, "ntname") == 0) {
993                                 map->nt_name = talloc_strdup(map, val);
994                                 if (!map->nt_name) {
995                                         errno = ENOMEM;
996                                         goto failed;
997                                 }
998                         } else if (strcasecmp_m(name, "comment") == 0) {
999                                 map->comment = talloc_strdup(map, val);
1000                                 if (!map->comment) {
1001                                         errno = ENOMEM;
1002                                         goto failed;
1003                                 }
1004                         } else if (strcasecmp_m(name, "member") == 0) {
1005                                 if (!string_to_sid(&members[j], val)) {
1006                                         errno = EIO;
1007                                         goto failed;
1008                                 }
1009                         }
1010
1011                         TALLOC_FREE(val);
1012                 }
1013
1014                 TALLOC_FREE(name);
1015         }
1016
1017         if (map->nt_name == NULL) {
1018                 errno = EIO;
1019                 goto failed;
1020         }
1021
1022         if (map->comment == NULL) {
1023                 map->comment = talloc_strdup(map, "");
1024         }
1025         if (map->comment == NULL) {
1026                 errno = ENOMEM;
1027                 goto failed;
1028         }
1029
1030         if (!add_mapping_entry(map, 0)) {
1031                 errno = EIO;
1032                 goto failed;
1033         }
1034
1035         if (num_mem) {
1036                 for (j = 0; j < num_mem; j++) {
1037                         NTSTATUS status;
1038                         status = add_aliasmem(&map->sid, &members[j]);
1039                         if (!NT_STATUS_IS_OK(status)) {
1040                                 errno = EIO;
1041                                 goto failed;
1042                         }
1043                 }
1044         }
1045
1046         if (remaining != 0) {
1047                 DEBUG(0, ("Error: %d bytes unread in ltdb_unpack_data\n",
1048                           remaining));
1049         }
1050
1051         TALLOC_FREE(map);
1052         return 0;
1053
1054 failed:
1055         TALLOC_FREE(map);
1056         return -1;
1057 }
1058
1059 static bool mapping_switch(const char *ldb_path)
1060 {
1061         TDB_CONTEXT *ltdb;
1062         TALLOC_CTX *frame;
1063         char *new_path;
1064         int ret;
1065
1066         frame = talloc_stackframe();
1067
1068         ltdb = tdb_open_log(ldb_path, 0, TDB_DEFAULT, O_RDONLY, 0600);
1069         if (ltdb == NULL) goto failed;
1070
1071         /* ldb is just a very fancy tdb, read out raw data and perform
1072          * conversion */
1073         ret = tdb_traverse(ltdb, convert_ldb_record, NULL);
1074         if (ret < 0) goto failed;
1075
1076         if (ltdb) {
1077                 tdb_close(ltdb);
1078                 ltdb = NULL;
1079         }
1080
1081         /* now rename the old db out of the way */
1082         new_path = state_path(talloc_tos(), "group_mapping.ldb.replaced");
1083         if (!new_path) {
1084                 goto failed;
1085         }
1086         if (rename(ldb_path, new_path) != 0) {
1087                 DEBUG(0,("Failed to rename old group mapping database\n"));
1088                 goto failed;
1089         }
1090         TALLOC_FREE(frame);
1091         return True;
1092
1093 failed:
1094         DEBUG(0, ("Failed to switch to tdb group mapping database\n"));
1095         if (ltdb) tdb_close(ltdb);
1096         TALLOC_FREE(frame);
1097         return False;
1098 }
1099
1100 static const struct mapping_backend tdb_backend = {
1101         .add_mapping_entry         = add_mapping_entry,
1102         .get_group_map_from_sid    = get_group_map_from_sid,
1103         .get_group_map_from_gid    = get_group_map_from_gid,
1104         .get_group_map_from_ntname = get_group_map_from_ntname,
1105         .group_map_remove          = group_map_remove,
1106         .enum_group_mapping        = enum_group_mapping,
1107         .one_alias_membership      = one_alias_membership,
1108         .add_aliasmem              = add_aliasmem,
1109         .del_aliasmem              = del_aliasmem,
1110         .enum_aliasmem             = enum_aliasmem      
1111 };
1112
1113 /*
1114   initialise the tdb mapping backend
1115  */
1116 const struct mapping_backend *groupdb_tdb_init(void)
1117 {
1118         if (!init_group_mapping()) {
1119                 DEBUG(0,("Failed to initialise tdb mapping backend\n"));
1120                 return NULL;
1121         }
1122
1123         return &tdb_backend;
1124 }