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