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