Release 1.5.29.
[wine] / server / registry.c
1 /*
2  * Server-side registry management
3  *
4  * Copyright (C) 1999 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /* To do:
22  * - symbolic links
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39
40 #include "ntstatus.h"
41 #define WIN32_NO_STATUS
42 #include "object.h"
43 #include "file.h"
44 #include "handle.h"
45 #include "request.h"
46 #include "process.h"
47 #include "unicode.h"
48 #include "security.h"
49
50 #include "winternl.h"
51 #include "wine/library.h"
52
53 struct notify
54 {
55     struct list       entry;    /* entry in list of notifications */
56     struct event     *event;    /* event to set when changing this key */
57     int               subtree;  /* true if subtree notification */
58     unsigned int      filter;   /* which events to notify on */
59     obj_handle_t      hkey;     /* hkey associated with this notification */
60     struct process   *process;  /* process in which the hkey is valid */
61 };
62
63 /* a registry key */
64 struct key
65 {
66     struct object     obj;         /* object header */
67     WCHAR            *name;        /* key name */
68     WCHAR            *class;       /* key class */
69     unsigned short    namelen;     /* length of key name */
70     unsigned short    classlen;    /* length of class name */
71     struct key       *parent;      /* parent key */
72     int               last_subkey; /* last in use subkey */
73     int               nb_subkeys;  /* count of allocated subkeys */
74     struct key      **subkeys;     /* subkeys array */
75     int               last_value;  /* last in use value */
76     int               nb_values;   /* count of allocated values in array */
77     struct key_value *values;      /* values array */
78     unsigned int      flags;       /* flags */
79     timeout_t         modif;       /* last modification time */
80     struct list       notify_list; /* list of notifications */
81 };
82
83 /* key flags */
84 #define KEY_VOLATILE 0x0001  /* key is volatile (not saved to disk) */
85 #define KEY_DELETED  0x0002  /* key has been deleted */
86 #define KEY_DIRTY    0x0004  /* key has been modified */
87 #define KEY_SYMLINK  0x0008  /* key is a symbolic link */
88 #define KEY_WOW64    0x0010  /* key contains a Wow6432Node subkey */
89 #define KEY_WOWSHARE 0x0020  /* key is a Wow64 shared key (used for Software\Classes) */
90
91 /* a key value */
92 struct key_value
93 {
94     WCHAR            *name;    /* value name */
95     unsigned short    namelen; /* length of value name */
96     unsigned short    type;    /* value type */
97     data_size_t       len;     /* value data length in bytes */
98     void             *data;    /* pointer to value data */
99 };
100
101 #define MIN_SUBKEYS  8   /* min. number of allocated subkeys per key */
102 #define MIN_VALUES   8   /* min. number of allocated values per key */
103
104 #define MAX_NAME_LEN  255    /* max. length of a key name */
105 #define MAX_VALUE_LEN 16383  /* max. length of a value name */
106
107 /* the root of the registry tree */
108 static struct key *root_key;
109
110 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
111 static const timeout_t save_period = 30 * -TICKS_PER_SEC;  /* delay between periodic saves */
112 static struct timeout_user *save_timeout_user;  /* saving timer */
113 static enum prefix_type { PREFIX_UNKNOWN, PREFIX_32BIT, PREFIX_64BIT } prefix_type;
114
115 static const WCHAR root_name[] = { '\\','R','e','g','i','s','t','r','y','\\' };
116 static const WCHAR wow6432node[] = {'W','o','w','6','4','3','2','N','o','d','e'};
117 static const WCHAR symlink_value[] = {'S','y','m','b','o','l','i','c','L','i','n','k','V','a','l','u','e'};
118 static const struct unicode_str symlink_str = { symlink_value, sizeof(symlink_value) };
119
120 static void set_periodic_save_timer(void);
121 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index );
122
123 /* information about where to save a registry branch */
124 struct save_branch_info
125 {
126     struct key  *key;
127     const char  *path;
128 };
129
130 #define MAX_SAVE_BRANCH_INFO 3
131 static int save_branch_count;
132 static struct save_branch_info save_branch_info[MAX_SAVE_BRANCH_INFO];
133
134
135 /* information about a file being loaded */
136 struct file_load_info
137 {
138     const char *filename; /* input file name */
139     FILE       *file;     /* input file */
140     char       *buffer;   /* line buffer */
141     int         len;      /* buffer length */
142     int         line;     /* current input line */
143     WCHAR      *tmp;      /* temp buffer to use while parsing input */
144     size_t      tmplen;   /* length of temp buffer */
145 };
146
147
148 static void key_dump( struct object *obj, int verbose );
149 static unsigned int key_map_access( struct object *obj, unsigned int access );
150 static struct security_descriptor *key_get_sd( struct object *obj );
151 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle );
152 static void key_destroy( struct object *obj );
153
154 static const struct object_ops key_ops =
155 {
156     sizeof(struct key),      /* size */
157     key_dump,                /* dump */
158     no_get_type,             /* get_type */
159     no_add_queue,            /* add_queue */
160     NULL,                    /* remove_queue */
161     NULL,                    /* signaled */
162     NULL,                    /* satisfied */
163     no_signal,               /* signal */
164     no_get_fd,               /* get_fd */
165     key_map_access,          /* map_access */
166     key_get_sd,              /* get_sd */
167     default_set_sd,          /* set_sd */
168     no_lookup_name,          /* lookup_name */
169     no_open_file,            /* open_file */
170     key_close_handle,        /* close_handle */
171     key_destroy              /* destroy */
172 };
173
174
175 static inline int is_wow6432node( const WCHAR *name, unsigned int len )
176 {
177     return (len == sizeof(wow6432node) &&
178             !memicmpW( name, wow6432node, sizeof(wow6432node)/sizeof(WCHAR) ));
179 }
180
181 /*
182  * The registry text file format v2 used by this code is similar to the one
183  * used by REGEDIT import/export functionality, with the following differences:
184  * - strings and key names can contain \x escapes for Unicode
185  * - key names use escapes too in order to support Unicode
186  * - the modification time optionally follows the key name
187  * - REG_EXPAND_SZ and REG_MULTI_SZ are saved as strings instead of hex
188  */
189
190 /* dump the full path of a key */
191 static void dump_path( const struct key *key, const struct key *base, FILE *f )
192 {
193     if (key->parent && key->parent != base)
194     {
195         dump_path( key->parent, base, f );
196         fprintf( f, "\\\\" );
197     }
198     dump_strW( key->name, key->namelen / sizeof(WCHAR), f, "[]" );
199 }
200
201 /* dump a value to a text file */
202 static void dump_value( const struct key_value *value, FILE *f )
203 {
204     unsigned int i, dw;
205     int count;
206
207     if (value->namelen)
208     {
209         fputc( '\"', f );
210         count = 1 + dump_strW( value->name, value->namelen / sizeof(WCHAR), f, "\"\"" );
211         count += fprintf( f, "\"=" );
212     }
213     else count = fprintf( f, "@=" );
214
215     switch(value->type)
216     {
217     case REG_SZ:
218     case REG_EXPAND_SZ:
219     case REG_MULTI_SZ:
220         /* only output properly terminated strings in string format */
221         if (value->len < sizeof(WCHAR)) break;
222         if (value->len % sizeof(WCHAR)) break;
223         if (((WCHAR *)value->data)[value->len / sizeof(WCHAR) - 1]) break;
224         if (value->type != REG_SZ) fprintf( f, "str(%x):", value->type );
225         fputc( '\"', f );
226         dump_strW( (WCHAR *)value->data, value->len / sizeof(WCHAR), f, "\"\"" );
227         fprintf( f, "\"\n" );
228         return;
229
230     case REG_DWORD:
231         if (value->len != sizeof(dw)) break;
232         memcpy( &dw, value->data, sizeof(dw) );
233         fprintf( f, "dword:%08x\n", dw );
234         return;
235     }
236
237     if (value->type == REG_BINARY) count += fprintf( f, "hex:" );
238     else count += fprintf( f, "hex(%x):", value->type );
239     for (i = 0; i < value->len; i++)
240     {
241         count += fprintf( f, "%02x", *((unsigned char *)value->data + i) );
242         if (i < value->len-1)
243         {
244             fputc( ',', f );
245             if (++count > 76)
246             {
247                 fprintf( f, "\\\n  " );
248                 count = 2;
249             }
250         }
251     }
252     fputc( '\n', f );
253 }
254
255 /* save a registry and all its subkeys to a text file */
256 static void save_subkeys( const struct key *key, const struct key *base, FILE *f )
257 {
258     int i;
259
260     if (key->flags & KEY_VOLATILE) return;
261     /* save key if it has either some values or no subkeys, or needs special options */
262     /* keys with no values but subkeys are saved implicitly by saving the subkeys */
263     if ((key->last_value >= 0) || (key->last_subkey == -1) || key->class || (key->flags & KEY_SYMLINK))
264     {
265         fprintf( f, "\n[" );
266         if (key != base) dump_path( key, base, f );
267         fprintf( f, "] %u\n", (unsigned int)((key->modif - ticks_1601_to_1970) / TICKS_PER_SEC) );
268         if (key->class)
269         {
270             fprintf( f, "#class=\"" );
271             dump_strW( key->class, key->classlen / sizeof(WCHAR), f, "\"\"" );
272             fprintf( f, "\"\n" );
273         }
274         if (key->flags & KEY_SYMLINK) fputs( "#link\n", f );
275         for (i = 0; i <= key->last_value; i++) dump_value( &key->values[i], f );
276     }
277     for (i = 0; i <= key->last_subkey; i++) save_subkeys( key->subkeys[i], base, f );
278 }
279
280 static void dump_operation( const struct key *key, const struct key_value *value, const char *op )
281 {
282     fprintf( stderr, "%s key ", op );
283     if (key) dump_path( key, NULL, stderr );
284     else fprintf( stderr, "ERROR" );
285     if (value)
286     {
287         fprintf( stderr, " value ");
288         dump_value( value, stderr );
289     }
290     else fprintf( stderr, "\n" );
291 }
292
293 static void key_dump( struct object *obj, int verbose )
294 {
295     struct key *key = (struct key *)obj;
296     assert( obj->ops == &key_ops );
297     fprintf( stderr, "Key flags=%x ", key->flags );
298     dump_path( key, NULL, stderr );
299     fprintf( stderr, "\n" );
300 }
301
302 /* notify waiter and maybe delete the notification */
303 static void do_notification( struct key *key, struct notify *notify, int del )
304 {
305     if (notify->event)
306     {
307         set_event( notify->event );
308         release_object( notify->event );
309         notify->event = NULL;
310     }
311     if (del)
312     {
313         list_remove( &notify->entry );
314         free( notify );
315     }
316 }
317
318 static inline struct notify *find_notify( struct key *key, struct process *process, obj_handle_t hkey )
319 {
320     struct notify *notify;
321
322     LIST_FOR_EACH_ENTRY( notify, &key->notify_list, struct notify, entry )
323     {
324         if (notify->process == process && notify->hkey == hkey) return notify;
325     }
326     return NULL;
327 }
328
329 static unsigned int key_map_access( struct object *obj, unsigned int access )
330 {
331     if (access & GENERIC_READ)    access |= KEY_READ;
332     if (access & GENERIC_WRITE)   access |= KEY_WRITE;
333     if (access & GENERIC_EXECUTE) access |= KEY_EXECUTE;
334     if (access & GENERIC_ALL)     access |= KEY_ALL_ACCESS;
335     /* filter the WOW64 masks, as they aren't real access bits */
336     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL |
337                       KEY_WOW64_64KEY | KEY_WOW64_32KEY);
338 }
339
340 static struct security_descriptor *key_get_sd( struct object *obj )
341 {
342     static struct security_descriptor *key_default_sd;
343
344     if (obj->sd) return obj->sd;
345
346     if (!key_default_sd)
347     {
348         size_t users_sid_len = security_sid_len( security_builtin_users_sid );
349         size_t admins_sid_len = security_sid_len( security_builtin_admins_sid );
350         size_t dacl_len = sizeof(ACL) + offsetof( ACCESS_ALLOWED_ACE, SidStart ) + users_sid_len;
351         ACCESS_ALLOWED_ACE *aaa;
352         ACL *dacl;
353
354         key_default_sd = mem_alloc( sizeof(*key_default_sd) + 2 * admins_sid_len + dacl_len );
355         key_default_sd->control   = SE_DACL_PRESENT;
356         key_default_sd->owner_len = admins_sid_len;
357         key_default_sd->group_len = admins_sid_len;
358         key_default_sd->sacl_len  = 0;
359         key_default_sd->dacl_len  = dacl_len;
360         memcpy( key_default_sd + 1, security_builtin_admins_sid, admins_sid_len );
361         memcpy( (char *)(key_default_sd + 1) + admins_sid_len, security_builtin_admins_sid, admins_sid_len );
362
363         dacl = (ACL *)((char *)(key_default_sd + 1) + 2 * admins_sid_len);
364         dacl->AclRevision = ACL_REVISION;
365         dacl->Sbz1 = 0;
366         dacl->AclSize = dacl_len;
367         dacl->AceCount = 1;
368         dacl->Sbz2 = 0;
369         aaa = (ACCESS_ALLOWED_ACE *)(dacl + 1);
370         aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
371         aaa->Header.AceFlags = INHERIT_ONLY_ACE | CONTAINER_INHERIT_ACE;
372         aaa->Header.AceSize = offsetof( ACCESS_ALLOWED_ACE, SidStart ) + users_sid_len;
373         aaa->Mask = GENERIC_READ;
374         memcpy( &aaa->SidStart, security_builtin_users_sid, users_sid_len );
375     }
376     return key_default_sd;
377 }
378
379 /* close the notification associated with a handle */
380 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
381 {
382     struct key * key = (struct key *) obj;
383     struct notify *notify = find_notify( key, process, handle );
384     if (notify) do_notification( key, notify, 1 );
385     return 1;  /* ok to close */
386 }
387
388 static void key_destroy( struct object *obj )
389 {
390     int i;
391     struct list *ptr;
392     struct key *key = (struct key *)obj;
393     assert( obj->ops == &key_ops );
394
395     free( key->name );
396     free( key->class );
397     for (i = 0; i <= key->last_value; i++)
398     {
399         free( key->values[i].name );
400         free( key->values[i].data );
401     }
402     free( key->values );
403     for (i = 0; i <= key->last_subkey; i++)
404     {
405         key->subkeys[i]->parent = NULL;
406         release_object( key->subkeys[i] );
407     }
408     free( key->subkeys );
409     /* unconditionally notify everything waiting on this key */
410     while ((ptr = list_head( &key->notify_list )))
411     {
412         struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
413         do_notification( key, notify, 1 );
414     }
415 }
416
417 /* get the request vararg as registry path */
418 static inline void get_req_path( struct unicode_str *str, int skip_root )
419 {
420     str->str = get_req_data();
421     str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
422
423     if (skip_root && str->len >= sizeof(root_name) &&
424         !memicmpW( str->str, root_name, sizeof(root_name)/sizeof(WCHAR) ))
425     {
426         str->str += sizeof(root_name)/sizeof(WCHAR);
427         str->len -= sizeof(root_name);
428     }
429 }
430
431 /* return the next token in a given path */
432 /* token->str must point inside the path, or be NULL for the first call */
433 static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
434 {
435     data_size_t i = 0, len = path->len / sizeof(WCHAR);
436
437     if (!token->str)  /* first time */
438     {
439         /* path cannot start with a backslash */
440         if (len && path->str[0] == '\\')
441         {
442             set_error( STATUS_OBJECT_PATH_INVALID );
443             return NULL;
444         }
445     }
446     else
447     {
448         i = token->str - path->str;
449         i += token->len / sizeof(WCHAR);
450         while (i < len && path->str[i] == '\\') i++;
451     }
452     token->str = path->str + i;
453     while (i < len && path->str[i] != '\\') i++;
454     token->len = (path->str + i - token->str) * sizeof(WCHAR);
455     return token;
456 }
457
458 /* allocate a key object */
459 static struct key *alloc_key( const struct unicode_str *name, timeout_t modif )
460 {
461     struct key *key;
462     if ((key = alloc_object( &key_ops )))
463     {
464         key->name        = NULL;
465         key->class       = NULL;
466         key->namelen     = name->len;
467         key->classlen    = 0;
468         key->flags       = 0;
469         key->last_subkey = -1;
470         key->nb_subkeys  = 0;
471         key->subkeys     = NULL;
472         key->nb_values   = 0;
473         key->last_value  = -1;
474         key->values      = NULL;
475         key->modif       = modif;
476         key->parent      = NULL;
477         list_init( &key->notify_list );
478         if (name->len && !(key->name = memdup( name->str, name->len )))
479         {
480             release_object( key );
481             key = NULL;
482         }
483     }
484     return key;
485 }
486
487 /* mark a key and all its parents as dirty (modified) */
488 static void make_dirty( struct key *key )
489 {
490     while (key)
491     {
492         if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return;  /* nothing to do */
493         key->flags |= KEY_DIRTY;
494         key = key->parent;
495     }
496 }
497
498 /* mark a key and all its subkeys as clean (not modified) */
499 static void make_clean( struct key *key )
500 {
501     int i;
502
503     if (key->flags & KEY_VOLATILE) return;
504     if (!(key->flags & KEY_DIRTY)) return;
505     key->flags &= ~KEY_DIRTY;
506     for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
507 }
508
509 /* go through all the notifications and send them if necessary */
510 static void check_notify( struct key *key, unsigned int change, int not_subtree )
511 {
512     struct list *ptr, *next;
513
514     LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
515     {
516         struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
517         if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
518             do_notification( key, n, 0 );
519     }
520 }
521
522 /* update key modification time */
523 static void touch_key( struct key *key, unsigned int change )
524 {
525     struct key *k;
526
527     key->modif = current_time;
528     make_dirty( key );
529
530     /* do notifications */
531     check_notify( key, change, 1 );
532     for ( k = key->parent; k; k = k->parent )
533         check_notify( k, change & ~REG_NOTIFY_CHANGE_LAST_SET, 0 );
534 }
535
536 /* try to grow the array of subkeys; return 1 if OK, 0 on error */
537 static int grow_subkeys( struct key *key )
538 {
539     struct key **new_subkeys;
540     int nb_subkeys;
541
542     if (key->nb_subkeys)
543     {
544         nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2);  /* grow by 50% */
545         if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
546         {
547             set_error( STATUS_NO_MEMORY );
548             return 0;
549         }
550     }
551     else
552     {
553         nb_subkeys = MIN_VALUES;
554         if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
555     }
556     key->subkeys    = new_subkeys;
557     key->nb_subkeys = nb_subkeys;
558     return 1;
559 }
560
561 /* allocate a subkey for a given key, and return its index */
562 static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
563                                  int index, timeout_t modif )
564 {
565     struct key *key;
566     int i;
567
568     if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
569     {
570         set_error( STATUS_NAME_TOO_LONG );
571         return NULL;
572     }
573     if (parent->last_subkey + 1 == parent->nb_subkeys)
574     {
575         /* need to grow the array */
576         if (!grow_subkeys( parent )) return NULL;
577     }
578     if ((key = alloc_key( name, modif )) != NULL)
579     {
580         key->parent = parent;
581         for (i = ++parent->last_subkey; i > index; i--)
582             parent->subkeys[i] = parent->subkeys[i-1];
583         parent->subkeys[index] = key;
584         if (is_wow6432node( key->name, key->namelen ) && !is_wow6432node( parent->name, parent->namelen ))
585             parent->flags |= KEY_WOW64;
586     }
587     return key;
588 }
589
590 /* free a subkey of a given key */
591 static void free_subkey( struct key *parent, int index )
592 {
593     struct key *key;
594     int i, nb_subkeys;
595
596     assert( index >= 0 );
597     assert( index <= parent->last_subkey );
598
599     key = parent->subkeys[index];
600     for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
601     parent->last_subkey--;
602     key->flags |= KEY_DELETED;
603     key->parent = NULL;
604     if (is_wow6432node( key->name, key->namelen )) parent->flags &= ~KEY_WOW64;
605     release_object( key );
606
607     /* try to shrink the array */
608     nb_subkeys = parent->nb_subkeys;
609     if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
610     {
611         struct key **new_subkeys;
612         nb_subkeys -= nb_subkeys / 3;  /* shrink by 33% */
613         if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
614         if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
615         parent->subkeys = new_subkeys;
616         parent->nb_subkeys = nb_subkeys;
617     }
618 }
619
620 /* find the named child of a given key and return its index */
621 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
622 {
623     int i, min, max, res;
624     data_size_t len;
625
626     min = 0;
627     max = key->last_subkey;
628     while (min <= max)
629     {
630         i = (min + max) / 2;
631         len = min( key->subkeys[i]->namelen, name->len );
632         res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
633         if (!res) res = key->subkeys[i]->namelen - name->len;
634         if (!res)
635         {
636             *index = i;
637             return key->subkeys[i];
638         }
639         if (res > 0) max = i - 1;
640         else min = i + 1;
641     }
642     *index = min;  /* this is where we should insert it */
643     return NULL;
644 }
645
646 /* return the wow64 variant of the key, or the key itself if none */
647 static struct key *find_wow64_subkey( struct key *key, const struct unicode_str *name )
648 {
649     static const struct unicode_str wow6432node_str = { wow6432node, sizeof(wow6432node) };
650     int index;
651
652     if (!(key->flags & KEY_WOW64)) return key;
653     if (!is_wow6432node( name->str, name->len ))
654     {
655         key = find_subkey( key, &wow6432node_str, &index );
656         assert( key );  /* if KEY_WOW64 is set we must find it */
657     }
658     return key;
659 }
660
661
662 /* follow a symlink and return the resolved key */
663 static struct key *follow_symlink( struct key *key, int iteration )
664 {
665     struct unicode_str path, token;
666     struct key_value *value;
667     int index;
668
669     if (iteration > 16) return NULL;
670     if (!(key->flags & KEY_SYMLINK)) return key;
671     if (!(value = find_value( key, &symlink_str, &index ))) return NULL;
672
673     path.str = value->data;
674     path.len = (value->len / sizeof(WCHAR)) * sizeof(WCHAR);
675     if (path.len <= sizeof(root_name)) return NULL;
676     if (memicmpW( path.str, root_name, sizeof(root_name)/sizeof(WCHAR) )) return NULL;
677     path.str += sizeof(root_name) / sizeof(WCHAR);
678     path.len -= sizeof(root_name);
679
680     key = root_key;
681     token.str = NULL;
682     if (!get_path_token( &path, &token )) return NULL;
683     while (token.len)
684     {
685         if (!(key = find_subkey( key, &token, &index ))) break;
686         if (!(key = follow_symlink( key, iteration + 1 ))) break;
687         get_path_token( &path, &token );
688     }
689     return key;
690 }
691
692 /* open a key until we find an element that doesn't exist */
693 /* helper for open_key and create_key */
694 static struct key *open_key_prefix( struct key *key, const struct unicode_str *name,
695                                     unsigned int access, struct unicode_str *token, int *index )
696 {
697     token->str = NULL;
698     if (!get_path_token( name, token )) return NULL;
699     if (access & KEY_WOW64_32KEY) key = find_wow64_subkey( key, token );
700     while (token->len)
701     {
702         struct key *subkey;
703         if (!(subkey = find_subkey( key, token, index )))
704         {
705             if ((key->flags & KEY_WOWSHARE) && !(access & KEY_WOW64_64KEY))
706             {
707                 /* try in the 64-bit parent */
708                 key = key->parent;
709                 subkey = find_subkey( key, token, index );
710             }
711         }
712         if (!subkey) break;
713         key = subkey;
714         get_path_token( name, token );
715         if (!token->len) break;
716         if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, token );
717         if (!(key = follow_symlink( key, 0 )))
718         {
719             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
720             return NULL;
721         }
722     }
723     return key;
724 }
725
726 /* open a subkey */
727 static struct key *open_key( struct key *key, const struct unicode_str *name, unsigned int access,
728                              unsigned int attributes )
729 {
730     int index;
731     struct unicode_str token;
732
733     if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
734
735     if (token.len)
736     {
737         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
738         return NULL;
739     }
740     if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
741     if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
742     {
743         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
744         return NULL;
745     }
746     if (debug_level > 1) dump_operation( key, NULL, "Open" );
747     grab_object( key );
748     return key;
749 }
750
751 /* create a subkey */
752 static struct key *create_key( struct key *key, const struct unicode_str *name,
753                                const struct unicode_str *class, unsigned int options,
754                                unsigned int access, unsigned int attributes, int *created )
755 {
756     int index;
757     struct unicode_str token, next;
758
759     *created = 0;
760     if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
761
762     if (!token.len)  /* the key already exists */
763     {
764         if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
765         if (options & REG_OPTION_CREATE_LINK)
766         {
767             set_error( STATUS_OBJECT_NAME_COLLISION );
768             return NULL;
769         }
770         if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
771         {
772             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
773             return NULL;
774         }
775         if (debug_level > 1) dump_operation( key, NULL, "Open" );
776         grab_object( key );
777         return key;
778     }
779
780     /* token must be the last path component at this point */
781     next = token;
782     get_path_token( name, &next );
783     if (next.len)
784     {
785         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
786         return NULL;
787     }
788
789     if ((key->flags & KEY_VOLATILE) && !(options & REG_OPTION_VOLATILE))
790     {
791         set_error( STATUS_CHILD_MUST_BE_VOLATILE );
792         return NULL;
793     }
794     *created = 1;
795     make_dirty( key );
796     if (!(key = alloc_subkey( key, &token, index, current_time ))) return NULL;
797
798     if (options & REG_OPTION_CREATE_LINK) key->flags |= KEY_SYMLINK;
799     if (options & REG_OPTION_VOLATILE) key->flags |= KEY_VOLATILE;
800     else key->flags |= KEY_DIRTY;
801
802     if (debug_level > 1) dump_operation( key, NULL, "Create" );
803     if (class && class->len)
804     {
805         key->classlen = class->len;
806         free(key->class);
807         if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
808     }
809     grab_object( key );
810     return key;
811 }
812
813 /* recursively create a subkey (for internal use only) */
814 static struct key *create_key_recursive( struct key *key, const struct unicode_str *name, timeout_t modif )
815 {
816     struct key *base;
817     int index;
818     struct unicode_str token;
819
820     token.str = NULL;
821     if (!get_path_token( name, &token )) return NULL;
822     while (token.len)
823     {
824         struct key *subkey;
825         if (!(subkey = find_subkey( key, &token, &index ))) break;
826         key = subkey;
827         if (!(key = follow_symlink( key, 0 )))
828         {
829             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
830             return NULL;
831         }
832         get_path_token( name, &token );
833     }
834
835     if (token.len)
836     {
837         if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
838         base = key;
839         for (;;)
840         {
841             get_path_token( name, &token );
842             if (!token.len) break;
843             /* we know the index is always 0 in a new key */
844             if (!(key = alloc_subkey( key, &token, 0, modif )))
845             {
846                 free_subkey( base, index );
847                 return NULL;
848             }
849         }
850     }
851
852     grab_object( key );
853     return key;
854 }
855
856 /* query information about a key or a subkey */
857 static void enum_key( const struct key *key, int index, int info_class,
858                       struct enum_key_reply *reply )
859 {
860     int i;
861     data_size_t len, namelen, classlen;
862     data_size_t max_subkey = 0, max_class = 0;
863     data_size_t max_value = 0, max_data = 0;
864     char *data;
865
866     if (index != -1)  /* -1 means use the specified key directly */
867     {
868         if ((index < 0) || (index > key->last_subkey))
869         {
870             set_error( STATUS_NO_MORE_ENTRIES );
871             return;
872         }
873         key = key->subkeys[index];
874     }
875
876     namelen = key->namelen;
877     classlen = key->classlen;
878
879     switch(info_class)
880     {
881     case KeyBasicInformation:
882         classlen = 0; /* only return the name */
883         /* fall through */
884     case KeyNodeInformation:
885         reply->max_subkey = 0;
886         reply->max_class  = 0;
887         reply->max_value  = 0;
888         reply->max_data   = 0;
889         break;
890     case KeyFullInformation:
891         for (i = 0; i <= key->last_subkey; i++)
892         {
893             struct key *subkey = key->subkeys[i];
894             len = subkey->namelen / sizeof(WCHAR);
895             if (len > max_subkey) max_subkey = len;
896             len = subkey->classlen / sizeof(WCHAR);
897             if (len > max_class) max_class = len;
898         }
899         for (i = 0; i <= key->last_value; i++)
900         {
901             len = key->values[i].namelen / sizeof(WCHAR);
902             if (len > max_value) max_value = len;
903             len = key->values[i].len;
904             if (len > max_data) max_data = len;
905         }
906         reply->max_subkey = max_subkey;
907         reply->max_class  = max_class;
908         reply->max_value  = max_value;
909         reply->max_data   = max_data;
910         namelen = 0;  /* only return the class */
911         break;
912     default:
913         set_error( STATUS_INVALID_PARAMETER );
914         return;
915     }
916     reply->subkeys = key->last_subkey + 1;
917     reply->values  = key->last_value + 1;
918     reply->modif   = key->modif;
919     reply->total   = namelen + classlen;
920
921     len = min( reply->total, get_reply_max_size() );
922     if (len && (data = set_reply_data_size( len )))
923     {
924         if (len > namelen)
925         {
926             reply->namelen = namelen;
927             memcpy( data, key->name, namelen );
928             memcpy( data + namelen, key->class, len - namelen );
929         }
930         else
931         {
932             reply->namelen = len;
933             memcpy( data, key->name, len );
934         }
935     }
936     if (debug_level > 1) dump_operation( key, NULL, "Enum" );
937 }
938
939 /* delete a key and its values */
940 static int delete_key( struct key *key, int recurse )
941 {
942     int index;
943     struct key *parent = key->parent;
944
945     /* must find parent and index */
946     if (key == root_key)
947     {
948         set_error( STATUS_ACCESS_DENIED );
949         return -1;
950     }
951     assert( parent );
952
953     while (recurse && (key->last_subkey>=0))
954         if (0 > delete_key(key->subkeys[key->last_subkey], 1))
955             return -1;
956
957     for (index = 0; index <= parent->last_subkey; index++)
958         if (parent->subkeys[index] == key) break;
959     assert( index <= parent->last_subkey );
960
961     /* we can only delete a key that has no subkeys */
962     if (key->last_subkey >= 0)
963     {
964         set_error( STATUS_ACCESS_DENIED );
965         return -1;
966     }
967
968     if (debug_level > 1) dump_operation( key, NULL, "Delete" );
969     free_subkey( parent, index );
970     touch_key( parent, REG_NOTIFY_CHANGE_NAME );
971     return 0;
972 }
973
974 /* try to grow the array of values; return 1 if OK, 0 on error */
975 static int grow_values( struct key *key )
976 {
977     struct key_value *new_val;
978     int nb_values;
979
980     if (key->nb_values)
981     {
982         nb_values = key->nb_values + (key->nb_values / 2);  /* grow by 50% */
983         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
984         {
985             set_error( STATUS_NO_MEMORY );
986             return 0;
987         }
988     }
989     else
990     {
991         nb_values = MIN_VALUES;
992         if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
993     }
994     key->values = new_val;
995     key->nb_values = nb_values;
996     return 1;
997 }
998
999 /* find the named value of a given key and return its index in the array */
1000 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
1001 {
1002     int i, min, max, res;
1003     data_size_t len;
1004
1005     min = 0;
1006     max = key->last_value;
1007     while (min <= max)
1008     {
1009         i = (min + max) / 2;
1010         len = min( key->values[i].namelen, name->len );
1011         res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
1012         if (!res) res = key->values[i].namelen - name->len;
1013         if (!res)
1014         {
1015             *index = i;
1016             return &key->values[i];
1017         }
1018         if (res > 0) max = i - 1;
1019         else min = i + 1;
1020     }
1021     *index = min;  /* this is where we should insert it */
1022     return NULL;
1023 }
1024
1025 /* insert a new value; the index must have been returned by find_value */
1026 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
1027 {
1028     struct key_value *value;
1029     WCHAR *new_name = NULL;
1030     int i;
1031
1032     if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
1033     {
1034         set_error( STATUS_NAME_TOO_LONG );
1035         return NULL;
1036     }
1037     if (key->last_value + 1 == key->nb_values)
1038     {
1039         if (!grow_values( key )) return NULL;
1040     }
1041     if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
1042     for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
1043     value = &key->values[index];
1044     value->name    = new_name;
1045     value->namelen = name->len;
1046     value->len     = 0;
1047     value->data    = NULL;
1048     return value;
1049 }
1050
1051 /* set a key value */
1052 static void set_value( struct key *key, const struct unicode_str *name,
1053                        int type, const void *data, data_size_t len )
1054 {
1055     struct key_value *value;
1056     void *ptr = NULL;
1057     int index;
1058
1059     if ((value = find_value( key, name, &index )))
1060     {
1061         /* check if the new value is identical to the existing one */
1062         if (value->type == type && value->len == len &&
1063             value->data && !memcmp( value->data, data, len ))
1064         {
1065             if (debug_level > 1) dump_operation( key, value, "Skip setting" );
1066             return;
1067         }
1068     }
1069
1070     if (key->flags & KEY_SYMLINK)
1071     {
1072         if (type != REG_LINK || name->len != symlink_str.len ||
1073             memicmpW( name->str, symlink_str.str, name->len / sizeof(WCHAR) ))
1074         {
1075             set_error( STATUS_ACCESS_DENIED );
1076             return;
1077         }
1078     }
1079
1080     if (len && !(ptr = memdup( data, len ))) return;
1081
1082     if (!value)
1083     {
1084         if (!(value = insert_value( key, name, index )))
1085         {
1086             free( ptr );
1087             return;
1088         }
1089     }
1090     else free( value->data ); /* already existing, free previous data */
1091
1092     value->type  = type;
1093     value->len   = len;
1094     value->data  = ptr;
1095     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1096     if (debug_level > 1) dump_operation( key, value, "Set" );
1097 }
1098
1099 /* get a key value */
1100 static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
1101 {
1102     struct key_value *value;
1103     int index;
1104
1105     if ((value = find_value( key, name, &index )))
1106     {
1107         *type = value->type;
1108         *len  = value->len;
1109         if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
1110         if (debug_level > 1) dump_operation( key, value, "Get" );
1111     }
1112     else
1113     {
1114         *type = -1;
1115         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1116     }
1117 }
1118
1119 /* enumerate a key value */
1120 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
1121 {
1122     struct key_value *value;
1123
1124     if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
1125     else
1126     {
1127         void *data;
1128         data_size_t namelen, maxlen;
1129
1130         value = &key->values[i];
1131         reply->type = value->type;
1132         namelen = value->namelen;
1133
1134         switch(info_class)
1135         {
1136         case KeyValueBasicInformation:
1137             reply->total = namelen;
1138             break;
1139         case KeyValueFullInformation:
1140             reply->total = namelen + value->len;
1141             break;
1142         case KeyValuePartialInformation:
1143             reply->total = value->len;
1144             namelen = 0;
1145             break;
1146         default:
1147             set_error( STATUS_INVALID_PARAMETER );
1148             return;
1149         }
1150
1151         maxlen = min( reply->total, get_reply_max_size() );
1152         if (maxlen && ((data = set_reply_data_size( maxlen ))))
1153         {
1154             if (maxlen > namelen)
1155             {
1156                 reply->namelen = namelen;
1157                 memcpy( data, value->name, namelen );
1158                 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
1159             }
1160             else
1161             {
1162                 reply->namelen = maxlen;
1163                 memcpy( data, value->name, maxlen );
1164             }
1165         }
1166         if (debug_level > 1) dump_operation( key, value, "Enum" );
1167     }
1168 }
1169
1170 /* delete a value */
1171 static void delete_value( struct key *key, const struct unicode_str *name )
1172 {
1173     struct key_value *value;
1174     int i, index, nb_values;
1175
1176     if (!(value = find_value( key, name, &index )))
1177     {
1178         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1179         return;
1180     }
1181     if (debug_level > 1) dump_operation( key, value, "Delete" );
1182     free( value->name );
1183     free( value->data );
1184     for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
1185     key->last_value--;
1186     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1187
1188     /* try to shrink the array */
1189     nb_values = key->nb_values;
1190     if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
1191     {
1192         struct key_value *new_val;
1193         nb_values -= nb_values / 3;  /* shrink by 33% */
1194         if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
1195         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
1196         key->values = new_val;
1197         key->nb_values = nb_values;
1198     }
1199 }
1200
1201 /* get the registry key corresponding to an hkey handle */
1202 static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1203 {
1204     struct key *key = (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1205
1206     if (key && key->flags & KEY_DELETED)
1207     {
1208         set_error( STATUS_KEY_DELETED );
1209         release_object( key );
1210         key = NULL;
1211     }
1212     return key;
1213 }
1214
1215 /* get the registry key corresponding to a parent key handle */
1216 static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
1217 {
1218     if (!hkey) return (struct key *)grab_object( root_key );
1219     return get_hkey_obj( hkey, 0 );
1220 }
1221
1222 /* read a line from the input file */
1223 static int read_next_line( struct file_load_info *info )
1224 {
1225     char *newbuf;
1226     int newlen, pos = 0;
1227
1228     info->line++;
1229     for (;;)
1230     {
1231         if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1232             return (pos != 0);  /* EOF */
1233         pos = strlen(info->buffer);
1234         if (info->buffer[pos-1] == '\n')
1235         {
1236             /* got a full line */
1237             info->buffer[--pos] = 0;
1238             if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1239             return 1;
1240         }
1241         if (pos < info->len - 1) return 1;  /* EOF but something was read */
1242
1243         /* need to enlarge the buffer */
1244         newlen = info->len + info->len / 2;
1245         if (!(newbuf = realloc( info->buffer, newlen )))
1246         {
1247             set_error( STATUS_NO_MEMORY );
1248             return -1;
1249         }
1250         info->buffer = newbuf;
1251         info->len = newlen;
1252     }
1253 }
1254
1255 /* make sure the temp buffer holds enough space */
1256 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1257 {
1258     WCHAR *tmp;
1259     if (info->tmplen >= size) return 1;
1260     if (!(tmp = realloc( info->tmp, size )))
1261     {
1262         set_error( STATUS_NO_MEMORY );
1263         return 0;
1264     }
1265     info->tmp = tmp;
1266     info->tmplen = size;
1267     return 1;
1268 }
1269
1270 /* report an error while loading an input file */
1271 static void file_read_error( const char *err, struct file_load_info *info )
1272 {
1273     if (info->filename)
1274         fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1275     else
1276         fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1277 }
1278
1279 /* convert a data type tag to a value type */
1280 static int get_data_type( const char *buffer, int *type, int *parse_type )
1281 {
1282     struct data_type { const char *tag; int len; int type; int parse_type; };
1283
1284     static const struct data_type data_types[] =
1285     {                   /* actual type */  /* type to assume for parsing */
1286         { "\"",        1,   REG_SZ,              REG_SZ },
1287         { "str:\"",    5,   REG_SZ,              REG_SZ },
1288         { "str(2):\"", 8,   REG_EXPAND_SZ,       REG_SZ },
1289         { "str(7):\"", 8,   REG_MULTI_SZ,        REG_SZ },
1290         { "hex:",      4,   REG_BINARY,          REG_BINARY },
1291         { "dword:",    6,   REG_DWORD,           REG_DWORD },
1292         { "hex(",      4,   -1,                  REG_BINARY },
1293         { NULL,        0,    0,                  0 }
1294     };
1295
1296     const struct data_type *ptr;
1297     char *end;
1298
1299     for (ptr = data_types; ptr->tag; ptr++)
1300     {
1301         if (strncmp( ptr->tag, buffer, ptr->len )) continue;
1302         *parse_type = ptr->parse_type;
1303         if ((*type = ptr->type) != -1) return ptr->len;
1304         /* "hex(xx):" is special */
1305         *type = (int)strtoul( buffer + 4, &end, 16 );
1306         if ((end <= buffer) || strncmp( end, "):", 2 )) return 0;
1307         return end + 2 - buffer;
1308     }
1309     return 0;
1310 }
1311
1312 /* load and create a key from the input file */
1313 static struct key *load_key( struct key *base, const char *buffer,
1314                              int prefix_len, struct file_load_info *info )
1315 {
1316     WCHAR *p;
1317     struct unicode_str name;
1318     int res;
1319     unsigned int mod;
1320     timeout_t modif = current_time;
1321     data_size_t len;
1322
1323     if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1324
1325     len = info->tmplen;
1326     if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1327     {
1328         file_read_error( "Malformed key", info );
1329         return NULL;
1330     }
1331     if (sscanf( buffer + res, " %u", &mod ) == 1)
1332         modif = (timeout_t)mod * TICKS_PER_SEC + ticks_1601_to_1970;
1333
1334     p = info->tmp;
1335     while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1336
1337     if (!*p)
1338     {
1339         if (prefix_len > 1)
1340         {
1341             file_read_error( "Malformed key", info );
1342             return NULL;
1343         }
1344         /* empty key name, return base key */
1345         return (struct key *)grab_object( base );
1346     }
1347     name.str = p;
1348     name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1349     return create_key_recursive( base, &name, modif );
1350 }
1351
1352 /* load a global option from the input file */
1353 static int load_global_option( const char *buffer, struct file_load_info *info )
1354 {
1355     const char *p;
1356
1357     if (!strncmp( buffer, "#arch=", 6 ))
1358     {
1359         enum prefix_type type;
1360         p = buffer + 6;
1361         if (!strcmp( p, "win32" )) type = PREFIX_32BIT;
1362         else if (!strcmp( p, "win64" )) type = PREFIX_64BIT;
1363         else
1364         {
1365             file_read_error( "Unknown architecture", info );
1366             set_error( STATUS_NOT_REGISTRY_FILE );
1367             return 0;
1368         }
1369         if (prefix_type == PREFIX_UNKNOWN) prefix_type = type;
1370         else if (type != prefix_type)
1371         {
1372             file_read_error( "Mismatched architecture", info );
1373             set_error( STATUS_NOT_REGISTRY_FILE );
1374             return 0;
1375         }
1376     }
1377     /* ignore unknown options */
1378     return 1;
1379 }
1380
1381 /* load a key option from the input file */
1382 static int load_key_option( struct key *key, const char *buffer, struct file_load_info *info )
1383 {
1384     const char *p;
1385     data_size_t len;
1386
1387     if (!strncmp( buffer, "#class=", 7 ))
1388     {
1389         p = buffer + 7;
1390         if (*p++ != '"') return 0;
1391         if (!get_file_tmp_space( info, strlen(p) * sizeof(WCHAR) )) return 0;
1392         len = info->tmplen;
1393         if (parse_strW( info->tmp, &len, p, '\"' ) == -1) return 0;
1394         free( key->class );
1395         if (!(key->class = memdup( info->tmp, len ))) len = 0;
1396         key->classlen = len;
1397     }
1398     if (!strncmp( buffer, "#link", 5 )) key->flags |= KEY_SYMLINK;
1399     /* ignore unknown options */
1400     return 1;
1401 }
1402
1403 /* parse a comma-separated list of hex digits */
1404 static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1405 {
1406     const char *p = buffer;
1407     data_size_t count = 0;
1408     char *end;
1409
1410     while (isxdigit(*p))
1411     {
1412         unsigned int val = strtoul( p, &end, 16 );
1413         if (end == p || val > 0xff) return -1;
1414         if (count++ >= *len) return -1;  /* dest buffer overflow */
1415         *dest++ = val;
1416         p = end;
1417         while (isspace(*p)) p++;
1418         if (*p == ',') p++;
1419         while (isspace(*p)) p++;
1420     }
1421     *len = count;
1422     return p - buffer;
1423 }
1424
1425 /* parse a value name and create the corresponding value */
1426 static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1427                                            struct file_load_info *info )
1428 {
1429     struct key_value *value;
1430     struct unicode_str name;
1431     int index;
1432
1433     if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1434     name.str = info->tmp;
1435     name.len = info->tmplen;
1436     if (buffer[0] == '@')
1437     {
1438         name.len = 0;
1439         *len = 1;
1440     }
1441     else
1442     {
1443         int r = parse_strW( info->tmp, &name.len, buffer + 1, '\"' );
1444         if (r == -1) goto error;
1445         *len = r + 1; /* for initial quote */
1446         name.len -= sizeof(WCHAR);  /* terminating null */
1447     }
1448     while (isspace(buffer[*len])) (*len)++;
1449     if (buffer[*len] != '=') goto error;
1450     (*len)++;
1451     while (isspace(buffer[*len])) (*len)++;
1452     if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1453     return value;
1454
1455  error:
1456     file_read_error( "Malformed value name", info );
1457     return NULL;
1458 }
1459
1460 /* load a value from the input file */
1461 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1462 {
1463     DWORD dw;
1464     void *ptr, *newptr;
1465     int res, type, parse_type;
1466     data_size_t maxlen, len;
1467     struct key_value *value;
1468
1469     if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1470     if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1471     buffer += len + res;
1472
1473     switch(parse_type)
1474     {
1475     case REG_SZ:
1476         if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return 0;
1477         len = info->tmplen;
1478         if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1479         ptr = info->tmp;
1480         break;
1481     case REG_DWORD:
1482         dw = strtoul( buffer, NULL, 16 );
1483         ptr = &dw;
1484         len = sizeof(dw);
1485         break;
1486     case REG_BINARY:  /* hex digits */
1487         len = 0;
1488         for (;;)
1489         {
1490             maxlen = 1 + strlen(buffer) / 2;  /* at least 2 chars for one hex byte */
1491             if (!get_file_tmp_space( info, len + maxlen )) return 0;
1492             if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1493             len += maxlen;
1494             buffer += res;
1495             while (isspace(*buffer)) buffer++;
1496             if (!*buffer) break;
1497             if (*buffer != '\\') goto error;
1498             if (read_next_line( info) != 1) goto error;
1499             buffer = info->buffer;
1500             while (isspace(*buffer)) buffer++;
1501         }
1502         ptr = info->tmp;
1503         break;
1504     default:
1505         assert(0);
1506         ptr = NULL;  /* keep compiler quiet */
1507         break;
1508     }
1509
1510     if (!len) newptr = NULL;
1511     else if (!(newptr = memdup( ptr, len ))) return 0;
1512
1513     free( value->data );
1514     value->data = newptr;
1515     value->len  = len;
1516     value->type = type;
1517     return 1;
1518
1519  error:
1520     file_read_error( "Malformed value", info );
1521     free( value->data );
1522     value->data = NULL;
1523     value->len  = 0;
1524     value->type = REG_NONE;
1525     return 0;
1526 }
1527
1528 /* return the length (in path elements) of name that is part of the key name */
1529 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1530 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1531 {
1532     WCHAR *p;
1533     int res;
1534     data_size_t len;
1535
1536     if (!get_file_tmp_space( info, strlen(name) * sizeof(WCHAR) )) return 0;
1537
1538     len = info->tmplen;
1539     if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1540     {
1541         file_read_error( "Malformed key", info );
1542         return 0;
1543     }
1544     for (p = info->tmp; *p; p++) if (*p == '\\') break;
1545     len = (p - info->tmp) * sizeof(WCHAR);
1546     for (res = 1; key != root_key; res++)
1547     {
1548         if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1549         key = key->parent;
1550     }
1551     if (key == root_key) res = 0;  /* no matching name */
1552     return res;
1553 }
1554
1555 /* load all the keys from the input file */
1556 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1557 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1558 {
1559     struct key *subkey = NULL;
1560     struct file_load_info info;
1561     char *p;
1562
1563     info.filename = filename;
1564     info.file   = f;
1565     info.len    = 4;
1566     info.tmplen = 4;
1567     info.line   = 0;
1568     if (!(info.buffer = mem_alloc( info.len ))) return;
1569     if (!(info.tmp = mem_alloc( info.tmplen )))
1570     {
1571         free( info.buffer );
1572         return;
1573     }
1574
1575     if ((read_next_line( &info ) != 1) ||
1576         strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1577     {
1578         set_error( STATUS_NOT_REGISTRY_FILE );
1579         goto done;
1580     }
1581
1582     while (read_next_line( &info ) == 1)
1583     {
1584         p = info.buffer;
1585         while (*p && isspace(*p)) p++;
1586         switch(*p)
1587         {
1588         case '[':   /* new key */
1589             if (subkey) release_object( subkey );
1590             if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1591             if (!(subkey = load_key( key, p + 1, prefix_len, &info )))
1592                 file_read_error( "Error creating key", &info );
1593             break;
1594         case '@':   /* default value */
1595         case '\"':  /* value */
1596             if (subkey) load_value( subkey, p, &info );
1597             else file_read_error( "Value without key", &info );
1598             break;
1599         case '#':   /* option */
1600             if (subkey) load_key_option( subkey, p, &info );
1601             else if (!load_global_option( p, &info )) goto done;
1602             break;
1603         case ';':   /* comment */
1604         case 0:     /* empty line */
1605             break;
1606         default:
1607             file_read_error( "Unrecognized input", &info );
1608             break;
1609         }
1610     }
1611
1612  done:
1613     if (subkey) release_object( subkey );
1614     free( info.buffer );
1615     free( info.tmp );
1616 }
1617
1618 /* load a part of the registry from a file */
1619 static void load_registry( struct key *key, obj_handle_t handle )
1620 {
1621     struct file *file;
1622     int fd;
1623
1624     if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1625     fd = dup( get_file_unix_fd( file ) );
1626     release_object( file );
1627     if (fd != -1)
1628     {
1629         FILE *f = fdopen( fd, "r" );
1630         if (f)
1631         {
1632             load_keys( key, NULL, f, -1 );
1633             fclose( f );
1634         }
1635         else file_set_error();
1636     }
1637 }
1638
1639 /* load one of the initial registry files */
1640 static int load_init_registry_from_file( const char *filename, struct key *key )
1641 {
1642     FILE *f;
1643
1644     if ((f = fopen( filename, "r" )))
1645     {
1646         load_keys( key, filename, f, 0 );
1647         fclose( f );
1648         if (get_error() == STATUS_NOT_REGISTRY_FILE)
1649         {
1650             fprintf( stderr, "%s is not a valid registry file\n", filename );
1651             return 1;
1652         }
1653     }
1654
1655     assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1656
1657     save_branch_info[save_branch_count].path = filename;
1658     save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1659     make_object_static( &key->obj );
1660     return (f != NULL);
1661 }
1662
1663 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1664 {
1665     static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1666     static const WCHAR formatW[] = {'-','%','u',0};
1667     WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1668     WCHAR *p = buffer;
1669     unsigned int i;
1670
1671     strcpyW( p, prefixW );
1672     p += strlenW( prefixW );
1673     p += sprintfW( p, formatW, sid->Revision );
1674     p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1675                                                    sid->IdentifierAuthority.Value[4] ),
1676                                          MAKEWORD( sid->IdentifierAuthority.Value[3],
1677                                                    sid->IdentifierAuthority.Value[2] )));
1678     for (i = 0; i < sid->SubAuthorityCount; i++)
1679         p += sprintfW( p, formatW, sid->SubAuthority[i] );
1680
1681     path->len = (p - buffer) * sizeof(WCHAR);
1682     path->str = p = memdup( buffer, path->len );
1683     return p;
1684 }
1685
1686 /* get the cpu architectures that can be supported in the current prefix */
1687 unsigned int get_prefix_cpu_mask(void)
1688 {
1689     /* Allowed server/client/prefix combinations:
1690      *
1691      *              prefix
1692      *            32     64
1693      *  server +------+------+ client
1694      *         |  ok  | fail | 32
1695      *      32 +------+------+---
1696      *         | fail | fail | 64
1697      *      ---+------+------+---
1698      *         |  ok  |  ok  | 32
1699      *      64 +------+------+---
1700      *         | fail |  ok  | 64
1701      *      ---+------+------+---
1702      */
1703     switch (prefix_type)
1704     {
1705     case PREFIX_64BIT:
1706         /* 64-bit prefix requires 64-bit server */
1707         return sizeof(void *) > sizeof(int) ? ~0 : 0;
1708     case PREFIX_32BIT:
1709     default:
1710         return ~CPU_64BIT_MASK;  /* only 32-bit cpus supported on 32-bit prefix */
1711     }
1712 }
1713
1714 /* registry initialisation */
1715 void init_registry(void)
1716 {
1717     static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1718     static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1719     static const WCHAR classes[] = {'S','o','f','t','w','a','r','e','\\',
1720                                     'C','l','a','s','s','e','s','\\',
1721                                     'W','o','w','6','4','3','2','N','o','d','e'};
1722     static const struct unicode_str root_name = { NULL, 0 };
1723     static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1724     static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1725     static const struct unicode_str classes_name = { classes, sizeof(classes) };
1726
1727     WCHAR *current_user_path;
1728     struct unicode_str current_user_str;
1729     struct key *key, *hklm, *hkcu;
1730
1731     /* switch to the config dir */
1732
1733     if (fchdir( config_dir_fd ) == -1) fatal_perror( "chdir to config dir" );
1734
1735     /* create the root key */
1736     root_key = alloc_key( &root_name, current_time );
1737     assert( root_key );
1738     make_object_static( &root_key->obj );
1739
1740     /* load system.reg into Registry\Machine */
1741
1742     if (!(hklm = create_key_recursive( root_key, &HKLM_name, current_time )))
1743         fatal_error( "could not create Machine registry key\n" );
1744
1745     if (!load_init_registry_from_file( "system.reg", hklm ))
1746         prefix_type = sizeof(void *) > sizeof(int) ? PREFIX_64BIT : PREFIX_32BIT;
1747     else if (prefix_type == PREFIX_UNKNOWN)
1748         prefix_type = PREFIX_32BIT;
1749
1750     /* load userdef.reg into Registry\User\.Default */
1751
1752     if (!(key = create_key_recursive( root_key, &HKU_name, current_time )))
1753         fatal_error( "could not create User\\.Default registry key\n" );
1754
1755     load_init_registry_from_file( "userdef.reg", key );
1756     release_object( key );
1757
1758     /* load user.reg into HKEY_CURRENT_USER */
1759
1760     /* FIXME: match default user in token.c. should get from process token instead */
1761     current_user_path = format_user_registry_path( security_local_user_sid, &current_user_str );
1762     if (!current_user_path ||
1763         !(hkcu = create_key_recursive( root_key, &current_user_str, current_time )))
1764         fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1765     free( current_user_path );
1766     load_init_registry_from_file( "user.reg", hkcu );
1767
1768     /* set the shared flag on Software\Classes\Wow6432Node */
1769     if (prefix_type == PREFIX_64BIT)
1770     {
1771         if ((key = create_key_recursive( hklm, &classes_name, current_time )))
1772         {
1773             key->flags |= KEY_WOWSHARE;
1774             release_object( key );
1775         }
1776         /* FIXME: handle HKCU too */
1777     }
1778
1779     release_object( hklm );
1780     release_object( hkcu );
1781
1782     /* start the periodic save timer */
1783     set_periodic_save_timer();
1784
1785     /* go back to the server dir */
1786     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1787 }
1788
1789 /* save a registry branch to a file */
1790 static void save_all_subkeys( struct key *key, FILE *f )
1791 {
1792     fprintf( f, "WINE REGISTRY Version 2\n" );
1793     fprintf( f, ";; All keys relative to " );
1794     dump_path( key, NULL, f );
1795     fprintf( f, "\n" );
1796     switch (prefix_type)
1797     {
1798     case PREFIX_32BIT:
1799         fprintf( f, "\n#arch=win32\n" );
1800         break;
1801     case PREFIX_64BIT:
1802         fprintf( f, "\n#arch=win64\n" );
1803         break;
1804     default:
1805         break;
1806     }
1807     save_subkeys( key, key, f );
1808 }
1809
1810 /* save a registry branch to a file handle */
1811 static void save_registry( struct key *key, obj_handle_t handle )
1812 {
1813     struct file *file;
1814     int fd;
1815
1816     if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1817     fd = dup( get_file_unix_fd( file ) );
1818     release_object( file );
1819     if (fd != -1)
1820     {
1821         FILE *f = fdopen( fd, "w" );
1822         if (f)
1823         {
1824             save_all_subkeys( key, f );
1825             if (fclose( f )) file_set_error();
1826         }
1827         else
1828         {
1829             file_set_error();
1830             close( fd );
1831         }
1832     }
1833 }
1834
1835 /* save a registry branch to a file */
1836 static int save_branch( struct key *key, const char *path )
1837 {
1838     struct stat st;
1839     char *p, *tmp = NULL;
1840     int fd, count = 0, ret = 0;
1841     FILE *f;
1842
1843     if (!(key->flags & KEY_DIRTY))
1844     {
1845         if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1846         return 1;
1847     }
1848
1849     /* test the file type */
1850
1851     if ((fd = open( path, O_WRONLY )) != -1)
1852     {
1853         /* if file is not a regular file or has multiple links or is accessed
1854          * via symbolic links, write directly into it; otherwise use a temp file */
1855         if (!lstat( path, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1))
1856         {
1857             ftruncate( fd, 0 );
1858             goto save;
1859         }
1860         close( fd );
1861     }
1862
1863     /* create a temp file in the same directory */
1864
1865     if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1866     strcpy( tmp, path );
1867     if ((p = strrchr( tmp, '/' ))) p++;
1868     else p = tmp;
1869     for (;;)
1870     {
1871         sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1872         if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1873         if (errno != EEXIST) goto done;
1874         close( fd );
1875     }
1876
1877     /* now save to it */
1878
1879  save:
1880     if (!(f = fdopen( fd, "w" )))
1881     {
1882         if (tmp) unlink( tmp );
1883         close( fd );
1884         goto done;
1885     }
1886
1887     if (debug_level > 1)
1888     {
1889         fprintf( stderr, "%s: ", path );
1890         dump_operation( key, NULL, "saving" );
1891     }
1892
1893     save_all_subkeys( key, f );
1894     ret = !fclose(f);
1895
1896     if (tmp)
1897     {
1898         /* if successfully written, rename to final name */
1899         if (ret) ret = !rename( tmp, path );
1900         if (!ret) unlink( tmp );
1901     }
1902
1903 done:
1904     free( tmp );
1905     if (ret) make_clean( key );
1906     return ret;
1907 }
1908
1909 /* periodic saving of the registry */
1910 static void periodic_save( void *arg )
1911 {
1912     int i;
1913
1914     if (fchdir( config_dir_fd ) == -1) return;
1915     save_timeout_user = NULL;
1916     for (i = 0; i < save_branch_count; i++)
1917         save_branch( save_branch_info[i].key, save_branch_info[i].path );
1918     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1919     set_periodic_save_timer();
1920 }
1921
1922 /* start the periodic save timer */
1923 static void set_periodic_save_timer(void)
1924 {
1925     if (save_timeout_user) remove_timeout_user( save_timeout_user );
1926     save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
1927 }
1928
1929 /* save the modified registry branches to disk */
1930 void flush_registry(void)
1931 {
1932     int i;
1933
1934     if (fchdir( config_dir_fd ) == -1) return;
1935     for (i = 0; i < save_branch_count; i++)
1936     {
1937         if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
1938         {
1939             fprintf( stderr, "wineserver: could not save registry branch to %s",
1940                      save_branch_info[i].path );
1941             perror( " " );
1942         }
1943     }
1944     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1945 }
1946
1947 /* determine if the thread is wow64 (32-bit client running on 64-bit prefix) */
1948 static int is_wow64_thread( struct thread *thread )
1949 {
1950     return (prefix_type == PREFIX_64BIT && !(CPU_FLAG(thread->process->cpu) & CPU_64BIT_MASK));
1951 }
1952
1953
1954 /* create a registry key */
1955 DECL_HANDLER(create_key)
1956 {
1957     struct key *key = NULL, *parent;
1958     struct unicode_str name, class;
1959     unsigned int access = req->access;
1960
1961     if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
1962
1963     reply->hkey = 0;
1964
1965     if (req->namelen > get_req_data_size())
1966     {
1967         set_error( STATUS_INVALID_PARAMETER );
1968         return;
1969     }
1970     class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
1971     class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
1972     get_req_path( &name, !req->parent );
1973     if (name.str > class.str)
1974     {
1975         set_error( STATUS_INVALID_PARAMETER );
1976         return;
1977     }
1978     name.len = (class.str - name.str) * sizeof(WCHAR);
1979
1980     /* NOTE: no access rights are required from the parent handle to create a key */
1981     if ((parent = get_parent_hkey_obj( req->parent )))
1982     {
1983         if ((key = create_key( parent, &name, &class, req->options, access,
1984                                req->attributes, &reply->created )))
1985         {
1986             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1987             release_object( key );
1988         }
1989         release_object( parent );
1990     }
1991 }
1992
1993 /* open a registry key */
1994 DECL_HANDLER(open_key)
1995 {
1996     struct key *key, *parent;
1997     struct unicode_str name;
1998     unsigned int access = req->access;
1999
2000     if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
2001
2002     reply->hkey = 0;
2003     /* NOTE: no access rights are required to open the parent key, only the child key */
2004     if ((parent = get_parent_hkey_obj( req->parent )))
2005     {
2006         get_req_path( &name, !req->parent );
2007         if ((key = open_key( parent, &name, access, req->attributes )))
2008         {
2009             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
2010             release_object( key );
2011         }
2012         release_object( parent );
2013     }
2014 }
2015
2016 /* delete a registry key */
2017 DECL_HANDLER(delete_key)
2018 {
2019     struct key *key;
2020
2021     if ((key = get_hkey_obj( req->hkey, DELETE )))
2022     {
2023         delete_key( key, 0);
2024         release_object( key );
2025     }
2026 }
2027
2028 /* flush a registry key */
2029 DECL_HANDLER(flush_key)
2030 {
2031     struct key *key = get_hkey_obj( req->hkey, 0 );
2032     if (key)
2033     {
2034         /* we don't need to do anything here with the current implementation */
2035         release_object( key );
2036     }
2037 }
2038
2039 /* enumerate registry subkeys */
2040 DECL_HANDLER(enum_key)
2041 {
2042     struct key *key;
2043
2044     if ((key = get_hkey_obj( req->hkey,
2045                              req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
2046     {
2047         enum_key( key, req->index, req->info_class, reply );
2048         release_object( key );
2049     }
2050 }
2051
2052 /* set a value of a registry key */
2053 DECL_HANDLER(set_key_value)
2054 {
2055     struct key *key;
2056     struct unicode_str name;
2057
2058     if (req->namelen > get_req_data_size())
2059     {
2060         set_error( STATUS_INVALID_PARAMETER );
2061         return;
2062     }
2063     name.str = get_req_data();
2064     name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2065
2066     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2067     {
2068         data_size_t datalen = get_req_data_size() - req->namelen;
2069         const char *data = (const char *)get_req_data() + req->namelen;
2070
2071         set_value( key, &name, req->type, data, datalen );
2072         release_object( key );
2073     }
2074 }
2075
2076 /* retrieve the value of a registry key */
2077 DECL_HANDLER(get_key_value)
2078 {
2079     struct key *key;
2080     struct unicode_str name;
2081
2082     reply->total = 0;
2083     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2084     {
2085         get_req_unicode_str( &name );
2086         get_value( key, &name, &reply->type, &reply->total );
2087         release_object( key );
2088     }
2089 }
2090
2091 /* enumerate the value of a registry key */
2092 DECL_HANDLER(enum_key_value)
2093 {
2094     struct key *key;
2095
2096     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2097     {
2098         enum_value( key, req->index, req->info_class, reply );
2099         release_object( key );
2100     }
2101 }
2102
2103 /* delete a value of a registry key */
2104 DECL_HANDLER(delete_key_value)
2105 {
2106     struct key *key;
2107     struct unicode_str name;
2108
2109     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2110     {
2111         get_req_unicode_str( &name );
2112         delete_value( key, &name );
2113         release_object( key );
2114     }
2115 }
2116
2117 /* load a registry branch from a file */
2118 DECL_HANDLER(load_registry)
2119 {
2120     struct key *key, *parent;
2121     struct token *token = thread_get_impersonation_token( current );
2122     struct unicode_str name;
2123
2124     const LUID_AND_ATTRIBUTES privs[] =
2125     {
2126         { SeBackupPrivilege,  0 },
2127         { SeRestorePrivilege, 0 },
2128     };
2129
2130     if (!token || !token_check_privileges( token, TRUE, privs,
2131                                            sizeof(privs)/sizeof(privs[0]), NULL ))
2132     {
2133         set_error( STATUS_PRIVILEGE_NOT_HELD );
2134         return;
2135     }
2136
2137     if ((parent = get_parent_hkey_obj( req->hkey )))
2138     {
2139         int dummy;
2140         get_req_path( &name, !req->hkey );
2141         if ((key = create_key( parent, &name, NULL, 0, KEY_WOW64_64KEY, 0, &dummy )))
2142         {
2143             load_registry( key, req->file );
2144             release_object( key );
2145         }
2146         release_object( parent );
2147     }
2148 }
2149
2150 DECL_HANDLER(unload_registry)
2151 {
2152     struct key *key;
2153     struct token *token = thread_get_impersonation_token( current );
2154
2155     const LUID_AND_ATTRIBUTES privs[] =
2156     {
2157         { SeBackupPrivilege,  0 },
2158         { SeRestorePrivilege, 0 },
2159     };
2160
2161     if (!token || !token_check_privileges( token, TRUE, privs,
2162                                            sizeof(privs)/sizeof(privs[0]), NULL ))
2163     {
2164         set_error( STATUS_PRIVILEGE_NOT_HELD );
2165         return;
2166     }
2167
2168     if ((key = get_hkey_obj( req->hkey, 0 )))
2169     {
2170         delete_key( key, 1 );     /* FIXME */
2171         release_object( key );
2172     }
2173 }
2174
2175 /* save a registry branch to a file */
2176 DECL_HANDLER(save_registry)
2177 {
2178     struct key *key;
2179
2180     if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
2181     {
2182         set_error( STATUS_PRIVILEGE_NOT_HELD );
2183         return;
2184     }
2185
2186     if ((key = get_hkey_obj( req->hkey, 0 )))
2187     {
2188         save_registry( key, req->file );
2189         release_object( key );
2190     }
2191 }
2192
2193 /* add a registry key change notification */
2194 DECL_HANDLER(set_registry_notification)
2195 {
2196     struct key *key;
2197     struct event *event;
2198     struct notify *notify;
2199
2200     key = get_hkey_obj( req->hkey, KEY_NOTIFY );
2201     if (key)
2202     {
2203         event = get_event_obj( current->process, req->event, SYNCHRONIZE );
2204         if (event)
2205         {
2206             notify = find_notify( key, current->process, req->hkey );
2207             if (notify)
2208             {
2209                 if (notify->event)
2210                     release_object( notify->event );
2211                 grab_object( event );
2212                 notify->event = event;
2213             }
2214             else
2215             {
2216                 notify = mem_alloc( sizeof(*notify) );
2217                 if (notify)
2218                 {
2219                     grab_object( event );
2220                     notify->event   = event;
2221                     notify->subtree = req->subtree;
2222                     notify->filter  = req->filter;
2223                     notify->hkey    = req->hkey;
2224                     notify->process = current->process;
2225                     list_add_head( &key->notify_list, &notify->entry );
2226                 }
2227             }
2228             release_object( event );
2229         }
2230         release_object( key );
2231     }
2232 }