source: trunk/lib/regfi.c @ 200

Last change on this file since 200 was 200, checked in by tim, 14 years ago

redesigned python key iterator and test script
updated documentation

  • Property svn:keywords set to Id
File size: 97.7 KB
Line 
1/*
2 * Copyright (C) 2005-2010 Timothy D. Morgan
3 * Copyright (C) 2005 Gerald (Jerry) Carter
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; version 3 of the License.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 *
18 * $Id: regfi.c 200 2010-06-03 05:08:20Z tim $
19 */
20
21/**
22 * @file
23 *
24 * Windows NT (and later) read-only registry library
25 *
26 * See @ref regfi.h for more information.
27 *
28 * Branched from Samba project Subversion repository, version #7470:
29 *   http://viewcvs.samba.org/cgi-bin/viewcvs.cgi/trunk/source/registry/regfio.c?rev=7470&view=auto
30 *
31 * Since then, it has been heavily rewritten, simplified, and improved.
32 */
33
34#include "regfi.h"
35
36
37/* Registry types mapping */
38const unsigned int regfi_num_reg_types = 12;
39static const char* regfi_type_names[] =
40  {"NONE", "SZ", "EXPAND_SZ", "BINARY", "DWORD", "DWORD_BE", "LINK",
41   "MULTI_SZ", "RSRC_LIST", "RSRC_DESC", "RSRC_REQ_LIST", "QWORD"};
42
43const char* regfi_encoding_names[] =
44  {"US-ASCII//TRANSLIT", "UTF-8//TRANSLIT", "UTF-16LE//TRANSLIT"};
45
46
47/* Ensures regfi_init runs only once */
48static pthread_once_t regfi_init_once = PTHREAD_ONCE_INIT;
49
50
51
52/******************************************************************************
53 ******************************************************************************/
54void regfi_log_free(void* ptr)
55{
56  REGFI_LOG* log_info = (REGFI_LOG*)ptr;
57 
58  if(log_info->messages != NULL)
59    free(log_info->messages);
60
61  talloc_free(log_info);
62}
63
64
65/******************************************************************************
66 ******************************************************************************/
67void regfi_init()
68{
69fprintf(stderr, "regfi_init called\n");
70  int err;
71  if((err = pthread_key_create(&regfi_log_key, regfi_log_free)) != 0)
72    fprintf(stderr, "ERROR: key_create: %s\n", strerror(err));
73  errno = err;
74}
75
76
77/******************************************************************************
78 ******************************************************************************/
79REGFI_LOG* regfi_log_new()
80{
81  int err;
82  REGFI_LOG* log_info = talloc(NULL, REGFI_LOG);
83  if(log_info == NULL)
84    return NULL;
85
86  log_info->msg_mask = REGFI_DEFAULT_LOG_MASK;
87  log_info->messages = NULL;
88
89  pthread_once(&regfi_init_once, regfi_init);
90
91  if((err = pthread_setspecific(regfi_log_key, log_info)) != 0)
92  {
93    fprintf(stderr, "ERROR: setspecific: %s\n", strerror(err));
94    goto fail;
95  }
96
97  return log_info;
98
99 fail:
100  talloc_free(log_info);
101  errno = err;
102  return NULL;
103}
104
105
106/******************************************************************************
107 ******************************************************************************/
108void regfi_log_add(uint16_t msg_type, const char* fmt, ...)
109{
110  /* XXX: Switch internal storage over to a linked list or stack.
111   *      Then add a regfi_log_get function that returns the list in some
112   *      convenient, user-friendly data structure.  regfi_log_get_str should
113   *      stick around and will simply smush the list into a big string when
114   *      it's called, rather than having messages smushed when they're first
115   *      written to the log.
116   */
117  uint32_t buf_size, buf_used;
118  char* new_msg;
119  REGFI_LOG* log_info;
120  va_list args;
121
122  log_info = (REGFI_LOG*)pthread_getspecific(regfi_log_key);
123  if(log_info == NULL && (log_info = regfi_log_new()) == NULL)
124    return;
125
126  if((log_info->msg_mask & msg_type) == 0)
127    return;
128
129  if(log_info->messages == NULL)
130    buf_used = 0;
131  else
132    buf_used = strlen(log_info->messages);
133 
134  buf_size = buf_used+strlen(fmt)+160;
135  new_msg = realloc(log_info->messages, buf_size);
136  if(new_msg == NULL)
137    /* XXX: should we report this? */
138    return;
139 
140  switch (msg_type)
141  {
142  case REGFI_LOG_INFO:
143    strcpy(new_msg+buf_used, "INFO: ");
144    buf_used += 6;
145    break;
146  case REGFI_LOG_WARN:
147    strcpy(new_msg+buf_used, "WARN: ");
148    buf_used += 6;
149    break;
150  case REGFI_LOG_ERROR:
151    strcpy(new_msg+buf_used, "ERROR: ");
152    buf_used += 7;
153    break;
154  }
155 
156  va_start(args, fmt);
157  vsnprintf(new_msg+buf_used, buf_size-buf_used, fmt, args);
158  va_end(args);
159  strncat(new_msg, "\n", buf_size-1);
160 
161  log_info->messages = new_msg;
162}
163
164
165/******************************************************************************
166 ******************************************************************************/
167char* regfi_log_get_str()
168{
169  char* ret_val;
170  REGFI_LOG* log_info = (REGFI_LOG*)pthread_getspecific(regfi_log_key);
171  if(log_info == NULL && (log_info = regfi_log_new()) == NULL)
172    return NULL;
173 
174  ret_val = log_info->messages;
175  log_info->messages = NULL;
176
177  return ret_val;
178}
179
180
181/******************************************************************************
182 ******************************************************************************/
183bool regfi_log_set_mask(uint16_t msg_mask)
184{
185  REGFI_LOG* log_info = (REGFI_LOG*)pthread_getspecific(regfi_log_key);
186  if(log_info == NULL && (log_info = regfi_log_new()) == NULL)
187  {
188      return false;
189  }
190
191  log_info->msg_mask = msg_mask;
192  return true;
193}
194
195
196/******************************************************************************
197 * Returns NULL for an invalid e
198 *****************************************************************************/
199static const char* regfi_encoding_int2str(REGFI_ENCODING e)
200{
201  if(e < REGFI_NUM_ENCODINGS)
202    return regfi_encoding_names[e];
203
204  return NULL;
205}
206
207
208/******************************************************************************
209 * Returns NULL for an invalid val
210 *****************************************************************************/
211const char* regfi_type_val2str(unsigned int val)
212{
213  if(val == REG_KEY)
214    return "KEY";
215 
216  if(val >= regfi_num_reg_types)
217    return NULL;
218 
219  return regfi_type_names[val];
220}
221
222
223/******************************************************************************
224 * Returns -1 on error
225 *****************************************************************************/
226int regfi_type_str2val(const char* str)
227{
228  int i;
229
230  if(strcmp("KEY", str) == 0)
231    return REG_KEY;
232
233  for(i=0; i < regfi_num_reg_types; i++)
234    if (strcmp(regfi_type_names[i], str) == 0) 
235      return i;
236
237  if(strcmp("DWORD_LE", str) == 0)
238    return REG_DWORD_LE;
239
240  return -1;
241}
242
243
244/* Security descriptor formatting functions  */
245
246const char* regfi_ace_type2str(uint8_t type)
247{
248  static const char* map[7] 
249    = {"ALLOW", "DENY", "AUDIT", "ALARM", 
250       "ALLOW CPD", "OBJ ALLOW", "OBJ DENY"};
251  if(type < 7)
252    return map[type];
253  else
254    /* XXX: would be nice to return the unknown integer value. 
255     *      However, as it is a const string, it can't be free()ed later on,
256     *      so that would need to change.
257     */
258    return "UNKNOWN";
259}
260
261
262/* XXX: need a better reference on the meaning of each flag. */
263/* For more info, see:
264 *   http://msdn2.microsoft.com/en-us/library/aa772242.aspx
265 */
266char* regfi_ace_flags2str(uint8_t flags)
267{
268  static const char* flag_map[32] = 
269    { "OI", /* Object Inherit */
270      "CI", /* Container Inherit */
271      "NP", /* Non-Propagate */
272      "IO", /* Inherit Only */
273      "IA", /* Inherited ACE */
274      NULL,
275      NULL,
276      NULL,
277    };
278
279  char* ret_val = malloc(35*sizeof(char));
280  char* fo = ret_val;
281  uint32_t i;
282  uint8_t f;
283
284  if(ret_val == NULL)
285    return NULL;
286
287  fo[0] = '\0';
288  if (!flags)
289    return ret_val;
290
291  for(i=0; i < 8; i++)
292  {
293    f = (1<<i);
294    if((flags & f) && (flag_map[i] != NULL))
295    {
296      strcpy(fo, flag_map[i]);
297      fo += strlen(flag_map[i]);
298      *(fo++) = ' ';
299      flags ^= f;
300    }
301  }
302 
303  /* Any remaining unknown flags are added at the end in hex. */
304  if(flags != 0)
305    sprintf(fo, "0x%.2X ", flags);
306
307  /* Chop off the last space if we've written anything to ret_val */
308  if(fo != ret_val)
309    fo[-1] = '\0';
310
311  return ret_val;
312}
313
314
315char* regfi_ace_perms2str(uint32_t perms)
316{
317  uint32_t i, p;
318  /* This is more than is needed by a fair margin. */
319  char* ret_val = malloc(350*sizeof(char));
320  char* r = ret_val;
321
322  /* Each represents one of 32 permissions bits.  NULL is for undefined/reserved bits.
323   * For more information, see:
324   *   http://msdn2.microsoft.com/en-gb/library/aa374892.aspx
325   *   http://msdn2.microsoft.com/en-gb/library/ms724878.aspx
326   */
327  static const char* perm_map[32] = 
328    {/* object-specific permissions (registry keys, in this case) */
329      "QRY_VAL",       /* KEY_QUERY_VALUE */
330      "SET_VAL",       /* KEY_SET_VALUE */
331      "CREATE_KEY",    /* KEY_CREATE_SUB_KEY */
332      "ENUM_KEYS",     /* KEY_ENUMERATE_SUB_KEYS */
333      "NOTIFY",        /* KEY_NOTIFY */
334      "CREATE_LNK",    /* KEY_CREATE_LINK - Reserved for system use. */
335      NULL,
336      NULL,
337      "WOW64_64",      /* KEY_WOW64_64KEY */
338      "WOW64_32",      /* KEY_WOW64_32KEY */
339      NULL,
340      NULL,
341      NULL,
342      NULL,
343      NULL,
344      NULL,
345      /* standard access rights */
346      "DELETE",        /* DELETE */
347      "R_CONT",        /* READ_CONTROL */
348      "W_DAC",         /* WRITE_DAC */
349      "W_OWNER",       /* WRITE_OWNER */
350      "SYNC",          /* SYNCHRONIZE - Shouldn't be set in registries */
351      NULL,
352      NULL,
353      NULL,
354      /* other generic */
355      "SYS_SEC",       /* ACCESS_SYSTEM_SECURITY */
356      "MAX_ALLWD",     /* MAXIMUM_ALLOWED */
357      NULL,
358      NULL,
359      "GEN_A",         /* GENERIC_ALL */
360      "GEN_X",         /* GENERIC_EXECUTE */
361      "GEN_W",         /* GENERIC_WRITE */
362      "GEN_R",         /* GENERIC_READ */
363    };
364
365
366  if(ret_val == NULL)
367    return NULL;
368
369  r[0] = '\0';
370  for(i=0; i < 32; i++)
371  {
372    p = (1<<i);
373    if((perms & p) && (perm_map[i] != NULL))
374    {
375      strcpy(r, perm_map[i]);
376      r += strlen(perm_map[i]);
377      *(r++) = ' ';
378      perms ^= p;
379    }
380  }
381 
382  /* Any remaining unknown permission bits are added at the end in hex. */
383  if(perms != 0)
384    sprintf(r, "0x%.8X ", perms);
385
386  /* Chop off the last space if we've written anything to ret_val */
387  if(r != ret_val)
388    r[-1] = '\0';
389
390  return ret_val;
391}
392
393
394char* regfi_sid2str(WINSEC_DOM_SID* sid)
395{
396  uint32_t i, size = WINSEC_MAX_SUBAUTHS*11 + 24;
397  uint32_t left = size;
398  uint8_t comps = sid->num_auths;
399  char* ret_val = malloc(size);
400 
401  if(ret_val == NULL)
402    return NULL;
403
404  if(comps > WINSEC_MAX_SUBAUTHS)
405    comps = WINSEC_MAX_SUBAUTHS;
406
407  left -= sprintf(ret_val, "S-%u-%u", sid->sid_rev_num, sid->id_auth[5]);
408
409  for (i = 0; i < comps; i++) 
410    left -= snprintf(ret_val+(size-left), left, "-%u", sid->sub_auths[i]);
411
412  return ret_val;
413}
414
415
416char* regfi_get_acl(WINSEC_ACL* acl)
417{
418  uint32_t i, extra, size = 0;
419  const char* type_str;
420  char* flags_str;
421  char* perms_str;
422  char* sid_str;
423  char* ace_delim = "";
424  char* ret_val = NULL;
425  char* tmp_val = NULL;
426  bool failed = false;
427  char field_delim = ':';
428
429  for (i = 0; i < acl->num_aces && !failed; i++)
430  {
431    sid_str = regfi_sid2str(acl->aces[i]->trustee);
432    type_str = regfi_ace_type2str(acl->aces[i]->type);
433    perms_str = regfi_ace_perms2str(acl->aces[i]->access_mask);
434    flags_str = regfi_ace_flags2str(acl->aces[i]->flags);
435   
436    if(flags_str != NULL && perms_str != NULL 
437       && type_str != NULL && sid_str != NULL)
438    {
439      /* XXX: this is slow */
440      extra = strlen(sid_str) + strlen(type_str) 
441        + strlen(perms_str) + strlen(flags_str) + 5;
442      tmp_val = realloc(ret_val, size+extra);
443
444      if(tmp_val == NULL)
445      {
446        free(ret_val);
447        ret_val = NULL;
448        failed = true;
449      }
450      else
451      {
452        ret_val = tmp_val;
453        size += sprintf(ret_val+size, "%s%s%c%s%c%s%c%s",
454                        ace_delim,sid_str,
455                        field_delim,type_str,
456                        field_delim,perms_str,
457                        field_delim,flags_str);
458        ace_delim = "|";
459      }
460    }
461    else
462      failed = true;
463
464    if(sid_str != NULL)
465      free(sid_str);
466    if(sid_str != NULL)
467      free(perms_str);
468    if(sid_str != NULL)
469      free(flags_str);
470  }
471
472  return ret_val;
473}
474
475
476char* regfi_get_sacl(WINSEC_DESC *sec_desc)
477{
478  if (sec_desc->sacl)
479    return regfi_get_acl(sec_desc->sacl);
480  else
481    return NULL;
482}
483
484
485char* regfi_get_dacl(WINSEC_DESC *sec_desc)
486{
487  if (sec_desc->dacl)
488    return regfi_get_acl(sec_desc->dacl);
489  else
490    return NULL;
491}
492
493
494char* regfi_get_owner(WINSEC_DESC *sec_desc)
495{
496  return regfi_sid2str(sec_desc->owner_sid);
497}
498
499
500char* regfi_get_group(WINSEC_DESC *sec_desc)
501{
502  return regfi_sid2str(sec_desc->grp_sid);
503}
504
505
506bool regfi_read_lock(REGFI_FILE* file, pthread_rwlock_t* lock, const char* context)
507{
508  int lock_ret = pthread_rwlock_rdlock(lock);
509  if(lock_ret != 0)
510  {
511    regfi_log_add(REGFI_LOG_ERROR, "Error obtaining read lock in"
512                      "%s due to: %s\n", context, strerror(lock_ret));
513    return false;
514  }
515
516  return true;
517}
518
519
520bool regfi_write_lock(REGFI_FILE* file, pthread_rwlock_t* lock, const char* context)
521{
522  int lock_ret = pthread_rwlock_wrlock(lock);
523  if(lock_ret != 0)
524  {
525    regfi_log_add(REGFI_LOG_ERROR, "Error obtaining write lock in"
526                      "%s due to: %s\n", context, strerror(lock_ret));
527    return false;
528  }
529
530  return true;
531}
532
533
534bool regfi_rw_unlock(REGFI_FILE* file, pthread_rwlock_t* lock, const char* context)
535{
536  int lock_ret = pthread_rwlock_unlock(lock);
537  if(lock_ret != 0)
538  {
539    regfi_log_add(REGFI_LOG_ERROR, "Error releasing lock in"
540                      "%s due to: %s\n", context, strerror(lock_ret));
541    return false;
542  }
543
544  return true;
545}
546
547
548bool regfi_lock(REGFI_FILE* file, pthread_mutex_t* lock, const char* context)
549{
550  int lock_ret = pthread_mutex_lock(lock);
551  if(lock_ret != 0)
552  {
553    regfi_log_add(REGFI_LOG_ERROR, "Error obtaining mutex lock in"
554                      "%s due to: %s\n", context, strerror(lock_ret));
555    return false;
556  }
557
558  return true;
559}
560
561
562bool regfi_unlock(REGFI_FILE* file, pthread_mutex_t* lock, const char* context)
563{
564  int lock_ret = pthread_mutex_unlock(lock);
565  if(lock_ret != 0)
566  {
567    regfi_log_add(REGFI_LOG_ERROR, "Error releasing mutex lock in"
568                      "%s due to: %s\n", context, strerror(lock_ret));
569    return false;
570  }
571
572  return true;
573}
574
575
576off_t regfi_raw_seek(REGFI_RAW_FILE* self, off_t offset, int whence)
577{
578  return lseek(*(int*)self->state, offset, whence);
579}
580
581ssize_t regfi_raw_read(REGFI_RAW_FILE* self, void* buf, size_t count)
582{
583  return read(*(int*)self->state, buf, count);
584}
585
586
587/*****************************************************************************
588 * Convenience function to wrap up the ugly callback stuff
589 *****************************************************************************/
590off_t regfi_seek(REGFI_RAW_FILE* file_cb, off_t offset, int whence)
591{
592  return file_cb->seek(file_cb, offset, whence);
593}
594
595
596/*****************************************************************************
597 * This function is just like read(2), except that it continues to
598 * re-try reading from the file descriptor if EINTR or EAGAIN is received. 
599 * regfi_read will attempt to read length bytes from the file and write them to
600 * buf.
601 *
602 * On success, 0 is returned.  Upon failure, an errno code is returned.
603 *
604 * The number of bytes successfully read is returned through the length
605 * parameter by reference.  If both the return value and length parameter are
606 * returned as 0, then EOF was encountered immediately
607 *****************************************************************************/
608uint32_t regfi_read(REGFI_RAW_FILE* file_cb, uint8_t* buf, uint32_t* length)
609{
610  uint32_t rsize = 0;
611  uint32_t rret = 0;
612
613  do
614  {
615    rret = file_cb->read(file_cb, buf + rsize, *length - rsize);
616    if(rret > 0)
617      rsize += rret;
618  }while(*length - rsize > 0 
619         && (rret > 0 || (rret == -1 && (errno == EAGAIN || errno == EINTR))));
620 
621  *length = rsize;
622  if (rret == -1 && errno != EINTR && errno != EAGAIN)
623    return errno;
624
625  return 0;
626}
627
628
629/*****************************************************************************
630 *
631 *****************************************************************************/
632bool regfi_parse_cell(REGFI_RAW_FILE* file_cb, uint32_t offset, uint8_t* hdr, 
633                      uint32_t hdr_len, uint32_t* cell_length, bool* unalloc)
634{
635  uint32_t length;
636  int32_t raw_length;
637  uint8_t tmp[4];
638
639  if(regfi_seek(file_cb, offset, SEEK_SET) == -1)
640    return false;
641
642  length = 4;
643  if((regfi_read(file_cb, tmp, &length) != 0) || length != 4)
644    return false;
645  raw_length = IVALS(tmp, 0);
646
647  if(raw_length < 0)
648  {
649    (*cell_length) = raw_length*(-1);
650    (*unalloc) = false;
651  }
652  else
653  {
654    (*cell_length) = raw_length;
655    (*unalloc) = true;
656  }
657
658  if(*cell_length - 4 < hdr_len)
659    return false;
660
661  if(hdr_len > 0)
662  {
663    length = hdr_len;
664    if((regfi_read(file_cb, hdr, &length) != 0) || length != hdr_len)
665      return false;
666  }
667
668  return true;
669}
670
671
672/******************************************************************************
673 * Given an offset and an hbin, is the offset within that hbin?
674 * The offset is a virtual file offset.
675 ******************************************************************************/
676static bool regfi_offset_in_hbin(const REGFI_HBIN* hbin, uint32_t voffset)
677{
678  if(!hbin)
679    return false;
680
681  if((voffset > hbin->first_hbin_off) 
682     && (voffset < (hbin->first_hbin_off + hbin->block_size)))
683    return true;
684               
685  return false;
686}
687
688
689
690/******************************************************************************
691 * Provide a physical offset and receive the correpsonding HBIN
692 * block for it.  NULL if one doesn't exist.
693 ******************************************************************************/
694const REGFI_HBIN* regfi_lookup_hbin(REGFI_FILE* file, uint32_t offset)
695{
696  return (const REGFI_HBIN*)range_list_find_data(file->hbins, offset);
697}
698
699
700/******************************************************************************
701 * Calculate the largest possible cell size given a physical offset.
702 * Largest size is based on the HBIN the offset is currently a member of.
703 * Returns negative values on error.
704 * (Since cells can only be ~2^31 in size, this works out.)
705 ******************************************************************************/
706int32_t regfi_calc_maxsize(REGFI_FILE* file, uint32_t offset)
707{
708  const REGFI_HBIN* hbin = regfi_lookup_hbin(file, offset);
709  if(hbin == NULL)
710    return -1;
711
712  return (hbin->block_size + hbin->file_off) - offset;
713}
714
715
716/******************************************************************************
717 ******************************************************************************/
718REGFI_SUBKEY_LIST* regfi_load_subkeylist(REGFI_FILE* file, uint32_t offset, 
719                                         uint32_t num_keys, uint32_t max_size, 
720                                         bool strict)
721{
722  REGFI_SUBKEY_LIST* ret_val;
723
724  ret_val = regfi_load_subkeylist_aux(file, offset, max_size, strict, 
725                                      REGFI_MAX_SUBKEY_DEPTH);
726  if(ret_val == NULL)
727  {
728    regfi_log_add(REGFI_LOG_WARN, "Failed to load subkey list at"
729                      " offset 0x%.8X.", offset);
730    return NULL;
731  }
732
733  if(num_keys != ret_val->num_keys)
734  {
735    /*  Not sure which should be authoritative, the number from the
736     *  NK record, or the number in the subkey list.  Just emit a warning for
737     *  now if they don't match.
738     */
739    regfi_log_add(REGFI_LOG_WARN, "Number of subkeys listed in parent"
740                      " (%d) did not match number found in subkey list/tree (%d)"
741                      " while parsing subkey list/tree at offset 0x%.8X.", 
742                      num_keys, ret_val->num_keys, offset);
743  }
744
745  return ret_val;
746}
747
748
749/******************************************************************************
750 ******************************************************************************/
751REGFI_SUBKEY_LIST* regfi_load_subkeylist_aux(REGFI_FILE* file, uint32_t offset, 
752                                             uint32_t max_size, bool strict,
753                                             uint8_t depth_left)
754{
755  REGFI_SUBKEY_LIST* ret_val;
756  REGFI_SUBKEY_LIST** sublists;
757  uint32_t i, num_sublists, off;
758  int32_t sublist_maxsize;
759
760  if(depth_left == 0)
761  {
762    regfi_log_add(REGFI_LOG_WARN, "Maximum depth reached"
763                      " while parsing subkey list/tree at offset 0x%.8X.", 
764                      offset);
765    return NULL;
766  }
767
768  ret_val = regfi_parse_subkeylist(file, offset, max_size, strict);
769  if(ret_val == NULL)
770    return NULL;
771
772  if(ret_val->recursive_type)
773  {
774    num_sublists = ret_val->num_children;
775    sublists = (REGFI_SUBKEY_LIST**)malloc(num_sublists
776                                           * sizeof(REGFI_SUBKEY_LIST*));
777    for(i=0; i < num_sublists; i++)
778    {
779      off = ret_val->elements[i].offset + REGFI_REGF_SIZE;
780
781      sublist_maxsize = regfi_calc_maxsize(file, off);
782      if(sublist_maxsize < 0)
783        sublists[i] = NULL;
784      else
785        sublists[i] = regfi_load_subkeylist_aux(file, off, sublist_maxsize, 
786                                                strict, depth_left-1);
787    }
788    talloc_free(ret_val);
789
790    return regfi_merge_subkeylists(num_sublists, sublists, strict);
791  }
792
793  return ret_val;
794}
795
796
797/******************************************************************************
798 ******************************************************************************/
799REGFI_SUBKEY_LIST* regfi_parse_subkeylist(REGFI_FILE* file, uint32_t offset, 
800                                          uint32_t max_size, bool strict)
801{
802  REGFI_SUBKEY_LIST* ret_val;
803  uint32_t i, cell_length, length, elem_size, read_len;
804  uint8_t* elements = NULL;
805  uint8_t buf[REGFI_SUBKEY_LIST_MIN_LEN];
806  bool unalloc;
807  bool recursive_type;
808
809  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_subkeylist"))
810     goto fail;
811
812  if(!regfi_parse_cell(file->cb, offset, buf, REGFI_SUBKEY_LIST_MIN_LEN,
813                       &cell_length, &unalloc))
814  {
815    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while "
816                      "parsing subkey-list at offset 0x%.8X.", offset);
817    goto fail_locked;
818  }
819
820  if(cell_length > max_size)
821  {
822    regfi_log_add(REGFI_LOG_WARN, "Cell size longer than max_size"
823                      " while parsing subkey-list at offset 0x%.8X.", offset);
824    if(strict)
825      goto fail_locked;
826    cell_length = max_size & 0xFFFFFFF8;
827  }
828
829  recursive_type = false;
830  if(buf[0] == 'r' && buf[1] == 'i')
831  {
832    recursive_type = true;
833    elem_size = sizeof(uint32_t);
834  }
835  else if(buf[0] == 'l' && buf[1] == 'i')
836    elem_size = sizeof(uint32_t);
837  else if((buf[0] == 'l') && (buf[1] == 'f' || buf[1] == 'h'))
838    elem_size = sizeof(REGFI_SUBKEY_LIST_ELEM);
839  else
840  {
841    regfi_log_add(REGFI_LOG_ERROR, "Unknown magic number"
842                      " (0x%.2X, 0x%.2X) encountered while parsing"
843                      " subkey-list at offset 0x%.8X.", buf[0], buf[1], offset);
844    goto fail_locked;
845  }
846
847  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
848  if(ret_val == NULL)
849    goto fail_locked;
850
851  ret_val->offset = offset;
852  ret_val->cell_size = cell_length;
853  ret_val->magic[0] = buf[0];
854  ret_val->magic[1] = buf[1];
855  ret_val->recursive_type = recursive_type;
856  ret_val->num_children = SVAL(buf, 0x2);
857
858  if(!recursive_type)
859    ret_val->num_keys = ret_val->num_children;
860
861  length = elem_size*ret_val->num_children;
862  if(cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t) < length)
863  {
864    regfi_log_add(REGFI_LOG_WARN, "Number of elements too large for"
865                      " cell while parsing subkey-list at offset 0x%.8X.", 
866                      offset);
867    if(strict)
868      goto fail_locked;
869    length = cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t);
870  }
871
872  ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM, 
873                                   ret_val->num_children);
874  if(ret_val->elements == NULL)
875    goto fail_locked;
876
877  elements = (uint8_t*)malloc(length);
878  if(elements == NULL)
879    goto fail_locked;
880
881  read_len = length;
882  if(regfi_read(file->cb, elements, &read_len) != 0 || read_len!=length)
883    goto fail_locked;
884
885  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_subkeylist"))
886     goto fail;
887
888  if(elem_size == sizeof(uint32_t))
889  {
890    for (i=0; i < ret_val->num_children; i++)
891    {
892      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
893      ret_val->elements[i].hash = 0;
894    }
895  }
896  else
897  {
898    for (i=0; i < ret_val->num_children; i++)
899    {
900      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
901      ret_val->elements[i].hash = IVAL(elements, i*elem_size+4);
902    }
903  }
904  free(elements);
905
906  return ret_val;
907
908 fail_locked:
909  regfi_unlock(file, &file->cb_lock, "regfi_parse_subkeylist");
910 fail:
911  if(elements != NULL)
912    free(elements);
913  talloc_free(ret_val);
914  return NULL;
915}
916
917
918/*******************************************************************
919 *******************************************************************/
920REGFI_SUBKEY_LIST* regfi_merge_subkeylists(uint16_t num_lists, 
921                                           REGFI_SUBKEY_LIST** lists,
922                                           bool strict)
923{
924  uint32_t i,j,k;
925  REGFI_SUBKEY_LIST* ret_val;
926
927  if(lists == NULL)
928    return NULL;
929  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
930
931  if(ret_val == NULL)
932    return NULL;
933 
934  /* Obtain total number of elements */
935  ret_val->num_keys = 0;
936  for(i=0; i < num_lists; i++)
937  {
938    if(lists[i] != NULL)
939      ret_val->num_keys += lists[i]->num_children;
940  }
941  ret_val->num_children = ret_val->num_keys;
942
943  if(ret_val->num_keys > 0)
944  {
945    ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM,
946                                     ret_val->num_keys);
947    k=0;
948
949    if(ret_val->elements != NULL)
950    {
951      for(i=0; i < num_lists; i++)
952      {
953        if(lists[i] != NULL)
954        {
955          for(j=0; j < lists[i]->num_keys; j++)
956          {
957            ret_val->elements[k].hash = lists[i]->elements[j].hash;
958            ret_val->elements[k++].offset = lists[i]->elements[j].offset;
959          }
960        }
961      }
962    }
963  }
964 
965  for(i=0; i < num_lists; i++)
966    talloc_free(lists[i]);
967  free(lists);
968
969  return ret_val;
970}
971
972
973/******************************************************************************
974 *
975 ******************************************************************************/
976REGFI_SK_REC* regfi_parse_sk(REGFI_FILE* file, uint32_t offset, uint32_t max_size, 
977                             bool strict)
978{
979  REGFI_SK_REC* ret_val = NULL;
980  uint8_t* sec_desc_buf = NULL;
981  uint32_t cell_length, length;
982  uint8_t sk_header[REGFI_SK_MIN_LENGTH];
983  bool unalloc = false;
984
985  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_sk"))
986     goto fail;
987
988  if(!regfi_parse_cell(file->cb, offset, sk_header, REGFI_SK_MIN_LENGTH,
989                       &cell_length, &unalloc))
990  {
991    regfi_log_add(REGFI_LOG_WARN, "Could not parse SK record cell"
992                      " at offset 0x%.8X.", offset);
993    goto fail_locked;
994  }
995   
996  if(sk_header[0] != 's' || sk_header[1] != 'k')
997  {
998    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch in parsing"
999                      " SK record at offset 0x%.8X.", offset);
1000    goto fail_locked;
1001  }
1002
1003  ret_val = talloc(NULL, REGFI_SK_REC);
1004  if(ret_val == NULL)
1005    goto fail_locked;
1006
1007  ret_val->offset = offset;
1008  /* XXX: Is there a way to be more conservative (shorter) with
1009   *      cell length when cell is unallocated?
1010   */
1011  ret_val->cell_size = cell_length;
1012
1013  if(ret_val->cell_size > max_size)
1014    ret_val->cell_size = max_size & 0xFFFFFFF8;
1015  if((ret_val->cell_size < REGFI_SK_MIN_LENGTH) 
1016     || (strict && (ret_val->cell_size & 0x00000007) != 0))
1017  {
1018    regfi_log_add(REGFI_LOG_WARN, "Invalid cell size found while"
1019                      " parsing SK record at offset 0x%.8X.", offset);
1020    goto fail_locked;
1021  }
1022
1023  ret_val->magic[0] = sk_header[0];
1024  ret_val->magic[1] = sk_header[1];
1025
1026  ret_val->unknown_tag = SVAL(sk_header, 0x2);
1027  ret_val->prev_sk_off = IVAL(sk_header, 0x4);
1028  ret_val->next_sk_off = IVAL(sk_header, 0x8);
1029  ret_val->ref_count = IVAL(sk_header, 0xC);
1030  ret_val->desc_size = IVAL(sk_header, 0x10);
1031
1032  if((ret_val->prev_sk_off & 0x00000007) != 0
1033     || (ret_val->next_sk_off & 0x00000007) != 0)
1034  {
1035    regfi_log_add(REGFI_LOG_WARN, "SK record's next/previous offsets"
1036                      " are not a multiple of 8 while parsing SK record at"
1037                      " offset 0x%.8X.", offset);
1038    goto fail_locked;
1039  }
1040
1041  if(ret_val->desc_size + REGFI_SK_MIN_LENGTH > ret_val->cell_size)
1042  {
1043    regfi_log_add(REGFI_LOG_WARN, "Security descriptor too large for"
1044                      " cell while parsing SK record at offset 0x%.8X.", 
1045                      offset);
1046    goto fail_locked;
1047  }
1048
1049  sec_desc_buf = (uint8_t*)malloc(ret_val->desc_size);
1050  if(sec_desc_buf == NULL)
1051    goto fail_locked;
1052
1053  length = ret_val->desc_size;
1054  if(regfi_read(file->cb, sec_desc_buf, &length) != 0 
1055     || length != ret_val->desc_size)
1056  {
1057    regfi_log_add(REGFI_LOG_ERROR, "Failed to read security"
1058                      " descriptor while parsing SK record at offset 0x%.8X.",
1059                      offset);
1060    goto fail_locked;
1061  }
1062
1063  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_sk"))
1064     goto fail;
1065
1066  if(!(ret_val->sec_desc = winsec_parse_desc(ret_val, sec_desc_buf, 
1067                                                   ret_val->desc_size)))
1068  {
1069    regfi_log_add(REGFI_LOG_ERROR, "Failed to parse security"
1070                      " descriptor while parsing SK record at offset 0x%.8X.",
1071                      offset);
1072    goto fail;
1073  }
1074
1075  free(sec_desc_buf);
1076  return ret_val;
1077
1078 fail_locked:
1079  regfi_unlock(file, &file->cb_lock, "regfi_parse_sk");
1080 fail:
1081  if(sec_desc_buf != NULL)
1082    free(sec_desc_buf);
1083  talloc_free(ret_val);
1084  return NULL;
1085}
1086
1087
1088REGFI_VALUE_LIST* regfi_parse_valuelist(REGFI_FILE* file, uint32_t offset, 
1089                                        uint32_t num_values, bool strict)
1090{
1091  REGFI_VALUE_LIST* ret_val;
1092  uint32_t i, cell_length, length, read_len;
1093  bool unalloc;
1094
1095  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_valuelist"))
1096     goto fail;
1097
1098  if(!regfi_parse_cell(file->cb, offset, NULL, 0, &cell_length, &unalloc))
1099  {
1100    regfi_log_add(REGFI_LOG_ERROR, "Failed to read cell header"
1101                      " while parsing value list at offset 0x%.8X.", offset);
1102    goto fail_locked;
1103  }
1104
1105  if((cell_length & 0x00000007) != 0)
1106  {
1107    regfi_log_add(REGFI_LOG_WARN, "Cell length not a multiple of 8"
1108                      " while parsing value list at offset 0x%.8X.", offset);
1109    if(strict)
1110      goto fail_locked;
1111    cell_length = cell_length & 0xFFFFFFF8;
1112  }
1113
1114  if((num_values * sizeof(uint32_t)) > cell_length-sizeof(uint32_t))
1115  {
1116    regfi_log_add(REGFI_LOG_WARN, "Too many values found"
1117                      " while parsing value list at offset 0x%.8X.", offset);
1118    if(strict)
1119      goto fail_locked;
1120    num_values = cell_length/sizeof(uint32_t) - sizeof(uint32_t);
1121  }
1122
1123  read_len = num_values*sizeof(uint32_t);
1124  ret_val = talloc(NULL, REGFI_VALUE_LIST);
1125  if(ret_val == NULL)
1126    goto fail_locked;
1127
1128  ret_val->elements = (REGFI_VALUE_LIST_ELEM*)talloc_size(ret_val, read_len);
1129  if(ret_val->elements == NULL)
1130    goto fail_locked;
1131
1132  ret_val->num_values = num_values;
1133
1134  length = read_len;
1135  if((regfi_read(file->cb, (uint8_t*)ret_val->elements, &length) != 0) 
1136     || length != read_len)
1137  {
1138    regfi_log_add(REGFI_LOG_ERROR, "Failed to read value pointers"
1139                      " while parsing value list at offset 0x%.8X.", offset);
1140    goto fail_locked;
1141  }
1142 
1143  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_valuelist"))
1144     goto fail;
1145
1146  for(i=0; i < num_values; i++)
1147  {
1148    /* Fix endianness */
1149    ret_val->elements[i] = IVAL(&ret_val->elements[i], 0);
1150
1151    /* Validate the first num_values values to ensure they make sense */
1152    if(strict)
1153    {
1154      /* XXX: Need to revisit this file length check when we start dealing
1155       *      with partial files. */
1156      if((ret_val->elements[i] + REGFI_REGF_SIZE > file->file_length)
1157         || ((ret_val->elements[i] & 0x00000007) != 0))
1158      {
1159        regfi_log_add(REGFI_LOG_WARN, "Invalid value pointer"
1160                          " (0x%.8X) found while parsing value list at offset"
1161                          " 0x%.8X.", ret_val->elements[i], offset);
1162        goto fail;
1163      }
1164    }
1165  }
1166
1167  return ret_val;
1168
1169 fail_locked:
1170  regfi_unlock(file, &file->cb_lock, "regfi_parse_valuelist");
1171 fail:
1172  talloc_free(ret_val);
1173  return NULL;
1174}
1175
1176
1177void regfi_interpret_valuename(REGFI_FILE* file, REGFI_VK_REC* vk, 
1178                               REGFI_ENCODING output_encoding, bool strict)
1179{
1180  /* XXX: Registry value names are supposedly limited to 16383 characters
1181   *      according to:
1182   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1183   *      Might want to emit a warning if this is exceeded. 
1184   *      It is expected that "characters" could be variable width.
1185   *      Also, it may be useful to use this information to limit false positives
1186   *      when recovering deleted VK records.
1187   */
1188  int32_t tmp_size;
1189  REGFI_ENCODING from_encoding = (vk->flags & REGFI_VK_FLAG_ASCIINAME)
1190    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
1191
1192  if(from_encoding == output_encoding)
1193  {
1194    vk->valuename_raw = talloc_realloc(vk, vk->valuename_raw,
1195                                            uint8_t, vk->name_length+1);
1196    vk->valuename_raw[vk->name_length] = '\0';
1197    vk->valuename = (char*)vk->valuename_raw;
1198  }
1199  else
1200  {
1201    vk->valuename = talloc_array(vk, char, vk->name_length+1);
1202    if(vk->valuename == NULL)
1203    {
1204      talloc_free(vk);
1205      return;
1206    }
1207
1208    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1209                                  regfi_encoding_int2str(output_encoding),
1210                                  vk->valuename_raw, vk->valuename,
1211                                  vk->name_length, vk->name_length+1);
1212    if(tmp_size < 0)
1213    {
1214      regfi_log_add(REGFI_LOG_WARN, "Error occurred while converting"
1215                        " valuename to encoding %s.  Error message: %s",
1216                        regfi_encoding_int2str(output_encoding), 
1217                        strerror(-tmp_size));
1218      talloc_free(vk->valuename);
1219      vk->valuename = NULL;
1220    }
1221  }
1222}
1223
1224
1225/******************************************************************************
1226 ******************************************************************************/
1227REGFI_VK_REC* regfi_load_value(REGFI_FILE* file, uint32_t offset, 
1228                               REGFI_ENCODING output_encoding, bool strict)
1229{
1230  REGFI_VK_REC* ret_val = NULL;
1231  int32_t max_size;
1232
1233  max_size = regfi_calc_maxsize(file, offset);
1234  if(max_size < 0)
1235    return NULL;
1236 
1237  ret_val = regfi_parse_vk(file, offset, max_size, strict);
1238  if(ret_val == NULL)
1239    return NULL;
1240
1241  regfi_interpret_valuename(file, ret_val, output_encoding, strict);
1242
1243  return ret_val;
1244}
1245
1246
1247/******************************************************************************
1248 * If !strict, the list may contain NULLs, VK records may point to NULL.
1249 ******************************************************************************/
1250REGFI_VALUE_LIST* regfi_load_valuelist(REGFI_FILE* file, uint32_t offset, 
1251                                       uint32_t num_values, uint32_t max_size,
1252                                       bool strict)
1253{
1254  uint32_t usable_num_values;
1255
1256  if((num_values+1) * sizeof(uint32_t) > max_size)
1257  {
1258    regfi_log_add(REGFI_LOG_WARN, "Number of values indicated by"
1259                      " parent key (%d) would cause cell to straddle HBIN"
1260                      " boundary while loading value list at offset"
1261                      " 0x%.8X.", num_values, offset);
1262    if(strict)
1263      return NULL;
1264    usable_num_values = max_size/sizeof(uint32_t) - sizeof(uint32_t);
1265  }
1266  else
1267    usable_num_values = num_values;
1268
1269  return regfi_parse_valuelist(file, offset, usable_num_values, strict);
1270}
1271
1272
1273void regfi_interpret_keyname(REGFI_FILE* file, REGFI_NK_REC* nk, 
1274                             REGFI_ENCODING output_encoding, bool strict)
1275{
1276  /* XXX: Registry key names are supposedly limited to 255 characters according to:
1277   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1278   *      Might want to emit a warning if this is exceeded. 
1279   *      It is expected that "characters" could be variable width.
1280   *      Also, it may be useful to use this information to limit false positives
1281   *      when recovering deleted NK records.
1282   */
1283  int32_t tmp_size;
1284  REGFI_ENCODING from_encoding = (nk->flags & REGFI_NK_FLAG_ASCIINAME) 
1285    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
1286 
1287  if(from_encoding == output_encoding)
1288  {
1289    nk->keyname_raw = talloc_realloc(nk, nk->keyname_raw, uint8_t, nk->name_length+1);
1290    nk->keyname_raw[nk->name_length] = '\0';
1291    nk->keyname = (char*)nk->keyname_raw;
1292  }
1293  else
1294  {
1295    nk->keyname = talloc_array(nk, char, nk->name_length+1);
1296    if(nk->keyname == NULL)
1297    {
1298      talloc_free(nk);
1299      return;
1300    }
1301
1302    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1303                                  regfi_encoding_int2str(output_encoding),
1304                                  nk->keyname_raw, nk->keyname,
1305                                  nk->name_length, nk->name_length+1);
1306    if(tmp_size < 0)
1307    {
1308      regfi_log_add(REGFI_LOG_WARN, "Error occurred while converting"
1309                        " keyname to encoding %s.  Error message: %s",
1310                        regfi_encoding_int2str(output_encoding), 
1311                        strerror(-tmp_size));
1312      talloc_free(nk->keyname);
1313      nk->keyname = NULL;
1314    }
1315  }
1316}
1317
1318
1319/******************************************************************************
1320 *
1321 ******************************************************************************/
1322REGFI_NK_REC* regfi_load_key(REGFI_FILE* file, uint32_t offset, 
1323                             REGFI_ENCODING output_encoding, bool strict)
1324{
1325  REGFI_NK_REC* nk;
1326  uint32_t off;
1327  int32_t max_size;
1328
1329  max_size = regfi_calc_maxsize(file, offset);
1330  if (max_size < 0) 
1331    return NULL;
1332
1333  /* get the initial nk record */
1334  if((nk = regfi_parse_nk(file, offset, max_size, true)) == NULL)
1335  {
1336    regfi_log_add(REGFI_LOG_ERROR, "Could not load NK record at"
1337                  " offset 0x%.8X.", offset);
1338    return NULL;
1339  }
1340
1341  regfi_interpret_keyname(file, nk, output_encoding, strict);
1342
1343  /* get value list */
1344  if(nk->num_values && (nk->values_off!=REGFI_OFFSET_NONE)) 
1345  {
1346    off = nk->values_off + REGFI_REGF_SIZE;
1347    max_size = regfi_calc_maxsize(file, off);
1348    if(max_size < 0)
1349    {
1350      if(strict)
1351      {
1352        talloc_free(nk);
1353        return NULL;
1354      }
1355      else
1356        nk->values = NULL;
1357
1358    }
1359    else
1360    {
1361      nk->values = regfi_load_valuelist(file, off, nk->num_values, 
1362                                        max_size, true);
1363      if(nk->values == NULL)
1364      {
1365        regfi_log_add(REGFI_LOG_WARN, "Could not load value list"
1366                      " for NK record at offset 0x%.8X.", offset);
1367        if(strict)
1368        {
1369          talloc_free(nk);
1370          return NULL;
1371        }
1372      }
1373      talloc_steal(nk, nk->values);
1374    }
1375  }
1376
1377  /* now get subkey list */
1378  if(nk->num_subkeys && (nk->subkeys_off != REGFI_OFFSET_NONE)) 
1379  {
1380    off = nk->subkeys_off + REGFI_REGF_SIZE;
1381    max_size = regfi_calc_maxsize(file, off);
1382    if(max_size < 0) 
1383    {
1384      if(strict)
1385      {
1386        talloc_free(nk);
1387        return NULL;
1388      }
1389      else
1390        nk->subkeys = NULL;
1391    }
1392    else
1393    {
1394      nk->subkeys = regfi_load_subkeylist(file, off, nk->num_subkeys,
1395                                          max_size, true);
1396
1397      if(nk->subkeys == NULL)
1398      {
1399        regfi_log_add(REGFI_LOG_WARN, "Could not load subkey list"
1400                      " while parsing NK record at offset 0x%.8X.", offset);
1401        nk->num_subkeys = 0;
1402      }
1403      talloc_steal(nk, nk->subkeys);
1404    }
1405  }
1406
1407  return nk;
1408}
1409
1410
1411/******************************************************************************
1412 ******************************************************************************/
1413const REGFI_SK_REC* regfi_load_sk(REGFI_FILE* file, uint32_t offset, bool strict)
1414{
1415  REGFI_SK_REC* ret_val = NULL;
1416  int32_t max_size;
1417  void* failure_ptr = NULL;
1418 
1419  max_size = regfi_calc_maxsize(file, offset);
1420  if(max_size < 0)
1421    return NULL;
1422
1423  if(file->sk_cache == NULL)
1424    return regfi_parse_sk(file, offset, max_size, strict);
1425
1426  if(!regfi_lock(file, &file->sk_lock, "regfi_load_sk"))
1427    return NULL;
1428
1429  /* First look if we have already parsed it */
1430  ret_val = (REGFI_SK_REC*)lru_cache_find(file->sk_cache, &offset, 4);
1431
1432  /* Bail out if we have previously cached a parse failure at this offset. */
1433  if(ret_val == (void*)REGFI_OFFSET_NONE)
1434    return NULL;
1435
1436  if(ret_val == NULL)
1437  {
1438    ret_val = regfi_parse_sk(file, offset, max_size, strict);
1439    if(ret_val == NULL)
1440    { /* Cache the parse failure and bail out. */
1441      failure_ptr = talloc(NULL, uint32_t);
1442      if(failure_ptr == NULL)
1443        return NULL;
1444      *(uint32_t*)failure_ptr = REGFI_OFFSET_NONE;
1445      lru_cache_update(file->sk_cache, &offset, 4, failure_ptr);
1446
1447      /* Let the cache be the only owner of this */
1448      talloc_unlink(NULL, failure_ptr);
1449      return NULL;
1450    }
1451  }
1452
1453  if(!regfi_unlock(file, &file->sk_lock, "regfi_load_sk"))
1454  {
1455    talloc_unlink(NULL, ret_val);
1456    return NULL;
1457  }
1458
1459  return ret_val;
1460}
1461
1462
1463
1464/******************************************************************************
1465 ******************************************************************************/
1466REGFI_NK_REC* regfi_find_root_nk(REGFI_FILE* file, const REGFI_HBIN* hbin, 
1467                                 REGFI_ENCODING output_encoding)
1468{
1469  REGFI_NK_REC* nk = NULL;
1470  uint32_t cell_length;
1471  uint32_t cur_offset = hbin->file_off+REGFI_HBIN_HEADER_SIZE;
1472  uint32_t hbin_end = hbin->file_off+hbin->block_size;
1473  bool unalloc;
1474
1475  while(cur_offset < hbin_end)
1476  {
1477
1478    if(!regfi_lock(file, &file->cb_lock, "regfi_find_root_nk"))
1479      return NULL;
1480
1481    if(!regfi_parse_cell(file->cb, cur_offset, NULL, 0, &cell_length, &unalloc))
1482    {
1483      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell at offset"
1484                    " 0x%.8X while searching for root key.", cur_offset);
1485      return NULL;
1486    }
1487
1488    if(!regfi_unlock(file, &file->cb_lock, "regfi_find_root_nk"))
1489      return NULL;
1490
1491    if(!unalloc)
1492    {
1493      nk = regfi_load_key(file, cur_offset, output_encoding, true);
1494      if(nk != NULL)
1495      {
1496        if(nk->flags & REGFI_NK_FLAG_ROOT)
1497          return nk;
1498      }
1499    }
1500
1501    cur_offset += cell_length;
1502  }
1503
1504  return NULL;
1505}
1506
1507
1508
1509/******************************************************************************
1510 ******************************************************************************/
1511REGFI_FILE* regfi_alloc(int fd)
1512{
1513  REGFI_FILE* ret_val;
1514  REGFI_RAW_FILE* file_cb = talloc(NULL, REGFI_RAW_FILE);
1515  if(file_cb == NULL) 
1516    return NULL;
1517
1518  file_cb->state = (void*)talloc(file_cb, int);
1519  if(file_cb->state == NULL)
1520    goto fail;
1521  *(int*)file_cb->state = fd;
1522 
1523  file_cb->cur_off = 0;
1524  file_cb->size = 0;
1525  file_cb->read = &regfi_raw_read;
1526  file_cb->seek = &regfi_raw_seek;
1527 
1528  ret_val = regfi_alloc_cb(file_cb);
1529  if(ret_val == NULL)
1530    goto fail;
1531
1532  /* In this case, we want file_cb to be freed when ret_val is */
1533  talloc_steal(ret_val, file_cb);
1534  return ret_val;
1535
1536 fail:
1537    talloc_free(file_cb);
1538    return NULL;
1539}
1540
1541
1542/******************************************************************************
1543 ******************************************************************************/
1544int regfi_free_cb(void* f)
1545{
1546  REGFI_FILE* file = (REGFI_FILE*)f;
1547
1548  pthread_mutex_destroy(&file->cb_lock);
1549  pthread_rwlock_destroy(&file->hbins_lock);
1550  pthread_mutex_destroy(&file->sk_lock);
1551
1552  return 0;
1553}
1554
1555
1556/******************************************************************************
1557 ******************************************************************************/
1558REGFI_FILE* regfi_alloc_cb(REGFI_RAW_FILE* file_cb)
1559{
1560  REGFI_FILE* rb;
1561  REGFI_HBIN* hbin = NULL;
1562  uint32_t hbin_off, cache_secret;
1563  int32_t file_length;
1564  bool rla;
1565
1566  /* Determine file length.  Must be at least big enough for the header
1567   * and one hbin.
1568   */
1569  file_length = file_cb->seek(file_cb, 0, SEEK_END);
1570  if(file_length < REGFI_REGF_SIZE+REGFI_HBIN_ALLOC)
1571  {
1572    regfi_log_add(REGFI_LOG_ERROR, "File length (%d) too short to contain a"
1573                  " header and at least one HBIN.", file_length);
1574    return NULL;
1575  }
1576  file_cb->seek(file_cb, 0, SEEK_SET);
1577
1578  /* Read file header */
1579  if ((rb = regfi_parse_regf(file_cb, false)) == NULL) 
1580  {
1581    regfi_log_add(REGFI_LOG_ERROR, "Failed to read REGF block.");
1582    return NULL;
1583  }
1584  rb->file_length = file_length; 
1585  rb->cb = file_cb;
1586
1587  if(pthread_mutex_init(&rb->cb_lock, NULL) != 0)
1588  {
1589    regfi_log_add(REGFI_LOG_ERROR, "Failed to create cb_lock mutex.");
1590    goto fail;
1591  }
1592
1593  if(pthread_rwlock_init(&rb->hbins_lock, NULL) != 0)
1594  {
1595    regfi_log_add(REGFI_LOG_ERROR, "Failed to create hbins_lock rwlock.");
1596    goto fail;
1597  }
1598
1599  if(pthread_mutex_init(&rb->sk_lock, NULL) != 0)
1600  {
1601    regfi_log_add(REGFI_LOG_ERROR, "Failed to create sk_lock mutex.");
1602    goto fail;
1603  }
1604
1605  rb->hbins = range_list_new();
1606  if(rb->hbins == NULL)
1607  {
1608    regfi_log_add(REGFI_LOG_ERROR, "Failed to create HBIN range_list.");
1609    goto fail;
1610  }
1611  talloc_steal(rb, rb->hbins);
1612
1613  rla = true;
1614  hbin_off = REGFI_REGF_SIZE;
1615  hbin = regfi_parse_hbin(rb, hbin_off, true);
1616  while(hbin && rla)
1617  {
1618    rla = range_list_add(rb->hbins, hbin->file_off, hbin->block_size, hbin);
1619    if(rla)
1620      talloc_steal(rb->hbins, hbin);
1621
1622    hbin_off = hbin->file_off + hbin->block_size;
1623    hbin = regfi_parse_hbin(rb, hbin_off, true);
1624  }
1625
1626  /* This secret isn't very secret, but we don't need a good one.  This
1627   * secret is just designed to prevent someone from trying to blow our
1628   * caching and make things slow.
1629   */
1630  cache_secret = 0x15DEAD05^time(NULL)^(getpid()<<16);
1631
1632  if(REGFI_CACHE_SK)
1633    rb->sk_cache = lru_cache_create_ctx(rb, 64, cache_secret, true);
1634  else
1635    rb->sk_cache = NULL;
1636
1637  /* success */
1638  talloc_set_destructor(rb, regfi_free_cb);
1639  return rb;
1640
1641 fail:
1642  pthread_mutex_destroy(&rb->cb_lock);
1643  pthread_rwlock_destroy(&rb->hbins_lock);
1644  pthread_mutex_destroy(&rb->sk_lock);
1645
1646  range_list_free(rb->hbins);
1647  talloc_free(rb);
1648  return NULL;
1649}
1650
1651
1652/******************************************************************************
1653 ******************************************************************************/
1654void regfi_free(REGFI_FILE* file)
1655{
1656  /* Callback handles cleanup side effects */
1657  talloc_free(file);
1658}
1659
1660
1661/******************************************************************************
1662 * First checks the offset given by the file header, then checks the
1663 * rest of the file if that fails.
1664 ******************************************************************************/
1665REGFI_NK_REC* regfi_rootkey(REGFI_FILE* file, REGFI_ENCODING output_encoding)
1666{
1667  REGFI_NK_REC* nk = NULL;
1668  REGFI_HBIN* hbin;
1669  uint32_t root_offset, i, num_hbins;
1670 
1671  if(!file)
1672    return NULL;
1673
1674  root_offset = file->root_cell+REGFI_REGF_SIZE;
1675  nk = regfi_load_key(file, root_offset, output_encoding, true);
1676  if(nk != NULL)
1677  {
1678    if(nk->flags & REGFI_NK_FLAG_ROOT)
1679      return nk;
1680  }
1681
1682  regfi_log_add(REGFI_LOG_WARN, "File header indicated root key at"
1683                " location 0x%.8X, but no root key found."
1684                " Searching rest of file...", root_offset);
1685 
1686  /* If the file header gives bad info, scan through the file one HBIN
1687   * block at a time looking for an NK record with a root key type.
1688   */
1689 
1690  if(!regfi_read_lock(file, &file->hbins_lock, "regfi_rootkey"))
1691    return NULL;
1692
1693  num_hbins = range_list_size(file->hbins);
1694  for(i=0; i < num_hbins && nk == NULL; i++)
1695  {
1696    hbin = (REGFI_HBIN*)range_list_get(file->hbins, i)->data;
1697    nk = regfi_find_root_nk(file, hbin, output_encoding);
1698  }
1699
1700  if(!regfi_rw_unlock(file, &file->hbins_lock, "regfi_rootkey"))
1701    return NULL;
1702
1703  return nk;
1704}
1705
1706
1707/******************************************************************************
1708 *****************************************************************************/
1709void regfi_free_record(const void* record)
1710{
1711  talloc_unlink(NULL, (void*)record);
1712}
1713
1714
1715
1716/******************************************************************************
1717 *****************************************************************************/
1718REGFI_ITERATOR* regfi_iterator_new(REGFI_FILE* file, 
1719                                   REGFI_ENCODING output_encoding)
1720{
1721  REGFI_NK_REC* root;
1722  REGFI_ITERATOR* ret_val;
1723
1724  if(output_encoding != REGFI_ENCODING_UTF8
1725     && output_encoding != REGFI_ENCODING_ASCII)
1726  { 
1727    regfi_log_add(REGFI_LOG_ERROR, "Invalid output_encoding supplied"
1728                  " in creation of regfi iterator.");
1729    return NULL;
1730  }
1731
1732  ret_val = talloc(NULL, REGFI_ITERATOR);
1733  if(ret_val == NULL)
1734    return NULL;
1735
1736  root = regfi_rootkey(file, output_encoding);
1737  if(root == NULL)
1738  {
1739    talloc_free(ret_val);
1740    return NULL;
1741  }
1742  ret_val->cur_key = root;
1743  talloc_reference(ret_val, root);
1744
1745  ret_val->key_positions = void_stack_new(REGFI_MAX_DEPTH);
1746  if(ret_val->key_positions == NULL)
1747  {
1748    talloc_free(ret_val);
1749    return NULL;
1750  }
1751  talloc_steal(ret_val, ret_val->key_positions);
1752
1753  ret_val->f = file;
1754  ret_val->cur_subkey = 0;
1755  ret_val->cur_value = 0;
1756  ret_val->string_encoding = output_encoding;
1757   
1758  return ret_val;
1759}
1760
1761
1762/******************************************************************************
1763 *****************************************************************************/
1764void regfi_iterator_free(REGFI_ITERATOR* i)
1765{
1766  talloc_free(i);
1767}
1768
1769
1770
1771/******************************************************************************
1772 *****************************************************************************/
1773/* XXX: some way of indicating reason for failure should be added. */
1774bool regfi_iterator_down(REGFI_ITERATOR* i)
1775{
1776  REGFI_NK_REC* subkey;
1777  REGFI_ITER_POSITION* pos;
1778
1779  pos = talloc(i->key_positions, REGFI_ITER_POSITION);
1780  if(pos == NULL)
1781    return false;
1782
1783  subkey = (REGFI_NK_REC*)regfi_iterator_cur_subkey(i);
1784  if(subkey == NULL)
1785  {
1786    talloc_free(pos);
1787    return false;
1788  }
1789
1790  pos->nk = i->cur_key;
1791  pos->cur_subkey = i->cur_subkey;
1792  if(!void_stack_push(i->key_positions, pos))
1793  {
1794    talloc_free(pos);
1795    talloc_unlink(NULL, subkey);
1796    return false;
1797  }
1798  talloc_reference(i, subkey);
1799
1800  i->cur_key = subkey;
1801  i->cur_subkey = 0;
1802  i->cur_value = 0;
1803
1804  return true;
1805}
1806
1807
1808/******************************************************************************
1809 *****************************************************************************/
1810bool regfi_iterator_up(REGFI_ITERATOR* i)
1811{
1812  REGFI_ITER_POSITION* pos;
1813
1814  pos = (REGFI_ITER_POSITION*)void_stack_pop(i->key_positions);
1815  if(pos == NULL)
1816    return false;
1817
1818  talloc_unlink(i, i->cur_key);
1819  i->cur_key = pos->nk;
1820  i->cur_subkey = pos->cur_subkey;
1821  i->cur_value = 0;
1822  talloc_free(pos);
1823
1824  return true;
1825}
1826
1827
1828/******************************************************************************
1829 *****************************************************************************/
1830bool regfi_iterator_to_root(REGFI_ITERATOR* i)
1831{
1832  while(regfi_iterator_up(i))
1833    continue;
1834
1835  return true;
1836}
1837
1838
1839/******************************************************************************
1840 *****************************************************************************/
1841bool regfi_iterator_find_subkey(REGFI_ITERATOR* i, const char* subkey_name)
1842{
1843  REGFI_NK_REC* subkey;
1844  bool found = false;
1845  uint32_t old_subkey = i->cur_subkey;
1846
1847  if(subkey_name == NULL)
1848    return false;
1849
1850  /* XXX: this alloc/free of each sub key might be a bit excessive */
1851  regfi_iterator_first_subkey(i);
1852  while((subkey = regfi_iterator_cur_subkey(i)) != NULL && (found == false))
1853  {
1854    if(subkey->keyname != NULL 
1855       && strcasecmp(subkey->keyname, subkey_name) == 0)
1856      found = true;
1857    else
1858    {
1859      talloc_unlink(NULL, subkey);
1860      regfi_iterator_next_subkey(i);
1861    }
1862  }
1863
1864  if(found == false)
1865  {
1866    i->cur_subkey = old_subkey;
1867    return false;
1868  }
1869
1870  talloc_unlink(NULL, subkey);
1871  return true;
1872}
1873
1874
1875/******************************************************************************
1876 *****************************************************************************/
1877bool regfi_iterator_walk_path(REGFI_ITERATOR* i, const char** path)
1878{
1879  uint32_t x;
1880  if(path == NULL)
1881    return false;
1882
1883  for(x=0; 
1884      ((path[x] != NULL) && regfi_iterator_find_subkey(i, path[x])
1885       && regfi_iterator_down(i));
1886      x++)
1887  { continue; }
1888
1889  if(path[x] == NULL)
1890    return true;
1891 
1892  /* XXX: is this the right number of times? */
1893  for(; x > 0; x--)
1894    regfi_iterator_up(i);
1895 
1896  return false;
1897}
1898
1899
1900/******************************************************************************
1901 *****************************************************************************/
1902const REGFI_NK_REC* regfi_iterator_cur_key(REGFI_ITERATOR* i)
1903{
1904  return i->cur_key;
1905}
1906
1907
1908/******************************************************************************
1909 *****************************************************************************/
1910const REGFI_SK_REC* regfi_iterator_cur_sk(REGFI_ITERATOR* i)
1911{
1912  if(i->cur_key == NULL || i->cur_key->sk_off == REGFI_OFFSET_NONE)
1913    return NULL;
1914
1915  return regfi_load_sk(i->f, i->cur_key->sk_off + REGFI_REGF_SIZE, true);
1916}
1917
1918
1919/******************************************************************************
1920 *****************************************************************************/
1921bool regfi_iterator_first_subkey(REGFI_ITERATOR* i)
1922{
1923  i->cur_subkey = 0;
1924 
1925  return ((i->cur_key != NULL) && (i->cur_key->subkeys_off!=REGFI_OFFSET_NONE) 
1926          && (i->cur_subkey < i->cur_key->num_subkeys)); 
1927}
1928
1929
1930/******************************************************************************
1931 *****************************************************************************/
1932const REGFI_NK_REC* regfi_iterator_cur_subkey(REGFI_ITERATOR* i)
1933{
1934  uint32_t nk_offset;
1935
1936  if((i->cur_key != NULL) && (i->cur_key->subkeys_off!=REGFI_OFFSET_NONE) 
1937     && (i->cur_subkey < i->cur_key->num_subkeys))
1938  {
1939    nk_offset = i->cur_key->subkeys->elements[i->cur_subkey].offset;
1940
1941    return regfi_load_key(i->f, nk_offset+REGFI_REGF_SIZE, 
1942                          i->string_encoding, true);
1943  }
1944
1945  return NULL;
1946}
1947
1948
1949/******************************************************************************
1950 *****************************************************************************/
1951bool regfi_iterator_next_subkey(REGFI_ITERATOR* i)
1952{
1953  i->cur_subkey++;
1954
1955  return ((i->cur_key != NULL) && (i->cur_key->subkeys_off!=REGFI_OFFSET_NONE) 
1956          && (i->cur_subkey < i->cur_key->num_subkeys)); 
1957}
1958
1959
1960/******************************************************************************
1961 *****************************************************************************/
1962bool regfi_iterator_find_value(REGFI_ITERATOR* i, const char* value_name)
1963{
1964  const REGFI_VK_REC* cur;
1965  bool found = false;
1966  uint32_t old_value = i->cur_value;
1967
1968  /* XXX: cur->valuename can be NULL in the registry. 
1969   *      Should we allow for a way to search for that?
1970   */
1971  if(value_name == NULL)
1972    return false;
1973
1974  regfi_iterator_first_value(i);
1975  while((cur = regfi_iterator_cur_value(i)) != NULL && (found == false))
1976  {
1977    if((cur->valuename != NULL)
1978       && (strcasecmp(cur->valuename, value_name) == 0))
1979      found = true;
1980    else
1981    {
1982      regfi_free_record(cur);
1983      regfi_iterator_next_value(i);
1984    }
1985  }
1986 
1987  if(found == false)
1988  {
1989    i->cur_value = old_value;
1990    return false;
1991  }
1992
1993  regfi_free_record(cur);
1994  return true;
1995}
1996
1997
1998/******************************************************************************
1999 *****************************************************************************/
2000bool regfi_iterator_first_value(REGFI_ITERATOR* i)
2001{
2002  i->cur_value = 0;
2003  return (i->cur_key->values != NULL && i->cur_key->values->elements != NULL 
2004          && (i->cur_value < i->cur_key->values->num_values));
2005}
2006
2007
2008/******************************************************************************
2009 *****************************************************************************/
2010const REGFI_VK_REC* regfi_iterator_cur_value(REGFI_ITERATOR* i)
2011{
2012  REGFI_VK_REC* ret_val = NULL;
2013  uint32_t voffset;
2014
2015  if(i->cur_key->values != NULL && i->cur_key->values->elements != NULL 
2016     && (i->cur_value < i->cur_key->values->num_values))
2017  {
2018    voffset = i->cur_key->values->elements[i->cur_value];
2019    ret_val = regfi_load_value(i->f, voffset+REGFI_REGF_SIZE, 
2020                               i->string_encoding, true);
2021  }
2022
2023  return ret_val;
2024}
2025
2026
2027/******************************************************************************
2028 *****************************************************************************/
2029bool regfi_iterator_next_value(REGFI_ITERATOR* i)
2030{
2031  i->cur_value++;
2032  return (i->cur_key->values != NULL && i->cur_key->values->elements != NULL 
2033          && (i->cur_value < i->cur_key->values->num_values));
2034}
2035
2036
2037/******************************************************************************
2038 *****************************************************************************/
2039const REGFI_CLASSNAME* regfi_iterator_fetch_classname(REGFI_ITERATOR* i,
2040                                                      const REGFI_NK_REC* key)
2041{
2042  REGFI_CLASSNAME* ret_val;
2043  uint8_t* raw;
2044  char* interpreted;
2045  uint32_t offset;
2046  int32_t conv_size, max_size;
2047  uint16_t parse_length;
2048
2049  if(key->classname_off == REGFI_OFFSET_NONE || key->classname_length == 0)
2050    return NULL;
2051
2052  offset = key->classname_off + REGFI_REGF_SIZE;
2053  max_size = regfi_calc_maxsize(i->f, offset);
2054  if(max_size <= 0)
2055    return NULL;
2056
2057  parse_length = key->classname_length;
2058  raw = regfi_parse_classname(i->f, offset, &parse_length, max_size, true);
2059 
2060  if(raw == NULL)
2061  {
2062    regfi_log_add(REGFI_LOG_WARN, "Could not parse class"
2063                  " name at offset 0x%.8X for key record at offset 0x%.8X.",
2064                  offset, key->offset);
2065    return NULL;
2066  }
2067
2068  ret_val = talloc(NULL, REGFI_CLASSNAME);
2069  if(ret_val == NULL)
2070    return NULL;
2071
2072  ret_val->raw = raw;
2073  ret_val->size = parse_length;
2074  talloc_steal(ret_val, raw);
2075
2076  interpreted = talloc_array(NULL, char, parse_length);
2077
2078  conv_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2079                                 regfi_encoding_int2str(i->string_encoding),
2080                                 raw, interpreted,
2081                                 parse_length, parse_length);
2082  if(conv_size < 0)
2083  {
2084    regfi_log_add(REGFI_LOG_WARN, "Error occurred while"
2085                  " converting classname to charset %s.  Error message: %s",
2086                  i->string_encoding, strerror(-conv_size));
2087    talloc_free(interpreted);
2088    ret_val->interpreted = NULL;
2089  }
2090  else
2091  {
2092    interpreted = talloc_realloc(NULL, interpreted, char, conv_size);
2093    ret_val->interpreted = interpreted;
2094    talloc_steal(ret_val, interpreted);
2095  }
2096
2097  return ret_val;
2098}
2099
2100
2101/******************************************************************************
2102 *****************************************************************************/
2103const REGFI_DATA* regfi_iterator_fetch_data(REGFI_ITERATOR* i, 
2104                                            const REGFI_VK_REC* value)
2105{
2106  REGFI_DATA* ret_val = NULL;
2107  REGFI_BUFFER raw_data;
2108
2109  if(value->data_size != 0)
2110  {
2111    raw_data = regfi_load_data(i->f, value->data_off, value->data_size,
2112                              value->data_in_offset, true);
2113    if(raw_data.buf == NULL)
2114    {
2115      regfi_log_add(REGFI_LOG_WARN, "Could not parse data record"
2116                    " while parsing VK record at offset 0x%.8X.",
2117                    value->offset);
2118    }
2119    else
2120    {
2121      ret_val = regfi_buffer_to_data(raw_data);
2122
2123      if(ret_val == NULL)
2124      {
2125        regfi_log_add(REGFI_LOG_WARN, "Error occurred in converting"
2126                      " data buffer to data structure while interpreting "
2127                      "data for VK record at offset 0x%.8X.",
2128                      value->offset);
2129        talloc_free(raw_data.buf);
2130        return NULL;
2131      }
2132
2133      if(!regfi_interpret_data(i->f, i->string_encoding, value->type, ret_val))
2134      {
2135        regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2136                      " interpreting data for VK record at offset 0x%.8X.",
2137                      value->offset);
2138      }
2139    }
2140  }
2141 
2142  return ret_val;
2143}
2144
2145
2146/******************************************************************************
2147 *****************************************************************************/
2148REGFI_DATA* regfi_buffer_to_data(REGFI_BUFFER raw_data)
2149{
2150  REGFI_DATA* ret_val;
2151
2152  if(raw_data.buf == NULL)
2153    return NULL;
2154
2155  ret_val = talloc(NULL, REGFI_DATA);
2156  if(ret_val == NULL)
2157    return NULL;
2158 
2159  talloc_steal(ret_val, raw_data.buf);
2160  ret_val->raw = raw_data.buf;
2161  ret_val->size = raw_data.len;
2162  ret_val->interpreted_size = 0;
2163  ret_val->interpreted.qword = 0;
2164
2165  return ret_val;
2166}
2167
2168
2169/******************************************************************************
2170 *****************************************************************************/
2171bool regfi_interpret_data(REGFI_FILE* file, REGFI_ENCODING string_encoding,
2172                          uint32_t type, REGFI_DATA* data)
2173{
2174  uint8_t** tmp_array;
2175  uint8_t* tmp_str;
2176  int32_t tmp_size;
2177  uint32_t i, j, array_size;
2178
2179  if(data == NULL)
2180    return false;
2181
2182  switch (type)
2183  {
2184  case REG_SZ:
2185  case REG_EXPAND_SZ:
2186  /* REG_LINK is a symbolic link, stored as a unicode string. */
2187  case REG_LINK:
2188    tmp_str = talloc_array(NULL, uint8_t, data->size);
2189    if(tmp_str == NULL)
2190    {
2191      data->interpreted.string = NULL;
2192      data->interpreted_size = 0;
2193      return false;
2194    }
2195     
2196    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2197                                  regfi_encoding_int2str(string_encoding),
2198                                  data->raw, (char*)tmp_str, 
2199                                  data->size, data->size);
2200    if(tmp_size < 0)
2201    {
2202      regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2203                    " converting data of type %d to %d.  Error message: %s",
2204                    type, string_encoding, strerror(-tmp_size));
2205      talloc_free(tmp_str);
2206      data->interpreted.string = NULL;
2207      data->interpreted_size = 0;
2208      return false;
2209    }
2210
2211    tmp_str = talloc_realloc(NULL, tmp_str, uint8_t, tmp_size);
2212    data->interpreted.string = tmp_str;
2213    data->interpreted_size = tmp_size;
2214    talloc_steal(data, tmp_str);
2215    break;
2216
2217  case REG_DWORD:
2218    if(data->size < 4)
2219    {
2220      data->interpreted.dword = 0;
2221      data->interpreted_size = 0;
2222      return false;
2223    }
2224    data->interpreted.dword = IVAL(data->raw, 0);
2225    data->interpreted_size = 4;
2226    break;
2227
2228  case REG_DWORD_BE:
2229    if(data->size < 4)
2230    {
2231      data->interpreted.dword_be = 0;
2232      data->interpreted_size = 0;
2233      return false;
2234    }
2235    data->interpreted.dword_be = RIVAL(data->raw, 0);
2236    data->interpreted_size = 4;
2237    break;
2238
2239  case REG_QWORD:
2240    if(data->size < 8)
2241    {
2242      data->interpreted.qword = 0;
2243      data->interpreted_size = 0;
2244      return false;
2245    }
2246    data->interpreted.qword = 
2247      (uint64_t)IVAL(data->raw, 0) + (((uint64_t)IVAL(data->raw, 4))<<32);
2248    data->interpreted_size = 8;
2249    break;
2250   
2251  case REG_MULTI_SZ:
2252    tmp_str = talloc_array(NULL, uint8_t, data->size);
2253    if(tmp_str == NULL)
2254    {
2255      data->interpreted.multiple_string = NULL;
2256      data->interpreted_size = 0;
2257      return false;
2258    }
2259
2260    /* Attempt to convert entire string from UTF-16LE to output encoding,
2261     * then parse and quote fields individually.
2262     */
2263    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2264                                  regfi_encoding_int2str(string_encoding),
2265                                  data->raw, (char*)tmp_str,
2266                                  data->size, data->size);
2267    if(tmp_size < 0)
2268    {
2269      regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2270                    " converting data of type %d to %s.  Error message: %s",
2271                    type, string_encoding, strerror(-tmp_size));
2272      talloc_free(tmp_str);
2273      data->interpreted.multiple_string = NULL;
2274      data->interpreted_size = 0;
2275      return false;
2276    }
2277
2278    array_size = tmp_size+1;
2279    tmp_array = talloc_array(NULL, uint8_t*, array_size);
2280    if(tmp_array == NULL)
2281    {
2282      talloc_free(tmp_str);
2283      data->interpreted.string = NULL;
2284      data->interpreted_size = 0;
2285      return false;
2286    }
2287   
2288    tmp_array[0] = tmp_str;
2289    for(i=0,j=1; i < tmp_size && j < array_size-1; i++)
2290    {
2291      if(tmp_str[i] == '\0' && (i+1 < tmp_size))
2292        tmp_array[j++] = tmp_str+i+1;
2293    }
2294    tmp_array[j] = NULL;
2295    tmp_array = talloc_realloc(NULL, tmp_array, uint8_t*, j+1);
2296    data->interpreted.multiple_string = tmp_array;
2297    /* XXX: how meaningful is this?  should we store number of strings instead? */
2298    data->interpreted_size = tmp_size;
2299    talloc_steal(tmp_array, tmp_str);
2300    talloc_steal(data, tmp_array);
2301    break;
2302
2303  /* XXX: Dont know how to interpret these yet, just treat as binary */
2304  case REG_NONE:
2305    data->interpreted.none = data->raw;
2306    data->interpreted_size = data->size;
2307    break;
2308
2309  case REG_RESOURCE_LIST:
2310    data->interpreted.resource_list = data->raw;
2311    data->interpreted_size = data->size;
2312    break;
2313
2314  case REG_FULL_RESOURCE_DESCRIPTOR:
2315    data->interpreted.full_resource_descriptor = data->raw;
2316    data->interpreted_size = data->size;
2317    break;
2318
2319  case REG_RESOURCE_REQUIREMENTS_LIST:
2320    data->interpreted.resource_requirements_list = data->raw;
2321    data->interpreted_size = data->size;
2322    break;
2323
2324  case REG_BINARY:
2325    data->interpreted.binary = data->raw;
2326    data->interpreted_size = data->size;
2327    break;
2328
2329  default:
2330    data->interpreted.qword = 0;
2331    data->interpreted_size = 0;
2332    return false;
2333  }
2334
2335  data->type = type;
2336  return true;
2337}
2338
2339
2340/******************************************************************************
2341 * Convert from UTF-16LE to specified character set.
2342 * On error, returns a negative errno code.
2343 *****************************************************************************/
2344int32_t regfi_conv_charset(const char* input_charset, const char* output_charset,
2345                         uint8_t* input, char* output, 
2346                         uint32_t input_len, uint32_t output_max)
2347{
2348  iconv_t conv_desc;
2349  char* inbuf = (char*)input;
2350  char* outbuf = output;
2351  size_t in_len = (size_t)input_len;
2352  size_t out_len = (size_t)(output_max-1);
2353  int ret;
2354
2355  /* XXX: Consider creating a couple of conversion descriptors earlier,
2356   *      storing them on an iterator so they don't have to be recreated
2357   *      each time.
2358   */
2359
2360  /* Set up conversion descriptor. */
2361  conv_desc = iconv_open(output_charset, input_charset);
2362
2363  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
2364  if(ret == -1)
2365  {
2366    iconv_close(conv_desc);
2367    return -errno;
2368  }
2369  *outbuf = '\0';
2370
2371  iconv_close(conv_desc); 
2372  return output_max-out_len-1;
2373}
2374
2375
2376
2377/*******************************************************************
2378 * Computes the checksum of the registry file header.
2379 * buffer must be at least the size of a regf header (4096 bytes).
2380 *******************************************************************/
2381static uint32_t regfi_compute_header_checksum(uint8_t* buffer)
2382{
2383  uint32_t checksum, x;
2384  int i;
2385
2386  /* XOR of all bytes 0x0000 - 0x01FB */
2387
2388  checksum = x = 0;
2389 
2390  for ( i=0; i<0x01FB; i+=4 ) {
2391    x = IVAL(buffer, i );
2392    checksum ^= x;
2393  }
2394 
2395  return checksum;
2396}
2397
2398
2399/*******************************************************************
2400 *******************************************************************/
2401REGFI_FILE* regfi_parse_regf(REGFI_RAW_FILE* file_cb, bool strict)
2402{
2403  uint8_t file_header[REGFI_REGF_SIZE];
2404  uint32_t length;
2405  REGFI_FILE* ret_val;
2406
2407  ret_val = talloc(NULL, REGFI_FILE);
2408  if(ret_val == NULL)
2409    return NULL;
2410
2411  ret_val->sk_cache = NULL;
2412  ret_val->hbins = NULL;
2413
2414  length = REGFI_REGF_SIZE;
2415  if((regfi_read(file_cb, file_header, &length)) != 0 
2416     || length != REGFI_REGF_SIZE)
2417  {
2418    regfi_log_add(REGFI_LOG_WARN, "Read failed while parsing REGF structure.");
2419    goto fail;
2420  }
2421
2422  ret_val->checksum = IVAL(file_header, 0x1FC);
2423  ret_val->computed_checksum = regfi_compute_header_checksum(file_header);
2424  if (strict && (ret_val->checksum != ret_val->computed_checksum))
2425  {
2426    regfi_log_add(REGFI_LOG_WARN, "Stored header checksum (%.8X) did not equal"
2427                  " computed checksum (%.8X).",
2428                  ret_val->checksum, ret_val->computed_checksum);
2429    if(strict)
2430      goto fail;
2431  }
2432
2433  memcpy(ret_val->magic, file_header, REGFI_REGF_MAGIC_SIZE);
2434  if(memcmp(ret_val->magic, "regf", REGFI_REGF_MAGIC_SIZE) != 0)
2435  {
2436    regfi_log_add(REGFI_LOG_ERROR, "Magic number mismatch "
2437                  "(%.2X %.2X %.2X %.2X) while parsing hive header",
2438                  ret_val->magic[0], ret_val->magic[1], 
2439                  ret_val->magic[2], ret_val->magic[3]);
2440    goto fail;
2441  }
2442
2443  ret_val->sequence1 = IVAL(file_header, 0x4);
2444  ret_val->sequence2 = IVAL(file_header, 0x8);
2445  ret_val->mtime.low = IVAL(file_header, 0xC);
2446  ret_val->mtime.high = IVAL(file_header, 0x10);
2447  ret_val->major_version = IVAL(file_header, 0x14);
2448  ret_val->minor_version = IVAL(file_header, 0x18);
2449  ret_val->type = IVAL(file_header, 0x1C);
2450  ret_val->format = IVAL(file_header, 0x20);
2451  ret_val->root_cell = IVAL(file_header, 0x24);
2452  ret_val->last_block = IVAL(file_header, 0x28);
2453  ret_val->cluster = IVAL(file_header, 0x2C);
2454
2455  memcpy(ret_val->file_name, file_header+0x30,  REGFI_REGF_NAME_SIZE);
2456
2457  /* XXX: Should we add a warning if these uuid parsers fail?  Can they? */
2458  ret_val->rm_id = winsec_parse_uuid(ret_val, file_header+0x70, 16);
2459  ret_val->log_id = winsec_parse_uuid(ret_val, file_header+0x80, 16);
2460  ret_val->flags = IVAL(file_header, 0x90);
2461  ret_val->tm_id = winsec_parse_uuid(ret_val, file_header+0x94, 16);
2462  ret_val->guid_signature = IVAL(file_header, 0xa4);
2463
2464  memcpy(ret_val->reserved1, file_header+0xa8, REGFI_REGF_RESERVED1_SIZE);
2465  memcpy(ret_val->reserved2, file_header+0x200, REGFI_REGF_RESERVED2_SIZE);
2466
2467  ret_val->thaw_tm_id = winsec_parse_uuid(ret_val, file_header+0xFC8, 16);
2468  ret_val->thaw_rm_id = winsec_parse_uuid(ret_val, file_header+0xFD8, 16);
2469  ret_val->thaw_log_id = winsec_parse_uuid(ret_val, file_header+0xFE8, 16);
2470  ret_val->boot_type = IVAL(file_header, 0xFF8);
2471  ret_val->boot_recover = IVAL(file_header, 0xFFC);
2472
2473  return ret_val;
2474
2475 fail:
2476  talloc_free(ret_val);
2477  return NULL;
2478}
2479
2480
2481
2482/******************************************************************************
2483 * Given real file offset, read and parse the hbin at that location
2484 * along with it's associated cells.
2485 ******************************************************************************/
2486REGFI_HBIN* regfi_parse_hbin(REGFI_FILE* file, uint32_t offset, bool strict)
2487{
2488  REGFI_HBIN* hbin = NULL;
2489  uint8_t hbin_header[REGFI_HBIN_HEADER_SIZE];
2490  uint32_t length;
2491 
2492  if(offset >= file->file_length)
2493    goto fail;
2494 
2495  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_hbin"))
2496    goto fail;
2497
2498  if(regfi_seek(file->cb, offset, SEEK_SET) == -1)
2499  {
2500    regfi_log_add(REGFI_LOG_ERROR, "Seek failed"
2501                  " while parsing hbin at offset 0x%.8X.", offset);
2502    goto fail_locked;
2503  }
2504
2505  length = REGFI_HBIN_HEADER_SIZE;
2506  if((regfi_read(file->cb, hbin_header, &length) != 0) 
2507     || length != REGFI_HBIN_HEADER_SIZE)
2508  {
2509    regfi_log_add(REGFI_LOG_ERROR, "Read failed"
2510                  " while parsing hbin at offset 0x%.8X.", offset);
2511    goto fail_locked;
2512  }
2513
2514  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_hbin"))
2515    goto fail;
2516
2517  hbin = talloc(NULL, REGFI_HBIN);
2518  if(hbin == NULL)
2519    goto fail;
2520  hbin->file_off = offset;
2521
2522  memcpy(hbin->magic, hbin_header, 4);
2523  if(strict && (memcmp(hbin->magic, "hbin", 4) != 0))
2524  {
2525    /* This always seems to happen at the end of a file, so we make it an INFO
2526     * message, rather than something more serious.
2527     */
2528    regfi_log_add(REGFI_LOG_INFO, "Magic number mismatch "
2529                  "(%.2X %.2X %.2X %.2X) while parsing hbin at offset"
2530                  " 0x%.8X.", hbin->magic[0], hbin->magic[1], 
2531                  hbin->magic[2], hbin->magic[3], offset);
2532    goto fail;
2533  }
2534
2535  hbin->first_hbin_off = IVAL(hbin_header, 0x4);
2536  hbin->block_size = IVAL(hbin_header, 0x8);
2537  /* this should be the same thing as hbin->block_size, but just in case */
2538  hbin->next_block = IVAL(hbin_header, 0x1C);
2539
2540
2541  /* Ensure the block size is a multiple of 0x1000 and doesn't run off
2542   * the end of the file.
2543   */
2544  /* XXX: This may need to be relaxed for dealing with
2545   *      partial or corrupt files.
2546   */
2547  if((offset + hbin->block_size > file->file_length)
2548     || (hbin->block_size & 0xFFFFF000) != hbin->block_size)
2549  {
2550    regfi_log_add(REGFI_LOG_ERROR, "The hbin offset is not aligned"
2551                  " or runs off the end of the file"
2552                  " while parsing hbin at offset 0x%.8X.", offset);
2553    goto fail;
2554  }
2555
2556  return hbin;
2557
2558 fail_locked:
2559  regfi_unlock(file, &file->cb_lock, "regfi_parse_hbin");
2560 fail:
2561  talloc_free(hbin);
2562  return NULL;
2563}
2564
2565
2566/*******************************************************************
2567 *******************************************************************/
2568REGFI_NK_REC* regfi_parse_nk(REGFI_FILE* file, uint32_t offset, 
2569                             uint32_t max_size, bool strict)
2570{
2571  uint8_t nk_header[REGFI_NK_MIN_LENGTH];
2572  REGFI_NK_REC* ret_val;
2573  uint32_t length,cell_length;
2574  bool unalloc = false;
2575
2576  ret_val = talloc(NULL, REGFI_NK_REC);
2577  if(ret_val == NULL)
2578  {
2579    regfi_log_add(REGFI_LOG_ERROR, "Failed to allocate memory while"
2580                  " parsing NK record at offset 0x%.8X.", offset);
2581    goto fail;
2582  }
2583
2584  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_nk"))
2585    goto fail;
2586
2587  if(!regfi_parse_cell(file->cb, offset, nk_header, REGFI_NK_MIN_LENGTH,
2588                       &cell_length, &unalloc))
2589  {
2590    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2591                  " while parsing NK record at offset 0x%.8X.", offset);
2592    goto fail_locked;
2593  }
2594
2595  if((nk_header[0x0] != 'n') || (nk_header[0x1] != 'k'))
2596  {
2597    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch in parsing"
2598                  " NK record at offset 0x%.8X.", offset);
2599    goto fail_locked;
2600  }
2601
2602  ret_val->values = NULL;
2603  ret_val->subkeys = NULL;
2604  ret_val->offset = offset;
2605  ret_val->cell_size = cell_length;
2606
2607  if(ret_val->cell_size > max_size)
2608    ret_val->cell_size = max_size & 0xFFFFFFF8;
2609  if((ret_val->cell_size < REGFI_NK_MIN_LENGTH) 
2610     || (strict && (ret_val->cell_size & 0x00000007) != 0))
2611  {
2612    regfi_log_add(REGFI_LOG_WARN, "A length check failed while"
2613                  " parsing NK record at offset 0x%.8X.", offset);
2614    goto fail_locked;
2615  }
2616
2617  ret_val->magic[0] = nk_header[0x0];
2618  ret_val->magic[1] = nk_header[0x1];
2619  ret_val->flags = SVAL(nk_header, 0x2);
2620 
2621  if((ret_val->flags & ~REGFI_NK_KNOWN_FLAGS) != 0)
2622  {
2623    regfi_log_add(REGFI_LOG_WARN, "Unknown key flags (0x%.4X) while"
2624                  " parsing NK record at offset 0x%.8X.", 
2625                  (ret_val->flags & ~REGFI_NK_KNOWN_FLAGS), offset);
2626  }
2627
2628  ret_val->mtime.low = IVAL(nk_header, 0x4);
2629  ret_val->mtime.high = IVAL(nk_header, 0x8);
2630  /* If the key is unallocated and the MTIME is earlier than Jan 1, 1990
2631   * or later than Jan 1, 2290, we consider this a bad key.  This helps
2632   * weed out some false positives during deleted data recovery.
2633   */
2634  if(unalloc
2635     && (ret_val->mtime.high < REGFI_MTIME_MIN_HIGH
2636         || ret_val->mtime.high > REGFI_MTIME_MAX_HIGH))
2637  { goto fail_locked; }
2638
2639  ret_val->unknown1 = IVAL(nk_header, 0xC);
2640  ret_val->parent_off = IVAL(nk_header, 0x10);
2641  ret_val->num_subkeys = IVAL(nk_header, 0x14);
2642  ret_val->unknown2 = IVAL(nk_header, 0x18);
2643  ret_val->subkeys_off = IVAL(nk_header, 0x1C);
2644  ret_val->unknown3 = IVAL(nk_header, 0x20);
2645  ret_val->num_values = IVAL(nk_header, 0x24);
2646  ret_val->values_off = IVAL(nk_header, 0x28);
2647  ret_val->sk_off = IVAL(nk_header, 0x2C);
2648  ret_val->classname_off = IVAL(nk_header, 0x30);
2649
2650  ret_val->max_bytes_subkeyname = IVAL(nk_header, 0x34);
2651  ret_val->max_bytes_subkeyclassname = IVAL(nk_header, 0x38);
2652  ret_val->max_bytes_valuename = IVAL(nk_header, 0x3C);
2653  ret_val->max_bytes_value = IVAL(nk_header, 0x40);
2654  ret_val->unk_index = IVAL(nk_header, 0x44);
2655
2656  ret_val->name_length = SVAL(nk_header, 0x48);
2657  ret_val->classname_length = SVAL(nk_header, 0x4A);
2658  ret_val->keyname = NULL;
2659
2660  if(ret_val->name_length + REGFI_NK_MIN_LENGTH > ret_val->cell_size)
2661  {
2662    if(strict)
2663    {
2664      regfi_log_add(REGFI_LOG_ERROR, "Contents too large for cell"
2665                    " while parsing NK record at offset 0x%.8X.", offset);
2666      goto fail_locked;
2667    }
2668    else
2669      ret_val->name_length = ret_val->cell_size - REGFI_NK_MIN_LENGTH;
2670  }
2671  else if (unalloc)
2672  { /* Truncate cell_size if it's much larger than the apparent total record length. */
2673    /* Round up to the next multiple of 8 */
2674    length = (ret_val->name_length + REGFI_NK_MIN_LENGTH) & 0xFFFFFFF8;
2675    if(length < ret_val->name_length + REGFI_NK_MIN_LENGTH)
2676      length+=8;
2677
2678    /* If cell_size is still greater, truncate. */
2679    if(length < ret_val->cell_size)
2680      ret_val->cell_size = length;
2681  }
2682
2683  ret_val->keyname_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2684  if(ret_val->keyname_raw == NULL)
2685    goto fail_locked;
2686
2687  /* Don't need to seek, should be at the right offset */
2688  length = ret_val->name_length;
2689  if((regfi_read(file->cb, (uint8_t*)ret_val->keyname_raw, &length) != 0)
2690     || length != ret_val->name_length)
2691  {
2692    regfi_log_add(REGFI_LOG_ERROR, "Failed to read key name"
2693                  " while parsing NK record at offset 0x%.8X.", offset);
2694    goto fail_locked;
2695  }
2696
2697  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_nk"))
2698    goto fail;
2699
2700  return ret_val;
2701
2702 fail_locked:
2703  regfi_unlock(file, &file->cb_lock, "regfi_parse_nk");
2704 fail:
2705  talloc_free(ret_val);
2706  return NULL;
2707}
2708
2709
2710uint8_t* regfi_parse_classname(REGFI_FILE* file, uint32_t offset, 
2711                             uint16_t* name_length, uint32_t max_size, bool strict)
2712{
2713  uint8_t* ret_val = NULL;
2714  uint32_t length;
2715  uint32_t cell_length;
2716  bool unalloc = false;
2717
2718  if(*name_length <= 0 || offset == REGFI_OFFSET_NONE 
2719     || (offset & 0x00000007) != 0)
2720  { goto fail; }
2721
2722  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_classname"))
2723    goto fail;
2724
2725  if(!regfi_parse_cell(file->cb, offset, NULL, 0, &cell_length, &unalloc))
2726  {
2727    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2728                  " while parsing class name at offset 0x%.8X.", offset);
2729    goto fail_locked;
2730  }
2731 
2732  if((cell_length & 0x0000007) != 0)
2733  {
2734    regfi_log_add(REGFI_LOG_ERROR, "Cell length not a multiple of 8"
2735                  " while parsing class name at offset 0x%.8X.", offset);
2736    goto fail_locked;
2737  }
2738 
2739  if(cell_length > max_size)
2740  {
2741    regfi_log_add(REGFI_LOG_WARN, "Cell stretches past hbin "
2742                  "boundary while parsing class name at offset 0x%.8X.",
2743                  offset);
2744    if(strict)
2745      goto fail_locked;
2746    cell_length = max_size;
2747  }
2748 
2749  if((cell_length - 4) < *name_length)
2750  {
2751    regfi_log_add(REGFI_LOG_WARN, "Class name is larger than"
2752                  " cell_length while parsing class name at offset"
2753                  " 0x%.8X.", offset);
2754    if(strict)
2755      goto fail_locked;
2756    *name_length = cell_length - 4;
2757  }
2758 
2759  ret_val = talloc_array(NULL, uint8_t, *name_length);
2760  if(ret_val != NULL)
2761  {
2762    length = *name_length;
2763    if((regfi_read(file->cb, ret_val, &length) != 0)
2764       || length != *name_length)
2765    {
2766      regfi_log_add(REGFI_LOG_ERROR, "Could not read class name"
2767                    " while parsing class name at offset 0x%.8X.", offset);
2768      goto fail_locked;
2769    }
2770  }
2771
2772  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_classname"))
2773    goto fail;
2774
2775  return ret_val;
2776
2777 fail_locked:
2778  regfi_unlock(file, &file->cb_lock, "regfi_parse_classname");
2779 fail:
2780  talloc_free(ret_val);
2781  return NULL;
2782}
2783
2784
2785/******************************************************************************
2786*******************************************************************************/
2787REGFI_VK_REC* regfi_parse_vk(REGFI_FILE* file, uint32_t offset, 
2788                             uint32_t max_size, bool strict)
2789{
2790  REGFI_VK_REC* ret_val;
2791  uint8_t vk_header[REGFI_VK_MIN_LENGTH];
2792  uint32_t raw_data_size, length, cell_length;
2793  bool unalloc = false;
2794
2795  ret_val = talloc(NULL, REGFI_VK_REC);
2796  if(ret_val == NULL)
2797    goto fail;
2798
2799  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_nk"))
2800    goto fail;
2801
2802  if(!regfi_parse_cell(file->cb, offset, vk_header, REGFI_VK_MIN_LENGTH,
2803                       &cell_length, &unalloc))
2804  {
2805    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2806                  " while parsing VK record at offset 0x%.8X.", offset);
2807    goto fail_locked;
2808  }
2809
2810  ret_val->offset = offset;
2811  ret_val->cell_size = cell_length;
2812  ret_val->valuename = NULL;
2813  ret_val->valuename_raw = NULL;
2814 
2815  if(ret_val->cell_size > max_size)
2816    ret_val->cell_size = max_size & 0xFFFFFFF8;
2817  if((ret_val->cell_size < REGFI_VK_MIN_LENGTH) 
2818     || (ret_val->cell_size & 0x00000007) != 0)
2819  {
2820    regfi_log_add(REGFI_LOG_WARN, "Invalid cell size encountered"
2821                  " while parsing VK record at offset 0x%.8X.", offset);
2822    goto fail_locked;
2823  }
2824
2825  ret_val->magic[0] = vk_header[0x0];
2826  ret_val->magic[1] = vk_header[0x1];
2827  if((ret_val->magic[0] != 'v') || (ret_val->magic[1] != 'k'))
2828  {
2829    /* XXX: This does not account for deleted keys under Win2K which
2830     *      often have this (and the name length) overwritten with
2831     *      0xFFFF.
2832     */
2833    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch"
2834                  " while parsing VK record at offset 0x%.8X.", offset);
2835    goto fail_locked;
2836  }
2837
2838  ret_val->name_length = SVAL(vk_header, 0x2);
2839  raw_data_size = IVAL(vk_header, 0x4);
2840  ret_val->data_size = raw_data_size & ~REGFI_VK_DATA_IN_OFFSET;
2841  /* The data is typically stored in the offset if the size <= 4,
2842   * in which case this flag is set.
2843   */
2844  ret_val->data_in_offset = (bool)(raw_data_size & REGFI_VK_DATA_IN_OFFSET);
2845  ret_val->data_off = IVAL(vk_header, 0x8);
2846  ret_val->type = IVAL(vk_header, 0xC);
2847  ret_val->flags = SVAL(vk_header, 0x10);
2848  ret_val->unknown1 = SVAL(vk_header, 0x12);
2849
2850  if(ret_val->name_length > 0)
2851  {
2852    if(ret_val->name_length + REGFI_VK_MIN_LENGTH + 4 > ret_val->cell_size)
2853    {
2854      regfi_log_add(REGFI_LOG_WARN, "Name too long for remaining cell"
2855                    " space while parsing VK record at offset 0x%.8X.",
2856                    offset);
2857      if(strict)
2858        goto fail_locked;
2859      else
2860        ret_val->name_length = ret_val->cell_size - REGFI_VK_MIN_LENGTH - 4;
2861    }
2862
2863    /* Round up to the next multiple of 8 */
2864    cell_length = (ret_val->name_length + REGFI_VK_MIN_LENGTH + 4) & 0xFFFFFFF8;
2865    if(cell_length < ret_val->name_length + REGFI_VK_MIN_LENGTH + 4)
2866      cell_length+=8;
2867
2868    ret_val->valuename_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2869    if(ret_val->valuename_raw == NULL)
2870      goto fail_locked;
2871
2872    length = ret_val->name_length;
2873    if((regfi_read(file->cb, (uint8_t*)ret_val->valuename_raw, &length) != 0)
2874       || length != ret_val->name_length)
2875    {
2876      regfi_log_add(REGFI_LOG_ERROR, "Could not read value name"
2877                    " while parsing VK record at offset 0x%.8X.", offset);
2878      goto fail_locked;
2879    }
2880  }
2881  else
2882    cell_length = REGFI_VK_MIN_LENGTH + 4;
2883
2884  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_nk"))
2885    goto fail;
2886
2887  if(unalloc)
2888  {
2889    /* If cell_size is still greater, truncate. */
2890    if(cell_length < ret_val->cell_size)
2891      ret_val->cell_size = cell_length;
2892  }
2893
2894  return ret_val;
2895 
2896 fail_locked:
2897  regfi_unlock(file, &file->cb_lock, "regfi_parse_vk");
2898 fail:
2899  talloc_free(ret_val);
2900  return NULL;
2901}
2902
2903
2904/******************************************************************************
2905 *
2906 ******************************************************************************/
2907REGFI_BUFFER regfi_load_data(REGFI_FILE* file, uint32_t voffset,
2908                             uint32_t length, bool data_in_offset,
2909                             bool strict)
2910{
2911  REGFI_BUFFER ret_val;
2912  uint32_t cell_length, offset;
2913  int32_t max_size;
2914  bool unalloc;
2915 
2916  /* Microsoft's documentation indicates that "available memory" is
2917   * the limit on value sizes for the more recent registry format version.
2918   * This is not only annoying, but it's probably also incorrect, since clearly
2919   * value data sizes are limited to 2^31 (high bit used as a flag) and even
2920   * with big data records, the apparent max size is:
2921   *   16344 * 2^16 = 1071104040 (~1GB).
2922   *
2923   * We choose to limit it to 1M which was the limit in older versions and
2924   * should rarely be exceeded unless the file is corrupt or malicious.
2925   * For more info, see:
2926   *   http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
2927   */
2928  /* XXX: add way to skip this check at user discression. */
2929  if(length > REGFI_VK_MAX_DATA_LENGTH)
2930  {
2931    regfi_log_add(REGFI_LOG_WARN, "Value data size %d larger than "
2932                  "%d, truncating...", length, REGFI_VK_MAX_DATA_LENGTH);
2933    length = REGFI_VK_MAX_DATA_LENGTH;
2934  }
2935
2936  if(data_in_offset)
2937    return regfi_parse_little_data(file, voffset, length, strict);
2938  else
2939  {
2940    offset = voffset + REGFI_REGF_SIZE;
2941    max_size = regfi_calc_maxsize(file, offset);
2942    if(max_size < 0)
2943    {
2944      regfi_log_add(REGFI_LOG_WARN, "Could not find HBIN for data"
2945                    " at offset 0x%.8X.", offset);
2946      goto fail;
2947    }
2948   
2949    if(!regfi_lock(file, &file->cb_lock, "regfi_load_data"))
2950      goto fail;
2951
2952    if(!regfi_parse_cell(file->cb, offset, NULL, 0,
2953                         &cell_length, &unalloc))
2954    {
2955      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
2956                    " parsing data record at offset 0x%.8X.", offset);
2957      goto fail_locked;
2958    }
2959
2960    if(!regfi_unlock(file, &file->cb_lock, "regfi_load_data"))
2961      goto fail;
2962
2963    if((cell_length & 0x00000007) != 0)
2964    {
2965      regfi_log_add(REGFI_LOG_WARN, "Cell length not multiple of 8"
2966                    " while parsing data record at offset 0x%.8X.",
2967                    offset);
2968      goto fail;
2969    }
2970
2971    if(cell_length > max_size)
2972    {
2973      regfi_log_add(REGFI_LOG_WARN, "Cell extends past HBIN boundary"
2974                    " while parsing data record at offset 0x%.8X.",
2975                    offset);
2976      goto fail;
2977    }
2978
2979    if(cell_length - 4 < length)
2980    {
2981      /* XXX: All big data records thus far have been 16 bytes long. 
2982       *      Should we check for this precise size instead of just
2983       *      relying upon the above check?
2984       */
2985      if (file->major_version >= 1 && file->minor_version >= 5)
2986      {
2987        /* Attempt to parse a big data record */
2988        return regfi_load_big_data(file, offset, length, cell_length, 
2989                                   NULL, strict);
2990      }
2991      else
2992      {
2993        regfi_log_add(REGFI_LOG_WARN, "Data length (0x%.8X) larger than"
2994                      " remaining cell length (0x%.8X)"
2995                      " while parsing data record at offset 0x%.8X.", 
2996                      length, cell_length - 4, offset);
2997        if(strict)
2998          goto fail;
2999        else
3000          length = cell_length - 4;
3001      }
3002    }
3003
3004    ret_val = regfi_parse_data(file, offset, length, strict);
3005  }
3006
3007  return ret_val;
3008
3009 fail_locked:
3010  regfi_unlock(file, &file->cb_lock, "regfi_load_data");
3011 fail:
3012  ret_val.buf = NULL;
3013  ret_val.len = 0;
3014  return ret_val;
3015}
3016
3017
3018/******************************************************************************
3019 * Parses the common case data records stored in a single cell.
3020 ******************************************************************************/
3021REGFI_BUFFER regfi_parse_data(REGFI_FILE* file, uint32_t offset,
3022                              uint32_t length, bool strict)
3023{
3024  REGFI_BUFFER ret_val;
3025  uint32_t read_length;
3026
3027  ret_val.buf = NULL;
3028  ret_val.len = 0;
3029 
3030  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
3031    goto fail;
3032  ret_val.len = length;
3033
3034  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_data"))
3035    goto fail;
3036
3037  if(regfi_seek(file->cb, offset+4, SEEK_SET) == -1)
3038  {
3039    regfi_log_add(REGFI_LOG_WARN, "Could not seek while "
3040                  "reading data at offset 0x%.8X.", offset);
3041    goto fail_locked;
3042  }
3043 
3044  read_length = length;
3045  if((regfi_read(file->cb, ret_val.buf, &read_length) != 0)
3046     || read_length != length)
3047  {
3048    regfi_log_add(REGFI_LOG_ERROR, "Could not read data block while"
3049                  " parsing data record at offset 0x%.8X.", offset);
3050    goto fail_locked;
3051  }
3052
3053  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_data"))
3054    goto fail;
3055
3056  return ret_val;
3057
3058 fail_locked:
3059  regfi_unlock(file, &file->cb_lock, "regfi_parse_data");
3060 fail:
3061  talloc_free(ret_val.buf);
3062  ret_val.buf = NULL;
3063  ret_val.buf = 0;
3064  return ret_val;
3065}
3066
3067
3068
3069/******************************************************************************
3070 *
3071 ******************************************************************************/
3072REGFI_BUFFER regfi_parse_little_data(REGFI_FILE* file, uint32_t voffset,
3073                                     uint32_t length, bool strict)
3074{
3075  uint8_t i;
3076  REGFI_BUFFER ret_val;
3077
3078  ret_val.buf = NULL;
3079  ret_val.len = 0;
3080
3081  if(length > 4)
3082  {
3083    regfi_log_add(REGFI_LOG_ERROR, "Data in offset but length > 4"
3084                  " while parsing data record. (voffset=0x%.8X, length=%d)",
3085                  voffset, length);
3086    return ret_val;
3087  }
3088
3089  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
3090    return ret_val;
3091  ret_val.len = length;
3092 
3093  for(i = 0; i < length; i++)
3094    ret_val.buf[i] = (uint8_t)((voffset >> i*8) & 0xFF);
3095
3096  return ret_val;
3097}
3098
3099/******************************************************************************
3100*******************************************************************************/
3101REGFI_BUFFER regfi_parse_big_data_header(REGFI_FILE* file, uint32_t offset, 
3102                                         uint32_t max_size, bool strict)
3103{
3104  REGFI_BUFFER ret_val;
3105  uint32_t cell_length;
3106  bool unalloc;
3107
3108  /* XXX: do something with unalloc? */
3109  ret_val.buf = (uint8_t*)talloc_array(NULL, uint8_t, REGFI_BIG_DATA_MIN_LENGTH);
3110  if(ret_val.buf == NULL)
3111    goto fail;
3112
3113  if(REGFI_BIG_DATA_MIN_LENGTH > max_size)
3114  {
3115    regfi_log_add(REGFI_LOG_WARN, "Big data header exceeded max_size "
3116                  "while parsing big data header at offset 0x%.8X.",offset);
3117    goto fail;
3118  }
3119
3120  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_big_data_header"))
3121    goto fail;
3122
3123
3124  if(!regfi_parse_cell(file->cb, offset, ret_val.buf, REGFI_BIG_DATA_MIN_LENGTH,
3125                       &cell_length, &unalloc))
3126  {
3127    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3128                  " parsing big data header at offset 0x%.8X.", offset);
3129    goto fail_locked;
3130  }
3131
3132  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_header"))
3133    goto fail;
3134
3135  if((ret_val.buf[0] != 'd') || (ret_val.buf[1] != 'b'))
3136  {
3137    regfi_log_add(REGFI_LOG_WARN, "Unknown magic number"
3138                  " (0x%.2X, 0x%.2X) encountered while parsing"
3139                  " big data header at offset 0x%.8X.", 
3140                  ret_val.buf[0], ret_val.buf[1], offset);
3141    goto fail;
3142  }
3143
3144  ret_val.len = REGFI_BIG_DATA_MIN_LENGTH;
3145  return ret_val;
3146
3147 fail_locked:
3148  regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_header");
3149 fail:
3150  talloc_free(ret_val.buf);
3151  ret_val.buf = NULL;
3152  ret_val.len = 0;
3153  return ret_val;
3154}
3155
3156
3157
3158/******************************************************************************
3159 *
3160 ******************************************************************************/
3161uint32_t* regfi_parse_big_data_indirect(REGFI_FILE* file, uint32_t offset,
3162                                      uint16_t num_chunks, bool strict)
3163{
3164  uint32_t* ret_val;
3165  uint32_t indirect_length;
3166  int32_t max_size;
3167  uint16_t i;
3168  bool unalloc;
3169
3170  /* XXX: do something with unalloc? */
3171
3172  max_size = regfi_calc_maxsize(file, offset);
3173  if((max_size < 0) || (num_chunks*sizeof(uint32_t) + 4 > max_size))
3174    return NULL;
3175
3176  ret_val = (uint32_t*)talloc_array(NULL, uint32_t, num_chunks);
3177  if(ret_val == NULL)
3178    goto fail;
3179
3180  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_big_data_indirect"))
3181    goto fail;
3182
3183  if(!regfi_parse_cell(file->cb, offset, (uint8_t*)ret_val,
3184                       num_chunks*sizeof(uint32_t),
3185                       &indirect_length, &unalloc))
3186  {
3187    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3188                  " parsing big data indirect record at offset 0x%.8X.", 
3189                  offset);
3190    goto fail_locked;
3191  }
3192
3193  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_indirect"))
3194    goto fail;
3195
3196  /* Convert pointers to proper endianess, verify they are aligned. */
3197  for(i=0; i<num_chunks; i++)
3198  {
3199    ret_val[i] = IVAL(ret_val, i*sizeof(uint32_t));
3200    if((ret_val[i] & 0x00000007) != 0)
3201      goto fail;
3202  }
3203 
3204  return ret_val;
3205
3206 fail_locked:
3207  regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_indirect");
3208 fail:
3209  talloc_free(ret_val);
3210  return NULL;
3211}
3212
3213
3214/******************************************************************************
3215 * Arguments:
3216 *  file       --
3217 *  offsets    -- list of virtual offsets.
3218 *  num_chunks --
3219 *  strict     --
3220 *
3221 * Returns:
3222 *  A range_list with physical offsets and complete lengths
3223 *  (including cell headers) of associated cells. 
3224 *  No data in range_list elements.
3225 ******************************************************************************/
3226range_list* regfi_parse_big_data_cells(REGFI_FILE* file, uint32_t* offsets,
3227                                       uint16_t num_chunks, bool strict)
3228{
3229  uint32_t cell_length, chunk_offset;
3230  range_list* ret_val;
3231  uint16_t i;
3232  bool unalloc;
3233 
3234  /* XXX: do something with unalloc? */
3235  ret_val = range_list_new();
3236  if(ret_val == NULL)
3237    goto fail;
3238 
3239  for(i=0; i<num_chunks; i++)
3240  {
3241    if(!regfi_lock(file, &file->cb_lock, "regfi_parse_big_data_cells"))
3242      goto fail;
3243
3244    chunk_offset = offsets[i]+REGFI_REGF_SIZE;
3245    if(!regfi_parse_cell(file->cb, chunk_offset, NULL, 0,
3246                         &cell_length, &unalloc))
3247    {
3248      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3249                    " parsing big data chunk at offset 0x%.8X.", 
3250                    chunk_offset);
3251      goto fail_locked;
3252    }
3253
3254    if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_cells"))
3255      goto fail;
3256
3257    if(!range_list_add(ret_val, chunk_offset, cell_length, NULL))
3258      goto fail;
3259  }
3260
3261  return ret_val;
3262
3263 fail_locked:
3264  regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_cells");
3265 fail:
3266  if(ret_val != NULL)
3267    range_list_free(ret_val);
3268  return NULL;
3269}
3270
3271
3272/******************************************************************************
3273*******************************************************************************/
3274REGFI_BUFFER regfi_load_big_data(REGFI_FILE* file, 
3275                                 uint32_t offset, uint32_t data_length, 
3276                                 uint32_t cell_length, range_list* used_ranges,
3277                                 bool strict)
3278{
3279  REGFI_BUFFER ret_val;
3280  uint16_t num_chunks, i;
3281  uint32_t read_length, data_left, tmp_len, indirect_offset;
3282  uint32_t* indirect_ptrs = NULL;
3283  REGFI_BUFFER bd_header;
3284  range_list* bd_cells = NULL;
3285  const range_list_element* cell_info;
3286
3287  ret_val.buf = NULL;
3288
3289  /* XXX: Add better error/warning messages */
3290
3291  bd_header = regfi_parse_big_data_header(file, offset, cell_length, strict);
3292  if(bd_header.buf == NULL)
3293    goto fail;
3294
3295  /* Keep track of used space for use by reglookup-recover */
3296  if(used_ranges != NULL)
3297    if(!range_list_add(used_ranges, offset, cell_length, NULL))
3298      goto fail;
3299
3300  num_chunks = SVAL(bd_header.buf, 0x2);
3301  indirect_offset = IVAL(bd_header.buf, 0x4) + REGFI_REGF_SIZE;
3302  talloc_free(bd_header.buf);
3303
3304  indirect_ptrs = regfi_parse_big_data_indirect(file, indirect_offset,
3305                                                num_chunks, strict);
3306  if(indirect_ptrs == NULL)
3307    goto fail;
3308
3309  if(used_ranges != NULL)
3310    if(!range_list_add(used_ranges, indirect_offset, num_chunks*4+4, NULL))
3311      goto fail;
3312 
3313  if((ret_val.buf = talloc_array(NULL, uint8_t, data_length)) == NULL)
3314    goto fail;
3315  data_left = data_length;
3316
3317  bd_cells = regfi_parse_big_data_cells(file, indirect_ptrs, num_chunks, strict);
3318  if(bd_cells == NULL)
3319    goto fail;
3320
3321  talloc_free(indirect_ptrs);
3322  indirect_ptrs = NULL;
3323 
3324  for(i=0; (i<num_chunks) && (data_left>0); i++)
3325  {
3326    cell_info = range_list_get(bd_cells, i);
3327    if(cell_info == NULL)
3328      goto fail;
3329
3330    /* XXX: This should be "cell_info->length-4" to account for the 4 byte cell
3331     *      length.  However, it has been observed that some (all?) chunks
3332     *      have an additional 4 bytes of 0 at the end of their cells that
3333     *      isn't part of the data, so we're trimming that off too.
3334     *      Perhaps it's just an 8 byte alignment requirement...
3335     */
3336    if(cell_info->length - 8 >= data_left)
3337    {
3338      if(i+1 != num_chunks)
3339      {
3340        regfi_log_add(REGFI_LOG_WARN, "Left over chunks detected "
3341                      "while constructing big data at offset 0x%.8X "
3342                      "(chunk offset 0x%.8X).", offset, cell_info->offset);
3343      }
3344      read_length = data_left;
3345    }
3346    else
3347      read_length = cell_info->length - 8;
3348
3349
3350    if(read_length > regfi_calc_maxsize(file, cell_info->offset))
3351    {
3352      regfi_log_add(REGFI_LOG_WARN, "A chunk exceeded the maxsize "
3353                    "while constructing big data at offset 0x%.8X "
3354                    "(chunk offset 0x%.8X).", offset, cell_info->offset);
3355      goto fail;
3356    }
3357
3358    if(!regfi_lock(file, &file->cb_lock, "regfi_load_big_data"))
3359      goto fail;
3360
3361    if(regfi_seek(file->cb, cell_info->offset+sizeof(uint32_t), SEEK_SET) == -1)
3362    {
3363      regfi_log_add(REGFI_LOG_WARN, "Could not seek to chunk while "
3364                    "constructing big data at offset 0x%.8X "
3365                    "(chunk offset 0x%.8X).", offset, cell_info->offset);
3366      goto fail_locked;
3367    }
3368
3369    tmp_len = read_length;
3370    if(regfi_read(file->cb, ret_val.buf+(data_length-data_left), 
3371                  &read_length) != 0 || (read_length != tmp_len))
3372    {
3373      regfi_log_add(REGFI_LOG_WARN, "Could not read data chunk while"
3374                    " constructing big data at offset 0x%.8X"
3375                    " (chunk offset 0x%.8X).", offset, cell_info->offset);
3376      goto fail_locked;
3377    }
3378
3379    if(!regfi_unlock(file, &file->cb_lock, "regfi_load_big_data"))
3380      goto fail;
3381
3382    if(used_ranges != NULL)
3383      if(!range_list_add(used_ranges, cell_info->offset,cell_info->length,NULL))
3384        goto fail;
3385
3386    data_left -= read_length;
3387  }
3388  range_list_free(bd_cells);
3389
3390  ret_val.len = data_length-data_left;
3391  return ret_val;
3392
3393 fail_locked:
3394  regfi_unlock(file, &file->cb_lock, "regfi_load_big_data");
3395 fail:
3396  talloc_free(ret_val.buf);
3397  talloc_free(indirect_ptrs);
3398  if(bd_cells != NULL)
3399    range_list_free(bd_cells);
3400  ret_val.buf = NULL;
3401  ret_val.len = 0;
3402  return ret_val;
3403}
3404
3405
3406range_list* regfi_parse_unalloc_cells(REGFI_FILE* file)
3407{
3408  range_list* ret_val;
3409  REGFI_HBIN* hbin;
3410  const range_list_element* hbins_elem;
3411  uint32_t i, num_hbins, curr_off, cell_len;
3412  bool is_unalloc;
3413
3414  ret_val = range_list_new();
3415  if(ret_val == NULL)
3416    return NULL;
3417
3418  if(!regfi_read_lock(file, &file->hbins_lock, "regfi_parse_unalloc_cells"))
3419  {
3420    range_list_free(ret_val);
3421    return NULL;
3422  }
3423
3424  num_hbins = range_list_size(file->hbins);
3425  for(i=0; i<num_hbins; i++)
3426  {
3427    hbins_elem = range_list_get(file->hbins, i);
3428    if(hbins_elem == NULL)
3429      break;
3430    hbin = (REGFI_HBIN*)hbins_elem->data;
3431
3432    curr_off = REGFI_HBIN_HEADER_SIZE;
3433    while(curr_off < hbin->block_size)
3434    {
3435      if(!regfi_lock(file, &file->cb_lock, "regfi_parse_unalloc_cells"))
3436        break;
3437
3438      if(!regfi_parse_cell(file->cb, hbin->file_off+curr_off, NULL, 0,
3439                           &cell_len, &is_unalloc))
3440      {
3441        regfi_unlock(file, &file->cb_lock, "regfi_parse_unalloc_cells");
3442        break;
3443      }
3444
3445      if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_unalloc_cells"))
3446        break;
3447
3448      if((cell_len == 0) || ((cell_len & 0x00000007) != 0))
3449      {
3450        regfi_log_add(REGFI_LOG_ERROR, "Bad cell length encountered"
3451                      " while parsing unallocated cells at offset 0x%.8X.",
3452                      hbin->file_off+curr_off);
3453        break;
3454      }
3455
3456      /* for some reason the record_size of the last record in
3457         an hbin block can extend past the end of the block
3458         even though the record fits within the remaining
3459         space....aaarrrgggghhhhhh */ 
3460      if(curr_off + cell_len >= hbin->block_size)
3461        cell_len = hbin->block_size - curr_off;
3462     
3463      if(is_unalloc)
3464        range_list_add(ret_val, hbin->file_off+curr_off, 
3465                       cell_len, NULL);
3466     
3467      curr_off = curr_off+cell_len;
3468    }
3469  }
3470
3471  if(!regfi_rw_unlock(file, &file->hbins_lock, "regfi_parse_unalloc_cells"))
3472  {
3473    range_list_free(ret_val);
3474    return NULL;
3475  }
3476
3477  return ret_val;
3478}
3479
3480
3481/* From lib/time.c */
3482
3483/****************************************************************************
3484 Put a 8 byte filetime from a time_t
3485 This takes real GMT as input and converts to kludge-GMT
3486****************************************************************************/
3487void regfi_unix2nt_time(REGFI_NTTIME *nt, time_t t)
3488{
3489  double d;
3490 
3491  if (t==0) 
3492  {
3493    nt->low = 0;
3494    nt->high = 0;
3495    return;
3496  }
3497 
3498  if (t == TIME_T_MAX) 
3499  {
3500    nt->low = 0xffffffff;
3501    nt->high = 0x7fffffff;
3502    return;
3503  }             
3504 
3505  if (t == -1) 
3506  {
3507    nt->low = 0xffffffff;
3508    nt->high = 0xffffffff;
3509    return;
3510  }             
3511 
3512  /* this converts GMT to kludge-GMT */
3513  /* XXX: This was removed due to difficult dependency requirements. 
3514   *      So far, times appear to be correct without this adjustment, but
3515   *      that may be proven wrong with adequate testing.
3516   */
3517  /* t -= TimeDiff(t) - get_serverzone(); */
3518 
3519  d = (double)(t);
3520  d += TIME_FIXUP_CONSTANT;
3521  d *= 1.0e7;
3522 
3523  nt->high = (uint32_t)(d * (1.0/(4.0*(double)(1<<30))));
3524  nt->low  = (uint32_t)(d - ((double)nt->high)*4.0*(double)(1<<30));
3525}
3526
3527
3528/****************************************************************************
3529 Interpret an 8 byte "filetime" structure to a time_t
3530 It's originally in "100ns units since jan 1st 1601"
3531
3532 An 8 byte value of 0xffffffffffffffff will be returned as (time_t)0.
3533
3534 It appears to be kludge-GMT (at least for file listings). This means
3535 its the GMT you get by taking a localtime and adding the
3536 serverzone. This is NOT the same as GMT in some cases. This routine
3537 converts this to real GMT.
3538****************************************************************************/
3539time_t regfi_nt2unix_time(const REGFI_NTTIME* nt)
3540{
3541  double d;
3542  time_t ret;
3543  /* The next two lines are a fix needed for the
3544     broken SCO compiler. JRA. */
3545  time_t l_time_min = TIME_T_MIN;
3546  time_t l_time_max = TIME_T_MAX;
3547 
3548  if (nt->high == 0 || (nt->high == 0xffffffff && nt->low == 0xffffffff))
3549    return(0);
3550 
3551  d = ((double)nt->high)*4.0*(double)(1<<30);
3552  d += (nt->low&0xFFF00000);
3553  d *= 1.0e-7;
3554 
3555  /* now adjust by 369 years to make the secs since 1970 */
3556  d -= TIME_FIXUP_CONSTANT;
3557 
3558  if (d <= l_time_min)
3559    return (l_time_min);
3560 
3561  if (d >= l_time_max)
3562    return (l_time_max);
3563 
3564  ret = (time_t)(d+0.5);
3565 
3566  /* this takes us from kludge-GMT to real GMT */
3567  /* XXX: This was removed due to difficult dependency requirements. 
3568   *      So far, times appear to be correct without this adjustment, but
3569   *      that may be proven wrong with adequate testing.
3570   */
3571  /*
3572    ret -= get_serverzone();
3573    ret += LocTimeDiff(ret);
3574  */
3575
3576  return(ret);
3577}
3578
3579/* End of stuff from lib/time.c */
Note: See TracBrowser for help on using the repository browser.