s3:registry: extract the reg_cachehook prototypes into their own header.
[sfrench/samba-autobuild/.git] / source3 / registry / reg_api.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  Virtual Windows Registry Layer
4  *  Copyright (C) Volker Lendecke 2006
5  *  Copyright (C) Michael Adam 2007-2008
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 /* Attempt to wrap the existing API in a more winreg.idl-like way */
22
23 /*
24  * Here is a list of winreg.idl functions and corresponding implementations
25  * provided here:
26  *
27  * 0x00         winreg_OpenHKCR
28  * 0x01         winreg_OpenHKCU
29  * 0x02         winreg_OpenHKLM
30  * 0x03         winreg_OpenHKPD
31  * 0x04         winreg_OpenHKU
32  * 0x05         winreg_CloseKey
33  * 0x06         winreg_CreateKey                        reg_createkey
34  * 0x07         winreg_DeleteKey                        reg_deletekey
35  * 0x08         winreg_DeleteValue                      reg_deletevalue
36  * 0x09         winreg_EnumKey                          reg_enumkey
37  * 0x0a         winreg_EnumValue                        reg_enumvalue
38  * 0x0b         winreg_FlushKey
39  * 0x0c         winreg_GetKeySecurity                   reg_getkeysecurity
40  * 0x0d         winreg_LoadKey
41  * 0x0e         winreg_NotifyChangeKeyValue
42  * 0x0f         winreg_OpenKey                          reg_openkey
43  * 0x10         winreg_QueryInfoKey                     reg_queryinfokey
44  * 0x11         winreg_QueryValue                       reg_queryvalue
45  * 0x12         winreg_ReplaceKey
46  * 0x13         winreg_RestoreKey                       reg_restorekey
47  * 0x14         winreg_SaveKey                          reg_savekey
48  * 0x15         winreg_SetKeySecurity                   reg_setkeysecurity
49  * 0x16         winreg_SetValue                         reg_setvalue
50  * 0x17         winreg_UnLoadKey
51  * 0x18         winreg_InitiateSystemShutdown
52  * 0x19         winreg_AbortSystemShutdown
53  * 0x1a         winreg_GetVersion                       reg_getversion
54  * 0x1b         winreg_OpenHKCC
55  * 0x1c         winreg_OpenHKDD
56  * 0x1d         winreg_QueryMultipleValues
57  * 0x1e         winreg_InitiateSystemShutdownEx
58  * 0x1f         winreg_SaveKeyEx
59  * 0x20         winreg_OpenHKPT
60  * 0x21         winreg_OpenHKPN
61  * 0x22         winreg_QueryMultipleValues2
62  *
63  */
64
65 #include "includes.h"
66 #include "registry.h"
67 #include "reg_cachehook.h"
68 #include "regfio.h"
69
70 #undef DBGC_CLASS
71 #define DBGC_CLASS DBGC_REGISTRY
72
73
74 /**********************************************************************
75  * Helper functions
76  **********************************************************************/
77
78 static WERROR fill_value_cache(struct registry_key *key)
79 {
80         if (key->values != NULL) {
81                 if (!reg_values_need_update(key->key, key->values)) {
82                         return WERR_OK;
83                 }
84         }
85
86         if (!(key->values = TALLOC_ZERO_P(key, struct regval_ctr))) {
87                 return WERR_NOMEM;
88         }
89         if (fetch_reg_values(key->key, key->values) == -1) {
90                 TALLOC_FREE(key->values);
91                 return WERR_BADFILE;
92         }
93
94         return WERR_OK;
95 }
96
97 static WERROR fill_subkey_cache(struct registry_key *key)
98 {
99         WERROR werr;
100
101         if (key->subkeys != NULL) {
102                 if (!reg_subkeys_need_update(key->key, key->subkeys)) {
103                         return WERR_OK;
104                 }
105         }
106
107         werr = regsubkey_ctr_init(key, &(key->subkeys));
108         W_ERROR_NOT_OK_RETURN(werr);
109
110         if (fetch_reg_keys(key->key, key->subkeys) == -1) {
111                 TALLOC_FREE(key->subkeys);
112                 return WERR_NO_MORE_ITEMS;
113         }
114
115         return WERR_OK;
116 }
117
118 static int regkey_destructor(struct registry_key_handle *key)
119 {
120         return regdb_close();
121 }
122
123 static WERROR regkey_open_onelevel(TALLOC_CTX *mem_ctx, 
124                                    struct registry_key *parent,
125                                    const char *name,
126                                    const struct nt_user_token *token,
127                                    uint32 access_desired,
128                                    struct registry_key **pregkey)
129 {
130         WERROR          result = WERR_OK;
131         struct registry_key *regkey;
132         struct registry_key_handle *key;
133         struct regsubkey_ctr    *subkeys = NULL;
134
135         DEBUG(7,("regkey_open_onelevel: name = [%s]\n", name));
136
137         SMB_ASSERT(strchr(name, '\\') == NULL);
138
139         if (!(regkey = TALLOC_ZERO_P(mem_ctx, struct registry_key)) ||
140             !(regkey->token = dup_nt_token(regkey, token)) ||
141             !(regkey->key = TALLOC_ZERO_P(regkey, struct registry_key_handle)))
142         {
143                 result = WERR_NOMEM;
144                 goto done;
145         }
146
147         if ( !(W_ERROR_IS_OK(result = regdb_open())) ) {
148                 goto done;
149         }
150
151         key = regkey->key;
152         talloc_set_destructor(key, regkey_destructor);
153
154         /* initialization */
155
156         key->type = REG_KEY_GENERIC;
157
158         if (name[0] == '\0') {
159                 /*
160                  * Open a copy of the parent key
161                  */
162                 if (!parent) {
163                         result = WERR_BADFILE;
164                         goto done;
165                 }
166                 key->name = talloc_strdup(key, parent->key->name);
167         }
168         else {
169                 /*
170                  * Normal subkey open
171                  */
172                 key->name = talloc_asprintf(key, "%s%s%s",
173                                             parent ? parent->key->name : "",
174                                             parent ? "\\": "",
175                                             name);
176         }
177
178         if (key->name == NULL) {
179                 result = WERR_NOMEM;
180                 goto done;
181         }
182
183         /* Tag this as a Performance Counter Key */
184
185         if( StrnCaseCmp(key->name, KEY_HKPD, strlen(KEY_HKPD)) == 0 )
186                 key->type = REG_KEY_HKPD;
187
188         /* Look up the table of registry I/O operations */
189
190         if ( !(key->ops = reghook_cache_find( key->name )) ) {
191                 DEBUG(0,("reg_open_onelevel: Failed to assign "
192                          "registry_ops to [%s]\n", key->name ));
193                 result = WERR_BADFILE;
194                 goto done;
195         }
196
197         /* check if the path really exists; failed is indicated by -1 */
198         /* if the subkey count failed, bail out */
199
200         result = regsubkey_ctr_init(key, &subkeys);
201         if (!W_ERROR_IS_OK(result)) {
202                 goto done;
203         }
204
205         if ( fetch_reg_keys( key, subkeys ) == -1 )  {
206                 result = WERR_BADFILE;
207                 goto done;
208         }
209
210         TALLOC_FREE( subkeys );
211
212         if ( !regkey_access_check( key, access_desired, &key->access_granted,
213                                    token ) ) {
214                 result = WERR_ACCESS_DENIED;
215                 goto done;
216         }
217
218         *pregkey = regkey;
219         result = WERR_OK;
220
221 done:
222         if ( !W_ERROR_IS_OK(result) ) {
223                 TALLOC_FREE(regkey);
224         }
225
226         return result;
227 }
228
229 WERROR reg_openhive(TALLOC_CTX *mem_ctx, const char *hive,
230                     uint32 desired_access,
231                     const struct nt_user_token *token,
232                     struct registry_key **pkey)
233 {
234         SMB_ASSERT(hive != NULL);
235         SMB_ASSERT(hive[0] != '\0');
236         SMB_ASSERT(strchr(hive, '\\') == NULL);
237
238         return regkey_open_onelevel(mem_ctx, NULL, hive, token, desired_access,
239                                     pkey);
240 }
241
242
243 /**********************************************************************
244  * The API functions
245  **********************************************************************/
246
247 WERROR reg_openkey(TALLOC_CTX *mem_ctx, struct registry_key *parent,
248                    const char *name, uint32 desired_access,
249                    struct registry_key **pkey)
250 {
251         struct registry_key *direct_parent = parent;
252         WERROR err;
253         char *p, *path, *to_free;
254         size_t len;
255
256         if (!(path = SMB_STRDUP(name))) {
257                 return WERR_NOMEM;
258         }
259         to_free = path;
260
261         len = strlen(path);
262
263         if ((len > 0) && (path[len-1] == '\\')) {
264                 path[len-1] = '\0';
265         }
266
267         while ((p = strchr(path, '\\')) != NULL) {
268                 char *name_component;
269                 struct registry_key *tmp;
270
271                 if (!(name_component = SMB_STRNDUP(path, (p - path)))) {
272                         err = WERR_NOMEM;
273                         goto error;
274                 }
275
276                 err = regkey_open_onelevel(mem_ctx, direct_parent,
277                                            name_component, parent->token,
278                                            KEY_ENUMERATE_SUB_KEYS, &tmp);
279                 SAFE_FREE(name_component);
280
281                 if (!W_ERROR_IS_OK(err)) {
282                         goto error;
283                 }
284                 if (direct_parent != parent) {
285                         TALLOC_FREE(direct_parent);
286                 }
287
288                 direct_parent = tmp;
289                 path = p+1;
290         }
291
292         err = regkey_open_onelevel(mem_ctx, direct_parent, path, parent->token,
293                                    desired_access, pkey);
294  error:
295         if (direct_parent != parent) {
296                 TALLOC_FREE(direct_parent);
297         }
298         SAFE_FREE(to_free);
299         return err;
300 }
301
302 WERROR reg_enumkey(TALLOC_CTX *mem_ctx, struct registry_key *key,
303                    uint32 idx, char **name, NTTIME *last_write_time)
304 {
305         WERROR err;
306
307         if (!(key->key->access_granted & KEY_ENUMERATE_SUB_KEYS)) {
308                 return WERR_ACCESS_DENIED;
309         }
310
311         if (!W_ERROR_IS_OK(err = fill_subkey_cache(key))) {
312                 return err;
313         }
314
315         if (idx >= regsubkey_ctr_numkeys(key->subkeys)) {
316                 return WERR_NO_MORE_ITEMS;
317         }
318
319         if (!(*name = talloc_strdup(mem_ctx,
320                         regsubkey_ctr_specific_key(key->subkeys, idx))))
321         {
322                 return WERR_NOMEM;
323         }
324
325         if (last_write_time) {
326                 *last_write_time = 0;
327         }
328
329         return WERR_OK;
330 }
331
332 WERROR reg_enumvalue(TALLOC_CTX *mem_ctx, struct registry_key *key,
333                      uint32 idx, char **pname, struct registry_value **pval)
334 {
335         struct registry_value *val;
336         WERROR err;
337
338         if (!(key->key->access_granted & KEY_QUERY_VALUE)) {
339                 return WERR_ACCESS_DENIED;
340         }
341
342         if (!(W_ERROR_IS_OK(err = fill_value_cache(key)))) {
343                 return err;
344         }
345
346         if (idx >= key->values->num_values) {
347                 return WERR_NO_MORE_ITEMS;
348         }
349
350         err = registry_pull_value(mem_ctx, &val,
351                                   key->values->values[idx]->type,
352                                   key->values->values[idx]->data_p,
353                                   key->values->values[idx]->size,
354                                   key->values->values[idx]->size);
355         if (!W_ERROR_IS_OK(err)) {
356                 return err;
357         }
358
359         if (pname
360             && !(*pname = talloc_strdup(
361                          mem_ctx, key->values->values[idx]->valuename))) {
362                 SAFE_FREE(val);
363                 return WERR_NOMEM;
364         }
365
366         *pval = val;
367         return WERR_OK;
368 }
369
370 WERROR reg_queryvalue(TALLOC_CTX *mem_ctx, struct registry_key *key,
371                       const char *name, struct registry_value **pval)
372 {
373         WERROR err;
374         uint32 i;
375
376         if (!(key->key->access_granted & KEY_QUERY_VALUE)) {
377                 return WERR_ACCESS_DENIED;
378         }
379
380         if (!(W_ERROR_IS_OK(err = fill_value_cache(key)))) {
381                 return err;
382         }
383
384         for (i=0; i<key->values->num_values; i++) {
385                 if (strequal(key->values->values[i]->valuename, name)) {
386                         return reg_enumvalue(mem_ctx, key, i, NULL, pval);
387                 }
388         }
389
390         return WERR_BADFILE;
391 }
392
393 WERROR reg_queryinfokey(struct registry_key *key, uint32_t *num_subkeys,
394                         uint32_t *max_subkeylen, uint32_t *max_subkeysize, 
395                         uint32_t *num_values, uint32_t *max_valnamelen, 
396                         uint32_t *max_valbufsize, uint32_t *secdescsize,
397                         NTTIME *last_changed_time)
398 {
399         uint32 i, max_size;
400         size_t max_len;
401         TALLOC_CTX *mem_ctx;
402         WERROR err;
403         struct security_descriptor *secdesc;
404
405         if (!(key->key->access_granted & KEY_QUERY_VALUE)) {
406                 return WERR_ACCESS_DENIED;
407         }
408
409         if (!W_ERROR_IS_OK(fill_subkey_cache(key)) ||
410             !W_ERROR_IS_OK(fill_value_cache(key))) {
411                 return WERR_BADFILE;
412         }
413
414         max_len = 0;
415         for (i=0; i< regsubkey_ctr_numkeys(key->subkeys); i++) {
416                 max_len = MAX(max_len,
417                         strlen(regsubkey_ctr_specific_key(key->subkeys, i)));
418         }
419
420         *num_subkeys = regsubkey_ctr_numkeys(key->subkeys);
421         *max_subkeylen = max_len;
422         *max_subkeysize = 0;    /* Class length? */
423
424         max_len = 0;
425         max_size = 0;
426         for (i=0; i<key->values->num_values; i++) {
427                 max_len = MAX(max_len,
428                               strlen(key->values->values[i]->valuename));
429                 max_size = MAX(max_size, key->values->values[i]->size);
430         }
431
432         *num_values = key->values->num_values;
433         *max_valnamelen = max_len;
434         *max_valbufsize = max_size;
435
436         if (!(mem_ctx = talloc_new(key))) {
437                 return WERR_NOMEM;
438         }
439
440         err = regkey_get_secdesc(mem_ctx, key->key, &secdesc);
441         if (!W_ERROR_IS_OK(err)) {
442                 TALLOC_FREE(mem_ctx);
443                 return err;
444         }
445
446         *secdescsize = ndr_size_security_descriptor(secdesc, 0);
447         TALLOC_FREE(mem_ctx);
448
449         *last_changed_time = 0;
450
451         return WERR_OK;
452 }
453
454 WERROR reg_createkey(TALLOC_CTX *ctx, struct registry_key *parent,
455                      const char *subkeypath, uint32 desired_access,
456                      struct registry_key **pkey,
457                      enum winreg_CreateAction *paction)
458 {
459         struct registry_key *key = parent;
460         struct registry_key *create_parent;
461         TALLOC_CTX *mem_ctx;
462         char *path, *end;
463         WERROR err;
464
465         /*
466          * We must refuse to handle subkey-paths containing
467          * a '/' character because at a lower level, after
468          * normalization, '/' is treated as a key separator
469          * just like '\\'.
470          */
471         if (strchr(subkeypath, '/') != NULL) {
472                 return WERR_INVALID_PARAM;
473         }
474
475         if (!(mem_ctx = talloc_new(ctx))) return WERR_NOMEM;
476
477         if (!(path = talloc_strdup(mem_ctx, subkeypath))) {
478                 err = WERR_NOMEM;
479                 goto done;
480         }
481
482         while ((end = strchr(path, '\\')) != NULL) {
483                 struct registry_key *tmp;
484                 enum winreg_CreateAction action;
485
486                 *end = '\0';
487
488                 err = reg_createkey(mem_ctx, key, path,
489                                     KEY_ENUMERATE_SUB_KEYS, &tmp, &action);
490                 if (!W_ERROR_IS_OK(err)) {
491                         goto done;
492                 }
493
494                 if (key != parent) {
495                         TALLOC_FREE(key);
496                 }
497
498                 key = tmp;
499                 path = end+1;
500         }
501
502         /*
503          * At this point, "path" contains the one-element subkey of "key". We
504          * can try to open it.
505          */
506
507         err = reg_openkey(ctx, key, path, desired_access, pkey);
508         if (W_ERROR_IS_OK(err)) {
509                 if (paction != NULL) {
510                         *paction = REG_OPENED_EXISTING_KEY;
511                 }
512                 goto done;
513         }
514
515         if (!W_ERROR_EQUAL(err, WERR_BADFILE)) {
516                 /*
517                  * Something but "notfound" has happened, so bail out
518                  */
519                 goto done;
520         }
521
522         /*
523          * We have to make a copy of the current key, as we opened it only
524          * with ENUM_SUBKEY access.
525          */
526
527         err = reg_openkey(mem_ctx, key, "", KEY_CREATE_SUB_KEY,
528                           &create_parent);
529         if (!W_ERROR_IS_OK(err)) {
530                 goto done;
531         }
532
533         /*
534          * Actually create the subkey
535          */
536
537         err = fill_subkey_cache(create_parent);
538         if (!W_ERROR_IS_OK(err)) goto done;
539
540         err = create_reg_subkey(key->key, path);
541         W_ERROR_NOT_OK_GOTO_DONE(err);
542
543         /*
544          * Now open the newly created key
545          */
546
547         err = reg_openkey(ctx, create_parent, path, desired_access, pkey);
548         if (W_ERROR_IS_OK(err) && (paction != NULL)) {
549                 *paction = REG_CREATED_NEW_KEY;
550         }
551
552  done:
553         TALLOC_FREE(mem_ctx);
554         return err;
555 }
556
557 WERROR reg_deletekey(struct registry_key *parent, const char *path)
558 {
559         WERROR err;
560         char *name, *end;
561         struct registry_key *tmp_key, *key;
562         TALLOC_CTX *mem_ctx = talloc_stackframe();
563
564         name = talloc_strdup(mem_ctx, path);
565         if (name == NULL) {
566                 err = WERR_NOMEM;
567                 goto done;
568         }
569
570         /* check if the key has subkeys */
571         err = reg_openkey(mem_ctx, parent, name, REG_KEY_READ, &key);
572         W_ERROR_NOT_OK_GOTO_DONE(err);
573
574         err = fill_subkey_cache(key);
575         W_ERROR_NOT_OK_GOTO_DONE(err);
576
577         if (regsubkey_ctr_numkeys(key->subkeys) > 0) {
578                 err = WERR_ACCESS_DENIED;
579                 goto done;
580         }
581
582         /* no subkeys - proceed with delete */
583         end = strrchr(name, '\\');
584         if (end != NULL) {
585                 *end = '\0';
586
587                 err = reg_openkey(mem_ctx, parent, name,
588                                   KEY_CREATE_SUB_KEY, &tmp_key);
589                 W_ERROR_NOT_OK_GOTO_DONE(err);
590
591                 parent = tmp_key;
592                 name = end+1;
593         }
594
595         if (name[0] == '\0') {
596                 err = WERR_INVALID_PARAM;
597                 goto done;
598         }
599
600         err = delete_reg_subkey(parent->key, name);
601
602 done:
603         TALLOC_FREE(mem_ctx);
604         return err;
605 }
606
607 WERROR reg_setvalue(struct registry_key *key, const char *name,
608                     const struct registry_value *val)
609 {
610         WERROR err;
611         DATA_BLOB value_data;
612         int res;
613
614         if (!(key->key->access_granted & KEY_SET_VALUE)) {
615                 return WERR_ACCESS_DENIED;
616         }
617
618         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
619                 return err;
620         }
621
622         err = registry_push_value(key, val, &value_data);
623         if (!W_ERROR_IS_OK(err)) {
624                 return err;
625         }
626
627         res = regval_ctr_addvalue(key->values, name, val->type,
628                                   (char *)value_data.data, value_data.length);
629         TALLOC_FREE(value_data.data);
630
631         if (res == 0) {
632                 TALLOC_FREE(key->values);
633                 return WERR_NOMEM;
634         }
635
636         if (!store_reg_values(key->key, key->values)) {
637                 TALLOC_FREE(key->values);
638                 return WERR_REG_IO_FAILURE;
639         }
640
641         return WERR_OK;
642 }
643
644 static WERROR reg_value_exists(struct registry_key *key, const char *name)
645 {
646         int i;
647
648         for (i=0; i<key->values->num_values; i++) {
649                 if (strequal(key->values->values[i]->valuename, name)) {
650                         return WERR_OK;
651                 }
652         }
653
654         return WERR_BADFILE;
655 }
656
657 WERROR reg_deletevalue(struct registry_key *key, const char *name)
658 {
659         WERROR err;
660
661         if (!(key->key->access_granted & KEY_SET_VALUE)) {
662                 return WERR_ACCESS_DENIED;
663         }
664
665         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
666                 return err;
667         }
668
669         err = reg_value_exists(key, name);
670         if (!W_ERROR_IS_OK(err)) {
671                 return err;
672         }
673
674         regval_ctr_delvalue(key->values, name);
675
676         if (!store_reg_values(key->key, key->values)) {
677                 TALLOC_FREE(key->values);
678                 return WERR_REG_IO_FAILURE;
679         }
680
681         return WERR_OK;
682 }
683
684 WERROR reg_getkeysecurity(TALLOC_CTX *mem_ctx, struct registry_key *key,
685                           struct security_descriptor **psecdesc)
686 {
687         return regkey_get_secdesc(mem_ctx, key->key, psecdesc);
688 }
689
690 WERROR reg_setkeysecurity(struct registry_key *key,
691                           struct security_descriptor *psecdesc)
692 {
693         return regkey_set_secdesc(key->key, psecdesc);
694 }
695
696 WERROR reg_getversion(uint32_t *version)
697 {
698         if (version == NULL) {
699                 return WERR_INVALID_PARAM;
700         }
701
702         *version = 0x00000005; /* Windows 2000 registry API version */
703         return WERR_OK;
704 }
705
706 /*******************************************************************
707  Note: topkeypat is the *full* path that this *key will be
708  loaded into (including the name of the key)
709  ********************************************************************/
710
711 static WERROR reg_load_tree(REGF_FILE *regfile, const char *topkeypath,
712                             REGF_NK_REC *key)
713 {
714         REGF_NK_REC *subkey;
715         struct registry_key_handle registry_key;
716         struct regval_ctr *values;
717         struct regsubkey_ctr *subkeys;
718         int i;
719         char *path = NULL;
720         WERROR result = WERR_OK;
721
722         /* initialize the struct registry_key_handle structure */
723
724         registry_key.ops = reghook_cache_find(topkeypath);
725         if (!registry_key.ops) {
726                 DEBUG(0, ("reg_load_tree: Failed to assign registry_ops "
727                           "to [%s]\n", topkeypath));
728                 return WERR_BADFILE;
729         }
730
731         registry_key.name = talloc_strdup(regfile->mem_ctx, topkeypath);
732         if (!registry_key.name) {
733                 DEBUG(0, ("reg_load_tree: Talloc failed for reg_key.name!\n"));
734                 return WERR_NOMEM;
735         }
736
737         /* now start parsing the values and subkeys */
738
739         result = regsubkey_ctr_init(regfile->mem_ctx, &subkeys);
740         W_ERROR_NOT_OK_RETURN(result);
741
742         values = TALLOC_ZERO_P(subkeys, struct regval_ctr);
743         if (values == NULL) {
744                 return WERR_NOMEM;
745         }
746
747         /* copy values into the struct regval_ctr */
748
749         for (i=0; i<key->num_values; i++) {
750                 regval_ctr_addvalue(values, key->values[i].valuename,
751                                     key->values[i].type,
752                                     (char*)key->values[i].data,
753                                     (key->values[i].data_size & ~VK_DATA_IN_OFFSET));
754         }
755
756         /* copy subkeys into the struct regsubkey_ctr */
757
758         key->subkey_index = 0;
759         while ((subkey = regfio_fetch_subkey( regfile, key ))) {
760                 result = regsubkey_ctr_addkey(subkeys, subkey->keyname);
761                 if (!W_ERROR_IS_OK(result)) {
762                         TALLOC_FREE(subkeys);
763                         return result;
764                 }
765         }
766
767         /* write this key and values out */
768
769         if (!store_reg_values(&registry_key, values)
770             || !store_reg_keys(&registry_key, subkeys))
771         {
772                 DEBUG(0,("reg_load_tree: Failed to load %s!\n", topkeypath));
773                 result = WERR_REG_IO_FAILURE;
774         }
775
776         TALLOC_FREE(subkeys);
777
778         if (!W_ERROR_IS_OK(result)) {
779                 return result;
780         }
781
782         /* now continue to load each subkey registry tree */
783
784         key->subkey_index = 0;
785         while ((subkey = regfio_fetch_subkey(regfile, key))) {
786                 path = talloc_asprintf(regfile->mem_ctx,
787                                        "%s\\%s",
788                                        topkeypath,
789                                        subkey->keyname);
790                 if (path == NULL) {
791                         return WERR_NOMEM;
792                 }
793                 result = reg_load_tree(regfile, path, subkey);
794                 if (!W_ERROR_IS_OK(result)) {
795                         break;
796                 }
797         }
798
799         return result;
800 }
801
802 /*******************************************************************
803  ********************************************************************/
804
805 static WERROR restore_registry_key(struct registry_key_handle *krecord,
806                                    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         struct 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         struct registry_key_handle registry_key;
858         WERROR result = WERR_OK;
859         struct security_descriptor *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_handle 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, struct 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(struct registry_key_handle *krecord,
950                                   const char *fname)
951 {
952         REGF_FILE *regfile;
953         WERROR result;
954
955         /* open the registry file....fail if the file already exists */
956
957         regfile = regfio_open(fname, (O_RDWR|O_CREAT|O_EXCL),
958                               (S_IREAD|S_IWRITE));
959         if (regfile == NULL) {
960                 DEBUG(0,("backup_registry_key: failed to open \"%s\" (%s)\n",
961                          fname, strerror(errno) ));
962                 return ntstatus_to_werror(map_nt_error_from_unix(errno));
963         }
964
965         /* write the registry tree to the file  */
966
967         result = reg_write_tree(regfile, krecord->name, NULL);
968
969         /* cleanup */
970
971         regfio_close(regfile);
972
973         return result;
974 }
975
976 WERROR reg_savekey(struct registry_key *key, const char *fname)
977 {
978         return backup_registry_key(key->key, fname);
979 }
980
981 /**********************************************************************
982  * Higher level utility functions
983  **********************************************************************/
984
985 WERROR reg_deleteallvalues(struct registry_key *key)
986 {
987         WERROR err;
988         int i;
989
990         if (!(key->key->access_granted & KEY_SET_VALUE)) {
991                 return WERR_ACCESS_DENIED;
992         }
993
994         if (!W_ERROR_IS_OK(err = fill_value_cache(key))) {
995                 return err;
996         }
997
998         for (i=0; i<key->values->num_values; i++) {
999                 regval_ctr_delvalue(key->values, key->values->values[i]->valuename);
1000         }
1001
1002         if (!store_reg_values(key->key, key->values)) {
1003                 TALLOC_FREE(key->values);
1004                 return WERR_REG_IO_FAILURE;
1005         }
1006
1007         return WERR_OK;
1008 }
1009
1010 /*
1011  * Utility function to open a complete registry path including the hive prefix.
1012  */
1013
1014 WERROR reg_open_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1015                      uint32 desired_access, const struct nt_user_token *token,
1016                      struct registry_key **pkey)
1017 {
1018         struct registry_key *hive, *key;
1019         char *path, *p;
1020         WERROR err;
1021
1022         if (!(path = SMB_STRDUP(orig_path))) {
1023                 return WERR_NOMEM;
1024         }
1025
1026         p = strchr(path, '\\');
1027
1028         if ((p == NULL) || (p[1] == '\0')) {
1029                 /*
1030                  * No key behind the hive, just return the hive
1031                  */
1032
1033                 err = reg_openhive(mem_ctx, path, desired_access, token,
1034                                    &hive);
1035                 if (!W_ERROR_IS_OK(err)) {
1036                         SAFE_FREE(path);
1037                         return err;
1038                 }
1039                 SAFE_FREE(path);
1040                 *pkey = hive;
1041                 return WERR_OK;
1042         }
1043
1044         *p = '\0';
1045
1046         err = reg_openhive(mem_ctx, path, KEY_ENUMERATE_SUB_KEYS, token,
1047                            &hive);
1048         if (!W_ERROR_IS_OK(err)) {
1049                 SAFE_FREE(path);
1050                 return err;
1051         }
1052
1053         err = reg_openkey(mem_ctx, hive, p+1, desired_access, &key);
1054
1055         TALLOC_FREE(hive);
1056         SAFE_FREE(path);
1057
1058         if (!W_ERROR_IS_OK(err)) {
1059                 return err;
1060         }
1061
1062         *pkey = key;
1063         return WERR_OK;
1064 }
1065
1066 /*
1067  * Utility function to delete a registry key with all its subkeys.
1068  * Note that reg_deletekey returns ACCESS_DENIED when called on a
1069  * key that has subkeys.
1070  */
1071 static WERROR reg_deletekey_recursive_internal(TALLOC_CTX *ctx,
1072                                                struct registry_key *parent,
1073                                                const char *path,
1074                                                bool del_key)
1075 {
1076         TALLOC_CTX *mem_ctx = NULL;
1077         WERROR werr = WERR_OK;
1078         struct registry_key *key;
1079         char *subkey_name = NULL;
1080         uint32 i;
1081
1082         mem_ctx = talloc_new(ctx);
1083         if (mem_ctx == NULL) {
1084                 werr = WERR_NOMEM;
1085                 goto done;
1086         }
1087
1088         /* recurse through subkeys first */
1089         werr = reg_openkey(mem_ctx, parent, path, REG_KEY_ALL, &key);
1090         if (!W_ERROR_IS_OK(werr)) {
1091                 goto done;
1092         }
1093
1094         werr = fill_subkey_cache(key);
1095         W_ERROR_NOT_OK_GOTO_DONE(werr);
1096
1097         /*
1098          * loop from top to bottom for perfomance:
1099          * this way, we need to rehash the regsubkey containers less
1100          */
1101         for (i = regsubkey_ctr_numkeys(key->subkeys) ; i > 0; i--) {
1102                 subkey_name = regsubkey_ctr_specific_key(key->subkeys, i-1);
1103                 werr = reg_deletekey_recursive_internal(mem_ctx, key,
1104                                         subkey_name,
1105                                         true);
1106                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1107         }
1108
1109         if (del_key) {
1110                 /* now delete the actual key */
1111                 werr = reg_deletekey(parent, path);
1112         }
1113
1114 done:
1115         TALLOC_FREE(mem_ctx);
1116         return werr;
1117 }
1118
1119 static WERROR reg_deletekey_recursive_trans(TALLOC_CTX *ctx,
1120                                             struct registry_key *parent,
1121                                             const char *path,
1122                                             bool del_key)
1123 {
1124         WERROR werr;
1125
1126         werr = regdb_transaction_start();
1127         if (!W_ERROR_IS_OK(werr)) {
1128                 DEBUG(0, ("reg_deletekey_recursive_trans: "
1129                           "error starting transaction: %s\n",
1130                           win_errstr(werr)));
1131                 return werr;
1132         }
1133
1134         werr = reg_deletekey_recursive_internal(ctx, parent, path, del_key);
1135
1136         if (!W_ERROR_IS_OK(werr)) {
1137                 DEBUG(1, (__location__ " failed to delete key '%s' from key "
1138                           "'%s': %s\n", path, parent->key->name,
1139                           win_errstr(werr)));
1140                 werr = regdb_transaction_cancel();
1141                 if (!W_ERROR_IS_OK(werr)) {
1142                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1143                                   "error cancelling transaction: %s\n",
1144                                   win_errstr(werr)));
1145                 }
1146         } else {
1147                 werr = regdb_transaction_commit();
1148                 if (!W_ERROR_IS_OK(werr)) {
1149                         DEBUG(0, ("reg_deletekey_recursive_trans: "
1150                                   "error committing transaction: %s\n",
1151                                   win_errstr(werr)));
1152                 }
1153         }
1154
1155         return werr;
1156 }
1157
1158 WERROR reg_deletekey_recursive(TALLOC_CTX *ctx,
1159                                struct registry_key *parent,
1160                                const char *path)
1161 {
1162         return reg_deletekey_recursive_trans(ctx, parent, path, true);
1163 }
1164
1165 WERROR reg_deletesubkeys_recursive(TALLOC_CTX *ctx,
1166                                    struct registry_key *parent,
1167                                    const char *path)
1168 {
1169         return reg_deletekey_recursive_trans(ctx, parent, path, false);
1170 }
1171
1172 #if 0
1173 /* these two functions are unused. */
1174
1175 /**
1176  * Utility function to create a registry key without opening the hive
1177  * before. Assumes the hive already exists.
1178  */
1179
1180 WERROR reg_create_path(TALLOC_CTX *mem_ctx, const char *orig_path,
1181                        uint32 desired_access,
1182                        const struct nt_user_token *token,
1183                        enum winreg_CreateAction *paction,
1184                        struct registry_key **pkey)
1185 {
1186         struct registry_key *hive;
1187         char *path, *p;
1188         WERROR err;
1189
1190         if (!(path = SMB_STRDUP(orig_path))) {
1191                 return WERR_NOMEM;
1192         }
1193
1194         p = strchr(path, '\\');
1195
1196         if ((p == NULL) || (p[1] == '\0')) {
1197                 /*
1198                  * No key behind the hive, just return the hive
1199                  */
1200
1201                 err = reg_openhive(mem_ctx, path, desired_access, token,
1202                                    &hive);
1203                 if (!W_ERROR_IS_OK(err)) {
1204                         SAFE_FREE(path);
1205                         return err;
1206                 }
1207                 SAFE_FREE(path);
1208                 *pkey = hive;
1209                 *paction = REG_OPENED_EXISTING_KEY;
1210                 return WERR_OK;
1211         }
1212
1213         *p = '\0';
1214
1215         err = reg_openhive(mem_ctx, path,
1216                            (strchr(p+1, '\\') != NULL) ?
1217                            KEY_ENUMERATE_SUB_KEYS : KEY_CREATE_SUB_KEY,
1218                            token, &hive);
1219         if (!W_ERROR_IS_OK(err)) {
1220                 SAFE_FREE(path);
1221                 return err;
1222         }
1223
1224         err = reg_createkey(mem_ctx, hive, p+1, desired_access, pkey, paction);
1225         SAFE_FREE(path);
1226         TALLOC_FREE(hive);
1227         return err;
1228 }
1229
1230 /*
1231  * Utility function to create a registry key without opening the hive
1232  * before. Will not delete a hive.
1233  */
1234
1235 WERROR reg_delete_path(const struct nt_user_token *token,
1236                        const char *orig_path)
1237 {
1238         struct registry_key *hive;
1239         char *path, *p;
1240         WERROR err;
1241
1242         if (!(path = SMB_STRDUP(orig_path))) {
1243                 return WERR_NOMEM;
1244         }
1245
1246         p = strchr(path, '\\');
1247
1248         if ((p == NULL) || (p[1] == '\0')) {
1249                 SAFE_FREE(path);
1250                 return WERR_INVALID_PARAM;
1251         }
1252
1253         *p = '\0';
1254
1255         err = reg_openhive(NULL, path,
1256                            (strchr(p+1, '\\') != NULL) ?
1257                            KEY_ENUMERATE_SUB_KEYS : KEY_CREATE_SUB_KEY,
1258                            token, &hive);
1259         if (!W_ERROR_IS_OK(err)) {
1260                 SAFE_FREE(path);
1261                 return err;
1262         }
1263
1264         err = reg_deletekey(hive, p+1);
1265         SAFE_FREE(path);
1266         TALLOC_FREE(hive);
1267         return err;
1268 }
1269 #endif /* #if 0 */