source: trunk/lib/regfi.c @ 185

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

reworked logging API again to simplify interface

updated regfi-threadtest to work with more recent commits

  • Property svn:keywords set to Id
File size: 97.5 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 185 2010-03-23 02:22:07Z 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, buf + rsize, *length - rsize);
615    if(rret > 0)
616      rsize += rret;
617  }while(*length - rsize > 0 
618         && (rret > 0 || (rret == -1 && (errno == EAGAIN || errno == EINTR))));
619 
620  *length = rsize;
621  if (rret == -1 && errno != EINTR && errno != EAGAIN)
622    return errno;
623
624  return 0;
625}
626
627
628/*****************************************************************************
629 *
630 *****************************************************************************/
631bool regfi_parse_cell(REGFI_RAW_FILE* file_cb, uint32_t offset, uint8_t* hdr, 
632                      uint32_t hdr_len, uint32_t* cell_length, bool* unalloc)
633{
634  uint32_t length;
635  int32_t raw_length;
636  uint8_t tmp[4];
637
638  if(regfi_seek(file_cb, offset, SEEK_SET) == -1)
639    return false;
640
641  length = 4;
642  if((regfi_read(file_cb, tmp, &length) != 0) || length != 4)
643    return false;
644  raw_length = IVALS(tmp, 0);
645
646  if(raw_length < 0)
647  {
648    (*cell_length) = raw_length*(-1);
649    (*unalloc) = false;
650  }
651  else
652  {
653    (*cell_length) = raw_length;
654    (*unalloc) = true;
655  }
656
657  if(*cell_length - 4 < hdr_len)
658    return false;
659
660  if(hdr_len > 0)
661  {
662    length = hdr_len;
663    if((regfi_read(file_cb, hdr, &length) != 0) || length != hdr_len)
664      return false;
665  }
666
667  return true;
668}
669
670
671/******************************************************************************
672 * Given an offset and an hbin, is the offset within that hbin?
673 * The offset is a virtual file offset.
674 ******************************************************************************/
675static bool regfi_offset_in_hbin(const REGFI_HBIN* hbin, uint32_t voffset)
676{
677  if(!hbin)
678    return false;
679
680  if((voffset > hbin->first_hbin_off) 
681     && (voffset < (hbin->first_hbin_off + hbin->block_size)))
682    return true;
683               
684  return false;
685}
686
687
688
689/******************************************************************************
690 * Provide a physical offset and receive the correpsonding HBIN
691 * block for it.  NULL if one doesn't exist.
692 ******************************************************************************/
693const REGFI_HBIN* regfi_lookup_hbin(REGFI_FILE* file, uint32_t offset)
694{
695  return (const REGFI_HBIN*)range_list_find_data(file->hbins, offset);
696}
697
698
699/******************************************************************************
700 * Calculate the largest possible cell size given a physical offset.
701 * Largest size is based on the HBIN the offset is currently a member of.
702 * Returns negative values on error.
703 * (Since cells can only be ~2^31 in size, this works out.)
704 ******************************************************************************/
705int32_t regfi_calc_maxsize(REGFI_FILE* file, uint32_t offset)
706{
707  const REGFI_HBIN* hbin = regfi_lookup_hbin(file, offset);
708  if(hbin == NULL)
709    return -1;
710
711  return (hbin->block_size + hbin->file_off) - offset;
712}
713
714
715/******************************************************************************
716 ******************************************************************************/
717REGFI_SUBKEY_LIST* regfi_load_subkeylist(REGFI_FILE* file, uint32_t offset, 
718                                         uint32_t num_keys, uint32_t max_size, 
719                                         bool strict)
720{
721  REGFI_SUBKEY_LIST* ret_val;
722
723  ret_val = regfi_load_subkeylist_aux(file, offset, max_size, strict, 
724                                      REGFI_MAX_SUBKEY_DEPTH);
725  if(ret_val == NULL)
726  {
727    regfi_log_add(REGFI_LOG_WARN, "Failed to load subkey list at"
728                      " offset 0x%.8X.", offset);
729    return NULL;
730  }
731
732  if(num_keys != ret_val->num_keys)
733  {
734    /*  Not sure which should be authoritative, the number from the
735     *  NK record, or the number in the subkey list.  Just emit a warning for
736     *  now if they don't match.
737     */
738    regfi_log_add(REGFI_LOG_WARN, "Number of subkeys listed in parent"
739                      " (%d) did not match number found in subkey list/tree (%d)"
740                      " while parsing subkey list/tree at offset 0x%.8X.", 
741                      num_keys, ret_val->num_keys, offset);
742  }
743
744  return ret_val;
745}
746
747
748/******************************************************************************
749 ******************************************************************************/
750REGFI_SUBKEY_LIST* regfi_load_subkeylist_aux(REGFI_FILE* file, uint32_t offset, 
751                                             uint32_t max_size, bool strict,
752                                             uint8_t depth_left)
753{
754  REGFI_SUBKEY_LIST* ret_val;
755  REGFI_SUBKEY_LIST** sublists;
756  uint32_t i, num_sublists, off;
757  int32_t sublist_maxsize;
758
759  if(depth_left == 0)
760  {
761    regfi_log_add(REGFI_LOG_WARN, "Maximum depth reached"
762                      " while parsing subkey list/tree at offset 0x%.8X.", 
763                      offset);
764    return NULL;
765  }
766
767  ret_val = regfi_parse_subkeylist(file, offset, max_size, strict);
768  if(ret_val == NULL)
769    return NULL;
770
771  if(ret_val->recursive_type)
772  {
773    num_sublists = ret_val->num_children;
774    sublists = (REGFI_SUBKEY_LIST**)malloc(num_sublists
775                                           * sizeof(REGFI_SUBKEY_LIST*));
776    for(i=0; i < num_sublists; i++)
777    {
778      off = ret_val->elements[i].offset + REGFI_REGF_SIZE;
779
780      sublist_maxsize = regfi_calc_maxsize(file, off);
781      if(sublist_maxsize < 0)
782        sublists[i] = NULL;
783      else
784        sublists[i] = regfi_load_subkeylist_aux(file, off, sublist_maxsize, 
785                                                strict, depth_left-1);
786    }
787    talloc_free(ret_val);
788
789    return regfi_merge_subkeylists(num_sublists, sublists, strict);
790  }
791
792  return ret_val;
793}
794
795
796/******************************************************************************
797 ******************************************************************************/
798REGFI_SUBKEY_LIST* regfi_parse_subkeylist(REGFI_FILE* file, uint32_t offset, 
799                                          uint32_t max_size, bool strict)
800{
801  REGFI_SUBKEY_LIST* ret_val;
802  uint32_t i, cell_length, length, elem_size, read_len;
803  uint8_t* elements = NULL;
804  uint8_t buf[REGFI_SUBKEY_LIST_MIN_LEN];
805  bool unalloc;
806  bool recursive_type;
807
808  if(!regfi_lock(file, file->cb_lock, "regfi_parse_subkeylist"))
809     goto fail;
810
811  if(!regfi_parse_cell(file->cb, offset, buf, REGFI_SUBKEY_LIST_MIN_LEN,
812                       &cell_length, &unalloc))
813  {
814    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while "
815                      "parsing subkey-list at offset 0x%.8X.", offset);
816    goto fail_locked;
817  }
818
819  if(cell_length > max_size)
820  {
821    regfi_log_add(REGFI_LOG_WARN, "Cell size longer than max_size"
822                      " while parsing subkey-list at offset 0x%.8X.", offset);
823    if(strict)
824      goto fail_locked;
825    cell_length = max_size & 0xFFFFFFF8;
826  }
827
828  recursive_type = false;
829  if(buf[0] == 'r' && buf[1] == 'i')
830  {
831    recursive_type = true;
832    elem_size = sizeof(uint32_t);
833  }
834  else if(buf[0] == 'l' && buf[1] == 'i')
835    elem_size = sizeof(uint32_t);
836  else if((buf[0] == 'l') && (buf[1] == 'f' || buf[1] == 'h'))
837    elem_size = sizeof(REGFI_SUBKEY_LIST_ELEM);
838  else
839  {
840    regfi_log_add(REGFI_LOG_ERROR, "Unknown magic number"
841                      " (0x%.2X, 0x%.2X) encountered while parsing"
842                      " subkey-list at offset 0x%.8X.", buf[0], buf[1], offset);
843    goto fail_locked;
844  }
845
846  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
847  if(ret_val == NULL)
848    goto fail_locked;
849
850  ret_val->offset = offset;
851  ret_val->cell_size = cell_length;
852  ret_val->magic[0] = buf[0];
853  ret_val->magic[1] = buf[1];
854  ret_val->recursive_type = recursive_type;
855  ret_val->num_children = SVAL(buf, 0x2);
856
857  if(!recursive_type)
858    ret_val->num_keys = ret_val->num_children;
859
860  length = elem_size*ret_val->num_children;
861  if(cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t) < length)
862  {
863    regfi_log_add(REGFI_LOG_WARN, "Number of elements too large for"
864                      " cell while parsing subkey-list at offset 0x%.8X.", 
865                      offset);
866    if(strict)
867      goto fail_locked;
868    length = cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t);
869  }
870
871  ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM, 
872                                   ret_val->num_children);
873  if(ret_val->elements == NULL)
874    goto fail_locked;
875
876  elements = (uint8_t*)malloc(length);
877  if(elements == NULL)
878    goto fail_locked;
879
880  read_len = length;
881  if(regfi_read(file->cb, elements, &read_len) != 0 || read_len!=length)
882    goto fail_locked;
883
884  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_subkeylist"))
885     goto fail;
886
887  if(elem_size == sizeof(uint32_t))
888  {
889    for (i=0; i < ret_val->num_children; i++)
890    {
891      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
892      ret_val->elements[i].hash = 0;
893    }
894  }
895  else
896  {
897    for (i=0; i < ret_val->num_children; i++)
898    {
899      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
900      ret_val->elements[i].hash = IVAL(elements, i*elem_size+4);
901    }
902  }
903  free(elements);
904
905  return ret_val;
906
907 fail_locked:
908  regfi_unlock(file, file->cb_lock, "regfi_parse_subkeylist");
909 fail:
910  if(elements != NULL)
911    free(elements);
912  talloc_free(ret_val);
913  return NULL;
914}
915
916
917/*******************************************************************
918 *******************************************************************/
919REGFI_SUBKEY_LIST* regfi_merge_subkeylists(uint16_t num_lists, 
920                                           REGFI_SUBKEY_LIST** lists,
921                                           bool strict)
922{
923  uint32_t i,j,k;
924  REGFI_SUBKEY_LIST* ret_val;
925
926  if(lists == NULL)
927    return NULL;
928  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
929
930  if(ret_val == NULL)
931    return NULL;
932 
933  /* Obtain total number of elements */
934  ret_val->num_keys = 0;
935  for(i=0; i < num_lists; i++)
936  {
937    if(lists[i] != NULL)
938      ret_val->num_keys += lists[i]->num_children;
939  }
940  ret_val->num_children = ret_val->num_keys;
941
942  if(ret_val->num_keys > 0)
943  {
944    ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM,
945                                     ret_val->num_keys);
946    k=0;
947
948    if(ret_val->elements != NULL)
949    {
950      for(i=0; i < num_lists; i++)
951      {
952        if(lists[i] != NULL)
953        {
954          for(j=0; j < lists[i]->num_keys; j++)
955          {
956            ret_val->elements[k].hash = lists[i]->elements[j].hash;
957            ret_val->elements[k++].offset = lists[i]->elements[j].offset;
958          }
959        }
960      }
961    }
962  }
963 
964  for(i=0; i < num_lists; i++)
965    talloc_free(lists[i]);
966  free(lists);
967
968  return ret_val;
969}
970
971
972/******************************************************************************
973 *
974 ******************************************************************************/
975REGFI_SK_REC* regfi_parse_sk(REGFI_FILE* file, uint32_t offset, uint32_t max_size, 
976                             bool strict)
977{
978  REGFI_SK_REC* ret_val = NULL;
979  uint8_t* sec_desc_buf = NULL;
980  uint32_t cell_length, length;
981  uint8_t sk_header[REGFI_SK_MIN_LENGTH];
982  bool unalloc = false;
983
984  if(!regfi_lock(file, file->cb_lock, "regfi_parse_sk"))
985     goto fail;
986
987  if(!regfi_parse_cell(file->cb, offset, sk_header, REGFI_SK_MIN_LENGTH,
988                       &cell_length, &unalloc))
989  {
990    regfi_log_add(REGFI_LOG_WARN, "Could not parse SK record cell"
991                      " at offset 0x%.8X.", offset);
992    goto fail_locked;
993  }
994   
995  if(sk_header[0] != 's' || sk_header[1] != 'k')
996  {
997    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch in parsing"
998                      " SK record at offset 0x%.8X.", offset);
999    goto fail_locked;
1000  }
1001
1002  ret_val = talloc(NULL, REGFI_SK_REC);
1003  if(ret_val == NULL)
1004    goto fail_locked;
1005
1006  ret_val->offset = offset;
1007  /* XXX: Is there a way to be more conservative (shorter) with
1008   *      cell length when cell is unallocated?
1009   */
1010  ret_val->cell_size = cell_length;
1011
1012  if(ret_val->cell_size > max_size)
1013    ret_val->cell_size = max_size & 0xFFFFFFF8;
1014  if((ret_val->cell_size < REGFI_SK_MIN_LENGTH) 
1015     || (strict && (ret_val->cell_size & 0x00000007) != 0))
1016  {
1017    regfi_log_add(REGFI_LOG_WARN, "Invalid cell size found while"
1018                      " parsing SK record at offset 0x%.8X.", offset);
1019    goto fail_locked;
1020  }
1021
1022  ret_val->magic[0] = sk_header[0];
1023  ret_val->magic[1] = sk_header[1];
1024
1025  ret_val->unknown_tag = SVAL(sk_header, 0x2);
1026  ret_val->prev_sk_off = IVAL(sk_header, 0x4);
1027  ret_val->next_sk_off = IVAL(sk_header, 0x8);
1028  ret_val->ref_count = IVAL(sk_header, 0xC);
1029  ret_val->desc_size = IVAL(sk_header, 0x10);
1030
1031  if((ret_val->prev_sk_off & 0x00000007) != 0
1032     || (ret_val->next_sk_off & 0x00000007) != 0)
1033  {
1034    regfi_log_add(REGFI_LOG_WARN, "SK record's next/previous offsets"
1035                      " are not a multiple of 8 while parsing SK record at"
1036                      " offset 0x%.8X.", offset);
1037    goto fail_locked;
1038  }
1039
1040  if(ret_val->desc_size + REGFI_SK_MIN_LENGTH > ret_val->cell_size)
1041  {
1042    regfi_log_add(REGFI_LOG_WARN, "Security descriptor too large for"
1043                      " cell while parsing SK record at offset 0x%.8X.", 
1044                      offset);
1045    goto fail_locked;
1046  }
1047
1048  sec_desc_buf = (uint8_t*)malloc(ret_val->desc_size);
1049  if(sec_desc_buf == NULL)
1050    goto fail_locked;
1051
1052  length = ret_val->desc_size;
1053  if(regfi_read(file->cb, sec_desc_buf, &length) != 0 
1054     || length != ret_val->desc_size)
1055  {
1056    regfi_log_add(REGFI_LOG_ERROR, "Failed to read security"
1057                      " descriptor while parsing SK record at offset 0x%.8X.",
1058                      offset);
1059    goto fail_locked;
1060  }
1061
1062  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_sk"))
1063     goto fail;
1064
1065  if(!(ret_val->sec_desc = winsec_parse_desc(ret_val, sec_desc_buf, 
1066                                                   ret_val->desc_size)))
1067  {
1068    regfi_log_add(REGFI_LOG_ERROR, "Failed to parse security"
1069                      " descriptor while parsing SK record at offset 0x%.8X.",
1070                      offset);
1071    goto fail;
1072  }
1073
1074  free(sec_desc_buf);
1075  return ret_val;
1076
1077 fail_locked:
1078  regfi_unlock(file, file->cb_lock, "regfi_parse_sk");
1079 fail:
1080  if(sec_desc_buf != NULL)
1081    free(sec_desc_buf);
1082  talloc_free(ret_val);
1083  return NULL;
1084}
1085
1086
1087REGFI_VALUE_LIST* regfi_parse_valuelist(REGFI_FILE* file, uint32_t offset, 
1088                                        uint32_t num_values, bool strict)
1089{
1090  REGFI_VALUE_LIST* ret_val;
1091  uint32_t i, cell_length, length, read_len;
1092  bool unalloc;
1093
1094  if(!regfi_lock(file, file->cb_lock, "regfi_parse_valuelist"))
1095     goto fail;
1096
1097  if(!regfi_parse_cell(file->cb, offset, NULL, 0, &cell_length, &unalloc))
1098  {
1099    regfi_log_add(REGFI_LOG_ERROR, "Failed to read cell header"
1100                      " while parsing value list at offset 0x%.8X.", offset);
1101    goto fail_locked;
1102  }
1103
1104  if((cell_length & 0x00000007) != 0)
1105  {
1106    regfi_log_add(REGFI_LOG_WARN, "Cell length not a multiple of 8"
1107                      " while parsing value list at offset 0x%.8X.", offset);
1108    if(strict)
1109      goto fail_locked;
1110    cell_length = cell_length & 0xFFFFFFF8;
1111  }
1112
1113  if((num_values * sizeof(uint32_t)) > cell_length-sizeof(uint32_t))
1114  {
1115    regfi_log_add(REGFI_LOG_WARN, "Too many values found"
1116                      " while parsing value list at offset 0x%.8X.", offset);
1117    if(strict)
1118      goto fail_locked;
1119    num_values = cell_length/sizeof(uint32_t) - sizeof(uint32_t);
1120  }
1121
1122  read_len = num_values*sizeof(uint32_t);
1123  ret_val = talloc(NULL, REGFI_VALUE_LIST);
1124  if(ret_val == NULL)
1125    goto fail_locked;
1126
1127  ret_val->elements = (REGFI_VALUE_LIST_ELEM*)talloc_size(ret_val, read_len);
1128  if(ret_val->elements == NULL)
1129    goto fail_locked;
1130
1131  ret_val->num_values = num_values;
1132
1133  length = read_len;
1134  if((regfi_read(file->cb, (uint8_t*)ret_val->elements, &length) != 0) 
1135     || length != read_len)
1136  {
1137    regfi_log_add(REGFI_LOG_ERROR, "Failed to read value pointers"
1138                      " while parsing value list at offset 0x%.8X.", offset);
1139    goto fail_locked;
1140  }
1141 
1142  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_valuelist"))
1143     goto fail;
1144
1145  for(i=0; i < num_values; i++)
1146  {
1147    /* Fix endianness */
1148    ret_val->elements[i] = IVAL(&ret_val->elements[i], 0);
1149
1150    /* Validate the first num_values values to ensure they make sense */
1151    if(strict)
1152    {
1153      /* XXX: Need to revisit this file length check when we start dealing
1154       *      with partial files. */
1155      if((ret_val->elements[i] + REGFI_REGF_SIZE > file->file_length)
1156         || ((ret_val->elements[i] & 0x00000007) != 0))
1157      {
1158        regfi_log_add(REGFI_LOG_WARN, "Invalid value pointer"
1159                          " (0x%.8X) found while parsing value list at offset"
1160                          " 0x%.8X.", ret_val->elements[i], offset);
1161        goto fail;
1162      }
1163    }
1164  }
1165
1166  return ret_val;
1167
1168 fail_locked:
1169  regfi_unlock(file, file->cb_lock, "regfi_parse_valuelist");
1170 fail:
1171  talloc_free(ret_val);
1172  return NULL;
1173}
1174
1175
1176void regfi_interpret_valuename(REGFI_FILE* file, REGFI_VK_REC* vk, 
1177                               REGFI_ENCODING output_encoding, bool strict)
1178{
1179  /* XXX: Registry value names are supposedly limited to 16383 characters
1180   *      according to:
1181   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1182   *      Might want to emit a warning if this is exceeded. 
1183   *      It is expected that "characters" could be variable width.
1184   *      Also, it may be useful to use this information to limit false positives
1185   *      when recovering deleted VK records.
1186   */
1187  int32_t tmp_size;
1188  REGFI_ENCODING from_encoding = (vk->flags & REGFI_VK_FLAG_ASCIINAME)
1189    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
1190
1191  if(from_encoding == output_encoding)
1192  {
1193    vk->valuename_raw = talloc_realloc(vk, vk->valuename_raw,
1194                                            uint8_t, vk->name_length+1);
1195    vk->valuename_raw[vk->name_length] = '\0';
1196    vk->valuename = (char*)vk->valuename_raw;
1197  }
1198  else
1199  {
1200    vk->valuename = talloc_array(vk, char, vk->name_length+1);
1201    if(vk->valuename == NULL)
1202    {
1203      talloc_free(vk);
1204      return;
1205    }
1206
1207    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1208                                  regfi_encoding_int2str(output_encoding),
1209                                  vk->valuename_raw, vk->valuename,
1210                                  vk->name_length, vk->name_length+1);
1211    if(tmp_size < 0)
1212    {
1213      regfi_log_add(REGFI_LOG_WARN, "Error occurred while converting"
1214                        " valuename to encoding %s.  Error message: %s",
1215                        regfi_encoding_int2str(output_encoding), 
1216                        strerror(-tmp_size));
1217      talloc_free(vk->valuename);
1218      vk->valuename = NULL;
1219    }
1220  }
1221}
1222
1223
1224/******************************************************************************
1225 ******************************************************************************/
1226REGFI_VK_REC* regfi_load_value(REGFI_FILE* file, uint32_t offset, 
1227                               REGFI_ENCODING output_encoding, bool strict)
1228{
1229  REGFI_VK_REC* ret_val = NULL;
1230  int32_t max_size;
1231
1232  max_size = regfi_calc_maxsize(file, offset);
1233  if(max_size < 0)
1234    return NULL;
1235 
1236  ret_val = regfi_parse_vk(file, offset, max_size, strict);
1237  if(ret_val == NULL)
1238    return NULL;
1239
1240  regfi_interpret_valuename(file, ret_val, output_encoding, strict);
1241
1242  return ret_val;
1243}
1244
1245
1246/******************************************************************************
1247 * If !strict, the list may contain NULLs, VK records may point to NULL.
1248 ******************************************************************************/
1249REGFI_VALUE_LIST* regfi_load_valuelist(REGFI_FILE* file, uint32_t offset, 
1250                                       uint32_t num_values, uint32_t max_size,
1251                                       bool strict)
1252{
1253  uint32_t usable_num_values;
1254
1255  if((num_values+1) * sizeof(uint32_t) > max_size)
1256  {
1257    regfi_log_add(REGFI_LOG_WARN, "Number of values indicated by"
1258                      " parent key (%d) would cause cell to straddle HBIN"
1259                      " boundary while loading value list at offset"
1260                      " 0x%.8X.", num_values, offset);
1261    if(strict)
1262      return NULL;
1263    usable_num_values = max_size/sizeof(uint32_t) - sizeof(uint32_t);
1264  }
1265  else
1266    usable_num_values = num_values;
1267
1268  return regfi_parse_valuelist(file, offset, usable_num_values, strict);
1269}
1270
1271
1272void regfi_interpret_keyname(REGFI_FILE* file, REGFI_NK_REC* nk, 
1273                             REGFI_ENCODING output_encoding, bool strict)
1274{
1275  /* XXX: Registry key names are supposedly limited to 255 characters according to:
1276   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1277   *      Might want to emit a warning if this is exceeded. 
1278   *      It is expected that "characters" could be variable width.
1279   *      Also, it may be useful to use this information to limit false positives
1280   *      when recovering deleted NK records.
1281   */
1282  int32_t tmp_size;
1283  REGFI_ENCODING from_encoding = (nk->flags & REGFI_NK_FLAG_ASCIINAME) 
1284    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
1285 
1286  if(from_encoding == output_encoding)
1287  {
1288    nk->keyname_raw = talloc_realloc(nk, nk->keyname_raw, uint8_t, nk->name_length+1);
1289    nk->keyname_raw[nk->name_length] = '\0';
1290    nk->keyname = (char*)nk->keyname_raw;
1291  }
1292  else
1293  {
1294    nk->keyname = talloc_array(nk, char, nk->name_length+1);
1295    if(nk->keyname == NULL)
1296    {
1297      talloc_free(nk);
1298      return;
1299    }
1300
1301    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1302                                  regfi_encoding_int2str(output_encoding),
1303                                  nk->keyname_raw, nk->keyname,
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                        " keyname to encoding %s.  Error message: %s",
1309                        regfi_encoding_int2str(output_encoding), 
1310                        strerror(-tmp_size));
1311      talloc_free(nk->keyname);
1312      nk->keyname = NULL;
1313    }
1314  }
1315}
1316
1317
1318/******************************************************************************
1319 *
1320 ******************************************************************************/
1321REGFI_NK_REC* regfi_load_key(REGFI_FILE* file, uint32_t offset, 
1322                             REGFI_ENCODING output_encoding, bool strict)
1323{
1324  REGFI_NK_REC* 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_steal(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_steal(nk, nk->subkeys);
1403    }
1404  }
1405
1406  return nk;
1407}
1408
1409
1410/******************************************************************************
1411 ******************************************************************************/
1412const REGFI_SK_REC* regfi_load_sk(REGFI_FILE* file, uint32_t offset, bool strict)
1413{
1414  REGFI_SK_REC* 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_REC*)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_REC* regfi_find_root_nk(REGFI_FILE* file, const REGFI_HBIN* hbin, 
1466                                 REGFI_ENCODING output_encoding)
1467{
1468  REGFI_NK_REC* 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)
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);
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_steal(ret_val, file_cb);
1533  return ret_val;
1534
1535 fail:
1536    talloc_free(file_cb);
1537    return NULL;
1538}
1539
1540
1541
1542REGFI_FILE* regfi_alloc_cb(REGFI_RAW_FILE* file_cb)
1543{
1544  REGFI_FILE* rb;
1545  REGFI_HBIN* hbin = NULL;
1546  uint32_t hbin_off, cache_secret;
1547  int32_t file_length;
1548  bool rla;
1549
1550  /* Determine file length.  Must be at least big enough for the header
1551   * and one hbin.
1552   */
1553  file_length = file_cb->seek(file_cb, 0, SEEK_END);
1554  if(file_length < REGFI_REGF_SIZE+REGFI_HBIN_ALLOC)
1555  {
1556    regfi_log_add(REGFI_LOG_ERROR, "File length (%d) too short to contain a"
1557                  " header and at least one HBIN.", file_length);
1558    return NULL;
1559  }
1560  file_cb->seek(file_cb, 0, SEEK_SET);
1561
1562  /* Read file header */
1563  if ((rb = regfi_parse_regf(file_cb, false)) == NULL) 
1564  {
1565    regfi_log_add(REGFI_LOG_ERROR, "Failed to read REGF block.");
1566    return NULL;
1567  }
1568  rb->file_length = file_length; 
1569  rb->cb = file_cb;
1570  rb->cb_lock = NULL;
1571  rb->hbins_lock = NULL;
1572  rb->sk_lock = NULL;
1573
1574  rb->cb_lock = talloc(rb, pthread_mutex_t);
1575  if(rb->cb_lock == NULL || pthread_mutex_init(rb->cb_lock, NULL) != 0)
1576  {
1577    regfi_log_add(REGFI_LOG_ERROR, "Failed to create cb_lock mutex.");
1578    goto fail;
1579  }
1580
1581  rb->hbins_lock = talloc(rb, pthread_rwlock_t);
1582  if(rb->hbins_lock == NULL || pthread_rwlock_init(rb->hbins_lock, NULL) != 0)
1583  {
1584    regfi_log_add(REGFI_LOG_ERROR, "Failed to create hbins_lock rwlock.");
1585    goto fail;
1586  }
1587
1588  rb->sk_lock = talloc(rb, pthread_mutex_t);
1589  if(rb->sk_lock == NULL || pthread_mutex_init(rb->sk_lock, NULL) != 0)
1590  {
1591    regfi_log_add(REGFI_LOG_ERROR, "Failed to create sk_lock mutex.");
1592    goto fail;
1593  }
1594
1595  rb->hbins = range_list_new();
1596  if(rb->hbins == NULL)
1597  {
1598    regfi_log_add(REGFI_LOG_ERROR, "Failed to create HBIN range_list.");
1599    goto fail;
1600  }
1601  talloc_steal(rb, rb->hbins);
1602
1603  rla = true;
1604  hbin_off = REGFI_REGF_SIZE;
1605  hbin = regfi_parse_hbin(rb, hbin_off, true);
1606  while(hbin && rla)
1607  {
1608    rla = range_list_add(rb->hbins, hbin->file_off, hbin->block_size, hbin);
1609    if(rla)
1610      talloc_steal(rb->hbins, hbin);
1611
1612    hbin_off = hbin->file_off + hbin->block_size;
1613    hbin = regfi_parse_hbin(rb, hbin_off, true);
1614  }
1615
1616  /* This secret isn't very secret, but we don't need a good one.  This
1617   * secret is just designed to prevent someone from trying to blow our
1618   * caching and make things slow.
1619   */
1620  cache_secret = 0x15DEAD05^time(NULL)^(getpid()<<16);
1621
1622  if(REGFI_CACHE_SK)
1623    rb->sk_cache = lru_cache_create_ctx(rb, 64, cache_secret, true);
1624  else
1625    rb->sk_cache = NULL;
1626
1627  /* success */
1628  return rb;
1629
1630 fail:
1631  if(rb->cb_lock != NULL)
1632    pthread_mutex_destroy(rb->cb_lock);
1633  if(rb->hbins_lock != NULL)
1634    pthread_rwlock_destroy(rb->hbins_lock);
1635  if(rb->sk_lock != NULL)
1636    pthread_mutex_destroy(rb->sk_lock);
1637
1638  range_list_free(rb->hbins);
1639  talloc_free(rb->cb_lock);
1640  talloc_free(rb->hbins_lock);
1641  talloc_free(rb);
1642  return NULL;
1643}
1644
1645
1646/******************************************************************************
1647 ******************************************************************************/
1648void regfi_free(REGFI_FILE *file)
1649{
1650  pthread_mutex_destroy(file->cb_lock);
1651  pthread_rwlock_destroy(file->hbins_lock);
1652  pthread_mutex_destroy(file->sk_lock);
1653  talloc_free(file);
1654}
1655
1656
1657/******************************************************************************
1658 * First checks the offset given by the file header, then checks the
1659 * rest of the file if that fails.
1660 ******************************************************************************/
1661REGFI_NK_REC* regfi_rootkey(REGFI_FILE* file, REGFI_ENCODING output_encoding)
1662{
1663  REGFI_NK_REC* nk = NULL;
1664  REGFI_HBIN* hbin;
1665  uint32_t root_offset, i, num_hbins;
1666 
1667  if(!file)
1668    return NULL;
1669
1670  root_offset = file->root_cell+REGFI_REGF_SIZE;
1671  nk = regfi_load_key(file, root_offset, output_encoding, true);
1672  if(nk != NULL)
1673  {
1674    if(nk->flags & REGFI_NK_FLAG_ROOT)
1675      return nk;
1676  }
1677
1678  regfi_log_add(REGFI_LOG_WARN, "File header indicated root key at"
1679                " location 0x%.8X, but no root key found."
1680                " Searching rest of file...", root_offset);
1681 
1682  /* If the file header gives bad info, scan through the file one HBIN
1683   * block at a time looking for an NK record with a root key type.
1684   */
1685 
1686  if(!regfi_read_lock(file, file->hbins_lock, "regfi_rootkey"))
1687    return NULL;
1688
1689  num_hbins = range_list_size(file->hbins);
1690  for(i=0; i < num_hbins && nk == NULL; i++)
1691  {
1692    hbin = (REGFI_HBIN*)range_list_get(file->hbins, i)->data;
1693    nk = regfi_find_root_nk(file, hbin, output_encoding);
1694  }
1695
1696  if(!regfi_rw_unlock(file, file->hbins_lock, "regfi_rootkey"))
1697    return NULL;
1698
1699  return nk;
1700}
1701
1702
1703/******************************************************************************
1704 *****************************************************************************/
1705void regfi_free_record(const void* record)
1706{
1707  talloc_unlink(NULL, (void*)record);
1708}
1709
1710
1711
1712/******************************************************************************
1713 *****************************************************************************/
1714REGFI_ITERATOR* regfi_iterator_new(REGFI_FILE* file, 
1715                                   REGFI_ENCODING output_encoding)
1716{
1717  REGFI_NK_REC* root;
1718  REGFI_ITERATOR* ret_val;
1719
1720  if(output_encoding != REGFI_ENCODING_UTF8
1721     && output_encoding != REGFI_ENCODING_ASCII)
1722  { 
1723    regfi_log_add(REGFI_LOG_ERROR, "Invalid output_encoding supplied"
1724                  " in creation of regfi iterator.");
1725    return NULL;
1726  }
1727
1728  ret_val = talloc(NULL, REGFI_ITERATOR);
1729  if(ret_val == NULL)
1730    return NULL;
1731
1732  root = regfi_rootkey(file, output_encoding);
1733  if(root == NULL)
1734  {
1735    talloc_free(ret_val);
1736    return NULL;
1737  }
1738  ret_val->cur_key = root;
1739  talloc_reference(ret_val, root);
1740
1741  ret_val->key_positions = void_stack_new(REGFI_MAX_DEPTH);
1742  if(ret_val->key_positions == NULL)
1743  {
1744    talloc_free(ret_val);
1745    return NULL;
1746  }
1747  talloc_steal(ret_val, ret_val->key_positions);
1748
1749  ret_val->f = file;
1750  ret_val->cur_subkey = 0;
1751  ret_val->cur_value = 0;
1752  ret_val->string_encoding = output_encoding;
1753   
1754  return ret_val;
1755}
1756
1757
1758/******************************************************************************
1759 *****************************************************************************/
1760void regfi_iterator_free(REGFI_ITERATOR* i)
1761{
1762  talloc_free(i);
1763}
1764
1765
1766
1767/******************************************************************************
1768 *****************************************************************************/
1769/* XXX: some way of indicating reason for failure should be added. */
1770bool regfi_iterator_down(REGFI_ITERATOR* i)
1771{
1772  REGFI_NK_REC* subkey;
1773  REGFI_ITER_POSITION* pos;
1774
1775  pos = talloc(i->key_positions, REGFI_ITER_POSITION);
1776  if(pos == NULL)
1777    return false;
1778
1779  subkey = (REGFI_NK_REC*)regfi_iterator_cur_subkey(i);
1780  if(subkey == NULL)
1781  {
1782    talloc_free(pos);
1783    return false;
1784  }
1785
1786  pos->nk = i->cur_key;
1787  pos->cur_subkey = i->cur_subkey;
1788  if(!void_stack_push(i->key_positions, pos))
1789  {
1790    talloc_free(pos);
1791    talloc_unlink(NULL, subkey);
1792    return false;
1793  }
1794  talloc_reference(i, subkey);
1795
1796  i->cur_key = subkey;
1797  i->cur_subkey = 0;
1798  i->cur_value = 0;
1799
1800  return true;
1801}
1802
1803
1804/******************************************************************************
1805 *****************************************************************************/
1806bool regfi_iterator_up(REGFI_ITERATOR* i)
1807{
1808  REGFI_ITER_POSITION* pos;
1809
1810  pos = (REGFI_ITER_POSITION*)void_stack_pop(i->key_positions);
1811  if(pos == NULL)
1812    return false;
1813
1814  talloc_unlink(i, i->cur_key);
1815  i->cur_key = pos->nk;
1816  i->cur_subkey = pos->cur_subkey;
1817  i->cur_value = 0;
1818  talloc_free(pos);
1819
1820  return true;
1821}
1822
1823
1824/******************************************************************************
1825 *****************************************************************************/
1826bool regfi_iterator_to_root(REGFI_ITERATOR* i)
1827{
1828  while(regfi_iterator_up(i))
1829    continue;
1830
1831  return true;
1832}
1833
1834
1835/******************************************************************************
1836 *****************************************************************************/
1837bool regfi_iterator_find_subkey(REGFI_ITERATOR* i, const char* subkey_name)
1838{
1839  REGFI_NK_REC* subkey;
1840  bool found = false;
1841  uint32_t old_subkey = i->cur_subkey;
1842
1843  if(subkey_name == NULL)
1844    return false;
1845
1846  /* XXX: this alloc/free of each sub key might be a bit excessive */
1847  subkey = (REGFI_NK_REC*)regfi_iterator_first_subkey(i);
1848  while((subkey != NULL) && (found == false))
1849  {
1850    if(subkey->keyname != NULL 
1851       && strcasecmp(subkey->keyname, subkey_name) == 0)
1852      found = true;
1853    else
1854    {
1855      talloc_unlink(NULL, subkey);
1856      subkey = (REGFI_NK_REC*)regfi_iterator_next_subkey(i);
1857    }
1858  }
1859
1860  if(found == false)
1861  {
1862    i->cur_subkey = old_subkey;
1863    return false;
1864  }
1865
1866  talloc_unlink(NULL, subkey);
1867  return true;
1868}
1869
1870
1871/******************************************************************************
1872 *****************************************************************************/
1873bool regfi_iterator_walk_path(REGFI_ITERATOR* i, const char** path)
1874{
1875  uint32_t x;
1876  if(path == NULL)
1877    return false;
1878
1879  for(x=0; 
1880      ((path[x] != NULL) && regfi_iterator_find_subkey(i, path[x])
1881       && regfi_iterator_down(i));
1882      x++)
1883  { continue; }
1884
1885  if(path[x] == NULL)
1886    return true;
1887 
1888  /* XXX: is this the right number of times? */
1889  for(; x > 0; x--)
1890    regfi_iterator_up(i);
1891 
1892  return false;
1893}
1894
1895
1896/******************************************************************************
1897 *****************************************************************************/
1898const REGFI_NK_REC* regfi_iterator_cur_key(REGFI_ITERATOR* i)
1899{
1900  return i->cur_key;
1901}
1902
1903
1904/******************************************************************************
1905 *****************************************************************************/
1906const REGFI_SK_REC* regfi_iterator_cur_sk(REGFI_ITERATOR* i)
1907{
1908  if(i->cur_key == NULL || i->cur_key->sk_off == REGFI_OFFSET_NONE)
1909    return NULL;
1910
1911  return regfi_load_sk(i->f, i->cur_key->sk_off + REGFI_REGF_SIZE, true);
1912}
1913
1914
1915/******************************************************************************
1916 *****************************************************************************/
1917const REGFI_NK_REC* regfi_iterator_first_subkey(REGFI_ITERATOR* i)
1918{
1919  i->cur_subkey = 0;
1920  return regfi_iterator_cur_subkey(i);
1921}
1922
1923
1924/******************************************************************************
1925 *****************************************************************************/
1926const REGFI_NK_REC* regfi_iterator_cur_subkey(REGFI_ITERATOR* i)
1927{
1928  uint32_t nk_offset;
1929
1930  /* see if there is anything left to report */
1931  if (!(i->cur_key) || (i->cur_key->subkeys_off==REGFI_OFFSET_NONE)
1932      || (i->cur_subkey >= i->cur_key->num_subkeys))
1933    return NULL;
1934
1935  nk_offset = i->cur_key->subkeys->elements[i->cur_subkey].offset;
1936
1937  return regfi_load_key(i->f, nk_offset+REGFI_REGF_SIZE, 
1938                        i->string_encoding, true);
1939}
1940
1941
1942/******************************************************************************
1943 *****************************************************************************/
1944/* XXX: some way of indicating reason for failure should be added. */
1945const REGFI_NK_REC* regfi_iterator_next_subkey(REGFI_ITERATOR* i)
1946{
1947  const REGFI_NK_REC* subkey;
1948
1949  i->cur_subkey++;
1950  subkey = regfi_iterator_cur_subkey(i);
1951
1952  if(subkey == NULL)
1953    i->cur_subkey--;
1954
1955  return subkey;
1956}
1957
1958
1959/******************************************************************************
1960 *****************************************************************************/
1961bool regfi_iterator_find_value(REGFI_ITERATOR* i, const char* value_name)
1962{
1963  const REGFI_VK_REC* cur;
1964  bool found = false;
1965  uint32_t old_value = i->cur_value;
1966
1967  /* XXX: cur->valuename can be NULL in the registry. 
1968   *      Should we allow for a way to search for that?
1969   */
1970  if(value_name == NULL)
1971    return false;
1972
1973  cur = regfi_iterator_first_value(i);
1974  while((cur != NULL) && (found == false))
1975  {
1976    if((cur->valuename != NULL)
1977       && (strcasecmp(cur->valuename, value_name) == 0))
1978      found = true;
1979    else
1980    {
1981      regfi_free_record(cur);
1982      cur = regfi_iterator_next_value(i);
1983    }
1984  }
1985 
1986  if(found == false)
1987  {
1988    i->cur_value = old_value;
1989    return false;
1990  }
1991
1992  regfi_free_record(cur);
1993  return true;
1994}
1995
1996
1997/******************************************************************************
1998 *****************************************************************************/
1999const REGFI_VK_REC* regfi_iterator_first_value(REGFI_ITERATOR* i)
2000{
2001  i->cur_value = 0;
2002  return regfi_iterator_cur_value(i);
2003}
2004
2005
2006/******************************************************************************
2007 *****************************************************************************/
2008const REGFI_VK_REC* regfi_iterator_cur_value(REGFI_ITERATOR* i)
2009{
2010  REGFI_VK_REC* ret_val = NULL;
2011  uint32_t voffset;
2012
2013  if(i->cur_key->values != NULL && i->cur_key->values->elements != NULL)
2014  {
2015    if(i->cur_value < i->cur_key->values->num_values)
2016    {
2017      voffset = i->cur_key->values->elements[i->cur_value];
2018      ret_val = regfi_load_value(i->f, voffset+REGFI_REGF_SIZE, 
2019                                 i->string_encoding, true);
2020    }
2021  }
2022
2023  return ret_val;
2024}
2025
2026
2027/******************************************************************************
2028 *****************************************************************************/
2029const REGFI_VK_REC* regfi_iterator_next_value(REGFI_ITERATOR* i)
2030{
2031  const REGFI_VK_REC* ret_val;
2032
2033  i->cur_value++;
2034  ret_val = regfi_iterator_cur_value(i);
2035  if(ret_val == NULL)
2036    i->cur_value--;
2037
2038  return ret_val;
2039}
2040
2041
2042/******************************************************************************
2043 *****************************************************************************/
2044const REGFI_CLASSNAME* regfi_iterator_fetch_classname(REGFI_ITERATOR* i,
2045                                                      const REGFI_NK_REC* key)
2046{
2047  REGFI_CLASSNAME* ret_val;
2048  uint8_t* raw;
2049  char* interpreted;
2050  uint32_t offset;
2051  int32_t conv_size, max_size;
2052  uint16_t parse_length;
2053
2054  if(key->classname_off == REGFI_OFFSET_NONE || key->classname_length == 0)
2055    return NULL;
2056
2057  offset = key->classname_off + REGFI_REGF_SIZE;
2058  max_size = regfi_calc_maxsize(i->f, offset);
2059  if(max_size <= 0)
2060    return NULL;
2061
2062  parse_length = key->classname_length;
2063  raw = regfi_parse_classname(i->f, offset, &parse_length, max_size, true);
2064 
2065  if(raw == NULL)
2066  {
2067    regfi_log_add(REGFI_LOG_WARN, "Could not parse class"
2068                  " name at offset 0x%.8X for key record at offset 0x%.8X.",
2069                  offset, key->offset);
2070    return NULL;
2071  }
2072
2073  ret_val = talloc(NULL, REGFI_CLASSNAME);
2074  if(ret_val == NULL)
2075    return NULL;
2076
2077  ret_val->raw = raw;
2078  ret_val->size = parse_length;
2079  talloc_steal(ret_val, raw);
2080
2081  interpreted = talloc_array(NULL, char, parse_length);
2082
2083  conv_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2084                                 regfi_encoding_int2str(i->string_encoding),
2085                                 raw, interpreted,
2086                                 parse_length, parse_length);
2087  if(conv_size < 0)
2088  {
2089    regfi_log_add(REGFI_LOG_WARN, "Error occurred while"
2090                  " converting classname to charset %s.  Error message: %s",
2091                  i->string_encoding, strerror(-conv_size));
2092    talloc_free(interpreted);
2093    ret_val->interpreted = NULL;
2094  }
2095  else
2096  {
2097    interpreted = talloc_realloc(NULL, interpreted, char, conv_size);
2098    ret_val->interpreted = interpreted;
2099    talloc_steal(ret_val, interpreted);
2100  }
2101
2102  return ret_val;
2103}
2104
2105
2106/******************************************************************************
2107 *****************************************************************************/
2108const REGFI_DATA* regfi_iterator_fetch_data(REGFI_ITERATOR* i, 
2109                                            const REGFI_VK_REC* value)
2110{
2111  REGFI_DATA* ret_val = NULL;
2112  REGFI_BUFFER raw_data;
2113
2114  if(value->data_size != 0)
2115  {
2116    raw_data = regfi_load_data(i->f, value->data_off, value->data_size,
2117                              value->data_in_offset, true);
2118    if(raw_data.buf == NULL)
2119    {
2120      regfi_log_add(REGFI_LOG_WARN, "Could not parse data record"
2121                    " while parsing VK record at offset 0x%.8X.",
2122                    value->offset);
2123    }
2124    else
2125    {
2126      ret_val = regfi_buffer_to_data(raw_data);
2127
2128      if(ret_val == NULL)
2129      {
2130        regfi_log_add(REGFI_LOG_WARN, "Error occurred in converting"
2131                      " data buffer to data structure while interpreting "
2132                      "data for VK record at offset 0x%.8X.",
2133                      value->offset);
2134        talloc_free(raw_data.buf);
2135        return NULL;
2136      }
2137
2138      if(!regfi_interpret_data(i->f, i->string_encoding, value->type, ret_val))
2139      {
2140        regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2141                      " interpreting data for VK record at offset 0x%.8X.",
2142                      value->offset);
2143      }
2144    }
2145  }
2146 
2147  return ret_val;
2148}
2149
2150
2151/******************************************************************************
2152 *****************************************************************************/
2153REGFI_DATA* regfi_buffer_to_data(REGFI_BUFFER raw_data)
2154{
2155  REGFI_DATA* ret_val;
2156
2157  if(raw_data.buf == NULL)
2158    return NULL;
2159
2160  ret_val = talloc(NULL, REGFI_DATA);
2161  if(ret_val == NULL)
2162    return NULL;
2163 
2164  talloc_steal(ret_val, raw_data.buf);
2165  ret_val->raw = raw_data.buf;
2166  ret_val->size = raw_data.len;
2167  ret_val->interpreted_size = 0;
2168  ret_val->interpreted.qword = 0;
2169
2170  return ret_val;
2171}
2172
2173
2174/******************************************************************************
2175 *****************************************************************************/
2176bool regfi_interpret_data(REGFI_FILE* file, REGFI_ENCODING string_encoding,
2177                          uint32_t type, REGFI_DATA* data)
2178{
2179  uint8_t** tmp_array;
2180  uint8_t* tmp_str;
2181  int32_t tmp_size;
2182  uint32_t i, j, array_size;
2183
2184  if(data == NULL)
2185    return false;
2186
2187  switch (type)
2188  {
2189  case REG_SZ:
2190  case REG_EXPAND_SZ:
2191  /* REG_LINK is a symbolic link, stored as a unicode string. */
2192  case REG_LINK:
2193    tmp_str = talloc_array(NULL, uint8_t, data->size);
2194    if(tmp_str == NULL)
2195    {
2196      data->interpreted.string = NULL;
2197      data->interpreted_size = 0;
2198      return false;
2199    }
2200     
2201    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2202                                  regfi_encoding_int2str(string_encoding),
2203                                  data->raw, (char*)tmp_str, 
2204                                  data->size, data->size);
2205    if(tmp_size < 0)
2206    {
2207      regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2208                    " converting data of type %d to %s.  Error message: %s",
2209                    type, string_encoding, strerror(-tmp_size));
2210      talloc_free(tmp_str);
2211      data->interpreted.string = NULL;
2212      data->interpreted_size = 0;
2213      return false;
2214    }
2215
2216    tmp_str = talloc_realloc(NULL, tmp_str, uint8_t, tmp_size);
2217    data->interpreted.string = tmp_str;
2218    data->interpreted_size = tmp_size;
2219    talloc_steal(data, tmp_str);
2220    break;
2221
2222  case REG_DWORD:
2223    if(data->size < 4)
2224    {
2225      data->interpreted.dword = 0;
2226      data->interpreted_size = 0;
2227      return false;
2228    }
2229    data->interpreted.dword = IVAL(data->raw, 0);
2230    data->interpreted_size = 4;
2231    break;
2232
2233  case REG_DWORD_BE:
2234    if(data->size < 4)
2235    {
2236      data->interpreted.dword_be = 0;
2237      data->interpreted_size = 0;
2238      return false;
2239    }
2240    data->interpreted.dword_be = RIVAL(data->raw, 0);
2241    data->interpreted_size = 4;
2242    break;
2243
2244  case REG_QWORD:
2245    if(data->size < 8)
2246    {
2247      data->interpreted.qword = 0;
2248      data->interpreted_size = 0;
2249      return false;
2250    }
2251    data->interpreted.qword = 
2252      (uint64_t)IVAL(data->raw, 0) + (((uint64_t)IVAL(data->raw, 4))<<32);
2253    data->interpreted_size = 8;
2254    break;
2255   
2256  case REG_MULTI_SZ:
2257    tmp_str = talloc_array(NULL, uint8_t, data->size);
2258    if(tmp_str == NULL)
2259    {
2260      data->interpreted.multiple_string = NULL;
2261      data->interpreted_size = 0;
2262      return false;
2263    }
2264
2265    /* Attempt to convert entire string from UTF-16LE to output encoding,
2266     * then parse and quote fields individually.
2267     */
2268    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2269                                  regfi_encoding_int2str(string_encoding),
2270                                  data->raw, (char*)tmp_str,
2271                                  data->size, data->size);
2272    if(tmp_size < 0)
2273    {
2274      regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2275                    " converting data of type %d to %s.  Error message: %s",
2276                    type, string_encoding, strerror(-tmp_size));
2277      talloc_free(tmp_str);
2278      data->interpreted.multiple_string = NULL;
2279      data->interpreted_size = 0;
2280      return false;
2281    }
2282
2283    array_size = tmp_size+1;
2284    tmp_array = talloc_array(NULL, uint8_t*, array_size);
2285    if(tmp_array == NULL)
2286    {
2287      talloc_free(tmp_str);
2288      data->interpreted.string = NULL;
2289      data->interpreted_size = 0;
2290      return false;
2291    }
2292   
2293    tmp_array[0] = tmp_str;
2294    for(i=0,j=1; i < tmp_size && j < array_size-1; i++)
2295    {
2296      if(tmp_str[i] == '\0' && (i+1 < tmp_size))
2297        tmp_array[j++] = tmp_str+i+1;
2298    }
2299    tmp_array[j] = NULL;
2300    tmp_array = talloc_realloc(NULL, tmp_array, uint8_t*, j+1);
2301    data->interpreted.multiple_string = tmp_array;
2302    /* XXX: how meaningful is this?  should we store number of strings instead? */
2303    data->interpreted_size = tmp_size;
2304    talloc_steal(tmp_array, tmp_str);
2305    talloc_steal(data, tmp_array);
2306    break;
2307
2308  /* XXX: Dont know how to interpret these yet, just treat as binary */
2309  case REG_NONE:
2310    data->interpreted.none = data->raw;
2311    data->interpreted_size = data->size;
2312    break;
2313
2314  case REG_RESOURCE_LIST:
2315    data->interpreted.resource_list = data->raw;
2316    data->interpreted_size = data->size;
2317    break;
2318
2319  case REG_FULL_RESOURCE_DESCRIPTOR:
2320    data->interpreted.full_resource_descriptor = data->raw;
2321    data->interpreted_size = data->size;
2322    break;
2323
2324  case REG_RESOURCE_REQUIREMENTS_LIST:
2325    data->interpreted.resource_requirements_list = data->raw;
2326    data->interpreted_size = data->size;
2327    break;
2328
2329  case REG_BINARY:
2330    data->interpreted.binary = data->raw;
2331    data->interpreted_size = data->size;
2332    break;
2333
2334  default:
2335    data->interpreted.qword = 0;
2336    data->interpreted_size = 0;
2337    return false;
2338  }
2339
2340  data->type = type;
2341  return true;
2342}
2343
2344
2345/******************************************************************************
2346 * Convert from UTF-16LE to specified character set.
2347 * On error, returns a negative errno code.
2348 *****************************************************************************/
2349int32_t regfi_conv_charset(const char* input_charset, const char* output_charset,
2350                         uint8_t* input, char* output, 
2351                         uint32_t input_len, uint32_t output_max)
2352{
2353  iconv_t conv_desc;
2354  char* inbuf = (char*)input;
2355  char* outbuf = output;
2356  size_t in_len = (size_t)input_len;
2357  size_t out_len = (size_t)(output_max-1);
2358  int ret;
2359
2360  /* XXX: Consider creating a couple of conversion descriptors earlier,
2361   *      storing them on an iterator so they don't have to be recreated
2362   *      each time.
2363   */
2364
2365  /* Set up conversion descriptor. */
2366  conv_desc = iconv_open(output_charset, input_charset);
2367
2368  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
2369  if(ret == -1)
2370  {
2371    iconv_close(conv_desc);
2372    return -errno;
2373  }
2374  *outbuf = '\0';
2375
2376  iconv_close(conv_desc); 
2377  return output_max-out_len-1;
2378}
2379
2380
2381
2382/*******************************************************************
2383 * Computes the checksum of the registry file header.
2384 * buffer must be at least the size of a regf header (4096 bytes).
2385 *******************************************************************/
2386static uint32_t regfi_compute_header_checksum(uint8_t* buffer)
2387{
2388  uint32_t checksum, x;
2389  int i;
2390
2391  /* XOR of all bytes 0x0000 - 0x01FB */
2392
2393  checksum = x = 0;
2394 
2395  for ( i=0; i<0x01FB; i+=4 ) {
2396    x = IVAL(buffer, i );
2397    checksum ^= x;
2398  }
2399 
2400  return checksum;
2401}
2402
2403
2404/*******************************************************************
2405 *******************************************************************/
2406REGFI_FILE* regfi_parse_regf(REGFI_RAW_FILE* file_cb, bool strict)
2407{
2408  uint8_t file_header[REGFI_REGF_SIZE];
2409  uint32_t length;
2410  REGFI_FILE* ret_val;
2411
2412  ret_val = talloc(NULL, REGFI_FILE);
2413  if(ret_val == NULL)
2414    return NULL;
2415
2416  ret_val->sk_cache = NULL;
2417  ret_val->hbins = NULL;
2418
2419  length = REGFI_REGF_SIZE;
2420  if((regfi_read(file_cb, file_header, &length)) != 0 
2421     || length != REGFI_REGF_SIZE)
2422  {
2423    regfi_log_add(REGFI_LOG_WARN, "Read failed while parsing REGF structure.");
2424    goto fail;
2425  }
2426
2427  ret_val->checksum = IVAL(file_header, 0x1FC);
2428  ret_val->computed_checksum = regfi_compute_header_checksum(file_header);
2429  if (strict && (ret_val->checksum != ret_val->computed_checksum))
2430  {
2431    regfi_log_add(REGFI_LOG_WARN, "Stored header checksum (%.8X) did not equal"
2432                  " computed checksum (%.8X).",
2433                  ret_val->checksum, ret_val->computed_checksum);
2434    if(strict)
2435      goto fail;
2436  }
2437
2438  memcpy(ret_val->magic, file_header, REGFI_REGF_MAGIC_SIZE);
2439  if(memcmp(ret_val->magic, "regf", REGFI_REGF_MAGIC_SIZE) != 0)
2440  {
2441    regfi_log_add(REGFI_LOG_ERROR, "Magic number mismatch "
2442                  "(%.2X %.2X %.2X %.2X) while parsing hive header",
2443                  ret_val->magic[0], ret_val->magic[1], 
2444                  ret_val->magic[2], ret_val->magic[3]);
2445    goto fail;
2446  }
2447
2448  ret_val->sequence1 = IVAL(file_header, 0x4);
2449  ret_val->sequence2 = IVAL(file_header, 0x8);
2450  ret_val->mtime.low = IVAL(file_header, 0xC);
2451  ret_val->mtime.high = IVAL(file_header, 0x10);
2452  ret_val->major_version = IVAL(file_header, 0x14);
2453  ret_val->minor_version = IVAL(file_header, 0x18);
2454  ret_val->type = IVAL(file_header, 0x1C);
2455  ret_val->format = IVAL(file_header, 0x20);
2456  ret_val->root_cell = IVAL(file_header, 0x24);
2457  ret_val->last_block = IVAL(file_header, 0x28);
2458  ret_val->cluster = IVAL(file_header, 0x2C);
2459
2460  memcpy(ret_val->file_name, file_header+0x30,  REGFI_REGF_NAME_SIZE);
2461
2462  /* XXX: Should we add a warning if these uuid parsers fail?  Can they? */
2463  ret_val->rm_id = winsec_parse_uuid(ret_val, file_header+0x70, 16);
2464  ret_val->log_id = winsec_parse_uuid(ret_val, file_header+0x80, 16);
2465  ret_val->flags = IVAL(file_header, 0x90);
2466  ret_val->tm_id = winsec_parse_uuid(ret_val, file_header+0x94, 16);
2467  ret_val->guid_signature = IVAL(file_header, 0xa4);
2468
2469  memcpy(ret_val->reserved1, file_header+0xa8, REGFI_REGF_RESERVED1_SIZE);
2470  memcpy(ret_val->reserved2, file_header+0x200, REGFI_REGF_RESERVED2_SIZE);
2471
2472  ret_val->thaw_tm_id = winsec_parse_uuid(ret_val, file_header+0xFC8, 16);
2473  ret_val->thaw_rm_id = winsec_parse_uuid(ret_val, file_header+0xFD8, 16);
2474  ret_val->thaw_log_id = winsec_parse_uuid(ret_val, file_header+0xFE8, 16);
2475  ret_val->boot_type = IVAL(file_header, 0xFF8);
2476  ret_val->boot_recover = IVAL(file_header, 0xFFC);
2477
2478  return ret_val;
2479
2480 fail:
2481  talloc_free(ret_val);
2482  return NULL;
2483}
2484
2485
2486
2487/******************************************************************************
2488 * Given real file offset, read and parse the hbin at that location
2489 * along with it's associated cells.
2490 ******************************************************************************/
2491REGFI_HBIN* regfi_parse_hbin(REGFI_FILE* file, uint32_t offset, bool strict)
2492{
2493  REGFI_HBIN* hbin = NULL;
2494  uint8_t hbin_header[REGFI_HBIN_HEADER_SIZE];
2495  uint32_t length;
2496 
2497  if(offset >= file->file_length)
2498    goto fail;
2499 
2500  if(!regfi_lock(file, file->cb_lock, "regfi_parse_hbin"))
2501    goto fail;
2502
2503  if(regfi_seek(file->cb, offset, SEEK_SET) == -1)
2504  {
2505    regfi_log_add(REGFI_LOG_ERROR, "Seek failed"
2506                  " while parsing hbin at offset 0x%.8X.", offset);
2507    goto fail_locked;
2508  }
2509
2510  length = REGFI_HBIN_HEADER_SIZE;
2511  if((regfi_read(file->cb, hbin_header, &length) != 0) 
2512     || length != REGFI_HBIN_HEADER_SIZE)
2513  {
2514    regfi_log_add(REGFI_LOG_ERROR, "Read failed"
2515                  " while parsing hbin at offset 0x%.8X.", offset);
2516    goto fail_locked;
2517  }
2518
2519  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_hbin"))
2520    goto fail;
2521
2522  hbin = talloc(NULL, REGFI_HBIN);
2523  if(hbin == NULL)
2524    goto fail;
2525  hbin->file_off = offset;
2526
2527  memcpy(hbin->magic, hbin_header, 4);
2528  if(strict && (memcmp(hbin->magic, "hbin", 4) != 0))
2529  {
2530    /* This always seems to happen at the end of a file, so we make it an INFO
2531     * message, rather than something more serious.
2532     */
2533    regfi_log_add(REGFI_LOG_INFO, "Magic number mismatch "
2534                  "(%.2X %.2X %.2X %.2X) while parsing hbin at offset"
2535                  " 0x%.8X.", hbin->magic[0], hbin->magic[1], 
2536                  hbin->magic[2], hbin->magic[3], offset);
2537    goto fail;
2538  }
2539
2540  hbin->first_hbin_off = IVAL(hbin_header, 0x4);
2541  hbin->block_size = IVAL(hbin_header, 0x8);
2542  /* this should be the same thing as hbin->block_size, but just in case */
2543  hbin->next_block = IVAL(hbin_header, 0x1C);
2544
2545
2546  /* Ensure the block size is a multiple of 0x1000 and doesn't run off
2547   * the end of the file.
2548   */
2549  /* XXX: This may need to be relaxed for dealing with
2550   *      partial or corrupt files.
2551   */
2552  if((offset + hbin->block_size > file->file_length)
2553     || (hbin->block_size & 0xFFFFF000) != hbin->block_size)
2554  {
2555    regfi_log_add(REGFI_LOG_ERROR, "The hbin offset is not aligned"
2556                  " or runs off the end of the file"
2557                  " while parsing hbin at offset 0x%.8X.", offset);
2558    goto fail;
2559  }
2560
2561  return hbin;
2562
2563 fail_locked:
2564  regfi_unlock(file, file->cb_lock, "regfi_parse_hbin");
2565 fail:
2566  talloc_free(hbin);
2567  return NULL;
2568}
2569
2570
2571/*******************************************************************
2572 *******************************************************************/
2573REGFI_NK_REC* regfi_parse_nk(REGFI_FILE* file, uint32_t offset, 
2574                             uint32_t max_size, bool strict)
2575{
2576  uint8_t nk_header[REGFI_NK_MIN_LENGTH];
2577  REGFI_NK_REC* ret_val;
2578  uint32_t length,cell_length;
2579  bool unalloc = false;
2580
2581  ret_val = talloc(NULL, REGFI_NK_REC);
2582  if(ret_val == NULL)
2583  {
2584    regfi_log_add(REGFI_LOG_ERROR, "Failed to allocate memory while"
2585                  " parsing NK record at offset 0x%.8X.", offset);
2586    goto fail;
2587  }
2588
2589  if(!regfi_lock(file, file->cb_lock, "regfi_parse_nk"))
2590    goto fail;
2591
2592  if(!regfi_parse_cell(file->cb, offset, nk_header, REGFI_NK_MIN_LENGTH,
2593                       &cell_length, &unalloc))
2594  {
2595    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2596                  " while parsing NK record at offset 0x%.8X.", offset);
2597    goto fail_locked;
2598  }
2599
2600  if((nk_header[0x0] != 'n') || (nk_header[0x1] != 'k'))
2601  {
2602    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch in parsing"
2603                  " NK record at offset 0x%.8X.", offset);
2604    goto fail_locked;
2605  }
2606
2607  ret_val->values = NULL;
2608  ret_val->subkeys = NULL;
2609  ret_val->offset = offset;
2610  ret_val->cell_size = cell_length;
2611
2612  if(ret_val->cell_size > max_size)
2613    ret_val->cell_size = max_size & 0xFFFFFFF8;
2614  if((ret_val->cell_size < REGFI_NK_MIN_LENGTH) 
2615     || (strict && (ret_val->cell_size & 0x00000007) != 0))
2616  {
2617    regfi_log_add(REGFI_LOG_WARN, "A length check failed while"
2618                  " parsing NK record at offset 0x%.8X.", offset);
2619    goto fail_locked;
2620  }
2621
2622  ret_val->magic[0] = nk_header[0x0];
2623  ret_val->magic[1] = nk_header[0x1];
2624  ret_val->flags = SVAL(nk_header, 0x2);
2625 
2626  if((ret_val->flags & ~REGFI_NK_KNOWN_FLAGS) != 0)
2627  {
2628    regfi_log_add(REGFI_LOG_WARN, "Unknown key flags (0x%.4X) while"
2629                  " parsing NK record at offset 0x%.8X.", 
2630                  (ret_val->flags & ~REGFI_NK_KNOWN_FLAGS), offset);
2631  }
2632
2633  ret_val->mtime.low = IVAL(nk_header, 0x4);
2634  ret_val->mtime.high = IVAL(nk_header, 0x8);
2635  /* If the key is unallocated and the MTIME is earlier than Jan 1, 1990
2636   * or later than Jan 1, 2290, we consider this a bad key.  This helps
2637   * weed out some false positives during deleted data recovery.
2638   */
2639  if(unalloc
2640     && (ret_val->mtime.high < REGFI_MTIME_MIN_HIGH
2641         || ret_val->mtime.high > REGFI_MTIME_MAX_HIGH))
2642  { goto fail_locked; }
2643
2644  ret_val->unknown1 = IVAL(nk_header, 0xC);
2645  ret_val->parent_off = IVAL(nk_header, 0x10);
2646  ret_val->num_subkeys = IVAL(nk_header, 0x14);
2647  ret_val->unknown2 = IVAL(nk_header, 0x18);
2648  ret_val->subkeys_off = IVAL(nk_header, 0x1C);
2649  ret_val->unknown3 = IVAL(nk_header, 0x20);
2650  ret_val->num_values = IVAL(nk_header, 0x24);
2651  ret_val->values_off = IVAL(nk_header, 0x28);
2652  ret_val->sk_off = IVAL(nk_header, 0x2C);
2653  ret_val->classname_off = IVAL(nk_header, 0x30);
2654
2655  ret_val->max_bytes_subkeyname = IVAL(nk_header, 0x34);
2656  ret_val->max_bytes_subkeyclassname = IVAL(nk_header, 0x38);
2657  ret_val->max_bytes_valuename = IVAL(nk_header, 0x3C);
2658  ret_val->max_bytes_value = IVAL(nk_header, 0x40);
2659  ret_val->unk_index = IVAL(nk_header, 0x44);
2660
2661  ret_val->name_length = SVAL(nk_header, 0x48);
2662  ret_val->classname_length = SVAL(nk_header, 0x4A);
2663  ret_val->keyname = NULL;
2664
2665  if(ret_val->name_length + REGFI_NK_MIN_LENGTH > ret_val->cell_size)
2666  {
2667    if(strict)
2668    {
2669      regfi_log_add(REGFI_LOG_ERROR, "Contents too large for cell"
2670                    " while parsing NK record at offset 0x%.8X.", offset);
2671      goto fail_locked;
2672    }
2673    else
2674      ret_val->name_length = ret_val->cell_size - REGFI_NK_MIN_LENGTH;
2675  }
2676  else if (unalloc)
2677  { /* Truncate cell_size if it's much larger than the apparent total record length. */
2678    /* Round up to the next multiple of 8 */
2679    length = (ret_val->name_length + REGFI_NK_MIN_LENGTH) & 0xFFFFFFF8;
2680    if(length < ret_val->name_length + REGFI_NK_MIN_LENGTH)
2681      length+=8;
2682
2683    /* If cell_size is still greater, truncate. */
2684    if(length < ret_val->cell_size)
2685      ret_val->cell_size = length;
2686  }
2687
2688  ret_val->keyname_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2689  if(ret_val->keyname_raw == NULL)
2690    goto fail_locked;
2691
2692  /* Don't need to seek, should be at the right offset */
2693  length = ret_val->name_length;
2694  if((regfi_read(file->cb, (uint8_t*)ret_val->keyname_raw, &length) != 0)
2695     || length != ret_val->name_length)
2696  {
2697    regfi_log_add(REGFI_LOG_ERROR, "Failed to read key name"
2698                  " while parsing NK record at offset 0x%.8X.", offset);
2699    goto fail_locked;
2700  }
2701
2702  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_nk"))
2703    goto fail;
2704
2705  return ret_val;
2706
2707 fail_locked:
2708  regfi_unlock(file, file->cb_lock, "regfi_parse_nk");
2709 fail:
2710  talloc_free(ret_val);
2711  return NULL;
2712}
2713
2714
2715uint8_t* regfi_parse_classname(REGFI_FILE* file, uint32_t offset, 
2716                             uint16_t* name_length, uint32_t max_size, bool strict)
2717{
2718  uint8_t* ret_val = NULL;
2719  uint32_t length;
2720  uint32_t cell_length;
2721  bool unalloc = false;
2722
2723  if(*name_length <= 0 || offset == REGFI_OFFSET_NONE 
2724     || (offset & 0x00000007) != 0)
2725  { goto fail; }
2726
2727  if(!regfi_lock(file, file->cb_lock, "regfi_parse_classname"))
2728    goto fail;
2729
2730  if(!regfi_parse_cell(file->cb, offset, NULL, 0, &cell_length, &unalloc))
2731  {
2732    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2733                  " while parsing class name at offset 0x%.8X.", offset);
2734    goto fail_locked;
2735  }
2736 
2737  if((cell_length & 0x0000007) != 0)
2738  {
2739    regfi_log_add(REGFI_LOG_ERROR, "Cell length not a multiple of 8"
2740                  " while parsing class name at offset 0x%.8X.", offset);
2741    goto fail_locked;
2742  }
2743 
2744  if(cell_length > max_size)
2745  {
2746    regfi_log_add(REGFI_LOG_WARN, "Cell stretches past hbin "
2747                  "boundary while parsing class name at offset 0x%.8X.",
2748                  offset);
2749    if(strict)
2750      goto fail_locked;
2751    cell_length = max_size;
2752  }
2753 
2754  if((cell_length - 4) < *name_length)
2755  {
2756    regfi_log_add(REGFI_LOG_WARN, "Class name is larger than"
2757                  " cell_length while parsing class name at offset"
2758                  " 0x%.8X.", offset);
2759    if(strict)
2760      goto fail_locked;
2761    *name_length = cell_length - 4;
2762  }
2763 
2764  ret_val = talloc_array(NULL, uint8_t, *name_length);
2765  if(ret_val != NULL)
2766  {
2767    length = *name_length;
2768    if((regfi_read(file->cb, ret_val, &length) != 0)
2769       || length != *name_length)
2770    {
2771      regfi_log_add(REGFI_LOG_ERROR, "Could not read class name"
2772                    " while parsing class name at offset 0x%.8X.", offset);
2773      goto fail_locked;
2774    }
2775  }
2776
2777  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_classname"))
2778    goto fail;
2779
2780  return ret_val;
2781
2782 fail_locked:
2783  regfi_unlock(file, file->cb_lock, "regfi_parse_classname");
2784 fail:
2785  talloc_free(ret_val);
2786  return NULL;
2787}
2788
2789
2790/******************************************************************************
2791*******************************************************************************/
2792REGFI_VK_REC* regfi_parse_vk(REGFI_FILE* file, uint32_t offset, 
2793                             uint32_t max_size, bool strict)
2794{
2795  REGFI_VK_REC* ret_val;
2796  uint8_t vk_header[REGFI_VK_MIN_LENGTH];
2797  uint32_t raw_data_size, length, cell_length;
2798  bool unalloc = false;
2799
2800  ret_val = talloc(NULL, REGFI_VK_REC);
2801  if(ret_val == NULL)
2802    goto fail;
2803
2804  if(!regfi_lock(file, file->cb_lock, "regfi_parse_nk"))
2805    goto fail;
2806
2807  if(!regfi_parse_cell(file->cb, offset, vk_header, REGFI_VK_MIN_LENGTH,
2808                       &cell_length, &unalloc))
2809  {
2810    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2811                  " while parsing VK record at offset 0x%.8X.", offset);
2812    goto fail_locked;
2813  }
2814
2815  ret_val->offset = offset;
2816  ret_val->cell_size = cell_length;
2817  ret_val->valuename = NULL;
2818  ret_val->valuename_raw = NULL;
2819 
2820  if(ret_val->cell_size > max_size)
2821    ret_val->cell_size = max_size & 0xFFFFFFF8;
2822  if((ret_val->cell_size < REGFI_VK_MIN_LENGTH) 
2823     || (ret_val->cell_size & 0x00000007) != 0)
2824  {
2825    regfi_log_add(REGFI_LOG_WARN, "Invalid cell size encountered"
2826                  " while parsing VK record at offset 0x%.8X.", offset);
2827    goto fail_locked;
2828  }
2829
2830  ret_val->magic[0] = vk_header[0x0];
2831  ret_val->magic[1] = vk_header[0x1];
2832  if((ret_val->magic[0] != 'v') || (ret_val->magic[1] != 'k'))
2833  {
2834    /* XXX: This does not account for deleted keys under Win2K which
2835     *      often have this (and the name length) overwritten with
2836     *      0xFFFF.
2837     */
2838    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch"
2839                  " while parsing VK record at offset 0x%.8X.", offset);
2840    goto fail_locked;
2841  }
2842
2843  ret_val->name_length = SVAL(vk_header, 0x2);
2844  raw_data_size = IVAL(vk_header, 0x4);
2845  ret_val->data_size = raw_data_size & ~REGFI_VK_DATA_IN_OFFSET;
2846  /* The data is typically stored in the offset if the size <= 4,
2847   * in which case this flag is set.
2848   */
2849  ret_val->data_in_offset = (bool)(raw_data_size & REGFI_VK_DATA_IN_OFFSET);
2850  ret_val->data_off = IVAL(vk_header, 0x8);
2851  ret_val->type = IVAL(vk_header, 0xC);
2852  ret_val->flags = SVAL(vk_header, 0x10);
2853  ret_val->unknown1 = SVAL(vk_header, 0x12);
2854
2855  if(ret_val->name_length > 0)
2856  {
2857    if(ret_val->name_length + REGFI_VK_MIN_LENGTH + 4 > ret_val->cell_size)
2858    {
2859      regfi_log_add(REGFI_LOG_WARN, "Name too long for remaining cell"
2860                    " space while parsing VK record at offset 0x%.8X.",
2861                    offset);
2862      if(strict)
2863        goto fail_locked;
2864      else
2865        ret_val->name_length = ret_val->cell_size - REGFI_VK_MIN_LENGTH - 4;
2866    }
2867
2868    /* Round up to the next multiple of 8 */
2869    cell_length = (ret_val->name_length + REGFI_VK_MIN_LENGTH + 4) & 0xFFFFFFF8;
2870    if(cell_length < ret_val->name_length + REGFI_VK_MIN_LENGTH + 4)
2871      cell_length+=8;
2872
2873    ret_val->valuename_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2874    if(ret_val->valuename_raw == NULL)
2875      goto fail_locked;
2876
2877    length = ret_val->name_length;
2878    if((regfi_read(file->cb, (uint8_t*)ret_val->valuename_raw, &length) != 0)
2879       || length != ret_val->name_length)
2880    {
2881      regfi_log_add(REGFI_LOG_ERROR, "Could not read value name"
2882                    " while parsing VK record at offset 0x%.8X.", offset);
2883      goto fail_locked;
2884    }
2885  }
2886  else
2887    cell_length = REGFI_VK_MIN_LENGTH + 4;
2888
2889  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_nk"))
2890    goto fail;
2891
2892  if(unalloc)
2893  {
2894    /* If cell_size is still greater, truncate. */
2895    if(cell_length < ret_val->cell_size)
2896      ret_val->cell_size = cell_length;
2897  }
2898
2899  return ret_val;
2900 
2901 fail_locked:
2902  regfi_unlock(file, file->cb_lock, "regfi_parse_vk");
2903 fail:
2904  talloc_free(ret_val);
2905  return NULL;
2906}
2907
2908
2909/******************************************************************************
2910 *
2911 ******************************************************************************/
2912REGFI_BUFFER regfi_load_data(REGFI_FILE* file, uint32_t voffset,
2913                             uint32_t length, bool data_in_offset,
2914                             bool strict)
2915{
2916  REGFI_BUFFER ret_val;
2917  uint32_t cell_length, offset;
2918  int32_t max_size;
2919  bool unalloc;
2920 
2921  /* Microsoft's documentation indicates that "available memory" is
2922   * the limit on value sizes for the more recent registry format version.
2923   * This is not only annoying, but it's probably also incorrect, since clearly
2924   * value data sizes are limited to 2^31 (high bit used as a flag) and even
2925   * with big data records, the apparent max size is:
2926   *   16344 * 2^16 = 1071104040 (~1GB).
2927   *
2928   * We choose to limit it to 1M which was the limit in older versions and
2929   * should rarely be exceeded unless the file is corrupt or malicious.
2930   * For more info, see:
2931   *   http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
2932   */
2933  /* XXX: add way to skip this check at user discression. */
2934  if(length > REGFI_VK_MAX_DATA_LENGTH)
2935  {
2936    regfi_log_add(REGFI_LOG_WARN, "Value data size %d larger than "
2937                  "%d, truncating...", length, REGFI_VK_MAX_DATA_LENGTH);
2938    length = REGFI_VK_MAX_DATA_LENGTH;
2939  }
2940
2941  if(data_in_offset)
2942    return regfi_parse_little_data(file, voffset, length, strict);
2943  else
2944  {
2945    offset = voffset + REGFI_REGF_SIZE;
2946    max_size = regfi_calc_maxsize(file, offset);
2947    if(max_size < 0)
2948    {
2949      regfi_log_add(REGFI_LOG_WARN, "Could not find HBIN for data"
2950                    " at offset 0x%.8X.", offset);
2951      goto fail;
2952    }
2953   
2954    if(!regfi_lock(file, file->cb_lock, "regfi_load_data"))
2955      goto fail;
2956
2957    if(!regfi_parse_cell(file->cb, offset, NULL, 0,
2958                         &cell_length, &unalloc))
2959    {
2960      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
2961                    " parsing data record at offset 0x%.8X.", offset);
2962      goto fail_locked;
2963    }
2964
2965    if(!regfi_unlock(file, file->cb_lock, "regfi_load_data"))
2966      goto fail;
2967
2968    if((cell_length & 0x00000007) != 0)
2969    {
2970      regfi_log_add(REGFI_LOG_WARN, "Cell length not multiple of 8"
2971                    " while parsing data record at offset 0x%.8X.",
2972                    offset);
2973      goto fail;
2974    }
2975
2976    if(cell_length > max_size)
2977    {
2978      regfi_log_add(REGFI_LOG_WARN, "Cell extends past HBIN boundary"
2979                    " while parsing data record at offset 0x%.8X.",
2980                    offset);
2981      goto fail;
2982    }
2983
2984    if(cell_length - 4 < length)
2985    {
2986      /* XXX: All big data records thus far have been 16 bytes long. 
2987       *      Should we check for this precise size instead of just
2988       *      relying upon the above check?
2989       */
2990      if (file->major_version >= 1 && file->minor_version >= 5)
2991      {
2992        /* Attempt to parse a big data record */
2993        return regfi_load_big_data(file, offset, length, cell_length, 
2994                                   NULL, strict);
2995      }
2996      else
2997      {
2998        regfi_log_add(REGFI_LOG_WARN, "Data length (0x%.8X) larger than"
2999                      " remaining cell length (0x%.8X)"
3000                      " while parsing data record at offset 0x%.8X.", 
3001                      length, cell_length - 4, offset);
3002        if(strict)
3003          goto fail;
3004        else
3005          length = cell_length - 4;
3006      }
3007    }
3008
3009    ret_val = regfi_parse_data(file, offset, length, strict);
3010  }
3011
3012  return ret_val;
3013
3014 fail_locked:
3015  regfi_unlock(file, file->cb_lock, "regfi_load_data");
3016 fail:
3017  ret_val.buf = NULL;
3018  ret_val.len = 0;
3019  return ret_val;
3020}
3021
3022
3023/******************************************************************************
3024 * Parses the common case data records stored in a single cell.
3025 ******************************************************************************/
3026REGFI_BUFFER regfi_parse_data(REGFI_FILE* file, uint32_t offset,
3027                              uint32_t length, bool strict)
3028{
3029  REGFI_BUFFER ret_val;
3030  uint32_t read_length;
3031
3032  ret_val.buf = NULL;
3033  ret_val.len = 0;
3034 
3035  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
3036    goto fail;
3037  ret_val.len = length;
3038
3039  if(!regfi_lock(file, file->cb_lock, "regfi_parse_data"))
3040    goto fail;
3041
3042  if(regfi_seek(file->cb, offset+4, SEEK_SET) == -1)
3043  {
3044    regfi_log_add(REGFI_LOG_WARN, "Could not seek while "
3045                  "reading data at offset 0x%.8X.", offset);
3046    goto fail_locked;
3047  }
3048 
3049  read_length = length;
3050  if((regfi_read(file->cb, ret_val.buf, &read_length) != 0)
3051     || read_length != length)
3052  {
3053    regfi_log_add(REGFI_LOG_ERROR, "Could not read data block while"
3054                  " parsing data record at offset 0x%.8X.", offset);
3055    goto fail_locked;
3056  }
3057
3058  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_data"))
3059    goto fail;
3060
3061  return ret_val;
3062
3063 fail_locked:
3064  regfi_unlock(file, file->cb_lock, "regfi_parse_data");
3065 fail:
3066  talloc_free(ret_val.buf);
3067  ret_val.buf = NULL;
3068  ret_val.buf = 0;
3069  return ret_val;
3070}
3071
3072
3073
3074/******************************************************************************
3075 *
3076 ******************************************************************************/
3077REGFI_BUFFER regfi_parse_little_data(REGFI_FILE* file, uint32_t voffset,
3078                                     uint32_t length, bool strict)
3079{
3080  uint8_t i;
3081  REGFI_BUFFER ret_val;
3082
3083  ret_val.buf = NULL;
3084  ret_val.len = 0;
3085
3086  if(length > 4)
3087  {
3088    regfi_log_add(REGFI_LOG_ERROR, "Data in offset but length > 4"
3089                  " while parsing data record. (voffset=0x%.8X, length=%d)",
3090                  voffset, length);
3091    return ret_val;
3092  }
3093
3094  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
3095    return ret_val;
3096  ret_val.len = length;
3097 
3098  for(i = 0; i < length; i++)
3099    ret_val.buf[i] = (uint8_t)((voffset >> i*8) & 0xFF);
3100
3101  return ret_val;
3102}
3103
3104/******************************************************************************
3105*******************************************************************************/
3106REGFI_BUFFER regfi_parse_big_data_header(REGFI_FILE* file, uint32_t offset, 
3107                                         uint32_t max_size, bool strict)
3108{
3109  REGFI_BUFFER ret_val;
3110  uint32_t cell_length;
3111  bool unalloc;
3112
3113  /* XXX: do something with unalloc? */
3114  ret_val.buf = (uint8_t*)talloc_array(NULL, uint8_t, REGFI_BIG_DATA_MIN_LENGTH);
3115  if(ret_val.buf == NULL)
3116    goto fail;
3117
3118  if(REGFI_BIG_DATA_MIN_LENGTH > max_size)
3119  {
3120    regfi_log_add(REGFI_LOG_WARN, "Big data header exceeded max_size "
3121                  "while parsing big data header at offset 0x%.8X.",offset);
3122    goto fail;
3123  }
3124
3125  if(!regfi_lock(file, file->cb_lock, "regfi_parse_big_data_header"))
3126    goto fail;
3127
3128
3129  if(!regfi_parse_cell(file->cb, offset, ret_val.buf, REGFI_BIG_DATA_MIN_LENGTH,
3130                       &cell_length, &unalloc))
3131  {
3132    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3133                  " parsing big data header at offset 0x%.8X.", offset);
3134    goto fail_locked;
3135  }
3136
3137  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_header"))
3138    goto fail;
3139
3140  if((ret_val.buf[0] != 'd') || (ret_val.buf[1] != 'b'))
3141  {
3142    regfi_log_add(REGFI_LOG_WARN, "Unknown magic number"
3143                  " (0x%.2X, 0x%.2X) encountered while parsing"
3144                  " big data header at offset 0x%.8X.", 
3145                  ret_val.buf[0], ret_val.buf[1], offset);
3146    goto fail;
3147  }
3148
3149  ret_val.len = REGFI_BIG_DATA_MIN_LENGTH;
3150  return ret_val;
3151
3152 fail_locked:
3153  regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_header");
3154 fail:
3155  talloc_free(ret_val.buf);
3156  ret_val.buf = NULL;
3157  ret_val.len = 0;
3158  return ret_val;
3159}
3160
3161
3162
3163/******************************************************************************
3164 *
3165 ******************************************************************************/
3166uint32_t* regfi_parse_big_data_indirect(REGFI_FILE* file, uint32_t offset,
3167                                      uint16_t num_chunks, bool strict)
3168{
3169  uint32_t* ret_val;
3170  uint32_t indirect_length;
3171  int32_t max_size;
3172  uint16_t i;
3173  bool unalloc;
3174
3175  /* XXX: do something with unalloc? */
3176
3177  max_size = regfi_calc_maxsize(file, offset);
3178  if((max_size < 0) || (num_chunks*sizeof(uint32_t) + 4 > max_size))
3179    return NULL;
3180
3181  ret_val = (uint32_t*)talloc_array(NULL, uint32_t, num_chunks);
3182  if(ret_val == NULL)
3183    goto fail;
3184
3185  if(!regfi_lock(file, file->cb_lock, "regfi_parse_big_data_indirect"))
3186    goto fail;
3187
3188  if(!regfi_parse_cell(file->cb, offset, (uint8_t*)ret_val,
3189                       num_chunks*sizeof(uint32_t),
3190                       &indirect_length, &unalloc))
3191  {
3192    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3193                  " parsing big data indirect record at offset 0x%.8X.", 
3194                  offset);
3195    goto fail_locked;
3196  }
3197
3198  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_indirect"))
3199    goto fail;
3200
3201  /* Convert pointers to proper endianess, verify they are aligned. */
3202  for(i=0; i<num_chunks; i++)
3203  {
3204    ret_val[i] = IVAL(ret_val, i*sizeof(uint32_t));
3205    if((ret_val[i] & 0x00000007) != 0)
3206      goto fail;
3207  }
3208 
3209  return ret_val;
3210
3211 fail_locked:
3212  regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_indirect");
3213 fail:
3214  talloc_free(ret_val);
3215  return NULL;
3216}
3217
3218
3219/******************************************************************************
3220 * Arguments:
3221 *  file       --
3222 *  offsets    -- list of virtual offsets.
3223 *  num_chunks --
3224 *  strict     --
3225 *
3226 * Returns:
3227 *  A range_list with physical offsets and complete lengths
3228 *  (including cell headers) of associated cells. 
3229 *  No data in range_list elements.
3230 ******************************************************************************/
3231range_list* regfi_parse_big_data_cells(REGFI_FILE* file, uint32_t* offsets,
3232                                       uint16_t num_chunks, bool strict)
3233{
3234  uint32_t cell_length, chunk_offset;
3235  range_list* ret_val;
3236  uint16_t i;
3237  bool unalloc;
3238 
3239  /* XXX: do something with unalloc? */
3240  ret_val = range_list_new();
3241  if(ret_val == NULL)
3242    goto fail;
3243 
3244  for(i=0; i<num_chunks; i++)
3245  {
3246    if(!regfi_lock(file, file->cb_lock, "regfi_parse_big_data_cells"))
3247      goto fail;
3248
3249    chunk_offset = offsets[i]+REGFI_REGF_SIZE;
3250    if(!regfi_parse_cell(file->cb, chunk_offset, NULL, 0,
3251                         &cell_length, &unalloc))
3252    {
3253      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3254                    " parsing big data chunk at offset 0x%.8X.", 
3255                    chunk_offset);
3256      goto fail_locked;
3257    }
3258
3259    if(!regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_cells"))
3260      goto fail;
3261
3262    if(!range_list_add(ret_val, chunk_offset, cell_length, NULL))
3263      goto fail;
3264  }
3265
3266  return ret_val;
3267
3268 fail_locked:
3269  regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_cells");
3270 fail:
3271  if(ret_val != NULL)
3272    range_list_free(ret_val);
3273  return NULL;
3274}
3275
3276
3277/******************************************************************************
3278*******************************************************************************/
3279REGFI_BUFFER regfi_load_big_data(REGFI_FILE* file, 
3280                                 uint32_t offset, uint32_t data_length, 
3281                                 uint32_t cell_length, range_list* used_ranges,
3282                                 bool strict)
3283{
3284  REGFI_BUFFER ret_val;
3285  uint16_t num_chunks, i;
3286  uint32_t read_length, data_left, tmp_len, indirect_offset;
3287  uint32_t* indirect_ptrs = NULL;
3288  REGFI_BUFFER bd_header;
3289  range_list* bd_cells = NULL;
3290  const range_list_element* cell_info;
3291
3292  ret_val.buf = NULL;
3293
3294  /* XXX: Add better error/warning messages */
3295
3296  bd_header = regfi_parse_big_data_header(file, offset, cell_length, strict);
3297  if(bd_header.buf == NULL)
3298    goto fail;
3299
3300  /* Keep track of used space for use by reglookup-recover */
3301  if(used_ranges != NULL)
3302    if(!range_list_add(used_ranges, offset, cell_length, NULL))
3303      goto fail;
3304
3305  num_chunks = SVAL(bd_header.buf, 0x2);
3306  indirect_offset = IVAL(bd_header.buf, 0x4) + REGFI_REGF_SIZE;
3307  talloc_free(bd_header.buf);
3308
3309  indirect_ptrs = regfi_parse_big_data_indirect(file, indirect_offset,
3310                                                num_chunks, strict);
3311  if(indirect_ptrs == NULL)
3312    goto fail;
3313
3314  if(used_ranges != NULL)
3315    if(!range_list_add(used_ranges, indirect_offset, num_chunks*4+4, NULL))
3316      goto fail;
3317 
3318  if((ret_val.buf = talloc_array(NULL, uint8_t, data_length)) == NULL)
3319    goto fail;
3320  data_left = data_length;
3321
3322  bd_cells = regfi_parse_big_data_cells(file, indirect_ptrs, num_chunks, strict);
3323  if(bd_cells == NULL)
3324    goto fail;
3325
3326  talloc_free(indirect_ptrs);
3327  indirect_ptrs = NULL;
3328 
3329  for(i=0; (i<num_chunks) && (data_left>0); i++)
3330  {
3331    cell_info = range_list_get(bd_cells, i);
3332    if(cell_info == NULL)
3333      goto fail;
3334
3335    /* XXX: This should be "cell_info->length-4" to account for the 4 byte cell
3336     *      length.  However, it has been observed that some (all?) chunks
3337     *      have an additional 4 bytes of 0 at the end of their cells that
3338     *      isn't part of the data, so we're trimming that off too.
3339     *      Perhaps it's just an 8 byte alignment requirement...
3340     */
3341    if(cell_info->length - 8 >= data_left)
3342    {
3343      if(i+1 != num_chunks)
3344      {
3345        regfi_log_add(REGFI_LOG_WARN, "Left over chunks detected "
3346                      "while constructing big data at offset 0x%.8X "
3347                      "(chunk offset 0x%.8X).", offset, cell_info->offset);
3348      }
3349      read_length = data_left;
3350    }
3351    else
3352      read_length = cell_info->length - 8;
3353
3354
3355    if(read_length > regfi_calc_maxsize(file, cell_info->offset))
3356    {
3357      regfi_log_add(REGFI_LOG_WARN, "A chunk exceeded the maxsize "
3358                    "while constructing big data at offset 0x%.8X "
3359                    "(chunk offset 0x%.8X).", offset, cell_info->offset);
3360      goto fail;
3361    }
3362
3363    if(!regfi_lock(file, file->cb_lock, "regfi_load_big_data"))
3364      goto fail;
3365
3366    if(regfi_seek(file->cb, cell_info->offset+sizeof(uint32_t), SEEK_SET) == -1)
3367    {
3368      regfi_log_add(REGFI_LOG_WARN, "Could not seek to chunk while "
3369                    "constructing big data at offset 0x%.8X "
3370                    "(chunk offset 0x%.8X).", offset, cell_info->offset);
3371      goto fail_locked;
3372    }
3373
3374    tmp_len = read_length;
3375    if(regfi_read(file->cb, ret_val.buf+(data_length-data_left), 
3376                  &read_length) != 0 || (read_length != tmp_len))
3377    {
3378      regfi_log_add(REGFI_LOG_WARN, "Could not read data chunk while"
3379                    " constructing big data at offset 0x%.8X"
3380                    " (chunk offset 0x%.8X).", offset, cell_info->offset);
3381      goto fail_locked;
3382    }
3383
3384    if(!regfi_unlock(file, file->cb_lock, "regfi_load_big_data"))
3385      goto fail;
3386
3387    if(used_ranges != NULL)
3388      if(!range_list_add(used_ranges, cell_info->offset,cell_info->length,NULL))
3389        goto fail;
3390
3391    data_left -= read_length;
3392  }
3393  range_list_free(bd_cells);
3394
3395  ret_val.len = data_length-data_left;
3396  return ret_val;
3397
3398 fail_locked:
3399  regfi_unlock(file, file->cb_lock, "regfi_load_big_data");
3400 fail:
3401  talloc_free(ret_val.buf);
3402  talloc_free(indirect_ptrs);
3403  if(bd_cells != NULL)
3404    range_list_free(bd_cells);
3405  ret_val.buf = NULL;
3406  ret_val.len = 0;
3407  return ret_val;
3408}
3409
3410
3411range_list* regfi_parse_unalloc_cells(REGFI_FILE* file)
3412{
3413  range_list* ret_val;
3414  REGFI_HBIN* hbin;
3415  const range_list_element* hbins_elem;
3416  uint32_t i, num_hbins, curr_off, cell_len;
3417  bool is_unalloc;
3418
3419  ret_val = range_list_new();
3420  if(ret_val == NULL)
3421    return NULL;
3422
3423  if(!regfi_read_lock(file, file->hbins_lock, "regfi_parse_unalloc_cells"))
3424  {
3425    range_list_free(ret_val);
3426    return NULL;
3427  }
3428
3429  num_hbins = range_list_size(file->hbins);
3430  for(i=0; i<num_hbins; i++)
3431  {
3432    hbins_elem = range_list_get(file->hbins, i);
3433    if(hbins_elem == NULL)
3434      break;
3435    hbin = (REGFI_HBIN*)hbins_elem->data;
3436
3437    curr_off = REGFI_HBIN_HEADER_SIZE;
3438    while(curr_off < hbin->block_size)
3439    {
3440      if(!regfi_lock(file, file->cb_lock, "regfi_parse_unalloc_cells"))
3441        break;
3442
3443      if(!regfi_parse_cell(file->cb, hbin->file_off+curr_off, NULL, 0,
3444                           &cell_len, &is_unalloc))
3445      {
3446        regfi_unlock(file, file->cb_lock, "regfi_parse_unalloc_cells");
3447        break;
3448      }
3449
3450      if(!regfi_unlock(file, file->cb_lock, "regfi_parse_unalloc_cells"))
3451        break;
3452
3453      if((cell_len == 0) || ((cell_len & 0x00000007) != 0))
3454      {
3455        regfi_log_add(REGFI_LOG_ERROR, "Bad cell length encountered"
3456                      " while parsing unallocated cells at offset 0x%.8X.",
3457                      hbin->file_off+curr_off);
3458        break;
3459      }
3460
3461      /* for some reason the record_size of the last record in
3462         an hbin block can extend past the end of the block
3463         even though the record fits within the remaining
3464         space....aaarrrgggghhhhhh */ 
3465      if(curr_off + cell_len >= hbin->block_size)
3466        cell_len = hbin->block_size - curr_off;
3467     
3468      if(is_unalloc)
3469        range_list_add(ret_val, hbin->file_off+curr_off, 
3470                       cell_len, NULL);
3471     
3472      curr_off = curr_off+cell_len;
3473    }
3474  }
3475
3476  if(!regfi_rw_unlock(file, file->hbins_lock, "regfi_parse_unalloc_cells"))
3477  {
3478    range_list_free(ret_val);
3479    return NULL;
3480  }
3481
3482  return ret_val;
3483}
3484
3485
3486/* From lib/time.c */
3487
3488/****************************************************************************
3489 Put a 8 byte filetime from a time_t
3490 This takes real GMT as input and converts to kludge-GMT
3491****************************************************************************/
3492void regfi_unix2nt_time(REGFI_NTTIME *nt, time_t t)
3493{
3494  double d;
3495 
3496  if (t==0) 
3497  {
3498    nt->low = 0;
3499    nt->high = 0;
3500    return;
3501  }
3502 
3503  if (t == TIME_T_MAX) 
3504  {
3505    nt->low = 0xffffffff;
3506    nt->high = 0x7fffffff;
3507    return;
3508  }             
3509 
3510  if (t == -1) 
3511  {
3512    nt->low = 0xffffffff;
3513    nt->high = 0xffffffff;
3514    return;
3515  }             
3516 
3517  /* this converts GMT to kludge-GMT */
3518  /* XXX: This was removed due to difficult dependency requirements. 
3519   *      So far, times appear to be correct without this adjustment, but
3520   *      that may be proven wrong with adequate testing.
3521   */
3522  /* t -= TimeDiff(t) - get_serverzone(); */
3523 
3524  d = (double)(t);
3525  d += TIME_FIXUP_CONSTANT;
3526  d *= 1.0e7;
3527 
3528  nt->high = (uint32_t)(d * (1.0/(4.0*(double)(1<<30))));
3529  nt->low  = (uint32_t)(d - ((double)nt->high)*4.0*(double)(1<<30));
3530}
3531
3532
3533/****************************************************************************
3534 Interpret an 8 byte "filetime" structure to a time_t
3535 It's originally in "100ns units since jan 1st 1601"
3536
3537 An 8 byte value of 0xffffffffffffffff will be returned as (time_t)0.
3538
3539 It appears to be kludge-GMT (at least for file listings). This means
3540 its the GMT you get by taking a localtime and adding the
3541 serverzone. This is NOT the same as GMT in some cases. This routine
3542 converts this to real GMT.
3543****************************************************************************/
3544time_t regfi_nt2unix_time(const REGFI_NTTIME* nt)
3545{
3546  double d;
3547  time_t ret;
3548  /* The next two lines are a fix needed for the
3549     broken SCO compiler. JRA. */
3550  time_t l_time_min = TIME_T_MIN;
3551  time_t l_time_max = TIME_T_MAX;
3552 
3553  if (nt->high == 0 || (nt->high == 0xffffffff && nt->low == 0xffffffff))
3554    return(0);
3555 
3556  d = ((double)nt->high)*4.0*(double)(1<<30);
3557  d += (nt->low&0xFFF00000);
3558  d *= 1.0e-7;
3559 
3560  /* now adjust by 369 years to make the secs since 1970 */
3561  d -= TIME_FIXUP_CONSTANT;
3562 
3563  if (d <= l_time_min)
3564    return (l_time_min);
3565 
3566  if (d >= l_time_max)
3567    return (l_time_max);
3568 
3569  ret = (time_t)(d+0.5);
3570 
3571  /* this takes us from kludge-GMT to real GMT */
3572  /* XXX: This was removed due to difficult dependency requirements. 
3573   *      So far, times appear to be correct without this adjustment, but
3574   *      that may be proven wrong with adequate testing.
3575   */
3576  /*
3577    ret -= get_serverzone();
3578    ret += LocTimeDiff(ret);
3579  */
3580
3581  return(ret);
3582}
3583
3584/* End of stuff from lib/time.c */
Note: See TracBrowser for help on using the repository browser.