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