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