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