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