registry.c 73.8 KB
Newer Older
1 2 3 4
/*
 * Server-side registry management
 *
 * Copyright (C) 1999 Alexandre Julliard
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
19 20 21 22 23 24
 */

/* To do:
 * - symbolic links
 */

25 26
#include "config.h"

27
#include <assert.h>
28
#include <ctype.h>
29 30
#include <errno.h>
#include <fcntl.h>
31 32
#include <limits.h>
#include <stdio.h>
33
#include <stdarg.h>
34
#include <string.h>
35
#include <stdlib.h>
36
#include <sys/stat.h>
37
#include <sys/types.h>
38
#include <unistd.h>
39

40 41
#include "ntstatus.h"
#define WIN32_NO_STATUS
42
#include "object.h"
43
#include "file.h"
44 45
#include "handle.h"
#include "request.h"
46
#include "process.h"
47
#include "unicode.h"
48
#include "security.h"
49

50
#include "winternl.h"
51

52 53
struct notify
{
54
    struct list       entry;    /* entry in list of notifications */
55 56
    struct event    **events;   /* events to set when changing this key */
    unsigned int      event_count; /* number of events */
57 58 59
    int               subtree;  /* true if subtree notification */
    unsigned int      filter;   /* which events to notify on */
    obj_handle_t      hkey;     /* hkey associated with this notification */
60
    struct process   *process;  /* process in which the hkey is valid */
61 62
};

63 64 65 66 67
static const WCHAR key_name[] = {'K','e','y'};

struct type_descr key_type =
{
    { key_name, sizeof(key_name) },   /* name */
68 69 70 71 72 73 74
    KEY_ALL_ACCESS | SYNCHRONIZE,     /* valid_access */
    {                                 /* mapping */
        STANDARD_RIGHTS_READ | KEY_NOTIFY | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
        STANDARD_RIGHTS_WRITE | KEY_CREATE_SUB_KEY | KEY_SET_VALUE,
        STANDARD_RIGHTS_EXECUTE | KEY_CREATE_LINK | KEY_NOTIFY | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE,
        KEY_ALL_ACCESS
    },
75 76
};

77 78 79 80 81 82
/* a registry key */
struct key
{
    struct object     obj;         /* object header */
    WCHAR            *name;        /* key name */
    WCHAR            *class;       /* key class */
83 84
    unsigned short    namelen;     /* length of key name */
    unsigned short    classlen;    /* length of class name */
85 86 87 88 89 90 91
    struct key       *parent;      /* parent key */
    int               last_subkey; /* last in use subkey */
    int               nb_subkeys;  /* count of allocated subkeys */
    struct key      **subkeys;     /* subkeys array */
    int               last_value;  /* last in use value */
    int               nb_values;   /* count of allocated values in array */
    struct key_value *values;      /* values array */
92
    unsigned int      flags;       /* flags */
93
    timeout_t         modif;       /* last modification time */
94
    struct list       notify_list; /* list of notifications */
95 96 97 98 99
};

/* key flags */
#define KEY_VOLATILE 0x0001  /* key is volatile (not saved to disk) */
#define KEY_DELETED  0x0002  /* key has been deleted */
100
#define KEY_DIRTY    0x0004  /* key has been modified */
101
#define KEY_SYMLINK  0x0008  /* key is a symbolic link */
102
#define KEY_WOW64    0x0010  /* key contains a Wow6432Node subkey */
103
#define KEY_WOWSHARE 0x0020  /* key is a Wow64 shared key (used for Software\Classes) */
104
#define KEY_PREDEF   0x0040  /* key is marked as predefined */
105 106 107 108 109

/* a key value */
struct key_value
{
    WCHAR            *name;    /* value name */
110
    unsigned short    namelen; /* length of value name */
111
    unsigned int      type;    /* value type */
112
    data_size_t       len;     /* value data length in bytes */
113 114 115 116 117 118
    void             *data;    /* pointer to value data */
};

#define MIN_SUBKEYS  8   /* min. number of allocated subkeys per key */
#define MIN_VALUES   8   /* min. number of allocated values per key */

119
#define MAX_NAME_LEN  256    /* max. length of a key name */
120
#define MAX_VALUE_LEN 16383  /* max. length of a value name */
121

122
/* the root of the registry tree */
123 124
static struct key *root_key;

125
static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
126
static const timeout_t save_period = 30 * -TICKS_PER_SEC;  /* delay between periodic saves */
127
static struct timeout_user *save_timeout_user;  /* saving timer */
128
static enum prefix_type { PREFIX_UNKNOWN, PREFIX_32BIT, PREFIX_64BIT } prefix_type;
129

130
static const WCHAR root_name[] = { '\\','R','e','g','i','s','t','r','y','\\' };
131
static const WCHAR wow6432node[] = {'W','o','w','6','4','3','2','N','o','d','e'};
132 133 134
static const WCHAR symlink_value[] = {'S','y','m','b','o','l','i','c','L','i','n','k','V','a','l','u','e'};
static const struct unicode_str symlink_str = { symlink_value, sizeof(symlink_value) };

135
static void set_periodic_save_timer(void);
136
static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index );
137

138 139 140 141
/* information about where to save a registry branch */
struct save_branch_info
{
    struct key  *key;
142
    const char  *path;
143 144
};

145
#define MAX_SAVE_BRANCH_INFO 3
146 147 148
static int save_branch_count;
static struct save_branch_info save_branch_info[MAX_SAVE_BRANCH_INFO];

149 150
unsigned int supported_machines_count = 0;
unsigned short supported_machines[8];
151
unsigned short native_machine = 0;
152

153 154 155
/* information about a file being loaded */
struct file_load_info
{
156 157 158 159 160 161 162
    const char *filename; /* input file name */
    FILE       *file;     /* input file */
    char       *buffer;   /* line buffer */
    int         len;      /* buffer length */
    int         line;     /* current input line */
    WCHAR      *tmp;      /* temp buffer to use while parsing input */
    size_t      tmplen;   /* length of temp buffer */
163 164 165
};


166
static void key_dump( struct object *obj, int verbose );
167
static unsigned int key_map_access( struct object *obj, unsigned int access );
168
static struct security_descriptor *key_get_sd( struct object *obj );
169
static WCHAR *key_get_full_name( struct object *obj, data_size_t *len );
170
static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle );
171 172 173 174
static void key_destroy( struct object *obj );

static const struct object_ops key_ops =
{
175
    sizeof(struct key),      /* size */
176
    &key_type,               /* type */
177 178 179 180 181
    key_dump,                /* dump */
    no_add_queue,            /* add_queue */
    NULL,                    /* remove_queue */
    NULL,                    /* signaled */
    NULL,                    /* satisfied */
182
    no_signal,               /* signal */
183
    no_get_fd,               /* get_fd */
184
    key_map_access,          /* map_access */
185
    key_get_sd,              /* get_sd */
186
    default_set_sd,          /* set_sd */
187
    key_get_full_name,       /* get_full_name */
188
    no_lookup_name,          /* lookup_name */
189 190
    no_link_name,            /* link_name */
    NULL,                    /* unlink_name */
191
    no_open_file,            /* open_file */
192
    no_kernel_obj_list,      /* get_kernel_obj_list */
193
    key_close_handle,        /* close_handle */
194
    key_destroy              /* destroy */
195 196 197
};


198 199
static inline int is_wow6432node( const WCHAR *name, unsigned int len )
{
200
    return (len == sizeof(wow6432node) && !memicmp_strW( name, wow6432node, sizeof( wow6432node )));
201 202
}

203 204 205 206 207 208 209 210 211 212
/*
 * The registry text file format v2 used by this code is similar to the one
 * used by REGEDIT import/export functionality, with the following differences:
 * - strings and key names can contain \x escapes for Unicode
 * - key names use escapes too in order to support Unicode
 * - the modification time optionally follows the key name
 * - REG_EXPAND_SZ and REG_MULTI_SZ are saved as strings instead of hex
 */

/* dump the full path of a key */
213
static void dump_path( const struct key *key, const struct key *base, FILE *f )
214
{
215
    if (key->parent && key->parent != base)
216
    {
217
        dump_path( key->parent, base, f );
218 219
        fprintf( f, "\\\\" );
    }
220
    dump_strW( key->name, key->namelen, f, "[]" );
221 222 223
}

/* dump a value to a text file */
224
static void dump_value( const struct key_value *value, FILE *f )
225
{
226
    unsigned int i, dw;
227
    int count;
228

229
    if (value->namelen)
230 231
    {
        fputc( '\"', f );
232
        count = 1 + dump_strW( value->name, value->namelen, f, "\"\"" );
233 234 235 236 237 238 239 240 241
        count += fprintf( f, "\"=" );
    }
    else count = fprintf( f, "@=" );

    switch(value->type)
    {
    case REG_SZ:
    case REG_EXPAND_SZ:
    case REG_MULTI_SZ:
242 243 244 245 246
        /* only output properly terminated strings in string format */
        if (value->len < sizeof(WCHAR)) break;
        if (value->len % sizeof(WCHAR)) break;
        if (((WCHAR *)value->data)[value->len / sizeof(WCHAR) - 1]) break;
        if (value->type != REG_SZ) fprintf( f, "str(%x):", value->type );
247
        fputc( '\"', f );
248
        dump_strW( (WCHAR *)value->data, value->len, f, "\"\"" );
249 250 251
        fprintf( f, "\"\n" );
        return;

252
    case REG_DWORD:
253 254 255 256 257 258 259 260 261 262 263 264
        if (value->len != sizeof(dw)) break;
        memcpy( &dw, value->data, sizeof(dw) );
        fprintf( f, "dword:%08x\n", dw );
        return;
    }

    if (value->type == REG_BINARY) count += fprintf( f, "hex:" );
    else count += fprintf( f, "hex(%x):", value->type );
    for (i = 0; i < value->len; i++)
    {
        count += fprintf( f, "%02x", *((unsigned char *)value->data + i) );
        if (i < value->len-1)
265
        {
266 267
            fputc( ',', f );
            if (++count > 76)
268
            {
269 270
                fprintf( f, "\\\n  " );
                count = 2;
271 272 273 274 275 276 277
            }
        }
    }
    fputc( '\n', f );
}

