s3:registry: streamline reg_deletekey() somewhat.
[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         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 = fill_subkey_cache(parent);
588         W_ERROR_NOT_OK_GOTO_DONE(err);
589
590         err = regsubkey_ctr_delkey(parent->subkeys, name);
591         W_ERROR_NOT_OK_GOTO_DONE(err);
592
593         if (!store_reg_keys(parent->key, parent->subkeys)) {
594                 TALLOC_FREE(parent->subkeys);
595                 err = WERR_REG_IO_FAILURE;
596                 goto done;
597         }
598
599         regkey_set_secdesc(key->key, NULL);
600
601         err = WERR_OK;
602
603 done:
604         TALLOC_FREE(mem_ctx);
605         return err;
606 }
607
608 WERROR reg_setvalue(struct registry_key *key, const char *name,
609                     const struct registry_value *val)
610 {
611         WERROR err;
612         DATA_BLOB value_data;
613         int res;
614
615         if (!(key->key->access_granted & SEC_RIGHTS_SET_VALUE)) {
616                 return WERR_ACCESS_DENIED;
617         }
618
619         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
620                 return err;
621         }
622
623         err = registry_push_value(key, val, &value_data);
624         if (!W_ERROR_IS_OK(err)) {
625                 return err;
626         }
627
628         res = regval_ctr_addvalue(key->values, name, val->type,
629                                   (char *)value_data.data, value_data.length);
630         TALLOC_FREE(value_data.data);
631
632         if (res == 0) {
633                 TALLOC_FREE(key->values);
634                 return WERR_NOMEM;
635         }
636
637         if (!store_reg_values(key->key, key->values)) {
638                 TALLOC_FREE(key->values);
639                 return WERR_REG_IO_FAILURE;
640         }
641
642         return WERR_OK;
643 }
644
645 static WERROR reg_value_exists(struct registry_key *key, const char *name)
646 {
647         int i;
648
649         for (i=0; i<key->values->num_values; i++) {
650                 if (strequal(key->values->values[i]->valuename, name)) {
651                         return WERR_OK;
652                 }
653         }
654
655         return WERR_BADFILE;
656 }
657
658 WERROR reg_deletevalue(struct registry_key *key, const char *name)
659 {
660         WERROR err;
661
662         if (!(key->key->access_granted & SEC_RIGHTS_SET_VALUE)) {
663                 return WERR_ACCESS_DENIED;
664         }
665
666         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
667                 return err;
668         }
669
670         err = reg_value_exists(key, name);
671         if (!W_ERROR_IS_OK(err)) {
672                 return err;
673         }
674
675         regval_ctr_delvalue(key->values, name);
676
677         if (!store_reg_values(key->key, key->values)) {
678                 TALLOC_FREE(key->values);
679                 return WERR_REG_IO_FAILURE;
680         }
681
682         return WERR_OK;
683 }
684
685 WERROR reg_getkeysecurity(TALLOC_CTX *mem_ctx, struct registry_key *key,
686                           struct security_descriptor **psecdesc)
687 {
688         return regkey_get_secdesc(mem_ctx, key->key, psecdesc);
689 }
690
691 WERROR reg_setkeysecurity(struct registry_key *key,
692                           struct security_descriptor *psecdesc)
693 {
694         return regkey_set_secdesc(key->key, psecdesc);
695 }
696
697 WERROR reg_getversion(uint32_t *version)
698 {
699         if (version == NULL) {
700                 return WERR_INVALID_PARAM;
701         }
702
703         *version = 0x00000005; /* Windows 2000 registry API version */
704         return WERR_OK;
705 }
706
707 /*******************************************************************
708  Note: topkeypat is the *full* path that this *key will be
709  loaded into (including the name of the key)
710  ********************************************************************/
711
712 static WERROR reg_load_tree(REGF_FILE *regfile, const char *topkeypath,
713                             REGF_NK_REC *key)
714 {
715         REGF_NK_REC *subkey;
716         REGISTRY_KEY registry_key;
717         REGVAL_CTR *values;
718         struct regsubkey_ctr *subkeys;
719         int i;
720         char *path = NULL;
721         WERROR result = WERR_OK;
722
723         /* initialize the REGISTRY_KEY structure */
724
725         registry_key.ops = reghook_cache_find(topkeypath);
726         if (!registry_key.ops) {
727                 DEBUG(0, ("reg_load_tree: Failed to assign  REGISTRY_OPS "
728                           "to [%s]\n", topkeypath));
729                 return WERR_BADFILE;
730         }
731
732         registry_key.name = talloc_strdup(regfile->mem_ctx, topkeypath);
733         if (!registry_key.name) {
734                 DEBUG(0, ("reg_load_tree: Talloc failed for reg_key.name!\n"));
735                 return WERR_NOMEM;
736         }
737
738         /* now start parsing the values and subkeys */
739
740         result = regsubkey_ctr_init(regfile->mem_ctx, &subkeys);
741         W_ERROR_NOT_OK_RETURN(result);
742
743         values = TALLOC_ZERO_P(subkeys, REGVAL_CTR);
744         if (values == NULL) {
745                 return WERR_NOMEM;
746         }
747
748         /* copy values into the REGVAL_CTR */
749
750         for (i=0; i<key->num_values; i++) {
751                 regval_ctr_addvalue(values, key->values[i].valuename,
752                                     key->values[i].type,
753                                     (char*)key->values[i].data,
754                                     (key->values[i].data_size & ~VK_DATA_IN_OFFSET));
755         }
756
757         /* copy subkeys into the struct regsubkey_ctr */
758
759         key->subkey_index = 0;
760         while ((subkey = regfio_fetch_subkey( regfile, key ))) {
761                 result = regsubkey_ctr_addkey(subkeys, subkey->keyname);
762                 if (!W_ERROR_IS_OK(result)) {
763                         TALLOC_FREE(subkeys);
764                         return result;
765                 }
766         }
767
768         /* write this key and values out */
769
770         if (!store_reg_values(&registry_key, values)
771             || !store_reg_keys(&registry_key, subkeys))
772         {
773                 DEBUG(0,("reg_load_tree: Failed to load %s!\n", topkeypath));
774                 result = WERR_REG_IO_FAILURE;
775         }
776
777         TALLOC_FREE(subkeys);
778
779         if (!W_ERROR_IS_OK(result)) {
780                 return result;
781         }
782
783         /* now continue to load each subkey registry tree */
784
785         key->subkey_index = 0;
786         while ((subkey = regfio_fetch_subkey(regfile, key))) {
787                 path = talloc_asprintf(regfile->mem_ctx,
788                                        "%s\\%s",
789                                        topkeypath,
790                                        subkey->keyname);
791                 if (path == NULL) {
792                         return WERR_NOMEM;
793                 }
794                 result = reg_load_tree(regfile, path, subkey);
795                 if (!W_ERROR_IS_OK(result)) {
796                         break;
797                 }
798         }
799
800         return result;
801 }
802
803 /*******************************************************************
804  ********************************************************************/
805
806 static WERROR restore_registry_key(REGISTRY_KEY *krecord, const char *fname)
807 {
808         REGF_FILE *regfile;
809         REGF_NK_REC *rootkey;
810         WERROR result;
811
812         /* open the registry file....fail if the file already exists */
813
814         regfile = regfio_open(fname, (O_RDONLY), 0);
815         if (regfile == NULL) {
816                 DEBUG(0, ("restore_registry_key: failed to open \"%s\" (%s)\n",
817                           fname, strerror(errno)));
818                 return ntstatus_to_werror(map_nt_error_from_unix(errno));
819         }
820
821         /* get the rootkey from the regf file and then load the tree
822            via recursive calls */
823
824         if (!(rootkey = regfio_rootkey(regfile))) {
825                 regfio_close(regfile);
826                 return WERR_REG_FILE_INVALID;
827         }
828
829         result = reg_load_tree(regfile, krecord->name, rootkey);
830
831         /* cleanup */
832
833         regfio_close(regfile);
834
835         return result;
836 }
837
838 WERROR reg_restorekey(struct registry_key *key, const char *fname)
839 {
840         return restore_registry_key(key->key, fname);
841 }
842
843 /********************************************************************
844 ********************************************************************/
845
846 static WERROR reg_write_tree(REGF_FILE *regfile, const char *keypath,
847                              REGF_NK_REC *parent)
848 {
849         REGF_NK_REC *key;
850         REGVAL_CTR *values;
851         struct regsubkey_ctr *subkeys;
852         int i, num_subkeys;
853         char *key_tmp = NULL;
854         char *keyname, *parentpath;
855         char *subkeypath = NULL;
856         char *subkeyname;
857         REGISTRY_KEY registry_key;
858         WERROR result = WERR_OK;
859         SEC_DESC *sec_desc = NULL;
860
861         if (!regfile) {
862                 return WERR_GENERAL_FAILURE;
863         }
864
865         if (!keypath) {
866                 return WERR_OBJECT_PATH_INVALID;
867         }
868
869         /* split up the registry key path */
870
871         key_tmp = talloc_strdup(regfile->mem_ctx, keypath);
872         if (!key_tmp) {
873                 return WERR_NOMEM;
874         }
875         if (!reg_split_key(key_tmp, &parentpath, &keyname)) {
876                 return WERR_OBJECT_PATH_INVALID;
877         }
878
879         if (!keyname) {
880                 keyname = parentpath;
881         }
882
883         /* we need a REGISTRY_KEY object here to enumerate subkeys and values */
884
885         ZERO_STRUCT(registry_key);
886
887         registry_key.name = talloc_strdup(regfile->mem_ctx, keypath);
888         if (registry_key.name == NULL) {
889                 return WERR_NOMEM;
890         }
891
892         registry_key.ops = reghook_cache_find(registry_key.name);
893         if (registry_key.ops == NULL) {
894                 return WERR_BADFILE;
895         }
896
897         /* lookup the values and subkeys */
898
899         result = regsubkey_ctr_init(regfile->mem_ctx, &subkeys);
900         W_ERROR_NOT_OK_RETURN(result);
901
902         values = TALLOC_ZERO_P(subkeys, REGVAL_CTR);
903         if (values == NULL) {
904                 return WERR_NOMEM;
905         }
906
907         fetch_reg_keys(&registry_key, subkeys);
908         fetch_reg_values(&registry_key, values);
909
910         result = regkey_get_secdesc(regfile->mem_ctx, &registry_key, &sec_desc);
911         if (!W_ERROR_IS_OK(result)) {
912                 goto done;
913         }
914
915         /* write out this key */
916
917         key = regfio_write_key(regfile, keyname, values, subkeys, sec_desc,
918                                parent);
919         if (key == NULL) {
920                 result = WERR_CAN_NOT_COMPLETE;
921                 goto done;
922         }
923
924         /* write each one of the subkeys out */
925
926         num_subkeys = regsubkey_ctr_numkeys(subkeys);
927         for (i=0; i<num_subkeys; i++) {
928                 subkeyname = regsubkey_ctr_specific_key(subkeys, i);
929                 subkeypath = talloc_asprintf(regfile->mem_ctx, "%s\\%s",
930                                              keypath, subkeyname);
931                 if (subkeypath == NULL) {
932                         result = WERR_NOMEM;
933                         goto done;
934                 }
935                 result = reg_write_tree(regfile, subkeypath, key);
936                 if (!W_ERROR_IS_OK(result))
937                         goto done;
938         }
939
940         DEBUG(6, ("reg_write_tree: wrote key [%s]\n", keypath));
941
942 done:
943         TALLOC_FREE(subkeys);
944         TALLOC_FREE(registry_key.name);
945
946         return result;
947 }
948
949 static WERROR backup_registry_key(REGISTRY_KEY *krecord, const char *fname)
950 {
951         REGF_FILE *regfile;
952         WERROR result;
953
954         /* open the registry file....fail if the file already exists */
955
956         regfile = regfio_open(fname, (O_RDWR|O_CREAT|O_EXCL),
957                               (S_IREAD|S_IWRITE));
958         if (regfile == NULL) {
959                 DEBUG(0,("backup_registry_key: failed to open \"%s\" (%s)\n",
960                          fname, strerror(errno) ));
961                 return ntstatus_to_werror(map_nt_error_from_unix(errno));
962         }
963
964         /* write the registry tree to the file  */
965
966         result = reg_write_tree(regfile, krecord->name, NULL);
967
968         /* cleanup */
969
970         regfio_close(regfile);
971
972         return result;
973 }
974
975 WERROR reg_savekey(struct registry_key *key, const char *fname)
976 {
977         return backup_registry_key(key->key, fname);
978 }
979
980 /**********************************************************************
981  * Higher level utility functions
982  **********************************************************************/
983
984 WERROR reg_deleteallvalues(struct registry_key *key)
985 {
986         WERROR err;
987         int i;
988
989         if (!(key->key->access_granted & SEC_RIGHTS_SET_VALUE)) {
990                 return WERR_ACCESS_DENIED;
991         }
992
993         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
994                 return err;
995         }
996
997         for (i=0; i<key->values->num_values; i++) {
998                 regval_ctr_delvalue(key->values, key->values->values[i]->valuename);
999         }
1000
1001         if (!store_reg_values(key->key, key->values)) {
1002                 TALLOC_FREE(key->values);
1003                 return WERR_REG_IO_FAILURE;
1004         }
1005
1006         return WERR_OK;
1007 }
1008
1009 /*
1010  * Utility function to open a complete registry path including the hive prefix.
1011  */
1012
1013 WERROR reg_open_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1014                      uint32 desired_access, const struct nt_user_token *token,
1015                      struct registry_key **pkey)
1016 {
1017         struct registry_key *hive, *key;
1018         char *path, *p;
1019         WERROR err;
1020
1021         if (!(path = SMB_STRDUP(orig_path))) {
1022                 return WERR_NOMEM;
1023         }
1024
1025         p = strchr(path, '\\');
1026
1027         if ((p == NULL) || (p[1] == '\0')) {
1028                 /*
1029                  * No key behind the hive, just return the hive
1030                  */
1031
1032                 err = reg_openhive(mem_ctx, path, desired_access, token,
1033                                    &hive);
1034                 if (!W_ERROR_IS_OK(err)) {
1035                         SAFE_FREE(path);
1036                         return err;
1037                 }
1038                 SAFE_FREE(path);
1039                 *pkey = hive;
1040                 return WERR_OK;
1041         }
1042
1043         *p = '\0';
1044
1045         err = reg_openhive(mem_ctx, path, SEC_RIGHTS_ENUM_SUBKEYS, token,
1046                            &hive);
1047         if (!W_ERROR_IS_OK(err)) {
1048                 SAFE_FREE(path);
1049                 return err;
1050         }
1051
1052         err = reg_openkey(mem_ctx, hive, p+1, desired_access, &key);
1053
1054         TALLOC_FREE(hive);
1055         SAFE_FREE(path);
1056
1057         if (!W_ERROR_IS_OK(err)) {
1058                 return err;
1059         }
1060
1061         *pkey = key;
1062         return WERR_OK;
1063 }
1064
1065 /*
1066  * Utility function to delete a registry key with all its subkeys.
1067  * Note that reg_deletekey returns ACCESS_DENIED when called on a
1068  * key that has subkeys.
1069  */
1070 static WERROR reg_deletekey_recursive_internal(TALLOC_CTX *ctx,
1071                                                struct registry_key *parent,
1072                                                const char *path,
1073                                                bool del_key)
1074 {
1075         TALLOC_CTX *mem_ctx = NULL;
1076         WERROR werr = WERR_OK;
1077         struct registry_key *key;
1078         char *subkey_name = NULL;
1079
1080         mem_ctx = talloc_new(ctx);
1081         if (mem_ctx == NULL) {
1082                 werr = WERR_NOMEM;
1083                 goto done;
1084         }
1085
1086         /* recurse through subkeys first */
1087         werr = reg_openkey(mem_ctx, parent, path, REG_KEY_ALL, &key);
1088         if (!W_ERROR_IS_OK(werr)) {
1089                 goto done;
1090         }
1091
1092         while (W_ERROR_IS_OK(werr = reg_enumkey(mem_ctx, key, 0,
1093                                                 &subkey_name, NULL)))
1094         {
1095                 werr = reg_deletekey_recursive_internal(mem_ctx, key,
1096                                                         subkey_name,
1097                                                         true);
1098                 if (!W_ERROR_IS_OK(werr)) {
1099                         goto done;
1100                 }
1101         }
1102         if (!W_ERROR_EQUAL(WERR_NO_MORE_ITEMS, werr)) {
1103                 DEBUG(1, ("reg_deletekey_recursive_internal: "
1104                           "Error enumerating subkeys: %s\n",
1105                           win_errstr(werr)));
1106                 goto done;
1107         }
1108
1109         werr = WERR_OK;
1110
1111         if (del_key) {
1112                 /* now delete the actual key */
1113                 werr = reg_deletekey(parent, path);
1114         }
1115
1116 done:
1117         TALLOC_FREE(mem_ctx);
1118         return werr;
1119 }
1120
1121 static WERROR reg_deletekey_recursive_trans(TALLOC_CTX *ctx,
1122                                             struct registry_key *parent,
1123                                             const char *path,
1124                                             bool del_key)
1125 {
1126         WERROR werr;
1127
1128         werr = regdb_transaction_start();
1129         if (!W_ERROR_IS_OK(werr)) {
1130                 DEBUG(0, ("reg_deletekey_recursive_trans: "
1131                           "error starting transaction: %s\n",
1132                           win_errstr(werr)));
1133                 return werr;
1134         }
1135
1136         werr = reg_deletekey_recursive_internal(ctx, parent, path, del_key);
1137
1138         if (!W_ERROR_IS_OK(werr)) {
1139                 DEBUG(1, (__location__ " failed to delete key '%s' from key "
1140                           "'%s': %s\n", path, parent->key->name,
1141                           win_errstr(werr)));
1142                 werr = regdb_transaction_cancel();
1143                 if (!W_ERROR_IS_OK(werr)) {
1144                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1145                                   "error cancelling transaction: %s\n",
1146                                   win_errstr(werr)));
1147                 }
1148         } else {
1149                 werr = regdb_transaction_commit();
1150                 if (!W_ERROR_IS_OK(werr)) {
1151                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1152                                   "error committing transaction: %s\n",
1153                                   win_errstr(werr)));
1154                 }
1155         }
1156
1157         return werr;
1158 }
1159
1160 WERROR reg_deletekey_recursive(TALLOC_CTX *ctx,
1161                                struct registry_key *parent,
1162                                const char *path)
1163 {
1164         return reg_deletekey_recursive_trans(ctx, parent, path, true);
1165 }
1166
1167 WERROR reg_deletesubkeys_recursive(TALLOC_CTX *ctx,
1168                                    struct registry_key *parent,
1169                                    const char *path)
1170 {
1171         return reg_deletekey_recursive_trans(ctx, parent, path, false);
1172 }
1173
1174 #if 0
1175 /* these two functions are unused. */
1176
1177 /**
1178  * Utility function to create a registry key without opening the hive
1179  * before. Assumes the hive already exists.
1180  */
1181
1182 WERROR reg_create_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1183                        uint32 desired_access,
1184                        const struct nt_user_token *token,
1185                        enum winreg_CreateAction *paction,
1186                        struct registry_key **pkey)
1187 {
1188         struct registry_key *hive;
1189         char *path, *p;
1190         WERROR err;
1191
1192         if (!(path = SMB_STRDUP(orig_path))) {
1193                 return WERR_NOMEM;
1194         }
1195
1196         p = strchr(path, '\\');
1197
1198         if ((p == NULL) || (p[1] == '\0')) {
1199                 /*
1200                  * No key behind the hive, just return the hive
1201                  */
1202
1203                 err = reg_openhive(mem_ctx, path, desired_access, token,
1204                                    &hive);
1205                 if (!W_ERROR_IS_OK(err)) {
1206                         SAFE_FREE(path);
1207                         return err;
1208                 }
1209                 SAFE_FREE(path);
1210                 *pkey = hive;
1211                 *paction = REG_OPENED_EXISTING_KEY;
1212                 return WERR_OK;
1213         }
1214
1215         *p = '\0';
1216
1217         err = reg_openhive(mem_ctx, path,
1218                            (strchr(p+1, '\\') != NULL) ?
1219                            SEC_RIGHTS_ENUM_SUBKEYS : SEC_RIGHTS_CREATE_SUBKEY,
1220                            token, &hive);
1221         if (!W_ERROR_IS_OK(err)) {
1222                 SAFE_FREE(path);
1223                 return err;
1224         }
1225
1226         err = reg_createkey(mem_ctx, hive, p+1, desired_access, pkey, paction);
1227         SAFE_FREE(path);
1228         TALLOC_FREE(hive);
1229         return err;
1230 }
1231
1232 /*
1233  * Utility function to create a registry key without opening the hive
1234  * before. Will not delete a hive.
1235  */
1236
1237 WERROR reg_delete_path(const struct nt_user_token *token,
1238                        const char *orig_path)
1239 {
1240         struct registry_key *hive;
1241         char *path, *p;
1242         WERROR err;
1243
1244         if (!(path = SMB_STRDUP(orig_path))) {
1245                 return WERR_NOMEM;
1246         }
1247
1248         p = strchr(path, '\\');
1249
1250         if ((p == NULL) || (p[1] == '\0')) {
1251                 SAFE_FREE(path);
1252                 return WERR_INVALID_PARAM;
1253         }
1254
1255         *p = '\0';
1256
1257         err = reg_openhive(NULL, path,
1258                            (strchr(p+1, '\\') != NULL) ?
1259                            SEC_RIGHTS_ENUM_SUBKEYS : SEC_RIGHTS_CREATE_SUBKEY,
1260                            token, &hive);
1261         if (!W_ERROR_IS_OK(err)) {
1262                 SAFE_FREE(path);
1263                 return err;
1264         }
1265
1266         err = reg_deletekey(hive, p+1);
1267         SAFE_FREE(path);
1268         TALLOC_FREE(hive);
1269         return err;
1270 }
1271 #endif /* #if 0 */