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