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