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