r12438: Remove an unused function
[metze/samba/wip.git] / source3 / groupdb / mapping.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-2000,
5  *  Copyright (C) Jean François Micouleau      1998-2001.
6  *  
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *  
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *  
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21
22 #include "includes.h"
23
24 static TDB_CONTEXT *tdb; /* used for driver files */
25
26 #define DATABASE_VERSION_V1 1 /* native byte format. */
27 #define DATABASE_VERSION_V2 2 /* le format. */
28
29 #define GROUP_PREFIX "UNIXGROUP/"
30
31 /* Alias memberships are stored reverse, as memberships. The performance
32  * critical operation is to determine the aliases a SID is member of, not
33  * listing alias members. So we store a list of alias SIDs a SID is member of
34  * hanging of the member as key.
35  */
36 #define MEMBEROF_PREFIX "MEMBEROF/"
37
38 /****************************************************************************
39 initialise first time the mapping list - called from init_group_mapping()
40 ****************************************************************************/
41 static BOOL default_group_mapping(void)
42 {
43         DOM_SID sid_admins;
44         DOM_SID sid_users;
45         DOM_SID sid_guests;
46         fstring str_admins;
47         fstring str_users;
48         fstring str_guests;
49
50         /* Add the Wellknown groups */
51
52         add_initial_entry(-1, "S-1-5-32-544", SID_NAME_WKN_GRP, "Administrators", "");
53         add_initial_entry(-1, "S-1-5-32-545", SID_NAME_WKN_GRP, "Users", "");
54         add_initial_entry(-1, "S-1-5-32-546", SID_NAME_WKN_GRP, "Guests", "");
55         add_initial_entry(-1, "S-1-5-32-547", SID_NAME_WKN_GRP, "Power Users", "");
56         add_initial_entry(-1, "S-1-5-32-548", SID_NAME_WKN_GRP, "Account Operators", "");
57         add_initial_entry(-1, "S-1-5-32-549", SID_NAME_WKN_GRP, "System Operators", "");
58         add_initial_entry(-1, "S-1-5-32-550", SID_NAME_WKN_GRP, "Print Operators", "");
59         add_initial_entry(-1, "S-1-5-32-551", SID_NAME_WKN_GRP, "Backup Operators", "");
60         add_initial_entry(-1, "S-1-5-32-552", SID_NAME_WKN_GRP, "Replicators", "");
61
62         /* Add the defaults domain groups */
63
64         sid_copy(&sid_admins, get_global_sam_sid());
65         sid_append_rid(&sid_admins, DOMAIN_GROUP_RID_ADMINS);
66         sid_to_string(str_admins, &sid_admins);
67         add_initial_entry(-1, str_admins, SID_NAME_DOM_GRP, "Domain Admins", "");
68
69         sid_copy(&sid_users,  get_global_sam_sid());
70         sid_append_rid(&sid_users,  DOMAIN_GROUP_RID_USERS);
71         sid_to_string(str_users, &sid_users);
72         add_initial_entry(-1, str_users,  SID_NAME_DOM_GRP, "Domain Users",  "");
73
74         sid_copy(&sid_guests, get_global_sam_sid());
75         sid_append_rid(&sid_guests, DOMAIN_GROUP_RID_GUESTS);
76         sid_to_string(str_guests, &sid_guests);
77         add_initial_entry(-1, str_guests, SID_NAME_DOM_GRP, "Domain Guests", "");
78
79         return True;
80 }
81
82 /****************************************************************************
83  Open the group mapping tdb.
84 ****************************************************************************/
85
86 static BOOL init_group_mapping(void)
87 {
88         const char *vstring = "INFO/version";
89         int32 vers_id;
90         
91         if (tdb)
92                 return True;
93         tdb = tdb_open_log(lock_path("group_mapping.tdb"), 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
94         if (!tdb) {
95                 DEBUG(0,("Failed to open group mapping database\n"));
96                 return False;
97         }
98
99         /* handle a Samba upgrade */
100         tdb_lock_bystring(tdb, vstring, 0);
101
102         /* Cope with byte-reversed older versions of the db. */
103         vers_id = tdb_fetch_int32(tdb, vstring);
104         if ((vers_id == DATABASE_VERSION_V1) || (IREV(vers_id) == DATABASE_VERSION_V1)) {
105                 /* Written on a bigendian machine with old fetch_int code. Save as le. */
106                 tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
107                 vers_id = DATABASE_VERSION_V2;
108         }
109
110         if (vers_id != DATABASE_VERSION_V2) {
111                 tdb_traverse(tdb, tdb_traverse_delete_fn, NULL);
112                 tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
113         }
114
115         tdb_unlock_bystring(tdb, vstring);
116
117         /* write a list of default groups */
118         if(!default_group_mapping())
119                 return False;
120
121         return True;
122 }
123
124 /****************************************************************************
125 ****************************************************************************/
126 static BOOL add_mapping_entry(GROUP_MAP *map, int flag)
127 {
128         TDB_DATA kbuf, dbuf;
129         pstring key, buf;
130         fstring string_sid="";
131         int len;
132
133         if(!init_group_mapping()) {
134                 DEBUG(0,("failed to initialize group mapping\n"));
135                 return(False);
136         }
137         
138         sid_to_string(string_sid, &map->sid);
139
140         len = tdb_pack(buf, sizeof(buf), "ddff",
141                         map->gid, map->sid_name_use, map->nt_name, map->comment);
142
143         if (len > sizeof(buf))
144                 return False;
145
146         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
147
148         kbuf.dsize = strlen(key)+1;
149         kbuf.dptr = key;
150         dbuf.dsize = len;
151         dbuf.dptr = buf;
152         if (tdb_store(tdb, kbuf, dbuf, flag) != 0) return False;
153
154         return True;
155 }
156
157 /****************************************************************************
158 initialise first time the mapping list
159 ****************************************************************************/
160 BOOL add_initial_entry(gid_t gid, const char *sid, enum SID_NAME_USE sid_name_use, const char *nt_name, const char *comment)
161 {
162         GROUP_MAP map;
163
164         if(!init_group_mapping()) {
165                 DEBUG(0,("failed to initialize group mapping\n"));
166                 return(False);
167         }
168         
169         map.gid=gid;
170         if (!string_to_sid(&map.sid, sid)) {
171                 DEBUG(0, ("string_to_sid failed: %s", sid));
172                 return False;
173         }
174         
175         map.sid_name_use=sid_name_use;
176         fstrcpy(map.nt_name, nt_name);
177         fstrcpy(map.comment, comment);
178
179         return pdb_add_group_mapping_entry(&map);
180 }
181
182 /****************************************************************************
183  Return the sid and the type of the unix group.
184 ****************************************************************************/
185
186 static BOOL get_group_map_from_sid(DOM_SID sid, GROUP_MAP *map)
187 {
188         TDB_DATA kbuf, dbuf;
189         pstring key;
190         fstring string_sid;
191         int ret = 0;
192         
193         if(!init_group_mapping()) {
194                 DEBUG(0,("failed to initialize group mapping\n"));
195                 return(False);
196         }
197
198         /* the key is the SID, retrieving is direct */
199
200         sid_to_string(string_sid, &sid);
201         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
202
203         kbuf.dptr = key;
204         kbuf.dsize = strlen(key)+1;
205                 
206         dbuf = tdb_fetch(tdb, kbuf);
207         if (!dbuf.dptr)
208                 return False;
209
210         ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
211                                 &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
212
213         SAFE_FREE(dbuf.dptr);
214         
215         if ( ret == -1 ) {
216                 DEBUG(3,("get_group_map_from_sid: tdb_unpack failure\n"));
217                 return False;
218         }
219
220         sid_copy(&map->sid, &sid);
221         
222         return True;
223 }
224
225 /****************************************************************************
226  Return the sid and the type of the unix group.
227 ****************************************************************************/
228
229 static BOOL get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
230 {
231         TDB_DATA kbuf, dbuf, newkey;
232         fstring string_sid;
233         int ret;
234
235         if(!init_group_mapping()) {
236                 DEBUG(0,("failed to initialize group mapping\n"));
237                 return(False);
238         }
239
240         /* we need to enumerate the TDB to find the GID */
241
242         for (kbuf = tdb_firstkey(tdb); 
243              kbuf.dptr; 
244              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
245
246                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
247                 
248                 dbuf = tdb_fetch(tdb, kbuf);
249                 if (!dbuf.dptr)
250                         continue;
251
252                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
253
254                 string_to_sid(&map->sid, string_sid);
255                 
256                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
257                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
258
259                 SAFE_FREE(dbuf.dptr);
260
261                 if ( ret == -1 ) {
262                         DEBUG(3,("get_group_map_from_gid: tdb_unpack failure\n"));
263                         return False;
264                 }
265         
266                 if (gid==map->gid) {
267                         SAFE_FREE(kbuf.dptr);
268                         return True;
269                 }
270         }
271
272         return False;
273 }
274
275 /****************************************************************************
276  Return the sid and the type of the unix group.
277 ****************************************************************************/
278
279 static BOOL get_group_map_from_ntname(const char *name, GROUP_MAP *map)
280 {
281         TDB_DATA kbuf, dbuf, newkey;
282         fstring string_sid;
283         int ret;
284
285         if(!init_group_mapping()) {
286                 DEBUG(0,("get_group_map_from_ntname:failed to initialize group mapping\n"));
287                 return(False);
288         }
289
290         /* we need to enumerate the TDB to find the name */
291
292         for (kbuf = tdb_firstkey(tdb); 
293              kbuf.dptr; 
294              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
295
296                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
297                 
298                 dbuf = tdb_fetch(tdb, kbuf);
299                 if (!dbuf.dptr)
300                         continue;
301
302                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
303
304                 string_to_sid(&map->sid, string_sid);
305                 
306                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
307                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
308
309                 SAFE_FREE(dbuf.dptr);
310                 
311                 if ( ret == -1 ) {
312                         DEBUG(3,("get_group_map_from_ntname: tdb_unpack failure\n"));
313                         return False;
314                 }
315
316                 if (StrCaseCmp(name, map->nt_name)==0) {
317                         SAFE_FREE(kbuf.dptr);
318                         return True;
319                 }
320         }
321
322         return False;
323 }
324
325 /****************************************************************************
326  Remove a group mapping entry.
327 ****************************************************************************/
328
329 static BOOL group_map_remove(const DOM_SID *sid)
330 {
331         TDB_DATA kbuf, dbuf;
332         pstring key;
333         fstring string_sid;
334         
335         if(!init_group_mapping()) {
336                 DEBUG(0,("failed to initialize group mapping\n"));
337                 return(False);
338         }
339
340         /* the key is the SID, retrieving is direct */
341
342         sid_to_string(string_sid, sid);
343         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
344
345         kbuf.dptr = key;
346         kbuf.dsize = strlen(key)+1;
347                 
348         dbuf = tdb_fetch(tdb, kbuf);
349         if (!dbuf.dptr)
350                 return False;
351         
352         SAFE_FREE(dbuf.dptr);
353
354         if(tdb_delete(tdb, kbuf) != TDB_SUCCESS)
355                 return False;
356
357         return True;
358 }
359
360 /****************************************************************************
361  Enumerate the group mapping.
362 ****************************************************************************/
363
364 static BOOL enum_group_mapping(enum SID_NAME_USE sid_name_use, GROUP_MAP **pp_rmap,
365                         size_t *p_num_entries, BOOL unix_only)
366 {
367         TDB_DATA kbuf, dbuf, newkey;
368         fstring string_sid;
369         GROUP_MAP map;
370         GROUP_MAP *mapt;
371         int ret;
372         size_t entries=0;
373
374         if(!init_group_mapping()) {
375                 DEBUG(0,("failed to initialize group mapping\n"));
376                 return(False);
377         }
378
379         *p_num_entries=0;
380         *pp_rmap=NULL;
381
382         for (kbuf = tdb_firstkey(tdb); 
383              kbuf.dptr; 
384              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
385
386                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0)
387                         continue;
388
389                 dbuf = tdb_fetch(tdb, kbuf);
390                 if (!dbuf.dptr)
391                         continue;
392
393                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
394                                 
395                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
396                                  &map.gid, &map.sid_name_use, &map.nt_name, &map.comment);
397
398                 SAFE_FREE(dbuf.dptr);
399
400                 if ( ret == -1 ) {
401                         DEBUG(3,("enum_group_mapping: tdb_unpack failure\n"));
402                         continue;
403                 }
404         
405                 /* list only the type or everything if UNKNOWN */
406                 if (sid_name_use!=SID_NAME_UNKNOWN  && sid_name_use!=map.sid_name_use) {
407                         DEBUG(11,("enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
408                         continue;
409                 }
410
411                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
412                         DEBUG(11,("enum_group_mapping: group %s is non mapped\n", map.nt_name));
413                         continue;
414                 }
415
416                 string_to_sid(&map.sid, string_sid);
417                 
418                 DEBUG(11,("enum_group_mapping: returning group %s of "
419                           "type %s\n", map.nt_name,
420                           sid_type_lookup(map.sid_name_use)));
421
422                 mapt= SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
423                 if (!mapt) {
424                         DEBUG(0,("enum_group_mapping: Unable to enlarge group map!\n"));
425                         SAFE_FREE(*pp_rmap);
426                         return False;
427                 }
428                 else
429                         (*pp_rmap) = mapt;
430
431                 mapt[entries].gid = map.gid;
432                 sid_copy( &mapt[entries].sid, &map.sid);
433                 mapt[entries].sid_name_use = map.sid_name_use;
434                 fstrcpy(mapt[entries].nt_name, map.nt_name);
435                 fstrcpy(mapt[entries].comment, map.comment);
436
437                 entries++;
438
439         }
440
441         *p_num_entries=entries;
442
443         return True;
444 }
445
446 /* This operation happens on session setup, so it should better be fast. We
447  * store a list of aliases a SID is member of hanging off MEMBEROF/SID. */
448
449 static NTSTATUS one_alias_membership(const DOM_SID *member,
450                                      DOM_SID **sids, size_t *num)
451 {
452         fstring key, string_sid;
453         TDB_DATA kbuf, dbuf;
454         const char *p;
455
456         if (!init_group_mapping()) {
457                 DEBUG(0,("failed to initialize group mapping\n"));
458                 return NT_STATUS_ACCESS_DENIED;
459         }
460
461         sid_to_string(string_sid, member);
462         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
463
464         kbuf.dsize = strlen(key)+1;
465         kbuf.dptr = key;
466
467         dbuf = tdb_fetch(tdb, kbuf);
468
469         if (dbuf.dptr == NULL) {
470                 return NT_STATUS_OK;
471         }
472
473         p = dbuf.dptr;
474
475         while (next_token(&p, string_sid, " ", sizeof(string_sid))) {
476
477                 DOM_SID alias;
478
479                 if (!string_to_sid(&alias, string_sid))
480                         continue;
481
482                 add_sid_to_array_unique(NULL, &alias, sids, num);
483
484                 if (sids == NULL)
485                         return NT_STATUS_NO_MEMORY;
486         }
487
488         SAFE_FREE(dbuf.dptr);
489         return NT_STATUS_OK;
490 }
491
492 static NTSTATUS alias_memberships(const DOM_SID *members, size_t num_members,
493                                   DOM_SID **sids, size_t *num)
494 {
495         size_t i;
496
497         *num = 0;
498         *sids = NULL;
499
500         for (i=0; i<num_members; i++) {
501                 NTSTATUS status = one_alias_membership(&members[i], sids, num);
502                 if (!NT_STATUS_IS_OK(status))
503                         return status;
504         }
505         return NT_STATUS_OK;
506 }
507
508 static BOOL is_aliasmem(const DOM_SID *alias, const DOM_SID *member)
509 {
510         DOM_SID *sids;
511         size_t i, num;
512
513         /* This feels the wrong way round, but the on-disk data structure
514          * dictates it this way. */
515         if (!NT_STATUS_IS_OK(alias_memberships(member, 1, &sids, &num)))
516                 return False;
517
518         for (i=0; i<num; i++) {
519                 if (sid_compare(alias, &sids[i]) == 0) {
520                         SAFE_FREE(sids);
521                         return True;
522                 }
523         }
524         SAFE_FREE(sids);
525         return False;
526 }
527
528 static NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
529 {
530         GROUP_MAP map;
531         TDB_DATA kbuf, dbuf;
532         pstring key;
533         fstring string_sid;
534         char *new_memberstring;
535         int result;
536
537         if(!init_group_mapping()) {
538                 DEBUG(0,("failed to initialize group mapping\n"));
539                 return NT_STATUS_ACCESS_DENIED;
540         }
541
542         if (!get_group_map_from_sid(*alias, &map))
543                 return NT_STATUS_NO_SUCH_ALIAS;
544
545         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
546              (map.sid_name_use != SID_NAME_WKN_GRP) )
547                 return NT_STATUS_NO_SUCH_ALIAS;
548
549         if (is_aliasmem(alias, member))
550                 return NT_STATUS_MEMBER_IN_ALIAS;
551
552         sid_to_string(string_sid, member);
553         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
554
555         kbuf.dsize = strlen(key)+1;
556         kbuf.dptr = key;
557
558         dbuf = tdb_fetch(tdb, kbuf);
559
560         sid_to_string(string_sid, alias);
561
562         if (dbuf.dptr != NULL) {
563                 asprintf(&new_memberstring, "%s %s", (char *)(dbuf.dptr),
564                          string_sid);
565         } else {
566                 new_memberstring = SMB_STRDUP(string_sid);
567         }
568
569         if (new_memberstring == NULL)
570                 return NT_STATUS_NO_MEMORY;
571
572         SAFE_FREE(dbuf.dptr);
573         dbuf.dsize = strlen(new_memberstring)+1;
574         dbuf.dptr = new_memberstring;
575
576         result = tdb_store(tdb, kbuf, dbuf, 0);
577
578         SAFE_FREE(new_memberstring);
579
580         return (result == 0 ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED);
581 }
582
583 struct aliasmem_closure {
584         const DOM_SID *alias;
585         DOM_SID **sids;
586         size_t *num;
587 };
588
589 static int collect_aliasmem(TDB_CONTEXT *tdb_ctx, TDB_DATA key, TDB_DATA data,
590                             void *state)
591 {
592         struct aliasmem_closure *closure = (struct aliasmem_closure *)state;
593         const char *p;
594         fstring alias_string;
595
596         if (strncmp(key.dptr, MEMBEROF_PREFIX,
597                     strlen(MEMBEROF_PREFIX)) != 0)
598                 return 0;
599
600         p = data.dptr;
601
602         while (next_token(&p, alias_string, " ", sizeof(alias_string))) {
603
604                 DOM_SID alias, member;
605                 const char *member_string;
606                 
607
608                 if (!string_to_sid(&alias, alias_string))
609                         continue;
610
611                 if (sid_compare(closure->alias, &alias) != 0)
612                         continue;
613
614                 /* Ok, we found the alias we're looking for in the membership
615                  * list currently scanned. The key represents the alias
616                  * member. Add that. */
617
618                 member_string = strchr(key.dptr, '/');
619
620                 /* Above we tested for MEMBEROF_PREFIX which includes the
621                  * slash. */
622
623                 SMB_ASSERT(member_string != NULL);
624                 member_string += 1;
625
626                 if (!string_to_sid(&member, member_string))
627                         continue;
628                 
629                 add_sid_to_array(NULL, &member, closure->sids, closure->num);
630         }
631
632         return 0;
633 }
634
635 static NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, size_t *num)
636 {
637         GROUP_MAP map;
638         struct aliasmem_closure closure;
639
640         if(!init_group_mapping()) {
641                 DEBUG(0,("failed to initialize group mapping\n"));
642                 return NT_STATUS_ACCESS_DENIED;
643         }
644
645         if (!get_group_map_from_sid(*alias, &map))
646                 return NT_STATUS_NO_SUCH_ALIAS;
647
648         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
649              (map.sid_name_use != SID_NAME_WKN_GRP) )
650                 return NT_STATUS_NO_SUCH_ALIAS;
651
652         *sids = NULL;
653         *num = 0;
654
655         closure.alias = alias;
656         closure.sids = sids;
657         closure.num = num;
658
659         tdb_traverse(tdb, collect_aliasmem, &closure);
660         return NT_STATUS_OK;
661 }
662
663 static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
664 {
665         NTSTATUS result;
666         DOM_SID *sids;
667         size_t i, num;
668         BOOL found = False;
669         char *member_string;
670         TDB_DATA kbuf, dbuf;
671         pstring key;
672         fstring sid_string;
673
674         result = alias_memberships(member, 1, &sids, &num);
675
676         if (!NT_STATUS_IS_OK(result))
677                 return result;
678
679         for (i=0; i<num; i++) {
680                 if (sid_compare(&sids[i], alias) == 0) {
681                         found = True;
682                         break;
683                 }
684         }
685
686         if (!found) {
687                 SAFE_FREE(sids);
688                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
689         }
690
691         if (i < num)
692                 sids[i] = sids[num-1];
693
694         num -= 1;
695
696         sid_to_string(sid_string, member);
697         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, sid_string);
698
699         kbuf.dsize = strlen(key)+1;
700         kbuf.dptr = key;
701
702         if (num == 0)
703                 return tdb_delete(tdb, kbuf) == 0 ?
704                         NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
705
706         member_string = SMB_STRDUP("");
707
708         if (member_string == NULL) {
709                 SAFE_FREE(sids);
710                 return NT_STATUS_NO_MEMORY;
711         }
712
713         for (i=0; i<num; i++) {
714                 char *s = member_string;
715
716                 sid_to_string(sid_string, &sids[i]);
717                 asprintf(&member_string, "%s %s", s, sid_string);
718
719                 SAFE_FREE(s);
720                 if (member_string == NULL) {
721                         SAFE_FREE(sids);
722                         return NT_STATUS_NO_MEMORY;
723                 }
724         }
725
726         dbuf.dsize = strlen(member_string)+1;
727         dbuf.dptr = member_string;
728
729         result = tdb_store(tdb, kbuf, dbuf, 0) == 0 ?
730                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
731
732         SAFE_FREE(sids);
733         SAFE_FREE(member_string);
734
735         return result;
736 }
737
738 /*
739  *
740  * High level functions
741  * better to use them than the lower ones.
742  *
743  * we are checking if the group is in the mapping file
744  * and if the group is an existing unix group
745  *
746  */
747
748 /* get a domain group from it's SID */
749
750 BOOL get_domain_group_from_sid(DOM_SID sid, GROUP_MAP *map)
751 {
752         struct group *grp;
753         BOOL ret;
754         
755         if(!init_group_mapping()) {
756                 DEBUG(0,("failed to initialize group mapping\n"));
757                 return(False);
758         }
759
760         DEBUG(10, ("get_domain_group_from_sid\n"));
761
762         /* if the group is NOT in the database, it CAN NOT be a domain group */
763         
764         become_root();
765         ret = pdb_getgrsid(map, sid);
766         unbecome_root();
767         
768         if ( !ret ) 
769                 return False;
770
771         DEBUG(10, ("get_domain_group_from_sid: SID found in the TDB\n"));
772
773         /* if it's not a domain group, continue */
774         if (map->sid_name_use!=SID_NAME_DOM_GRP) {
775                 return False;
776         }
777
778         DEBUG(10, ("get_domain_group_from_sid: SID is a domain group\n"));
779         
780         if (map->gid==-1) {
781                 return False;
782         }
783
784         DEBUG(10, ("get_domain_group_from_sid: SID is mapped to gid:%lu\n",(unsigned long)map->gid));
785         
786         grp = getgrgid(map->gid);
787         if ( !grp ) {
788                 DEBUG(10, ("get_domain_group_from_sid: gid DOESN'T exist in UNIX security\n"));
789                 return False;
790         }
791
792         DEBUG(10, ("get_domain_group_from_sid: gid exists in UNIX security\n"));
793
794         return True;
795 }
796
797
798 /* get a local (alias) group from it's SID */
799
800 BOOL get_local_group_from_sid(DOM_SID *sid, GROUP_MAP *map)
801 {
802         BOOL ret;
803         
804         if(!init_group_mapping()) {
805                 DEBUG(0,("failed to initialize group mapping\n"));
806                 return(False);
807         }
808
809         /* The group is in the mapping table */
810         become_root();
811         ret = pdb_getgrsid(map, *sid);
812         unbecome_root();
813         
814         if ( !ret )
815                 return False;
816                 
817         if ( ( (map->sid_name_use != SID_NAME_ALIAS) &&
818                (map->sid_name_use != SID_NAME_WKN_GRP) )
819                 || (map->gid == -1)
820                 || (getgrgid(map->gid) == NULL) ) 
821         {
822                 return False;
823         }               
824                         
825 #if 1   /* JERRY */
826         /* local groups only exist in the group mapping DB so this 
827            is not necessary */
828            
829         else {
830                 /* the group isn't in the mapping table.
831                  * make one based on the unix information */
832                 uint32 alias_rid;
833                 struct group *grp;
834
835                 sid_peek_rid(sid, &alias_rid);
836                 map->gid=pdb_group_rid_to_gid(alias_rid);
837                 
838                 grp = getgrgid(map->gid);
839                 if ( !grp ) {
840                         DEBUG(3,("get_local_group_from_sid: No unix group for [%ul]\n", map->gid));
841                         return False;
842                 }
843
844                 map->sid_name_use=SID_NAME_ALIAS;
845
846                 fstrcpy(map->nt_name, grp->gr_name);
847                 fstrcpy(map->comment, "Local Unix Group");
848
849                 sid_copy(&map->sid, sid);
850         }
851 #endif
852
853         return True;
854 }
855
856 /* get a builtin group from it's SID */
857
858 BOOL get_builtin_group_from_sid(DOM_SID *sid, GROUP_MAP *map)
859 {
860         BOOL ret;
861         
862
863         if(!init_group_mapping()) {
864                 DEBUG(0,("failed to initialize group mapping\n"));
865                 return(False);
866         }
867
868         become_root();
869         ret = pdb_getgrsid(map, *sid);
870         unbecome_root();
871         
872         if ( !ret )
873                 return False;
874
875         if (map->sid_name_use!=SID_NAME_WKN_GRP) {
876                 return False;
877         }
878
879         if (map->gid==-1) {
880                 return False;
881         }
882
883         if ( getgrgid(map->gid) == NULL) {
884                 return False;
885         }
886
887         return True;
888 }
889
890 /****************************************************************************
891  Create a UNIX group on demand.
892 ****************************************************************************/
893
894 int smb_create_group(char *unix_group, gid_t *new_gid)
895 {
896         pstring add_script;
897         int     ret = -1;
898         int     fd = 0;
899         
900         *new_gid = 0;
901
902         /* defer to scripts */
903         
904         if ( *lp_addgroup_script() ) {
905                 pstrcpy(add_script, lp_addgroup_script());
906                 pstring_sub(add_script, "%g", unix_group);
907                 ret = smbrun(add_script, (new_gid!=NULL) ? &fd : NULL);
908                 DEBUG(ret ? 0 : 3,("smb_create_group: Running the command `%s' gave %d\n",add_script,ret));
909                 if (ret != 0)
910                         return ret;
911                         
912                 if (fd != 0) {
913                         fstring output;
914
915                         *new_gid = 0;
916                         if (read(fd, output, sizeof(output)) > 0) {
917                                 *new_gid = (gid_t)strtoul(output, NULL, 10);
918                         }
919                         
920                         close(fd);
921                 }
922
923         }
924
925         if (*new_gid == 0) {
926                 struct group *grp = getgrnam(unix_group);
927
928                 if (grp != NULL)
929                         *new_gid = grp->gr_gid;
930         }
931                         
932         return ret;     
933 }
934
935 /****************************************************************************
936  Delete a UNIX group on demand.
937 ****************************************************************************/
938
939 int smb_delete_group(char *unix_group)
940 {
941         pstring del_script;
942         int ret;
943
944         /* defer to scripts */
945         
946         if ( *lp_delgroup_script() ) {
947                 pstrcpy(del_script, lp_delgroup_script());
948                 pstring_sub(del_script, "%g", unix_group);
949                 ret = smbrun(del_script,NULL);
950                 DEBUG(ret ? 0 : 3,("smb_delete_group: Running the command `%s' gave %d\n",del_script,ret));
951                 return ret;
952         }
953                 
954         return -1;
955 }
956
957 /****************************************************************************
958  Set a user's primary UNIX group.
959 ****************************************************************************/
960 int smb_set_primary_group(const char *unix_group, const char* unix_user)
961 {
962         pstring add_script;
963         int ret;
964
965         /* defer to scripts */
966         
967         if ( *lp_setprimarygroup_script() ) {
968                 pstrcpy(add_script, lp_setprimarygroup_script());
969                 all_string_sub(add_script, "%g", unix_group, sizeof(add_script));
970                 all_string_sub(add_script, "%u", unix_user, sizeof(add_script));
971                 ret = smbrun(add_script,NULL);
972                 flush_pwnam_cache();
973                 DEBUG(ret ? 0 : 3,("smb_set_primary_group: "
974                          "Running the command `%s' gave %d\n",add_script,ret));
975                 return ret;
976         }
977
978         return -1;
979 }
980
981 /****************************************************************************
982  Add a user to a UNIX group.
983 ****************************************************************************/
984
985 int smb_add_user_group(char *unix_group, char *unix_user)
986 {
987         pstring add_script;
988         int ret;
989
990         /* defer to scripts */
991         
992         if ( *lp_addusertogroup_script() ) {
993                 pstrcpy(add_script, lp_addusertogroup_script());
994                 pstring_sub(add_script, "%g", unix_group);
995                 pstring_sub(add_script, "%u", unix_user);
996                 ret = smbrun(add_script,NULL);
997                 DEBUG(ret ? 0 : 3,("smb_add_user_group: Running the command `%s' gave %d\n",add_script,ret));
998                 return ret;
999         }
1000         
1001         return -1;
1002 }
1003
1004 /****************************************************************************
1005  Delete a user from a UNIX group
1006 ****************************************************************************/
1007
1008 int smb_delete_user_group(const char *unix_group, const char *unix_user)
1009 {
1010         pstring del_script;
1011         int ret;
1012
1013         /* defer to scripts */
1014         
1015         if ( *lp_deluserfromgroup_script() ) {
1016                 pstrcpy(del_script, lp_deluserfromgroup_script());
1017                 pstring_sub(del_script, "%g", unix_group);
1018                 pstring_sub(del_script, "%u", unix_user);
1019                 ret = smbrun(del_script,NULL);
1020                 DEBUG(ret ? 0 : 3,("smb_delete_user_group: Running the command `%s' gave %d\n",del_script,ret));
1021                 return ret;
1022         }
1023         
1024         return -1;
1025 }
1026
1027
1028 NTSTATUS pdb_default_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1029                                  DOM_SID sid)
1030 {
1031         return get_group_map_from_sid(sid, map) ?
1032                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1033 }
1034
1035 NTSTATUS pdb_default_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1036                                  gid_t gid)
1037 {
1038         return get_group_map_from_gid(gid, map) ?
1039                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1040 }
1041
1042 NTSTATUS pdb_default_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1043                                  const char *name)
1044 {
1045         return get_group_map_from_ntname(name, map) ?
1046                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1047 }
1048
1049 NTSTATUS pdb_default_add_group_mapping_entry(struct pdb_methods *methods,
1050                                                 GROUP_MAP *map)
1051 {
1052         return add_mapping_entry(map, TDB_INSERT) ?
1053                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1054 }
1055
1056 NTSTATUS pdb_default_update_group_mapping_entry(struct pdb_methods *methods,
1057                                                    GROUP_MAP *map)
1058 {
1059         return add_mapping_entry(map, TDB_REPLACE) ?
1060                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1061 }
1062
1063 NTSTATUS pdb_default_delete_group_mapping_entry(struct pdb_methods *methods,
1064                                                    DOM_SID sid)
1065 {
1066         return group_map_remove(&sid) ?
1067                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1068 }
1069
1070 NTSTATUS pdb_default_enum_group_mapping(struct pdb_methods *methods,
1071                                            enum SID_NAME_USE sid_name_use,
1072                                            GROUP_MAP **pp_rmap, size_t *p_num_entries,
1073                                            BOOL unix_only)
1074 {
1075         return enum_group_mapping(sid_name_use, pp_rmap, p_num_entries, unix_only) ?
1076                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1077 }
1078
1079 NTSTATUS pdb_default_find_alias(struct pdb_methods *methods,
1080                                 const char *name, DOM_SID *sid)
1081 {
1082         GROUP_MAP map;
1083
1084         if (!pdb_getgrnam(&map, name))
1085                 return NT_STATUS_NO_SUCH_ALIAS;
1086
1087         if ((map.sid_name_use != SID_NAME_WKN_GRP) &&
1088             (map.sid_name_use != SID_NAME_ALIAS))
1089                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
1090
1091         sid_copy(sid, &map.sid);
1092         return NT_STATUS_OK;
1093 }
1094
1095 NTSTATUS pdb_default_create_alias(struct pdb_methods *methods,
1096                                   const char *name, uint32 *rid)
1097 {
1098         DOM_SID sid;
1099         enum SID_NAME_USE type;
1100         uint32 new_rid;
1101         gid_t gid;
1102         BOOL exists;
1103         GROUP_MAP map;
1104
1105         TALLOC_CTX *mem_ctx = talloc_new(NULL);
1106
1107         if (mem_ctx == NULL) {
1108                 return NT_STATUS_NO_MEMORY;
1109         }
1110
1111         exists = lookup_name(mem_ctx, name, LOOKUP_NAME_ISOLATED,
1112                              NULL, NULL, &sid, &type);
1113         talloc_free(mem_ctx);
1114
1115         if (exists) {
1116                 return NT_STATUS_ALIAS_EXISTS;
1117         }
1118
1119         if (!winbind_allocate_rid_and_gid(&new_rid, &gid))
1120                 return NT_STATUS_ACCESS_DENIED;
1121
1122         sid_copy(&sid, get_global_sam_sid());
1123         sid_append_rid(&sid, new_rid);
1124
1125         map.gid = gid;
1126         sid_copy(&map.sid, &sid);
1127         map.sid_name_use = SID_NAME_ALIAS;
1128         fstrcpy(map.nt_name, name);
1129         fstrcpy(map.comment, "");
1130
1131         if (!pdb_add_group_mapping_entry(&map)) {
1132                 DEBUG(0, ("Could not add group mapping entry for alias %s\n",
1133                           name));
1134                 return NT_STATUS_ACCESS_DENIED;
1135         }
1136
1137         *rid = new_rid;
1138
1139         return NT_STATUS_OK;
1140 }
1141
1142 NTSTATUS pdb_default_delete_alias(struct pdb_methods *methods,
1143                                   const DOM_SID *sid)
1144 {
1145         return pdb_delete_group_mapping_entry(*sid) ?
1146                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1147 }
1148
1149 NTSTATUS pdb_default_get_aliasinfo(struct pdb_methods *methods,
1150                                    const DOM_SID *sid,
1151                                    struct acct_info *info)
1152 {
1153         GROUP_MAP map;
1154
1155         if (!pdb_getgrsid(&map, *sid))
1156                 return NT_STATUS_NO_SUCH_ALIAS;
1157
1158         fstrcpy(info->acct_name, map.nt_name);
1159         fstrcpy(info->acct_desc, map.comment);
1160         sid_peek_rid(&map.sid, &info->rid);
1161         return NT_STATUS_OK;
1162 }
1163
1164 NTSTATUS pdb_default_set_aliasinfo(struct pdb_methods *methods,
1165                                    const DOM_SID *sid,
1166                                    struct acct_info *info)
1167 {
1168         GROUP_MAP map;
1169
1170         if (!pdb_getgrsid(&map, *sid))
1171                 return NT_STATUS_NO_SUCH_ALIAS;
1172
1173         fstrcpy(map.comment, info->acct_desc);
1174
1175         if (!pdb_update_group_mapping_entry(&map))
1176                 return NT_STATUS_ACCESS_DENIED;
1177
1178         return NT_STATUS_OK;
1179 }
1180
1181 NTSTATUS pdb_default_add_aliasmem(struct pdb_methods *methods,
1182                                   const DOM_SID *alias, const DOM_SID *member)
1183 {
1184         return add_aliasmem(alias, member);
1185 }
1186
1187 NTSTATUS pdb_default_del_aliasmem(struct pdb_methods *methods,
1188                                   const DOM_SID *alias, const DOM_SID *member)
1189 {
1190         return del_aliasmem(alias, member);
1191 }
1192
1193 NTSTATUS pdb_default_enum_aliasmem(struct pdb_methods *methods,
1194                                    const DOM_SID *alias, DOM_SID **pp_members,
1195                                    size_t *p_num_members)
1196 {
1197         return enum_aliasmem(alias, pp_members, p_num_members);
1198 }
1199
1200 NTSTATUS pdb_default_alias_memberships(struct pdb_methods *methods,
1201                                        TALLOC_CTX *mem_ctx,
1202                                        const DOM_SID *domain_sid,
1203                                        const DOM_SID *members,
1204                                        size_t num_members,
1205                                        uint32 **pp_alias_rids,
1206                                        size_t *p_num_alias_rids)
1207 {
1208         DOM_SID *alias_sids;
1209         size_t i, num_alias_sids;
1210         NTSTATUS result;
1211
1212         alias_sids = NULL;
1213         num_alias_sids = 0;
1214
1215         result = alias_memberships(members, num_members,
1216                                    &alias_sids, &num_alias_sids);
1217
1218         if (!NT_STATUS_IS_OK(result))
1219                 return result;
1220
1221         *pp_alias_rids = TALLOC_ARRAY(mem_ctx, uint32, num_alias_sids);
1222         if (*pp_alias_rids == NULL)
1223                 return NT_STATUS_NO_MEMORY;
1224
1225         *p_num_alias_rids = 0;
1226
1227         for (i=0; i<num_alias_sids; i++) {
1228                 if (!sid_peek_check_rid(domain_sid, &alias_sids[i],
1229                                         &(*pp_alias_rids)[*p_num_alias_rids]))
1230                         continue;
1231                 *p_num_alias_rids += 1;
1232         }
1233
1234         SAFE_FREE(alias_sids);
1235
1236         return NT_STATUS_OK;
1237 }
1238
1239 /**********************************************************************
1240  no ops for passdb backends that don't implement group mapping
1241  *********************************************************************/
1242
1243 NTSTATUS pdb_nop_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1244                                  DOM_SID sid)
1245 {
1246         return NT_STATUS_UNSUCCESSFUL;
1247 }
1248
1249 NTSTATUS pdb_nop_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1250                                  gid_t gid)
1251 {
1252         return NT_STATUS_UNSUCCESSFUL;
1253 }
1254
1255 NTSTATUS pdb_nop_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1256                                  const char *name)
1257 {
1258         return NT_STATUS_UNSUCCESSFUL;
1259 }
1260
1261 NTSTATUS pdb_nop_add_group_mapping_entry(struct pdb_methods *methods,
1262                                                 GROUP_MAP *map)
1263 {
1264         return NT_STATUS_UNSUCCESSFUL;
1265 }
1266
1267 NTSTATUS pdb_nop_update_group_mapping_entry(struct pdb_methods *methods,
1268                                                    GROUP_MAP *map)
1269 {
1270         return NT_STATUS_UNSUCCESSFUL;
1271 }
1272
1273 NTSTATUS pdb_nop_delete_group_mapping_entry(struct pdb_methods *methods,
1274                                                    DOM_SID sid)
1275 {
1276         return NT_STATUS_UNSUCCESSFUL;
1277 }
1278
1279 NTSTATUS pdb_nop_enum_group_mapping(struct pdb_methods *methods,
1280                                            enum SID_NAME_USE sid_name_use,
1281                                            GROUP_MAP **rmap, size_t *num_entries,
1282                                            BOOL unix_only)
1283 {
1284         return NT_STATUS_UNSUCCESSFUL;
1285 }
1286
1287 /****************************************************************************
1288  These need to be redirected through pdb_interface.c
1289 ****************************************************************************/
1290 BOOL pdb_get_dom_grp_info(const DOM_SID *sid, struct acct_info *info)
1291 {
1292         GROUP_MAP map;
1293         BOOL res;
1294
1295         become_root();
1296         res = get_domain_group_from_sid(*sid, &map);
1297         unbecome_root();
1298
1299         if (!res)
1300                 return False;
1301
1302         fstrcpy(info->acct_name, map.nt_name);
1303         fstrcpy(info->acct_desc, map.comment);
1304         sid_peek_rid(sid, &info->rid);
1305         return True;
1306 }
1307
1308 BOOL pdb_set_dom_grp_info(const DOM_SID *sid, const struct acct_info *info)
1309 {
1310         GROUP_MAP map;
1311
1312         if (!get_domain_group_from_sid(*sid, &map))
1313                 return False;
1314
1315         fstrcpy(map.nt_name, info->acct_name);
1316         fstrcpy(map.comment, info->acct_desc);
1317
1318         return pdb_update_group_mapping_entry(&map);
1319 }
1320
1321