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