ruby: Add unit test for new RLenValue type
[hivex.git] / lib / hivex.c
1 /* hivex - Windows Registry "hive" extraction library.
2  * Copyright (C) 2009-2011 Red Hat Inc.
3  * Derived from code by Petter Nordahl-Hagen under a compatible license:
4  *   Copyright (c) 1997-2007 Petter Nordahl-Hagen.
5  * Derived from code by Markus Stephany under a compatible license:
6  *   Copyright (c) 2000-2004, Markus Stephany.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation;
11  * version 2.1 of the License.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * See file LICENSE for the full license.
19  */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdint.h>
26 #include <stddef.h>
27 #include <inttypes.h>
28 #include <string.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <iconv.h>
33 #include <sys/stat.h>
34 #include <assert.h>
35
36 #ifdef HAVE_MMAP
37 #include <sys/mman.h>
38 #else
39 /* On systems without mmap (and munmap), use a replacement function. */
40 #include "mmap.h"
41 #endif
42
43 #include "c-ctype.h"
44 #include "full-read.h"
45 #include "full-write.h"
46
47 #include "hivex.h"
48 #include "hivex-internal.h"
49 #include "byte_conversions.h"
50
51 /* These limits are in place to stop really stupid stuff and/or exploits. */
52 #define HIVEX_MAX_SUBKEYS       15000
53 #define HIVEX_MAX_VALUES        10000
54 #define HIVEX_MAX_VALUE_LEN   1000000
55 #define HIVEX_MAX_ALLOCATION  1000000
56
57 static char *windows_utf16_to_utf8 (/* const */ char *input, size_t len);
58 static size_t utf16_string_len_in_bytes_max (const char *str, size_t len);
59
60 /* NB. All fields are little endian. */
61 struct ntreg_header {
62   char magic[4];                /* "regf" */
63   uint32_t sequence1;
64   uint32_t sequence2;
65   int64_t last_modified;
66   uint32_t major_ver;           /* 1 */
67   uint32_t minor_ver;           /* 3 */
68   uint32_t unknown5;            /* 0 */
69   uint32_t unknown6;            /* 1 */
70   uint32_t offset;              /* offset of root key record - 4KB */
71   uint32_t blocks;              /* pointer AFTER last hbin in file - 4KB */
72   uint32_t unknown7;            /* 1 */
73   /* 0x30 */
74   char name[64];                /* original file name of hive */
75   char unknown_guid1[16];
76   char unknown_guid2[16];
77   /* 0x90 */
78   uint32_t unknown8;
79   char unknown_guid3[16];
80   uint32_t unknown9;
81   /* 0xa8 */
82   char unknown10[340];
83   /* 0x1fc */
84   uint32_t csum;                /* checksum: xor of dwords 0-0x1fb. */
85   /* 0x200 */
86   char unknown11[3528];
87   /* 0xfc8 */
88   char unknown_guid4[16];
89   char unknown_guid5[16];
90   char unknown_guid6[16];
91   uint32_t unknown12;
92   uint32_t unknown13;
93   /* 0x1000 */
94 } __attribute__((__packed__));
95
96 struct ntreg_hbin_page {
97   char magic[4];                /* "hbin" */
98   uint32_t offset_first;        /* offset from 1st block */
99   uint32_t page_size;           /* size of this page (multiple of 4KB) */
100   char unknown[20];
101   /* Linked list of blocks follows here. */
102 } __attribute__((__packed__));
103
104 struct ntreg_hbin_block {
105   int32_t seg_len;              /* length of this block (-ve for used block) */
106   char id[2];                   /* the block type (eg. "nk" for nk record) */
107   /* Block data follows here. */
108 } __attribute__((__packed__));
109
110 #define BLOCK_ID_EQ(h,offs,eqid) \
111   (STREQLEN (((struct ntreg_hbin_block *)((h)->addr + (offs)))->id, (eqid), 2))
112
113 static size_t
114 block_len (hive_h *h, size_t blkoff, int *used)
115 {
116   struct ntreg_hbin_block *block;
117   block = (struct ntreg_hbin_block *) (h->addr + blkoff);
118
119   int32_t len = le32toh (block->seg_len);
120   if (len < 0) {
121     if (used) *used = 1;
122     len = -len;
123   } else {
124     if (used) *used = 0;
125   }
126
127   return (size_t) len;
128 }
129
130 struct ntreg_nk_record {
131   int32_t seg_len;              /* length (always -ve because used) */
132   char id[2];                   /* "nk" */
133   uint16_t flags;
134   int64_t timestamp;
135   uint32_t unknown1;
136   uint32_t parent;              /* offset of owner/parent */
137   uint32_t nr_subkeys;          /* number of subkeys */
138   uint32_t nr_subkeys_volatile;
139   uint32_t subkey_lf;           /* lf record containing list of subkeys */
140   uint32_t subkey_lf_volatile;
141   uint32_t nr_values;           /* number of values */
142   uint32_t vallist;             /* value-list record */
143   uint32_t sk;                  /* offset of sk-record */
144   uint32_t classname;           /* offset of classname record */
145   uint16_t max_subkey_name_len; /* maximum length of a subkey name in bytes
146                                    if the subkey was reencoded as UTF-16LE */
147   uint16_t unknown2;
148   uint32_t unknown3;
149   uint32_t max_vk_name_len;     /* maximum length of any vk name in bytes
150                                    if the name was reencoded as UTF-16LE */
151   uint32_t max_vk_data_len;     /* maximum length of any vk data in bytes */
152   uint32_t unknown6;
153   uint16_t name_len;            /* length of name */
154   uint16_t classname_len;       /* length of classname */
155   char name[1];                 /* name follows here */
156 } __attribute__((__packed__));
157
158 struct ntreg_lf_record {
159   int32_t seg_len;
160   char id[2];                   /* "lf"|"lh" */
161   uint16_t nr_keys;             /* number of keys in this record */
162   struct {
163     uint32_t offset;            /* offset of nk-record for this subkey */
164     char hash[4];               /* hash of subkey name */
165   } keys[1];
166 } __attribute__((__packed__));
167
168 struct ntreg_ri_record {
169   int32_t seg_len;
170   char id[2];                   /* "ri" */
171   uint16_t nr_offsets;          /* number of pointers to lh records */
172   uint32_t offset[1];           /* list of pointers to lh records */
173 } __attribute__((__packed__));
174
175 /* This has no ID header. */
176 struct ntreg_value_list {
177   int32_t seg_len;
178   uint32_t offset[1];           /* list of pointers to vk records */
179 } __attribute__((__packed__));
180
181 struct ntreg_vk_record {
182   int32_t seg_len;              /* length (always -ve because used) */
183   char id[2];                   /* "vk" */
184   uint16_t name_len;            /* length of name */
185   /* length of the data:
186    * If data_len is <= 4, then it's stored inline.
187    * Top bit is set to indicate inline.
188    */
189   uint32_t data_len;
190   uint32_t data_offset;         /* pointer to the data (or data if inline) */
191   uint32_t data_type;           /* type of the data */
192   uint16_t flags;               /* bit 0 set => key name ASCII,
193                                    bit 0 clr => key name UTF-16.
194                                    Only seen ASCII here in the wild.
195                                    NB: this is CLEAR for default key. */
196   uint16_t unknown2;
197   char name[1];                 /* key name follows here */
198 } __attribute__((__packed__));
199
200 struct ntreg_sk_record {
201   int32_t seg_len;              /* length (always -ve because used) */
202   char id[2];                   /* "sk" */
203   uint16_t unknown1;
204   uint32_t sk_next;             /* linked into a circular list */
205   uint32_t sk_prev;
206   uint32_t refcount;            /* reference count */
207   uint32_t sec_len;             /* length of security info */
208   char sec_desc[1];             /* security info follows */
209 } __attribute__((__packed__));
210
211 static uint32_t
212 header_checksum (const hive_h *h)
213 {
214   uint32_t *daddr = (uint32_t *) h->addr;
215   size_t i;
216   uint32_t sum = 0;
217
218   for (i = 0; i < 0x1fc / 4; ++i) {
219     sum ^= le32toh (*daddr);
220     daddr++;
221   }
222
223   return sum;
224 }
225
226 #define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG)
227
228 hive_h *
229 hivex_open (const char *filename, int flags)
230 {
231   hive_h *h = NULL;
232
233   assert (sizeof (struct ntreg_header) == 0x1000);
234   assert (offsetof (struct ntreg_header, csum) == 0x1fc);
235
236   h = calloc (1, sizeof *h);
237   if (h == NULL)
238     goto error;
239
240   h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;
241
242   const char *debug = getenv ("HIVEX_DEBUG");
243   if (debug && STREQ (debug, "1"))
244     h->msglvl = 2;
245
246   if (h->msglvl >= 2)
247     fprintf (stderr, "hivex_open: created handle %p\n", h);
248
249   h->writable = !!(flags & HIVEX_OPEN_WRITE);
250   h->filename = strdup (filename);
251   if (h->filename == NULL)
252     goto error;
253
254 #ifdef O_CLOEXEC
255   h->fd = open (filename, O_RDONLY | O_CLOEXEC);
256 #else
257   h->fd = open (filename, O_RDONLY);
258 #endif
259   if (h->fd == -1)
260     goto error;
261 #ifndef O_CLOEXEC
262   fcntl (h->fd, F_SETFD, FD_CLOEXEC);
263 #endif
264
265   struct stat statbuf;
266   if (fstat (h->fd, &statbuf) == -1)
267     goto error;
268
269   h->size = statbuf.st_size;
270
271   if (!h->writable) {
272     h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);
273     if (h->addr == MAP_FAILED)
274       goto error;
275
276     if (h->msglvl >= 2)
277       fprintf (stderr, "hivex_open: mapped file at %p\n", h->addr);
278   } else {
279     h->addr = malloc (h->size);
280     if (h->addr == NULL)
281       goto error;
282
283     if (full_read (h->fd, h->addr, h->size) < h->size)
284       goto error;
285
286     /* We don't need the file descriptor along this path, since we
287      * have read all the data.
288      */
289     if (close (h->fd) == -1)
290       goto error;
291     h->fd = -1;
292   }
293
294   /* Check header. */
295   if (h->hdr->magic[0] != 'r' ||
296       h->hdr->magic[1] != 'e' ||
297       h->hdr->magic[2] != 'g' ||
298       h->hdr->magic[3] != 'f') {
299     fprintf (stderr, "hivex: %s: not a Windows NT Registry hive file\n",
300              filename);
301     errno = ENOTSUP;
302     goto error;
303   }
304
305   /* Check major version. */
306   uint32_t major_ver = le32toh (h->hdr->major_ver);
307   if (major_ver != 1) {
308     fprintf (stderr,
309              "hivex: %s: hive file major version %" PRIu32 " (expected 1)\n",
310              filename, major_ver);
311     errno = ENOTSUP;
312     goto error;
313   }
314
315   h->bitmap = calloc (1 + h->size / 32, 1);
316   if (h->bitmap == NULL)
317     goto error;
318
319   /* Header checksum. */
320   uint32_t sum = header_checksum (h);
321   if (sum != le32toh (h->hdr->csum)) {
322     fprintf (stderr, "hivex: %s: bad checksum in hive header\n", filename);
323     errno = EINVAL;
324     goto error;
325   }
326
327   /* Last modified time. */
328   h->last_modified = le64toh ((int64_t) h->hdr->last_modified);
329
330   if (h->msglvl >= 2) {
331     char *name = windows_utf16_to_utf8 (h->hdr->name, 64);
332
333     fprintf (stderr,
334              "hivex_open: header fields:\n"
335              "  file version             %" PRIu32 ".%" PRIu32 "\n"
336              "  sequence nos             %" PRIu32 " %" PRIu32 "\n"
337              "    (sequences nos should match if hive was synched at shutdown)\n"
338              "  last modified            %" PRIu64 "\n"
339              "    (Windows filetime, x 100 ns since 1601-01-01)\n"
340              "  original file name       %s\n"
341              "    (only 32 chars are stored, name is probably truncated)\n"
342              "  root offset              0x%x + 0x1000\n"
343              "  end of last page         0x%x + 0x1000 (total file size 0x%zx)\n"
344              "  checksum                 0x%x (calculated 0x%x)\n",
345              major_ver, le32toh (h->hdr->minor_ver),
346              le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),
347              h->last_modified,
348              name ? name : "(conversion failed)",
349              le32toh (h->hdr->offset),
350              le32toh (h->hdr->blocks), h->size,
351              le32toh (h->hdr->csum), sum);
352     free (name);
353   }
354
355   h->rootoffs = le32toh (h->hdr->offset) + 0x1000;
356   h->endpages = le32toh (h->hdr->blocks) + 0x1000;
357
358   if (h->msglvl >= 2)
359     fprintf (stderr, "hivex_open: root offset = 0x%zx\n", h->rootoffs);
360
361   /* We'll set this flag when we see a block with the root offset (ie.
362    * the root block).
363    */
364   int seen_root_block = 0, bad_root_block = 0;
365
366   /* Collect some stats. */
367   size_t pages = 0;           /* Number of hbin pages read. */
368   size_t smallest_page = SIZE_MAX, largest_page = 0;
369   size_t blocks = 0;          /* Total number of blocks found. */
370   size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;
371   size_t used_blocks = 0;     /* Total number of used blocks found. */
372   size_t used_size = 0;       /* Total size (bytes) of used blocks. */
373
374   /* Read the pages and blocks.  The aim here is to be robust against
375    * corrupt or malicious registries.  So we make sure the loops
376    * always make forward progress.  We add the address of each block
377    * we read to a hash table so pointers will only reference the start
378    * of valid blocks.
379    */
380   size_t off;
381   struct ntreg_hbin_page *page;
382   for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {
383     if (off >= h->endpages)
384       break;
385
386     page = (struct ntreg_hbin_page *) (h->addr + off);
387     if (page->magic[0] != 'h' ||
388         page->magic[1] != 'b' ||
389         page->magic[2] != 'i' ||
390         page->magic[3] != 'n') {
391       fprintf (stderr, "hivex: %s: trailing garbage at end of file "
392                "(at 0x%zx, after %zu pages)\n",
393                filename, off, pages);
394       errno = ENOTSUP;
395       goto error;
396     }
397
398     size_t page_size = le32toh (page->page_size);
399     if (h->msglvl >= 2)
400       fprintf (stderr, "hivex_open: page at 0x%zx, size %zu\n", off, page_size);
401     pages++;
402     if (page_size < smallest_page) smallest_page = page_size;
403     if (page_size > largest_page) largest_page = page_size;
404
405     if (page_size <= sizeof (struct ntreg_hbin_page) ||
406         (page_size & 0x0fff) != 0) {
407       fprintf (stderr, "hivex: %s: page size %zu at 0x%zx, bad registry\n",
408                filename, page_size, off);
409       errno = ENOTSUP;
410       goto error;
411     }
412
413     /* Read the blocks in this page. */
414     size_t blkoff;
415     struct ntreg_hbin_block *block;
416     size_t seg_len;
417     for (blkoff = off + 0x20;
418          blkoff < off + page_size;
419          blkoff += seg_len) {
420       blocks++;
421
422       int is_root = blkoff == h->rootoffs;
423       if (is_root)
424         seen_root_block = 1;
425
426       block = (struct ntreg_hbin_block *) (h->addr + blkoff);
427       int used;
428       seg_len = block_len (h, blkoff, &used);
429       if (seg_len <= 4 || (seg_len & 3) != 0) {
430         fprintf (stderr, "hivex: %s: block size %" PRIu32 " at 0x%zx,"
431                  " bad registry\n",
432                  filename, le32toh (block->seg_len), blkoff);
433         errno = ENOTSUP;
434         goto error;
435       }
436
437       if (h->msglvl >= 2)
438         fprintf (stderr, "hivex_open: %s block id %d,%d at 0x%zx size %zu%s\n",
439                  used ? "used" : "free", block->id[0], block->id[1], blkoff,
440                  seg_len, is_root ? " (root)" : "");
441
442       blocks_bytes += seg_len;
443       if (seg_len < smallest_block) smallest_block = seg_len;
444       if (seg_len > largest_block) largest_block = seg_len;
445
446       if (is_root && !used)
447         bad_root_block = 1;
448
449       if (used) {
450         used_blocks++;
451         used_size += seg_len;
452
453         /* Root block must be an nk-block. */
454         if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))
455           bad_root_block = 1;
456
457         /* Note this blkoff is a valid address. */
458         BITMAP_SET (h->bitmap, blkoff);
459       }
460     }
461   }
462
463   if (!seen_root_block) {
464     fprintf (stderr, "hivex: %s: no root block found\n", filename);
465     errno = ENOTSUP;
466     goto error;
467   }
468
469   if (bad_root_block) {
470     fprintf (stderr, "hivex: %s: bad root block (free or not nk)\n", filename);
471     errno = ENOTSUP;
472     goto error;
473   }
474
475   if (h->msglvl >= 1)
476     fprintf (stderr,
477              "hivex_open: successfully read Windows Registry hive file:\n"
478              "  pages:          %zu [sml: %zu, lge: %zu]\n"
479              "  blocks:         %zu [sml: %zu, avg: %zu, lge: %zu]\n"
480              "  blocks used:    %zu\n"
481              "  bytes used:     %zu\n",
482              pages, smallest_page, largest_page,
483              blocks, smallest_block, blocks_bytes / blocks, largest_block,
484              used_blocks, used_size);
485
486   return h;
487
488  error:;
489   int err = errno;
490   if (h) {
491     free (h->bitmap);
492     if (h->addr && h->size && h->addr != MAP_FAILED) {
493       if (!h->writable)
494         munmap (h->addr, h->size);
495       else
496         free (h->addr);
497     }
498     if (h->fd >= 0)
499       close (h->fd);
500     free (h->filename);
501     free (h);
502   }
503   errno = err;
504   return NULL;
505 }
506
507 int
508 hivex_close (hive_h *h)
509 {
510   int r;
511
512   if (h->msglvl >= 1)
513     fprintf (stderr, "hivex_close\n");
514
515   free (h->bitmap);
516   if (!h->writable)
517     munmap (h->addr, h->size);
518   else
519     free (h->addr);
520   if (h->fd >= 0)
521     r = close (h->fd);
522   else
523     r = 0;
524   free (h->filename);
525   free (h);
526
527   return r;
528 }
529
530 /*----------------------------------------------------------------------
531  * Reading.
532  */
533
534 hive_node_h
535 hivex_root (hive_h *h)
536 {
537   hive_node_h ret = h->rootoffs;
538   if (!IS_VALID_BLOCK (h, ret)) {
539     errno = HIVEX_NO_KEY;
540     return 0;
541   }
542   return ret;
543 }
544
545 size_t
546 hivex_node_struct_length (hive_h *h, hive_node_h node)
547 {
548   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
549     errno = EINVAL;
550     return 0;
551   }
552
553   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
554   size_t name_len = le16toh (nk->name_len);
555   /* -1 to avoid double-counting the first name character */
556   size_t ret = name_len + sizeof (struct ntreg_nk_record) - 1;
557   int used;
558   size_t seg_len = block_len (h, node, &used);
559   if (ret > seg_len) {
560     if (h->msglvl >= 2)
561       fprintf (stderr, "hivex_node_struct_length: returning EFAULT because"
562                " node name is too long (%zu, %zu)\n", name_len, seg_len);
563     errno = EFAULT;
564     return 0;
565   }
566   return ret;
567 }
568
569 char *
570 hivex_node_name (hive_h *h, hive_node_h node)
571 {
572   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
573     errno = EINVAL;
574     return NULL;
575   }
576
577   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
578
579   /* AFAIK the node name is always plain ASCII, so no conversion
580    * to UTF-8 is necessary.  However we do need to nul-terminate
581    * the string.
582    */
583
584   /* nk->name_len is unsigned, 16 bit, so this is safe ...  However
585    * we have to make sure the length doesn't exceed the block length.
586    */
587   size_t len = le16toh (nk->name_len);
588   size_t seg_len = block_len (h, node, NULL);
589   if (sizeof (struct ntreg_nk_record) + len - 1 > seg_len) {
590     if (h->msglvl >= 2)
591       fprintf (stderr, "hivex_node_name: returning EFAULT because node name"
592                " is too long (%zu, %zu)\n",
593               len, seg_len);
594     errno = EFAULT;
595     return NULL;
596   }
597
598   char *ret = malloc (len + 1);
599   if (ret == NULL)
600     return NULL;
601   memcpy (ret, nk->name, len);
602   ret[len] = '\0';
603   return ret;
604 }
605
606 static int64_t
607 timestamp_check (hive_h *h, hive_node_h node, int64_t timestamp)
608 {
609   if (timestamp < 0) {
610     if (h->msglvl >= 2)
611       fprintf (stderr, "hivex: timestamp_check: "
612                "negative time reported at %zu: %" PRIi64 "\n",
613                node, timestamp);
614     errno = EINVAL;
615     return -1;
616   }
617
618   return timestamp;
619 }
620
621 int64_t
622 hivex_last_modified (hive_h *h)
623 {
624   return timestamp_check (h, 0, h->last_modified);
625 }
626
627 int64_t
628 hivex_node_timestamp (hive_h *h, hive_node_h node)
629 {
630   int64_t ret;
631
632   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
633     errno = EINVAL;
634     return -1;
635   }
636
637   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
638
639   ret = le64toh (nk->timestamp);
640   return timestamp_check (h, node, ret);
641 }
642
643 #if 0
644 /* I think the documentation for the sk and classname fields in the nk
645  * record is wrong, or else the offset field is in the wrong place.
646  * Otherwise this makes no sense.  Disabled this for now -- it's not
647  * useful for reading the registry anyway.
648  */
649
650 hive_security_h
651 hivex_node_security (hive_h *h, hive_node_h node)
652 {
653   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
654     errno = EINVAL;
655     return 0;
656   }
657
658   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
659
660   hive_node_h ret = le32toh (nk->sk);
661   ret += 0x1000;
662   if (!IS_VALID_BLOCK (h, ret)) {
663     errno = EFAULT;
664     return 0;
665   }
666   return ret;
667 }
668
669 hive_classname_h
670 hivex_node_classname (hive_h *h, hive_node_h node)
671 {
672   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
673     errno = EINVAL;
674     return 0;
675   }
676
677   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
678
679   hive_node_h ret = le32toh (nk->classname);
680   ret += 0x1000;
681   if (!IS_VALID_BLOCK (h, ret)) {
682     errno = EFAULT;
683     return 0;
684   }
685   return ret;
686 }
687 #endif
688
689 /* Structure for returning 0-terminated lists of offsets (nodes,
690  * values, etc).
691  */
692 struct offset_list {
693   size_t *offsets;
694   size_t len;
695   size_t alloc;
696 };
697
698 static void
699 init_offset_list (struct offset_list *list)
700 {
701   list->len = 0;
702   list->alloc = 0;
703   list->offsets = NULL;
704 }
705
706 #define INIT_OFFSET_LIST(name) \
707   struct offset_list name; \
708   init_offset_list (&name)
709
710 /* Preallocates the offset_list, but doesn't make the contents longer. */
711 static int
712 grow_offset_list (struct offset_list *list, size_t alloc)
713 {
714   assert (alloc >= list->len);
715   size_t *p = realloc (list->offsets, alloc * sizeof (size_t));
716   if (p == NULL)
717     return -1;
718   list->offsets = p;
719   list->alloc = alloc;
720   return 0;
721 }
722
723 static int
724 add_to_offset_list (struct offset_list *list, size_t offset)
725 {
726   if (list->len >= list->alloc) {
727     if (grow_offset_list (list, list->alloc ? list->alloc * 2 : 4) == -1)
728       return -1;
729   }
730   list->offsets[list->len] = offset;
731   list->len++;
732   return 0;
733 }
734
735 static void
736 free_offset_list (struct offset_list *list)
737 {
738   free (list->offsets);
739 }
740
741 static size_t *
742 return_offset_list (struct offset_list *list)
743 {
744   if (add_to_offset_list (list, 0) == -1)
745     return NULL;
746   return list->offsets;         /* caller frees */
747 }
748
749 /* Iterate over children, returning child nodes and intermediate blocks. */
750 #define GET_CHILDREN_NO_CHECK_NK 1
751
752 static int
753 get_children (hive_h *h, hive_node_h node,
754               hive_node_h **children_ret, size_t **blocks_ret,
755               int flags)
756 {
757   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
758     errno = EINVAL;
759     return -1;
760   }
761
762   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
763
764   size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
765
766   INIT_OFFSET_LIST (children);
767   INIT_OFFSET_LIST (blocks);
768
769   /* Deal with the common "no subkeys" case quickly. */
770   if (nr_subkeys_in_nk == 0)
771     goto ok;
772
773   /* Arbitrarily limit the number of subkeys we will ever deal with. */
774   if (nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS) {
775     if (h->msglvl >= 2)
776       fprintf (stderr, "hivex: get_children: returning ERANGE because "
777                "nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS (%zu > %d)\n",
778                nr_subkeys_in_nk, HIVEX_MAX_SUBKEYS);
779     errno = ERANGE;
780     goto error;
781   }
782
783   /* Preallocate space for the children. */
784   if (grow_offset_list (&children, nr_subkeys_in_nk) == -1)
785     goto error;
786
787   /* The subkey_lf field can point either to an lf-record, which is
788    * the common case, or if there are lots of subkeys, to an
789    * ri-record.
790    */
791   size_t subkey_lf = le32toh (nk->subkey_lf);
792   subkey_lf += 0x1000;
793   if (!IS_VALID_BLOCK (h, subkey_lf)) {
794     if (h->msglvl >= 2)
795       fprintf (stderr, "hivex_node_children: returning EFAULT"
796                " because subkey_lf is not a valid block (0x%zx)\n",
797                subkey_lf);
798     errno = EFAULT;
799     goto error;
800   }
801
802   if (add_to_offset_list (&blocks, subkey_lf) == -1)
803     goto error;
804
805   struct ntreg_hbin_block *block =
806     (struct ntreg_hbin_block *) (h->addr + subkey_lf);
807
808   /* Points to lf-record?  (Note, also "lh" but that is basically the
809    * same as "lf" as far as we are concerned here).
810    */
811   if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
812     struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
813
814     /* Check number of subkeys in the nk-record matches number of subkeys
815      * in the lf-record.
816      */
817     size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
818
819     if (h->msglvl >= 2)
820       fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu,"
821                " nr_subkeys_in_lf = %zu\n",
822                nr_subkeys_in_nk, nr_subkeys_in_lf);
823
824     if (nr_subkeys_in_nk != nr_subkeys_in_lf) {
825       errno = ENOTSUP;
826       goto error;
827     }
828
829     size_t len = block_len (h, subkey_lf, NULL);
830     if (8 + nr_subkeys_in_lf * 8 > len) {
831       if (h->msglvl >= 2)
832         fprintf (stderr, "hivex_node_children: returning EFAULT"
833                  " because too many subkeys (%zu, %zu)\n",
834                  nr_subkeys_in_lf, len);
835       errno = EFAULT;
836       goto error;
837     }
838
839     size_t i;
840     for (i = 0; i < nr_subkeys_in_lf; ++i) {
841       hive_node_h subkey = le32toh (lf->keys[i].offset);
842       subkey += 0x1000;
843       if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
844         if (!IS_VALID_BLOCK (h, subkey)) {
845           if (h->msglvl >= 2)
846             fprintf (stderr, "hivex_node_children: returning EFAULT"
847                      " because subkey is not a valid block (0x%zx)\n",
848                      subkey);
849           errno = EFAULT;
850           goto error;
851         }
852       }
853       if (add_to_offset_list (&children, subkey) == -1)
854         goto error;
855     }
856     goto ok;
857   }
858   /* Points to ri-record? */
859   else if (block->id[0] == 'r' && block->id[1] == 'i') {
860     struct ntreg_ri_record *ri = (struct ntreg_ri_record *) block;
861
862     size_t nr_offsets = le16toh (ri->nr_offsets);
863
864     /* Count total number of children. */
865     size_t i, count = 0;
866     for (i = 0; i < nr_offsets; ++i) {
867       hive_node_h offset = le32toh (ri->offset[i]);
868       offset += 0x1000;
869       if (!IS_VALID_BLOCK (h, offset)) {
870         if (h->msglvl >= 2)
871           fprintf (stderr, "hivex_node_children: returning EFAULT"
872                    " because ri-offset is not a valid block (0x%zx)\n",
873                    offset);
874         errno = EFAULT;
875         goto error;
876       }
877       if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
878         if (h->msglvl >= 2)
879           fprintf (stderr, "get_children: returning ENOTSUP"
880                    " because ri-record offset does not point to lf/lh (0x%zx)\n",
881                    offset);
882         errno = ENOTSUP;
883         goto error;
884       }
885
886       if (add_to_offset_list (&blocks, offset) == -1)
887         goto error;
888
889       struct ntreg_lf_record *lf =
890         (struct ntreg_lf_record *) (h->addr + offset);
891
892       count += le16toh (lf->nr_keys);
893     }
894
895     if (h->msglvl >= 2)
896       fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu,"
897                " counted = %zu\n",
898                nr_subkeys_in_nk, count);
899
900     if (nr_subkeys_in_nk != count) {
901       errno = ENOTSUP;
902       goto error;
903     }
904
905     /* Copy list of children.  Note nr_subkeys_in_nk is limited to
906      * something reasonable above.
907      */
908     for (i = 0; i < nr_offsets; ++i) {
909       hive_node_h offset = le32toh (ri->offset[i]);
910       offset += 0x1000;
911       if (!IS_VALID_BLOCK (h, offset)) {
912         if (h->msglvl >= 2)
913           fprintf (stderr, "hivex_node_children: returning EFAULT"
914                    " because ri-offset is not a valid block (0x%zx)\n",
915                    offset);
916         errno = EFAULT;
917         goto error;
918       }
919       if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
920         if (h->msglvl >= 2)
921           fprintf (stderr, "get_children: returning ENOTSUP"
922                    " because ri-record offset does not point to lf/lh (0x%zx)\n",
923                    offset);
924         errno = ENOTSUP;
925         goto error;
926       }
927
928       struct ntreg_lf_record *lf =
929         (struct ntreg_lf_record *) (h->addr + offset);
930
931       size_t j;
932       for (j = 0; j < le16toh (lf->nr_keys); ++j) {
933         hive_node_h subkey = le32toh (lf->keys[j].offset);
934         subkey += 0x1000;
935         if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
936           if (!IS_VALID_BLOCK (h, subkey)) {
937             if (h->msglvl >= 2)
938               fprintf (stderr, "hivex_node_children: returning EFAULT"
939                        " because indirect subkey is not a valid block (0x%zx)\n",
940                        subkey);
941             errno = EFAULT;
942             goto error;
943           }
944         }
945         if (add_to_offset_list (&children, subkey) == -1)
946           goto error;
947       }
948     }
949     goto ok;
950   }
951   /* else not supported, set errno and fall through */
952   if (h->msglvl >= 2)
953     fprintf (stderr, "get_children: returning ENOTSUP"
954              " because subkey block is not lf/lh/ri (0x%zx, %d, %d)\n",
955              subkey_lf, block->id[0], block->id[1]);
956   errno = ENOTSUP;
957  error:
958   free_offset_list (&children);
959   free_offset_list (&blocks);
960   return -1;
961
962  ok:
963   *children_ret = return_offset_list (&children);
964   *blocks_ret = return_offset_list (&blocks);
965   if (!*children_ret || !*blocks_ret)
966     goto error;
967   return 0;
968 }
969
970 hive_node_h *
971 hivex_node_children (hive_h *h, hive_node_h node)
972 {
973   hive_node_h *children;
974   size_t *blocks;
975
976   if (get_children (h, node, &children, &blocks, 0) == -1)
977     return NULL;
978
979   free (blocks);
980   return children;
981 }
982
983 /* Very inefficient, but at least having a separate API call
984  * allows us to make it more efficient in future.
985  */
986 hive_node_h
987 hivex_node_get_child (hive_h *h, hive_node_h node, const char *nname)
988 {
989   hive_node_h *children = NULL;
990   char *name = NULL;
991   hive_node_h ret = 0;
992
993   children = hivex_node_children (h, node);
994   if (!children) goto error;
995
996   size_t i;
997   for (i = 0; children[i] != 0; ++i) {
998     name = hivex_node_name (h, children[i]);
999     if (!name) goto error;
1000     if (STRCASEEQ (name, nname)) {
1001       ret = children[i];
1002       break;
1003     }
1004     free (name); name = NULL;
1005   }
1006
1007  error:
1008   free (children);
1009   free (name);
1010   return ret;
1011 }
1012
1013 hive_node_h
1014 hivex_node_parent (hive_h *h, hive_node_h node)
1015 {
1016   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
1017     errno = EINVAL;
1018     return 0;
1019   }
1020
1021   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
1022
1023   hive_node_h ret = le32toh (nk->parent);
1024   ret += 0x1000;
1025   if (!IS_VALID_BLOCK (h, ret)) {
1026     if (h->msglvl >= 2)
1027       fprintf (stderr, "hivex_node_parent: returning EFAULT"
1028                " because parent is not a valid block (0x%zx)\n",
1029               ret);
1030     errno = EFAULT;
1031     return 0;
1032   }
1033   return ret;
1034 }
1035
1036 static int
1037 get_values (hive_h *h, hive_node_h node,
1038             hive_value_h **values_ret, size_t **blocks_ret)
1039 {
1040   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
1041     errno = EINVAL;
1042     return -1;
1043   }
1044
1045   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
1046
1047   size_t nr_values = le32toh (nk->nr_values);
1048
1049   if (h->msglvl >= 2)
1050     fprintf (stderr, "hivex_node_values: nr_values = %zu\n", nr_values);
1051
1052   INIT_OFFSET_LIST (values);
1053   INIT_OFFSET_LIST (blocks);
1054
1055   /* Deal with the common "no values" case quickly. */
1056   if (nr_values == 0)
1057     goto ok;
1058
1059   /* Arbitrarily limit the number of values we will ever deal with. */
1060   if (nr_values > HIVEX_MAX_VALUES) {
1061     if (h->msglvl >= 2)
1062       fprintf (stderr, "hivex: get_values: returning ERANGE"
1063                " because nr_values > HIVEX_MAX_VALUES (%zu > %d)\n",
1064                nr_values, HIVEX_MAX_VALUES);
1065     errno = ERANGE;
1066     goto error;
1067   }
1068
1069   /* Preallocate space for the values. */
1070   if (grow_offset_list (&values, nr_values) == -1)
1071     goto error;
1072
1073   /* Get the value list and check it looks reasonable. */
1074   size_t vlist_offset = le32toh (nk->vallist);
1075   vlist_offset += 0x1000;
1076   if (!IS_VALID_BLOCK (h, vlist_offset)) {
1077     if (h->msglvl >= 2)
1078       fprintf (stderr, "hivex_node_values: returning EFAULT"
1079                " because value list is not a valid block (0x%zx)\n",
1080                vlist_offset);
1081     errno = EFAULT;
1082     goto error;
1083   }
1084
1085   if (add_to_offset_list (&blocks, vlist_offset) == -1)
1086     goto error;
1087
1088   struct ntreg_value_list *vlist =
1089     (struct ntreg_value_list *) (h->addr + vlist_offset);
1090
1091   size_t len = block_len (h, vlist_offset, NULL);
1092   if (4 + nr_values * 4 > len) {
1093     if (h->msglvl >= 2)
1094       fprintf (stderr, "hivex_node_values: returning EFAULT"
1095                " because value list is too long (%zu, %zu)\n",
1096                nr_values, len);
1097     errno = EFAULT;
1098     goto error;
1099   }
1100
1101   size_t i;
1102   for (i = 0; i < nr_values; ++i) {
1103     hive_node_h value = le32toh (vlist->offset[i]);
1104     value += 0x1000;
1105     if (!IS_VALID_BLOCK (h, value)) {
1106       if (h->msglvl >= 2)
1107         fprintf (stderr, "hivex_node_values: returning EFAULT"
1108                  " because value is not a valid block (0x%zx)\n",
1109                  value);
1110       errno = EFAULT;
1111       goto error;
1112     }
1113     if (add_to_offset_list (&values, value) == -1)
1114       goto error;
1115   }
1116
1117  ok:
1118   *values_ret = return_offset_list (&values);
1119   *blocks_ret = return_offset_list (&blocks);
1120   if (!*values_ret || !*blocks_ret)
1121     goto error;
1122   return 0;
1123
1124  error:
1125   free_offset_list (&values);
1126   free_offset_list (&blocks);
1127   return -1;
1128 }
1129
1130 hive_value_h *
1131 hivex_node_values (hive_h *h, hive_node_h node)
1132 {
1133   hive_value_h *values;
1134   size_t *blocks;
1135
1136   if (get_values (h, node, &values, &blocks) == -1)
1137     return NULL;
1138
1139   free (blocks);
1140   return values;
1141 }
1142
1143 /* Very inefficient, but at least having a separate API call
1144  * allows us to make it more efficient in future.
1145  */
1146 hive_value_h
1147 hivex_node_get_value (hive_h *h, hive_node_h node, const char *key)
1148 {
1149   hive_value_h *values = NULL;
1150   char *name = NULL;
1151   hive_value_h ret = 0;
1152
1153   values = hivex_node_values (h, node);
1154   if (!values) goto error;
1155
1156   size_t i;
1157   for (i = 0; values[i] != 0; ++i) {
1158     name = hivex_value_key (h, values[i]);
1159     if (!name) goto error;
1160     if (STRCASEEQ (name, key)) {
1161       ret = values[i];
1162       break;
1163     }
1164     free (name); name = NULL;
1165   }
1166
1167  error:
1168   free (values);
1169   free (name);
1170   return ret;
1171 }
1172
1173 size_t
1174 hivex_value_struct_length (hive_h *h, hive_value_h value)
1175 {
1176   size_t key_len;
1177
1178   errno = 0;
1179   key_len = hivex_value_key_len (h, value);
1180   if (key_len == 0 && errno != 0)
1181     return 0;
1182
1183   /* -1 to avoid double-counting the first name character */
1184   return key_len + sizeof (struct ntreg_vk_record) - 1;
1185 }
1186
1187 size_t
1188 hivex_value_key_len (hive_h *h, hive_value_h value)
1189 {
1190   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1191     errno = EINVAL;
1192     return 0;
1193   }
1194
1195   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1196
1197   /* vk->name_len is unsigned, 16 bit, so this is safe ...  However
1198    * we have to make sure the length doesn't exceed the block length.
1199    */
1200   size_t ret = le16toh (vk->name_len);
1201   size_t seg_len = block_len (h, value, NULL);
1202   if (sizeof (struct ntreg_vk_record) + ret - 1 > seg_len) {
1203     if (h->msglvl >= 2)
1204       fprintf (stderr, "hivex_value_key_len: returning EFAULT"
1205                " because key length is too long (%zu, %zu)\n",
1206                ret, seg_len);
1207     errno = EFAULT;
1208     return 0;
1209   }
1210   return ret;
1211 }
1212
1213 char *
1214 hivex_value_key (hive_h *h, hive_value_h value)
1215 {
1216   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1217     errno = EINVAL;
1218     return 0;
1219   }
1220
1221   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1222
1223   /* AFAIK the key is always plain ASCII, so no conversion to UTF-8 is
1224    * necessary.  However we do need to nul-terminate the string.
1225    */
1226   errno = 0;
1227   size_t len = hivex_value_key_len (h, value);
1228   if (len == 0 && errno != 0)
1229     return NULL;
1230
1231   char *ret = malloc (len + 1);
1232   if (ret == NULL)
1233     return NULL;
1234   memcpy (ret, vk->name, len);
1235   ret[len] = '\0';
1236   return ret;
1237 }
1238
1239 int
1240 hivex_value_type (hive_h *h, hive_value_h value, hive_type *t, size_t *len)
1241 {
1242   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1243     errno = EINVAL;
1244     return -1;
1245   }
1246
1247   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1248
1249   if (t)
1250     *t = le32toh (vk->data_type);
1251
1252   if (len) {
1253     *len = le32toh (vk->data_len);
1254     *len &= 0x7fffffff;         /* top bit indicates if data is stored inline */
1255   }
1256
1257   return 0;
1258 }
1259
1260 hive_value_h
1261 hivex_value_data_cell_offset (hive_h *h, hive_value_h value, size_t *len)
1262 {
1263   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1264     errno = EINVAL;
1265     return 0;
1266   }
1267
1268   if (h->msglvl >= 2)
1269     fprintf (stderr, "hivex_value_data_cell_offset: value=0x%zx\n", value);
1270   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1271
1272   size_t data_len;
1273   int is_inline;
1274
1275   data_len = le32toh (vk->data_len);
1276   is_inline = !!(data_len & 0x80000000);
1277   data_len &= 0x7fffffff;
1278
1279   if (h->msglvl >= 2)
1280     fprintf (stderr, "hivex_value_data_cell_offset: is_inline=%d\n", is_inline);
1281
1282   if (h->msglvl >= 2)
1283     fprintf (stderr, "hivex_value_data_cell_offset: data_len=%zx\n", data_len);
1284
1285   if (is_inline && data_len > 4) {
1286     errno = ENOTSUP;
1287     return 0;
1288   }
1289
1290   if (is_inline) {
1291     /* There is no other location for the value data. */
1292     if (len)
1293       *len = 0;
1294     return 0;
1295   } else {
1296     if (len)
1297       *len = data_len + 4;  /* Include 4 header length bytes */
1298   }
1299
1300   if (h->msglvl >= 2)
1301     fprintf (stderr, "hivex_value_data_cell_offset: Proceeding with indirect data.\n");
1302
1303   size_t data_offset = le32toh (vk->data_offset);
1304   data_offset += 0x1000;  /* Add 0x1000 because everything's off by 4KiB */
1305   if (!IS_VALID_BLOCK (h, data_offset)) {
1306     if (h->msglvl >= 2)
1307       fprintf (stderr, "hivex_value_data_cell_offset: returning EFAULT because data "
1308                "offset is not a valid block (0x%zx)\n",
1309                data_offset);
1310     errno = EFAULT;
1311     return 0;
1312   }
1313
1314   if (h->msglvl >= 2)
1315     fprintf (stderr, "hivex_value_data_cell_offset: data_offset=%zx\n", data_offset);
1316
1317   return data_offset;
1318 }
1319
1320 char *
1321 hivex_value_value (hive_h *h, hive_value_h value,
1322                    hive_type *t_rtn, size_t *len_rtn)
1323 {
1324   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1325     errno = EINVAL;
1326     return NULL;
1327   }
1328
1329   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1330
1331   hive_type t;
1332   size_t len;
1333   int is_inline;
1334
1335   t = le32toh (vk->data_type);
1336
1337   len = le32toh (vk->data_len);
1338   is_inline = !!(len & 0x80000000);
1339   len &= 0x7fffffff;
1340
1341   if (h->msglvl >= 2)
1342     fprintf (stderr, "hivex_value_value: value=0x%zx, t=%d, len=%zu, inline=%d\n",
1343              value, t, len, is_inline);
1344
1345   if (t_rtn)
1346     *t_rtn = t;
1347   if (len_rtn)
1348     *len_rtn = len;
1349
1350   if (is_inline && len > 4) {
1351     errno = ENOTSUP;
1352     return NULL;
1353   }
1354
1355   /* Arbitrarily limit the length that we will read. */
1356   if (len > HIVEX_MAX_VALUE_LEN) {
1357     if (h->msglvl >= 2)
1358       fprintf (stderr, "hivex_value_value: returning ERANGE because data "
1359                "length > HIVEX_MAX_VALUE_LEN (%zu > %d)\n",
1360                len, HIVEX_MAX_SUBKEYS);
1361     errno = ERANGE;
1362     return NULL;
1363   }
1364
1365   char *ret = malloc (len);
1366   if (ret == NULL)
1367     return NULL;
1368
1369   if (is_inline) {
1370     memcpy (ret, (char *) &vk->data_offset, len);
1371     return ret;
1372   }
1373
1374   size_t data_offset = le32toh (vk->data_offset);
1375   data_offset += 0x1000;
1376   if (!IS_VALID_BLOCK (h, data_offset)) {
1377     if (h->msglvl >= 2)
1378       fprintf (stderr, "hivex_value_value: returning EFAULT because data "
1379                "offset is not a valid block (0x%zx)\n",
1380                data_offset);
1381     errno = EFAULT;
1382     free (ret);
1383     return NULL;
1384   }
1385
1386   /* Check that the declared size isn't larger than the block its in.
1387    *
1388    * XXX Some apparently valid registries are seen to have this,
1389    * so turn this into a warning and substitute the smaller length
1390    * instead.
1391    */
1392   size_t blen = block_len (h, data_offset, NULL);
1393   if (len > blen - 4 /* subtract 4 for block header */) {
1394     if (h->msglvl >= 2)
1395       fprintf (stderr, "hivex_value_value: warning: declared data length "
1396                "is longer than the block it is in "
1397                "(data 0x%zx, data len %zu, block len %zu)\n",
1398                data_offset, len, blen);
1399     len = blen - 4;
1400
1401     /* Return the smaller length to the caller too. */
1402     if (len_rtn)
1403       *len_rtn = len;
1404   }
1405
1406   char *data = h->addr + data_offset + 4;
1407   memcpy (ret, data, len);
1408   return ret;
1409 }
1410
1411 static char *
1412 windows_utf16_to_utf8 (/* const */ char *input, size_t len)
1413 {
1414   iconv_t ic = iconv_open ("UTF-8", "UTF-16");
1415   if (ic == (iconv_t) -1)
1416     return NULL;
1417
1418   /* iconv(3) has an insane interface ... */
1419
1420   /* Mostly UTF-8 will be smaller, so this is a good initial guess. */
1421   size_t outalloc = len;
1422
1423  again:;
1424   size_t inlen = len;
1425   size_t outlen = outalloc;
1426   char *out = malloc (outlen + 1);
1427   if (out == NULL) {
1428     int err = errno;
1429     iconv_close (ic);
1430     errno = err;
1431     return NULL;
1432   }
1433   char *inp = input;
1434   char *outp = out;
1435
1436   size_t r = iconv (ic, &inp, &inlen, &outp, &outlen);
1437   if (r == (size_t) -1) {
1438     if (errno == E2BIG) {
1439       int err = errno;
1440       size_t prev = outalloc;
1441       /* Try again with a larger output buffer. */
1442       free (out);
1443       outalloc *= 2;
1444       if (outalloc < prev) {
1445         iconv_close (ic);
1446         errno = err;
1447         return NULL;
1448       }
1449       goto again;
1450     }
1451     else {
1452       /* Else some conversion failure, eg. EILSEQ, EINVAL. */
1453       int err = errno;
1454       iconv_close (ic);
1455       free (out);
1456       errno = err;
1457       return NULL;
1458     }
1459   }
1460
1461   *outp = '\0';
1462   iconv_close (ic);
1463
1464   return out;
1465 }
1466
1467 char *
1468 hivex_value_string (hive_h *h, hive_value_h value)
1469 {
1470   hive_type t;
1471   size_t len;
1472   char *data = hivex_value_value (h, value, &t, &len);
1473
1474   if (data == NULL)
1475     return NULL;
1476
1477   if (t != hive_t_string && t != hive_t_expand_string && t != hive_t_link) {
1478     free (data);
1479     errno = EINVAL;
1480     return NULL;
1481   }
1482
1483   /* Deal with the case where Windows has allocated a large buffer
1484    * full of random junk, and only the first few bytes of the buffer
1485    * contain a genuine UTF-16 string.
1486    *
1487    * In this case, iconv would try to process the junk bytes as UTF-16
1488    * and inevitably find an illegal sequence (EILSEQ).  Instead, stop
1489    * after we find the first \0\0.
1490    *
1491    * (Found by Hilko Bengen in a fresh Windows XP SOFTWARE hive).
1492    */
1493   size_t slen = utf16_string_len_in_bytes_max (data, len);
1494   if (slen < len)
1495     len = slen;
1496
1497   char *ret = windows_utf16_to_utf8 (data, len);
1498   free (data);
1499   if (ret == NULL)
1500     return NULL;
1501
1502   return ret;
1503 }
1504
1505 static void
1506 free_strings (char **argv)
1507 {
1508   if (argv) {
1509     size_t i;
1510
1511     for (i = 0; argv[i] != NULL; ++i)
1512       free (argv[i]);
1513     free (argv);
1514   }
1515 }
1516
1517 /* Get the length of a UTF-16 format string.  Handle the string as
1518  * pairs of bytes, looking for the first \0\0 pair.  Only read up to
1519  * 'len' maximum bytes.
1520  */
1521 static size_t
1522 utf16_string_len_in_bytes_max (const char *str, size_t len)
1523 {
1524   size_t ret = 0;
1525
1526   while (len >= 2 && (str[0] || str[1])) {
1527     str += 2;
1528     ret += 2;
1529     len -= 2;
1530   }
1531
1532   return ret;
1533 }
1534
1535 /* http://blogs.msdn.com/oldnewthing/archive/2009/10/08/9904646.aspx */
1536 char **
1537 hivex_value_multiple_strings (hive_h *h, hive_value_h value)
1538 {
1539   hive_type t;
1540   size_t len;
1541   char *data = hivex_value_value (h, value, &t, &len);
1542
1543   if (data == NULL)
1544     return NULL;
1545
1546   if (t != hive_t_multiple_strings) {
1547     free (data);
1548     errno = EINVAL;
1549     return NULL;
1550   }
1551
1552   size_t nr_strings = 0;
1553   char **ret = malloc ((1 + nr_strings) * sizeof (char *));
1554   if (ret == NULL) {
1555     free (data);
1556     return NULL;
1557   }
1558   ret[0] = NULL;
1559
1560   char *p = data;
1561   size_t plen;
1562
1563   while (p < data + len &&
1564          (plen = utf16_string_len_in_bytes_max (p, data + len - p)) > 0) {
1565     nr_strings++;
1566     char **ret2 = realloc (ret, (1 + nr_strings) * sizeof (char *));
1567     if (ret2 == NULL) {
1568       free_strings (ret);
1569       free (data);
1570       return NULL;
1571     }
1572     ret = ret2;
1573
1574     ret[nr_strings-1] = windows_utf16_to_utf8 (p, plen);
1575     ret[nr_strings] = NULL;
1576     if (ret[nr_strings-1] == NULL) {
1577       free_strings (ret);
1578       free (data);
1579       return NULL;
1580     }
1581
1582     p += plen + 2 /* skip over UTF-16 \0\0 at the end of this string */;
1583   }
1584
1585   free (data);
1586   return ret;
1587 }
1588
1589 int32_t
1590 hivex_value_dword (hive_h *h, hive_value_h value)
1591 {
1592   hive_type t;
1593   size_t len;
1594   char *data = hivex_value_value (h, value, &t, &len);
1595
1596   if (data == NULL)
1597     return -1;
1598
1599   if ((t != hive_t_dword && t != hive_t_dword_be) || len != 4) {
1600     free (data);
1601     errno = EINVAL;
1602     return -1;
1603   }
1604
1605   int32_t ret = *(int32_t*)data;
1606   free (data);
1607   if (t == hive_t_dword)        /* little endian */
1608     ret = le32toh (ret);
1609   else
1610     ret = be32toh (ret);
1611
1612   return ret;
1613 }
1614
1615 int64_t
1616 hivex_value_qword (hive_h *h, hive_value_h value)
1617 {
1618   hive_type t;
1619   size_t len;
1620   char *data = hivex_value_value (h, value, &t, &len);
1621
1622   if (data == NULL)
1623     return -1;
1624
1625   if (t != hive_t_qword || len != 8) {
1626     free (data);
1627     errno = EINVAL;
1628     return -1;
1629   }
1630
1631   int64_t ret = *(int64_t*)data;
1632   free (data);
1633   ret = le64toh (ret);          /* always little endian */
1634
1635   return ret;
1636 }
1637
1638 /*----------------------------------------------------------------------
1639  * Visiting.
1640  */
1641
1642 int
1643 hivex_visit (hive_h *h, const struct hivex_visitor *visitor, size_t len,
1644              void *opaque, int flags)
1645 {
1646   return hivex_visit_node (h, hivex_root (h), visitor, len, opaque, flags);
1647 }
1648
1649 static int hivex__visit_node (hive_h *h, hive_node_h node,
1650                               const struct hivex_visitor *vtor,
1651                               char *unvisited, void *opaque, int flags);
1652
1653 int
1654 hivex_visit_node (hive_h *h, hive_node_h node,
1655                   const struct hivex_visitor *visitor, size_t len, void *opaque,
1656                   int flags)
1657 {
1658   struct hivex_visitor vtor;
1659   memset (&vtor, 0, sizeof vtor);
1660
1661   /* Note that len might be larger *or smaller* than the expected size. */
1662   size_t copysize = len <= sizeof vtor ? len : sizeof vtor;
1663   memcpy (&vtor, visitor, copysize);
1664
1665   /* This bitmap records unvisited nodes, so we don't loop if the
1666    * registry contains cycles.
1667    */
1668   char *unvisited = malloc (1 + h->size / 32);
1669   if (unvisited == NULL)
1670     return -1;
1671   memcpy (unvisited, h->bitmap, 1 + h->size / 32);
1672
1673   int r = hivex__visit_node (h, node, &vtor, unvisited, opaque, flags);
1674   free (unvisited);
1675   return r;
1676 }
1677
1678 static int
1679 hivex__visit_node (hive_h *h, hive_node_h node,
1680                    const struct hivex_visitor *vtor, char *unvisited,
1681                    void *opaque, int flags)
1682 {
1683   int skip_bad = flags & HIVEX_VISIT_SKIP_BAD;
1684   char *name = NULL;
1685   hive_value_h *values = NULL;
1686   hive_node_h *children = NULL;
1687   char *key = NULL;
1688   char *str = NULL;
1689   char **strs = NULL;
1690   int i;
1691
1692   /* Return -1 on all callback errors.  However on internal errors,
1693    * check if skip_bad is set and suppress those errors if so.
1694    */
1695   int ret = -1;
1696
1697   if (!BITMAP_TST (unvisited, node)) {
1698     if (h->msglvl >= 2)
1699       fprintf (stderr, "hivex__visit_node: contains cycle:"
1700                " visited node 0x%zx already\n",
1701                node);
1702
1703     errno = ELOOP;
1704     return skip_bad ? 0 : -1;
1705   }
1706   BITMAP_CLR (unvisited, node);
1707
1708   name = hivex_node_name (h, node);
1709   if (!name) return skip_bad ? 0 : -1;
1710   if (vtor->node_start && vtor->node_start (h, opaque, node, name) == -1)
1711     goto error;
1712
1713   values = hivex_node_values (h, node);
1714   if (!values) {
1715     ret = skip_bad ? 0 : -1;
1716     goto error;
1717   }
1718
1719   for (i = 0; values[i] != 0; ++i) {
1720     hive_type t;
1721     size_t len;
1722
1723     if (hivex_value_type (h, values[i], &t, &len) == -1) {
1724       ret = skip_bad ? 0 : -1;
1725       goto error;
1726     }
1727
1728     key = hivex_value_key (h, values[i]);
1729     if (key == NULL) {
1730       ret = skip_bad ? 0 : -1;
1731       goto error;
1732     }
1733
1734     if (vtor->value_any) {
1735       str = hivex_value_value (h, values[i], &t, &len);
1736       if (str == NULL) {
1737         ret = skip_bad ? 0 : -1;
1738         goto error;
1739       }
1740       if (vtor->value_any (h, opaque, node, values[i], t, len, key, str) == -1)
1741         goto error;
1742       free (str); str = NULL;
1743     }
1744     else {
1745       switch (t) {
1746       case hive_t_none:
1747         str = hivex_value_value (h, values[i], &t, &len);
1748         if (str == NULL) {
1749           ret = skip_bad ? 0 : -1;
1750           goto error;
1751         }
1752         if (t != hive_t_none) {
1753           ret = skip_bad ? 0 : -1;
1754           goto error;
1755         }
1756         if (vtor->value_none &&
1757             vtor->value_none (h, opaque, node, values[i], t, len, key, str) == -1)
1758           goto error;
1759         free (str); str = NULL;
1760         break;
1761
1762       case hive_t_string:
1763       case hive_t_expand_string:
1764       case hive_t_link:
1765         str = hivex_value_string (h, values[i]);
1766         if (str == NULL) {
1767           if (errno != EILSEQ && errno != EINVAL) {
1768             ret = skip_bad ? 0 : -1;
1769             goto error;
1770           }
1771           if (vtor->value_string_invalid_utf16) {
1772             str = hivex_value_value (h, values[i], &t, &len);
1773             if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i],
1774                                                   t, len, key, str) == -1)
1775               goto error;
1776             free (str); str = NULL;
1777           }
1778           break;
1779         }
1780         if (vtor->value_string &&
1781             vtor->value_string (h, opaque, node, values[i],
1782                                 t, len, key, str) == -1)
1783           goto error;
1784         free (str); str = NULL;
1785         break;
1786
1787       case hive_t_dword:
1788       case hive_t_dword_be: {
1789         int32_t i32 = hivex_value_dword (h, values[i]);
1790         if (vtor->value_dword &&
1791             vtor->value_dword (h, opaque, node, values[i],
1792                                t, len, key, i32) == -1)
1793           goto error;
1794         break;
1795       }
1796
1797       case hive_t_qword: {
1798         int64_t i64 = hivex_value_qword (h, values[i]);
1799         if (vtor->value_qword &&
1800             vtor->value_qword (h, opaque, node, values[i],
1801                                t, len, key, i64) == -1)
1802           goto error;
1803         break;
1804       }
1805
1806       case hive_t_binary:
1807         str = hivex_value_value (h, values[i], &t, &len);
1808         if (str == NULL) {
1809           ret = skip_bad ? 0 : -1;
1810           goto error;
1811         }
1812         if (t != hive_t_binary) {
1813           ret = skip_bad ? 0 : -1;
1814           goto error;
1815         }
1816         if (vtor->value_binary &&
1817             vtor->value_binary (h, opaque, node, values[i],
1818                                 t, len, key, str) == -1)
1819           goto error;
1820         free (str); str = NULL;
1821         break;
1822
1823       case hive_t_multiple_strings:
1824         strs = hivex_value_multiple_strings (h, values[i]);
1825         if (strs == NULL) {
1826           if (errno != EILSEQ && errno != EINVAL) {
1827             ret = skip_bad ? 0 : -1;
1828             goto error;
1829           }
1830           if (vtor->value_string_invalid_utf16) {
1831             str = hivex_value_value (h, values[i], &t, &len);
1832             if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i],
1833                                                   t, len, key, str) == -1)
1834               goto error;
1835             free (str); str = NULL;
1836           }
1837           break;
1838         }
1839         if (vtor->value_multiple_strings &&
1840             vtor->value_multiple_strings (h, opaque, node, values[i],
1841                                           t, len, key, strs) == -1)
1842           goto error;
1843         free_strings (strs); strs = NULL;
1844         break;
1845
1846       case hive_t_resource_list:
1847       case hive_t_full_resource_description:
1848       case hive_t_resource_requirements_list:
1849       default:
1850         str = hivex_value_value (h, values[i], &t, &len);
1851         if (str == NULL) {
1852           ret = skip_bad ? 0 : -1;
1853           goto error;
1854         }
1855         if (vtor->value_other &&
1856             vtor->value_other (h, opaque, node, values[i],
1857                                t, len, key, str) == -1)
1858           goto error;
1859         free (str); str = NULL;
1860         break;
1861       }
1862     }
1863
1864     free (key); key = NULL;
1865   }
1866
1867   children = hivex_node_children (h, node);
1868   if (children == NULL) {
1869     ret = skip_bad ? 0 : -1;
1870     goto error;
1871   }
1872
1873   for (i = 0; children[i] != 0; ++i) {
1874     if (h->msglvl >= 2)
1875       fprintf (stderr, "hivex__visit_node: %s: visiting subkey %d (0x%zx)\n",
1876                name, i, children[i]);
1877
1878     if (hivex__visit_node (h, children[i], vtor, unvisited, opaque, flags) == -1)
1879       goto error;
1880   }
1881
1882   if (vtor->node_end && vtor->node_end (h, opaque, node, name) == -1)
1883     goto error;
1884
1885   ret = 0;
1886
1887  error:
1888   free (name);
1889   free (values);
1890   free (children);
1891   free (key);
1892   free (str);
1893   free_strings (strs);
1894   return ret;
1895 }
1896
1897 /*----------------------------------------------------------------------
1898  * Writing.
1899  */
1900
1901 /* Allocate an hbin (page), extending the malloc'd space if necessary,
1902  * and updating the hive handle fields (but NOT the hive disk header
1903  * -- the hive disk header is updated when we commit).  This function
1904  * also extends the bitmap if necessary.
1905  *
1906  * 'allocation_hint' is the size of the block allocation we would like
1907  * to make.  Normally registry blocks are very small (avg 50 bytes)
1908  * and are contained in standard-sized pages (4KB), but the registry
1909  * can support blocks which are larger than a standard page, in which
1910  * case it creates a page of 8KB, 12KB etc.
1911  *
1912  * Returns:
1913  * > 0 : offset of first usable byte of new page (after page header)
1914  * 0   : error (errno set)
1915  */
1916 static size_t
1917 allocate_page (hive_h *h, size_t allocation_hint)
1918 {
1919   /* In almost all cases this will be 1. */
1920   size_t nr_4k_pages =
1921     1 + (allocation_hint + sizeof (struct ntreg_hbin_page) - 1) / 4096;
1922   assert (nr_4k_pages >= 1);
1923
1924   /* 'extend' is the number of bytes to extend the file by.  Note that
1925    * hives found in the wild often contain slack between 'endpages'
1926    * and the actual end of the file, so we don't always need to make
1927    * the file larger.
1928    */
1929   ssize_t extend = h->endpages + nr_4k_pages * 4096 - h->size;
1930
1931   if (h->msglvl >= 2) {
1932     fprintf (stderr, "allocate_page: current endpages = 0x%zx,"
1933              " current size = 0x%zx\n",
1934              h->endpages, h->size);
1935     fprintf (stderr, "allocate_page: extending file by %zd bytes"
1936              " (<= 0 if no extension)\n",
1937              extend);
1938   }
1939
1940   if (extend > 0) {
1941     size_t oldsize = h->size;
1942     size_t newsize = h->size + extend;
1943     char *newaddr = realloc (h->addr, newsize);
1944     if (newaddr == NULL)
1945       return 0;
1946
1947     size_t oldbitmapsize = 1 + oldsize / 32;
1948     size_t newbitmapsize = 1 + newsize / 32;
1949     char *newbitmap = realloc (h->bitmap, newbitmapsize);
1950     if (newbitmap == NULL) {
1951       free (newaddr);
1952       return 0;
1953     }
1954
1955     h->addr = newaddr;
1956     h->size = newsize;
1957     h->bitmap = newbitmap;
1958
1959     memset (h->addr + oldsize, 0, newsize - oldsize);
1960     memset (h->bitmap + oldbitmapsize, 0, newbitmapsize - oldbitmapsize);
1961   }
1962
1963   size_t offset = h->endpages;
1964   h->endpages += nr_4k_pages * 4096;
1965
1966   if (h->msglvl >= 2)
1967     fprintf (stderr, "allocate_page: new endpages = 0x%zx, new size = 0x%zx\n",
1968              h->endpages, h->size);
1969
1970   /* Write the hbin header. */
1971   struct ntreg_hbin_page *page =
1972     (struct ntreg_hbin_page *) (h->addr + offset);
1973   page->magic[0] = 'h';
1974   page->magic[1] = 'b';
1975   page->magic[2] = 'i';
1976   page->magic[3] = 'n';
1977   page->offset_first = htole32 (offset - 0x1000);
1978   page->page_size = htole32 (nr_4k_pages * 4096);
1979   memset (page->unknown, 0, sizeof (page->unknown));
1980
1981   if (h->msglvl >= 2)
1982     fprintf (stderr, "allocate_page: new page at 0x%zx\n", offset);
1983
1984   /* Offset of first usable byte after the header. */
1985   return offset + sizeof (struct ntreg_hbin_page);
1986 }
1987
1988 /* Allocate a single block, first allocating an hbin (page) at the end
1989  * of the current file if necessary.  NB. To keep the implementation
1990  * simple and more likely to be correct, we do not reuse existing free
1991  * blocks.
1992  *
1993  * seg_len is the size of the block (this INCLUDES the block header).
1994  * The header of the block is initialized to -seg_len (negative to
1995  * indicate used).  id[2] is the block ID (type), eg. "nk" for nk-
1996  * record.  The block bitmap is updated to show this block as valid.
1997  * The rest of the contents of the block will be zero.
1998  *
1999  * **NB** Because allocate_block may reallocate the memory, all
2000  * pointers into the memory become potentially invalid.  I really
2001  * love writing in C, can't you tell?
2002  *
2003  * Returns:
2004  * > 0 : offset of new block
2005  * 0   : error (errno set)
2006  */
2007 static size_t
2008 allocate_block (hive_h *h, size_t seg_len, const char id[2])
2009 {
2010   if (!h->writable) {
2011     errno = EROFS;
2012     return 0;
2013   }
2014
2015   if (seg_len < 4) {
2016     /* The caller probably forgot to include the header.  Note that
2017      * value lists have no ID field, so seg_len == 4 would be possible
2018      * for them, albeit unusual.
2019      */
2020     if (h->msglvl >= 2)
2021       fprintf (stderr, "allocate_block: refusing too small allocation (%zu),"
2022                " returning ERANGE\n", seg_len);
2023     errno = ERANGE;
2024     return 0;
2025   }
2026
2027   /* Refuse really large allocations. */
2028   if (seg_len > HIVEX_MAX_ALLOCATION) {
2029     if (h->msglvl >= 2)
2030       fprintf (stderr, "allocate_block: refusing large allocation (%zu),"
2031                " returning ERANGE\n", seg_len);
2032     errno = ERANGE;
2033     return 0;
2034   }
2035
2036   /* Round up allocation to multiple of 8 bytes.  All blocks must be
2037    * on an 8 byte boundary.
2038    */
2039   seg_len = (seg_len + 7) & ~7;
2040
2041   /* Allocate a new page if necessary. */
2042   if (h->endblocks == 0 || h->endblocks + seg_len > h->endpages) {
2043     size_t newendblocks = allocate_page (h, seg_len);
2044     if (newendblocks == 0)
2045       return 0;
2046     h->endblocks = newendblocks;
2047   }
2048
2049   size_t offset = h->endblocks;
2050
2051   if (h->msglvl >= 2)
2052     fprintf (stderr, "allocate_block: new block at 0x%zx, size %zu\n",
2053              offset, seg_len);
2054
2055   struct ntreg_hbin_block *blockhdr =
2056     (struct ntreg_hbin_block *) (h->addr + offset);
2057
2058   memset (blockhdr, 0, seg_len);
2059
2060   blockhdr->seg_len = htole32 (- (int32_t) seg_len);
2061   if (id[0] && id[1] && seg_len >= sizeof (struct ntreg_hbin_block)) {
2062     blockhdr->id[0] = id[0];
2063     blockhdr->id[1] = id[1];
2064   }
2065
2066   BITMAP_SET (h->bitmap, offset);
2067
2068   h->endblocks += seg_len;
2069
2070   /* If there is space after the last block in the last page, then we
2071    * have to put a dummy free block header here to mark the rest of
2072    * the page as free.
2073    */
2074   ssize_t rem = h->endpages - h->endblocks;
2075   if (rem > 0) {
2076     if (h->msglvl >= 2)
2077       fprintf (stderr, "allocate_block: marking remainder of page free"
2078                " starting at 0x%zx, size %zd\n", h->endblocks, rem);
2079
2080     assert (rem >= 4);
2081
2082     blockhdr = (struct ntreg_hbin_block *) (h->addr + h->endblocks);
2083     blockhdr->seg_len = htole32 ((int32_t) rem);
2084   }
2085
2086   return offset;
2087 }
2088
2089 /* 'offset' must point to a valid, used block.  This function marks
2090  * the block unused (by updating the seg_len field) and invalidates
2091  * the bitmap.  It does NOT do this recursively, so to avoid creating
2092  * unreachable used blocks, callers may have to recurse over the hive
2093  * structures.  Also callers must ensure there are no references to
2094  * this block from other parts of the hive.
2095  */
2096 static void
2097 mark_block_unused (hive_h *h, size_t offset)
2098 {
2099   assert (h->writable);
2100   assert (IS_VALID_BLOCK (h, offset));
2101
2102   if (h->msglvl >= 2)
2103     fprintf (stderr, "mark_block_unused: marking 0x%zx unused\n", offset);
2104
2105   struct ntreg_hbin_block *blockhdr =
2106     (struct ntreg_hbin_block *) (h->addr + offset);
2107
2108   size_t seg_len = block_len (h, offset, NULL);
2109   blockhdr->seg_len = htole32 (seg_len);
2110
2111   BITMAP_CLR (h->bitmap, offset);
2112 }
2113
2114 /* Delete all existing values at this node. */
2115 static int
2116 delete_values (hive_h *h, hive_node_h node)
2117 {
2118   assert (h->writable);
2119
2120   hive_value_h *values;
2121   size_t *blocks;
2122   if (get_values (h, node, &values, &blocks) == -1)
2123     return -1;
2124
2125   size_t i;
2126   for (i = 0; blocks[i] != 0; ++i)
2127     mark_block_unused (h, blocks[i]);
2128
2129   free (blocks);
2130
2131   for (i = 0; values[i] != 0; ++i) {
2132     struct ntreg_vk_record *vk =
2133       (struct ntreg_vk_record *) (h->addr + values[i]);
2134
2135     size_t len;
2136     int is_inline;
2137     len = le32toh (vk->data_len);
2138     is_inline = !!(len & 0x80000000); /* top bit indicates is inline */
2139     len &= 0x7fffffff;
2140
2141     if (!is_inline) {           /* non-inline, so remove data block */
2142       size_t data_offset = le32toh (vk->data_offset);
2143       data_offset += 0x1000;
2144       mark_block_unused (h, data_offset);
2145     }
2146
2147     /* remove vk record */
2148     mark_block_unused (h, values[i]);
2149   }
2150
2151   free (values);
2152
2153   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2154   nk->nr_values = htole32 (0);
2155   nk->vallist = htole32 (0xffffffff);
2156
2157   return 0;
2158 }
2159
2160 int
2161 hivex_commit (hive_h *h, const char *filename, int flags)
2162 {
2163   if (flags != 0) {
2164     errno = EINVAL;
2165     return -1;
2166   }
2167
2168   if (!h->writable) {
2169     errno = EROFS;
2170     return -1;
2171   }
2172
2173   filename = filename ? : h->filename;
2174   int fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2175   if (fd == -1)
2176     return -1;
2177
2178   /* Update the header fields. */
2179   uint32_t sequence = le32toh (h->hdr->sequence1);
2180   sequence++;
2181   h->hdr->sequence1 = htole32 (sequence);
2182   h->hdr->sequence2 = htole32 (sequence);
2183   /* XXX Ought to update h->hdr->last_modified. */
2184   h->hdr->blocks = htole32 (h->endpages - 0x1000);
2185
2186   /* Recompute header checksum. */
2187   uint32_t sum = header_checksum (h);
2188   h->hdr->csum = htole32 (sum);
2189
2190   if (h->msglvl >= 2)
2191     fprintf (stderr, "hivex_commit: new header checksum: 0x%x\n", sum);
2192
2193   if (full_write (fd, h->addr, h->size) != h->size) {
2194     int err = errno;
2195     close (fd);
2196     errno = err;
2197     return -1;
2198   }
2199
2200   if (close (fd) == -1)
2201     return -1;
2202
2203   return 0;
2204 }
2205
2206 /* Calculate the hash for a lf or lh record offset.
2207  */
2208 static void
2209 calc_hash (const char *type, const char *name, char *ret)
2210 {
2211   size_t len = strlen (name);
2212
2213   if (STRPREFIX (type, "lf"))
2214     /* Old-style, not used in current registries. */
2215     memcpy (ret, name, len < 4 ? len : 4);
2216   else {
2217     /* New-style for lh-records. */
2218     size_t i, c;
2219     uint32_t h = 0;
2220     for (i = 0; i < len; ++i) {
2221       c = c_toupper (name[i]);
2222       h *= 37;
2223       h += c;
2224     }
2225     *((uint32_t *) ret) = htole32 (h);
2226   }
2227 }
2228
2229 /* Create a completely new lh-record containing just the single node. */
2230 static size_t
2231 new_lh_record (hive_h *h, const char *name, hive_node_h node)
2232 {
2233   static const char id[2] = { 'l', 'h' };
2234   size_t seg_len = sizeof (struct ntreg_lf_record);
2235   size_t offset = allocate_block (h, seg_len, id);
2236   if (offset == 0)
2237     return 0;
2238
2239   struct ntreg_lf_record *lh = (struct ntreg_lf_record *) (h->addr + offset);
2240   lh->nr_keys = htole16 (1);
2241   lh->keys[0].offset = htole32 (node - 0x1000);
2242   calc_hash ("lh", name, lh->keys[0].hash);
2243
2244   return offset;
2245 }
2246
2247 /* Insert node into existing lf/lh-record at position.
2248  * This allocates a new record and marks the old one as unused.
2249  */
2250 static size_t
2251 insert_lf_record (hive_h *h, size_t old_offs, size_t posn,
2252                   const char *name, hive_node_h node)
2253 {
2254   assert (IS_VALID_BLOCK (h, old_offs));
2255
2256   /* Work around C stupidity.
2257    * http://www.redhat.com/archives/libguestfs/2010-February/msg00056.html
2258    */
2259   int test = BLOCK_ID_EQ (h, old_offs, "lf") || BLOCK_ID_EQ (h, old_offs, "lh");
2260   assert (test);
2261
2262   struct ntreg_lf_record *old_lf =
2263     (struct ntreg_lf_record *) (h->addr + old_offs);
2264   size_t nr_keys = le16toh (old_lf->nr_keys);
2265
2266   nr_keys++; /* in new record ... */
2267
2268   size_t seg_len = sizeof (struct ntreg_lf_record) + (nr_keys-1) * 8;
2269
2270   /* Copy the old_lf->id in case it moves during allocate_block. */
2271   char id[2];
2272   memcpy (id, old_lf->id, sizeof id);
2273
2274   size_t new_offs = allocate_block (h, seg_len, id);
2275   if (new_offs == 0)
2276     return 0;
2277
2278   /* old_lf could have been invalidated by allocate_block. */
2279   old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2280
2281   struct ntreg_lf_record *new_lf =
2282     (struct ntreg_lf_record *) (h->addr + new_offs);
2283   new_lf->nr_keys = htole16 (nr_keys);
2284
2285   /* Copy the keys until we reach posn, insert the new key there, then
2286    * copy the remaining keys.
2287    */
2288   size_t i;
2289   for (i = 0; i < posn; ++i)
2290     new_lf->keys[i] = old_lf->keys[i];
2291
2292   new_lf->keys[i].offset = htole32 (node - 0x1000);
2293   calc_hash (new_lf->id, name, new_lf->keys[i].hash);
2294
2295   for (i = posn+1; i < nr_keys; ++i)
2296     new_lf->keys[i] = old_lf->keys[i-1];
2297
2298   /* Old block is unused, return new block. */
2299   mark_block_unused (h, old_offs);
2300   return new_offs;
2301 }
2302
2303 /* Compare name with name in nk-record. */
2304 static int
2305 compare_name_with_nk_name (hive_h *h, const char *name, hive_node_h nk_offs)
2306 {
2307   assert (IS_VALID_BLOCK (h, nk_offs));
2308   assert (BLOCK_ID_EQ (h, nk_offs, "nk"));
2309
2310   /* Name in nk is not necessarily nul-terminated. */
2311   char *nname = hivex_node_name (h, nk_offs);
2312
2313   /* Unfortunately we don't have a way to return errors here. */
2314   if (!nname) {
2315     perror ("compare_name_with_nk_name");
2316     return 0;
2317   }
2318
2319   int r = strcasecmp (name, nname);
2320   free (nname);
2321
2322   return r;
2323 }
2324
2325 hive_node_h
2326 hivex_node_add_child (hive_h *h, hive_node_h parent, const char *name)
2327 {
2328   if (!h->writable) {
2329     errno = EROFS;
2330     return 0;
2331   }
2332
2333   if (!IS_VALID_BLOCK (h, parent) || !BLOCK_ID_EQ (h, parent, "nk")) {
2334     errno = EINVAL;
2335     return 0;
2336   }
2337
2338   if (name == NULL || strlen (name) == 0) {
2339     errno = EINVAL;
2340     return 0;
2341   }
2342
2343   if (hivex_node_get_child (h, parent, name) != 0) {
2344     errno = EEXIST;
2345     return 0;
2346   }
2347
2348   /* Create the new nk-record. */
2349   static const char nk_id[2] = { 'n', 'k' };
2350   size_t seg_len = sizeof (struct ntreg_nk_record) + strlen (name);
2351   hive_node_h node = allocate_block (h, seg_len, nk_id);
2352   if (node == 0)
2353     return 0;
2354
2355   if (h->msglvl >= 2)
2356     fprintf (stderr, "hivex_node_add_child: allocated new nk-record"
2357              " for child at 0x%zx\n", node);
2358
2359   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2360   nk->flags = htole16 (0x0020); /* key is ASCII. */
2361   nk->parent = htole32 (parent - 0x1000);
2362   nk->subkey_lf = htole32 (0xffffffff);
2363   nk->subkey_lf_volatile = htole32 (0xffffffff);
2364   nk->vallist = htole32 (0xffffffff);
2365   nk->classname = htole32 (0xffffffff);
2366   nk->name_len = htole16 (strlen (name));
2367   strcpy (nk->name, name);
2368
2369   /* Inherit parent sk. */
2370   struct ntreg_nk_record *parent_nk =
2371     (struct ntreg_nk_record *) (h->addr + parent);
2372   size_t parent_sk_offset = le32toh (parent_nk->sk);
2373   parent_sk_offset += 0x1000;
2374   if (!IS_VALID_BLOCK (h, parent_sk_offset) ||
2375       !BLOCK_ID_EQ (h, parent_sk_offset, "sk")) {
2376     if (h->msglvl >= 2)
2377       fprintf (stderr, "hivex_node_add_child: returning EFAULT"
2378                " because parent sk is not a valid block (%zu)\n",
2379                parent_sk_offset);
2380     errno = EFAULT;
2381     return 0;
2382   }
2383   struct ntreg_sk_record *sk =
2384     (struct ntreg_sk_record *) (h->addr + parent_sk_offset);
2385   sk->refcount = htole32 (le32toh (sk->refcount) + 1);
2386   nk->sk = htole32 (parent_sk_offset - 0x1000);
2387
2388   /* Inherit parent timestamp. */
2389   nk->timestamp = parent_nk->timestamp;
2390
2391   /* What I found out the hard way (not documented anywhere): the
2392    * subkeys in lh-records must be kept sorted.  If you just add a
2393    * subkey in a non-sorted position (eg. just add it at the end) then
2394    * Windows won't see the subkey _and_ Windows will corrupt the hive
2395    * itself when it modifies or saves it.
2396    *
2397    * So use get_children() to get a list of intermediate
2398    * lf/lh-records.  get_children() returns these in reading order
2399    * (which is sorted), so we look for the lf/lh-records in sequence
2400    * until we find the key name just after the one we are inserting,
2401    * and we insert the subkey just before it.
2402    *
2403    * The only other case is the no-subkeys case, where we have to
2404    * create a brand new lh-record.
2405    */
2406   hive_node_h *unused;
2407   size_t *blocks;
2408
2409   if (get_children (h, parent, &unused, &blocks, 0) == -1)
2410     return 0;
2411   free (unused);
2412
2413   size_t i, j;
2414   size_t nr_subkeys_in_parent_nk = le32toh (parent_nk->nr_subkeys);
2415   if (nr_subkeys_in_parent_nk == 0) { /* No subkeys case. */
2416     /* Free up any existing intermediate blocks. */
2417     for (i = 0; blocks[i] != 0; ++i)
2418       mark_block_unused (h, blocks[i]);
2419     size_t lh_offs = new_lh_record (h, name, node);
2420     if (lh_offs == 0) {
2421       free (blocks);
2422       return 0;
2423     }
2424
2425     /* Recalculate pointers that could have been invalidated by
2426      * previous call to allocate_block (via new_lh_record).
2427      */
2428     nk = (struct ntreg_nk_record *) (h->addr + node);
2429     parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2430
2431     if (h->msglvl >= 2)
2432       fprintf (stderr, "hivex_node_add_child: no keys, allocated new"
2433                " lh-record at 0x%zx\n", lh_offs);
2434
2435     parent_nk->subkey_lf = htole32 (lh_offs - 0x1000);
2436   }
2437   else {                        /* Insert subkeys case. */
2438     size_t old_offs = 0, new_offs = 0;
2439     struct ntreg_lf_record *old_lf = NULL;
2440
2441     /* Find lf/lh key name just after the one we are inserting. */
2442     for (i = 0; blocks[i] != 0; ++i) {
2443       if (BLOCK_ID_EQ (h, blocks[i], "lf") ||
2444           BLOCK_ID_EQ (h, blocks[i], "lh")) {
2445         old_offs = blocks[i];
2446         old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2447         for (j = 0; j < le16toh (old_lf->nr_keys); ++j) {
2448           hive_node_h nk_offs = le32toh (old_lf->keys[j].offset);
2449           nk_offs += 0x1000;
2450           if (compare_name_with_nk_name (h, name, nk_offs) < 0)
2451             goto insert_it;
2452         }
2453       }
2454     }
2455
2456     /* Insert it at the end.
2457      * old_offs points to the last lf record, set j.
2458      */
2459     assert (old_offs != 0);   /* should never happen if nr_subkeys > 0 */
2460     j = le16toh (old_lf->nr_keys);
2461
2462     /* Insert it. */
2463   insert_it:
2464     if (h->msglvl >= 2)
2465       fprintf (stderr, "hivex_node_add_child: insert key in existing"
2466                " lh-record at 0x%zx, posn %zu\n", old_offs, j);
2467
2468     new_offs = insert_lf_record (h, old_offs, j, name, node);
2469     if (new_offs == 0) {
2470       free (blocks);
2471       return 0;
2472     }
2473
2474     /* Recalculate pointers that could have been invalidated by
2475      * previous call to allocate_block (via insert_lf_record).
2476      */
2477     nk = (struct ntreg_nk_record *) (h->addr + node);
2478     parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2479
2480     if (h->msglvl >= 2)
2481       fprintf (stderr, "hivex_node_add_child: new lh-record at 0x%zx\n",
2482                new_offs);
2483
2484     /* If the lf/lh-record was directly referenced by the parent nk,
2485      * then update the parent nk.
2486      */
2487     if (le32toh (parent_nk->subkey_lf) + 0x1000 == old_offs)
2488       parent_nk->subkey_lf = htole32 (new_offs - 0x1000);
2489     /* Else we have to look for the intermediate ri-record and update
2490      * that in-place.
2491      */
2492     else {
2493       for (i = 0; blocks[i] != 0; ++i) {
2494         if (BLOCK_ID_EQ (h, blocks[i], "ri")) {
2495           struct ntreg_ri_record *ri =
2496             (struct ntreg_ri_record *) (h->addr + blocks[i]);
2497           for (j = 0; j < le16toh (ri->nr_offsets); ++j)
2498             if (le32toh (ri->offset[j] + 0x1000) == old_offs) {
2499               ri->offset[j] = htole32 (new_offs - 0x1000);
2500               goto found_it;
2501             }
2502         }
2503       }
2504
2505       /* Not found ..  This is an internal error. */
2506       if (h->msglvl >= 2)
2507         fprintf (stderr, "hivex_node_add_child: returning ENOTSUP"
2508                  " because could not find ri->lf link\n");
2509       errno = ENOTSUP;
2510       free (blocks);
2511       return 0;
2512
2513     found_it:
2514       ;
2515     }
2516   }
2517
2518   free (blocks);
2519
2520   /* Update nr_subkeys in parent nk. */
2521   nr_subkeys_in_parent_nk++;
2522   parent_nk->nr_subkeys = htole32 (nr_subkeys_in_parent_nk);
2523
2524   /* Update max_subkey_name_len in parent nk. */
2525   uint16_t max = le16toh (parent_nk->max_subkey_name_len);
2526   if (max < strlen (name) * 2)  /* *2 because "recoded" in UTF16-LE. */
2527     parent_nk->max_subkey_name_len = htole16 (strlen (name) * 2);
2528
2529   return node;
2530 }
2531
2532 /* Decrement the refcount of an sk-record, and if it reaches zero,
2533  * unlink it from the chain and delete it.
2534  */
2535 static int
2536 delete_sk (hive_h *h, size_t sk_offset)
2537 {
2538   if (!IS_VALID_BLOCK (h, sk_offset) || !BLOCK_ID_EQ (h, sk_offset, "sk")) {
2539     if (h->msglvl >= 2)
2540       fprintf (stderr, "delete_sk: not an sk record: 0x%zx\n", sk_offset);
2541     errno = EFAULT;
2542     return -1;
2543   }
2544
2545   struct ntreg_sk_record *sk = (struct ntreg_sk_record *) (h->addr + sk_offset);
2546
2547   if (sk->refcount == 0) {
2548     if (h->msglvl >= 2)
2549       fprintf (stderr, "delete_sk: sk record already has refcount 0: 0x%zx\n",
2550                sk_offset);
2551     errno = EINVAL;
2552     return -1;
2553   }
2554
2555   sk->refcount--;
2556
2557   if (sk->refcount == 0) {
2558     size_t sk_prev_offset = sk->sk_prev;
2559     sk_prev_offset += 0x1000;
2560
2561     size_t sk_next_offset = sk->sk_next;
2562     sk_next_offset += 0x1000;
2563
2564     /* Update sk_prev/sk_next SKs, unless they both point back to this
2565      * cell in which case we are deleting the last SK.
2566      */
2567     if (sk_prev_offset != sk_offset && sk_next_offset != sk_offset) {
2568       struct ntreg_sk_record *sk_prev =
2569         (struct ntreg_sk_record *) (h->addr + sk_prev_offset);
2570       struct ntreg_sk_record *sk_next =
2571         (struct ntreg_sk_record *) (h->addr + sk_next_offset);
2572
2573       sk_prev->sk_next = htole32 (sk_next_offset - 0x1000);
2574       sk_next->sk_prev = htole32 (sk_prev_offset - 0x1000);
2575     }
2576
2577     /* Refcount is zero so really delete this block. */
2578     mark_block_unused (h, sk_offset);
2579   }
2580
2581   return 0;
2582 }
2583
2584 /* Callback from hivex_node_delete_child which is called to delete a
2585  * node AFTER its subnodes have been visited.  The subnodes have been
2586  * deleted but we still have to delete any lf/lh/li/ri records and the
2587  * value list block and values, followed by deleting the node itself.
2588  */
2589 static int
2590 delete_node (hive_h *h, void *opaque, hive_node_h node, const char *name)
2591 {
2592   /* Get the intermediate blocks.  The subkeys have already been
2593    * deleted by this point, so tell get_children() not to check for
2594    * validity of the nk-records.
2595    */
2596   hive_node_h *unused;
2597   size_t *blocks;
2598   if (get_children (h, node, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK) == -1)
2599     return -1;
2600   free (unused);
2601
2602   /* We don't care what's in these intermediate blocks, so we can just
2603    * delete them unconditionally.
2604    */
2605   size_t i;
2606   for (i = 0; blocks[i] != 0; ++i)
2607     mark_block_unused (h, blocks[i]);
2608
2609   free (blocks);
2610
2611   /* Delete the values in the node. */
2612   if (delete_values (h, node) == -1)
2613     return -1;
2614
2615   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2616
2617   /* If the NK references an SK, delete it. */
2618   size_t sk_offs = le32toh (nk->sk);
2619   if (sk_offs != 0xffffffff) {
2620     sk_offs += 0x1000;
2621     if (delete_sk (h, sk_offs) == -1)
2622       return -1;
2623     nk->sk = htole32 (0xffffffff);
2624   }
2625
2626   /* If the NK references a classname, delete it. */
2627   size_t cl_offs = le32toh (nk->classname);
2628   if (cl_offs != 0xffffffff) {
2629     cl_offs += 0x1000;
2630     mark_block_unused (h, cl_offs);
2631     nk->classname = htole32 (0xffffffff);
2632   }
2633
2634   /* Delete the node itself. */
2635   mark_block_unused (h, node);
2636
2637   return 0;
2638 }
2639
2640 int
2641 hivex_node_delete_child (hive_h *h, hive_node_h node)
2642 {
2643   if (!h->writable) {
2644     errno = EROFS;
2645     return -1;
2646   }
2647
2648   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2649     errno = EINVAL;
2650     return -1;
2651   }
2652
2653   if (node == hivex_root (h)) {
2654     if (h->msglvl >= 2)
2655       fprintf (stderr, "hivex_node_delete_child: cannot delete root node\n");
2656     errno = EINVAL;
2657     return -1;
2658   }
2659
2660   hive_node_h parent = hivex_node_parent (h, node);
2661   if (parent == 0)
2662     return -1;
2663
2664   /* Delete node and all its children and values recursively. */
2665   static const struct hivex_visitor visitor = { .node_end = delete_node };
2666   if (hivex_visit_node (h, node, &visitor, sizeof visitor, NULL, 0) == -1)
2667     return -1;
2668
2669   /* Delete the link from parent to child.  We need to find the lf/lh
2670    * record which contains the offset and remove the offset from that
2671    * record, then decrement the element count in that record, and
2672    * decrement the overall number of subkeys stored in the parent
2673    * node.
2674    */
2675   hive_node_h *unused;
2676   size_t *blocks;
2677   if (get_children (h, parent, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK)== -1)
2678     return -1;
2679   free (unused);
2680
2681   size_t i, j;
2682   for (i = 0; blocks[i] != 0; ++i) {
2683     struct ntreg_hbin_block *block =
2684       (struct ntreg_hbin_block *) (h->addr + blocks[i]);
2685
2686     if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
2687       struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
2688
2689       size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
2690
2691       for (j = 0; j < nr_subkeys_in_lf; ++j)
2692         if (le32toh (lf->keys[j].offset) + 0x1000 == node) {
2693           for (; j < nr_subkeys_in_lf - 1; ++j)
2694             memcpy (&lf->keys[j], &lf->keys[j+1], sizeof (lf->keys[j]));
2695           lf->nr_keys = htole16 (nr_subkeys_in_lf - 1);
2696           goto found;
2697         }
2698     }
2699   }
2700   if (h->msglvl >= 2)
2701     fprintf (stderr, "hivex_node_delete_child: could not find parent"
2702              " to child link\n");
2703   errno = ENOTSUP;
2704   return -1;
2705
2706  found:;
2707   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + parent);
2708   size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
2709   nk->nr_subkeys = htole32 (nr_subkeys_in_nk - 1);
2710
2711   if (h->msglvl >= 2)
2712     fprintf (stderr, "hivex_node_delete_child: updating nr_subkeys"
2713              " in parent 0x%zx to %zu\n", parent, nr_subkeys_in_nk);
2714
2715   return 0;
2716 }
2717
2718 int
2719 hivex_node_set_values (hive_h *h, hive_node_h node,
2720                        size_t nr_values, const hive_set_value *values,
2721                        int flags)
2722 {
2723   if (!h->writable) {
2724     errno = EROFS;
2725     return -1;
2726   }
2727
2728   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2729     errno = EINVAL;
2730     return -1;
2731   }
2732
2733   /* Delete all existing values. */
2734   if (delete_values (h, node) == -1)
2735     return -1;
2736
2737   if (nr_values == 0)
2738     return 0;
2739
2740   /* Allocate value list node.  Value lists have no id field. */
2741   static const char nul_id[2] = { 0, 0 };
2742   size_t seg_len =
2743     sizeof (struct ntreg_value_list) + (nr_values - 1) * sizeof (uint32_t);
2744   size_t vallist_offs = allocate_block (h, seg_len, nul_id);
2745   if (vallist_offs == 0)
2746     return -1;
2747
2748   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2749   nk->nr_values = htole32 (nr_values);
2750   nk->vallist = htole32 (vallist_offs - 0x1000);
2751
2752   struct ntreg_value_list *vallist =
2753     (struct ntreg_value_list *) (h->addr + vallist_offs);
2754
2755   size_t i;
2756   for (i = 0; i < nr_values; ++i) {
2757     /* Allocate vk record to store this (key, value) pair. */
2758     static const char vk_id[2] = { 'v', 'k' };
2759     seg_len = sizeof (struct ntreg_vk_record) + strlen (values[i].key);
2760     size_t vk_offs = allocate_block (h, seg_len, vk_id);
2761     if (vk_offs == 0)
2762       return -1;
2763
2764     /* Recalculate pointers that could have been invalidated by
2765      * previous call to allocate_block.
2766      */
2767     nk = (struct ntreg_nk_record *) (h->addr + node);
2768     vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2769
2770     vallist->offset[i] = htole32 (vk_offs - 0x1000);
2771
2772     struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2773     size_t name_len = strlen (values[i].key);
2774     vk->name_len = htole16 (name_len);
2775     strcpy (vk->name, values[i].key);
2776     vk->data_type = htole32 (values[i].t);
2777     uint32_t len = values[i].len;
2778     if (len <= 4)               /* store it inline => set MSB flag */
2779       len |= 0x80000000;
2780     vk->data_len = htole32 (len);
2781     vk->flags = name_len == 0 ? 0 : 1;
2782
2783     if (values[i].len <= 4)     /* store it inline */
2784       memcpy (&vk->data_offset, values[i].value, values[i].len);
2785     else {
2786       size_t offs = allocate_block (h, values[i].len + 4, nul_id);
2787       if (offs == 0)
2788         return -1;
2789
2790       /* Recalculate pointers that could have been invalidated by
2791        * previous call to allocate_block.
2792        */
2793       nk = (struct ntreg_nk_record *) (h->addr + node);
2794       vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2795       vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2796
2797       memcpy (h->addr + offs + 4, values[i].value, values[i].len);
2798       vk->data_offset = htole32 (offs - 0x1000);
2799     }
2800
2801     if (name_len * 2 > le32toh (nk->max_vk_name_len))
2802       /* * 2 for UTF16-LE "reencoding" */
2803       nk->max_vk_name_len = htole32 (name_len * 2);
2804     if (values[i].len > le32toh (nk->max_vk_data_len))
2805       nk->max_vk_data_len = htole32 (values[i].len);
2806   }
2807
2808   return 0;
2809 }
2810
2811 int
2812 hivex_node_set_value (hive_h *h, hive_node_h node,
2813                       const hive_set_value *val, int flags)
2814 {
2815   hive_value_h *prev_values = hivex_node_values (h, node);
2816   if (prev_values == NULL)
2817     return -1;
2818
2819   int retval = -1;
2820
2821   size_t nr_values = 0;
2822   for (hive_value_h *itr = prev_values; *itr != 0; ++itr)
2823     ++nr_values;
2824
2825   hive_set_value *values = malloc ((nr_values + 1) * (sizeof (hive_set_value)));
2826   if (values == NULL)
2827     goto leave_prev_values;
2828
2829   int alloc_ct = 0;
2830   int idx_of_val = -1;
2831   hive_value_h *prev_val;
2832   for (prev_val = prev_values; *prev_val != 0; ++prev_val) {
2833     size_t len;
2834     hive_type t;
2835
2836     hive_set_value *value = &values[prev_val - prev_values];
2837
2838     char *valval = hivex_value_value (h, *prev_val, &t, &len);
2839     if (valval == NULL) goto leave_partial;
2840
2841     ++alloc_ct;
2842     value->value = valval;
2843     value->t = t;
2844     value->len = len;
2845
2846     char *valkey = hivex_value_key (h, *prev_val);
2847     if (valkey == NULL) goto leave_partial;
2848
2849     ++alloc_ct;
2850     value->key = valkey;
2851
2852     if (STRCASEEQ (valkey, val->key))
2853       idx_of_val = prev_val - prev_values;
2854   }
2855
2856   if (idx_of_val > -1) {
2857     free (values[idx_of_val].key);
2858     free (values[idx_of_val].value);
2859   } else {
2860     idx_of_val = nr_values;
2861     ++nr_values;
2862   }
2863
2864   hive_set_value *value = &values[idx_of_val];
2865   *value = (hive_set_value){
2866     .key = strdup (val->key),
2867     .value = malloc (val->len),
2868     .len = val->len,
2869     .t = val->t
2870   };
2871
2872   if (value->key == NULL || value->value == NULL) goto leave_partial;
2873   memcpy (value->value, val->value, val->len);
2874
2875   retval = hivex_node_set_values (h, node, nr_values, values, 0);
2876
2877  leave_partial:
2878   for (int i = 0; i < alloc_ct; i += 2) {
2879     free (values[i / 2].value);
2880     if (i + 1 < alloc_ct && values[i / 2].key != NULL)
2881       free (values[i / 2].key);
2882   }
2883   free (values);
2884
2885  leave_prev_values:
2886   free (prev_values);
2887   return retval;
2888 }