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