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