r16628: Fix bug #3880, reported by jason@ncac.gwu.edu
[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                          enum SID_NAME_USE *attrs)
960 {
961         struct pdb_methods *pdb = pdb_get_methods();
962         return pdb->lookup_rids(pdb, domain_sid, num_rids, rids, names, attrs);
963 }
964
965 NTSTATUS pdb_lookup_names(const DOM_SID *domain_sid,
966                           int num_names,
967                           const char **names,
968                           uint32 *rids,
969                           enum SID_NAME_USE *attrs)
970 {
971         struct pdb_methods *pdb = pdb_get_methods();
972         return pdb->lookup_names(pdb, domain_sid, num_names, names, rids, attrs);
973 }
974
975 BOOL pdb_get_account_policy(int policy_index, uint32 *value)
976 {
977         struct pdb_methods *pdb = pdb_get_methods();
978         return NT_STATUS_IS_OK(pdb->get_account_policy(pdb, policy_index, value));
979 }
980
981 BOOL pdb_set_account_policy(int policy_index, uint32 value)
982 {
983         struct pdb_methods *pdb = pdb_get_methods();
984         return NT_STATUS_IS_OK(pdb->set_account_policy(pdb, policy_index, value));
985 }
986
987 BOOL pdb_get_seq_num(time_t *seq_num)
988 {
989         struct pdb_methods *pdb = pdb_get_methods();
990         return NT_STATUS_IS_OK(pdb->get_seq_num(pdb, seq_num));
991 }
992
993 BOOL pdb_uid_to_rid(uid_t uid, uint32 *rid)
994 {
995         struct pdb_methods *pdb = pdb_get_methods();
996         return pdb->uid_to_rid(pdb, uid, rid);
997 }
998
999 BOOL pdb_gid_to_sid(gid_t gid, DOM_SID *sid)
1000 {
1001         struct pdb_methods *pdb = pdb_get_methods();
1002         return pdb->gid_to_sid(pdb, gid, sid);
1003 }
1004
1005 BOOL pdb_sid_to_id(const DOM_SID *sid, union unid_t *id,
1006                    enum SID_NAME_USE *type)
1007 {
1008         struct pdb_methods *pdb = pdb_get_methods();
1009         return pdb->sid_to_id(pdb, sid, id, type);
1010 }
1011
1012 BOOL pdb_rid_algorithm(void)
1013 {
1014         struct pdb_methods *pdb = pdb_get_methods();
1015         return pdb->rid_algorithm(pdb);
1016 }
1017
1018 /********************************************************************
1019  Allocate a new RID from the passdb backend.  Verify that it is free
1020  by calling lookup_global_sam_rid() to verify that the RID is not
1021  in use.  This handles servers that have existing users or groups
1022  with add RIDs (assigned from previous algorithmic mappings)
1023 ********************************************************************/
1024
1025 BOOL pdb_new_rid(uint32 *rid)
1026 {
1027         struct pdb_methods *pdb = pdb_get_methods();
1028         const char *name = NULL;
1029         enum SID_NAME_USE type;
1030         uint32 allocated_rid = 0;
1031         int i;
1032         TALLOC_CTX *ctx;
1033
1034         if (pdb_rid_algorithm()) {
1035                 DEBUG(0, ("Trying to allocate a RID when algorithmic RIDs "
1036                           "are active\n"));
1037                 return False;
1038         }
1039
1040         if (algorithmic_rid_base() != BASE_RID) {
1041                 DEBUG(0, ("'algorithmic rid base' is set but a passdb backend "
1042                           "without algorithmic RIDs is chosen.\n"));
1043                 DEBUGADD(0, ("Please map all used groups using 'net groupmap "
1044                              "add', set the maximum used RID using\n"));
1045                 DEBUGADD(0, ("'net setmaxrid' and remove the parameter\n"));
1046                 return False;
1047         }
1048
1049         if ( (ctx = talloc_init("pdb_new_rid")) == NULL ) {
1050                 DEBUG(0,("pdb_new_rid: Talloc initialization failure\n"));
1051                 return False;
1052         }
1053
1054         /* Attempt to get an unused RID (max tires is 250...yes that it is 
1055            and arbitrary number I pulkled out of my head).   -- jerry */
1056
1057         for ( i=0; allocated_rid==0 && i<250; i++ ) {
1058                 /* get a new RID */
1059
1060                 if ( !pdb->new_rid(pdb, &allocated_rid) ) {
1061                         return False;
1062                 }
1063
1064                 /* validate that the RID is not in use */
1065
1066                 if ( lookup_global_sam_rid( ctx, allocated_rid, &name, &type, NULL ) ) {
1067                         allocated_rid = 0;
1068                 }
1069         }
1070
1071         TALLOC_FREE( ctx );
1072
1073         if ( allocated_rid == 0 ) {
1074                 DEBUG(0,("pdb_new_rid: Failed to find unused RID\n"));
1075                 return False;
1076         }
1077
1078         *rid = allocated_rid;
1079
1080         return True;
1081 }
1082
1083 /***************************************************************
1084   Initialize the static context (at smbd startup etc). 
1085
1086   If uninitialised, context will auto-init on first use.
1087  ***************************************************************/
1088
1089 BOOL initialize_password_db(BOOL reload)
1090 {       
1091         return (pdb_get_methods_reload(reload) != NULL);
1092 }
1093
1094
1095 /***************************************************************************
1096   Default implementations of some functions.
1097  ****************************************************************************/
1098
1099 static NTSTATUS pdb_default_getsampwnam (struct pdb_methods *methods, struct samu *user, const char *sname)
1100 {
1101         return NT_STATUS_NO_SUCH_USER;
1102 }
1103
1104 static NTSTATUS pdb_default_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1105 {
1106         return NT_STATUS_NO_SUCH_USER;
1107 }
1108
1109 static NTSTATUS pdb_default_add_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1110 {
1111         return NT_STATUS_NOT_IMPLEMENTED;
1112 }
1113
1114 static NTSTATUS pdb_default_update_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1115 {
1116         return NT_STATUS_NOT_IMPLEMENTED;
1117 }
1118
1119 static NTSTATUS pdb_default_delete_sam_account (struct pdb_methods *methods, struct samu *pwd)
1120 {
1121         return NT_STATUS_NOT_IMPLEMENTED;
1122 }
1123
1124 static NTSTATUS pdb_default_rename_sam_account (struct pdb_methods *methods, struct samu *pwd, const char *newname)
1125 {
1126         return NT_STATUS_NOT_IMPLEMENTED;
1127 }
1128
1129 static NTSTATUS pdb_default_update_login_attempts (struct pdb_methods *methods, struct samu *newpwd, BOOL success)
1130 {
1131         return NT_STATUS_OK;
1132 }
1133
1134 static NTSTATUS pdb_default_setsampwent(struct pdb_methods *methods, BOOL update, uint32 acb_mask)
1135 {
1136         return NT_STATUS_NOT_IMPLEMENTED;
1137 }
1138
1139 static NTSTATUS pdb_default_getsampwent(struct pdb_methods *methods, struct samu *user)
1140 {
1141         return NT_STATUS_NOT_IMPLEMENTED;
1142 }
1143
1144 static void pdb_default_endsampwent(struct pdb_methods *methods)
1145 {
1146         return; /* NT_STATUS_NOT_IMPLEMENTED; */
1147 }
1148
1149 static NTSTATUS pdb_default_get_account_policy(struct pdb_methods *methods, int policy_index, uint32 *value)
1150 {
1151         return account_policy_get(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1152 }
1153
1154 static NTSTATUS pdb_default_set_account_policy(struct pdb_methods *methods, int policy_index, uint32 value)
1155 {
1156         return account_policy_set(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1157 }
1158
1159 static NTSTATUS pdb_default_get_seq_num(struct pdb_methods *methods, time_t *seq_num)
1160 {
1161         *seq_num = time(NULL);
1162         return NT_STATUS_OK;
1163 }
1164
1165 static BOOL pdb_default_uid_to_rid(struct pdb_methods *methods, uid_t uid,
1166                                    uint32 *rid)
1167 {
1168         struct samu *sampw = NULL;
1169         struct passwd *unix_pw;
1170         BOOL ret;
1171         
1172         unix_pw = sys_getpwuid( uid );
1173
1174         if ( !unix_pw ) {
1175                 DEBUG(4,("pdb_default_uid_to_rid: host has no idea of uid "
1176                          "%lu\n", (unsigned long)uid));
1177                 return False;
1178         }
1179         
1180         if ( !(sampw = samu_new( NULL )) ) {
1181                 DEBUG(0,("pdb_default_uid_to_rid: samu_new() failed!\n"));
1182                 return False;
1183         }
1184
1185         become_root();
1186         ret = NT_STATUS_IS_OK(
1187                 methods->getsampwnam(methods, sampw, unix_pw->pw_name ));
1188         unbecome_root();
1189
1190         if (!ret) {
1191                 DEBUG(5, ("pdb_default_uid_to_rid: Did not find user "
1192                           "%s (%d)\n", unix_pw->pw_name, uid));
1193                 TALLOC_FREE(sampw);
1194                 return False;
1195         }
1196
1197         ret = sid_peek_check_rid(get_global_sam_sid(),
1198                                  pdb_get_user_sid(sampw), rid);
1199
1200         if (!ret) {
1201                 DEBUG(1, ("Could not peek rid out of sid %s\n",
1202                           sid_string_static(pdb_get_user_sid(sampw))));
1203         }
1204
1205         TALLOC_FREE(sampw);
1206         return ret;
1207 }
1208
1209 static BOOL pdb_default_gid_to_sid(struct pdb_methods *methods, gid_t gid,
1210                                    DOM_SID *sid)
1211 {
1212         GROUP_MAP map;
1213
1214         if (!NT_STATUS_IS_OK(methods->getgrgid(methods, &map, gid))) {
1215                 return False;
1216         }
1217
1218         sid_copy(sid, &map.sid);
1219         return True;
1220 }
1221
1222 static BOOL pdb_default_sid_to_id(struct pdb_methods *methods,
1223                                   const DOM_SID *sid,
1224                                   union unid_t *id, enum SID_NAME_USE *type)
1225 {
1226         TALLOC_CTX *mem_ctx;
1227         BOOL ret = False;
1228         const char *name;
1229         uint32 rid;
1230
1231         mem_ctx = talloc_new(NULL);
1232
1233         if (mem_ctx == NULL) {
1234                 DEBUG(0, ("talloc_new failed\n"));
1235                 return False;
1236         }
1237
1238         if (sid_peek_check_rid(get_global_sam_sid(), sid, &rid)) {
1239                 /* Here we might have users as well as groups and aliases */
1240                 ret = lookup_global_sam_rid(mem_ctx, rid, &name, type, id);
1241                 goto done;
1242         }
1243
1244         if (sid_peek_check_rid(&global_sid_Builtin, sid, &rid)) {
1245                 /* Here we only have aliases */
1246                 GROUP_MAP map;
1247                 if (!NT_STATUS_IS_OK(methods->getgrsid(methods, &map, *sid))) {
1248                         DEBUG(10, ("Could not find map for sid %s\n",
1249                                    sid_string_static(sid)));
1250                         goto done;
1251                 }
1252                 if ((map.sid_name_use != SID_NAME_ALIAS) &&
1253                     (map.sid_name_use != SID_NAME_WKN_GRP)) {
1254                         DEBUG(10, ("Map for sid %s is a %s, expected an "
1255                                    "alias\n", sid_string_static(sid),
1256                                    sid_type_lookup(map.sid_name_use)));
1257                         goto done;
1258                 }
1259
1260                 id->gid = map.gid;
1261                 *type = SID_NAME_ALIAS;
1262                 ret = True;
1263                 goto done;
1264         }
1265
1266         DEBUG(5, ("Sid %s is neither ours nor builtin, don't know it\n",
1267                   sid_string_static(sid)));
1268
1269  done:
1270
1271         TALLOC_FREE(mem_ctx);
1272         return ret;
1273 }
1274
1275 static void add_uid_to_array_unique(TALLOC_CTX *mem_ctx,
1276                                     uid_t uid, uid_t **pp_uids, size_t *p_num)
1277 {
1278         size_t i;
1279
1280         for (i=0; i<*p_num; i++) {
1281                 if ((*pp_uids)[i] == uid)
1282                         return;
1283         }
1284         
1285         *pp_uids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_uids, uid_t, *p_num+1);
1286
1287         if (*pp_uids == NULL)
1288                 return;
1289
1290         (*pp_uids)[*p_num] = uid;
1291         *p_num += 1;
1292 }
1293
1294 static BOOL get_memberuids(TALLOC_CTX *mem_ctx, gid_t gid, uid_t **pp_uids, size_t *p_num)
1295 {
1296         struct group *grp;
1297         char **gr;
1298         struct passwd *pwd;
1299         char *winbindd_env;
1300  
1301         *pp_uids = NULL;
1302         *p_num = 0;
1303
1304         /* We only look at our own sam, so don't care about imported stuff */
1305
1306         winbindd_env = getenv(WINBINDD_DONT_ENV);
1307         winbind_off();
1308
1309         if ((grp = getgrgid(gid)) == NULL) {
1310                 /* allow winbindd lookups, but only if they weren't already disabled */
1311                 if ( !(winbindd_env && strequal(winbindd_env, "1")) ) {
1312                         winbind_on();
1313                 }
1314
1315                 return False;
1316         }
1317
1318         /* Primary group members */
1319
1320         setpwent();
1321         while ((pwd = getpwent()) != NULL) {
1322                 if (pwd->pw_gid == gid) {
1323                         add_uid_to_array_unique(mem_ctx, pwd->pw_uid,
1324                                                 pp_uids, p_num);
1325                 }
1326         }
1327         endpwent();
1328
1329         /* Secondary group members */
1330
1331         for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
1332                 struct passwd *pw = getpwnam(*gr);
1333
1334                 if (pw == NULL)
1335                         continue;
1336                 add_uid_to_array_unique(mem_ctx, pw->pw_uid, pp_uids, p_num);
1337         }
1338
1339         /* allow winbindd lookups, but only if they weren't already disabled */
1340
1341         if ( !(winbindd_env && strequal(winbindd_env, "1")) ) {
1342                 winbind_on();
1343         }
1344
1345         return True;
1346 }
1347
1348 NTSTATUS pdb_default_enum_group_members(struct pdb_methods *methods,
1349                                         TALLOC_CTX *mem_ctx,
1350                                         const DOM_SID *group,
1351                                         uint32 **pp_member_rids,
1352                                         size_t *p_num_members)
1353 {
1354         gid_t gid;
1355         uid_t *uids;
1356         size_t i, num_uids;
1357
1358         *pp_member_rids = NULL;
1359         *p_num_members = 0;
1360
1361         if (!sid_to_gid(group, &gid))
1362                 return NT_STATUS_NO_SUCH_GROUP;
1363
1364         if(!get_memberuids(mem_ctx, gid, &uids, &num_uids))
1365                 return NT_STATUS_NO_SUCH_GROUP;
1366
1367         if (num_uids == 0)
1368                 return NT_STATUS_OK;
1369
1370         *pp_member_rids = TALLOC_ZERO_ARRAY(mem_ctx, uint32, num_uids);
1371
1372         for (i=0; i<num_uids; i++) {
1373                 DOM_SID sid;
1374
1375                 uid_to_sid(&sid, uids[i]);
1376
1377                 if (!sid_check_is_in_our_domain(&sid)) {
1378                         DEBUG(5, ("Inconsistent SAM -- group member uid not "
1379                                   "in our domain\n"));
1380                         continue;
1381                 }
1382
1383                 sid_peek_rid(&sid, &(*pp_member_rids)[*p_num_members]);
1384                 *p_num_members += 1;
1385         }
1386
1387         return NT_STATUS_OK;
1388 }
1389
1390 NTSTATUS pdb_default_enum_group_memberships(struct pdb_methods *methods,
1391                                             TALLOC_CTX *mem_ctx,
1392                                             struct samu *user,
1393                                             DOM_SID **pp_sids,
1394                                             gid_t **pp_gids,
1395                                             size_t *p_num_groups)
1396 {
1397         size_t i;
1398         gid_t gid;
1399         struct passwd *pw;
1400         const char *username = pdb_get_username(user);
1401         
1402
1403         /* Ignore the primary group SID.  Honor the real Unix primary group.
1404            The primary group SID is only of real use to Windows clients */
1405            
1406         if ( !(pw = getpwnam_alloc(mem_ctx, username)) ) {
1407                 return NT_STATUS_NO_SUCH_USER;
1408         }
1409         
1410         gid = pw->pw_gid;
1411         
1412         TALLOC_FREE( pw );
1413
1414         if (!getgroups_unix_user(mem_ctx, username, gid, pp_gids, p_num_groups)) {
1415                 return NT_STATUS_NO_SUCH_USER;
1416         }
1417
1418         if (*p_num_groups == 0) {
1419                 smb_panic("primary group missing");
1420         }
1421
1422         *pp_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, *p_num_groups);
1423
1424         if (*pp_sids == NULL) {
1425                 TALLOC_FREE(*pp_gids);
1426                 return NT_STATUS_NO_MEMORY;
1427         }
1428
1429         for (i=0; i<*p_num_groups; i++) {
1430                 gid_to_sid(&(*pp_sids)[i], (*pp_gids)[i]);
1431         }
1432
1433         return NT_STATUS_OK;
1434 }
1435
1436 /*******************************************************************
1437  Look up a rid in the SAM we're responsible for (i.e. passdb)
1438  ********************************************************************/
1439
1440 static BOOL lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32 rid,
1441                                   const char **name,
1442                                   enum SID_NAME_USE *psid_name_use,
1443                                   union unid_t *unix_id)
1444 {
1445         struct samu *sam_account = NULL;
1446         GROUP_MAP map;
1447         BOOL ret;
1448         DOM_SID sid;
1449
1450         *psid_name_use = SID_NAME_UNKNOWN;
1451         
1452         DEBUG(5,("lookup_global_sam_rid: looking up RID %u.\n",
1453                  (unsigned int)rid));
1454
1455         sid_copy(&sid, get_global_sam_sid());
1456         sid_append_rid(&sid, rid);
1457         
1458         /* see if the passdb can help us with the name of the user */
1459
1460         if ( !(sam_account = samu_new( NULL )) ) {
1461                 return False;
1462         }
1463
1464         /* BEING ROOT BLLOCK */
1465         become_root();
1466         if (pdb_getsampwsid(sam_account, &sid)) {
1467                 struct passwd *pw;
1468
1469                 unbecome_root();                /* -----> EXIT BECOME_ROOT() */
1470                 *name = talloc_strdup(mem_ctx, pdb_get_username(sam_account));
1471                 if (!*name) {
1472                         TALLOC_FREE(sam_account);
1473                         return False;
1474                 }
1475
1476                 *psid_name_use = SID_NAME_USER;
1477
1478                 TALLOC_FREE(sam_account);
1479
1480                 if (unix_id == NULL) {
1481                         return True;
1482                 }
1483
1484                 pw = Get_Pwnam(*name);
1485                 if (pw == NULL) {
1486                         return False;
1487                 }
1488                 unix_id->uid = pw->pw_uid;
1489                 return True;
1490         }
1491         TALLOC_FREE(sam_account);
1492         
1493         ret = pdb_getgrsid(&map, sid);
1494         unbecome_root();
1495         /* END BECOME_ROOT BLOCK */
1496   
1497         /* do not resolve SIDs to a name unless there is a valid 
1498            gid associated with it */
1499                    
1500         if ( ret && (map.gid != (gid_t)-1) ) {
1501                 *name = talloc_strdup(mem_ctx, map.nt_name);
1502                 *psid_name_use = map.sid_name_use;
1503
1504                 if ( unix_id ) {
1505                         unix_id->gid = map.gid;
1506                 }
1507
1508                 return True;
1509         }
1510         
1511         /* Windows will always map RID 513 to something.  On a non-domain 
1512            controller, this gets mapped to SERVER\None. */
1513
1514         if ( unix_id ) {
1515                 DEBUG(5, ("Can't find a unix id for an unmapped group\n"));
1516                 return False;
1517         }
1518         
1519         if ( rid == DOMAIN_GROUP_RID_USERS ) {
1520                 *name = talloc_strdup(mem_ctx, "None" );
1521                 *psid_name_use = SID_NAME_DOM_GRP;
1522                 
1523                 return True;
1524         }
1525
1526         return False;
1527 }
1528
1529 NTSTATUS pdb_default_lookup_rids(struct pdb_methods *methods,
1530                                  const DOM_SID *domain_sid,
1531                                  int num_rids,
1532                                  uint32 *rids,
1533                                  const char **names,
1534                                  enum SID_NAME_USE *attrs)
1535 {
1536         int i;
1537         NTSTATUS result;
1538         BOOL have_mapped = False;
1539         BOOL have_unmapped = False;
1540
1541         if (sid_check_is_builtin(domain_sid)) {
1542
1543                 for (i=0; i<num_rids; i++) {
1544                         const char *name;
1545
1546                         if (lookup_builtin_rid(names, rids[i], &name)) {
1547                                 attrs[i] = SID_NAME_ALIAS;
1548                                 names[i] = name;
1549                                 DEBUG(5,("lookup_rids: %s:%d\n",
1550                                          names[i], attrs[i]));
1551                                 have_mapped = True;
1552                         } else {
1553                                 have_unmapped = True;
1554                                 attrs[i] = SID_NAME_UNKNOWN;
1555                         }
1556                 }
1557                 goto done;
1558         }
1559
1560         /* Should not happen, but better check once too many */
1561         if (!sid_check_is_domain(domain_sid)) {
1562                 return NT_STATUS_INVALID_HANDLE;
1563         }
1564
1565         for (i = 0; i < num_rids; i++) {
1566                 const char *name;
1567
1568                 if (lookup_global_sam_rid(names, rids[i], &name, &attrs[i],
1569                                           NULL)) {
1570                         if (name == NULL) {
1571                                 return NT_STATUS_NO_MEMORY;
1572                         }
1573                         names[i] = name;
1574                         DEBUG(5,("lookup_rids: %s:%d\n", names[i], attrs[i]));
1575                         have_mapped = True;
1576                 } else {
1577                         have_unmapped = True;
1578                         attrs[i] = SID_NAME_UNKNOWN;
1579                 }
1580         }
1581
1582  done:
1583
1584         result = NT_STATUS_NONE_MAPPED;
1585
1586         if (have_mapped)
1587                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1588
1589         return result;
1590 }
1591
1592 NTSTATUS pdb_default_lookup_names(struct pdb_methods *methods,
1593                                   const DOM_SID *domain_sid,
1594                                   int num_names,
1595                                   const char **names,
1596                                   uint32 *rids,
1597                                   enum SID_NAME_USE *attrs)
1598 {
1599         int i;
1600         NTSTATUS result;
1601         BOOL have_mapped = False;
1602         BOOL have_unmapped = False;
1603
1604         if (sid_check_is_builtin(domain_sid)) {
1605
1606                 for (i=0; i<num_names; i++) {
1607                         uint32 rid;
1608
1609                         if (lookup_builtin_name(names[i], &rid)) {
1610                                 attrs[i] = SID_NAME_ALIAS;
1611                                 rids[i] = rid;
1612                                 DEBUG(5,("lookup_rids: %s:%d\n",
1613                                          names[i], attrs[i]));
1614                                 have_mapped = True;
1615                         } else {
1616                                 have_unmapped = True;
1617                                 attrs[i] = SID_NAME_UNKNOWN;
1618                         }
1619                 }
1620                 goto done;
1621         }
1622
1623         /* Should not happen, but better check once too many */
1624         if (!sid_check_is_domain(domain_sid)) {
1625                 return NT_STATUS_INVALID_HANDLE;
1626         }
1627
1628         for (i = 0; i < num_names; i++) {
1629                 if (lookup_global_sam_name(names[i], 0, &rids[i], &attrs[i])) {
1630                         DEBUG(5,("lookup_names: %s-> %d:%d\n", names[i],
1631                                  rids[i], attrs[i]));
1632                         have_mapped = True;
1633                 } else {
1634                         have_unmapped = True;
1635                         attrs[i] = SID_NAME_UNKNOWN;
1636                 }
1637         }
1638
1639  done:
1640
1641         result = NT_STATUS_NONE_MAPPED;
1642
1643         if (have_mapped)
1644                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1645
1646         return result;
1647 }
1648
1649 static struct pdb_search *pdb_search_init(enum pdb_search_type type)
1650 {
1651         TALLOC_CTX *mem_ctx;
1652         struct pdb_search *result;
1653
1654         mem_ctx = talloc_init("pdb_search");
1655         if (mem_ctx == NULL) {
1656                 DEBUG(0, ("talloc_init failed\n"));
1657                 return NULL;
1658         }
1659
1660         result = TALLOC_P(mem_ctx, struct pdb_search);
1661         if (result == NULL) {
1662                 DEBUG(0, ("talloc failed\n"));
1663                 return NULL;
1664         }
1665
1666         result->mem_ctx = mem_ctx;
1667         result->type = type;
1668         result->cache = NULL;
1669         result->num_entries = 0;
1670         result->cache_size = 0;
1671         result->search_ended = False;
1672
1673         /* Segfault appropriately if not initialized */
1674         result->next_entry = NULL;
1675         result->search_end = NULL;
1676
1677         return result;
1678 }
1679
1680 static void fill_displayentry(TALLOC_CTX *mem_ctx, uint32 rid,
1681                               uint16 acct_flags,
1682                               const char *account_name,
1683                               const char *fullname,
1684                               const char *description,
1685                               struct samr_displayentry *entry)
1686 {
1687         entry->rid = rid;
1688         entry->acct_flags = acct_flags;
1689
1690         if (account_name != NULL)
1691                 entry->account_name = talloc_strdup(mem_ctx, account_name);
1692         else
1693                 entry->account_name = "";
1694
1695         if (fullname != NULL)
1696                 entry->fullname = talloc_strdup(mem_ctx, fullname);
1697         else
1698                 entry->fullname = "";
1699
1700         if (description != NULL)
1701                 entry->description = talloc_strdup(mem_ctx, description);
1702         else
1703                 entry->description = "";
1704 }
1705
1706 static BOOL user_search_in_progress = False;
1707 struct user_search {
1708         uint16 acct_flags;
1709 };
1710
1711 static BOOL next_entry_users(struct pdb_search *s,
1712                              struct samr_displayentry *entry)
1713 {
1714         struct user_search *state = s->private_data;
1715         struct samu *user = NULL;
1716
1717  next:
1718         if ( !(user = samu_new( NULL )) ) {
1719                 DEBUG(0, ("next_entry_users: samu_new() failed!\n"));
1720                 return False;
1721         }
1722
1723         if (!pdb_getsampwent(user)) {
1724                 TALLOC_FREE(user);
1725                 return False;
1726         }
1727
1728         if ((state->acct_flags != 0) &&
1729             ((pdb_get_acct_ctrl(user) & state->acct_flags) == 0)) {
1730                 TALLOC_FREE(user);
1731                 goto next;
1732         }
1733
1734         fill_displayentry(s->mem_ctx, pdb_get_user_rid(user),
1735                           pdb_get_acct_ctrl(user), pdb_get_username(user),
1736                           pdb_get_fullname(user), pdb_get_acct_desc(user),
1737                           entry);
1738
1739         TALLOC_FREE(user);
1740         return True;
1741 }
1742
1743 static void search_end_users(struct pdb_search *search)
1744 {
1745         pdb_endsampwent();
1746         user_search_in_progress = False;
1747 }
1748
1749 static BOOL pdb_default_search_users(struct pdb_methods *methods,
1750                                      struct pdb_search *search,
1751                                      uint32 acct_flags)
1752 {
1753         struct user_search *state;
1754
1755         if (user_search_in_progress) {
1756                 DEBUG(1, ("user search in progress\n"));
1757                 return False;
1758         }
1759
1760         if (!pdb_setsampwent(False, acct_flags)) {
1761                 DEBUG(5, ("Could not start search\n"));
1762                 return False;
1763         }
1764
1765         user_search_in_progress = True;
1766
1767         state = TALLOC_P(search->mem_ctx, struct user_search);
1768         if (state == NULL) {
1769                 DEBUG(0, ("talloc failed\n"));
1770                 return False;
1771         }
1772
1773         state->acct_flags = acct_flags;
1774
1775         search->private_data = state;
1776         search->next_entry = next_entry_users;
1777         search->search_end = search_end_users;
1778         return True;
1779 }
1780
1781 struct group_search {
1782         GROUP_MAP *groups;
1783         size_t num_groups, current_group;
1784 };
1785
1786 static BOOL next_entry_groups(struct pdb_search *s,
1787                               struct samr_displayentry *entry)
1788 {
1789         struct group_search *state = s->private_data;
1790         uint32 rid;
1791         GROUP_MAP *map = &state->groups[state->current_group];
1792
1793         if (state->current_group == state->num_groups)
1794                 return False;
1795
1796         sid_peek_rid(&map->sid, &rid);
1797
1798         fill_displayentry(s->mem_ctx, rid, 0, map->nt_name, NULL, map->comment,
1799                           entry);
1800
1801         state->current_group += 1;
1802         return True;
1803 }
1804
1805 static void search_end_groups(struct pdb_search *search)
1806 {
1807         struct group_search *state = search->private_data;
1808         SAFE_FREE(state->groups);
1809 }
1810
1811 static BOOL pdb_search_grouptype(struct pdb_search *search,
1812                                  const DOM_SID *sid, enum SID_NAME_USE type)
1813 {
1814         struct group_search *state;
1815
1816         state = TALLOC_P(search->mem_ctx, struct group_search);
1817         if (state == NULL) {
1818                 DEBUG(0, ("talloc failed\n"));
1819                 return False;
1820         }
1821
1822         if (!pdb_enum_group_mapping(sid, type, &state->groups, &state->num_groups,
1823                                     True)) {
1824                 DEBUG(0, ("Could not enum groups\n"));
1825                 return False;
1826         }
1827
1828         state->current_group = 0;
1829         search->private_data = state;
1830         search->next_entry = next_entry_groups;
1831         search->search_end = search_end_groups;
1832         return True;
1833 }
1834
1835 static BOOL pdb_default_search_groups(struct pdb_methods *methods,
1836                                       struct pdb_search *search)
1837 {
1838         return pdb_search_grouptype(search, get_global_sam_sid(), SID_NAME_DOM_GRP);
1839 }
1840
1841 static BOOL pdb_default_search_aliases(struct pdb_methods *methods,
1842                                        struct pdb_search *search,
1843                                        const DOM_SID *sid)
1844 {
1845
1846         return pdb_search_grouptype(search, sid, SID_NAME_ALIAS);
1847 }
1848
1849 static struct samr_displayentry *pdb_search_getentry(struct pdb_search *search,
1850                                                      uint32 idx)
1851 {
1852         if (idx < search->num_entries)
1853                 return &search->cache[idx];
1854
1855         if (search->search_ended)
1856                 return NULL;
1857
1858         while (idx >= search->num_entries) {
1859                 struct samr_displayentry entry;
1860
1861                 if (!search->next_entry(search, &entry)) {
1862                         search->search_end(search);
1863                         search->search_ended = True;
1864                         break;
1865                 }
1866
1867                 ADD_TO_LARGE_ARRAY(search->mem_ctx, struct samr_displayentry,
1868                                    entry, &search->cache, &search->num_entries,
1869                                    &search->cache_size);
1870         }
1871
1872         return (search->num_entries > idx) ? &search->cache[idx] : NULL;
1873 }
1874
1875 struct pdb_search *pdb_search_users(uint32 acct_flags)
1876 {
1877         struct pdb_methods *pdb = pdb_get_methods();
1878         struct pdb_search *result;
1879
1880         result = pdb_search_init(PDB_USER_SEARCH);
1881         if (result == NULL) {
1882                 return NULL;
1883         }
1884
1885         if (!pdb->search_users(pdb, result, acct_flags)) {
1886                 talloc_destroy(result->mem_ctx);
1887                 return NULL;
1888         }
1889         return result;
1890 }
1891
1892 struct pdb_search *pdb_search_groups(void)
1893 {
1894         struct pdb_methods *pdb = pdb_get_methods();
1895         struct pdb_search *result;
1896
1897         result = pdb_search_init(PDB_GROUP_SEARCH);
1898         if (result == NULL) {
1899                  return NULL;
1900         }
1901
1902         if (!pdb->search_groups(pdb, result)) {
1903                 talloc_destroy(result->mem_ctx);
1904                 return NULL;
1905         }
1906         return result;
1907 }
1908
1909 struct pdb_search *pdb_search_aliases(const DOM_SID *sid)
1910 {
1911         struct pdb_methods *pdb = pdb_get_methods();
1912         struct pdb_search *result;
1913
1914         if (pdb == NULL) return NULL;
1915
1916         result = pdb_search_init(PDB_ALIAS_SEARCH);
1917         if (result == NULL) return NULL;
1918
1919         if (!pdb->search_aliases(pdb, result, sid)) {
1920                 talloc_destroy(result->mem_ctx);
1921                 return NULL;
1922         }
1923         return result;
1924 }
1925
1926 uint32 pdb_search_entries(struct pdb_search *search,
1927                           uint32 start_idx, uint32 max_entries,
1928                           struct samr_displayentry **result)
1929 {
1930         struct samr_displayentry *end_entry;
1931         uint32 end_idx = start_idx+max_entries-1;
1932
1933         /* The first entry needs to be searched after the last. Otherwise the
1934          * first entry might have moved due to a realloc during the search for
1935          * the last entry. */
1936
1937         end_entry = pdb_search_getentry(search, end_idx);
1938         *result = pdb_search_getentry(search, start_idx);
1939
1940         if (end_entry != NULL)
1941                 return max_entries;
1942
1943         if (start_idx >= search->num_entries)
1944                 return 0;
1945
1946         return search->num_entries - start_idx;
1947 }
1948
1949 void pdb_search_destroy(struct pdb_search *search)
1950 {
1951         if (search == NULL)
1952                 return;
1953
1954         if (!search->search_ended)
1955                 search->search_end(search);
1956
1957         talloc_destroy(search->mem_ctx);
1958 }
1959
1960 /*******************************************************************
1961  Create a pdb_methods structure and initialize it with the default
1962  operations.  In this way a passdb module can simply implement
1963  the functionality it cares about.  However, normally this is done 
1964  in groups of related functions.
1965 *******************************************************************/
1966
1967 NTSTATUS make_pdb_method( struct pdb_methods **methods ) 
1968 {
1969         /* allocate memory for the structure as its own talloc CTX */
1970
1971         if ( !(*methods = TALLOC_ZERO_P(NULL, struct pdb_methods) ) ) {
1972                 return NT_STATUS_NO_MEMORY;
1973         }
1974
1975         (*methods)->setsampwent = pdb_default_setsampwent;
1976         (*methods)->endsampwent = pdb_default_endsampwent;
1977         (*methods)->getsampwent = pdb_default_getsampwent;
1978         (*methods)->getsampwnam = pdb_default_getsampwnam;
1979         (*methods)->getsampwsid = pdb_default_getsampwsid;
1980         (*methods)->create_user = pdb_default_create_user;
1981         (*methods)->delete_user = pdb_default_delete_user;
1982         (*methods)->add_sam_account = pdb_default_add_sam_account;
1983         (*methods)->update_sam_account = pdb_default_update_sam_account;
1984         (*methods)->delete_sam_account = pdb_default_delete_sam_account;
1985         (*methods)->rename_sam_account = pdb_default_rename_sam_account;
1986         (*methods)->update_login_attempts = pdb_default_update_login_attempts;
1987
1988         (*methods)->getgrsid = pdb_default_getgrsid;
1989         (*methods)->getgrgid = pdb_default_getgrgid;
1990         (*methods)->getgrnam = pdb_default_getgrnam;
1991         (*methods)->create_dom_group = pdb_default_create_dom_group;
1992         (*methods)->delete_dom_group = pdb_default_delete_dom_group;
1993         (*methods)->add_group_mapping_entry = pdb_default_add_group_mapping_entry;
1994         (*methods)->update_group_mapping_entry = pdb_default_update_group_mapping_entry;
1995         (*methods)->delete_group_mapping_entry = pdb_default_delete_group_mapping_entry;
1996         (*methods)->enum_group_mapping = pdb_default_enum_group_mapping;
1997         (*methods)->enum_group_members = pdb_default_enum_group_members;
1998         (*methods)->enum_group_memberships = pdb_default_enum_group_memberships;
1999         (*methods)->set_unix_primary_group = pdb_default_set_unix_primary_group;
2000         (*methods)->add_groupmem = pdb_default_add_groupmem;
2001         (*methods)->del_groupmem = pdb_default_del_groupmem;
2002         (*methods)->find_alias = pdb_default_find_alias;
2003         (*methods)->create_alias = pdb_default_create_alias;
2004         (*methods)->delete_alias = pdb_default_delete_alias;
2005         (*methods)->get_aliasinfo = pdb_default_get_aliasinfo;
2006         (*methods)->set_aliasinfo = pdb_default_set_aliasinfo;
2007         (*methods)->add_aliasmem = pdb_default_add_aliasmem;
2008         (*methods)->del_aliasmem = pdb_default_del_aliasmem;
2009         (*methods)->enum_aliasmem = pdb_default_enum_aliasmem;
2010         (*methods)->enum_alias_memberships = pdb_default_alias_memberships;
2011         (*methods)->lookup_rids = pdb_default_lookup_rids;
2012         (*methods)->get_account_policy = pdb_default_get_account_policy;
2013         (*methods)->set_account_policy = pdb_default_set_account_policy;
2014         (*methods)->get_seq_num = pdb_default_get_seq_num;
2015         (*methods)->uid_to_rid = pdb_default_uid_to_rid;
2016         (*methods)->gid_to_sid = pdb_default_gid_to_sid;
2017         (*methods)->sid_to_id = pdb_default_sid_to_id;
2018
2019         (*methods)->search_users = pdb_default_search_users;
2020         (*methods)->search_groups = pdb_default_search_groups;
2021         (*methods)->search_aliases = pdb_default_search_aliases;
2022
2023         return NT_STATUS_OK;
2024 }