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