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