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