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