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