wimgapi: Add stub for WIMRegisterMessageCallback.
[wine.git] / server / registry.c
blob3c9ae70363d8dd3003adc0ad19766d0aaf0a8eb1
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 fprintf( f, "#time=%x%08x\n", (unsigned int)(key->modif >> 32), (unsigned int)key->modif );
269 if (key->class)
271 fprintf( f, "#class=\"" );
272 dump_strW( key->class, key->classlen / sizeof(WCHAR), f, "\"\"" );
273 fprintf( f, "\"\n" );
275 if (key->flags & KEY_SYMLINK) fputs( "#link\n", f );
276 for (i = 0; i <= key->last_value; i++) dump_value( &key->values[i], f );
278 for (i = 0; i <= key->last_subkey; i++) save_subkeys( key->subkeys[i], base, f );
281 static void dump_operation( const struct key *key, const struct key_value *value, const char *op )
283 fprintf( stderr, "%s key ", op );
284 if (key) dump_path( key, NULL, stderr );
285 else fprintf( stderr, "ERROR" );
286 if (value)
288 fprintf( stderr, " value ");
289 dump_value( value, stderr );
291 else fprintf( stderr, "\n" );
294 static void key_dump( struct object *obj, int verbose )
296 struct key *key = (struct key *)obj;
297 assert( obj->ops == &key_ops );
298 fprintf( stderr, "Key flags=%x ", key->flags );
299 dump_path( key, NULL, stderr );
300 fprintf( stderr, "\n" );
303 /* notify waiter and maybe delete the notification */
304 static void do_notification( struct key *key, struct notify *notify, int del )
306 if (notify->event)
308 set_event( notify->event );
309 release_object( notify->event );
310 notify->event = NULL;
312 if (del)
314 list_remove( &notify->entry );
315 free( notify );
319 static inline struct notify *find_notify( struct key *key, struct process *process, obj_handle_t hkey )
321 struct notify *notify;
323 LIST_FOR_EACH_ENTRY( notify, &key->notify_list, struct notify, entry )
325 if (notify->process == process && notify->hkey == hkey) return notify;
327 return NULL;
330 static unsigned int key_map_access( struct object *obj, unsigned int access )
332 if (access & GENERIC_READ) access |= KEY_READ;
333 if (access & GENERIC_WRITE) access |= KEY_WRITE;
334 if (access & GENERIC_EXECUTE) access |= KEY_EXECUTE;
335 if (access & GENERIC_ALL) access |= KEY_ALL_ACCESS;
336 /* filter the WOW64 masks, as they aren't real access bits */
337 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL |
338 KEY_WOW64_64KEY | KEY_WOW64_32KEY);
341 static struct security_descriptor *key_get_sd( struct object *obj )
343 static struct security_descriptor *key_default_sd;
345 if (obj->sd) return obj->sd;
347 if (!key_default_sd)
349 size_t users_sid_len = security_sid_len( security_builtin_users_sid );
350 size_t admins_sid_len = security_sid_len( security_builtin_admins_sid );
351 size_t dacl_len = sizeof(ACL) + 2 * offsetof( ACCESS_ALLOWED_ACE, SidStart )
352 + users_sid_len + admins_sid_len;
353 ACCESS_ALLOWED_ACE *aaa;
354 ACL *dacl;
356 key_default_sd = mem_alloc( sizeof(*key_default_sd) + 2 * admins_sid_len + dacl_len );
357 key_default_sd->control = SE_DACL_PRESENT;
358 key_default_sd->owner_len = admins_sid_len;
359 key_default_sd->group_len = admins_sid_len;
360 key_default_sd->sacl_len = 0;
361 key_default_sd->dacl_len = dacl_len;
362 memcpy( key_default_sd + 1, security_builtin_admins_sid, admins_sid_len );
363 memcpy( (char *)(key_default_sd + 1) + admins_sid_len, security_builtin_admins_sid, admins_sid_len );
365 dacl = (ACL *)((char *)(key_default_sd + 1) + 2 * admins_sid_len);
366 dacl->AclRevision = ACL_REVISION;
367 dacl->Sbz1 = 0;
368 dacl->AclSize = dacl_len;
369 dacl->AceCount = 2;
370 dacl->Sbz2 = 0;
371 aaa = (ACCESS_ALLOWED_ACE *)(dacl + 1);
372 aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
373 aaa->Header.AceFlags = INHERIT_ONLY_ACE | CONTAINER_INHERIT_ACE;
374 aaa->Header.AceSize = offsetof( ACCESS_ALLOWED_ACE, SidStart ) + users_sid_len;
375 aaa->Mask = GENERIC_READ;
376 memcpy( &aaa->SidStart, security_builtin_users_sid, users_sid_len );
377 aaa = (ACCESS_ALLOWED_ACE *)((char *)aaa + aaa->Header.AceSize);
378 aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
379 aaa->Header.AceFlags = 0;
380 aaa->Header.AceSize = offsetof( ACCESS_ALLOWED_ACE, SidStart ) + admins_sid_len;
381 aaa->Mask = KEY_ALL_ACCESS;
382 memcpy( &aaa->SidStart, security_builtin_admins_sid, admins_sid_len );
384 return key_default_sd;
387 /* close the notification associated with a handle */
388 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
390 struct key * key = (struct key *) obj;
391 struct notify *notify = find_notify( key, process, handle );
392 if (notify) do_notification( key, notify, 1 );
393 return 1; /* ok to close */
396 static void key_destroy( struct object *obj )
398 int i;
399 struct list *ptr;
400 struct key *key = (struct key *)obj;
401 assert( obj->ops == &key_ops );
403 free( key->name );
404 free( key->class );
405 for (i = 0; i <= key->last_value; i++)
407 free( key->values[i].name );
408 free( key->values[i].data );
410 free( key->values );
411 for (i = 0; i <= key->last_subkey; i++)
413 key->subkeys[i]->parent = NULL;
414 release_object( key->subkeys[i] );
416 free( key->subkeys );
417 /* unconditionally notify everything waiting on this key */
418 while ((ptr = list_head( &key->notify_list )))
420 struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
421 do_notification( key, notify, 1 );
425 /* get the request vararg as registry path */
426 static inline void get_req_path( struct unicode_str *str, int skip_root )
428 str->str = get_req_data();
429 str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
431 if (skip_root && str->len >= sizeof(root_name) &&
432 !memicmpW( str->str, root_name, sizeof(root_name)/sizeof(WCHAR) ))
434 str->str += sizeof(root_name)/sizeof(WCHAR);
435 str->len -= sizeof(root_name);
439 /* return the next token in a given path */
440 /* token->str must point inside the path, or be NULL for the first call */
441 static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
443 data_size_t i = 0, len = path->len / sizeof(WCHAR);
445 if (!token->str) /* first time */
447 /* path cannot start with a backslash */
448 if (len && path->str[0] == '\\')
450 set_error( STATUS_OBJECT_PATH_INVALID );
451 return NULL;
454 else
456 i = token->str - path->str;
457 i += token->len / sizeof(WCHAR);
458 while (i < len && path->str[i] == '\\') i++;
460 token->str = path->str + i;
461 while (i < len && path->str[i] != '\\') i++;
462 token->len = (path->str + i - token->str) * sizeof(WCHAR);
463 return token;
466 /* allocate a key object */
467 static struct key *alloc_key( const struct unicode_str *name, timeout_t modif )
469 struct key *key;
470 if ((key = alloc_object( &key_ops )))
472 key->name = NULL;
473 key->class = NULL;
474 key->namelen = name->len;
475 key->classlen = 0;
476 key->flags = 0;
477 key->last_subkey = -1;
478 key->nb_subkeys = 0;
479 key->subkeys = NULL;
480 key->nb_values = 0;
481 key->last_value = -1;
482 key->values = NULL;
483 key->modif = modif;
484 key->parent = NULL;
485 list_init( &key->notify_list );
486 if (name->len && !(key->name = memdup( name->str, name->len )))
488 release_object( key );
489 key = NULL;
492 return key;
495 /* mark a key and all its parents as dirty (modified) */
496 static void make_dirty( struct key *key )
498 while (key)
500 if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return; /* nothing to do */
501 key->flags |= KEY_DIRTY;
502 key = key->parent;
506 /* mark a key and all its subkeys as clean (not modified) */
507 static void make_clean( struct key *key )
509 int i;
511 if (key->flags & KEY_VOLATILE) return;
512 if (!(key->flags & KEY_DIRTY)) return;
513 key->flags &= ~KEY_DIRTY;
514 for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
517 /* go through all the notifications and send them if necessary */
518 static void check_notify( struct key *key, unsigned int change, int not_subtree )
520 struct list *ptr, *next;
522 LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
524 struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
525 if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
526 do_notification( key, n, 0 );
530 /* update key modification time */
531 static void touch_key( struct key *key, unsigned int change )
533 struct key *k;
535 key->modif = current_time;
536 make_dirty( key );
538 /* do notifications */
539 check_notify( key, change, 1 );
540 for ( k = key->parent; k; k = k->parent )
541 check_notify( k, change & ~REG_NOTIFY_CHANGE_LAST_SET, 0 );
544 /* try to grow the array of subkeys; return 1 if OK, 0 on error */
545 static int grow_subkeys( struct key *key )
547 struct key **new_subkeys;
548 int nb_subkeys;
550 if (key->nb_subkeys)
552 nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2); /* grow by 50% */
553 if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
555 set_error( STATUS_NO_MEMORY );
556 return 0;
559 else
561 nb_subkeys = MIN_VALUES;
562 if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
564 key->subkeys = new_subkeys;
565 key->nb_subkeys = nb_subkeys;
566 return 1;
569 /* allocate a subkey for a given key, and return its index */
570 static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
571 int index, timeout_t modif )
573 struct key *key;
574 int i;
576 if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
578 set_error( STATUS_NAME_TOO_LONG );
579 return NULL;
581 if (parent->last_subkey + 1 == parent->nb_subkeys)
583 /* need to grow the array */
584 if (!grow_subkeys( parent )) return NULL;
586 if ((key = alloc_key( name, modif )) != NULL)
588 key->parent = parent;
589 for (i = ++parent->last_subkey; i > index; i--)
590 parent->subkeys[i] = parent->subkeys[i-1];
591 parent->subkeys[index] = key;
592 if (is_wow6432node( key->name, key->namelen ) && !is_wow6432node( parent->name, parent->namelen ))
593 parent->flags |= KEY_WOW64;
595 return key;
598 /* free a subkey of a given key */
599 static void free_subkey( struct key *parent, int index )
601 struct key *key;
602 int i, nb_subkeys;
604 assert( index >= 0 );
605 assert( index <= parent->last_subkey );
607 key = parent->subkeys[index];
608 for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
609 parent->last_subkey--;
610 key->flags |= KEY_DELETED;
611 key->parent = NULL;
612 if (is_wow6432node( key->name, key->namelen )) parent->flags &= ~KEY_WOW64;
613 release_object( key );
615 /* try to shrink the array */
616 nb_subkeys = parent->nb_subkeys;
617 if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
619 struct key **new_subkeys;
620 nb_subkeys -= nb_subkeys / 3; /* shrink by 33% */
621 if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
622 if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
623 parent->subkeys = new_subkeys;
624 parent->nb_subkeys = nb_subkeys;
628 /* find the named child of a given key and return its index */
629 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
631 int i, min, max, res;
632 data_size_t len;
634 min = 0;
635 max = key->last_subkey;
636 while (min <= max)
638 i = (min + max) / 2;
639 len = min( key->subkeys[i]->namelen, name->len );
640 res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
641 if (!res) res = key->subkeys[i]->namelen - name->len;
642 if (!res)
644 *index = i;
645 return key->subkeys[i];
647 if (res > 0) max = i - 1;
648 else min = i + 1;
650 *index = min; /* this is where we should insert it */
651 return NULL;
654 /* return the wow64 variant of the key, or the key itself if none */
655 static struct key *find_wow64_subkey( struct key *key, const struct unicode_str *name )
657 static const struct unicode_str wow6432node_str = { wow6432node, sizeof(wow6432node) };
658 int index;
660 if (!(key->flags & KEY_WOW64)) return key;
661 if (!is_wow6432node( name->str, name->len ))
663 key = find_subkey( key, &wow6432node_str, &index );
664 assert( key ); /* if KEY_WOW64 is set we must find it */
666 return key;
670 /* follow a symlink and return the resolved key */
671 static struct key *follow_symlink( struct key *key, int iteration )
673 struct unicode_str path, token;
674 struct key_value *value;
675 int index;
677 if (iteration > 16) return NULL;
678 if (!(key->flags & KEY_SYMLINK)) return key;
679 if (!(value = find_value( key, &symlink_str, &index ))) return NULL;
681 path.str = value->data;
682 path.len = (value->len / sizeof(WCHAR)) * sizeof(WCHAR);
683 if (path.len <= sizeof(root_name)) return NULL;
684 if (memicmpW( path.str, root_name, sizeof(root_name)/sizeof(WCHAR) )) return NULL;
685 path.str += sizeof(root_name) / sizeof(WCHAR);
686 path.len -= sizeof(root_name);
688 key = root_key;
689 token.str = NULL;
690 if (!get_path_token( &path, &token )) return NULL;
691 while (token.len)
693 if (!(key = find_subkey( key, &token, &index ))) break;
694 if (!(key = follow_symlink( key, iteration + 1 ))) break;
695 get_path_token( &path, &token );
697 return key;
700 /* open a key until we find an element that doesn't exist */
701 /* helper for open_key and create_key */
702 static struct key *open_key_prefix( struct key *key, const struct unicode_str *name,
703 unsigned int access, struct unicode_str *token, int *index )
705 token->str = NULL;
706 if (!get_path_token( name, token )) return NULL;
707 if (access & KEY_WOW64_32KEY) key = find_wow64_subkey( key, token );
708 while (token->len)
710 struct key *subkey;
711 if (!(subkey = find_subkey( key, token, index )))
713 if ((key->flags & KEY_WOWSHARE) && !(access & KEY_WOW64_64KEY))
715 /* try in the 64-bit parent */
716 key = key->parent;
717 subkey = find_subkey( key, token, index );
720 if (!subkey) break;
721 key = subkey;
722 get_path_token( name, token );
723 if (!token->len) break;
724 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, token );
725 if (!(key = follow_symlink( key, 0 )))
727 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
728 return NULL;
731 return key;
734 /* open a subkey */
735 static struct key *open_key( struct key *key, const struct unicode_str *name, unsigned int access,
736 unsigned int attributes )
738 int index;
739 struct unicode_str token;
741 if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
743 if (token.len)
745 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
746 return NULL;
748 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
749 if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
751 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
752 return NULL;
754 if (debug_level > 1) dump_operation( key, NULL, "Open" );
755 grab_object( key );
756 return key;
759 /* create a subkey */
760 static struct key *create_key( struct key *key, const struct unicode_str *name,
761 const struct unicode_str *class, unsigned int options,
762 unsigned int access, unsigned int attributes, int *created )
764 int index;
765 struct unicode_str token, next;
767 *created = 0;
768 if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
770 if (!token.len) /* the key already exists */
772 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
773 if (options & REG_OPTION_CREATE_LINK)
775 set_error( STATUS_OBJECT_NAME_COLLISION );
776 return NULL;
778 if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
780 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
781 return NULL;
783 if (debug_level > 1) dump_operation( key, NULL, "Open" );
784 grab_object( key );
785 return key;
788 /* token must be the last path component at this point */
789 next = token;
790 get_path_token( name, &next );
791 if (next.len)
793 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
794 return NULL;
797 if ((key->flags & KEY_VOLATILE) && !(options & REG_OPTION_VOLATILE))
799 set_error( STATUS_CHILD_MUST_BE_VOLATILE );
800 return NULL;
802 *created = 1;
803 make_dirty( key );
804 if (!(key = alloc_subkey( key, &token, index, current_time ))) return NULL;
806 if (options & REG_OPTION_CREATE_LINK) key->flags |= KEY_SYMLINK;
807 if (options & REG_OPTION_VOLATILE) key->flags |= KEY_VOLATILE;
808 else key->flags |= KEY_DIRTY;
810 if (debug_level > 1) dump_operation( key, NULL, "Create" );
811 if (class && class->len)
813 key->classlen = class->len;
814 free(key->class);
815 if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
817 touch_key( key->parent, REG_NOTIFY_CHANGE_NAME );
818 grab_object( key );
819 return key;
822 /* recursively create a subkey (for internal use only) */
823 static struct key *create_key_recursive( struct key *key, const struct unicode_str *name, timeout_t modif )
825 struct key *base;
826 int index;
827 struct unicode_str token;
829 token.str = NULL;
830 if (!get_path_token( name, &token )) return NULL;
831 while (token.len)
833 struct key *subkey;
834 if (!(subkey = find_subkey( key, &token, &index ))) break;
835 key = subkey;
836 if (!(key = follow_symlink( key, 0 )))
838 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
839 return NULL;
841 get_path_token( name, &token );
844 if (token.len)
846 if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
847 base = key;
848 for (;;)
850 get_path_token( name, &token );
851 if (!token.len) break;
852 /* we know the index is always 0 in a new key */
853 if (!(key = alloc_subkey( key, &token, 0, modif )))
855 free_subkey( base, index );
856 return NULL;
861 grab_object( key );
862 return key;
865 /* query information about a key or a subkey */
866 static void enum_key( const struct key *key, int index, int info_class,
867 struct enum_key_reply *reply )
869 static const WCHAR backslash[] = { '\\' };
870 int i;
871 data_size_t len, namelen, classlen;
872 data_size_t max_subkey = 0, max_class = 0;
873 data_size_t max_value = 0, max_data = 0;
874 const struct key *k;
875 char *data;
877 if (index != -1) /* -1 means use the specified key directly */
879 if ((index < 0) || (index > key->last_subkey))
881 set_error( STATUS_NO_MORE_ENTRIES );
882 return;
884 key = key->subkeys[index];
887 namelen = key->namelen;
888 classlen = key->classlen;
890 switch(info_class)
892 case KeyNameInformation:
893 namelen = 0;
894 for (k = key; k != root_key; k = k->parent)
895 namelen += k->namelen + sizeof(backslash);
896 if (!namelen) return;
897 namelen += sizeof(root_name) - sizeof(backslash);
898 /* fall through */
899 case KeyBasicInformation:
900 classlen = 0; /* only return the name */
901 /* fall through */
902 case KeyNodeInformation:
903 reply->max_subkey = 0;
904 reply->max_class = 0;
905 reply->max_value = 0;
906 reply->max_data = 0;
907 break;
908 case KeyFullInformation:
909 for (i = 0; i <= key->last_subkey; i++)
911 struct key *subkey = key->subkeys[i];
912 len = subkey->namelen / sizeof(WCHAR);
913 if (len > max_subkey) max_subkey = len;
914 len = subkey->classlen / sizeof(WCHAR);
915 if (len > max_class) max_class = len;
917 for (i = 0; i <= key->last_value; i++)
919 len = key->values[i].namelen / sizeof(WCHAR);
920 if (len > max_value) max_value = len;
921 len = key->values[i].len;
922 if (len > max_data) max_data = len;
924 reply->max_subkey = max_subkey;
925 reply->max_class = max_class;
926 reply->max_value = max_value;
927 reply->max_data = max_data;
928 namelen = 0; /* only return the class */
929 break;
930 default:
931 set_error( STATUS_INVALID_PARAMETER );
932 return;
934 reply->subkeys = key->last_subkey + 1;
935 reply->values = key->last_value + 1;
936 reply->modif = key->modif;
937 reply->total = namelen + classlen;
939 len = min( reply->total, get_reply_max_size() );
940 if (len && (data = set_reply_data_size( len )))
942 if (len > namelen)
944 reply->namelen = namelen;
945 memcpy( data, key->name, namelen );
946 memcpy( data + namelen, key->class, len - namelen );
948 else if (info_class == KeyNameInformation)
950 data_size_t pos = namelen;
951 reply->namelen = namelen;
952 for (k = key; k != root_key; k = k->parent)
954 pos -= k->namelen;
955 if (pos < len) memcpy( data + pos, k->name,
956 min( k->namelen, len - pos ) );
957 pos -= sizeof(backslash);
958 if (pos < len) memcpy( data + pos, backslash,
959 min( sizeof(backslash), len - pos ) );
961 memcpy( data, root_name, min( sizeof(root_name) - sizeof(backslash), len ) );
963 else
965 reply->namelen = len;
966 memcpy( data, key->name, len );
969 if (debug_level > 1) dump_operation( key, NULL, "Enum" );
972 /* delete a key and its values */
973 static int delete_key( struct key *key, int recurse )
975 int index;
976 struct key *parent = key->parent;
978 /* must find parent and index */
979 if (key == root_key)
981 set_error( STATUS_ACCESS_DENIED );
982 return -1;
984 assert( parent );
986 while (recurse && (key->last_subkey>=0))
987 if (0 > delete_key(key->subkeys[key->last_subkey], 1))
988 return -1;
990 for (index = 0; index <= parent->last_subkey; index++)
991 if (parent->subkeys[index] == key) break;
992 assert( index <= parent->last_subkey );
994 /* we can only delete a key that has no subkeys */
995 if (key->last_subkey >= 0)
997 set_error( STATUS_ACCESS_DENIED );
998 return -1;
1001 if (debug_level > 1) dump_operation( key, NULL, "Delete" );
1002 free_subkey( parent, index );
1003 touch_key( parent, REG_NOTIFY_CHANGE_NAME );
1004 return 0;
1007 /* try to grow the array of values; return 1 if OK, 0 on error */
1008 static int grow_values( struct key *key )
1010 struct key_value *new_val;
1011 int nb_values;
1013 if (key->nb_values)
1015 nb_values = key->nb_values + (key->nb_values / 2); /* grow by 50% */
1016 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
1018 set_error( STATUS_NO_MEMORY );
1019 return 0;
1022 else
1024 nb_values = MIN_VALUES;
1025 if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
1027 key->values = new_val;
1028 key->nb_values = nb_values;
1029 return 1;
1032 /* find the named value of a given key and return its index in the array */
1033 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
1035 int i, min, max, res;
1036 data_size_t len;
1038 min = 0;
1039 max = key->last_value;
1040 while (min <= max)
1042 i = (min + max) / 2;
1043 len = min( key->values[i].namelen, name->len );
1044 res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
1045 if (!res) res = key->values[i].namelen - name->len;
1046 if (!res)
1048 *index = i;
1049 return &key->values[i];
1051 if (res > 0) max = i - 1;
1052 else min = i + 1;
1054 *index = min; /* this is where we should insert it */
1055 return NULL;
1058 /* insert a new value; the index must have been returned by find_value */
1059 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
1061 struct key_value *value;
1062 WCHAR *new_name = NULL;
1063 int i;
1065 if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
1067 set_error( STATUS_NAME_TOO_LONG );
1068 return NULL;
1070 if (key->last_value + 1 == key->nb_values)
1072 if (!grow_values( key )) return NULL;
1074 if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
1075 for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
1076 value = &key->values[index];
1077 value->name = new_name;
1078 value->namelen = name->len;
1079 value->len = 0;
1080 value->data = NULL;
1081 return value;
1084 /* set a key value */
1085 static void set_value( struct key *key, const struct unicode_str *name,
1086 int type, const void *data, data_size_t len )
1088 struct key_value *value;
1089 void *ptr = NULL;
1090 int index;
1092 if ((value = find_value( key, name, &index )))
1094 /* check if the new value is identical to the existing one */
1095 if (value->type == type && value->len == len &&
1096 value->data && !memcmp( value->data, data, len ))
1098 if (debug_level > 1) dump_operation( key, value, "Skip setting" );
1099 return;
1103 if (key->flags & KEY_SYMLINK)
1105 if (type != REG_LINK || name->len != symlink_str.len ||
1106 memicmpW( name->str, symlink_str.str, name->len / sizeof(WCHAR) ))
1108 set_error( STATUS_ACCESS_DENIED );
1109 return;
1113 if (len && !(ptr = memdup( data, len ))) return;
1115 if (!value)
1117 if (!(value = insert_value( key, name, index )))
1119 free( ptr );
1120 return;
1123 else free( value->data ); /* already existing, free previous data */
1125 value->type = type;
1126 value->len = len;
1127 value->data = ptr;
1128 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1129 if (debug_level > 1) dump_operation( key, value, "Set" );
1132 /* get a key value */
1133 static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
1135 struct key_value *value;
1136 int index;
1138 if ((value = find_value( key, name, &index )))
1140 *type = value->type;
1141 *len = value->len;
1142 if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
1143 if (debug_level > 1) dump_operation( key, value, "Get" );
1145 else
1147 *type = -1;
1148 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1152 /* enumerate a key value */
1153 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
1155 struct key_value *value;
1157 if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
1158 else
1160 void *data;
1161 data_size_t namelen, maxlen;
1163 value = &key->values[i];
1164 reply->type = value->type;
1165 namelen = value->namelen;
1167 switch(info_class)
1169 case KeyValueBasicInformation:
1170 reply->total = namelen;
1171 break;
1172 case KeyValueFullInformation:
1173 reply->total = namelen + value->len;
1174 break;
1175 case KeyValuePartialInformation:
1176 reply->total = value->len;
1177 namelen = 0;
1178 break;
1179 default:
1180 set_error( STATUS_INVALID_PARAMETER );
1181 return;
1184 maxlen = min( reply->total, get_reply_max_size() );
1185 if (maxlen && ((data = set_reply_data_size( maxlen ))))
1187 if (maxlen > namelen)
1189 reply->namelen = namelen;
1190 memcpy( data, value->name, namelen );
1191 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
1193 else
1195 reply->namelen = maxlen;
1196 memcpy( data, value->name, maxlen );
1199 if (debug_level > 1) dump_operation( key, value, "Enum" );
1203 /* delete a value */
1204 static void delete_value( struct key *key, const struct unicode_str *name )
1206 struct key_value *value;
1207 int i, index, nb_values;
1209 if (!(value = find_value( key, name, &index )))
1211 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1212 return;
1214 if (debug_level > 1) dump_operation( key, value, "Delete" );
1215 free( value->name );
1216 free( value->data );
1217 for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
1218 key->last_value--;
1219 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1221 /* try to shrink the array */
1222 nb_values = key->nb_values;
1223 if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
1225 struct key_value *new_val;
1226 nb_values -= nb_values / 3; /* shrink by 33% */
1227 if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
1228 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
1229 key->values = new_val;
1230 key->nb_values = nb_values;
1234 /* get the registry key corresponding to an hkey handle */
1235 static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1237 struct key *key = (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1239 if (key && key->flags & KEY_DELETED)
1241 set_error( STATUS_KEY_DELETED );
1242 release_object( key );
1243 key = NULL;
1245 return key;
1248 /* get the registry key corresponding to a parent key handle */
1249 static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
1251 if (!hkey) return (struct key *)grab_object( root_key );
1252 return get_hkey_obj( hkey, 0 );
1255 /* read a line from the input file */
1256 static int read_next_line( struct file_load_info *info )
1258 char *newbuf;
1259 int newlen, pos = 0;
1261 info->line++;
1262 for (;;)
1264 if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1265 return (pos != 0); /* EOF */
1266 pos = strlen(info->buffer);
1267 if (info->buffer[pos-1] == '\n')
1269 /* got a full line */
1270 info->buffer[--pos] = 0;
1271 if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1272 return 1;
1274 if (pos < info->len - 1) return 1; /* EOF but something was read */
1276 /* need to enlarge the buffer */
1277 newlen = info->len + info->len / 2;
1278 if (!(newbuf = realloc( info->buffer, newlen )))
1280 set_error( STATUS_NO_MEMORY );
1281 return -1;
1283 info->buffer = newbuf;
1284 info->len = newlen;
1288 /* make sure the temp buffer holds enough space */
1289 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1291 WCHAR *tmp;
1292 if (info->tmplen >= size) return 1;
1293 if (!(tmp = realloc( info->tmp, size )))
1295 set_error( STATUS_NO_MEMORY );
1296 return 0;
1298 info->tmp = tmp;
1299 info->tmplen = size;
1300 return 1;
1303 /* report an error while loading an input file */
1304 static void file_read_error( const char *err, struct file_load_info *info )
1306 if (info->filename)
1307 fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1308 else
1309 fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1312 /* convert a data type tag to a value type */
1313 static int get_data_type( const char *buffer, int *type, int *parse_type )
1315 struct data_type { const char *tag; int len; int type; int parse_type; };
1317 static const struct data_type data_types[] =
1318 { /* actual type */ /* type to assume for parsing */
1319 { "\"", 1, REG_SZ, REG_SZ },
1320 { "str:\"", 5, REG_SZ, REG_SZ },
1321 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
1322 { "str(7):\"", 8, REG_MULTI_SZ, REG_SZ },
1323 { "hex:", 4, REG_BINARY, REG_BINARY },
1324 { "dword:", 6, REG_DWORD, REG_DWORD },
1325 { "hex(", 4, -1, REG_BINARY },
1326 { NULL, 0, 0, 0 }
1329 const struct data_type *ptr;
1330 char *end;
1332 for (ptr = data_types; ptr->tag; ptr++)
1334 if (strncmp( ptr->tag, buffer, ptr->len )) continue;
1335 *parse_type = ptr->parse_type;
1336 if ((*type = ptr->type) != -1) return ptr->len;
1337 /* "hex(xx):" is special */
1338 *type = (int)strtoul( buffer + 4, &end, 16 );
1339 if ((end <= buffer) || strncmp( end, "):", 2 )) return 0;
1340 return end + 2 - buffer;
1342 return 0;
1345 /* load and create a key from the input file */
1346 static struct key *load_key( struct key *base, const char *buffer, int prefix_len,
1347 struct file_load_info *info, timeout_t *modif )
1349 WCHAR *p;
1350 struct unicode_str name;
1351 int res;
1352 unsigned int mod;
1353 data_size_t len;
1355 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1357 len = info->tmplen;
1358 if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1360 file_read_error( "Malformed key", info );
1361 return NULL;
1363 if (sscanf( buffer + res, " %u", &mod ) == 1)
1364 *modif = (timeout_t)mod * TICKS_PER_SEC + ticks_1601_to_1970;
1365 else
1366 *modif = current_time;
1368 p = info->tmp;
1369 while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1371 if (!*p)
1373 if (prefix_len > 1)
1375 file_read_error( "Malformed key", info );
1376 return NULL;
1378 /* empty key name, return base key */
1379 return (struct key *)grab_object( base );
1381 name.str = p;
1382 name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1383 return create_key_recursive( base, &name, 0 );
1386 /* update the modification time of a key (and its parents) after it has been loaded from a file */
1387 static void update_key_time( struct key *key, timeout_t modif )
1389 while (key && !key->modif)
1391 key->modif = modif;
1392 key = key->parent;
1396 /* load a global option from the input file */
1397 static int load_global_option( const char *buffer, struct file_load_info *info )
1399 const char *p;
1401 if (!strncmp( buffer, "#arch=", 6 ))
1403 enum prefix_type type;
1404 p = buffer + 6;
1405 if (!strcmp( p, "win32" )) type = PREFIX_32BIT;
1406 else if (!strcmp( p, "win64" )) type = PREFIX_64BIT;
1407 else
1409 file_read_error( "Unknown architecture", info );
1410 set_error( STATUS_NOT_REGISTRY_FILE );
1411 return 0;
1413 if (prefix_type == PREFIX_UNKNOWN) prefix_type = type;
1414 else if (type != prefix_type)
1416 file_read_error( "Mismatched architecture", info );
1417 set_error( STATUS_NOT_REGISTRY_FILE );
1418 return 0;
1421 /* ignore unknown options */
1422 return 1;
1425 /* load a key option from the input file */
1426 static int load_key_option( struct key *key, const char *buffer, struct file_load_info *info )
1428 const char *p;
1429 data_size_t len;
1431 if (!strncmp( buffer, "#time=", 6 ))
1433 timeout_t modif = 0;
1434 for (p = buffer + 6; *p; p++)
1436 if (*p >= '0' && *p <= '9') modif = (modif << 4) | (*p - '0');
1437 else if (*p >= 'A' && *p <= 'F') modif = (modif << 4) | (*p - 'A' + 10);
1438 else if (*p >= 'a' && *p <= 'f') modif = (modif << 4) | (*p - 'a' + 10);
1439 else break;
1441 update_key_time( key, modif );
1443 if (!strncmp( buffer, "#class=", 7 ))
1445 p = buffer + 7;
1446 if (*p++ != '"') return 0;
1447 if (!get_file_tmp_space( info, strlen(p) * sizeof(WCHAR) )) return 0;
1448 len = info->tmplen;
1449 if (parse_strW( info->tmp, &len, p, '\"' ) == -1) return 0;
1450 free( key->class );
1451 if (!(key->class = memdup( info->tmp, len ))) len = 0;
1452 key->classlen = len;
1454 if (!strncmp( buffer, "#link", 5 )) key->flags |= KEY_SYMLINK;
1455 /* ignore unknown options */
1456 return 1;
1459 /* parse a comma-separated list of hex digits */
1460 static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1462 const char *p = buffer;
1463 data_size_t count = 0;
1464 char *end;
1466 while (isxdigit(*p))
1468 unsigned int val = strtoul( p, &end, 16 );
1469 if (end == p || val > 0xff) return -1;
1470 if (count++ >= *len) return -1; /* dest buffer overflow */
1471 *dest++ = val;
1472 p = end;
1473 while (isspace(*p)) p++;
1474 if (*p == ',') p++;
1475 while (isspace(*p)) p++;
1477 *len = count;
1478 return p - buffer;
1481 /* parse a value name and create the corresponding value */
1482 static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1483 struct file_load_info *info )
1485 struct key_value *value;
1486 struct unicode_str name;
1487 int index;
1489 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1490 name.str = info->tmp;
1491 name.len = info->tmplen;
1492 if (buffer[0] == '@')
1494 name.len = 0;
1495 *len = 1;
1497 else
1499 int r = parse_strW( info->tmp, &name.len, buffer + 1, '\"' );
1500 if (r == -1) goto error;
1501 *len = r + 1; /* for initial quote */
1502 name.len -= sizeof(WCHAR); /* terminating null */
1504 while (isspace(buffer[*len])) (*len)++;
1505 if (buffer[*len] != '=') goto error;
1506 (*len)++;
1507 while (isspace(buffer[*len])) (*len)++;
1508 if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1509 return value;
1511 error:
1512 file_read_error( "Malformed value name", info );
1513 return NULL;
1516 /* load a value from the input file */
1517 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1519 DWORD dw;
1520 void *ptr, *newptr;
1521 int res, type, parse_type;
1522 data_size_t maxlen, len;
1523 struct key_value *value;
1525 if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1526 if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1527 buffer += len + res;
1529 switch(parse_type)
1531 case REG_SZ:
1532 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return 0;
1533 len = info->tmplen;
1534 if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1535 ptr = info->tmp;
1536 break;
1537 case REG_DWORD:
1538 dw = strtoul( buffer, NULL, 16 );
1539 ptr = &dw;
1540 len = sizeof(dw);
1541 break;
1542 case REG_BINARY: /* hex digits */
1543 len = 0;
1544 for (;;)
1546 maxlen = 1 + strlen(buffer) / 2; /* at least 2 chars for one hex byte */
1547 if (!get_file_tmp_space( info, len + maxlen )) return 0;
1548 if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1549 len += maxlen;
1550 buffer += res;
1551 while (isspace(*buffer)) buffer++;
1552 if (!*buffer) break;
1553 if (*buffer != '\\') goto error;
1554 if (read_next_line( info) != 1) goto error;
1555 buffer = info->buffer;
1556 while (isspace(*buffer)) buffer++;
1558 ptr = info->tmp;
1559 break;
1560 default:
1561 assert(0);
1562 ptr = NULL; /* keep compiler quiet */
1563 break;
1566 if (!len) newptr = NULL;
1567 else if (!(newptr = memdup( ptr, len ))) return 0;
1569 free( value->data );
1570 value->data = newptr;
1571 value->len = len;
1572 value->type = type;
1573 return 1;
1575 error:
1576 file_read_error( "Malformed value", info );
1577 free( value->data );
1578 value->data = NULL;
1579 value->len = 0;
1580 value->type = REG_NONE;
1581 return 0;
1584 /* return the length (in path elements) of name that is part of the key name */
1585 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1586 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1588 WCHAR *p;
1589 int res;
1590 data_size_t len;
1592 if (!get_file_tmp_space( info, strlen(name) * sizeof(WCHAR) )) return 0;
1594 len = info->tmplen;
1595 if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1597 file_read_error( "Malformed key", info );
1598 return 0;
1600 for (p = info->tmp; *p; p++) if (*p == '\\') break;
1601 len = (p - info->tmp) * sizeof(WCHAR);
1602 for (res = 1; key != root_key; res++)
1604 if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1605 key = key->parent;
1607 if (key == root_key) res = 0; /* no matching name */
1608 return res;
1611 /* load all the keys from the input file */
1612 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1613 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1615 struct key *subkey = NULL;
1616 struct file_load_info info;
1617 timeout_t modif = current_time;
1618 char *p;
1620 info.filename = filename;
1621 info.file = f;
1622 info.len = 4;
1623 info.tmplen = 4;
1624 info.line = 0;
1625 if (!(info.buffer = mem_alloc( info.len ))) return;
1626 if (!(info.tmp = mem_alloc( info.tmplen )))
1628 free( info.buffer );
1629 return;
1632 if ((read_next_line( &info ) != 1) ||
1633 strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1635 set_error( STATUS_NOT_REGISTRY_FILE );
1636 goto done;
1639 while (read_next_line( &info ) == 1)
1641 p = info.buffer;
1642 while (*p && isspace(*p)) p++;
1643 switch(*p)
1645 case '[': /* new key */
1646 if (subkey)
1648 update_key_time( subkey, modif );
1649 release_object( subkey );
1651 if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1652 if (!(subkey = load_key( key, p + 1, prefix_len, &info, &modif )))
1653 file_read_error( "Error creating key", &info );
1654 break;
1655 case '@': /* default value */
1656 case '\"': /* value */
1657 if (subkey) load_value( subkey, p, &info );
1658 else file_read_error( "Value without key", &info );
1659 break;
1660 case '#': /* option */
1661 if (subkey) load_key_option( subkey, p, &info );
1662 else if (!load_global_option( p, &info )) goto done;
1663 break;
1664 case ';': /* comment */
1665 case 0: /* empty line */
1666 break;
1667 default:
1668 file_read_error( "Unrecognized input", &info );
1669 break;
1673 done:
1674 if (subkey)
1676 update_key_time( subkey, modif );
1677 release_object( subkey );
1679 free( info.buffer );
1680 free( info.tmp );
1683 /* load a part of the registry from a file */
1684 static void load_registry( struct key *key, obj_handle_t handle )
1686 struct file *file;
1687 int fd;
1689 if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1690 fd = dup( get_file_unix_fd( file ) );
1691 release_object( file );
1692 if (fd != -1)
1694 FILE *f = fdopen( fd, "r" );
1695 if (f)
1697 load_keys( key, NULL, f, -1 );
1698 fclose( f );
1700 else file_set_error();
1704 /* load one of the initial registry files */
1705 static int load_init_registry_from_file( const char *filename, struct key *key )
1707 FILE *f;
1709 if ((f = fopen( filename, "r" )))
1711 load_keys( key, filename, f, 0 );
1712 fclose( f );
1713 if (get_error() == STATUS_NOT_REGISTRY_FILE)
1715 fprintf( stderr, "%s is not a valid registry file\n", filename );
1716 return 1;
1720 assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1722 save_branch_info[save_branch_count].path = filename;
1723 save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1724 make_object_static( &key->obj );
1725 return (f != NULL);
1728 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1730 static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1731 static const WCHAR formatW[] = {'-','%','u',0};
1732 WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1733 WCHAR *p = buffer;
1734 unsigned int i;
1736 strcpyW( p, prefixW );
1737 p += strlenW( prefixW );
1738 p += sprintfW( p, formatW, sid->Revision );
1739 p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1740 sid->IdentifierAuthority.Value[4] ),
1741 MAKEWORD( sid->IdentifierAuthority.Value[3],
1742 sid->IdentifierAuthority.Value[2] )));
1743 for (i = 0; i < sid->SubAuthorityCount; i++)
1744 p += sprintfW( p, formatW, sid->SubAuthority[i] );
1746 path->len = (p - buffer) * sizeof(WCHAR);
1747 path->str = p = memdup( buffer, path->len );
1748 return p;
1751 /* get the cpu architectures that can be supported in the current prefix */
1752 unsigned int get_prefix_cpu_mask(void)
1754 /* Allowed server/client/prefix combinations:
1756 * prefix
1757 * 32 64
1758 * server +------+------+ client
1759 * | ok | fail | 32
1760 * 32 +------+------+---
1761 * | fail | fail | 64
1762 * ---+------+------+---
1763 * | ok | ok | 32
1764 * 64 +------+------+---
1765 * | fail | ok | 64
1766 * ---+------+------+---
1768 switch (prefix_type)
1770 case PREFIX_64BIT:
1771 /* 64-bit prefix requires 64-bit server */
1772 return sizeof(void *) > sizeof(int) ? ~0 : 0;
1773 case PREFIX_32BIT:
1774 default:
1775 return ~CPU_64BIT_MASK; /* only 32-bit cpus supported on 32-bit prefix */
1779 /* registry initialisation */
1780 void init_registry(void)
1782 static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1783 static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1784 static const WCHAR classes[] = {'S','o','f','t','w','a','r','e','\\',
1785 'C','l','a','s','s','e','s','\\',
1786 'W','o','w','6','4','3','2','N','o','d','e'};
1787 static const struct unicode_str root_name = { NULL, 0 };
1788 static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1789 static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1790 static const struct unicode_str classes_name = { classes, sizeof(classes) };
1792 WCHAR *current_user_path;
1793 struct unicode_str current_user_str;
1794 struct key *key, *hklm, *hkcu;
1796 /* switch to the config dir */
1798 if (fchdir( config_dir_fd ) == -1) fatal_error( "chdir to config dir: %s\n", strerror( errno ));
1800 /* create the root key */
1801 root_key = alloc_key( &root_name, current_time );
1802 assert( root_key );
1803 make_object_static( &root_key->obj );
1805 /* load system.reg into Registry\Machine */
1807 if (!(hklm = create_key_recursive( root_key, &HKLM_name, current_time )))
1808 fatal_error( "could not create Machine registry key\n" );
1810 if (!load_init_registry_from_file( "system.reg", hklm ))
1811 prefix_type = sizeof(void *) > sizeof(int) ? PREFIX_64BIT : PREFIX_32BIT;
1812 else if (prefix_type == PREFIX_UNKNOWN)
1813 prefix_type = PREFIX_32BIT;
1815 /* load userdef.reg into Registry\User\.Default */
1817 if (!(key = create_key_recursive( root_key, &HKU_name, current_time )))
1818 fatal_error( "could not create User\\.Default registry key\n" );
1820 load_init_registry_from_file( "userdef.reg", key );
1821 release_object( key );
1823 /* load user.reg into HKEY_CURRENT_USER */
1825 /* FIXME: match default user in token.c. should get from process token instead */
1826 current_user_path = format_user_registry_path( security_local_user_sid, &current_user_str );
1827 if (!current_user_path ||
1828 !(hkcu = create_key_recursive( root_key, &current_user_str, current_time )))
1829 fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1830 free( current_user_path );
1831 load_init_registry_from_file( "user.reg", hkcu );
1833 /* set the shared flag on Software\Classes\Wow6432Node */
1834 if (prefix_type == PREFIX_64BIT)
1836 if ((key = create_key_recursive( hklm, &classes_name, current_time )))
1838 key->flags |= KEY_WOWSHARE;
1839 release_object( key );
1841 /* FIXME: handle HKCU too */
1844 release_object( hklm );
1845 release_object( hkcu );
1847 /* start the periodic save timer */
1848 set_periodic_save_timer();
1850 /* go back to the server dir */
1851 if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
1854 /* save a registry branch to a file */
1855 static void save_all_subkeys( struct key *key, FILE *f )
1857 fprintf( f, "WINE REGISTRY Version 2\n" );
1858 fprintf( f, ";; All keys relative to " );
1859 dump_path( key, NULL, f );
1860 fprintf( f, "\n" );
1861 switch (prefix_type)
1863 case PREFIX_32BIT:
1864 fprintf( f, "\n#arch=win32\n" );
1865 break;
1866 case PREFIX_64BIT:
1867 fprintf( f, "\n#arch=win64\n" );
1868 break;
1869 default:
1870 break;
1872 save_subkeys( key, key, f );
1875 /* save a registry branch to a file handle */
1876 static void save_registry( struct key *key, obj_handle_t handle )
1878 struct file *file;
1879 int fd;
1881 if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1882 fd = dup( get_file_unix_fd( file ) );
1883 release_object( file );
1884 if (fd != -1)
1886 FILE *f = fdopen( fd, "w" );
1887 if (f)
1889 save_all_subkeys( key, f );
1890 if (fclose( f )) file_set_error();
1892 else
1894 file_set_error();
1895 close( fd );
1900 /* save a registry branch to a file */
1901 static int save_branch( struct key *key, const char *path )
1903 struct stat st;
1904 char *p, *tmp = NULL;
1905 int fd, count = 0, ret = 0;
1906 FILE *f;
1908 if (!(key->flags & KEY_DIRTY))
1910 if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1911 return 1;
1914 /* test the file type */
1916 if ((fd = open( path, O_WRONLY )) != -1)
1918 /* if file is not a regular file or has multiple links or is accessed
1919 * via symbolic links, write directly into it; otherwise use a temp file */
1920 if (!lstat( path, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1))
1922 ftruncate( fd, 0 );
1923 goto save;
1925 close( fd );
1928 /* create a temp file in the same directory */
1930 if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1931 strcpy( tmp, path );
1932 if ((p = strrchr( tmp, '/' ))) p++;
1933 else p = tmp;
1934 for (;;)
1936 sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1937 if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1938 if (errno != EEXIST) goto done;
1939 close( fd );
1942 /* now save to it */
1944 save:
1945 if (!(f = fdopen( fd, "w" )))
1947 if (tmp) unlink( tmp );
1948 close( fd );
1949 goto done;
1952 if (debug_level > 1)
1954 fprintf( stderr, "%s: ", path );
1955 dump_operation( key, NULL, "saving" );
1958 save_all_subkeys( key, f );
1959 ret = !fclose(f);
1961 if (tmp)
1963 /* if successfully written, rename to final name */
1964 if (ret) ret = !rename( tmp, path );
1965 if (!ret) unlink( tmp );
1968 done:
1969 free( tmp );
1970 if (ret) make_clean( key );
1971 return ret;
1974 /* periodic saving of the registry */
1975 static void periodic_save( void *arg )
1977 int i;
1979 if (fchdir( config_dir_fd ) == -1) return;
1980 save_timeout_user = NULL;
1981 for (i = 0; i < save_branch_count; i++)
1982 save_branch( save_branch_info[i].key, save_branch_info[i].path );
1983 if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
1984 set_periodic_save_timer();
1987 /* start the periodic save timer */
1988 static void set_periodic_save_timer(void)
1990 if (save_timeout_user) remove_timeout_user( save_timeout_user );
1991 save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
1994 /* save the modified registry branches to disk */
1995 void flush_registry(void)
1997 int i;
1999 if (fchdir( config_dir_fd ) == -1) return;
2000 for (i = 0; i < save_branch_count; i++)
2002 if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
2004 fprintf( stderr, "wineserver: could not save registry branch to %s",
2005 save_branch_info[i].path );
2006 perror( " " );
2009 if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
2012 /* determine if the thread is wow64 (32-bit client running on 64-bit prefix) */
2013 static int is_wow64_thread( struct thread *thread )
2015 return (prefix_type == PREFIX_64BIT && !(CPU_FLAG(thread->process->cpu) & CPU_64BIT_MASK));
2019 /* create a registry key */
2020 DECL_HANDLER(create_key)
2022 struct key *key = NULL, *parent;
2023 struct unicode_str name, class;
2024 unsigned int access = req->access;
2026 if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
2028 reply->hkey = 0;
2030 if (req->namelen > get_req_data_size())
2032 set_error( STATUS_INVALID_PARAMETER );
2033 return;
2035 class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
2036 class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
2037 get_req_path( &name, !req->parent );
2038 if (name.str > class.str)
2040 set_error( STATUS_INVALID_PARAMETER );
2041 return;
2043 name.len = (class.str - name.str) * sizeof(WCHAR);
2045 /* NOTE: no access rights are required from the parent handle to create a key */
2046 if ((parent = get_parent_hkey_obj( req->parent )))
2048 if ((key = create_key( parent, &name, &class, req->options, access,
2049 req->attributes, &reply->created )))
2051 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
2052 release_object( key );
2054 release_object( parent );
2058 /* open a registry key */
2059 DECL_HANDLER(open_key)
2061 struct key *key, *parent;
2062 struct unicode_str name;
2063 unsigned int access = req->access;
2065 if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
2067 reply->hkey = 0;
2068 /* NOTE: no access rights are required to open the parent key, only the child key */
2069 if ((parent = get_parent_hkey_obj( req->parent )))
2071 get_req_path( &name, !req->parent );
2072 if ((key = open_key( parent, &name, access, req->attributes )))
2074 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
2075 release_object( key );
2077 release_object( parent );
2081 /* delete a registry key */
2082 DECL_HANDLER(delete_key)
2084 struct key *key;
2086 if ((key = get_hkey_obj( req->hkey, DELETE )))
2088 delete_key( key, 0);
2089 release_object( key );
2093 /* flush a registry key */
2094 DECL_HANDLER(flush_key)
2096 struct key *key = get_hkey_obj( req->hkey, 0 );
2097 if (key)
2099 /* we don't need to do anything here with the current implementation */
2100 release_object( key );
2104 /* enumerate registry subkeys */
2105 DECL_HANDLER(enum_key)
2107 struct key *key;
2109 if ((key = get_hkey_obj( req->hkey,
2110 req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
2112 enum_key( key, req->index, req->info_class, reply );
2113 release_object( key );
2117 /* set a value of a registry key */
2118 DECL_HANDLER(set_key_value)
2120 struct key *key;
2121 struct unicode_str name;
2123 if (req->namelen > get_req_data_size())
2125 set_error( STATUS_INVALID_PARAMETER );
2126 return;
2128 name.str = get_req_data();
2129 name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2131 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2133 data_size_t datalen = get_req_data_size() - req->namelen;
2134 const char *data = (const char *)get_req_data() + req->namelen;
2136 set_value( key, &name, req->type, data, datalen );
2137 release_object( key );
2141 /* retrieve the value of a registry key */
2142 DECL_HANDLER(get_key_value)
2144 struct key *key;
2145 struct unicode_str name;
2147 reply->total = 0;
2148 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2150 get_req_unicode_str( &name );
2151 get_value( key, &name, &reply->type, &reply->total );
2152 release_object( key );
2156 /* enumerate the value of a registry key */
2157 DECL_HANDLER(enum_key_value)
2159 struct key *key;
2161 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2163 enum_value( key, req->index, req->info_class, reply );
2164 release_object( key );
2168 /* delete a value of a registry key */
2169 DECL_HANDLER(delete_key_value)
2171 struct key *key;
2172 struct unicode_str name;
2174 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2176 get_req_unicode_str( &name );
2177 delete_value( key, &name );
2178 release_object( key );
2182 /* load a registry branch from a file */
2183 DECL_HANDLER(load_registry)
2185 struct key *key, *parent;
2186 struct token *token = thread_get_impersonation_token( current );
2187 struct unicode_str name;
2189 const LUID_AND_ATTRIBUTES privs[] =
2191 { SeBackupPrivilege, 0 },
2192 { SeRestorePrivilege, 0 },
2195 if (!token || !token_check_privileges( token, TRUE, privs,
2196 sizeof(privs)/sizeof(privs[0]), NULL ))
2198 set_error( STATUS_PRIVILEGE_NOT_HELD );
2199 return;
2202 if ((parent = get_parent_hkey_obj( req->hkey )))
2204 int dummy;
2205 get_req_path( &name, !req->hkey );
2206 if ((key = create_key( parent, &name, NULL, 0, KEY_WOW64_64KEY, 0, &dummy )))
2208 load_registry( key, req->file );
2209 release_object( key );
2211 release_object( parent );
2215 DECL_HANDLER(unload_registry)
2217 struct key *key;
2218 struct token *token = thread_get_impersonation_token( current );
2220 const LUID_AND_ATTRIBUTES privs[] =
2222 { SeBackupPrivilege, 0 },
2223 { SeRestorePrivilege, 0 },
2226 if (!token || !token_check_privileges( token, TRUE, privs,
2227 sizeof(privs)/sizeof(privs[0]), NULL ))
2229 set_error( STATUS_PRIVILEGE_NOT_HELD );
2230 return;
2233 if ((key = get_hkey_obj( req->hkey, 0 )))
2235 delete_key( key, 1 ); /* FIXME */
2236 release_object( key );
2240 /* save a registry branch to a file */
2241 DECL_HANDLER(save_registry)
2243 struct key *key;
2245 if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
2247 set_error( STATUS_PRIVILEGE_NOT_HELD );
2248 return;
2251 if ((key = get_hkey_obj( req->hkey, 0 )))
2253 save_registry( key, req->file );
2254 release_object( key );
2258 /* add a registry key change notification */
2259 DECL_HANDLER(set_registry_notification)
2261 struct key *key;
2262 struct event *event;
2263 struct notify *notify;
2265 key = get_hkey_obj( req->hkey, KEY_NOTIFY );
2266 if (key)
2268 event = get_event_obj( current->process, req->event, SYNCHRONIZE );
2269 if (event)
2271 notify = find_notify( key, current->process, req->hkey );
2272 if (notify)
2274 if (notify->event)
2275 release_object( notify->event );
2276 grab_object( event );
2277 notify->event = event;
2279 else
2281 notify = mem_alloc( sizeof(*notify) );
2282 if (notify)
2284 grab_object( event );
2285 notify->event = event;
2286 notify->subtree = req->subtree;
2287 notify->filter = req->filter;
2288 notify->hkey = req->hkey;
2289 notify->process = current->process;
2290 list_add_head( &key->notify_list, &notify->entry );
2293 if (notify)
2295 reset_event( event );
2296 set_error( STATUS_PENDING );
2298 release_object( event );
2300 release_object( key );