registry: check for existence of key in regdb_get_secdesc() before proceeding.
[kai/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
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 /**
774  * Check for the existence of a key.
775  *
776  * Existence of a key is authoritatively defined by its
777  * existence in the list of subkeys of its parent key.
778  * The exeption of this are keys without a parent key,
779  * i.e. the "base" keys (HKLM, HKCU, ...).
780  */
781 static bool regdb_key_exists(const char *key)
782 {
783         TALLOC_CTX *mem_ctx = talloc_stackframe();
784         TDB_DATA value;
785         bool ret = false;
786         char *path, *p;
787
788         if (key == NULL) {
789                 goto done;
790         }
791
792         path = normalize_reg_path(mem_ctx, key);
793         if (path == NULL) {
794                 DEBUG(0, ("out of memory! (talloc failed)\n"));
795                 goto done;
796         }
797
798         if (*path == '\0') {
799                 goto done;
800         }
801
802         p = strrchr(path, '/');
803         if (p == NULL) {
804                 /* this is a base key */
805                 value = regdb_fetch_key_internal(mem_ctx, path);
806                 ret = (value.dptr != NULL);
807         } else {
808                 /* get the list of subkeys of the parent key */
809                 uint32 num_items, len, i;
810                 fstring subkeyname;
811
812                 *p = '\0';
813                 p++;
814                 value = regdb_fetch_key_internal(mem_ctx, path);
815                 if (value.dptr == NULL) {
816                         goto done;
817                 }
818
819                 len = tdb_unpack(value.dptr, value.dsize, "d", &num_items);
820                 for (i = 0; i < num_items; i++) {
821                         len += tdb_unpack(value.dptr +len, value.dsize -len,
822                                           "f", &subkeyname);
823                         if (strequal(subkeyname, p)) {
824                                 ret = true;
825                                 goto done;
826                         }
827                 }
828         }
829
830 done:
831         TALLOC_FREE(mem_ctx);
832         return ret;
833 }
834
835
836 /***********************************************************************
837  Retrieve an array of strings containing subkeys.  Memory should be
838  released by the caller.
839  ***********************************************************************/
840
841 int regdb_fetch_keys(const char *key, REGSUBKEY_CTR *ctr)
842 {
843         WERROR werr;
844         uint32 num_items;
845         uint8 *buf;
846         uint32 buflen, len;
847         int i;
848         fstring subkeyname;
849         int ret = -1;
850         TALLOC_CTX *frame = talloc_stackframe();
851         TDB_DATA value;
852
853         DEBUG(11,("regdb_fetch_keys: Enter key => [%s]\n", key ? key : "NULL"));
854
855         if (!regdb_key_exists(key)) {
856                 goto fail;
857         }
858
859         ctr->seqnum = regdb_get_seqnum();
860
861         value = regdb_fetch_key_internal(frame, key);
862
863         buf = value.dptr;
864         buflen = value.dsize;
865
866         if ( !buf ) {
867                 DEBUG(5,("regdb_fetch_keys: tdb lookup failed to locate key [%s]\n", key));
868                 goto fail;
869         }
870
871         len = tdb_unpack( buf, buflen, "d", &num_items);
872
873         for (i=0; i<num_items; i++) {
874                 len += tdb_unpack(buf+len, buflen-len, "f", subkeyname);
875                 werr = regsubkey_ctr_addkey(ctr, subkeyname);
876                 if (!W_ERROR_IS_OK(werr)) {
877                         DEBUG(5, ("regdb_fetch_keys: regsubkey_ctr_addkey "
878                                   "failed: %s\n", dos_errstr(werr)));
879                         goto fail;
880                 }
881         }
882
883         DEBUG(11,("regdb_fetch_keys: Exit [%d] items\n", num_items));
884
885         ret = num_items;
886  fail:
887         TALLOC_FREE(frame);
888         return ret;
889 }
890
891 /****************************************************************************
892  Unpack a list of registry values frem the TDB
893  ***************************************************************************/
894
895 static int regdb_unpack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
896 {
897         int             len = 0;
898         uint32          type;
899         fstring valuename;
900         uint32          size;
901         uint8           *data_p;
902         uint32          num_values = 0;
903         int             i;
904
905         /* loop and unpack the rest of the registry values */
906
907         len += tdb_unpack(buf+len, buflen-len, "d", &num_values);
908
909         for ( i=0; i<num_values; i++ ) {
910                 /* unpack the next regval */
911
912                 type = REG_NONE;
913                 size = 0;
914                 data_p = NULL;
915                 valuename[0] = '\0';
916                 len += tdb_unpack(buf+len, buflen-len, "fdB",
917                                   valuename,
918                                   &type,
919                                   &size,
920                                   &data_p);
921
922                 /* add the new value. Paranoid protective code -- make sure data_p is valid */
923
924                 if (*valuename && size && data_p) {
925                         regval_ctr_addvalue(values, valuename, type,
926                                         (const char *)data_p, size);
927                 }
928                 SAFE_FREE(data_p); /* 'B' option to tdb_unpack does a malloc() */
929
930                 DEBUG(8,("specific: [%s], len: %d\n", valuename, size));
931         }
932
933         return len;
934 }
935
936 /****************************************************************************
937  Pack all values in all printer keys
938  ***************************************************************************/
939
940 static int regdb_pack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
941 {
942         int             len = 0;
943         int             i;
944         REGISTRY_VALUE  *val;
945         int             num_values;
946
947         if ( !values )
948                 return 0;
949
950         num_values = regval_ctr_numvals( values );
951
952         /* pack the number of values first */
953
954         len += tdb_pack( buf+len, buflen-len, "d", num_values );
955
956         /* loop over all values */
957
958         for ( i=0; i<num_values; i++ ) {
959                 val = regval_ctr_specific_value( values, i );
960                 len += tdb_pack(buf+len, buflen-len, "fdB",
961                                 regval_name(val),
962                                 regval_type(val),
963                                 regval_size(val),
964                                 regval_data_p(val) );
965         }
966
967         return len;
968 }
969
970 /***********************************************************************
971  Retrieve an array of strings containing subkeys.  Memory should be
972  released by the caller.
973  ***********************************************************************/
974
975 int regdb_fetch_values( const char* key, REGVAL_CTR *values )
976 {
977         char *keystr = NULL;
978         TALLOC_CTX *ctx = talloc_stackframe();
979         int ret = 0;
980         TDB_DATA value;
981
982         DEBUG(10,("regdb_fetch_values: Looking for value of key [%s] \n", key));
983
984         if (!regdb_key_exists(key)) {
985                 goto done;
986         }
987
988         keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key);
989         if (!keystr) {
990                 goto done;
991         }
992
993         values->seqnum = regdb_get_seqnum();
994
995         value = regdb_fetch_key_internal(ctx, keystr);
996
997         if (!value.dptr) {
998                 /* all keys have zero values by default */
999                 goto done;
1000         }
1001
1002         regdb_unpack_values(values, value.dptr, value.dsize);
1003         ret = regval_ctr_numvals(values);
1004
1005 done:
1006         TALLOC_FREE(ctx);
1007         return ret;
1008 }
1009
1010 bool regdb_store_values( const char *key, REGVAL_CTR *values )
1011 {
1012         TDB_DATA old_data, data;
1013         char *keystr = NULL;
1014         TALLOC_CTX *ctx = talloc_stackframe();
1015         int len;
1016         NTSTATUS status;
1017         bool result = false;
1018
1019         DEBUG(10,("regdb_store_values: Looking for value of key [%s] \n", key));
1020
1021         if (!regdb_key_exists(key)) {
1022                 goto done;
1023         }
1024
1025         ZERO_STRUCT(data);
1026
1027         len = regdb_pack_values(values, data.dptr, data.dsize);
1028         if (len <= 0) {
1029                 DEBUG(0,("regdb_store_values: unable to pack values. len <= 0\n"));
1030                 goto done;
1031         }
1032
1033         data.dptr = TALLOC_ARRAY(ctx, uint8, len);
1034         data.dsize = len;
1035
1036         len = regdb_pack_values(values, data.dptr, data.dsize);
1037
1038         SMB_ASSERT( len == data.dsize );
1039
1040         keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key );
1041         if (!keystr) {
1042                 goto done;
1043         }
1044         keystr = normalize_reg_path(ctx, keystr);
1045         if (!keystr) {
1046                 goto done;
1047         }
1048
1049         old_data = dbwrap_fetch_bystring(regdb, ctx, keystr);
1050
1051         if ((old_data.dptr != NULL)
1052             && (old_data.dsize == data.dsize)
1053             && (memcmp(old_data.dptr, data.dptr, data.dsize) == 0))
1054         {
1055                 result = true;
1056                 goto done;
1057         }
1058
1059         status = dbwrap_trans_store(regdb, string_term_tdb_data(keystr), data,
1060                                     TDB_REPLACE);
1061
1062         result = NT_STATUS_IS_OK(status);
1063
1064 done:
1065         TALLOC_FREE(ctx);
1066         return result;
1067 }
1068
1069 static WERROR regdb_get_secdesc(TALLOC_CTX *mem_ctx, const char *key,
1070                                 struct security_descriptor **psecdesc)
1071 {
1072         char *tdbkey;
1073         TDB_DATA data;
1074         NTSTATUS status;
1075         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1076         WERROR err = WERR_OK;
1077
1078         DEBUG(10, ("regdb_get_secdesc: Getting secdesc of key [%s]\n", key));
1079
1080         if (!regdb_key_exists(key)) {
1081                 err = WERR_BADFILE;
1082                 goto done;
1083         }
1084
1085         tdbkey = talloc_asprintf(tmp_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
1086         if (tdbkey == NULL) {
1087                 err = WERR_NOMEM;
1088                 goto done;
1089         }
1090         normalize_dbkey(tdbkey);
1091
1092         data = dbwrap_fetch_bystring(regdb, tmp_ctx, tdbkey);
1093         if (data.dptr == NULL) {
1094                 err = WERR_BADFILE;
1095                 goto done;
1096         }
1097
1098         status = unmarshall_sec_desc(mem_ctx, (uint8 *)data.dptr, data.dsize,
1099                                      psecdesc);
1100
1101         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1102                 err = WERR_NOMEM;
1103         } else if (!NT_STATUS_IS_OK(status)) {
1104                 err = WERR_REG_CORRUPT;
1105         }
1106
1107 done:
1108         TALLOC_FREE(tmp_ctx);
1109         return err;
1110 }
1111
1112 static WERROR regdb_set_secdesc(const char *key,
1113                                 struct security_descriptor *secdesc)
1114 {
1115         TALLOC_CTX *mem_ctx = talloc_stackframe();
1116         char *tdbkey;
1117         NTSTATUS status;
1118         WERROR err = WERR_NOMEM;
1119         TDB_DATA tdbdata;
1120
1121         tdbkey = talloc_asprintf(mem_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
1122         if (tdbkey == NULL) {
1123                 goto done;
1124         }
1125         normalize_dbkey(tdbkey);
1126
1127         if (secdesc == NULL) {
1128                 /* assuming a delete */
1129                 status = dbwrap_trans_delete(regdb,
1130                                              string_term_tdb_data(tdbkey));
1131                 if (NT_STATUS_IS_OK(status)) {
1132                         err = WERR_OK;
1133                 } else {
1134                         err = ntstatus_to_werror(status);
1135                 }
1136                 goto done;
1137         }
1138
1139         err = ntstatus_to_werror(marshall_sec_desc(mem_ctx, secdesc,
1140                                                    &tdbdata.dptr,
1141                                                    &tdbdata.dsize));
1142         if (!W_ERROR_IS_OK(err)) {
1143                 goto done;
1144         }
1145
1146         status = dbwrap_trans_store(regdb, string_term_tdb_data(tdbkey),
1147                                     tdbdata, 0);
1148         if (!NT_STATUS_IS_OK(status)) {
1149                 err = ntstatus_to_werror(status);
1150                 goto done;
1151         }
1152
1153  done:
1154         TALLOC_FREE(mem_ctx);
1155         return err;
1156 }
1157
1158 bool regdb_subkeys_need_update(REGSUBKEY_CTR *subkeys)
1159 {
1160         return (regdb_get_seqnum() != subkeys->seqnum);
1161 }
1162
1163 bool regdb_values_need_update(REGVAL_CTR *values)
1164 {
1165         return (regdb_get_seqnum() != values->seqnum);
1166 }
1167
1168 /* 
1169  * Table of function pointers for default access
1170  */
1171  
1172 REGISTRY_OPS regdb_ops = {
1173         .fetch_subkeys = regdb_fetch_keys,
1174         .fetch_values = regdb_fetch_values,
1175         .store_subkeys = regdb_store_keys,
1176         .store_values = regdb_store_values,
1177         .get_secdesc = regdb_get_secdesc,
1178         .set_secdesc = regdb_set_secdesc,
1179         .subkeys_need_update = regdb_subkeys_need_update,
1180         .values_need_update = regdb_values_need_update
1181 };