wined3d: Fix error handling in fixed_get_input().
[wine/gsoc_dplay.git] / server / registry.c
blob03828e15f6cdcec7957e594ba225576bb355f963
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 "unicode.h"
47 #include "security.h"
49 #include "winternl.h"
50 #include "wine/library.h"
52 struct notify
54 struct list entry; /* entry in list of notifications */
55 struct event *event; /* event to set when changing this key */
56 int subtree; /* true if subtree notification */
57 unsigned int filter; /* which events to notify on */
58 obj_handle_t hkey; /* hkey associated with this notification */
59 struct process *process; /* process in which the hkey is valid */
62 /* a registry key */
63 struct key
65 struct object obj; /* object header */
66 WCHAR *name; /* key name */
67 WCHAR *class; /* key class */
68 unsigned short namelen; /* length of key name */
69 unsigned short classlen; /* length of class name */
70 struct key *parent; /* parent key */
71 int last_subkey; /* last in use subkey */
72 int nb_subkeys; /* count of allocated subkeys */
73 struct key **subkeys; /* subkeys array */
74 int last_value; /* last in use value */
75 int nb_values; /* count of allocated values in array */
76 struct key_value *values; /* values array */
77 unsigned int flags; /* flags */
78 time_t modif; /* last modification time */
79 struct list notify_list; /* list of notifications */
82 /* key flags */
83 #define KEY_VOLATILE 0x0001 /* key is volatile (not saved to disk) */
84 #define KEY_DELETED 0x0002 /* key has been deleted */
85 #define KEY_DIRTY 0x0004 /* key has been modified */
87 /* a key value */
88 struct key_value
90 WCHAR *name; /* value name */
91 unsigned short namelen; /* length of value name */
92 unsigned short type; /* value type */
93 data_size_t len; /* value data length in bytes */
94 void *data; /* pointer to value data */
97 #define MIN_SUBKEYS 8 /* min. number of allocated subkeys per key */
98 #define MIN_VALUES 8 /* min. number of allocated values per key */
100 #define MAX_NAME_LEN MAX_PATH /* max. length of a key name */
101 #define MAX_VALUE_LEN MAX_PATH /* max. length of a value name */
103 /* the root of the registry tree */
104 static struct key *root_key;
106 static const timeout_t save_period = 30 * -TICKS_PER_SEC; /* delay between periodic saves */
107 static struct timeout_user *save_timeout_user; /* saving timer */
109 static void set_periodic_save_timer(void);
111 /* information about where to save a registry branch */
112 struct save_branch_info
114 struct key *key;
115 char *path;
118 #define MAX_SAVE_BRANCH_INFO 3
119 static int save_branch_count;
120 static struct save_branch_info save_branch_info[MAX_SAVE_BRANCH_INFO];
123 /* information about a file being loaded */
124 struct file_load_info
126 const char *filename; /* input file name */
127 FILE *file; /* input file */
128 char *buffer; /* line buffer */
129 int len; /* buffer length */
130 int line; /* current input line */
131 WCHAR *tmp; /* temp buffer to use while parsing input */
132 size_t tmplen; /* length of temp buffer */
136 static void key_dump( struct object *obj, int verbose );
137 static unsigned int key_map_access( struct object *obj, unsigned int access );
138 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle );
139 static void key_destroy( struct object *obj );
141 static const struct object_ops key_ops =
143 sizeof(struct key), /* size */
144 key_dump, /* dump */
145 no_add_queue, /* add_queue */
146 NULL, /* remove_queue */
147 NULL, /* signaled */
148 NULL, /* satisfied */
149 no_signal, /* signal */
150 no_get_fd, /* get_fd */
151 key_map_access, /* map_access */
152 default_get_sd, /* get_sd */
153 default_set_sd, /* set_sd */
154 no_lookup_name, /* lookup_name */
155 no_open_file, /* open_file */
156 key_close_handle, /* close_handle */
157 key_destroy /* destroy */
162 * The registry text file format v2 used by this code is similar to the one
163 * used by REGEDIT import/export functionality, with the following differences:
164 * - strings and key names can contain \x escapes for Unicode
165 * - key names use escapes too in order to support Unicode
166 * - the modification time optionally follows the key name
167 * - REG_EXPAND_SZ and REG_MULTI_SZ are saved as strings instead of hex
170 static inline char to_hex( char ch )
172 if (isdigit(ch)) return ch - '0';
173 return tolower(ch) - 'a' + 10;
176 /* dump the full path of a key */
177 static void dump_path( const struct key *key, const struct key *base, FILE *f )
179 if (key->parent && key->parent != base)
181 dump_path( key->parent, base, f );
182 fprintf( f, "\\\\" );
184 dump_strW( key->name, key->namelen / sizeof(WCHAR), f, "[]" );
187 /* dump a value to a text file */
188 static void dump_value( const struct key_value *value, FILE *f )
190 unsigned int i;
191 int count;
193 if (value->namelen)
195 fputc( '\"', f );
196 count = 1 + dump_strW( value->name, value->namelen / sizeof(WCHAR), f, "\"\"" );
197 count += fprintf( f, "\"=" );
199 else count = fprintf( f, "@=" );
201 switch(value->type)
203 case REG_SZ:
204 case REG_EXPAND_SZ:
205 case REG_MULTI_SZ:
206 if (value->type != REG_SZ) fprintf( f, "str(%d):", value->type );
207 fputc( '\"', f );
208 if (value->data) dump_strW( (WCHAR *)value->data, value->len / sizeof(WCHAR), f, "\"\"" );
209 fputc( '\"', f );
210 break;
211 case REG_DWORD:
212 if (value->len == sizeof(DWORD))
214 DWORD dw;
215 memcpy( &dw, value->data, sizeof(DWORD) );
216 fprintf( f, "dword:%08x", dw );
217 break;
219 /* else fall through */
220 default:
221 if (value->type == REG_BINARY) count += fprintf( f, "hex:" );
222 else count += fprintf( f, "hex(%x):", value->type );
223 for (i = 0; i < value->len; i++)
225 count += fprintf( f, "%02x", *((unsigned char *)value->data + i) );
226 if (i < value->len-1)
228 fputc( ',', f );
229 if (++count > 76)
231 fprintf( f, "\\\n " );
232 count = 2;
236 break;
238 fputc( '\n', f );
241 /* save a registry and all its subkeys to a text file */
242 static void save_subkeys( const struct key *key, const struct key *base, FILE *f )
244 int i;
246 if (key->flags & KEY_VOLATILE) return;
247 /* save key if it has either some values or no subkeys */
248 /* keys with no values but subkeys are saved implicitly by saving the subkeys */
249 if ((key->last_value >= 0) || (key->last_subkey == -1))
251 fprintf( f, "\n[" );
252 if (key != base) dump_path( key, base, f );
253 fprintf( f, "] %ld\n", (long)key->modif );
254 for (i = 0; i <= key->last_value; i++) dump_value( &key->values[i], f );
256 for (i = 0; i <= key->last_subkey; i++) save_subkeys( key->subkeys[i], base, f );
259 static void dump_operation( const struct key *key, const struct key_value *value, const char *op )
261 fprintf( stderr, "%s key ", op );
262 if (key) dump_path( key, NULL, stderr );
263 else fprintf( stderr, "ERROR" );
264 if (value)
266 fprintf( stderr, " value ");
267 dump_value( value, stderr );
269 else fprintf( stderr, "\n" );
272 static void key_dump( struct object *obj, int verbose )
274 struct key *key = (struct key *)obj;
275 assert( obj->ops == &key_ops );
276 fprintf( stderr, "Key flags=%x ", key->flags );
277 dump_path( key, NULL, stderr );
278 fprintf( stderr, "\n" );
281 /* notify waiter and maybe delete the notification */
282 static void do_notification( struct key *key, struct notify *notify, int del )
284 if (notify->event)
286 set_event( notify->event );
287 release_object( notify->event );
288 notify->event = NULL;
290 if (del)
292 list_remove( &notify->entry );
293 free( notify );
297 static inline struct notify *find_notify( struct key *key, struct process *process, obj_handle_t hkey )
299 struct notify *notify;
301 LIST_FOR_EACH_ENTRY( notify, &key->notify_list, struct notify, entry )
303 if (notify->process == process && notify->hkey == hkey) return notify;
305 return NULL;
308 static unsigned int key_map_access( struct object *obj, unsigned int access )
310 if (access & GENERIC_READ) access |= KEY_READ;
311 if (access & GENERIC_WRITE) access |= KEY_WRITE;
312 if (access & GENERIC_EXECUTE) access |= KEY_EXECUTE;
313 if (access & GENERIC_ALL) access |= KEY_ALL_ACCESS;
314 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
317 /* close the notification associated with a handle */
318 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
320 struct key * key = (struct key *) obj;
321 struct notify *notify = find_notify( key, process, handle );
322 if (notify) do_notification( key, notify, 1 );
323 return 1; /* ok to close */
326 static void key_destroy( struct object *obj )
328 int i;
329 struct list *ptr;
330 struct key *key = (struct key *)obj;
331 assert( obj->ops == &key_ops );
333 free( key->name );
334 free( key->class );
335 for (i = 0; i <= key->last_value; i++)
337 free( key->values[i].name );
338 free( key->values[i].data );
340 free( key->values );
341 for (i = 0; i <= key->last_subkey; i++)
343 key->subkeys[i]->parent = NULL;
344 release_object( key->subkeys[i] );
346 free( key->subkeys );
347 /* unconditionally notify everything waiting on this key */
348 while ((ptr = list_head( &key->notify_list )))
350 struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
351 do_notification( key, notify, 1 );
355 /* get the request vararg as registry path */
356 static inline void get_req_path( struct unicode_str *str, int skip_root )
358 static const WCHAR root_name[] = { '\\','R','e','g','i','s','t','r','y','\\' };
360 str->str = get_req_data();
361 str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
363 if (skip_root && str->len >= sizeof(root_name) &&
364 !memicmpW( str->str, root_name, sizeof(root_name)/sizeof(WCHAR) ))
366 str->str += sizeof(root_name)/sizeof(WCHAR);
367 str->len -= sizeof(root_name);
371 /* return the next token in a given path */
372 /* token->str must point inside the path, or be NULL for the first call */
373 static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
375 data_size_t i = 0, len = path->len / sizeof(WCHAR);
377 if (!token->str) /* first time */
379 /* path cannot start with a backslash */
380 if (len && path->str[0] == '\\')
382 set_error( STATUS_OBJECT_PATH_INVALID );
383 return NULL;
386 else
388 i = token->str - path->str;
389 i += token->len / sizeof(WCHAR);
390 while (i < len && path->str[i] == '\\') i++;
392 token->str = path->str + i;
393 while (i < len && path->str[i] != '\\') i++;
394 token->len = (path->str + i - token->str) * sizeof(WCHAR);
395 return token;
398 /* allocate a key object */
399 static struct key *alloc_key( const struct unicode_str *name, time_t modif )
401 struct key *key;
402 if ((key = alloc_object( &key_ops )))
404 key->name = NULL;
405 key->class = NULL;
406 key->namelen = name->len;
407 key->classlen = 0;
408 key->flags = 0;
409 key->last_subkey = -1;
410 key->nb_subkeys = 0;
411 key->subkeys = NULL;
412 key->nb_values = 0;
413 key->last_value = -1;
414 key->values = NULL;
415 key->modif = modif;
416 key->parent = NULL;
417 list_init( &key->notify_list );
418 if (name->len && !(key->name = memdup( name->str, name->len )))
420 release_object( key );
421 key = NULL;
424 return key;
427 /* mark a key and all its parents as dirty (modified) */
428 static void make_dirty( struct key *key )
430 while (key)
432 if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return; /* nothing to do */
433 key->flags |= KEY_DIRTY;
434 key = key->parent;
438 /* mark a key and all its subkeys as clean (not modified) */
439 static void make_clean( struct key *key )
441 int i;
443 if (key->flags & KEY_VOLATILE) return;
444 if (!(key->flags & KEY_DIRTY)) return;
445 key->flags &= ~KEY_DIRTY;
446 for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
449 /* go through all the notifications and send them if necessary */
450 static void check_notify( struct key *key, unsigned int change, int not_subtree )
452 struct list *ptr, *next;
454 LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
456 struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
457 if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
458 do_notification( key, n, 0 );
462 /* update key modification time */
463 static void touch_key( struct key *key, unsigned int change )
465 struct key *k;
467 key->modif = time(NULL);
468 make_dirty( key );
470 /* do notifications */
471 check_notify( key, change, 1 );
472 for ( k = key->parent; k; k = k->parent )
473 check_notify( k, change & ~REG_NOTIFY_CHANGE_LAST_SET, 0 );
476 /* try to grow the array of subkeys; return 1 if OK, 0 on error */
477 static int grow_subkeys( struct key *key )
479 struct key **new_subkeys;
480 int nb_subkeys;
482 if (key->nb_subkeys)
484 nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2); /* grow by 50% */
485 if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
487 set_error( STATUS_NO_MEMORY );
488 return 0;
491 else
493 nb_subkeys = MIN_VALUES;
494 if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
496 key->subkeys = new_subkeys;
497 key->nb_subkeys = nb_subkeys;
498 return 1;
501 /* allocate a subkey for a given key, and return its index */
502 static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
503 int index, time_t modif )
505 struct key *key;
506 int i;
508 if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
510 set_error( STATUS_NAME_TOO_LONG );
511 return NULL;
513 if (parent->last_subkey + 1 == parent->nb_subkeys)
515 /* need to grow the array */
516 if (!grow_subkeys( parent )) return NULL;
518 if ((key = alloc_key( name, modif )) != NULL)
520 key->parent = parent;
521 for (i = ++parent->last_subkey; i > index; i--)
522 parent->subkeys[i] = parent->subkeys[i-1];
523 parent->subkeys[index] = key;
525 return key;
528 /* free a subkey of a given key */
529 static void free_subkey( struct key *parent, int index )
531 struct key *key;
532 int i, nb_subkeys;
534 assert( index >= 0 );
535 assert( index <= parent->last_subkey );
537 key = parent->subkeys[index];
538 for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
539 parent->last_subkey--;
540 key->flags |= KEY_DELETED;
541 key->parent = NULL;
542 release_object( key );
544 /* try to shrink the array */
545 nb_subkeys = parent->nb_subkeys;
546 if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
548 struct key **new_subkeys;
549 nb_subkeys -= nb_subkeys / 3; /* shrink by 33% */
550 if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
551 if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
552 parent->subkeys = new_subkeys;
553 parent->nb_subkeys = nb_subkeys;
557 /* find the named child of a given key and return its index */
558 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
560 int i, min, max, res;
561 data_size_t len;
563 min = 0;
564 max = key->last_subkey;
565 while (min <= max)
567 i = (min + max) / 2;
568 len = min( key->subkeys[i]->namelen, name->len );
569 res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
570 if (!res) res = key->subkeys[i]->namelen - name->len;
571 if (!res)
573 *index = i;
574 return key->subkeys[i];
576 if (res > 0) max = i - 1;
577 else min = i + 1;
579 *index = min; /* this is where we should insert it */
580 return NULL;
583 /* open a subkey */
584 static struct key *open_key( struct key *key, const struct unicode_str *name )
586 int index;
587 struct unicode_str token;
589 token.str = NULL;
590 if (!get_path_token( name, &token )) return NULL;
591 while (token.len)
593 if (!(key = find_subkey( key, &token, &index )))
595 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
596 break;
598 get_path_token( name, &token );
601 if (debug_level > 1) dump_operation( key, NULL, "Open" );
602 if (key) grab_object( key );
603 return key;
606 /* create a subkey */
607 static struct key *create_key( struct key *key, const struct unicode_str *name,
608 const struct unicode_str *class, int flags, time_t modif, int *created )
610 struct key *base;
611 int index;
612 struct unicode_str token;
614 if (key->flags & KEY_DELETED) /* we cannot create a subkey under a deleted key */
616 set_error( STATUS_KEY_DELETED );
617 return NULL;
619 if (!(flags & KEY_VOLATILE) && (key->flags & KEY_VOLATILE))
621 set_error( STATUS_CHILD_MUST_BE_VOLATILE );
622 return NULL;
624 if (!modif) modif = time(NULL);
626 token.str = NULL;
627 if (!get_path_token( name, &token )) return NULL;
628 *created = 0;
629 while (token.len)
631 struct key *subkey;
632 if (!(subkey = find_subkey( key, &token, &index ))) break;
633 key = subkey;
634 get_path_token( name, &token );
637 /* create the remaining part */
639 if (!token.len) goto done;
640 *created = 1;
641 if (flags & KEY_DIRTY) make_dirty( key );
642 if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
643 base = key;
644 for (;;)
646 key->flags |= flags;
647 get_path_token( name, &token );
648 if (!token.len) break;
649 /* we know the index is always 0 in a new key */
650 if (!(key = alloc_subkey( key, &token, 0, modif )))
652 free_subkey( base, index );
653 return NULL;
657 done:
658 if (debug_level > 1) dump_operation( key, NULL, "Create" );
659 if (class && class->len)
661 key->classlen = class->len;
662 free(key->class);
663 if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
665 grab_object( key );
666 return key;
669 /* query information about a key or a subkey */
670 static void enum_key( const struct key *key, int index, int info_class,
671 struct enum_key_reply *reply )
673 int i;
674 data_size_t len, namelen, classlen;
675 data_size_t max_subkey = 0, max_class = 0;
676 data_size_t max_value = 0, max_data = 0;
677 char *data;
679 if (index != -1) /* -1 means use the specified key directly */
681 if ((index < 0) || (index > key->last_subkey))
683 set_error( STATUS_NO_MORE_ENTRIES );
684 return;
686 key = key->subkeys[index];
689 namelen = key->namelen;
690 classlen = key->classlen;
692 switch(info_class)
694 case KeyBasicInformation:
695 classlen = 0; /* only return the name */
696 /* fall through */
697 case KeyNodeInformation:
698 reply->max_subkey = 0;
699 reply->max_class = 0;
700 reply->max_value = 0;
701 reply->max_data = 0;
702 break;
703 case KeyFullInformation:
704 for (i = 0; i <= key->last_subkey; i++)
706 struct key *subkey = key->subkeys[i];
707 len = subkey->namelen / sizeof(WCHAR);
708 if (len > max_subkey) max_subkey = len;
709 len = subkey->classlen / sizeof(WCHAR);
710 if (len > max_class) max_class = len;
712 for (i = 0; i <= key->last_value; i++)
714 len = key->values[i].namelen / sizeof(WCHAR);
715 if (len > max_value) max_value = len;
716 len = key->values[i].len;
717 if (len > max_data) max_data = len;
719 reply->max_subkey = max_subkey;
720 reply->max_class = max_class;
721 reply->max_value = max_value;
722 reply->max_data = max_data;
723 namelen = 0; /* only return the class */
724 break;
725 default:
726 set_error( STATUS_INVALID_PARAMETER );
727 return;
729 reply->subkeys = key->last_subkey + 1;
730 reply->values = key->last_value + 1;
731 reply->modif = key->modif;
732 reply->total = namelen + classlen;
734 len = min( reply->total, get_reply_max_size() );
735 if (len && (data = set_reply_data_size( len )))
737 if (len > namelen)
739 reply->namelen = namelen;
740 memcpy( data, key->name, namelen );
741 memcpy( data + namelen, key->class, len - namelen );
743 else
745 reply->namelen = len;
746 memcpy( data, key->name, len );
749 if (debug_level > 1) dump_operation( key, NULL, "Enum" );
752 /* delete a key and its values */
753 static int delete_key( struct key *key, int recurse )
755 int index;
756 struct key *parent;
758 /* must find parent and index */
759 if (key == root_key)
761 set_error( STATUS_ACCESS_DENIED );
762 return -1;
764 if (!(parent = key->parent) || (key->flags & KEY_DELETED))
766 set_error( STATUS_KEY_DELETED );
767 return -1;
770 while (recurse && (key->last_subkey>=0))
771 if (0 > delete_key(key->subkeys[key->last_subkey], 1))
772 return -1;
774 for (index = 0; index <= parent->last_subkey; index++)
775 if (parent->subkeys[index] == key) break;
776 assert( index <= parent->last_subkey );
778 /* we can only delete a key that has no subkeys */
779 if (key->last_subkey >= 0)
781 set_error( STATUS_ACCESS_DENIED );
782 return -1;
785 if (debug_level > 1) dump_operation( key, NULL, "Delete" );
786 free_subkey( parent, index );
787 touch_key( parent, REG_NOTIFY_CHANGE_NAME );
788 return 0;
791 /* try to grow the array of values; return 1 if OK, 0 on error */
792 static int grow_values( struct key *key )
794 struct key_value *new_val;
795 int nb_values;
797 if (key->nb_values)
799 nb_values = key->nb_values + (key->nb_values / 2); /* grow by 50% */
800 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
802 set_error( STATUS_NO_MEMORY );
803 return 0;
806 else
808 nb_values = MIN_VALUES;
809 if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
811 key->values = new_val;
812 key->nb_values = nb_values;
813 return 1;
816 /* find the named value of a given key and return its index in the array */
817 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
819 int i, min, max, res;
820 data_size_t len;
822 min = 0;
823 max = key->last_value;
824 while (min <= max)
826 i = (min + max) / 2;
827 len = min( key->values[i].namelen, name->len );
828 res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
829 if (!res) res = key->values[i].namelen - name->len;
830 if (!res)
832 *index = i;
833 return &key->values[i];
835 if (res > 0) max = i - 1;
836 else min = i + 1;
838 *index = min; /* this is where we should insert it */
839 return NULL;
842 /* insert a new value; the index must have been returned by find_value */
843 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
845 struct key_value *value;
846 WCHAR *new_name = NULL;
847 int i;
849 if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
851 set_error( STATUS_NAME_TOO_LONG );
852 return NULL;
854 if (key->last_value + 1 == key->nb_values)
856 if (!grow_values( key )) return NULL;
858 if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
859 for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
860 value = &key->values[index];
861 value->name = new_name;
862 value->namelen = name->len;
863 value->len = 0;
864 value->data = NULL;
865 return value;
868 /* set a key value */
869 static void set_value( struct key *key, const struct unicode_str *name,
870 int type, const void *data, data_size_t len )
872 struct key_value *value;
873 void *ptr = NULL;
874 int index;
876 if ((value = find_value( key, name, &index )))
878 /* check if the new value is identical to the existing one */
879 if (value->type == type && value->len == len &&
880 value->data && !memcmp( value->data, data, len ))
882 if (debug_level > 1) dump_operation( key, value, "Skip setting" );
883 return;
887 if (len && !(ptr = memdup( data, len ))) return;
889 if (!value)
891 if (!(value = insert_value( key, name, index )))
893 free( ptr );
894 return;
897 else free( value->data ); /* already existing, free previous data */
899 value->type = type;
900 value->len = len;
901 value->data = ptr;
902 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
903 if (debug_level > 1) dump_operation( key, value, "Set" );
906 /* get a key value */
907 static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
909 struct key_value *value;
910 int index;
912 if ((value = find_value( key, name, &index )))
914 *type = value->type;
915 *len = value->len;
916 if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
917 if (debug_level > 1) dump_operation( key, value, "Get" );
919 else
921 *type = -1;
922 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
926 /* enumerate a key value */
927 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
929 struct key_value *value;
931 if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
932 else
934 void *data;
935 data_size_t namelen, maxlen;
937 value = &key->values[i];
938 reply->type = value->type;
939 namelen = value->namelen;
941 switch(info_class)
943 case KeyValueBasicInformation:
944 reply->total = namelen;
945 break;
946 case KeyValueFullInformation:
947 reply->total = namelen + value->len;
948 break;
949 case KeyValuePartialInformation:
950 reply->total = value->len;
951 namelen = 0;
952 break;
953 default:
954 set_error( STATUS_INVALID_PARAMETER );
955 return;
958 maxlen = min( reply->total, get_reply_max_size() );
959 if (maxlen && ((data = set_reply_data_size( maxlen ))))
961 if (maxlen > namelen)
963 reply->namelen = namelen;
964 memcpy( data, value->name, namelen );
965 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
967 else
969 reply->namelen = maxlen;
970 memcpy( data, value->name, maxlen );
973 if (debug_level > 1) dump_operation( key, value, "Enum" );
977 /* delete a value */
978 static void delete_value( struct key *key, const struct unicode_str *name )
980 struct key_value *value;
981 int i, index, nb_values;
983 if (!(value = find_value( key, name, &index )))
985 set_error( STATUS_OBJECT_NAME_NOT_FOUND );
986 return;
988 if (debug_level > 1) dump_operation( key, value, "Delete" );
989 free( value->name );
990 free( value->data );
991 for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
992 key->last_value--;
993 touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
995 /* try to shrink the array */
996 nb_values = key->nb_values;
997 if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
999 struct key_value *new_val;
1000 nb_values -= nb_values / 3; /* shrink by 33% */
1001 if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
1002 if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
1003 key->values = new_val;
1004 key->nb_values = nb_values;
1008 /* get the registry key corresponding to an hkey handle */
1009 static inline struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1011 return (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1014 /* get the registry key corresponding to a parent key handle */
1015 static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
1017 if (!hkey) return (struct key *)grab_object( root_key );
1018 return (struct key *)get_handle_obj( current->process, hkey, 0, &key_ops );
1021 /* read a line from the input file */
1022 static int read_next_line( struct file_load_info *info )
1024 char *newbuf;
1025 int newlen, pos = 0;
1027 info->line++;
1028 for (;;)
1030 if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1031 return (pos != 0); /* EOF */
1032 pos = strlen(info->buffer);
1033 if (info->buffer[pos-1] == '\n')
1035 /* got a full line */
1036 info->buffer[--pos] = 0;
1037 if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1038 return 1;
1040 if (pos < info->len - 1) return 1; /* EOF but something was read */
1042 /* need to enlarge the buffer */
1043 newlen = info->len + info->len / 2;
1044 if (!(newbuf = realloc( info->buffer, newlen )))
1046 set_error( STATUS_NO_MEMORY );
1047 return -1;
1049 info->buffer = newbuf;
1050 info->len = newlen;
1054 /* make sure the temp buffer holds enough space */
1055 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1057 WCHAR *tmp;
1058 if (info->tmplen >= size) return 1;
1059 if (!(tmp = realloc( info->tmp, size )))
1061 set_error( STATUS_NO_MEMORY );
1062 return 0;
1064 info->tmp = tmp;
1065 info->tmplen = size;
1066 return 1;
1069 /* report an error while loading an input file */
1070 static void file_read_error( const char *err, struct file_load_info *info )
1072 if (info->filename)
1073 fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1074 else
1075 fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1078 /* parse an escaped string back into Unicode */
1079 /* return the number of chars read from the input, or -1 on output overflow */
1080 static int parse_strW( WCHAR *dest, data_size_t *len, const char *src, char endchar )
1082 data_size_t count = sizeof(WCHAR); /* for terminating null */
1083 const char *p = src;
1084 while (*p && *p != endchar)
1086 if (*p != '\\') *dest = (WCHAR)*p++;
1087 else
1089 p++;
1090 switch(*p)
1092 case 'a': *dest = '\a'; p++; break;
1093 case 'b': *dest = '\b'; p++; break;
1094 case 'e': *dest = '\e'; p++; break;
1095 case 'f': *dest = '\f'; p++; break;
1096 case 'n': *dest = '\n'; p++; break;
1097 case 'r': *dest = '\r'; p++; break;
1098 case 't': *dest = '\t'; p++; break;
1099 case 'v': *dest = '\v'; p++; break;
1100 case 'x': /* hex escape */
1101 p++;
1102 if (!isxdigit(*p)) *dest = 'x';
1103 else
1105 *dest = to_hex(*p++);
1106 if (isxdigit(*p)) *dest = (*dest * 16) + to_hex(*p++);
1107 if (isxdigit(*p)) *dest = (*dest * 16) + to_hex(*p++);
1108 if (isxdigit(*p)) *dest = (*dest * 16) + to_hex(*p++);
1110 break;
1111 case '0':
1112 case '1':
1113 case '2':
1114 case '3':
1115 case '4':
1116 case '5':
1117 case '6':
1118 case '7': /* octal escape */
1119 *dest = *p++ - '0';
1120 if (*p >= '0' && *p <= '7') *dest = (*dest * 8) + (*p++ - '0');
1121 if (*p >= '0' && *p <= '7') *dest = (*dest * 8) + (*p++ - '0');
1122 break;
1123 default:
1124 *dest = (WCHAR)*p++;
1125 break;
1128 if ((count += sizeof(WCHAR)) > *len) return -1; /* dest buffer overflow */
1129 dest++;
1131 *dest = 0;
1132 if (!*p) return -1; /* delimiter not found */
1133 *len = count;
1134 return p + 1 - src;
1137 /* convert a data type tag to a value type */
1138 static int get_data_type( const char *buffer, int *type, int *parse_type )
1140 struct data_type { const char *tag; int len; int type; int parse_type; };
1142 static const struct data_type data_types[] =
1143 { /* actual type */ /* type to assume for parsing */
1144 { "\"", 1, REG_SZ, REG_SZ },
1145 { "str:\"", 5, REG_SZ, REG_SZ },
1146 { "str(2):\"", 8, REG_EXPAND_SZ, REG_SZ },
1147 { "str(7):\"", 8, REG_MULTI_SZ, REG_SZ },
1148 { "hex:", 4, REG_BINARY, REG_BINARY },
1149 { "dword:", 6, REG_DWORD, REG_DWORD },
1150 { "hex(", 4, -1, REG_BINARY },
1151 { NULL, 0, 0, 0 }
1154 const struct data_type *ptr;
1155 char *end;
1157 for (ptr = data_types; ptr->tag; ptr++)
1159 if (memcmp( ptr->tag, buffer, ptr->len )) continue;
1160 *parse_type = ptr->parse_type;
1161 if ((*type = ptr->type) != -1) return ptr->len;
1162 /* "hex(xx):" is special */
1163 *type = (int)strtoul( buffer + 4, &end, 16 );
1164 if ((end <= buffer) || memcmp( end, "):", 2 )) return 0;
1165 return end + 2 - buffer;
1167 return 0;
1170 /* load and create a key from the input file */
1171 static struct key *load_key( struct key *base, const char *buffer, int flags,
1172 int prefix_len, struct file_load_info *info,
1173 int default_modif )
1175 WCHAR *p;
1176 struct unicode_str name;
1177 int res, modif;
1178 data_size_t len = strlen(buffer) * sizeof(WCHAR);
1180 if (!get_file_tmp_space( info, len )) return NULL;
1182 if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1184 file_read_error( "Malformed key", info );
1185 return NULL;
1187 if (sscanf( buffer + res, " %d", &modif ) != 1) modif = default_modif;
1189 p = info->tmp;
1190 while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1192 if (!*p)
1194 if (prefix_len > 1)
1196 file_read_error( "Malformed key", info );
1197 return NULL;
1199 /* empty key name, return base key */
1200 return (struct key *)grab_object( base );
1202 name.str = p;
1203 name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1204 return create_key( base, &name, NULL, flags, modif, &res );
1207 /* parse a comma-separated list of hex digits */
1208 static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1210 const char *p = buffer;
1211 data_size_t count = 0;
1212 while (isxdigit(*p))
1214 int val;
1215 char buf[3];
1216 memcpy( buf, p, 2 );
1217 buf[2] = 0;
1218 sscanf( buf, "%x", &val );
1219 if (count++ >= *len) return -1; /* dest buffer overflow */
1220 *dest++ = (unsigned char )val;
1221 p += 2;
1222 if (*p == ',') p++;
1224 *len = count;
1225 return p - buffer;
1228 /* parse a value name and create the corresponding value */
1229 static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1230 struct file_load_info *info )
1232 struct key_value *value;
1233 struct unicode_str name;
1234 int index;
1235 data_size_t maxlen = strlen(buffer) * sizeof(WCHAR);
1237 if (!get_file_tmp_space( info, maxlen )) return NULL;
1238 name.str = info->tmp;
1239 if (buffer[0] == '@')
1241 name.len = 0;
1242 *len = 1;
1244 else
1246 int r = parse_strW( info->tmp, &maxlen, buffer + 1, '\"' );
1247 if (r == -1) goto error;
1248 *len = r + 1; /* for initial quote */
1249 name.len = maxlen - sizeof(WCHAR);
1251 while (isspace(buffer[*len])) (*len)++;
1252 if (buffer[*len] != '=') goto error;
1253 (*len)++;
1254 while (isspace(buffer[*len])) (*len)++;
1255 if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1256 return value;
1258 error:
1259 file_read_error( "Malformed value name", info );
1260 return NULL;
1263 /* load a value from the input file */
1264 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1266 DWORD dw;
1267 void *ptr, *newptr;
1268 int res, type, parse_type;
1269 data_size_t maxlen, len;
1270 struct key_value *value;
1272 if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1273 if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1274 buffer += len + res;
1276 switch(parse_type)
1278 case REG_SZ:
1279 len = strlen(buffer) * sizeof(WCHAR);
1280 if (!get_file_tmp_space( info, len )) return 0;
1281 if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1282 ptr = info->tmp;
1283 break;
1284 case REG_DWORD:
1285 dw = strtoul( buffer, NULL, 16 );
1286 ptr = &dw;
1287 len = sizeof(dw);
1288 break;
1289 case REG_BINARY: /* hex digits */
1290 len = 0;
1291 for (;;)
1293 maxlen = 1 + strlen(buffer)/3; /* 3 chars for one hex byte */
1294 if (!get_file_tmp_space( info, len + maxlen )) return 0;
1295 if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1296 len += maxlen;
1297 buffer += res;
1298 while (isspace(*buffer)) buffer++;
1299 if (!*buffer) break;
1300 if (*buffer != '\\') goto error;
1301 if (read_next_line( info) != 1) goto error;
1302 buffer = info->buffer;
1303 while (isspace(*buffer)) buffer++;
1305 ptr = info->tmp;
1306 break;
1307 default:
1308 assert(0);
1309 ptr = NULL; /* keep compiler quiet */
1310 break;
1313 if (!len) newptr = NULL;
1314 else if (!(newptr = memdup( ptr, len ))) return 0;
1316 free( value->data );
1317 value->data = newptr;
1318 value->len = len;
1319 value->type = type;
1320 make_dirty( key );
1321 return 1;
1323 error:
1324 file_read_error( "Malformed value", info );
1325 return 0;
1328 /* return the length (in path elements) of name that is part of the key name */
1329 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1330 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1332 WCHAR *p;
1333 int res;
1334 data_size_t len = strlen(name) * sizeof(WCHAR);
1336 if (!get_file_tmp_space( info, len )) return 0;
1338 if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1340 file_read_error( "Malformed key", info );
1341 return 0;
1343 for (p = info->tmp; *p; p++) if (*p == '\\') break;
1344 len = (p - info->tmp) * sizeof(WCHAR);
1345 for (res = 1; key != root_key; res++)
1347 if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1348 key = key->parent;
1350 if (key == root_key) res = 0; /* no matching name */
1351 return res;
1354 /* load all the keys from the input file */
1355 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1356 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1358 struct key *subkey = NULL;
1359 struct file_load_info info;
1360 char *p;
1361 int default_modif = time(NULL);
1362 int flags = (key->flags & KEY_VOLATILE) ? KEY_VOLATILE : KEY_DIRTY;
1364 info.filename = filename;
1365 info.file = f;
1366 info.len = 4;
1367 info.tmplen = 4;
1368 info.line = 0;
1369 if (!(info.buffer = mem_alloc( info.len ))) return;
1370 if (!(info.tmp = mem_alloc( info.tmplen )))
1372 free( info.buffer );
1373 return;
1376 if ((read_next_line( &info ) != 1) ||
1377 strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1379 set_error( STATUS_NOT_REGISTRY_FILE );
1380 goto done;
1383 while (read_next_line( &info ) == 1)
1385 p = info.buffer;
1386 while (*p && isspace(*p)) p++;
1387 switch(*p)
1389 case '[': /* new key */
1390 if (subkey) release_object( subkey );
1391 if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1392 if (!(subkey = load_key( key, p + 1, flags, prefix_len, &info, default_modif )))
1393 file_read_error( "Error creating key", &info );
1394 break;
1395 case '@': /* default value */
1396 case '\"': /* value */
1397 if (subkey) load_value( subkey, p, &info );
1398 else file_read_error( "Value without key", &info );
1399 break;
1400 case '#': /* comment */
1401 case ';': /* comment */
1402 case 0: /* empty line */
1403 break;
1404 default:
1405 file_read_error( "Unrecognized input", &info );
1406 break;
1410 done:
1411 if (subkey) release_object( subkey );
1412 free( info.buffer );
1413 free( info.tmp );
1416 /* load a part of the registry from a file */
1417 static void load_registry( struct key *key, obj_handle_t handle )
1419 struct file *file;
1420 int fd;
1422 if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1423 fd = dup( get_file_unix_fd( file ) );
1424 release_object( file );
1425 if (fd != -1)
1427 FILE *f = fdopen( fd, "r" );
1428 if (f)
1430 load_keys( key, NULL, f, -1 );
1431 fclose( f );
1433 else file_set_error();
1437 /* load one of the initial registry files */
1438 static void load_init_registry_from_file( const char *filename, struct key *key )
1440 FILE *f;
1442 if ((f = fopen( filename, "r" )))
1444 load_keys( key, filename, f, 0 );
1445 fclose( f );
1446 if (get_error() == STATUS_NOT_REGISTRY_FILE)
1448 fprintf( stderr, "%s is not a valid registry file\n", filename );
1449 return;
1453 assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1455 if ((save_branch_info[save_branch_count].path = strdup( filename )))
1457 save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1458 make_object_static( &key->obj );
1462 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1464 static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1465 static const WCHAR formatW[] = {'-','%','u',0};
1466 WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1467 WCHAR *p = buffer;
1468 unsigned int i;
1470 strcpyW( p, prefixW );
1471 p += strlenW( prefixW );
1472 p += sprintfW( p, formatW, sid->Revision );
1473 p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1474 sid->IdentifierAuthority.Value[4] ),
1475 MAKEWORD( sid->IdentifierAuthority.Value[3],
1476 sid->IdentifierAuthority.Value[2] )));
1477 for (i = 0; i < sid->SubAuthorityCount; i++)
1478 p += sprintfW( p, formatW, sid->SubAuthority[i] );
1480 path->len = (p - buffer) * sizeof(WCHAR);
1481 path->str = p = memdup( buffer, path->len );
1482 return p;
1485 /* registry initialisation */
1486 void init_registry(void)
1488 static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1489 static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1490 static const struct unicode_str root_name = { NULL, 0 };
1491 static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1492 static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1494 WCHAR *current_user_path;
1495 struct unicode_str current_user_str;
1497 const char *config = wine_get_config_dir();
1498 char *p, *filename;
1499 struct key *key;
1500 int dummy;
1502 /* create the root key */
1503 root_key = alloc_key( &root_name, time(NULL) );
1504 assert( root_key );
1505 make_object_static( &root_key->obj );
1507 if (!(filename = malloc( strlen(config) + 16 ))) fatal_error( "out of memory\n" );
1508 strcpy( filename, config );
1509 p = filename + strlen(filename);
1511 /* load system.reg into Registry\Machine */
1513 if (!(key = create_key( root_key, &HKLM_name, NULL, 0, time(NULL), &dummy )))
1514 fatal_error( "could not create Machine registry key\n" );
1516 strcpy( p, "/system.reg" );
1517 load_init_registry_from_file( filename, key );
1518 release_object( key );
1520 /* load userdef.reg into Registry\User\.Default */
1522 if (!(key = create_key( root_key, &HKU_name, NULL, 0, time(NULL), &dummy )))
1523 fatal_error( "could not create User\\.Default registry key\n" );
1525 strcpy( p, "/userdef.reg" );
1526 load_init_registry_from_file( filename, key );
1527 release_object( key );
1529 /* load user.reg into HKEY_CURRENT_USER */
1531 /* FIXME: match default user in token.c. should get from process token instead */
1532 current_user_path = format_user_registry_path( security_interactive_sid, &current_user_str );
1533 if (!current_user_path ||
1534 !(key = create_key( root_key, &current_user_str, NULL, 0, time(NULL), &dummy )))
1535 fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1536 free( current_user_path );
1537 strcpy( p, "/user.reg" );
1538 load_init_registry_from_file( filename, key );
1539 release_object( key );
1541 free( filename );
1543 /* start the periodic save timer */
1544 set_periodic_save_timer();
1547 /* save a registry branch to a file */
1548 static void save_all_subkeys( struct key *key, FILE *f )
1550 fprintf( f, "WINE REGISTRY Version 2\n" );
1551 fprintf( f, ";; All keys relative to " );
1552 dump_path( key, NULL, f );
1553 fprintf( f, "\n" );
1554 save_subkeys( key, key, f );
1557 /* save a registry branch to a file handle */
1558 static void save_registry( struct key *key, obj_handle_t handle )
1560 struct file *file;
1561 int fd;
1563 if (key->flags & KEY_DELETED)
1565 set_error( STATUS_KEY_DELETED );
1566 return;
1568 if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1569 fd = dup( get_file_unix_fd( file ) );
1570 release_object( file );
1571 if (fd != -1)
1573 FILE *f = fdopen( fd, "w" );
1574 if (f)
1576 save_all_subkeys( key, f );
1577 if (fclose( f )) file_set_error();
1579 else
1581 file_set_error();
1582 close( fd );
1587 /* save a registry branch to a file */
1588 static int save_branch( struct key *key, const char *path )
1590 struct stat st;
1591 char *p, *real, *tmp = NULL;
1592 int fd, count = 0, ret = 0, by_symlink;
1593 FILE *f;
1595 if (!(key->flags & KEY_DIRTY))
1597 if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1598 return 1;
1601 /* get the real path */
1603 by_symlink = (!lstat(path, &st) && S_ISLNK (st.st_mode));
1604 if (!(real = malloc( PATH_MAX ))) return 0;
1605 if (!realpath( path, real ))
1607 free( real );
1608 real = NULL;
1610 else path = real;
1612 /* test the file type */
1614 if ((fd = open( path, O_WRONLY )) != -1)
1616 /* if file is not a regular file or has multiple links or is accessed
1617 * via symbolic links, write directly into it; otherwise use a temp file */
1618 if (by_symlink ||
1619 (!fstat( fd, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1)))
1621 ftruncate( fd, 0 );
1622 goto save;
1624 close( fd );
1627 /* create a temp file in the same directory */
1629 if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1630 strcpy( tmp, path );
1631 if ((p = strrchr( tmp, '/' ))) p++;
1632 else p = tmp;
1633 for (;;)
1635 sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1636 if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1637 if (errno != EEXIST) goto done;
1638 close( fd );
1641 /* now save to it */
1643 save:
1644 if (!(f = fdopen( fd, "w" )))
1646 if (tmp) unlink( tmp );
1647 close( fd );
1648 goto done;
1651 if (debug_level > 1)
1653 fprintf( stderr, "%s: ", path );
1654 dump_operation( key, NULL, "saving" );
1657 save_all_subkeys( key, f );
1658 ret = !fclose(f);
1660 if (tmp)
1662 /* if successfully written, rename to final name */
1663 if (ret) ret = !rename( tmp, path );
1664 if (!ret) unlink( tmp );
1667 done:
1668 free( tmp );
1669 free( real );
1670 if (ret) make_clean( key );
1671 return ret;
1674 /* periodic saving of the registry */
1675 static void periodic_save( void *arg )
1677 int i;
1679 save_timeout_user = NULL;
1680 for (i = 0; i < save_branch_count; i++)
1681 save_branch( save_branch_info[i].key, save_branch_info[i].path );
1682 set_periodic_save_timer();
1685 /* start the periodic save timer */
1686 static void set_periodic_save_timer(void)
1688 if (save_timeout_user) remove_timeout_user( save_timeout_user );
1689 save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
1692 /* save the modified registry branches to disk */
1693 void flush_registry(void)
1695 int i;
1697 for (i = 0; i < save_branch_count; i++)
1699 if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
1701 fprintf( stderr, "wineserver: could not save registry branch to %s",
1702 save_branch_info[i].path );
1703 perror( " " );
1709 /* create a registry key */
1710 DECL_HANDLER(create_key)
1712 struct key *key = NULL, *parent;
1713 struct unicode_str name, class;
1714 unsigned int access = req->access;
1716 reply->hkey = 0;
1718 if (req->namelen > get_req_data_size())
1720 set_error( STATUS_INVALID_PARAMETER );
1721 return;
1723 class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
1724 class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
1725 get_req_path( &name, !req->parent );
1726 if (name.str > class.str)
1728 set_error( STATUS_INVALID_PARAMETER );
1729 return;
1731 name.len = (class.str - name.str) * sizeof(WCHAR);
1733 /* NOTE: no access rights are required from the parent handle to create a key */
1734 if ((parent = get_parent_hkey_obj( req->parent )))
1736 int flags = (req->options & REG_OPTION_VOLATILE) ? KEY_VOLATILE : KEY_DIRTY;
1738 if ((key = create_key( parent, &name, &class, flags, req->modif, &reply->created )))
1740 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1741 release_object( key );
1743 release_object( parent );
1747 /* open a registry key */
1748 DECL_HANDLER(open_key)
1750 struct key *key, *parent;
1751 struct unicode_str name;
1752 unsigned int access = req->access;
1754 reply->hkey = 0;
1755 /* NOTE: no access rights are required to open the parent key, only the child key */
1756 if ((parent = get_parent_hkey_obj( req->parent )))
1758 get_req_path( &name, !req->parent );
1759 if ((key = open_key( parent, &name )))
1761 reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1762 release_object( key );
1764 release_object( parent );
1768 /* delete a registry key */
1769 DECL_HANDLER(delete_key)
1771 struct key *key;
1773 if ((key = get_hkey_obj( req->hkey, DELETE )))
1775 delete_key( key, 0);
1776 release_object( key );
1780 /* flush a registry key */
1781 DECL_HANDLER(flush_key)
1783 struct key *key = get_hkey_obj( req->hkey, 0 );
1784 if (key)
1786 /* we don't need to do anything here with the current implementation */
1787 release_object( key );
1791 /* enumerate registry subkeys */
1792 DECL_HANDLER(enum_key)
1794 struct key *key;
1796 if ((key = get_hkey_obj( req->hkey,
1797 req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
1799 enum_key( key, req->index, req->info_class, reply );
1800 release_object( key );
1804 /* set a value of a registry key */
1805 DECL_HANDLER(set_key_value)
1807 struct key *key;
1808 struct unicode_str name;
1810 if (req->namelen > get_req_data_size())
1812 set_error( STATUS_INVALID_PARAMETER );
1813 return;
1815 name.str = get_req_data();
1816 name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
1818 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
1820 data_size_t datalen = get_req_data_size() - req->namelen;
1821 const char *data = (const char *)get_req_data() + req->namelen;
1823 set_value( key, &name, req->type, data, datalen );
1824 release_object( key );
1828 /* retrieve the value of a registry key */
1829 DECL_HANDLER(get_key_value)
1831 struct key *key;
1832 struct unicode_str name;
1834 reply->total = 0;
1835 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
1837 get_req_unicode_str( &name );
1838 get_value( key, &name, &reply->type, &reply->total );
1839 release_object( key );
1843 /* enumerate the value of a registry key */
1844 DECL_HANDLER(enum_key_value)
1846 struct key *key;
1848 if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
1850 enum_value( key, req->index, req->info_class, reply );
1851 release_object( key );
1855 /* delete a value of a registry key */
1856 DECL_HANDLER(delete_key_value)
1858 struct key *key;
1859 struct unicode_str name;
1861 if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
1863 get_req_unicode_str( &name );
1864 delete_value( key, &name );
1865 release_object( key );
1869 /* load a registry branch from a file */
1870 DECL_HANDLER(load_registry)
1872 struct key *key, *parent;
1873 struct token *token = thread_get_impersonation_token( current );
1874 struct unicode_str name;
1876 const LUID_AND_ATTRIBUTES privs[] =
1878 { SeBackupPrivilege, 0 },
1879 { SeRestorePrivilege, 0 },
1882 if (!token || !token_check_privileges( token, TRUE, privs,
1883 sizeof(privs)/sizeof(privs[0]), NULL ))
1885 set_error( STATUS_PRIVILEGE_NOT_HELD );
1886 return;
1889 if ((parent = get_parent_hkey_obj( req->hkey )))
1891 int dummy;
1892 get_req_path( &name, !req->hkey );
1893 if ((key = create_key( parent, &name, NULL, KEY_DIRTY, time(NULL), &dummy )))
1895 load_registry( key, req->file );
1896 release_object( key );
1898 release_object( parent );
1902 DECL_HANDLER(unload_registry)
1904 struct key *key;
1905 struct token *token = thread_get_impersonation_token( current );
1907 const LUID_AND_ATTRIBUTES privs[] =
1909 { SeBackupPrivilege, 0 },
1910 { SeRestorePrivilege, 0 },
1913 if (!token || !token_check_privileges( token, TRUE, privs,
1914 sizeof(privs)/sizeof(privs[0]), NULL ))
1916 set_error( STATUS_PRIVILEGE_NOT_HELD );
1917 return;
1920 if ((key = get_hkey_obj( req->hkey, 0 )))
1922 delete_key( key, 1 ); /* FIXME */
1923 release_object( key );
1927 /* save a registry branch to a file */
1928 DECL_HANDLER(save_registry)
1930 struct key *key;
1932 if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
1934 set_error( STATUS_PRIVILEGE_NOT_HELD );
1935 return;
1938 if ((key = get_hkey_obj( req->hkey, 0 )))
1940 save_registry( key, req->file );
1941 release_object( key );
1945 /* add a registry key change notification */
1946 DECL_HANDLER(set_registry_notification)
1948 struct key *key;
1949 struct event *event;
1950 struct notify *notify;
1952 key = get_hkey_obj( req->hkey, KEY_NOTIFY );
1953 if (key)
1955 event = get_event_obj( current->process, req->event, SYNCHRONIZE );
1956 if (event)
1958 notify = find_notify( key, current->process, req->hkey );
1959 if (notify)
1961 if (notify->event)
1962 release_object( notify->event );
1963 grab_object( event );
1964 notify->event = event;
1966 else
1968 notify = mem_alloc( sizeof(*notify) );
1969 if (notify)
1971 grab_object( event );
1972 notify->event = event;
1973 notify->subtree = req->subtree;
1974 notify->filter = req->filter;
1975 notify->hkey = req->hkey;
1976 notify->process = current->process;
1977 list_add_head( &key->notify_list, &notify->entry );
1980 release_object( event );
1982 release_object( key );