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