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