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