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