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