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