Missing break in conversion function prevents tdb password database update.
[obnox/samba-ctdb.git] / source / 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-2003
6  * Copyright (C) Gerald Carter     2000-2006
7  * Copyright (C) Jeremy Allison    2001
8  * Copyright (C) Andrew Bartlett   2002
9  * Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2005
10  * 
11  * This program is free software; you can redistribute it and/or modify it under
12  * the terms of the GNU General Public License as published by the Free
13  * Software Foundation; either version 3 of the License, or (at your option)
14  * any later version.
15  * 
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
19  * more details.
20  * 
21  * You should have received a copy of the GNU General Public License along with
22  * this program; if not, see <http://www.gnu.org/licenses/>.
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 TDBSAM_VERSION  4       /* Most recent TDBSAM version */
41 #define TDBSAM_VERSION_STRING   "INFO/version"
42 #define PASSDB_FILE_NAME        "passdb.tdb"
43 #define USERPREFIX              "USER_"
44 #define USERPREFIX_LEN          5
45 #define RIDPREFIX               "RID_"
46 #define PRIVPREFIX              "PRIV_"
47 #define NEXT_RID_STRING         "NEXT_RID"
48
49 /* GLOBAL TDB SAM CONTEXT */
50
51 static struct db_context *db_sam;
52 static char *tdbsam_filename;
53
54 struct tdbsam_convert_state {
55         int32_t from;
56         bool success;
57 };
58
59 static int tdbsam_convert_one(struct db_record *rec, void *priv)
60 {
61         struct tdbsam_convert_state *state =
62                 (struct tdbsam_convert_state *)priv;
63         struct samu *user;
64         TDB_DATA data;
65         NTSTATUS status;
66         bool ret;
67
68         if (rec->key.dsize < USERPREFIX_LEN) {
69                 return 0;
70         }
71         if (strncmp((char *)rec->key.dptr, USERPREFIX, USERPREFIX_LEN) != 0) {
72                 return 0;
73         }
74
75         user = samu_new(talloc_tos());
76         if (user == NULL) {
77                 DEBUG(0,("tdbsam_convert: samu_new() failed!\n"));
78                 state->success = false;
79                 return -1;
80         }
81
82         DEBUG(10,("tdbsam_convert: Try unpacking a record with (key:%s) "
83                   "(version:%d)\n", rec->key.dptr, state->from));
84
85         switch (state->from) {
86         case 0:
87                 ret = init_samu_from_buffer(user, SAMU_BUFFER_V0,
88                                             (uint8 *)rec->value.dptr,
89                                             rec->value.dsize);
90                 break;
91         case 1:
92                 ret = init_samu_from_buffer(user, SAMU_BUFFER_V1,
93                                             (uint8 *)rec->value.dptr,
94                                             rec->value.dsize);
95                 break;
96         case 2:
97                 ret = init_samu_from_buffer(user, SAMU_BUFFER_V2,
98                                             (uint8 *)rec->value.dptr,
99                                             rec->value.dsize);
100                 break;
101         case 3:
102                 ret = init_samu_from_buffer(user, SAMU_BUFFER_V3,
103                                             (uint8 *)rec->value.dptr,
104                                             rec->value.dsize);
105                 break;
106         case 4:
107                 ret = init_samu_from_buffer(user, SAMU_BUFFER_V4,
108                                             (uint8 *)rec->value.dptr,
109                                             rec->value.dsize);
110                 break;
111         default:
112                 /* unknown tdbsam version */
113                 ret = False;
114         }
115         if (!ret) {
116                 DEBUG(0,("tdbsam_convert: Bad struct samu entry returned "
117                          "from TDB (key:%s) (version:%d)\n", rec->key.dptr,
118                          state->from));
119                 TALLOC_FREE(user);
120                 state->success = false;
121                 return -1;
122         }
123
124         data.dsize = init_buffer_from_samu(&data.dptr, user, false);
125         TALLOC_FREE(user);
126
127         if (data.dsize == -1) {
128                 DEBUG(0,("tdbsam_convert: cannot pack the struct samu into "
129                          "the new format\n"));
130                 state->success = false;
131                 return -1;
132         }
133
134         status = rec->store(rec, data, TDB_MODIFY);
135         if (!NT_STATUS_IS_OK(status)) {
136                 DEBUG(0, ("Could not store the new record: %s\n",
137                           nt_errstr(status)));
138                 state->success = false;
139                 return -1;
140         }
141
142         return 0;
143 }
144
145 static bool tdbsam_upgrade_next_rid(struct db_context *db)
146 {
147         TDB_CONTEXT *tdb;
148         uint32 rid;
149         bool ok = false;
150
151         ok = dbwrap_fetch_uint32(db, NEXT_RID_STRING, &rid);
152         if (ok) {
153                 return true;
154         }
155
156         tdb = tdb_open_log(state_path("winbindd_idmap.tdb"), 0,
157                            TDB_DEFAULT, O_RDONLY, 0644);
158
159         if (tdb) {
160                 ok = tdb_fetch_uint32(tdb, "RID_COUNTER", &rid);
161                 if (!ok) {
162                         rid = BASE_RID;
163                 }
164                 tdb_close(tdb);
165         } else {
166                 rid = BASE_RID;
167         }
168
169         if (dbwrap_store_uint32(db, NEXT_RID_STRING, rid) != 0) {
170                 return false;
171         }
172
173         return true;
174 }
175
176 static bool tdbsam_convert(struct db_context *db, int32 from)
177 {
178         struct tdbsam_convert_state state;
179         int ret;
180
181         state.from = from;
182         state.success = true;
183
184         if (db->transaction_start(db) != 0) {
185                 DEBUG(0, ("Could not start transaction\n"));
186                 return false;
187         }
188
189         if (!tdbsam_upgrade_next_rid(db)) {
190                 DEBUG(0, ("tdbsam_upgrade_next_rid failed\n"));
191                 goto cancel;
192         }
193
194         ret = db->traverse(db, tdbsam_convert_one, &state);
195         if (ret < 0) {
196                 DEBUG(0, ("traverse failed\n"));
197                 goto cancel;
198         }
199
200         if (!state.success) {
201                 DEBUG(0, ("Converting records failed\n"));
202                 goto cancel;
203         }
204
205         if (dbwrap_store_int32(db, TDBSAM_VERSION_STRING,
206                                TDBSAM_VERSION) != 0) {
207                 DEBUG(0, ("Could not store tdbsam version\n"));
208                 goto cancel;
209         }
210
211         if (db->transaction_commit(db) != 0) {
212                 DEBUG(0, ("Could not commit transaction\n"));
213                 return false;
214         }
215
216         return true;
217
218  cancel:
219         if (db->transaction_cancel(db) != 0) {
220                 smb_panic("transaction_cancel failed");
221         }
222
223         return false;
224 }
225
226 /*********************************************************************
227  Open the tdbsam file based on the absolute path specified.
228  Uses a reference count to allow multiple open calls.
229 *********************************************************************/
230
231 static bool tdbsam_open( const char *name )
232 {
233         int32   version;
234
235         /* check if we are already open */
236
237         if ( db_sam ) {
238                 return true;
239         }
240
241         /* Try to open tdb passwd.  Create a new one if necessary */
242
243         db_sam = db_open(NULL, name, 0, TDB_DEFAULT, O_CREAT|O_RDWR, 0600);
244         if (db_sam == NULL) {
245                 DEBUG(0, ("tdbsam_open: Failed to open/create TDB passwd "
246                           "[%s]\n", name));
247                 return false;
248         }
249
250         /* Check the version */
251         version = dbwrap_fetch_int32(db_sam, TDBSAM_VERSION_STRING);
252         if (version == -1) {
253                 version = 0;    /* Version not found, assume version 0 */
254         }
255
256         /* Compare the version */
257         if (version > TDBSAM_VERSION) {
258                 /* Version more recent than the latest known */
259                 DEBUG(0, ("tdbsam_open: unknown version => %d\n", version));
260                 TALLOC_FREE(db_sam);
261                 return false;
262         }
263
264         if ( version < TDBSAM_VERSION ) {
265                 DEBUG(1, ("tdbsam_open: Converting version %d database to "
266                           "version %d.\n", version, TDBSAM_VERSION));
267
268                 if ( !tdbsam_convert(db_sam, version) ) {
269                         DEBUG(0, ("tdbsam_open: Error when trying to convert "
270                                   "tdbsam [%s]\n",name));
271                         TALLOC_FREE(db_sam);
272                         return false;
273                 }
274
275                 DEBUG(3, ("TDBSAM converted successfully.\n"));
276         }
277
278         DEBUG(4,("tdbsam_open: successfully opened %s\n", name ));
279
280         return true;
281 }
282
283 /******************************************************************
284  Lookup a name in the SAM TDB
285 ******************************************************************/
286
287 static NTSTATUS tdbsam_getsampwnam (struct pdb_methods *my_methods,
288                                     struct samu *user, const char *sname)
289 {
290         TDB_DATA        data;
291         fstring         keystr;
292         fstring         name;
293
294         if ( !user ) {
295                 DEBUG(0,("pdb_getsampwnam: struct samu is NULL.\n"));
296                 return NT_STATUS_NO_MEMORY;
297         }
298
299         /* Data is stored in all lower-case */
300         fstrcpy(name, sname);
301         strlower_m(name);
302
303         /* set search key */
304         slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name);
305
306         /* open the database */
307
308         if ( !tdbsam_open( tdbsam_filename ) ) {
309                 DEBUG(0,("tdbsam_getsampwnam: failed to open %s!\n", tdbsam_filename));
310                 return NT_STATUS_ACCESS_DENIED;
311         }
312
313         /* get the record */
314
315         data = dbwrap_fetch_bystring(db_sam, talloc_tos(), keystr);
316         if (!data.dptr) {
317                 DEBUG(5,("pdb_getsampwnam (TDB): error fetching database.\n"));
318                 DEBUGADD(5, (" Key: %s\n", keystr));
319                 return NT_STATUS_NO_SUCH_USER;
320         }
321
322         /* unpack the buffer */
323
324         if (!init_samu_from_buffer(user, SAMU_BUFFER_LATEST, data.dptr, data.dsize)) {
325                 DEBUG(0,("pdb_getsampwent: Bad struct samu entry returned from TDB!\n"));
326                 SAFE_FREE(data.dptr);
327                 return NT_STATUS_NO_MEMORY;
328         }
329
330         /* success */
331
332         TALLOC_FREE(data.dptr);
333
334         return NT_STATUS_OK;
335 }
336
337 /***************************************************************************
338  Search by rid
339  **************************************************************************/
340
341 static NTSTATUS tdbsam_getsampwrid (struct pdb_methods *my_methods,
342                                     struct samu *user, uint32 rid)
343 {
344         NTSTATUS                nt_status = NT_STATUS_UNSUCCESSFUL;
345         TDB_DATA                data;
346         fstring                 keystr;
347         fstring                 name;
348
349         if ( !user ) {
350                 DEBUG(0,("pdb_getsampwrid: struct samu is NULL.\n"));
351                 return nt_status;
352         }
353
354         /* set search key */
355
356         slprintf(keystr, sizeof(keystr)-1, "%s%.8x", RIDPREFIX, rid);
357
358         /* open the database */
359
360         if ( !tdbsam_open( tdbsam_filename ) ) {
361                 DEBUG(0,("tdbsam_getsampwrid: failed to open %s!\n", tdbsam_filename));
362                 return NT_STATUS_ACCESS_DENIED;
363         }
364
365         /* get the record */
366
367         data = dbwrap_fetch_bystring(db_sam, talloc_tos(), keystr);
368         if (!data.dptr) {
369                 DEBUG(5,("pdb_getsampwrid (TDB): error looking up RID %d by key %s.\n", rid, keystr));
370                 return NT_STATUS_UNSUCCESSFUL;
371         }
372
373         fstrcpy(name, (const char *)data.dptr);
374         TALLOC_FREE(data.dptr);
375
376         return tdbsam_getsampwnam (my_methods, user, name);
377 }
378
379 static NTSTATUS tdbsam_getsampwsid(struct pdb_methods *my_methods,
380                                    struct samu * user, const DOM_SID *sid)
381 {
382         uint32 rid;
383
384         if ( !sid_peek_check_rid(get_global_sam_sid(), sid, &rid) )
385                 return NT_STATUS_UNSUCCESSFUL;
386
387         return tdbsam_getsampwrid(my_methods, user, rid);
388 }
389
390 static bool tdb_delete_samacct_only( struct samu *sam_pass )
391 {
392         fstring         keystr;
393         fstring         name;
394         NTSTATUS status;
395
396         fstrcpy(name, pdb_get_username(sam_pass));
397         strlower_m(name);
398
399         /* set the search key */
400
401         slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name);
402
403         /* it's outaa here!  8^) */
404         if ( !tdbsam_open( tdbsam_filename ) ) {
405                 DEBUG(0,("tdb_delete_samacct_only: failed to open %s!\n",
406                          tdbsam_filename));
407                 return false;
408         }
409
410         status = dbwrap_delete_bystring(db_sam, keystr);
411         if (!NT_STATUS_IS_OK(status)) {
412                 DEBUG(5, ("Error deleting entry from tdb passwd "
413                           "database: %s!\n", nt_errstr(status)));
414                 return false;
415         }
416
417         return true;
418 }
419
420 /***************************************************************************
421  Delete a struct samu records for the username and RID key
422 ****************************************************************************/
423
424 static NTSTATUS tdbsam_delete_sam_account(struct pdb_methods *my_methods,
425                                           struct samu *sam_pass)
426 {
427         NTSTATUS        nt_status = NT_STATUS_UNSUCCESSFUL;
428         fstring         keystr;
429         uint32          rid;
430         fstring         name;
431
432         /* open the database */
433
434         if ( !tdbsam_open( tdbsam_filename ) ) {
435                 DEBUG(0,("tdbsam_delete_sam_account: failed to open %s!\n",
436                          tdbsam_filename));
437                 return NT_STATUS_ACCESS_DENIED;
438         }
439
440         fstrcpy(name, pdb_get_username(sam_pass));
441         strlower_m(name);
442
443         /* set the search key */
444
445         slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name);
446
447         rid = pdb_get_user_rid(sam_pass);
448
449         /* it's outaa here!  8^) */
450
451         if (db_sam->transaction_start(db_sam) != 0) {
452                 DEBUG(0, ("Could not start transaction\n"));
453                 return NT_STATUS_UNSUCCESSFUL;
454         }
455
456         nt_status = dbwrap_delete_bystring(db_sam, keystr);
457         if (!NT_STATUS_IS_OK(nt_status)) {
458                 DEBUG(5, ("Error deleting entry from tdb passwd "
459                           "database: %s!\n", nt_errstr(nt_status)));
460                 goto cancel;
461         }
462
463         /* set the search key */
464
465         slprintf(keystr, sizeof(keystr)-1, "%s%.8x", RIDPREFIX, rid);
466
467         /* it's outaa here!  8^) */
468
469         nt_status = dbwrap_delete_bystring(db_sam, keystr);
470         if (!NT_STATUS_IS_OK(nt_status)) {
471                 DEBUG(5, ("Error deleting entry from tdb rid "
472                           "database: %s!\n", nt_errstr(nt_status)));
473                 goto cancel;
474         }
475
476         if (db_sam->transaction_commit(db_sam) != 0) {
477                 DEBUG(0, ("Could not commit transaction\n"));
478                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
479         }
480
481         return NT_STATUS_OK;
482
483  cancel:
484         if (db_sam->transaction_cancel(db_sam) != 0) {
485                 smb_panic("transaction_cancel failed");
486         }
487
488         return nt_status;
489 }
490
491
492 /***************************************************************************
493  Update the TDB SAM account record only
494  Assumes that the tdbsam is already open 
495 ****************************************************************************/
496 static bool tdb_update_samacct_only( struct samu* newpwd, int flag )
497 {
498         TDB_DATA        data;
499         uint8           *buf = NULL;
500         fstring         keystr;
501         fstring         name;
502         bool            ret = false;
503         NTSTATUS status;
504
505         /* copy the struct samu struct into a BYTE buffer for storage */
506
507         if ( (data.dsize=init_buffer_from_samu(&buf, newpwd, False)) == -1 ) {
508                 DEBUG(0,("tdb_update_sam: ERROR - Unable to copy struct samu info BYTE buffer!\n"));
509                 goto done;
510         }
511         data.dptr = buf;
512
513         fstrcpy(name, pdb_get_username(newpwd));
514         strlower_m(name);
515
516         DEBUG(5, ("Storing %saccount %s with RID %d\n",
517                   flag == TDB_INSERT ? "(new) " : "", name,
518                   pdb_get_user_rid(newpwd)));
519
520         /* setup the USER index key */
521         slprintf(keystr, sizeof(keystr)-1, "%s%s", USERPREFIX, name);
522
523         /* add the account */
524
525         status = dbwrap_store_bystring(db_sam, keystr, data, flag);
526         if (!NT_STATUS_IS_OK(status)) {
527                 DEBUG(0, ("Unable to modify passwd TDB: %s!",
528                           nt_errstr(status)));
529                 goto done;
530         }
531
532         ret = true;
533
534 done:
535         /* cleanup */
536         SAFE_FREE(buf);
537         return ret;
538 }
539
540 /***************************************************************************
541  Update the TDB SAM RID record only
542  Assumes that the tdbsam is already open
543 ****************************************************************************/
544 static bool tdb_update_ridrec_only( struct samu* newpwd, int flag )
545 {
546         TDB_DATA        data;
547         fstring         keystr;
548         fstring         name;
549         NTSTATUS status;
550
551         fstrcpy(name, pdb_get_username(newpwd));
552         strlower_m(name);
553
554         /* setup RID data */
555         data = string_term_tdb_data(name);
556
557         /* setup the RID index key */
558         slprintf(keystr, sizeof(keystr)-1, "%s%.8x", RIDPREFIX,
559                  pdb_get_user_rid(newpwd));
560
561         /* add the reference */
562         status = dbwrap_store_bystring(db_sam, keystr, data, flag);
563         if (!NT_STATUS_IS_OK(status)) {
564                 DEBUG(0, ("Unable to modify TDB passwd: %s!\n",
565                           nt_errstr(status)));
566                 return false;
567         }
568
569         return true;
570
571 }
572
573 /***************************************************************************
574  Update the TDB SAM
575 ****************************************************************************/
576
577 static bool tdb_update_sam(struct pdb_methods *my_methods, struct samu* newpwd,
578                            int flag)
579 {
580         if (!pdb_get_user_rid(newpwd)) {
581                 DEBUG(0,("tdb_update_sam: struct samu (%s) with no RID!\n",
582                          pdb_get_username(newpwd)));
583                 return False;
584         }
585
586         /* open the database */
587
588         if ( !tdbsam_open( tdbsam_filename ) ) {
589                 DEBUG(0,("tdbsam_getsampwnam: failed to open %s!\n", tdbsam_filename));
590                 return False;
591         }
592
593         if (db_sam->transaction_start(db_sam) != 0) {
594                 DEBUG(0, ("Could not start transaction\n"));
595                 return false;
596         }
597
598         if (!tdb_update_samacct_only(newpwd, flag)
599             || !tdb_update_ridrec_only(newpwd, flag)) {
600                 goto cancel;
601         }
602
603         if (db_sam->transaction_commit(db_sam) != 0) {
604                 DEBUG(0, ("Could not commit transaction\n"));
605                 return false;
606         }
607
608         return true;
609
610  cancel:
611         if (db_sam->transaction_cancel(db_sam) != 0) {
612                 smb_panic("transaction_cancel failed");
613         }
614         return false;
615 }
616
617 /***************************************************************************
618  Modifies an existing struct samu
619 ****************************************************************************/
620
621 static NTSTATUS tdbsam_update_sam_account (struct pdb_methods *my_methods, struct samu *newpwd)
622 {
623         if ( !tdb_update_sam(my_methods, newpwd, TDB_MODIFY) )
624                 return NT_STATUS_UNSUCCESSFUL;
625         
626         return NT_STATUS_OK;
627 }
628
629 /***************************************************************************
630  Adds an existing struct samu
631 ****************************************************************************/
632
633 static NTSTATUS tdbsam_add_sam_account (struct pdb_methods *my_methods, struct samu *newpwd)
634 {
635         if ( !tdb_update_sam(my_methods, newpwd, TDB_INSERT) )
636                 return NT_STATUS_UNSUCCESSFUL;
637                 
638         return NT_STATUS_OK;
639 }
640
641 /***************************************************************************
642  Renames a struct samu
643  - check for the posix user/rename user script
644  - Add and lock the new user record
645  - rename the posix user
646  - rewrite the rid->username record
647  - delete the old user
648  - unlock the new user record
649 ***************************************************************************/
650 static NTSTATUS tdbsam_rename_sam_account(struct pdb_methods *my_methods,
651                                           struct samu *old_acct,
652                                           const char *newname)
653 {
654         struct samu      *new_acct = NULL;
655         char *rename_script = NULL;
656         int              rename_ret;
657         fstring          oldname_lower;
658         fstring          newname_lower;
659
660         /* can't do anything without an external script */
661
662         if ( !(new_acct = samu_new( talloc_tos() )) ) {
663                 return NT_STATUS_NO_MEMORY;
664         }
665
666         rename_script = talloc_strdup(new_acct, lp_renameuser_script());
667         if (!rename_script) {
668                 TALLOC_FREE(new_acct);
669                 return NT_STATUS_NO_MEMORY;
670         }
671         if (!*rename_script) {
672                 TALLOC_FREE(new_acct);
673                 return NT_STATUS_ACCESS_DENIED;
674         }
675
676         if ( !pdb_copy_sam_account(new_acct, old_acct)
677                 || !pdb_set_username(new_acct, newname, PDB_CHANGED))
678         {
679                 TALLOC_FREE(new_acct);
680                 return NT_STATUS_NO_MEMORY;
681         }
682
683         /* open the database */
684         if ( !tdbsam_open( tdbsam_filename ) ) {
685                 DEBUG(0, ("tdbsam_getsampwnam: failed to open %s!\n",
686                           tdbsam_filename));
687                 TALLOC_FREE(new_acct);
688                 return NT_STATUS_ACCESS_DENIED;
689         }
690
691         if (db_sam->transaction_start(db_sam) != 0) {
692                 DEBUG(0, ("Could not start transaction\n"));
693                 TALLOC_FREE(new_acct);
694                 return NT_STATUS_ACCESS_DENIED;
695
696         }
697
698         /* add the new account and lock it */
699         if ( !tdb_update_samacct_only(new_acct, TDB_INSERT) ) {
700                 goto cancel;
701         }
702
703         /* Rename the posix user.  Follow the semantics of _samr_create_user()
704            so that we lower case the posix name but preserve the case in passdb */
705
706         fstrcpy( oldname_lower, pdb_get_username(old_acct) );
707         strlower_m( oldname_lower );
708
709         fstrcpy( newname_lower, newname );
710         strlower_m( newname_lower );
711
712         rename_script = talloc_string_sub2(new_acct,
713                                 rename_script,
714                                 "%unew",
715                                 newname_lower,
716                                 true,
717                                 false,
718                                 true);
719         if (!rename_script) {
720                 goto cancel;
721         }
722         rename_script = talloc_string_sub2(new_acct,
723                                 rename_script,
724                                 "%uold",
725                                 oldname_lower,
726                                 true,
727                                 false,
728                                 true);
729         if (!rename_script) {
730                 goto cancel;
731         }
732         rename_ret = smbrun(rename_script, NULL);
733
734         DEBUG(rename_ret ? 0 : 3,("Running the command `%s' gave %d\n",
735                                 rename_script, rename_ret));
736
737         if (rename_ret != 0) {
738                 goto cancel;
739         }
740
741         smb_nscd_flush_user_cache();
742
743         /* rewrite the rid->username record */
744
745         if ( !tdb_update_ridrec_only( new_acct, TDB_MODIFY) ) {
746                 goto cancel;
747         }
748
749         tdb_delete_samacct_only( old_acct );
750
751         if (db_sam->transaction_commit(db_sam) != 0) {
752                 /*
753                  * Ok, we're screwed. We've changed the posix account, but
754                  * could not adapt passdb.tdb. Shall we change the posix
755                  * account back?
756                  */
757                 DEBUG(0, ("transaction_commit failed\n"));
758                 TALLOC_FREE(new_acct);
759                 return NT_STATUS_INTERNAL_DB_CORRUPTION;        
760         }
761
762         TALLOC_FREE(new_acct );
763         return NT_STATUS_OK;
764
765  cancel:
766         if (db_sam->transaction_cancel(db_sam) != 0) {
767                 smb_panic("transaction_cancel failed");
768         }
769
770         TALLOC_FREE(new_acct);
771
772         return NT_STATUS_ACCESS_DENIED; 
773 }
774
775 static bool tdbsam_rid_algorithm(struct pdb_methods *methods)
776 {
777         return False;
778 }
779
780 static bool tdbsam_new_rid(struct pdb_methods *methods, uint32 *prid)
781 {
782         uint32 rid;
783
784         rid = BASE_RID;         /* Default if not set */
785
786         if (!tdbsam_open(tdbsam_filename)) {
787                 DEBUG(0,("tdbsam_new_rid: failed to open %s!\n",
788                         tdbsam_filename));
789                 return false;
790         }
791
792         if (dbwrap_change_uint32_atomic(db_sam, NEXT_RID_STRING, &rid, 1) != 0) {
793                 DEBUG(3, ("tdbsam_new_rid: Failed to increase %s\n",
794                         NEXT_RID_STRING));
795                 return false;
796         }
797
798         *prid = rid;
799
800         return true;
801 }
802
803 struct tdbsam_search_state {
804         struct pdb_methods *methods;
805         uint32_t acct_flags;
806
807         uint32_t *rids;
808         uint32_t num_rids;
809         ssize_t array_size;
810         uint32_t current;
811 };
812
813 static int tdbsam_collect_rids(struct db_record *rec, void *private_data)
814 {
815         struct tdbsam_search_state *state = talloc_get_type_abort(
816                 private_data, struct tdbsam_search_state);
817         size_t prefixlen = strlen(RIDPREFIX);
818         uint32 rid;
819
820         if ((rec->key.dsize < prefixlen)
821             || (strncmp((char *)rec->key.dptr, RIDPREFIX, prefixlen))) {
822                 return 0;
823         }
824
825         rid = strtoul((char *)rec->key.dptr+prefixlen, NULL, 16);
826
827         ADD_TO_LARGE_ARRAY(state, uint32, rid, &state->rids, &state->num_rids,
828                            &state->array_size);
829
830         return 0;
831 }
832
833 static void tdbsam_search_end(struct pdb_search *search)
834 {
835         struct tdbsam_search_state *state = talloc_get_type_abort(
836                 search->private_data, struct tdbsam_search_state);
837         TALLOC_FREE(state);
838 }
839
840 static bool tdbsam_search_next_entry(struct pdb_search *search,
841                                      struct samr_displayentry *entry)
842 {
843         struct tdbsam_search_state *state = talloc_get_type_abort(
844                 search->private_data, struct tdbsam_search_state);
845         struct samu *user = NULL;
846         NTSTATUS status;
847         uint32_t rid;
848
849  again:
850         TALLOC_FREE(user);
851         user = samu_new(talloc_tos());
852         if (user == NULL) {
853                 DEBUG(0, ("samu_new failed\n"));
854                 return false;
855         }
856
857         if (state->current == state->num_rids) {
858                 return false;
859         }
860
861         rid = state->rids[state->current++];
862
863         status = tdbsam_getsampwrid(state->methods, user, rid);
864
865         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
866                 /*
867                  * Someone has deleted that user since we listed the RIDs
868                  */
869                 goto again;
870         }
871
872         if (!NT_STATUS_IS_OK(status)) {
873                 DEBUG(10, ("tdbsam_getsampwrid failed: %s\n",
874                            nt_errstr(status)));
875                 TALLOC_FREE(user);
876                 return false;
877         }
878
879         if ((state->acct_flags != 0) &&
880             ((state->acct_flags & pdb_get_acct_ctrl(user)) == 0)) {
881                 goto again;
882         }
883
884         entry->acct_flags = pdb_get_acct_ctrl(user);
885         entry->rid = rid;
886         entry->account_name = talloc_strdup(
887                 search->mem_ctx, pdb_get_username(user));
888         entry->fullname = talloc_strdup(
889                 search->mem_ctx, pdb_get_fullname(user));
890         entry->description = talloc_strdup(
891                 search->mem_ctx, pdb_get_acct_desc(user));
892
893         TALLOC_FREE(user);
894
895         if ((entry->account_name == NULL) || (entry->fullname == NULL)
896             || (entry->description == NULL)) {
897                 DEBUG(0, ("talloc_strdup failed\n"));
898                 return false;
899         }
900
901         return true;
902 }
903
904 static bool tdbsam_search_users(struct pdb_methods *methods,
905                                 struct pdb_search *search,
906                                 uint32 acct_flags)
907 {
908         struct tdbsam_search_state *state;
909
910         if (!tdbsam_open(tdbsam_filename)) {
911                 DEBUG(0,("tdbsam_getsampwnam: failed to open %s!\n",
912                          tdbsam_filename));
913                 return false;
914         }
915
916         state = TALLOC_ZERO_P(search->mem_ctx, struct tdbsam_search_state);
917         if (state == NULL) {
918                 DEBUG(0, ("talloc failed\n"));
919                 return false;
920         }
921         state->acct_flags = acct_flags;
922         state->methods = methods;
923
924         db_sam->traverse_read(db_sam, tdbsam_collect_rids, state);
925
926         search->private_data = state;
927         search->next_entry = tdbsam_search_next_entry;
928         search->search_end = tdbsam_search_end;
929
930         return true;
931 }
932
933 /*********************************************************************
934  Initialize the tdb sam backend.  Setup the dispath table of methods,
935  open the tdb, etc...
936 *********************************************************************/
937
938 static NTSTATUS pdb_init_tdbsam(struct pdb_methods **pdb_method, const char *location)
939 {
940         NTSTATUS nt_status;
941         char *tdbfile = NULL;
942         const char *pfile = location;
943
944         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
945                 return nt_status;
946         }
947
948         (*pdb_method)->name = "tdbsam";
949
950         (*pdb_method)->getsampwnam = tdbsam_getsampwnam;
951         (*pdb_method)->getsampwsid = tdbsam_getsampwsid;
952         (*pdb_method)->add_sam_account = tdbsam_add_sam_account;
953         (*pdb_method)->update_sam_account = tdbsam_update_sam_account;
954         (*pdb_method)->delete_sam_account = tdbsam_delete_sam_account;
955         (*pdb_method)->rename_sam_account = tdbsam_rename_sam_account;
956         (*pdb_method)->search_users = tdbsam_search_users;
957
958         (*pdb_method)->rid_algorithm = tdbsam_rid_algorithm;
959         (*pdb_method)->new_rid = tdbsam_new_rid;
960
961         /* save the path for later */
962
963         if (!location) {
964                 if (asprintf(&tdbfile, "%s/%s", lp_private_dir(),
965                              PASSDB_FILE_NAME) < 0) {
966                         return NT_STATUS_NO_MEMORY;
967                 }
968                 pfile = tdbfile;
969         }
970         tdbsam_filename = SMB_STRDUP(pfile);
971         if (!tdbsam_filename) {
972                 return NT_STATUS_NO_MEMORY;
973         }
974         SAFE_FREE(tdbfile);
975
976         /* no private data */
977
978         (*pdb_method)->private_data      = NULL;
979         (*pdb_method)->free_private_data = NULL;
980
981         return NT_STATUS_OK;
982 }
983
984 NTSTATUS pdb_tdbsam_init(void)
985 {
986         return smb_register_passdb(PASSDB_INTERFACE_VERSION, "tdbsam", pdb_init_tdbsam);
987 }