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