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