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