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