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