server: Added access rights mapping to file objects.
[wine] / server / registry.c
1 /*
2  * Server-side registry management
3  *
4  * Copyright (C) 1999 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /* To do:
22  * - symbolic links
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39
40 #include "ntstatus.h"
41 #define WIN32_NO_STATUS
42 #include "object.h"
43 #include "file.h"
44 #include "handle.h"
45 #include "request.h"
46 #include "unicode.h"
47 #include "security.h"
48
49 #include "winternl.h"
50 #include "wine/library.h"
51
52 struct notify
53 {
54     struct list       entry;    /* entry in list of notifications */
55     struct event     *event;    /* event to set when changing this key */
56     int               subtree;  /* true if subtree notification */
57     unsigned int      filter;   /* which events to notify on */
58     obj_handle_t      hkey;     /* hkey associated with this notification */
59     struct process   *process;  /* process in which the hkey is valid */
60 };
61
62 /* a registry key */
63 struct key
64 {
65     struct object     obj;         /* object header */
66     WCHAR            *name;        /* key name */
67     WCHAR            *class;       /* key class */
68     unsigned short    namelen;     /* length of key name */
69     unsigned short    classlen;    /* length of class name */
70     struct key       *parent;      /* parent key */
71     int               last_subkey; /* last in use subkey */
72     int               nb_subkeys;  /* count of allocated subkeys */
73     struct key      **subkeys;     /* subkeys array */
74     int               last_value;  /* last in use value */
75     int               nb_values;   /* count of allocated values in array */
76     struct key_value *values;      /* values array */
77     unsigned int      flags;       /* flags */
78     time_t            modif;       /* last modification time */
79     struct list       notify_list; /* list of notifications */
80 };
81
82 /* key flags */
83 #define KEY_VOLATILE 0x0001  /* key is volatile (not saved to disk) */
84 #define KEY_DELETED  0x0002  /* key has been deleted */
85 #define KEY_DIRTY    0x0004  /* key has been modified */
86
87 /* a key value */
88 struct key_value
89 {
90     WCHAR            *name;    /* value name */
91     unsigned short    namelen; /* length of value name */
92     unsigned short    type;    /* value type */
93     size_t            len;     /* value data length in bytes */
94     void             *data;    /* pointer to value data */
95 };
96
97 #define MIN_SUBKEYS  8   /* min. number of allocated subkeys per key */
98 #define MIN_VALUES   8   /* min. number of allocated values per key */
99
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 */
102
103 /* the root of the registry tree */
104 static struct key *root_key;
105
106 static const int save_period = 30000;           /* delay between periodic saves (in ms) */
107 static struct timeout_user *save_timeout_user;  /* saving timer */
108
109 static void set_periodic_save_timer(void);
110
111 /* information about where to save a registry branch */
112 struct save_branch_info
113 {
114     struct key  *key;
115     char        *path;
116 };
117
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];
121
122
123 /* information about a file being loaded */
124 struct file_load_info
125 {
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 */
133 };
134
135
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 );
140
141 static const struct object_ops key_ops =
142 {
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     no_lookup_name,          /* lookup_name */
153     key_close_handle,        /* close_handle */
154     key_destroy              /* destroy */
155 };
156
157
158 /*
159  * The registry text file format v2 used by this code is similar to the one
160  * used by REGEDIT import/export functionality, with the following differences:
161  * - strings and key names can contain \x escapes for Unicode
162  * - key names use escapes too in order to support Unicode
163  * - the modification time optionally follows the key name
164  * - REG_EXPAND_SZ and REG_MULTI_SZ are saved as strings instead of hex
165  */
166
167 static inline char to_hex( char ch )
168 {
169     if (isdigit(ch)) return ch - '0';
170     return tolower(ch) - 'a' + 10;
171 }
172
173 /* dump the full path of a key */
174 static void dump_path( const struct key *key, const struct key *base, FILE *f )
175 {
176     if (key->parent && key->parent != base)
177     {
178         dump_path( key->parent, base, f );
179         fprintf( f, "\\\\" );
180     }
181     dump_strW( key->name, key->namelen / sizeof(WCHAR), f, "[]" );
182 }
183
184 /* dump a value to a text file */
185 static void dump_value( const struct key_value *value, FILE *f )
186 {
187     unsigned int i;
188     int count;
189
190     if (value->namelen)
191     {
192         fputc( '\"', f );
193         count = 1 + dump_strW( value->name, value->namelen / sizeof(WCHAR), f, "\"\"" );
194         count += fprintf( f, "\"=" );
195     }
196     else count = fprintf( f, "@=" );
197
198     switch(value->type)
199     {
200     case REG_SZ:
201     case REG_EXPAND_SZ:
202     case REG_MULTI_SZ:
203         if (value->type != REG_SZ) fprintf( f, "str(%d):", value->type );
204         fputc( '\"', f );
205         if (value->data) dump_strW( (WCHAR *)value->data, value->len / sizeof(WCHAR), f, "\"\"" );
206         fputc( '\"', f );
207         break;
208     case REG_DWORD:
209         if (value->len == sizeof(DWORD))
210         {
211             DWORD dw;
212             memcpy( &dw, value->data, sizeof(DWORD) );
213             fprintf( f, "dword:%08lx", dw );
214             break;
215         }
216         /* else fall through */
217     default:
218         if (value->type == REG_BINARY) count += fprintf( f, "hex:" );
219         else count += fprintf( f, "hex(%x):", value->type );
220         for (i = 0; i < value->len; i++)
221         {
222             count += fprintf( f, "%02x", *((unsigned char *)value->data + i) );
223             if (i < value->len-1)
224             {
225                 fputc( ',', f );
226                 if (++count > 76)
227                 {
228                     fprintf( f, "\\\n  " );
229                     count = 2;
230                 }
231             }
232         }
233         break;
234     }
235     fputc( '\n', f );
236 }
237
238 /* save a registry and all its subkeys to a text file */
239 static void save_subkeys( const struct key *key, const struct key *base, FILE *f )
240 {
241     int i;
242
243     if (key->flags & KEY_VOLATILE) return;
244     /* save key if it has either some values or no subkeys */
245     /* keys with no values but subkeys are saved implicitly by saving the subkeys */
246     if ((key->last_value >= 0) || (key->last_subkey == -1))
247     {
248         fprintf( f, "\n[" );
249         if (key != base) dump_path( key, base, f );
250         fprintf( f, "] %ld\n", (long)key->modif );
251         for (i = 0; i <= key->last_value; i++) dump_value( &key->values[i], f );
252     }
253     for (i = 0; i <= key->last_subkey; i++) save_subkeys( key->subkeys[i], base, f );
254 }
255
256 static void dump_operation( const struct key *key, const struct key_value *value, const char *op )
257 {
258     fprintf( stderr, "%s key ", op );
259     if (key) dump_path( key, NULL, stderr );
260     else fprintf( stderr, "ERROR" );
261     if (value)
262     {
263         fprintf( stderr, " value ");
264         dump_value( value, stderr );
265     }
266     else fprintf( stderr, "\n" );
267 }
268
269 static void key_dump( struct object *obj, int verbose )
270 {
271     struct key *key = (struct key *)obj;
272     assert( obj->ops == &key_ops );
273     fprintf( stderr, "Key flags=%x ", key->flags );
274     dump_path( key, NULL, stderr );
275     fprintf( stderr, "\n" );
276 }
277
278 /* notify waiter and maybe delete the notification */
279 static void do_notification( struct key *key, struct notify *notify, int del )
280 {
281     if (notify->event)
282     {
283         set_event( notify->event );
284         release_object( notify->event );
285         notify->event = NULL;
286     }
287     if (del)
288     {
289         list_remove( &notify->entry );
290         free( notify );
291     }
292 }
293
294 static inline struct notify *find_notify( struct key *key, struct process *process, obj_handle_t hkey )
295 {
296     struct notify *notify;
297
298     LIST_FOR_EACH_ENTRY( notify, &key->notify_list, struct notify, entry )
299     {
300         if (notify->process == process && notify->hkey == hkey) return notify;
301     }
302     return NULL;
303 }
304
305 static unsigned int key_map_access( struct object *obj, unsigned int access )
306 {
307     if (access & GENERIC_READ)    access |= KEY_READ;
308     if (access & GENERIC_WRITE)   access |= KEY_WRITE;
309     if (access & GENERIC_EXECUTE) access |= KEY_EXECUTE;
310     if (access & GENERIC_ALL)     access |= KEY_ALL_ACCESS;
311     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
312 }
313
314 /* close the notification associated with a handle */
315 static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
316 {
317     struct key * key = (struct key *) obj;
318     struct notify *notify = find_notify( key, process, handle );
319     if (notify) do_notification( key, notify, 1 );
320     return 1;  /* ok to close */
321 }
322
323 static void key_destroy( struct object *obj )
324 {
325     int i;
326     struct list *ptr;
327     struct key *key = (struct key *)obj;
328     assert( obj->ops == &key_ops );
329
330     if (key->name) free( key->name );
331     if (key->class) free( key->class );
332     for (i = 0; i <= key->last_value; i++)
333     {
334         if (key->values[i].name) free( key->values[i].name );
335         if (key->values[i].data) free( key->values[i].data );
336     }
337     if (key->values) free( key->values );
338     for (i = 0; i <= key->last_subkey; i++)
339     {
340         key->subkeys[i]->parent = NULL;
341         release_object( key->subkeys[i] );
342     }
343     if (key->subkeys) free( key->subkeys );
344     /* unconditionally notify everything waiting on this key */
345     while ((ptr = list_head( &key->notify_list )))
346     {
347         struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
348         do_notification( key, notify, 1 );
349     }
350 }
351
352 /* get the request vararg as registry path */
353 inline static void get_req_path( struct unicode_str *str, int skip_root )
354 {
355     static const WCHAR root_name[] = { '\\','R','e','g','i','s','t','r','y','\\' };
356
357     str->str = get_req_data();
358     str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
359
360     if (skip_root && str->len >= sizeof(root_name) &&
361         !memicmpW( str->str, root_name, sizeof(root_name)/sizeof(WCHAR) ))
362     {
363         str->str += sizeof(root_name)/sizeof(WCHAR);
364         str->len -= sizeof(root_name);
365     }
366 }
367
368 /* return the next token in a given path */
369 /* token->str must point inside the path, or be NULL for the first call */
370 static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
371 {
372     size_t i = 0, len = path->len / sizeof(WCHAR);
373
374     if (!token->str)  /* first time */
375     {
376         /* path cannot start with a backslash */
377         if (len && path->str[0] == '\\')
378         {
379             set_error( STATUS_OBJECT_PATH_INVALID );
380             return NULL;
381         }
382     }
383     else
384     {
385         i = token->str - path->str;
386         i += token->len / sizeof(WCHAR);
387         while (i < len && path->str[i] == '\\') i++;
388     }
389     token->str = path->str + i;
390     while (i < len && path->str[i] != '\\') i++;
391     token->len = (path->str + i - token->str) * sizeof(WCHAR);
392     return token;
393 }
394
395 /* allocate a key object */
396 static struct key *alloc_key( const struct unicode_str *name, time_t modif )
397 {
398     struct key *key;
399     if ((key = alloc_object( &key_ops )))
400     {
401         key->name        = NULL;
402         key->class       = NULL;
403         key->namelen     = name->len;
404         key->classlen    = 0;
405         key->flags       = 0;
406         key->last_subkey = -1;
407         key->nb_subkeys  = 0;
408         key->subkeys     = NULL;
409         key->nb_values   = 0;
410         key->last_value  = -1;
411         key->values      = NULL;
412         key->modif       = modif;
413         key->parent      = NULL;
414         list_init( &key->notify_list );
415         if (name->len && !(key->name = memdup( name->str, name->len )))
416         {
417             release_object( key );
418             key = NULL;
419         }
420     }
421     return key;
422 }
423
424 /* mark a key and all its parents as dirty (modified) */
425 static void make_dirty( struct key *key )
426 {
427     while (key)
428     {
429         if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return;  /* nothing to do */
430         key->flags |= KEY_DIRTY;
431         key = key->parent;
432     }
433 }
434
435 /* mark a key and all its subkeys as clean (not modified) */
436 static void make_clean( struct key *key )
437 {
438     int i;
439
440     if (key->flags & KEY_VOLATILE) return;
441     if (!(key->flags & KEY_DIRTY)) return;
442     key->flags &= ~KEY_DIRTY;
443     for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
444 }
445
446 /* go through all the notifications and send them if necessary */
447 static void check_notify( struct key *key, unsigned int change, int not_subtree )
448 {
449     struct list *ptr, *next;
450
451     LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
452     {
453         struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
454         if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
455             do_notification( key, n, 0 );
456     }
457 }
458
459 /* update key modification time */
460 static void touch_key( struct key *key, unsigned int change )
461 {
462     struct key *k;
463
464     key->modif = time(NULL);
465     make_dirty( key );
466
467     /* do notifications */
468     check_notify( key, change, 1 );
469     for ( k = key->parent; k; k = k->parent )
470         check_notify( k, change & ~REG_NOTIFY_CHANGE_LAST_SET, 0 );
471 }
472
473 /* try to grow the array of subkeys; return 1 if OK, 0 on error */
474 static int grow_subkeys( struct key *key )
475 {
476     struct key **new_subkeys;
477     int nb_subkeys;
478
479     if (key->nb_subkeys)
480     {
481         nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2);  /* grow by 50% */
482         if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
483         {
484             set_error( STATUS_NO_MEMORY );
485             return 0;
486         }
487     }
488     else
489     {
490         nb_subkeys = MIN_VALUES;
491         if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
492     }
493     key->subkeys    = new_subkeys;
494     key->nb_subkeys = nb_subkeys;
495     return 1;
496 }
497
498 /* allocate a subkey for a given key, and return its index */
499 static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
500                                  int index, time_t modif )
501 {
502     struct key *key;
503     int i;
504
505     if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
506     {
507         set_error( STATUS_NAME_TOO_LONG );
508         return NULL;
509     }
510     if (parent->last_subkey + 1 == parent->nb_subkeys)
511     {
512         /* need to grow the array */
513         if (!grow_subkeys( parent )) return NULL;
514     }
515     if ((key = alloc_key( name, modif )) != NULL)
516     {
517         key->parent = parent;
518         for (i = ++parent->last_subkey; i > index; i--)
519             parent->subkeys[i] = parent->subkeys[i-1];
520         parent->subkeys[index] = key;
521     }
522     return key;
523 }
524
525 /* free a subkey of a given key */
526 static void free_subkey( struct key *parent, int index )
527 {
528     struct key *key;
529     int i, nb_subkeys;
530
531     assert( index >= 0 );
532     assert( index <= parent->last_subkey );
533
534     key = parent->subkeys[index];
535     for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
536     parent->last_subkey--;
537     key->flags |= KEY_DELETED;
538     key->parent = NULL;
539     release_object( key );
540
541     /* try to shrink the array */
542     nb_subkeys = parent->nb_subkeys;
543     if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
544     {
545         struct key **new_subkeys;
546         nb_subkeys -= nb_subkeys / 3;  /* shrink by 33% */
547         if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
548         if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
549         parent->subkeys = new_subkeys;
550         parent->nb_subkeys = nb_subkeys;
551     }
552 }
553
554 /* find the named child of a given key and return its index */
555 static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
556 {
557     int i, min, max, res;
558     size_t len;
559
560     min = 0;
561     max = key->last_subkey;
562     while (min <= max)
563     {
564         i = (min + max) / 2;
565         len = min( key->subkeys[i]->namelen, name->len );
566         res = memicmpW( key->subkeys[i]->name, name->str, len / sizeof(WCHAR) );
567         if (!res) res = key->subkeys[i]->namelen - name->len;
568         if (!res)
569         {
570             *index = i;
571             return key->subkeys[i];
572         }
573         if (res > 0) max = i - 1;
574         else min = i + 1;
575     }
576     *index = min;  /* this is where we should insert it */
577     return NULL;
578 }
579
580 /* open a subkey */
581 static struct key *open_key( struct key *key, const struct unicode_str *name )
582 {
583     int index;
584     struct unicode_str token;
585
586     token.str = NULL;
587     if (!get_path_token( name, &token )) return NULL;
588     while (token.len)
589     {
590         if (!(key = find_subkey( key, &token, &index )))
591         {
592             set_error( STATUS_OBJECT_NAME_NOT_FOUND );
593             break;
594         }
595         get_path_token( name, &token );
596     }
597
598     if (debug_level > 1) dump_operation( key, NULL, "Open" );
599     if (key) grab_object( key );
600     return key;
601 }
602
603 /* create a subkey */
604 static struct key *create_key( struct key *key, const struct unicode_str *name,
605                                const struct unicode_str *class, int flags, time_t modif, int *created )
606 {
607     struct key *base;
608     int index;
609     struct unicode_str token;
610
611     if (key->flags & KEY_DELETED) /* we cannot create a subkey under a deleted key */
612     {
613         set_error( STATUS_KEY_DELETED );
614         return NULL;
615     }
616     if (!(flags & KEY_VOLATILE) && (key->flags & KEY_VOLATILE))
617     {
618         set_error( STATUS_CHILD_MUST_BE_VOLATILE );
619         return NULL;
620     }
621     if (!modif) modif = time(NULL);
622
623     token.str = NULL;
624     if (!get_path_token( name, &token )) return NULL;
625     *created = 0;
626     while (token.len)
627     {
628         struct key *subkey;
629         if (!(subkey = find_subkey( key, &token, &index ))) break;
630         key = subkey;
631         get_path_token( name, &token );
632     }
633
634     /* create the remaining part */
635
636     if (!token.len) goto done;
637     *created = 1;
638     if (flags & KEY_DIRTY) make_dirty( key );
639     if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
640     base = key;
641     for (;;)
642     {
643         key->flags |= flags;
644         get_path_token( name, &token );
645         if (!token.len) break;
646         /* we know the index is always 0 in a new key */
647         if (!(key = alloc_subkey( key, &token, 0, modif )))
648         {
649             free_subkey( base, index );
650             return NULL;
651         }
652     }
653
654  done:
655     if (debug_level > 1) dump_operation( key, NULL, "Create" );
656     if (class && class->len)
657     {
658         key->classlen = class->len;
659         if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
660     }
661     grab_object( key );
662     return key;
663 }
664
665 /* query information about a key or a subkey */
666 static void enum_key( const struct key *key, int index, int info_class,
667                       struct enum_key_reply *reply )
668 {
669     int i;
670     size_t len, namelen, classlen;
671     int max_subkey = 0, max_class = 0;
672     int max_value = 0, max_data = 0;
673     char *data;
674
675     if (index != -1)  /* -1 means use the specified key directly */
676     {
677         if ((index < 0) || (index > key->last_subkey))
678         {
679             set_error( STATUS_NO_MORE_ENTRIES );
680             return;
681         }
682         key = key->subkeys[index];
683     }
684
685     namelen = key->namelen;
686     classlen = key->classlen;
687
688     switch(info_class)
689     {
690     case KeyBasicInformation:
691         classlen = 0; /* only return the name */
692         /* fall through */
693     case KeyNodeInformation:
694         reply->max_subkey = 0;
695         reply->max_class  = 0;
696         reply->max_value  = 0;
697         reply->max_data   = 0;
698         break;
699     case KeyFullInformation:
700         for (i = 0; i <= key->last_subkey; i++)
701         {
702             struct key *subkey = key->subkeys[i];
703             len = subkey->namelen / sizeof(WCHAR);
704             if (len > max_subkey) max_subkey = len;
705             len = subkey->classlen / sizeof(WCHAR);
706             if (len > max_class) max_class = len;
707         }
708         for (i = 0; i <= key->last_value; i++)
709         {
710             len = key->values[i].namelen / sizeof(WCHAR);
711             if (len > max_value) max_value = len;
712             len = key->values[i].len;
713             if (len > max_data) max_data = len;
714         }
715         reply->max_subkey = max_subkey;
716         reply->max_class  = max_class;
717         reply->max_value  = max_value;
718         reply->max_data   = max_data;
719         namelen = 0;  /* only return the class */
720         break;
721     default:
722         set_error( STATUS_INVALID_PARAMETER );
723         return;
724     }
725     reply->subkeys = key->last_subkey + 1;
726     reply->values  = key->last_value + 1;
727     reply->modif   = key->modif;
728     reply->total   = namelen + classlen;
729
730     len = min( reply->total, get_reply_max_size() );
731     if (len && (data = set_reply_data_size( len )))
732     {
733         if (len > namelen)
734         {
735             reply->namelen = namelen;
736             memcpy( data, key->name, namelen );
737             memcpy( data + namelen, key->class, len - namelen );
738         }
739         else
740         {
741             reply->namelen = len;
742             memcpy( data, key->name, len );
743         }
744     }
745     if (debug_level > 1) dump_operation( key, NULL, "Enum" );
746 }
747
748 /* delete a key and its values */
749 static int delete_key( struct key *key, int recurse )
750 {
751     int index;
752     struct key *parent;
753
754     /* must find parent and index */
755     if (key == root_key)
756     {
757         set_error( STATUS_ACCESS_DENIED );
758         return -1;
759     }
760     if (!(parent = key->parent) || (key->flags & KEY_DELETED))
761     {
762         set_error( STATUS_KEY_DELETED );
763         return -1;
764     }
765
766     while (recurse && (key->last_subkey>=0))
767         if (0 > delete_key(key->subkeys[key->last_subkey], 1))
768             return -1;
769
770     for (index = 0; index <= parent->last_subkey; index++)
771         if (parent->subkeys[index] == key) break;
772     assert( index <= parent->last_subkey );
773
774     /* we can only delete a key that has no subkeys */
775     if (key->last_subkey >= 0)
776     {
777         set_error( STATUS_ACCESS_DENIED );
778         return -1;
779     }
780
781     if (debug_level > 1) dump_operation( key, NULL, "Delete" );
782     free_subkey( parent, index );
783     touch_key( parent, REG_NOTIFY_CHANGE_NAME );
784     return 0;
785 }
786
787 /* try to grow the array of values; return 1 if OK, 0 on error */
788 static int grow_values( struct key *key )
789 {
790     struct key_value *new_val;
791     int nb_values;
792
793     if (key->nb_values)
794     {
795         nb_values = key->nb_values + (key->nb_values / 2);  /* grow by 50% */
796         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
797         {
798             set_error( STATUS_NO_MEMORY );
799             return 0;
800         }
801     }
802     else
803     {
804         nb_values = MIN_VALUES;
805         if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
806     }
807     key->values = new_val;
808     key->nb_values = nb_values;
809     return 1;
810 }
811
812 /* find the named value of a given key and return its index in the array */
813 static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
814 {
815     int i, min, max, res;
816     size_t len;
817
818     min = 0;
819     max = key->last_value;
820     while (min <= max)
821     {
822         i = (min + max) / 2;
823         len = min( key->values[i].namelen, name->len );
824         res = memicmpW( key->values[i].name, name->str, len / sizeof(WCHAR) );
825         if (!res) res = key->values[i].namelen - name->len;
826         if (!res)
827         {
828             *index = i;
829             return &key->values[i];
830         }
831         if (res > 0) max = i - 1;
832         else min = i + 1;
833     }
834     *index = min;  /* this is where we should insert it */
835     return NULL;
836 }
837
838 /* insert a new value; the index must have been returned by find_value */
839 static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
840 {
841     struct key_value *value;
842     WCHAR *new_name = NULL;
843     int i;
844
845     if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
846     {
847         set_error( STATUS_NAME_TOO_LONG );
848         return NULL;
849     }
850     if (key->last_value + 1 == key->nb_values)
851     {
852         if (!grow_values( key )) return NULL;
853     }
854     if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
855     for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
856     value = &key->values[index];
857     value->name    = new_name;
858     value->namelen = name->len;
859     value->len     = 0;
860     value->data    = NULL;
861     return value;
862 }
863
864 /* set a key value */
865 static void set_value( struct key *key, const struct unicode_str *name,
866                        int type, const void *data, size_t len )
867 {
868     struct key_value *value;
869     void *ptr = NULL;
870     int index;
871
872     if ((value = find_value( key, name, &index )))
873     {
874         /* check if the new value is identical to the existing one */
875         if (value->type == type && value->len == len &&
876             value->data && !memcmp( value->data, data, len ))
877         {
878             if (debug_level > 1) dump_operation( key, value, "Skip setting" );
879             return;
880         }
881     }
882
883     if (len && !(ptr = memdup( data, len ))) return;
884
885     if (!value)
886     {
887         if (!(value = insert_value( key, name, index )))
888         {
889             if (ptr) free( ptr );
890             return;
891         }
892     }
893     else if (value->data) free( value->data ); /* already existing, free previous data */
894
895     value->type  = type;
896     value->len   = len;
897     value->data  = ptr;
898     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
899     if (debug_level > 1) dump_operation( key, value, "Set" );
900 }
901
902 /* get a key value */
903 static void get_value( struct key *key, const struct unicode_str *name, int *type, size_t *len )
904 {
905     struct key_value *value;
906     int index;
907
908     if ((value = find_value( key, name, &index )))
909     {
910         *type = value->type;
911         *len  = value->len;
912         if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
913         if (debug_level > 1) dump_operation( key, value, "Get" );
914     }
915     else
916     {
917         *type = -1;
918         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
919     }
920 }
921
922 /* enumerate a key value */
923 static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
924 {
925     struct key_value *value;
926
927     if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
928     else
929     {
930         void *data;
931         size_t namelen, maxlen;
932
933         value = &key->values[i];
934         reply->type = value->type;
935         namelen = value->namelen;
936
937         switch(info_class)
938         {
939         case KeyValueBasicInformation:
940             reply->total = namelen;
941             break;
942         case KeyValueFullInformation:
943             reply->total = namelen + value->len;
944             break;
945         case KeyValuePartialInformation:
946             reply->total = value->len;
947             namelen = 0;
948             break;
949         default:
950             set_error( STATUS_INVALID_PARAMETER );
951             return;
952         }
953
954         maxlen = min( reply->total, get_reply_max_size() );
955         if (maxlen && ((data = set_reply_data_size( maxlen ))))
956         {
957             if (maxlen > namelen)
958             {
959                 reply->namelen = namelen;
960                 memcpy( data, value->name, namelen );
961                 memcpy( (char *)data + namelen, value->data, maxlen - namelen );
962             }
963             else
964             {
965                 reply->namelen = maxlen;
966                 memcpy( data, value->name, maxlen );
967             }
968         }
969         if (debug_level > 1) dump_operation( key, value, "Enum" );
970     }
971 }
972
973 /* delete a value */
974 static void delete_value( struct key *key, const struct unicode_str *name )
975 {
976     struct key_value *value;
977     int i, index, nb_values;
978
979     if (!(value = find_value( key, name, &index )))
980     {
981         set_error( STATUS_OBJECT_NAME_NOT_FOUND );
982         return;
983     }
984     if (debug_level > 1) dump_operation( key, value, "Delete" );
985     if (value->name) free( value->name );
986     if (value->data) free( value->data );
987     for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
988     key->last_value--;
989     touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
990
991     /* try to shrink the array */
992     nb_values = key->nb_values;
993     if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
994     {
995         struct key_value *new_val;
996         nb_values -= nb_values / 3;  /* shrink by 33% */
997         if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
998         if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
999         key->values = new_val;
1000         key->nb_values = nb_values;
1001     }
1002 }
1003
1004 /* get the registry key corresponding to an hkey handle */
1005 static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1006 {
1007     if (!hkey) return (struct key *)grab_object( root_key );
1008     return (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );
1009 }
1010
1011 /* read a line from the input file */
1012 static int read_next_line( struct file_load_info *info )
1013 {
1014     char *newbuf;
1015     int newlen, pos = 0;
1016
1017     info->line++;
1018     for (;;)
1019     {
1020         if (!fgets( info->buffer + pos, info->len - pos, info->file ))
1021             return (pos != 0);  /* EOF */
1022         pos = strlen(info->buffer);
1023         if (info->buffer[pos-1] == '\n')
1024         {
1025             /* got a full line */
1026             info->buffer[--pos] = 0;
1027             if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
1028             return 1;
1029         }
1030         if (pos < info->len - 1) return 1;  /* EOF but something was read */
1031
1032         /* need to enlarge the buffer */
1033         newlen = info->len + info->len / 2;
1034         if (!(newbuf = realloc( info->buffer, newlen )))
1035         {
1036             set_error( STATUS_NO_MEMORY );
1037             return -1;
1038         }
1039         info->buffer = newbuf;
1040         info->len = newlen;
1041     }
1042 }
1043
1044 /* make sure the temp buffer holds enough space */
1045 static int get_file_tmp_space( struct file_load_info *info, size_t size )
1046 {
1047     WCHAR *tmp;
1048     if (info->tmplen >= size) return 1;
1049     if (!(tmp = realloc( info->tmp, size )))
1050     {
1051         set_error( STATUS_NO_MEMORY );
1052         return 0;
1053     }
1054     info->tmp = tmp;
1055     info->tmplen = size;
1056     return 1;
1057 }
1058
1059 /* report an error while loading an input file */
1060 static void file_read_error( const char *err, struct file_load_info *info )
1061 {
1062     if (info->filename)
1063         fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
1064     else
1065         fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1066 }
1067
1068 /* parse an escaped string back into Unicode */
1069 /* return the number of chars read from the input, or -1 on output overflow */
1070 static int parse_strW( WCHAR *dest, size_t *len, const char *src, char endchar )
1071 {
1072     size_t count = sizeof(WCHAR);  /* for terminating null */
1073     const char *p = src;
1074     while (*p && *p != endchar)
1075     {
1076         if (*p != '\\') *dest = (WCHAR)*p++;
1077         else
1078         {
1079             p++;
1080             switch(*p)
1081             {
1082             case 'a': *dest = '\a'; p++; break;
1083             case 'b': *dest = '\b'; p++; break;
1084             case 'e': *dest = '\e'; p++; break;
1085             case 'f': *dest = '\f'; p++; break;
1086             case 'n': *dest = '\n'; p++; break;
1087             case 'r': *dest = '\r'; p++; break;
1088             case 't': *dest = '\t'; p++; break;
1089             case 'v': *dest = '\v'; p++; break;
1090             case 'x':  /* hex escape */
1091                 p++;
1092                 if (!isxdigit(*p)) *dest = 'x';
1093                 else
1094                 {
1095                     *dest = to_hex(*p++);
1096                     if (isxdigit(*p)) *dest = (*dest * 16) + to_hex(*p++);
1097                     if (isxdigit(*p)) *dest = (*dest * 16) + to_hex(*p++);
1098                     if (isxdigit(*p)) *dest = (*dest * 16) + to_hex(*p++);
1099                 }
1100                 break;
1101             case '0':
1102             case '1':
1103             case '2':
1104             case '3':
1105             case '4':
1106             case '5':
1107             case '6':
1108             case '7':  /* octal escape */
1109                 *dest = *p++ - '0';
1110                 if (*p >= '0' && *p <= '7') *dest = (*dest * 8) + (*p++ - '0');
1111                 if (*p >= '0' && *p <= '7') *dest = (*dest * 8) + (*p++ - '0');
1112                 break;
1113             default:
1114                 *dest = (WCHAR)*p++;
1115                 break;
1116             }
1117         }
1118         if ((count += sizeof(WCHAR)) > *len) return -1;  /* dest buffer overflow */
1119         dest++;
1120     }
1121     *dest = 0;
1122     if (!*p) return -1;  /* delimiter not found */
1123     *len = count;
1124     return p + 1 - src;
1125 }
1126
1127 /* convert a data type tag to a value type */
1128 static int get_data_type( const char *buffer, int *type, int *parse_type )
1129 {
1130     struct data_type { const char *tag; int len; int type; int parse_type; };
1131
1132     static const struct data_type data_types[] =
1133     {                   /* actual type */  /* type to assume for parsing */
1134         { "\"",        1,   REG_SZ,              REG_SZ },
1135         { "str:\"",    5,   REG_SZ,              REG_SZ },
1136         { "str(2):\"", 8,   REG_EXPAND_SZ,       REG_SZ },
1137         { "str(7):\"", 8,   REG_MULTI_SZ,        REG_SZ },
1138         { "hex:",      4,   REG_BINARY,          REG_BINARY },
1139         { "dword:",    6,   REG_DWORD,           REG_DWORD },
1140         { "hex(",      4,   -1,                  REG_BINARY },
1141         { NULL,        0,    0,                  0 }
1142     };
1143
1144     const struct data_type *ptr;
1145     char *end;
1146
1147     for (ptr = data_types; ptr->tag; ptr++)
1148     {
1149         if (memcmp( ptr->tag, buffer, ptr->len )) continue;
1150         *parse_type = ptr->parse_type;
1151         if ((*type = ptr->type) != -1) return ptr->len;
1152         /* "hex(xx):" is special */
1153         *type = (int)strtoul( buffer + 4, &end, 16 );
1154         if ((end <= buffer) || memcmp( end, "):", 2 )) return 0;
1155         return end + 2 - buffer;
1156     }
1157     return 0;
1158 }
1159
1160 /* load and create a key from the input file */
1161 static struct key *load_key( struct key *base, const char *buffer, int flags,
1162                              int prefix_len, struct file_load_info *info,
1163                              int default_modif )
1164 {
1165     WCHAR *p;
1166     struct unicode_str name;
1167     int res, modif;
1168     size_t len = strlen(buffer) * sizeof(WCHAR);
1169
1170     if (!get_file_tmp_space( info, len )) return NULL;
1171
1172     if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1173     {
1174         file_read_error( "Malformed key", info );
1175         return NULL;
1176     }
1177     if (sscanf( buffer + res, " %d", &modif ) != 1) modif = default_modif;
1178
1179     p = info->tmp;
1180     while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }
1181
1182     if (!*p)
1183     {
1184         if (prefix_len > 1)
1185         {
1186             file_read_error( "Malformed key", info );
1187             return NULL;
1188         }
1189         /* empty key name, return base key */
1190         return (struct key *)grab_object( base );
1191     }
1192     name.str = p;
1193     name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1194     return create_key( base, &name, NULL, flags, modif, &res );
1195 }
1196
1197 /* parse a comma-separated list of hex digits */
1198 static int parse_hex( unsigned char *dest, size_t *len, const char *buffer )
1199 {
1200     const char *p = buffer;
1201     size_t count = 0;
1202     while (isxdigit(*p))
1203     {
1204         int val;
1205         char buf[3];
1206         memcpy( buf, p, 2 );
1207         buf[2] = 0;
1208         sscanf( buf, "%x", &val );
1209         if (count++ >= *len) return -1;  /* dest buffer overflow */
1210         *dest++ = (unsigned char )val;
1211         p += 2;
1212         if (*p == ',') p++;
1213     }
1214     *len = count;
1215     return p - buffer;
1216 }
1217
1218 /* parse a value name and create the corresponding value */
1219 static struct key_value *parse_value_name( struct key *key, const char *buffer, size_t *len,
1220                                            struct file_load_info *info )
1221 {
1222     struct key_value *value;
1223     struct unicode_str name;
1224     int index;
1225     size_t maxlen = strlen(buffer) * sizeof(WCHAR);
1226
1227     if (!get_file_tmp_space( info, maxlen )) return NULL;
1228     name.str = info->tmp;
1229     if (buffer[0] == '@')
1230     {
1231         name.len = 0;
1232         *len = 1;
1233     }
1234     else
1235     {
1236         if ((*len = parse_strW( info->tmp, &maxlen, buffer + 1, '\"' )) == -1) goto error;
1237         name.len = maxlen - sizeof(WCHAR);
1238         (*len)++;  /* for initial quote */
1239     }
1240     while (isspace(buffer[*len])) (*len)++;
1241     if (buffer[*len] != '=') goto error;
1242     (*len)++;
1243     while (isspace(buffer[*len])) (*len)++;
1244     if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1245     return value;
1246
1247  error:
1248     file_read_error( "Malformed value name", info );
1249     return NULL;
1250 }
1251
1252 /* load a value from the input file */
1253 static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
1254 {
1255     DWORD dw;
1256     void *ptr, *newptr;
1257     int res, type, parse_type;
1258     size_t maxlen, len;
1259     struct key_value *value;
1260
1261     if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
1262     if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
1263     buffer += len + res;
1264
1265     switch(parse_type)
1266     {
1267     case REG_SZ:
1268         len = strlen(buffer) * sizeof(WCHAR);
1269         if (!get_file_tmp_space( info, len )) return 0;
1270         if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1271         ptr = info->tmp;
1272         break;
1273     case REG_DWORD:
1274         dw = strtoul( buffer, NULL, 16 );
1275         ptr = &dw;
1276         len = sizeof(dw);
1277         break;
1278     case REG_BINARY:  /* hex digits */
1279         len = 0;
1280         for (;;)
1281         {
1282             maxlen = 1 + strlen(buffer)/3;  /* 3 chars for one hex byte */
1283             if (!get_file_tmp_space( info, len + maxlen )) return 0;
1284             if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1285             len += maxlen;
1286             buffer += res;
1287             while (isspace(*buffer)) buffer++;
1288             if (!*buffer) break;
1289             if (*buffer != '\\') goto error;
1290             if (read_next_line( info) != 1) goto error;
1291             buffer = info->buffer;
1292             while (isspace(*buffer)) buffer++;
1293         }
1294         ptr = info->tmp;
1295         break;
1296     default:
1297         assert(0);
1298         ptr = NULL;  /* keep compiler quiet */
1299         break;
1300     }
1301
1302     if (!len) newptr = NULL;
1303     else if (!(newptr = memdup( ptr, len ))) return 0;
1304
1305     if (value->data) free( value->data );
1306     value->data = newptr;
1307     value->len  = len;
1308     value->type = type;
1309     make_dirty( key );
1310     return 1;
1311
1312  error:
1313     file_read_error( "Malformed value", info );
1314     return 0;
1315 }
1316
1317 /* return the length (in path elements) of name that is part of the key name */
1318 /* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
1319 static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
1320 {
1321     WCHAR *p;
1322     int res;
1323     size_t len = strlen(name) * sizeof(WCHAR);
1324
1325     if (!get_file_tmp_space( info, len )) return 0;
1326
1327     if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1328     {
1329         file_read_error( "Malformed key", info );
1330         return 0;
1331     }
1332     for (p = info->tmp; *p; p++) if (*p == '\\') break;
1333     len = (p - info->tmp) * sizeof(WCHAR);
1334     for (res = 1; key != root_key; res++)
1335     {
1336         if (len == key->namelen && !memicmpW( info->tmp, key->name, len / sizeof(WCHAR) )) break;
1337         key = key->parent;
1338     }
1339     if (key == root_key) res = 0;  /* no matching name */
1340     return res;
1341 }
1342
1343 /* load all the keys from the input file */
1344 /* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1345 static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1346 {
1347     struct key *subkey = NULL;
1348     struct file_load_info info;
1349     char *p;
1350     int default_modif = time(NULL);
1351     int flags = (key->flags & KEY_VOLATILE) ? KEY_VOLATILE : KEY_DIRTY;
1352
1353     info.filename = filename;
1354     info.file   = f;
1355     info.len    = 4;
1356     info.tmplen = 4;
1357     info.line   = 0;
1358     if (!(info.buffer = mem_alloc( info.len ))) return;
1359     if (!(info.tmp = mem_alloc( info.tmplen )))
1360     {
1361         free( info.buffer );
1362         return;
1363     }
1364
1365     if ((read_next_line( &info ) != 1) ||
1366         strcmp( info.buffer, "WINE REGISTRY Version 2" ))
1367     {
1368         set_error( STATUS_NOT_REGISTRY_FILE );
1369         goto done;
1370     }
1371
1372     while (read_next_line( &info ) == 1)
1373     {
1374         p = info.buffer;
1375         while (*p && isspace(*p)) p++;
1376         switch(*p)
1377         {
1378         case '[':   /* new key */
1379             if (subkey) release_object( subkey );
1380             if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1381             if (!(subkey = load_key( key, p + 1, flags, prefix_len, &info, default_modif )))
1382                 file_read_error( "Error creating key", &info );
1383             break;
1384         case '@':   /* default value */
1385         case '\"':  /* value */
1386             if (subkey) load_value( subkey, p, &info );
1387             else file_read_error( "Value without key", &info );
1388             break;
1389         case '#':   /* comment */
1390         case ';':   /* comment */
1391         case 0:     /* empty line */
1392             break;
1393         default:
1394             file_read_error( "Unrecognized input", &info );
1395             break;
1396         }
1397     }
1398
1399  done:
1400     if (subkey) release_object( subkey );
1401     free( info.buffer );
1402     free( info.tmp );
1403 }
1404
1405 /* load a part of the registry from a file */
1406 static void load_registry( struct key *key, obj_handle_t handle )
1407 {
1408     struct file *file;
1409     int fd;
1410
1411     if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1412     fd = dup( get_file_unix_fd( file ) );
1413     release_object( file );
1414     if (fd != -1)
1415     {
1416         FILE *f = fdopen( fd, "r" );
1417         if (f)
1418         {
1419             load_keys( key, NULL, f, -1 );
1420             fclose( f );
1421         }
1422         else file_set_error();
1423     }
1424 }
1425
1426 /* load one of the initial registry files */
1427 static void load_init_registry_from_file( const char *filename, struct key *key )
1428 {
1429     FILE *f;
1430
1431     if ((f = fopen( filename, "r" )))
1432     {
1433         load_keys( key, filename, f, 0 );
1434         fclose( f );
1435         if (get_error() == STATUS_NOT_REGISTRY_FILE)
1436         {
1437             fprintf( stderr, "%s is not a valid registry file\n", filename );
1438             return;
1439         }
1440     }
1441
1442     assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1443
1444     if ((save_branch_info[save_branch_count].path = strdup( filename )))
1445         save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1446 }
1447
1448 static WCHAR *format_user_registry_path( const SID *sid, struct unicode_str *path )
1449 {
1450     static const WCHAR prefixW[] = {'U','s','e','r','\\','S',0};
1451     static const WCHAR formatW[] = {'-','%','u',0};
1452     WCHAR buffer[7 + 10 + 10 + 10 * SID_MAX_SUB_AUTHORITIES];
1453     WCHAR *p = buffer;
1454     unsigned int i;
1455
1456     strcpyW( p, prefixW );
1457     p += strlenW( prefixW );
1458     p += sprintfW( p, formatW, sid->Revision );
1459     p += sprintfW( p, formatW, MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5],
1460                                                    sid->IdentifierAuthority.Value[4] ),
1461                                          MAKEWORD( sid->IdentifierAuthority.Value[3],
1462                                                    sid->IdentifierAuthority.Value[2] )));
1463     for (i = 0; i < sid->SubAuthorityCount; i++)
1464         p += sprintfW( p, formatW, sid->SubAuthority[i] );
1465
1466     path->len = (p - buffer) * sizeof(WCHAR);
1467     path->str = p = memdup( buffer, path->len );
1468     return p;
1469 }
1470
1471 /* registry initialisation */
1472 void init_registry(void)
1473 {
1474     static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
1475     static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1476     static const struct unicode_str root_name = { NULL, 0 };
1477     static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
1478     static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1479
1480     WCHAR *current_user_path;
1481     struct unicode_str current_user_str;
1482
1483     const char *config = wine_get_config_dir();
1484     char *p, *filename;
1485     struct key *key;
1486     int dummy;
1487
1488     /* create the root key */
1489     root_key = alloc_key( &root_name, time(NULL) );
1490     assert( root_key );
1491
1492     if (!(filename = malloc( strlen(config) + 16 ))) fatal_error( "out of memory\n" );
1493     strcpy( filename, config );
1494     p = filename + strlen(filename);
1495
1496     /* load system.reg into Registry\Machine */
1497
1498     if (!(key = create_key( root_key, &HKLM_name, NULL, 0, time(NULL), &dummy )))
1499         fatal_error( "could not create Machine registry key\n" );
1500
1501     strcpy( p, "/system.reg" );
1502     load_init_registry_from_file( filename, key );
1503     release_object( key );
1504
1505     /* load userdef.reg into Registry\User\.Default */
1506
1507     if (!(key = create_key( root_key, &HKU_name, NULL, 0, time(NULL), &dummy )))
1508         fatal_error( "could not create User\\.Default registry key\n" );
1509
1510     strcpy( p, "/userdef.reg" );
1511     load_init_registry_from_file( filename, key );
1512     release_object( key );
1513
1514     /* load user.reg into HKEY_CURRENT_USER */
1515
1516     /* FIXME: match default user in token.c. should get from process token instead */
1517     current_user_path = format_user_registry_path( security_interactive_sid, &current_user_str );
1518     if (!current_user_path ||
1519         !(key = create_key( root_key, &current_user_str, NULL, 0, time(NULL), &dummy )))
1520         fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1521     free( current_user_path );
1522     strcpy( p, "/user.reg" );
1523     load_init_registry_from_file( filename, key );
1524     release_object( key );
1525
1526     free( filename );
1527
1528     /* start the periodic save timer */
1529     set_periodic_save_timer();
1530 }
1531
1532 /* save a registry branch to a file */
1533 static void save_all_subkeys( struct key *key, FILE *f )
1534 {
1535     fprintf( f, "WINE REGISTRY Version 2\n" );
1536     fprintf( f, ";; All keys relative to " );
1537     dump_path( key, NULL, f );
1538     fprintf( f, "\n" );
1539     save_subkeys( key, key, f );
1540 }
1541
1542 /* save a registry branch to a file handle */
1543 static void save_registry( struct key *key, obj_handle_t handle )
1544 {
1545     struct file *file;
1546     int fd;
1547
1548     if (key->flags & KEY_DELETED)
1549     {
1550         set_error( STATUS_KEY_DELETED );
1551         return;
1552     }
1553     if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1554     fd = dup( get_file_unix_fd( file ) );
1555     release_object( file );
1556     if (fd != -1)
1557     {
1558         FILE *f = fdopen( fd, "w" );
1559         if (f)
1560         {
1561             save_all_subkeys( key, f );
1562             if (fclose( f )) file_set_error();
1563         }
1564         else
1565         {
1566             file_set_error();
1567             close( fd );
1568         }
1569     }
1570 }
1571
1572 /* save a registry branch to a file */
1573 static int save_branch( struct key *key, const char *path )
1574 {
1575     struct stat st;
1576     char *p, *real, *tmp = NULL;
1577     int fd, count = 0, ret = 0, by_symlink;
1578     FILE *f;
1579
1580     if (!(key->flags & KEY_DIRTY))
1581     {
1582         if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
1583         return 1;
1584     }
1585
1586     /* get the real path */
1587
1588     by_symlink = (!lstat(path, &st) && S_ISLNK (st.st_mode));
1589     if (!(real = malloc( PATH_MAX ))) return 0;
1590     if (!realpath( path, real ))
1591     {
1592         free( real );
1593         real = NULL;
1594     }
1595     else path = real;
1596
1597     /* test the file type */
1598
1599     if ((fd = open( path, O_WRONLY )) != -1)
1600     {
1601         /* if file is not a regular file or has multiple links or is accessed
1602          * via symbolic links, write directly into it; otherwise use a temp file */
1603         if (by_symlink ||
1604             (!fstat( fd, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1)))
1605         {
1606             ftruncate( fd, 0 );
1607             goto save;
1608         }
1609         close( fd );
1610     }
1611
1612     /* create a temp file in the same directory */
1613
1614     if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
1615     strcpy( tmp, path );
1616     if ((p = strrchr( tmp, '/' ))) p++;
1617     else p = tmp;
1618     for (;;)
1619     {
1620         sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
1621         if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
1622         if (errno != EEXIST) goto done;
1623         close( fd );
1624     }
1625
1626     /* now save to it */
1627
1628  save:
1629     if (!(f = fdopen( fd, "w" )))
1630     {
1631         if (tmp) unlink( tmp );
1632         close( fd );
1633         goto done;
1634     }
1635
1636     if (debug_level > 1)
1637     {
1638         fprintf( stderr, "%s: ", path );
1639         dump_operation( key, NULL, "saving" );
1640     }
1641
1642     save_all_subkeys( key, f );
1643     ret = !fclose(f);
1644
1645     if (tmp)
1646     {
1647         /* if successfully written, rename to final name */
1648         if (ret) ret = !rename( tmp, path );
1649         if (!ret) unlink( tmp );
1650     }
1651
1652 done:
1653     free( tmp );
1654     free( real );
1655     if (ret) make_clean( key );
1656     return ret;
1657 }
1658
1659 /* periodic saving of the registry */
1660 static void periodic_save( void *arg )
1661 {
1662     int i;
1663
1664     save_timeout_user = NULL;
1665     for (i = 0; i < save_branch_count; i++)
1666         save_branch( save_branch_info[i].key, save_branch_info[i].path );
1667     set_periodic_save_timer();
1668 }
1669
1670 /* start the periodic save timer */
1671 static void set_periodic_save_timer(void)
1672 {
1673     struct timeval next;
1674
1675     gettimeofday( &next, NULL );
1676     add_timeout( &next, save_period );
1677     if (save_timeout_user) remove_timeout_user( save_timeout_user );
1678     save_timeout_user = add_timeout_user( &next, periodic_save, NULL );
1679 }
1680
1681 /* save the modified registry branches to disk */
1682 void flush_registry(void)
1683 {
1684     int i;
1685
1686     for (i = 0; i < save_branch_count; i++)
1687     {
1688         if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
1689         {
1690             fprintf( stderr, "wineserver: could not save registry branch to %s",
1691                      save_branch_info[i].path );
1692             perror( " " );
1693         }
1694     }
1695 }
1696
1697 /* close the top-level keys; used on server exit */
1698 void close_registry(void)
1699 {
1700     int i;
1701
1702     if (save_timeout_user) remove_timeout_user( save_timeout_user );
1703     save_timeout_user = NULL;
1704     for (i = 0; i < save_branch_count; i++)
1705     {
1706         release_object( save_branch_info[i].key );
1707         free( save_branch_info[i].path );
1708     }
1709     release_object( root_key );
1710 }
1711
1712
1713 /* create a registry key */
1714 DECL_HANDLER(create_key)
1715 {
1716     struct key *key = NULL, *parent;
1717     struct unicode_str name, class;
1718     unsigned int access = req->access;
1719
1720     if (access & MAXIMUM_ALLOWED) access = KEY_ALL_ACCESS;  /* FIXME: needs general solution */
1721     reply->hkey = 0;
1722
1723     if (req->namelen > get_req_data_size())
1724     {
1725         set_error( STATUS_INVALID_PARAMETER );
1726         return;
1727     }
1728     class.str = (const WCHAR *)get_req_data() + req->namelen / sizeof(WCHAR);
1729     class.len = ((get_req_data_size() - req->namelen) / sizeof(WCHAR)) * sizeof(WCHAR);
1730     get_req_path( &name, !req->parent );
1731     if (name.str > class.str)
1732     {
1733         set_error( STATUS_INVALID_PARAMETER );
1734         return;
1735     }
1736     name.len = (class.str - name.str) * sizeof(WCHAR);
1737
1738     /* NOTE: no access rights are required from the parent handle to create a key */
1739     if ((parent = get_hkey_obj( req->parent, 0 )))
1740     {
1741         int flags = (req->options & REG_OPTION_VOLATILE) ? KEY_VOLATILE : KEY_DIRTY;
1742
1743         if ((key = create_key( parent, &name, &class, flags, req->modif, &reply->created )))
1744         {
1745             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1746             release_object( key );
1747         }
1748         release_object( parent );
1749     }
1750 }
1751
1752 /* open a registry key */
1753 DECL_HANDLER(open_key)
1754 {
1755     struct key *key, *parent;
1756     struct unicode_str name;
1757     unsigned int access = req->access;
1758
1759     if (access & MAXIMUM_ALLOWED) access = KEY_ALL_ACCESS;  /* FIXME: needs general solution */
1760     reply->hkey = 0;
1761     /* NOTE: no access rights are required to open the parent key, only the child key */
1762     if ((parent = get_hkey_obj( req->parent, 0 )))
1763     {
1764         get_req_path( &name, !req->parent );
1765         if ((key = open_key( parent, &name )))
1766         {
1767             reply->hkey = alloc_handle( current->process, key, access, req->attributes );
1768             release_object( key );
1769         }
1770         release_object( parent );
1771     }
1772 }
1773
1774 /* delete a registry key */
1775 DECL_HANDLER(delete_key)
1776 {
1777     struct key *key;
1778
1779     if ((key = get_hkey_obj( req->hkey, DELETE )))
1780     {
1781         delete_key( key, 0);
1782         release_object( key );
1783     }
1784 }
1785
1786 /* flush a registry key */
1787 DECL_HANDLER(flush_key)
1788 {
1789     struct key *key = get_hkey_obj( req->hkey, 0 );
1790     if (key)
1791     {
1792         /* we don't need to do anything here with the current implementation */
1793         release_object( key );
1794     }
1795 }
1796
1797 /* enumerate registry subkeys */
1798 DECL_HANDLER(enum_key)
1799 {
1800     struct key *key;
1801
1802     if ((key = get_hkey_obj( req->hkey,
1803                              req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
1804     {
1805         enum_key( key, req->index, req->info_class, reply );
1806         release_object( key );
1807     }
1808 }
1809
1810 /* set a value of a registry key */
1811 DECL_HANDLER(set_key_value)
1812 {
1813     struct key *key;
1814     struct unicode_str name;
1815
1816     if (req->namelen > get_req_data_size())
1817     {
1818         set_error( STATUS_INVALID_PARAMETER );
1819         return;
1820     }
1821     name.str = get_req_data();
1822     name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
1823
1824     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
1825     {
1826         size_t datalen = get_req_data_size() - req->namelen;
1827         const char *data = (const char *)get_req_data() + req->namelen;
1828
1829         set_value( key, &name, req->type, data, datalen );
1830         release_object( key );
1831     }
1832 }
1833
1834 /* retrieve the value of a registry key */
1835 DECL_HANDLER(get_key_value)
1836 {
1837     struct key *key;
1838     struct unicode_str name;
1839
1840     reply->total = 0;
1841     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
1842     {
1843         get_req_unicode_str( &name );
1844         get_value( key, &name, &reply->type, &reply->total );
1845         release_object( key );
1846     }
1847 }
1848
1849 /* enumerate the value of a registry key */
1850 DECL_HANDLER(enum_key_value)
1851 {
1852     struct key *key;
1853
1854     if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
1855     {
1856         enum_value( key, req->index, req->info_class, reply );
1857         release_object( key );
1858     }
1859 }
1860
1861 /* delete a value of a registry key */
1862 DECL_HANDLER(delete_key_value)
1863 {
1864     struct key *key;
1865     struct unicode_str name;
1866
1867     if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
1868     {
1869         get_req_unicode_str( &name );
1870         delete_value( key, &name );
1871         release_object( key );
1872     }
1873 }
1874
1875 /* load a registry branch from a file */
1876 DECL_HANDLER(load_registry)
1877 {
1878     struct key *key, *parent;
1879     struct token *token = thread_get_impersonation_token( current );
1880     struct unicode_str name;
1881
1882     const LUID_AND_ATTRIBUTES privs[] =
1883     {
1884         { SeBackupPrivilege,  0 },
1885         { SeRestorePrivilege, 0 },
1886     };
1887
1888     if (!token || !token_check_privileges( token, TRUE, privs,
1889                                            sizeof(privs)/sizeof(privs[0]), NULL ))
1890     {
1891         set_error( STATUS_PRIVILEGE_NOT_HELD );
1892         return;
1893     }
1894
1895     if ((parent = get_hkey_obj( req->hkey, 0 )))
1896     {
1897         int dummy;
1898         get_req_path( &name, !req->hkey );
1899         if ((key = create_key( parent, &name, NULL, KEY_DIRTY, time(NULL), &dummy )))
1900         {
1901             load_registry( key, req->file );
1902             release_object( key );
1903         }
1904         release_object( parent );
1905     }
1906 }
1907
1908 DECL_HANDLER(unload_registry)
1909 {
1910     struct key *key;
1911     struct token *token = thread_get_impersonation_token( current );
1912
1913     const LUID_AND_ATTRIBUTES privs[] =
1914     {
1915         { SeBackupPrivilege,  0 },
1916         { SeRestorePrivilege, 0 },
1917     };
1918
1919     if (!token || !token_check_privileges( token, TRUE, privs,
1920                                            sizeof(privs)/sizeof(privs[0]), NULL ))
1921     {
1922         set_error( STATUS_PRIVILEGE_NOT_HELD );
1923         return;
1924     }
1925
1926     if ((key = get_hkey_obj( req->hkey, 0 )))
1927     {
1928         delete_key( key, 1 );     /* FIXME */
1929         release_object( key );
1930     }
1931 }
1932
1933 /* save a registry branch to a file */
1934 DECL_HANDLER(save_registry)
1935 {
1936     struct key *key;
1937
1938     if (!thread_single_check_privilege( current, &SeBackupPrivilege ))
1939     {
1940         set_error( STATUS_PRIVILEGE_NOT_HELD );
1941         return;
1942     }
1943
1944     if ((key = get_hkey_obj( req->hkey, 0 )))
1945     {
1946         save_registry( key, req->file );
1947         release_object( key );
1948     }
1949 }
1950
1951 /* add a registry key change notification */
1952 DECL_HANDLER(set_registry_notification)
1953 {
1954     struct key *key;
1955     struct event *event;
1956     struct notify *notify;
1957
1958     key = get_hkey_obj( req->hkey, KEY_NOTIFY );
1959     if (key)
1960     {
1961         event = get_event_obj( current->process, req->event, SYNCHRONIZE );
1962         if (event)
1963         {
1964             notify = find_notify( key, current->process, req->hkey );
1965             if (notify)
1966             {
1967                 release_object( notify->event );
1968                 grab_object( event );
1969                 notify->event = event;
1970             }
1971             else
1972             {
1973                 notify = mem_alloc( sizeof(*notify) );
1974                 if (notify)
1975                 {
1976                     grab_object( event );
1977                     notify->event   = event;
1978                     notify->subtree = req->subtree;
1979                     notify->filter  = req->filter;
1980                     notify->hkey    = req->hkey;
1981                     notify->process = current->process;
1982                     list_add_head( &key->notify_list, &notify->entry );
1983                 }
1984             }
1985             release_object( event );
1986         }
1987         release_object( key );
1988     }
1989 }