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