registry: untangle assignment and if-clause in init_registry_data().
[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 /* 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                 values = TALLOC_ZERO_P(frame, REGVAL_CTR);
200                 if (values == NULL) {
201                         goto fail;
202                 }
203
204                 regdb_fetch_values(builtin_registry_values[i].path, values);
205
206                 /* preserve existing values across restarts. Only add new ones */
207
208                 if (!regval_ctr_key_exists(values,
209                                         builtin_registry_values[i].valuename))
210                 {
211                         switch(builtin_registry_values[i].type) {
212                         case REG_DWORD:
213                                 regval_ctr_addvalue(values,
214                                         builtin_registry_values[i].valuename,
215                                         REG_DWORD,
216                                         (char*)&builtin_registry_values[i].data.dw_value,
217                                         sizeof(uint32));
218                                 break;
219
220                         case REG_SZ:
221                                 init_unistr2(&data,
222                                         builtin_registry_values[i].data.string,
223                                         UNI_STR_TERMINATE);
224                                 regval_ctr_addvalue(values,
225                                         builtin_registry_values[i].valuename,
226                                         REG_SZ,
227                                         (char*)data.buffer,
228                                         data.uni_str_len*sizeof(uint16));
229                                 break;
230
231                         default:
232                                 DEBUG(0, ("init_registry_data: invalid value "
233                                           "type in builtin_registry_values "
234                                           "[%d]\n",
235                                           builtin_registry_values[i].type));
236                         }
237                         regdb_store_values(builtin_registry_values[i].path,
238                                            values);
239                 }
240                 TALLOC_FREE(values);
241         }
242
243         TALLOC_FREE(frame);
244
245         if (regdb->transaction_commit(regdb) == -1) {
246                 DEBUG(0, ("init_registry_data: Could not commit "
247                           "transaction\n"));
248                 return false;
249         }
250
251         return true;
252
253  fail:
254
255         TALLOC_FREE(frame);
256
257         if (regdb->transaction_cancel(regdb) == -1) {
258                 smb_panic("init_registry_data: tdb_transaction_cancel "
259                           "failed\n");
260         }
261
262         return false;
263 }
264
265 /***********************************************************************
266  Open the registry database
267  ***********************************************************************/
268  
269 bool regdb_init( void )
270 {
271         const char *vstring = "INFO/version";
272         uint32 vers_id;
273
274         if ( regdb ) {
275                 DEBUG(10,("regdb_init: incrementing refcount (%d)\n", regdb_refcount));
276                 regdb_refcount++;
277                 return true;
278         }
279
280         if ( !(regdb = db_open(NULL, state_path("registry.tdb"), 0, REG_TDB_FLAGS, O_RDWR, 0600)) )
281         {
282                 regdb = db_open(NULL, state_path("registry.tdb"), 0, REG_TDB_FLAGS, O_RDWR|O_CREAT, 0600);
283                 if ( !regdb ) {
284                         DEBUG(0,("regdb_init: Failed to open registry %s (%s)\n",
285                                 state_path("registry.tdb"), strerror(errno) ));
286                         return false;
287                 }
288                 
289                 DEBUG(10,("regdb_init: Successfully created registry tdb\n"));
290         }
291
292         regdb_refcount = 1;
293
294         vers_id = dbwrap_fetch_int32(regdb, vstring);
295
296         if ( vers_id != REGVER_V1 ) {
297                 /* any upgrade code here if needed */
298                 DEBUG(10, ("regdb_init: got INFO/version = %d != %d\n",
299                            vers_id, REGVER_V1));
300         }
301
302         /* always setup the necessary keys and values */
303
304         if ( !init_registry_data() ) {
305                 DEBUG(0,("regdb_init: Failed to initialize data in registry!\n"));
306                 return false;
307         }
308
309         return true;
310 }
311
312 /***********************************************************************
313  Open the registry.  Must already have been initialized by regdb_init()
314  ***********************************************************************/
315
316 WERROR regdb_open( void )
317 {
318         WERROR result = WERR_OK;
319
320         if ( regdb ) {
321                 DEBUG(10,("regdb_open: incrementing refcount (%d)\n", regdb_refcount));
322                 regdb_refcount++;
323                 return WERR_OK;
324         }
325         
326         become_root();
327
328         regdb = db_open(NULL, state_path("registry.tdb"), 0, REG_TDB_FLAGS, O_RDWR, 0600);
329         if ( !regdb ) {
330                 result = ntstatus_to_werror( map_nt_error_from_unix( errno ) );
331                 DEBUG(0,("regdb_open: Failed to open %s! (%s)\n", 
332                         state_path("registry.tdb"), strerror(errno) ));
333         }
334
335         unbecome_root();
336
337         regdb_refcount = 1;
338         DEBUG(10,("regdb_open: refcount reset (%d)\n", regdb_refcount));
339
340         return result;
341 }
342
343 /***********************************************************************
344  ***********************************************************************/
345
346 int regdb_close( void )
347 {
348         if (regdb_refcount == 0) {
349                 return 0;
350         }
351
352         regdb_refcount--;
353
354         DEBUG(10,("regdb_close: decrementing refcount (%d)\n", regdb_refcount));
355
356         if ( regdb_refcount > 0 )
357                 return 0;
358
359         SMB_ASSERT( regdb_refcount >= 0 );
360
361         TALLOC_FREE(regdb);
362         return 0;
363 }
364
365 /***********************************************************************
366  return the tdb sequence number of the registry tdb.
367  this is an indicator for the content of the registry
368  having changed. it will change upon regdb_init, too, though.
369  ***********************************************************************/
370 int regdb_get_seqnum(void)
371 {
372         return regdb->get_seqnum(regdb);
373 }
374
375 /***********************************************************************
376  Add subkey strings to the registry tdb under a defined key
377  fmt is the same format as tdb_pack except this function only supports
378  fstrings
379  ***********************************************************************/
380
381 static bool regdb_store_keys_internal(const char *key, REGSUBKEY_CTR *ctr)
382 {
383         TDB_DATA dbuf;
384         uint8 *buffer = NULL;
385         int i = 0;
386         uint32 len, buflen;
387         bool ret = true;
388         uint32 num_subkeys = regsubkey_ctr_numkeys(ctr);
389         char *keyname = NULL;
390         TALLOC_CTX *ctx = talloc_stackframe();
391         NTSTATUS status;
392
393         if (!key) {
394                 return false;
395         }
396
397         keyname = talloc_strdup(ctx, key);
398         if (!keyname) {
399                 return false;
400         }
401         keyname = normalize_reg_path(ctx, keyname);
402
403         /* allocate some initial memory */
404
405         buffer = (uint8 *)SMB_MALLOC(1024);
406         if (buffer == NULL) {
407                 return false;
408         }
409         buflen = 1024;
410         len = 0;
411
412         /* store the number of subkeys */
413
414         len += tdb_pack(buffer+len, buflen-len, "d", num_subkeys);
415
416         /* pack all the strings */
417
418         for (i=0; i<num_subkeys; i++) {
419                 len += tdb_pack(buffer+len, buflen-len, "f",
420                                 regsubkey_ctr_specific_key(ctr, i));
421                 if (len > buflen) {
422                         /* allocate some extra space */
423                         buffer = (uint8 *)SMB_REALLOC(buffer, len*2);
424                         if(buffer == NULL) {
425                                 DEBUG(0, ("regdb_store_keys: Failed to realloc "
426                                           "memory of size [%d]\n", len*2));
427                                 ret = false;
428                                 goto done;
429                         }
430                         buflen = len*2;
431                         len = tdb_pack(buffer+len, buflen-len, "f",
432                                        regsubkey_ctr_specific_key(ctr, i));
433                 }
434         }
435
436         /* finally write out the data */
437
438         dbuf.dptr = buffer;
439         dbuf.dsize = len;
440         status = dbwrap_store_bystring(regdb, keyname, dbuf, TDB_REPLACE);
441         if (!NT_STATUS_IS_OK(status)) {
442                 ret = false;
443                 goto done;
444         }
445
446 done:
447         TALLOC_FREE(ctx);
448         SAFE_FREE(buffer);
449         return ret;
450 }
451
452 /***********************************************************************
453  Store the new subkey record and create any child key records that
454  do not currently exist
455  ***********************************************************************/
456
457 bool regdb_store_keys(const char *key, REGSUBKEY_CTR *ctr)
458 {
459         int num_subkeys, i;
460         char *path = NULL;
461         REGSUBKEY_CTR *subkeys = NULL, *old_subkeys = NULL;
462         char *oldkeyname = NULL;
463         TALLOC_CTX *ctx = talloc_stackframe();
464         NTSTATUS status;
465
466         /*
467          * fetch a list of the old subkeys so we can determine if anything has
468          * changed
469          */
470
471         if (!(old_subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR))) {
472                 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
473                 return false;
474         }
475
476         regdb_fetch_keys(key, old_subkeys);
477
478         if ((ctr->num_subkeys && old_subkeys->num_subkeys) &&
479             (ctr->num_subkeys == old_subkeys->num_subkeys)) {
480
481                 for (i = 0; i<ctr->num_subkeys; i++) {
482                         if (strcmp(ctr->subkeys[i],
483                                    old_subkeys->subkeys[i]) != 0) {
484                                 break;
485                         }
486                 }
487                 if (i == ctr->num_subkeys) {
488                         /*
489                          * Nothing changed, no point to even start a tdb
490                          * transaction
491                          */
492                         TALLOC_FREE(old_subkeys);
493                         return true;
494                 }
495         }
496
497         TALLOC_FREE(old_subkeys);
498
499         if (regdb->transaction_start(regdb) == -1) {
500                 DEBUG(0, ("regdb_store_keys: transaction_start failed\n"));
501                 goto fail;
502         }
503
504         /*
505          * Re-fetch the old keys inside the transaction
506          */
507
508         if (!(old_subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR))) {
509                 DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
510                 goto cancel;
511         }
512
513         regdb_fetch_keys(key, old_subkeys);
514
515         /* store the subkey list for the parent */
516
517         if (!regdb_store_keys_internal(key, ctr) ) {
518                 DEBUG(0,("regdb_store_keys: Failed to store new subkey list "
519                          "for parent [%s]\n", key));
520                 goto cancel;
521         }
522
523         /* now delete removed keys */
524
525         num_subkeys = regsubkey_ctr_numkeys(old_subkeys);
526         for (i=0; i<num_subkeys; i++) {
527                 oldkeyname = regsubkey_ctr_specific_key(old_subkeys, i);
528
529                 if (regsubkey_ctr_key_exists(ctr, oldkeyname)) {
530                         /*
531                          * It's still around, don't delete
532                          */
533
534                         continue;
535                 }
536
537                 path = talloc_asprintf(ctx, "%s/%s", key, oldkeyname);
538                 if (!path) {
539                         goto cancel;
540                 }
541                 path = normalize_reg_path(ctx, path);
542                 if (!path) {
543                         goto cancel;
544                 }
545                 status = dbwrap_delete_bystring(regdb, path);
546                 if (!NT_STATUS_IS_OK(status)) {
547                         DEBUG(1, ("Deleting %s failed\n", path));
548                         goto cancel;
549                 }
550
551                 TALLOC_FREE(path);
552                 path = talloc_asprintf(ctx, "%s/%s/%s",
553                                 REG_VALUE_PREFIX,
554                                 key,
555                                 oldkeyname );
556                 if (!path) {
557                         goto cancel;
558                 }
559                 path = normalize_reg_path(ctx, path);
560                 if (!path) {
561                         goto cancel;
562                 }
563
564                 /*
565                  * Ignore errors here, we might have no values around
566                  */
567                 dbwrap_delete_bystring(regdb, path);
568                 TALLOC_FREE(path);
569         }
570
571         TALLOC_FREE(old_subkeys);
572
573         /* now create records for any subkeys that don't already exist */
574
575         num_subkeys = regsubkey_ctr_numkeys(ctr);
576
577         if (num_subkeys == 0) {
578                 if (!(subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR)) ) {
579                         DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
580                         goto cancel;
581                 }
582
583                 if (!regdb_store_keys_internal(key, subkeys)) {
584                         DEBUG(0,("regdb_store_keys: Failed to store "
585                                  "new record for key [%s]\n", key));
586                         goto cancel;
587                 }
588                 TALLOC_FREE(subkeys);
589
590         }
591
592         for (i=0; i<num_subkeys; i++) {
593                 path = talloc_asprintf(ctx, "%s/%s",
594                                         key,
595                                         regsubkey_ctr_specific_key(ctr, i));
596                 if (!path) {
597                         goto cancel;
598                 }
599                 if (!(subkeys = TALLOC_ZERO_P(ctx, REGSUBKEY_CTR)) ) {
600                         DEBUG(0,("regdb_store_keys: talloc() failure!\n"));
601                         goto cancel;
602                 }
603
604                 if (regdb_fetch_keys( path, subkeys ) == -1) {
605                         /* create a record with 0 subkeys */
606                         if (!regdb_store_keys_internal(path, subkeys)) {
607                                 DEBUG(0,("regdb_store_keys: Failed to store "
608                                          "new record for key [%s]\n", path));
609                                 goto cancel;
610                         }
611                 }
612
613                 TALLOC_FREE(subkeys);
614                 TALLOC_FREE(path);
615         }
616
617         if (regdb->transaction_commit(regdb) == -1) {
618                 DEBUG(0, ("regdb_store_keys: Could not commit transaction\n"));
619                 goto fail;
620         }
621
622         TALLOC_FREE(ctx);
623         return true;
624
625 cancel:
626         if (regdb->transaction_cancel(regdb) == -1) {
627                 smb_panic("regdb_store_keys: transaction_cancel failed\n");
628         }
629
630 fail:
631         TALLOC_FREE(ctx);
632
633         return false;
634 }
635
636
637 /***********************************************************************
638  Retrieve an array of strings containing subkeys.  Memory should be
639  released by the caller.
640  ***********************************************************************/
641
642 int regdb_fetch_keys(const char *key, REGSUBKEY_CTR *ctr)
643 {
644         char *path = NULL;
645         uint32 num_items;
646         uint8 *buf;
647         uint32 buflen, len;
648         int i;
649         fstring subkeyname;
650         int ret = -1;
651         TALLOC_CTX *frame = talloc_stackframe();
652         struct db_record *rec;
653
654         DEBUG(11,("regdb_fetch_keys: Enter key => [%s]\n", key ? key : "NULL"));
655
656         path = talloc_strdup(frame, key);
657         if (!path) {
658                 goto fail;
659         }
660
661         /* convert to key format */
662         path = talloc_string_sub(frame, path, "\\", "/");
663         if (!path) {
664                 goto fail;
665         }
666         strupper_m(path);
667
668         rec = regdb->fetch_locked(regdb, frame, string_term_tdb_data(path));
669         if (rec == NULL) {
670                 ret = 0;
671                 goto fail;
672         }
673
674         ctr->seqnum = regdb_get_seqnum();
675
676         buf = rec->value.dptr;
677         buflen = rec->value.dsize;
678
679         if ( !buf ) {
680                 DEBUG(5,("regdb_fetch_keys: tdb lookup failed to locate key [%s]\n", key));
681                 goto fail;
682         }
683
684         len = tdb_unpack( buf, buflen, "d", &num_items);
685
686         for (i=0; i<num_items; i++) {
687                 len += tdb_unpack(buf+len, buflen-len, "f", subkeyname);
688                 regsubkey_ctr_addkey(ctr, subkeyname);
689         }
690
691         DEBUG(11,("regdb_fetch_keys: Exit [%d] items\n", num_items));
692
693         ret = num_items;
694  fail:
695         TALLOC_FREE(frame);
696         return ret;
697 }
698
699 /****************************************************************************
700  Unpack a list of registry values frem the TDB
701  ***************************************************************************/
702
703 static int regdb_unpack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
704 {
705         int             len = 0;
706         uint32          type;
707         fstring valuename;
708         uint32          size;
709         uint8           *data_p;
710         uint32          num_values = 0;
711         int             i;
712
713         /* loop and unpack the rest of the registry values */
714
715         len += tdb_unpack(buf+len, buflen-len, "d", &num_values);
716
717         for ( i=0; i<num_values; i++ ) {
718                 /* unpack the next regval */
719
720                 type = REG_NONE;
721                 size = 0;
722                 data_p = NULL;
723                 valuename[0] = '\0';
724                 len += tdb_unpack(buf+len, buflen-len, "fdB",
725                                   valuename,
726                                   &type,
727                                   &size,
728                                   &data_p);
729
730                 /* add the new value. Paranoid protective code -- make sure data_p is valid */
731
732                 if (*valuename && size && data_p) {
733                         regval_ctr_addvalue(values, valuename, type,
734                                         (const char *)data_p, size);
735                 }
736                 SAFE_FREE(data_p); /* 'B' option to tdb_unpack does a malloc() */
737
738                 DEBUG(8,("specific: [%s], len: %d\n", valuename, size));
739         }
740
741         return len;
742 }
743
744 /****************************************************************************
745  Pack all values in all printer keys
746  ***************************************************************************/
747
748 static int regdb_pack_values(REGVAL_CTR *values, uint8 *buf, int buflen)
749 {
750         int             len = 0;
751         int             i;
752         REGISTRY_VALUE  *val;
753         int             num_values;
754
755         if ( !values )
756                 return 0;
757
758         num_values = regval_ctr_numvals( values );
759
760         /* pack the number of values first */
761
762         len += tdb_pack( buf+len, buflen-len, "d", num_values );
763
764         /* loop over all values */
765
766         for ( i=0; i<num_values; i++ ) {
767                 val = regval_ctr_specific_value( values, i );
768                 len += tdb_pack(buf+len, buflen-len, "fdB",
769                                 regval_name(val),
770                                 regval_type(val),
771                                 regval_size(val),
772                                 regval_data_p(val) );
773         }
774
775         return len;
776 }
777
778 /***********************************************************************
779  Retrieve an array of strings containing subkeys.  Memory should be
780  released by the caller.
781  ***********************************************************************/
782
783 int regdb_fetch_values( const char* key, REGVAL_CTR *values )
784 {
785         char *keystr = NULL;
786         TALLOC_CTX *ctx = talloc_stackframe();
787         struct db_record *rec;
788         int ret = 0;
789
790         DEBUG(10,("regdb_fetch_values: Looking for value of key [%s] \n", key));
791
792         keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key);
793         if (!keystr) {
794                 return 0;
795         }
796         keystr = normalize_reg_path(ctx, keystr);
797         if (!keystr) {
798                 goto done;
799         }
800
801         rec = regdb->fetch_locked(regdb, ctx, string_term_tdb_data(keystr));
802         if (rec == NULL) {
803                 goto done;
804         }
805
806         values->seqnum = regdb_get_seqnum();
807
808         if (!rec->value.dptr) {
809                 /* all keys have zero values by default */
810                 goto done;
811         }
812
813         regdb_unpack_values(values, rec->value.dptr, rec->value.dsize);
814         ret = regval_ctr_numvals(values);
815
816 done:
817         TALLOC_FREE(ctx);
818         return ret;
819 }
820
821 bool regdb_store_values( const char *key, REGVAL_CTR *values )
822 {
823         TDB_DATA old_data, data;
824         char *keystr = NULL;
825         TALLOC_CTX *ctx = talloc_stackframe();
826         int len, ret;
827         bool result = false;
828
829         DEBUG(10,("regdb_store_values: Looking for value of key [%s] \n", key));
830
831         ZERO_STRUCT(data);
832
833         len = regdb_pack_values(values, data.dptr, data.dsize);
834         if (len <= 0) {
835                 DEBUG(0,("regdb_store_values: unable to pack values. len <= 0\n"));
836                 goto done;
837         }
838
839         data.dptr = TALLOC_ARRAY(ctx, uint8, len);
840         data.dsize = len;
841
842         len = regdb_pack_values(values, data.dptr, data.dsize);
843
844         SMB_ASSERT( len == data.dsize );
845
846         keystr = talloc_asprintf(ctx, "%s/%s", REG_VALUE_PREFIX, key );
847         if (!keystr) {
848                 goto done;
849         }
850         keystr = normalize_reg_path(ctx, keystr);
851         if (!keystr) {
852                 goto done;
853         }
854
855         old_data = dbwrap_fetch_bystring(regdb, ctx, keystr);
856
857         if ((old_data.dptr != NULL)
858             && (old_data.dsize == data.dsize)
859             && (memcmp(old_data.dptr, data.dptr, data.dsize) == 0))
860         {
861                 result = true;
862                 goto done;
863         }
864
865         ret = dbwrap_trans_store(regdb, string_term_tdb_data(keystr), data,
866                                  TDB_REPLACE);
867         result = (ret != -1);
868
869 done:
870         TALLOC_FREE(ctx);
871         return result;
872 }
873
874 static WERROR regdb_get_secdesc(TALLOC_CTX *mem_ctx, const char *key,
875                                 struct security_descriptor **psecdesc)
876 {
877         char *tdbkey;
878         TDB_DATA data;
879         NTSTATUS status;
880         TALLOC_CTX *tmp_ctx = talloc_stackframe();
881         WERROR err = WERR_OK;
882
883         DEBUG(10, ("regdb_get_secdesc: Getting secdesc of key [%s]\n", key));
884
885         tdbkey = talloc_asprintf(tmp_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
886         if (tdbkey == NULL) {
887                 err = WERR_NOMEM;
888                 goto done;
889         }
890         normalize_dbkey(tdbkey);
891
892         data = dbwrap_fetch_bystring(regdb, tmp_ctx, tdbkey);
893         if (data.dptr == NULL) {
894                 err = WERR_BADFILE;
895                 goto done;
896         }
897
898         status = unmarshall_sec_desc(mem_ctx, (uint8 *)data.dptr, data.dsize,
899                                      psecdesc);
900
901         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
902                 err = WERR_NOMEM;
903         } else if (!NT_STATUS_IS_OK(status)) {
904                 err = WERR_REG_CORRUPT;
905         }
906
907 done:
908         TALLOC_FREE(tmp_ctx);
909         return err;
910 }
911
912 static WERROR regdb_set_secdesc(const char *key,
913                                 struct security_descriptor *secdesc)
914 {
915         TALLOC_CTX *mem_ctx = talloc_stackframe();
916         char *tdbkey;
917         WERROR err = WERR_NOMEM;
918         TDB_DATA tdbdata;
919         int tdb_ret;
920
921         tdbkey = talloc_asprintf(mem_ctx, "%s/%s", REG_SECDESC_PREFIX, key);
922         if (tdbkey == NULL) {
923                 goto done;
924         }
925         normalize_dbkey(tdbkey);
926
927         if (secdesc == NULL) {
928                 /* assuming a delete */
929                 tdb_ret = dbwrap_trans_delete(regdb,
930                                               string_term_tdb_data(tdbkey));
931                 if (tdb_ret == -1) {
932                         err = ntstatus_to_werror(map_nt_error_from_unix(errno));
933                 } else {
934                         err = WERR_OK;
935                 }
936                 goto done;
937         }
938
939         err = ntstatus_to_werror(marshall_sec_desc(mem_ctx, secdesc,
940                                                    &tdbdata.dptr,
941                                                    &tdbdata.dsize));
942         if (!W_ERROR_IS_OK(err)) {
943                 goto done;
944         }
945
946         tdb_ret = dbwrap_trans_store(regdb, string_term_tdb_data(tdbkey),
947                                      tdbdata, 0);
948         if (tdb_ret == -1) {
949                 err = ntstatus_to_werror(map_nt_error_from_unix(errno));
950                 goto done;
951         }
952
953  done:
954         TALLOC_FREE(mem_ctx);
955         return err;
956 }
957
958 bool regdb_subkeys_need_update(REGSUBKEY_CTR *subkeys)
959 {
960         return (regdb_get_seqnum() != subkeys->seqnum);
961 }
962
963 bool regdb_values_need_update(REGVAL_CTR *values)
964 {
965         return (regdb_get_seqnum() != values->seqnum);
966 }
967
968 /* 
969  * Table of function pointers for default access
970  */
971  
972 REGISTRY_OPS regdb_ops = {
973         .fetch_subkeys = regdb_fetch_keys,
974         .fetch_values = regdb_fetch_values,
975         .store_subkeys = regdb_store_keys,
976         .store_values = regdb_store_values,
977         .get_secdesc = regdb_get_secdesc,
978         .set_secdesc = regdb_set_secdesc,
979         .subkeys_need_update = regdb_subkeys_need_update,
980         .values_need_update = regdb_values_need_update
981 };