b7c9bace2a9ba62a232f773962e02d2149508886
[samba.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                         }
1477                 }
1478                 goto done;
1479         }
1480
1481         /* check for "Unix User" */
1482
1483         if ( sid_peek_check_rid(&global_sid_Unix_Users, sid, &rid) ) {
1484                 id->id = rid;
1485                 id->type = ID_TYPE_UID;
1486                 ret = True;             
1487                 goto done;              
1488         }
1489
1490         /* check for "Unix Group" */
1491
1492         if ( sid_peek_check_rid(&global_sid_Unix_Groups, sid, &rid) ) {
1493                 id->id = rid;
1494                 id->type = ID_TYPE_GID;
1495                 ret = True;             
1496                 goto done;              
1497         }
1498
1499         /* BUILTIN */
1500
1501         if (sid_check_is_in_builtin(sid) ||
1502             sid_check_is_in_wellknown_domain(sid)) {
1503                 /* Here we only have aliases */
1504                 GROUP_MAP *map;
1505
1506                 map = talloc_zero(mem_ctx, GROUP_MAP);
1507                 if (!map) {
1508                         ret = false;
1509                         goto done;
1510                 }
1511
1512                 if (!NT_STATUS_IS_OK(methods->getgrsid(methods, map, *sid))) {
1513                         DEBUG(10, ("Could not find map for sid %s\n",
1514                                    sid_string_dbg(sid)));
1515                         goto done;
1516                 }
1517                 if ((map->sid_name_use != SID_NAME_ALIAS) &&
1518                     (map->sid_name_use != SID_NAME_WKN_GRP)) {
1519                         DEBUG(10, ("Map for sid %s is a %s, expected an "
1520                                    "alias\n", sid_string_dbg(sid),
1521                                    sid_type_lookup(map->sid_name_use)));
1522                         goto done;
1523                 }
1524
1525                 id->id = map->gid;
1526                 id->type = ID_TYPE_GID;
1527                 ret = True;
1528                 goto done;
1529         }
1530
1531         DEBUG(5, ("Sid %s is neither ours, a Unix SID, nor builtin\n",
1532                   sid_string_dbg(sid)));
1533
1534  done:
1535
1536         TALLOC_FREE(mem_ctx);
1537         return ret;
1538 }
1539
1540 static bool get_memberuids(TALLOC_CTX *mem_ctx, gid_t gid, uid_t **pp_uids, uint32_t *p_num)
1541 {
1542         struct group *grp;
1543         char **gr;
1544         struct passwd *pwd;
1545         bool winbind_env;
1546         bool ret = False;
1547  
1548         *pp_uids = NULL;
1549         *p_num = 0;
1550
1551         /* We only look at our own sam, so don't care about imported stuff */
1552         winbind_env = winbind_env_set();
1553         (void)winbind_off();
1554
1555         if ((grp = getgrgid(gid)) == NULL) {
1556                 /* allow winbindd lookups, but only if they weren't already disabled */
1557                 goto done;
1558         }
1559
1560         /* Primary group members */
1561         setpwent();
1562         while ((pwd = getpwent()) != NULL) {
1563                 if (pwd->pw_gid == gid) {
1564                         if (!add_uid_to_array_unique(mem_ctx, pwd->pw_uid,
1565                                                 pp_uids, p_num)) {
1566                                 goto done;
1567                         }
1568                 }
1569         }
1570         endpwent();
1571
1572         /* Secondary group members */
1573         for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
1574                 struct passwd *pw = getpwnam(*gr);
1575
1576                 if (pw == NULL)
1577                         continue;
1578                 if (!add_uid_to_array_unique(mem_ctx, pw->pw_uid, pp_uids, p_num)) {
1579                         goto done;
1580                 }
1581         }
1582
1583         ret = True;
1584
1585   done:
1586
1587         /* allow winbindd lookups, but only if they weren't already disabled */
1588         if (!winbind_env) {
1589                 (void)winbind_on();
1590         }
1591
1592         return ret;
1593 }
1594
1595 static NTSTATUS pdb_default_enum_group_members(struct pdb_methods *methods,
1596                                                TALLOC_CTX *mem_ctx,
1597                                                const struct dom_sid *group,
1598                                                uint32_t **pp_member_rids,
1599                                                size_t *p_num_members)
1600 {
1601         gid_t gid;
1602         uid_t *uids;
1603         uint32_t i, num_uids;
1604
1605         *pp_member_rids = NULL;
1606         *p_num_members = 0;
1607
1608         if (!sid_to_gid(group, &gid))
1609                 return NT_STATUS_NO_SUCH_GROUP;
1610
1611         if(!get_memberuids(mem_ctx, gid, &uids, &num_uids))
1612                 return NT_STATUS_NO_SUCH_GROUP;
1613
1614         if (num_uids == 0)
1615                 return NT_STATUS_OK;
1616
1617         *pp_member_rids = talloc_zero_array(mem_ctx, uint32_t, num_uids);
1618
1619         for (i=0; i<num_uids; i++) {
1620                 struct dom_sid sid;
1621
1622                 uid_to_sid(&sid, uids[i]);
1623
1624                 if (!sid_check_is_in_our_domain(&sid)) {
1625                         DEBUG(5, ("Inconsistent SAM -- group member uid not "
1626                                   "in our domain\n"));
1627                         continue;
1628                 }
1629
1630                 sid_peek_rid(&sid, &(*pp_member_rids)[*p_num_members]);
1631                 *p_num_members += 1;
1632         }
1633
1634         return NT_STATUS_OK;
1635 }
1636
1637 static NTSTATUS pdb_default_enum_group_memberships(struct pdb_methods *methods,
1638                                                    TALLOC_CTX *mem_ctx,
1639                                                    struct samu *user,
1640                                                    struct dom_sid **pp_sids,
1641                                                    gid_t **pp_gids,
1642                                                    uint32_t *p_num_groups)
1643 {
1644         size_t i;
1645         gid_t gid;
1646         struct passwd *pw;
1647         const char *username = pdb_get_username(user);
1648
1649
1650         /* Ignore the primary group SID.  Honor the real Unix primary group.
1651            The primary group SID is only of real use to Windows clients */
1652
1653         if ( !(pw = Get_Pwnam_alloc(mem_ctx, username)) ) {
1654                 return NT_STATUS_NO_SUCH_USER;
1655         }
1656
1657         gid = pw->pw_gid;
1658
1659         TALLOC_FREE( pw );
1660
1661         if (!getgroups_unix_user(mem_ctx, username, gid, pp_gids, p_num_groups)) {
1662                 return NT_STATUS_NO_SUCH_USER;
1663         }
1664
1665         if (*p_num_groups == 0) {
1666                 smb_panic("primary group missing");
1667         }
1668
1669         *pp_sids = talloc_array(mem_ctx, struct dom_sid, *p_num_groups);
1670
1671         if (*pp_sids == NULL) {
1672                 TALLOC_FREE(*pp_gids);
1673                 return NT_STATUS_NO_MEMORY;
1674         }
1675
1676         for (i=0; i<*p_num_groups; i++) {
1677                 gid_to_sid(&(*pp_sids)[i], (*pp_gids)[i]);
1678         }
1679
1680         return NT_STATUS_OK;
1681 }
1682
1683 /*******************************************************************
1684  Look up a rid in the SAM we're responsible for (i.e. passdb)
1685  ********************************************************************/
1686
1687 static bool lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32_t rid,
1688                                   const char **name,
1689                                   enum lsa_SidType *psid_name_use,
1690                                   uid_t *uid, gid_t *gid)
1691 {
1692         struct samu *sam_account = NULL;
1693         GROUP_MAP *map = NULL;
1694         bool ret;
1695         struct dom_sid sid;
1696
1697         *psid_name_use = SID_NAME_UNKNOWN;
1698
1699         DEBUG(5,("lookup_global_sam_rid: looking up RID %u.\n",
1700                  (unsigned int)rid));
1701
1702         sid_compose(&sid, get_global_sam_sid(), rid);
1703
1704         /* see if the passdb can help us with the name of the user */
1705
1706         if ( !(sam_account = samu_new( NULL )) ) {
1707                 return False;
1708         }
1709
1710         map = talloc_zero(mem_ctx, GROUP_MAP);
1711         if (!map) {
1712                 return false;
1713         }
1714
1715         /* BEING ROOT BLOCK */
1716         become_root();
1717         ret = pdb_getsampwsid(sam_account, &sid);
1718         if (!ret) {
1719                 TALLOC_FREE(sam_account);
1720                 ret = pdb_getgrsid(map, sid);
1721         }
1722         unbecome_root();
1723         /* END BECOME_ROOT BLOCK */
1724
1725         if (sam_account || !ret) {
1726                 TALLOC_FREE(map);
1727         }
1728
1729         if (sam_account) {
1730                 struct passwd *pw;
1731
1732                 *name = talloc_strdup(mem_ctx, pdb_get_username(sam_account));
1733                 if (!*name) {
1734                         TALLOC_FREE(sam_account);
1735                         return False;
1736                 }
1737
1738                 *psid_name_use = SID_NAME_USER;
1739
1740                 TALLOC_FREE(sam_account);
1741
1742                 if (uid == NULL) {
1743                         return True;
1744                 }
1745
1746                 pw = Get_Pwnam_alloc(talloc_tos(), *name);
1747                 if (pw == NULL) {
1748                         return False;
1749                 }
1750                 *uid = pw->pw_uid;
1751                 TALLOC_FREE(pw);
1752                 return True;
1753
1754         } else if (map && (map->gid != (gid_t)-1)) {
1755
1756                 /* do not resolve SIDs to a name unless there is a valid
1757                    gid associated with it */
1758
1759                 *name = talloc_steal(mem_ctx, map->nt_name);
1760                 *psid_name_use = map->sid_name_use;
1761
1762                 if (gid) {
1763                         *gid = map->gid;
1764                 }
1765
1766                 TALLOC_FREE(map);
1767                 return True;
1768         }
1769
1770         TALLOC_FREE(map);
1771
1772         /* Windows will always map RID 513 to something.  On a non-domain 
1773            controller, this gets mapped to SERVER\None. */
1774
1775         if (uid || gid) {
1776                 DEBUG(5, ("Can't find a unix id for an unmapped group\n"));
1777                 return False;
1778         }
1779
1780         if ( rid == DOMAIN_RID_USERS ) {
1781                 *name = talloc_strdup(mem_ctx, "None" );
1782                 *psid_name_use = SID_NAME_DOM_GRP;
1783
1784                 return True;
1785         }
1786
1787         return False;
1788 }
1789
1790 static NTSTATUS pdb_default_lookup_rids(struct pdb_methods *methods,
1791                                         const struct dom_sid *domain_sid,
1792                                         int num_rids,
1793                                         uint32_t *rids,
1794                                         const char **names,
1795                                         enum lsa_SidType *attrs)
1796 {
1797         int i;
1798         NTSTATUS result;
1799         bool have_mapped = False;
1800         bool have_unmapped = False;
1801
1802         if (sid_check_is_builtin(domain_sid)) {
1803
1804                 for (i=0; i<num_rids; i++) {
1805                         const char *name;
1806
1807                         if (lookup_builtin_rid(names, rids[i], &name)) {
1808                                 attrs[i] = SID_NAME_ALIAS;
1809                                 names[i] = name;
1810                                 DEBUG(5,("lookup_rids: %s:%d\n",
1811                                          names[i], attrs[i]));
1812                                 have_mapped = True;
1813                         } else {
1814                                 have_unmapped = True;
1815                                 attrs[i] = SID_NAME_UNKNOWN;
1816                         }
1817                 }
1818                 goto done;
1819         }
1820
1821         /* Should not happen, but better check once too many */
1822         if (!sid_check_is_domain(domain_sid)) {
1823                 return NT_STATUS_INVALID_HANDLE;
1824         }
1825
1826         for (i = 0; i < num_rids; i++) {
1827                 const char *name;
1828
1829                 if (lookup_global_sam_rid(names, rids[i], &name, &attrs[i],
1830                                           NULL, NULL)) {
1831                         if (name == NULL) {
1832                                 return NT_STATUS_NO_MEMORY;
1833                         }
1834                         names[i] = name;
1835                         DEBUG(5,("lookup_rids: %s:%d\n", names[i], attrs[i]));
1836                         have_mapped = True;
1837                 } else {
1838                         have_unmapped = True;
1839                         attrs[i] = SID_NAME_UNKNOWN;
1840                 }
1841         }
1842
1843  done:
1844
1845         result = NT_STATUS_NONE_MAPPED;
1846
1847         if (have_mapped)
1848                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1849
1850         return result;
1851 }
1852
1853 #if 0
1854 static NTSTATUS pdb_default_lookup_names(struct pdb_methods *methods,
1855                                          const struct dom_sid *domain_sid,
1856                                          int num_names,
1857                                          const char **names,
1858                                          uint32_t *rids,
1859                                          enum lsa_SidType *attrs)
1860 {
1861         int i;
1862         NTSTATUS result;
1863         bool have_mapped = False;
1864         bool have_unmapped = False;
1865
1866         if (sid_check_is_builtin(domain_sid)) {
1867
1868                 for (i=0; i<num_names; i++) {
1869                         uint32_t rid;
1870
1871                         if (lookup_builtin_name(names[i], &rid)) {
1872                                 attrs[i] = SID_NAME_ALIAS;
1873                                 rids[i] = rid;
1874                                 DEBUG(5,("lookup_rids: %s:%d\n",
1875                                          names[i], attrs[i]));
1876                                 have_mapped = True;
1877                         } else {
1878                                 have_unmapped = True;
1879                                 attrs[i] = SID_NAME_UNKNOWN;
1880                         }
1881                 }
1882                 goto done;
1883         }
1884
1885         /* Should not happen, but better check once too many */
1886         if (!sid_check_is_domain(domain_sid)) {
1887                 return NT_STATUS_INVALID_HANDLE;
1888         }
1889
1890         for (i = 0; i < num_names; i++) {
1891                 if (lookup_global_sam_name(names[i], 0, &rids[i], &attrs[i])) {
1892                         DEBUG(5,("lookup_names: %s-> %d:%d\n", names[i],
1893                                  rids[i], attrs[i]));
1894                         have_mapped = True;
1895                 } else {
1896                         have_unmapped = True;
1897                         attrs[i] = SID_NAME_UNKNOWN;
1898                 }
1899         }
1900
1901  done:
1902
1903         result = NT_STATUS_NONE_MAPPED;
1904
1905         if (have_mapped)
1906                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1907
1908         return result;
1909 }
1910 #endif
1911
1912 static int pdb_search_destructor(struct pdb_search *search)
1913 {
1914         if ((!search->search_ended) && (search->search_end != NULL)) {
1915                 search->search_end(search);
1916         }
1917         return 0;
1918 }
1919
1920 struct pdb_search *pdb_search_init(TALLOC_CTX *mem_ctx,
1921                                    enum pdb_search_type type)
1922 {
1923         struct pdb_search *result;
1924
1925         result = talloc(mem_ctx, struct pdb_search);
1926         if (result == NULL) {
1927                 DEBUG(0, ("talloc failed\n"));
1928                 return NULL;
1929         }
1930
1931         result->type = type;
1932         result->cache = NULL;
1933         result->num_entries = 0;
1934         result->cache_size = 0;
1935         result->search_ended = False;
1936         result->search_end = NULL;
1937
1938         /* Segfault appropriately if not initialized */
1939         result->next_entry = NULL;
1940         result->search_end = NULL;
1941
1942         talloc_set_destructor(result, pdb_search_destructor);
1943
1944         return result;
1945 }
1946
1947 static void fill_displayentry(TALLOC_CTX *mem_ctx, uint32_t rid,
1948                               uint16_t acct_flags,
1949                               const char *account_name,
1950                               const char *fullname,
1951                               const char *description,
1952                               struct samr_displayentry *entry)
1953 {
1954         entry->rid = rid;
1955         entry->acct_flags = acct_flags;
1956
1957         if (account_name != NULL)
1958                 entry->account_name = talloc_strdup(mem_ctx, account_name);
1959         else
1960                 entry->account_name = "";
1961
1962         if (fullname != NULL)
1963                 entry->fullname = talloc_strdup(mem_ctx, fullname);
1964         else
1965                 entry->fullname = "";
1966
1967         if (description != NULL)
1968                 entry->description = talloc_strdup(mem_ctx, description);
1969         else
1970                 entry->description = "";
1971 }
1972
1973 struct group_search {
1974         GROUP_MAP **groups;
1975         size_t num_groups, current_group;
1976 };
1977
1978 static bool next_entry_groups(struct pdb_search *s,
1979                               struct samr_displayentry *entry)
1980 {
1981         struct group_search *state = (struct group_search *)s->private_data;
1982         uint32_t rid;
1983         GROUP_MAP *map;
1984
1985         if (state->current_group == state->num_groups)
1986                 return False;
1987
1988         map = state->groups[state->current_group];
1989
1990         sid_peek_rid(&map->sid, &rid);
1991
1992         fill_displayentry(s, rid, 0, map->nt_name, NULL, map->comment, entry);
1993
1994         state->current_group += 1;
1995         return True;
1996 }
1997
1998 static void search_end_groups(struct pdb_search *search)
1999 {
2000         struct group_search *state =
2001                 (struct group_search *)search->private_data;
2002         TALLOC_FREE(state->groups);
2003 }
2004
2005 static bool pdb_search_grouptype(struct pdb_methods *methods,
2006                                  struct pdb_search *search,
2007                                  const struct dom_sid *sid, enum lsa_SidType type)
2008 {
2009         struct group_search *state;
2010
2011         state = talloc_zero(search, struct group_search);
2012         if (state == NULL) {
2013                 DEBUG(0, ("talloc failed\n"));
2014                 return False;
2015         }
2016
2017         if (!NT_STATUS_IS_OK(methods->enum_group_mapping(methods, sid, type, 
2018                                                          &state->groups, &state->num_groups,
2019                                                          True))) {
2020                 DEBUG(0, ("Could not enum groups\n"));
2021                 return False;
2022         }
2023
2024         state->current_group = 0;
2025         search->private_data = state;
2026         search->next_entry = next_entry_groups;
2027         search->search_end = search_end_groups;
2028         return True;
2029 }
2030
2031 static bool pdb_default_search_groups(struct pdb_methods *methods,
2032                                       struct pdb_search *search)
2033 {
2034         return pdb_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
2035 }
2036
2037 static bool pdb_default_search_aliases(struct pdb_methods *methods,
2038                                        struct pdb_search *search,
2039                                        const struct dom_sid *sid)
2040 {
2041
2042         return pdb_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
2043 }
2044
2045 static struct samr_displayentry *pdb_search_getentry(struct pdb_search *search,
2046                                                      uint32_t idx)
2047 {
2048         if (idx < search->num_entries)
2049                 return &search->cache[idx];
2050
2051         if (search->search_ended)
2052                 return NULL;
2053
2054         while (idx >= search->num_entries) {
2055                 struct samr_displayentry entry;
2056
2057                 if (!search->next_entry(search, &entry)) {
2058                         search->search_end(search);
2059                         search->search_ended = True;
2060                         break;
2061                 }
2062
2063                 ADD_TO_LARGE_ARRAY(search, struct samr_displayentry,
2064                                    entry, &search->cache, &search->num_entries,
2065                                    &search->cache_size);
2066         }
2067
2068         return (search->num_entries > idx) ? &search->cache[idx] : NULL;
2069 }
2070
2071 struct pdb_search *pdb_search_users(TALLOC_CTX *mem_ctx, uint32_t acct_flags)
2072 {
2073         struct pdb_methods *pdb = pdb_get_methods();
2074         struct pdb_search *result;
2075
2076         result = pdb_search_init(mem_ctx, PDB_USER_SEARCH);
2077         if (result == NULL) {
2078                 return NULL;
2079         }
2080
2081         if (!pdb->search_users(pdb, result, acct_flags)) {
2082                 TALLOC_FREE(result);
2083                 return NULL;
2084         }
2085         return result;
2086 }
2087
2088 struct pdb_search *pdb_search_groups(TALLOC_CTX *mem_ctx)
2089 {
2090         struct pdb_methods *pdb = pdb_get_methods();
2091         struct pdb_search *result;
2092
2093         result = pdb_search_init(mem_ctx, PDB_GROUP_SEARCH);
2094         if (result == NULL) {
2095                  return NULL;
2096         }
2097
2098         if (!pdb->search_groups(pdb, result)) {
2099                 TALLOC_FREE(result);
2100                 return NULL;
2101         }
2102         return result;
2103 }
2104
2105 struct pdb_search *pdb_search_aliases(TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
2106 {
2107         struct pdb_methods *pdb = pdb_get_methods();
2108         struct pdb_search *result;
2109
2110         if (pdb == NULL) return NULL;
2111
2112         result = pdb_search_init(mem_ctx, PDB_ALIAS_SEARCH);
2113         if (result == NULL) {
2114                 return NULL;
2115         }
2116
2117         if (!pdb->search_aliases(pdb, result, sid)) {
2118                 TALLOC_FREE(result);
2119                 return NULL;
2120         }
2121         return result;
2122 }
2123
2124 uint32_t pdb_search_entries(struct pdb_search *search,
2125                           uint32_t start_idx, uint32_t max_entries,
2126                           struct samr_displayentry **result)
2127 {
2128         struct samr_displayentry *end_entry;
2129         uint32_t end_idx = start_idx+max_entries-1;
2130
2131         /* The first entry needs to be searched after the last. Otherwise the
2132          * first entry might have moved due to a realloc during the search for
2133          * the last entry. */
2134
2135         end_entry = pdb_search_getentry(search, end_idx);
2136         *result = pdb_search_getentry(search, start_idx);
2137
2138         if (end_entry != NULL)
2139                 return max_entries;
2140
2141         if (start_idx >= search->num_entries)
2142                 return 0;
2143
2144         return search->num_entries - start_idx;
2145 }
2146
2147 /*******************************************************************
2148  trustdom methods
2149  *******************************************************************/
2150
2151 bool pdb_get_trusteddom_pw(const char *domain, char** pwd, struct dom_sid *sid,
2152                            time_t *pass_last_set_time)
2153 {
2154         struct pdb_methods *pdb = pdb_get_methods();
2155         return pdb->get_trusteddom_pw(pdb, domain, pwd, sid, 
2156                         pass_last_set_time);
2157 }
2158
2159 bool pdb_set_trusteddom_pw(const char* domain, const char* pwd,
2160                            const struct dom_sid *sid)
2161 {
2162         struct pdb_methods *pdb = pdb_get_methods();
2163         return pdb->set_trusteddom_pw(pdb, domain, pwd, sid);
2164 }
2165
2166 bool pdb_del_trusteddom_pw(const char *domain)
2167 {
2168         struct pdb_methods *pdb = pdb_get_methods();
2169         return pdb->del_trusteddom_pw(pdb, domain);
2170 }
2171
2172 NTSTATUS pdb_enum_trusteddoms(TALLOC_CTX *mem_ctx, uint32_t *num_domains,
2173                               struct trustdom_info ***domains)
2174 {
2175         struct pdb_methods *pdb = pdb_get_methods();
2176         return pdb->enum_trusteddoms(pdb, mem_ctx, num_domains, domains);
2177 }
2178
2179 /*******************************************************************
2180  the defaults for trustdom methods: 
2181  these simply call the original passdb/secrets.c actions,
2182  to be replaced by pdb_ldap.
2183  *******************************************************************/
2184
2185 static bool pdb_default_get_trusteddom_pw(struct pdb_methods *methods,
2186                                           const char *domain, 
2187                                           char** pwd, 
2188                                           struct dom_sid *sid,
2189                                           time_t *pass_last_set_time)
2190 {
2191         return secrets_fetch_trusted_domain_password(domain, pwd,
2192                                 sid, pass_last_set_time);
2193
2194 }
2195
2196 static bool pdb_default_set_trusteddom_pw(struct pdb_methods *methods, 
2197                                           const char* domain, 
2198                                           const char* pwd,
2199                                           const struct dom_sid *sid)
2200 {
2201         return secrets_store_trusted_domain_password(domain, pwd, sid);
2202 }
2203
2204 static bool pdb_default_del_trusteddom_pw(struct pdb_methods *methods, 
2205                                           const char *domain)
2206 {
2207         return trusted_domain_password_delete(domain);
2208 }
2209
2210 static NTSTATUS pdb_default_enum_trusteddoms(struct pdb_methods *methods,
2211                                              TALLOC_CTX *mem_ctx, 
2212                                              uint32_t *num_domains,
2213                                              struct trustdom_info ***domains)
2214 {
2215         return secrets_trusted_domains(mem_ctx, num_domains, domains);
2216 }
2217
2218 /*******************************************************************
2219  trusted_domain methods
2220  *******************************************************************/
2221
2222 NTSTATUS pdb_get_trusted_domain(TALLOC_CTX *mem_ctx, const char *domain,
2223                                 struct pdb_trusted_domain **td)
2224 {
2225         struct pdb_methods *pdb = pdb_get_methods();
2226         return pdb->get_trusted_domain(pdb, mem_ctx, domain, td);
2227 }
2228
2229 NTSTATUS pdb_get_trusted_domain_by_sid(TALLOC_CTX *mem_ctx, struct dom_sid *sid,
2230                                 struct pdb_trusted_domain **td)
2231 {
2232         struct pdb_methods *pdb = pdb_get_methods();
2233         return pdb->get_trusted_domain_by_sid(pdb, mem_ctx, sid, td);
2234 }
2235
2236 NTSTATUS pdb_set_trusted_domain(const char* domain,
2237                                 const struct pdb_trusted_domain *td)
2238 {
2239         struct pdb_methods *pdb = pdb_get_methods();
2240         return pdb->set_trusted_domain(pdb, domain, td);
2241 }
2242
2243 NTSTATUS pdb_del_trusted_domain(const char *domain)
2244 {
2245         struct pdb_methods *pdb = pdb_get_methods();
2246         return pdb->del_trusted_domain(pdb, domain);
2247 }
2248
2249 NTSTATUS pdb_enum_trusted_domains(TALLOC_CTX *mem_ctx, uint32_t *num_domains,
2250                                   struct pdb_trusted_domain ***domains)
2251 {
2252         struct pdb_methods *pdb = pdb_get_methods();
2253         return pdb->enum_trusted_domains(pdb, mem_ctx, num_domains, domains);
2254 }
2255
2256 static NTSTATUS pdb_default_get_trusted_domain(struct pdb_methods *methods,
2257                                                TALLOC_CTX *mem_ctx,
2258                                                const char *domain,
2259                                                struct pdb_trusted_domain **td)
2260 {
2261         struct trustAuthInOutBlob taiob;
2262         struct AuthenticationInformation aia;
2263         struct pdb_trusted_domain *tdom;
2264         enum ndr_err_code ndr_err;
2265         time_t last_set_time;
2266         char *pwd;
2267         bool ok;
2268
2269         tdom = talloc(mem_ctx, struct pdb_trusted_domain);
2270         if (!tdom) {
2271                 return NT_STATUS_NO_MEMORY;
2272         }
2273
2274         tdom->domain_name = talloc_strdup(tdom, domain);
2275         tdom->netbios_name = talloc_strdup(tdom, domain);
2276         if (!tdom->domain_name || !tdom->netbios_name) {
2277                 talloc_free(tdom);
2278                 return NT_STATUS_NO_MEMORY;
2279         }
2280
2281         tdom->trust_auth_incoming = data_blob_null;
2282
2283         ok = pdb_get_trusteddom_pw(domain, &pwd, &tdom->security_identifier,
2284                                    &last_set_time);
2285         if (!ok) {
2286                 talloc_free(tdom);
2287                 return NT_STATUS_UNSUCCESSFUL;
2288         }
2289
2290         ZERO_STRUCT(taiob);
2291         ZERO_STRUCT(aia);
2292         taiob.count = 1;
2293         taiob.current.count = 1;
2294         taiob.current.array = &aia;
2295         unix_to_nt_time(&aia.LastUpdateTime, last_set_time);
2296         aia.AuthType = TRUST_AUTH_TYPE_CLEAR;
2297         aia.AuthInfo.clear.password = (uint8_t *) pwd;
2298         aia.AuthInfo.clear.size = strlen(pwd);
2299         taiob.previous.count = 0;
2300         taiob.previous.array = NULL;
2301
2302         ndr_err = ndr_push_struct_blob(&tdom->trust_auth_outgoing,
2303                                         tdom, &taiob,
2304                         (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2305         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2306                 talloc_free(tdom);
2307                 return NT_STATUS_UNSUCCESSFUL;
2308         }
2309
2310         tdom->trust_direction = LSA_TRUST_DIRECTION_OUTBOUND;
2311         tdom->trust_type = LSA_TRUST_TYPE_DOWNLEVEL;
2312         tdom->trust_attributes = 0;
2313         tdom->trust_forest_trust_info = data_blob_null;
2314
2315         *td = tdom;
2316         return NT_STATUS_OK;
2317 }
2318
2319 static NTSTATUS pdb_default_get_trusted_domain_by_sid(struct pdb_methods *methods,
2320                                                       TALLOC_CTX *mem_ctx,
2321                                                       struct dom_sid *sid,
2322                                                       struct pdb_trusted_domain **td)
2323 {
2324         return NT_STATUS_NOT_IMPLEMENTED;
2325 }
2326
2327 #define IS_NULL_DATA_BLOB(d) ((d).data == NULL && (d).length == 0)
2328
2329 static NTSTATUS pdb_default_set_trusted_domain(struct pdb_methods *methods,
2330                                                const char* domain,
2331                                                const struct pdb_trusted_domain *td)
2332 {
2333         struct trustAuthInOutBlob taiob;
2334         struct AuthenticationInformation *aia;
2335         enum ndr_err_code ndr_err;
2336         char *pwd;
2337         bool ok;
2338
2339         if (td->trust_attributes != 0 ||
2340             td->trust_type != LSA_TRUST_TYPE_DOWNLEVEL ||
2341             td->trust_direction != LSA_TRUST_DIRECTION_OUTBOUND ||
2342             !IS_NULL_DATA_BLOB(td->trust_auth_incoming) ||
2343             !IS_NULL_DATA_BLOB(td->trust_forest_trust_info)) {
2344             return NT_STATUS_NOT_IMPLEMENTED;
2345         }
2346
2347         ZERO_STRUCT(taiob);
2348         ndr_err = ndr_pull_struct_blob(&td->trust_auth_outgoing, talloc_tos(),
2349                               &taiob,
2350                               (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2351         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2352                 return NT_STATUS_UNSUCCESSFUL;
2353         }
2354
2355         aia = (struct AuthenticationInformation *) taiob.current.array;
2356
2357         if (taiob.count != 1 || taiob.current.count != 1 ||
2358             taiob.previous.count != 0 ||
2359             aia->AuthType != TRUST_AUTH_TYPE_CLEAR) {
2360             return NT_STATUS_NOT_IMPLEMENTED;
2361         }
2362
2363         pwd = talloc_strndup(talloc_tos(), (char *) aia->AuthInfo.clear.password,
2364                              aia->AuthInfo.clear.size);
2365         if (!pwd) {
2366                 return NT_STATUS_NO_MEMORY;
2367         }
2368
2369         ok = pdb_set_trusteddom_pw(domain, pwd, &td->security_identifier);
2370         if (!ok) {
2371                 return NT_STATUS_UNSUCCESSFUL;
2372         }
2373
2374         return NT_STATUS_OK;
2375 }
2376
2377 static NTSTATUS pdb_default_del_trusted_domain(struct pdb_methods *methods,
2378                                                const char *domain)
2379 {
2380         return NT_STATUS_NOT_IMPLEMENTED;
2381 }
2382
2383 static NTSTATUS pdb_default_enum_trusted_domains(struct pdb_methods *methods,
2384                                                  TALLOC_CTX *mem_ctx,
2385                                                  uint32_t *num_domains,
2386                                                  struct pdb_trusted_domain ***domains)
2387 {
2388         return NT_STATUS_NOT_IMPLEMENTED;
2389 }
2390
2391 static struct pdb_domain_info *pdb_default_get_domain_info(
2392         struct pdb_methods *m, TALLOC_CTX *mem_ctx)
2393 {
2394         return NULL;
2395 }
2396
2397 /*******************************************************************
2398  secret methods
2399  *******************************************************************/
2400
2401 NTSTATUS pdb_get_secret(TALLOC_CTX *mem_ctx,
2402                         const char *secret_name,
2403                         DATA_BLOB *secret_current,
2404                         NTTIME *secret_current_lastchange,
2405                         DATA_BLOB *secret_old,
2406                         NTTIME *secret_old_lastchange,
2407                         struct security_descriptor **sd)
2408 {
2409         struct pdb_methods *pdb = pdb_get_methods();
2410         return pdb->get_secret(pdb, mem_ctx, secret_name,
2411                                secret_current, secret_current_lastchange,
2412                                secret_old, secret_old_lastchange,
2413                                sd);
2414 }
2415
2416 NTSTATUS pdb_set_secret(const char *secret_name,
2417                         DATA_BLOB *secret_current,
2418                         DATA_BLOB *secret_old,
2419                         struct security_descriptor *sd)
2420 {
2421         struct pdb_methods *pdb = pdb_get_methods();
2422         return pdb->set_secret(pdb, secret_name,
2423                                secret_current,
2424                                secret_old,
2425                                sd);
2426 }
2427
2428 NTSTATUS pdb_delete_secret(const char *secret_name)
2429 {
2430         struct pdb_methods *pdb = pdb_get_methods();
2431         return pdb->delete_secret(pdb, secret_name);
2432 }
2433
2434 static NTSTATUS pdb_default_get_secret(struct pdb_methods *methods,
2435                                        TALLOC_CTX *mem_ctx,
2436                                        const char *secret_name,
2437                                        DATA_BLOB *secret_current,
2438                                        NTTIME *secret_current_lastchange,
2439                                        DATA_BLOB *secret_old,
2440                                        NTTIME *secret_old_lastchange,
2441                                        struct security_descriptor **sd)
2442 {
2443         return lsa_secret_get(mem_ctx, secret_name,
2444                               secret_current,
2445                               secret_current_lastchange,
2446                               secret_old,
2447                               secret_old_lastchange,
2448                               sd);
2449 }
2450
2451 static NTSTATUS pdb_default_set_secret(struct pdb_methods *methods,
2452                                        const char *secret_name,
2453                                        DATA_BLOB *secret_current,
2454                                        DATA_BLOB *secret_old,
2455                                        struct security_descriptor *sd)
2456 {
2457         return lsa_secret_set(secret_name,
2458                               secret_current,
2459                               secret_old,
2460                               sd);
2461 }
2462
2463 static NTSTATUS pdb_default_delete_secret(struct pdb_methods *methods,
2464                                           const char *secret_name)
2465 {
2466         return lsa_secret_delete(secret_name);
2467 }
2468
2469 /*******************************************************************
2470  Create a pdb_methods structure and initialize it with the default
2471  operations.  In this way a passdb module can simply implement
2472  the functionality it cares about.  However, normally this is done 
2473  in groups of related functions.
2474 *******************************************************************/
2475
2476 NTSTATUS make_pdb_method( struct pdb_methods **methods ) 
2477 {
2478         /* allocate memory for the structure as its own talloc CTX */
2479
2480         *methods = talloc_zero(NULL, struct pdb_methods);
2481         if (*methods == NULL) {
2482                 return NT_STATUS_NO_MEMORY;
2483         }
2484
2485         (*methods)->get_domain_info = pdb_default_get_domain_info;
2486         (*methods)->getsampwnam = pdb_default_getsampwnam;
2487         (*methods)->getsampwsid = pdb_default_getsampwsid;
2488         (*methods)->create_user = pdb_default_create_user;
2489         (*methods)->delete_user = pdb_default_delete_user;
2490         (*methods)->add_sam_account = pdb_default_add_sam_account;
2491         (*methods)->update_sam_account = pdb_default_update_sam_account;
2492         (*methods)->delete_sam_account = pdb_default_delete_sam_account;
2493         (*methods)->rename_sam_account = pdb_default_rename_sam_account;
2494         (*methods)->update_login_attempts = pdb_default_update_login_attempts;
2495
2496         (*methods)->getgrsid = pdb_default_getgrsid;
2497         (*methods)->getgrgid = pdb_default_getgrgid;
2498         (*methods)->getgrnam = pdb_default_getgrnam;
2499         (*methods)->create_dom_group = pdb_default_create_dom_group;
2500         (*methods)->delete_dom_group = pdb_default_delete_dom_group;
2501         (*methods)->add_group_mapping_entry = pdb_default_add_group_mapping_entry;
2502         (*methods)->update_group_mapping_entry = pdb_default_update_group_mapping_entry;
2503         (*methods)->delete_group_mapping_entry = pdb_default_delete_group_mapping_entry;
2504         (*methods)->enum_group_mapping = pdb_default_enum_group_mapping;
2505         (*methods)->enum_group_members = pdb_default_enum_group_members;
2506         (*methods)->enum_group_memberships = pdb_default_enum_group_memberships;
2507         (*methods)->set_unix_primary_group = pdb_default_set_unix_primary_group;
2508         (*methods)->add_groupmem = pdb_default_add_groupmem;
2509         (*methods)->del_groupmem = pdb_default_del_groupmem;
2510         (*methods)->create_alias = pdb_default_create_alias;
2511         (*methods)->delete_alias = pdb_default_delete_alias;
2512         (*methods)->get_aliasinfo = pdb_default_get_aliasinfo;
2513         (*methods)->set_aliasinfo = pdb_default_set_aliasinfo;
2514         (*methods)->add_aliasmem = pdb_default_add_aliasmem;
2515         (*methods)->del_aliasmem = pdb_default_del_aliasmem;
2516         (*methods)->enum_aliasmem = pdb_default_enum_aliasmem;
2517         (*methods)->enum_alias_memberships = pdb_default_alias_memberships;
2518         (*methods)->lookup_rids = pdb_default_lookup_rids;
2519         (*methods)->get_account_policy = pdb_default_get_account_policy;
2520         (*methods)->set_account_policy = pdb_default_set_account_policy;
2521         (*methods)->get_seq_num = pdb_default_get_seq_num;
2522         (*methods)->uid_to_sid = pdb_default_uid_to_sid;
2523         (*methods)->gid_to_sid = pdb_default_gid_to_sid;
2524         (*methods)->sid_to_id = pdb_default_sid_to_id;
2525
2526         (*methods)->search_groups = pdb_default_search_groups;
2527         (*methods)->search_aliases = pdb_default_search_aliases;
2528
2529         (*methods)->get_trusteddom_pw = pdb_default_get_trusteddom_pw;
2530         (*methods)->set_trusteddom_pw = pdb_default_set_trusteddom_pw;
2531         (*methods)->del_trusteddom_pw = pdb_default_del_trusteddom_pw;
2532         (*methods)->enum_trusteddoms  = pdb_default_enum_trusteddoms;
2533
2534         (*methods)->get_trusted_domain = pdb_default_get_trusted_domain;
2535         (*methods)->get_trusted_domain_by_sid = pdb_default_get_trusted_domain_by_sid;
2536         (*methods)->set_trusted_domain = pdb_default_set_trusted_domain;
2537         (*methods)->del_trusted_domain = pdb_default_del_trusted_domain;
2538         (*methods)->enum_trusted_domains = pdb_default_enum_trusted_domains;
2539
2540         (*methods)->get_secret = pdb_default_get_secret;
2541         (*methods)->set_secret = pdb_default_set_secret;
2542         (*methods)->delete_secret = pdb_default_delete_secret;
2543
2544         return NT_STATUS_OK;
2545 }