source: trunk/lib/regfi.c @ 184

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

redesigned memory management to allow for multiple references to talloc-ed objects

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