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