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