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