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