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