source: trunk/lib/regfi.c @ 225

Last change on this file since 225 was 225, checked in by tim, 13 years ago

added test case for python callback read/seek
began adding windows support in pyregfi
improved win32 build target

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