/* save a registry and all its subkeys to a text file */
278
static void save_subkeys( const struct key *key, const struct key *base, FILE *f )
279 280 281 282
{
    int i;

    if (key->flags & KEY_VOLATILE) return;
283
    /* save key if it has either some values or no subkeys, or needs special options */
284
    /* keys with no values but subkeys are saved implicitly by saving the subkeys */
285
    if ((key->last_value >= 0) || (key->last_subkey == -1) || key->class || (key->flags & KEY_SYMLINK))
286 287
    {
        fprintf( f, "\n[" );
288
        if (key != base) dump_path( key, base, f );
289
        fprintf( f, "] %u\n", (unsigned int)((key->modif - ticks_1601_to_1970) / TICKS_PER_SEC) );
290
        fprintf( f, "#time=%x%08x\n", (unsigned int)(key->modif >> 32), (unsigned int)key->modif );
291 292 293
        if (key->class)
        {
            fprintf( f, "#class=\"" );
294
            dump_strW( key->class, key->classlen, f, "\"\"" );
295 296
            fprintf( f, "\"\n" );
        }
297
        if (key->flags & KEY_SYMLINK) fputs( "#link\n", f );
298 299
        for (i = 0; i <= key->last_value; i++) dump_value( &key->values[i], f );
    }
300
    for (i = 0; i <= key->last_subkey; i++) save_subkeys( key->subkeys[i], base, f );
301 302
}

303
static void dump_operation( const struct key *key, const struct key_value *value, const char *op )
304 305
{
    fprintf( stderr, "%s key ", op );
306
    if (key) dump_path( key, NULL, stderr );
307 308 309 310 311 312 313 314 315 316 317 318 319 320
    else fprintf( stderr, "ERROR" );
    if (value)
    {
        fprintf( stderr, " value ");
        dump_value( value, stderr );
    }
    else fprintf( stderr, "\n" );
}

static void key_dump( struct object *obj, int verbose )
{
    struct key *key = (struct key *)obj;
    assert( obj->ops == &key_ops );
    fprintf( stderr, "Key flags=%x ", key->flags );
321
    dump_path( key, NULL, stderr );
322 323 324
    fprintf( stderr, "\n" );
}

325 326 327
/* notify waiter and maybe delete the notification */
static void do_notification( struct key *key, struct notify *notify, int del )
{
328 329 330
    unsigned int i;

    for (i = 0; i < notify->event_count; ++i)
331
    {
332 333
        set_event( notify->events[i] );
        release_object( notify->events[i] );
334
    }
335 336 337 338
    free( notify->events );
    notify->events = NULL;
    notify->event_count = 0;

339 340 341 342 343
    if (del)
    {
        list_remove( &notify->entry );
        free( notify );
    }
344 345
}

346
static inline struct notify *find_notify( struct key *key, struct process *process, obj_handle_t hkey )
347
{
348
    struct notify *notify;
349

350 351
    LIST_FOR_EACH_ENTRY( notify, &key->notify_list, struct notify, entry )
    {
352
        if (notify->process == process && notify->hkey == hkey) return notify;
353 354
    }
    return NULL;
355 356
}

357 358
static unsigned int key_map_access( struct object *obj, unsigned int access )
{
359
    access = default_map_access( obj, access );
360
    /* filter the WOW64 masks, as they aren't real access bits */
361
    return access & ~(KEY_WOW64_64KEY | KEY_WOW64_32KEY);
362 363
}

364 365 366 367 368 369 370 371
static struct security_descriptor *key_get_sd( struct object *obj )
{
    static struct security_descriptor *key_default_sd;

    if (obj->sd) return obj->sd;

    if (!key_default_sd)
    {
372
        struct acl *dacl;
373
        struct ace *ace;
374 375 376
        struct sid *sid;
        size_t users_sid_len = sid_len( &builtin_users_sid );
        size_t admins_sid_len = sid_len( &builtin_admins_sid );
377
        size_t dacl_len = sizeof(*dacl) + 2 * sizeof(*ace) + users_sid_len + admins_sid_len;
378 379 380 381 382

        key_default_sd = mem_alloc( sizeof(*key_default_sd) + 2 * admins_sid_len + dacl_len );
        key_default_sd->control   = SE_DACL_PRESENT;
        key_default_sd->owner_len = admins_sid_len;
        key_default_sd->group_len = admins_sid_len;
383
        key_default_sd->sacl_len  = 0;
384
        key_default_sd->dacl_len  = dacl_len;
385 386 387
        sid = (struct sid *)(key_default_sd + 1);
        sid = copy_sid( sid, &builtin_admins_sid );
        sid = copy_sid( sid, &builtin_admins_sid );
388

389 390 391 392 393 394
        dacl = (struct acl *)((char *)(key_default_sd + 1) + 2 * admins_sid_len);
        dacl->revision = ACL_REVISION;
        dacl->pad1     = 0;
        dacl->size     = dacl_len;
        dacl->count    = 2;
        dacl->pad2     = 0;
395
        ace = set_ace( ace_first( dacl ), &builtin_users_sid, ACCESS_ALLOWED_ACE_TYPE,
396
                       INHERIT_ONLY_ACE | CONTAINER_INHERIT_ACE, GENERIC_READ );
397
        set_ace( ace_next( ace ), &builtin_admins_sid, ACCESS_ALLOWED_ACE_TYPE, 0, KEY_ALL_ACCESS );
398 399 400 401
    }
    return key_default_sd;
}

402 403 404 405 406 407 408
static WCHAR *key_get_full_name( struct object *obj, data_size_t *ret_len )
{
    static const WCHAR backslash = '\\';
    struct key *key = (struct key *) obj;
    data_size_t len = sizeof(root_name) - sizeof(WCHAR);
    char *ret;

409 410 411 412 413 414
    if (key->flags & KEY_DELETED)
    {
        set_error( STATUS_KEY_DELETED );
        return NULL;
    }

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    for (key = (struct key *)obj; key != root_key; key = key->parent) len += key->namelen + sizeof(WCHAR);
    if (!(ret = malloc( len ))) return NULL;

    *ret_len = len;
    key = (struct key *)obj;
    for (key = (struct key *)obj; key != root_key; key = key->parent)
    {
        memcpy( ret + len - key->namelen, key->name, key->namelen );
        len -= key->namelen + sizeof(WCHAR);
        memcpy( ret + len, &backslash, sizeof(WCHAR) );
    }
    memcpy( ret, root_name, sizeof(root_name) - sizeof(WCHAR) );
    return (WCHAR *)ret;
}

430
/* close the notification associated with a handle */
431
static int key_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
432 433
{
    struct key * key = (struct key *) obj;
434
    struct notify *notify = find_notify( key, process, handle );
435 436
    if (notify) do_notification( key, notify, 1 );
    return 1;  /* ok to close */
437 438
}

439 440 441
static void key_destroy( struct object *obj )
{
    int i;
442
    struct list *ptr;
443 444 445
    struct key *key = (struct key *)obj;
    assert( obj->ops == &key_ops );

446 447
    free( key->name );
    free( key->class );
448 449
    for (i = 0; i <= key->last_value; i++)
    {
450 451
        free( key->values[i].name );
        free( key->values[i].data );
452
    }
453
    free( key->values );
454 455 456 457 458
    for (i = 0; i <= key->last_subkey; i++)
    {
        key->subkeys[i]->parent = NULL;
        release_object( key->subkeys[i] );
    }
459
    free( key->subkeys );
460
    /* unconditionally notify everything waiting on this key */
461 462 463 464 465
    while ((ptr = list_head( &key->notify_list )))
    {
        struct notify *notify = LIST_ENTRY( ptr, struct notify, entry );
        do_notification( key, notify, 1 );
    }
466 467
}

468
/* get the request vararg as registry path */
469
static inline void get_req_path( struct unicode_str *str, int skip_root )
470
{
471 472
    str->str = get_req_data();
    str->len = (get_req_data_size() / sizeof(WCHAR)) * sizeof(WCHAR);
473

474
    if (skip_root && str->len >= sizeof(root_name) && !memicmp_strW( str->str, root_name, sizeof(root_name) ))
475
    {
476
        str->str += ARRAY_SIZE( root_name );
477
        str->len -= sizeof(root_name);
478 479 480
    }
}

481
/* return the next token in a given path */
482 483
/* token->str must point inside the path, or be NULL for the first call */
static struct unicode_str *get_path_token( const struct unicode_str *path, struct unicode_str *token )
484
{
485
    data_size_t i = 0, len = path->len / sizeof(WCHAR);
486

487
    if (!token->str)  /* first time */
488
    {
489
        /* path cannot start with a backslash */
490
        if (len && path->str[0] == '\\')
491 492 493 494
        {
            set_error( STATUS_OBJECT_PATH_INVALID );
            return NULL;
        }
495
    }
496
    else
497
    {
498 499 500
        i = token->str - path->str;
        i += token->len / sizeof(WCHAR);
        while (i < len && path->str[i] == '\\') i++;
501
    }
502 503 504 505
    token->str = path->str + i;
    while (i < len && path->str[i] != '\\') i++;
    token->len = (path->str + i - token->str) * sizeof(WCHAR);
    return token;
506 507 508
}

/* allocate a key object */
509
static struct key *alloc_key( const struct unicode_str *name, timeout_t modif )
510 511
{
    struct key *key;
512
    if ((key = alloc_object( &key_ops )))
513
    {
514
        key->name        = NULL;
515
        key->class       = NULL;
516 517
        key->namelen     = name->len;
        key->classlen    = 0;
518 519 520 521 522 523 524 525 526
        key->flags       = 0;
        key->last_subkey = -1;
        key->nb_subkeys  = 0;
        key->subkeys     = NULL;
        key->nb_values   = 0;
        key->last_value  = -1;
        key->values      = NULL;
        key->modif       = modif;
        key->parent      = NULL;
527
        list_init( &key->notify_list );
528
        if (name->len && !(key->name = memdup( name->str, name->len )))
529 530 531 532 533 534 535 536
        {
            release_object( key );
            key = NULL;
        }
    }
    return key;
}

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
/* mark a key and all its parents as dirty (modified) */
static void make_dirty( struct key *key )
{
    while (key)
    {
        if (key->flags & (KEY_DIRTY|KEY_VOLATILE)) return;  /* nothing to do */
        key->flags |= KEY_DIRTY;
        key = key->parent;
    }
}

/* mark a key and all its subkeys as clean (not modified) */
static void make_clean( struct key *key )
{
    int i;

    if (key->flags & KEY_VOLATILE) return;
    if (!(key->flags & KEY_DIRTY)) return;
    key->flags &= ~KEY_DIRTY;
    for (i = 0; i <= key->last_subkey; i++) make_clean( key->subkeys[i] );
}

559
/* go through all the notifications and send them if necessary */
560
static void check_notify( struct key *key, unsigned int change, int not_subtree )
561
{
562 563 564
    struct list *ptr, *next;

    LIST_FOR_EACH_SAFE( ptr, next, &key->notify_list )
565
    {
566
        struct notify *n = LIST_ENTRY( ptr, struct notify, entry );
567 568 569 570 571
        if ( ( not_subtree || n->subtree ) && ( change & n->filter ) )
            do_notification( key, n, 0 );
    }
}

572
/* update key modification time */
573
static void touch_key( struct key *key, unsigned int change )
574
{
575 576
    struct key *k;

577
    key->modif = current_time;
578
    make_dirty( key );
579 580 581 582

    /* do notifications */
    check_notify( key, change, 1 );
    for ( k = key->parent; k; k = k->parent )
583
        check_notify( k, change, 0 );
584 585 586 587 588 589 590 591 592 593 594 595 596
}

