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