registry: free temporary data in regdb_fetch_key_internal().
[kai/samba.git] / source / 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(const char *key);
31
32 /* List the deepest path into the registry.  All part components will be created.*/
33
34 /* If you want to have a part of the path controlled by the tdb and part by
35    a virtual registry db (e.g. printing), then you have to list the deepest path.
36    For example,"HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion/Print" 
37    allows the reg_db backend to handle everything up to 
38    "HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion" and then we'll hook 
39    the reg_printing backend onto the last component of the path (see 
40    KEY_PRINTING_2K in include/rpc_reg.h)   --jerry */
41
42 static const char *builtin_registry_paths[] = {
43         KEY_PRINTING_2K,
44         KEY_PRINTING_PORTS,
45         KEY_PRINTING,
46         KEY_SHARES,
47         KEY_EVENTLOG,
48         KEY_SMBCONF,
49         KEY_PERFLIB,
50         KEY_PERFLIB_009,
51         KEY_GROUP_POLICY,
52         KEY_SAMBA_GROUP_POLICY,
53         KEY_GP_MACHINE_POLICY,
54         KEY_GP_MACHINE_WIN_POLICY,
55         KEY_HKCU,
56         KEY_GP_USER_POLICY,
57         KEY_GP_USER_WIN_POLICY,
58         KEY_WINLOGON_GPEXT_PATH,
59         "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Print\\Monitors",
60         KEY_PROD_OPTIONS,
61         "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\DefaultUserConfiguration",
62         KEY_TCPIP_PARAMS,
63         KEY_NETLOGON_PARAMS,
64         KEY_HKU,
65         KEY_HKCR,
66         KEY_HKPD,
67         KEY_HKPT,
68          NULL };
69
70 struct builtin_regkey_value {
71         const char *path;
72         const char *valuename;
73         uint32 type;
74         union {
75                 const char *string;
76                 uint32 dw_value;
77         } data;
78 };
79
80 static struct builtin_regkey_value builtin_registry_values[] = {
81         { KEY_PRINTING_PORTS,
82                 SAMBA_PRINTER_PORT_NAME, REG_SZ, { "" } },
83         { KEY_PRINTING_2K,
84                 "DefaultSpoolDirectory", REG_SZ, { "C:\\Windows\\System32\\Spool\\Printers" } },
85         { KEY_EVENTLOG,
86                 "DisplayName", REG_SZ, { "Event Log" } }, 
87         { KEY_EVENTLOG,
88                 "ErrorControl", REG_DWORD, { (char*)0x00000001 } },
89         { NULL, NULL, 0, { NULL } }
90 };
91
92 /**
93  * Initialize a key in the registry:
94  * create each component key of the specified path.
95  */
96 static WERROR init_registry_key_internal(const char *add_path)
97 {
98         WERROR werr;
99         TALLOC_CTX *frame = talloc_stackframe();
100         char *path = NULL;
101         char *base = NULL;
102         char *remaining = NULL;
103         char *keyname;
104         char *subkeyname;
105         REGSUBKEY_CTR *subkeys;
106         const char *p, *p2;
107
108         DEBUG(6, ("init_registry_key: Adding [%s]\n", add_path));
109
110         path = talloc_strdup(frame, add_path);
111         base = talloc_strdup(frame, "");
112         if (!path || !base) {
113                 werr = WERR_NOMEM;
114                 goto fail;
115         }
116         p = path;
117
118         while (next_token_talloc(frame, &p, &keyname, "\\")) {
119
120                 /* build up the registry path from the components */
121
122                 if (*base) {
123                         base = talloc_asprintf(frame, "%s\\", base);
124                         if (!base) {
125                                 werr = WERR_NOMEM;
126                                 goto fail;
127                         }
128                 }
129                 base = talloc_asprintf_append(base, "%s", keyname);
130                 if (!base) {
131                         werr = WERR_NOMEM;
132                         goto fail;
133                 }
134
135                 /* get the immediate subkeyname (if we have one ) */
136
137                 subkeyname = talloc_strdup(frame, "");
138                 if (!subkeyname) {
139                         werr = WERR_NOMEM;
140                         goto fail;
141                 }
142                 if (*p) {
143                         remaining = talloc_strdup(frame, p);
144                         if (!remaining) {
145                                 werr = WERR_NOMEM;
146                                 goto fail;
147                         }
148                         p2 = remaining;
149
150                         if (!next_token_talloc(frame, &p2,
151                                                 &subkeyname, "\\"))
152                         {
153                                 subkeyname = talloc_strdup(frame,p2);
154                                 if (!subkeyname) {
155                                         werr = WERR_NOMEM;
156                                         goto fail;
157                                 }
158                         }
159                 }
160
161                 DEBUG(10,("init_registry_key: Storing key [%s] with "
162                           "subkey [%s]\n", base,
163                           *subkeyname ? subkeyname : "NULL"));
164
165                 /* we don't really care if the lookup succeeds or not
166                  * since we are about to update the record.
167                  * We just want any subkeys already present */
168
169                 if (!(subkeys = TALLOC_ZERO_P(frame, REGSUBKEY_CTR))) {
170                         DEBUG(0,("talloc() failure!\n"));
171                         werr = WERR_NOMEM;
172                         goto fail;
173                 }
174
175                 regdb_fetch_keys(base, subkeys);
176                 if (*subkeyname) {
177                         werr = regsubkey_ctr_addkey(subkeys, subkeyname);
178                         if (!W_ERROR_IS_OK(werr)) {
179                                 goto fail;
180                         }
181                 }
182                 if (!regdb_store_keys( base, subkeys)) {
183                         werr = WERR_CAN_NOT_COMPLETE;
184                         goto fail;
185                 }
186         }
187
188         werr = WERR_OK;
189
190 fail:
191         TALLOC_FREE(frame);
192         return werr;
193 }
194
195 /**
196  * Initialize a key in the registry:
197  * create each component key of the specified path,
198  * wrapped in one db transaction.
199  */
200 WERROR init_registry_key(const char *add_path)
201 {
202         WERROR werr;
203
204         if (regdb_key_exists(add_path)) {
205                 return WERR_OK;
206         }
207
208         if (regdb->transaction_start(regdb) != 0) {
209                 DEBUG(0, ("init_registry_key: transaction_start failed\n"));
210                 return WERR_REG_IO_FAILURE;
211         }
212
213         werr = init_registry_key_internal(add_path);
214         if (!W_ERROR_IS_OK(werr)) {
215                 goto fail;
216         }
217
218         if (regdb->transaction_commit(regdb) != 0) {
219                 DEBUG(0, ("init_registry_key: Could not commit transaction\n"));
220                 return WERR_REG_IO_FAILURE;
221         }
222
223         return WERR_OK;
224
225 fail:
226         if (regdb->transaction_cancel(regdb) != 0) {
227                 smb_panic("init_registry_key: transaction_cancel failed\n");
228         }
229
230         return werr;
231 }
232
233 /***********************************************************************
234  Open the registry data in the tdb
235  ***********************************************************************/
236
237 WERROR init_registry_data(void)
238 {
239         WERROR werr;
240         TALLOC_CTX *frame = talloc_stackframe();
241         REGVAL_CTR *values;
242         int i;
243         UNISTR2 data;
244
245         /*
246          * First, check for the existence of the needed keys and values.
247          * If all do already exist, we can save the writes.
248          */
249         for (i=0; builtin_registry_paths[i] != NULL; i++) {
250                 if (!regdb_key_exists(builtin_registry_paths[i])) {
251                         goto do_init;
252                 }
253         }
254
255         for (i=0; builtin_registry_values[i].path != NULL; i++) {
256                 values = TALLOC_ZERO_P(frame, REGVAL_CTR);
257                 if (values == NULL) {
258                         werr = WERR_NOMEM;
259                         goto done;
260                 }
261
262                 regdb_fetch_values(builtin_registry_values[i].path, values);
263                 if (!regval_ctr_key_exists(values,
264                                         builtin_registry_values[i].valuename))
265                 {
266                         TALLOC_FREE(values);
267                         goto do_init;
268                 }
269
270                 TALLOC_FREE(values);
271         }
272
273         werr = WERR_OK;
274         goto done;
275
276 do_init:
277
278         /*
279          * There are potentially quite a few store operations which are all
280          * indiviually wrapped in tdb transactions. Wrapping them in a single
281          * transaction gives just a single transaction_commit() to actually do
282          * its fsync()s. See tdb/common/transaction.c for info about nested
283          * transaction behaviour.
284          */
285
286         if (regdb->transaction_start(regdb) != 0) {
287                 DEBUG(0, ("init_registry_data: tdb_transaction_start "
288                           "failed\n"));
289                 werr = WERR_REG_IO_FAILURE;
290                 goto done;
291         }
292
293         /* loop over all of the predefined paths and add each component */
294
295         for (i=0; builtin_registry_paths[i] != NULL; i++) {
296                 if (regdb_key_exists(builtin_registry_paths[i])) {
297                         continue;
298                 }
299                 werr = init_registry_key_internal(builtin_registry_paths[i]);
300                 if (!W_ERROR_IS_OK(werr)) {
301                         goto fail;
302                 }
303         }
304
305         /* loop over all of the predefined values and add each component */
306
307         for (i=0; builtin_registry_values[i].path != NULL; i++) {
308
309                 values = TALLOC_ZERO_P(frame, REGVAL_CTR);
310                 if (values == NULL) {
311                         werr = WERR_NOMEM;
312                         goto fail;
313                 }
314
315                 regdb_fetch_values(builtin_registry_values[i].path, values);
316
317                 /* preserve existing values across restarts. Only add new ones */
318
319                 if (!regval_ctr_key_exists(values,
320                                         builtin_registry_values[i].valuename))
321                 {
322                         switch(builtin_registry_values[i].type) {
323                         case REG_DWORD:
324                                 regval_ctr_addvalue(values,
325                                         builtin_registry_values[i].valuename,
326                                         REG_DWORD,
327                                         (char*)&builtin_registry_values[i].data.dw_value,
328                                         sizeof(uint32));
329                                 break;
330
331                         case REG_SZ:
332                                 init_unistr2(&data,
333                                         builtin_registry_values[i].data.string,
334                                         UNI_STR_TERMINATE);
335                                 regval_ctr_addvalue(values,
336                                         builtin_registry_values[i].valuename,
337                                         REG_SZ,
338                                         (char*)data.buffer,
339                                         data.uni_str_len*sizeof(uint16));
340                                 break;
341
342                         default:
343                                 DEBUG(0, ("init_registry_data: invalid value "
344                                           "type in builtin_registry_values "
345                                           "[%d]\n",
346                                           builtin_registry_values[i].type));
347                         }
348                         regdb_store_values(builtin_registry_values[i].path,
349                                            values);
350                 }
351                 TALLOC_FREE(values);
352         }
353
354         if (regdb->transaction_commit(regdb) != 0) {
355                 DEBUG(0, ("init_registry_data: Could not commit "
356                           "transaction\n"));
357                 werr = WERR_REG_IO_FAILURE;
358         } else {
359                 werr = WERR_OK;
360         }
361
362         goto done;
363
364 fail:
365         if (regdb->transaction_cancel(regdb) != 0) {
366                 smb_panic("init_registry_data: tdb_transaction_cancel "
367                           "failed\n");
368         }
369
370 done:
371         TALLOC_FREE(frame);
372         return werr;
373 }
374
375 /***********************************************************************
376  Open the registry database
377  ***********************************************************************/
378  
379 WERROR regdb_init(void)
380 {
381         const char *vstring = "INFO/version";
382         uint32 vers_id;
383         WERROR werr;
384
385         if (regdb) {
386                 DEBUG(10, ("regdb_init: incrementing refcount (%d)\n",
387                           regdb_refcount));
388                 regdb_refcount++;
389                 return WERR_OK;
390         }
391
392         regdb = db_open_trans(NULL, state_path("registry.tdb"), 0,
393                               REG_TDB_FLAGS, O_RDWR, 0600);
394         if (!regdb) {
395                 regdb = db_open_trans(NULL, state_path("registry.tdb"), 0,
396                                       REG_TDB_FLAGS, O_RDWR|O_CREAT, 0600);
397                 if (!regdb) {
398                         werr = ntstatus_to_werror(map_nt_error_from_unix(errno));
399                         DEBUG(0,("regdb_init: Failed to open registry %s (%s)\n",
400                                 state_path("registry.tdb"), strerror(errno) ));
401                         return werr;
402                 }
403                 
404                 DEBUG(10,("regdb_init: Successfully created registry tdb\n"));
405         }
406
407         regdb_refcount = 1;
408
409         vers_id = dbwrap_fetch_int32(regdb, vstring);
410
411         if ( vers_id != REGVER_V1 ) {
412                 NTSTATUS status;
413                 /* any upgrade code here if needed */
414                 DEBUG(10, ("regdb_init: got %s = %d != %d\n", vstring,
415                            vers_id, REGVER_V1));
416                 status = dbwrap_trans_store_int32(regdb, vstring, REGVER_V1);
417                 if (!NT_STATUS_IS_OK(status)) {
418                         DEBUG(0, ("regdb_init: error storing %s = %d: %s\n",
419                                   vstring, REGVER_V1, nt_errstr(status)));
420                         return ntstatus_to_werror(status);
421                 } else {
422                         DEBUG(10, ("regdb_init: stored %s = %d\n",
423                                   vstring, REGVER_V1));
424                 }
425         }
426
427         return WERR_OK;
428 }
429
430 /***********************************************************************
431  Open the registry.  Must already have been initialized by regdb_init()
432  ***********************************************************************/
433
434 WERROR regdb_open( void )
435 {
436         WERROR result = WERR_OK;
437
438         if ( regdb ) {
439                 DEBUG(10,("regdb_open: incrementing refcount (%d)\n", regdb_refcount));
440                 regdb_refcount++;
441                 return WERR_OK;
442         }
443         
444         become_root();
445
446         regdb = db_open_trans(NULL, state_path("registry.tdb"), 0,
447                               REG_TDB_FLAGS, O_RDWR, 0600);
448         if ( !regdb ) {
449                 result = ntstatus_to_werror( map_nt_error_from_unix( errno ) );
450                 DEBUG(0,("regdb_open: Failed to open %s! (%s)\n", 
451                         state_path("registry.tdb"), strerror(errno) ));
452         }
453
454         unbecome_root();
455
456         regdb_refcount = 1;
457         DEBUG(10,("regdb_open: refcount reset (%d)\n", regdb_refcount));
458
459         return result;
460 }
461
462 /***********************************************************************
463  ***********************************************************************/
464
465 int regdb_close( void )
466 {
467         if (regdb_refcount == 0) {
468                 return 0;
469         }
470
471         regdb_refcount--;
472
473         DEBUG(10,("regdb_close: decrementing refcount (%d)\n", regdb_refcount));
474
475         if ( regdb_refcount > 0 )
476                 return 0;
477
478         SMB_ASSERT( regdb_refcount >= 0 );
479
480         TALLOC_FREE(regdb);
481         return 0;
482 }
483
484 /***********************************************************************
485  return the tdb sequence number of the registry tdb.
486  this is an indicator for the content of the registry
487  having changed. it will change upon regdb_init, too, though.
488  ***********************************************************************/
489 int regdb_get_seqnum(void)
490 {
491         return regdb->get_seqnum(regdb);
492 }
493
494 /***********************************************************************
495  Add subkey strings to the registry tdb under a defined key
496  fmt is the same format as tdb_pack except this function only supports
497  fstrings
498  ***********************************************************************/
499
500 static bool regdb_store_keys_internal(const char *key, REGSUBKEY_CTR *ctr)
501 {
502         TDB_DATA dbuf;
503         uint8 *buffer = NULL;
504         int i = 0;
505         uint32 len, buflen;
506         bool ret = true;
507         uint32 num_subkeys = regsubkey_ctr_numkeys(ctr);
508         char *keyname = NULL;
509         TALLOC_CTX *ctx = talloc_stackframe();
510         NTSTATUS status;
511
512         if (!key) {
513                 return false;
514         }
515
516         keyname = talloc_strdup(ctx, key);
517         if (!keyname) {
518                 return false;
519         }
520         keyname = normalize_reg_path(ctx, keyname);
521
522         /* allocate some initial memory */
523
524         buffer = (uint8 *)SMB_MALLOC(1024);
525         if (buffer == NULL) {
526                 return false;
527         }
528         buflen = 1024;
529         len = 0;
530
531         /* store the number of subkeys */
532
533         len += tdb_pack(buffer+len, buflen-len, "d", num_subkeys);
534
535         /* pack all the strings */
536
537         for (i=0; i<num_subkeys; i++) {
538                 len += tdb_pack(buffer+len, buflen-len, "f",
539                                 regsubkey_ctr_specific_key(ctr, i));
540                 if (len > buflen) {
541                         /* allocate some extra space */
542                         buffer = (uint8 *)SMB_REALLOC(buffer, len*2);
543                         if(buffer == NULL) {
544                                 DEBUG(0, ("regdb_store_keys: Failed to realloc "
545                                           "memory of size [%d]\n", len*2));
546                                 ret = false;
547                                 goto done;
548                         }
549                         buflen = len*2;
550                         len = tdb_pack(buffer+len, buflen-len, "f",
551                                        regsubkey_ctr_specific_key(ctr, i));
552                 }
553         }
554
555         /* finally write out the data */
556
557         dbuf.dptr = buffer;
558         dbuf.dsize = len;
559         status = dbwrap_store_bystring(regdb, keyname, dbuf, TDB_REPLACE);
560         if (!NT_STATUS_IS_OK(status)) {
561                 ret = false;
562                 goto done;
563         }
564
565 done:
566         TALLOC_FREE(ctx);
567         SAFE_FREE(buffer);
568         return ret;
569 }
570
571 /***********************************************************************
572  Store the new subkey record and create any child key records that
573  do not currently exist
574  ***********************************************************************/
575
576 bool regdb_store_keys(const char *key, REGSUBKEY_CTR *ctr)
577 {
578         int num_subkeys, i;
579         char *path = NULL;
580         REGSUBKEY_CTR *subkeys = NULL, *old_subkeys = NULL;
581         char *oldkeyname = NULL;
582         TALLOC_CTX *ctx = talloc_stackframe();
583         NTSTATUS status;
584
585         /*
586          * fetch a list of the old subkeys so we can determine if anything has
587          * changed
588          */
589
590         if (!(old_subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR))) {
591                 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
592                 return false;
593         }
594
595         regdb_fetch_keys(key, old_subkeys);
596
597         if ((ctr->num_subkeys && old_subkeys->num_subkeys) &&
598             (ctr->num_subkeys == old_subkeys->num_subkeys)) {
599
600                 for (i = 0; i<ctr->num_subkeys; i++) {
601                         if (strcmp(ctr->subkeys[i],
602                                    old_subkeys->subkeys[i]) != 0) {
603                                 break;
604                         }
605                 }
606                 if (i == ctr->num_subkeys) {
607                         /*
608                          * Nothing changed, no point to even start a tdb
609                          * transaction
610                          */
611                         TALLOC_FREE(old_subkeys);
612                         return true;
613                 }
614         }
615
616         TALLOC_FREE(old_subkeys);
617
618         if (regdb->transaction_start(regdb) != 0) {
619                 DEBUG(0, ("regdb_store_keys: transaction_start failed\n"));
620                 goto fail;
621         }
622
623         /*
624          * Re-fetch the old keys inside the transaction
625          */
626
627         if (!(old_subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR))) {
628                 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
629                 goto cancel;
630         }
631
632         regdb_fetch_keys(key, old_subkeys);
633
634         /* store the subkey list for the parent */
635
636         if (!regdb_store_keys_internal(key, ctr) ) {
637                 DEBUG(0,("regdb_store_keys: Failed to store new subkey list "
638                          "for parent [%s]\n", key));
639                 goto cancel;
640         }
641
642         /* now delete removed keys */
643
644         num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
645         for (i=0; i<num_subkeys; i++) {
646                 oldkeyname = regsubkey_ctr_specific_key(old_subkeys, i);
647
648                 if (regsubkey_ctr_key_exists(ctr, oldkeyname)) {
649                         /*
650                          * It's still around, don't delete
651                          */
652
653                         continue;
654                 }
655
656                 path = talloc_asprintf(ctx, "%s/%s", key, oldkeyname);
657                 if (!path) {
658                         goto cancel;
659                 }
660                 path = normalize_reg_path(ctx, path);
661                 if (!path) {
662                         goto cancel;
663                 }
664                 status = dbwrap_delete_bystring(regdb, path);
665                 if (!NT_STATUS_IS_OK(status)) {
666                         DEBUG(1, ("Deleting %s failed\n", path));
667                         goto cancel;
668                 }
669
670                 TALLOC_FREE(path);
671                 path = talloc_asprintf(ctx, "%s/%s/%s",
672                                 REG_VALUE_PREFIX,
673                                 key,
674                                 oldkeyname );
675                 if (!path) {
676                         goto cancel;
677                 }
678                 path = normalize_reg_path(ctx, path);
679                 if (!path) {
680                         goto cancel;
681                 }
682
683                 /*
684                  * Ignore errors here, we might have no values around
685                  */
686                 dbwrap_delete_bystring(regdb, path);
687                 TALLOC_FREE(path);
688         }
689
690         TALLOC_FREE(old_subkeys);
691
692         /* now create records for any subkeys that don't already exist */
693
694         num_subkeys = regsubkey_ctr_numkeys(ctr);
695
696         if (num_subkeys == 0) {
697                 if (!(subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR)) ) {
698                         DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
699                         goto cancel;
700                 }
701
702                 if (!regdb_store_keys_internal(key, subkeys)) {
703                         DEBUG(0,("regdb_store_keys: Failed to store "
704                                  "new record for key [%s]\n", key));
705                         goto cancel;
706                 }
707                 TALLOC_FREE(subkeys);
708
709         }
710
711         for (i=0; i<num_subkeys; i++) {
712                 path = talloc_asprintf(ctx, "%s/%s",
713                                         key,
714                                         regsubkey_ctr_specific_key(ctr, i));
715                 if (!path) {
716                         goto cancel;
717                 }
718                 if (!(subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR)) ) {
719                         DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
720                         goto cancel;
721                 }
722
723                 if (regdb_fetch_keys( path, subkeys ) == -1) {
724                         /* create a record with 0 subkeys */
725                         if (!regdb_store_keys_internal(path, subkeys)) {
726                                 DEBUG(0,("regdb_store_keys: Failed to store "
727                                          "new record for key [%s]\n", path));
728                                 goto cancel;
729                         }
730                 }
731
732                 TALLOC_FREE(subkeys);
733                 TALLOC_FREE(path);
734         }
735
736         if (regdb->transaction_commit(regdb) != 0) {
737                 DEBUG(0, ("regdb_store_keys: Could not commit transaction\n"));
738                 goto fail;
739         }
740
741         TALLOC_FREE(ctx);
742         return true;
743
744 cancel:
745         if (regdb->transaction_cancel(regdb) != 0) {
746                 smb_panic("regdb_store_keys: transaction_cancel failed\n");
747         }
748
749 fail:
750         TALLOC_FREE(ctx);
751
752         return false;
753 }
754
755
756 static TDB_DATA regdb_fetch_key_internal(TALLOC_CTX *mem_ctx, const char *key)
757 {
758         char *path = NULL;
759         TDB_DATA data;
760
761         path = normalize_reg_path(mem_ctx, key);
762         if (!path) {
763                 return make_tdb_data(NULL, 0);
764         }
765
766         data = dbwrap_fetch_bystring(regdb, mem_ctx, path);
767
768         TALLOC_FREE(path);
769         return data;
770 }
771
772
773 static bool regdb_key_exists(const char *key)
774 {
775         TALLOC_CTX *mem_ctx = talloc_stackframe();
776         TDB_DATA value;
777         bool ret;
778
779         value = regdb_fetch_key_internal(mem_ctx, key);
780         ret = (value.dptr != NULL);
781
782         TALLOC_FREE(mem_ctx);
783         return ret;
784 }
785
786
787 /***********************************************************************
788  Retrieve an array of strings containing subkeys.  Memory should be
789  released by the caller.
790  ***********************************************************************/
791
792 int regdb_fetch_keys(const char *key, REGSUBKEY_CTR *ctr)
793 {
794         WERROR werr;
795         uint32 num_items;
796         uint8 *buf;
797         uint32 buflen, len;
798         int i;
799         fstring subkeyname;
800         int ret = -1;
801         TALLOC_CTX *frame = talloc_stackframe();
802         TDB_DATA value;
803
804         DEBUG(11,("regdb_fetch_keys: Enter key => [%s]\n", key ? key : "NULL"));
805
806         ctr->seqnum = regdb_get_seqnum();
807
808         value = regdb_fetch_key_internal(frame, key);
809
810         buf = value.dptr;
811         buflen = value.dsize;
812
813         if ( !buf ) {
814                 DEBUG(5,("regdb_fetch_keys: tdb lookup failed to locate key [%s]\n", key));
815                 goto fail;
816         }
817
818         len = tdb_unpack( buf, buflen, "d", &num_items);
819
820         for (i=0; i<num_items; i++) {
821                 len += tdb_unpack(buf+len, buflen-len, "f", subkeyname);
822                 werr = regsubkey_ctr_addkey(ctr, subkeyname);
823                 if (!W_ERROR_IS_OK(werr)) {
824                         DEBUG(5, ("regdb_fetch_keys: regsubkey_ctr_addkey "
825                                   "failed: %s\n", dos_errstr(werr)));
826                         goto fail;
827                 }
828         }
829
830         DEBUG(11,("regdb_fetch_keys: Exit [%d] items\n", num_items));
831
832         ret = num_items;
833  fail:
834         TALLOC_FREE(frame);
835         return ret;
836 }
837
838 /****************************************************************************
839  Unpack a list of registry values frem the TDB
840  ***************************************************************************/
841
842 static int regdb_unpack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
843 {
844         int             len = 0;
845         uint32          type;
846         fstring valuename;
847         uint32          size;
848         uint8           *data_p;
849         uint32          num_values = 0;
850         int             i;
851
852         /* loop and unpack the rest of the registry values */
853
854         len += tdb_unpack(buf+len, buflen-len, "d", &num_values);
855
856         for ( i=0; i<num_values; i++ ) {
857                 /* unpack the next regval */
858
859                 type = REG_NONE;
860                 size = 0;
861                 data_p = NULL;
862                 valuename[0] = '\0';
863                 len += tdb_unpack(buf+len, buflen-len, "fdB",
864                                   valuename,
865                                   &type,
866                                   &size,
867                                   &data_p);
868
869                 /* add the new value. Paranoid protective code -- make sure data_p is valid */
870
871                 if (*valuename && size && data_p) {
872                         regval_ctr_addvalue(values, valuename, type,
873                                         (const char *)data_p, size);
874                 }
875                 SAFE_FREE(data_p); /* 'B' option to tdb_unpack does a malloc() */
876
877                 DEBUG(8,("specific: [%s], len: %d\n", valuename, size));
878         }
879
880         return len;
881 }
882
883 /****************************************************************************
884  Pack all values in all printer keys
885  ***************************************************************************/
886
887 static int regdb_pack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
888 {
889         int             len = 0;
890         int             i;
891         REGISTRY_VALUE  *val;
892         int             num_values;
893
894         if ( !values )
895                 return 0;
896
897         num_values = regval_ctr_numvals( values );
898
899         /* pack the number of values first */
900
901         len += tdb_pack( buf+len, buflen-len, "d", num_values );
902
903         /* loop over all values */
904
905         for ( i=0; i<num_values; i++ ) {
906                 val = regval_ctr_specific_value( values, i );
907                 len += tdb_pack(buf+len, buflen-len, "fdB",
908                                 regval_name(val),
909                                 regval_type(val),
910                                 regval_size(val),
911                                 regval_data_p(val) );
912         }
913
914         return len;
915 }
916
917 /***********************************************************************
918  Retrieve an array of strings containing subkeys.  Memory should be
919  released by the caller.
920  ***********************************************************************/
921
922 int regdb_fetch_values( const char* key, REGVAL_CTR *values )
923 {
924         char *keystr = NULL;
925         TALLOC_CTX *ctx = talloc_stackframe();
926         int ret = 0;
927         TDB_DATA value;
928
929         DEBUG(10,("regdb_fetch_values: Looking for value of key [%s] \n", key));
930
931         keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key);
932         if (!keystr) {
933                 return 0;
934         }
935
936         values->seqnum = regdb_get_seqnum();
937
938         value = regdb_fetch_key_internal(ctx, keystr);
939
940         if (!value.dptr) {
941                 /* all keys have zero values by default */
942                 goto done;
943         }
944
945         regdb_unpack_values(values, value.dptr, value.dsize);
946         ret = regval_ctr_numvals(values);
947
948 done:
949         TALLOC_FREE(ctx);
950         return ret;
951 }
952
953 bool regdb_store_values( const char *key, REGVAL_CTR *values )
954 {
955         TDB_DATA old_data, data;
956         char *keystr = NULL;
957         TALLOC_CTX *ctx = talloc_stackframe();
958         int len;
959         NTSTATUS status;
960         bool result = false;
961
962         DEBUG(10,("regdb_store_values: Looking for value of key [%s] \n", key));
963
964         ZERO_STRUCT(data);
965
966         len = regdb_pack_values(values, data.dptr, data.dsize);
967         if (len <= 0) {
968                 DEBUG(0,("regdb_store_values: unable to pack values. len <= 0\n"));
969                 goto done;
970         }
971
972         data.dptr = TALLOC_ARRAY(ctx, uint8, len);
973         data.dsize = len;
974
975         len = regdb_pack_values(values, data.dptr, data.dsize);
976
977         SMB_ASSERT( len == data.dsize );
978
979         keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key );
980         if (!keystr) {
981                 goto done;
982         }
983         keystr = normalize_reg_path(ctx, keystr);
984         if (!keystr) {
985                 goto done;
986         }
987
988         old_data = dbwrap_fetch_bystring(regdb, ctx, keystr);
989
990         if ((old_data.dptr != NULL)
991             && (old_data.dsize == data.dsize)
992             && (memcmp(old_data.dptr, data.dptr, data.dsize) == 0))
993         {
994                 result = true;
995                 goto done;
996         }
997
998         status = dbwrap_trans_store(regdb, string_term_tdb_data(keystr), data,
999                                     TDB_REPLACE);
1000
1001         result = NT_STATUS_IS_OK(status);
1002
1003 done:
1004         TALLOC_FREE(ctx);
1005         return result;
1006 }
1007
1008 static WERROR regdb_get_secdesc(TALLOC_CTX *mem_ctx, const char *key,
1009                                 struct security_descriptor **psecdesc)
1010 {
1011         char *tdbkey;
1012         TDB_DATA data;
1013         NTSTATUS status;
1014         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1015         WERROR err = WERR_OK;
1016
1017         DEBUG(10, ("regdb_get_secdesc: Getting secdesc of key [%s]\n", key));
1018
1019         tdbkey = talloc_asprintf(tmp_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
1020         if (tdbkey == NULL) {
1021                 err = WERR_NOMEM;
1022                 goto done;
1023         }
1024         normalize_dbkey(tdbkey);
1025
1026         data = dbwrap_fetch_bystring(regdb, tmp_ctx, tdbkey);
1027         if (data.dptr == NULL) {
1028                 err = WERR_BADFILE;
1029                 goto done;
1030         }
1031
1032         status = unmarshall_sec_desc(mem_ctx, (uint8 *)data.dptr, data.dsize,
1033                                      psecdesc);
1034
1035         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1036                 err = WERR_NOMEM;
1037         } else if (!NT_STATUS_IS_OK(status)) {
1038                 err = WERR_REG_CORRUPT;
1039         }
1040
1041 done:
1042         TALLOC_FREE(tmp_ctx);
1043         return err;
1044 }
1045
1046 static WERROR regdb_set_secdesc(const char *key,
1047                                 struct security_descriptor *secdesc)
1048 {
1049         TALLOC_CTX *mem_ctx = talloc_stackframe();
1050         char *tdbkey;
1051         NTSTATUS status;
1052         WERROR err = WERR_NOMEM;
1053         TDB_DATA tdbdata;
1054
1055         tdbkey = talloc_asprintf(mem_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
1056         if (tdbkey == NULL) {
1057                 goto done;
1058         }
1059         normalize_dbkey(tdbkey);
1060
1061         if (secdesc == NULL) {
1062                 /* assuming a delete */
1063                 status = dbwrap_trans_delete(regdb,
1064                                              string_term_tdb_data(tdbkey));
1065                 if (NT_STATUS_IS_OK(status)) {
1066                         err = WERR_OK;
1067                 } else {
1068                         err = ntstatus_to_werror(status);
1069                 }
1070                 goto done;
1071         }
1072
1073         err = ntstatus_to_werror(marshall_sec_desc(mem_ctx, secdesc,
1074                                                    &tdbdata.dptr,
1075                                                    &tdbdata.dsize));
1076         if (!W_ERROR_IS_OK(err)) {
1077                 goto done;
1078         }
1079
1080         status = dbwrap_trans_store(regdb, string_term_tdb_data(tdbkey),
1081                                     tdbdata, 0);
1082         if (!NT_STATUS_IS_OK(status)) {
1083                 err = ntstatus_to_werror(status);
1084                 goto done;
1085         }
1086
1087  done:
1088         TALLOC_FREE(mem_ctx);
1089         return err;
1090 }
1091
1092 bool regdb_subkeys_need_update(REGSUBKEY_CTR *subkeys)
1093 {
1094         return (regdb_get_seqnum() != subkeys->seqnum);
1095 }
1096
1097 bool regdb_values_need_update(REGVAL_CTR *values)
1098 {
1099         return (regdb_get_seqnum() != values->seqnum);
1100 }
1101
1102 /* 
1103  * Table of function pointers for default access
1104  */
1105  
1106 REGISTRY_OPS regdb_ops = {
1107         .fetch_subkeys = regdb_fetch_keys,
1108         .fetch_values = regdb_fetch_values,
1109         .store_subkeys = regdb_store_keys,
1110         .store_values = regdb_store_values,
1111         .get_secdesc = regdb_get_secdesc,
1112         .set_secdesc = regdb_set_secdesc,
1113         .subkeys_need_update = regdb_subkeys_need_update,
1114         .values_need_update = regdb_values_need_update
1115 };