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