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