/* try to grow the array of subkeys; return 1 if OK, 0 on error */
static int grow_subkeys( struct key *key )
{
    struct key **new_subkeys;
    int nb_subkeys;

    if (key->nb_subkeys)
    {
        nb_subkeys = key->nb_subkeys + (key->nb_subkeys / 2);  /* grow by 50% */
        if (!(new_subkeys = realloc( key->subkeys, nb_subkeys * sizeof(*new_subkeys) )))
        {
597
            set_error( STATUS_NO_MEMORY );
598 599 600 601 602
            return 0;
        }
    }
    else
    {
603
        nb_subkeys = MIN_SUBKEYS;
604 605 606 607 608 609 610 611
        if (!(new_subkeys = mem_alloc( nb_subkeys * sizeof(*new_subkeys) ))) return 0;
    }
    key->subkeys    = new_subkeys;
    key->nb_subkeys = nb_subkeys;
    return 1;
}

/* allocate a subkey for a given key, and return its index */
612
static struct key *alloc_subkey( struct key *parent, const struct unicode_str *name,
613
                                 int index, timeout_t modif )
614 615 616 617
{
    struct key *key;
    int i;

618 619
    if (name->len > MAX_NAME_LEN * sizeof(WCHAR))
    {
620
        set_error( STATUS_INVALID_PARAMETER );
621 622
        return NULL;
    }
623 624 625 626 627 628 629 630 631 632 633
    if (parent->last_subkey + 1 == parent->nb_subkeys)
    {
        /* need to grow the array */
        if (!grow_subkeys( parent )) return NULL;
    }
    if ((key = alloc_key( name, modif )) != NULL)
    {
        key->parent = parent;
        for (i = ++parent->last_subkey; i > index; i--)
            parent->subkeys[i] = parent->subkeys[i-1];
        parent->subkeys[index] = key;
634 635
        if (is_wow6432node( key->name, key->namelen ) && !is_wow6432node( parent->name, parent->namelen ))
            parent->flags |= KEY_WOW64;
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    }
    return key;
}

/* free a subkey of a given key */
static void free_subkey( struct key *parent, int index )
{
    struct key *key;
    int i, nb_subkeys;

    assert( index >= 0 );
    assert( index <= parent->last_subkey );

    key = parent->subkeys[index];
    for (i = index; i < parent->last_subkey; i++) parent->subkeys[i] = parent->subkeys[i + 1];
    parent->last_subkey--;
    key->flags |= KEY_DELETED;
    key->parent = NULL;
654
    if (is_wow6432node( key->name, key->namelen )) parent->flags &= ~KEY_WOW64;
655
    release_object( key );
656

657
    /* try to shrink the array */
658 659
    nb_subkeys = parent->nb_subkeys;
    if (nb_subkeys > MIN_SUBKEYS && parent->last_subkey < nb_subkeys / 2)
660 661 662 663
    {
        struct key **new_subkeys;
        nb_subkeys -= nb_subkeys / 3;  /* shrink by 33% */
        if (nb_subkeys < MIN_SUBKEYS) nb_subkeys = MIN_SUBKEYS;
664 665 666
        if (!(new_subkeys = realloc( parent->subkeys, nb_subkeys * sizeof(*new_subkeys) ))) return;
        parent->subkeys = new_subkeys;
        parent->nb_subkeys = nb_subkeys;
667 668 669 670
    }
}

/* find the named child of a given key and return its index */
671
static struct key *find_subkey( const struct key *key, const struct unicode_str *name, int *index )
672 673
{
    int i, min, max, res;
674
    data_size_t len;
675 676 677 678 679 680

    min = 0;
    max = key->last_subkey;
    while (min <= max)
    {
        i = (min + max) / 2;
681
        len = min( key->subkeys[i]->namelen, name->len );
682
        res = memicmp_strW( key->subkeys[i]->name, name->str, len );
683 684
        if (!res) res = key->subkeys[i]->namelen - name->len;
        if (!res)
685 686 687 688 689 690 691 692 693 694 695
        {
            *index = i;
            return key->subkeys[i];
        }
        if (res > 0) max = i - 1;
        else min = i + 1;
    }
    *index = min;  /* this is where we should insert it */
    return NULL;
}

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
/* return the wow64 variant of the key, or the key itself if none */
static struct key *find_wow64_subkey( struct key *key, const struct unicode_str *name )
{
    static const struct unicode_str wow6432node_str = { wow6432node, sizeof(wow6432node) };
    int index;

    if (!(key->flags & KEY_WOW64)) return key;
    if (!is_wow6432node( name->str, name->len ))
    {
        key = find_subkey( key, &wow6432node_str, &index );
        assert( key );  /* if KEY_WOW64 is set we must find it */
    }
    return key;
}


712 713 714 715 716 717 718 719 720 721 722 723 724 725
/* follow a symlink and return the resolved key */
static struct key *follow_symlink( struct key *key, int iteration )
{
    struct unicode_str path, token;
    struct key_value *value;
    int index;

    if (iteration > 16) return NULL;
    if (!(key->flags & KEY_SYMLINK)) return key;
    if (!(value = find_value( key, &symlink_str, &index ))) return NULL;

    path.str = value->data;
    path.len = (value->len / sizeof(WCHAR)) * sizeof(WCHAR);
    if (path.len <= sizeof(root_name)) return NULL;
726
    if (memicmp_strW( path.str, root_name, sizeof(root_name) )) return NULL;
727
    path.str += ARRAY_SIZE( root_name );
728 729 730 731 732 733 734 735 736 737 738 739 740 741
    path.len -= sizeof(root_name);

    key = root_key;
    token.str = NULL;
    if (!get_path_token( &path, &token )) return NULL;
    while (token.len)
    {
        if (!(key = find_subkey( key, &token, &index ))) break;
        if (!(key = follow_symlink( key, iteration + 1 ))) break;
        get_path_token( &path, &token );
    }
    return key;
}

742 743 744 745
/* open a key until we find an element that doesn't exist */
/* helper for open_key and create_key */
static struct key *open_key_prefix( struct key *key, const struct unicode_str *name,
                                    unsigned int access, struct unicode_str *token, int *index )
746
{
747 748 749 750
    token->str = NULL;
    if (!get_path_token( name, token )) return NULL;
    if (access & KEY_WOW64_32KEY) key = find_wow64_subkey( key, token );
    while (token->len)
751
    {
752
        struct key *subkey;
753 754 755 756 757 758 759 760 761 762
        if (!(subkey = find_subkey( key, token, index )))
        {
            if ((key->flags & KEY_WOWSHARE) && !(access & KEY_WOW64_64KEY))
            {
                /* try in the 64-bit parent */
                key = key->parent;
                subkey = find_subkey( key, token, index );
            }
        }
        if (!subkey) break;
763 764 765 766
        key = subkey;
        get_path_token( name, token );
        if (!token->len) break;
        if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, token );
767 768 769 770 771
        if (!(key = follow_symlink( key, 0 )))
        {
            set_error( STATUS_OBJECT_NAME_NOT_FOUND );
            return NULL;
        }
772
    }
773 774
    return key;
}
775

776 777 778 779 780 781 782 783 784 785 786 787 788 789
/* open a subkey */
static struct key *open_key( struct key *key, const struct unicode_str *name, unsigned int access,
                             unsigned int attributes )
{
    int index;
    struct unicode_str token;

    if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;

    if (token.len)
    {
        set_error( STATUS_OBJECT_NAME_NOT_FOUND );
        return NULL;
    }
790
    if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
791 792 793 794 795
    if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
    {
        set_error( STATUS_OBJECT_NAME_NOT_FOUND );
        return NULL;
    }
796
    if (debug_level > 1) dump_operation( key, NULL, "Open" );
797
    if (key->flags & KEY_PREDEF) set_error( STATUS_PREDEFINED_HANDLE );
798
    grab_object( key );
799 800 801 802
    return key;
}

/* create a subkey */
803
static struct key *create_key( struct key *key, const struct unicode_str *name,
804
                               const struct unicode_str *class, unsigned int options,
805 806
                               unsigned int access, unsigned int attributes,
                               const struct security_descriptor *sd, int *created )
807
{
808
    int index;
809
    struct unicode_str token, next;
810 811

    *created = 0;
812
    if (!(key = open_key_prefix( key, name, access, &token, &index ))) return NULL;
813

814
    if (!token.len)  /* the key already exists */
815
    {
816
        if (!(access & KEY_WOW64_64KEY)) key = find_wow64_subkey( key, &token );
817 818 819 820 821 822 823 824 825 826
        if (options & REG_OPTION_CREATE_LINK)
        {
            set_error( STATUS_OBJECT_NAME_COLLISION );
            return NULL;
        }
        if (!(attributes & OBJ_OPENLINK) && !(key = follow_symlink( key, 0 )))
        {
            set_error( STATUS_OBJECT_NAME_NOT_FOUND );
            return NULL;
        }
827
        if (debug_level > 1) dump_operation( key, NULL, "Open" );
828
        if (key->flags & KEY_PREDEF) set_error( STATUS_PREDEFINED_HANDLE );
829 830 831 832 833 834 835 836 837 838 839
        grab_object( key );
        return key;
    }

    /* token must be the last path component at this point */
    next = token;
    get_path_token( name, &next );
    if (next.len)
    {
        set_error( STATUS_OBJECT_NAME_NOT_FOUND );
        return NULL;
840
    }
841

842
    if ((key->flags & KEY_VOLATILE) && !(options & REG_OPTION_VOLATILE))
843 844 845 846
    {
        set_error( STATUS_CHILD_MUST_BE_VOLATILE );
        return NULL;
    }
847
    *created = 1;
848 849
    make_dirty( key );
    if (!(key = alloc_subkey( key, &token, index, current_time ))) return NULL;
850

851
    if (options & REG_OPTION_CREATE_LINK) key->flags |= KEY_SYMLINK;
852 853
    if (options & REG_OPTION_VOLATILE) key->flags |= KEY_VOLATILE;
    else key->flags |= KEY_DIRTY;
854

855 856 857
    if (sd) default_set_sd( &key->obj, sd, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION |
                            DACL_SECURITY_INFORMATION | SACL_SECURITY_INFORMATION );

858
    if (debug_level > 1) dump_operation( key, NULL, "Create" );
859 860 861
    if (class && class->len)
    {
        key->classlen = class->len;
862
        free(key->class);
863 864
        if (!(key->class = memdup( class->str, key->classlen ))) key->classlen = 0;
    }
865
    touch_key( key->parent, REG_NOTIFY_CHANGE_NAME );
866 867 868 869
    grab_object( key );
    return key;
}

