s3:registry: move reg_objects.h to registry/ and use it only where needed
[mat/samba.git] / source3 / registry / reg_api.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  Virtual Windows Registry Layer
4  *  Copyright (C) Volker Lendecke 2006
5  *  Copyright (C) Michael Adam 2007-2008
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 /* Attempt to wrap the existing API in a more winreg.idl-like way */
22
23 /*
24  * Here is a list of winreg.idl functions and corresponding implementations
25  * provided here:
26  *
27  * 0x00         winreg_OpenHKCR
28  * 0x01         winreg_OpenHKCU
29  * 0x02         winreg_OpenHKLM
30  * 0x03         winreg_OpenHKPD
31  * 0x04         winreg_OpenHKU
32  * 0x05         winreg_CloseKey
33  * 0x06         winreg_CreateKey                        reg_createkey
34  * 0x07         winreg_DeleteKey                        reg_deletekey
35  * 0x08         winreg_DeleteValue                      reg_deletevalue
36  * 0x09         winreg_EnumKey                          reg_enumkey
37  * 0x0a         winreg_EnumValue                        reg_enumvalue
38  * 0x0b         winreg_FlushKey
39  * 0x0c         winreg_GetKeySecurity                   reg_getkeysecurity
40  * 0x0d         winreg_LoadKey
41  * 0x0e         winreg_NotifyChangeKeyValue
42  * 0x0f         winreg_OpenKey                          reg_openkey
43  * 0x10         winreg_QueryInfoKey                     reg_queryinfokey
44  * 0x11         winreg_QueryValue                       reg_queryvalue
45  * 0x12         winreg_ReplaceKey
46  * 0x13         winreg_RestoreKey                       reg_restorekey
47  * 0x14         winreg_SaveKey                          reg_savekey
48  * 0x15         winreg_SetKeySecurity                   reg_setkeysecurity
49  * 0x16         winreg_SetValue                         reg_setvalue
50  * 0x17         winreg_UnLoadKey
51  * 0x18         winreg_InitiateSystemShutdown
52  * 0x19         winreg_AbortSystemShutdown
53  * 0x1a         winreg_GetVersion                       reg_getversion
54  * 0x1b         winreg_OpenHKCC
55  * 0x1c         winreg_OpenHKDD
56  * 0x1d         winreg_QueryMultipleValues
57  * 0x1e         winreg_InitiateSystemShutdownEx
58  * 0x1f         winreg_SaveKeyEx
59  * 0x20         winreg_OpenHKPT
60  * 0x21         winreg_OpenHKPN
61  * 0x22         winreg_QueryMultipleValues2
62  *
63  */
64
65 #include "includes.h"
66 #include "registry.h"
67 #include "reg_cachehook.h"
68 #include "regfio.h"
69 #include "reg_util_internal.h"
70 #include "reg_backend_db.h"
71 #include "reg_dispatcher.h"
72 #include "reg_util_marshalling.h"
73 #include "reg_objects.h"
74
75 #undef DBGC_CLASS
76 #define DBGC_CLASS DBGC_REGISTRY
77
78
79 /**********************************************************************
80  * Helper functions
81  **********************************************************************/
82
83 static WERROR fill_value_cache(struct registry_key *key)
84 {
85         WERROR werr;
86
87         if (key->values != NULL) {
88                 if (!reg_values_need_update(key->key, key->values)) {
89                         return WERR_OK;
90                 }
91         }
92
93         werr = regval_ctr_init(key, &(key->values));
94         W_ERROR_NOT_OK_RETURN(werr);
95
96         if (fetch_reg_values(key->key, key->values) == -1) {
97                 TALLOC_FREE(key->values);
98                 return WERR_BADFILE;
99         }
100
101         return WERR_OK;
102 }
103
104 static WERROR fill_subkey_cache(struct registry_key *key)
105 {
106         WERROR werr;
107
108         if (key->subkeys != NULL) {
109                 if (!reg_subkeys_need_update(key->key, key->subkeys)) {
110                         return WERR_OK;
111                 }
112         }
113
114         werr = regsubkey_ctr_init(key, &(key->subkeys));
115         W_ERROR_NOT_OK_RETURN(werr);
116
117         if (fetch_reg_keys(key->key, key->subkeys) == -1) {
118                 TALLOC_FREE(key->subkeys);
119                 return WERR_NO_MORE_ITEMS;
120         }
121
122         return WERR_OK;
123 }
124
125 static int regkey_destructor(struct registry_key_handle *key)
126 {
127         return regdb_close();
128 }
129
130 static WERROR regkey_open_onelevel(TALLOC_CTX *mem_ctx, 
131                                    struct registry_key *parent,
132                                    const char *name,
133                                    const struct nt_user_token *token,
134                                    uint32 access_desired,
135                                    struct registry_key **pregkey)
136 {
137         WERROR          result = WERR_OK;
138         struct registry_key *regkey;
139         struct registry_key_handle *key;
140         struct regsubkey_ctr    *subkeys = NULL;
141
142         DEBUG(7,("regkey_open_onelevel: name = [%s]\n", name));
143
144         SMB_ASSERT(strchr(name, '\\') == NULL);
145
146         if (!(regkey = TALLOC_ZERO_P(mem_ctx, struct registry_key)) ||
147             !(regkey->token = dup_nt_token(regkey, token)) ||
148             !(regkey->key = TALLOC_ZERO_P(regkey, struct registry_key_handle)))
149         {
150                 result = WERR_NOMEM;
151                 goto done;
152         }
153
154         if ( !(W_ERROR_IS_OK(result = regdb_open())) ) {
155                 goto done;
156         }
157
158         key = regkey->key;
159         talloc_set_destructor(key, regkey_destructor);
160
161         /* initialization */
162
163         key->type = REG_KEY_GENERIC;
164
165         if (name[0] == '\0') {
166                 /*
167                  * Open a copy of the parent key
168                  */
169                 if (!parent) {
170                         result = WERR_BADFILE;
171                         goto done;
172                 }
173                 key->name = talloc_strdup(key, parent->key->name);
174         }
175         else {
176                 /*
177                  * Normal subkey open
178                  */
179                 key->name = talloc_asprintf(key, "%s%s%s",
180                                             parent ? parent->key->name : "",
181                                             parent ? "\\": "",
182                                             name);
183         }
184
185         if (key->name == NULL) {
186                 result = WERR_NOMEM;
187                 goto done;
188         }
189
190         /* Tag this as a Performance Counter Key */
191
192         if( StrnCaseCmp(key->name, KEY_HKPD, strlen(KEY_HKPD)) == 0 )
193                 key->type = REG_KEY_HKPD;
194
195         /* Look up the table of registry I/O operations */
196
197         if ( !(key->ops = reghook_cache_find( key->name )) ) {
198                 DEBUG(0,("reg_open_onelevel: Failed to assign "
199                          "registry_ops to [%s]\n", key->name ));
200                 result = WERR_BADFILE;
201                 goto done;
202         }
203
204         /* check if the path really exists; failed is indicated by -1 */
205         /* if the subkey count failed, bail out */
206
207         result = regsubkey_ctr_init(key, &subkeys);
208         if (!W_ERROR_IS_OK(result)) {
209                 goto done;
210         }
211
212         if ( fetch_reg_keys( key, subkeys ) == -1 )  {
213                 result = WERR_BADFILE;
214                 goto done;
215         }
216
217         TALLOC_FREE( subkeys );
218
219         if ( !regkey_access_check( key, access_desired, &key->access_granted,
220                                    token ) ) {
221                 result = WERR_ACCESS_DENIED;
222                 goto done;
223         }
224
225         *pregkey = regkey;
226         result = WERR_OK;
227
228 done:
229         if ( !W_ERROR_IS_OK(result) ) {
230                 TALLOC_FREE(regkey);
231         }
232
233         return result;
234 }
235
236 WERROR reg_openhive(TALLOC_CTX *mem_ctx, const char *hive,
237                     uint32 desired_access,
238                     const struct nt_user_token *token,
239                     struct registry_key **pkey)
240 {
241         SMB_ASSERT(hive != NULL);
242         SMB_ASSERT(hive[0] != '\0');
243         SMB_ASSERT(strchr(hive, '\\') == NULL);
244
245         return regkey_open_onelevel(mem_ctx, NULL, hive, token, desired_access,
246                                     pkey);
247 }
248
249
250 /**********************************************************************
251  * The API functions
252  **********************************************************************/
253
254 WERROR reg_openkey(TALLOC_CTX *mem_ctx, struct registry_key *parent,
255                    const char *name, uint32 desired_access,
256                    struct registry_key **pkey)
257 {
258         struct registry_key *direct_parent = parent;
259         WERROR err;
260         char *p, *path, *to_free;
261         size_t len;
262
263         if (!(path = SMB_STRDUP(name))) {
264                 return WERR_NOMEM;
265         }
266         to_free = path;
267
268         len = strlen(path);
269
270         if ((len > 0) && (path[len-1] == '\\')) {
271                 path[len-1] = '\0';
272         }
273
274         while ((p = strchr(path, '\\')) != NULL) {
275                 char *name_component;
276                 struct registry_key *tmp;
277
278                 if (!(name_component = SMB_STRNDUP(path, (p - path)))) {
279                         err = WERR_NOMEM;
280                         goto error;
281                 }
282
283                 err = regkey_open_onelevel(mem_ctx, direct_parent,
284                                            name_component, parent->token,
285                                            KEY_ENUMERATE_SUB_KEYS, &tmp);
286                 SAFE_FREE(name_component);
287
288                 if (!W_ERROR_IS_OK(err)) {
289                         goto error;
290                 }
291                 if (direct_parent != parent) {
292                         TALLOC_FREE(direct_parent);
293                 }
294
295                 direct_parent = tmp;
296                 path = p+1;
297         }
298
299         err = regkey_open_onelevel(mem_ctx, direct_parent, path, parent->token,
300                                    desired_access, pkey);
301  error:
302         if (direct_parent != parent) {
303                 TALLOC_FREE(direct_parent);
304         }
305         SAFE_FREE(to_free);
306         return err;
307 }
308
309 WERROR reg_enumkey(TALLOC_CTX *mem_ctx, struct registry_key *key,
310                    uint32 idx, char **name, NTTIME *last_write_time)
311 {
312         WERROR err;
313
314         if (!(key->key->access_granted & KEY_ENUMERATE_SUB_KEYS)) {
315                 return WERR_ACCESS_DENIED;
316         }
317
318         if (!W_ERROR_IS_OK(err = fill_subkey_cache(key))) {
319                 return err;
320         }
321
322         if (idx >= regsubkey_ctr_numkeys(key->subkeys)) {
323                 return WERR_NO_MORE_ITEMS;
324         }
325
326         if (!(*name = talloc_strdup(mem_ctx,
327                         regsubkey_ctr_specific_key(key->subkeys, idx))))
328         {
329                 return WERR_NOMEM;
330         }
331
332         if (last_write_time) {
333                 *last_write_time = 0;
334         }
335
336         return WERR_OK;
337 }
338
339 WERROR reg_enumvalue(TALLOC_CTX *mem_ctx, struct registry_key *key,
340                      uint32 idx, char **pname, struct registry_value **pval)
341 {
342         struct registry_value *val;
343         struct regval_blob *blob;
344         WERROR err;
345
346         if (!(key->key->access_granted & KEY_QUERY_VALUE)) {
347                 return WERR_ACCESS_DENIED;
348         }
349
350         if (!(W_ERROR_IS_OK(err = fill_value_cache(key)))) {
351                 return err;
352         }
353
354         if (idx >= regval_ctr_numvals(key->values)) {
355                 return WERR_NO_MORE_ITEMS;
356         }
357
358         blob = regval_ctr_specific_value(key->values, idx);
359         err = registry_pull_value(mem_ctx, &val,
360                                   regval_type(blob),
361                                   regval_data_p(blob),
362                                   regval_size(blob),
363                                   regval_size(blob));
364         if (!W_ERROR_IS_OK(err)) {
365                 return err;
366         }
367
368         if (pname
369             && !(*pname = talloc_strdup(
370                          mem_ctx, regval_name(blob)))) {
371                 SAFE_FREE(val);
372                 return WERR_NOMEM;
373         }
374
375         *pval = val;
376         return WERR_OK;
377 }
378
379 WERROR reg_queryvalue(TALLOC_CTX *mem_ctx, struct registry_key *key,
380                       const char *name, struct registry_value **pval)
381 {
382         WERROR err;
383         uint32 i;
384
385         if (!(key->key->access_granted & KEY_QUERY_VALUE)) {
386                 return WERR_ACCESS_DENIED;
387         }
388
389         if (!(W_ERROR_IS_OK(err = fill_value_cache(key)))) {
390                 return err;
391         }
392
393         for (i=0; i < regval_ctr_numvals(key->values); i++) {
394                 struct regval_blob *blob;
395                 blob = regval_ctr_specific_value(key->values, i);
396                 if (strequal(regval_name(blob), name)) {
397                         return reg_enumvalue(mem_ctx, key, i, NULL, pval);
398                 }
399         }
400
401         return WERR_BADFILE;
402 }
403
404 WERROR reg_queryinfokey(struct registry_key *key, uint32_t *num_subkeys,
405                         uint32_t *max_subkeylen, uint32_t *max_subkeysize, 
406                         uint32_t *num_values, uint32_t *max_valnamelen, 
407                         uint32_t *max_valbufsize, uint32_t *secdescsize,
408                         NTTIME *last_changed_time)
409 {
410         uint32 i, max_size;
411         size_t max_len;
412         TALLOC_CTX *mem_ctx;
413         WERROR err;
414         struct security_descriptor *secdesc;
415
416         if (!(key->key->access_granted & KEY_QUERY_VALUE)) {
417                 return WERR_ACCESS_DENIED;
418         }
419
420         if (!W_ERROR_IS_OK(fill_subkey_cache(key)) ||
421             !W_ERROR_IS_OK(fill_value_cache(key))) {
422                 return WERR_BADFILE;
423         }
424
425         max_len = 0;
426         for (i=0; i< regsubkey_ctr_numkeys(key->subkeys); i++) {
427                 max_len = MAX(max_len,
428                         strlen(regsubkey_ctr_specific_key(key->subkeys, i)));
429         }
430
431         *num_subkeys = regsubkey_ctr_numkeys(key->subkeys);
432         *max_subkeylen = max_len;
433         *max_subkeysize = 0;    /* Class length? */
434
435         max_len = 0;
436         max_size = 0;
437         for (i=0; i < regval_ctr_numvals(key->values); i++) {
438                 struct regval_blob *blob;
439                 blob = regval_ctr_specific_value(key->values, i);
440                 max_len = MAX(max_len, strlen(regval_name(blob)));
441                 max_size = MAX(max_size, regval_size(blob));
442         }
443
444         *num_values = regval_ctr_numvals(key->values);
445         *max_valnamelen = max_len;
446         *max_valbufsize = max_size;
447
448         if (!(mem_ctx = talloc_new(key))) {
449                 return WERR_NOMEM;
450         }
451
452         err = regkey_get_secdesc(mem_ctx, key->key, &secdesc);
453         if (!W_ERROR_IS_OK(err)) {
454                 TALLOC_FREE(mem_ctx);
455                 return err;
456         }
457
458         *secdescsize = ndr_size_security_descriptor(secdesc, 0);
459         TALLOC_FREE(mem_ctx);
460
461         *last_changed_time = 0;
462
463         return WERR_OK;
464 }
465
466 WERROR reg_createkey(TALLOC_CTX *ctx, struct registry_key *parent,
467                      const char *subkeypath, uint32 desired_access,
468                      struct registry_key **pkey,
469                      enum winreg_CreateAction *paction)
470 {
471         struct registry_key *key = parent;
472         struct registry_key *create_parent;
473         TALLOC_CTX *mem_ctx;
474         char *path, *end;
475         WERROR err;
476
477         /*
478          * We must refuse to handle subkey-paths containing
479          * a '/' character because at a lower level, after
480          * normalization, '/' is treated as a key separator
481          * just like '\\'.
482          */
483         if (strchr(subkeypath, '/') != NULL) {
484                 return WERR_INVALID_PARAM;
485         }
486
487         if (!(mem_ctx = talloc_new(ctx))) return WERR_NOMEM;
488
489         if (!(path = talloc_strdup(mem_ctx, subkeypath))) {
490                 err = WERR_NOMEM;
491                 goto done;
492         }
493
494         while ((end = strchr(path, '\\')) != NULL) {
495                 struct registry_key *tmp;
496                 enum winreg_CreateAction action;
497
498                 *end = '\0';
499
500                 err = reg_createkey(mem_ctx, key, path,
501                                     KEY_ENUMERATE_SUB_KEYS, &tmp, &action);
502                 if (!W_ERROR_IS_OK(err)) {
503                         goto done;
504                 }
505
506                 if (key != parent) {
507                         TALLOC_FREE(key);
508                 }
509
510                 key = tmp;
511                 path = end+1;
512         }
513
514         /*
515          * At this point, "path" contains the one-element subkey of "key". We
516          * can try to open it.
517          */
518
519         err = reg_openkey(ctx, key, path, desired_access, pkey);
520         if (W_ERROR_IS_OK(err)) {
521                 if (paction != NULL) {
522                         *paction = REG_OPENED_EXISTING_KEY;
523                 }
524                 goto done;
525         }
526
527         if (!W_ERROR_EQUAL(err, WERR_BADFILE)) {
528                 /*
529                  * Something but "notfound" has happened, so bail out
530                  */
531                 goto done;
532         }
533
534         /*
535          * We have to make a copy of the current key, as we opened it only
536          * with ENUM_SUBKEY access.
537          */
538
539         err = reg_openkey(mem_ctx, key, "", KEY_CREATE_SUB_KEY,
540                           &create_parent);
541         if (!W_ERROR_IS_OK(err)) {
542                 goto done;
543         }
544
545         /*
546          * Actually create the subkey
547          */
548
549         err = fill_subkey_cache(create_parent);
550         if (!W_ERROR_IS_OK(err)) goto done;
551
552         err = create_reg_subkey(key->key, path);
553         W_ERROR_NOT_OK_GOTO_DONE(err);
554
555         /*
556          * Now open the newly created key
557          */
558
559         err = reg_openkey(ctx, create_parent, path, desired_access, pkey);
560         if (W_ERROR_IS_OK(err) && (paction != NULL)) {
561                 *paction = REG_CREATED_NEW_KEY;
562         }
563
564  done:
565         TALLOC_FREE(mem_ctx);
566         return err;
567 }
568
569 WERROR reg_deletekey(struct registry_key *parent, const char *path)
570 {
571         WERROR err;
572         char *name, *end;
573         struct registry_key *tmp_key, *key;
574         TALLOC_CTX *mem_ctx = talloc_stackframe();
575
576         name = talloc_strdup(mem_ctx, path);
577         if (name == NULL) {
578                 err = WERR_NOMEM;
579                 goto done;
580         }
581
582         /* check if the key has subkeys */
583         err = reg_openkey(mem_ctx, parent, name, REG_KEY_READ, &key);
584         W_ERROR_NOT_OK_GOTO_DONE(err);
585
586         err = fill_subkey_cache(key);
587         W_ERROR_NOT_OK_GOTO_DONE(err);
588
589         if (regsubkey_ctr_numkeys(key->subkeys) > 0) {
590                 err = WERR_ACCESS_DENIED;
591                 goto done;
592         }
593
594         /* no subkeys - proceed with delete */
595         end = strrchr(name, '\\');
596         if (end != NULL) {
597                 *end = '\0';
598
599                 err = reg_openkey(mem_ctx, parent, name,
600                                   KEY_CREATE_SUB_KEY, &tmp_key);
601                 W_ERROR_NOT_OK_GOTO_DONE(err);
602
603                 parent = tmp_key;
604                 name = end+1;
605         }
606
607         if (name[0] == '\0') {
608                 err = WERR_INVALID_PARAM;
609                 goto done;
610         }
611
612         err = delete_reg_subkey(parent->key, name);
613
614 done:
615         TALLOC_FREE(mem_ctx);
616         return err;
617 }
618
619 WERROR reg_setvalue(struct registry_key *key, const char *name,
620                     const struct registry_value *val)
621 {
622         WERROR err;
623         DATA_BLOB value_data;
624         int res;
625
626         if (!(key->key->access_granted & KEY_SET_VALUE)) {
627                 return WERR_ACCESS_DENIED;
628         }
629
630         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
631                 return err;
632         }
633
634         err = registry_push_value(key, val, &value_data);
635         if (!W_ERROR_IS_OK(err)) {
636                 return err;
637         }
638
639         res = regval_ctr_addvalue(key->values, name, val->type,
640                                   value_data.data, value_data.length);
641         TALLOC_FREE(value_data.data);
642
643         if (res == 0) {
644                 TALLOC_FREE(key->values);
645                 return WERR_NOMEM;
646         }
647
648         if (!store_reg_values(key->key, key->values)) {
649                 TALLOC_FREE(key->values);
650                 return WERR_REG_IO_FAILURE;
651         }
652
653         return WERR_OK;
654 }
655
656 static WERROR reg_value_exists(struct registry_key *key, const char *name)
657 {
658         struct regval_blob *blob;
659
660         blob = regval_ctr_getvalue(key->values, name);
661
662         if (blob == NULL) {
663                 return WERR_BADFILE;
664         } else {
665                 return WERR_OK;
666         }
667 }
668
669 WERROR reg_deletevalue(struct registry_key *key, const char *name)
670 {
671         WERROR err;
672
673         if (!(key->key->access_granted & KEY_SET_VALUE)) {
674                 return WERR_ACCESS_DENIED;
675         }
676
677         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
678                 return err;
679         }
680
681         err = reg_value_exists(key, name);
682         if (!W_ERROR_IS_OK(err)) {
683                 return err;
684         }
685
686         regval_ctr_delvalue(key->values, name);
687
688         if (!store_reg_values(key->key, key->values)) {
689                 TALLOC_FREE(key->values);
690                 return WERR_REG_IO_FAILURE;
691         }
692
693         return WERR_OK;
694 }
695
696 WERROR reg_getkeysecurity(TALLOC_CTX *mem_ctx, struct registry_key *key,
697                           struct security_descriptor **psecdesc)
698 {
699         return regkey_get_secdesc(mem_ctx, key->key, psecdesc);
700 }
701
702 WERROR reg_setkeysecurity(struct registry_key *key,
703                           struct security_descriptor *psecdesc)
704 {
705         return regkey_set_secdesc(key->key, psecdesc);
706 }
707
708 WERROR reg_getversion(uint32_t *version)
709 {
710         if (version == NULL) {
711                 return WERR_INVALID_PARAM;
712         }
713
714         *version = 0x00000005; /* Windows 2000 registry API version */
715         return WERR_OK;
716 }
717
718 /*******************************************************************
719  Note: topkeypat is the *full* path that this *key will be
720  loaded into (including the name of the key)
721  ********************************************************************/
722
723 static WERROR reg_load_tree(REGF_FILE *regfile, const char *topkeypath,
724                             REGF_NK_REC *key)
725 {
726         REGF_NK_REC *subkey;
727         struct registry_key_handle registry_key;
728         struct regval_ctr *values;
729         struct regsubkey_ctr *subkeys;
730         int i;
731         char *path = NULL;
732         WERROR result = WERR_OK;
733
734         /* initialize the struct registry_key_handle structure */
735
736         registry_key.ops = reghook_cache_find(topkeypath);
737         if (!registry_key.ops) {
738                 DEBUG(0, ("reg_load_tree: Failed to assign registry_ops "
739                           "to [%s]\n", topkeypath));
740                 return WERR_BADFILE;
741         }
742
743         registry_key.name = talloc_strdup(regfile->mem_ctx, topkeypath);
744         if (!registry_key.name) {
745                 DEBUG(0, ("reg_load_tree: Talloc failed for reg_key.name!\n"));
746                 return WERR_NOMEM;
747         }
748
749         /* now start parsing the values and subkeys */
750
751         result = regsubkey_ctr_init(regfile->mem_ctx, &subkeys);
752         W_ERROR_NOT_OK_RETURN(result);
753
754         result = regval_ctr_init(subkeys, &values);
755         W_ERROR_NOT_OK_RETURN(result);
756
757         /* copy values into the struct regval_ctr */
758
759         for (i=0; i<key->num_values; i++) {
760                 regval_ctr_addvalue(values, key->values[i].valuename,
761                                     key->values[i].type,
762                                     key->values[i].data,
763                                     (key->values[i].data_size & ~VK_DATA_IN_OFFSET));
764         }
765
766         /* copy subkeys into the struct regsubkey_ctr */
767
768         key->subkey_index = 0;
769         while ((subkey = regfio_fetch_subkey( regfile, key ))) {
770                 result = regsubkey_ctr_addkey(subkeys, subkey->keyname);
771                 if (!W_ERROR_IS_OK(result)) {
772                         TALLOC_FREE(subkeys);
773                         return result;
774                 }
775         }
776
777         /* write this key and values out */
778
779         if (!store_reg_values(&registry_key, values)
780             || !store_reg_keys(&registry_key, subkeys))
781         {
782                 DEBUG(0,("reg_load_tree: Failed to load %s!\n", topkeypath));
783                 result = WERR_REG_IO_FAILURE;
784         }
785
786         TALLOC_FREE(subkeys);
787
788         if (!W_ERROR_IS_OK(result)) {
789                 return result;
790         }
791
792         /* now continue to load each subkey registry tree */
793
794         key->subkey_index = 0;
795         while ((subkey = regfio_fetch_subkey(regfile, key))) {
796                 path = talloc_asprintf(regfile->mem_ctx,
797                                        "%s\\%s",
798                                        topkeypath,
799                                        subkey->keyname);
800                 if (path == NULL) {
801                         return WERR_NOMEM;
802                 }
803                 result = reg_load_tree(regfile, path, subkey);
804                 if (!W_ERROR_IS_OK(result)) {
805                         break;
806                 }
807         }
808
809         return result;
810 }
811
812 /*******************************************************************
813  ********************************************************************/
814
815 static WERROR restore_registry_key(struct registry_key_handle *krecord,
816                                    const char *fname)
817 {
818         REGF_FILE *regfile;
819         REGF_NK_REC *rootkey;
820         WERROR result;
821
822         /* open the registry file....fail if the file already exists */
823
824         regfile = regfio_open(fname, (O_RDONLY), 0);
825         if (regfile == NULL) {
826                 DEBUG(0, ("restore_registry_key: failed to open \"%s\" (%s)\n",
827                           fname, strerror(errno)));
828                 return ntstatus_to_werror(map_nt_error_from_unix(errno));
829         }
830
831         /* get the rootkey from the regf file and then load the tree
832            via recursive calls */
833
834         if (!(rootkey = regfio_rootkey(regfile))) {
835                 regfio_close(regfile);
836                 return WERR_REG_FILE_INVALID;
837         }
838
839         result = reg_load_tree(regfile, krecord->name, rootkey);
840
841         /* cleanup */
842
843         regfio_close(regfile);
844
845         return result;
846 }
847
848 WERROR reg_restorekey(struct registry_key *key, const char *fname)
849 {
850         return restore_registry_key(key->key, fname);
851 }
852
853 /********************************************************************
854 ********************************************************************/
855
856 static WERROR reg_write_tree(REGF_FILE *regfile, const char *keypath,
857                              REGF_NK_REC *parent)
858 {
859         REGF_NK_REC *key;
860         struct regval_ctr *values;
861         struct regsubkey_ctr *subkeys;
862         int i, num_subkeys;
863         char *key_tmp = NULL;
864         char *keyname, *parentpath;
865         char *subkeypath = NULL;
866         char *subkeyname;
867         struct registry_key_handle registry_key;
868         WERROR result = WERR_OK;
869         struct security_descriptor *sec_desc = NULL;
870
871         if (!regfile) {
872                 return WERR_GENERAL_FAILURE;
873         }
874
875         if (!keypath) {
876                 return WERR_OBJECT_PATH_INVALID;
877         }
878
879         /* split up the registry key path */
880
881         key_tmp = talloc_strdup(regfile->mem_ctx, keypath);
882         if (!key_tmp) {
883                 return WERR_NOMEM;
884         }
885         if (!reg_split_key(key_tmp, &parentpath, &keyname)) {
886                 return WERR_OBJECT_PATH_INVALID;
887         }
888
889         if (!keyname) {
890                 keyname = parentpath;
891         }
892
893         /* we need a registry_key_handle object here to enumerate subkeys and values */
894
895         ZERO_STRUCT(registry_key);
896
897         registry_key.name = talloc_strdup(regfile->mem_ctx, keypath);
898         if (registry_key.name == NULL) {
899                 return WERR_NOMEM;
900         }
901
902         registry_key.ops = reghook_cache_find(registry_key.name);
903         if (registry_key.ops == NULL) {
904                 return WERR_BADFILE;
905         }
906
907         /* lookup the values and subkeys */
908
909         result = regsubkey_ctr_init(regfile->mem_ctx, &subkeys);
910         W_ERROR_NOT_OK_RETURN(result);
911
912         result = regval_ctr_init(subkeys, &values); 
913         W_ERROR_NOT_OK_RETURN(result);
914
915         fetch_reg_keys(&registry_key, subkeys);
916         fetch_reg_values(&registry_key, values);
917
918         result = regkey_get_secdesc(regfile->mem_ctx, &registry_key, &sec_desc);
919         if (!W_ERROR_IS_OK(result)) {
920                 goto done;
921         }
922
923         /* write out this key */
924
925         key = regfio_write_key(regfile, keyname, values, subkeys, sec_desc,
926                                parent);
927         if (key == NULL) {
928                 result = WERR_CAN_NOT_COMPLETE;
929                 goto done;
930         }
931
932         /* write each one of the subkeys out */
933
934         num_subkeys = regsubkey_ctr_numkeys(subkeys);
935         for (i=0; i<num_subkeys; i++) {
936                 subkeyname = regsubkey_ctr_specific_key(subkeys, i);
937                 subkeypath = talloc_asprintf(regfile->mem_ctx, "%s\\%s",
938                                              keypath, subkeyname);
939                 if (subkeypath == NULL) {
940                         result = WERR_NOMEM;
941                         goto done;
942                 }
943                 result = reg_write_tree(regfile, subkeypath, key);
944                 if (!W_ERROR_IS_OK(result))
945                         goto done;
946         }
947
948         DEBUG(6, ("reg_write_tree: wrote key [%s]\n", keypath));
949
950 done:
951         TALLOC_FREE(subkeys);
952         TALLOC_FREE(registry_key.name);
953
954         return result;
955 }
956
957 static WERROR backup_registry_key(struct registry_key_handle *krecord,
958                                   const char *fname)
959 {
960         REGF_FILE *regfile;
961         WERROR result;
962
963         /* open the registry file....fail if the file already exists */
964
965         regfile = regfio_open(fname, (O_RDWR|O_CREAT|O_EXCL),
966                               (S_IREAD|S_IWRITE));
967         if (regfile == NULL) {
968                 DEBUG(0,("backup_registry_key: failed to open \"%s\" (%s)\n",
969                          fname, strerror(errno) ));
970                 return ntstatus_to_werror(map_nt_error_from_unix(errno));
971         }
972
973         /* write the registry tree to the file  */
974
975         result = reg_write_tree(regfile, krecord->name, NULL);
976
977         /* cleanup */
978
979         regfio_close(regfile);
980
981         return result;
982 }
983
984 WERROR reg_savekey(struct registry_key *key, const char *fname)
985 {
986         return backup_registry_key(key->key, fname);
987 }
988
989 /**********************************************************************
990  * Higher level utility functions
991  **********************************************************************/
992
993 WERROR reg_deleteallvalues(struct registry_key *key)
994 {
995         WERROR err;
996         int i;
997
998         if (!(key->key->access_granted & KEY_SET_VALUE)) {
999                 return WERR_ACCESS_DENIED;
1000         }
1001
1002         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
1003                 return err;
1004         }
1005
1006         for (i=0; i < regval_ctr_numvals(key->values); i++) {
1007                 struct regval_blob *blob;
1008                 blob = regval_ctr_specific_value(key->values, i);
1009                 regval_ctr_delvalue(key->values, regval_name(blob));
1010         }
1011
1012         if (!store_reg_values(key->key, key->values)) {
1013                 TALLOC_FREE(key->values);
1014                 return WERR_REG_IO_FAILURE;
1015         }
1016
1017         return WERR_OK;
1018 }
1019
1020 /*
1021  * Utility function to open a complete registry path including the hive prefix.
1022  */
1023
1024 WERROR reg_open_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1025                      uint32 desired_access, const struct nt_user_token *token,
1026                      struct registry_key **pkey)
1027 {
1028         struct registry_key *hive, *key;
1029         char *path, *p;
1030         WERROR err;
1031
1032         if (!(path = SMB_STRDUP(orig_path))) {
1033                 return WERR_NOMEM;
1034         }
1035
1036         p = strchr(path, '\\');
1037
1038         if ((p == NULL) || (p[1] == '\0')) {
1039                 /*
1040                  * No key behind the hive, just return the hive
1041                  */
1042
1043                 err = reg_openhive(mem_ctx, path, desired_access, token,
1044                                    &hive);
1045                 if (!W_ERROR_IS_OK(err)) {
1046                         SAFE_FREE(path);
1047                         return err;
1048                 }
1049                 SAFE_FREE(path);
1050                 *pkey = hive;
1051                 return WERR_OK;
1052         }
1053
1054         *p = '\0';
1055
1056         err = reg_openhive(mem_ctx, path, KEY_ENUMERATE_SUB_KEYS, token,
1057                            &hive);
1058         if (!W_ERROR_IS_OK(err)) {
1059                 SAFE_FREE(path);
1060                 return err;
1061         }
1062
1063         err = reg_openkey(mem_ctx, hive, p+1, desired_access, &key);
1064
1065         TALLOC_FREE(hive);
1066         SAFE_FREE(path);
1067
1068         if (!W_ERROR_IS_OK(err)) {
1069                 return err;
1070         }
1071
1072         *pkey = key;
1073         return WERR_OK;
1074 }
1075
1076 /*
1077  * Utility function to delete a registry key with all its subkeys.
1078  * Note that reg_deletekey returns ACCESS_DENIED when called on a
1079  * key that has subkeys.
1080  */
1081 static WERROR reg_deletekey_recursive_internal(TALLOC_CTX *ctx,
1082                                                struct registry_key *parent,
1083                                                const char *path,
1084                                                bool del_key)
1085 {
1086         TALLOC_CTX *mem_ctx = NULL;
1087         WERROR werr = WERR_OK;
1088         struct registry_key *key;
1089         char *subkey_name = NULL;
1090         uint32 i;
1091
1092         mem_ctx = talloc_new(ctx);
1093         if (mem_ctx == NULL) {
1094                 werr = WERR_NOMEM;
1095                 goto done;
1096         }
1097
1098         /* recurse through subkeys first */
1099         werr = reg_openkey(mem_ctx, parent, path, REG_KEY_ALL, &key);
1100         if (!W_ERROR_IS_OK(werr)) {
1101                 goto done;
1102         }
1103
1104         werr = fill_subkey_cache(key);
1105         W_ERROR_NOT_OK_GOTO_DONE(werr);
1106
1107         /*
1108          * loop from top to bottom for perfomance:
1109          * this way, we need to rehash the regsubkey containers less
1110          */
1111         for (i = regsubkey_ctr_numkeys(key->subkeys) ; i > 0; i--) {
1112                 subkey_name = regsubkey_ctr_specific_key(key->subkeys, i-1);
1113                 werr = reg_deletekey_recursive_internal(mem_ctx, key,
1114                                         subkey_name,
1115                                         true);
1116                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1117         }
1118
1119         if (del_key) {
1120                 /* now delete the actual key */
1121                 werr = reg_deletekey(parent, path);
1122         }
1123
1124 done:
1125         TALLOC_FREE(mem_ctx);
1126         return werr;
1127 }
1128
1129 static WERROR reg_deletekey_recursive_trans(TALLOC_CTX *ctx,
1130                                             struct registry_key *parent,
1131                                             const char *path,
1132                                             bool del_key)
1133 {
1134         WERROR werr;
1135
1136         werr = regdb_transaction_start();
1137         if (!W_ERROR_IS_OK(werr)) {
1138                 DEBUG(0, ("reg_deletekey_recursive_trans: "
1139                           "error starting transaction: %s\n",
1140                           win_errstr(werr)));
1141                 return werr;
1142         }
1143
1144         werr = reg_deletekey_recursive_internal(ctx, parent, path, del_key);
1145
1146         if (!W_ERROR_IS_OK(werr)) {
1147                 DEBUG(1, (__location__ " failed to delete key '%s' from key "
1148                           "'%s': %s\n", path, parent->key->name,
1149                           win_errstr(werr)));
1150                 werr = regdb_transaction_cancel();
1151                 if (!W_ERROR_IS_OK(werr)) {
1152                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1153                                   "error cancelling transaction: %s\n",
1154                                   win_errstr(werr)));
1155                 }
1156         } else {
1157                 werr = regdb_transaction_commit();
1158                 if (!W_ERROR_IS_OK(werr)) {
1159                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1160                                   "error committing transaction: %s\n",
1161                                   win_errstr(werr)));
1162                 }
1163         }
1164
1165         return werr;
1166 }
1167
1168 WERROR reg_deletekey_recursive(TALLOC_CTX *ctx,
1169                                struct registry_key *parent,
1170                                const char *path)
1171 {
1172         return reg_deletekey_recursive_trans(ctx, parent, path, true);
1173 }
1174
1175 WERROR reg_deletesubkeys_recursive(TALLOC_CTX *ctx,
1176                                    struct registry_key *parent,
1177                                    const char *path)
1178 {
1179         return reg_deletekey_recursive_trans(ctx, parent, path, false);
1180 }
1181
1182 #if 0
1183 /* these two functions are unused. */
1184
1185 /**
1186  * Utility function to create a registry key without opening the hive
1187  * before. Assumes the hive already exists.
1188  */
1189
1190 WERROR reg_create_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1191                        uint32 desired_access,
1192                        const struct nt_user_token *token,
1193                        enum winreg_CreateAction *paction,
1194                        struct registry_key **pkey)
1195 {
1196         struct registry_key *hive;
1197         char *path, *p;
1198         WERROR err;
1199
1200         if (!(path = SMB_STRDUP(orig_path))) {
1201                 return WERR_NOMEM;
1202         }
1203
1204         p = strchr(path, '\\');
1205
1206         if ((p == NULL) || (p[1] == '\0')) {
1207                 /*
1208                  * No key behind the hive, just return the hive
1209                  */
1210
1211                 err = reg_openhive(mem_ctx, path, desired_access, token,
1212                                    &hive);
1213                 if (!W_ERROR_IS_OK(err)) {
1214                         SAFE_FREE(path);
1215                         return err;
1216                 }
1217                 SAFE_FREE(path);
1218                 *pkey = hive;
1219                 *paction = REG_OPENED_EXISTING_KEY;
1220                 return WERR_OK;
1221         }
1222
1223         *p = '\0';
1224
1225         err = reg_openhive(mem_ctx, path,
1226                            (strchr(p+1, '\\') != NULL) ?
1227                            KEY_ENUMERATE_SUB_KEYS : KEY_CREATE_SUB_KEY,
1228                            token, &hive);
1229         if (!W_ERROR_IS_OK(err)) {
1230                 SAFE_FREE(path);
1231                 return err;
1232         }
1233
1234         err = reg_createkey(mem_ctx, hive, p+1, desired_access, pkey, paction);
1235         SAFE_FREE(path);
1236         TALLOC_FREE(hive);
1237         return err;
1238 }
1239
1240 /*
1241  * Utility function to create a registry key without opening the hive
1242  * before. Will not delete a hive.
1243  */
1244
1245 WERROR reg_delete_path(const struct nt_user_token *token,
1246                        const char *orig_path)
1247 {
1248         struct registry_key *hive;
1249         char *path, *p;
1250         WERROR err;
1251
1252         if (!(path = SMB_STRDUP(orig_path))) {
1253                 return WERR_NOMEM;
1254         }
1255
1256         p = strchr(path, '\\');
1257
1258         if ((p == NULL) || (p[1] == '\0')) {
1259                 SAFE_FREE(path);
1260                 return WERR_INVALID_PARAM;
1261         }
1262
1263         *p = '\0';
1264
1265         err = reg_openhive(NULL, path,
1266                            (strchr(p+1, '\\') != NULL) ?
1267                            KEY_ENUMERATE_SUB_KEYS : KEY_CREATE_SUB_KEY,
1268                            token, &hive);
1269         if (!W_ERROR_IS_OK(err)) {
1270                 SAFE_FREE(path);
1271                 return err;
1272         }
1273
1274         err = reg_deletekey(hive, p+1);
1275         SAFE_FREE(path);
1276         TALLOC_FREE(hive);
1277         return err;
1278 }
1279 #endif /* #if 0 */