source: trunk/lib/regfi.c @ 181

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

fixed memory management issues and a talloc_free() of an uninitialized pointer

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