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