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