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