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