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