s3:registry: implement regdb_set_secdesc() with regdb_trans_do()
[abartlet/samba.git/.git] / source3 / registry / reg_backend_db.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  Virtual Windows Registry Layer
4  *  Copyright (C) Gerald Carter                     2002-2005
5  *  Copyright (C) Michael Adam                      2007-2011
6  *  Copyright (C) Gregor Beck                       2011
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 3 of the License, or
11  *  (at your option) any later version.
12  *  
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *  
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
20  */
21
22 /* Implementation of internal registry database functions. */
23
24 #include "includes.h"
25 #include "system/filesys.h"
26 #include "registry.h"
27 #include "reg_db.h"
28 #include "reg_util_internal.h"
29 #include "reg_backend_db.h"
30 #include "reg_objects.h"
31 #include "nt_printing.h"
32 #include "util_tdb.h"
33 #include "dbwrap/dbwrap.h"
34 #include "dbwrap/dbwrap_open.h"
35 #include "../libcli/security/secdesc.h"
36
37 #undef DBGC_CLASS
38 #define DBGC_CLASS DBGC_REGISTRY
39
40 #define REGDB_VERSION_KEYNAME "INFO/version"
41
42 static struct db_context *regdb = NULL;
43 static int regdb_refcount;
44
45 static bool regdb_key_exists(struct db_context *db, const char *key);
46 static WERROR regdb_fetch_keys_internal(struct db_context *db, const char *key,
47                                         struct regsubkey_ctr *ctr);
48 static bool regdb_store_keys_internal(struct db_context *db, const char *key,
49                                       struct regsubkey_ctr *ctr);
50 static int regdb_fetch_values_internal(struct db_context *db, const char* key,
51                                        struct regval_ctr *values);
52 static NTSTATUS regdb_store_values_internal(struct db_context *db, const char *key,
53                                             struct regval_ctr *values);
54 static WERROR regdb_store_subkey_list(struct db_context *db, const char *parent,
55                                       const char *key);
56
57 static WERROR regdb_create_basekey(struct db_context *db, const char *key);
58 static WERROR regdb_create_subkey_internal(struct db_context *db,
59                                            const char *key,
60                                            const char *subkey);
61
62
63 struct regdb_trans_ctx {
64         NTSTATUS (*action)(struct db_context *, void *);
65         void *private_data;
66 };
67
68 static NTSTATUS regdb_trans_do_action(struct db_context *db, void *private_data)
69 {
70         NTSTATUS status;
71         int32_t version_id;
72         struct regdb_trans_ctx *ctx = (struct regdb_trans_ctx *)private_data;
73
74         version_id = dbwrap_fetch_int32(db, REGDB_VERSION_KEYNAME);
75
76         if (version_id != REGVER_V3) {
77                 DEBUG(0, ("ERROR: changed registry version %d found while "
78                           "trying to write to the registry. Version %d "
79                           "expected.  Denying access.\n",
80                           version_id, REGVER_V3));
81                 return NT_STATUS_ACCESS_DENIED;
82         }
83
84         status = ctx->action(db,  ctx->private_data);
85         return status;
86 }
87
88 static WERROR regdb_trans_do(struct db_context *db,
89                              NTSTATUS (*action)(struct db_context *, void *),
90                              void *private_data)
91 {
92         NTSTATUS status;
93         struct regdb_trans_ctx ctx;
94
95
96         ctx.action = action;
97         ctx.private_data = private_data;
98
99         status = dbwrap_trans_do(db, regdb_trans_do_action, &ctx);
100
101         return ntstatus_to_werror(status);
102 }
103
104 /* List the deepest path into the registry.  All part components will be created.*/
105
106 /* If you want to have a part of the path controlled by the tdb and part by
107    a virtual registry db (e.g. printing), then you have to list the deepest path.
108    For example,"HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion/Print" 
109    allows the reg_db backend to handle everything up to 
110    "HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion" and then we'll hook 
111    the reg_printing backend onto the last component of the path (see 
112    KEY_PRINTING_2K in include/rpc_reg.h)   --jerry */
113
114 static const char *builtin_registry_paths[] = {
115         KEY_PRINTING_2K,
116         KEY_PRINTING_PORTS,
117         KEY_PRINTING,
118         KEY_PRINTING "\\Forms",
119         KEY_PRINTING "\\Printers",
120         KEY_PRINTING "\\Environments\\Windows NT x86\\Print Processors\\winprint",
121         KEY_SHARES,
122         KEY_EVENTLOG,
123         KEY_SMBCONF,
124         KEY_PERFLIB,
125         KEY_PERFLIB_009,
126         KEY_GROUP_POLICY,
127         KEY_SAMBA_GROUP_POLICY,
128         KEY_GP_MACHINE_POLICY,
129         KEY_GP_MACHINE_WIN_POLICY,
130         KEY_HKCU,
131         KEY_GP_USER_POLICY,
132         KEY_GP_USER_WIN_POLICY,
133         "HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\GPExtensions",
134         "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Print\\Monitors",
135         KEY_PROD_OPTIONS,
136         "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\DefaultUserConfiguration",
137         KEY_TCPIP_PARAMS,
138         KEY_NETLOGON_PARAMS,
139         KEY_HKU,
140         KEY_HKCR,
141         KEY_HKPD,
142         KEY_HKPT,
143          NULL };
144
145 struct builtin_regkey_value {
146         const char *path;
147         const char *valuename;
148         uint32 type;
149         union {
150                 const char *string;
151                 uint32 dw_value;
152         } data;
153 };
154
155 static struct builtin_regkey_value builtin_registry_values[] = {
156         { KEY_PRINTING_PORTS,
157                 SAMBA_PRINTER_PORT_NAME, REG_SZ, { "" } },
158         { KEY_PRINTING_2K,
159                 "DefaultSpoolDirectory", REG_SZ, { "C:\\Windows\\System32\\Spool\\Printers" } },
160         { KEY_EVENTLOG,
161                 "DisplayName", REG_SZ, { "Event Log" } },
162         { KEY_EVENTLOG,
163                 "ErrorControl", REG_DWORD, { (char*)0x00000001 } },
164         { NULL, NULL, 0, { NULL } }
165 };
166
167 static WERROR create_key_recursive(struct db_context *db,
168                                    char *path,
169                                    const char *subkey)
170 {
171         WERROR werr;
172         char *p;
173
174         if (subkey == NULL) {
175                 return WERR_INVALID_PARAM;
176         }
177
178         if (path == NULL) {
179                 return regdb_create_basekey(db, subkey);
180         }
181
182         p = strrchr_m(path, '\\');
183
184         if (p == NULL) {
185                 werr = create_key_recursive(db, NULL, path);
186         } else {
187                 *p = '\0';
188                 werr = create_key_recursive(db, path, p+1);
189                 *p = '\\';
190         }
191
192         if (!W_ERROR_IS_OK(werr)) {
193                 goto done;
194         }
195
196         werr = regdb_create_subkey_internal(db, path, subkey);
197
198 done:
199         return werr;
200 }
201
202 /**
203  * Initialize a key in the registry:
204  * create each component key of the specified path.
205  */
206 static WERROR init_registry_key_internal(struct db_context *db,
207                                          const char *add_path)
208 {
209         char *subkey, *key;
210         WERROR werr;
211         TALLOC_CTX *frame = talloc_stackframe();
212
213         if (add_path == NULL) {
214                 werr = WERR_INVALID_PARAM;
215                 goto done;
216         }
217
218         key = talloc_strdup(frame, add_path);
219
220         subkey = strrchr_m(key, '\\');
221         if (subkey == NULL) {
222                 subkey = key;
223                 key = NULL;
224         } else {
225                 *subkey = '\0';
226                 subkey++;
227         }
228
229         werr = create_key_recursive(db, key, subkey);
230
231 done:
232         talloc_free(frame);
233         return werr;
234 }
235
236 struct init_registry_key_context {
237         const char *add_path;
238 };
239
240 static NTSTATUS init_registry_key_action(struct db_context *db,
241                                          void *private_data)
242 {
243         struct init_registry_key_context *init_ctx =
244                 (struct init_registry_key_context *)private_data;
245
246         return werror_to_ntstatus(init_registry_key_internal(
247                                         db, init_ctx->add_path));
248 }
249
250 /**
251  * Initialize a key in the registry:
252  * create each component key of the specified path,
253  * wrapped in one db transaction.
254  */
255 WERROR init_registry_key(const char *add_path)
256 {
257         struct init_registry_key_context init_ctx;
258
259         if (regdb_key_exists(regdb, add_path)) {
260                 return WERR_OK;
261         }
262
263         init_ctx.add_path = add_path;
264
265         return regdb_trans_do(regdb,
266                               init_registry_key_action,
267                               &init_ctx);
268 }
269
270 /***********************************************************************
271  Open the registry data in the tdb
272  ***********************************************************************/
273
274 static void regdb_ctr_add_value(struct regval_ctr *ctr,
275                                 struct builtin_regkey_value *value)
276 {
277         switch(value->type) {
278         case REG_DWORD:
279                 regval_ctr_addvalue(ctr, value->valuename, REG_DWORD,
280                                     (uint8_t *)&value->data.dw_value,
281                                     sizeof(uint32));
282                 break;
283
284         case REG_SZ:
285                 regval_ctr_addvalue_sz(ctr, value->valuename,
286                                        value->data.string);
287                 break;
288
289         default:
290                 DEBUG(0, ("regdb_ctr_add_value: invalid value type in "
291                           "registry values [%d]\n", value->type));
292         }
293 }
294
295 static NTSTATUS init_registry_data_action(struct db_context *db,
296                                           void *private_data)
297 {
298         NTSTATUS status;
299         TALLOC_CTX *frame = talloc_stackframe();
300         struct regval_ctr *values;
301         int i;
302
303         /* loop over all of the predefined paths and add each component */
304
305         for (i=0; builtin_registry_paths[i] != NULL; i++) {
306                 if (regdb_key_exists(db, builtin_registry_paths[i])) {
307                         continue;
308                 }
309                 status = werror_to_ntstatus(init_registry_key_internal(db,
310                                                   builtin_registry_paths[i]));
311                 if (!NT_STATUS_IS_OK(status)) {
312                         goto done;
313                 }
314         }
315
316         /* loop over all of the predefined values and add each component */
317
318         for (i=0; builtin_registry_values[i].path != NULL; i++) {
319                 WERROR werr;
320
321                 werr = regval_ctr_init(frame, &values);
322                 if (!W_ERROR_IS_OK(werr)) {
323                         status = werror_to_ntstatus(werr);
324                         goto done;
325                 }
326
327                 regdb_fetch_values_internal(db,
328                                             builtin_registry_values[i].path,
329                                             values);
330
331                 /* preserve existing values across restarts. Only add new ones */
332
333                 if (!regval_ctr_key_exists(values,
334                                         builtin_registry_values[i].valuename))
335                 {
336                         regdb_ctr_add_value(values,
337                                             &builtin_registry_values[i]);
338                         status = regdb_store_values_internal(db,
339                                         builtin_registry_values[i].path,
340                                         values);
341                         if (!NT_STATUS_IS_OK(status)) {
342                                 goto done;
343                         }
344                 }
345                 TALLOC_FREE(values);
346         }
347
348         status = NT_STATUS_OK;
349
350 done:
351
352         TALLOC_FREE(frame);
353         return status;
354 }
355
356 WERROR init_registry_data(void)
357 {
358         WERROR werr;
359         TALLOC_CTX *frame = talloc_stackframe();
360         struct regval_ctr *values;
361         int i;
362
363         /*
364          * First, check for the existence of the needed keys and values.
365          * If all do already exist, we can save the writes.
366          */
367         for (i=0; builtin_registry_paths[i] != NULL; i++) {
368                 if (!regdb_key_exists(regdb, builtin_registry_paths[i])) {
369                         goto do_init;
370                 }
371         }
372
373         for (i=0; builtin_registry_values[i].path != NULL; i++) {
374                 werr = regval_ctr_init(frame, &values);
375                 W_ERROR_NOT_OK_GOTO_DONE(werr);
376
377                 regdb_fetch_values_internal(regdb,
378                                             builtin_registry_values[i].path,
379                                             values);
380                 if (!regval_ctr_key_exists(values,
381                                         builtin_registry_values[i].valuename))
382                 {
383                         TALLOC_FREE(values);
384                         goto do_init;
385                 }
386
387                 TALLOC_FREE(values);
388         }
389
390         werr = WERR_OK;
391         goto done;
392
393 do_init:
394
395         /*
396          * There are potentially quite a few store operations which are all
397          * indiviually wrapped in tdb transactions. Wrapping them in a single
398          * transaction gives just a single transaction_commit() to actually do
399          * its fsync()s. See tdb/common/transaction.c for info about nested
400          * transaction behaviour.
401          */
402
403         werr = regdb_trans_do(regdb,
404                               init_registry_data_action,
405                               NULL);
406
407 done:
408         TALLOC_FREE(frame);
409         return werr;
410 }
411
412 static int regdb_normalize_keynames_fn(struct db_record *rec,
413                                        void *private_data)
414 {
415         TALLOC_CTX *mem_ctx = talloc_tos();
416         const char *keyname;
417         NTSTATUS status;
418         struct db_context *db = (struct db_context *)private_data;
419
420         if (rec->key.dptr == NULL || rec->key.dsize == 0) {
421                 return 0;
422         }
423
424         if (db == NULL) {
425                 DEBUG(0, ("regdb_normalize_keynames_fn: ERROR: "
426                           "NULL db context handed in via private_data\n"));
427                 return 1;
428         }
429
430         if (strncmp((const char *)rec->key.dptr, REGDB_VERSION_KEYNAME,
431             strlen(REGDB_VERSION_KEYNAME)) == 0)
432         {
433                 return 0;
434         }
435
436         keyname = strchr((const char *) rec->key.dptr, '/');
437         if (keyname) {
438                 keyname = talloc_string_sub(mem_ctx,
439                                             (const char *) rec->key.dptr,
440                                             "/",
441                                             "\\");
442
443                 DEBUG(2, ("regdb_normalize_keynames_fn: Convert %s to %s\n",
444                           (const char *) rec->key.dptr,
445                           keyname));
446
447                 /* Delete the original record and store the normalized key */
448                 status = rec->delete_rec(rec);
449                 if (!NT_STATUS_IS_OK(status)) {
450                         DEBUG(0,("regdb_normalize_keynames_fn: "
451                                  "tdb_delete for [%s] failed!\n",
452                                  rec->key.dptr));
453                         return 1;
454                 }
455
456                 status = dbwrap_store_bystring(db, keyname, rec->value,
457                                                TDB_REPLACE);
458                 if (!NT_STATUS_IS_OK(status)) {
459                         DEBUG(0,("regdb_normalize_keynames_fn: "
460                                  "failed to store new record for [%s]!\n",
461                                  keyname));
462                         return 1;
463                 }
464         }
465
466         return 0;
467 }
468
469 static WERROR regdb_store_regdb_version(struct db_context *db, uint32_t version)
470 {
471         NTSTATUS status;
472         if (db == NULL) {
473                 return WERR_CAN_NOT_COMPLETE;
474         }
475
476         status = dbwrap_trans_store_int32(db, REGDB_VERSION_KEYNAME, version);
477         if (!NT_STATUS_IS_OK(status)) {
478                 DEBUG(1, ("regdb_store_regdb_version: error storing %s = %d: %s\n",
479                           REGDB_VERSION_KEYNAME, version, nt_errstr(status)));
480                 return ntstatus_to_werror(status);
481         } else {
482                 DEBUG(10, ("regdb_store_regdb_version: stored %s = %d\n",
483                           REGDB_VERSION_KEYNAME, version));
484                 return WERR_OK;
485         }
486 }
487
488 static WERROR regdb_upgrade_v1_to_v2(struct db_context *db)
489 {
490         TALLOC_CTX *mem_ctx;
491         int rc;
492         WERROR werr;
493
494         mem_ctx = talloc_stackframe();
495
496         rc = db->traverse(db, regdb_normalize_keynames_fn, db);
497
498         talloc_free(mem_ctx);
499
500         if (rc < 0) {
501                 return WERR_REG_IO_FAILURE;
502         }
503
504         werr = regdb_store_regdb_version(db, REGVER_V2);
505         return werr;
506 }
507
508 static int regdb_upgrade_v2_to_v3_fn(struct db_record *rec, void *private_data)
509 {
510         const char *keyname;
511         fstring subkeyname;
512         NTSTATUS status;
513         WERROR werr;
514         uint8_t *buf;
515         uint32_t buflen, len;
516         uint32_t num_items;
517         uint32_t i;
518         struct db_context *db = (struct db_context *)private_data;
519
520         if (rec->key.dptr == NULL || rec->key.dsize == 0) {
521                 return 0;
522         }
523
524         if (db == NULL) {
525                 DEBUG(0, ("regdb_normalize_keynames_fn: ERROR: "
526                           "NULL db context handed in via private_data\n"));
527                 return 1;
528         }
529
530         keyname = (const char *)rec->key.dptr;
531
532         if (strncmp(keyname, REGDB_VERSION_KEYNAME,
533                     strlen(REGDB_VERSION_KEYNAME)) == 0)
534         {
535                 return 0;
536         }
537
538         if (strncmp(keyname, REG_SORTED_SUBKEYS_PREFIX,
539                     strlen(REG_SORTED_SUBKEYS_PREFIX)) == 0)
540         {
541                 /* Delete the deprecated sorted subkeys cache. */
542
543                 DEBUG(10, ("regdb_upgrade_v2_to_v3: deleting [%s]\n", keyname));
544
545                 status = rec->delete_rec(rec);
546                 if (!NT_STATUS_IS_OK(status)) {
547                         DEBUG(0, ("regdb_upgrade_v2_to_v3: tdb_delete for [%s] "
548                                   "failed!\n", keyname));
549                         return 1;
550                 }
551
552                 return 0;
553         }
554
555         if (strncmp(keyname, REG_VALUE_PREFIX, strlen(REG_VALUE_PREFIX)) == 0) {
556                 DEBUG(10, ("regdb_upgrade_v2_to_v3: skipping [%s]\n", keyname));
557                 return 0;
558         }
559
560         if (strncmp(keyname, REG_SECDESC_PREFIX,
561                     strlen(REG_SECDESC_PREFIX)) == 0)
562         {
563                 DEBUG(10, ("regdb_upgrade_v2_to_v3: skipping [%s]\n", keyname));
564                 return 0;
565         }
566
567         /*
568          * Found a regular subkey list record.
569          * Walk the list and create the list record for those
570          * subkeys that don't already have one.
571          */
572         DEBUG(10, ("regdb_upgrade_v2_to_v3: scanning subkey list of [%s]\n",
573                    keyname));
574
575         buf = rec->value.dptr;
576         buflen = rec->value.dsize;
577
578         len = tdb_unpack(buf, buflen, "d", &num_items);
579         if (len == (uint32_t)-1) {
580                 /* invalid or empty - skip */
581                 return 0;
582         }
583
584         for (i=0; i<num_items; i++) {
585                 len += tdb_unpack(buf+len, buflen-len, "f", subkeyname);
586                 DEBUG(10, ("regdb_upgrade_v2_to_v3: "
587                            "writing subkey list for [%s\\%s]\n",
588                            keyname, subkeyname));
589                 werr = regdb_store_subkey_list(db, keyname, subkeyname);
590                 if (!W_ERROR_IS_OK(werr)) {
591                         return 1;
592                 }
593         }
594
595         return 0;
596 }
597
598 static WERROR regdb_upgrade_v2_to_v3(struct db_context *db)
599 {
600         int rc;
601         WERROR werr;
602
603         rc = regdb->traverse(db, regdb_upgrade_v2_to_v3_fn, db);
604         if (rc < 0) {
605                 werr = WERR_REG_IO_FAILURE;
606                 goto done;
607         }
608
609         werr = regdb_store_regdb_version(db, REGVER_V3);
610
611 done:
612         return werr;
613 }
614
615 /***********************************************************************
616  Open the registry database
617  ***********************************************************************/
618
619 WERROR regdb_init(void)
620 {
621         uint32 vers_id, expected_version;
622         WERROR werr;
623
624         if (regdb) {
625                 DEBUG(10, ("regdb_init: incrementing refcount (%d->%d)\n",
626                            regdb_refcount, regdb_refcount+1));
627                 regdb_refcount++;
628                 return WERR_OK;
629         }
630
631         regdb = db_open(NULL, state_path("registry.tdb"), 0,
632                               REG_TDB_FLAGS, O_RDWR, 0600);
633         if (!regdb) {
634                 regdb = db_open(NULL, state_path("registry.tdb"), 0,
635                                       REG_TDB_FLAGS, O_RDWR|O_CREAT, 0600);
636                 if (!regdb) {
637                         werr = ntstatus_to_werror(map_nt_error_from_unix(errno));
638                         DEBUG(1,("regdb_init: Failed to open registry %s (%s)\n",
639                                 state_path("registry.tdb"), strerror(errno) ));
640                         return werr;
641                 }
642
643                 DEBUG(10,("regdb_init: Successfully created registry tdb\n"));
644         }
645
646         regdb_refcount = 1;
647         DEBUG(10, ("regdb_init: registry db openend. refcount reset (%d)\n",
648                    regdb_refcount));
649
650         expected_version = REGVER_V3;
651
652         vers_id = dbwrap_fetch_int32(regdb, REGDB_VERSION_KEYNAME);
653         if (vers_id == -1) {
654                 DEBUG(10, ("regdb_init: registry version uninitialized "
655                            "(got %d), initializing to version %d\n",
656                            vers_id, expected_version));
657
658                 werr = regdb_store_regdb_version(regdb, expected_version);
659                 return werr;
660         }
661
662         if (vers_id > expected_version || vers_id == 0) {
663                 DEBUG(0, ("regdb_init: unknown registry version %d "
664                           "(code version = %d), refusing initialization\n",
665                           vers_id, expected_version));
666                 return WERR_CAN_NOT_COMPLETE;
667         }
668
669         if (regdb->transaction_start(regdb) != 0) {
670                 return WERR_REG_IO_FAILURE;
671         }
672
673         if (vers_id == REGVER_V1) {
674                 DEBUG(10, ("regdb_init: upgrading registry fromversion %d "
675                            "to %d\n", REGVER_V1, REGVER_V2));
676
677                 werr = regdb_upgrade_v1_to_v2(regdb);
678                 if (!W_ERROR_IS_OK(werr)) {
679                         regdb->transaction_cancel(regdb);
680                         return werr;
681                 }
682
683                 vers_id = REGVER_V2;
684         }
685
686         if (vers_id == REGVER_V2) {
687                 DEBUG(10, ("regdb_init: upgrading registry from version %d "
688                            "to %d\n", REGVER_V2, REGVER_V3));
689
690                 werr = regdb_upgrade_v2_to_v3(regdb);
691                 if (!W_ERROR_IS_OK(werr)) {
692                         regdb->transaction_cancel(regdb);
693                         return werr;
694                 }
695
696                 vers_id = REGVER_V3;
697         }
698
699         /* future upgrade code should go here */
700
701         if (regdb->transaction_commit(regdb) != 0) {
702                 return WERR_REG_IO_FAILURE;
703         }
704
705         return WERR_OK;
706 }
707
708 /***********************************************************************
709  Open the registry.  Must already have been initialized by regdb_init()
710  ***********************************************************************/
711
712 WERROR regdb_open( void )
713 {
714         WERROR result = WERR_OK;
715
716         if ( regdb ) {
717                 DEBUG(10, ("regdb_open: incrementing refcount (%d->%d)\n",
718                            regdb_refcount, regdb_refcount+1));
719                 regdb_refcount++;
720                 return WERR_OK;
721         }
722
723         become_root();
724
725         regdb = db_open(NULL, state_path("registry.tdb"), 0,
726                               REG_TDB_FLAGS, O_RDWR, 0600);
727         if ( !regdb ) {
728                 result = ntstatus_to_werror( map_nt_error_from_unix( errno ) );
729                 DEBUG(0,("regdb_open: Failed to open %s! (%s)\n",
730                         state_path("registry.tdb"), strerror(errno) ));
731         }
732
733         unbecome_root();
734
735         regdb_refcount = 1;
736         DEBUG(10, ("regdb_open: registry db opened. refcount reset (%d)\n",
737                    regdb_refcount));
738
739         return result;
740 }
741
742 /***********************************************************************
743  ***********************************************************************/
744
745 int regdb_close( void )
746 {
747         if (regdb_refcount == 0) {
748                 return 0;
749         }
750
751         regdb_refcount--;
752
753         DEBUG(10, ("regdb_close: decrementing refcount (%d->%d)\n",
754                    regdb_refcount+1, regdb_refcount));
755
756         if ( regdb_refcount > 0 )
757                 return 0;
758
759         SMB_ASSERT( regdb_refcount >= 0 );
760
761         TALLOC_FREE(regdb);
762         return 0;
763 }
764
765 WERROR regdb_transaction_start(void)
766 {
767         return (regdb->transaction_start(regdb) == 0) ?
768                 WERR_OK : WERR_REG_IO_FAILURE;
769 }
770
771 WERROR regdb_transaction_commit(void)
772 {
773         return (regdb->transaction_commit(regdb) == 0) ?
774                 WERR_OK : WERR_REG_IO_FAILURE;
775 }
776
777 WERROR regdb_transaction_cancel(void)
778 {
779         return (regdb->transaction_cancel(regdb) == 0) ?
780                 WERR_OK : WERR_REG_IO_FAILURE;
781 }
782
783 /***********************************************************************
784  return the tdb sequence number of the registry tdb.
785  this is an indicator for the content of the registry
786  having changed. it will change upon regdb_init, too, though.
787  ***********************************************************************/
788 int regdb_get_seqnum(void)
789 {
790         return regdb->get_seqnum(regdb);
791 }
792
793
794 static WERROR regdb_delete_key_with_prefix(struct db_context *db,
795                                            const char *keyname,
796                                            const char *prefix)
797 {
798         char *path;
799         WERROR werr = WERR_NOMEM;
800         TALLOC_CTX *mem_ctx = talloc_stackframe();
801
802         if (keyname == NULL) {
803                 werr = WERR_INVALID_PARAM;
804                 goto done;
805         }
806
807         if (prefix == NULL) {
808                 path = discard_const_p(char, keyname);
809         } else {
810                 path = talloc_asprintf(mem_ctx, "%s\\%s", prefix, keyname);
811                 if (path == NULL) {
812                         goto done;
813                 }
814         }
815
816         path = normalize_reg_path(mem_ctx, path);
817         if (path == NULL) {
818                 goto done;
819         }
820
821         werr = ntstatus_to_werror(dbwrap_delete_bystring(db, path));
822
823         /* treat "not found" as ok */
824         if (W_ERROR_EQUAL(werr, WERR_NOT_FOUND)) {
825                 werr = WERR_OK;
826         }
827
828 done:
829         talloc_free(mem_ctx);
830         return werr;
831 }
832
833
834 static WERROR regdb_delete_values(struct db_context *db, const char *keyname)
835 {
836         return regdb_delete_key_with_prefix(db, keyname, REG_VALUE_PREFIX);
837 }
838
839 static WERROR regdb_delete_secdesc(struct db_context *db, const char *keyname)
840 {
841         return regdb_delete_key_with_prefix(db, keyname, REG_SECDESC_PREFIX);
842 }
843
844 static WERROR regdb_delete_subkeylist(struct db_context *db, const char *keyname)
845 {
846         return regdb_delete_key_with_prefix(db, keyname, NULL);
847 }
848
849
850 static WERROR regdb_delete_key_lists(struct db_context *db, const char *keyname)
851 {
852         WERROR werr;
853
854         werr = regdb_delete_values(db, keyname);
855         if (!W_ERROR_IS_OK(werr)) {
856                 DEBUG(1, (__location__ " Deleting %s\\%s failed: %s\n",
857                           REG_VALUE_PREFIX, keyname, win_errstr(werr)));
858                 goto done;
859         }
860
861         werr = regdb_delete_secdesc(db, keyname);
862         if (!W_ERROR_IS_OK(werr)) {
863                 DEBUG(1, (__location__ " Deleting %s\\%s failed: %s\n",
864                           REG_SECDESC_PREFIX, keyname, win_errstr(werr)));
865                 goto done;
866         }
867
868         werr = regdb_delete_subkeylist(db, keyname);
869         if (!W_ERROR_IS_OK(werr)) {
870                 DEBUG(1, (__location__ " Deleting %s failed: %s\n",
871                           keyname, win_errstr(werr)));
872                 goto done;
873         }
874
875 done:
876         return werr;
877 }
878
879 /***********************************************************************
880  Add subkey strings to the registry tdb under a defined key
881  fmt is the same format as tdb_pack except this function only supports
882  fstrings
883  ***********************************************************************/
884
885 static WERROR regdb_store_keys_internal2(struct db_context *db,
886                                          const char *key,
887                                          struct regsubkey_ctr *ctr)
888 {
889         TDB_DATA dbuf;
890         uint8 *buffer = NULL;
891         int i = 0;
892         uint32 len, buflen;
893         uint32 num_subkeys = regsubkey_ctr_numkeys(ctr);
894         char *keyname = NULL;
895         TALLOC_CTX *ctx = talloc_stackframe();
896         WERROR werr;
897
898         if (!key) {
899                 werr = WERR_INVALID_PARAM;
900                 goto done;
901         }
902
903         keyname = talloc_strdup(ctx, key);
904         if (!keyname) {
905                 werr = WERR_NOMEM;
906                 goto done;
907         }
908
909         keyname = normalize_reg_path(ctx, keyname);
910         if (!keyname) {
911                 werr = WERR_NOMEM;
912                 goto done;
913         }
914
915         /* allocate some initial memory */
916
917         buffer = (uint8 *)SMB_MALLOC(1024);
918         if (buffer == NULL) {
919                 werr = WERR_NOMEM;
920                 goto done;
921         }
922         buflen = 1024;
923         len = 0;
924
925         /* store the number of subkeys */
926
927         len += tdb_pack(buffer+len, buflen-len, "d", num_subkeys);
928
929         /* pack all the strings */
930
931         for (i=0; i<num_subkeys; i++) {
932                 size_t thistime;
933
934                 thistime = tdb_pack(buffer+len, buflen-len, "f",
935                                     regsubkey_ctr_specific_key(ctr, i));
936                 if (len+thistime > buflen) {
937                         size_t thistime2;
938                         /*
939                          * tdb_pack hasn't done anything because of the short
940                          * buffer, allocate extra space.
941                          */
942                         buffer = SMB_REALLOC_ARRAY(buffer, uint8_t,
943                                                    (len+thistime)*2);
944                         if(buffer == NULL) {
945                                 DEBUG(0, ("regdb_store_keys: Failed to realloc "
946                                           "memory of size [%u]\n",
947                                           (unsigned int)(len+thistime)*2));
948                                 werr = WERR_NOMEM;
949                                 goto done;
950                         }
951                         buflen = (len+thistime)*2;
952                         thistime2 = tdb_pack(
953                                 buffer+len, buflen-len, "f",
954                                 regsubkey_ctr_specific_key(ctr, i));
955                         if (thistime2 != thistime) {
956                                 DEBUG(0, ("tdb_pack failed\n"));
957                                 werr = WERR_CAN_NOT_COMPLETE;
958                                 goto done;
959                         }
960                 }
961                 len += thistime;
962         }
963
964         /* finally write out the data */
965
966         dbuf.dptr = buffer;
967         dbuf.dsize = len;
968         werr = ntstatus_to_werror(dbwrap_store_bystring(db, keyname, dbuf,
969                                                         TDB_REPLACE));
970
971 done:
972         TALLOC_FREE(ctx);
973         SAFE_FREE(buffer);
974         return werr;
975 }
976
977 /**
978  * Utility function to store a new empty list of
979  * subkeys of given key specified as parent and subkey name
980  * (thereby creating the key).
981  * If the parent keyname is NULL, then the "subkey" is
982  * interpreted as a base key.
983  * If the subkey list does already exist, it is not modified.
984  *
985  * Must be called from within a transaction.
986  */
987 static WERROR regdb_store_subkey_list(struct db_context *db, const char *parent,
988                                       const char *key)
989 {
990         WERROR werr;
991         char *path = NULL;
992         struct regsubkey_ctr *subkeys = NULL;
993         TALLOC_CTX *frame = talloc_stackframe();
994
995         if (parent == NULL) {
996                 path = talloc_strdup(frame, key);
997         } else {
998                 path = talloc_asprintf(frame, "%s\\%s", parent, key);
999         }
1000         if (!path) {
1001                 werr = WERR_NOMEM;
1002                 goto done;
1003         }
1004
1005         werr = regsubkey_ctr_init(frame, &subkeys);
1006         W_ERROR_NOT_OK_GOTO_DONE(werr);
1007
1008         werr = regdb_fetch_keys_internal(db, path, subkeys);
1009         if (W_ERROR_IS_OK(werr)) {
1010                 /* subkey list exists already - don't modify */
1011                 goto done;
1012         }
1013
1014         werr = regsubkey_ctr_reinit(subkeys);
1015         W_ERROR_NOT_OK_GOTO_DONE(werr);
1016
1017         /* create a record with 0 subkeys */
1018         werr = regdb_store_keys_internal2(db, path, subkeys);
1019         if (!W_ERROR_IS_OK(werr)) {
1020                 DEBUG(0, ("regdb_store_keys: Failed to store new record for "
1021                           "key [%s]: %s\n", path, win_errstr(werr)));
1022                 goto done;
1023         }
1024
1025 done:
1026         talloc_free(frame);
1027         return werr;
1028 }
1029
1030 /***********************************************************************
1031  Store the new subkey record and create any child key records that
1032  do not currently exist
1033  ***********************************************************************/
1034
1035 struct regdb_store_keys_context {
1036         const char *key;
1037         struct regsubkey_ctr *ctr;
1038 };
1039
1040 static NTSTATUS regdb_store_keys_action(struct db_context *db,
1041                                         void *private_data)
1042 {
1043         struct regdb_store_keys_context *store_ctx;
1044         WERROR werr;
1045         int num_subkeys, i;
1046         char *path = NULL;
1047         struct regsubkey_ctr *old_subkeys = NULL;
1048         char *oldkeyname = NULL;
1049         TALLOC_CTX *mem_ctx = talloc_stackframe();
1050
1051         store_ctx = (struct regdb_store_keys_context *)private_data;
1052
1053         /*
1054          * Re-fetch the old keys inside the transaction
1055          */
1056
1057         werr = regsubkey_ctr_init(mem_ctx, &old_subkeys);
1058         W_ERROR_NOT_OK_GOTO_DONE(werr);
1059
1060         werr = regdb_fetch_keys_internal(db, store_ctx->key, old_subkeys);
1061         if (!W_ERROR_IS_OK(werr) &&
1062             !W_ERROR_EQUAL(werr, WERR_NOT_FOUND))
1063         {
1064                 goto done;
1065         }
1066
1067         /*
1068          * Make the store operation as safe as possible without transactions:
1069          *
1070          * (1) For each subkey removed from ctr compared with old_subkeys:
1071          *
1072          *     (a) First delete the value db entry.
1073          *
1074          *     (b) Next delete the secdesc db record.
1075          *
1076          *     (c) Then delete the subkey list entry.
1077          *
1078          * (2) Now write the list of subkeys of the parent key,
1079          *     deleting removed entries and adding new ones.
1080          *
1081          * (3) Finally create the subkey list entries for the added keys.
1082          *
1083          * This way if we crash half-way in between deleting the subkeys
1084          * and storing the parent's list of subkeys, no old data can pop up
1085          * out of the blue when re-adding keys later on.
1086          */
1087
1088         /* (1) delete removed keys' lists (values/secdesc/subkeys) */
1089
1090         num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
1091         for (i=0; i<num_subkeys; i++) {
1092                 oldkeyname = regsubkey_ctr_specific_key(old_subkeys, i);
1093
1094                 if (regsubkey_ctr_key_exists(store_ctx->ctr, oldkeyname)) {
1095                         /*
1096                          * It's still around, don't delete
1097                          */
1098                         continue;
1099                 }
1100
1101                 path = talloc_asprintf(mem_ctx, "%s\\%s", store_ctx->key,
1102                                        oldkeyname);
1103                 if (!path) {
1104                         werr = WERR_NOMEM;
1105                         goto done;
1106                 }
1107
1108                 werr = regdb_delete_key_lists(db, path);
1109                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1110
1111                 TALLOC_FREE(path);
1112         }
1113
1114         TALLOC_FREE(old_subkeys);
1115
1116         /* (2) store the subkey list for the parent */
1117
1118         werr = regdb_store_keys_internal2(db, store_ctx->key, store_ctx->ctr);
1119         if (!W_ERROR_IS_OK(werr)) {
1120                 DEBUG(0,("regdb_store_keys: Failed to store new subkey list "
1121                          "for parent [%s]: %s\n", store_ctx->key,
1122                          win_errstr(werr)));
1123                 goto done;
1124         }
1125
1126         /* (3) now create records for any subkeys that don't already exist */
1127
1128         num_subkeys = regsubkey_ctr_numkeys(store_ctx->ctr);
1129
1130         for (i=0; i<num_subkeys; i++) {
1131                 const char *subkey;
1132
1133                 subkey = regsubkey_ctr_specific_key(store_ctx->ctr, i);
1134
1135                 werr = regdb_store_subkey_list(db, store_ctx->key, subkey);
1136                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1137         }
1138
1139         werr = WERR_OK;
1140
1141 done:
1142         talloc_free(mem_ctx);
1143         return werror_to_ntstatus(werr);
1144 }
1145
1146 static bool regdb_store_keys_internal(struct db_context *db, const char *key,
1147                                       struct regsubkey_ctr *ctr)
1148 {
1149         int num_subkeys, old_num_subkeys, i;
1150         struct regsubkey_ctr *old_subkeys = NULL;
1151         TALLOC_CTX *ctx = talloc_stackframe();
1152         WERROR werr;
1153         bool ret = false;
1154         struct regdb_store_keys_context store_ctx;
1155
1156         if (!regdb_key_exists(db, key)) {
1157                 goto done;
1158         }
1159
1160         /*
1161          * fetch a list of the old subkeys so we can determine if anything has
1162          * changed
1163          */
1164
1165         werr = regsubkey_ctr_init(ctx, &old_subkeys);
1166         if (!W_ERROR_IS_OK(werr)) {
1167                 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
1168                 goto done;
1169         }
1170
1171         werr = regdb_fetch_keys_internal(db, key, old_subkeys);
1172         if (!W_ERROR_IS_OK(werr) &&
1173             !W_ERROR_EQUAL(werr, WERR_NOT_FOUND))
1174         {
1175                 goto done;
1176         }
1177
1178         num_subkeys = regsubkey_ctr_numkeys(ctr);
1179         old_num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
1180         if ((num_subkeys && old_num_subkeys) &&
1181             (num_subkeys == old_num_subkeys)) {
1182
1183                 for (i = 0; i < num_subkeys; i++) {
1184                         if (strcmp(regsubkey_ctr_specific_key(ctr, i),
1185                                    regsubkey_ctr_specific_key(old_subkeys, i))
1186                             != 0)
1187                         {
1188                                 break;
1189                         }
1190                 }
1191                 if (i == num_subkeys) {
1192                         /*
1193                          * Nothing changed, no point to even start a tdb
1194                          * transaction
1195                          */
1196
1197                         ret = true;
1198                         goto done;
1199                 }
1200         }
1201
1202         TALLOC_FREE(old_subkeys);
1203
1204         store_ctx.key = key;
1205         store_ctx.ctr = ctr;
1206
1207         werr = regdb_trans_do(db,
1208                               regdb_store_keys_action,
1209                               &store_ctx);
1210
1211         ret = W_ERROR_IS_OK(werr);
1212
1213 done:
1214         TALLOC_FREE(ctx);
1215
1216         return ret;
1217 }
1218
1219 bool regdb_store_keys(const char *key, struct regsubkey_ctr *ctr)
1220 {
1221         return regdb_store_keys_internal(regdb, key, ctr);
1222 }
1223
1224 /**
1225  * create a subkey of a given key
1226  */
1227
1228 struct regdb_create_subkey_context {
1229         const char *key;
1230         const char *subkey;
1231 };
1232
1233 static NTSTATUS regdb_create_subkey_action(struct db_context *db,
1234                                            void *private_data)
1235 {
1236         WERROR werr;
1237         struct regdb_create_subkey_context *create_ctx;
1238         struct regsubkey_ctr *subkeys;
1239         TALLOC_CTX *mem_ctx = talloc_stackframe();
1240
1241         create_ctx = (struct regdb_create_subkey_context *)private_data;
1242
1243         werr = regsubkey_ctr_init(mem_ctx, &subkeys);
1244         W_ERROR_NOT_OK_GOTO_DONE(werr);
1245
1246         werr = regdb_fetch_keys_internal(db, create_ctx->key, subkeys);
1247         W_ERROR_NOT_OK_GOTO_DONE(werr);
1248
1249         werr = regsubkey_ctr_addkey(subkeys, create_ctx->subkey);
1250         W_ERROR_NOT_OK_GOTO_DONE(werr);
1251
1252         werr = regdb_store_keys_internal2(db, create_ctx->key, subkeys);
1253         if (!W_ERROR_IS_OK(werr)) {
1254                 DEBUG(0, (__location__ " failed to store new subkey list for "
1255                          "parent key %s: %s\n", create_ctx->key,
1256                          win_errstr(werr)));
1257         }
1258
1259         werr = regdb_store_subkey_list(db, create_ctx->key, create_ctx->subkey);
1260
1261 done:
1262         talloc_free(mem_ctx);
1263         return werror_to_ntstatus(werr);
1264 }
1265
1266 static WERROR regdb_create_subkey_internal(struct db_context *db,
1267                                            const char *key,
1268                                            const char *subkey)
1269 {
1270         WERROR werr;
1271         struct regsubkey_ctr *subkeys;
1272         TALLOC_CTX *mem_ctx = talloc_stackframe();
1273         struct regdb_create_subkey_context create_ctx;
1274
1275         if (!regdb_key_exists(db, key)) {
1276                 werr = WERR_NOT_FOUND;
1277                 goto done;
1278         }
1279
1280         werr = regsubkey_ctr_init(mem_ctx, &subkeys);
1281         W_ERROR_NOT_OK_GOTO_DONE(werr);
1282
1283         werr = regdb_fetch_keys_internal(db, key, subkeys);
1284         W_ERROR_NOT_OK_GOTO_DONE(werr);
1285
1286         if (regsubkey_ctr_key_exists(subkeys, subkey)) {
1287                 werr = WERR_OK;
1288                 goto done;
1289         }
1290
1291         talloc_free(subkeys);
1292
1293         create_ctx.key = key;
1294         create_ctx.subkey = subkey;
1295
1296         werr = regdb_trans_do(db,
1297                               regdb_create_subkey_action,
1298                               &create_ctx);
1299
1300 done:
1301         talloc_free(mem_ctx);
1302         return werr;
1303 }
1304
1305 static WERROR regdb_create_subkey(const char *key, const char *subkey)
1306 {
1307         return regdb_create_subkey_internal(regdb, key, subkey);
1308 }
1309
1310 /**
1311  * create a base key
1312  */
1313
1314 struct regdb_create_basekey_context {
1315         const char *key;
1316 };
1317
1318 static NTSTATUS regdb_create_basekey_action(struct db_context *db,
1319                                             void *private_data)
1320 {
1321         WERROR werr;
1322         struct regdb_create_basekey_context *create_ctx;
1323
1324         create_ctx = (struct regdb_create_basekey_context *)private_data;
1325
1326         werr = regdb_store_subkey_list(db, NULL, create_ctx->key);
1327
1328         return werror_to_ntstatus(werr);
1329 }
1330
1331 static WERROR regdb_create_basekey(struct db_context *db, const char *key)
1332 {
1333         WERROR werr;
1334         struct regdb_create_subkey_context create_ctx;
1335
1336         create_ctx.key = key;
1337
1338         werr = regdb_trans_do(db,
1339                               regdb_create_basekey_action,
1340                               &create_ctx);
1341
1342         return werr;
1343 }
1344
1345 /**
1346  * create a subkey of a given key
1347  */
1348
1349 struct regdb_delete_subkey_context {
1350         const char *key;
1351         const char *subkey;
1352         const char *path;
1353         bool lazy;
1354 };
1355
1356 static NTSTATUS regdb_delete_subkey_action(struct db_context *db,
1357                                            void *private_data)
1358 {
1359         WERROR werr;
1360         struct regdb_delete_subkey_context *delete_ctx;
1361         struct regsubkey_ctr *subkeys;
1362         TALLOC_CTX *mem_ctx = talloc_stackframe();
1363
1364         delete_ctx = (struct regdb_delete_subkey_context *)private_data;
1365
1366         werr = regdb_delete_key_lists(db, delete_ctx->path);
1367         W_ERROR_NOT_OK_GOTO_DONE(werr);
1368
1369         if (delete_ctx->lazy) {
1370                 goto done;
1371         }
1372
1373         werr = regsubkey_ctr_init(mem_ctx, &subkeys);
1374         W_ERROR_NOT_OK_GOTO_DONE(werr);
1375
1376         werr = regdb_fetch_keys_internal(db, delete_ctx->key, subkeys);
1377         W_ERROR_NOT_OK_GOTO_DONE(werr);
1378
1379         werr = regsubkey_ctr_delkey(subkeys, delete_ctx->subkey);
1380         W_ERROR_NOT_OK_GOTO_DONE(werr);
1381
1382         werr = regdb_store_keys_internal2(db, delete_ctx->key, subkeys);
1383         if (!W_ERROR_IS_OK(werr)) {
1384                 DEBUG(0, (__location__ " failed to store new subkey_list for "
1385                          "parent key %s: %s\n", delete_ctx->key,
1386                          win_errstr(werr)));
1387         }
1388
1389 done:
1390         talloc_free(mem_ctx);
1391         return werror_to_ntstatus(werr);
1392 }
1393
1394 static WERROR regdb_delete_subkey(const char *key, const char *subkey, bool lazy)
1395 {
1396         WERROR werr;
1397         char *path;
1398         struct regdb_delete_subkey_context delete_ctx;
1399         TALLOC_CTX *mem_ctx = talloc_stackframe();
1400
1401         if (!regdb_key_exists(regdb, key)) {
1402                 werr = WERR_NOT_FOUND;
1403                 goto done;
1404         }
1405
1406         path = talloc_asprintf(mem_ctx, "%s\\%s", key, subkey);
1407         if (path == NULL) {
1408                 werr = WERR_NOMEM;
1409                 goto done;
1410         }
1411
1412         if (!regdb_key_exists(regdb, path)) {
1413                 werr = WERR_OK;
1414                 goto done;
1415         }
1416
1417         delete_ctx.key = key;
1418         delete_ctx.subkey = subkey;
1419         delete_ctx.path = path;
1420         delete_ctx.lazy = lazy;
1421
1422         werr = regdb_trans_do(regdb,
1423                               regdb_delete_subkey_action,
1424                               &delete_ctx);
1425
1426 done:
1427         talloc_free(mem_ctx);
1428         return werr;
1429 }
1430
1431 static TDB_DATA regdb_fetch_key_internal(struct db_context *db,
1432                                          TALLOC_CTX *mem_ctx, const char *key)
1433 {
1434         char *path = NULL;
1435         TDB_DATA data;
1436
1437         path = normalize_reg_path(mem_ctx, key);
1438         if (!path) {
1439                 return make_tdb_data(NULL, 0);
1440         }
1441
1442         data = dbwrap_fetch_bystring(db, mem_ctx, path);
1443
1444         TALLOC_FREE(path);
1445         return data;
1446 }
1447
1448
1449 /**
1450  * Check for the existence of a key.
1451  *
1452  * Existence of a key is authoritatively defined by
1453  * the existence of the record that contains the list
1454  * of its subkeys.
1455  *
1456  * Return false, if the record does not match the correct
1457  * structure of an initial 4-byte counter and then a
1458  * list of the corresponding number of zero-terminated
1459  * strings.
1460  */
1461 static bool regdb_key_exists(struct db_context *db, const char *key)
1462 {
1463         TALLOC_CTX *mem_ctx = talloc_stackframe();
1464         TDB_DATA value;
1465         bool ret = false;
1466         char *path;
1467         uint32_t buflen;
1468         const char *buf;
1469         uint32_t num_items, i;
1470         int32_t len;
1471
1472         if (key == NULL) {
1473                 goto done;
1474         }
1475
1476         path = normalize_reg_path(mem_ctx, key);
1477         if (path == NULL) {
1478                 DEBUG(0, ("out of memory! (talloc failed)\n"));
1479                 goto done;
1480         }
1481
1482         if (*path == '\0') {
1483                 goto done;
1484         }
1485
1486         value = regdb_fetch_key_internal(db, mem_ctx, path);
1487         if (value.dptr == NULL) {
1488                 goto done;
1489         }
1490
1491         if (value.dsize == 0) {
1492                 DEBUG(10, ("regdb_key_exists: subkeylist-record for key "
1493                           "[%s] is empty: Could be a deleted record in a "
1494                           "clustered (ctdb) environment?\n",
1495                           path));
1496                 goto done;
1497         }
1498
1499         len = tdb_unpack(value.dptr, value.dsize, "d", &num_items);
1500         if (len == (int32_t)-1) {
1501                 DEBUG(1, ("regdb_key_exists: ERROR: subkeylist-record for key "
1502                           "[%s] is invalid: Could not parse initial 4-byte "
1503                           "counter. record data length is %u.\n",
1504                           path, (unsigned int)value.dsize));
1505                 goto done;
1506         }
1507
1508         /*
1509          * Note: the tdb_unpack check above implies that len <= value.dsize
1510          */
1511         buflen = value.dsize - len;
1512         buf = (const char *)value.dptr + len;
1513
1514         len = 0;
1515
1516         for (i = 0; i < num_items; i++) {
1517                 if (buflen == 0) {
1518                         break;
1519                 }
1520                 len = strnlen(buf, buflen) + 1;
1521                 if (buflen < len) {
1522                         DEBUG(1, ("regdb_key_exists: ERROR: subkeylist-record "
1523                                   "for key [%s] is corrupt: %u items expected, "
1524                                   "item number %u is not zero terminated.\n",
1525                                   path, num_items, i+1));
1526                         goto done;
1527                 }
1528
1529                 buf += len;
1530                 buflen -= len;
1531         }
1532
1533         if (buflen > 0) {
1534                 DEBUG(1, ("regdb_key_exists: ERROR: subkeylist-record for key "
1535                           "[%s] is corrupt: %u items expected and found, but "
1536                           "the record contains additional %u bytes\n",
1537                           path, num_items, buflen));
1538                 goto done;
1539         }
1540
1541         if (i < num_items) {
1542                 DEBUG(1, ("regdb_key_exists: ERROR: subkeylist-record for key "
1543                           "[%s] is corrupt: %u items expected, but only %u "
1544                           "items found.\n",
1545                           path, num_items, i+1));
1546                 goto done;
1547         }
1548
1549         ret = true;
1550
1551 done:
1552         TALLOC_FREE(mem_ctx);
1553         return ret;
1554 }
1555
1556
1557 /***********************************************************************
1558  Retrieve an array of strings containing subkeys.  Memory should be
1559  released by the caller.
1560  ***********************************************************************/
1561
1562 static WERROR regdb_fetch_keys_internal(struct db_context *db, const char *key,
1563                                         struct regsubkey_ctr *ctr)
1564 {
1565         WERROR werr;
1566         uint32_t num_items;
1567         uint8 *buf;
1568         uint32 buflen, len;
1569         int i;
1570         fstring subkeyname;
1571         TALLOC_CTX *frame = talloc_stackframe();
1572         TDB_DATA value;
1573
1574         DEBUG(11,("regdb_fetch_keys: Enter key => [%s]\n", key ? key : "NULL"));
1575
1576         if (!regdb_key_exists(db, key)) {
1577                 DEBUG(10, ("key [%s] not found\n", key));
1578                 werr = WERR_NOT_FOUND;
1579                 goto done;
1580         }
1581
1582         werr = regsubkey_ctr_reinit(ctr);
1583         W_ERROR_NOT_OK_GOTO_DONE(werr);
1584
1585         werr = regsubkey_ctr_set_seqnum(ctr, db->get_seqnum(db));
1586         W_ERROR_NOT_OK_GOTO_DONE(werr);
1587
1588         value = regdb_fetch_key_internal(db, frame, key);
1589
1590         if (value.dsize == 0 || value.dptr == NULL) {
1591                 DEBUG(10, ("regdb_fetch_keys: no subkeys found for key [%s]\n",
1592                            key));
1593                 goto done;
1594         }
1595
1596         buf = value.dptr;
1597         buflen = value.dsize;
1598         len = tdb_unpack( buf, buflen, "d", &num_items);
1599         if (len == (uint32_t)-1) {
1600                 werr = WERR_NOT_FOUND;
1601                 goto done;
1602         }
1603
1604         for (i=0; i<num_items; i++) {
1605                 len += tdb_unpack(buf+len, buflen-len, "f", subkeyname);
1606                 werr = regsubkey_ctr_addkey(ctr, subkeyname);
1607                 if (!W_ERROR_IS_OK(werr)) {
1608                         DEBUG(5, ("regdb_fetch_keys: regsubkey_ctr_addkey "
1609                                   "failed: %s\n", win_errstr(werr)));
1610                         num_items = 0;
1611                         goto done;
1612                 }
1613         }
1614
1615         DEBUG(11,("regdb_fetch_keys: Exit [%d] items\n", num_items));
1616
1617 done:
1618         TALLOC_FREE(frame);
1619         return werr;
1620 }
1621
1622 int regdb_fetch_keys(const char *key, struct regsubkey_ctr *ctr)
1623 {
1624         WERROR werr;
1625
1626         werr = regdb_fetch_keys_internal(regdb, key, ctr);
1627         if (!W_ERROR_IS_OK(werr)) {
1628                 return -1;
1629         }
1630
1631         return regsubkey_ctr_numkeys(ctr);
1632 }
1633
1634 /****************************************************************************
1635  Unpack a list of registry values frem the TDB
1636  ***************************************************************************/
1637
1638 static int regdb_unpack_values(struct regval_ctr *values, uint8 *buf, int buflen)
1639 {
1640         int             len = 0;
1641         uint32          type;
1642         fstring valuename;
1643         uint32          size;
1644         uint8           *data_p;
1645         uint32          num_values = 0;
1646         int             i;
1647
1648         /* loop and unpack the rest of the registry values */
1649
1650         len += tdb_unpack(buf+len, buflen-len, "d", &num_values);
1651
1652         for ( i=0; i<num_values; i++ ) {
1653                 /* unpack the next regval */
1654
1655                 type = REG_NONE;
1656                 size = 0;
1657                 data_p = NULL;
1658                 valuename[0] = '\0';
1659                 len += tdb_unpack(buf+len, buflen-len, "fdB",
1660                                   valuename,
1661                                   &type,
1662                                   &size,
1663                                   &data_p);
1664
1665                 regval_ctr_addvalue(values, valuename, type,
1666                                 (uint8_t *)data_p, size);
1667                 SAFE_FREE(data_p); /* 'B' option to tdb_unpack does a malloc() */
1668
1669                 DEBUG(8,("specific: [%s], len: %d\n", valuename, size));
1670         }
1671
1672         return len;
1673 }
1674
1675 /****************************************************************************
1676  Pack all values in all printer keys
1677  ***************************************************************************/
1678
1679 static int regdb_pack_values(struct regval_ctr *values, uint8 *buf, int buflen)
1680 {
1681         int             len = 0;
1682         int             i;
1683         struct regval_blob      *val;
1684         int             num_values;
1685
1686         if ( !values )
1687                 return 0;
1688
1689         num_values = regval_ctr_numvals( values );
1690
1691         /* pack the number of values first */
1692
1693         len += tdb_pack( buf+len, buflen-len, "d", num_values );
1694
1695         /* loop over all values */
1696
1697         for ( i=0; i<num_values; i++ ) {
1698                 val = regval_ctr_specific_value( values, i );
1699                 len += tdb_pack(buf+len, buflen-len, "fdB",
1700                                 regval_name(val),
1701                                 regval_type(val),
1702                                 regval_size(val),
1703                                 regval_data_p(val) );
1704         }
1705
1706         return len;
1707 }
1708
1709 /***********************************************************************
1710  Retrieve an array of strings containing subkeys.  Memory should be
1711  released by the caller.
1712  ***********************************************************************/
1713
1714 static int regdb_fetch_values_internal(struct db_context *db, const char* key,
1715                                        struct regval_ctr *values)
1716 {
1717         char *keystr = NULL;
1718         TALLOC_CTX *ctx = talloc_stackframe();
1719         int ret = 0;
1720         TDB_DATA value;
1721         WERROR werr;
1722
1723         DEBUG(10,("regdb_fetch_values: Looking for value of key [%s] \n", key));
1724
1725         if (!regdb_key_exists(db, key)) {
1726                 goto done;
1727         }
1728
1729         keystr = talloc_asprintf(ctx, "%s\\%s", REG_VALUE_PREFIX, key);
1730         if (!keystr) {
1731                 goto done;
1732         }
1733
1734         werr = regval_ctr_set_seqnum(values, db->get_seqnum(db));
1735         W_ERROR_NOT_OK_GOTO_DONE(werr);
1736
1737         value = regdb_fetch_key_internal(db, ctx, keystr);
1738
1739         if (!value.dptr) {
1740                 /* all keys have zero values by default */
1741                 goto done;
1742         }
1743
1744         regdb_unpack_values(values, value.dptr, value.dsize);
1745         ret = regval_ctr_numvals(values);
1746
1747 done:
1748         TALLOC_FREE(ctx);
1749         return ret;
1750 }
1751
1752 int regdb_fetch_values(const char* key, struct regval_ctr *values)
1753 {
1754         return regdb_fetch_values_internal(regdb, key, values);
1755 }
1756
1757 static NTSTATUS regdb_store_values_internal(struct db_context *db,
1758                                             const char *key,
1759                                             struct regval_ctr *values)
1760 {
1761         TDB_DATA old_data, data;
1762         char *keystr = NULL;
1763         TALLOC_CTX *ctx = talloc_stackframe();
1764         int len;
1765         NTSTATUS status;
1766
1767         DEBUG(10,("regdb_store_values: Looking for value of key [%s] \n", key));
1768
1769         if (!regdb_key_exists(db, key)) {
1770                 status = NT_STATUS_NOT_FOUND;
1771                 goto done;
1772         }
1773
1774         ZERO_STRUCT(data);
1775
1776         len = regdb_pack_values(values, data.dptr, data.dsize);
1777         if (len <= 0) {
1778                 DEBUG(0,("regdb_store_values: unable to pack values. len <= 0\n"));
1779                 status = NT_STATUS_UNSUCCESSFUL;
1780                 goto done;
1781         }
1782
1783         data.dptr = talloc_array(ctx, uint8, len);
1784         data.dsize = len;
1785
1786         len = regdb_pack_values(values, data.dptr, data.dsize);
1787
1788         SMB_ASSERT( len == data.dsize );
1789
1790         keystr = talloc_asprintf(ctx, "%s\\%s", REG_VALUE_PREFIX, key );
1791         if (!keystr) {
1792                 status = NT_STATUS_NO_MEMORY;
1793                 goto done;
1794         }
1795         keystr = normalize_reg_path(ctx, keystr);
1796         if (!keystr) {
1797                 goto done;
1798         }
1799
1800         old_data = dbwrap_fetch_bystring(db, ctx, keystr);
1801
1802         if ((old_data.dptr != NULL)
1803             && (old_data.dsize == data.dsize)
1804             && (memcmp(old_data.dptr, data.dptr, data.dsize) == 0))
1805         {
1806                 status = NT_STATUS_OK;
1807                 goto done;
1808         }
1809
1810         status = dbwrap_trans_store_bystring(db, keystr, data, TDB_REPLACE);
1811
1812 done:
1813         TALLOC_FREE(ctx);
1814         return status;
1815 }
1816
1817 struct regdb_store_values_ctx {
1818         const char *key;
1819         struct regval_ctr *values;
1820 };
1821
1822 static NTSTATUS regdb_store_values_action(struct db_context *db,
1823                                           void *private_data)
1824 {
1825         NTSTATUS status;
1826         struct regdb_store_values_ctx *ctx =
1827                 (struct regdb_store_values_ctx *)private_data;
1828
1829         status = regdb_store_values_internal(db, ctx->key, ctx->values);
1830
1831         return status;
1832 }
1833
1834 bool regdb_store_values(const char *key, struct regval_ctr *values)
1835 {
1836         WERROR werr;
1837         struct regdb_store_values_ctx ctx;
1838
1839         ctx.key = key;
1840         ctx.values = values;
1841
1842         werr = regdb_trans_do(regdb, regdb_store_values_action, &ctx);
1843
1844         return W_ERROR_IS_OK(werr);
1845 }
1846
1847 static WERROR regdb_get_secdesc(TALLOC_CTX *mem_ctx, const char *key,
1848                                 struct security_descriptor **psecdesc)
1849 {
1850         char *tdbkey;
1851         TDB_DATA data;
1852         NTSTATUS status;
1853         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1854         WERROR err = WERR_OK;
1855
1856         DEBUG(10, ("regdb_get_secdesc: Getting secdesc of key [%s]\n", key));
1857
1858         if (!regdb_key_exists(regdb, key)) {
1859                 err = WERR_BADFILE;
1860                 goto done;
1861         }
1862
1863         tdbkey = talloc_asprintf(tmp_ctx, "%s\\%s", REG_SECDESC_PREFIX, key);
1864         if (tdbkey == NULL) {
1865                 err = WERR_NOMEM;
1866                 goto done;
1867         }
1868
1869         tdbkey = normalize_reg_path(tmp_ctx, tdbkey);
1870         if (tdbkey == NULL) {
1871                 err = WERR_NOMEM;
1872                 goto done;
1873         }
1874
1875         data = dbwrap_fetch_bystring(regdb, tmp_ctx, tdbkey);
1876         if (data.dptr == NULL) {
1877                 err = WERR_BADFILE;
1878                 goto done;
1879         }
1880
1881         status = unmarshall_sec_desc(mem_ctx, (uint8 *)data.dptr, data.dsize,
1882                                      psecdesc);
1883
1884         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1885                 err = WERR_NOMEM;
1886         } else if (!NT_STATUS_IS_OK(status)) {
1887                 err = WERR_REG_CORRUPT;
1888         }
1889
1890 done:
1891         TALLOC_FREE(tmp_ctx);
1892         return err;
1893 }
1894
1895 struct regdb_set_secdesc_ctx {
1896         const char *key;
1897         struct security_descriptor *secdesc;
1898 };
1899
1900 static NTSTATUS regdb_set_secdesc_action(struct db_context *db,
1901                                          void *private_data)
1902 {
1903         char *tdbkey;
1904         NTSTATUS status;
1905         TDB_DATA tdbdata;
1906         struct regdb_set_secdesc_ctx *ctx =
1907                 (struct regdb_set_secdesc_ctx *)private_data;
1908         TALLOC_CTX *frame = talloc_stackframe();
1909
1910         tdbkey = talloc_asprintf(frame, "%s\\%s", REG_SECDESC_PREFIX, ctx->key);
1911         if (tdbkey == NULL) {
1912                 goto done;
1913         }
1914
1915         tdbkey = normalize_reg_path(frame, tdbkey);
1916         if (tdbkey == NULL) {
1917                 status = NT_STATUS_NO_MEMORY;
1918                 goto done;
1919         }
1920
1921         if (ctx->secdesc == NULL) {
1922                 /* assuming a delete */
1923                 status = dbwrap_delete_bystring(db, tdbkey);
1924                 goto done;
1925         }
1926
1927         status = marshall_sec_desc(frame, ctx->secdesc, &tdbdata.dptr,
1928                                    &tdbdata.dsize);
1929         if (!NT_STATUS_IS_OK(status)) {
1930                 goto done;
1931         }
1932
1933         status = dbwrap_store_bystring(db, tdbkey, tdbdata, 0);
1934
1935 done:
1936         TALLOC_FREE(frame);
1937         return status;
1938 }
1939
1940 static WERROR regdb_set_secdesc(const char *key,
1941                                 struct security_descriptor *secdesc)
1942 {
1943         WERROR err;
1944         struct regdb_set_secdesc_ctx ctx;
1945
1946         if (!regdb_key_exists(regdb, key)) {
1947                 err = WERR_BADFILE;
1948                 goto done;
1949         }
1950
1951         ctx.key = key;
1952         ctx.secdesc = secdesc;
1953
1954         err = regdb_trans_do(regdb, regdb_set_secdesc_action, &ctx);
1955
1956 done:
1957         return err;
1958 }
1959
1960 bool regdb_subkeys_need_update(struct regsubkey_ctr *subkeys)
1961 {
1962         return (regdb_get_seqnum() != regsubkey_ctr_get_seqnum(subkeys));
1963 }
1964
1965 bool regdb_values_need_update(struct regval_ctr *values)
1966 {
1967         return (regdb_get_seqnum() != regval_ctr_get_seqnum(values));
1968 }
1969
1970 /*
1971  * Table of function pointers for default access
1972  */
1973
1974 struct registry_ops regdb_ops = {
1975         .fetch_subkeys = regdb_fetch_keys,
1976         .fetch_values = regdb_fetch_values,
1977         .store_subkeys = regdb_store_keys,
1978         .store_values = regdb_store_values,
1979         .create_subkey = regdb_create_subkey,
1980         .delete_subkey = regdb_delete_subkey,
1981         .get_secdesc = regdb_get_secdesc,
1982         .set_secdesc = regdb_set_secdesc,
1983         .subkeys_need_update = regdb_subkeys_need_update,
1984         .values_need_update = regdb_values_need_update
1985 };