870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
/* recursively create a subkey (for internal use only) */
static struct key *create_key_recursive( struct key *key, const struct unicode_str *name, timeout_t modif )
{
    struct key *base;
    int index;
    struct unicode_str token;

    token.str = NULL;
    if (!get_path_token( name, &token )) return NULL;
    while (token.len)
    {
        struct key *subkey;
        if (!(subkey = find_subkey( key, &token, &index ))) break;
        key = subkey;
        if (!(key = follow_symlink( key, 0 )))
        {
            set_error( STATUS_OBJECT_NAME_NOT_FOUND );
            return NULL;
        }
        get_path_token( name, &token );
    }

    if (token.len)
    {
        if (!(key = alloc_subkey( key, &token, index, modif ))) return NULL;
        base = key;
        for (;;)
        {
            get_path_token( name, &token );
            if (!token.len) break;
            /* we know the index is always 0 in a new key */
            if (!(key = alloc_subkey( key, &token, 0, modif )))
            {
                free_subkey( base, index );
                return NULL;
            }
        }
    }

    grab_object( key );
    return key;
}

913
/* query information about a key or a subkey */
914
static void enum_key( struct key *key, int index, int info_class, struct enum_key_reply *reply )
915
{
916
    int i;
917
    data_size_t len, namelen, classlen;
918 919
    data_size_t max_subkey = 0, max_class = 0;
    data_size_t max_value = 0, max_data = 0;
920
    WCHAR *fullname = NULL;
921
    char *data;
922

923 924 925 926 927 928
    if (key->flags & KEY_PREDEF)
    {
        set_error( STATUS_INVALID_HANDLE );
        return;
    }

929 930 931 932 933
    if (index != -1)  /* -1 means use the specified key directly */
    {
        if ((index < 0) || (index > key->last_subkey))
        {
            set_error( STATUS_NO_MORE_ENTRIES );
934
            return;
935 936 937 938
        }
        key = key->subkeys[index];
    }

939 940
    namelen = key->namelen;
    classlen = key->classlen;
941 942

    switch(info_class)
943
    {
944
    case KeyNameInformation:
945
        if (!(fullname = key->obj.ops->get_full_name( &key->obj, &namelen ))) return;
946 947
        /* fall through */
    case KeyBasicInformation:
948 949 950 951 952 953 954 955 956
        classlen = 0; /* only return the name */
        /* fall through */
    case KeyNodeInformation:
        reply->max_subkey = 0;
        reply->max_class  = 0;
        reply->max_value  = 0;
        reply->max_data   = 0;
        break;
    case KeyFullInformation:
957
    case KeyCachedInformation:
958 959
        for (i = 0; i <= key->last_subkey; i++)
        {
960 961
            if (key->subkeys[i]->namelen > max_subkey) max_subkey = key->subkeys[i]->namelen;
            if (key->subkeys[i]->classlen > max_class) max_class = key->subkeys[i]->classlen;
962 963 964
        }
        for (i = 0; i <= key->last_value; i++)
        {
965 966
            if (key->values[i].namelen > max_value) max_value = key->values[i].namelen;
            if (key->values[i].len > max_data) max_data = key->values[i].len;
967
        }
968 969 970 971
        reply->max_subkey = max_subkey;
        reply->max_class  = max_class;
        reply->max_value  = max_value;
        reply->max_data   = max_data;
972 973 974 975
        reply->namelen    = namelen;
        if (info_class == KeyCachedInformation)
            classlen = 0; /* don't return any data, only its size */
        namelen = 0;  /* don't return name */
976 977 978 979
        break;
    default:
        set_error( STATUS_INVALID_PARAMETER );
        return;
980
    }
981 982 983 984
    reply->subkeys = key->last_subkey + 1;
    reply->values  = key->last_value + 1;
    reply->modif   = key->modif;
    reply->total   = namelen + classlen;
985

986 987
    len = min( reply->total, get_reply_max_size() );
    if (len && (data = set_reply_data_size( len )))
988
    {
989 990 991 992
        if (len > namelen)
        {
            reply->namelen = namelen;
            memcpy( data, key->name, namelen );
993
            memcpy( data + namelen, key->class, len - namelen );
994
        }
995 996 997
        else if (info_class == KeyNameInformation)
        {
            reply->namelen = namelen;
998
            memcpy( data, fullname, len );
999
        }
1000 1001 1002 1003 1004
        else
        {
            reply->namelen = len;
            memcpy( data, key->name, len );
        }
1005
    }
1006
    free( fullname );
1007
    if (debug_level > 1) dump_operation( key, NULL, "Enum" );
1008 1009 1010
}

/* delete a key and its values */
1011
static int delete_key( struct key *key, int recurse )
1012 1013
{
    int index;
1014
    struct key *parent = key->parent;
1015

1016
    /* must find parent and index */
1017
    if (key == root_key)
1018
    {
1019
        set_error( STATUS_ACCESS_DENIED );
1020
        return -1;
1021
    }
1022
    assert( parent );
1023

1024 1025 1026 1027 1028 1029
    if (key->flags & KEY_PREDEF)
    {
        set_error( STATUS_INVALID_HANDLE );
        return -1;
    }

1030
    while (recurse && (key->last_subkey>=0))
1031
        if (0 > delete_key(key->subkeys[key->last_subkey], 1))
1032 1033
            return -1;

1034 1035 1036
    for (index = 0; index <= parent->last_subkey; index++)
        if (parent->subkeys[index] == key) break;
    assert( index <= parent->last_subkey );
1037

1038 1039
    /* we can only delete a key that has no subkeys */
    if (key->last_subkey >= 0)
1040
    {
1041
        set_error( STATUS_ACCESS_DENIED );
1042
        return -1;
1043
    }
1044

1045 1046
    if (debug_level > 1) dump_operation( key, NULL, "Delete" );
    free_subkey( parent, index );
1047
    touch_key( parent, REG_NOTIFY_CHANGE_NAME );
1048
    return 0;
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
}

/* try to grow the array of values; return 1 if OK, 0 on error */
static int grow_values( struct key *key )
{
    struct key_value *new_val;
    int nb_values;

    if (key->nb_values)
    {
        nb_values = key->nb_values + (key->nb_values / 2);  /* grow by 50% */
        if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) )))
        {
1062
            set_error( STATUS_NO_MEMORY );
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
            return 0;
        }
    }
    else
    {
        nb_values = MIN_VALUES;
        if (!(new_val = mem_alloc( nb_values * sizeof(*new_val) ))) return 0;
    }
    key->values = new_val;
    key->nb_values = nb_values;
    return 1;
}

/* find the named value of a given key and return its index in the array */
1077
static struct key_value *find_value( const struct key *key, const struct unicode_str *name, int *index )
1078 1079
{
    int i, min, max, res;
1080
    data_size_t len;
1081 1082 1083 1084 1085 1086

    min = 0;
    max = key->last_value;
    while (min <= max)
    {
        i = (min + max) / 2;
1087
        len = min( key->values[i].namelen, name->len );
1088
        res = memicmp_strW( key->values[i].name, name->str, len );
1089 1090
        if (!res) res = key->values[i].namelen - name->len;
        if (!res)
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        {
            *index = i;
            return &key->values[i];
        }
        if (res > 0) max = i - 1;
        else min = i + 1;
    }
    *index = min;  /* this is where we should insert it */
    return NULL;
}

1102
/* insert a new value; the index must have been returned by find_value */
1103
static struct key_value *insert_value( struct key *key, const struct unicode_str *name, int index )
1104 1105
{
    struct key_value *value;
1106
    WCHAR *new_name = NULL;
1107
    int i;
1108

1109 1110 1111 1112 1113
    if (name->len > MAX_VALUE_LEN * sizeof(WCHAR))
    {
        set_error( STATUS_NAME_TOO_LONG );
        return NULL;
    }
1114
    if (key->last_value + 1 == key->nb_values)
1115
    {
1116
        if (!grow_values( key )) return NULL;
1117
    }
1118
    if (name->len && !(new_name = memdup( name->str, name->len ))) return NULL;
1119 1120
    for (i = ++key->last_value; i > index; i--) key->values[i] = key->values[i - 1];
    value = &key->values[index];
1121 1122 1123 1124
    value->name    = new_name;
    value->namelen = name->len;
    value->len     = 0;
    value->data    = NULL;
1125 1126 1127 1128
    return value;
}

/* set a key value */
1129
static void set_value( struct key *key, const struct unicode_str *name,
1130
                       int type, const void *data, data_size_t len )
1131 1132 1133
{
    struct key_value *value;
    void *ptr = NULL;
1134 1135
    int index;

1136 1137 1138 1139 1140 1141
    if (key->flags & KEY_PREDEF)
    {
        set_error( STATUS_INVALID_HANDLE );
        return;
    }

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    if ((value = find_value( key, name, &index )))
    {
        /* check if the new value is identical to the existing one */
        if (value->type == type && value->len == len &&
            value->data && !memcmp( value->data, data, len ))
        {
            if (debug_level > 1) dump_operation( key, value, "Skip setting" );
            return;
        }
    }
1152

1153 1154 1155
    if (key->flags & KEY_SYMLINK)
    {
        if (type != REG_LINK || name->len != symlink_str.len ||
1156
            memicmp_strW( name->str, symlink_str.str, name->len ))
1157 1158 1159 1160 1161 1162
        {
            set_error( STATUS_ACCESS_DENIED );
            return;
        }
    }

1163
    if (len && !(ptr = memdup( data, len ))) return;
1164

1165
    if (!value)
1166
    {
1167 1168
        if (!(value = insert_value( key, name, index )))
        {
1169
            free( ptr );
1170 1171
            return;
        }
1172
    }
1173
    else free( value->data ); /* already existing, free previous data */
1174

1175
    value->type  = type;
1176
    value->len   = len;
1177
    value->data  = ptr;
1178
    touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1179 1180 1181 1182
    if (debug_level > 1) dump_operation( key, value, "Set" );
}

/* get a key value */
1183
static void get_value( struct key *key, const struct unicode_str *name, int *type, data_size_t *len )
1184 1185 1186 1187
{
    struct key_value *value;
    int index;

1188 1189 1190 1191 1192 1193
    if (key->flags & KEY_PREDEF)
    {
        set_error( STATUS_INVALID_HANDLE );
        return;
    }

1194 1195 1196 1197
    if ((value = find_value( key, name, &index )))
    {
        *type = value->type;
        *len  = value->len;
1198
        if (value->data) set_reply_data( value->data, min( value->len, get_reply_max_size() ));
1199 1200 1201 1202 1203
        if (debug_level > 1) dump_operation( key, value, "Get" );
    }
    else
    {
        *type = -1;
1204
        set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1205 1206 1207 1208
    }
}

