05f3a5a0ab7c1f014da1e563be08bb1d34c2d986
[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 == -1) {
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_key_lists(struct db_context *db, const char *keyname)
716 {
717         WERROR werr;
718
719         werr = regdb_delete_values(db, keyname);
720         if (!W_ERROR_IS_OK(werr)) {
721                 DEBUG(1, (__location__ " Deleting %s\\%s failed: %s\n",
722                           REG_VALUE_PREFIX, keyname, win_errstr(werr)));
723                 goto done;
724         }
725
726         werr = regdb_delete_secdesc(db, keyname);
727         if (!W_ERROR_IS_OK(werr)) {
728                 DEBUG(1, (__location__ " Deleting %s\\%s failed: %s\n",
729                           REG_SECDESC_PREFIX, keyname, win_errstr(werr)));
730                 goto done;
731         }
732
733         werr = regdb_delete_subkeylist(db, keyname);
734         if (!W_ERROR_IS_OK(werr)) {
735                 DEBUG(1, (__location__ " Deleting %s failed: %s\n",
736                           keyname, win_errstr(werr)));
737                 goto done;
738         }
739
740 done:
741         return werr;
742 }
743
744 /***********************************************************************
745  Add subkey strings to the registry tdb under a defined key
746  fmt is the same format as tdb_pack except this function only supports
747  fstrings
748  ***********************************************************************/
749
750 static WERROR regdb_store_keys_internal2(struct db_context *db,
751                                          const char *key,
752                                          struct regsubkey_ctr *ctr)
753 {
754         TDB_DATA dbuf;
755         uint8 *buffer = NULL;
756         int i = 0;
757         uint32 len, buflen;
758         uint32 num_subkeys = regsubkey_ctr_numkeys(ctr);
759         char *keyname = NULL;
760         TALLOC_CTX *ctx = talloc_stackframe();
761         WERROR werr;
762
763         if (!key) {
764                 werr = WERR_INVALID_PARAM;
765                 goto done;
766         }
767
768         keyname = talloc_strdup(ctx, key);
769         if (!keyname) {
770                 werr = WERR_NOMEM;
771                 goto done;
772         }
773
774         keyname = normalize_reg_path(ctx, keyname);
775         if (!keyname) {
776                 werr = WERR_NOMEM;
777                 goto done;
778         }
779
780         /* allocate some initial memory */
781
782         buffer = (uint8 *)SMB_MALLOC(1024);
783         if (buffer == NULL) {
784                 werr = WERR_NOMEM;
785                 goto done;
786         }
787         buflen = 1024;
788         len = 0;
789
790         /* store the number of subkeys */
791
792         len += tdb_pack(buffer+len, buflen-len, "d", num_subkeys);
793
794         /* pack all the strings */
795
796         for (i=0; i<num_subkeys; i++) {
797                 size_t thistime;
798
799                 thistime = tdb_pack(buffer+len, buflen-len, "f",
800                                     regsubkey_ctr_specific_key(ctr, i));
801                 if (len+thistime > buflen) {
802                         size_t thistime2;
803                         /*
804                          * tdb_pack hasn't done anything because of the short
805                          * buffer, allocate extra space.
806                          */
807                         buffer = SMB_REALLOC_ARRAY(buffer, uint8_t,
808                                                    (len+thistime)*2);
809                         if(buffer == NULL) {
810                                 DEBUG(0, ("regdb_store_keys: Failed to realloc "
811                                           "memory of size [%u]\n",
812                                           (unsigned int)(len+thistime)*2));
813                                 werr = WERR_NOMEM;
814                                 goto done;
815                         }
816                         buflen = (len+thistime)*2;
817                         thistime2 = tdb_pack(
818                                 buffer+len, buflen-len, "f",
819                                 regsubkey_ctr_specific_key(ctr, i));
820                         if (thistime2 != thistime) {
821                                 DEBUG(0, ("tdb_pack failed\n"));
822                                 werr = WERR_CAN_NOT_COMPLETE;
823                                 goto done;
824                         }
825                 }
826                 len += thistime;
827         }
828
829         /* finally write out the data */
830
831         dbuf.dptr = buffer;
832         dbuf.dsize = len;
833         werr = ntstatus_to_werror(dbwrap_store_bystring(db, keyname, dbuf,
834                                                         TDB_REPLACE));
835         W_ERROR_NOT_OK_GOTO_DONE(werr);
836
837         /*
838          * recreate the sorted subkey cache for regdb_key_exists()
839          */
840         werr = ntstatus_to_werror(create_sorted_subkeys(keyname));
841
842 done:
843         TALLOC_FREE(ctx);
844         SAFE_FREE(buffer);
845         return werr;
846 }
847
848 /***********************************************************************
849  Store the new subkey record and create any child key records that
850  do not currently exist
851  ***********************************************************************/
852
853 struct regdb_store_keys_context {
854         const char *key;
855         struct regsubkey_ctr *ctr;
856 };
857
858 static NTSTATUS regdb_store_keys_action(struct db_context *db,
859                                         void *private_data)
860 {
861         struct regdb_store_keys_context *store_ctx;
862         WERROR werr;
863         int num_subkeys, i;
864         char *path = NULL;
865         struct regsubkey_ctr *subkeys = NULL, *old_subkeys = NULL;
866         char *oldkeyname = NULL;
867         TALLOC_CTX *mem_ctx = talloc_stackframe();
868
869         store_ctx = (struct regdb_store_keys_context *)private_data;
870
871         /*
872          * Re-fetch the old keys inside the transaction
873          */
874
875         werr = regsubkey_ctr_init(mem_ctx, &old_subkeys);
876         W_ERROR_NOT_OK_GOTO_DONE(werr);
877
878         werr = regdb_fetch_keys_internal(db, store_ctx->key, old_subkeys);
879         if (!W_ERROR_IS_OK(werr) &&
880             !W_ERROR_EQUAL(werr, WERR_NOT_FOUND))
881         {
882                 goto done;
883         }
884
885         /*
886          * Make the store operation as safe as possible without transactions:
887          *
888          * (1) For each subkey removed from ctr compared with old_subkeys:
889          *
890          *     (a) First delete the value db entry.
891          *
892          *     (b) Next delete the secdesc db record.
893          *
894          *     (c) Then delete the subkey list entry.
895          *
896          * (2) Now write the list of subkeys of the parent key,
897          *     deleting removed entries and adding new ones.
898          *
899          * (3) Finally create the subkey list entries for the added keys.
900          *
901          * This way if we crash half-way in between deleting the subkeys
902          * and storing the parent's list of subkeys, no old data can pop up
903          * out of the blue when re-adding keys later on.
904          */
905
906         /* (1) delete removed keys' lists (values/secdesc/subkeys) */
907
908         num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
909         for (i=0; i<num_subkeys; i++) {
910                 oldkeyname = regsubkey_ctr_specific_key(old_subkeys, i);
911
912                 if (regsubkey_ctr_key_exists(store_ctx->ctr, oldkeyname)) {
913                         /*
914                          * It's still around, don't delete
915                          */
916                         continue;
917                 }
918
919                 path = talloc_asprintf(mem_ctx, "%s\\%s", store_ctx->key,
920                                        oldkeyname);
921                 if (!path) {
922                         werr = WERR_NOMEM;
923                         goto done;
924                 }
925
926                 werr = regdb_delete_key_lists(db, path);
927                 W_ERROR_NOT_OK_GOTO_DONE(werr);
928
929                 TALLOC_FREE(path);
930         }
931
932         TALLOC_FREE(old_subkeys);
933
934         /* (2) store the subkey list for the parent */
935
936         werr = regdb_store_keys_internal2(db, store_ctx->key, store_ctx->ctr);
937         if (!W_ERROR_IS_OK(werr)) {
938                 DEBUG(0,("regdb_store_keys: Failed to store new subkey list "
939                          "for parent [%s]: %s\n", store_ctx->key,
940                          win_errstr(werr)));
941                 goto done;
942         }
943
944         /* (3) now create records for any subkeys that don't already exist */
945
946         num_subkeys = regsubkey_ctr_numkeys(store_ctx->ctr);
947
948         if (num_subkeys == 0) {
949                 werr = regsubkey_ctr_init(mem_ctx, &subkeys);
950                 W_ERROR_NOT_OK_GOTO_DONE(werr);
951
952                 werr = regdb_store_keys_internal2(db, store_ctx->key, subkeys);
953                 if (!W_ERROR_IS_OK(werr)) {
954                         DEBUG(0,("regdb_store_keys: Failed to store "
955                                  "new record for key [%s]: %s\n",
956                                  store_ctx->key, win_errstr(werr)));
957                         goto done;
958                 }
959                 TALLOC_FREE(subkeys);
960         }
961
962         for (i=0; i<num_subkeys; i++) {
963                 path = talloc_asprintf(mem_ctx, "%s\\%s", store_ctx->key,
964                                 regsubkey_ctr_specific_key(store_ctx->ctr, i));
965                 if (!path) {
966                         werr = WERR_NOMEM;
967                         goto done;
968                 }
969                 werr = regsubkey_ctr_init(mem_ctx, &subkeys);
970                 W_ERROR_NOT_OK_GOTO_DONE(werr);
971
972                 werr = regdb_fetch_keys_internal(db, path, subkeys);
973                 if (!W_ERROR_IS_OK(werr)) {
974                         /* create a record with 0 subkeys */
975                         werr = regdb_store_keys_internal2(db, path, subkeys);
976                         if (!W_ERROR_IS_OK(werr)) {
977                                 DEBUG(0,("regdb_store_keys: Failed to store "
978                                          "new record for key [%s]: %s\n", path,
979                                          win_errstr(werr)));
980                                 goto done;
981                         }
982                 }
983
984                 TALLOC_FREE(subkeys);
985                 TALLOC_FREE(path);
986         }
987
988         werr = WERR_OK;
989
990 done:
991         talloc_free(mem_ctx);
992         return werror_to_ntstatus(werr);
993 }
994
995 static bool regdb_store_keys_internal(struct db_context *db, const char *key,
996                                       struct regsubkey_ctr *ctr)
997 {
998         int num_subkeys, old_num_subkeys, i;
999         struct regsubkey_ctr *old_subkeys = NULL;
1000         TALLOC_CTX *ctx = talloc_stackframe();
1001         WERROR werr;
1002         bool ret = false;
1003         struct regdb_store_keys_context store_ctx;
1004
1005         if (!regdb_key_is_base_key(key) && !regdb_key_exists(db, key)) {
1006                 goto done;
1007         }
1008
1009         /*
1010          * fetch a list of the old subkeys so we can determine if anything has
1011          * changed
1012          */
1013
1014         werr = regsubkey_ctr_init(ctx, &old_subkeys);
1015         if (!W_ERROR_IS_OK(werr)) {
1016                 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
1017                 goto done;
1018         }
1019
1020         werr = regdb_fetch_keys_internal(db, key, old_subkeys);
1021         if (!W_ERROR_IS_OK(werr) &&
1022             !W_ERROR_EQUAL(werr, WERR_NOT_FOUND))
1023         {
1024                 goto done;
1025         }
1026
1027         num_subkeys = regsubkey_ctr_numkeys(ctr);
1028         old_num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
1029         if ((num_subkeys && old_num_subkeys) &&
1030             (num_subkeys == old_num_subkeys)) {
1031
1032                 for (i = 0; i < num_subkeys; i++) {
1033                         if (strcmp(regsubkey_ctr_specific_key(ctr, i),
1034                                    regsubkey_ctr_specific_key(old_subkeys, i))
1035                             != 0)
1036                         {
1037                                 break;
1038                         }
1039                 }
1040                 if (i == num_subkeys) {
1041                         /*
1042                          * Nothing changed, no point to even start a tdb
1043                          * transaction
1044                          */
1045
1046                         ret = true;
1047                         goto done;
1048                 }
1049         }
1050
1051         TALLOC_FREE(old_subkeys);
1052
1053         store_ctx.key = key;
1054         store_ctx.ctr = ctr;
1055
1056         werr = ntstatus_to_werror(dbwrap_trans_do(db,
1057                                                   regdb_store_keys_action,
1058                                                   &store_ctx));
1059
1060         ret = W_ERROR_IS_OK(werr);
1061
1062 done:
1063         TALLOC_FREE(ctx);
1064
1065         return ret;
1066 }
1067
1068 bool regdb_store_keys(const char *key, struct regsubkey_ctr *ctr)
1069 {
1070         return regdb_store_keys_internal(regdb, key, ctr);
1071 }
1072
1073 /**
1074  * create a subkey of a given key
1075  */
1076
1077 struct regdb_create_subkey_context {
1078         const char *key;
1079         const char *subkey;
1080 };
1081
1082 static NTSTATUS regdb_create_subkey_action(struct db_context *db,
1083                                            void *private_data)
1084 {
1085         WERROR werr;
1086         struct regdb_create_subkey_context *create_ctx;
1087         struct regsubkey_ctr *subkeys;
1088         TALLOC_CTX *mem_ctx = talloc_stackframe();
1089
1090         create_ctx = (struct regdb_create_subkey_context *)private_data;
1091
1092         werr = regsubkey_ctr_init(mem_ctx, &subkeys);
1093         W_ERROR_NOT_OK_GOTO_DONE(werr);
1094
1095         werr = regdb_fetch_keys_internal(db, create_ctx->key, subkeys);
1096         W_ERROR_NOT_OK_GOTO_DONE(werr);
1097
1098         werr = regsubkey_ctr_addkey(subkeys, create_ctx->subkey);
1099         W_ERROR_NOT_OK_GOTO_DONE(werr);
1100
1101         werr = regdb_store_keys_internal2(db, create_ctx->key, subkeys);
1102         if (!W_ERROR_IS_OK(werr)) {
1103                 DEBUG(0, (__location__ " failed to store new subkey list for "
1104                          "parent key %s: %s\n", create_ctx->key,
1105                          win_errstr(werr)));
1106         }
1107
1108 done:
1109         talloc_free(mem_ctx);
1110         return werror_to_ntstatus(werr);
1111 }
1112
1113 static WERROR regdb_create_subkey(const char *key, const char *subkey)
1114 {
1115         WERROR werr;
1116         struct regsubkey_ctr *subkeys;
1117         TALLOC_CTX *mem_ctx = talloc_stackframe();
1118         struct regdb_create_subkey_context create_ctx;
1119
1120         if (!regdb_key_is_base_key(key) && !regdb_key_exists(regdb, key)) {
1121                 werr = WERR_NOT_FOUND;
1122                 goto done;
1123         }
1124
1125         werr = regsubkey_ctr_init(mem_ctx, &subkeys);
1126         W_ERROR_NOT_OK_GOTO_DONE(werr);
1127
1128         werr = regdb_fetch_keys_internal(regdb, key, subkeys);
1129         W_ERROR_NOT_OK_GOTO_DONE(werr);
1130
1131         if (regsubkey_ctr_key_exists(subkeys, subkey)) {
1132                 werr = WERR_OK;
1133                 goto done;
1134         }
1135
1136         talloc_free(subkeys);
1137
1138         create_ctx.key = key;
1139         create_ctx.subkey = subkey;
1140
1141         werr = ntstatus_to_werror(dbwrap_trans_do(regdb,
1142                                                   regdb_create_subkey_action,
1143                                                   &create_ctx));
1144
1145 done:
1146         talloc_free(mem_ctx);
1147         return werr;
1148 }
1149
1150 /**
1151  * create a subkey of a given key
1152  */
1153
1154 struct regdb_delete_subkey_context {
1155         const char *key;
1156         const char *subkey;
1157         const char *path;
1158 };
1159
1160 static NTSTATUS regdb_delete_subkey_action(struct db_context *db,
1161                                            void *private_data)
1162 {
1163         WERROR werr;
1164         struct regdb_delete_subkey_context *delete_ctx;
1165         struct regsubkey_ctr *subkeys;
1166         TALLOC_CTX *mem_ctx = talloc_stackframe();
1167
1168         delete_ctx = (struct regdb_delete_subkey_context *)private_data;
1169
1170         werr = regdb_delete_key_lists(db, delete_ctx->path);
1171         W_ERROR_NOT_OK_GOTO_DONE(werr);
1172
1173         werr = regsubkey_ctr_init(mem_ctx, &subkeys);
1174         W_ERROR_NOT_OK_GOTO_DONE(werr);
1175
1176         werr = regdb_fetch_keys_internal(db, delete_ctx->key, subkeys);
1177         W_ERROR_NOT_OK_GOTO_DONE(werr);
1178
1179         werr = regsubkey_ctr_delkey(subkeys, delete_ctx->subkey);
1180         W_ERROR_NOT_OK_GOTO_DONE(werr);
1181
1182         werr = regdb_store_keys_internal2(db, delete_ctx->key, subkeys);
1183         if (!W_ERROR_IS_OK(werr)) {
1184                 DEBUG(0, (__location__ " failed to store new subkey_list for "
1185                          "parent key %s: %s\n", delete_ctx->key,
1186                          win_errstr(werr)));
1187         }
1188
1189 done:
1190         talloc_free(mem_ctx);
1191         return werror_to_ntstatus(werr);
1192 }
1193
1194 static WERROR regdb_delete_subkey(const char *key, const char *subkey)
1195 {
1196         WERROR werr;
1197         char *path;
1198         struct regdb_delete_subkey_context delete_ctx;
1199         TALLOC_CTX *mem_ctx = talloc_stackframe();
1200
1201         if (!regdb_key_is_base_key(key) && !regdb_key_exists(regdb, key)) {
1202                 werr = WERR_NOT_FOUND;
1203                 goto done;
1204         }
1205
1206         path = talloc_asprintf(mem_ctx, "%s\\%s", key, subkey);
1207         if (path == NULL) {
1208                 werr = WERR_NOMEM;
1209                 goto done;
1210         }
1211
1212         if (!regdb_key_exists(regdb, path)) {
1213                 werr = WERR_OK;
1214                 goto done;
1215         }
1216
1217         delete_ctx.key = key;
1218         delete_ctx.subkey = subkey;
1219         delete_ctx.path = path;
1220
1221         werr = ntstatus_to_werror(dbwrap_trans_do(regdb,
1222                                                   regdb_delete_subkey_action,
1223                                                   &delete_ctx));
1224
1225 done:
1226         talloc_free(mem_ctx);
1227         return werr;
1228 }
1229
1230 static TDB_DATA regdb_fetch_key_internal(struct db_context *db,
1231                                          TALLOC_CTX *mem_ctx, const char *key)
1232 {
1233         char *path = NULL;
1234         TDB_DATA data;
1235
1236         path = normalize_reg_path(mem_ctx, key);
1237         if (!path) {
1238                 return make_tdb_data(NULL, 0);
1239         }
1240
1241         data = dbwrap_fetch_bystring(db, mem_ctx, path);
1242
1243         TALLOC_FREE(path);
1244         return data;
1245 }
1246
1247
1248 /**
1249  * check whether a given key name represents a base key,
1250  * i.e one without a subkey separator ('\').
1251  */
1252 static bool regdb_key_is_base_key(const char *key)
1253 {
1254         TALLOC_CTX *mem_ctx = talloc_stackframe();
1255         bool ret = false;
1256         char *path;
1257
1258         if (key == NULL) {
1259                 goto done;
1260         }
1261
1262         path = normalize_reg_path(mem_ctx, key);
1263         if (path == NULL) {
1264                 DEBUG(0, ("out of memory! (talloc failed)\n"));
1265                 goto done;
1266         }
1267
1268         if (*path == '\0') {
1269                 goto done;
1270         }
1271
1272         ret = (strrchr(path, '\\') == NULL);
1273
1274 done:
1275         TALLOC_FREE(mem_ctx);
1276         return ret;
1277 }
1278
1279 /*
1280  * regdb_key_exists() is a very frequent operation. It can be quite
1281  * time-consuming to fully fetch the parent's subkey list, talloc_strdup all
1282  * subkeys and then compare the keyname linearly to all the parent's subkeys.
1283  *
1284  * The following code tries to make this operation as efficient as possible:
1285  * Per registry key we create a list of subkeys that is very efficient to
1286  * search for existence of a subkey. Its format is:
1287  *
1288  * 4 bytes num_subkeys
1289  * 4*num_subkey bytes offset into the string array
1290  * then follows a sorted list of subkeys in uppercase
1291  *
1292  * This record is created by create_sorted_subkeys() on demand if it does not
1293  * exist. scan_parent_subkeys() uses regdb->parse_record to search the sorted
1294  * list, the parsing code and the binary search can be found in
1295  * parent_subkey_scanner. The code uses parse_record() to avoid a memcpy of
1296  * the potentially large subkey record.
1297  *
1298  * The sorted subkey record is deleted in regdb_store_keys_internal2 and
1299  * recreated on demand.
1300  */
1301
1302 static int cmp_keynames(char **p1, char **p2)
1303 {
1304         return strcasecmp_m(*p1, *p2);
1305 }
1306
1307 struct create_sorted_subkeys_context {
1308         const char *key;
1309         const char *sorted_keyname;
1310 };
1311
1312 static NTSTATUS create_sorted_subkeys_action(struct db_context *db,
1313                                              void *private_data)
1314 {
1315         char **sorted_subkeys;
1316         struct regsubkey_ctr *ctr;
1317         NTSTATUS status;
1318         char *buf;
1319         char *p;
1320         int i;
1321         size_t len;
1322         int num_subkeys;
1323         struct create_sorted_subkeys_context *sorted_ctx;
1324
1325         sorted_ctx = (struct create_sorted_subkeys_context *)private_data;
1326
1327         /*
1328          * In this function, we only treat failing of the actual write to
1329          * the db as a real error. All preliminary errors, at a stage when
1330          * nothing has been written to the DB yet are treated as success
1331          * to be committed (as an empty transaction).
1332          *
1333          * The reason is that this (disposable) call might be nested in other
1334          * transactions. Doing a cancel here would destroy the possibility of
1335          * a transaction_commit for transactions that we might be wrapped in.
1336          */
1337
1338         status = werror_to_ntstatus(regsubkey_ctr_init(talloc_tos(), &ctr));
1339         if (!NT_STATUS_IS_OK(status)) {
1340                 /* don't treat this as an error */
1341                 status = NT_STATUS_OK;
1342                 goto done;
1343         }
1344
1345         status = werror_to_ntstatus(regdb_fetch_keys_internal(db,
1346                                                               sorted_ctx->key,
1347                                                               ctr));
1348         if (!NT_STATUS_IS_OK(status)) {
1349                 /* don't treat this as an error */
1350                 status = NT_STATUS_OK;
1351                 goto done;
1352         }
1353
1354         num_subkeys = regsubkey_ctr_numkeys(ctr);
1355         sorted_subkeys = talloc_array(ctr, char *, num_subkeys);
1356         if (sorted_subkeys == NULL) {
1357                 /* don't treat this as an error */
1358                 goto done;
1359         }
1360
1361         len = 4 + 4*num_subkeys;
1362
1363         for (i = 0; i < num_subkeys; i++) {
1364                 sorted_subkeys[i] = talloc_strdup_upper(sorted_subkeys,
1365                                         regsubkey_ctr_specific_key(ctr, i));
1366                 if (sorted_subkeys[i] == NULL) {
1367                         /* don't treat this as an error */
1368                         goto done;
1369                 }
1370                 len += strlen(sorted_subkeys[i])+1;
1371         }
1372
1373         TYPESAFE_QSORT(sorted_subkeys, num_subkeys, cmp_keynames);
1374
1375         buf = talloc_array(ctr, char, len);
1376         if (buf == NULL) {
1377                 /* don't treat this as an error */
1378                 goto done;
1379         }
1380         p = buf + 4 + 4*num_subkeys;
1381
1382         SIVAL(buf, 0, num_subkeys);
1383
1384         for (i=0; i < num_subkeys; i++) {
1385                 ptrdiff_t offset = p - buf;
1386                 SIVAL(buf, 4 + 4*i, offset);
1387                 strlcpy(p, sorted_subkeys[i], len-offset);
1388                 p += strlen(sorted_subkeys[i]) + 1;
1389         }
1390
1391         status = dbwrap_store_bystring(
1392                 db, sorted_ctx->sorted_keyname, make_tdb_data((uint8_t *)buf,
1393                 len),
1394                 TDB_REPLACE);
1395
1396 done:
1397         talloc_free(ctr);
1398         return status;
1399 }
1400
1401 static NTSTATUS create_sorted_subkeys_internal(const char *key,
1402                                                const char *sorted_keyname)
1403 {
1404         NTSTATUS status;
1405         struct create_sorted_subkeys_context sorted_ctx;
1406
1407         sorted_ctx.key = key;
1408         sorted_ctx.sorted_keyname = sorted_keyname;
1409
1410         status = dbwrap_trans_do(regdb,
1411                                  create_sorted_subkeys_action,
1412                                  &sorted_ctx);
1413
1414         return status;
1415 }
1416
1417 static NTSTATUS create_sorted_subkeys(const char *key)
1418 {
1419         char *sorted_subkeys_keyname;
1420         NTSTATUS status;
1421
1422         sorted_subkeys_keyname = talloc_asprintf(talloc_tos(), "%s\\%s",
1423                                                  REG_SORTED_SUBKEYS_PREFIX,
1424                                                  key);
1425         if (sorted_subkeys_keyname == NULL) {
1426                 status = NT_STATUS_NO_MEMORY;
1427                 goto done;
1428         }
1429
1430         status = create_sorted_subkeys_internal(key, sorted_subkeys_keyname);
1431
1432 done:
1433         return status;
1434 }
1435
1436 struct scan_subkey_state {
1437         char *name;
1438         bool scanned;
1439         bool found;
1440 };
1441
1442 static int parent_subkey_scanner(TDB_DATA key, TDB_DATA data,
1443                                  void *private_data)
1444 {
1445         struct scan_subkey_state *state =
1446                 (struct scan_subkey_state *)private_data;
1447         uint32_t num_subkeys;
1448         uint32_t l, u;
1449
1450         if (data.dsize < sizeof(uint32_t)) {
1451                 return -1;
1452         }
1453
1454         state->scanned = true;
1455         state->found = false;
1456
1457         tdb_unpack(data.dptr, data.dsize, "d", &num_subkeys);
1458
1459         l = 0;
1460         u = num_subkeys;
1461
1462         while (l < u) {
1463                 uint32_t idx = (l+u)/2;
1464                 char *s = (char *)data.dptr + IVAL(data.dptr, 4 + 4*idx);
1465                 int comparison = strcmp(state->name, s);
1466
1467                 if (comparison < 0) {
1468                         u = idx;
1469                 } else if (comparison > 0) {
1470                         l = idx + 1;
1471                 } else {
1472                         state->found = true;
1473                         return 0;
1474                 }
1475         }
1476         return 0;
1477 }
1478
1479 static bool scan_parent_subkeys(struct db_context *db, const char *parent,
1480                                 const char *name)
1481 {
1482         char *path = NULL;
1483         char *key = NULL;
1484         struct scan_subkey_state state = { 0, };
1485         bool result = false;
1486         int res;
1487
1488         state.name = NULL;
1489
1490         path = normalize_reg_path(talloc_tos(), parent);
1491         if (path == NULL) {
1492                 goto fail;
1493         }
1494
1495         key = talloc_asprintf(talloc_tos(), "%s\\%s",
1496                               REG_SORTED_SUBKEYS_PREFIX, path);
1497         if (key == NULL) {
1498                 goto fail;
1499         }
1500
1501         state.name = talloc_strdup_upper(talloc_tos(), name);
1502         if (state.name == NULL) {
1503                 goto fail;
1504         }
1505         state.scanned = false;
1506
1507         res = db->parse_record(db, string_term_tdb_data(key),
1508                                parent_subkey_scanner, &state);
1509
1510         if (state.scanned) {
1511                 result = state.found;
1512         } else {
1513                 NTSTATUS status;
1514
1515                 res = db->transaction_start(db);
1516                 if (res != 0) {
1517                         DEBUG(0, ("error starting transaction\n"));
1518                         goto fail;
1519                 }
1520
1521                 DEBUG(2, (__location__ " WARNING: recreating the sorted "
1522                           "subkeys cache for key '%s' from scan_parent_subkeys "
1523                           "this should not happen (too frequently)...\n",
1524                           path));
1525
1526                 status = create_sorted_subkeys_internal(path, key);
1527                 if (!NT_STATUS_IS_OK(status)) {
1528                         res = db->transaction_cancel(db);
1529                         if (res != 0) {
1530                                 smb_panic("Failed to cancel transaction.");
1531                         }
1532                         goto fail;
1533                 }
1534
1535                 res = db->parse_record(db, string_term_tdb_data(key),
1536                                        parent_subkey_scanner, &state);
1537                 if ((res == 0) && (state.scanned)) {
1538                         result = state.found;
1539                 }
1540
1541                 res = db->transaction_commit(db);
1542                 if (res != 0) {
1543                         DEBUG(0, ("error committing transaction\n"));
1544                         result = false;
1545                 }
1546         }
1547
1548  fail:
1549         TALLOC_FREE(path);
1550         TALLOC_FREE(state.name);
1551         return result;
1552 }
1553
1554 /**
1555  * Check for the existence of a key.
1556  *
1557  * Existence of a key is authoritatively defined by its
1558  * existence in the list of subkeys of its parent key.
1559  * The exeption of this are keys without a parent key,
1560  * i.e. the "base" keys (HKLM, HKCU, ...).
1561  */
1562 static bool regdb_key_exists(struct db_context *db, const char *key)
1563 {
1564         TALLOC_CTX *mem_ctx = talloc_stackframe();
1565         TDB_DATA value;
1566         bool ret = false;
1567         char *path, *p;
1568
1569         if (key == NULL) {
1570                 goto done;
1571         }
1572
1573         path = normalize_reg_path(mem_ctx, key);
1574         if (path == NULL) {
1575                 DEBUG(0, ("out of memory! (talloc failed)\n"));
1576                 goto done;
1577         }
1578
1579         if (*path == '\0') {
1580                 goto done;
1581         }
1582
1583         p = strrchr(path, '\\');
1584         if (p == NULL) {
1585                 /* this is a base key */
1586                 value = regdb_fetch_key_internal(db, mem_ctx, path);
1587                 ret = (value.dptr != NULL);
1588         } else {
1589                 *p = '\0';
1590                 ret = scan_parent_subkeys(db, path, p+1);
1591         }
1592
1593 done:
1594         TALLOC_FREE(mem_ctx);
1595         return ret;
1596 }
1597
1598
1599 /***********************************************************************
1600  Retrieve an array of strings containing subkeys.  Memory should be
1601  released by the caller.
1602  ***********************************************************************/
1603
1604 static WERROR regdb_fetch_keys_internal(struct db_context *db, const char *key,
1605                                         struct regsubkey_ctr *ctr)
1606 {
1607         WERROR werr;
1608         uint32_t num_items;
1609         uint8 *buf;
1610         uint32 buflen, len;
1611         int i;
1612         fstring subkeyname;
1613         TALLOC_CTX *frame = talloc_stackframe();
1614         TDB_DATA value;
1615
1616         DEBUG(11,("regdb_fetch_keys: Enter key => [%s]\n", key ? key : "NULL"));
1617
1618         if (!regdb_key_exists(db, key)) {
1619                 DEBUG(10, ("key [%s] not found\n", key));
1620                 werr = WERR_NOT_FOUND;
1621                 goto done;
1622         }
1623
1624         werr = regsubkey_ctr_set_seqnum(ctr, db->get_seqnum(db));
1625         W_ERROR_NOT_OK_GOTO_DONE(werr);
1626
1627         value = regdb_fetch_key_internal(db, frame, key);
1628
1629         if (value.dsize == 0 || value.dptr == NULL) {
1630                 DEBUG(10, ("regdb_fetch_keys: no subkeys found for key [%s]\n",
1631                            key));
1632                 goto done;
1633         }
1634
1635         buf = value.dptr;
1636         buflen = value.dsize;
1637         len = tdb_unpack( buf, buflen, "d", &num_items);
1638         if (len == (uint32_t)-1) {
1639                 werr = WERR_NOT_FOUND;
1640                 goto done;
1641         }
1642
1643         werr = regsubkey_ctr_reinit(ctr);
1644         W_ERROR_NOT_OK_GOTO_DONE(werr);
1645
1646         for (i=0; i<num_items; i++) {
1647                 len += tdb_unpack(buf+len, buflen-len, "f", subkeyname);
1648                 werr = regsubkey_ctr_addkey(ctr, subkeyname);
1649                 if (!W_ERROR_IS_OK(werr)) {
1650                         DEBUG(5, ("regdb_fetch_keys: regsubkey_ctr_addkey "
1651                                   "failed: %s\n", win_errstr(werr)));
1652                         num_items = 0;
1653                         goto done;
1654                 }
1655         }
1656
1657         DEBUG(11,("regdb_fetch_keys: Exit [%d] items\n", num_items));
1658
1659 done:
1660         TALLOC_FREE(frame);
1661         return werr;
1662 }
1663
1664 int regdb_fetch_keys(const char *key, struct regsubkey_ctr *ctr)
1665 {
1666         WERROR werr;
1667
1668         werr = regdb_fetch_keys_internal(regdb, key, ctr);
1669         if (!W_ERROR_IS_OK(werr)) {
1670                 return -1;
1671         }
1672
1673         return regsubkey_ctr_numkeys(ctr);
1674 }
1675
1676 /****************************************************************************
1677  Unpack a list of registry values frem the TDB
1678  ***************************************************************************/
1679
1680 static int regdb_unpack_values(struct regval_ctr *values, uint8 *buf, int buflen)
1681 {
1682         int             len = 0;
1683         uint32          type;
1684         fstring valuename;
1685         uint32          size;
1686         uint8           *data_p;
1687         uint32          num_values = 0;
1688         int             i;
1689
1690         /* loop and unpack the rest of the registry values */
1691
1692         len += tdb_unpack(buf+len, buflen-len, "d", &num_values);
1693
1694         for ( i=0; i<num_values; i++ ) {
1695                 /* unpack the next regval */
1696
1697                 type = REG_NONE;
1698                 size = 0;
1699                 data_p = NULL;
1700                 valuename[0] = '\0';
1701                 len += tdb_unpack(buf+len, buflen-len, "fdB",
1702                                   valuename,
1703                                   &type,
1704                                   &size,
1705                                   &data_p);
1706
1707                 regval_ctr_addvalue(values, valuename, type,
1708                                 (uint8_t *)data_p, size);
1709                 SAFE_FREE(data_p); /* 'B' option to tdb_unpack does a malloc() */
1710
1711                 DEBUG(8,("specific: [%s], len: %d\n", valuename, size));
1712         }
1713
1714         return len;
1715 }
1716
1717 /****************************************************************************
1718  Pack all values in all printer keys
1719  ***************************************************************************/
1720
1721 static int regdb_pack_values(struct regval_ctr *values, uint8 *buf, int buflen)
1722 {
1723         int             len = 0;
1724         int             i;
1725         struct regval_blob      *val;
1726         int             num_values;
1727
1728         if ( !values )
1729                 return 0;
1730
1731         num_values = regval_ctr_numvals( values );
1732
1733         /* pack the number of values first */
1734
1735         len += tdb_pack( buf+len, buflen-len, "d", num_values );
1736
1737         /* loop over all values */
1738
1739         for ( i=0; i<num_values; i++ ) {
1740                 val = regval_ctr_specific_value( values, i );
1741                 len += tdb_pack(buf+len, buflen-len, "fdB",
1742                                 regval_name(val),
1743                                 regval_type(val),
1744                                 regval_size(val),
1745                                 regval_data_p(val) );
1746         }
1747
1748         return len;
1749 }
1750
1751 /***********************************************************************
1752  Retrieve an array of strings containing subkeys.  Memory should be
1753  released by the caller.
1754  ***********************************************************************/
1755
1756 static int regdb_fetch_values_internal(struct db_context *db, const char* key,
1757                                        struct regval_ctr *values)
1758 {
1759         char *keystr = NULL;
1760         TALLOC_CTX *ctx = talloc_stackframe();
1761         int ret = 0;
1762         TDB_DATA value;
1763         WERROR werr;
1764
1765         DEBUG(10,("regdb_fetch_values: Looking for value of key [%s] \n", key));
1766
1767         if (!regdb_key_exists(db, key)) {
1768                 goto done;
1769         }
1770
1771         keystr = talloc_asprintf(ctx, "%s\\%s", REG_VALUE_PREFIX, key);
1772         if (!keystr) {
1773                 goto done;
1774         }
1775
1776         werr = regval_ctr_set_seqnum(values, db->get_seqnum(db));
1777         W_ERROR_NOT_OK_GOTO_DONE(werr);
1778
1779         value = regdb_fetch_key_internal(db, ctx, keystr);
1780
1781         if (!value.dptr) {
1782                 /* all keys have zero values by default */
1783                 goto done;
1784         }
1785
1786         regdb_unpack_values(values, value.dptr, value.dsize);
1787         ret = regval_ctr_numvals(values);
1788
1789 done:
1790         TALLOC_FREE(ctx);
1791         return ret;
1792 }
1793
1794 int regdb_fetch_values(const char* key, struct regval_ctr *values)
1795 {
1796         return regdb_fetch_values_internal(regdb, key, values);
1797 }
1798
1799 static bool regdb_store_values_internal(struct db_context *db, const char *key,
1800                                         struct regval_ctr *values)
1801 {
1802         TDB_DATA old_data, data;
1803         char *keystr = NULL;
1804         TALLOC_CTX *ctx = talloc_stackframe();
1805         int len;
1806         NTSTATUS status;
1807         bool result = false;
1808
1809         DEBUG(10,("regdb_store_values: Looking for value of key [%s] \n", key));
1810
1811         if (!regdb_key_exists(db, key)) {
1812                 goto done;
1813         }
1814
1815         ZERO_STRUCT(data);
1816
1817         len = regdb_pack_values(values, data.dptr, data.dsize);
1818         if (len <= 0) {
1819                 DEBUG(0,("regdb_store_values: unable to pack values. len <= 0\n"));
1820                 goto done;
1821         }
1822
1823         data.dptr = talloc_array(ctx, uint8, len);
1824         data.dsize = len;
1825
1826         len = regdb_pack_values(values, data.dptr, data.dsize);
1827
1828         SMB_ASSERT( len == data.dsize );
1829
1830         keystr = talloc_asprintf(ctx, "%s\\%s", REG_VALUE_PREFIX, key );
1831         if (!keystr) {
1832                 goto done;
1833         }
1834         keystr = normalize_reg_path(ctx, keystr);
1835         if (!keystr) {
1836                 goto done;
1837         }
1838
1839         old_data = dbwrap_fetch_bystring(db, ctx, keystr);
1840
1841         if ((old_data.dptr != NULL)
1842             && (old_data.dsize == data.dsize)
1843             && (memcmp(old_data.dptr, data.dptr, data.dsize) == 0))
1844         {
1845                 result = true;
1846                 goto done;
1847         }
1848
1849         status = dbwrap_trans_store_bystring(db, keystr, data, TDB_REPLACE);
1850
1851         result = NT_STATUS_IS_OK(status);
1852
1853 done:
1854         TALLOC_FREE(ctx);
1855         return result;
1856 }
1857
1858 bool regdb_store_values(const char *key, struct regval_ctr *values)
1859 {
1860         return regdb_store_values_internal(regdb, key, values);
1861 }
1862
1863 static WERROR regdb_get_secdesc(TALLOC_CTX *mem_ctx, const char *key,
1864                                 struct security_descriptor **psecdesc)
1865 {
1866         char *tdbkey;
1867         TDB_DATA data;
1868         NTSTATUS status;
1869         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1870         WERROR err = WERR_OK;
1871
1872         DEBUG(10, ("regdb_get_secdesc: Getting secdesc of key [%s]\n", key));
1873
1874         if (!regdb_key_exists(regdb, key)) {
1875                 err = WERR_BADFILE;
1876                 goto done;
1877         }
1878
1879         tdbkey = talloc_asprintf(tmp_ctx, "%s\\%s", REG_SECDESC_PREFIX, key);
1880         if (tdbkey == NULL) {
1881                 err = WERR_NOMEM;
1882                 goto done;
1883         }
1884
1885         tdbkey = normalize_reg_path(tmp_ctx, tdbkey);
1886         if (tdbkey == NULL) {
1887                 err = WERR_NOMEM;
1888                 goto done;
1889         }
1890
1891         data = dbwrap_fetch_bystring(regdb, tmp_ctx, tdbkey);
1892         if (data.dptr == NULL) {
1893                 err = WERR_BADFILE;
1894                 goto done;
1895         }
1896
1897         status = unmarshall_sec_desc(mem_ctx, (uint8 *)data.dptr, data.dsize,
1898                                      psecdesc);
1899
1900         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1901                 err = WERR_NOMEM;
1902         } else if (!NT_STATUS_IS_OK(status)) {
1903                 err = WERR_REG_CORRUPT;
1904         }
1905
1906 done:
1907         TALLOC_FREE(tmp_ctx);
1908         return err;
1909 }
1910
1911 static WERROR regdb_set_secdesc(const char *key,
1912                                 struct security_descriptor *secdesc)
1913 {
1914         TALLOC_CTX *mem_ctx = talloc_stackframe();
1915         char *tdbkey;
1916         WERROR err = WERR_NOMEM;
1917         TDB_DATA tdbdata;
1918
1919         if (!regdb_key_exists(regdb, key)) {
1920                 err = WERR_BADFILE;
1921                 goto done;
1922         }
1923
1924         tdbkey = talloc_asprintf(mem_ctx, "%s\\%s", REG_SECDESC_PREFIX, key);
1925         if (tdbkey == NULL) {
1926                 goto done;
1927         }
1928
1929         tdbkey = normalize_reg_path(mem_ctx, tdbkey);
1930         if (tdbkey == NULL) {
1931                 err = WERR_NOMEM;
1932                 goto done;
1933         }
1934
1935         if (secdesc == NULL) {
1936                 /* assuming a delete */
1937                 err = ntstatus_to_werror(dbwrap_trans_delete_bystring(regdb,
1938                                                                       tdbkey));
1939                 goto done;
1940         }
1941
1942         err = ntstatus_to_werror(marshall_sec_desc(mem_ctx, secdesc,
1943                                                    &tdbdata.dptr,
1944                                                    &tdbdata.dsize));
1945         W_ERROR_NOT_OK_GOTO_DONE(err);
1946
1947         err = ntstatus_to_werror(dbwrap_trans_store_bystring(regdb, tdbkey,
1948                                                              tdbdata, 0));
1949
1950  done:
1951         TALLOC_FREE(mem_ctx);
1952         return err;
1953 }
1954
1955 bool regdb_subkeys_need_update(struct regsubkey_ctr *subkeys)
1956 {
1957         return (regdb_get_seqnum() != regsubkey_ctr_get_seqnum(subkeys));
1958 }
1959
1960 bool regdb_values_need_update(struct regval_ctr *values)
1961 {
1962         return (regdb_get_seqnum() != regval_ctr_get_seqnum(values));
1963 }
1964
1965 /*
1966  * Table of function pointers for default access
1967  */
1968
1969 struct registry_ops regdb_ops = {
1970         .fetch_subkeys = regdb_fetch_keys,
1971         .fetch_values = regdb_fetch_values,
1972         .store_subkeys = regdb_store_keys,
1973         .store_values = regdb_store_values,
1974         .create_subkey = regdb_create_subkey,
1975         .delete_subkey = regdb_delete_subkey,
1976         .get_secdesc = regdb_get_secdesc,
1977         .set_secdesc = regdb_set_secdesc,
1978         .subkeys_need_update = regdb_subkeys_need_update,
1979         .values_need_update = regdb_values_need_update
1980 };