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