r20090: Fix a class of bugs found by James Peach. Ensure
[tprouty/samba.git] / source / passdb / pdb_interface.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Andrew Bartlett                        2002
5    Copyright (C) Jelmer Vernooij                        2002
6    Copyright (C) Simo Sorce                             2003
7    Copyright (C) Volker Lendecke                        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 2 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, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_PASSDB
28
29 /* Cache of latest SAM lookup query */
30
31 static struct samu *csamuser = NULL;
32
33 static_decl_pdb;
34
35 static struct pdb_init_function_entry *backends = NULL;
36
37 static void lazy_initialize_passdb(void)
38 {
39         static BOOL initialized = False;
40         if(initialized) {
41                 return;
42         }
43         static_init_pdb;
44         initialized = True;
45 }
46
47 static BOOL lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32 rid,
48                                   const char **name,
49                                   enum lsa_SidType *psid_name_use,
50                                   union unid_t *unix_id);
51
52 NTSTATUS smb_register_passdb(int version, const char *name, pdb_init_function init) 
53 {
54         struct pdb_init_function_entry *entry = backends;
55
56         if(version != PASSDB_INTERFACE_VERSION) {
57                 DEBUG(0,("Can't register passdb backend!\n"
58                          "You tried to register a passdb module with PASSDB_INTERFACE_VERSION %d, "
59                          "while this version of samba uses version %d\n", 
60                          version,PASSDB_INTERFACE_VERSION));
61                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
62         }
63
64         if (!name || !init) {
65                 return NT_STATUS_INVALID_PARAMETER;
66         }
67
68         DEBUG(5,("Attempting to register passdb backend %s\n", name));
69
70         /* Check for duplicates */
71         if (pdb_find_backend_entry(name)) {
72                 DEBUG(0,("There already is a passdb backend registered with the name %s!\n", name));
73                 return NT_STATUS_OBJECT_NAME_COLLISION;
74         }
75
76         entry = SMB_XMALLOC_P(struct pdb_init_function_entry);
77         entry->name = smb_xstrdup(name);
78         entry->init = init;
79
80         DLIST_ADD(backends, entry);
81         DEBUG(5,("Successfully added passdb backend '%s'\n", name));
82         return NT_STATUS_OK;
83 }
84
85 struct pdb_init_function_entry *pdb_find_backend_entry(const char *name)
86 {
87         struct pdb_init_function_entry *entry = backends;
88
89         while(entry) {
90                 if (strcmp(entry->name, name)==0) return entry;
91                 entry = entry->next;
92         }
93
94         return NULL;
95 }
96
97 /******************************************************************
98   Make a pdb_methods from scratch
99  *******************************************************************/
100
101 NTSTATUS make_pdb_method_name(struct pdb_methods **methods, const char *selected)
102 {
103         char *module_name = smb_xstrdup(selected);
104         char *module_location = NULL, *p;
105         struct pdb_init_function_entry *entry;
106         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
107
108         lazy_initialize_passdb();
109
110         p = strchr(module_name, ':');
111
112         if (p) {
113                 *p = 0;
114                 module_location = p+1;
115                 trim_char(module_location, ' ', ' ');
116         }
117
118         trim_char(module_name, ' ', ' ');
119
120
121         DEBUG(5,("Attempting to find an passdb backend to match %s (%s)\n", selected, module_name));
122
123         entry = pdb_find_backend_entry(module_name);
124         
125         /* Try to find a module that contains this module */
126         if (!entry) { 
127                 DEBUG(2,("No builtin backend found, trying to load plugin\n"));
128                 if(NT_STATUS_IS_OK(smb_probe_module("pdb", module_name)) && !(entry = pdb_find_backend_entry(module_name))) {
129                         DEBUG(0,("Plugin is available, but doesn't register passdb backend %s\n", module_name));
130                         SAFE_FREE(module_name);
131                         return NT_STATUS_UNSUCCESSFUL;
132                 }
133         }
134         
135         /* No such backend found */
136         if(!entry) { 
137                 DEBUG(0,("No builtin nor plugin backend for %s found\n", module_name));
138                 SAFE_FREE(module_name);
139                 return NT_STATUS_INVALID_PARAMETER;
140         }
141
142         DEBUG(5,("Found pdb backend %s\n", module_name));
143
144         if ( !NT_STATUS_IS_OK( nt_status = entry->init(methods, module_location) ) ) {
145                 DEBUG(0,("pdb backend %s did not correctly init (error was %s)\n", 
146                         selected, nt_errstr(nt_status)));
147                 SAFE_FREE(module_name);
148                 return nt_status;
149         }
150
151         SAFE_FREE(module_name);
152
153         DEBUG(5,("pdb backend %s has a valid init\n", selected));
154
155         return nt_status;
156 }
157
158 /******************************************************************
159  Return an already initialised pdn_methods structure
160 *******************************************************************/
161
162 static struct pdb_methods *pdb_get_methods_reload( BOOL reload ) 
163 {
164         static struct pdb_methods *pdb = NULL;
165
166         if ( pdb && reload ) {
167                 pdb->free_private_data( &(pdb->private_data) );
168                 if ( !NT_STATUS_IS_OK( make_pdb_method_name( &pdb, lp_passdb_backend() ) ) ) {
169                         pstring msg;
170                         slprintf(msg, sizeof(msg)-1, "pdb_get_methods_reload: failed to get pdb methods for backend %s\n",
171                                 lp_passdb_backend() );
172                         smb_panic(msg);
173                 }
174         }
175
176         if ( !pdb ) {
177                 if ( !NT_STATUS_IS_OK( make_pdb_method_name( &pdb, lp_passdb_backend() ) ) ) {
178                         pstring msg;
179                         slprintf(msg, sizeof(msg)-1, "pdb_get_methods_reload: failed to get pdb methods for backend %s\n",
180                                 lp_passdb_backend() );
181                         smb_panic(msg);
182                 }
183         }
184
185         return pdb;
186 }
187
188 static struct pdb_methods *pdb_get_methods(void)
189 {
190         return pdb_get_methods_reload(False);
191 }
192
193 /******************************************************************
194  Backward compatibility functions for the original passdb interface
195 *******************************************************************/
196
197 BOOL pdb_setsampwent(BOOL update, uint16 acb_mask) 
198 {
199         struct pdb_methods *pdb = pdb_get_methods();
200         return NT_STATUS_IS_OK(pdb->setsampwent(pdb, update, acb_mask));
201 }
202
203 void pdb_endsampwent(void) 
204 {
205         struct pdb_methods *pdb = pdb_get_methods();
206         pdb->endsampwent(pdb);
207 }
208
209 BOOL pdb_getsampwent(struct samu *user) 
210 {
211         struct pdb_methods *pdb = pdb_get_methods();
212
213         if ( !NT_STATUS_IS_OK(pdb->getsampwent(pdb, user) ) ) {
214                 return False;
215         }
216
217         return True;
218 }
219
220 BOOL pdb_getsampwnam(struct samu *sam_acct, const char *username) 
221 {
222         struct pdb_methods *pdb = pdb_get_methods();
223
224         if (!NT_STATUS_IS_OK(pdb->getsampwnam(pdb, sam_acct, username))) {
225                 return False;
226         }
227
228         if ( csamuser ) {
229                 TALLOC_FREE(csamuser);
230         }
231
232         csamuser = samu_new( NULL );
233         if (!csamuser) {
234                 return False;
235         }
236
237         if (!pdb_copy_sam_account(csamuser, sam_acct)) {
238                 TALLOC_FREE(csamuser);
239                 return False;
240         }
241
242         return True;
243 }
244
245 /**********************************************************************
246 **********************************************************************/
247
248 BOOL guest_user_info( struct samu *user )
249 {
250         struct passwd *pwd;
251         NTSTATUS result;
252         const char *guestname = lp_guestaccount();
253         
254         if ( !(pwd = getpwnam_alloc( NULL, guestname ) ) ) {
255                 DEBUG(0,("guest_user_info: Unable to locate guest account [%s]!\n", 
256                         guestname));
257                 return False;
258         }
259         
260         result = samu_set_unix(user, pwd );
261
262         TALLOC_FREE( pwd );
263
264         return NT_STATUS_IS_OK( result );
265 }
266
267 /**********************************************************************
268 **********************************************************************/
269
270 BOOL pdb_getsampwsid(struct samu *sam_acct, const DOM_SID *sid) 
271 {
272         struct pdb_methods *pdb = pdb_get_methods();
273         uint32 rid;
274
275         /* hard code the Guest RID of 501 */
276
277         if ( !sid_peek_check_rid( get_global_sam_sid(), sid, &rid ) )
278                 return False;
279
280         if ( rid == DOMAIN_USER_RID_GUEST ) {
281                 DEBUG(6,("pdb_getsampwsid: Building guest account\n"));
282                 return guest_user_info( sam_acct );
283         }
284         
285         /* check the cache first */
286         
287         if ( csamuser && sid_equal(sid, pdb_get_user_sid(csamuser) ) )
288                 return pdb_copy_sam_account(sam_acct, csamuser);
289
290         return NT_STATUS_IS_OK(pdb->getsampwsid(pdb, sam_acct, sid));
291 }
292
293 static NTSTATUS pdb_default_create_user(struct pdb_methods *methods,
294                                         TALLOC_CTX *tmp_ctx, const char *name,
295                                         uint32 acb_info, uint32 *rid)
296 {
297         struct samu *sam_pass;
298         NTSTATUS status;
299         struct passwd *pwd;
300
301         if ((sam_pass = samu_new(tmp_ctx)) == NULL) {
302                 return NT_STATUS_NO_MEMORY;
303         }
304
305         if ( !(pwd = Get_Pwnam_alloc(tmp_ctx, name)) ) {
306                 pstring add_script;
307                 int add_ret;
308                 fstring name2;
309
310                 if ((acb_info & ACB_NORMAL) && name[strlen(name)-1] != '$') {
311                         pstrcpy(add_script, lp_adduser_script());
312                 } else {
313                         pstrcpy(add_script, lp_addmachine_script());
314                 }
315
316                 if (add_script[0] == '\0') {
317                         DEBUG(3, ("Could not find user %s and no add script "
318                                   "defined\n", name));
319                         return NT_STATUS_NO_SUCH_USER;
320                 }
321
322                 /* lowercase the username before creating the Unix account for 
323                    compatibility with previous Samba releases */
324                 fstrcpy( name2, name );
325                 strlower_m( name2 );
326                 all_string_sub(add_script, "%u", name2, sizeof(add_script));
327                 add_ret = smbrun(add_script,NULL);
328                 DEBUG(add_ret ? 0 : 3, ("_samr_create_user: Running the command `%s' gave %d\n",
329                                         add_script, add_ret));
330                 if (add_ret == 0) {
331                         smb_nscd_flush_user_cache();
332                 }
333
334 #ifdef ENABLE_BUILD_FARM_HACKS
335                 if (add_ret != 0) {
336                         DEBUG(1, ("Creating a faked user %s for build farm "
337                                   "purposes\n", name));
338                         faked_create_user(name);
339                 }
340 #endif
341
342                 flush_pwnam_cache();
343
344                 pwd = Get_Pwnam_alloc(tmp_ctx, name);
345         }
346
347         /* we have a valid SID coming out of this call */
348
349         status = samu_alloc_rid_unix( sam_pass, pwd );
350
351         TALLOC_FREE( pwd );
352
353         if (!NT_STATUS_IS_OK(status)) {
354                 DEBUG(3, ("pdb_default_create_user: failed to create a new user structure: %s\n", nt_errstr(status)));
355                 return status;
356         }
357
358         if (!sid_peek_check_rid(get_global_sam_sid(),
359                                 pdb_get_user_sid(sam_pass), rid)) {
360                 DEBUG(0, ("Could not get RID of fresh user\n"));
361                 return NT_STATUS_INTERNAL_ERROR;
362         }
363
364         /* Use the username case specified in the original request */
365
366         pdb_set_username( sam_pass, name, PDB_SET );
367
368         /* Disable the account on creation, it does not have a reasonable password yet. */
369
370         acb_info |= ACB_DISABLED;
371
372         pdb_set_acct_ctrl(sam_pass, acb_info, PDB_CHANGED);
373
374         status = pdb_add_sam_account(sam_pass);
375
376         TALLOC_FREE(sam_pass);
377
378         return status;
379 }
380
381 NTSTATUS pdb_create_user(TALLOC_CTX *mem_ctx, const char *name, uint32 flags,
382                          uint32 *rid)
383 {
384         struct pdb_methods *pdb = pdb_get_methods();
385         return pdb->create_user(pdb, mem_ctx, name, flags, rid);
386 }
387
388 /****************************************************************************
389  Delete a UNIX user on demand.
390 ****************************************************************************/
391
392 static int smb_delete_user(const char *unix_user)
393 {
394         pstring del_script;
395         int ret;
396
397         /* safety check */
398
399         if ( strequal( unix_user, "root" ) ) {
400                 DEBUG(0,("smb_delete_user: Refusing to delete local system root account!\n"));
401                 return -1;
402         }
403
404         pstrcpy(del_script, lp_deluser_script());
405         if (! *del_script)
406                 return -1;
407         all_string_sub(del_script, "%u", unix_user, sizeof(del_script));
408         ret = smbrun(del_script,NULL);
409         flush_pwnam_cache();
410         if (ret == 0) {
411                 smb_nscd_flush_user_cache();
412         }
413         DEBUG(ret ? 0 : 3,("smb_delete_user: Running the command `%s' gave %d\n",del_script,ret));
414
415         return ret;
416 }
417
418 static NTSTATUS pdb_default_delete_user(struct pdb_methods *methods,
419                                         TALLOC_CTX *mem_ctx,
420                                         struct samu *sam_acct)
421 {
422         NTSTATUS status;
423         fstring username;
424
425         status = pdb_delete_sam_account(sam_acct);
426         if (!NT_STATUS_IS_OK(status)) {
427                 return status;
428         }
429
430         /*
431          * Now delete the unix side ....
432          * note: we don't check if the delete really happened as the script is
433          * not necessary present and maybe the sysadmin doesn't want to delete
434          * the unix side
435          */
436
437         /* always lower case the username before handing it off to 
438            external scripts */
439
440         fstrcpy( username, pdb_get_username(sam_acct) );
441         strlower_m( username );
442
443         smb_delete_user( username );
444         
445         return status;
446 }
447
448 NTSTATUS pdb_delete_user(TALLOC_CTX *mem_ctx, struct samu *sam_acct)
449 {
450         struct pdb_methods *pdb = pdb_get_methods();
451         uid_t uid = -1;
452
453         /* sanity check to make sure we don't delete root */
454
455         if ( !sid_to_uid( pdb_get_user_sid(sam_acct), &uid ) ) {
456                 return NT_STATUS_NO_SUCH_USER;
457         }
458
459         if ( uid == 0 ) {
460                 return NT_STATUS_ACCESS_DENIED;
461         }
462
463         return pdb->delete_user(pdb, mem_ctx, sam_acct);
464 }
465
466 NTSTATUS pdb_add_sam_account(struct samu *sam_acct) 
467 {
468         struct pdb_methods *pdb = pdb_get_methods();
469         return pdb->add_sam_account(pdb, sam_acct);
470 }
471
472 NTSTATUS pdb_update_sam_account(struct samu *sam_acct) 
473 {
474         struct pdb_methods *pdb = pdb_get_methods();
475
476         if (csamuser != NULL) {
477                 TALLOC_FREE(csamuser);
478                 csamuser = NULL;
479         }
480
481         return pdb->update_sam_account(pdb, sam_acct);
482 }
483
484 NTSTATUS pdb_delete_sam_account(struct samu *sam_acct) 
485 {
486         struct pdb_methods *pdb = pdb_get_methods();
487
488         if (csamuser != NULL) {
489                 TALLOC_FREE(csamuser);
490                 csamuser = NULL;
491         }
492
493         return pdb->delete_sam_account(pdb, sam_acct);
494 }
495
496 NTSTATUS pdb_rename_sam_account(struct samu *oldname, const char *newname)
497 {
498         struct pdb_methods *pdb = pdb_get_methods();
499         uid_t uid;
500         NTSTATUS status;
501
502         if (csamuser != NULL) {
503                 TALLOC_FREE(csamuser);
504                 csamuser = NULL;
505         }
506
507         /* sanity check to make sure we don't rename root */
508
509         if ( !sid_to_uid( pdb_get_user_sid(oldname), &uid ) ) {
510                 return NT_STATUS_NO_SUCH_USER;
511         }
512
513         if ( uid == 0 ) {
514                 return NT_STATUS_ACCESS_DENIED;
515         }
516
517         status = pdb->rename_sam_account(pdb, oldname, newname);
518
519         /* always flush the cache here just to be safe */
520         flush_pwnam_cache();
521
522         return status;
523 }
524
525 NTSTATUS pdb_update_login_attempts(struct samu *sam_acct, BOOL success)
526 {
527         struct pdb_methods *pdb = pdb_get_methods();
528         return pdb->update_login_attempts(pdb, sam_acct, success);
529 }
530
531 BOOL pdb_getgrsid(GROUP_MAP *map, DOM_SID sid)
532 {
533         struct pdb_methods *pdb = pdb_get_methods();
534         return NT_STATUS_IS_OK(pdb->getgrsid(pdb, map, sid));
535 }
536
537 BOOL pdb_getgrgid(GROUP_MAP *map, gid_t gid)
538 {
539         struct pdb_methods *pdb = pdb_get_methods();
540         return NT_STATUS_IS_OK(pdb->getgrgid(pdb, map, gid));
541 }
542
543 BOOL pdb_getgrnam(GROUP_MAP *map, const char *name)
544 {
545         struct pdb_methods *pdb = pdb_get_methods();
546         return NT_STATUS_IS_OK(pdb->getgrnam(pdb, map, name));
547 }
548
549 static NTSTATUS pdb_default_create_dom_group(struct pdb_methods *methods,
550                                              TALLOC_CTX *mem_ctx,
551                                              const char *name,
552                                              uint32 *rid)
553 {
554         DOM_SID group_sid;
555         struct group *grp;
556
557         grp = getgrnam(name);
558
559         if (grp == NULL) {
560                 gid_t gid;
561
562                 if (smb_create_group(name, &gid) != 0) {
563                         return NT_STATUS_ACCESS_DENIED;
564                 }
565
566                 grp = getgrgid(gid);
567         }
568
569         if (grp == NULL) {
570                 return NT_STATUS_ACCESS_DENIED;
571         }
572
573         if (pdb_rid_algorithm()) {
574                 *rid = algorithmic_pdb_gid_to_group_rid( grp->gr_gid );
575         } else {
576                 if (!pdb_new_rid(rid)) {
577                         return NT_STATUS_ACCESS_DENIED;
578                 }
579         }
580
581         sid_compose(&group_sid, get_global_sam_sid(), *rid);
582                 
583         return add_initial_entry(grp->gr_gid, sid_string_static(&group_sid),
584                                  SID_NAME_DOM_GRP, name, NULL);
585 }
586
587 NTSTATUS pdb_create_dom_group(TALLOC_CTX *mem_ctx, const char *name,
588                               uint32 *rid)
589 {
590         struct pdb_methods *pdb = pdb_get_methods();
591         return pdb->create_dom_group(pdb, mem_ctx, name, rid);
592 }
593
594 static NTSTATUS pdb_default_delete_dom_group(struct pdb_methods *methods,
595                                              TALLOC_CTX *mem_ctx,
596                                              uint32 rid)
597 {
598         DOM_SID group_sid;
599         GROUP_MAP map;
600         NTSTATUS status;
601         struct group *grp;
602         const char *grp_name;
603
604         sid_compose(&group_sid, get_global_sam_sid(), rid);
605
606         if (!get_domain_group_from_sid(group_sid, &map)) {
607                 DEBUG(10, ("Could not find group for rid %d\n", rid));
608                 return NT_STATUS_NO_SUCH_GROUP;
609         }
610
611         /* We need the group name for the smb_delete_group later on */
612
613         if (map.gid == (gid_t)-1) {
614                 return NT_STATUS_NO_SUCH_GROUP;
615         }
616
617         grp = getgrgid(map.gid);
618         if (grp == NULL) {
619                 return NT_STATUS_NO_SUCH_GROUP;
620         }
621
622         /* Copy the name, no idea what pdb_delete_group_mapping_entry does.. */
623
624         grp_name = talloc_strdup(mem_ctx, grp->gr_name);
625         if (grp_name == NULL) {
626                 return NT_STATUS_NO_MEMORY;
627         }
628
629         status = pdb_delete_group_mapping_entry(group_sid);
630
631         if (!NT_STATUS_IS_OK(status)) {
632                 return status;
633         }
634
635         /* Don't check the result of smb_delete_group */
636         
637         smb_delete_group(grp_name);
638
639         return NT_STATUS_OK;
640 }
641
642 NTSTATUS pdb_delete_dom_group(TALLOC_CTX *mem_ctx, uint32 rid)
643 {
644         struct pdb_methods *pdb = pdb_get_methods();
645         return pdb->delete_dom_group(pdb, mem_ctx, rid);
646 }
647
648 NTSTATUS pdb_add_group_mapping_entry(GROUP_MAP *map)
649 {
650         struct pdb_methods *pdb = pdb_get_methods();
651         return pdb->add_group_mapping_entry(pdb, map);
652 }
653
654 NTSTATUS pdb_update_group_mapping_entry(GROUP_MAP *map)
655 {
656         struct pdb_methods *pdb = pdb_get_methods();
657         return pdb->update_group_mapping_entry(pdb, map);
658 }
659
660 NTSTATUS pdb_delete_group_mapping_entry(DOM_SID sid)
661 {
662         struct pdb_methods *pdb = pdb_get_methods();
663         return pdb->delete_group_mapping_entry(pdb, sid);
664 }
665
666 BOOL pdb_enum_group_mapping(const DOM_SID *sid, enum lsa_SidType sid_name_use, GROUP_MAP **pp_rmap,
667                             size_t *p_num_entries, BOOL unix_only)
668 {
669         struct pdb_methods *pdb = pdb_get_methods();
670         return NT_STATUS_IS_OK(pdb-> enum_group_mapping(pdb, sid, sid_name_use,
671                 pp_rmap, p_num_entries, unix_only));
672 }
673
674 NTSTATUS pdb_enum_group_members(TALLOC_CTX *mem_ctx,
675                                 const DOM_SID *sid,
676                                 uint32 **pp_member_rids,
677                                 size_t *p_num_members)
678 {
679         struct pdb_methods *pdb = pdb_get_methods();
680         NTSTATUS result;
681
682         result = pdb->enum_group_members(pdb, mem_ctx, 
683                         sid, pp_member_rids, p_num_members);
684                 
685         /* special check for rid 513 */
686                 
687         if ( !NT_STATUS_IS_OK( result ) ) {
688                 uint32 rid;
689                 
690                 sid_peek_rid( sid, &rid );
691                 
692                 if ( rid == DOMAIN_GROUP_RID_USERS ) {
693                         *p_num_members = 0;
694                         *pp_member_rids = NULL;
695                         
696                         return NT_STATUS_OK;
697                 }
698         }
699         
700         return result;
701 }
702
703 NTSTATUS pdb_enum_group_memberships(TALLOC_CTX *mem_ctx, struct samu *user,
704                                     DOM_SID **pp_sids, gid_t **pp_gids,
705                                     size_t *p_num_groups)
706 {
707         struct pdb_methods *pdb = pdb_get_methods();
708         return pdb->enum_group_memberships(
709                 pdb, mem_ctx, user,
710                 pp_sids, pp_gids, p_num_groups);
711 }
712
713 static NTSTATUS pdb_default_set_unix_primary_group(struct pdb_methods *methods,
714                                                    TALLOC_CTX *mem_ctx,
715                                                    struct samu *sampass)
716 {
717         struct group *grp;
718         gid_t gid;
719
720         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid) ||
721             (grp = getgrgid(gid)) == NULL) {
722                 return NT_STATUS_INVALID_PRIMARY_GROUP;
723         }
724
725         if (smb_set_primary_group(grp->gr_name,
726                                   pdb_get_username(sampass)) != 0) {
727                 return NT_STATUS_ACCESS_DENIED;
728         }
729
730         return NT_STATUS_OK;
731 }
732
733 NTSTATUS pdb_set_unix_primary_group(TALLOC_CTX *mem_ctx, struct samu *user)
734 {
735         struct pdb_methods *pdb = pdb_get_methods();
736         return pdb->set_unix_primary_group(pdb, mem_ctx, user);
737 }
738
739 /*
740  * Helper function to see whether a user is in a group. We can't use
741  * user_in_group_sid here because this creates dependencies only smbd can
742  * fulfil.
743  */
744
745 static BOOL pdb_user_in_group(TALLOC_CTX *mem_ctx, struct samu *account,
746                               const DOM_SID *group_sid)
747 {
748         DOM_SID *sids;
749         gid_t *gids;
750         size_t i, num_groups;
751
752         if (!NT_STATUS_IS_OK(pdb_enum_group_memberships(mem_ctx, account,
753                                                         &sids, &gids,
754                                                         &num_groups))) {
755                 return False;
756         }
757
758         for (i=0; i<num_groups; i++) {
759                 if (sid_equal(group_sid, &sids[i])) {
760                         return True;
761                 }
762         }
763         return False;
764 }
765
766 static NTSTATUS pdb_default_add_groupmem(struct pdb_methods *methods,
767                                          TALLOC_CTX *mem_ctx,
768                                          uint32 group_rid,
769                                          uint32 member_rid)
770 {
771         DOM_SID group_sid, member_sid;
772         struct samu *account = NULL;
773         GROUP_MAP map;
774         struct group *grp;
775         struct passwd *pwd;
776         const char *group_name;
777         uid_t uid;
778
779         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
780         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
781
782         if (!get_domain_group_from_sid(group_sid, &map) ||
783             (map.gid == (gid_t)-1) ||
784             ((grp = getgrgid(map.gid)) == NULL)) {
785                 return NT_STATUS_NO_SUCH_GROUP;
786         }
787
788         group_name = talloc_strdup(mem_ctx, grp->gr_name);
789         if (group_name == NULL) {
790                 return NT_STATUS_NO_MEMORY;
791         }
792
793         if ( !(account = samu_new( NULL )) ) {
794                 return NT_STATUS_NO_MEMORY;
795         }
796
797         if (!pdb_getsampwsid(account, &member_sid) ||
798             !sid_to_uid(&member_sid, &uid) ||
799             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
800                 return NT_STATUS_NO_SUCH_USER;
801         }
802
803         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
804                 return NT_STATUS_MEMBER_IN_GROUP;
805         }
806
807         /* 
808          * ok, the group exist, the user exist, the user is not in the group,
809          * we can (finally) add it to the group !
810          */
811
812         smb_add_user_group(group_name, pwd->pw_name);
813
814         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
815                 return NT_STATUS_ACCESS_DENIED;
816         }
817
818         return NT_STATUS_OK;
819 }
820
821 NTSTATUS pdb_add_groupmem(TALLOC_CTX *mem_ctx, uint32 group_rid,
822                           uint32 member_rid)
823 {
824         struct pdb_methods *pdb = pdb_get_methods();
825         return pdb->add_groupmem(pdb, mem_ctx, group_rid, member_rid);
826 }
827
828 static NTSTATUS pdb_default_del_groupmem(struct pdb_methods *methods,
829                                          TALLOC_CTX *mem_ctx,
830                                          uint32 group_rid,
831                                          uint32 member_rid)
832 {
833         DOM_SID group_sid, member_sid;
834         struct samu *account = NULL;
835         GROUP_MAP map;
836         struct group *grp;
837         struct passwd *pwd;
838         const char *group_name;
839         uid_t uid;
840
841         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
842         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
843
844         if (!get_domain_group_from_sid(group_sid, &map) ||
845             (map.gid == (gid_t)-1) ||
846             ((grp = getgrgid(map.gid)) == NULL)) {
847                 return NT_STATUS_NO_SUCH_GROUP;
848         }
849
850         group_name = talloc_strdup(mem_ctx, grp->gr_name);
851         if (group_name == NULL) {
852                 return NT_STATUS_NO_MEMORY;
853         }
854
855         if ( !(account = samu_new( NULL )) ) {
856                 return NT_STATUS_NO_MEMORY;
857         }
858
859         if (!pdb_getsampwsid(account, &member_sid) ||
860             !sid_to_uid(&member_sid, &uid) ||
861             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
862                 return NT_STATUS_NO_SUCH_USER;
863         }
864
865         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
866                 return NT_STATUS_MEMBER_NOT_IN_GROUP;
867         }
868
869         /* 
870          * ok, the group exist, the user exist, the user is in the group,
871          * we can (finally) delete it from the group!
872          */
873
874         smb_delete_user_group(group_name, pwd->pw_name);
875
876         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
877                 return NT_STATUS_ACCESS_DENIED;
878         }
879
880         return NT_STATUS_OK;
881 }
882
883 NTSTATUS pdb_del_groupmem(TALLOC_CTX *mem_ctx, uint32 group_rid,
884                           uint32 member_rid)
885 {
886         struct pdb_methods *pdb = pdb_get_methods();
887         return pdb->del_groupmem(pdb, mem_ctx, group_rid, member_rid);
888 }
889
890 BOOL pdb_find_alias(const char *name, DOM_SID *sid)
891 {
892         struct pdb_methods *pdb = pdb_get_methods();
893         return NT_STATUS_IS_OK(pdb->find_alias(pdb, name, sid));
894 }
895
896 NTSTATUS pdb_create_alias(const char *name, uint32 *rid)
897 {
898         struct pdb_methods *pdb = pdb_get_methods();
899         return pdb->create_alias(pdb, name, rid);
900 }
901
902 BOOL pdb_delete_alias(const DOM_SID *sid)
903 {
904         struct pdb_methods *pdb = pdb_get_methods();
905         return NT_STATUS_IS_OK(pdb->delete_alias(pdb, sid));
906                                                             
907 }
908
909 BOOL pdb_get_aliasinfo(const DOM_SID *sid, struct acct_info *info)
910 {
911         struct pdb_methods *pdb = pdb_get_methods();
912         return NT_STATUS_IS_OK(pdb->get_aliasinfo(pdb, sid, info));
913 }
914
915 BOOL pdb_set_aliasinfo(const DOM_SID *sid, struct acct_info *info)
916 {
917         struct pdb_methods *pdb = pdb_get_methods();
918         return NT_STATUS_IS_OK(pdb->set_aliasinfo(pdb, sid, info));
919 }
920
921 NTSTATUS pdb_add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
922 {
923         struct pdb_methods *pdb = pdb_get_methods();
924         return pdb->add_aliasmem(pdb, alias, member);
925 }
926
927 NTSTATUS pdb_del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
928 {
929         struct pdb_methods *pdb = pdb_get_methods();
930         return pdb->del_aliasmem(pdb, alias, member);
931 }
932
933 NTSTATUS pdb_enum_aliasmem(const DOM_SID *alias,
934                            DOM_SID **pp_members, size_t *p_num_members)
935 {
936         struct pdb_methods *pdb = pdb_get_methods();
937         return pdb->enum_aliasmem(pdb, alias, pp_members, p_num_members);
938 }
939
940 NTSTATUS pdb_enum_alias_memberships(TALLOC_CTX *mem_ctx,
941                                     const DOM_SID *domain_sid,
942                                     const DOM_SID *members, size_t num_members,
943                                     uint32 **pp_alias_rids,
944                                     size_t *p_num_alias_rids)
945 {
946         struct pdb_methods *pdb = pdb_get_methods();
947         return pdb->enum_alias_memberships(pdb, mem_ctx,
948                                                        domain_sid,
949                                                        members, num_members,
950                                                        pp_alias_rids,
951                                                        p_num_alias_rids);
952 }
953
954 NTSTATUS pdb_lookup_rids(const DOM_SID *domain_sid,
955                          int num_rids,
956                          uint32 *rids,
957                          const char **names,
958                          enum lsa_SidType *attrs)
959 {
960         struct pdb_methods *pdb = pdb_get_methods();
961         return pdb->lookup_rids(pdb, domain_sid, num_rids, rids, names, attrs);
962 }
963
964 NTSTATUS pdb_lookup_names(const DOM_SID *domain_sid,
965                           int num_names,
966                           const char **names,
967                           uint32 *rids,
968                           enum lsa_SidType *attrs)
969 {
970         struct pdb_methods *pdb = pdb_get_methods();
971         return pdb->lookup_names(pdb, domain_sid, num_names, names, rids, attrs);
972 }
973
974 BOOL pdb_get_account_policy(int policy_index, uint32 *value)
975 {
976         struct pdb_methods *pdb = pdb_get_methods();
977         return NT_STATUS_IS_OK(pdb->get_account_policy(pdb, policy_index, value));
978 }
979
980 BOOL pdb_set_account_policy(int policy_index, uint32 value)
981 {
982         struct pdb_methods *pdb = pdb_get_methods();
983         return NT_STATUS_IS_OK(pdb->set_account_policy(pdb, policy_index, value));
984 }
985
986 BOOL pdb_get_seq_num(time_t *seq_num)
987 {
988         struct pdb_methods *pdb = pdb_get_methods();
989         return NT_STATUS_IS_OK(pdb->get_seq_num(pdb, seq_num));
990 }
991
992 BOOL pdb_uid_to_rid(uid_t uid, uint32 *rid)
993 {
994         struct pdb_methods *pdb = pdb_get_methods();
995         return pdb->uid_to_rid(pdb, uid, rid);
996 }
997
998 BOOL pdb_gid_to_sid(gid_t gid, DOM_SID *sid)
999 {
1000         struct pdb_methods *pdb = pdb_get_methods();
1001         return pdb->gid_to_sid(pdb, gid, sid);
1002 }
1003
1004 BOOL pdb_sid_to_id(const DOM_SID *sid, union unid_t *id,
1005                    enum lsa_SidType *type)
1006 {
1007         struct pdb_methods *pdb = pdb_get_methods();
1008         return pdb->sid_to_id(pdb, sid, id, type);
1009 }
1010
1011 BOOL pdb_rid_algorithm(void)
1012 {
1013         struct pdb_methods *pdb = pdb_get_methods();
1014         return pdb->rid_algorithm(pdb);
1015 }
1016
1017 /********************************************************************
1018  Allocate a new RID from the passdb backend.  Verify that it is free
1019  by calling lookup_global_sam_rid() to verify that the RID is not
1020  in use.  This handles servers that have existing users or groups
1021  with add RIDs (assigned from previous algorithmic mappings)
1022 ********************************************************************/
1023
1024 BOOL pdb_new_rid(uint32 *rid)
1025 {
1026         struct pdb_methods *pdb = pdb_get_methods();
1027         const char *name = NULL;
1028         enum lsa_SidType type;
1029         uint32 allocated_rid = 0;
1030         int i;
1031         TALLOC_CTX *ctx;
1032
1033         if (pdb_rid_algorithm()) {
1034                 DEBUG(0, ("Trying to allocate a RID when algorithmic RIDs "
1035                           "are active\n"));
1036                 return False;
1037         }
1038
1039         if (algorithmic_rid_base() != BASE_RID) {
1040                 DEBUG(0, ("'algorithmic rid base' is set but a passdb backend "
1041                           "without algorithmic RIDs is chosen.\n"));
1042                 DEBUGADD(0, ("Please map all used groups using 'net groupmap "
1043                              "add', set the maximum used RID using\n"));
1044                 DEBUGADD(0, ("'net setmaxrid' and remove the parameter\n"));
1045                 return False;
1046         }
1047
1048         if ( (ctx = talloc_init("pdb_new_rid")) == NULL ) {
1049                 DEBUG(0,("pdb_new_rid: Talloc initialization failure\n"));
1050                 return False;
1051         }
1052
1053         /* Attempt to get an unused RID (max tires is 250...yes that it is 
1054            and arbitrary number I pulkled out of my head).   -- jerry */
1055
1056         for ( i=0; allocated_rid==0 && i<250; i++ ) {
1057                 /* get a new RID */
1058
1059                 if ( !pdb->new_rid(pdb, &allocated_rid) ) {
1060                         return False;
1061                 }
1062
1063                 /* validate that the RID is not in use */
1064
1065                 if ( lookup_global_sam_rid( ctx, allocated_rid, &name, &type, NULL ) ) {
1066                         allocated_rid = 0;
1067                 }
1068         }
1069
1070         TALLOC_FREE( ctx );
1071
1072         if ( allocated_rid == 0 ) {
1073                 DEBUG(0,("pdb_new_rid: Failed to find unused RID\n"));
1074                 return False;
1075         }
1076
1077         *rid = allocated_rid;
1078
1079         return True;
1080 }
1081
1082 /***************************************************************
1083   Initialize the static context (at smbd startup etc). 
1084
1085   If uninitialised, context will auto-init on first use.
1086  ***************************************************************/
1087
1088 BOOL initialize_password_db(BOOL reload)
1089 {       
1090         return (pdb_get_methods_reload(reload) != NULL);
1091 }
1092
1093
1094 /***************************************************************************
1095   Default implementations of some functions.
1096  ****************************************************************************/
1097
1098 static NTSTATUS pdb_default_getsampwnam (struct pdb_methods *methods, struct samu *user, const char *sname)
1099 {
1100         return NT_STATUS_NO_SUCH_USER;
1101 }
1102
1103 static NTSTATUS pdb_default_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1104 {
1105         return NT_STATUS_NO_SUCH_USER;
1106 }
1107
1108 static NTSTATUS pdb_default_add_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1109 {
1110         return NT_STATUS_NOT_IMPLEMENTED;
1111 }
1112
1113 static NTSTATUS pdb_default_update_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1114 {
1115         return NT_STATUS_NOT_IMPLEMENTED;
1116 }
1117
1118 static NTSTATUS pdb_default_delete_sam_account (struct pdb_methods *methods, struct samu *pwd)
1119 {
1120         return NT_STATUS_NOT_IMPLEMENTED;
1121 }
1122
1123 static NTSTATUS pdb_default_rename_sam_account (struct pdb_methods *methods, struct samu *pwd, const char *newname)
1124 {
1125         return NT_STATUS_NOT_IMPLEMENTED;
1126 }
1127
1128 static NTSTATUS pdb_default_update_login_attempts (struct pdb_methods *methods, struct samu *newpwd, BOOL success)
1129 {
1130         return NT_STATUS_OK;
1131 }
1132
1133 static NTSTATUS pdb_default_setsampwent(struct pdb_methods *methods, BOOL update, uint32 acb_mask)
1134 {
1135         return NT_STATUS_NOT_IMPLEMENTED;
1136 }
1137
1138 static NTSTATUS pdb_default_getsampwent(struct pdb_methods *methods, struct samu *user)
1139 {
1140         return NT_STATUS_NOT_IMPLEMENTED;
1141 }
1142
1143 static void pdb_default_endsampwent(struct pdb_methods *methods)
1144 {
1145         return; /* NT_STATUS_NOT_IMPLEMENTED; */
1146 }
1147
1148 static NTSTATUS pdb_default_get_account_policy(struct pdb_methods *methods, int policy_index, uint32 *value)
1149 {
1150         return account_policy_get(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1151 }
1152
1153 static NTSTATUS pdb_default_set_account_policy(struct pdb_methods *methods, int policy_index, uint32 value)
1154 {
1155         return account_policy_set(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1156 }
1157
1158 static NTSTATUS pdb_default_get_seq_num(struct pdb_methods *methods, time_t *seq_num)
1159 {
1160         *seq_num = time(NULL);
1161         return NT_STATUS_OK;
1162 }
1163
1164 static BOOL pdb_default_uid_to_rid(struct pdb_methods *methods, uid_t uid,
1165                                    uint32 *rid)
1166 {
1167         struct samu *sampw = NULL;
1168         struct passwd *unix_pw;
1169         BOOL ret;
1170         
1171         unix_pw = sys_getpwuid( uid );
1172
1173         if ( !unix_pw ) {
1174                 DEBUG(4,("pdb_default_uid_to_rid: host has no idea of uid "
1175                          "%lu\n", (unsigned long)uid));
1176                 return False;
1177         }
1178         
1179         if ( !(sampw = samu_new( NULL )) ) {
1180                 DEBUG(0,("pdb_default_uid_to_rid: samu_new() failed!\n"));
1181                 return False;
1182         }
1183
1184         become_root();
1185         ret = NT_STATUS_IS_OK(
1186                 methods->getsampwnam(methods, sampw, unix_pw->pw_name ));
1187         unbecome_root();
1188
1189         if (!ret) {
1190                 DEBUG(5, ("pdb_default_uid_to_rid: Did not find user "
1191                           "%s (%d)\n", unix_pw->pw_name, uid));
1192                 TALLOC_FREE(sampw);
1193                 return False;
1194         }
1195
1196         ret = sid_peek_check_rid(get_global_sam_sid(),
1197                                  pdb_get_user_sid(sampw), rid);
1198
1199         if (!ret) {
1200                 DEBUG(1, ("Could not peek rid out of sid %s\n",
1201                           sid_string_static(pdb_get_user_sid(sampw))));
1202         }
1203
1204         TALLOC_FREE(sampw);
1205         return ret;
1206 }
1207
1208 static BOOL pdb_default_gid_to_sid(struct pdb_methods *methods, gid_t gid,
1209                                    DOM_SID *sid)
1210 {
1211         GROUP_MAP map;
1212
1213         if (!NT_STATUS_IS_OK(methods->getgrgid(methods, &map, gid))) {
1214                 return False;
1215         }
1216
1217         sid_copy(sid, &map.sid);
1218         return True;
1219 }
1220
1221 static BOOL pdb_default_sid_to_id(struct pdb_methods *methods,
1222                                   const DOM_SID *sid,
1223                                   union unid_t *id, enum lsa_SidType *type)
1224 {
1225         TALLOC_CTX *mem_ctx;
1226         BOOL ret = False;
1227         const char *name;
1228         uint32 rid;
1229
1230         mem_ctx = talloc_new(NULL);
1231
1232         if (mem_ctx == NULL) {
1233                 DEBUG(0, ("talloc_new failed\n"));
1234                 return False;
1235         }
1236
1237         if (sid_peek_check_rid(get_global_sam_sid(), sid, &rid)) {
1238                 /* Here we might have users as well as groups and aliases */
1239                 ret = lookup_global_sam_rid(mem_ctx, rid, &name, type, id);
1240                 goto done;
1241         }
1242
1243         if (sid_peek_check_rid(&global_sid_Builtin, sid, &rid)) {
1244                 /* Here we only have aliases */
1245                 GROUP_MAP map;
1246                 if (!NT_STATUS_IS_OK(methods->getgrsid(methods, &map, *sid))) {
1247                         DEBUG(10, ("Could not find map for sid %s\n",
1248                                    sid_string_static(sid)));
1249                         goto done;
1250                 }
1251                 if ((map.sid_name_use != SID_NAME_ALIAS) &&
1252                     (map.sid_name_use != SID_NAME_WKN_GRP)) {
1253                         DEBUG(10, ("Map for sid %s is a %s, expected an "
1254                                    "alias\n", sid_string_static(sid),
1255                                    sid_type_lookup(map.sid_name_use)));
1256                         goto done;
1257                 }
1258
1259                 id->gid = map.gid;
1260                 *type = SID_NAME_ALIAS;
1261                 ret = True;
1262                 goto done;
1263         }
1264
1265         DEBUG(5, ("Sid %s is neither ours nor builtin, don't know it\n",
1266                   sid_string_static(sid)));
1267
1268  done:
1269
1270         TALLOC_FREE(mem_ctx);
1271         return ret;
1272 }
1273
1274 static BOOL add_uid_to_array_unique(TALLOC_CTX *mem_ctx,
1275                                     uid_t uid, uid_t **pp_uids, size_t *p_num)
1276 {
1277         size_t i;
1278
1279         for (i=0; i<*p_num; i++) {
1280                 if ((*pp_uids)[i] == uid)
1281                         return True;
1282         }
1283         
1284         *pp_uids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_uids, uid_t, *p_num+1);
1285
1286         if (*pp_uids == NULL)
1287                 return False;
1288
1289         (*pp_uids)[*p_num] = uid;
1290         *p_num += 1;
1291         return True;
1292 }
1293
1294 static BOOL get_memberuids(TALLOC_CTX *mem_ctx, gid_t gid, uid_t **pp_uids, size_t *p_num)
1295 {
1296         struct group *grp;
1297         char **gr;
1298         struct passwd *pwd;
1299         BOOL winbind_env;
1300         BOOL ret = False;
1301  
1302         *pp_uids = NULL;
1303         *p_num = 0;
1304
1305         /* We only look at our own sam, so don't care about imported stuff */
1306         winbind_env = winbind_env_set();
1307         winbind_off();
1308
1309         if ((grp = getgrgid(gid)) == NULL) {
1310                 /* allow winbindd lookups, but only if they weren't already disabled */
1311                 goto done;
1312         }
1313
1314         /* Primary group members */
1315         setpwent();
1316         while ((pwd = getpwent()) != NULL) {
1317                 if (pwd->pw_gid == gid) {
1318                         if (!add_uid_to_array_unique(mem_ctx, pwd->pw_uid,
1319                                                 pp_uids, p_num)) {
1320                                 goto done;
1321                         }
1322                 }
1323         }
1324         endpwent();
1325
1326         /* Secondary group members */
1327         for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
1328                 struct passwd *pw = getpwnam(*gr);
1329
1330                 if (pw == NULL)
1331                         continue;
1332                 if (!add_uid_to_array_unique(mem_ctx, pw->pw_uid, pp_uids, p_num)) {
1333                         goto done;
1334                 }
1335         }
1336
1337         ret = True;
1338
1339   done:
1340
1341         /* allow winbindd lookups, but only if they weren't already disabled */
1342         if (!winbind_env) {
1343                 winbind_on();
1344         }
1345         
1346         return ret;
1347 }
1348
1349 NTSTATUS pdb_default_enum_group_members(struct pdb_methods *methods,
1350                                         TALLOC_CTX *mem_ctx,
1351                                         const DOM_SID *group,
1352                                         uint32 **pp_member_rids,
1353                                         size_t *p_num_members)
1354 {
1355         gid_t gid;
1356         uid_t *uids;
1357         size_t i, num_uids;
1358
1359         *pp_member_rids = NULL;
1360         *p_num_members = 0;
1361
1362         if (!sid_to_gid(group, &gid))
1363                 return NT_STATUS_NO_SUCH_GROUP;
1364
1365         if(!get_memberuids(mem_ctx, gid, &uids, &num_uids))
1366                 return NT_STATUS_NO_SUCH_GROUP;
1367
1368         if (num_uids == 0)
1369                 return NT_STATUS_OK;
1370
1371         *pp_member_rids = TALLOC_ZERO_ARRAY(mem_ctx, uint32, num_uids);
1372
1373         for (i=0; i<num_uids; i++) {
1374                 DOM_SID sid;
1375
1376                 uid_to_sid(&sid, uids[i]);
1377
1378                 if (!sid_check_is_in_our_domain(&sid)) {
1379                         DEBUG(5, ("Inconsistent SAM -- group member uid not "
1380                                   "in our domain\n"));
1381                         continue;
1382                 }
1383
1384                 sid_peek_rid(&sid, &(*pp_member_rids)[*p_num_members]);
1385                 *p_num_members += 1;
1386         }
1387
1388         return NT_STATUS_OK;
1389 }
1390
1391 NTSTATUS pdb_default_enum_group_memberships(struct pdb_methods *methods,
1392                                             TALLOC_CTX *mem_ctx,
1393                                             struct samu *user,
1394                                             DOM_SID **pp_sids,
1395                                             gid_t **pp_gids,
1396                                             size_t *p_num_groups)
1397 {
1398         size_t i;
1399         gid_t gid;
1400         struct passwd *pw;
1401         const char *username = pdb_get_username(user);
1402         
1403
1404         /* Ignore the primary group SID.  Honor the real Unix primary group.
1405            The primary group SID is only of real use to Windows clients */
1406            
1407         if ( !(pw = getpwnam_alloc(mem_ctx, username)) ) {
1408                 return NT_STATUS_NO_SUCH_USER;
1409         }
1410         
1411         gid = pw->pw_gid;
1412         
1413         TALLOC_FREE( pw );
1414
1415         if (!getgroups_unix_user(mem_ctx, username, gid, pp_gids, p_num_groups)) {
1416                 return NT_STATUS_NO_SUCH_USER;
1417         }
1418
1419         if (*p_num_groups == 0) {
1420                 smb_panic("primary group missing");
1421         }
1422
1423         *pp_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, *p_num_groups);
1424
1425         if (*pp_sids == NULL) {
1426                 TALLOC_FREE(*pp_gids);
1427                 return NT_STATUS_NO_MEMORY;
1428         }
1429
1430         for (i=0; i<*p_num_groups; i++) {
1431                 gid_to_sid(&(*pp_sids)[i], (*pp_gids)[i]);
1432         }
1433
1434         return NT_STATUS_OK;
1435 }
1436
1437 /*******************************************************************
1438  Look up a rid in the SAM we're responsible for (i.e. passdb)
1439  ********************************************************************/
1440
1441 static BOOL lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32 rid,
1442                                   const char **name,
1443                                   enum lsa_SidType *psid_name_use,
1444                                   union unid_t *unix_id)
1445 {
1446         struct samu *sam_account = NULL;
1447         GROUP_MAP map;
1448         BOOL ret;
1449         DOM_SID sid;
1450
1451         *psid_name_use = SID_NAME_UNKNOWN;
1452         
1453         DEBUG(5,("lookup_global_sam_rid: looking up RID %u.\n",
1454                  (unsigned int)rid));
1455
1456         sid_copy(&sid, get_global_sam_sid());
1457         sid_append_rid(&sid, rid);
1458         
1459         /* see if the passdb can help us with the name of the user */
1460
1461         if ( !(sam_account = samu_new( NULL )) ) {
1462                 return False;
1463         }
1464
1465         /* BEING ROOT BLLOCK */
1466         become_root();
1467         if (pdb_getsampwsid(sam_account, &sid)) {
1468                 struct passwd *pw;
1469
1470                 unbecome_root();                /* -----> EXIT BECOME_ROOT() */
1471                 *name = talloc_strdup(mem_ctx, pdb_get_username(sam_account));
1472                 if (!*name) {
1473                         TALLOC_FREE(sam_account);
1474                         return False;
1475                 }
1476
1477                 *psid_name_use = SID_NAME_USER;
1478
1479                 TALLOC_FREE(sam_account);
1480
1481                 if (unix_id == NULL) {
1482                         return True;
1483                 }
1484
1485                 pw = Get_Pwnam(*name);
1486                 if (pw == NULL) {
1487                         return False;
1488                 }
1489                 unix_id->uid = pw->pw_uid;
1490                 return True;
1491         }
1492         TALLOC_FREE(sam_account);
1493         
1494         ret = pdb_getgrsid(&map, sid);
1495         unbecome_root();
1496         /* END BECOME_ROOT BLOCK */
1497   
1498         /* do not resolve SIDs to a name unless there is a valid 
1499            gid associated with it */
1500                    
1501         if ( ret && (map.gid != (gid_t)-1) ) {
1502                 *name = talloc_strdup(mem_ctx, map.nt_name);
1503                 *psid_name_use = map.sid_name_use;
1504
1505                 if ( unix_id ) {
1506                         unix_id->gid = map.gid;
1507                 }
1508
1509                 return True;
1510         }
1511         
1512         /* Windows will always map RID 513 to something.  On a non-domain 
1513            controller, this gets mapped to SERVER\None. */
1514
1515         if ( unix_id ) {
1516                 DEBUG(5, ("Can't find a unix id for an unmapped group\n"));
1517                 return False;
1518         }
1519         
1520         if ( rid == DOMAIN_GROUP_RID_USERS ) {
1521                 *name = talloc_strdup(mem_ctx, "None" );
1522                 *psid_name_use = SID_NAME_DOM_GRP;
1523                 
1524                 return True;
1525         }
1526
1527         return False;
1528 }
1529
1530 NTSTATUS pdb_default_lookup_rids(struct pdb_methods *methods,
1531                                  const DOM_SID *domain_sid,
1532                                  int num_rids,
1533                                  uint32 *rids,
1534                                  const char **names,
1535                                  enum lsa_SidType *attrs)
1536 {
1537         int i;
1538         NTSTATUS result;
1539         BOOL have_mapped = False;
1540         BOOL have_unmapped = False;
1541
1542         if (sid_check_is_builtin(domain_sid)) {
1543
1544                 for (i=0; i<num_rids; i++) {
1545                         const char *name;
1546
1547                         if (lookup_builtin_rid(names, rids[i], &name)) {
1548                                 attrs[i] = SID_NAME_ALIAS;
1549                                 names[i] = name;
1550                                 DEBUG(5,("lookup_rids: %s:%d\n",
1551                                          names[i], attrs[i]));
1552                                 have_mapped = True;
1553                         } else {
1554                                 have_unmapped = True;
1555                                 attrs[i] = SID_NAME_UNKNOWN;
1556                         }
1557                 }
1558                 goto done;
1559         }
1560
1561         /* Should not happen, but better check once too many */
1562         if (!sid_check_is_domain(domain_sid)) {
1563                 return NT_STATUS_INVALID_HANDLE;
1564         }
1565
1566         for (i = 0; i < num_rids; i++) {
1567                 const char *name;
1568
1569                 if (lookup_global_sam_rid(names, rids[i], &name, &attrs[i],
1570                                           NULL)) {
1571                         if (name == NULL) {
1572                                 return NT_STATUS_NO_MEMORY;
1573                         }
1574                         names[i] = name;
1575                         DEBUG(5,("lookup_rids: %s:%d\n", names[i], attrs[i]));
1576                         have_mapped = True;
1577                 } else {
1578                         have_unmapped = True;
1579                         attrs[i] = SID_NAME_UNKNOWN;
1580                 }
1581         }
1582
1583  done:
1584
1585         result = NT_STATUS_NONE_MAPPED;
1586
1587         if (have_mapped)
1588                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1589
1590         return result;
1591 }
1592
1593 NTSTATUS pdb_default_lookup_names(struct pdb_methods *methods,
1594                                   const DOM_SID *domain_sid,
1595                                   int num_names,
1596                                   const char **names,
1597                                   uint32 *rids,
1598                                   enum lsa_SidType *attrs)
1599 {
1600         int i;
1601         NTSTATUS result;
1602         BOOL have_mapped = False;
1603         BOOL have_unmapped = False;
1604
1605         if (sid_check_is_builtin(domain_sid)) {
1606
1607                 for (i=0; i<num_names; i++) {
1608                         uint32 rid;
1609
1610                         if (lookup_builtin_name(names[i], &rid)) {
1611                                 attrs[i] = SID_NAME_ALIAS;
1612                                 rids[i] = rid;
1613                                 DEBUG(5,("lookup_rids: %s:%d\n",
1614                                          names[i], attrs[i]));
1615                                 have_mapped = True;
1616                         } else {
1617                                 have_unmapped = True;
1618                                 attrs[i] = SID_NAME_UNKNOWN;
1619                         }
1620                 }
1621                 goto done;
1622         }
1623
1624         /* Should not happen, but better check once too many */
1625         if (!sid_check_is_domain(domain_sid)) {
1626                 return NT_STATUS_INVALID_HANDLE;
1627         }
1628
1629         for (i = 0; i < num_names; i++) {
1630                 if (lookup_global_sam_name(names[i], 0, &rids[i], &attrs[i])) {
1631                         DEBUG(5,("lookup_names: %s-> %d:%d\n", names[i],
1632                                  rids[i], attrs[i]));
1633                         have_mapped = True;
1634                 } else {
1635                         have_unmapped = True;
1636                         attrs[i] = SID_NAME_UNKNOWN;
1637                 }
1638         }
1639
1640  done:
1641
1642         result = NT_STATUS_NONE_MAPPED;
1643
1644         if (have_mapped)
1645                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1646
1647         return result;
1648 }
1649
1650 static struct pdb_search *pdb_search_init(enum pdb_search_type type)
1651 {
1652         TALLOC_CTX *mem_ctx;
1653         struct pdb_search *result;
1654
1655         mem_ctx = talloc_init("pdb_search");
1656         if (mem_ctx == NULL) {
1657                 DEBUG(0, ("talloc_init failed\n"));
1658                 return NULL;
1659         }
1660
1661         result = TALLOC_P(mem_ctx, struct pdb_search);
1662         if (result == NULL) {
1663                 DEBUG(0, ("talloc failed\n"));
1664                 return NULL;
1665         }
1666
1667         result->mem_ctx = mem_ctx;
1668         result->type = type;
1669         result->cache = NULL;
1670         result->num_entries = 0;
1671         result->cache_size = 0;
1672         result->search_ended = False;
1673
1674         /* Segfault appropriately if not initialized */
1675         result->next_entry = NULL;
1676         result->search_end = NULL;
1677
1678         return result;
1679 }
1680
1681 static void fill_displayentry(TALLOC_CTX *mem_ctx, uint32 rid,
1682                               uint16 acct_flags,
1683                               const char *account_name,
1684                               const char *fullname,
1685                               const char *description,
1686                               struct samr_displayentry *entry)
1687 {
1688         entry->rid = rid;
1689         entry->acct_flags = acct_flags;
1690
1691         if (account_name != NULL)
1692                 entry->account_name = talloc_strdup(mem_ctx, account_name);
1693         else
1694                 entry->account_name = "";
1695
1696         if (fullname != NULL)
1697                 entry->fullname = talloc_strdup(mem_ctx, fullname);
1698         else
1699                 entry->fullname = "";
1700
1701         if (description != NULL)
1702                 entry->description = talloc_strdup(mem_ctx, description);
1703         else
1704                 entry->description = "";
1705 }
1706
1707 static BOOL user_search_in_progress = False;
1708 struct user_search {
1709         uint16 acct_flags;
1710 };
1711
1712 static BOOL next_entry_users(struct pdb_search *s,
1713                              struct samr_displayentry *entry)
1714 {
1715         struct user_search *state = (struct user_search *)s->private_data;
1716         struct samu *user = NULL;
1717
1718  next:
1719         if ( !(user = samu_new( NULL )) ) {
1720                 DEBUG(0, ("next_entry_users: samu_new() failed!\n"));
1721                 return False;
1722         }
1723
1724         if (!pdb_getsampwent(user)) {
1725                 TALLOC_FREE(user);
1726                 return False;
1727         }
1728
1729         if ((state->acct_flags != 0) &&
1730             ((pdb_get_acct_ctrl(user) & state->acct_flags) == 0)) {
1731                 TALLOC_FREE(user);
1732                 goto next;
1733         }
1734
1735         fill_displayentry(s->mem_ctx, pdb_get_user_rid(user),
1736                           pdb_get_acct_ctrl(user), pdb_get_username(user),
1737                           pdb_get_fullname(user), pdb_get_acct_desc(user),
1738                           entry);
1739
1740         TALLOC_FREE(user);
1741         return True;
1742 }
1743
1744 static void search_end_users(struct pdb_search *search)
1745 {
1746         pdb_endsampwent();
1747         user_search_in_progress = False;
1748 }
1749
1750 static BOOL pdb_default_search_users(struct pdb_methods *methods,
1751                                      struct pdb_search *search,
1752                                      uint32 acct_flags)
1753 {
1754         struct user_search *state;
1755
1756         if (user_search_in_progress) {
1757                 DEBUG(1, ("user search in progress\n"));
1758                 return False;
1759         }
1760
1761         if (!pdb_setsampwent(False, acct_flags)) {
1762                 DEBUG(5, ("Could not start search\n"));
1763                 return False;
1764         }
1765
1766         user_search_in_progress = True;
1767
1768         state = TALLOC_P(search->mem_ctx, struct user_search);
1769         if (state == NULL) {
1770                 DEBUG(0, ("talloc failed\n"));
1771                 return False;
1772         }
1773
1774         state->acct_flags = acct_flags;
1775
1776         search->private_data = state;
1777         search->next_entry = next_entry_users;
1778         search->search_end = search_end_users;
1779         return True;
1780 }
1781
1782 struct group_search {
1783         GROUP_MAP *groups;
1784         size_t num_groups, current_group;
1785 };
1786
1787 static BOOL next_entry_groups(struct pdb_search *s,
1788                               struct samr_displayentry *entry)
1789 {
1790         struct group_search *state = (struct group_search *)s->private_data;
1791         uint32 rid;
1792         GROUP_MAP *map = &state->groups[state->current_group];
1793
1794         if (state->current_group == state->num_groups)
1795                 return False;
1796
1797         sid_peek_rid(&map->sid, &rid);
1798
1799         fill_displayentry(s->mem_ctx, rid, 0, map->nt_name, NULL, map->comment,
1800                           entry);
1801
1802         state->current_group += 1;
1803         return True;
1804 }
1805
1806 static void search_end_groups(struct pdb_search *search)
1807 {
1808         struct group_search *state =
1809                 (struct group_search *)search->private_data;
1810         SAFE_FREE(state->groups);
1811 }
1812
1813 static BOOL pdb_search_grouptype(struct pdb_search *search,
1814                                  const DOM_SID *sid, enum lsa_SidType type)
1815 {
1816         struct group_search *state;
1817
1818         state = TALLOC_P(search->mem_ctx, struct group_search);
1819         if (state == NULL) {
1820                 DEBUG(0, ("talloc failed\n"));
1821                 return False;
1822         }
1823
1824         if (!pdb_enum_group_mapping(sid, type, &state->groups, &state->num_groups,
1825                                     True)) {
1826                 DEBUG(0, ("Could not enum groups\n"));
1827                 return False;
1828         }
1829
1830         state->current_group = 0;
1831         search->private_data = state;
1832         search->next_entry = next_entry_groups;
1833         search->search_end = search_end_groups;
1834         return True;
1835 }
1836
1837 static BOOL pdb_default_search_groups(struct pdb_methods *methods,
1838                                       struct pdb_search *search)
1839 {
1840         return pdb_search_grouptype(search, get_global_sam_sid(), SID_NAME_DOM_GRP);
1841 }
1842
1843 static BOOL pdb_default_search_aliases(struct pdb_methods *methods,
1844                                        struct pdb_search *search,
1845                                        const DOM_SID *sid)
1846 {
1847
1848         return pdb_search_grouptype(search, sid, SID_NAME_ALIAS);
1849 }
1850
1851 static struct samr_displayentry *pdb_search_getentry(struct pdb_search *search,
1852                                                      uint32 idx)
1853 {
1854         if (idx < search->num_entries)
1855                 return &search->cache[idx];
1856
1857         if (search->search_ended)
1858                 return NULL;
1859
1860         while (idx >= search->num_entries) {
1861                 struct samr_displayentry entry;
1862
1863                 if (!search->next_entry(search, &entry)) {
1864                         search->search_end(search);
1865                         search->search_ended = True;
1866                         break;
1867                 }
1868
1869                 ADD_TO_LARGE_ARRAY(search->mem_ctx, struct samr_displayentry,
1870                                    entry, &search->cache, &search->num_entries,
1871                                    &search->cache_size);
1872         }
1873
1874         return (search->num_entries > idx) ? &search->cache[idx] : NULL;
1875 }
1876
1877 struct pdb_search *pdb_search_users(uint32 acct_flags)
1878 {
1879         struct pdb_methods *pdb = pdb_get_methods();
1880         struct pdb_search *result;
1881
1882         result = pdb_search_init(PDB_USER_SEARCH);
1883         if (result == NULL) {
1884                 return NULL;
1885         }
1886
1887         if (!pdb->search_users(pdb, result, acct_flags)) {
1888                 talloc_destroy(result->mem_ctx);
1889                 return NULL;
1890         }
1891         return result;
1892 }
1893
1894 struct pdb_search *pdb_search_groups(void)
1895 {
1896         struct pdb_methods *pdb = pdb_get_methods();
1897         struct pdb_search *result;
1898
1899         result = pdb_search_init(PDB_GROUP_SEARCH);
1900         if (result == NULL) {
1901                  return NULL;
1902         }
1903
1904         if (!pdb->search_groups(pdb, result)) {
1905                 talloc_destroy(result->mem_ctx);
1906                 return NULL;
1907         }
1908         return result;
1909 }
1910
1911 struct pdb_search *pdb_search_aliases(const DOM_SID *sid)
1912 {
1913         struct pdb_methods *pdb = pdb_get_methods();
1914         struct pdb_search *result;
1915
1916         if (pdb == NULL) return NULL;
1917
1918         result = pdb_search_init(PDB_ALIAS_SEARCH);
1919         if (result == NULL) return NULL;
1920
1921         if (!pdb->search_aliases(pdb, result, sid)) {
1922                 talloc_destroy(result->mem_ctx);
1923                 return NULL;
1924         }
1925         return result;
1926 }
1927
1928 uint32 pdb_search_entries(struct pdb_search *search,
1929                           uint32 start_idx, uint32 max_entries,
1930                           struct samr_displayentry **result)
1931 {
1932         struct samr_displayentry *end_entry;
1933         uint32 end_idx = start_idx+max_entries-1;
1934
1935         /* The first entry needs to be searched after the last. Otherwise the
1936          * first entry might have moved due to a realloc during the search for
1937          * the last entry. */
1938
1939         end_entry = pdb_search_getentry(search, end_idx);
1940         *result = pdb_search_getentry(search, start_idx);
1941
1942         if (end_entry != NULL)
1943                 return max_entries;
1944
1945         if (start_idx >= search->num_entries)
1946                 return 0;
1947
1948         return search->num_entries - start_idx;
1949 }
1950
1951 void pdb_search_destroy(struct pdb_search *search)
1952 {
1953         if (search == NULL)
1954                 return;
1955
1956         if (!search->search_ended)
1957                 search->search_end(search);
1958
1959         talloc_destroy(search->mem_ctx);
1960 }
1961
1962 /*******************************************************************
1963  Create a pdb_methods structure and initialize it with the default
1964  operations.  In this way a passdb module can simply implement
1965  the functionality it cares about.  However, normally this is done 
1966  in groups of related functions.
1967 *******************************************************************/
1968
1969 NTSTATUS make_pdb_method( struct pdb_methods **methods ) 
1970 {
1971         /* allocate memory for the structure as its own talloc CTX */
1972
1973         if ( !(*methods = TALLOC_ZERO_P(NULL, struct pdb_methods) ) ) {
1974                 return NT_STATUS_NO_MEMORY;
1975         }
1976
1977         (*methods)->setsampwent = pdb_default_setsampwent;
1978         (*methods)->endsampwent = pdb_default_endsampwent;
1979         (*methods)->getsampwent = pdb_default_getsampwent;
1980         (*methods)->getsampwnam = pdb_default_getsampwnam;
1981         (*methods)->getsampwsid = pdb_default_getsampwsid;
1982         (*methods)->create_user = pdb_default_create_user;
1983         (*methods)->delete_user = pdb_default_delete_user;
1984         (*methods)->add_sam_account = pdb_default_add_sam_account;
1985         (*methods)->update_sam_account = pdb_default_update_sam_account;
1986         (*methods)->delete_sam_account = pdb_default_delete_sam_account;
1987         (*methods)->rename_sam_account = pdb_default_rename_sam_account;
1988         (*methods)->update_login_attempts = pdb_default_update_login_attempts;
1989
1990         (*methods)->getgrsid = pdb_default_getgrsid;
1991         (*methods)->getgrgid = pdb_default_getgrgid;
1992         (*methods)->getgrnam = pdb_default_getgrnam;
1993         (*methods)->create_dom_group = pdb_default_create_dom_group;
1994         (*methods)->delete_dom_group = pdb_default_delete_dom_group;
1995         (*methods)->add_group_mapping_entry = pdb_default_add_group_mapping_entry;
1996         (*methods)->update_group_mapping_entry = pdb_default_update_group_mapping_entry;
1997         (*methods)->delete_group_mapping_entry = pdb_default_delete_group_mapping_entry;
1998         (*methods)->enum_group_mapping = pdb_default_enum_group_mapping;
1999         (*methods)->enum_group_members = pdb_default_enum_group_members;
2000         (*methods)->enum_group_memberships = pdb_default_enum_group_memberships;
2001         (*methods)->set_unix_primary_group = pdb_default_set_unix_primary_group;
2002         (*methods)->add_groupmem = pdb_default_add_groupmem;
2003         (*methods)->del_groupmem = pdb_default_del_groupmem;
2004         (*methods)->find_alias = pdb_default_find_alias;
2005         (*methods)->create_alias = pdb_default_create_alias;
2006         (*methods)->delete_alias = pdb_default_delete_alias;
2007         (*methods)->get_aliasinfo = pdb_default_get_aliasinfo;
2008         (*methods)->set_aliasinfo = pdb_default_set_aliasinfo;
2009         (*methods)->add_aliasmem = pdb_default_add_aliasmem;
2010         (*methods)->del_aliasmem = pdb_default_del_aliasmem;
2011         (*methods)->enum_aliasmem = pdb_default_enum_aliasmem;
2012         (*methods)->enum_alias_memberships = pdb_default_alias_memberships;
2013         (*methods)->lookup_rids = pdb_default_lookup_rids;
2014         (*methods)->get_account_policy = pdb_default_get_account_policy;
2015         (*methods)->set_account_policy = pdb_default_set_account_policy;
2016         (*methods)->get_seq_num = pdb_default_get_seq_num;
2017         (*methods)->uid_to_rid = pdb_default_uid_to_rid;
2018         (*methods)->gid_to_sid = pdb_default_gid_to_sid;
2019         (*methods)->sid_to_id = pdb_default_sid_to_id;
2020
2021         (*methods)->search_users = pdb_default_search_users;
2022         (*methods)->search_groups = pdb_default_search_groups;
2023         (*methods)->search_aliases = pdb_default_search_aliases;
2024
2025         return NT_STATUS_OK;
2026 }