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