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