/* enumerate a key value */
1209
static void enum_value( struct key *key, int i, int info_class, struct enum_key_value_reply *reply )
1210 1211 1212
{
    struct key_value *value;

1213 1214 1215 1216 1217 1218
    if (key->flags & KEY_PREDEF)
    {
        set_error( STATUS_INVALID_HANDLE );
        return;
    }

1219
    if (i < 0 || i > key->last_value) set_error( STATUS_NO_MORE_ENTRIES );
1220 1221
    else
    {
1222
        void *data;
1223
        data_size_t namelen, maxlen;
1224

1225
        value = &key->values[i];
1226
        reply->type = value->type;
1227
        namelen = value->namelen;
1228

1229
        switch(info_class)
1230
        {
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
        case KeyValueBasicInformation:
            reply->total = namelen;
            break;
        case KeyValueFullInformation:
            reply->total = namelen + value->len;
            break;
        case KeyValuePartialInformation:
            reply->total = value->len;
            namelen = 0;
            break;
        default:
            set_error( STATUS_INVALID_PARAMETER );
            return;
        }

        maxlen = min( reply->total, get_reply_max_size() );
        if (maxlen && ((data = set_reply_data_size( maxlen ))))
        {
            if (maxlen > namelen)
1250
            {
1251 1252 1253
                reply->namelen = namelen;
                memcpy( data, value->name, namelen );
                memcpy( (char *)data + namelen, value->data, maxlen - namelen );
1254
            }
1255
            else
1256
            {
1257 1258
                reply->namelen = maxlen;
                memcpy( data, value->name, maxlen );
1259
            }
1260
        }
1261 1262 1263 1264 1265
        if (debug_level > 1) dump_operation( key, value, "Enum" );
    }
}

/* delete a value */
1266
static void delete_value( struct key *key, const struct unicode_str *name )
1267 1268 1269 1270
{
    struct key_value *value;
    int i, index, nb_values;

1271 1272 1273 1274 1275 1276
    if (key->flags & KEY_PREDEF)
    {
        set_error( STATUS_INVALID_HANDLE );
        return;
    }

1277 1278
    if (!(value = find_value( key, name, &index )))
    {
1279
        set_error( STATUS_OBJECT_NAME_NOT_FOUND );
1280 1281 1282
        return;
    }
    if (debug_level > 1) dump_operation( key, value, "Delete" );
1283 1284
    free( value->name );
    free( value->data );
1285 1286
    for (i = index; i < key->last_value; i++) key->values[i] = key->values[i + 1];
    key->last_value--;
1287
    touch_key( key, REG_NOTIFY_CHANGE_LAST_SET );
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

    /* try to shrink the array */
    nb_values = key->nb_values;
    if (nb_values > MIN_VALUES && key->last_value < nb_values / 2)
    {
        struct key_value *new_val;
        nb_values -= nb_values / 3;  /* shrink by 33% */
        if (nb_values < MIN_VALUES) nb_values = MIN_VALUES;
        if (!(new_val = realloc( key->values, nb_values * sizeof(*new_val) ))) return;
        key->values = new_val;
        key->nb_values = nb_values;
    }
1300
}
1301 1302

/* get the registry key corresponding to an hkey handle */
1303
static struct key *get_hkey_obj( obj_handle_t hkey, unsigned int access )
1304
{
1305 1306 1307 1308 1309 1310 1311 1312 1313
    struct key *key = (struct key *)get_handle_obj( current->process, hkey, access, &key_ops );

    if (key && key->flags & KEY_DELETED)
    {
        set_error( STATUS_KEY_DELETED );
        release_object( key );
        key = NULL;
    }
    return key;
1314 1315
}

1316 1317 1318 1319
/* get the registry key corresponding to a parent key handle */
static inline struct key *get_parent_hkey_obj( obj_handle_t hkey )
{
    if (!hkey) return (struct key *)grab_object( root_key );
1320
    return get_hkey_obj( hkey, 0 );
1321 1322
}

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
/* read a line from the input file */
static int read_next_line( struct file_load_info *info )
{
    char *newbuf;
    int newlen, pos = 0;

    info->line++;
    for (;;)
    {
        if (!fgets( info->buffer + pos, info->len - pos, info->file ))
            return (pos != 0);  /* EOF */
        pos = strlen(info->buffer);
        if (info->buffer[pos-1] == '\n')
        {
            /* got a full line */
            info->buffer[--pos] = 0;
            if (pos > 0 && info->buffer[pos-1] == '\r') info->buffer[pos-1] = 0;
            return 1;
        }
        if (pos < info->len - 1) return 1;  /* EOF but something was read */

        /* need to enlarge the buffer */
        newlen = info->len + info->len / 2;
        if (!(newbuf = realloc( info->buffer, newlen )))
        {
1348
            set_error( STATUS_NO_MEMORY );
1349 1350 1351 1352 1353 1354 1355 1356
            return -1;
        }
        info->buffer = newbuf;
        info->len = newlen;
    }
}

/* make sure the temp buffer holds enough space */
1357
static int get_file_tmp_space( struct file_load_info *info, size_t size )
1358
{
1359
    WCHAR *tmp;
1360 1361 1362
    if (info->tmplen >= size) return 1;
    if (!(tmp = realloc( info->tmp, size )))
    {
1363
        set_error( STATUS_NO_MEMORY );
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
        return 0;
    }
    info->tmp = tmp;
    info->tmplen = size;
    return 1;
}

/* report an error while loading an input file */
static void file_read_error( const char *err, struct file_load_info *info )
{
1374 1375 1376 1377
    if (info->filename)
        fprintf( stderr, "%s:%d: %s '%s'\n", info->filename, info->line, err, info->buffer );
    else
        fprintf( stderr, "<fd>:%d: %s '%s'\n", info->line, err, info->buffer );
1378 1379 1380 1381 1382 1383 1384
}

/* convert a data type tag to a value type */
static int get_data_type( const char *buffer, int *type, int *parse_type )
{
    struct data_type { const char *tag; int len; int type; int parse_type; };

1385
    static const struct data_type data_types[] =
1386 1387 1388 1389 1390 1391 1392 1393
    {                   /* actual type */  /* type to assume for parsing */
        { "\"",        1,   REG_SZ,              REG_SZ },
        { "str:\"",    5,   REG_SZ,              REG_SZ },
        { "str(2):\"", 8,   REG_EXPAND_SZ,       REG_SZ },
        { "str(7):\"", 8,   REG_MULTI_SZ,        REG_SZ },
        { "hex:",      4,   REG_BINARY,          REG_BINARY },
        { "dword:",    6,   REG_DWORD,           REG_DWORD },
        { "hex(",      4,   -1,                  REG_BINARY },
1394
        { NULL,        0,    0,                  0 }
1395 1396 1397 1398 1399 1400 1401
    };

    const struct data_type *ptr;
    char *end;

    for (ptr = data_types; ptr->tag; ptr++)
    {
1402
        if (strncmp( ptr->tag, buffer, ptr->len )) continue;
1403 1404 1405 1406
        *parse_type = ptr->parse_type;
        if ((*type = ptr->type) != -1) return ptr->len;
        /* "hex(xx):" is special */
        *type = (int)strtoul( buffer + 4, &end, 16 );
1407
        if ((end <= buffer) || strncmp( end, "):", 2 )) return 0;
1408 1409 1410 1411 1412 1413
        return end + 2 - buffer;
    }
    return 0;
}

/* load and create a key from the input file */
1414 1415
static struct key *load_key( struct key *base, const char *buffer, int prefix_len,
                             struct file_load_info *info, timeout_t *modif )
1416
{
1417 1418
    WCHAR *p;
    struct unicode_str name;
1419 1420
    int res;
    unsigned int mod;
1421
    data_size_t len;
1422

1423
    if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1424

1425
    len = info->tmplen;
1426
    if ((res = parse_strW( info->tmp, &len, buffer, ']' )) == -1)
1427 1428 1429 1430
    {
        file_read_error( "Malformed key", info );
        return NULL;
    }
1431
    if (sscanf( buffer + res, " %u", &mod ) == 1)
1432 1433 1434
        *modif = (timeout_t)mod * TICKS_PER_SEC + ticks_1601_to_1970;
    else
        *modif = current_time;
1435

1436
    p = info->tmp;
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
    while (prefix_len && *p) { if (*p++ == '\\') prefix_len--; }

    if (!*p)
    {
        if (prefix_len > 1)
        {
            file_read_error( "Malformed key", info );
            return NULL;
        }
        /* empty key name, return base key */
        return (struct key *)grab_object( base );
    }
1449 1450
    name.str = p;
    name.len = len - (p - info->tmp + 1) * sizeof(WCHAR);
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
    return create_key_recursive( base, &name, 0 );
}

/* update the modification time of a key (and its parents) after it has been loaded from a file */
static void update_key_time( struct key *key, timeout_t modif )
{
    while (key && !key->modif)
    {
        key->modif = modif;
        key = key->parent;
    }
1462 1463
}

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
/* load a global option from the input file */
static int load_global_option( const char *buffer, struct file_load_info *info )
{
    const char *p;

    if (!strncmp( buffer, "#arch=", 6 ))
    {
        enum prefix_type type;
        p = buffer + 6;
        if (!strcmp( p, "win32" )) type = PREFIX_32BIT;
        else if (!strcmp( p, "win64" )) type = PREFIX_64BIT;
        else
        {
            file_read_error( "Unknown architecture", info );
            set_error( STATUS_NOT_REGISTRY_FILE );
            return 0;
        }
        if (prefix_type == PREFIX_UNKNOWN) prefix_type = type;
        else if (type != prefix_type)
        {
            file_read_error( "Mismatched architecture", info );
            set_error( STATUS_NOT_REGISTRY_FILE );
            return 0;
        }
    }
    /* ignore unknown options */
    return 1;
}

1493 1494 1495 1496 1497 1498
/* load a key option from the input file */
static int load_key_option( struct key *key, const char *buffer, struct file_load_info *info )
{
    const char *p;
    data_size_t len;

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
    if (!strncmp( buffer, "#time=", 6 ))
    {
        timeout_t modif = 0;
        for (p = buffer + 6; *p; p++)
        {
            if (*p >= '0' && *p <= '9') modif = (modif << 4) | (*p - '0');
            else if (*p >= 'A' && *p <= 'F') modif = (modif << 4) | (*p - 'A' + 10);
            else if (*p >= 'a' && *p <= 'f') modif = (modif << 4) | (*p - 'a' + 10);
            else break;
        }
        update_key_time( key, modif );
    }
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
    if (!strncmp( buffer, "#class=", 7 ))
    {
        p = buffer + 7;
        if (*p++ != '"') return 0;
        if (!get_file_tmp_space( info, strlen(p) * sizeof(WCHAR) )) return 0;
        len = info->tmplen;
        if (parse_strW( info->tmp, &len, p, '\"' ) == -1) return 0;
        free( key->class );
        if (!(key->class = memdup( info->tmp, len ))) len = 0;
        key->classlen = len;
    }
1522
    if (!strncmp( buffer, "#link", 5 )) key->flags |= KEY_SYMLINK;
1523 1524 1525 1526
    /* ignore unknown options */
    return 1;
}

