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