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