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