shell32/tests: Add tests for SHGetStockIconInfo.
[wine.git] / server / registry.c
blobeb182f2112252e188485633be0d23b224f02af97
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) + offsetof( ACCESS_ALLOWED_ACE, SidStart ) + users_sid_len;
351 ACCESS_ALLOWED_ACE *aaa;
352 ACL *dacl;
354 key_default_sd = mem_alloc( sizeof(*key_default_sd) + 2 * admins_sid_len + dacl_len );
355 key_default_sd->control = SE_DACL_PRESENT;
356 key_default_sd->owner_len = admins_sid_len;
357 key_default_sd->group_len = admins_sid_len;
358 key_default_sd->sacl_len = 0;
359 key_default_sd->dacl_len = dacl_len;
360 memcpy( key_default_sd + 1, security_builtin_admins_sid, admins_sid_len );
361 memcpy( (char *)(key_default_sd + 1) + admins_sid_len, security_builtin_admins_sid, admins_sid_len );
363 dacl = (ACL *)((char *)(key_default_sd + 1) + 2 * admins_sid_len);
364 dacl->AclRevision = ACL_REVISION;
365 dacl->Sbz1 = 0;
366 dacl->AclSize = dacl_len;
367 dacl->AceCount = 1;
368 dacl->Sbz2 = 0;
369 aaa = (ACCESS_ALLOWED_ACE *)(dacl + 1);
370 aaa->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
371 aaa->Header.AceFlags = INHERIT_ONLY_ACE | CONTAINER_INHERIT_ACE;
372 aaa->Header.AceSize = offsetof( ACCESS_ALLOWED_ACE, SidStart ) + users_sid_len;
373 aaa->Mask = GENERIC_READ;
374 memcpy( &aaa->SidStart, security_builtin_users_sid, users_sid_len );
376 return key_default_sd;
379 /* close the notification associated with a handle */
380 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
382 struct key * key = (struct key *) obj;
383 struct notify *notify = find_notify( key, process, handle );
384 if (notify) do_notification( key, notify, 1 );
385 return 1; /* ok to close */
388 static void key_destroy( struct object *obj )
390 int i;
391 struct list *ptr;
392 struct key *key = (struct key *)obj;
393 assert( obj->ops == &key_ops );
395 free( key->name );
396 free( key->class );
397 for (i = 0; i <= key->last_value; i++)
399 free( key->values[i].name );
400 free( key->values[i].data );
402 free( key->values );
403 for (i = 0; i <= key->last_subkey; i++)
405 key->subkeys[i]->parent = NULL;
406 release_object( key->subkeys[i] );
408 free( key->subkeys );
409 /* unconditionally notify everything waiting on this key */
410 while ((ptr = list_head( &key->notify_list )))
412 struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
413 do_notification( key, notify, 1 );
417 /* get the request vararg as registry path */
418 static inline void get_req_path( struct unicode_str *str, int skip_root )
420 str->str = get_req_data();
421 str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
423 if (skip_root && str->len >= sizeof(root_name) &&
424 !memicmpW( str->str, root_name, sizeof(root_name)/sizeof(WCHAR) ))
426 str->str += sizeof(root_name)/sizeof(WCHAR);
427 str->len -= sizeof(root_name);
431 /* return the next token in a given path */
432 /* token->str must point inside the path, or be NULL for the first call */
433 static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
435 data_size_t i = 0, len = path->len / sizeof(WCHAR);
437 if (!token->str) /* first time */
439 /* path cannot start with a backslash */
440 if (len && path->str[0] == '\\')
442 set_error( STATUS_OBJECT_PATH_INVALID );
443 return NULL;
446 else
448 i = token->str - path->str;
449 i += token->len / sizeof(WCHAR);
450 while (i < len && path->str[i] == '\\') i++;
452 token->str = path->str + i;
453 while (i < len && path->str[i] != '\\') i++;
454 token->len = (path->str + i - token->str) * sizeof(WCHAR);
455 return token;
458 /* allocate a key object */
459 static struct key *alloc_key( const struct unicode_str *name, timeout_t modif )
461 struct key *key;
462 if ((key = alloc_object( &key_ops )))
464 key->name = NULL;
465 key->class = NULL;
466 key->namelen = name->len;
467 key->classlen = 0;
468 key->flags = 0;
469 key->last_subkey = -1;
470 key->nb_subkeys = 0;
471 key->subkeys = NULL;
472 key->nb_values = 0;
473 key->last_value = -1;
474 key->values = NULL;
475 key->modif = modif;
476 key->parent = NULL;
477 list_init( &key->notify_list );
478 if (name->len && !(key->name = memdup( name->str, name->len )))
480 release_object( key );
481 key = NULL;
484 return key;
487 /* mark a key and all its parents as dirty (modified) */
488 static void make_dirty( struct key *key )
490 while (key)
492 if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return; /* nothing to do */
493 key->flags |= KEY_DIRTY;
494 key = key->parent;
498 /* mark a key and all its subkeys as clean (not modified) */
499 static void make_clean( struct key *key )
501 int i;
503 if (key->flags & KEY_VOLATILE) return;
504 if (!(key->flags & KEY_DIRTY)) return;
505 key->flags &= ~KEY_DIRTY;
506 for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
509 /* go through all the notifications and send them if necessary */
510 static void check_notify( struct key *key, unsigned int change, int not_subtree )
512 struct list *ptr, *next;
514 LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
516 struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
517 if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
518 do_notification( key, n, 0 );
522 /* update key modification time */
523 static void touch_key( struct key *key, unsigned int change )
525 struct key *k;
527 key->modif = current_time;
528 make_dirty( key );
530 /* do notifications */
531 check_notify( key, change, 1 );
532 for ( k = key->parent; k; k = k->parent )
533 check_notify( k, change & ~REG_NOTIFY_CHANGE_LAST_SET, 0 );
536 /* try to grow the array of subkeys; return 1 if OK, 0 on error */
537 static int grow_subkeys( struct key *key )
539 struct key **new_subkeys;
540 int nb_subkeys;
542 if (key->nb_subkeys)
544 nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2); /* grow by 50% */
545 if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
547 set_error( STATUS_NO_MEMORY );
548 return 0;
551 else
553 nb_subkeys = MIN_VALUES;
554 if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
556 key->subkeys = new_subkeys;
557 key->nb_subkeys = nb_subkeys;
558 return 1;
561 /* allocate a subkey for a given key, and return its index */
562 static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
563 int index, timeout_t modif )
565 struct key *key;
566 int i;
568 if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
570 set_error( STATUS_NAME_TOO_LONG );
571 return NULL;
573 if (parent->last_subkey + 1 == parent->nb_subkeys)
575 /* need to grow the array */
576 if (!grow_subkeys( parent )) return NULL;
578 if ((key = alloc_key( name, modif )) != NULL)
580 key->parent = parent;
581 for (i = ++parent->last_subkey; i > index; i--)
582 parent->subkeys[i] = parent->subkeys[i-1];
583 parent->subkeys[index] = key;
584 if (is_wow6432node( key->name, key->namelen ) && !is_wow6432node( parent->name, parent->namelen ))
585 parent->flags |= KEY_WOW64;
587 return key;
590 /* free a subkey of a given key */
591 static void free_subkey( struct key *parent, int index )
593 struct key *key;
594 int i, nb_subkeys;
596 assert( index >= 0 );
597 assert( index <= parent->last_subkey );
599 key = parent->subkeys[index];
600 for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
601 parent->last_subkey--;
602 key->flags |= KEY_DELETED;
603 key->parent = NULL;
604 if (is_wow6432node( key->name, key->namelen )) parent->flags &= ~KEY_WOW64;
605 release_object( key );
607 /* try to shrink the array */
608 nb_subkeys = parent->nb_subkeys;
609 if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
611 struct key **new_subkeys;
612 nb_subkeys -= nb_subkeys / 3; /* shrink by 33% */
613 if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
614 if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
615 parent->subkeys = new_subkeys;
616 parent->nb_subkeys = nb_subkeys;
620 /* find the named child of a given key and return its index */
621 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
623 int i, min, max, res;
624 data_size_t len;
626 min = 0;
627 max = key->last_subkey;
628 while (min <= max)
630 i = (min + max) / 2;
631 len = min( key->subkeys[i]->namelen, name->len );
632 res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
633 if (!res) res = key->subkeys[i]->namelen - name->len;
634 if (!res)
636 *index = i;
637 return key->subkeys[i];
639 if (res > 0) max = i - 1;
640 else min = i + 1;
642 *index = min; /* this is where we should insert it */
643 return NULL;
646 /* return the wow64 variant of the key, or the key itself if none */
647 static struct key *find_wow64_subkey( struct key *key, const struct unicode_str *name )
649 static const struct unicode_str wow6432node_str = { wow6432node, sizeof(wow6432node) };
650 int index;
652 if (!(key->flags & KEY_WOW64)) return key;
653 if (!is_wow6432node( name->str, name->len ))
655 key = find_subkey( key, &wow6432node_str, &index );
656 assert( key ); /* if KEY_WOW64 is set we must find it */
658 return key;
662 /* follow a symlink and return the resolved key */
663 static struct key *follow_symlink( struct key *key, int iteration )
665 struct unicode_str path, token;
666 struct key_value *value;
667 int index;
669 if (iteration > 16) return NULL;
670 if (!(key->flags & KEY_SYMLINK)) return key;
671 if (!(value = find_value( key, &symlink_str, &index ))) return NULL;
673 path.str = value->data;
674 path.len = (value->len / sizeof(WCHAR)) * sizeof(WCHAR);
675 if (path.len <= sizeof(root_name)) return NULL;
676 if (memicmpW( path.str, root_name, sizeof(root_name)/sizeof(WCHAR) )) return NULL;
677 path.str += sizeof(root_name) / sizeof(WCHAR);
678 path.len -= sizeof(root_name);
680 key = root_key;
681 token.str = NULL;
682 if (!get_path_token( &path, &token )) return NULL;
683 while (token.len)
685 if (!(key = find_subkey( key, &token, &index ))) break;
686 if (!(key = follow_symlink( key, iteration + 1 ))) break;
687 get_path_token( &path, &token );
689 return key;
692 /* open a key until we find an element that doesn't exist */
693 /* helper for open_key and create_key */
694 static struct key *open_key_prefix( struct key *key, const struct unicode_str *name,
695 unsigned int access, struct unicode_str *token, int *index )
697 token->str = NULL;
698 if (!get_path_token( name, token )) return NULL;
699 if (access & KEY_WOW64_32KEY) key = find_wow64_subkey( key, token );
700 while (token->len)
702 struct key *subkey;
703 if (!(subkey = find_subkey( key, token, index )))
705 if ((key->flags & KEY_WOWSHARE) && !(access & KEY_WOW64_64KEY))
707 /* try in the 64-bit parent */
708 key = key->parent;
709 subkey = find_subkey( key, token, index );
712 if (!subkey) break;
713 key = subkey;
714 get_path_token( name, token );
715 if (!token->len) break;
716 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, token );
717 if (!(key = follow_symlink( key, 0 )))
719 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
720 return NULL;
723 return key;
726 /* open a subkey */
727 static struct key *open_key( struct key *key, const struct unicode_str *name, unsigned int access,
728 unsigned int attributes )
730 int index;
731 struct unicode_str token;
733 if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
735 if (token.len)
737 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
738 return NULL;
740 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
741 if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
743 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
744 return NULL;
746 if (debug_level > 1) dump_operation( key, NULL, "Open" );
747 grab_object( key );
748 return key;
751 /* create a subkey */
752 static struct key *create_key( struct key *key, const struct unicode_str *name,
753 const struct unicode_str *class, unsigned int options,
754 unsigned int access, unsigned int attributes, int *created )
756 int index;
757 struct unicode_str token, next;
759 *created = 0;
760 if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
762 if (!token.len) /* the key already exists */
764 if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
765 if (options & REG_OPTION_CREATE_LINK)
767 set_error( STATUS_OBJECT_NAME_COLLISION );
768 return NULL;
770 if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
772 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
773 return NULL;
775 if (debug_level > 1) dump_operation( key, NULL, "Open" );
776 grab_object( key );
777 return key;
780 /* token must be the last path component at this point */
781 next = token;
782 get_path_token( name, &next );
783 if (next.len)
785 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
786 return NULL;
789 if ((key->flags & KEY_VOLATILE) && !(options & REG_OPTION_VOLATILE))
791 set_error( STATUS_CHILD_MUST_BE_VOLATILE );
792 return NULL;
794 *created = 1;
795 make_dirty( key );
796 if (!(key = alloc_subkey( key, &token, index, current_time ))) return NULL;
798 if (options & REG_OPTION_CREATE_LINK) key->flags |= KEY_SYMLINK;
799 if (options & REG_OPTION_VOLATILE) key->flags |= KEY_VOLATILE;
800 else key->flags |= KEY_DIRTY;
802 if (debug_level > 1) dump_operation( key, NULL, "Create" );
803 if (class && class->len)
805 key->classlen = class->len;
806 free(key->class);
807 if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
809 grab_object( key );
810 return key;
813 /* recursively create a subkey (for internal use only) */
814 static struct key *create_key_recursive( struct key *key, const struct unicode_str *name, timeout_t modif )
816 struct key *base;
817 int index;
818 struct unicode_str token;
820 token.str = NULL;
821 if (!get_path_token( name, &token )) return NULL;
822 while (token.len)
824 struct key *subkey;
825 if (!(subkey = find_subkey( key, &token, &index ))) break;
826 key = subkey;
827 if (!(key = follow_symlink( key, 0 )))
829 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
830 return NULL;
832 get_path_token( name, &token );
835 if (token.len)
837 if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
838 base = key;
839 for (;;)
841 get_path_token( name, &token );
842 if (!token.len) break;
843 /* we know the index is always 0 in a new key */
844 if (!(key = alloc_subkey( key, &token, 0, modif )))
846 free_subkey( base, index );
847 return NULL;
852 grab_object( key );
853 return key;
856 /* query information about a key or a subkey */
857 static void enum_key( const struct key *key, int index, int info_class,
858 struct enum_key_reply *reply )
860 int i;
861 data_size_t len, namelen, classlen;
862 data_size_t max_subkey = 0, max_class = 0;
863 data_size_t max_value = 0, max_data = 0;
864 char *data;
866 if (index != -1) /* -1 means use the specified key directly */
868 if ((index < 0) || (index > key->last_subkey))
870 set_error( STATUS_NO_MORE_ENTRIES );
871 return;
873 key = key->subkeys[index];
876 namelen = key->namelen;
877 classlen = key->classlen;
879 switch(info_class)
881 case KeyBasicInformation:
882 classlen = 0; /* only return the name */
883 /* fall through */
884 case KeyNodeInformation:
885 reply->max_subkey = 0;
886 reply->max_class = 0;
887 reply->max_value = 0;
888 reply->max_data = 0;
889 break;
890 case KeyFullInformation:
891 for (i = 0; i <= key->last_subkey; i++)
893 struct key *subkey = key->subkeys[i];
894 len = subkey->namelen / sizeof(WCHAR);
895 if (len > max_subkey) max_subkey = len;
896 len = subkey->classlen / sizeof(WCHAR);
897 if (len > max_class) max_class = len;
899 for (i = 0; i <= key->last_value; i++)
901 len = key->values[i].namelen / sizeof(WCHAR);
902 if (len > max_value) max_value = len;
903 len = key->values[i].len;
904 if (len > max_data) max_data = len;
906 reply->max_subkey = max_subkey;
907 reply->max_class = max_class;
908 reply->max_value = max_value;
909 reply->max_data = max_data;
910 namelen = 0; /* only return the class */
911 break;
912 default:
913 set_error( STATUS_INVALID_PARAMETER );
914 return;
916 reply->subkeys = key->last_subkey + 1;
917 reply->values = key->last_value + 1;
918 reply->modif = key->modif;
919 reply->total = namelen + classlen;
921 len = min( reply->total, get_reply_max_size() );
922 if (len && (data = set_reply_data_size( len )))
924 if (len > namelen)
926 reply->namelen = namelen;
927 memcpy( data, key->name, namelen );
928 memcpy( data + namelen, key->class, len - namelen );
930 else
932 reply->namelen = len;
933 memcpy( data, key->name, len );
936 if (debug_level > 1) dump_operation( key, NULL, "Enum" );
939 /* delete a key and its values */
940 static int delete_key( struct key *key, int recurse )
942 int index;
943 struct key *parent = key->parent;
945 /* must find parent and index */
946 if (key == root_key)
948 set_error( STATUS_ACCESS_DENIED );
949 return -1;
951 assert( parent );
953 while (recurse && (key->last_subkey>=0))
954 if (0 > delete_key(key->subkeys[key->last_subkey], 1))
955 return -1;
957 for (index = 0; index <= parent->last_subkey; index++)
958 if (parent->subkeys[index] == key) break;
959 assert( index <= parent->last_subkey );
961 /* we can only delete a key that has no subkeys */
962 if (key->last_subkey >= 0)
964 set_error( STATUS_ACCESS_DENIED );
965 return -1;
968 if (debug_level > 1) dump_operation( key, NULL, "Delete" );
969 free_subkey( parent, index );
970 touch_key( parent, REG_NOTIFY_CHANGE_NAME );
971 return 0;
974 /* try to grow the array of values; return 1 if OK, 0 on error */
975 static int grow_values( struct key *key )
977 struct key_value *new_val;
978 int nb_values;
980 if (key->nb_values)
982 nb_values = key->nb_values + (key->nb_values / 2); /* grow by 50% */
983 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
985 set_error( STATUS_NO_MEMORY );
986 return 0;
989 else
991 nb_values = MIN_VALUES;
992 if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
994 key->values = new_val;
995 key->nb_values = nb_values;
996 return 1;
999 /* find the named value of a given key and return its index in the array */
1000 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
1002 int i, min, max, res;
1003 data_size_t len;
1005 min = 0;
1006 max = key->last_value;
1007 while (min <= max)
1009 i = (min + max) / 2;
1010 len = min( key->values[i].namelen, name->len );
1011 res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
1012 if (!res) res = key->values[i].namelen - name->len;
1013 if (!res)
1015 *index = i;
1016 return &key->values[i];
1018 if (res > 0) max = i - 1;
1019 else min = i + 1;
1021 *index = min; /* this is where we should insert it */
1022 return NULL;
1025 /* insert a new value; the index must have been returned by find_value */
1026 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
1028 struct key_value *value;
1029 WCHAR *new_name = NULL;
1030 int i;
1032 if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
1034 set_error( STATUS_NAME_TOO_LONG );
1035 return NULL;
1037 if (key->last_value + 1 == key->nb_values)
1039 if (!grow_values( key )) return NULL;
1041 if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
1042 for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
1043 value = &key->values[index];
1044 value->name = new_name;
1045 value->namelen = name->len;
1046 value->len = 0;
1047 value->data = NULL;
1048 return value;
1051 /* set a key value */
1052 static void set_value( struct key *key, const struct unicode_str *name,
1053 int type, const void *data, data_size_t len )
1055 struct key_value *value;
1056 void *ptr = NULL;
1057 int index;
1059 if ((value = find_value( key, name, &index )))
1061 /* check if the new value is identical to the existing one */
1062 if (value->type == type && value->len == len &&
1063 value->data && !memcmp( value->data, data, len ))
1065 if (debug_level > 1) dump_operation( key, value, "Skip setting" );
1066 return;
1070 if (key->flags & KEY_SYMLINK)
1072 if (type != REG_LINK || name->len != symlink_str.len ||
1073 memicmpW( name->str, symlink_str.str, name->len / sizeof(WCHAR) ))
1075 set_error( STATUS_ACCESS_DENIED );
1076 return;
1080 if (len && !(ptr = memdup( data, len ))) return;
1082 if (!value)
1084 if (!(value = insert_value( key, name, index )))
1086 free( ptr );
1087 return;
1090 else free( value->data ); /* already existing, free previous data */
1092 value->type = type;
1093 value->len = len;
1094 value->data = ptr;
1095 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1096 if (debug_level > 1) dump_operation( key, value, "Set" );
1099 /* get a key value */
1100 static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
1102 struct key_value *value;
1103 int index;
1105 if ((value = find_value( key, name, &index )))
1107 *type = value->type;
1108 *len = value->len;
1109 if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
1110 if (debug_level > 1) dump_operation( key, value, "Get" );
1112 else
1114 *type = -1;
1115 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1119 /* enumerate a key value */
1120 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
1122 struct key_value *value;
1124 if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
1125 else
1127 void *data;
1128 data_size_t namelen, maxlen;
1130 value = &key->values[i];
1131 reply->type = value->type;
1132 namelen = value->namelen;
1134 switch(info_class)
1136 case KeyValueBasicInformation:
1137 reply->total = namelen;
1138 break;
1139 case KeyValueFullInformation:
1140 reply->total = namelen + value->len;
1141 break;
1142 case KeyValuePartialInformation:
1143 reply->total = value->len;
1144 namelen = 0;
1145 break;
1146 default:
1147 set_error( STATUS_INVALID_PARAMETER );
1148 return;
1151 maxlen = min( reply->total, get_reply_max_size() );
1152 if (maxlen && ((data = set_reply_data_size( maxlen ))))
1154 if (maxlen > namelen)
1156 reply->namelen = namelen;
1157 memcpy( data, value->name, namelen );
1158 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
1160 else
1162 reply->namelen = maxlen;
1163 memcpy( data, value->name, maxlen );
1166 if (debug_level > 1) dump_operation( key, value, "Enum" );
1170 /* delete a value */
1171 static void delete_value( struct key *key, const struct unicode_str *name )
1173 struct key_value *value;
1174 int i, index, nb_values;
1176 if (!(value = find_value( key, name, &index )))
1178 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1179 return;
1181 if (debug_level > 1) dump_operation( key, value, "Delete" );
1182 free( value->name );
1183 free( value->data );
1184 for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
1185 key->last_value--;
1186 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1188 /* try to shrink the array */
1189 nb_values = key->nb_values;
1190 if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
1192 struct key_value *new_val;
1193 nb_values -= nb_values / 3; /* shrink by 33% */
1194 if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
1195 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
1196 key->values = new_val;
1197 key->nb_values = nb_values;
1201 /* get the registry key corresponding to an hkey handle */
1202 static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1204 struct key *key = (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1206 if (key && key->flags & KEY_DELETED)
1208 set_error( STATUS_KEY_DELETED );
1209 release_object( key );
1210 key = NULL;
1212 return key;
1215 /* get the registry key corresponding to a parent key handle */
1216 static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
1218 if (!hkey) return (struct key *)grab_object( root_key );
1219 return get_hkey_obj( hkey, 0 );
1222 /* read a line from the input file */
1223 static int read_next_line( struct file_load_info *info )
1225 char *newbuf;
1226 int newlen, pos = 0;
1228 info->line++;
1229 for (;;)
1231 if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1232 return (pos != 0); /* EOF */
1233 pos = strlen(info->buffer);
1234 if (info->buffer[pos-1] == '\n')
1236 /* got a full line */
1237 info->buffer[--pos] = 0;
1238 if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1239 return 1;
1241 if (pos < info->len - 1) return 1; /* EOF but something was read */
1243 /* need to enlarge the buffer */
1244 newlen = info->len + info->len / 2;
1245 if (!(newbuf = realloc( info->buffer, newlen )))
1247 set_error( STATUS_NO_MEMORY );
1248 return -1;
1250 info->buffer = newbuf;
1251 info->len = newlen;
1255 /* make sure the temp buffer holds enough space */
1256 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1258 WCHAR *tmp;
1259 if (info->tmplen >= size) return 1;
1260 if (!(tmp = realloc( info->tmp, size )))
1262 set_error( STATUS_NO_MEMORY );
1263 return 0;
1265 info->tmp = tmp;
1266 info->tmplen = size;
1267 return 1;
1270 /* report an error while loading an input file */
1271 static void file_read_error( const char *err, struct file_load_info *info )
1273 if (info->filename)
1274 fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1275 else
1276 fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1279 /* convert a data type tag to a value type */
1280 static int get_data_type( const char *buffer, int *type, int *parse_type )
1282 struct data_type { const char *tag; int len; int type; int parse_type; };
1284 static const struct data_type data_types[] =
1285 { /* actual type */ /* type to assume for parsing */
1286 { "\"", 1, REG_SZ, REG_SZ },
1287 { "str:\"", 5, REG_SZ, REG_SZ },
1288 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
1289 { "str(7):\"", 8, REG_MULTI_SZ, REG_SZ },
1290 { "hex:", 4, REG_BINARY, REG_BINARY },
1291 { "dword:", 6, REG_DWORD, REG_DWORD },
1292 { "hex(", 4, -1, REG_BINARY },
1293 { NULL, 0, 0, 0 }
1296 const struct data_type *ptr;
1297 char *end;
1299 for (ptr = data_types; ptr->tag; ptr++)
1301 if (strncmp( ptr->tag, buffer, ptr->len )) continue;
1302 *parse_type = ptr->parse_type;
1303 if ((*type = ptr->type) != -1) return ptr->len;
1304 /* "hex(xx):" is special */
1305 *type = (int)strtoul( buffer + 4, &end, 16 );
1306 if ((end <= buffer) || strncmp( end, "):", 2 )) return 0;
1307 return end + 2 - buffer;
1309 return 0;
1312 /* load and create a key from the input file */
1313 static struct key *load_key( struct key *base, const char *buffer,
1314 int prefix_len, struct file_load_info *info )
1316 WCHAR *p;
1317 struct unicode_str name;
1318 int res;
1319 unsigned int mod;
1320 timeout_t modif = current_time;
1321 data_size_t len;
1323 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1325 len = info->tmplen;
1326 if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1328 file_read_error( "Malformed key", info );
1329 return NULL;
1331 if (sscanf( buffer + res, " %u", &mod ) == 1)
1332 modif = (timeout_t)mod * TICKS_PER_SEC + ticks_1601_to_1970;
1334 p = info->tmp;
1335 while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1337 if (!*p)
1339 if (prefix_len > 1)
1341 file_read_error( "Malformed key", info );
1342 return NULL;
1344 /* empty key name, return base key */
1345 return (struct key *)grab_object( base );
1347 name.str = p;
1348 name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1349 return create_key_recursive( base, &name, modif );
1352 /* load a global option from the input file */
1353 static int load_global_option( const char *buffer, struct file_load_info *info )
1355 const char *p;
1357 if (!strncmp( buffer, "#arch=", 6 ))
1359 enum prefix_type type;
1360 p = buffer + 6;
1361 if (!strcmp( p, "win32" )) type = PREFIX_32BIT;
1362 else if (!strcmp( p, "win64" )) type = PREFIX_64BIT;
1363 else
1365 file_read_error( "Unknown architecture", info );
1366 set_error( STATUS_NOT_REGISTRY_FILE );
1367 return 0;
1369 if (prefix_type == PREFIX_UNKNOWN) prefix_type = type;
1370 else if (type != prefix_type)
1372 file_read_error( "Mismatched architecture", info );
1373 set_error( STATUS_NOT_REGISTRY_FILE );
1374 return 0;
1377 /* ignore unknown options */
1378 return 1;
1381 /* load a key option from the input file */
1382 static int load_key_option( struct key *key, const char *buffer, struct file_load_info *info )
1384 const char *p;
1385 data_size_t len;
1387 if (!strncmp( buffer, "#class=", 7 ))
1389 p = buffer + 7;
1390 if (*p++ != '"') return 0;
1391 if (!get_file_tmp_space( info, strlen(p) * sizeof(WCHAR) )) return 0;
1392 len = info->tmplen;
1393 if (parse_strW( info->tmp, &len, p, '\"' ) == -1) return 0;
1394 free( key->class );
1395 if (!(key->class = memdup( info->tmp, len ))) len = 0;
1396 key->classlen = len;
1398 if (!strncmp( buffer, "#link", 5 )) key->flags |= KEY_SYMLINK;
1399 /* ignore unknown options */
1400 return 1;
1403 /* parse a comma-separated list of hex digits */
1404 static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1406 const char *p = buffer;
1407 data_size_t count = 0;
1408 char *end;
1410 while (isxdigit(*p))
1412 unsigned int val = strtoul( p, &end, 16 );
1413 if (end == p || val > 0xff) return -1;
1414 if (count++ >= *len) return -1; /* dest buffer overflow */
1415 *dest++ = val;
1416 p = end;
1417 while (isspace(*p)) p++;
1418 if (*p == ',') p++;
1419 while (isspace(*p)) p++;
1421 *len = count;
1422 return p - buffer;
1425 /* parse a value name and create the corresponding value */
1426 static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1427 struct file_load_info *info )
1429 struct key_value *value;
1430 struct unicode_str name;
1431 int index;
1433 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1434 name.str = info->tmp;
1435 name.len = info->tmplen;
1436 if (buffer[0] == '@')
1438 name.len = 0;
1439 *len = 1;
1441 else
1443 int r = parse_strW( info->tmp, &name.len, buffer + 1, '\"' );
1444 if (r == -1) goto error;
1445 *len = r + 1; /* for initial quote */
1446 name.len -= sizeof(WCHAR); /* terminating null */
1448 while (isspace(buffer[*len])) (*len)++;
1449 if (buffer[*len] != '=') goto error;
1450 (*len)++;
1451 while (isspace(buffer[*len])) (*len)++;
1452 if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1453 return value;
1455 error:
1456 file_read_error( "Malformed value name", info );
1457 return NULL;
1460 /* load a value from the input file */
1461 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1463 DWORD dw;
1464 void *ptr, *newptr;
1465 int res, type, parse_type;
1466 data_size_t maxlen, len;
1467 struct key_value *value;
1469 if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1470 if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1471 buffer += len + res;
1473 switch(parse_type)
1475 case REG_SZ:
1476 if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return 0;
1477 len = info->tmplen;
1478 if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1479 ptr = info->tmp;
1480 break;
1481 case REG_DWORD:
1482 dw = strtoul( buffer, NULL, 16 );
1483 ptr = &dw;
1484 len = sizeof(dw);
1485 break;
1486 case REG_BINARY: /* hex digits */
1487 len = 0;
1488 for (;;)
1490 maxlen = 1 + strlen(buffer) / 2; /* at least 2 chars for one hex byte */
1491 if (!get_file_tmp_space( info, len + maxlen )) return 0;
1492 if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1493 len += maxlen;
1494 buffer += res;
1495 while (isspace(*buffer)) buffer++;
1496 if (!*buffer) break;
1497 if (*buffer != '\\') goto error;
1498 if (read_next_line( info) != 1) goto error;
1499 buffer = info->buffer;
1500 while (isspace(*buffer)) buffer++;
1502 ptr = info->tmp;
1503 break;
1504 default:
1505 assert(0);
1506 ptr = NULL; /* keep compiler quiet */
1507 break;
1510 if (!len) newptr = NULL;
1511 else if (!(newptr = memdup( ptr, len ))) return 0;
1513 free( value->data );
1514 value->data = newptr;
1515 value->len = len;
1516 value->type = type;
1517 return 1;
1519 error:
1520 file_read_error( "Malformed value", info );
1521 free( value->data );
1522 value->data = NULL;
1523 value->len = 0;
1524 value->type = REG_NONE;
1525 return 0;
1528 /* return the length (in path elements) of name that is part of the key name */
1529 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1530 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1532 WCHAR *p;
1533 int res;
1534 data_size_t len;
1536 if (!get_file_tmp_space( info, strlen(name) * sizeof(WCHAR) )) return 0;
1538 len = info->tmplen;
1539 if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1541 file_read_error( "Malformed key", info );
1542 return 0;
1544 for (p = info->tmp; *p; p++) if (*p == '\\') break;
1545 len = (p - info->tmp) * sizeof(WCHAR);
1546 for (res = 1; key != root_key; res++)
1548 if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1549 key = key->parent;
1551 if (key == root_key) res = 0; /* no matching name */
1552 return res;
1555 /* load all the keys from the input file */
1556 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1557 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1559 struct key *subkey = NULL;
1560 struct file_load_info info;
1561 char *p;
1563 info.filename = filename;
1564 info.file = f;
1565 info.len = 4;
1566 info.tmplen = 4;
1567 info.line = 0;
1568 if (!(info.buffer = mem_alloc( info.len ))) return;
1569 if (!(info.tmp = mem_alloc( info.tmplen )))
1571 free( info.buffer );
1572 return;
1575 if ((read_next_line( &info ) != 1) ||
1576 strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1578 set_error( STATUS_NOT_REGISTRY_FILE );
1579 goto done;
1582 while (read_next_line( &info ) == 1)
1584 p = info.buffer;
1585 while (*p && isspace(*p)) p++;
1586 switch(*p)
1588 case '[': /* new key */
1589 if (subkey) release_object( subkey );
1590 if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1591 if (!(subkey = load_key( key, p + 1, prefix_len, &info )))
1592 file_read_error( "Error creating key", &info );
1593 break;
1594 case '@': /* default value */
1595 case '\"': /* value */
1596 if (subkey) load_value( subkey, p, &info );
1597 else file_read_error( "Value without key", &info );
1598 break;
1599 case '#': /* option */
1600 if (subkey) load_key_option( subkey, p, &info );
1601 else if (!load_global_option( p, &info )) goto done;
1602 break;
1603 case ';': /* comment */
1604 case 0: /* empty line */
1605 break;
1606 default:
1607 file_read_error( "Unrecognized input", &info );
1608 break;
1612 done:
1613 if (subkey) release_object( subkey );
1614 free( info.buffer );
1615 free( info.tmp );
1618 /* load a part of the registry from a file */
1619 static void load_registry( struct key *key, obj_handle_t handle )
1621 struct file *file;
1622 int fd;
1624 if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1625 fd = dup( get_file_unix_fd( file ) );
1626 release_object( file );
1627 if (fd != -1)
1629 FILE *f = fdopen( fd, "r" );
1630 if (f)
1632 load_keys( key, NULL, f, -1 );
1633 fclose( f );
1635 else file_set_error();
1639 /* load one of the initial registry files */
1640 static int load_init_registry_from_file( const char *filename, struct key *key )
1642 FILE *f;
1644 if ((f = fopen( filename, "r" )))
1646 load_keys( key, filename, f, 0 );
1647 fclose( f );
1648 if (get_error() == STATUS_NOT_REGISTRY_FILE)
1650 fprintf( stderr, "%s is not a valid registry file\n", filename );
1651 return 1;
1655 assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1657 save_branch_info[save_branch_count].path = filename;
1658 save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1659 make_object_static( &key->obj );
1660 return (f != NULL);
1663 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1665 static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1666 static const WCHAR formatW[] = {'-','%','u',0};
1667 WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1668 WCHAR *p = buffer;
1669 unsigned int i;
1671 strcpyW( p, prefixW );
1672 p += strlenW( prefixW );
1673 p += sprintfW( p, formatW, sid->Revision );
1674 p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1675 sid->IdentifierAuthority.Value[4] ),
1676 MAKEWORD( sid->IdentifierAuthority.Value[3],
1677 sid->IdentifierAuthority.Value[2] )));
1678 for (i = 0; i < sid->SubAuthorityCount; i++)
1679 p += sprintfW( p, formatW, sid->SubAuthority[i] );
1681 path->len = (p - buffer) * sizeof(WCHAR);
1682 path->str = p = memdup( buffer, path->len );
1683 return p;
1686 /* get the cpu architectures that can be supported in the current prefix */
1687 unsigned int get_prefix_cpu_mask(void)
1689 /* Allowed server/client/prefix combinations:
1691 * prefix
1692 * 32 64
1693 * server +------+------+ client
1694 * | ok | fail | 32
1695 * 32 +------+------+---
1696 * | fail | fail | 64
1697 * ---+------+------+---
1698 * | ok | ok | 32
1699 * 64 +------+------+---
1700 * | fail | ok | 64
1701 * ---+------+------+---
1703 switch (prefix_type)
1705 case PREFIX_64BIT:
1706 /* 64-bit prefix requires 64-bit server */
1707 return sizeof(void *) > sizeof(int) ? ~0 : 0;
1708 case PREFIX_32BIT:
1709 default:
1710 return ~CPU_64BIT_MASK; /* only 32-bit cpus supported on 32-bit prefix */
1714 /* registry initialisation */
1715 void init_registry(void)
1717 static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1718 static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1719 static const WCHAR classes[] = {'S','o','f','t','w','a','r','e','\\',
1720 'C','l','a','s','s','e','s','\\',
1721 'W','o','w','6','4','3','2','N','o','d','e'};
1722 static const struct unicode_str root_name = { NULL, 0 };
1723 static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1724 static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1725 static const struct unicode_str classes_name = { classes, sizeof(classes) };
1727 WCHAR *current_user_path;
1728 struct unicode_str current_user_str;
1729 struct key *key, *hklm, *hkcu;
1731 /* switch to the config dir */
1733 if (fchdir( config_dir_fd ) == -1) fatal_perror( "chdir to config dir" );
1735 /* create the root key */
1736 root_key = alloc_key( &root_name, current_time );
1737 assert( root_key );
1738 make_object_static( &root_key->obj );
1740 /* load system.reg into Registry\Machine */
1742 if (!(hklm = create_key_recursive( root_key, &HKLM_name, current_time )))
1743 fatal_error( "could not create Machine registry key\n" );
1745 if (!load_init_registry_from_file( "system.reg", hklm ))
1746 prefix_type = sizeof(void *) > sizeof(int) ? PREFIX_64BIT : PREFIX_32BIT;
1747 else if (prefix_type == PREFIX_UNKNOWN)
1748 prefix_type = PREFIX_32BIT;
1750 /* load userdef.reg into Registry\User\.Default */
1752 if (!(key = create_key_recursive( root_key, &HKU_name, current_time )))
1753 fatal_error( "could not create User\\.Default registry key\n" );
1755 load_init_registry_from_file( "userdef.reg", key );
1756 release_object( key );
1758 /* load user.reg into HKEY_CURRENT_USER */
1760 /* FIXME: match default user in token.c. should get from process token instead */
1761 current_user_path = format_user_registry_path( security_local_user_sid, &current_user_str );
1762 if (!current_user_path ||
1763 !(hkcu = create_key_recursive( root_key, &current_user_str, current_time )))
1764 fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1765 free( current_user_path );
1766 load_init_registry_from_file( "user.reg", hkcu );
1768 /* set the shared flag on Software\Classes\Wow6432Node */
1769 if (prefix_type == PREFIX_64BIT)
1771 if ((key = create_key_recursive( hklm, &classes_name, current_time )))
1773 key->flags |= KEY_WOWSHARE;
1774 release_object( key );
1776 /* FIXME: handle HKCU too */
1779 release_object( hklm );
1780 release_object( hkcu );
1782 /* start the periodic save timer */
1783 set_periodic_save_timer();
1785 /* go back to the server dir */
1786 if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1789 /* save a registry branch to a file */
1790 static void save_all_subkeys( struct key *key, FILE *f )
1792 fprintf( f, "WINE REGISTRY Version 2\n" );
1793 fprintf( f, ";; All keys relative to " );
1794 dump_path( key, NULL, f );
1795 fprintf( f, "\n" );
1796 switch (prefix_type)
1798 case PREFIX_32BIT:
1799 fprintf( f, "\n#arch=win32\n" );
1800 break;
1801 case PREFIX_64BIT:
1802 fprintf( f, "\n#arch=win64\n" );
1803 break;
1804 default:
1805 break;
1807 save_subkeys( key, key, f );
1810 /* save a registry branch to a file handle */
1811 static void save_registry( struct key *key, obj_handle_t handle )
1813 struct file *file;
1814 int fd;
1816 if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1817 fd = dup( get_file_unix_fd( file ) );
1818 release_object( file );
1819 if (fd != -1)
1821 FILE *f = fdopen( fd, "w" );
1822 if (f)
1824 save_all_subkeys( key, f );
1825 if (fclose( f )) file_set_error();
1827 else
1829 file_set_error();
1830 close( fd );
1835 /* save a registry branch to a file */
1836 static int save_branch( struct key *key, const char *path )
1838 struct stat st;
1839 char *p, *tmp = NULL;
1840 int fd, count = 0, ret = 0;
1841 FILE *f;
1843 if (!(key->flags & KEY_DIRTY))
1845 if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1846 return 1;
1849 /* test the file type */
1851 if ((fd = open( path, O_WRONLY )) != -1)
1853 /* if file is not a regular file or has multiple links or is accessed
1854 * via symbolic links, write directly into it; otherwise use a temp file */
1855 if (!lstat( path, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1))
1857 ftruncate( fd, 0 );
1858 goto save;
1860 close( fd );
1863 /* create a temp file in the same directory */
1865 if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1866 strcpy( tmp, path );
1867 if ((p = strrchr( tmp, '/' ))) p++;
1868 else p = tmp;
1869 for (;;)
1871 sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1872 if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1873 if (errno != EEXIST) goto done;
1874 close( fd );
1877 /* now save to it */
1879 save:
1880 if (!(f = fdopen( fd, "w" )))
1882 if (tmp) unlink( tmp );
1883 close( fd );
1884 goto done;
1887 if (debug_level > 1)
1889 fprintf( stderr, "%s: ", path );
1890 dump_operation( key, NULL, "saving" );
1893 save_all_subkeys( key, f );
1894 ret = !fclose(f);
1896 if (tmp)
1898 /* if successfully written, rename to final name */
1899 if (ret) ret = !rename( tmp, path );
1900 if (!ret) unlink( tmp );
1903 done:
1904 free( tmp );
1905 if (ret) make_clean( key );
1906 return ret;
1909 /* periodic saving of the registry */
1910 static void periodic_save( void *arg )
1912 int i;
1914 if (fchdir( config_dir_fd ) == -1) return;
1915 save_timeout_user = NULL;
1916 for (i = 0; i < save_branch_count; i++)
1917 save_branch( save_branch_info[i].key, save_branch_info[i].path );
1918 if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1919 set_periodic_save_timer();
1922 /* start the periodic save timer */
1923 static void set_periodic_save_timer(void)
1925 if (save_timeout_user) remove_timeout_user( save_timeout_user );
1926 save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
1929 /* save the modified registry branches to disk */
1930 void flush_registry(void)
1932 int i;
1934 if (fchdir( config_dir_fd ) == -1) return;
1935 for (i = 0; i < save_branch_count; i++)
1937 if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
1939 fprintf( stderr, "wineserver: could not save registry branch to %s",
1940 save_branch_info[i].path );
1941 perror( " " );
1944 if (fchdir( server_dir_fd ) == -1) fatal_perror( "chdir to server dir" );
1947 /* determine if the thread is wow64 (32-bit client running on 64-bit prefix) */
1948 static int is_wow64_thread( struct thread *thread )
1950 return (prefix_type == PREFIX_64BIT && !(CPU_FLAG(thread->process->cpu) & CPU_64BIT_MASK));
1954 /* create a registry key */
1955 DECL_HANDLER(create_key)
1957 struct key *key = NULL, *parent;
1958 struct unicode_str name, class;
1959 unsigned int access = req->access;
1961 if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
1963 reply->hkey = 0;
1965 if (req->namelen > get_req_data_size())
1967 set_error( STATUS_INVALID_PARAMETER );
1968 return;
1970 class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
1971 class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
1972 get_req_path( &name, !req->parent );
1973 if (name.str > class.str)
1975 set_error( STATUS_INVALID_PARAMETER );
1976 return;
1978 name.len = (class.str - name.str) * sizeof(WCHAR);
1980 /* NOTE: no access rights are required from the parent handle to create a key */
1981 if ((parent = get_parent_hkey_obj( req->parent )))
1983 if ((key = create_key( parent, &name, &class, req->options, access,
1984 req->attributes, &reply->created )))
1986 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1987 release_object( key );
1989 release_object( parent );
1993 /* open a registry key */
1994 DECL_HANDLER(open_key)
1996 struct key *key, *parent;
1997 struct unicode_str name;
1998 unsigned int access = req->access;
2000 if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;
2002 reply->hkey = 0;
2003 /* NOTE: no access rights are required to open the parent key, only the child key */
2004 if ((parent = get_parent_hkey_obj( req->parent )))
2006 get_req_path( &name, !req->parent );
2007 if ((key = open_key( parent, &name, access, req->attributes )))
2009 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
2010 release_object( key );
2012 release_object( parent );
2016 /* delete a registry key */
2017 DECL_HANDLER(delete_key)
2019 struct key *key;
2021 if ((key = get_hkey_obj( req->hkey, DELETE )))
2023 delete_key( key, 0);
2024 release_object( key );
2028 /* flush a registry key */
2029 DECL_HANDLER(flush_key)
2031 struct key *key = get_hkey_obj( req->hkey, 0 );
2032 if (key)
2034 /* we don't need to do anything here with the current implementation */
2035 release_object( key );
2039 /* enumerate registry subkeys */
2040 DECL_HANDLER(enum_key)
2042 struct key *key;
2044 if ((key = get_hkey_obj( req->hkey,
2045 req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
2047 enum_key( key, req->index, req->info_class, reply );
2048 release_object( key );
2052 /* set a value of a registry key */
2053 DECL_HANDLER(set_key_value)
2055 struct key *key;
2056 struct unicode_str name;
2058 if (req->namelen > get_req_data_size())
2060 set_error( STATUS_INVALID_PARAMETER );
2061 return;
2063 name.str = get_req_data();
2064 name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2066 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2068 data_size_t datalen = get_req_data_size() - req->namelen;
2069 const char *data = (const char *)get_req_data() + req->namelen;
2071 set_value( key, &name, req->type, data, datalen );
2072 release_object( key );
2076 /* retrieve the value of a registry key */
2077 DECL_HANDLER(get_key_value)
2079 struct key *key;
2080 struct unicode_str name;
2082 reply->total = 0;
2083 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2085 get_req_unicode_str( &name );
2086 get_value( key, &name, &reply->type, &reply->total );
2087 release_object( key );
2091 /* enumerate the value of a registry key */
2092 DECL_HANDLER(enum_key_value)
2094 struct key *key;
2096 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
2098 enum_value( key, req->index, req->info_class, reply );
2099 release_object( key );
2103 /* delete a value of a registry key */
2104 DECL_HANDLER(delete_key_value)
2106 struct key *key;
2107 struct unicode_str name;
2109 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
2111 get_req_unicode_str( &name );
2112 delete_value( key, &name );
2113 release_object( key );
2117 /* load a registry branch from a file */
2118 DECL_HANDLER(load_registry)
2120 struct key *key, *parent;
2121 struct token *token = thread_get_impersonation_token( current );
2122 struct unicode_str name;
2124 const LUID_AND_ATTRIBUTES privs[] =
2126 { SeBackupPrivilege, 0 },
2127 { SeRestorePrivilege, 0 },
2130 if (!token || !token_check_privileges( token, TRUE, privs,
2131 sizeof(privs)/sizeof(privs[0]), NULL ))
2133 set_error( STATUS_PRIVILEGE_NOT_HELD );
2134 return;
2137 if ((parent = get_parent_hkey_obj( req->hkey )))
2139 int dummy;
2140 get_req_path( &name, !req->hkey );
2141 if ((key = create_key( parent, &name, NULL, 0, KEY_WOW64_64KEY, 0, &dummy )))
2143 load_registry( key, req->file );
2144 release_object( key );
2146 release_object( parent );
2150 DECL_HANDLER(unload_registry)
2152 struct key *key;
2153 struct token *token = thread_get_impersonation_token( current );
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 ((key = get_hkey_obj( req->hkey, 0 )))
2170 delete_key( key, 1 ); /* FIXME */
2171 release_object( key );
2175 /* save a registry branch to a file */
2176 DECL_HANDLER(save_registry)
2178 struct key *key;
2180 if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
2182 set_error( STATUS_PRIVILEGE_NOT_HELD );
2183 return;
2186 if ((key = get_hkey_obj( req->hkey, 0 )))
2188 save_registry( key, req->file );
2189 release_object( key );
2193 /* add a registry key change notification */
2194 DECL_HANDLER(set_registry_notification)
2196 struct key *key;
2197 struct event *event;
2198 struct notify *notify;
2200 key = get_hkey_obj( req->hkey, KEY_NOTIFY );
2201 if (key)
2203 event = get_event_obj( current->process, req->event, SYNCHRONIZE );
2204 if (event)
2206 notify = find_notify( key, current->process, req->hkey );
2207 if (notify)
2209 if (notify->event)
2210 release_object( notify->event );
2211 grab_object( event );
2212 notify->event = event;
2214 else
2216 notify = mem_alloc( sizeof(*notify) );
2217 if (notify)
2219 grab_object( event );
2220 notify->event = event;
2221 notify->subtree = req->subtree;
2222 notify->filter = req->filter;
2223 notify->hkey = req->hkey;
2224 notify->process = current->process;
2225 list_add_head( &key->notify_list, &notify->entry );
2228 release_object( event );
2230 release_object( key );