s3:registry: don't directly access key->subkeys->subkeys[] in reg_api.c
[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, struct 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         struct 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->ops = reghook_cache_find( key->name )) ) {
187                 DEBUG(0,("reg_open_onelevel: Failed to assign "
188                          "REGISTRY_OPS 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, struct 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 >= regsubkey_ctr_numkeys(key->subkeys)) {
312                 return WERR_NO_MORE_ITEMS;
313         }
314
315         if (!(*name = talloc_strdup(mem_ctx,
316                         regsubkey_ctr_specific_key(key->subkeys, idx))))
317         {
318                 return WERR_NOMEM;
319         }
320
321         if (last_write_time) {
322                 *last_write_time = 0;
323         }
324
325         return WERR_OK;
326 }
327
328 WERROR reg_enumvalue(TALLOC_CTX *mem_ctx, struct registry_key *key,
329                      uint32 idx, char **pname, struct registry_value **pval)
330 {
331         struct registry_value *val;
332         WERROR err;
333
334         if (!(key->key->access_granted & SEC_RIGHTS_QUERY_VALUE)) {
335                 return WERR_ACCESS_DENIED;
336         }
337
338         if (!(W_ERROR_IS_OK(err = fill_value_cache(key)))) {
339                 return err;
340         }
341
342         if (idx >= key->values->num_values) {
343                 return WERR_NO_MORE_ITEMS;
344         }
345
346         err = registry_pull_value(mem_ctx, &val,
347                                   key->values->values[idx]->type,
348                                   key->values->values[idx]->data_p,
349                                   key->values->values[idx]->size,
350                                   key->values->values[idx]->size);
351         if (!W_ERROR_IS_OK(err)) {
352                 return err;
353         }
354
355         if (pname
356             && !(*pname = talloc_strdup(
357                          mem_ctx, key->values->values[idx]->valuename))) {
358                 SAFE_FREE(val);
359                 return WERR_NOMEM;
360         }
361
362         *pval = val;
363         return WERR_OK;
364 }
365
366 WERROR reg_queryvalue(TALLOC_CTX *mem_ctx, struct registry_key *key,
367                       const char *name, struct registry_value **pval)
368 {
369         WERROR err;
370         uint32 i;
371
372         if (!(key->key->access_granted & SEC_RIGHTS_QUERY_VALUE)) {
373                 return WERR_ACCESS_DENIED;
374         }
375
376         if (!(W_ERROR_IS_OK(err = fill_value_cache(key)))) {
377                 return err;
378         }
379
380         for (i=0; i<key->values->num_values; i++) {
381                 if (strequal(key->values->values[i]->valuename, name)) {
382                         return reg_enumvalue(mem_ctx, key, i, NULL, pval);
383                 }
384         }
385
386         return WERR_BADFILE;
387 }
388
389 WERROR reg_queryinfokey(struct registry_key *key, uint32_t *num_subkeys,
390                         uint32_t *max_subkeylen, uint32_t *max_subkeysize, 
391                         uint32_t *num_values, uint32_t *max_valnamelen, 
392                         uint32_t *max_valbufsize, uint32_t *secdescsize,
393                         NTTIME *last_changed_time)
394 {
395         uint32 i, max_size;
396         size_t max_len;
397         TALLOC_CTX *mem_ctx;
398         WERROR err;
399         struct security_descriptor *secdesc;
400
401         if (!(key->key->access_granted & SEC_RIGHTS_QUERY_VALUE)) {
402                 return WERR_ACCESS_DENIED;
403         }
404
405         if (!W_ERROR_IS_OK(fill_subkey_cache(key)) ||
406             !W_ERROR_IS_OK(fill_value_cache(key))) {
407                 return WERR_BADFILE;
408         }
409
410         max_len = 0;
411         for (i=0; i< regsubkey_ctr_numkeys(key->subkeys); i++) {
412                 max_len = MAX(max_len,
413                         strlen(regsubkey_ctr_specific_key(key->subkeys, i)));
414         }
415
416         *num_subkeys = regsubkey_ctr_numkeys(key->subkeys);
417         *max_subkeylen = max_len;
418         *max_subkeysize = 0;    /* Class length? */
419
420         max_len = 0;
421         max_size = 0;
422         for (i=0; i<key->values->num_values; i++) {
423                 max_len = MAX(max_len,
424                               strlen(key->values->values[i]->valuename));
425                 max_size = MAX(max_size, key->values->values[i]->size);
426         }
427
428         *num_values = key->values->num_values;
429         *max_valnamelen = max_len;
430         *max_valbufsize = max_size;
431
432         if (!(mem_ctx = talloc_new(key))) {
433                 return WERR_NOMEM;
434         }
435
436         err = regkey_get_secdesc(mem_ctx, key->key, &secdesc);
437         if (!W_ERROR_IS_OK(err)) {
438                 TALLOC_FREE(mem_ctx);
439                 return err;
440         }
441
442         *secdescsize = ndr_size_security_descriptor(secdesc, NULL, 0);
443         TALLOC_FREE(mem_ctx);
444
445         *last_changed_time = 0;
446
447         return WERR_OK;
448 }
449
450 WERROR reg_createkey(TALLOC_CTX *ctx, struct registry_key *parent,
451                      const char *subkeypath, uint32 desired_access,
452                      struct registry_key **pkey,
453                      enum winreg_CreateAction *paction)
454 {
455         struct registry_key *key = parent;
456         struct registry_key *create_parent;
457         TALLOC_CTX *mem_ctx;
458         char *path, *end;
459         WERROR err;
460
461         if (!(mem_ctx = talloc_new(ctx))) return WERR_NOMEM;
462
463         if (!(path = talloc_strdup(mem_ctx, subkeypath))) {
464                 err = WERR_NOMEM;
465                 goto done;
466         }
467
468         while ((end = strchr(path, '\\')) != NULL) {
469                 struct registry_key *tmp;
470                 enum winreg_CreateAction action;
471
472                 *end = '\0';
473
474                 err = reg_createkey(mem_ctx, key, path,
475                                     SEC_RIGHTS_ENUM_SUBKEYS, &tmp, &action);
476                 if (!W_ERROR_IS_OK(err)) {
477                         goto done;
478                 }
479
480                 if (key != parent) {
481                         TALLOC_FREE(key);
482                 }
483
484                 key = tmp;
485                 path = end+1;
486         }
487
488         /*
489          * At this point, "path" contains the one-element subkey of "key". We
490          * can try to open it.
491          */
492
493         err = reg_openkey(ctx, key, path, desired_access, pkey);
494         if (W_ERROR_IS_OK(err)) {
495                 if (paction != NULL) {
496                         *paction = REG_OPENED_EXISTING_KEY;
497                 }
498                 goto done;
499         }
500
501         if (!W_ERROR_EQUAL(err, WERR_BADFILE)) {
502                 /*
503                  * Something but "notfound" has happened, so bail out
504                  */
505                 goto done;
506         }
507
508         /*
509          * We have to make a copy of the current key, as we opened it only
510          * with ENUM_SUBKEY access.
511          */
512
513         err = reg_openkey(mem_ctx, key, "", SEC_RIGHTS_CREATE_SUBKEY,
514                           &create_parent);
515         if (!W_ERROR_IS_OK(err)) {
516                 goto done;
517         }
518
519         /*
520          * Actually create the subkey
521          */
522
523         err = fill_subkey_cache(create_parent);
524         if (!W_ERROR_IS_OK(err)) goto done;
525
526         err = regsubkey_ctr_addkey(create_parent->subkeys, path);
527         if (!W_ERROR_IS_OK(err)) goto done;
528
529         if (!store_reg_keys(create_parent->key, create_parent->subkeys)) {
530                 TALLOC_FREE(create_parent->subkeys);
531                 err = WERR_REG_IO_FAILURE;
532                 goto done;
533         }
534
535         /*
536          * Now open the newly created key
537          */
538
539         err = reg_openkey(ctx, create_parent, path, desired_access, pkey);
540         if (W_ERROR_IS_OK(err) && (paction != NULL)) {
541                 *paction = REG_CREATED_NEW_KEY;
542         }
543
544  done:
545         TALLOC_FREE(mem_ctx);
546         return err;
547 }
548
549 WERROR reg_deletekey(struct registry_key *parent, const char *path)
550 {
551         WERROR err;
552         TALLOC_CTX *mem_ctx;
553         char *name, *end;
554         int num_subkeys;
555         struct registry_key *tmp_key, *key;
556
557         if (!(mem_ctx = talloc_init("reg_createkey"))) return WERR_NOMEM;
558
559         if (!(name = talloc_strdup(mem_ctx, path))) {
560                 err = WERR_NOMEM;
561                 goto error;
562         }
563
564         /* check if the key has subkeys */
565         err = reg_openkey(mem_ctx, parent, name, REG_KEY_READ, &key);
566         if (!W_ERROR_IS_OK(err)) {
567                 goto error;
568         }
569         if (!W_ERROR_IS_OK(err = fill_subkey_cache(key))) {
570                 goto error;
571         }
572         if (regsubkey_ctr_numkeys(key->subkeys) > 0) {
573                 err = WERR_ACCESS_DENIED;
574                 goto error;
575         }
576
577         /* no subkeys - proceed with delete */
578         if ((end = strrchr(name, '\\')) != NULL) {
579                 *end = '\0';
580
581                 err = reg_openkey(mem_ctx, parent, name,
582                                   SEC_RIGHTS_CREATE_SUBKEY, &tmp_key);
583                 if (!W_ERROR_IS_OK(err)) {
584                         goto error;
585                 }
586
587                 parent = tmp_key;
588                 name = end+1;
589         }
590
591         if (name[0] == '\0') {
592                 err = WERR_INVALID_PARAM;
593                 goto error;
594         }
595
596         if (!W_ERROR_IS_OK(err = fill_subkey_cache(parent))) {
597                 goto error;
598         }
599
600         num_subkeys = regsubkey_ctr_numkeys(parent->subkeys);
601
602         if (regsubkey_ctr_delkey(parent->subkeys, name) == num_subkeys) {
603                 err = WERR_BADFILE;
604                 goto error;
605         }
606
607         if (!store_reg_keys(parent->key, parent->subkeys)) {
608                 TALLOC_FREE(parent->subkeys);
609                 err = WERR_REG_IO_FAILURE;
610                 goto error;
611         }
612
613         regkey_set_secdesc(key->key, NULL);
614
615         err = WERR_OK;
616
617  error:
618         TALLOC_FREE(mem_ctx);
619         return err;
620 }
621
622 WERROR reg_setvalue(struct registry_key *key, const char *name,
623                     const struct registry_value *val)
624 {
625         WERROR err;
626         DATA_BLOB value_data;
627         int res;
628
629         if (!(key->key->access_granted & SEC_RIGHTS_SET_VALUE)) {
630                 return WERR_ACCESS_DENIED;
631         }
632
633         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
634                 return err;
635         }
636
637         err = registry_push_value(key, val, &value_data);
638         if (!W_ERROR_IS_OK(err)) {
639                 return err;
640         }
641
642         res = regval_ctr_addvalue(key->values, name, val->type,
643                                   (char *)value_data.data, value_data.length);
644         TALLOC_FREE(value_data.data);
645
646         if (res == 0) {
647                 TALLOC_FREE(key->values);
648                 return WERR_NOMEM;
649         }
650
651         if (!store_reg_values(key->key, key->values)) {
652                 TALLOC_FREE(key->values);
653                 return WERR_REG_IO_FAILURE;
654         }
655
656         return WERR_OK;
657 }
658
659 static WERROR reg_value_exists(struct registry_key *key, const char *name)
660 {
661         int i;
662
663         for (i=0; i<key->values->num_values; i++) {
664                 if (strequal(key->values->values[i]->valuename, name)) {
665                         return WERR_OK;
666                 }
667         }
668
669         return WERR_BADFILE;
670 }
671
672 WERROR reg_deletevalue(struct registry_key *key, const char *name)
673 {
674         WERROR err;
675
676         if (!(key->key->access_granted & SEC_RIGHTS_SET_VALUE)) {
677                 return WERR_ACCESS_DENIED;
678         }
679
680         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
681                 return err;
682         }
683
684         err = reg_value_exists(key, name);
685         if (!W_ERROR_IS_OK(err)) {
686                 return err;
687         }
688
689         regval_ctr_delvalue(key->values, name);
690
691         if (!store_reg_values(key->key, key->values)) {
692                 TALLOC_FREE(key->values);
693                 return WERR_REG_IO_FAILURE;
694         }
695
696         return WERR_OK;
697 }
698
699 WERROR reg_getkeysecurity(TALLOC_CTX *mem_ctx, struct registry_key *key,
700                           struct security_descriptor **psecdesc)
701 {
702         return regkey_get_secdesc(mem_ctx, key->key, psecdesc);
703 }
704
705 WERROR reg_setkeysecurity(struct registry_key *key,
706                           struct security_descriptor *psecdesc)
707 {
708         return regkey_set_secdesc(key->key, psecdesc);
709 }
710
711 WERROR reg_getversion(uint32_t *version)
712 {
713         if (version == NULL) {
714                 return WERR_INVALID_PARAM;
715         }
716
717         *version = 0x00000005; /* Windows 2000 registry API version */
718         return WERR_OK;
719 }
720
721 /*******************************************************************
722  Note: topkeypat is the *full* path that this *key will be
723  loaded into (including the name of the key)
724  ********************************************************************/
725
726 static WERROR reg_load_tree(REGF_FILE *regfile, const char *topkeypath,
727                             REGF_NK_REC *key)
728 {
729         REGF_NK_REC *subkey;
730         REGISTRY_KEY registry_key;
731         REGVAL_CTR *values;
732         struct regsubkey_ctr *subkeys;
733         int i;
734         char *path = NULL;
735         WERROR result = WERR_OK;
736
737         /* initialize the REGISTRY_KEY structure */
738
739         registry_key.ops = reghook_cache_find(topkeypath);
740         if (!registry_key.ops) {
741                 DEBUG(0, ("reg_load_tree: Failed to assign  REGISTRY_OPS "
742                           "to [%s]\n", topkeypath));
743                 return WERR_BADFILE;
744         }
745
746         registry_key.name = talloc_strdup(regfile->mem_ctx, topkeypath);
747         if (!registry_key.name) {
748                 DEBUG(0, ("reg_load_tree: Talloc failed for reg_key.name!\n"));
749                 return WERR_NOMEM;
750         }
751
752         /* now start parsing the values and subkeys */
753
754         subkeys = TALLOC_ZERO_P(regfile->mem_ctx, struct regsubkey_ctr);
755         if (subkeys == NULL) {
756                 return WERR_NOMEM;
757         }
758
759         values = TALLOC_ZERO_P(subkeys, REGVAL_CTR);
760         if (values == NULL) {
761                 return WERR_NOMEM;
762         }
763
764         /* copy values into the REGVAL_CTR */
765
766         for (i=0; i<key->num_values; i++) {
767                 regval_ctr_addvalue(values, key->values[i].valuename,
768                                     key->values[i].type,
769                                     (char*)key->values[i].data,
770                                     (key->values[i].data_size & ~VK_DATA_IN_OFFSET));
771         }
772
773         /* copy subkeys into the struct regsubkey_ctr */
774
775         key->subkey_index = 0;
776         while ((subkey = regfio_fetch_subkey( regfile, key ))) {
777                 result = regsubkey_ctr_addkey(subkeys, subkey->keyname);
778                 if (!W_ERROR_IS_OK(result)) {
779                         TALLOC_FREE(subkeys);
780                         return result;
781                 }
782         }
783
784         /* write this key and values out */
785
786         if (!store_reg_values(&registry_key, values)
787             || !store_reg_keys(&registry_key, subkeys))
788         {
789                 DEBUG(0,("reg_load_tree: Failed to load %s!\n", topkeypath));
790                 result = WERR_REG_IO_FAILURE;
791         }
792
793         TALLOC_FREE(subkeys);
794
795         if (!W_ERROR_IS_OK(result)) {
796                 return result;
797         }
798
799         /* now continue to load each subkey registry tree */
800
801         key->subkey_index = 0;
802         while ((subkey = regfio_fetch_subkey(regfile, key))) {
803                 path = talloc_asprintf(regfile->mem_ctx,
804                                        "%s\\%s",
805                                        topkeypath,
806                                        subkey->keyname);
807                 if (path == NULL) {
808                         return WERR_NOMEM;
809                 }
810                 result = reg_load_tree(regfile, path, subkey);
811                 if (!W_ERROR_IS_OK(result)) {
812                         break;
813                 }
814         }
815
816         return result;
817 }
818
819 /*******************************************************************
820  ********************************************************************/
821
822 static WERROR restore_registry_key(REGISTRY_KEY *krecord, const char *fname)
823 {
824         REGF_FILE *regfile;
825         REGF_NK_REC *rootkey;
826         WERROR result;
827
828         /* open the registry file....fail if the file already exists */
829
830         regfile = regfio_open(fname, (O_RDONLY), 0);
831         if (regfile == NULL) {
832                 DEBUG(0, ("restore_registry_key: failed to open \"%s\" (%s)\n",
833                           fname, strerror(errno)));
834                 return ntstatus_to_werror(map_nt_error_from_unix(errno));
835         }
836
837         /* get the rootkey from the regf file and then load the tree
838            via recursive calls */
839
840         if (!(rootkey = regfio_rootkey(regfile))) {
841                 regfio_close(regfile);
842                 return WERR_REG_FILE_INVALID;
843         }
844
845         result = reg_load_tree(regfile, krecord->name, rootkey);
846
847         /* cleanup */
848
849         regfio_close(regfile);
850
851         return result;
852 }
853
854 WERROR reg_restorekey(struct registry_key *key, const char *fname)
855 {
856         return restore_registry_key(key->key, fname);
857 }
858
859 /********************************************************************
860 ********************************************************************/
861
862 static WERROR reg_write_tree(REGF_FILE *regfile, const char *keypath,
863                              REGF_NK_REC *parent)
864 {
865         REGF_NK_REC *key;
866         REGVAL_CTR *values;
867         struct regsubkey_ctr *subkeys;
868         int i, num_subkeys;
869         char *key_tmp = NULL;
870         char *keyname, *parentpath;
871         char *subkeypath = NULL;
872         char *subkeyname;
873         REGISTRY_KEY registry_key;
874         WERROR result = WERR_OK;
875         SEC_DESC *sec_desc = NULL;
876
877         if (!regfile) {
878                 return WERR_GENERAL_FAILURE;
879         }
880
881         if (!keypath) {
882                 return WERR_OBJECT_PATH_INVALID;
883         }
884
885         /* split up the registry key path */
886
887         key_tmp = talloc_strdup(regfile->mem_ctx, keypath);
888         if (!key_tmp) {
889                 return WERR_NOMEM;
890         }
891         if (!reg_split_key(key_tmp, &parentpath, &keyname)) {
892                 return WERR_OBJECT_PATH_INVALID;
893         }
894
895         if (!keyname) {
896                 keyname = parentpath;
897         }
898
899         /* we need a REGISTRY_KEY object here to enumerate subkeys and values */
900
901         ZERO_STRUCT(registry_key);
902
903         registry_key.name = talloc_strdup(regfile->mem_ctx, keypath);
904         if (registry_key.name == NULL) {
905                 return WERR_NOMEM;
906         }
907
908         registry_key.ops = reghook_cache_find(registry_key.name);
909         if (registry_key.ops == NULL) {
910                 return WERR_BADFILE;
911         }
912
913         /* lookup the values and subkeys */
914
915         subkeys = TALLOC_ZERO_P(regfile->mem_ctx, struct regsubkey_ctr);
916         if (subkeys == NULL) {
917                 return WERR_NOMEM;
918         }
919
920         values = TALLOC_ZERO_P(subkeys, REGVAL_CTR);
921         if (values == NULL) {
922                 return WERR_NOMEM;
923         }
924
925         fetch_reg_keys(&registry_key, subkeys);
926         fetch_reg_values(&registry_key, values);
927
928         result = regkey_get_secdesc(regfile->mem_ctx, &registry_key, &sec_desc);
929         if (!W_ERROR_IS_OK(result)) {
930                 goto done;
931         }
932
933         /* write out this key */
934
935         key = regfio_write_key(regfile, keyname, values, subkeys, sec_desc,
936                                parent);
937         if (key == NULL) {
938                 result = WERR_CAN_NOT_COMPLETE;
939                 goto done;
940         }
941
942         /* write each one of the subkeys out */
943
944         num_subkeys = regsubkey_ctr_numkeys(subkeys);
945         for (i=0; i<num_subkeys; i++) {
946                 subkeyname = regsubkey_ctr_specific_key(subkeys, i);
947                 subkeypath = talloc_asprintf(regfile->mem_ctx, "%s\\%s",
948                                              keypath, subkeyname);
949                 if (subkeypath == NULL) {
950                         result = WERR_NOMEM;
951                         goto done;
952                 }
953                 result = reg_write_tree(regfile, subkeypath, key);
954                 if (!W_ERROR_IS_OK(result))
955                         goto done;
956         }
957
958         DEBUG(6, ("reg_write_tree: wrote key [%s]\n", keypath));
959
960 done:
961         TALLOC_FREE(subkeys);
962         TALLOC_FREE(registry_key.name);
963
964         return result;
965 }
966
967 static WERROR backup_registry_key(REGISTRY_KEY *krecord, const char *fname)
968 {
969         REGF_FILE *regfile;
970         WERROR result;
971
972         /* open the registry file....fail if the file already exists */
973
974         regfile = regfio_open(fname, (O_RDWR|O_CREAT|O_EXCL),
975                               (S_IREAD|S_IWRITE));
976         if (regfile == NULL) {
977                 DEBUG(0,("backup_registry_key: failed to open \"%s\" (%s)\n",
978                          fname, strerror(errno) ));
979                 return ntstatus_to_werror(map_nt_error_from_unix(errno));
980         }
981
982         /* write the registry tree to the file  */
983
984         result = reg_write_tree(regfile, krecord->name, NULL);
985
986         /* cleanup */
987
988         regfio_close(regfile);
989
990         return result;
991 }
992
993 WERROR reg_savekey(struct registry_key *key, const char *fname)
994 {
995         return backup_registry_key(key->key, fname);
996 }
997
998 /**********************************************************************
999  * Higher level utility functions
1000  **********************************************************************/
1001
1002 WERROR reg_deleteallvalues(struct registry_key *key)
1003 {
1004         WERROR err;
1005         int i;
1006
1007         if (!(key->key->access_granted & SEC_RIGHTS_SET_VALUE)) {
1008                 return WERR_ACCESS_DENIED;
1009         }
1010
1011         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
1012                 return err;
1013         }
1014
1015         for (i=0; i<key->values->num_values; i++) {
1016                 regval_ctr_delvalue(key->values, key->values->values[i]->valuename);
1017         }
1018
1019         if (!store_reg_values(key->key, key->values)) {
1020                 TALLOC_FREE(key->values);
1021                 return WERR_REG_IO_FAILURE;
1022         }
1023
1024         return WERR_OK;
1025 }
1026
1027 /*
1028  * Utility function to open a complete registry path including the hive prefix.
1029  */
1030
1031 WERROR reg_open_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1032                      uint32 desired_access, const struct nt_user_token *token,
1033                      struct registry_key **pkey)
1034 {
1035         struct registry_key *hive, *key;
1036         char *path, *p;
1037         WERROR err;
1038
1039         if (!(path = SMB_STRDUP(orig_path))) {
1040                 return WERR_NOMEM;
1041         }
1042
1043         p = strchr(path, '\\');
1044
1045         if ((p == NULL) || (p[1] == '\0')) {
1046                 /*
1047                  * No key behind the hive, just return the hive
1048                  */
1049
1050                 err = reg_openhive(mem_ctx, path, desired_access, token,
1051                                    &hive);
1052                 if (!W_ERROR_IS_OK(err)) {
1053                         SAFE_FREE(path);
1054                         return err;
1055                 }
1056                 SAFE_FREE(path);
1057                 *pkey = hive;
1058                 return WERR_OK;
1059         }
1060
1061         *p = '\0';
1062
1063         err = reg_openhive(mem_ctx, path, SEC_RIGHTS_ENUM_SUBKEYS, token,
1064                            &hive);
1065         if (!W_ERROR_IS_OK(err)) {
1066                 SAFE_FREE(path);
1067                 return err;
1068         }
1069
1070         err = reg_openkey(mem_ctx, hive, p+1, desired_access, &key);
1071
1072         TALLOC_FREE(hive);
1073         SAFE_FREE(path);
1074
1075         if (!W_ERROR_IS_OK(err)) {
1076                 return err;
1077         }
1078
1079         *pkey = key;
1080         return WERR_OK;
1081 }
1082
1083 /*
1084  * Utility function to delete a registry key with all its subkeys.
1085  * Note that reg_deletekey returns ACCESS_DENIED when called on a
1086  * key that has subkeys.
1087  */
1088 static WERROR reg_deletekey_recursive_internal(TALLOC_CTX *ctx,
1089                                                struct registry_key *parent,
1090                                                const char *path,
1091                                                bool del_key)
1092 {
1093         TALLOC_CTX *mem_ctx = NULL;
1094         WERROR werr = WERR_OK;
1095         struct registry_key *key;
1096         char *subkey_name = NULL;
1097
1098         mem_ctx = talloc_new(ctx);
1099         if (mem_ctx == NULL) {
1100                 werr = WERR_NOMEM;
1101                 goto done;
1102         }
1103
1104         /* recurse through subkeys first */
1105         werr = reg_openkey(mem_ctx, parent, path, REG_KEY_ALL, &key);
1106         if (!W_ERROR_IS_OK(werr)) {
1107                 goto done;
1108         }
1109
1110         while (W_ERROR_IS_OK(werr = reg_enumkey(mem_ctx, key, 0,
1111                                                 &subkey_name, NULL)))
1112         {
1113                 werr = reg_deletekey_recursive_internal(mem_ctx, key,
1114                                                         subkey_name,
1115                                                         true);
1116                 if (!W_ERROR_IS_OK(werr)) {
1117                         goto done;
1118                 }
1119         }
1120         if (!W_ERROR_EQUAL(WERR_NO_MORE_ITEMS, werr)) {
1121                 DEBUG(1, ("reg_deletekey_recursive_internal: "
1122                           "Error enumerating subkeys: %s\n",
1123                           win_errstr(werr)));
1124                 goto done;
1125         }
1126
1127         werr = WERR_OK;
1128
1129         if (del_key) {
1130                 /* now delete the actual key */
1131                 werr = reg_deletekey(parent, path);
1132         }
1133
1134 done:
1135         TALLOC_FREE(mem_ctx);
1136         return werr;
1137 }
1138
1139 static WERROR reg_deletekey_recursive_trans(TALLOC_CTX *ctx,
1140                                             struct registry_key *parent,
1141                                             const char *path,
1142                                             bool del_key)
1143 {
1144         WERROR werr;
1145
1146         werr = regdb_transaction_start();
1147         if (!W_ERROR_IS_OK(werr)) {
1148                 DEBUG(0, ("reg_deletekey_recursive_trans: "
1149                           "error starting transaction: %s\n",
1150                           win_errstr(werr)));
1151                 return werr;
1152         }
1153
1154         werr = reg_deletekey_recursive_internal(ctx, parent, path, del_key);
1155
1156         if (!W_ERROR_IS_OK(werr)) {
1157                 werr = regdb_transaction_cancel();
1158                 if (!W_ERROR_IS_OK(werr)) {
1159                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1160                                   "error cancelling transaction: %s\n",
1161                                   win_errstr(werr)));
1162                 }
1163         } else {
1164                 werr = regdb_transaction_commit();
1165                 if (!W_ERROR_IS_OK(werr)) {
1166                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1167                                   "error committing transaction: %s\n",
1168                                   win_errstr(werr)));
1169                 }
1170         }
1171
1172         return werr;
1173 }
1174
1175 WERROR reg_deletekey_recursive(TALLOC_CTX *ctx,
1176                                struct registry_key *parent,
1177                                const char *path)
1178 {
1179         return reg_deletekey_recursive_trans(ctx, parent, path, true);
1180 }
1181
1182 WERROR reg_deletesubkeys_recursive(TALLOC_CTX *ctx,
1183                                    struct registry_key *parent,
1184                                    const char *path)
1185 {
1186         return reg_deletekey_recursive_trans(ctx, parent, path, false);
1187 }
1188
1189 #if 0
1190 /* these two functions are unused. */
1191
1192 /**
1193  * Utility function to create a registry key without opening the hive
1194  * before. Assumes the hive already exists.
1195  */
1196
1197 WERROR reg_create_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1198                        uint32 desired_access,
1199                        const struct nt_user_token *token,
1200                        enum winreg_CreateAction *paction,
1201                        struct registry_key **pkey)
1202 {
1203         struct registry_key *hive;
1204         char *path, *p;
1205         WERROR err;
1206
1207         if (!(path = SMB_STRDUP(orig_path))) {
1208                 return WERR_NOMEM;
1209         }
1210
1211         p = strchr(path, '\\');
1212
1213         if ((p == NULL) || (p[1] == '\0')) {
1214                 /*
1215                  * No key behind the hive, just return the hive
1216                  */
1217
1218                 err = reg_openhive(mem_ctx, path, desired_access, token,
1219                                    &hive);
1220                 if (!W_ERROR_IS_OK(err)) {
1221                         SAFE_FREE(path);
1222                         return err;
1223                 }
1224                 SAFE_FREE(path);
1225                 *pkey = hive;
1226                 *paction = REG_OPENED_EXISTING_KEY;
1227                 return WERR_OK;
1228         }
1229
1230         *p = '\0';
1231
1232         err = reg_openhive(mem_ctx, path,
1233                            (strchr(p+1, '\\') != NULL) ?
1234                            SEC_RIGHTS_ENUM_SUBKEYS : SEC_RIGHTS_CREATE_SUBKEY,
1235                            token, &hive);
1236         if (!W_ERROR_IS_OK(err)) {
1237                 SAFE_FREE(path);
1238                 return err;
1239         }
1240
1241         err = reg_createkey(mem_ctx, hive, p+1, desired_access, pkey, paction);
1242         SAFE_FREE(path);
1243         TALLOC_FREE(hive);
1244         return err;
1245 }
1246
1247 /*
1248  * Utility function to create a registry key without opening the hive
1249  * before. Will not delete a hive.
1250  */
1251
1252 WERROR reg_delete_path(const struct nt_user_token *token,
1253                        const char *orig_path)
1254 {
1255         struct registry_key *hive;
1256         char *path, *p;
1257         WERROR err;
1258
1259         if (!(path = SMB_STRDUP(orig_path))) {
1260                 return WERR_NOMEM;
1261         }
1262
1263         p = strchr(path, '\\');
1264
1265         if ((p == NULL) || (p[1] == '\0')) {
1266                 SAFE_FREE(path);
1267                 return WERR_INVALID_PARAM;
1268         }
1269
1270         *p = '\0';
1271
1272         err = reg_openhive(NULL, path,
1273                            (strchr(p+1, '\\') != NULL) ?
1274                            SEC_RIGHTS_ENUM_SUBKEYS : SEC_RIGHTS_CREATE_SUBKEY,
1275                            token, &hive);
1276         if (!W_ERROR_IS_OK(err)) {
1277                 SAFE_FREE(path);
1278                 return err;
1279         }
1280
1281         err = reg_deletekey(hive, p+1);
1282         SAFE_FREE(path);
1283         TALLOC_FREE(hive);
1284         return err;
1285 }
1286 #endif /* #if 0 */