s3:registry: refactor deletion of value/secdesc/subkey list tdb records out
[Samba.git] / source3 / registry / reg_backend_db.c
blobee0e81f680be2137ddced766a34fa856ffd09843
1 /*
2 * Unix SMB/CIFS implementation.
3 * Virtual Windows Registry Layer
4 * Copyright (C) Gerald Carter 2002-2005
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 /* Implementation of internal registry database functions. */
22 #include "includes.h"
24 #undef DBGC_CLASS
25 #define DBGC_CLASS DBGC_REGISTRY
27 static struct db_context *regdb = NULL;
28 static int regdb_refcount;
30 static bool regdb_key_exists(const char *key);
31 static bool regdb_key_is_base_key(const char *key);
33 /* List the deepest path into the registry. All part components will be created.*/
35 /* If you want to have a part of the path controlled by the tdb and part by
36 a virtual registry db (e.g. printing), then you have to list the deepest path.
37 For example,"HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion/Print"
38 allows the reg_db backend to handle everything up to
39 "HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion" and then we'll hook
40 the reg_printing backend onto the last component of the path (see
41 KEY_PRINTING_2K in include/rpc_reg.h) --jerry */
43 static const char *builtin_registry_paths[] = {
44 KEY_PRINTING_2K,
45 KEY_PRINTING_PORTS,
46 KEY_PRINTING,
47 KEY_SHARES,
48 KEY_EVENTLOG,
49 KEY_SMBCONF,
50 KEY_PERFLIB,
51 KEY_PERFLIB_009,
52 KEY_GROUP_POLICY,
53 KEY_SAMBA_GROUP_POLICY,
54 KEY_GP_MACHINE_POLICY,
55 KEY_GP_MACHINE_WIN_POLICY,
56 KEY_HKCU,
57 KEY_GP_USER_POLICY,
58 KEY_GP_USER_WIN_POLICY,
59 KEY_WINLOGON_GPEXT_PATH,
60 "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Print\\Monitors",
61 KEY_PROD_OPTIONS,
62 "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\DefaultUserConfiguration",
63 KEY_TCPIP_PARAMS,
64 KEY_NETLOGON_PARAMS,
65 KEY_HKU,
66 KEY_HKCR,
67 KEY_HKPD,
68 KEY_HKPT,
69 NULL };
71 struct builtin_regkey_value {
72 const char *path;
73 const char *valuename;
74 uint32 type;
75 union {
76 const char *string;
77 uint32 dw_value;
78 } data;
81 static struct builtin_regkey_value builtin_registry_values[] = {
82 { KEY_PRINTING_PORTS,
83 SAMBA_PRINTER_PORT_NAME, REG_SZ, { "" } },
84 { KEY_PRINTING_2K,
85 "DefaultSpoolDirectory", REG_SZ, { "C:\\Windows\\System32\\Spool\\Printers" } },
86 { KEY_EVENTLOG,
87 "DisplayName", REG_SZ, { "Event Log" } },
88 { KEY_EVENTLOG,
89 "ErrorControl", REG_DWORD, { (char*)0x00000001 } },
90 { NULL, NULL, 0, { NULL } }
93 /**
94 * Initialize a key in the registry:
95 * create each component key of the specified path.
97 static WERROR init_registry_key_internal(const char *add_path)
99 WERROR werr;
100 TALLOC_CTX *frame = talloc_stackframe();
101 char *path = NULL;
102 char *base = NULL;
103 char *remaining = NULL;
104 char *keyname;
105 char *subkeyname;
106 struct regsubkey_ctr *subkeys;
107 const char *p, *p2;
109 DEBUG(6, ("init_registry_key: Adding [%s]\n", add_path));
111 path = talloc_strdup(frame, add_path);
112 base = talloc_strdup(frame, "");
113 if (!path || !base) {
114 werr = WERR_NOMEM;
115 goto fail;
117 p = path;
119 while (next_token_talloc(frame, &p, &keyname, "\\")) {
121 /* build up the registry path from the components */
123 if (*base) {
124 base = talloc_asprintf(frame, "%s\\", base);
125 if (!base) {
126 werr = WERR_NOMEM;
127 goto fail;
130 base = talloc_asprintf_append(base, "%s", keyname);
131 if (!base) {
132 werr = WERR_NOMEM;
133 goto fail;
136 /* get the immediate subkeyname (if we have one ) */
138 subkeyname = talloc_strdup(frame, "");
139 if (!subkeyname) {
140 werr = WERR_NOMEM;
141 goto fail;
143 if (*p) {
144 remaining = talloc_strdup(frame, p);
145 if (!remaining) {
146 werr = WERR_NOMEM;
147 goto fail;
149 p2 = remaining;
151 if (!next_token_talloc(frame, &p2,
152 &subkeyname, "\\"))
154 subkeyname = talloc_strdup(frame,p2);
155 if (!subkeyname) {
156 werr = WERR_NOMEM;
157 goto fail;
162 DEBUG(10,("init_registry_key: Storing key [%s] with "
163 "subkey [%s]\n", base,
164 *subkeyname ? subkeyname : "NULL"));
166 /* we don't really care if the lookup succeeds or not
167 * since we are about to update the record.
168 * We just want any subkeys already present */
170 werr = regsubkey_ctr_init(frame, &subkeys);
171 if (!W_ERROR_IS_OK(werr)) {
172 DEBUG(0,("talloc() failure!\n"));
173 goto fail;
176 regdb_fetch_keys(base, subkeys);
177 if (*subkeyname) {
178 werr = regsubkey_ctr_addkey(subkeys, subkeyname);
179 if (!W_ERROR_IS_OK(werr)) {
180 goto fail;
183 if (!regdb_store_keys( base, subkeys)) {
184 werr = WERR_CAN_NOT_COMPLETE;
185 goto fail;
189 werr = WERR_OK;
191 fail:
192 TALLOC_FREE(frame);
193 return werr;
197 * Initialize a key in the registry:
198 * create each component key of the specified path,
199 * wrapped in one db transaction.
201 WERROR init_registry_key(const char *add_path)
203 WERROR werr;
205 if (regdb_key_exists(add_path)) {
206 return WERR_OK;
209 if (regdb->transaction_start(regdb) != 0) {
210 DEBUG(0, ("init_registry_key: transaction_start failed\n"));
211 return WERR_REG_IO_FAILURE;
214 werr = init_registry_key_internal(add_path);
215 if (!W_ERROR_IS_OK(werr)) {
216 goto fail;
219 if (regdb->transaction_commit(regdb) != 0) {
220 DEBUG(0, ("init_registry_key: Could not commit transaction\n"));
221 return WERR_REG_IO_FAILURE;
224 return WERR_OK;
226 fail:
227 if (regdb->transaction_cancel(regdb) != 0) {
228 smb_panic("init_registry_key: transaction_cancel failed\n");
231 return werr;
234 /***********************************************************************
235 Open the registry data in the tdb
236 ***********************************************************************/
238 WERROR init_registry_data(void)
240 WERROR werr;
241 TALLOC_CTX *frame = talloc_stackframe();
242 REGVAL_CTR *values;
243 int i;
244 UNISTR2 data;
247 * First, check for the existence of the needed keys and values.
248 * If all do already exist, we can save the writes.
250 for (i=0; builtin_registry_paths[i] != NULL; i++) {
251 if (!regdb_key_exists(builtin_registry_paths[i])) {
252 goto do_init;
256 for (i=0; builtin_registry_values[i].path != NULL; i++) {
257 values = TALLOC_ZERO_P(frame, REGVAL_CTR);
258 if (values == NULL) {
259 werr = WERR_NOMEM;
260 goto done;
263 regdb_fetch_values(builtin_registry_values[i].path, values);
264 if (!regval_ctr_key_exists(values,
265 builtin_registry_values[i].valuename))
267 TALLOC_FREE(values);
268 goto do_init;
271 TALLOC_FREE(values);
274 werr = WERR_OK;
275 goto done;
277 do_init:
280 * There are potentially quite a few store operations which are all
281 * indiviually wrapped in tdb transactions. Wrapping them in a single
282 * transaction gives just a single transaction_commit() to actually do
283 * its fsync()s. See tdb/common/transaction.c for info about nested
284 * transaction behaviour.
287 if (regdb->transaction_start(regdb) != 0) {
288 DEBUG(0, ("init_registry_data: tdb_transaction_start "
289 "failed\n"));
290 werr = WERR_REG_IO_FAILURE;
291 goto done;
294 /* loop over all of the predefined paths and add each component */
296 for (i=0; builtin_registry_paths[i] != NULL; i++) {
297 if (regdb_key_exists(builtin_registry_paths[i])) {
298 continue;
300 werr = init_registry_key_internal(builtin_registry_paths[i]);
301 if (!W_ERROR_IS_OK(werr)) {
302 goto fail;
306 /* loop over all of the predefined values and add each component */
308 for (i=0; builtin_registry_values[i].path != NULL; i++) {
310 values = TALLOC_ZERO_P(frame, REGVAL_CTR);
311 if (values == NULL) {
312 werr = WERR_NOMEM;
313 goto fail;
316 regdb_fetch_values(builtin_registry_values[i].path, values);
318 /* preserve existing values across restarts. Only add new ones */
320 if (!regval_ctr_key_exists(values,
321 builtin_registry_values[i].valuename))
323 switch(builtin_registry_values[i].type) {
324 case REG_DWORD:
325 regval_ctr_addvalue(values,
326 builtin_registry_values[i].valuename,
327 REG_DWORD,
328 (char*)&builtin_registry_values[i].data.dw_value,
329 sizeof(uint32));
330 break;
332 case REG_SZ:
333 init_unistr2(&data,
334 builtin_registry_values[i].data.string,
335 UNI_STR_TERMINATE);
336 regval_ctr_addvalue(values,
337 builtin_registry_values[i].valuename,
338 REG_SZ,
339 (char*)data.buffer,
340 data.uni_str_len*sizeof(uint16));
341 break;
343 default:
344 DEBUG(0, ("init_registry_data: invalid value "
345 "type in builtin_registry_values "
346 "[%d]\n",
347 builtin_registry_values[i].type));
349 regdb_store_values(builtin_registry_values[i].path,
350 values);
352 TALLOC_FREE(values);
355 if (regdb->transaction_commit(regdb) != 0) {
356 DEBUG(0, ("init_registry_data: Could not commit "
357 "transaction\n"));
358 werr = WERR_REG_IO_FAILURE;
359 } else {
360 werr = WERR_OK;
363 goto done;
365 fail:
366 if (regdb->transaction_cancel(regdb) != 0) {
367 smb_panic("init_registry_data: tdb_transaction_cancel "
368 "failed\n");
371 done:
372 TALLOC_FREE(frame);
373 return werr;
376 /***********************************************************************
377 Open the registry database
378 ***********************************************************************/
380 WERROR regdb_init(void)
382 const char *vstring = "INFO/version";
383 uint32 vers_id;
384 WERROR werr;
386 if (regdb) {
387 DEBUG(10, ("regdb_init: incrementing refcount (%d)\n",
388 regdb_refcount));
389 regdb_refcount++;
390 return WERR_OK;
393 regdb = db_open(NULL, state_path("registry.tdb"), 0,
394 REG_TDB_FLAGS, O_RDWR, 0600);
395 if (!regdb) {
396 regdb = db_open(NULL, state_path("registry.tdb"), 0,
397 REG_TDB_FLAGS, O_RDWR|O_CREAT, 0600);
398 if (!regdb) {
399 werr = ntstatus_to_werror(map_nt_error_from_unix(errno));
400 DEBUG(1,("regdb_init: Failed to open registry %s (%s)\n",
401 state_path("registry.tdb"), strerror(errno) ));
402 return werr;
405 DEBUG(10,("regdb_init: Successfully created registry tdb\n"));
408 regdb_refcount = 1;
410 vers_id = dbwrap_fetch_int32(regdb, vstring);
412 if ( vers_id != REGVER_V1 ) {
413 NTSTATUS status;
414 /* any upgrade code here if needed */
415 DEBUG(10, ("regdb_init: got %s = %d != %d\n", vstring,
416 vers_id, REGVER_V1));
417 status = dbwrap_trans_store_int32(regdb, vstring, REGVER_V1);
418 if (!NT_STATUS_IS_OK(status)) {
419 DEBUG(1, ("regdb_init: error storing %s = %d: %s\n",
420 vstring, REGVER_V1, nt_errstr(status)));
421 return ntstatus_to_werror(status);
422 } else {
423 DEBUG(10, ("regdb_init: stored %s = %d\n",
424 vstring, REGVER_V1));
428 return WERR_OK;
431 /***********************************************************************
432 Open the registry. Must already have been initialized by regdb_init()
433 ***********************************************************************/
435 WERROR regdb_open( void )
437 WERROR result = WERR_OK;
439 if ( regdb ) {
440 DEBUG(10,("regdb_open: incrementing refcount (%d)\n", regdb_refcount));
441 regdb_refcount++;
442 return WERR_OK;
445 become_root();
447 regdb = db_open(NULL, state_path("registry.tdb"), 0,
448 REG_TDB_FLAGS, O_RDWR, 0600);
449 if ( !regdb ) {
450 result = ntstatus_to_werror( map_nt_error_from_unix( errno ) );
451 DEBUG(0,("regdb_open: Failed to open %s! (%s)\n",
452 state_path("registry.tdb"), strerror(errno) ));
455 unbecome_root();
457 regdb_refcount = 1;
458 DEBUG(10,("regdb_open: refcount reset (%d)\n", regdb_refcount));
460 return result;
463 /***********************************************************************
464 ***********************************************************************/
466 int regdb_close( void )
468 if (regdb_refcount == 0) {
469 return 0;
472 regdb_refcount--;
474 DEBUG(10,("regdb_close: decrementing refcount (%d)\n", regdb_refcount));
476 if ( regdb_refcount > 0 )
477 return 0;
479 SMB_ASSERT( regdb_refcount >= 0 );
481 TALLOC_FREE(regdb);
482 return 0;
485 WERROR regdb_transaction_start(void)
487 return (regdb->transaction_start(regdb) == 0) ?
488 WERR_OK : WERR_REG_IO_FAILURE;
491 WERROR regdb_transaction_commit(void)
493 return (regdb->transaction_commit(regdb) == 0) ?
494 WERR_OK : WERR_REG_IO_FAILURE;
497 WERROR regdb_transaction_cancel(void)
499 return (regdb->transaction_cancel(regdb) == 0) ?
500 WERR_OK : WERR_REG_IO_FAILURE;
503 /***********************************************************************
504 return the tdb sequence number of the registry tdb.
505 this is an indicator for the content of the registry
506 having changed. it will change upon regdb_init, too, though.
507 ***********************************************************************/
508 int regdb_get_seqnum(void)
510 return regdb->get_seqnum(regdb);
514 static WERROR regdb_delete_key_with_prefix(const char *keyname,
515 const char *prefix)
517 char *path;
518 WERROR werr = WERR_NOMEM;
519 TALLOC_CTX *mem_ctx = talloc_stackframe();
521 if (keyname == NULL) {
522 werr = WERR_INVALID_PARAM;
523 goto done;
526 if (prefix == NULL) {
527 path = discard_const_p(char, keyname);
528 } else {
529 path = talloc_asprintf(mem_ctx, "%s/%s", prefix, keyname);
530 if (path == NULL) {
531 goto done;
535 path = normalize_reg_path(mem_ctx, path);
536 if (path == NULL) {
537 goto done;
540 werr = ntstatus_to_werror(dbwrap_delete_bystring(regdb, path));
542 /* treat "not" found" as ok */
543 if (W_ERROR_EQUAL(werr, WERR_NOT_FOUND)) {
544 werr = WERR_OK;
547 done:
548 talloc_free(mem_ctx);
549 return werr;
553 static WERROR regdb_delete_values(const char *keyname)
555 return regdb_delete_key_with_prefix(keyname, REG_VALUE_PREFIX);
558 static WERROR regdb_delete_secdesc(const char *keyname)
560 return regdb_delete_key_with_prefix(keyname, REG_SECDESC_PREFIX);
563 static WERROR regdb_delete_subkeylist(const char *keyname)
565 return regdb_delete_key_with_prefix(keyname, NULL);
568 /***********************************************************************
569 Add subkey strings to the registry tdb under a defined key
570 fmt is the same format as tdb_pack except this function only supports
571 fstrings
572 ***********************************************************************/
574 static bool regdb_store_keys_internal(const char *key, struct regsubkey_ctr *ctr)
576 TDB_DATA dbuf;
577 uint8 *buffer = NULL;
578 int i = 0;
579 uint32 len, buflen;
580 bool ret = true;
581 uint32 num_subkeys = regsubkey_ctr_numkeys(ctr);
582 char *keyname = NULL;
583 TALLOC_CTX *ctx = talloc_stackframe();
584 NTSTATUS status;
586 if (!key) {
587 return false;
590 keyname = talloc_strdup(ctx, key);
591 if (!keyname) {
592 return false;
594 keyname = normalize_reg_path(ctx, keyname);
596 /* allocate some initial memory */
598 buffer = (uint8 *)SMB_MALLOC(1024);
599 if (buffer == NULL) {
600 return false;
602 buflen = 1024;
603 len = 0;
605 /* store the number of subkeys */
607 len += tdb_pack(buffer+len, buflen-len, "d", num_subkeys);
609 /* pack all the strings */
611 for (i=0; i<num_subkeys; i++) {
612 size_t thistime;
614 thistime = tdb_pack(buffer+len, buflen-len, "f",
615 regsubkey_ctr_specific_key(ctr, i));
616 if (len+thistime > buflen) {
617 size_t thistime2;
619 * tdb_pack hasn't done anything because of the short
620 * buffer, allocate extra space.
622 buffer = SMB_REALLOC_ARRAY(buffer, uint8_t,
623 (len+thistime)*2);
624 if(buffer == NULL) {
625 DEBUG(0, ("regdb_store_keys: Failed to realloc "
626 "memory of size [%u]\n",
627 (unsigned int)(len+thistime)*2));
628 ret = false;
629 goto done;
631 buflen = (len+thistime)*2;
632 thistime2 = tdb_pack(
633 buffer+len, buflen-len, "f",
634 regsubkey_ctr_specific_key(ctr, i));
635 if (thistime2 != thistime) {
636 DEBUG(0, ("tdb_pack failed\n"));
637 ret = false;
638 goto done;
641 len += thistime;
644 /* finally write out the data */
646 dbuf.dptr = buffer;
647 dbuf.dsize = len;
648 status = dbwrap_store_bystring(regdb, keyname, dbuf, TDB_REPLACE);
649 if (!NT_STATUS_IS_OK(status)) {
650 ret = false;
651 goto done;
655 * Delete a sorted subkey cache for regdb_key_exists, will be
656 * recreated automatically
658 keyname = talloc_asprintf(ctx, "%s/%s", REG_SORTED_SUBKEYS_PREFIX,
659 keyname);
660 if (keyname != NULL) {
661 dbwrap_delete_bystring(regdb, keyname);
664 done:
665 TALLOC_FREE(ctx);
666 SAFE_FREE(buffer);
667 return ret;
670 /***********************************************************************
671 Store the new subkey record and create any child key records that
672 do not currently exist
673 ***********************************************************************/
675 bool regdb_store_keys(const char *key, struct regsubkey_ctr *ctr)
677 int num_subkeys, old_num_subkeys, i;
678 char *path = NULL;
679 struct regsubkey_ctr *subkeys = NULL, *old_subkeys = NULL;
680 char *oldkeyname = NULL;
681 TALLOC_CTX *ctx = talloc_stackframe();
682 WERROR werr;
684 if (!regdb_key_is_base_key(key) && !regdb_key_exists(key)) {
685 goto fail;
689 * fetch a list of the old subkeys so we can determine if anything has
690 * changed
693 werr = regsubkey_ctr_init(ctx, &old_subkeys);
694 if (!W_ERROR_IS_OK(werr)) {
695 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
696 return false;
699 regdb_fetch_keys(key, old_subkeys);
701 num_subkeys = regsubkey_ctr_numkeys(ctr);
702 old_num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
703 if ((num_subkeys && old_num_subkeys) &&
704 (num_subkeys == old_num_subkeys)) {
706 for (i = 0; i < num_subkeys; i++) {
707 if (strcmp(regsubkey_ctr_specific_key(ctr, i),
708 regsubkey_ctr_specific_key(old_subkeys, i))
709 != 0)
711 break;
714 if (i == num_subkeys) {
716 * Nothing changed, no point to even start a tdb
717 * transaction
719 TALLOC_FREE(old_subkeys);
720 return true;
724 TALLOC_FREE(old_subkeys);
726 if (regdb->transaction_start(regdb) != 0) {
727 DEBUG(0, ("regdb_store_keys: transaction_start failed\n"));
728 goto fail;
732 * Re-fetch the old keys inside the transaction
735 werr = regsubkey_ctr_init(ctx, &old_subkeys);
736 if (!W_ERROR_IS_OK(werr)) {
737 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
738 goto cancel;
741 regdb_fetch_keys(key, old_subkeys);
744 * Make the store operation as safe as possible without transactions:
746 * (1) For each subkey removed from ctr compared with old_subkeys:
748 * (a) First delete the value db entry.
750 * (b) Next delete the secdesc db record.
752 * (c) Then delete the subkey list entry.
754 * (2) Now write the list of subkeys of the parent key,
755 * deleting removed entries and adding new ones.
757 * (3) Finally create the subkey list entries for the added keys.
759 * This way if we crash half-way in between deleting the subkeys
760 * and storing the parent's list of subkeys, no old data can pop up
761 * out of the blue when re-adding keys later on.
764 /* (1) delete removed keys' lists (values/secdesc/subkeys) */
766 num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
767 for (i=0; i<num_subkeys; i++) {
768 oldkeyname = regsubkey_ctr_specific_key(old_subkeys, i);
770 if (regsubkey_ctr_key_exists(ctr, oldkeyname)) {
772 * It's still around, don't delete
775 continue;
778 path = talloc_asprintf(ctx, "%s/%s", key, oldkeyname);
779 if (!path) {
780 goto cancel;
782 path = normalize_reg_path(ctx, path);
783 if (!path) {
784 goto cancel;
787 /* (a) Delete the value list for this key */
789 werr = regdb_delete_values(path);
790 if (!W_ERROR_IS_OK(werr)) {
791 DEBUG(1, (__location__ " Deleting %s/%s failed: %s\n",
792 REG_VALUE_PREFIX, path, win_errstr(werr)));
793 goto cancel;
796 /* (b) Delete the secdesc for this key */
798 werr = regdb_delete_secdesc(path);
799 if (!W_ERROR_IS_OK(werr)) {
800 DEBUG(1, (__location__ " Deleting %s/%s failed: %s\n",
801 REG_SECDESC_PREFIX, path, win_errstr(werr)));
802 goto cancel;
805 /* (c) Delete the list of subkeys of this key */
807 werr = regdb_delete_subkeylist(path);
808 if (!W_ERROR_IS_OK(werr)) {
809 DEBUG(1, (__location__ " Deleting %s failed: %s\n",
810 path, win_errstr(werr)));
811 goto cancel;
814 TALLOC_FREE(path);
817 TALLOC_FREE(old_subkeys);
819 /* (2) store the subkey list for the parent */
821 if (!regdb_store_keys_internal(key, ctr) ) {
822 DEBUG(0,("regdb_store_keys: Failed to store new subkey list "
823 "for parent [%s]\n", key));
824 goto cancel;
827 /* (3) now create records for any subkeys that don't already exist */
829 num_subkeys = regsubkey_ctr_numkeys(ctr);
831 if (num_subkeys == 0) {
832 werr = regsubkey_ctr_init(ctx, &subkeys);
833 if (!W_ERROR_IS_OK(werr)) {
834 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
835 goto cancel;
838 if (!regdb_store_keys_internal(key, subkeys)) {
839 DEBUG(0,("regdb_store_keys: Failed to store "
840 "new record for key [%s]\n", key));
841 goto cancel;
843 TALLOC_FREE(subkeys);
847 for (i=0; i<num_subkeys; i++) {
848 path = talloc_asprintf(ctx, "%s/%s",
849 key,
850 regsubkey_ctr_specific_key(ctr, i));
851 if (!path) {
852 goto cancel;
854 werr = regsubkey_ctr_init(ctx, &subkeys);
855 if (!W_ERROR_IS_OK(werr)) {
856 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
857 goto cancel;
860 if (regdb_fetch_keys( path, subkeys ) == -1) {
861 /* create a record with 0 subkeys */
862 if (!regdb_store_keys_internal(path, subkeys)) {
863 DEBUG(0,("regdb_store_keys: Failed to store "
864 "new record for key [%s]\n", path));
865 goto cancel;
869 TALLOC_FREE(subkeys);
870 TALLOC_FREE(path);
873 if (regdb->transaction_commit(regdb) != 0) {
874 DEBUG(0, ("regdb_store_keys: Could not commit transaction\n"));
875 goto fail;
878 TALLOC_FREE(ctx);
879 return true;
881 cancel:
882 if (regdb->transaction_cancel(regdb) != 0) {
883 smb_panic("regdb_store_keys: transaction_cancel failed\n");
886 fail:
887 TALLOC_FREE(ctx);
889 return false;
892 static WERROR regdb_create_subkey(const char *key, const char *subkey)
894 WERROR werr;
895 struct regsubkey_ctr *subkeys;
896 TALLOC_CTX *mem_ctx = talloc_stackframe();
898 if (!regdb_key_is_base_key(key) && !regdb_key_exists(key)) {
899 werr = WERR_NOT_FOUND;
900 goto done;
903 werr = regsubkey_ctr_init(mem_ctx, &subkeys);
904 W_ERROR_NOT_OK_GOTO_DONE(werr);
906 if (regdb_fetch_keys(key, subkeys) < 0) {
907 werr = WERR_REG_IO_FAILURE;
908 goto done;
911 if (regsubkey_ctr_key_exists(subkeys, subkey)) {
912 werr = WERR_OK;
913 goto done;
916 talloc_free(subkeys);
918 werr = regdb_transaction_start();
919 W_ERROR_NOT_OK_GOTO_DONE(werr);
921 werr = regsubkey_ctr_init(mem_ctx, &subkeys);
922 W_ERROR_NOT_OK_GOTO(werr, cancel);
924 if (regdb_fetch_keys(key, subkeys) < 0) {
925 werr = WERR_REG_IO_FAILURE;
926 goto cancel;
929 werr = regsubkey_ctr_addkey(subkeys, subkey);
930 W_ERROR_NOT_OK_GOTO(werr, cancel);
932 if (!regdb_store_keys_internal(key, subkeys)) {
933 DEBUG(0, (__location__ " failed to store new subkey list for "
934 "parent key %s\n", key));
935 werr = WERR_REG_IO_FAILURE;
936 goto cancel;
939 werr = regdb_transaction_commit();
940 if (!W_ERROR_IS_OK(werr)) {
941 DEBUG(0, (__location__ " failed to commit transaction: %s\n",
942 win_errstr(werr)));
945 goto done;
947 cancel:
948 werr = regdb_transaction_cancel();
949 if (!W_ERROR_IS_OK(werr)) {
950 DEBUG(0, (__location__ " failed to cancel transaction: %s\n",
951 win_errstr(werr)));
954 done:
955 talloc_free(mem_ctx);
956 return werr;
959 static TDB_DATA regdb_fetch_key_internal(TALLOC_CTX *mem_ctx, const char *key)
961 char *path = NULL;
962 TDB_DATA data;
964 path = normalize_reg_path(mem_ctx, key);
965 if (!path) {
966 return make_tdb_data(NULL, 0);
969 data = dbwrap_fetch_bystring(regdb, mem_ctx, path);
971 TALLOC_FREE(path);
972 return data;
977 * check whether a given key name represents a base key,
978 * i.e one without a subkey separator ('/' or '\').
980 static bool regdb_key_is_base_key(const char *key)
982 TALLOC_CTX *mem_ctx = talloc_stackframe();
983 bool ret = false;
984 char *path;
986 if (key == NULL) {
987 goto done;
990 path = normalize_reg_path(mem_ctx, key);
991 if (path == NULL) {
992 DEBUG(0, ("out of memory! (talloc failed)\n"));
993 goto done;
996 if (*path == '\0') {
997 goto done;
1000 ret = (strrchr(path, '/') == NULL);
1002 done:
1003 TALLOC_FREE(mem_ctx);
1004 return ret;
1008 * regdb_key_exists() is a very frequent operation. It can be quite
1009 * time-consuming to fully fetch the parent's subkey list, talloc_strdup all
1010 * subkeys and then compare the keyname linearly to all the parent's subkeys.
1012 * The following code tries to make this operation as efficient as possible:
1013 * Per registry key we create a list of subkeys that is very efficient to
1014 * search for existence of a subkey. Its format is:
1016 * 4 bytes num_subkeys
1017 * 4*num_subkey bytes offset into the string array
1018 * then follows a sorted list of subkeys in uppercase
1020 * This record is created by create_sorted_subkeys() on demand if it does not
1021 * exist. scan_parent_subkeys() uses regdb->parse_record to search the sorted
1022 * list, the parsing code and the binary search can be found in
1023 * parent_subkey_scanner. The code uses parse_record() to avoid a memcpy of
1024 * the potentially large subkey record.
1026 * The sorted subkey record is deleted in regdb_store_keys_internal and
1027 * recreated on demand.
1030 static int cmp_keynames(const void *p1, const void *p2)
1032 return StrCaseCmp(*((char **)p1), *((char **)p2));
1035 static bool create_sorted_subkeys(const char *key, const char *sorted_keyname)
1037 char **sorted_subkeys;
1038 struct regsubkey_ctr *ctr;
1039 bool result = false;
1040 NTSTATUS status;
1041 char *buf;
1042 char *p;
1043 int i, res;
1044 size_t len;
1045 int num_subkeys;
1046 WERROR werr;
1048 if (regdb->transaction_start(regdb) != 0) {
1049 DEBUG(0, ("create_sorted_subkeys: transaction_start "
1050 "failed\n"));
1051 return false;
1054 werr = regsubkey_ctr_init(talloc_tos(), &ctr);
1055 if (!W_ERROR_IS_OK(werr)) {
1056 goto fail;
1059 res = regdb_fetch_keys(key, ctr);
1060 if (res == -1) {
1061 goto fail;
1064 num_subkeys = regsubkey_ctr_numkeys(ctr);
1065 sorted_subkeys = talloc_array(ctr, char *, num_subkeys);
1066 if (sorted_subkeys == NULL) {
1067 goto fail;
1070 len = 4 + 4*num_subkeys;
1072 for (i = 0; i < num_subkeys; i++) {
1073 sorted_subkeys[i] = talloc_strdup_upper(sorted_subkeys,
1074 regsubkey_ctr_specific_key(ctr, i));
1075 if (sorted_subkeys[i] == NULL) {
1076 goto fail;
1078 len += strlen(sorted_subkeys[i])+1;
1081 qsort(sorted_subkeys, num_subkeys, sizeof(char *), cmp_keynames);
1083 buf = talloc_array(ctr, char, len);
1084 if (buf == NULL) {
1085 goto fail;
1087 p = buf + 4 + 4*num_subkeys;
1089 SIVAL(buf, 0, num_subkeys);
1091 for (i=0; i < num_subkeys; i++) {
1092 ptrdiff_t offset = p - buf;
1093 SIVAL(buf, 4 + 4*i, offset);
1094 strlcpy(p, sorted_subkeys[i], len-offset);
1095 p += strlen(sorted_subkeys[i]) + 1;
1098 status = dbwrap_store_bystring(
1099 regdb, sorted_keyname, make_tdb_data((uint8_t *)buf, len),
1100 TDB_REPLACE);
1101 if (!NT_STATUS_IS_OK(status)) {
1103 * Don't use a "goto fail;" here, this would commit the broken
1104 * transaction. See below for an explanation.
1106 if (regdb->transaction_cancel(regdb) == -1) {
1107 DEBUG(0, ("create_sorted_subkeys: transaction_cancel "
1108 "failed\n"));
1110 TALLOC_FREE(ctr);
1111 return false;
1114 result = true;
1115 fail:
1117 * We only get here via the "goto fail" when we did not write anything
1118 * yet. Using transaction_commit even in a failure case is necessary
1119 * because this (disposable) call might be nested in other
1120 * transactions. Doing a cancel here would destroy the possibility of
1121 * a transaction_commit for transactions that we might be wrapped in.
1123 if (regdb->transaction_commit(regdb) == -1) {
1124 DEBUG(0, ("create_sorted_subkeys: transaction_start "
1125 "failed\n"));
1126 goto fail;
1129 TALLOC_FREE(ctr);
1130 return result;
1133 struct scan_subkey_state {
1134 char *name;
1135 bool scanned;
1136 bool found;
1139 static int parent_subkey_scanner(TDB_DATA key, TDB_DATA data,
1140 void *private_data)
1142 struct scan_subkey_state *state =
1143 (struct scan_subkey_state *)private_data;
1144 uint32_t num_subkeys;
1145 uint32_t l, u;
1147 if (data.dsize < sizeof(uint32_t)) {
1148 return -1;
1151 state->scanned = true;
1152 state->found = false;
1154 tdb_unpack(data.dptr, data.dsize, "d", &num_subkeys);
1156 l = 0;
1157 u = num_subkeys;
1159 while (l < u) {
1160 uint32_t idx = (l+u)/2;
1161 char *s = (char *)data.dptr + IVAL(data.dptr, 4 + 4*idx);
1162 int comparison = strcmp(state->name, s);
1164 if (comparison < 0) {
1165 u = idx;
1166 } else if (comparison > 0) {
1167 l = idx + 1;
1168 } else {
1169 state->found = true;
1170 return 0;
1173 return 0;
1176 static bool scan_parent_subkeys(const char *parent, const char *name)
1178 char *path = NULL;
1179 char *key = NULL;
1180 struct scan_subkey_state state = { 0, };
1181 bool result = false;
1182 int res;
1184 state.name = NULL;
1186 path = normalize_reg_path(talloc_tos(), parent);
1187 if (path == NULL) {
1188 goto fail;
1191 key = talloc_asprintf(talloc_tos(), "%s/%s",
1192 REG_SORTED_SUBKEYS_PREFIX, path);
1193 if (key == NULL) {
1194 goto fail;
1197 state.name = talloc_strdup_upper(talloc_tos(), name);
1198 if (state.name == NULL) {
1199 goto fail;
1201 state.scanned = false;
1203 res = regdb->parse_record(regdb, string_term_tdb_data(key),
1204 parent_subkey_scanner, &state);
1206 if (state.scanned) {
1207 result = state.found;
1208 } else {
1209 if (!create_sorted_subkeys(path, key)) {
1210 goto fail;
1212 res = regdb->parse_record(regdb, string_term_tdb_data(key),
1213 parent_subkey_scanner, &state);
1214 if ((res == 0) && (state.scanned)) {
1215 result = state.found;
1219 fail:
1220 TALLOC_FREE(path);
1221 TALLOC_FREE(state.name);
1222 return result;
1226 * Check for the existence of a key.
1228 * Existence of a key is authoritatively defined by its
1229 * existence in the list of subkeys of its parent key.
1230 * The exeption of this are keys without a parent key,
1231 * i.e. the "base" keys (HKLM, HKCU, ...).
1233 static bool regdb_key_exists(const char *key)
1235 TALLOC_CTX *mem_ctx = talloc_stackframe();
1236 TDB_DATA value;
1237 bool ret = false;
1238 char *path, *p;
1240 if (key == NULL) {
1241 goto done;
1244 path = normalize_reg_path(mem_ctx, key);
1245 if (path == NULL) {
1246 DEBUG(0, ("out of memory! (talloc failed)\n"));
1247 goto done;
1250 if (*path == '\0') {
1251 goto done;
1254 p = strrchr(path, '/');
1255 if (p == NULL) {
1256 /* this is a base key */
1257 value = regdb_fetch_key_internal(mem_ctx, path);
1258 ret = (value.dptr != NULL);
1259 } else {
1260 *p = '\0';
1261 ret = scan_parent_subkeys(path, p+1);
1264 done:
1265 TALLOC_FREE(mem_ctx);
1266 return ret;
1270 /***********************************************************************
1271 Retrieve an array of strings containing subkeys. Memory should be
1272 released by the caller.
1273 ***********************************************************************/
1275 int regdb_fetch_keys(const char *key, struct regsubkey_ctr *ctr)
1277 WERROR werr;
1278 uint32 num_items;
1279 uint8 *buf;
1280 uint32 buflen, len;
1281 int i;
1282 fstring subkeyname;
1283 int ret = -1;
1284 TALLOC_CTX *frame = talloc_stackframe();
1285 TDB_DATA value;
1287 DEBUG(11,("regdb_fetch_keys: Enter key => [%s]\n", key ? key : "NULL"));
1289 if (!regdb_key_exists(key)) {
1290 goto done;
1293 werr = regsubkey_ctr_set_seqnum(ctr, regdb_get_seqnum());
1294 if (!W_ERROR_IS_OK(werr)) {
1295 goto done;
1298 value = regdb_fetch_key_internal(frame, key);
1300 if (value.dptr == NULL) {
1301 DEBUG(10, ("regdb_fetch_keys: no subkeys found for key [%s]\n",
1302 key));
1303 ret = 0;
1304 goto done;
1307 buf = value.dptr;
1308 buflen = value.dsize;
1309 len = tdb_unpack( buf, buflen, "d", &num_items);
1311 for (i=0; i<num_items; i++) {
1312 len += tdb_unpack(buf+len, buflen-len, "f", subkeyname);
1313 werr = regsubkey_ctr_addkey(ctr, subkeyname);
1314 if (!W_ERROR_IS_OK(werr)) {
1315 DEBUG(5, ("regdb_fetch_keys: regsubkey_ctr_addkey "
1316 "failed: %s\n", win_errstr(werr)));
1317 goto done;
1321 DEBUG(11,("regdb_fetch_keys: Exit [%d] items\n", num_items));
1323 ret = num_items;
1324 done:
1325 TALLOC_FREE(frame);
1326 return ret;
1329 /****************************************************************************
1330 Unpack a list of registry values frem the TDB
1331 ***************************************************************************/
1333 static int regdb_unpack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
1335 int len = 0;
1336 uint32 type;
1337 fstring valuename;
1338 uint32 size;
1339 uint8 *data_p;
1340 uint32 num_values = 0;
1341 int i;
1343 /* loop and unpack the rest of the registry values */
1345 len += tdb_unpack(buf+len, buflen-len, "d", &num_values);
1347 for ( i=0; i<num_values; i++ ) {
1348 /* unpack the next regval */
1350 type = REG_NONE;
1351 size = 0;
1352 data_p = NULL;
1353 valuename[0] = '\0';
1354 len += tdb_unpack(buf+len, buflen-len, "fdB",
1355 valuename,
1356 &type,
1357 &size,
1358 &data_p);
1360 /* add the new value. Paranoid protective code -- make sure data_p is valid */
1362 if (*valuename && size && data_p) {
1363 regval_ctr_addvalue(values, valuename, type,
1364 (const char *)data_p, size);
1366 SAFE_FREE(data_p); /* 'B' option to tdb_unpack does a malloc() */
1368 DEBUG(8,("specific: [%s], len: %d\n", valuename, size));
1371 return len;
1374 /****************************************************************************
1375 Pack all values in all printer keys
1376 ***************************************************************************/
1378 static int regdb_pack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
1380 int len = 0;
1381 int i;
1382 REGISTRY_VALUE *val;
1383 int num_values;
1385 if ( !values )
1386 return 0;
1388 num_values = regval_ctr_numvals( values );
1390 /* pack the number of values first */
1392 len += tdb_pack( buf+len, buflen-len, "d", num_values );
1394 /* loop over all values */
1396 for ( i=0; i<num_values; i++ ) {
1397 val = regval_ctr_specific_value( values, i );
1398 len += tdb_pack(buf+len, buflen-len, "fdB",
1399 regval_name(val),
1400 regval_type(val),
1401 regval_size(val),
1402 regval_data_p(val) );
1405 return len;
1408 /***********************************************************************
1409 Retrieve an array of strings containing subkeys. Memory should be
1410 released by the caller.
1411 ***********************************************************************/
1413 int regdb_fetch_values( const char* key, REGVAL_CTR *values )
1415 char *keystr = NULL;
1416 TALLOC_CTX *ctx = talloc_stackframe();
1417 int ret = 0;
1418 TDB_DATA value;
1420 DEBUG(10,("regdb_fetch_values: Looking for value of key [%s] \n", key));
1422 if (!regdb_key_exists(key)) {
1423 goto done;
1426 keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key);
1427 if (!keystr) {
1428 goto done;
1431 values->seqnum = regdb_get_seqnum();
1433 value = regdb_fetch_key_internal(ctx, keystr);
1435 if (!value.dptr) {
1436 /* all keys have zero values by default */
1437 goto done;
1440 regdb_unpack_values(values, value.dptr, value.dsize);
1441 ret = regval_ctr_numvals(values);
1443 done:
1444 TALLOC_FREE(ctx);
1445 return ret;
1448 bool regdb_store_values( const char *key, REGVAL_CTR *values )
1450 TDB_DATA old_data, data;
1451 char *keystr = NULL;
1452 TALLOC_CTX *ctx = talloc_stackframe();
1453 int len;
1454 NTSTATUS status;
1455 bool result = false;
1457 DEBUG(10,("regdb_store_values: Looking for value of key [%s] \n", key));
1459 if (!regdb_key_exists(key)) {
1460 goto done;
1463 ZERO_STRUCT(data);
1465 len = regdb_pack_values(values, data.dptr, data.dsize);
1466 if (len <= 0) {
1467 DEBUG(0,("regdb_store_values: unable to pack values. len <= 0\n"));
1468 goto done;
1471 data.dptr = TALLOC_ARRAY(ctx, uint8, len);
1472 data.dsize = len;
1474 len = regdb_pack_values(values, data.dptr, data.dsize);
1476 SMB_ASSERT( len == data.dsize );
1478 keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key );
1479 if (!keystr) {
1480 goto done;
1482 keystr = normalize_reg_path(ctx, keystr);
1483 if (!keystr) {
1484 goto done;
1487 old_data = dbwrap_fetch_bystring(regdb, ctx, keystr);
1489 if ((old_data.dptr != NULL)
1490 && (old_data.dsize == data.dsize)
1491 && (memcmp(old_data.dptr, data.dptr, data.dsize) == 0))
1493 result = true;
1494 goto done;
1497 status = dbwrap_trans_store_bystring(regdb, keystr, data, TDB_REPLACE);
1499 result = NT_STATUS_IS_OK(status);
1501 done:
1502 TALLOC_FREE(ctx);
1503 return result;
1506 static WERROR regdb_get_secdesc(TALLOC_CTX *mem_ctx, const char *key,
1507 struct security_descriptor **psecdesc)
1509 char *tdbkey;
1510 TDB_DATA data;
1511 NTSTATUS status;
1512 TALLOC_CTX *tmp_ctx = talloc_stackframe();
1513 WERROR err = WERR_OK;
1515 DEBUG(10, ("regdb_get_secdesc: Getting secdesc of key [%s]\n", key));
1517 if (!regdb_key_exists(key)) {
1518 err = WERR_BADFILE;
1519 goto done;
1522 tdbkey = talloc_asprintf(tmp_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
1523 if (tdbkey == NULL) {
1524 err = WERR_NOMEM;
1525 goto done;
1527 normalize_dbkey(tdbkey);
1529 data = dbwrap_fetch_bystring(regdb, tmp_ctx, tdbkey);
1530 if (data.dptr == NULL) {
1531 err = WERR_BADFILE;
1532 goto done;
1535 status = unmarshall_sec_desc(mem_ctx, (uint8 *)data.dptr, data.dsize,
1536 psecdesc);
1538 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1539 err = WERR_NOMEM;
1540 } else if (!NT_STATUS_IS_OK(status)) {
1541 err = WERR_REG_CORRUPT;
1544 done:
1545 TALLOC_FREE(tmp_ctx);
1546 return err;
1549 static WERROR regdb_set_secdesc(const char *key,
1550 struct security_descriptor *secdesc)
1552 TALLOC_CTX *mem_ctx = talloc_stackframe();
1553 char *tdbkey;
1554 NTSTATUS status;
1555 WERROR err = WERR_NOMEM;
1556 TDB_DATA tdbdata;
1558 if (!regdb_key_exists(key)) {
1559 err = WERR_BADFILE;
1560 goto done;
1563 tdbkey = talloc_asprintf(mem_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
1564 if (tdbkey == NULL) {
1565 goto done;
1567 normalize_dbkey(tdbkey);
1569 if (secdesc == NULL) {
1570 /* assuming a delete */
1571 status = dbwrap_trans_delete_bystring(regdb, tdbkey);
1572 if (NT_STATUS_IS_OK(status)) {
1573 err = WERR_OK;
1574 } else {
1575 err = ntstatus_to_werror(status);
1577 goto done;
1580 err = ntstatus_to_werror(marshall_sec_desc(mem_ctx, secdesc,
1581 &tdbdata.dptr,
1582 &tdbdata.dsize));
1583 if (!W_ERROR_IS_OK(err)) {
1584 goto done;
1587 status = dbwrap_trans_store_bystring(regdb, tdbkey, tdbdata, 0);
1588 if (!NT_STATUS_IS_OK(status)) {
1589 err = ntstatus_to_werror(status);
1590 goto done;
1593 done:
1594 TALLOC_FREE(mem_ctx);
1595 return err;
1598 bool regdb_subkeys_need_update(struct regsubkey_ctr *subkeys)
1600 return (regdb_get_seqnum() != regsubkey_ctr_get_seqnum(subkeys));
1603 bool regdb_values_need_update(REGVAL_CTR *values)
1605 return (regdb_get_seqnum() != values->seqnum);
1609 * Table of function pointers for default access
1612 REGISTRY_OPS regdb_ops = {
1613 .fetch_subkeys = regdb_fetch_keys,
1614 .fetch_values = regdb_fetch_values,
1615 .store_subkeys = regdb_store_keys,
1616 .store_values = regdb_store_values,
1617 .create_subkey = regdb_create_subkey,
1618 .get_secdesc = regdb_get_secdesc,
1619 .set_secdesc = regdb_set_secdesc,
1620 .subkeys_need_update = regdb_subkeys_need_update,
1621 .values_need_update = regdb_values_need_update