1527
/* parse a comma-separated list of hex digits */
1528
static int parse_hex( unsigned char *dest, data_size_t *len, const char *buffer )
1529 1530
{
    const char *p = buffer;
1531
    data_size_t count = 0;
1532 1533
    char *end;

1534 1535
    while (isxdigit(*p))
    {
1536 1537
        unsigned int val = strtoul( p, &end, 16 );
        if (end == p || val > 0xff) return -1;
1538
        if (count++ >= *len) return -1;  /* dest buffer overflow */
1539 1540 1541
        *dest++ = val;
        p = end;
        while (isspace(*p)) p++;
1542
        if (*p == ',') p++;
1543
        while (isspace(*p)) p++;
1544 1545 1546 1547 1548 1549
    }
    *len = count;
    return p - buffer;
}

/* parse a value name and create the corresponding value */
1550
static struct key_value *parse_value_name( struct key *key, const char *buffer, data_size_t *len,
1551 1552
                                           struct file_load_info *info )
{
1553
    struct key_value *value;
1554 1555
    struct unicode_str name;
    int index;
1556

1557
    if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return NULL;
1558
    name.str = info->tmp;
1559
    name.len = info->tmplen;
1560 1561
    if (buffer[0] == '@')
    {
1562
        name.len = 0;
1563 1564 1565 1566
        *len = 1;
    }
    else
    {
1567
        int r = parse_strW( info->tmp, &name.len, buffer + 1, '\"' );
1568 1569
        if (r == -1) goto error;
        *len = r + 1; /* for initial quote */
1570
        name.len -= sizeof(WCHAR);  /* terminating null */
1571
    }
1572
    while (isspace(buffer[*len])) (*len)++;
1573 1574
    if (buffer[*len] != '=') goto error;
    (*len)++;
1575
    while (isspace(buffer[*len])) (*len)++;
1576
    if (!(value = find_value( key, &name, &index ))) value = insert_value( key, &name, index );
1577
    return value;
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588

 error:
    file_read_error( "Malformed value name", info );
    return NULL;
}

/* load a value from the input file */
static int load_value( struct key *key, const char *buffer, struct file_load_info *info )
{
    DWORD dw;
    void *ptr, *newptr;
1589
    int res, type, parse_type;
1590
    data_size_t maxlen, len;
1591 1592 1593 1594 1595 1596 1597 1598 1599
    struct key_value *value;

    if (!(value = parse_value_name( key, buffer, &len, info ))) return 0;
    if (!(res = get_data_type( buffer + len, &type, &parse_type ))) goto error;
    buffer += len + res;

    switch(parse_type)
    {
    case REG_SZ:
1600 1601
        if (!get_file_tmp_space( info, strlen(buffer) * sizeof(WCHAR) )) return 0;
        len = info->tmplen;
1602
        if ((res = parse_strW( info->tmp, &len, buffer, '\"' )) == -1) goto error;
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        ptr = info->tmp;
        break;
    case REG_DWORD:
        dw = strtoul( buffer, NULL, 16 );
        ptr = &dw;
        len = sizeof(dw);
        break;
    case REG_BINARY:  /* hex digits */
        len = 0;
        for (;;)
        {
1614
            maxlen = 1 + strlen(buffer) / 2;  /* at least 2 chars for one hex byte */
1615
            if (!get_file_tmp_space( info, len + maxlen )) return 0;
1616
            if ((res = parse_hex( (unsigned char *)info->tmp + len, &maxlen, buffer )) == -1) goto error;
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
            len += maxlen;
            buffer += res;
            while (isspace(*buffer)) buffer++;
            if (!*buffer) break;
            if (*buffer != '\\') goto error;
            if (read_next_line( info) != 1) goto error;
            buffer = info->buffer;
            while (isspace(*buffer)) buffer++;
        }
        ptr = info->tmp;
        break;
    default:
        assert(0);
        ptr = NULL;  /* keep compiler quiet */
        break;
    }

    if (!len) newptr = NULL;
    else if (!(newptr = memdup( ptr, len ))) return 0;

1637
    free( value->data );
1638 1639 1640 1641 1642 1643 1644
    value->data = newptr;
    value->len  = len;
    value->type = type;
    return 1;

 error:
    file_read_error( "Malformed value", info );
1645 1646 1647 1648
    free( value->data );
    value->data = NULL;
    value->len  = 0;
    value->type = REG_NONE;
1649 1650 1651
    return 0;
}

1652 1653 1654 1655 1656 1657
/* return the length (in path elements) of name that is part of the key name */
/* for instance if key is USER\foo\bar and name is foo\bar\baz, return 2 */
static int get_prefix_len( struct key *key, const char *name, struct file_load_info *info )
{
    WCHAR *p;
    int res;
1658
    data_size_t len;
1659

1660
    if (!get_file_tmp_space( info, strlen(name) * sizeof(WCHAR) )) return 0;
1661

1662
    len = info->tmplen;
1663
    if ((res = parse_strW( info->tmp, &len, name, ']' )) == -1)
1664 1665
    {
        file_read_error( "Malformed key", info );
1666
        return 0;
1667
    }
1668
    for (p = info->tmp; *p; p++) if (*p == '\\') break;
1669
    len = (p - info->tmp) * sizeof(WCHAR);
1670
    for (res = 1; key != root_key; res++)
1671
    {
1672
        if (len == key->namelen && !memicmp_strW( info->tmp, key->name, len )) break;
1673 1674
        key = key->parent;
    }
1675
    if (key == root_key) res = 0;  /* no matching name */
1676 1677 1678
    return res;
}

1679
/* load all the keys from the input file */
1680
/* prefix_len is the number of key name prefixes to skip, or -1 for autodetection */
1681
static void load_keys( struct key *key, const char *filename, FILE *f, int prefix_len )
1682 1683 1684
{
    struct key *subkey = NULL;
    struct file_load_info info;
1685
    timeout_t modif = current_time;
1686
    char *p;
1687

1688
    info.filename = filename;
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    info.file   = f;
    info.len    = 4;
    info.tmplen = 4;
    info.line   = 0;
    if (!(info.buffer = mem_alloc( info.len ))) return;
    if (!(info.tmp = mem_alloc( info.tmplen )))
    {
        free( info.buffer );
        return;
    }

    if ((read_next_line( &info ) != 1) ||
        strcmp( info.buffer, "WINE REGISTRY Version 2" ))
    {
1703
        set_error( STATUS_NOT_REGISTRY_FILE );
1704 1705 1706 1707 1708
        goto done;
    }

    while (read_next_line( &info ) == 1)
    {
1709 1710
        p = info.buffer;
        while (*p && isspace(*p)) p++;
1711 1712 1713
        switch(*p)
        {
        case '[':   /* new key */
1714 1715 1716 1717 1718
            if (subkey)
            {
                update_key_time( subkey, modif );
                release_object( subkey );
            }
1719
            if (prefix_len == -1) prefix_len = get_prefix_len( key, p + 1, &info );
1720
            if (!(subkey = load_key( key, p + 1, prefix_len, &info, &modif )))
1721
                file_read_error( "Error creating key", &info );
1722 1723 1724 1725 1726 1727
            break;
        case '@':   /* default value */
        case '\"':  /* value */
            if (subkey) load_value( subkey, p, &info );
            else file_read_error( "Value without key", &info );
            break;
1728 1729
        case '#':   /* option */
            if (subkey) load_key_option( subkey, p, &info );
1730
            else if (!load_global_option( p, &info )) goto done;
1731
            break;
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
        case ';':   /* comment */
        case 0:     /* empty line */
            break;
        default:
            file_read_error( "Unrecognized input", &info );
            break;
        }
    }

 done:
1742 1743 1744 1745 1746
    if (subkey)
    {
        update_key_time( subkey, modif );
        release_object( subkey );
    }
1747 1748 1749 1750 1751
    free( info.buffer );
    free( info.tmp );
}

/* load a part of the registry from a file */
1752
static void load_registry( struct key *key, obj_handle_t handle )
1753
{
1754
    struct file *file;
1755 1756
    int fd;

1757
    if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) return;
1758 1759
    fd = dup( get_file_unix_fd( file ) );
    release_object( file );
1760 1761 1762 1763 1764
    if (fd != -1)
    {
        FILE *f = fdopen( fd, "r" );
        if (f)
        {
1765
            load_keys( key, NULL, f, -1 );
1766 1767 1768 1769 1770 1771
            fclose( f );
        }
        else file_set_error();
    }
}

1772
/* load one of the initial registry files */
1773
static int load_init_registry_from_file( const char *filename, struct key *key )
1774 1775 1776
{
    FILE *f;

1777 1778
    if ((f = fopen( filename, "r" )))
    {
1779
        load_keys( key, filename, f, 0 );
1780 1781
        fclose( f );
        if (get_error() == STATUS_NOT_REGISTRY_FILE)
1782 1783
        {
            fprintf( stderr, "%s is not a valid registry file\n", filename );
1784
            return 1;
1785
        }
1786
    }
1787

1788
    assert( save_branch_count < MAX_SAVE_BRANCH_INFO );
1789

1790 1791
    save_branch_info[save_branch_count].path = filename;
    save_branch_info[save_branch_count++].key = (struct key *)grab_object( key );
1792
    make_object_permanent( &key->obj );
1793
    return (f != NULL);
1794 1795
}

1796
static WCHAR *format_user_registry_path( const struct sid *sid, struct unicode_str *path )
1797
{
1798
    char buffer[7 + 11 + 11 + 11 * ARRAY_SIZE(sid->sub_auth)], *p = buffer;
1799 1800
    unsigned int i;

1801 1802 1803 1804 1805 1806
    p += sprintf( p, "User\\S-%u-%u", sid->revision,
                  ((unsigned int)sid->id_auth[2] << 24) |
                  ((unsigned int)sid->id_auth[3] << 16) |
                  ((unsigned int)sid->id_auth[4] << 8) |
                  ((unsigned int)sid->id_auth[5]) );
    for (i = 0; i < sid->sub_count; i++) p += sprintf( p, "-%u", sid->sub_auth[i] );
1807
    return ascii_to_unicode_str( buffer, path );
1808 1809
}

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
static void init_supported_machines(void)
{
    unsigned int count = 0;
#ifdef __i386__
    if (prefix_type == PREFIX_32BIT) supported_machines[count++] = IMAGE_FILE_MACHINE_I386;
#elif defined(__x86_64__)
    if (prefix_type == PREFIX_64BIT) supported_machines[count++] = IMAGE_FILE_MACHINE_AMD64;
    supported_machines[count++] = IMAGE_FILE_MACHINE_I386;
#elif defined(__arm__)
    if (prefix_type == PREFIX_32BIT) supported_machines[count++] = IMAGE_FILE_MACHINE_ARMNT;
#elif defined(__aarch64__)
    if (prefix_type == PREFIX_64BIT)
    {
        supported_machines[count++] = IMAGE_FILE_MACHINE_ARM64;
        supported_machines[count++] = IMAGE_FILE_MACHINE_I386;
    }
    supported_machines[count++] = IMAGE_FILE_MACHINE_ARMNT;
#else
#error Unsupported machine
#endif
    supported_machines_count = count;
1831
    native_machine = supported_machines[0];
1832 1833
}

