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