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