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