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