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