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