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