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