hivex: display bad block offset in hex
[libguestfs.git] / hivex / hivex.c
1 /* hivex - Windows Registry "hive" extraction library.
2  * Copyright (C) 2009 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 #ifdef HAVE_ENDIAN_H
37 #include <endian.h>
38 #endif
39 #ifdef HAVE_BYTESWAP_H
40 #include <byteswap.h>
41 #endif
42
43 #define STREQ(a,b) (strcmp((a),(b)) == 0)
44 #define STRCASEEQ(a,b) (strcasecmp((a),(b)) == 0)
45 //#define STRNEQ(a,b) (strcmp((a),(b)) != 0)
46 //#define STRCASENEQ(a,b) (strcasecmp((a),(b)) != 0)
47 #define STREQLEN(a,b,n) (strncmp((a),(b),(n)) == 0)
48 //#define STRCASEEQLEN(a,b,n) (strncasecmp((a),(b),(n)) == 0)
49 //#define STRNEQLEN(a,b,n) (strncmp((a),(b),(n)) != 0)
50 //#define STRCASENEQLEN(a,b,n) (strncasecmp((a),(b),(n)) != 0)
51 //#define STRPREFIX(a,b) (strncmp((a),(b),strlen((b))) == 0)
52
53 #if __BYTE_ORDER == __LITTLE_ENDIAN
54 #ifndef be32toh
55 #define be32toh(x) __bswap_32 (x)
56 #endif
57 #ifndef be64toh
58 #define be64toh(x) __bswap_64 (x)
59 #endif
60 #ifndef le16toh
61 #define le16toh(x) (x)
62 #endif
63 #ifndef le32toh
64 #define le32toh(x) (x)
65 #endif
66 #ifndef le64toh
67 #define le64toh(x) (x)
68 #endif
69 #else
70 #ifndef be32toh
71 #define be32toh(x) (x)
72 #endif
73 #ifndef be64toh
74 #define be64toh(x) (x)
75 #endif
76 #ifndef le16toh
77 #define le16toh(x) __bswap_16 (x)
78 #endif
79 #ifndef le32toh
80 #define le32toh(x) __bswap_32 (x)
81 #endif
82 #ifndef le64toh
83 #define le64toh(x) __bswap_64 (x)
84 #endif
85 #endif
86
87 #include "hivex.h"
88
89 static char *windows_utf16_to_utf8 (/* const */ char *input, size_t len);
90
91 struct hive_h {
92   char *filename;
93   int fd;
94   size_t size;
95   int msglvl;
96
97   /* Memory-mapped (readonly) registry file. */
98   union {
99     char *addr;
100     struct ntreg_header *hdr;
101   };
102
103   /* Use a bitmap to store which file offsets are valid (point to a
104    * used block).  We only need to store 1 bit per 32 bits of the file
105    * (because blocks are 4-byte aligned).  We found that the average
106    * block size in a registry file is ~50 bytes.  So roughly 1 in 12
107    * bits in the bitmap will be set, making it likely a more efficient
108    * structure than a hash table.
109    */
110   char *bitmap;
111 #define BITMAP_SET(bitmap,off) (bitmap[(off)>>5] |= 1 << (((off)>>2)&7))
112 #define BITMAP_CLR(bitmap,off) (bitmap[(off)>>5] &= ~ (1 << (((off)>>2)&7)))
113 #define BITMAP_TST(bitmap,off) (bitmap[(off)>>5] & (1 << (((off)>>2)&7)))
114 #define IS_VALID_BLOCK(h,off)               \
115   (((off) & 3) == 0 &&                      \
116    (off) >= 0x1000 &&                       \
117    (off) < (h)->size &&                     \
118    BITMAP_TST((h)->bitmap,(off)))
119
120   /* Fields from the header, extracted from little-endianness hell. */
121   size_t rootoffs;              /* Root key offset (always an nk-block). */
122   size_t endpages;              /* Offset of end of pages. */
123 };
124
125 /* NB. All fields are little endian. */
126 struct ntreg_header {
127   char magic[4];                /* "regf" */
128   uint32_t sequence1;
129   uint32_t sequence2;
130   char last_modified[8];
131   uint32_t major_ver;           /* 1 */
132   uint32_t minor_ver;           /* 3 */
133   uint32_t unknown5;            /* 0 */
134   uint32_t unknown6;            /* 1 */
135   uint32_t offset;              /* offset of root key record - 4KB */
136   uint32_t blocks;              /* pointer AFTER last hbin in file - 4KB */
137   uint32_t unknown7;            /* 1 */
138   /* 0x30 */
139   char name[64];                /* original file name of hive */
140   char unknown_guid1[16];
141   char unknown_guid2[16];
142   /* 0x90 */
143   uint32_t unknown8;
144   char unknown_guid3[16];
145   uint32_t unknown9;
146   /* 0xa8 */
147   char unknown10[340];
148   /* 0x1fc */
149   uint32_t csum;                /* checksum: xor of dwords 0-0x1fb. */
150   /* 0x200 */
151   char unknown11[3528];
152   /* 0xfc8 */
153   char unknown_guid4[16];
154   char unknown_guid5[16];
155   char unknown_guid6[16];
156   uint32_t unknown12;
157   uint32_t unknown13;
158   /* 0x1000 */
159 } __attribute__((__packed__));
160
161 struct ntreg_hbin_page {
162   char magic[4];                /* "hbin" */
163   uint32_t offset_first;        /* offset from 1st block */
164   uint32_t page_size;           /* size of this page (multiple of 4KB) */
165   char unknown[20];
166   /* Linked list of blocks follows here. */
167 } __attribute__((__packed__));
168
169 struct ntreg_hbin_block {
170   int32_t seg_len;              /* length of this block (-ve for used block) */
171   char id[2];                   /* the block type (eg. "nk" for nk record) */
172   /* Block data follows here. */
173 } __attribute__((__packed__));
174
175 #define BLOCK_ID_EQ(h,offs,eqid) \
176   (STREQLEN (((struct ntreg_hbin_block *)((h)->addr + (offs)))->id, (eqid), 2))
177
178 static size_t
179 block_len (hive_h *h, size_t blkoff, int *used)
180 {
181   struct ntreg_hbin_block *block;
182   block = (struct ntreg_hbin_block *) (h->addr + blkoff);
183
184   int32_t len = le32toh (block->seg_len);
185   if (len < 0) {
186     if (used) *used = 1;
187     len = -len;
188   } else {
189     if (used) *used = 0;
190   }
191
192   return (size_t) len;
193 }
194
195 struct ntreg_nk_record {
196   int32_t seg_len;              /* length (always -ve because used) */
197   char id[2];                   /* "nk" */
198   uint16_t flags;
199   char timestamp[8];
200   char unknown0[4];
201   uint32_t parent;              /* offset of owner/parent */
202   uint32_t nr_subkeys;          /* number of subkeys */
203   uint32_t unknown1;
204   uint32_t subkey_lf;           /* lf record containing list of subkeys */
205   uint32_t unknown2;
206   uint32_t nr_values;           /* number of values */
207   uint32_t vallist;             /* value-list record */
208   uint32_t sk;                  /* offset of sk-record */
209   uint32_t classname;           /* offset of classname record */
210   char unknown3[16];
211   uint32_t unknown4;
212   uint16_t name_len;            /* length of name */
213   uint16_t classname_len;       /* length of classname */
214   char name[1];                 /* name follows here */
215 } __attribute__((__packed__));
216
217 struct ntreg_lf_record {
218   int32_t seg_len;
219   char id[2];                   /* "lf" */
220   uint16_t nr_keys;             /* number of keys in this record */
221   struct {
222     uint32_t offset;            /* offset of nk-record for this subkey */
223     char hash[4];               /* hash of subkey name */
224   } keys[1];
225 } __attribute__((__packed__));
226
227 struct ntreg_ri_record {
228   int32_t seg_len;
229   char id[2];                   /* "ri" */
230   uint16_t nr_offsets;          /* number of pointers to lh records */
231   uint32_t offset[1];           /* list of pointers to lh records */
232 } __attribute__((__packed__));
233
234 /* This has no ID header. */
235 struct ntreg_value_list {
236   int32_t seg_len;
237   uint32_t offset[1];           /* list of pointers to vk records */
238 } __attribute__((__packed__));
239
240 struct ntreg_vk_record {
241   int32_t seg_len;              /* length (always -ve because used) */
242   char id[2];                   /* "vk" */
243   uint16_t name_len;            /* length of name */
244   /* length of the data:
245    * If data_len is <= 4, then it's stored inline.
246    * If data_len is 0x80000000, then it's an inline dword.
247    * Top bit may be set or not set at random.
248    */
249   uint32_t data_len;
250   uint32_t data_offset;         /* pointer to the data (or data if inline) */
251   uint32_t data_type;           /* type of the data */
252   uint16_t flags;               /* bit 0 set => key name ASCII,
253                                    bit 0 clr => key name UTF-16.
254                                    Only seen ASCII here in the wild. */
255   uint16_t unknown2;
256   char name[1];                 /* key name follows here */
257 } __attribute__((__packed__));
258
259 static uint32_t
260 header_checksum (hive_h *h)
261 {
262   uint32_t *daddr = (uint32_t *) h->addr;
263   size_t i;
264   uint32_t sum = 0;
265
266   for (i = 0; i < 0x1fc / 4; ++i) {
267     sum ^= le32toh (*daddr);
268     daddr++;
269   }
270
271   return sum;
272 }
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->filename = strdup (filename);
296   if (h->filename == NULL)
297     goto error;
298
299   h->fd = open (filename, O_RDONLY);
300   if (h->fd == -1)
301     goto error;
302
303   struct stat statbuf;
304   if (fstat (h->fd, &statbuf) == -1)
305     goto error;
306
307   h->size = statbuf.st_size;
308
309   h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);
310   if (h->addr == MAP_FAILED)
311     goto error;
312
313   if (h->msglvl >= 2)
314     fprintf (stderr, "hivex_open: mapped file at %p\n", h->addr);
315
316   /* Check header. */
317   if (h->hdr->magic[0] != 'r' ||
318       h->hdr->magic[1] != 'e' ||
319       h->hdr->magic[2] != 'g' ||
320       h->hdr->magic[3] != 'f') {
321     fprintf (stderr, "hivex: %s: not a Windows NT Registry hive file\n",
322              filename);
323     errno = ENOTSUP;
324     goto error;
325   }
326
327   /* Check major version. */
328   uint32_t major_ver = le32toh (h->hdr->major_ver);
329   if (major_ver != 1) {
330     fprintf (stderr,
331              "hivex: %s: hive file major version %" PRIu32 " (expected 1)\n",
332              filename, major_ver);
333     errno = ENOTSUP;
334     goto error;
335   }
336
337   h->bitmap = calloc (1 + h->size / 32, 1);
338   if (h->bitmap == NULL)
339     goto error;
340
341   /* Header checksum. */
342   uint32_t sum = header_checksum (h);
343   if (sum != le32toh (h->hdr->csum)) {
344     fprintf (stderr, "hivex: %s: bad checksum in hive header\n", filename);
345     errno = EINVAL;
346     goto error;
347   }
348
349   if (h->msglvl >= 2) {
350     char *name = windows_utf16_to_utf8 (h->hdr->name, 64);
351
352     fprintf (stderr,
353              "hivex_open: header fields:\n"
354              "  file version             %" PRIu32 ".%" PRIu32 "\n"
355              "  sequence nos             %" PRIu32 " %" PRIu32 "\n"
356              "    (sequences nos should match if hive was synched at shutdown)\n"
357              "  original file name       %s\n"
358              "    (only 32 chars are stored, name is probably truncated)\n"
359              "  root offset              0x%x + 0x1000\n"
360              "  end of last page         0x%x + 0x1000 (total file size 0x%zx)\n"
361              "  checksum                 0x%x (calculated 0x%x)\n",
362              major_ver, le32toh (h->hdr->minor_ver),
363              le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),
364              name ? name : "(conversion failed)",
365              le32toh (h->hdr->offset),
366              le32toh (h->hdr->blocks), h->size,
367              le32toh (h->hdr->csum), sum);
368     free (name);
369   }
370
371   h->rootoffs = le32toh (h->hdr->offset) + 0x1000;
372   h->endpages = le32toh (h->hdr->blocks) + 0x1000;
373
374   if (h->msglvl >= 2)
375     fprintf (stderr, "hivex_open: root offset = 0x%zx\n", h->rootoffs);
376
377   /* We'll set this flag when we see a block with the root offset (ie.
378    * the root block).
379    */
380   int seen_root_block = 0, bad_root_block = 0;
381
382   /* Collect some stats. */
383   size_t pages = 0;           /* Number of hbin pages read. */
384   size_t smallest_page = SIZE_MAX, largest_page = 0;
385   size_t blocks = 0;          /* Total number of blocks found. */
386   size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;
387   size_t used_blocks = 0;     /* Total number of used blocks found. */
388   size_t used_size = 0;       /* Total size (bytes) of used blocks. */
389
390   /* Read the pages and blocks.  The aim here is to be robust against
391    * corrupt or malicious registries.  So we make sure the loops
392    * always make forward progress.  We add the address of each block
393    * we read to a hash table so pointers will only reference the start
394    * of valid blocks.
395    */
396   size_t off;
397   struct ntreg_hbin_page *page;
398   for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {
399     if (off >= h->endpages)
400       break;
401
402     page = (struct ntreg_hbin_page *) (h->addr + off);
403     if (page->magic[0] != 'h' ||
404         page->magic[1] != 'b' ||
405         page->magic[2] != 'i' ||
406         page->magic[3] != 'n') {
407       fprintf (stderr, "hivex: %s: trailing garbage at end of file (at 0x%zx, after %zu pages)\n",
408                filename, off, pages);
409       errno = ENOTSUP;
410       goto error;
411     }
412
413     size_t page_size = le32toh (page->page_size);
414     if (h->msglvl >= 2)
415       fprintf (stderr, "hivex_open: page at 0x%zx, size %zu\n", off, page_size);
416     pages++;
417     if (page_size < smallest_page) smallest_page = page_size;
418     if (page_size > largest_page) largest_page = page_size;
419
420     if (page_size <= sizeof (struct ntreg_hbin_page) ||
421         (page_size & 0x0fff) != 0) {
422       fprintf (stderr, "hivex: %s: page size %zu at 0x%zx, bad registry\n",
423                filename, page_size, off);
424       errno = ENOTSUP;
425       goto error;
426     }
427
428     /* Read the blocks in this page. */
429     size_t blkoff;
430     struct ntreg_hbin_block *block;
431     size_t seg_len;
432     for (blkoff = off + 0x20;
433          blkoff < off + page_size;
434          blkoff += seg_len) {
435       blocks++;
436
437       int is_root = blkoff == h->rootoffs;
438       if (is_root)
439         seen_root_block = 1;
440
441       block = (struct ntreg_hbin_block *) (h->addr + blkoff);
442       int used;
443       seg_len = block_len (h, blkoff, &used);
444       if (seg_len <= 4 || (seg_len & 3) != 0) {
445         fprintf (stderr, "hivex: %s: block size %d at 0x%zx, bad registry\n",
446                  filename, le32toh (block->seg_len), blkoff);
447         errno = ENOTSUP;
448         goto error;
449       }
450
451       if (h->msglvl >= 2)
452         fprintf (stderr, "hivex_open: %s block id %d,%d at 0x%zx size %zu%s\n",
453                  used ? "used" : "free", block->id[0], block->id[1], blkoff,
454                  seg_len, is_root ? " (root)" : "");
455
456       blocks_bytes += seg_len;
457       if (seg_len < smallest_block) smallest_block = seg_len;
458       if (seg_len > largest_block) largest_block = seg_len;
459
460       if (is_root && !used)
461         bad_root_block = 1;
462
463       if (used) {
464         used_blocks++;
465         used_size += seg_len;
466
467         /* Root block must be an nk-block. */
468         if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))
469           bad_root_block = 1;
470
471         /* Note this blkoff is a valid address. */
472         BITMAP_SET (h->bitmap, blkoff);
473       }
474     }
475   }
476
477   if (!seen_root_block) {
478     fprintf (stderr, "hivex: %s: no root block found\n", filename);
479     errno = ENOTSUP;
480     goto error;
481   }
482
483   if (bad_root_block) {
484     fprintf (stderr, "hivex: %s: bad root block (free or not nk)\n", filename);
485     errno = ENOTSUP;
486     goto error;
487   }
488
489   if (h->msglvl >= 1)
490     fprintf (stderr,
491              "hivex_open: successfully read Windows Registry hive file:\n"
492              "  pages:          %zu [sml: %zu, lge: %zu]\n"
493              "  blocks:         %zu [sml: %zu, avg: %zu, lge: %zu]\n"
494              "  blocks used:    %zu\n"
495              "  bytes used:     %zu\n",
496              pages, smallest_page, largest_page,
497              blocks, smallest_block, blocks_bytes / blocks, largest_block,
498              used_blocks, used_size);
499
500   return h;
501
502  error:;
503   int err = errno;
504   if (h) {
505     free (h->bitmap);
506     if (h->addr && h->size && h->addr != MAP_FAILED)
507       munmap (h->addr, h->size);
508     if (h->fd >= 0)
509       close (h->fd);
510     free (h->filename);
511     free (h);
512   }
513   errno = err;
514   return NULL;
515 }
516
517 int
518 hivex_close (hive_h *h)
519 {
520   int r;
521
522   free (h->bitmap);
523   munmap (h->addr, h->size);
524   r = close (h->fd);
525   free (h->filename);
526   free (h);
527
528   return r;
529 }
530
531 hive_node_h
532 hivex_root (hive_h *h)
533 {
534   hive_node_h ret = h->rootoffs;
535   if (!IS_VALID_BLOCK (h, ret)) {
536     errno = ENOKEY;
537     return 0;
538   }
539   return ret;
540 }
541
542 char *
543 hivex_node_name (hive_h *h, hive_node_h node)
544 {
545   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
546     errno = EINVAL;
547     return NULL;
548   }
549
550   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
551
552   /* AFAIK the node name is always plain ASCII, so no conversion
553    * to UTF-8 is necessary.  However we do need to nul-terminate
554    * the string.
555    */
556
557   /* nk->name_len is unsigned, 16 bit, so this is safe ...  However
558    * we have to make sure the length doesn't exceed the block length.
559    */
560   size_t len = le16toh (nk->name_len);
561   size_t seg_len = block_len (h, node, NULL);
562   if (sizeof (struct ntreg_nk_record) + len - 1 > seg_len) {
563     if (h->msglvl >= 2)
564       fprintf (stderr, "hivex_node_name: returning EFAULT because node name is too long (%zu, %zu)\n",
565               len, seg_len);
566     errno = EFAULT;
567     return NULL;
568   }
569
570   char *ret = malloc (len + 1);
571   if (ret == NULL)
572     return NULL;
573   memcpy (ret, nk->name, len);
574   ret[len] = '\0';
575   return ret;
576 }
577
578 #if 0
579 /* I think the documentation for the sk and classname fields in the nk
580  * record is wrong, or else the offset field is in the wrong place.
581  * Otherwise this makes no sense.  Disabled this for now -- it's not
582  * useful for reading the registry anyway.
583  */
584
585 hive_security_h
586 hivex_node_security (hive_h *h, hive_node_h node)
587 {
588   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
589     errno = EINVAL;
590     return 0;
591   }
592
593   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
594
595   hive_node_h ret = le32toh (nk->sk);
596   ret += 0x1000;
597   if (!IS_VALID_BLOCK (h, ret)) {
598     errno = EFAULT;
599     return 0;
600   }
601   return ret;
602 }
603
604 hive_classname_h
605 hivex_node_classname (hive_h *h, hive_node_h node)
606 {
607   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
608     errno = EINVAL;
609     return 0;
610   }
611
612   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
613
614   hive_node_h ret = le32toh (nk->classname);
615   ret += 0x1000;
616   if (!IS_VALID_BLOCK (h, ret)) {
617     errno = EFAULT;
618     return 0;
619   }
620   return ret;
621 }
622 #endif
623
624 /* Structure for returning 0-terminated lists of offsets (nodes,
625  * values, etc).
626  */
627 struct offset_list {
628   size_t *offsets;
629   size_t len;
630   size_t alloc;
631 };
632
633 static void
634 init_offset_list (struct offset_list *list)
635 {
636   list->len = 0;
637   list->alloc = 0;
638   list->offsets = NULL;
639 }
640
641 #define INIT_OFFSET_LIST(name) \
642   struct offset_list name; \
643   init_offset_list (&name)
644
645 /* Preallocates the offset_list, but doesn't make the contents longer. */
646 static int
647 grow_offset_list (struct offset_list *list, size_t alloc)
648 {
649   assert (alloc >= list->len);
650   size_t *p = realloc (list->offsets, alloc * sizeof (size_t));
651   if (p == NULL)
652     return -1;
653   list->offsets = p;
654   list->alloc = alloc;
655   return 0;
656 }
657
658 static int
659 add_to_offset_list (struct offset_list *list, size_t offset)
660 {
661   if (list->len >= list->alloc) {
662     if (grow_offset_list (list, list->alloc ? list->alloc * 2 : 4) == -1)
663       return -1;
664   }
665   list->offsets[list->len] = offset;
666   list->len++;
667   return 0;
668 }
669
670 static void
671 free_offset_list (struct offset_list *list)
672 {
673   free (list->offsets);
674 }
675
676 static size_t *
677 return_offset_list (struct offset_list *list)
678 {
679   if (add_to_offset_list (list, 0) == -1)
680     return NULL;
681   return list->offsets;         /* caller frees */
682 }
683
684 /* Iterate over children, returning child nodes and intermediate blocks. */
685 static int
686 get_children (hive_h *h, hive_node_h node,
687               hive_node_h **children_ret, size_t **blocks_ret)
688 {
689   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
690     errno = EINVAL;
691     return -1;
692   }
693
694   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
695
696   size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
697
698   INIT_OFFSET_LIST (children);
699   INIT_OFFSET_LIST (blocks);
700
701   /* Deal with the common "no subkeys" case quickly. */
702   if (nr_subkeys_in_nk == 0)
703     goto ok;
704
705   /* Arbitrarily limit the number of subkeys we will ever deal with. */
706   if (nr_subkeys_in_nk > 1000000) {
707     errno = ERANGE;
708     goto error;
709   }
710
711   /* Preallocate space for the children. */
712   if (grow_offset_list (&children, nr_subkeys_in_nk) == -1)
713     goto error;
714
715   /* The subkey_lf field can point either to an lf-record, which is
716    * the common case, or if there are lots of subkeys, to an
717    * ri-record.
718    */
719   size_t subkey_lf = le32toh (nk->subkey_lf);
720   subkey_lf += 0x1000;
721   if (!IS_VALID_BLOCK (h, subkey_lf)) {
722     if (h->msglvl >= 2)
723       fprintf (stderr, "hivex_node_children: returning EFAULT because subkey_lf is not a valid block (%zu)\n",
724                subkey_lf);
725     errno = EFAULT;
726     goto error;
727   }
728
729   if (add_to_offset_list (&blocks, subkey_lf) == -1)
730     goto error;
731
732   struct ntreg_hbin_block *block =
733     (struct ntreg_hbin_block *) (h->addr + subkey_lf);
734
735   /* Points to lf-record?  (Note, also "lh" but that is basically the
736    * same as "lf" as far as we are concerned here).
737    */
738   if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
739     struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
740
741     /* Check number of subkeys in the nk-record matches number of subkeys
742      * in the lf-record.
743      */
744     size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
745
746     if (h->msglvl >= 2)
747       fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu, nr_subkeys_in_lf = %zu\n",
748                nr_subkeys_in_nk, nr_subkeys_in_lf);
749
750     if (nr_subkeys_in_nk != nr_subkeys_in_lf) {
751       errno = ENOTSUP;
752       goto error;
753     }
754
755     size_t len = block_len (h, subkey_lf, NULL);
756     if (8 + nr_subkeys_in_lf * 8 > len) {
757       if (h->msglvl >= 2)
758         fprintf (stderr, "hivex_node_children: returning EFAULT because too many subkeys (%zu, %zu)\n",
759                  nr_subkeys_in_lf, len);
760       errno = EFAULT;
761       goto error;
762     }
763
764     size_t i;
765     for (i = 0; i < nr_subkeys_in_lf; ++i) {
766       hive_node_h subkey = le32toh (lf->keys[i].offset);
767       subkey += 0x1000;
768       if (!IS_VALID_BLOCK (h, subkey)) {
769         if (h->msglvl >= 2)
770           fprintf (stderr, "hivex_node_children: returning EFAULT because subkey is not a valid block (0x%zx)\n",
771                    subkey);
772         errno = EFAULT;
773         goto error;
774       }
775       if (add_to_offset_list (&children, subkey) == -1)
776         goto error;
777     }
778     goto ok;
779   }
780   /* Points to ri-record? */
781   else if (block->id[0] == 'r' && block->id[1] == 'i') {
782     struct ntreg_ri_record *ri = (struct ntreg_ri_record *) block;
783
784     size_t nr_offsets = le16toh (ri->nr_offsets);
785
786     /* Count total number of children. */
787     size_t i, count = 0;
788     for (i = 0; i < nr_offsets; ++i) {
789       hive_node_h offset = ri->offset[i];
790       offset += 0x1000;
791       if (!IS_VALID_BLOCK (h, offset)) {
792         if (h->msglvl >= 2)
793           fprintf (stderr, "hivex_node_children: returning EFAULT because ri-offset is not a valid block (0x%zx)\n",
794                    offset);
795         errno = EFAULT;
796         goto error;
797       }
798       if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
799         errno = ENOTSUP;
800         goto error;
801       }
802
803       if (add_to_offset_list (&blocks, offset) == -1)
804         goto error;
805
806       struct ntreg_lf_record *lf =
807         (struct ntreg_lf_record *) (h->addr + offset);
808
809       count += le16toh (lf->nr_keys);
810     }
811
812     if (h->msglvl >= 2)
813       fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu, counted = %zu\n",
814                nr_subkeys_in_nk, count);
815
816     if (nr_subkeys_in_nk != count) {
817       errno = ENOTSUP;
818       goto error;
819     }
820
821     /* Copy list of children.  Note nr_subkeys_in_nk is limited to
822      * something reasonable above.
823      */
824     for (i = 0; i < nr_offsets; ++i) {
825       hive_node_h offset = 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 because ri-offset is not a valid block (0x%zx)\n",
830                    offset);
831         errno = EFAULT;
832         goto error;
833       }
834       if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
835         errno = ENOTSUP;
836         goto error;
837       }
838
839       struct ntreg_lf_record *lf =
840         (struct ntreg_lf_record *) (h->addr + offset);
841
842       size_t j;
843       for (j = 0; j < le16toh (lf->nr_keys); ++j) {
844         hive_node_h subkey = le32toh (lf->keys[j].offset);
845         subkey += 0x1000;
846         if (!IS_VALID_BLOCK (h, subkey)) {
847           if (h->msglvl >= 2)
848             fprintf (stderr, "hivex_node_children: returning EFAULT because indirect subkey is not a valid block (0x%zx)\n",
849                      subkey);
850           errno = EFAULT;
851           goto error;
852         }
853         if (add_to_offset_list (&children, subkey) == -1)
854           goto error;
855       }
856     }
857     goto ok;
858   }
859   /* else not supported, set errno and fall through */
860   errno = ENOTSUP;
861  error:
862   free_offset_list (&children);
863   free_offset_list (&blocks);
864   return -1;
865
866  ok:
867   *children_ret = return_offset_list (&children);
868   *blocks_ret = return_offset_list (&blocks);
869   if (!*children_ret || !*blocks_ret)
870     goto error;
871   return 0;
872 }
873
874 hive_node_h *
875 hivex_node_children (hive_h *h, hive_node_h node)
876 {
877   hive_node_h *children;
878   size_t *blocks;
879
880   if (get_children (h, node, &children, &blocks) == -1)
881     return NULL;
882
883   free (blocks);
884   return children;
885 }
886
887 /* Very inefficient, but at least having a separate API call
888  * allows us to make it more efficient in future.
889  */
890 hive_node_h
891 hivex_node_get_child (hive_h *h, hive_node_h node, const char *nname)
892 {
893   hive_node_h *children = NULL;
894   char *name = NULL;
895   hive_node_h ret = 0;
896
897   children = hivex_node_children (h, node);
898   if (!children) goto error;
899
900   size_t i;
901   for (i = 0; children[i] != 0; ++i) {
902     name = hivex_node_name (h, children[i]);
903     if (!name) goto error;
904     if (STRCASEEQ (name, nname)) {
905       ret = children[i];
906       break;
907     }
908     free (name); name = NULL;
909   }
910
911  error:
912   free (children);
913   free (name);
914   return ret;
915 }
916
917 hive_node_h
918 hivex_node_parent (hive_h *h, hive_node_h node)
919 {
920   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
921     errno = EINVAL;
922     return 0;
923   }
924
925   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
926
927   hive_node_h ret = le32toh (nk->parent);
928   ret += 0x1000;
929   if (!IS_VALID_BLOCK (h, ret)) {
930     if (h->msglvl >= 2)
931       fprintf (stderr, "hivex_node_parent: returning EFAULT because parent is not a valid block (0x%zx)\n",
932               ret);
933     errno = EFAULT;
934     return 0;
935   }
936   return ret;
937 }
938
939 static int
940 get_values (hive_h *h, hive_node_h node,
941             hive_value_h **values_ret, size_t **blocks_ret)
942 {
943   if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
944     errno = EINVAL;
945     return -1;
946   }
947
948   struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
949
950   size_t nr_values = le32toh (nk->nr_values);
951
952   if (h->msglvl >= 2)
953     fprintf (stderr, "hivex_node_values: nr_values = %zu\n", nr_values);
954
955   INIT_OFFSET_LIST (values);
956   INIT_OFFSET_LIST (blocks);
957
958   /* Deal with the common "no values" case quickly. */
959   if (nr_values == 0)
960     goto ok;
961
962   /* Arbitrarily limit the number of values we will ever deal with. */
963   if (nr_values > 100000) {
964     errno = ERANGE;
965     goto error;
966   }
967
968   /* Preallocate space for the values. */
969   if (grow_offset_list (&values, nr_values) == -1)
970     goto error;
971
972   /* Get the value list and check it looks reasonable. */
973   size_t vlist_offset = le32toh (nk->vallist);
974   vlist_offset += 0x1000;
975   if (!IS_VALID_BLOCK (h, vlist_offset)) {
976     if (h->msglvl >= 2)
977       fprintf (stderr, "hivex_node_values: returning EFAULT because value list is not a valid block (0x%zx)\n",
978                vlist_offset);
979     errno = EFAULT;
980     goto error;
981   }
982
983   if (add_to_offset_list (&blocks, vlist_offset) == -1)
984     goto error;
985
986   struct ntreg_value_list *vlist =
987     (struct ntreg_value_list *) (h->addr + vlist_offset);
988
989   size_t len = block_len (h, vlist_offset, NULL);
990   if (4 + nr_values * 4 > len) {
991     if (h->msglvl >= 2)
992       fprintf (stderr, "hivex_node_values: returning EFAULT because value list is too long (%zu, %zu)\n",
993                nr_values, len);
994     errno = EFAULT;
995     goto error;
996   }
997
998   size_t i;
999   for (i = 0; i < nr_values; ++i) {
1000     hive_node_h value = vlist->offset[i];
1001     value += 0x1000;
1002     if (!IS_VALID_BLOCK (h, value)) {
1003       if (h->msglvl >= 2)
1004         fprintf (stderr, "hivex_node_values: returning EFAULT because value is not a valid block (0x%zx)\n",
1005                  value);
1006       errno = EFAULT;
1007       goto error;
1008     }
1009     if (add_to_offset_list (&values, value) == -1)
1010       goto error;
1011   }
1012
1013  ok:
1014   *values_ret = return_offset_list (&values);
1015   *blocks_ret = return_offset_list (&blocks);
1016   if (!*values_ret || !*blocks_ret)
1017     goto error;
1018   return 0;
1019
1020  error:
1021   free_offset_list (&values);
1022   free_offset_list (&blocks);
1023   return -1;
1024 }
1025
1026 hive_value_h *
1027 hivex_node_values (hive_h *h, hive_node_h node)
1028 {
1029   hive_value_h *values;
1030   size_t *blocks;
1031
1032   if (get_values (h, node, &values, &blocks) == -1)
1033     return NULL;
1034
1035   free (blocks);
1036   return values;
1037 }
1038
1039 /* Very inefficient, but at least having a separate API call
1040  * allows us to make it more efficient in future.
1041  */
1042 hive_value_h
1043 hivex_node_get_value (hive_h *h, hive_node_h node, const char *key)
1044 {
1045   hive_value_h *values = NULL;
1046   char *name = NULL;
1047   hive_value_h ret = 0;
1048
1049   values = hivex_node_values (h, node);
1050   if (!values) goto error;
1051
1052   size_t i;
1053   for (i = 0; values[i] != 0; ++i) {
1054     name = hivex_value_key (h, values[i]);
1055     if (!name) goto error;
1056     if (STRCASEEQ (name, key)) {
1057       ret = values[i];
1058       break;
1059     }
1060     free (name); name = NULL;
1061   }
1062
1063  error:
1064   free (values);
1065   free (name);
1066   return ret;
1067 }
1068
1069 char *
1070 hivex_value_key (hive_h *h, hive_value_h value)
1071 {
1072   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1073     errno = EINVAL;
1074     return 0;
1075   }
1076
1077   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1078
1079   /* AFAIK the key is always plain ASCII, so no conversion to UTF-8 is
1080    * necessary.  However we do need to nul-terminate the string.
1081    */
1082
1083   /* vk->name_len is unsigned, 16 bit, so this is safe ...  However
1084    * we have to make sure the length doesn't exceed the block length.
1085    */
1086   size_t len = le16toh (vk->name_len);
1087   size_t seg_len = block_len (h, value, NULL);
1088   if (sizeof (struct ntreg_vk_record) + len - 1 > seg_len) {
1089     if (h->msglvl >= 2)
1090       fprintf (stderr, "hivex_value_key: returning EFAULT because key length is too long (%zu, %zu)\n",
1091                len, seg_len);
1092     errno = EFAULT;
1093     return NULL;
1094   }
1095
1096   char *ret = malloc (len + 1);
1097   if (ret == NULL)
1098     return NULL;
1099   memcpy (ret, vk->name, len);
1100   ret[len] = '\0';
1101   return ret;
1102 }
1103
1104 int
1105 hivex_value_type (hive_h *h, hive_value_h value, hive_type *t, size_t *len)
1106 {
1107   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1108     errno = EINVAL;
1109     return -1;
1110   }
1111
1112   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1113
1114   if (t)
1115     *t = le32toh (vk->data_type);
1116
1117   if (len) {
1118     *len = le32toh (vk->data_len);
1119     if (*len == 0x80000000) {   /* special case */
1120       *len = 4;
1121       if (t) *t = hive_t_dword;
1122     }
1123     *len &= 0x7fffffff;
1124   }
1125
1126   return 0;
1127 }
1128
1129 char *
1130 hivex_value_value (hive_h *h, hive_value_h value,
1131                    hive_type *t_rtn, size_t *len_rtn)
1132 {
1133   if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1134     errno = EINVAL;
1135     return NULL;
1136   }
1137
1138   struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1139
1140   hive_type t;
1141   size_t len;
1142
1143   t = le32toh (vk->data_type);
1144
1145   len = le32toh (vk->data_len);
1146   if (len == 0x80000000) {      /* special case */
1147     len = 4;
1148     t = hive_t_dword;
1149   }
1150   len &= 0x7fffffff;
1151
1152   if (h->msglvl >= 2)
1153     fprintf (stderr, "hivex_value_value: value=0x%zx, t=%d, len=%zu\n",
1154              value, t, len);
1155
1156   if (t_rtn)
1157     *t_rtn = t;
1158   if (len_rtn)
1159     *len_rtn = len;
1160
1161   /* Arbitrarily limit the length that we will read. */
1162   if (len > 1000000) {
1163     errno = ERANGE;
1164     return NULL;
1165   }
1166
1167   char *ret = malloc (len);
1168   if (ret == NULL)
1169     return NULL;
1170
1171   /* If length is <= 4 it's always stored inline. */
1172   if (len <= 4) {
1173     memcpy (ret, (char *) &vk->data_offset, len);
1174     return ret;
1175   }
1176
1177   size_t data_offset = le32toh (vk->data_offset);
1178   data_offset += 0x1000;
1179   if (!IS_VALID_BLOCK (h, data_offset)) {
1180     if (h->msglvl >= 2)
1181       fprintf (stderr, "hivex_value_value: returning EFAULT because data offset is not a valid block (0x%zx)\n",
1182                data_offset);
1183     errno = EFAULT;
1184     free (ret);
1185     return NULL;
1186   }
1187
1188   /* Check that the declared size isn't larger than the block its in. */
1189   size_t blen = block_len (h, data_offset, NULL);
1190   if (len > blen) {
1191     if (h->msglvl >= 2)
1192       fprintf (stderr, "hivex_value_value: returning EFAULT because data is longer than its block (data 0x%zx, data len %zu, block len %zu)\n",
1193                data_offset, len, blen);
1194     errno = EFAULT;
1195     free (ret);
1196     return NULL;
1197   }
1198
1199   char *data = h->addr + data_offset + 4;
1200   memcpy (ret, data, len);
1201   return ret;
1202 }
1203
1204 static char *
1205 windows_utf16_to_utf8 (/* const */ char *input, size_t len)
1206 {
1207   iconv_t ic = iconv_open ("UTF-8", "UTF-16");
1208   if (ic == (iconv_t) -1)
1209     return NULL;
1210
1211   /* iconv(3) has an insane interface ... */
1212
1213   /* Mostly UTF-8 will be smaller, so this is a good initial guess. */
1214   size_t outalloc = len;
1215
1216  again:;
1217   size_t inlen = len;
1218   size_t outlen = outalloc;
1219   char *out = malloc (outlen + 1);
1220   if (out == NULL) {
1221     int err = errno;
1222     iconv_close (ic);
1223     errno = err;
1224     return NULL;
1225   }
1226   char *inp = input;
1227   char *outp = out;
1228
1229   size_t r = iconv (ic, &inp, &inlen, &outp, &outlen);
1230   if (r == (size_t) -1) {
1231     if (errno == E2BIG) {
1232       size_t prev = outalloc;
1233       /* Try again with a larger output buffer. */
1234       free (out);
1235       outalloc *= 2;
1236       if (outalloc < prev)
1237         return NULL;
1238       goto again;
1239     }
1240     else {
1241       /* Else some conversion failure, eg. EILSEQ, EINVAL. */
1242       int err = errno;
1243       iconv_close (ic);
1244       free (out);
1245       errno = err;
1246       return NULL;
1247     }
1248   }
1249
1250   *outp = '\0';
1251   iconv_close (ic);
1252
1253   return out;
1254 }
1255
1256 char *
1257 hivex_value_string (hive_h *h, hive_value_h value)
1258 {
1259   hive_type t;
1260   size_t len;
1261   char *data = hivex_value_value (h, value, &t, &len);
1262
1263   if (data == NULL)
1264     return NULL;
1265
1266   if (t != hive_t_string && t != hive_t_expand_string && t != hive_t_link) {
1267     free (data);
1268     errno = EINVAL;
1269     return NULL;
1270   }
1271
1272   char *ret = windows_utf16_to_utf8 (data, len);
1273   free (data);
1274   if (ret == NULL)
1275     return NULL;
1276
1277   return ret;
1278 }
1279
1280 static void
1281 free_strings (char **argv)
1282 {
1283   if (argv) {
1284     size_t i;
1285
1286     for (i = 0; argv[i] != NULL; ++i)
1287       free (argv[i]);
1288     free (argv);
1289   }
1290 }
1291
1292 /* Get the length of a UTF-16 format string.  Handle the string as
1293  * pairs of bytes, looking for the first \0\0 pair.
1294  */
1295 static size_t
1296 utf16_string_len_in_bytes (const char *str)
1297 {
1298   size_t ret = 0;
1299
1300   while (str[0] || str[1]) {
1301     str += 2;
1302     ret += 2;
1303   }
1304
1305   return ret;
1306 }
1307
1308 /* http://blogs.msdn.com/oldnewthing/archive/2009/10/08/9904646.aspx */
1309 char **
1310 hivex_value_multiple_strings (hive_h *h, hive_value_h value)
1311 {
1312   hive_type t;
1313   size_t len;
1314   char *data = hivex_value_value (h, value, &t, &len);
1315
1316   if (data == NULL)
1317     return NULL;
1318
1319   if (t != hive_t_multiple_strings) {
1320     free (data);
1321     errno = EINVAL;
1322     return NULL;
1323   }
1324
1325   size_t nr_strings = 0;
1326   char **ret = malloc ((1 + nr_strings) * sizeof (char *));
1327   if (ret == NULL) {
1328     free (data);
1329     return NULL;
1330   }
1331   ret[0] = NULL;
1332
1333   char *p = data;
1334   size_t plen;
1335
1336   while (p < data + len && (plen = utf16_string_len_in_bytes (p)) > 0) {
1337     nr_strings++;
1338     char **ret2 = realloc (ret, (1 + nr_strings) * sizeof (char *));
1339     if (ret2 == NULL) {
1340       free_strings (ret);
1341       free (data);
1342       return NULL;
1343     }
1344     ret = ret2;
1345
1346     ret[nr_strings-1] = windows_utf16_to_utf8 (p, plen);
1347     ret[nr_strings] = NULL;
1348     if (ret[nr_strings-1] == NULL) {
1349       free_strings (ret);
1350       free (data);
1351       return NULL;
1352     }
1353
1354     p += plen + 2 /* skip over UTF-16 \0\0 at the end of this string */;
1355   }
1356
1357   free (data);
1358   return ret;
1359 }
1360
1361 int32_t
1362 hivex_value_dword (hive_h *h, hive_value_h value)
1363 {
1364   hive_type t;
1365   size_t len;
1366   char *data = hivex_value_value (h, value, &t, &len);
1367
1368   if (data == NULL)
1369     return -1;
1370
1371   if ((t != hive_t_dword && t != hive_t_dword_be) || len != 4) {
1372     free (data);
1373     errno = EINVAL;
1374     return -1;
1375   }
1376
1377   int32_t ret = *(int32_t*)data;
1378   free (data);
1379   if (t == hive_t_dword)        /* little endian */
1380     ret = le32toh (ret);
1381   else
1382     ret = be32toh (ret);
1383
1384   return ret;
1385 }
1386
1387 int64_t
1388 hivex_value_qword (hive_h *h, hive_value_h value)
1389 {
1390   hive_type t;
1391   size_t len;
1392   char *data = hivex_value_value (h, value, &t, &len);
1393
1394   if (data == NULL)
1395     return -1;
1396
1397   if (t != hive_t_qword || len != 8) {
1398     free (data);
1399     errno = EINVAL;
1400     return -1;
1401   }
1402
1403   int64_t ret = *(int64_t*)data;
1404   free (data);
1405   ret = le64toh (ret);          /* always little endian */
1406
1407   return ret;
1408 }
1409
1410 int
1411 hivex_visit (hive_h *h, const struct hivex_visitor *visitor, size_t len,
1412              void *opaque, int flags)
1413 {
1414   return hivex_visit_node (h, hivex_root (h), visitor, len, opaque, flags);
1415 }
1416
1417 static int hivex__visit_node (hive_h *h, hive_node_h node, const struct hivex_visitor *vtor, char *unvisited, void *opaque, int flags);
1418
1419 int
1420 hivex_visit_node (hive_h *h, hive_node_h node,
1421                   const struct hivex_visitor *visitor, size_t len, void *opaque,
1422                   int flags)
1423 {
1424   struct hivex_visitor vtor;
1425   memset (&vtor, 0, sizeof vtor);
1426
1427   /* Note that len might be larger *or smaller* than the expected size. */
1428   size_t copysize = len <= sizeof vtor ? len : sizeof vtor;
1429   memcpy (&vtor, visitor, copysize);
1430
1431   /* This bitmap records unvisited nodes, so we don't loop if the
1432    * registry contains cycles.
1433    */
1434   char *unvisited = malloc (1 + h->size / 32);
1435   if (unvisited == NULL)
1436     return -1;
1437   memcpy (unvisited, h->bitmap, 1 + h->size / 32);
1438
1439   int r = hivex__visit_node (h, node, &vtor, unvisited, opaque, flags);
1440   free (unvisited);
1441   return r;
1442 }
1443
1444 static int
1445 hivex__visit_node (hive_h *h, hive_node_h node,
1446                    const struct hivex_visitor *vtor, char *unvisited,
1447                    void *opaque, int flags)
1448 {
1449   int skip_bad = flags & HIVEX_VISIT_SKIP_BAD;
1450   char *name = NULL;
1451   hive_value_h *values = NULL;
1452   hive_node_h *children = NULL;
1453   char *key = NULL;
1454   char *str = NULL;
1455   char **strs = NULL;
1456   int i;
1457
1458   /* Return -1 on all callback errors.  However on internal errors,
1459    * check if skip_bad is set and suppress those errors if so.
1460    */
1461   int ret = -1;
1462
1463   if (!BITMAP_TST (unvisited, node)) {
1464     if (h->msglvl >= 2)
1465       fprintf (stderr, "hivex__visit_node: contains cycle: visited node 0x%zx already\n",
1466                node);
1467
1468     errno = ELOOP;
1469     return skip_bad ? 0 : -1;
1470   }
1471   BITMAP_CLR (unvisited, node);
1472
1473   name = hivex_node_name (h, node);
1474   if (!name) return skip_bad ? 0 : -1;
1475   if (vtor->node_start && vtor->node_start (h, opaque, node, name) == -1)
1476     goto error;
1477
1478   values = hivex_node_values (h, node);
1479   if (!values) {
1480     ret = skip_bad ? 0 : -1;
1481     goto error;
1482   }
1483
1484   for (i = 0; values[i] != 0; ++i) {
1485     hive_type t;
1486     size_t len;
1487
1488     if (hivex_value_type (h, values[i], &t, &len) == -1) {
1489       ret = skip_bad ? 0 : -1;
1490       goto error;
1491     }
1492
1493     key = hivex_value_key (h, values[i]);
1494     if (key == NULL) {
1495       ret = skip_bad ? 0 : -1;
1496       goto error;
1497     }
1498
1499     if (vtor->value_any) {
1500       str = hivex_value_value (h, values[i], &t, &len);
1501       if (str == NULL) {
1502         ret = skip_bad ? 0 : -1;
1503         goto error;
1504       }
1505       if (vtor->value_any (h, opaque, node, values[i], t, len, key, str) == -1)
1506         goto error;
1507       free (str); str = NULL;
1508     }
1509     else {
1510       switch (t) {
1511       case hive_t_none:
1512         str = hivex_value_value (h, values[i], &t, &len);
1513         if (str == NULL) {
1514           ret = skip_bad ? 0 : -1;
1515           goto error;
1516         }
1517         if (t != hive_t_none) {
1518           ret = skip_bad ? 0 : -1;
1519           goto error;
1520         }
1521         if (vtor->value_none &&
1522             vtor->value_none (h, opaque, node, values[i], t, len, key, str) == -1)
1523           goto error;
1524         free (str); str = NULL;
1525         break;
1526
1527       case hive_t_string:
1528       case hive_t_expand_string:
1529       case hive_t_link:
1530         str = hivex_value_string (h, values[i]);
1531         if (str == NULL) {
1532           if (errno != EILSEQ && errno != EINVAL) {
1533             ret = skip_bad ? 0 : -1;
1534             goto error;
1535           }
1536           if (vtor->value_string_invalid_utf16) {
1537             str = hivex_value_value (h, values[i], &t, &len);
1538             if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i], t, len, key, str) == -1)
1539               goto error;
1540             free (str); str = NULL;
1541           }
1542           break;
1543         }
1544         if (vtor->value_string &&
1545             vtor->value_string (h, opaque, node, values[i], t, len, key, str) == -1)
1546           goto error;
1547         free (str); str = NULL;
1548         break;
1549
1550       case hive_t_dword:
1551       case hive_t_dword_be: {
1552         int32_t i32 = hivex_value_dword (h, values[i]);
1553         if (vtor->value_dword &&
1554             vtor->value_dword (h, opaque, node, values[i], t, len, key, i32) == -1)
1555           goto error;
1556         break;
1557       }
1558
1559       case hive_t_qword: {
1560         int64_t i64 = hivex_value_qword (h, values[i]);
1561         if (vtor->value_qword &&
1562             vtor->value_qword (h, opaque, node, values[i], t, len, key, i64) == -1)
1563           goto error;
1564         break;
1565       }
1566
1567       case hive_t_binary:
1568         str = hivex_value_value (h, values[i], &t, &len);
1569         if (str == NULL) {
1570           ret = skip_bad ? 0 : -1;
1571           goto error;
1572         }
1573         if (t != hive_t_binary) {
1574           ret = skip_bad ? 0 : -1;
1575           goto error;
1576         }
1577         if (vtor->value_binary &&
1578             vtor->value_binary (h, opaque, node, values[i], t, len, key, str) == -1)
1579           goto error;
1580         free (str); str = NULL;
1581         break;
1582
1583       case hive_t_multiple_strings:
1584         strs = hivex_value_multiple_strings (h, values[i]);
1585         if (strs == NULL) {
1586           if (errno != EILSEQ && errno != EINVAL) {
1587             ret = skip_bad ? 0 : -1;
1588             goto error;
1589           }
1590           if (vtor->value_string_invalid_utf16) {
1591             str = hivex_value_value (h, values[i], &t, &len);
1592             if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i], t, len, key, str) == -1)
1593               goto error;
1594             free (str); str = NULL;
1595           }
1596           break;
1597         }
1598         if (vtor->value_multiple_strings &&
1599             vtor->value_multiple_strings (h, opaque, node, values[i], t, len, key, strs) == -1)
1600           goto error;
1601         free_strings (strs); strs = NULL;
1602         break;
1603
1604       case hive_t_resource_list:
1605       case hive_t_full_resource_description:
1606       case hive_t_resource_requirements_list:
1607       default:
1608         str = hivex_value_value (h, values[i], &t, &len);
1609         if (str == NULL) {
1610           ret = skip_bad ? 0 : -1;
1611           goto error;
1612         }
1613         if (vtor->value_other &&
1614             vtor->value_other (h, opaque, node, values[i], t, len, key, str) == -1)
1615           goto error;
1616         free (str); str = NULL;
1617         break;
1618       }
1619     }
1620
1621     free (key); key = NULL;
1622   }
1623
1624   children = hivex_node_children (h, node);
1625   if (children == NULL) {
1626     ret = skip_bad ? 0 : -1;
1627     goto error;
1628   }
1629
1630   for (i = 0; children[i] != 0; ++i) {
1631     if (h->msglvl >= 2)
1632       fprintf (stderr, "hivex__visit_node: %s: visiting subkey %d (0x%zx)\n",
1633                name, i, children[i]);
1634
1635     if (hivex__visit_node (h, children[i], vtor, unvisited, opaque, flags) == -1)
1636       goto error;
1637   }
1638
1639   if (vtor->node_end && vtor->node_end (h, opaque, node, name) == -1)
1640     goto error;
1641
1642   ret = 0;
1643
1644  error:
1645   free (name);
1646   free (values);
1647   free (children);
1648   free (key);
1649   free (str);
1650   free_strings (strs);
1651   return ret;
1652 }