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