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