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