1834 1835 1836
/* registry initialisation */
void init_registry(void)
{
1837 1838
    static const WCHAR HKLM[] = { 'M','a','c','h','i','n','e' };
    static const WCHAR HKU_default[] = { 'U','s','e','r','\\','.','D','e','f','a','u','l','t' };
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
    static const WCHAR classes_i386[] = {'S','o','f','t','w','a','r','e','\\',
                                         'C','l','a','s','s','e','s','\\',
                                         'W','o','w','6','4','3','2','N','o','d','e'};
    static const WCHAR classes_amd64[] = {'S','o','f','t','w','a','r','e','\\',
                                          'C','l','a','s','s','e','s','\\',
                                          'W','o','w','6','4','6','4','N','o','d','e'};
    static const WCHAR classes_arm[] = {'S','o','f','t','w','a','r','e','\\',
                                        'C','l','a','s','s','e','s','\\',
                                        'W','o','w','A','A','3','2','N','o','d','e'};
    static const WCHAR classes_arm64[] = {'S','o','f','t','w','a','r','e','\\',
                                          'C','l','a','s','s','e','s','\\',
                                          'W','o','w','A','A','6','4','N','o','d','e'};
1851 1852 1853 1854 1855 1856
    static const WCHAR perflib[] = {'S','o','f','t','w','a','r','e','\\',
                                    'M','i','c','r','o','s','o','f','t','\\',
                                    'W','i','n','d','o','w','s',' ','N','T','\\',
                                    'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                    'P','e','r','f','l','i','b','\\',
                                    '0','0','9'};
1857 1858 1859
    static const struct unicode_str root_name = { NULL, 0 };
    static const struct unicode_str HKLM_name = { HKLM, sizeof(HKLM) };
    static const struct unicode_str HKU_name = { HKU_default, sizeof(HKU_default) };
1860
    static const struct unicode_str perflib_name = { perflib, sizeof(perflib) };
1861

1862
    WCHAR *current_user_path;
1863
    struct unicode_str current_user_str;
1864
    struct key *key, *hklm, *hkcu;
1865
    unsigned int i;
1866
    char *p;
1867

1868 1869
    /* switch to the config dir */

1870
    if (fchdir( config_dir_fd ) == -1) fatal_error( "chdir to config dir: %s\n", strerror( errno ));
1871

1872
    /* create the root key */
1873
    root_key = alloc_key( &root_name, current_time );
1874
    assert( root_key );
1875
    make_object_permanent( &root_key->obj );
1876

1877 1878
    /* load system.reg into Registry\Machine */

1879
    if (!(hklm = create_key_recursive( root_key, &HKLM_name, current_time )))
1880 1881
        fatal_error( "could not create Machine registry key\n" );

1882
    if (!load_init_registry_from_file( "system.reg", hklm ))
1883 1884 1885 1886 1887 1888
    {
        if ((p = getenv( "WINEARCH" )) && !strcmp( p, "win32" ))
            prefix_type = PREFIX_32BIT;
        else
            prefix_type = sizeof(void *) > sizeof(int) ? PREFIX_64BIT : PREFIX_32BIT;
    }
1889 1890
    else if (prefix_type == PREFIX_UNKNOWN)
        prefix_type = PREFIX_32BIT;
1891

1892 1893
    init_supported_machines();

1894 1895
    /* load userdef.reg into Registry\User\.Default */

1896
    if (!(key = create_key_recursive( root_key, &HKU_name, current_time )))
1897 1898
        fatal_error( "could not create User\\.Default registry key\n" );

1899
    load_init_registry_from_file( "userdef.reg", key );
1900 1901
    release_object( key );

1902 1903
    /* load user.reg into HKEY_CURRENT_USER */

1904
    /* FIXME: match default user in token.c. should get from process token instead */
1905
    current_user_path = format_user_registry_path( &local_user_sid, &current_user_str );
1906
    if (!current_user_path ||
1907
        !(hkcu = create_key_recursive( root_key, &current_user_str, current_time )))
1908
        fatal_error( "could not create HKEY_CURRENT_USER registry key\n" );
1909
    free( current_user_path );
1910 1911
    load_init_registry_from_file( "user.reg", hkcu );

1912 1913
    /* set the shared flag on Software\Classes\Wow6432Node for all platforms */
    for (i = 1; i < supported_machines_count; i++)
1914
    {
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
        struct unicode_str name;

        switch (supported_machines[i])
        {
        case IMAGE_FILE_MACHINE_I386:  name.str = classes_i386;  name.len = sizeof(classes_i386);  break;
        case IMAGE_FILE_MACHINE_ARMNT: name.str = classes_arm;   name.len = sizeof(classes_arm);   break;
        case IMAGE_FILE_MACHINE_AMD64: name.str = classes_amd64; name.len = sizeof(classes_amd64); break;
        case IMAGE_FILE_MACHINE_ARM64: name.str = classes_arm64; name.len = sizeof(classes_arm64); break;
        }
        if ((key = create_key_recursive( hklm, &name, current_time )))
1925 1926 1927 1928 1929 1930 1931
        {
            key->flags |= KEY_WOWSHARE;
            release_object( key );
        }
        /* FIXME: handle HKCU too */
    }

1932 1933 1934 1935 1936 1937
    if ((key = create_key_recursive( hklm, &perflib_name, current_time )))
    {
        key->flags |= KEY_PREDEF;
        release_object( key );
    }

1938 1939
    release_object( hklm );
    release_object( hkcu );
1940 1941 1942

    /* start the periodic save timer */
    set_periodic_save_timer();
1943

1944 1945 1946 1947 1948
    /* create windows directories */

    if (!mkdir( "drive_c/windows", 0777 ))
    {
        mkdir( "drive_c/windows/system32", 0777 );
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
        for (i = 1; i < supported_machines_count; i++)
        {
            switch (supported_machines[i])
            {
            case IMAGE_FILE_MACHINE_I386:  mkdir( "drive_c/windows/syswow64", 0777 ); break;
            case IMAGE_FILE_MACHINE_ARMNT: mkdir( "drive_c/windows/sysarm32", 0777 ); break;
            case IMAGE_FILE_MACHINE_AMD64: mkdir( "drive_c/windows/sysx8664", 0777 ); break;
            case IMAGE_FILE_MACHINE_ARM64: mkdir( "drive_c/windows/sysarm64", 0777 ); break;
            }
        }
1959 1960
    }

1961
    /* go back to the server dir */
1962
    if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
1963 1964
}

1965 1966
/* save a registry branch to a file */
static void save_all_subkeys( struct key *key, FILE *f )
1967
{
1968 1969 1970 1971
    fprintf( f, "WINE REGISTRY Version 2\n" );
    fprintf( f, ";; All keys relative to " );
    dump_path( key, NULL, f );
    fprintf( f, "\n" );
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
    switch (prefix_type)
    {
    case PREFIX_32BIT:
        fprintf( f, "\n#arch=win32\n" );
        break;
    case PREFIX_64BIT:
        fprintf( f, "\n#arch=win64\n" );
        break;
    default:
        break;
    }
1983
    save_subkeys( key, key, f );
1984 1985 1986
}

/* save a registry branch to a file handle */
1987
static void save_registry( struct key *key, obj_handle_t handle )
1988
{
1989
    struct file *file;
1990 1991
    int fd;

1992
    if (!(file = get_file_obj( current->process, handle, FILE_WRITE_DATA ))) return;
1993 1994
    fd = dup( get_file_unix_fd( file ) );
    release_object( file );
1995 1996 1997 1998 1999
    if (fd != -1)
    {
        FILE *f = fdopen( fd, "w" );
        if (f)
        {
2000
            save_all_subkeys( key, f );
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
            if (fclose( f )) file_set_error();
        }
        else
        {
            file_set_error();
            close( fd );
        }
    }
}

2011 2012 2013
/* save a registry branch to a file */
static int save_branch( struct key *key, const char *path )
{
2014
    struct stat st;
2015 2016
    char *p, *tmp = NULL;
    int fd, count = 0, ret = 0;
2017 2018
    FILE *f;

2019 2020 2021 2022 2023 2024
    if (!(key->flags & KEY_DIRTY))
    {
        if (debug_level > 1) dump_operation( key, NULL, "Not saving clean" );
        return 1;
    }

2025 2026 2027 2028
    /* test the file type */

    if ((fd = open( path, O_WRONLY )) != -1)
    {
2029 2030
        /* if file is not a regular file or has multiple links or is accessed
         * via symbolic links, write directly into it; otherwise use a temp file */
2031
        if (!lstat( path, &st ) && (!S_ISREG(st.st_mode) || st.st_nlink > 1))
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
        {
            ftruncate( fd, 0 );
            goto save;
        }
        close( fd );
    }

    /* create a temp file in the same directory */

    if (!(tmp = malloc( strlen(path) + 20 ))) goto done;
    strcpy( tmp, path );
    if ((p = strrchr( tmp, '/' ))) p++;
    else p = tmp;
    for (;;)
    {
Patrik Stridvall's avatar
Patrik Stridvall committed
2047
        sprintf( p, "reg%lx%04x.tmp", (long) getpid(), count++ );
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
        if ((fd = open( tmp, O_CREAT | O_EXCL | O_WRONLY, 0666 )) != -1) break;
        if (errno != EEXIST) goto done;
        close( fd );
    }

    /* now save to it */

 save:
    if (!(f = fdopen( fd, "w" )))
    {
        if (tmp) unlink( tmp );
        close( fd );
        goto done;
    }

    if (debug_level > 1)
    {
        fprintf( stderr, "%s: ", path );
        dump_operation( key, NULL, "saving" );
    }

2069
    save_all_subkeys( key, f );
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
    ret = !fclose(f);

    if (tmp)
    {
        /* if successfully written, rename to final name */
        if (ret) ret = !rename( tmp, path );
        if (!ret) unlink( tmp );
    }

done:
2080
    free( tmp );
2081
    if (ret) make_clean( key );
2082 2083 2084 2085 2086 2087 2088
    return ret;
}

/* periodic saving of the registry */
static void periodic_save( void *arg )
{
    int i;
2089

2090
    if (fchdir( config_dir_fd ) == -1) return;
2091
    save_timeout_user = NULL;
2092 2093
    for (i = 0; i < save_branch_count; i++)
        save_branch( save_branch_info[i].key, save_branch_info[i].path );
2094
    if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
2095 2096 2097 2098 2099 2100 2101
    set_periodic_save_timer();
}

