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