This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[tprouty/samba.git] / source3 / passdb / pdb_tdb.c
1 /*
2  * Unix SMB/CIFS implementation. 
3  * SMB parameters and setup
4  * Copyright (C) Andrew Tridgell 1992-1998
5  * Copyright (C) Simo Sorce 2000-2002
6  * Copyright (C) Gerald Carter 2000
7  * Copyright (C) Jeremy Allison 2001
8  * Copyright (C) Andrew Bartlett 2002
9  * 
10  * This program is free software; you can redistribute it and/or modify it under
11  * the terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 2 of the License, or (at your option)
13  * any later version.
14  * 
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
18  * more details.
19  * 
20  * You should have received a copy of the GNU General Public License along with
21  * this program; if not, write to the Free Software Foundation, Inc., 675
22  * Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include "includes.h"
26
27 #if 0 /* when made a module use this */
28
29 static int tdbsam_debug_level = DBGC_ALL;
30 #undef DBGC_CLASS
31 #define DBGC_CLASS tdbsam_debug_level
32
33 #else
34
35 #undef DBGC_CLASS
36 #define DBGC_CLASS DBGC_PASSDB
37
38 #endif
39
40 #define PDB_VERSION             "20010830"
41 #define PASSDB_FILE_NAME        "passdb.tdb"
42 #define TDB_FORMAT_STRING       "ddddddBBBBBBBBBBBBddBBwdwdBdd"
43 #define USERPREFIX              "USER_"
44 #define RIDPREFIX               "RID_"
45
46 struct tdbsam_privates {
47         TDB_CONTEXT     *passwd_tdb;
48         TDB_DATA        key;
49
50         /* retrive-once info */
51         const char *tdbsam_location;
52
53         BOOL permit_non_unix_accounts;
54
55         BOOL algorithmic_rids;
56
57         uint32 low_nua_rid; 
58         uint32 high_nua_rid;
59 };
60
61 /**********************************************************************
62  Intialize a SAM_ACCOUNT struct from a BYTE buffer of size len
63  *********************************************************************/
64
65 static BOOL init_sam_from_buffer (struct tdbsam_privates *tdb_state,
66                                   SAM_ACCOUNT *sampass, uint8 *buf, uint32 buflen)
67 {
68
69         /* times are stored as 32bit integer
70            take care on system with 64bit wide time_t
71            --SSS */
72         uint32  logon_time,
73                 logoff_time,
74                 kickoff_time,
75                 pass_last_set_time,
76                 pass_can_change_time,
77                 pass_must_change_time;
78         char *username;
79         char *domain;
80         char *nt_username;
81         char *dir_drive;
82         char *unknown_str;
83         char *munged_dial;
84         char *fullname;
85         char *homedir;
86         char *logon_script;
87         char *profile_path;
88         char *acct_desc;
89         char *workstations;
90         uint32  username_len, domain_len, nt_username_len,
91                 dir_drive_len, unknown_str_len, munged_dial_len,
92                 fullname_len, homedir_len, logon_script_len,
93                 profile_path_len, acct_desc_len, workstations_len;
94                 
95         uint32  user_rid, group_rid, unknown_3, hours_len, unknown_5, unknown_6;
96         uint16  acct_ctrl, logon_divs;
97         uint8   *hours;
98         static uint8    *lm_pw_ptr, *nt_pw_ptr;
99         uint32          len = 0;
100         uint32          lm_pw_len, nt_pw_len, hourslen;
101         BOOL ret = True;
102         struct passwd *pw;
103         uid_t uid = -1;
104         gid_t gid = -1; /* This is what standard sub advanced expects if no gid is known */
105         
106         if(sampass == NULL || buf == NULL) {
107                 DEBUG(0, ("init_sam_from_buffer: NULL parameters found!\n"));
108                 return False;
109         }
110                                                                         
111         /* unpack the buffer into variables */
112         len = tdb_unpack (buf, buflen, TDB_FORMAT_STRING,
113                 &logon_time,
114                 &logoff_time,
115                 &kickoff_time,
116                 &pass_last_set_time,
117                 &pass_can_change_time,
118                 &pass_must_change_time,
119                 &username_len, &username,
120                 &domain_len, &domain,
121                 &nt_username_len, &nt_username,
122                 &fullname_len, &fullname,
123                 &homedir_len, &homedir,
124                 &dir_drive_len, &dir_drive,
125                 &logon_script_len, &logon_script,
126                 &profile_path_len, &profile_path,
127                 &acct_desc_len, &acct_desc,
128                 &workstations_len, &workstations,
129                 &unknown_str_len, &unknown_str,
130                 &munged_dial_len, &munged_dial,
131                 &user_rid,
132                 &group_rid,
133                 &lm_pw_len, &lm_pw_ptr,
134                 &nt_pw_len, &nt_pw_ptr,
135                 &acct_ctrl,
136                 &unknown_3,
137                 &logon_divs,
138                 &hours_len,
139                 &hourslen, &hours,
140                 &unknown_5,
141                 &unknown_6);
142                 
143         if (len == -1)  {
144                 ret = False;
145                 goto done;
146         }
147
148         /* validate the account and fill in UNIX uid and gid. Standard
149          * getpwnam() is used instead of Get_Pwnam() as we do not need
150          * to try case permutations
151          */
152         if (!username || !(pw = getpwnam_alloc(username))) {
153                 if (!(tdb_state->permit_non_unix_accounts)) {
154                         DEBUG(0,("tdbsam: getpwnam_alloc(%s) return NULL.  User does not exist!\n", username));
155                         ret = False;
156                         goto done;
157                 }
158         }
159                 
160         if (pw) {
161                 uid = pw->pw_uid;
162                 gid = pw->pw_gid;
163                 
164                 pdb_set_unix_homedir(sampass, pw->pw_dir, PDB_SET);
165
166                 passwd_free(&pw);
167
168                 pdb_set_uid(sampass, uid, PDB_SET);
169                 pdb_set_gid(sampass, gid, PDB_SET);
170         }
171
172         pdb_set_logon_time(sampass, logon_time, PDB_SET);
173         pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
174         pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
175         pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
176         pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
177         pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
178
179         pdb_set_username     (sampass, username, PDB_SET); 
180         pdb_set_domain       (sampass, domain, PDB_SET);
181         pdb_set_nt_username  (sampass, nt_username, PDB_SET);
182         pdb_set_fullname     (sampass, fullname, PDB_SET);
183
184         if (homedir) {
185                 pdb_set_homedir(sampass, homedir, PDB_SET);
186         }
187         else {
188                 pdb_set_homedir(sampass, 
189                                 talloc_sub_specified(sampass->mem_ctx, 
190                                                        lp_logon_home(),
191                                                        username, domain, 
192                                                        uid, gid),
193                                 PDB_DEFAULT);
194         }
195
196         if (dir_drive)  
197                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
198         else {
199                 pdb_set_dir_drive(sampass, 
200                                   talloc_sub_specified(sampass->mem_ctx, 
201                                                          lp_logon_drive(),
202                                                          username, domain, 
203                                                          uid, gid),
204                                   PDB_DEFAULT);
205         }
206
207         if (logon_script) 
208                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
209         else {
210                 pdb_set_logon_script(sampass, 
211                                      talloc_sub_specified(sampass->mem_ctx, 
212                                                             lp_logon_script(),
213                                                             username, domain, 
214                                                             uid, gid),
215                                   PDB_DEFAULT);
216         }
217         
218         if (profile_path) {     
219                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
220         } else {
221                 pdb_set_profile_path(sampass, 
222                                      talloc_sub_specified(sampass->mem_ctx, 
223                                                             lp_logon_path(),
224                                                             username, domain, 
225                                                             uid, gid),
226                                      PDB_DEFAULT);
227         }
228
229         pdb_set_acct_desc    (sampass, acct_desc, PDB_SET);
230         pdb_set_workstations (sampass, workstations, PDB_SET);
231         pdb_set_munged_dial  (sampass, munged_dial, PDB_SET);
232
233         if (lm_pw_ptr && lm_pw_len == LM_HASH_LEN) {
234                 if (!pdb_set_lanman_passwd(sampass, lm_pw_ptr, PDB_SET)) {
235                         ret = False;
236                         goto done;
237                 }
238         }
239
240         if (nt_pw_ptr && nt_pw_len == NT_HASH_LEN) {
241                 if (!pdb_set_nt_passwd(sampass, nt_pw_ptr, PDB_SET)) {
242                         ret = False;
243                         goto done;
244                 }
245         }
246
247         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
248         pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
249         pdb_set_unknown_3(sampass, unknown_3, PDB_SET);
250         pdb_set_hours_len(sampass, hours_len, PDB_SET);
251         pdb_set_unknown_5(sampass, unknown_5, PDB_SET);
252         pdb_set_unknown_6(sampass, unknown_6, PDB_SET);
253         pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
254         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
255         pdb_set_hours(sampass, hours, PDB_SET);
256
257 done:
258
259         SAFE_FREE(username);
260         SAFE_FREE(domain);
261         SAFE_FREE(nt_username);
262         SAFE_FREE(fullname);
263         SAFE_FREE(homedir);
264         SAFE_FREE(dir_drive);
265         SAFE_FREE(logon_script);
266         SAFE_FREE(profile_path);
267         SAFE_FREE(acct_desc);
268         SAFE_FREE(workstations);
269         SAFE_FREE(munged_dial);
270
271         return ret;
272 }
273
274 /**********************************************************************
275  Intialize a BYTE buffer from a SAM_ACCOUNT struct
276  *********************************************************************/
277 static uint32 init_buffer_from_sam (struct tdbsam_privates *tdb_state,
278                                     uint8 **buf, const SAM_ACCOUNT *sampass)
279 {
280         size_t          len, buflen;
281
282         /* times are stored as 32bit integer
283            take care on system with 64bit wide time_t
284            --SSS */
285         uint32  logon_time,
286                 logoff_time,
287                 kickoff_time,
288                 pass_last_set_time,
289                 pass_can_change_time,
290                 pass_must_change_time;
291
292         uint32  user_rid, group_rid;
293
294         const char *username;
295         const char *domain;
296         const char *nt_username;
297         const char *dir_drive;
298         const char *unknown_str;
299         const char *munged_dial;
300         const char *fullname;
301         const char *homedir;
302         const char *logon_script;
303         const char *profile_path;
304         const char *acct_desc;
305         const char *workstations;
306         uint32  username_len, domain_len, nt_username_len,
307                 dir_drive_len, unknown_str_len, munged_dial_len,
308                 fullname_len, homedir_len, logon_script_len,
309                 profile_path_len, acct_desc_len, workstations_len;
310
311         const uint8 *lm_pw;
312         const uint8 *nt_pw;
313         uint32  lm_pw_len = 16;
314         uint32  nt_pw_len = 16;
315
316         /* do we have a valid SAM_ACCOUNT pointer? */
317         if (sampass == NULL) {
318                 DEBUG(0, ("init_buffer_from_sam: SAM_ACCOUNT is NULL!\n"));
319                 return -1;
320         }
321         
322         *buf = NULL;
323         buflen = 0;
324
325         logon_time = (uint32)pdb_get_logon_time(sampass);
326         logoff_time = (uint32)pdb_get_logoff_time(sampass);
327         kickoff_time = (uint32)pdb_get_kickoff_time(sampass);
328         pass_can_change_time = (uint32)pdb_get_pass_can_change_time(sampass);
329         pass_must_change_time = (uint32)pdb_get_pass_must_change_time(sampass);
330         pass_last_set_time = (uint32)pdb_get_pass_last_set_time(sampass);
331
332         user_rid = pdb_get_user_rid(sampass);
333         group_rid = pdb_get_group_rid(sampass);
334
335         username = pdb_get_username(sampass);
336         if (username) username_len = strlen(username) +1;
337         else username_len = 0;
338
339         domain = pdb_get_domain(sampass);
340         if (domain) domain_len = strlen(domain) +1;
341         else domain_len = 0;
342
343         nt_username = pdb_get_nt_username(sampass);
344         if (nt_username) nt_username_len = strlen(nt_username) +1;
345         else nt_username_len = 0;
346
347         fullname = pdb_get_fullname(sampass);
348         if (fullname) fullname_len = strlen(fullname) +1;
349         else fullname_len = 0;
350
351         /*
352          * Only updates fields which have been set (not defaults from smb.conf)
353          */
354
355         if (!IS_SAM_DEFAULT(sampass, PDB_DRIVE)) 
356           dir_drive = pdb_get_dir_drive(sampass);
357         else dir_drive = NULL;
358         if (dir_drive) dir_drive_len = strlen(dir_drive) +1;
359         else dir_drive_len = 0;
360
361         if (!IS_SAM_DEFAULT(sampass, PDB_SMBHOME)) homedir = pdb_get_homedir(sampass);
362         else homedir = NULL;
363         if (homedir) homedir_len = strlen(homedir) +1;
364         else homedir_len = 0;
365
366         if (!IS_SAM_DEFAULT(sampass, PDB_LOGONSCRIPT)) logon_script = pdb_get_logon_script(sampass);
367         else logon_script = NULL;
368         if (logon_script) logon_script_len = strlen(logon_script) +1;
369         else logon_script_len = 0;
370
371         if (!IS_SAM_DEFAULT(sampass, PDB_PROFILE)) profile_path = pdb_get_profile_path(sampass);
372         else profile_path = NULL;
373         if (profile_path) profile_path_len = strlen(profile_path) +1;
374         else profile_path_len = 0;
375         
376         lm_pw = pdb_get_lanman_passwd(sampass);
377         if (!lm_pw) lm_pw_len = 0;
378         
379         nt_pw = pdb_get_nt_passwd(sampass);
380         if (!nt_pw) nt_pw_len = 0;
381                 
382         acct_desc = pdb_get_acct_desc(sampass);
383         if (acct_desc) acct_desc_len = strlen(acct_desc) +1;
384         else acct_desc_len = 0;
385
386         workstations = pdb_get_workstations(sampass);
387         if (workstations) workstations_len = strlen(workstations) +1;
388         else workstations_len = 0;
389
390         unknown_str = NULL;
391         unknown_str_len = 0;
392
393         munged_dial = pdb_get_munged_dial(sampass);
394         if (munged_dial) munged_dial_len = strlen(munged_dial) +1;
395         else munged_dial_len = 0;       
396                 
397         /* one time to get the size needed */
398         len = tdb_pack(NULL, 0,  TDB_FORMAT_STRING,
399                 logon_time,
400                 logoff_time,
401                 kickoff_time,
402                 pass_last_set_time,
403                 pass_can_change_time,
404                 pass_must_change_time,
405                 username_len, username,
406                 domain_len, domain,
407                 nt_username_len, nt_username,
408                 fullname_len, fullname,
409                 homedir_len, homedir,
410                 dir_drive_len, dir_drive,
411                 logon_script_len, logon_script,
412                 profile_path_len, profile_path,
413                 acct_desc_len, acct_desc,
414                 workstations_len, workstations,
415                 unknown_str_len, unknown_str,
416                 munged_dial_len, munged_dial,
417                 user_rid,
418                 group_rid,
419                 lm_pw_len, lm_pw,
420                 nt_pw_len, nt_pw,
421                 pdb_get_acct_ctrl(sampass),
422                 pdb_get_unknown_3(sampass),
423                 pdb_get_logon_divs(sampass),
424                 pdb_get_hours_len(sampass),
425                 MAX_HOURS_LEN, pdb_get_hours(sampass),
426                 pdb_get_unknown_5(sampass),
427                 pdb_get_unknown_6(sampass));
428
429
430         /* malloc the space needed */
431         if ( (*buf=(uint8*)malloc(len)) == NULL) {
432                 DEBUG(0,("init_buffer_from_sam: Unable to malloc() memory for buffer!\n"));
433                 return (-1);
434         }
435         
436         /* now for the real call to tdb_pack() */
437         buflen = tdb_pack(*buf, len,  TDB_FORMAT_STRING,
438                 logon_time,
439                 logoff_time,
440                 kickoff_time,
441                 pass_last_set_time,
442                 pass_can_change_time,
443                 pass_must_change_time,
444                 username_len, username,
445                 domain_len, domain,
446                 nt_username_len, nt_username,
447                 fullname_len, fullname,
448                 homedir_len, homedir,
449                 dir_drive_len, dir_drive,
450                 logon_script_len, logon_script,
451                 profile_path_len, profile_path,
452                 acct_desc_len, acct_desc,
453                 workstations_len, workstations,
454                 unknown_str_len, unknown_str,
455                 munged_dial_len, munged_dial,
456                 user_rid,
457                 group_rid,
458                 lm_pw_len, lm_pw,
459                 nt_pw_len, nt_pw,
460                 pdb_get_acct_ctrl(sampass),
461                 pdb_get_unknown_3(sampass),
462                 pdb_get_logon_divs(sampass),
463                 pdb_get_hours_len(sampass),
464                 MAX_HOURS_LEN, pdb_get_hours(sampass),
465                 pdb_get_unknown_5(sampass),
466                 pdb_get_unknown_6(sampass));
467         
468         
469         /* check to make sure we got it correct */
470         if (buflen != len) {
471                 DEBUG(0, ("init_buffer_from_sam: somthing odd is going on here: bufflen (%d) != len (%d) in tdb_pack operations!\n", 
472                           buflen, len));  
473                 /* error */
474                 SAFE_FREE (*buf);
475                 return (-1);
476         }
477
478         return (buflen);
479 }
480
481 /***************************************************************
482  Open the TDB passwd database for SAM account enumeration.
483 ****************************************************************/
484
485 static NTSTATUS tdbsam_setsampwent(struct pdb_methods *my_methods, BOOL update)
486 {
487         struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data;
488         
489         /* Open tdb passwd */
490         if (!(tdb_state->passwd_tdb = tdb_open_log(tdb_state->tdbsam_location, 0, TDB_DEFAULT, update?(O_RDWR|O_CREAT):O_RDONLY, 0600)))
491         {
492                 DEBUG(0, ("Unable to open/create TDB passwd\n"));
493                 return NT_STATUS_UNSUCCESSFUL;
494         }
495         
496         tdb_state->key = tdb_firstkey(tdb_state->passwd_tdb);
497
498         return NT_STATUS_OK;
499 }
500
501 static void close_tdb(struct tdbsam_privates *tdb_state) 
502 {
503         if (tdb_state->passwd_tdb) {
504                 tdb_close(tdb_state->passwd_tdb);
505                 tdb_state->passwd_tdb = NULL;
506         }
507 }
508
509 /***************************************************************
510  End enumeration of the TDB passwd list.
511 ****************************************************************/
512
513 static void tdbsam_endsampwent(struct pdb_methods *my_methods)
514 {
515         struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data;
516         close_tdb(tdb_state);
517         
518         DEBUG(7, ("endtdbpwent: closed sam database.\n"));
519 }
520
521 /*****************************************************************
522  Get one SAM_ACCOUNT from the TDB (next in line)
523 *****************************************************************/
524
525 static NTSTATUS tdbsam_getsampwent(struct pdb_methods *my_methods, SAM_ACCOUNT *user)
526 {
527         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
528         struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data;
529         TDB_DATA        data;
530         const char *prefix = USERPREFIX;
531         int  prefixlen = strlen (prefix);
532
533
534         if (user==NULL) {
535                 DEBUG(0,("pdb_get_sampwent: SAM_ACCOUNT is NULL.\n"));
536                 return nt_status;
537         }
538
539         /* skip all non-USER entries (eg. RIDs) */
540         while ((tdb_state->key.dsize != 0) && (strncmp(tdb_state->key.dptr, prefix, prefixlen)))
541                 /* increment to next in line */
542                 tdb_state->key = tdb_nextkey(tdb_state->passwd_tdb, tdb_state->key);
543
544         /* do we have an valid iteration pointer? */
545         if(tdb_state->passwd_tdb == NULL) {
546                 DEBUG(0,("pdb_get_sampwent: Bad TDB Context pointer.\n"));
547                 return nt_status;
548         }
549
550         data = tdb_fetch(tdb_state->passwd_tdb, tdb_state->key);
551         if (!data.dptr) {
552                 DEBUG(5,("pdb_getsampwent: database entry not found.\n"));
553                 return nt_status;
554         }
555   
556         /* unpack the buffer */
557         if (!init_sam_from_buffer(tdb_state, user, data.dptr, data.dsize)) {
558                 DEBUG(0,("pdb_getsampwent: Bad SAM_ACCOUNT entry returned from TDB!\n"));
559                 SAFE_FREE(data.dptr);
560                 return nt_status;
561         }
562         SAFE_FREE(data.dptr);
563         
564         /* increment to next in line */
565         tdb_state->key = tdb_nextkey(tdb_state->passwd_tdb, tdb_state->key);
566
567         return NT_STATUS_OK;
568 }
569
570 /******************************************************************
571  Lookup a name in the SAM TDB
572 ******************************************************************/
573
574 static NTSTATUS tdbsam_getsampwnam (struct pdb_methods *my_methods, SAM_ACCOUNT *user, const char *sname)
575 {
576         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
577         struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data;
578         TDB_CONTEXT     *pwd_tdb;
579         TDB_DATA        data, key;
580         fstring         keystr;
581         fstring         name;
582
583         if (user==NULL) {
584                 DEBUG(0,("pdb_getsampwnam: SAM_ACCOUNT is NULL.\n"));
585                 return nt_status;
586         }
587
588         
589         /* Data is stored in all lower-case */
590         fstrcpy(name, sname);
591         strlower(name);
592
593         /* set search key */
594         slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name);
595         key.dptr = keystr;
596         key.dsize = strlen(keystr) + 1;
597
598         /* open the accounts TDB */
599         if (!(pwd_tdb = tdb_open_log(tdb_state->tdbsam_location, 0, TDB_DEFAULT, O_RDONLY, 0600))) {
600                 DEBUG(0, ("pdb_getsampwnam: Unable to open TDB passwd (%s)!\n", tdb_state->tdbsam_location));
601                 return nt_status;
602         }
603
604         /* get the record */
605         data = tdb_fetch(pwd_tdb, key);
606         if (!data.dptr) {
607                 DEBUG(5,("pdb_getsampwnam (TDB): error fetching database.\n"));
608                 DEBUGADD(5, (" Error: %s\n", tdb_errorstr(pwd_tdb)));
609                 DEBUGADD(5, (" Key: %s\n", keystr));
610                 tdb_close(pwd_tdb);
611                 return nt_status;
612         }
613   
614         /* unpack the buffer */
615         if (!init_sam_from_buffer(tdb_state, user, data.dptr, data.dsize)) {
616                 DEBUG(0,("pdb_getsampwent: Bad SAM_ACCOUNT entry returned from TDB!\n"));
617                 SAFE_FREE(data.dptr);
618                 tdb_close(pwd_tdb);
619                 return nt_status;
620         }
621         SAFE_FREE(data.dptr);
622
623         /* no further use for database, close it now */
624         tdb_close(pwd_tdb);
625         
626         return NT_STATUS_OK;
627 }
628
629 /***************************************************************************
630  Search by rid
631  **************************************************************************/
632
633 static NTSTATUS tdbsam_getsampwrid (struct pdb_methods *my_methods, SAM_ACCOUNT *user, uint32 rid)
634 {
635         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
636         struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data;
637         TDB_CONTEXT             *pwd_tdb;
638         TDB_DATA                data, key;
639         fstring                 keystr;
640         fstring                 name;
641         
642         if (user==NULL) {
643                 DEBUG(0,("pdb_getsampwrid: SAM_ACCOUNT is NULL.\n"));
644                 return nt_status;
645         }
646
647         /* set search key */
648         slprintf(keystr, sizeof(keystr)-1, "%s%.8x", RIDPREFIX, rid);
649         key.dptr = keystr;
650         key.dsize = strlen (keystr) + 1;
651
652         /* open the accounts TDB */
653         if (!(pwd_tdb = tdb_open_log(tdb_state->tdbsam_location, 0, TDB_DEFAULT, O_RDONLY, 0600))) {
654                 DEBUG(0, ("pdb_getsampwrid: Unable to open TDB rid database!\n"));
655                 return nt_status;
656         }
657
658         /* get the record */
659         data = tdb_fetch (pwd_tdb, key);
660         if (!data.dptr) {
661                 DEBUG(5,("pdb_getsampwrid (TDB): error looking up RID %d by key %s.\n", rid, keystr));
662                 DEBUGADD(5, (" Error: %s\n", tdb_errorstr(pwd_tdb)));
663                 tdb_close (pwd_tdb);
664                 return nt_status;
665         }
666
667         fstrcpy (name, data.dptr);
668         SAFE_FREE(data.dptr);
669         
670         tdb_close (pwd_tdb);
671         
672         return tdbsam_getsampwnam (my_methods, user, name);
673 }
674
675 static NTSTATUS tdbsam_getsampwsid(struct pdb_methods *my_methods, SAM_ACCOUNT * user, const DOM_SID *sid)
676 {
677         uint32 rid;
678         if (!sid_peek_check_rid(get_global_sam_sid(), sid, &rid))
679                 return NT_STATUS_UNSUCCESSFUL;
680         return tdbsam_getsampwrid(my_methods, user, rid);
681 }
682
683 /***************************************************************************
684  Delete a SAM_ACCOUNT
685 ****************************************************************************/
686
687 static NTSTATUS tdbsam_delete_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT *sam_pass)
688 {
689         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
690         struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data;
691         TDB_CONTEXT     *pwd_tdb;
692         TDB_DATA        key;
693         fstring         keystr;
694         uint32          rid;
695         fstring         name;
696         
697         fstrcpy(name, pdb_get_username(sam_pass));
698         strlower(name);
699         
700         /* open the TDB */
701         if (!(pwd_tdb = tdb_open_log(tdb_state->tdbsam_location, 0, TDB_DEFAULT, O_RDWR, 0600))) {
702                 DEBUG(0, ("Unable to open TDB passwd!"));
703                 return nt_status;
704         }
705   
706         /* set the search key */
707         slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name);
708         key.dptr = keystr;
709         key.dsize = strlen (keystr) + 1;
710         
711         rid = pdb_get_user_rid(sam_pass);
712
713         /* it's outaa here!  8^) */
714         if (tdb_delete(pwd_tdb, key) != TDB_SUCCESS) {
715                 DEBUG(5, ("Error deleting entry from tdb passwd database!\n"));
716                 DEBUGADD(5, (" Error: %s\n", tdb_errorstr(pwd_tdb)));
717                 tdb_close(pwd_tdb); 
718                 return nt_status;
719         }       
720
721         /* delete also the RID key */
722
723         /* set the search key */
724         slprintf(keystr, sizeof(keystr)-1, "%s%.8x", RIDPREFIX, rid);
725         key.dptr = keystr;
726         key.dsize = strlen (keystr) + 1;
727
728         /* it's outaa here!  8^) */
729         if (tdb_delete(pwd_tdb, key) != TDB_SUCCESS) {
730                 DEBUG(5, ("Error deleting entry from tdb rid database!\n"));
731                 DEBUGADD(5, (" Error: %s\n", tdb_errorstr(pwd_tdb)));
732                 tdb_close(pwd_tdb); 
733                 return nt_status;
734         }
735         
736         tdb_close(pwd_tdb);
737         
738         return NT_STATUS_OK;
739 }
740
741 /***************************************************************************
742  Update the TDB SAM
743 ****************************************************************************/
744
745 static BOOL tdb_update_sam(struct pdb_methods *my_methods, SAM_ACCOUNT* newpwd, int flag)
746 {
747         struct tdbsam_privates *tdb_state = (struct tdbsam_privates *)my_methods->private_data;
748         TDB_CONTEXT     *pwd_tdb = NULL;
749         TDB_DATA        key, data;
750         uint8           *buf = NULL;
751         fstring         keystr;
752         fstring         name;
753         BOOL            ret = True;
754         uint32          user_rid;
755         BOOL            tdb_ret;
756
757         /* invalidate the existing TDB iterator if it is open */
758         if (tdb_state->passwd_tdb) {
759                 tdb_close(tdb_state->passwd_tdb);
760                 tdb_state->passwd_tdb = NULL;
761         }
762
763         /* open the account TDB passwd*/
764         pwd_tdb = tdb_open_log(tdb_state->tdbsam_location, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0600);
765         if (!pwd_tdb)
766         {
767                 DEBUG(0, ("tdb_update_sam: Unable to open TDB passwd (%s)!\n", tdb_state->tdbsam_location));
768                 return False;
769         }
770
771         /* if flag == TDB_INSERT then make up a new RID else throw an error. */
772         if (!(user_rid = pdb_get_user_rid(newpwd))) {
773                 if (flag & TDB_INSERT) {
774                         if (IS_SAM_UNIX_USER(newpwd)) {
775                                 if (tdb_state->algorithmic_rids) {
776                                         user_rid = fallback_pdb_uid_to_user_rid(pdb_get_uid(newpwd));
777                                 } else {
778                                         user_rid = BASE_RID;
779                                         tdb_ret = tdb_change_uint32_atomic(pwd_tdb, "RID_COUNTER", &user_rid, RID_MULTIPLIER);
780                                         if (!tdb_ret) {
781                                                 ret = False;
782                                                 goto done;
783                                         }
784                                 }
785                                 pdb_set_user_sid_from_rid(newpwd, user_rid, PDB_CHANGED);
786                         } else {
787                                 user_rid = tdb_state->low_nua_rid;
788                                 tdb_ret = tdb_change_uint32_atomic(pwd_tdb, "NUA_RID_COUNTER", &user_rid, RID_MULTIPLIER);
789                                 if (!tdb_ret) {
790                                         ret = False;
791                                         goto done;
792                                 }
793                                 if (user_rid > tdb_state->high_nua_rid) {
794                                         DEBUG(0, ("tdbsam: no NUA rids available, cannot add user %s!\n", pdb_get_username(newpwd)));
795                                         ret = False;
796                                         goto done;
797                                 }
798                                 pdb_set_user_sid_from_rid(newpwd, user_rid, PDB_CHANGED);
799                         }
800                 } else {
801                         DEBUG (0,("tdb_update_sam: Failing to store a SAM_ACCOUNT for [%s] without a RID\n",pdb_get_username(newpwd)));
802                         ret = False;
803                         goto done;
804                 }
805         }
806
807         if (!pdb_get_group_rid(newpwd)) {
808                 if (flag & TDB_INSERT) {
809                         if (!tdb_state->permit_non_unix_accounts) {
810                                 DEBUG (0,("tdb_update_sam: Failing to store a SAM_ACCOUNT for [%s] without a primary group RID\n",pdb_get_username(newpwd)));
811                                 ret = False;
812                                 goto done;
813                         } else {
814                                 /* This seems like a good default choice for non-unix users */
815                                 pdb_set_group_sid_from_rid(newpwd, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
816                         }
817                 } else {
818                         DEBUG (0,("tdb_update_sam: Failing to store a SAM_ACCOUNT for [%s] without a primary group RID\n",pdb_get_username(newpwd)));
819                         ret = False;
820                         goto done;
821                 }
822         }
823
824         /* copy the SAM_ACCOUNT struct into a BYTE buffer for storage */
825         if ((data.dsize=init_buffer_from_sam (tdb_state, &buf, newpwd)) == -1) {
826                 DEBUG(0,("tdb_update_sam: ERROR - Unable to copy SAM_ACCOUNT info BYTE buffer!\n"));
827                 ret = False;
828                 goto done;
829         }
830         data.dptr = buf;
831
832         fstrcpy(name, pdb_get_username(newpwd));
833         strlower(name);
834         
835         DEBUG(5, ("Storing %saccount %s with RID %d\n", flag == TDB_INSERT ? "(new) " : "", name, user_rid));
836
837         /* setup the USER index key */
838         slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name);
839         key.dptr = keystr;
840         key.dsize = strlen (keystr) + 1;
841
842         /* add the account */
843         if (tdb_store(pwd_tdb, key, data, flag) != TDB_SUCCESS) {
844                 DEBUG(0, ("Unable to modify passwd TDB!"));
845                 DEBUGADD(0, (" Error: %s", tdb_errorstr(pwd_tdb)));
846                 DEBUGADD(0, (" occured while storing the main record (%s)\n", keystr));
847                 ret = False;
848                 goto done;
849         }
850         
851         /* setup RID data */
852         data.dsize = sizeof(fstring);
853         data.dptr = name;
854
855         /* setup the RID index key */
856         slprintf(keystr, sizeof(keystr)-1, "%s%.8x", RIDPREFIX, user_rid);
857         key.dptr = keystr;
858         key.dsize = strlen (keystr) + 1;
859         
860         /* add the reference */
861         if (tdb_store(pwd_tdb, key, data, flag) != TDB_SUCCESS) {
862                 DEBUG(0, ("Unable to modify TDB passwd !"));
863                 DEBUGADD(0, (" Error: %s\n", tdb_errorstr(pwd_tdb)));
864                 DEBUGADD(0, (" occured while storing the RID index (%s)\n", keystr));
865                 ret = False;
866                 goto done;
867         }
868
869 done:   
870         /* cleanup */
871         tdb_close (pwd_tdb);
872         SAFE_FREE(buf);
873         
874         return (ret);   
875 }
876
877 /***************************************************************************
878  Modifies an existing SAM_ACCOUNT
879 ****************************************************************************/
880
881 static NTSTATUS tdbsam_update_sam_account (struct pdb_methods *my_methods, SAM_ACCOUNT *newpwd)
882 {
883         if (tdb_update_sam(my_methods, newpwd, TDB_MODIFY))
884                 return NT_STATUS_OK;
885         else
886                 return NT_STATUS_UNSUCCESSFUL;
887 }
888
889 /***************************************************************************
890  Adds an existing SAM_ACCOUNT
891 ****************************************************************************/
892
893 static NTSTATUS tdbsam_add_sam_account (struct pdb_methods *my_methods, SAM_ACCOUNT *newpwd)
894 {
895         if (tdb_update_sam(my_methods, newpwd, TDB_INSERT))
896                 return NT_STATUS_OK;
897         else
898                 return NT_STATUS_UNSUCCESSFUL;
899 }
900
901 static void free_private_data(void **vp) 
902 {
903         struct tdbsam_privates **tdb_state = (struct tdbsam_privates **)vp;
904         close_tdb(*tdb_state);
905         *tdb_state = NULL;
906
907         /* No need to free any further, as it is talloc()ed */
908 }
909
910
911 NTSTATUS pdb_init_tdbsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
912 {
913         NTSTATUS nt_status;
914         struct tdbsam_privates *tdb_state;
915
916 #if 0 /* when made a module use this */
917         tdbsam_debug_level = debug_add_class("tdbsam");
918         if(tdbsam_debug_level == -1) {
919                 tdbsam_debug_level = DBGC_ALL;
920                 DEBUG(0, ("tdbsam: Couldn't register custom debugging class!\n"));
921         }
922 #endif
923
924         if (!NT_STATUS_IS_OK(nt_status = make_pdb_methods(pdb_context->mem_ctx, pdb_method))) {
925                 return nt_status;
926         }
927
928         (*pdb_method)->name = "tdbsam";
929
930         (*pdb_method)->setsampwent = tdbsam_setsampwent;
931         (*pdb_method)->endsampwent = tdbsam_endsampwent;
932         (*pdb_method)->getsampwent = tdbsam_getsampwent;
933         (*pdb_method)->getsampwnam = tdbsam_getsampwnam;
934         (*pdb_method)->getsampwsid = tdbsam_getsampwsid;
935         (*pdb_method)->add_sam_account = tdbsam_add_sam_account;
936         (*pdb_method)->update_sam_account = tdbsam_update_sam_account;
937         (*pdb_method)->delete_sam_account = tdbsam_delete_sam_account;
938
939         tdb_state = talloc_zero(pdb_context->mem_ctx, sizeof(struct tdbsam_privates));
940
941         if (!tdb_state) {
942                 DEBUG(0, ("talloc() failed for tdbsam private_data!\n"));
943                 return NT_STATUS_NO_MEMORY;
944         }
945
946         if (location) {
947                 tdb_state->tdbsam_location = talloc_strdup(pdb_context->mem_ctx, location);
948         } else {
949                 pstring tdbfile;
950                 get_private_directory(tdbfile);
951                 pstrcat(tdbfile, "/");
952                 pstrcat(tdbfile, PASSDB_FILE_NAME);
953                 tdb_state->tdbsam_location = talloc_strdup(pdb_context->mem_ctx, tdbfile);
954         }
955
956         tdb_state->algorithmic_rids = True;
957
958         (*pdb_method)->private_data = tdb_state;
959
960         (*pdb_method)->free_private_data = free_private_data;
961
962         return NT_STATUS_OK;
963 }
964
965 NTSTATUS pdb_init_tdbsam_nua(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
966 {
967         NTSTATUS nt_status;
968         struct tdbsam_privates *tdb_state;
969         uint32 low_nua_uid, high_nua_uid;
970
971         if (!NT_STATUS_IS_OK(nt_status = pdb_init_tdbsam(pdb_context, pdb_method, location))) {
972                 return nt_status;
973         }
974
975         (*pdb_method)->name = "tdbsam_nua";
976
977         tdb_state = (*pdb_method)->private_data;
978
979         tdb_state->permit_non_unix_accounts = True;
980
981         if (!lp_winbind_uid(&low_nua_uid, &high_nua_uid)) {
982                 DEBUG(0, ("cannot use tdbsam_nua without 'winbind uid' range in smb.conf!\n"));
983                 return NT_STATUS_UNSUCCESSFUL;
984         }
985
986         tdb_state->low_nua_rid=fallback_pdb_uid_to_user_rid(low_nua_uid);
987
988         tdb_state->high_nua_rid=fallback_pdb_uid_to_user_rid(high_nua_uid);
989
990         return NT_STATUS_OK;
991 }
992
993 NTSTATUS pdb_tdbsam_init(void)
994 {
995         smb_register_passdb(PASSDB_INTERFACE_VERSION, "tdbsam", pdb_init_tdbsam);
996         smb_register_passdb(PASSDB_INTERFACE_VERSION, "tdbsam_nua", pdb_init_tdbsam_nua);
997         return NT_STATUS_OK;
998 }
999