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