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