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