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