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