server: Disallow all operations on deleted registry keys.
[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  255    /* max. length of a key name */
104 #define MAX_VALUE_LEN 16383  /* 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 ) && !is_wow6432node( parent->name, parent->namelen ))
541             parent->flags |= KEY_WOW64;
542     }
543     return key;
544 }
545
546 /* free a subkey of a given key */
547 static void free_subkey( struct key *parent, int index )
548 {
549     struct key *key;
550     int i, nb_subkeys;
551
552     assert( index >= 0 );
553     assert( index <= parent->last_subkey );
554
555     key = parent->subkeys[index];
556     for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
557     parent->last_subkey--;
558     key->flags |= KEY_DELETED;
559     key->parent = NULL;
560     if (is_wow6432node( key->name, key->namelen )) parent->flags &= ~KEY_WOW64;
561     release_object( key );
562
563     /* try to shrink the array */
564     nb_subkeys = parent->nb_subkeys;
565     if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
566     {
567         struct key **new_subkeys;
568         nb_subkeys -= nb_subkeys / 3;  /* shrink by 33% */
569         if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
570         if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
571         parent->subkeys = new_subkeys;
572         parent->nb_subkeys = nb_subkeys;
573     }
574 }
575
576 /* find the named child of a given key and return its index */
577 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
578 {
579     int i, min, max, res;
580     data_size_t len;
581
582     min = 0;
583     max = key->last_subkey;
584     while (min <= max)
585     {
586         i = (min + max) / 2;
587         len = min( key->subkeys[i]->namelen, name->len );
588         res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
589         if (!res) res = key->subkeys[i]->namelen - name->len;
590         if (!res)
591         {
592             *index = i;
593             return key->subkeys[i];
594         }
595         if (res > 0) max = i - 1;
596         else min = i + 1;
597     }
598     *index = min;  /* this is where we should insert it */
599     return NULL;
600 }
601
602 /* return the wow64 variant of the key, or the key itself if none */
603 static struct key *find_wow64_subkey( struct key *key, const struct unicode_str *name )
604 {
605     static const struct unicode_str wow6432node_str = { wow6432node, sizeof(wow6432node) };
606     int index;
607
608     if (!(key->flags & KEY_WOW64)) return key;
609     if (!is_wow6432node( name->str, name->len ))
610     {
611         key = find_subkey( key, &wow6432node_str, &index );
612         assert( key );  /* if KEY_WOW64 is set we must find it */
613     }
614     return key;
615 }
616
617
618 /* follow a symlink and return the resolved key */
619 static struct key *follow_symlink( struct key *key, int iteration )
620 {
621     struct unicode_str path, token;
622     struct key_value *value;
623     int index;
624
625     if (iteration > 16) return NULL;
626     if (!(key->flags & KEY_SYMLINK)) return key;
627     if (!(value = find_value( key, &symlink_str, &index ))) return NULL;
628
629     path.str = value->data;
630     path.len = (value->len / sizeof(WCHAR)) * sizeof(WCHAR);
631     if (path.len <= sizeof(root_name)) return NULL;
632     if (memicmpW( path.str, root_name, sizeof(root_name)/sizeof(WCHAR) )) return NULL;
633     path.str += sizeof(root_name) / sizeof(WCHAR);
634     path.len -= sizeof(root_name);
635
636     key = root_key;
637     token.str = NULL;
638     if (!get_path_token( &path, &token )) return NULL;
639     while (token.len)
640     {
641         if (!(key = find_subkey( key, &token, &index ))) break;
642         if (!(key = follow_symlink( key, iteration + 1 ))) break;
643         get_path_token( &path, &token );
644     }
645     return key;
646 }
647
648 /* open a key until we find an element that doesn't exist */
649 /* helper for open_key and create_key */
650 static struct key *open_key_prefix( struct key *key, const struct unicode_str *name,
651                                     unsigned int access, struct unicode_str *token, int *index )
652 {
653     token->str = NULL;
654     if (!get_path_token( name, token )) return NULL;
655     if (access & KEY_WOW64_32KEY) key = find_wow64_subkey( key, token );
656     while (token->len)
657     {
658         struct key *subkey;
659         if (!(subkey = find_subkey( key, token, index )))
660         {
661             if ((key->flags & KEY_WOWSHARE) && !(access & KEY_WOW64_64KEY))
662             {
663                 /* try in the 64-bit parent */
664                 key = key->parent;
665                 subkey = find_subkey( key, token, index );
666             }
667         }
668         if (!subkey) break;
669         key = subkey;
670         get_path_token( name, token );
671         if (!token->len) break;
672         if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, token );
673         if (!(key = follow_symlink( key, 0 )))
674         {
675             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
676             return NULL;
677         }
678     }
679     return key;
680 }
681
682 /* open a subkey */
683 static struct key *open_key( struct key *key, const struct unicode_str *name, unsigned int access,
684                              unsigned int attributes )
685 {
686     int index;
687     struct unicode_str token;
688
689     if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
690
691     if (token.len)
692     {
693         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
694         return NULL;
695     }
696     if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
697     if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
698     {
699         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
700         return NULL;
701     }
702     if (debug_level > 1) dump_operation( key, NULL, "Open" );
703     grab_object( key );
704     return key;
705 }
706
707 /* create a subkey */
708 static struct key *create_key( struct key *key, const struct unicode_str *name,
709                                const struct unicode_str *class, unsigned int options,
710                                unsigned int access, unsigned int attributes, int *created )
711 {
712     int index;
713     struct unicode_str token, next;
714
715     *created = 0;
716     if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
717
718     if (!token.len)  /* the key already exists */
719     {
720         if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
721         if (options & REG_OPTION_CREATE_LINK)
722         {
723             set_error( STATUS_OBJECT_NAME_COLLISION );
724             return NULL;
725         }
726         if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
727         {
728             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
729             return NULL;
730         }
731         if (debug_level > 1) dump_operation( key, NULL, "Open" );
732         grab_object( key );
733         return key;
734     }
735
736     /* token must be the last path component at this point */
737     next = token;
738     get_path_token( name, &next );
739     if (next.len)
740     {
741         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
742         return NULL;
743     }
744
745     if ((key->flags & KEY_VOLATILE) && !(options & REG_OPTION_VOLATILE))
746     {
747         set_error( STATUS_CHILD_MUST_BE_VOLATILE );
748         return NULL;
749     }
750     *created = 1;
751     make_dirty( key );
752     if (!(key = alloc_subkey( key, &token, index, current_time ))) return NULL;
753
754     if (options & REG_OPTION_CREATE_LINK) key->flags |= KEY_SYMLINK;
755     if (options & REG_OPTION_VOLATILE) key->flags |= KEY_VOLATILE;
756     else key->flags |= KEY_DIRTY;
757
758     if (debug_level > 1) dump_operation( key, NULL, "Create" );
759     if (class && class->len)
760     {
761         key->classlen = class->len;
762         free(key->class);
763         if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
764     }
765     grab_object( key );
766     return key;
767 }
768
769 /* recursively create a subkey (for internal use only) */
770 static struct key *create_key_recursive( struct key *key, const struct unicode_str *name, timeout_t modif )
771 {
772     struct key *base;
773     int index;
774     struct unicode_str token;
775
776     token.str = NULL;
777     if (!get_path_token( name, &token )) return NULL;
778     while (token.len)
779     {
780         struct key *subkey;
781         if (!(subkey = find_subkey( key, &token, &index ))) break;
782         key = subkey;
783         if (!(key = follow_symlink( key, 0 )))
784         {
785             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
786             return NULL;
787         }
788         get_path_token( name, &token );
789     }
790
791     if (token.len)
792     {
793         if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
794         base = key;
795         for (;;)
796         {
797             get_path_token( name, &token );
798             if (!token.len) break;
799             /* we know the index is always 0 in a new key */
800             if (!(key = alloc_subkey( key, &token, 0, modif )))
801             {
802                 free_subkey( base, index );
803                 return NULL;
804             }
805         }
806     }
807
808     grab_object( key );
809     return key;
810 }
811
812 /* query information about a key or a subkey */
813 static void enum_key( const struct key *key, int index, int info_class,
814                       struct enum_key_reply *reply )
815 {
816     int i;
817     data_size_t len, namelen, classlen;
818     data_size_t max_subkey = 0, max_class = 0;
819     data_size_t max_value = 0, max_data = 0;
820     char *data;
821
822     if (index != -1)  /* -1 means use the specified key directly */
823     {
824         if ((index < 0) || (index > key->last_subkey))
825         {
826             set_error( STATUS_NO_MORE_ENTRIES );
827             return;
828         }
829         key = key->subkeys[index];
830     }
831
832     namelen = key->namelen;
833     classlen = key->classlen;
834
835     switch(info_class)
836     {
837     case KeyBasicInformation:
838         classlen = 0; /* only return the name */
839         /* fall through */
840     case KeyNodeInformation:
841         reply->max_subkey = 0;
842         reply->max_class  = 0;
843         reply->max_value  = 0;
844         reply->max_data   = 0;
845         break;
846     case KeyFullInformation:
847         for (i = 0; i <= key->last_subkey; i++)
848         {
849             struct key *subkey = key->subkeys[i];
850             len = subkey->namelen / sizeof(WCHAR);
851             if (len > max_subkey) max_subkey = len;
852             len = subkey->classlen / sizeof(WCHAR);
853             if (len > max_class) max_class = len;
854         }
855         for (i = 0; i <= key->last_value; i++)
856         {
857             len = key->values[i].namelen / sizeof(WCHAR);
858             if (len > max_value) max_value = len;
859             len = key->values[i].len;
860             if (len > max_data) max_data = len;
861         }
862         reply->max_subkey = max_subkey;
863         reply->max_class  = max_class;
864         reply->max_value  = max_value;
865         reply->max_data   = max_data;
866         namelen = 0;  /* only return the class */
867         break;
868     default:
869         set_error( STATUS_INVALID_PARAMETER );
870         return;
871     }
872     reply->subkeys = key->last_subkey + 1;
873     reply->values  = key->last_value + 1;
874     reply->modif   = key->modif;
875     reply->total   = namelen + classlen;
876
877     len = min( reply->total, get_reply_max_size() );
878     if (len && (data = set_reply_data_size( len )))
879     {
880         if (len > namelen)
881         {
882             reply->namelen = namelen;
883             memcpy( data, key->name, namelen );
884             memcpy( data + namelen, key->class, len - namelen );
885         }
886         else
887         {
888             reply->namelen = len;
889             memcpy( data, key->name, len );
890         }
891     }
892     if (debug_level > 1) dump_operation( key, NULL, "Enum" );
893 }
894
895 /* delete a key and its values */
896 static int delete_key( struct key *key, int recurse )
897 {
898     int index;
899     struct key *parent = key->parent;
900
901     /* must find parent and index */
902     if (key == root_key)
903     {
904         set_error( STATUS_ACCESS_DENIED );
905         return -1;
906     }
907     assert( parent );
908
909     while (recurse && (key->last_subkey>=0))
910         if (0 > delete_key(key->subkeys[key->last_subkey], 1))
911             return -1;
912
913     for (index = 0; index <= parent->last_subkey; index++)
914         if (parent->subkeys[index] == key) break;
915     assert( index <= parent->last_subkey );
916
917     /* we can only delete a key that has no subkeys */
918     if (key->last_subkey >= 0)
919     {
920         set_error( STATUS_ACCESS_DENIED );
921         return -1;
922     }
923
924     if (debug_level > 1) dump_operation( key, NULL, "Delete" );
925     free_subkey( parent, index );
926     touch_key( parent, REG_NOTIFY_CHANGE_NAME );
927     return 0;
928 }
929
930 /* try to grow the array of values; return 1 if OK, 0 on error */
931 static int grow_values( struct key *key )
932 {
933     struct key_value *new_val;
934     int nb_values;
935
936     if (key->nb_values)
937     {
938         nb_values = key->nb_values + (key->nb_values / 2);  /* grow by 50% */
939         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
940         {
941             set_error( STATUS_NO_MEMORY );
942             return 0;
943         }
944     }
945     else
946     {
947         nb_values = MIN_VALUES;
948         if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
949     }
950     key->values = new_val;
951     key->nb_values = nb_values;
952     return 1;
953 }
954
955 /* find the named value of a given key and return its index in the array */
956 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
957 {
958     int i, min, max, res;
959     data_size_t len;
960
961     min = 0;
962     max = key->last_value;
963     while (min <= max)
964     {
965         i = (min + max) / 2;
966         len = min( key->values[i].namelen, name->len );
967         res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
968         if (!res) res = key->values[i].namelen - name->len;
969         if (!res)
970         {
971             *index = i;
972             return &key->values[i];
973         }
974         if (res > 0) max = i - 1;
975         else min = i + 1;
976     }
977     *index = min;  /* this is where we should insert it */
978     return NULL;
979 }
980
981 /* insert a new value; the index must have been returned by find_value */
982 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
983 {
984     struct key_value *value;
985     WCHAR *new_name = NULL;
986     int i;
987
988     if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
989     {
990         set_error( STATUS_NAME_TOO_LONG );
991         return NULL;
992     }
993     if (key->last_value + 1 == key->nb_values)
994     {
995         if (!grow_values( key )) return NULL;
996     }
997     if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
998     for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
999     value = &key->values[index];
1000     value->name    = new_name;
1001     value->namelen = name->len;
1002     value->len     = 0;
1003     value->data    = NULL;
1004     return value;
1005 }
1006
1007 /* set a key value */
1008 static void set_value( struct key *key, const struct unicode_str *name,
1009                        int type, const void *data, data_size_t len )
1010 {
1011     struct key_value *value;
1012     void *ptr = NULL;
1013     int index;
1014
1015     if ((value = find_value( key, name, &index )))
1016     {
1017         /* check if the new value is identical to the existing one */
1018         if (value->type == type && value->len == len &&
1019             value->data && !memcmp( value->data, data, len ))
1020         {
1021             if (debug_level > 1) dump_operation( key, value, "Skip setting" );
1022             return;
1023         }
1024     }
1025
1026     if (key->flags & KEY_SYMLINK)
1027     {
1028         if (type != REG_LINK || name->len != symlink_str.len ||
1029             memicmpW( name->str, symlink_str.str, name->len / sizeof(WCHAR) ))
1030         {
1031             set_error( STATUS_ACCESS_DENIED );
1032             return;
1033         }
1034     }
1035
1036     if (len && !(ptr = memdup( data, len ))) return;
1037
1038     if (!value)
1039     {
1040         if (!(value = insert_value( key, name, index )))
1041         {
1042             free( ptr );
1043             return;
1044         }
1045     }
1046     else free( value->data ); /* already existing, free previous data */
1047
1048     value->type  = type;
1049     value->len   = len;
1050     value->data  = ptr;
1051     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1052     if (debug_level > 1) dump_operation( key, value, "Set" );
1053 }
1054
1055 /* get a key value */
1056 static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
1057 {
1058     struct key_value *value;
1059     int index;
1060
1061     if ((value = find_value( key, name, &index )))
1062     {
1063         *type = value->type;
1064         *len  = value->len;
1065         if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
1066         if (debug_level > 1) dump_operation( key, value, "Get" );
1067     }
1068     else
1069     {
1070         *type = -1;
1071         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1072     }
1073 }
1074
1075 /* enumerate a key value */
1076 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
1077 {
1078     struct key_value *value;
1079
1080     if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
1081     else
1082     {
1083         void *data;
1084         data_size_t namelen, maxlen;
1085
1086         value = &key->values[i];
1087         reply->type = value->type;
1088         namelen = value->namelen;
1089
1090         switch(info_class)
1091         {
1092         case KeyValueBasicInformation:
1093             reply->total = namelen;
1094             break;
1095         case KeyValueFullInformation:
1096             reply->total = namelen + value->len;
1097             break;
1098         case KeyValuePartialInformation:
1099             reply->total = value->len;
1100             namelen = 0;
1101             break;
1102         default:
1103             set_error( STATUS_INVALID_PARAMETER );
1104             return;
1105         }
1106
1107         maxlen = min( reply->total, get_reply_max_size() );
1108         if (maxlen && ((data = set_reply_data_size( maxlen ))))
1109         {
1110             if (maxlen > namelen)
1111             {
1112                 reply->namelen = namelen;
1113                 memcpy( data, value->name, namelen );
1114                 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
1115             }
1116             else
1117             {
1118                 reply->namelen = maxlen;
1119                 memcpy( data, value->name, maxlen );
1120             }
1121         }
1122         if (debug_level > 1) dump_operation( key, value, "Enum" );
1123     }
1124 }
1125
1126 /* delete a value */
1127 static void delete_value( struct key *key, const struct unicode_str *name )
1128 {
1129     struct key_value *value;
1130     int i, index, nb_values;
1131
1132     if (!(value = find_value( key, name, &index )))
1133     {
1134         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1135         return;
1136     }
1137     if (debug_level > 1) dump_operation( key, value, "Delete" );
1138     free( value->name );
1139     free( value->data );
1140     for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
1141     key->last_value--;
1142     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1143
1144     /* try to shrink the array */
1145     nb_values = key->nb_values;
1146     if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
1147     {
1148         struct key_value *new_val;
1149         nb_values -= nb_values / 3;  /* shrink by 33% */
1150         if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
1151         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
1152         key->values = new_val;
1153         key->nb_values = nb_values;
1154     }
1155 }
1156
1157 /* get the registry key corresponding to an hkey handle */
1158 static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1159 {
1160     struct key *key = (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1161
1162     if (key && key->flags & KEY_DELETED)
1163     {
1164         set_error( STATUS_KEY_DELETED );
1165         release_object( key );
1166         key = NULL;
1167     }
1168     return key;
1169 }
1170
1171 /* get the registry key corresponding to a parent key handle */
1172 static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
1173 {
1174     if (!hkey) return (struct key *)grab_object( root_key );
1175     return get_hkey_obj( hkey, 0 );
1176 }
1177
1178 /* read a line from the input file */
1179 static int read_next_line( struct file_load_info *info )
1180 {
1181     char *newbuf;
1182     int newlen, pos = 0;
1183
1184     info->line++;
1185     for (;;)
1186     {
1187         if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1188             return (pos != 0);  /* EOF */
1189         pos = strlen(info->buffer);
1190         if (info->buffer[pos-1] == '\n')
1191         {
1192             /* got a full line */
1193             info->buffer[--pos] = 0;
1194             if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1195             return 1;
1196         }
1197         if (pos < info->len - 1) return 1;  /* EOF but something was read */
1198
1199         /* need to enlarge the buffer */
1200         newlen = info->len + info->len / 2;
1201         if (!(newbuf = realloc( info->buffer, newlen )))
1202         {
1203             set_error( STATUS_NO_MEMORY );
1204             return -1;
1205         }
1206         info->buffer = newbuf;
1207         info->len = newlen;
1208     }
1209 }
1210
1211 /* make sure the temp buffer holds enough space */
1212 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1213 {
1214     WCHAR *tmp;
1215     if (info->tmplen >= size) return 1;
1216     if (!(tmp = realloc( info->tmp, size )))
1217     {
1218         set_error( STATUS_NO_MEMORY );
1219         return 0;
1220     }
1221     info->tmp = tmp;
1222     info->tmplen = size;
1223     return 1;
1224 }
1225
1226 /* report an error while loading an input file */
1227 static void file_read_error( const char *err, struct file_load_info *info )
1228 {
1229     if (info->filename)
1230         fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1231     else
1232         fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1233 }
1234
1235 /* convert a data type tag to a value type */
1236 static int get_data_type( const char *buffer, int *type, int *parse_type )
1237 {
1238     struct data_type { const char *tag; int len; int type; int parse_type; };
1239
1240     static const struct data_type data_types[] =
1241     {                   /* actual type */  /* type to assume for parsing */
1242         { "\"",        1,   REG_SZ,              REG_SZ },
1243         { "str:\"",    5,   REG_SZ,              REG_SZ },
1244         { "str(2):\"", 8,   REG_EXPAND_SZ,       REG_SZ },
1245         { "str(7):\"", 8,   REG_MULTI_SZ,        REG_SZ },
1246         { "hex:",      4,   REG_BINARY,          REG_BINARY },
1247         { "dword:",    6,   REG_DWORD,           REG_DWORD },
1248         { "hex(",      4,   -1,                  REG_BINARY },
1249         { NULL,        0,    0,                  0 }
1250     };
1251
1252     const struct data_type *ptr;
1253     char *end;
1254
1255     for (ptr = data_types; ptr->tag; ptr++)
1256     {
1257         if (strncmp( ptr->tag, buffer, ptr->len )) continue;
1258         *parse_type = ptr->parse_type;
1259         if ((*type = ptr->type) != -1) return ptr->len;
1260         /* "hex(xx):" is special */
1261         *type = (int)strtoul( buffer + 4, &end, 16 );
1262         if ((end <= buffer) || strncmp( end, "):", 2 )) return 0;
1263         return end + 2 - buffer;
1264     }
1265     return 0;
1266 }
1267
1268 /* load and create a key from the input file */
1269 static struct key *load_key( struct key *base, const char *buffer,
1270                              int prefix_len, struct file_load_info *info )
1271 {
1272     WCHAR *p;
1273     struct unicode_str name;
1274     int res;
1275     unsigned int mod;
1276     timeout_t modif = current_time;
1277     data_size_t len;
1278
1279     if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1280
1281     len = info->tmplen;
1282     if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1283     {
1284         file_read_error( "Malformed key", info );
1285         return NULL;
1286     }
1287     if (sscanf( buffer + res, " %u", &mod ) == 1)
1288         modif = (timeout_t)mod * TICKS_PER_SEC + ticks_1601_to_1970;
1289
1290     p = info->tmp;
1291     while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1292
1293     if (!*p)
1294     {
1295         if (prefix_len > 1)
1296         {
1297             file_read_error( "Malformed key", info );
1298             return NULL;
1299         }
1300         /* empty key name, return base key */
1301         return (struct key *)grab_object( base );
1302     }
1303     name.str = p;
1304     name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1305     return create_key_recursive( base, &name, modif );
1306 }
1307
1308 /* load a key option from the input file */
1309 static int load_key_option( struct key *key, const char *buffer, struct file_load_info *info )
1310 {
1311     const char *p;
1312     data_size_t len;
1313
1314     if (!strncmp( buffer, "#class=", 7 ))
1315     {
1316         p = buffer + 7;
1317         if (*p++ != '"') return 0;
1318         if (!get_file_tmp_space( info, strlen(p) * sizeof(WCHAR) )) return 0;
1319         len = info->tmplen;
1320         if (parse_strW( info->tmp, &len, p, '\"' ) == -1) return 0;
1321         free( key->class );
1322         if (!(key->class = memdup( info->tmp, len ))) len = 0;
1323         key->classlen = len;
1324     }
1325     if (!strncmp( buffer, "#link", 5 )) key->flags |= KEY_SYMLINK;
1326     /* ignore unknown options */
1327     return 1;
1328 }
1329
1330 /* parse a comma-separated list of hex digits */
1331 static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1332 {
1333     const char *p = buffer;
1334     data_size_t count = 0;
1335     char *end;
1336
1337     while (isxdigit(*p))
1338     {
1339         unsigned int val = strtoul( p, &end, 16 );
1340         if (end == p || val > 0xff) return -1;
1341         if (count++ >= *len) return -1;  /* dest buffer overflow */
1342         *dest++ = val;
1343         p = end;
1344         while (isspace(*p)) p++;
1345         if (*p == ',') p++;
1346         while (isspace(*p)) p++;
1347     }
1348     *len = count;
1349     return p - buffer;
1350 }
1351
1352 /* parse a value name and create the corresponding value */
1353 static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1354                                            struct file_load_info *info )
1355 {
1356     struct key_value *value;
1357     struct unicode_str name;
1358     int index;
1359
1360     if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1361     name.str = info->tmp;
1362     name.len = info->tmplen;
1363     if (buffer[0] == '@')
1364     {
1365         name.len = 0;
1366         *len = 1;
1367     }
1368     else
1369     {
1370         int r = parse_strW( info->tmp, &name.len, buffer + 1, '\"' );
1371         if (r == -1) goto error;
1372         *len = r + 1; /* for initial quote */
1373         name.len -= sizeof(WCHAR);  /* terminating null */
1374     }
1375     while (isspace(buffer[*len])) (*len)++;
1376     if (buffer[*len] != '=') goto error;
1377     (*len)++;
1378     while (isspace(buffer[*len])) (*len)++;
1379     if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1380     return value;
1381
1382  error:
1383     file_read_error( "Malformed value name", info );
1384     return NULL;
1385 }
1386
1387 /* load a value from the input file */
1388 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1389 {
1390     DWORD dw;
1391     void *ptr, *newptr;
1392     int res, type, parse_type;
1393     data_size_t maxlen, len;
1394     struct key_value *value;
1395
1396     if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1397     if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1398     buffer += len + res;
1399
1400     switch(parse_type)
1401     {
1402     case REG_SZ:
1403         if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return 0;
1404         len = info->tmplen;
1405         if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1406         ptr = info->tmp;
1407         break;
1408     case REG_DWORD:
1409         dw = strtoul( buffer, NULL, 16 );
1410         ptr = &dw;
1411         len = sizeof(dw);
1412         break;
1413     case REG_BINARY:  /* hex digits */
1414         len = 0;
1415         for (;;)
1416         {
1417             maxlen = 1 + strlen(buffer) / 2;  /* at least 2 chars for one hex byte */
1418             if (!get_file_tmp_space( info, len + maxlen )) return 0;
1419             if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1420             len += maxlen;
1421             buffer += res;
1422             while (isspace(*buffer)) buffer++;
1423             if (!*buffer) break;
1424             if (*buffer != '\\') goto error;
1425             if (read_next_line( info) != 1) goto error;
1426             buffer = info->buffer;
1427             while (isspace(*buffer)) buffer++;
1428         }
1429         ptr = info->tmp;
1430         break;
1431     default:
1432         assert(0);
1433         ptr = NULL;  /* keep compiler quiet */
1434         break;
1435     }
1436
1437     if (!len) newptr = NULL;
1438     else if (!(newptr = memdup( ptr, len ))) return 0;
1439
1440     free( value->data );
1441     value->data = newptr;
1442     value->len  = len;
1443     value->type = type;
1444     return 1;
1445
1446  error:
1447     file_read_error( "Malformed value", info );
1448     free( value->data );
1449     value->data = NULL;
1450     value->len  = 0;
1451     value->type = REG_NONE;
1452     return 0;
1453 }
1454
1455 /* return the length (in path elements) of name that is part of the key name */
1456 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1457 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1458 {
1459     WCHAR *p;
1460     int res;
1461     data_size_t len;
1462
1463     if (!get_file_tmp_space( info, strlen(name) * sizeof(WCHAR) )) return 0;
1464
1465     len = info->tmplen;
1466     if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1467     {
1468         file_read_error( "Malformed key", info );
1469         return 0;
1470     }
1471     for (p = info->tmp; *p; p++) if (*p == '\\') break;
1472     len = (p - info->tmp) * sizeof(WCHAR);
1473     for (res = 1; key != root_key; res++)
1474     {
1475         if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1476         key = key->parent;
1477     }
1478     if (key == root_key) res = 0;  /* no matching name */
1479     return res;
1480 }
1481
1482 /* load all the keys from the input file */
1483 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1484 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1485 {
1486     struct key *subkey = NULL;
1487     struct file_load_info info;
1488     char *p;
1489
1490     info.filename = filename;
1491     info.file   = f;
1492     info.len    = 4;
1493     info.tmplen = 4;
1494     info.line   = 0;
1495     if (!(info.buffer = mem_alloc( info.len ))) return;
1496     if (!(info.tmp = mem_alloc( info.tmplen )))
1497     {
1498         free( info.buffer );
1499         return;
1500     }
1501
1502     if ((read_next_line( &info ) != 1) ||
1503         strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1504     {
1505         set_error( STATUS_NOT_REGISTRY_FILE );
1506         goto done;
1507     }
1508
1509     while (read_next_line( &info ) == 1)
1510     {
1511         p = info.buffer;
1512         while (*p && isspace(*p)) p++;
1513         switch(*p)
1514         {
1515         case '[':   /* new key */
1516             if (subkey) release_object( subkey );
1517             if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1518             if (!(subkey = load_key( key, p + 1, prefix_len, &info )))
1519                 file_read_error( "Error creating key", &info );
1520             break;
1521         case '@':   /* default value */
1522         case '\"':  /* value */
1523             if (subkey) load_value( subkey, p, &info );
1524             else file_read_error( "Value without key", &info );
1525             break;
1526         case '#':   /* option */
1527             if (subkey) load_key_option( subkey, p, &info );
1528             break;
1529         case ';':   /* comment */
1530         case 0:     /* empty line */
1531             break;
1532         default:
1533             file_read_error( "Unrecognized input", &info );
1534             break;
1535         }
1536     }
1537
1538  done:
1539     if (subkey) release_object( subkey );
1540     free( info.buffer );
1541     free( info.tmp );
1542 }
1543
1544 /* load a part of the registry from a file */
1545 static void load_registry( struct key *key, obj_handle_t handle )
1546 {
1547     struct file *file;
1548     int fd;
1549
1550     if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1551     fd = dup( get_file_unix_fd( file ) );
1552     release_object( file );
1553     if (fd != -1)
1554     {
1555         FILE *f = fdopen( fd, "r" );
1556         if (f)
1557         {
1558             load_keys( key, NULL, f, -1 );
1559             fclose( f );
1560         }
1561         else file_set_error();
1562     }
1563 }
1564
1565 /* load one of the initial registry files */
1566 static void load_init_registry_from_file( const char *filename, struct key *key )
1567 {
1568     FILE *f;
1569
1570     if ((f = fopen( filename, "r" )))
1571     {
1572         load_keys( key, filename, f, 0 );
1573         fclose( f );
1574         if (get_error() == STATUS_NOT_REGISTRY_FILE)
1575         {
1576             fprintf( stderr, "%s is not a valid registry file\n", filename );
1577             return;
1578         }
1579     }
1580
1581     assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1582
1583     save_branch_info[save_branch_count].path = filename;
1584     save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1585     make_object_static( &key->obj );
1586 }
1587
1588 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1589 {
1590     static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1591     static const WCHAR formatW[] = {'-','%','u',0};
1592     WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1593     WCHAR *p = buffer;
1594     unsigned int i;
1595
1596     strcpyW( p, prefixW );
1597     p += strlenW( prefixW );
1598     p += sprintfW( p, formatW, sid->Revision );
1599     p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1600                                                    sid->IdentifierAuthority.Value[4] ),
1601                                          MAKEWORD( sid->IdentifierAuthority.Value[3],
1602                                                    sid->IdentifierAuthority.Value[2] )));
1603     for (i = 0; i < sid->SubAuthorityCount; i++)
1604         p += sprintfW( p, formatW, sid->SubAuthority[i] );
1605
1606     path->len = (p - buffer) * sizeof(WCHAR);
1607     path->str = p = memdup( buffer, path->len );
1608     return p;
1609 }
1610
1611 /* registry initialisation */
1612 void init_registry(void)
1613 {
1614     static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1615     static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1616     static const WCHAR classes[] = {'S','o','f','t','w','a','r','e','\\',
1617                                     'C','l','a','s','s','e','s','\\',
1618                                     'W','o','w','6','4','3','2','N','o','d','e'};
1619     static const struct unicode_str root_name = { NULL, 0 };
1620     static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1621     static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1622     static const struct unicode_str classes_name = { classes, sizeof(classes) };
1623
1624     WCHAR *current_user_path;
1625     struct unicode_str current_user_str;
1626     struct key *key, *hklm, *hkcu;
1627
1628     /* switch to the config dir */
1629
1630     if (fchdir( config_dir_fd ) == -1) fatal_perror( "chdir to config dir" );
1631
1632     /* create the root key */
1633     root_key = alloc_key( &root_name, current_time );
1634     assert( root_key );
1635     make_object_static( &root_key->obj );
1636
1637     /* load system.reg into Registry\Machine */
1638
1639     if (!(hklm = create_key_recursive( root_key, &HKLM_name, current_time )))
1640         fatal_error( "could not create Machine registry key\n" );
1641
1642     load_init_registry_from_file( "system.reg", hklm );
1643
1644     /* load userdef.reg into Registry\User\.Default */
1645
1646     if (!(key = create_key_recursive( root_key, &HKU_name, current_time )))
1647         fatal_error( "could not create User\\.Default registry key\n" );
1648
1649     load_init_registry_from_file( "userdef.reg", key );
1650     release_object( key );
1651
1652     /* load user.reg into HKEY_CURRENT_USER */
1653
1654     /* FIXME: match default user in token.c. should get from process token instead */
1655     current_user_path = format_user_registry_path( security_interactive_sid, &current_user_str );
1656     if (!current_user_path ||
1657         !(hkcu = create_key_recursive( root_key, &current_user_str, current_time )))
1658         fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1659     free( current_user_path );
1660     load_init_registry_from_file( "user.reg", hkcu );
1661
1662     /* set the shared flag on Software\Classes\Wow6432Node */
1663     if (sizeof(void *) > sizeof(int))
1664     {
1665         if ((key = create_key_recursive( hklm, &classes_name, current_time )))
1666         {
1667             key->flags |= KEY_WOWSHARE;
1668             release_object( key );
1669         }
1670         /* FIXME: handle HKCU too */
1671     }
1672
1673     release_object( hklm );
1674     release_object( hkcu );
1675
1676     /* start the periodic save timer */
1677     set_periodic_save_timer();
1678
1679     /* go back to the server dir */
1680     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1681 }
1682
1683 /* save a registry branch to a file */
1684 static void save_all_subkeys( struct key *key, FILE *f )
1685 {
1686     fprintf( f, "WINE REGISTRY Version 2\n" );
1687     fprintf( f, ";; All keys relative to " );
1688     dump_path( key, NULL, f );
1689     fprintf( f, "\n" );
1690     save_subkeys( key, key, f );
1691 }
1692
1693 /* save a registry branch to a file handle */
1694 static void save_registry( struct key *key, obj_handle_t handle )
1695 {
1696     struct file *file;
1697     int fd;
1698
1699     if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1700     fd = dup( get_file_unix_fd( file ) );
1701     release_object( file );
1702     if (fd != -1)
1703     {
1704         FILE *f = fdopen( fd, "w" );
1705         if (f)
1706         {
1707             save_all_subkeys( key, f );
1708             if (fclose( f )) file_set_error();
1709         }
1710         else
1711         {
1712             file_set_error();
1713             close( fd );
1714         }
1715     }
1716 }
1717
1718 /* save a registry branch to a file */
1719 static int save_branch( struct key *key, const char *path )
1720 {
1721     struct stat st;
1722     char *p, *tmp = NULL;
1723     int fd, count = 0, ret = 0;
1724     FILE *f;
1725
1726     if (!(key->flags & KEY_DIRTY))
1727     {
1728         if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1729         return 1;
1730     }
1731
1732     /* test the file type */
1733
1734     if ((fd = open( path, O_WRONLY )) != -1)
1735     {
1736         /* if file is not a regular file or has multiple links or is accessed
1737          * via symbolic links, write directly into it; otherwise use a temp file */
1738         if (!lstat( path, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1))
1739         {
1740             ftruncate( fd, 0 );
1741             goto save;
1742         }
1743         close( fd );
1744     }
1745
1746     /* create a temp file in the same directory */
1747
1748     if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1749     strcpy( tmp, path );
1750     if ((p = strrchr( tmp, '/' ))) p++;
1751     else p = tmp;
1752     for (;;)
1753     {
1754         sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1755         if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1756         if (errno != EEXIST) goto done;
1757         close( fd );
1758     }
1759
1760     /* now save to it */
1761
1762  save:
1763     if (!(f = fdopen( fd, "w" )))
1764     {
1765         if (tmp) unlink( tmp );
1766         close( fd );
1767         goto done;
1768     }
1769
1770     if (debug_level > 1)
1771     {
1772         fprintf( stderr, "%s: ", path );
1773         dump_operation( key, NULL, "saving" );
1774     }
1775
1776     save_all_subkeys( key, f );
1777     ret = !fclose(f);
1778
1779     if (tmp)
1780     {
1781         /* if successfully written, rename to final name */
1782         if (ret) ret = !rename( tmp, path );
1783         if (!ret) unlink( tmp );
1784     }
1785
1786 done:
1787     free( tmp );
1788     if (ret) make_clean( key );
1789     return ret;
1790 }
1791
1792 /* periodic saving of the registry */
1793 static void periodic_save( void *arg )
1794 {
1795     int i;
1796
1797     if (fchdir( config_dir_fd ) == -1) return;
1798     save_timeout_user = NULL;
1799     for (i = 0; i < save_branch_count; i++)
1800         save_branch( save_branch_info[i].key, save_branch_info[i].path );
1801     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1802     set_periodic_save_timer();
1803 }
1804
1805 /* start the periodic save timer */
1806 static void set_periodic_save_timer(void)
1807 {
1808     if (save_timeout_user) remove_timeout_user( save_timeout_user );
1809     save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
1810 }
1811
1812 /* save the modified registry branches to disk */
1813 void flush_registry(void)
1814 {
1815     int i;
1816
1817     if (fchdir( config_dir_fd ) == -1) return;
1818     for (i = 0; i < save_branch_count; i++)
1819     {
1820         if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
1821         {
1822             fprintf( stderr, "wineserver: could not save registry branch to %s",
1823                      save_branch_info[i].path );
1824             perror( " " );
1825         }
1826     }
1827     if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1828 }
1829
1830
1831 /* create a registry key */
1832 DECL_HANDLER(create_key)
1833 {
1834     struct key *key = NULL, *parent;
1835     struct unicode_str name, class;
1836     unsigned int access = req->access;
1837
1838     if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
1839
1840     reply->hkey = 0;
1841
1842     if (req->namelen > get_req_data_size())
1843     {
1844         set_error( STATUS_INVALID_PARAMETER );
1845         return;
1846     }
1847     class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
1848     class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
1849     get_req_path( &name, !req->parent );
1850     if (name.str > class.str)
1851     {
1852         set_error( STATUS_INVALID_PARAMETER );
1853         return;
1854     }
1855     name.len = (class.str - name.str) * sizeof(WCHAR);
1856
1857     /* NOTE: no access rights are required from the parent handle to create a key */
1858     if ((parent = get_parent_hkey_obj( req->parent )))
1859     {
1860         if ((key = create_key( parent, &name, &class, req->options, access,
1861                                req->attributes, &reply->created )))
1862         {
1863             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1864             release_object( key );
1865         }
1866         release_object( parent );
1867     }
1868 }
1869
1870 /* open a registry key */
1871 DECL_HANDLER(open_key)
1872 {
1873     struct key *key, *parent;
1874     struct unicode_str name;
1875     unsigned int access = req->access;
1876
1877     if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
1878
1879     reply->hkey = 0;
1880     /* NOTE: no access rights are required to open the parent key, only the child key */
1881     if ((parent = get_parent_hkey_obj( req->parent )))
1882     {
1883         get_req_path( &name, !req->parent );
1884         if ((key = open_key( parent, &name, access, req->attributes )))
1885         {
1886             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1887             release_object( key );
1888         }
1889         release_object( parent );
1890     }
1891 }
1892
1893 /* delete a registry key */
1894 DECL_HANDLER(delete_key)
1895 {
1896     struct key *key;
1897
1898     if ((key = get_hkey_obj( req->hkey, DELETE )))
1899     {
1900         delete_key( key, 0);
1901         release_object( key );
1902     }
1903 }
1904
1905 /* flush a registry key */
1906 DECL_HANDLER(flush_key)
1907 {
1908     struct key *key = get_hkey_obj( req->hkey, 0 );
1909     if (key)
1910     {
1911         /* we don't need to do anything here with the current implementation */
1912         release_object( key );
1913     }
1914 }
1915
1916 /* enumerate registry subkeys */
1917 DECL_HANDLER(enum_key)
1918 {
1919     struct key *key;
1920
1921     if ((key = get_hkey_obj( req->hkey,
1922                              req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
1923     {
1924         enum_key( key, req->index, req->info_class, reply );
1925         release_object( key );
1926     }
1927 }
1928
1929 /* set a value of a registry key */
1930 DECL_HANDLER(set_key_value)
1931 {
1932     struct key *key;
1933     struct unicode_str name;
1934
1935     if (req->namelen > get_req_data_size())
1936     {
1937         set_error( STATUS_INVALID_PARAMETER );
1938         return;
1939     }
1940     name.str = get_req_data();
1941     name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
1942
1943     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
1944     {
1945         data_size_t datalen = get_req_data_size() - req->namelen;
1946         const char *data = (const char *)get_req_data() + req->namelen;
1947
1948         set_value( key, &name, req->type, data, datalen );
1949         release_object( key );
1950     }
1951 }
1952
1953 /* retrieve the value of a registry key */
1954 DECL_HANDLER(get_key_value)
1955 {
1956     struct key *key;
1957     struct unicode_str name;
1958
1959     reply->total = 0;
1960     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
1961     {
1962         get_req_unicode_str( &name );
1963         get_value( key, &name, &reply->type, &reply->total );
1964         release_object( key );
1965     }
1966 }
1967
1968 /* enumerate the value of a registry key */
1969 DECL_HANDLER(enum_key_value)
1970 {
1971     struct key *key;
1972
1973     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
1974     {
1975         enum_value( key, req->index, req->info_class, reply );
1976         release_object( key );
1977     }
1978 }
1979
1980 /* delete a value of a registry key */
1981 DECL_HANDLER(delete_key_value)
1982 {
1983     struct key *key;
1984     struct unicode_str name;
1985
1986     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
1987     {
1988         get_req_unicode_str( &name );
1989         delete_value( key, &name );
1990         release_object( key );
1991     }
1992 }
1993
1994 /* load a registry branch from a file */
1995 DECL_HANDLER(load_registry)
1996 {
1997     struct key *key, *parent;
1998     struct token *token = thread_get_impersonation_token( current );
1999     struct unicode_str name;
2000
2001     const LUID_AND_ATTRIBUTES privs[] =
2002     {
2003         { SeBackupPrivilege,  0 },
2004         { SeRestorePrivilege, 0 },
2005     };
2006
2007     if (!token || !token_check_privileges( token, TRUE, privs,
2008                                            sizeof(privs)/sizeof(privs[0]), NULL ))
2009     {
2010         set_error( STATUS_PRIVILEGE_NOT_HELD );
2011         return;
2012     }
2013
2014     if ((parent = get_parent_hkey_obj( req->hkey )))
2015     {
2016         int dummy;
2017         get_req_path( &name, !req->hkey );
2018         if ((key = create_key( parent, &name, NULL, 0, KEY_WOW64_64KEY, 0, &dummy )))
2019         {
2020             load_registry( key, req->file );
2021             release_object( key );
2022         }
2023         release_object( parent );
2024     }
2025 }
2026
2027 DECL_HANDLER(unload_registry)
2028 {
2029     struct key *key;
2030     struct token *token = thread_get_impersonation_token( current );
2031
2032     const LUID_AND_ATTRIBUTES privs[] =
2033     {
2034         { SeBackupPrivilege,  0 },
2035         { SeRestorePrivilege, 0 },
2036     };
2037
2038     if (!token || !token_check_privileges( token, TRUE, privs,
2039                                            sizeof(privs)/sizeof(privs[0]), NULL ))
2040     {
2041         set_error( STATUS_PRIVILEGE_NOT_HELD );
2042         return;
2043     }
2044
2045     if ((key = get_hkey_obj( req->hkey, 0 )))
2046     {
2047         delete_key( key, 1 );     /* FIXME */
2048         release_object( key );
2049     }
2050 }
2051
2052 /* save a registry branch to a file */
2053 DECL_HANDLER(save_registry)
2054 {
2055     struct key *key;
2056
2057     if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
2058     {
2059         set_error( STATUS_PRIVILEGE_NOT_HELD );
2060         return;
2061     }
2062
2063     if ((key = get_hkey_obj( req->hkey, 0 )))
2064     {
2065         save_registry( key, req->file );
2066         release_object( key );
2067     }
2068 }
2069
2070 /* add a registry key change notification */
2071 DECL_HANDLER(set_registry_notification)
2072 {
2073     struct key *key;
2074     struct event *event;
2075     struct notify *notify;
2076
2077     key = get_hkey_obj( req->hkey, KEY_NOTIFY );
2078     if (key)
2079     {
2080         event = get_event_obj( current->process, req->event, SYNCHRONIZE );
2081         if (event)
2082         {
2083             notify = find_notify( key, current->process, req->hkey );
2084             if (notify)
2085             {
2086                 if (notify->event)
2087                     release_object( notify->event );
2088                 grab_object( event );
2089                 notify->event = event;
2090             }
2091             else
2092             {
2093                 notify = mem_alloc( sizeof(*notify) );
2094                 if (notify)
2095                 {
2096                     grab_object( event );
2097                     notify->event   = event;
2098                     notify->subtree = req->subtree;
2099                     notify->filter  = req->filter;
2100                     notify->hkey    = req->hkey;
2101                     notify->process = current->process;
2102                     list_add_head( &key->notify_list, &notify->entry );
2103                 }
2104             }
2105             release_object( event );
2106         }
2107         release_object( key );
2108     }
2109 }