winejoystick: Fix a crash on accessing a CFArray past its end due to an off-by-one...
[wine/multimedia.git] / server / registry.c
blob43527df06e9f5158e77c9ef6e8b8761968d211ba
1 /*
2 * Server-side registry management
4 * Copyright (C) 1999 Alexandre Julliard
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.
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.
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
21 /* To do:
22 * - symbolic links
25 #include "config.h"
26 #include "wine/port.h"
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>
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 "process.h"
47 #include "unicode.h"
48 #include "security.h"
50 #include "winternl.h"
51 #include "wine/library.h"
53 struct notify
55 struct list entry; /* entry in list of notifications */
56 struct event *event; /* event to set when changing this key */
57 int subtree; /* true if subtree notification */
58 unsigned int filter; /* which events to notify on */
59 obj_handle_t hkey; /* hkey associated with this notification */
60 struct process *process; /* process in which the hkey is valid */
63 /* a registry key */
64 struct key
66 struct object obj; /* object header */
67 WCHAR *name; /* key name */
68 WCHAR *class; /* key class */
69 unsigned short namelen; /* length of key name */
70 unsigned short classlen; /* length of class name */
71 struct key *parent; /* parent key */
72 int last_subkey; /* last in use subkey */
73 int nb_subkeys; /* count of allocated subkeys */
74 struct key **subkeys; /* subkeys array */
75 int last_value; /* last in use value */
76 int nb_values; /* count of allocated values in array */
77 struct key_value *values; /* values array */
78 unsigned int flags; /* flags */
79 timeout_t modif; /* last modification time */
80 struct list notify_list; /* list of notifications */
83 /* key flags */
84 #define KEY_VOLATILE 0x0001 /* key is volatile (not saved to disk) */
85 #define KEY_DELETED 0x0002 /* key has been deleted */
86 #define KEY_DIRTY 0x0004 /* key has been modified */
87 #define KEY_SYMLINK 0x0008 /* key is a symbolic link */
88 #define KEY_WOW64 0x0010 /* key contains a Wow6432Node subkey */
89 #define KEY_WOWSHARE 0x0020 /* key is a Wow64 shared key (used for Software\Classes) */
91 /* a key value */
92 struct key_value
94 WCHAR *name; /* value name */
95 unsigned short namelen; /* length of value name */
96 unsigned short type; /* value type */
97 data_size_t len; /* value data length in bytes */
98 void *data; /* pointer to value data */
101 #define MIN_SUBKEYS 8 /* min. number of allocated subkeys per key */
102 #define MIN_VALUES 8 /* min. number of allocated values per key */
104 #define MAX_NAME_LEN 255 /* max. length of a key name */
105 #define MAX_VALUE_LEN 16383 /* max. length of a value name */
107 /* the root of the registry tree */
108 static struct key *root_key;
110 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
111 static const timeout_t save_period = 30 * -TICKS_PER_SEC; /* delay between periodic saves */
112 static struct timeout_user *save_timeout_user; /* saving timer */
113 static enum prefix_type { PREFIX_UNKNOWN, PREFIX_32BIT, PREFIX_64BIT } prefix_type;
115 static const WCHAR root_name[] = { '\\','R','e','g','i','s','t','r','y','\\' };
116 static const WCHAR wow6432node[] = {'W','o','w','6','4','3','2','N','o','d','e'};
117 static const WCHAR symlink_value[] = {'S','y','m','b','o','l','i','c','L','i','n','k','V','a','l','u','e'};
118 static const struct unicode_str symlink_str = { symlink_value, sizeof(symlink_value) };
120 static void set_periodic_save_timer(void);
121 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index );
123 /* information about where to save a registry branch */
124 struct save_branch_info
126 struct key *key;
127 const char *path;
130 #define MAX_SAVE_BRANCH_INFO 3
131 static int save_branch_count;
132 static struct save_branch_info save_branch_info[MAX_SAVE_BRANCH_INFO];
135 /* information about a file being loaded */
136 struct file_load_info
138 const char *filename; /* input file name */
139 FILE *file; /* input file */
140 char *buffer; /* line buffer */
141 int len; /* buffer length */
142 int line; /* current input line */
143 WCHAR *tmp; /* temp buffer to use while parsing input */
144 size_t tmplen; /* length of temp buffer */
148 static void key_dump( struct object *obj, int verbose );
149 static unsigned int key_map_access( struct object *obj, unsigned int access );
150 static struct security_descriptor *key_get_sd( struct object *obj );
151 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle );
152 static void key_destroy( struct object *obj );
154 static const struct object_ops key_ops =
156 sizeof(struct key), /* size */
157 key_dump, /* dump */
158 no_get_type, /* get_type */
159 no_add_queue, /* add_queue */
160 NULL, /* remove_queue */
161 NULL, /* signaled */
162 NULL, /* satisfied */
163 no_signal, /* signal */
164 no_get_fd, /* get_fd */
165 key_map_access, /* map_access */
166 key_get_sd, /* get_sd */
167 default_set_sd, /* set_sd */
168 no_lookup_name, /* lookup_name */
169 no_open_file, /* open_file */
170 key_close_handle, /* close_handle */
171 key_destroy /* destroy */
175 static inline int is_wow6432node( const WCHAR *name, unsigned int len )
177 return (len == sizeof(wow6432node) &&
178 !memicmpW( name, wow6432node, sizeof(wow6432node)/sizeof(WCHAR) ));
182 * The registry text file format v2 used by this code is similar to the one
183 * used by REGEDIT import/export functionality, with the following differences:
184 * - strings and key names can contain \x escapes for Unicode
185 * - key names use escapes too in order to support Unicode
186 * - the modification time optionally follows the key name
187 * - REG_EXPAND_SZ and REG_MULTI_SZ are saved as strings instead of hex
190 /* dump the full path of a key */
191 static void dump_path( const struct key *key, const struct key *base, FILE *f )
193 if (key->parent && key->parent != base)
195 dump_path( key->parent, base, f );
196 fprintf( f, "\\\\" );
198 dump_strW( key->name, key->namelen / sizeof(WCHAR), f, "[]" );
201 /* dump a value to a text file */
202 static void dump_value( const struct key_value *value, FILE *f )
204 unsigned int i, dw;
205 int count;
207 if (value->namelen)
209 fputc( '\"', f );
210 count = 1 + dump_strW( value->name, value->namelen / sizeof(WCHAR), f, "\"\"" );
211 count += fprintf( f, "\"=" );
213 else count = fprintf( f, "@=" );
215 switch(value->type)
217 case REG_SZ:
218 case REG_EXPAND_SZ:
219 case REG_MULTI_SZ:
220 /* only output properly terminated strings in string format */
221 if (value->len < sizeof(WCHAR)) break;
222 if (value->len % sizeof(WCHAR)) break;
223 if (((WCHAR *)value->data)[value->len / sizeof(WCHAR) - 1]) break;
224 if (value->type != REG_SZ) fprintf( f, "str(%x):", value->type );
225 fputc( '\"', f );
226 dump_strW( (WCHAR *)value->data, value->len / sizeof(WCHAR), f, "\"\"" );
227 fprintf( f, "\"\n" );
228 return;
230 case REG_DWORD:
231 if (value->len != sizeof(dw)) break;
232 memcpy( &dw, value->data, sizeof(dw) );
233 fprintf( f, "dword:%08x\n", dw );
234 return;
237 if (value->type == REG_BINARY) count += fprintf( f, "hex:" );
238 else count += fprintf( f, "hex(%x):", value->type );
239 for (i = 0; i < value->len; i++)
241 count += fprintf( f, "%02x", *((unsigned char *)value->data + i) );
242 if (i < value->len-1)
244 fputc( ',', f );
245 if (++count > 76)
247 fprintf( f, "\\\n " );
248 count = 2;
252 fputc( '\n', f );
255 /* save a registry and all its subkeys to a text file */
256 static void save_subkeys( const struct key *key, const struct key *base, FILE *f )
258 int i;
260 if (key->flags & KEY_VOLATILE) return;
261 /* save key if it has either some values or no subkeys, or needs special options */
262 /* keys with no values but subkeys are saved implicitly by saving the subkeys */
263 if ((key->last_value >= 0) || (key->last_subkey == -1) || key->class || (key->flags & KEY_SYMLINK))
265 fprintf( f, "\n[" );
266 if (key != base) dump_path( key, base, f );
267 fprintf( f, "] %u\n", (unsigned int)((key->modif - ticks_1601_to_1970) / TICKS_PER_SEC) );
268 if (key->class)
270 fprintf( f, "#class=\"" );
271 dump_strW( key->class, key->classlen / sizeof(WCHAR), f, "\"\"" );
272 fprintf( f, "\"\n" );
274 if (key->flags & KEY_SYMLINK) fputs( "#link\n", f );
275 for (i = 0; i <= key->last_value; i++) dump_value( &key->values[i], f );
277 for (i = 0; i <= key->last_subkey; i++) save_subkeys( key->subkeys[i], base, f );
280 static void dump_operation( const struct key *key, const struct key_value *value, const char *op )
282 fprintf( stderr, "%s key ", op );
283 if (key) dump_path( key, NULL, stderr );
284 else fprintf( stderr, "ERROR" );
285 if (value)
287 fprintf( stderr, " value ");
288 dump_value( value, stderr );
290 else fprintf( stderr, "\n" );
293 static void key_dump( struct object *obj, int verbose )
295 struct key *key = (struct key *)obj;
296 assert( obj->ops == &key_ops );
297 fprintf( stderr, "Key flags=%x ", key->flags );
298 dump_path( key, NULL, stderr );
299 fprintf( stderr, "\n" );
302 /* notify waiter and maybe delete the notification */
303 static void do_notification( struct key *key, struct notify *notify, int del )
305 if (notify->event)
307 set_event( notify->event );
308 release_object( notify->event );
309 notify->event = NULL;
311 if (del)
313 list_remove( &notify->entry );
314 free( notify );
318 static inline struct notify *find_notify( struct key *key, struct process *process, obj_handle_t hkey )
320 struct notify *notify;
322 LIST_FOR_EACH_ENTRY( notify, &key->notify_list, struct notify, entry )
324 if (notify->process == process && notify->hkey == hkey) return notify;
326 return NULL;
329 static unsigned int key_map_access( struct object *obj, unsigned int access )
331 if (access & GENERIC_READ) access |= KEY_READ;
332 if (access & GENERIC_WRITE) access |= KEY_WRITE;
333 if (access & GENERIC_EXECUTE) access |= KEY_EXECUTE;
334 if (access & GENERIC_ALL) access |= KEY_ALL_ACCESS;
335 /* filter the WOW64 masks, as they aren't real access bits */
336 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL |
337 KEY_WOW64_64KEY | KEY_WOW64_32KEY);
340 static struct security_descriptor *key_get_sd( struct object *obj )
342 static struct security_descriptor *key_default_sd;
344 if (obj->sd) return obj->sd;
346 if (!key_default_sd)
348 size_t users_sid_len = security_sid_len( security_builtin_users_sid );
349 size_t admins_sid_len = security_sid_len( security_builtin_admins_sid );
350 size_t dacl_len = sizeof(ACL) + 2 * offsetof( ACCESS_ALLOWED_ACE, SidStart )
351 + users_sid_len + admins_sid_len;
352 ACCESS_ALLOWED_ACE *aaa;
353 ACL *dacl;
355 key_default_sd = mem_alloc( sizeof(*key_default_sd) + 2 * admins_sid_len + dacl_len );
356 key_default_sd->control = SE_DACL_PRESENT;
357 key_default_sd->owner_len = admins_sid_len;
358 key_default_sd->group_len = admins_sid_len;
359 key_default_sd->sacl_len = 0;
360 key_default_sd->dacl_len = dacl_len;
361 memcpy( key_default_sd + 1, security_builtin_admins_sid, admins_sid_len );
362 memcpy( (char *)(key_default_sd + 1) + admins_sid_len, security_builtin_admins_sid, admins_sid_len );
364 dacl = (ACL *)((char *)(key_default_sd + 1) + 2 * admins_sid_len);
365 dacl->AclRevision = ACL_REVISION;
366 dacl->Sbz1 = 0;
367 dacl->AclSize = dacl_len;
368 dacl->AceCount = 2;
369 dacl->Sbz2 = 0;
370 aaa = (ACCESS_ALLOWED_ACE *)(dacl + 1);
371 aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
372 aaa->Header.AceFlags = INHERIT_ONLY_ACE | CONTAINER_INHERIT_ACE;
373 aaa->Header.AceSize = offsetof( ACCESS_ALLOWED_ACE, SidStart ) + users_sid_len;
374 aaa->Mask = GENERIC_READ;
375 memcpy( &aaa->SidStart, security_builtin_users_sid, users_sid_len );
376 aaa = (ACCESS_ALLOWED_ACE *)((char *)aaa + aaa->Header.AceSize);
377 aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
378 aaa->Header.AceFlags = 0;
379 aaa->Header.AceSize = offsetof( ACCESS_ALLOWED_ACE, SidStart ) + admins_sid_len;
380 aaa->Mask = KEY_ALL_ACCESS;
381 memcpy( &aaa->SidStart, security_builtin_admins_sid, admins_sid_len );
383 return key_default_sd;
386 /* close the notification associated with a handle */
387 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
389 struct key * key = (struct key *) obj;
390 struct notify *notify = find_notify( key, process, handle );
391 if (notify) do_notification( key, notify, 1 );
392 return 1; /* ok to close */
395 static void key_destroy( struct object *obj )
397 int i;
398 struct list *ptr;
399 struct key *key = (struct key *)obj;
400 assert( obj->ops == &key_ops );
402 free( key->name );
403 free( key->class );
404 for (i = 0; i <= key->last_value; i++)
406 free( key->values[i].name );
407 free( key->values[i].data );
409 free( key->values );
410 for (i = 0; i <= key->last_subkey; i++)
412 key->subkeys[i]->parent = NULL;
413 release_object( key->subkeys[i] );
415 free( key->subkeys );
416 /* unconditionally notify everything waiting on this key */
417 while ((ptr = list_head( &key->notify_list )))
419 struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
420 do_notification( key, notify, 1 );
424 /* get the request vararg as registry path */
425 static inline void get_req_path( struct unicode_str *str, int skip_root )
427 str->str = get_req_data();
428 str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
430 if (skip_root && str->len >= sizeof(root_name) &&
431 !memicmpW( str->str, root_name, sizeof(root_name)/sizeof(WCHAR) ))
433 str->str += sizeof(root_name)/sizeof(WCHAR);
434 str->len -= sizeof(root_name);
438 /* return the next token in a given path */
439 /* token->str must point inside the path, or be NULL for the first call */
440 static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
442 data_size_t i = 0, len = path->len / sizeof(WCHAR);
444 if (!token->str) /* first time */
446 /* path cannot start with a backslash */
447 if (len && path->str[0] == '\\')
449 set_error( STATUS_OBJECT_PATH_INVALID );
450 return NULL;
453 else
455 i = token->str - path->str;
456 i += token->len / sizeof(WCHAR);
457 while (i < len && path->str[i] == '\\') i++;
459 token->str = path->str + i;
460 while (i < len && path->str[i] != '\\') i++;
461 token->len = (path->str + i - token->str) * sizeof(WCHAR);
462 return token;
465 /* allocate a key object */
466 static struct key *alloc_key( const struct unicode_str *name, timeout_t modif )
468 struct key *key;
469 if ((key = alloc_object( &key_ops )))
471 key->name = NULL;
472 key->class = NULL;
473 key->namelen = name->len;
474 key->classlen = 0;
475 key->flags = 0;
476 key->last_subkey = -1;
477 key->nb_subkeys = 0;
478 key->subkeys = NULL;
479 key->nb_values = 0;
480 key->last_value = -1;
481 key->values = NULL;
482 key->modif = modif;
483 key->parent = NULL;
484 list_init( &key->notify_list );
485 if (name->len && !(key->name = memdup( name->str, name->len )))
487 release_object( key );
488 key = NULL;
491 return key;
494 /* mark a key and all its parents as dirty (modified) */
495 static void make_dirty( struct key *key )
497 while (key)
499 if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return; /* nothing to do */
500 key->flags |= KEY_DIRTY;
501 key = key->parent;
505 /* mark a key and all its subkeys as clean (not modified) */
506 static void make_clean( struct key *key )
508 int i;
510 if (key->flags & KEY_VOLATILE) return;
511 if (!(key->flags & KEY_DIRTY)) return;
512 key->flags &= ~KEY_DIRTY;
513 for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
516 /* go through all the notifications and send them if necessary */
517 static void check_notify( struct key *key, unsigned int change, int not_subtree )
519 struct list *ptr, *next;
521 LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
523 struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
524 if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
525 do_notification( key, n, 0 );
529 /* update key modification time */
530 static void touch_key( struct key *key, unsigned int change )
532 struct key *k;
534 key->modif = current_time;
535 make_dirty( key );
537 /* do notifications */
538 check_notify( key, change, 1 );
539 for ( k = key->parent; k; k = k->parent )
540 check_notify( k, change & ~REG_NOTIFY_CHANGE_LAST_SET, 0 );
543 /* try to grow the array of subkeys; return 1 if OK, 0 on error */
544 static int grow_subkeys( struct key *key )
546 struct key **new_subkeys;
547 int nb_subkeys;
549 if (key->nb_subkeys)
551 nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2); /* grow by 50% */
552 if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
554 set_error( STATUS_NO_MEMORY );
555 return 0;
558 else
560 nb_subkeys = MIN_VALUES;
561 if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
563 key->subkeys = new_subkeys;
564 key->nb_subkeys = nb_subkeys;
565 return 1;
568 /* allocate a subkey for a given key, and return its index */
569 static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
570 int index, timeout_t modif )
572 struct key *key;
573 int i;
575 if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
577 set_error( STATUS_NAME_TOO_LONG );
578 return NULL;
580 if (parent->last_subkey + 1 == parent->nb_subkeys)
582 /* need to grow the array */
583 if (!grow_subkeys( parent )) return NULL;
585 if ((key = alloc_key( name, modif )) != NULL)
587 key->parent = parent;
588 for (i = ++parent->last_subkey; i > index; i--)
589 parent->subkeys[i] = parent->subkeys[i-1];
590 parent->subkeys[index] = key;
591 if (is_wow6432node( key->name, key->namelen ) && !is_wow6432node( parent->name, parent->namelen ))
592 parent->flags |= KEY_WOW64;
594 return key;
597 /* free a subkey of a given key */
598 static void free_subkey( struct key *parent, int index )
600 struct key *key;
601 int i, nb_subkeys;
603 assert( index >= 0 );
604 assert( index <= parent->last_subkey );
606 key = parent->subkeys[index];
607 for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
608 parent->last_subkey--;
609 key->flags |= KEY_DELETED;
610 key->parent = NULL;
611 if (is_wow6432node( key->name, key->namelen )) parent->flags &= ~KEY_WOW64;
612 release_object( key );
614 /* try to shrink the array */
615 nb_subkeys = parent->nb_subkeys;
616 if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
618 struct key **new_subkeys;
619 nb_subkeys -= nb_subkeys / 3; /* shrink by 33% */
620 if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
621 if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
622 parent->subkeys = new_subkeys;
623 parent->nb_subkeys = nb_subkeys;
627 /* find the named child of a given key and return its index */
628 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
630 int i, min, max, res;
631 data_size_t len;
633 min = 0;
634 max = key->last_subkey;
635 while (min <= max)
637 i = (min + max) / 2;
638 len = min( key->subkeys[i]->namelen, name->len );
639 res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
640 if (!res) res = key->subkeys[i]->namelen - name->len;
641 if (!res)
643 *index = i;
644 return key->subkeys[i];
646 if (res > 0) max = i - 1;
647 else min = i + 1;
649 *index = min; /* this is where we should insert it */
650 return NULL;
653 /* return the wow64 variant of the key, or the key itself if none */
654 static struct key *find_wow64_subkey( struct key *key, const struct unicode_str *name )
656 static const struct unicode_str wow6432node_str = { wow6432node, sizeof(wow6432node) };
657 int index;
659 if (!(key->flags & KEY_WOW64)) return key;
660 if (!is_wow6432node( name->str, name->len ))
662 key = find_subkey( key, &wow6432node_str, &index );
663 assert( key ); /* if KEY_WOW64 is set we must find it */
665 return key;
669 /* follow a symlink and return the resolved key */
670 static struct key *follow_symlink( struct key *key, int iteration )
672 struct unicode_str path, token;
673 struct key_value *value;
674 int index;
676 if (iteration > 16) return NULL;
677 if (!(key->flags & KEY_SYMLINK)) return key;
678 if (!(value = find_value( key, &symlink_str, &index ))) return NULL;
680 path.str = value->data;
681 path.len = (value->len / sizeof(WCHAR)) * sizeof(WCHAR);
682 if (path.len <= sizeof(root_name)) return NULL;
683 if (memicmpW( path.str, root_name, sizeof(root_name)/sizeof(WCHAR) )) return NULL;
684 path.str += sizeof(root_name) / sizeof(WCHAR);
685 path.len -= sizeof(root_name);
687 key = root_key;
688 token.str = NULL;
689 if (!get_path_token( &path, &token )) return NULL;
690 while (token.len)
692 if (!(key = find_subkey( key, &token, &index ))) break;
693 if (!(key = follow_symlink( key, iteration + 1 ))) break;
694 get_path_token( &path, &token );
696 return key;
699 /* open a key until we find an element that doesn't exist */
700 /* helper for open_key and create_key */
701 static struct key *open_key_prefix( struct key *key, const struct unicode_str *name,
702 unsigned int access, struct unicode_str *token, int *index )
704 token->str = NULL;
705 if (!get_path_token( name, token )) return NULL;
706 if (access & KEY_WOW64_32KEY) key = find_wow64_subkey( key, token );
707 while (token->len)
709 struct key *subkey;
710 if (!(subkey = find_subkey( key, token, index )))
712 if ((key->flags & KEY_WOWSHARE) && !(access & KEY_WOW64_64KEY))
714 /* try in the 64-bit parent */
715 key = key->parent;
716 subkey = find_subkey( key, token, index );
719 if (!subkey) break;
720 key = subkey;
721 get_path_token( name, token );
722 if (!token->len) break;
723 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, token );
724 if (!(key = follow_symlink( key, 0 )))
726 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
727 return NULL;
730 return key;
733 /* open a subkey */
734 static struct key *open_key( struct key *key, const struct unicode_str *name, unsigned int access,
735 unsigned int attributes )
737 int index;
738 struct unicode_str token;
740 if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
742 if (token.len)
744 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
745 return NULL;
747 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
748 if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
750 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
751 return NULL;
753 if (debug_level > 1) dump_operation( key, NULL, "Open" );
754 grab_object( key );
755 return key;
758 /* create a subkey */
759 static struct key *create_key( struct key *key, const struct unicode_str *name,
760 const struct unicode_str *class, unsigned int options,
761 unsigned int access, unsigned int attributes, int *created )
763 int index;
764 struct unicode_str token, next;
766 *created = 0;
767 if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
769 if (!token.len) /* the key already exists */
771 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
772 if (options & REG_OPTION_CREATE_LINK)
774 set_error( STATUS_OBJECT_NAME_COLLISION );
775 return NULL;
777 if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
779 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
780 return NULL;
782 if (debug_level > 1) dump_operation( key, NULL, "Open" );
783 grab_object( key );
784 return key;
787 /* token must be the last path component at this point */
788 next = token;
789 get_path_token( name, &next );
790 if (next.len)
792 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
793 return NULL;
796 if ((key->flags & KEY_VOLATILE) && !(options & REG_OPTION_VOLATILE))
798 set_error( STATUS_CHILD_MUST_BE_VOLATILE );
799 return NULL;
801 *created = 1;
802 make_dirty( key );
803 if (!(key = alloc_subkey( key, &token, index, current_time ))) return NULL;
805 if (options & REG_OPTION_CREATE_LINK) key->flags |= KEY_SYMLINK;
806 if (options & REG_OPTION_VOLATILE) key->flags |= KEY_VOLATILE;
807 else key->flags |= KEY_DIRTY;
809 if (debug_level > 1) dump_operation( key, NULL, "Create" );
810 if (class && class->len)
812 key->classlen = class->len;
813 free(key->class);
814 if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
816 grab_object( key );
817 return key;
820 /* recursively create a subkey (for internal use only) */
821 static struct key *create_key_recursive( struct key *key, const struct unicode_str *name, timeout_t modif )
823 struct key *base;
824 int index;
825 struct unicode_str token;
827 token.str = NULL;
828 if (!get_path_token( name, &token )) return NULL;
829 while (token.len)
831 struct key *subkey;
832 if (!(subkey = find_subkey( key, &token, &index ))) break;
833 key = subkey;
834 if (!(key = follow_symlink( key, 0 )))
836 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
837 return NULL;
839 get_path_token( name, &token );
842 if (token.len)
844 if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
845 base = key;
846 for (;;)
848 get_path_token( name, &token );
849 if (!token.len) break;
850 /* we know the index is always 0 in a new key */
851 if (!(key = alloc_subkey( key, &token, 0, modif )))
853 free_subkey( base, index );
854 return NULL;
859 grab_object( key );
860 return key;
863 /* query information about a key or a subkey */
864 static void enum_key( const struct key *key, int index, int info_class,
865 struct enum_key_reply *reply )
867 static const WCHAR backslash[] = { '\\' };
868 int i;
869 data_size_t len, namelen, classlen;
870 data_size_t max_subkey = 0, max_class = 0;
871 data_size_t max_value = 0, max_data = 0;
872 const struct key *k;
873 char *data;
875 if (index != -1) /* -1 means use the specified key directly */
877 if ((index < 0) || (index > key->last_subkey))
879 set_error( STATUS_NO_MORE_ENTRIES );
880 return;
882 key = key->subkeys[index];
885 namelen = key->namelen;
886 classlen = key->classlen;
888 switch(info_class)
890 case KeyNameInformation:
891 namelen = 0;
892 for (k = key; k != root_key; k = k->parent)
893 namelen += k->namelen + sizeof(backslash);
894 if (!namelen) return;
895 namelen += sizeof(root_name) - sizeof(backslash);
896 /* fall through */
897 case KeyBasicInformation:
898 classlen = 0; /* only return the name */
899 /* fall through */
900 case KeyNodeInformation:
901 reply->max_subkey = 0;
902 reply->max_class = 0;
903 reply->max_value = 0;
904 reply->max_data = 0;
905 break;
906 case KeyFullInformation:
907 for (i = 0; i <= key->last_subkey; i++)
909 struct key *subkey = key->subkeys[i];
910 len = subkey->namelen / sizeof(WCHAR);
911 if (len > max_subkey) max_subkey = len;
912 len = subkey->classlen / sizeof(WCHAR);
913 if (len > max_class) max_class = len;
915 for (i = 0; i <= key->last_value; i++)
917 len = key->values[i].namelen / sizeof(WCHAR);
918 if (len > max_value) max_value = len;
919 len = key->values[i].len;
920 if (len > max_data) max_data = len;
922 reply->max_subkey = max_subkey;
923 reply->max_class = max_class;
924 reply->max_value = max_value;
925 reply->max_data = max_data;
926 namelen = 0; /* only return the class */
927 break;
928 default:
929 set_error( STATUS_INVALID_PARAMETER );
930 return;
932 reply->subkeys = key->last_subkey + 1;
933 reply->values = key->last_value + 1;
934 reply->modif = key->modif;
935 reply->total = namelen + classlen;
937 len = min( reply->total, get_reply_max_size() );
938 if (len && (data = set_reply_data_size( len )))
940 if (len > namelen)
942 reply->namelen = namelen;
943 memcpy( data, key->name, namelen );
944 memcpy( data + namelen, key->class, len - namelen );
946 else if (info_class == KeyNameInformation)
948 data_size_t pos = namelen;
949 reply->namelen = namelen;
950 for (k = key; k != root_key; k = k->parent)
952 pos -= k->namelen;
953 if (pos < len) memcpy( data + pos, k->name,
954 min( k->namelen, len - pos ) );
955 pos -= sizeof(backslash);
956 if (pos < len) memcpy( data + pos, backslash,
957 min( sizeof(backslash), len - pos ) );
959 memcpy( data, root_name, min( sizeof(root_name) - sizeof(backslash), len ) );
961 else
963 reply->namelen = len;
964 memcpy( data, key->name, len );
967 if (debug_level > 1) dump_operation( key, NULL, "Enum" );
970 /* delete a key and its values */
971 static int delete_key( struct key *key, int recurse )
973 int index;
974 struct key *parent = key->parent;
976 /* must find parent and index */
977 if (key == root_key)
979 set_error( STATUS_ACCESS_DENIED );
980 return -1;
982 assert( parent );
984 while (recurse && (key->last_subkey>=0))
985 if (0 > delete_key(key->subkeys[key->last_subkey], 1))
986 return -1;
988 for (index = 0; index <= parent->last_subkey; index++)
989 if (parent->subkeys[index] == key) break;
990 assert( index <= parent->last_subkey );
992 /* we can only delete a key that has no subkeys */
993 if (key->last_subkey >= 0)
995 set_error( STATUS_ACCESS_DENIED );
996 return -1;
999 if (debug_level > 1) dump_operation( key, NULL, "Delete" );
1000 free_subkey( parent, index );
1001 touch_key( parent, REG_NOTIFY_CHANGE_NAME );
1002 return 0;
1005 /* try to grow the array of values; return 1 if OK, 0 on error */
1006 static int grow_values( struct key *key )
1008 struct key_value *new_val;
1009 int nb_values;
1011 if (key->nb_values)
1013 nb_values = key->nb_values + (key->nb_values / 2); /* grow by 50% */
1014 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
1016 set_error( STATUS_NO_MEMORY );
1017 return 0;
1020 else
1022 nb_values = MIN_VALUES;
1023 if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
1025 key->values = new_val;
1026 key->nb_values = nb_values;
1027 return 1;
1030 /* find the named value of a given key and return its index in the array */
1031 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
1033 int i, min, max, res;
1034 data_size_t len;
1036 min = 0;
1037 max = key->last_value;
1038 while (min <= max)
1040 i = (min + max) / 2;
1041 len = min( key->values[i].namelen, name->len );
1042 res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
1043 if (!res) res = key->values[i].namelen - name->len;
1044 if (!res)
1046 *index = i;
1047 return &key->values[i];
1049 if (res > 0) max = i - 1;
1050 else min = i + 1;
1052 *index = min; /* this is where we should insert it */
1053 return NULL;
1056 /* insert a new value; the index must have been returned by find_value */
1057 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
1059 struct key_value *value;
1060 WCHAR *new_name = NULL;
1061 int i;
1063 if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
1065 set_error( STATUS_NAME_TOO_LONG );
1066 return NULL;
1068 if (key->last_value + 1 == key->nb_values)
1070 if (!grow_values( key )) return NULL;
1072 if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
1073 for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
1074 value = &key->values[index];
1075 value->name = new_name;
1076 value->namelen = name->len;
1077 value->len = 0;
1078 value->data = NULL;
1079 return value;
1082 /* set a key value */
1083 static void set_value( struct key *key, const struct unicode_str *name,
1084 int type, const void *data, data_size_t len )
1086 struct key_value *value;
1087 void *ptr = NULL;
1088 int index;
1090 if ((value = find_value( key, name, &index )))
1092 /* check if the new value is identical to the existing one */
1093 if (value->type == type && value->len == len &&
1094 value->data && !memcmp( value->data, data, len ))
1096 if (debug_level > 1) dump_operation( key, value, "Skip setting" );
1097 return;
1101 if (key->flags & KEY_SYMLINK)
1103 if (type != REG_LINK || name->len != symlink_str.len ||
1104 memicmpW( name->str, symlink_str.str, name->len / sizeof(WCHAR) ))
1106 set_error( STATUS_ACCESS_DENIED );
1107 return;
1111 if (len && !(ptr = memdup( data, len ))) return;
1113 if (!value)
1115 if (!(value = insert_value( key, name, index )))
1117 free( ptr );
1118 return;
1121 else free( value->data ); /* already existing, free previous data */
1123 value->type = type;
1124 value->len = len;
1125 value->data = ptr;
1126 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1127 if (debug_level > 1) dump_operation( key, value, "Set" );
1130 /* get a key value */
1131 static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
1133 struct key_value *value;
1134 int index;
1136 if ((value = find_value( key, name, &index )))
1138 *type = value->type;
1139 *len = value->len;
1140 if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
1141 if (debug_level > 1) dump_operation( key, value, "Get" );
1143 else
1145 *type = -1;
1146 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1150 /* enumerate a key value */
1151 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
1153 struct key_value *value;
1155 if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
1156 else
1158 void *data;
1159 data_size_t namelen, maxlen;
1161 value = &key->values[i];
1162 reply->type = value->type;
1163 namelen = value->namelen;
1165 switch(info_class)
1167 case KeyValueBasicInformation:
1168 reply->total = namelen;
1169 break;
1170 case KeyValueFullInformation:
1171 reply->total = namelen + value->len;
1172 break;
1173 case KeyValuePartialInformation:
1174 reply->total = value->len;
1175 namelen = 0;
1176 break;
1177 default:
1178 set_error( STATUS_INVALID_PARAMETER );
1179 return;
1182 maxlen = min( reply->total, get_reply_max_size() );
1183 if (maxlen && ((data = set_reply_data_size( maxlen ))))
1185 if (maxlen > namelen)
1187 reply->namelen = namelen;
1188 memcpy( data, value->name, namelen );
1189 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
1191 else
1193 reply->namelen = maxlen;
1194 memcpy( data, value->name, maxlen );
1197 if (debug_level > 1) dump_operation( key, value, "Enum" );
1201 /* delete a value */
1202 static void delete_value( struct key *key, const struct unicode_str *name )
1204 struct key_value *value;
1205 int i, index, nb_values;
1207 if (!(value = find_value( key, name, &index )))
1209 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1210 return;
1212 if (debug_level > 1) dump_operation( key, value, "Delete" );
1213 free( value->name );
1214 free( value->data );
1215 for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
1216 key->last_value--;
1217 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1219 /* try to shrink the array */
1220 nb_values = key->nb_values;
1221 if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
1223 struct key_value *new_val;
1224 nb_values -= nb_values / 3; /* shrink by 33% */
1225 if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
1226 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
1227 key->values = new_val;
1228 key->nb_values = nb_values;
1232 /* get the registry key corresponding to an hkey handle */
1233 static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1235 struct key *key = (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1237 if (key && key->flags & KEY_DELETED)
1239 set_error( STATUS_KEY_DELETED );
1240 release_object( key );
1241 key = NULL;
1243 return key;
1246 /* get the registry key corresponding to a parent key handle */
1247 static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
1249 if (!hkey) return (struct key *)grab_object( root_key );
1250 return get_hkey_obj( hkey, 0 );
1253 /* read a line from the input file */
1254 static int read_next_line( struct file_load_info *info )
1256 char *newbuf;
1257 int newlen, pos = 0;
1259 info->line++;
1260 for (;;)
1262 if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1263 return (pos != 0); /* EOF */
1264 pos = strlen(info->buffer);
1265 if (info->buffer[pos-1] == '\n')
1267 /* got a full line */
1268 info->buffer[--pos] = 0;
1269 if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1270 return 1;
1272 if (pos < info->len - 1) return 1; /* EOF but something was read */
1274 /* need to enlarge the buffer */
1275 newlen = info->len + info->len / 2;
1276 if (!(newbuf = realloc( info->buffer, newlen )))
1278 set_error( STATUS_NO_MEMORY );
1279 return -1;
1281 info->buffer = newbuf;
1282 info->len = newlen;
1286 /* make sure the temp buffer holds enough space */
1287 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1289 WCHAR *tmp;
1290 if (info->tmplen >= size) return 1;
1291 if (!(tmp = realloc( info->tmp, size )))
1293 set_error( STATUS_NO_MEMORY );
1294 return 0;
1296 info->tmp = tmp;
1297 info->tmplen = size;
1298 return 1;
1301 /* report an error while loading an input file */
1302 static void file_read_error( const char *err, struct file_load_info *info )
1304 if (info->filename)
1305 fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1306 else
1307 fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1310 /* convert a data type tag to a value type */
1311 static int get_data_type( const char *buffer, int *type, int *parse_type )
1313 struct data_type { const char *tag; int len; int type; int parse_type; };
1315 static const struct data_type data_types[] =
1316 { /* actual type */ /* type to assume for parsing */
1317 { "\"", 1, REG_SZ, REG_SZ },
1318 { "str:\"", 5, REG_SZ, REG_SZ },
1319 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
1320 { "str(7):\"", 8, REG_MULTI_SZ, REG_SZ },
1321 { "hex:", 4, REG_BINARY, REG_BINARY },
1322 { "dword:", 6, REG_DWORD, REG_DWORD },
1323 { "hex(", 4, -1, REG_BINARY },
1324 { NULL, 0, 0, 0 }
1327 const struct data_type *ptr;
1328 char *end;
1330 for (ptr = data_types; ptr->tag; ptr++)
1332 if (strncmp( ptr->tag, buffer, ptr->len )) continue;
1333 *parse_type = ptr->parse_type;
1334 if ((*type = ptr->type) != -1) return ptr->len;
1335 /* "hex(xx):" is special */
1336 *type = (int)strtoul( buffer + 4, &end, 16 );
1337 if ((end <= buffer) || strncmp( end, "):", 2 )) return 0;
1338 return end + 2 - buffer;
1340 return 0;
1343 /* load and create a key from the input file */
1344 static struct key *load_key( struct key *base, const char *buffer,
1345 int prefix_len, struct file_load_info *info )
1347 WCHAR *p;
1348 struct unicode_str name;
1349 int res;
1350 unsigned int mod;
1351 timeout_t modif = current_time;
1352 data_size_t len;
1354 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1356 len = info->tmplen;
1357 if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1359 file_read_error( "Malformed key", info );
1360 return NULL;
1362 if (sscanf( buffer + res, " %u", &mod ) == 1)
1363 modif = (timeout_t)mod * TICKS_PER_SEC + ticks_1601_to_1970;
1365 p = info->tmp;
1366 while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1368 if (!*p)
1370 if (prefix_len > 1)
1372 file_read_error( "Malformed key", info );
1373 return NULL;
1375 /* empty key name, return base key */
1376 return (struct key *)grab_object( base );
1378 name.str = p;
1379 name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1380 return create_key_recursive( base, &name, modif );
1383 /* load a global option from the input file */
1384 static int load_global_option( const char *buffer, struct file_load_info *info )
1386 const char *p;
1388 if (!strncmp( buffer, "#arch=", 6 ))
1390 enum prefix_type type;
1391 p = buffer + 6;
1392 if (!strcmp( p, "win32" )) type = PREFIX_32BIT;
1393 else if (!strcmp( p, "win64" )) type = PREFIX_64BIT;
1394 else
1396 file_read_error( "Unknown architecture", info );
1397 set_error( STATUS_NOT_REGISTRY_FILE );
1398 return 0;
1400 if (prefix_type == PREFIX_UNKNOWN) prefix_type = type;
1401 else if (type != prefix_type)
1403 file_read_error( "Mismatched architecture", info );
1404 set_error( STATUS_NOT_REGISTRY_FILE );
1405 return 0;
1408 /* ignore unknown options */
1409 return 1;
1412 /* load a key option from the input file */
1413 static int load_key_option( struct key *key, const char *buffer, struct file_load_info *info )
1415 const char *p;
1416 data_size_t len;
1418 if (!strncmp( buffer, "#class=", 7 ))
1420 p = buffer + 7;
1421 if (*p++ != '"') return 0;
1422 if (!get_file_tmp_space( info, strlen(p) * sizeof(WCHAR) )) return 0;
1423 len = info->tmplen;
1424 if (parse_strW( info->tmp, &len, p, '\"' ) == -1) return 0;
1425 free( key->class );
1426 if (!(key->class = memdup( info->tmp, len ))) len = 0;
1427 key->classlen = len;
1429 if (!strncmp( buffer, "#link", 5 )) key->flags |= KEY_SYMLINK;
1430 /* ignore unknown options */
1431 return 1;
1434 /* parse a comma-separated list of hex digits */
1435 static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1437 const char *p = buffer;
1438 data_size_t count = 0;
1439 char *end;
1441 while (isxdigit(*p))
1443 unsigned int val = strtoul( p, &end, 16 );
1444 if (end == p || val > 0xff) return -1;
1445 if (count++ >= *len) return -1; /* dest buffer overflow */
1446 *dest++ = val;
1447 p = end;
1448 while (isspace(*p)) p++;
1449 if (*p == ',') p++;
1450 while (isspace(*p)) p++;
1452 *len = count;
1453 return p - buffer;
1456 /* parse a value name and create the corresponding value */
1457 static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1458 struct file_load_info *info )
1460 struct key_value *value;
1461 struct unicode_str name;
1462 int index;
1464 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1465 name.str = info->tmp;
1466 name.len = info->tmplen;
1467 if (buffer[0] == '@')
1469 name.len = 0;
1470 *len = 1;
1472 else
1474 int r = parse_strW( info->tmp, &name.len, buffer + 1, '\"' );
1475 if (r == -1) goto error;
1476 *len = r + 1; /* for initial quote */
1477 name.len -= sizeof(WCHAR); /* terminating null */
1479 while (isspace(buffer[*len])) (*len)++;
1480 if (buffer[*len] != '=') goto error;
1481 (*len)++;
1482 while (isspace(buffer[*len])) (*len)++;
1483 if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1484 return value;
1486 error:
1487 file_read_error( "Malformed value name", info );
1488 return NULL;
1491 /* load a value from the input file */
1492 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1494 DWORD dw;
1495 void *ptr, *newptr;
1496 int res, type, parse_type;
1497 data_size_t maxlen, len;
1498 struct key_value *value;
1500 if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1501 if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1502 buffer += len + res;
1504 switch(parse_type)
1506 case REG_SZ:
1507 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return 0;
1508 len = info->tmplen;
1509 if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1510 ptr = info->tmp;
1511 break;
1512 case REG_DWORD:
1513 dw = strtoul( buffer, NULL, 16 );
1514 ptr = &dw;
1515 len = sizeof(dw);
1516 break;
1517 case REG_BINARY: /* hex digits */
1518 len = 0;
1519 for (;;)
1521 maxlen = 1 + strlen(buffer) / 2; /* at least 2 chars for one hex byte */
1522 if (!get_file_tmp_space( info, len + maxlen )) return 0;
1523 if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1524 len += maxlen;
1525 buffer += res;
1526 while (isspace(*buffer)) buffer++;
1527 if (!*buffer) break;
1528 if (*buffer != '\\') goto error;
1529 if (read_next_line( info) != 1) goto error;
1530 buffer = info->buffer;
1531 while (isspace(*buffer)) buffer++;
1533 ptr = info->tmp;
1534 break;
1535 default:
1536 assert(0);
1537 ptr = NULL; /* keep compiler quiet */
1538 break;
1541 if (!len) newptr = NULL;
1542 else if (!(newptr = memdup( ptr, len ))) return 0;
1544 free( value->data );
1545 value->data = newptr;
1546 value->len = len;
1547 value->type = type;
1548 return 1;
1550 error:
1551 file_read_error( "Malformed value", info );
1552 free( value->data );
1553 value->data = NULL;
1554 value->len = 0;
1555 value->type = REG_NONE;
1556 return 0;
1559 /* return the length (in path elements) of name that is part of the key name */
1560 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1561 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1563 WCHAR *p;
1564 int res;
1565 data_size_t len;
1567 if (!get_file_tmp_space( info, strlen(name) * sizeof(WCHAR) )) return 0;
1569 len = info->tmplen;
1570 if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1572 file_read_error( "Malformed key", info );
1573 return 0;
1575 for (p = info->tmp; *p; p++) if (*p == '\\') break;
1576 len = (p - info->tmp) * sizeof(WCHAR);
1577 for (res = 1; key != root_key; res++)
1579 if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1580 key = key->parent;
1582 if (key == root_key) res = 0; /* no matching name */
1583 return res;
1586 /* load all the keys from the input file */
1587 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1588 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1590 struct key *subkey = NULL;
1591 struct file_load_info info;
1592 char *p;
1594 info.filename = filename;
1595 info.file = f;
1596 info.len = 4;
1597 info.tmplen = 4;
1598 info.line = 0;
1599 if (!(info.buffer = mem_alloc( info.len ))) return;
1600 if (!(info.tmp = mem_alloc( info.tmplen )))
1602 free( info.buffer );
1603 return;
1606 if ((read_next_line( &info ) != 1) ||
1607 strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1609 set_error( STATUS_NOT_REGISTRY_FILE );
1610 goto done;
1613 while (read_next_line( &info ) == 1)
1615 p = info.buffer;
1616 while (*p && isspace(*p)) p++;
1617 switch(*p)
1619 case '[': /* new key */
1620 if (subkey) release_object( subkey );
1621 if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1622 if (!(subkey = load_key( key, p + 1, prefix_len, &info )))
1623 file_read_error( "Error creating key", &info );
1624 break;
1625 case '@': /* default value */
1626 case '\"': /* value */
1627 if (subkey) load_value( subkey, p, &info );
1628 else file_read_error( "Value without key", &info );
1629 break;
1630 case '#': /* option */
1631 if (subkey) load_key_option( subkey, p, &info );
1632 else if (!load_global_option( p, &info )) goto done;
1633 break;
1634 case ';': /* comment */
1635 case 0: /* empty line */
1636 break;
1637 default:
1638 file_read_error( "Unrecognized input", &info );
1639 break;
1643 done:
1644 if (subkey) release_object( subkey );
1645 free( info.buffer );
1646 free( info.tmp );
1649 /* load a part of the registry from a file */
1650 static void load_registry( struct key *key, obj_handle_t handle )
1652 struct file *file;
1653 int fd;
1655 if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1656 fd = dup( get_file_unix_fd( file ) );
1657 release_object( file );
1658 if (fd != -1)
1660 FILE *f = fdopen( fd, "r" );
1661 if (f)
1663 load_keys( key, NULL, f, -1 );
1664 fclose( f );
1666 else file_set_error();
1670 /* load one of the initial registry files */
1671 static int load_init_registry_from_file( const char *filename, struct key *key )
1673 FILE *f;
1675 if ((f = fopen( filename, "r" )))
1677 load_keys( key, filename, f, 0 );
1678 fclose( f );
1679 if (get_error() == STATUS_NOT_REGISTRY_FILE)
1681 fprintf( stderr, "%s is not a valid registry file\n", filename );
1682 return 1;
1686 assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1688 save_branch_info[save_branch_count].path = filename;
1689 save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1690 make_object_static( &key->obj );
1691 return (f != NULL);
1694 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1696 static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1697 static const WCHAR formatW[] = {'-','%','u',0};
1698 WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1699 WCHAR *p = buffer;
1700 unsigned int i;
1702 strcpyW( p, prefixW );
1703 p += strlenW( prefixW );
1704 p += sprintfW( p, formatW, sid->Revision );
1705 p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1706 sid->IdentifierAuthority.Value[4] ),
1707 MAKEWORD( sid->IdentifierAuthority.Value[3],
1708 sid->IdentifierAuthority.Value[2] )));
1709 for (i = 0; i < sid->SubAuthorityCount; i++)
1710 p += sprintfW( p, formatW, sid->SubAuthority[i] );
1712 path->len = (p - buffer) * sizeof(WCHAR);
1713 path->str = p = memdup( buffer, path->len );
1714 return p;
1717 /* get the cpu architectures that can be supported in the current prefix */
1718 unsigned int get_prefix_cpu_mask(void)
1720 /* Allowed server/client/prefix combinations:
1722 * prefix
1723 * 32 64
1724 * server +------+------+ client
1725 * | ok | fail | 32
1726 * 32 +------+------+---
1727 * | fail | fail | 64
1728 * ---+------+------+---
1729 * | ok | ok | 32
1730 * 64 +------+------+---
1731 * | fail | ok | 64
1732 * ---+------+------+---
1734 switch (prefix_type)
1736 case PREFIX_64BIT:
1737 /* 64-bit prefix requires 64-bit server */
1738 return sizeof(void *) > sizeof(int) ? ~0 : 0;
1739 case PREFIX_32BIT:
1740 default:
1741 return ~CPU_64BIT_MASK; /* only 32-bit cpus supported on 32-bit prefix */
1745 /* registry initialisation */
1746 void init_registry(void)
1748 static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1749 static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1750 static const WCHAR classes[] = {'S','o','f','t','w','a','r','e','\\',
1751 'C','l','a','s','s','e','s','\\',
1752 'W','o','w','6','4','3','2','N','o','d','e'};
1753 static const struct unicode_str root_name = { NULL, 0 };
1754 static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1755 static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1756 static const struct unicode_str classes_name = { classes, sizeof(classes) };
1758 WCHAR *current_user_path;
1759 struct unicode_str current_user_str;
1760 struct key *key, *hklm, *hkcu;
1762 /* switch to the config dir */
1764 if (fchdir( config_dir_fd ) == -1) fatal_error( "chdir to config dir: %s\n", strerror( errno ));
1766 /* create the root key */
1767 root_key = alloc_key( &root_name, current_time );
1768 assert( root_key );
1769 make_object_static( &root_key->obj );
1771 /* load system.reg into Registry\Machine */
1773 if (!(hklm = create_key_recursive( root_key, &HKLM_name, current_time )))
1774 fatal_error( "could not create Machine registry key\n" );
1776 if (!load_init_registry_from_file( "system.reg", hklm ))
1777 prefix_type = sizeof(void *) > sizeof(int) ? PREFIX_64BIT : PREFIX_32BIT;
1778 else if (prefix_type == PREFIX_UNKNOWN)
1779 prefix_type = PREFIX_32BIT;
1781 /* load userdef.reg into Registry\User\.Default */
1783 if (!(key = create_key_recursive( root_key, &HKU_name, current_time )))
1784 fatal_error( "could not create User\\.Default registry key\n" );
1786 load_init_registry_from_file( "userdef.reg", key );
1787 release_object( key );
1789 /* load user.reg into HKEY_CURRENT_USER */
1791 /* FIXME: match default user in token.c. should get from process token instead */
1792 current_user_path = format_user_registry_path( security_local_user_sid, &current_user_str );
1793 if (!current_user_path ||
1794 !(hkcu = create_key_recursive( root_key, &current_user_str, current_time )))
1795 fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1796 free( current_user_path );
1797 load_init_registry_from_file( "user.reg", hkcu );
1799 /* set the shared flag on Software\Classes\Wow6432Node */
1800 if (prefix_type == PREFIX_64BIT)
1802 if ((key = create_key_recursive( hklm, &classes_name, current_time )))
1804 key->flags |= KEY_WOWSHARE;
1805 release_object( key );
1807 /* FIXME: handle HKCU too */
1810 release_object( hklm );
1811 release_object( hkcu );
1813 /* start the periodic save timer */
1814 set_periodic_save_timer();
1816 /* go back to the server dir */
1817 if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
1820 /* save a registry branch to a file */
1821 static void save_all_subkeys( struct key *key, FILE *f )
1823 fprintf( f, "WINE REGISTRY Version 2\n" );
1824 fprintf( f, ";; All keys relative to " );
1825 dump_path( key, NULL, f );
1826 fprintf( f, "\n" );
1827 switch (prefix_type)
1829 case PREFIX_32BIT:
1830 fprintf( f, "\n#arch=win32\n" );
1831 break;
1832 case PREFIX_64BIT:
1833 fprintf( f, "\n#arch=win64\n" );
1834 break;
1835 default:
1836 break;
1838 save_subkeys( key, key, f );
1841 /* save a registry branch to a file handle */
1842 static void save_registry( struct key *key, obj_handle_t handle )
1844 struct file *file;
1845 int fd;
1847 if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1848 fd = dup( get_file_unix_fd( file ) );
1849 release_object( file );
1850 if (fd != -1)
1852 FILE *f = fdopen( fd, "w" );
1853 if (f)
1855 save_all_subkeys( key, f );
1856 if (fclose( f )) file_set_error();
1858 else
1860 file_set_error();
1861 close( fd );
1866 /* save a registry branch to a file */
1867 static int save_branch( struct key *key, const char *path )
1869 struct stat st;
1870 char *p, *tmp = NULL;
1871 int fd, count = 0, ret = 0;
1872 FILE *f;
1874 if (!(key->flags & KEY_DIRTY))
1876 if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1877 return 1;
1880 /* test the file type */
1882 if ((fd = open( path, O_WRONLY )) != -1)
1884 /* if file is not a regular file or has multiple links or is accessed
1885 * via symbolic links, write directly into it; otherwise use a temp file */
1886 if (!lstat( path, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1))
1888 ftruncate( fd, 0 );
1889 goto save;
1891 close( fd );
1894 /* create a temp file in the same directory */
1896 if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1897 strcpy( tmp, path );
1898 if ((p = strrchr( tmp, '/' ))) p++;
1899 else p = tmp;
1900 for (;;)
1902 sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1903 if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1904 if (errno != EEXIST) goto done;
1905 close( fd );
1908 /* now save to it */
1910 save:
1911 if (!(f = fdopen( fd, "w" )))
1913 if (tmp) unlink( tmp );
1914 close( fd );
1915 goto done;
1918 if (debug_level > 1)
1920 fprintf( stderr, "%s: ", path );
1921 dump_operation( key, NULL, "saving" );
1924 save_all_subkeys( key, f );
1925 ret = !fclose(f);
1927 if (tmp)
1929 /* if successfully written, rename to final name */
1930 if (ret) ret = !rename( tmp, path );
1931 if (!ret) unlink( tmp );
1934 done:
1935 free( tmp );
1936 if (ret) make_clean( key );
1937 return ret;
1940 /* periodic saving of the registry */
1941 static void periodic_save( void *arg )
1943 int i;
1945 if (fchdir( config_dir_fd ) == -1) return;
1946 save_timeout_user = NULL;
1947 for (i = 0; i < save_branch_count; i++)
1948 save_branch( save_branch_info[i].key, save_branch_info[i].path );
1949 if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
1950 set_periodic_save_timer();
1953 /* start the periodic save timer */
1954 static void set_periodic_save_timer(void)
1956 if (save_timeout_user) remove_timeout_user( save_timeout_user );
1957 save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
1960 /* save the modified registry branches to disk */
1961 void flush_registry(void)
1963 int i;
1965 if (fchdir( config_dir_fd ) == -1) return;
1966 for (i = 0; i < save_branch_count; i++)
1968 if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
1970 fprintf( stderr, "wineserver: could not save registry branch to %s",
1971 save_branch_info[i].path );
1972 perror( " " );
1975 if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
1978 /* determine if the thread is wow64 (32-bit client running on 64-bit prefix) */
1979 static int is_wow64_thread( struct thread *thread )
1981 return (prefix_type == PREFIX_64BIT && !(CPU_FLAG(thread->process->cpu) & CPU_64BIT_MASK));
1985 /* create a registry key */
1986 DECL_HANDLER(create_key)
1988 struct key *key = NULL, *parent;
1989 struct unicode_str name, class;
1990 unsigned int access = req->access;
1992 if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
1994 reply->hkey = 0;
1996 if (req->namelen > get_req_data_size())
1998 set_error( STATUS_INVALID_PARAMETER );
1999 return;
2001 class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
2002 class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
2003 get_req_path( &name, !req->parent );
2004 if (name.str > class.str)
2006 set_error( STATUS_INVALID_PARAMETER );
2007 return;
2009 name.len = (class.str - name.str) * sizeof(WCHAR);
2011 /* NOTE: no access rights are required from the parent handle to create a key */
2012 if ((parent = get_parent_hkey_obj( req->parent )))
2014 if ((key = create_key( parent, &name, &class, req->options, access,
2015 req->attributes, &reply->created )))
2017 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
2018 release_object( key );
2020 release_object( parent );
2024 /* open a registry key */
2025 DECL_HANDLER(open_key)
2027 struct key *key, *parent;
2028 struct unicode_str name;
2029 unsigned int access = req->access;
2031 if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
2033 reply->hkey = 0;
2034 /* NOTE: no access rights are required to open the parent key, only the child key */
2035 if ((parent = get_parent_hkey_obj( req->parent )))
2037 get_req_path( &name, !req->parent );
2038 if ((key = open_key( parent, &name, access, req->attributes )))
2040 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
2041 release_object( key );
2043 release_object( parent );
2047 /* delete a registry key */
2048 DECL_HANDLER(delete_key)
2050 struct key *key;
2052 if ((key = get_hkey_obj( req->hkey, DELETE )))
2054 delete_key( key, 0);
2055 release_object( key );
2059 /* flush a registry key */
2060 DECL_HANDLER(flush_key)
2062 struct key *key = get_hkey_obj( req->hkey, 0 );
2063 if (key)
2065 /* we don't need to do anything here with the current implementation */
2066 release_object( key );
2070 /* enumerate registry subkeys */
2071 DECL_HANDLER(enum_key)
2073 struct key *key;
2075 if ((key = get_hkey_obj( req->hkey,
2076 req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
2078 enum_key( key, req->index, req->info_class, reply );
2079 release_object( key );
2083 /* set a value of a registry key */
2084 DECL_HANDLER(set_key_value)
2086 struct key *key;
2087 struct unicode_str name;
2089 if (req->namelen > get_req_data_size())
2091 set_error( STATUS_INVALID_PARAMETER );
2092 return;
2094 name.str = get_req_data();
2095 name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2097 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2099 data_size_t datalen = get_req_data_size() - req->namelen;
2100 const char *data = (const char *)get_req_data() + req->namelen;
2102 set_value( key, &name, req->type, data, datalen );
2103 release_object( key );
2107 /* retrieve the value of a registry key */
2108 DECL_HANDLER(get_key_value)
2110 struct key *key;
2111 struct unicode_str name;
2113 reply->total = 0;
2114 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2116 get_req_unicode_str( &name );
2117 get_value( key, &name, &reply->type, &reply->total );
2118 release_object( key );
2122 /* enumerate the value of a registry key */
2123 DECL_HANDLER(enum_key_value)
2125 struct key *key;
2127 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2129 enum_value( key, req->index, req->info_class, reply );
2130 release_object( key );
2134 /* delete a value of a registry key */
2135 DECL_HANDLER(delete_key_value)
2137 struct key *key;
2138 struct unicode_str name;
2140 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2142 get_req_unicode_str( &name );
2143 delete_value( key, &name );
2144 release_object( key );
2148 /* load a registry branch from a file */
2149 DECL_HANDLER(load_registry)
2151 struct key *key, *parent;
2152 struct token *token = thread_get_impersonation_token( current );
2153 struct unicode_str name;
2155 const LUID_AND_ATTRIBUTES privs[] =
2157 { SeBackupPrivilege, 0 },
2158 { SeRestorePrivilege, 0 },
2161 if (!token || !token_check_privileges( token, TRUE, privs,
2162 sizeof(privs)/sizeof(privs[0]), NULL ))
2164 set_error( STATUS_PRIVILEGE_NOT_HELD );
2165 return;
2168 if ((parent = get_parent_hkey_obj( req->hkey )))
2170 int dummy;
2171 get_req_path( &name, !req->hkey );
2172 if ((key = create_key( parent, &name, NULL, 0, KEY_WOW64_64KEY, 0, &dummy )))
2174 load_registry( key, req->file );
2175 release_object( key );
2177 release_object( parent );
2181 DECL_HANDLER(unload_registry)
2183 struct key *key;
2184 struct token *token = thread_get_impersonation_token( current );
2186 const LUID_AND_ATTRIBUTES privs[] =
2188 { SeBackupPrivilege, 0 },
2189 { SeRestorePrivilege, 0 },
2192 if (!token || !token_check_privileges( token, TRUE, privs,
2193 sizeof(privs)/sizeof(privs[0]), NULL ))
2195 set_error( STATUS_PRIVILEGE_NOT_HELD );
2196 return;
2199 if ((key = get_hkey_obj( req->hkey, 0 )))
2201 delete_key( key, 1 ); /* FIXME */
2202 release_object( key );
2206 /* save a registry branch to a file */
2207 DECL_HANDLER(save_registry)
2209 struct key *key;
2211 if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
2213 set_error( STATUS_PRIVILEGE_NOT_HELD );
2214 return;
2217 if ((key = get_hkey_obj( req->hkey, 0 )))
2219 save_registry( key, req->file );
2220 release_object( key );
2224 /* add a registry key change notification */
2225 DECL_HANDLER(set_registry_notification)
2227 struct key *key;
2228 struct event *event;
2229 struct notify *notify;
2231 key = get_hkey_obj( req->hkey, KEY_NOTIFY );
2232 if (key)
2234 event = get_event_obj( current->process, req->event, SYNCHRONIZE );
2235 if (event)
2237 notify = find_notify( key, current->process, req->hkey );
2238 if (notify)
2240 if (notify->event)
2241 release_object( notify->event );
2242 grab_object( event );
2243 notify->event = event;
2245 else
2247 notify = mem_alloc( sizeof(*notify) );
2248 if (notify)
2250 grab_object( event );
2251 notify->event = event;
2252 notify->subtree = req->subtree;
2253 notify->filter = req->filter;
2254 notify->hkey = req->hkey;
2255 notify->process = current->process;
2256 list_add_head( &key->notify_list, &notify->entry );
2259 release_object( event );
2261 release_object( key );