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