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