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