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