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