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