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