/* start the periodic save timer */
static void set_periodic_save_timer(void)
{
    if (save_timeout_user) remove_timeout_user( save_timeout_user );
2102
    save_timeout_user = add_timeout_user( save_period, periodic_save, NULL );
2103 2104
}

2105 2106
/* save the modified registry branches to disk */
void flush_registry(void)
2107 2108 2109
{
    int i;

2110
    if (fchdir( config_dir_fd ) == -1) return;
2111 2112 2113 2114 2115 2116 2117 2118 2119
    for (i = 0; i < save_branch_count; i++)
    {
        if (!save_branch( save_branch_info[i].key, save_branch_info[i].path ))
        {
            fprintf( stderr, "wineserver: could not save registry branch to %s",
                     save_branch_info[i].path );
            perror( " " );
        }
    }
2120
    if (fchdir( server_dir_fd ) == -1) fatal_error( "chdir to server dir: %s\n", strerror( errno ));
2121 2122
}

2123 2124 2125
/* determine if the thread is wow64 (32-bit client running on 64-bit prefix) */
static int is_wow64_thread( struct thread *thread )
{
2126
    return (is_machine_64bit( native_machine ) && !is_machine_64bit( thread->process->machine ));
2127 2128
}

2129

2130 2131 2132
/* create a registry key */
DECL_HANDLER(create_key)
{
2133
    struct key *key = NULL, *parent;
2134
    struct unicode_str name, class;
2135
    unsigned int access = req->access;
2136
    const struct security_descriptor *sd;
2137
    const struct object_attributes *objattr = get_req_object_attributes( &sd, &name, NULL );
2138 2139

    if (!objattr) return;
2140

2141 2142
    if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;

2143 2144
    class.str = get_req_data_after_objattr( objattr, &class.len );
    class.len = (class.len / sizeof(WCHAR)) * sizeof(WCHAR);
2145

2146
    if (!objattr->rootdir && name.len >= sizeof(root_name) &&
2147
        !memicmp_strW( name.str, root_name, sizeof(root_name) ))
2148
    {
2149
        name.str += ARRAY_SIZE( root_name );
2150
        name.len -= sizeof(root_name);
2151 2152
    }

2153
    /* NOTE: no access rights are required from the parent handle to create a key */
2154
    if ((parent = get_parent_hkey_obj( objattr->rootdir )))
2155
    {
2156
        if ((key = create_key( parent, &name, &class, req->options, access,
2157
                               objattr->attributes, sd, &reply->created )))
2158
        {
2159
            reply->hkey = alloc_handle( current->process, key, access, objattr->attributes );
2160 2161
            release_object( key );
        }
2162 2163 2164 2165 2166 2167 2168 2169
        release_object( parent );
    }
}

/* open a registry key */
DECL_HANDLER(open_key)
{
    struct key *key, *parent;
2170
    struct unicode_str name;
2171 2172
    unsigned int access = req->access;

2173 2174
    if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;

2175
    reply->hkey = 0;
2176
    /* NOTE: no access rights are required to open the parent key, only the child key */
2177
    if ((parent = get_parent_hkey_obj( req->parent )))
2178
    {
2179
        get_req_path( &name, !req->parent );
2180
        if ((key = open_key( parent, &name, access, req->attributes )))
2181
        {
2182
            reply->hkey = alloc_handle( current->process, key, access, req->attributes );
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
            release_object( key );
        }
        release_object( parent );
    }
}

/* delete a registry key */
DECL_HANDLER(delete_key)
{
    struct key *key;

2194
    if ((key = get_hkey_obj( req->hkey, DELETE )))
2195
    {
2196
        delete_key( key, 0);
2197 2198 2199 2200
        release_object( key );
    }
}

2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
/* flush a registry key */
DECL_HANDLER(flush_key)
{
    struct key *key = get_hkey_obj( req->hkey, 0 );
    if (key)
    {
        /* we don't need to do anything here with the current implementation */
        release_object( key );
    }
}

2212 2213 2214 2215 2216
/* enumerate registry subkeys */
DECL_HANDLER(enum_key)
{
    struct key *key;

2217 2218
    if ((key = get_hkey_obj( req->hkey,
                             req->index == -1 ? KEY_QUERY_VALUE : KEY_ENUMERATE_SUB_KEYS )))
2219
    {
2220
        enum_key( key, req->index, req->info_class, reply );
2221 2222 2223 2224 2225 2226 2227 2228
        release_object( key );
    }
}

/* set a value of a registry key */
DECL_HANDLER(set_key_value)
{
    struct key *key;
2229 2230 2231 2232 2233 2234 2235 2236 2237
    struct unicode_str name;

    if (req->namelen > get_req_data_size())
    {
        set_error( STATUS_INVALID_PARAMETER );
        return;
    }
    name.str = get_req_data();
    name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2238

2239 2240
    if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
    {
2241
        data_size_t datalen = get_req_data_size() - req->namelen;
Eric Pouech's avatar
Eric Pouech committed
2242
        const char *data = (const char *)get_req_data() + req->namelen;
2243

2244
        set_value( key, &name, req->type, data, datalen );
2245 2246 2247 2248 2249 2250 2251 2252
        release_object( key );
    }
}

/* retrieve the value of a registry key */
DECL_HANDLER(get_key_value)
{
    struct key *key;
2253
    struct unicode_str name = get_req_unicode_str();
2254

2255
    reply->total = 0;
2256 2257
    if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
    {
2258
        get_value( key, &name, &reply->type, &reply->total );
2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
        release_object( key );
    }
}

/* enumerate the value of a registry key */
DECL_HANDLER(enum_key_value)
{
    struct key *key;

    if ((key = get_hkey_obj( req->hkey, KEY_QUERY_VALUE )))
    {
2270
        enum_value( key, req->index, req->info_class, reply );
2271 2272 2273 2274 2275 2276 2277 2278
        release_object( key );
    }
}

/* delete a value of a registry key */
DECL_HANDLER(delete_key_value)
{
    struct key *key;
2279
    struct unicode_str name = get_req_unicode_str();
2280 2281 2282

    if ((key = get_hkey_obj( req->hkey, KEY_SET_VALUE )))
    {
2283
        delete_value( key, &name );
2284 2285 2286 2287 2288 2289 2290
        release_object( key );
    }
}

/* load a registry branch from a file */
DECL_HANDLER(load_registry)
{
James Hawkins's avatar
James Hawkins committed
2291
    struct key *key, *parent;
2292
    struct unicode_str name;
2293
    const struct security_descriptor *sd;
2294
    const struct object_attributes *objattr = get_req_object_attributes( &sd, &name, NULL );
2295

2296 2297
    if (!objattr) return;

2298
    if (!thread_single_check_privilege( current, SeRestorePrivilege ))
2299 2300 2301 2302 2303
    {
        set_error( STATUS_PRIVILEGE_NOT_HELD );
        return;
    }

2304
    if (!objattr->rootdir && name.len >= sizeof(root_name) &&
2305
        !memicmp_strW( name.str, root_name, sizeof(root_name) ))
2306
    {
2307
        name.str += ARRAY_SIZE( root_name );
2308 2309 2310 2311
        name.len -= sizeof(root_name);
    }

    if ((parent = get_parent_hkey_obj( objattr->rootdir )))
2312
    {
James Hawkins's avatar
James Hawkins committed
2313
        int dummy;
2314
        if ((key = create_key( parent, &name, NULL, 0, KEY_WOW64_64KEY, 0, sd, &dummy )))
James Hawkins's avatar
James Hawkins committed
2315 2316 2317 2318 2319
        {
            load_registry( key, req->file );
            release_object( key );
        }
        release_object( parent );
2320 2321 2322
    }
}

2323 2324
DECL_HANDLER(unload_registry)
{
2325 2326 2327
    struct key *key, *parent;
    struct unicode_str name;
    unsigned int access = 0;
2328

2329
    if (!thread_single_check_privilege( current, SeRestorePrivilege ))
2330 2331 2332 2333
    {
        set_error( STATUS_PRIVILEGE_NOT_HELD );
        return;
    }
2334

2335 2336 2337
    if (!is_wow64_thread( current )) access = (access & ~KEY_WOW64_32KEY) | KEY_WOW64_64KEY;

    if ((parent = get_parent_hkey_obj( req->parent )))
2338
    {
2339 2340 2341
        get_req_path( &name, !req->parent );
        if ((key = open_key( parent, &name, access, req->attributes )))
        {
2342 2343 2344 2345
            if (key->obj.handle_count)
                set_error( STATUS_CANNOT_DELETE );
            else
                delete_key( key, 1 );     /* FIXME */
2346 2347 2348
            release_object( key );
        }
        release_object( parent );
2349 2350 2351
    }
}

2352 2353 2354 2355 2356
/* save a registry branch to a file */
DECL_HANDLER(save_registry)
{
    struct key *key;

2357
    if (!thread_single_check_privilege( current, SeBackupPrivilege ))
2358 2359 2360 2361 2362 2363
    {
        set_error( STATUS_PRIVILEGE_NOT_HELD );
        return;
    }

    if ((key = get_hkey_obj( req->hkey, 0 )))
2364 2365 2366 2367 2368 2369
    {
        save_registry( key, req->file );
        release_object( key );
    }
}

2370 2371 2372 2373 2374 2375 2376 2377
/* add a registry key change notification */
DECL_HANDLER(set_registry_notification)
{
    struct key *key;
    struct event *event;
    struct notify *notify;

    key = get_hkey_obj( req->hkey, KEY_NOTIFY );
2378
    if (key)
2379 2380
    {
        event = get_event_obj( current->process, req->event, SYNCHRONIZE );
2381
        if (event)
2382
        {
2383
            notify = find_notify( key, current->process, req->hkey );
2384
            if (!notify)
2385
            {
2386
                notify = mem_alloc( sizeof(*notify) );
2387
                if (notify)
2388
                {
2389 2390
                    notify->events  = NULL;
                    notify->event_count = 0;
2391 2392 2393
                    notify->subtree = req->subtree;
                    notify->filter  = req->filter;
                    notify->hkey    = req->hkey;
2394
                    notify->process = current->process;
2395
                    list_add_head( &key->notify_list, &notify->entry );
2396 2397
                }
            }
2398
            if (notify)
2399
            {
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
                struct event **new_array;

                if ((new_array = realloc( notify->events, (notify->event_count + 1) * sizeof(*notify->events) )))
                {
                    notify->events = new_array;
                    notify->events[notify->event_count++] = (struct event *)grab_object( event );
                    reset_event( event );
                    set_error( STATUS_PENDING );
                }
                else set_error( STATUS_NO_MEMORY );
2410
            }
2411 2412 2413 2414 2415
            release_object( event );
        }
        release_object( key );
    }
}