source: trunk/lib/regfi.c @ 180

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

Added locks to make transactions on REGFI_FILE objects thread safe

Added initial version of a threading smoke test

  • 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 180 2010-03-14 20:02:38Z 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_reference(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_reference(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_reference(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_reference(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_reference(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
1658  ret_val->key_positions = void_stack_new(REGFI_MAX_DEPTH);
1659  if(ret_val->key_positions == NULL)
1660  {
1661    talloc_free(ret_val);
1662    return NULL;
1663  }
1664  talloc_reference(ret_val, ret_val->key_positions);
1665
1666  ret_val->f = file;
1667  ret_val->cur_key = root;
1668  ret_val->cur_subkey = 0;
1669  ret_val->cur_value = 0;
1670  ret_val->string_encoding = output_encoding;
1671   
1672  return ret_val;
1673}
1674
1675
1676/******************************************************************************
1677 *****************************************************************************/
1678void regfi_iterator_free(REGFI_ITERATOR* i)
1679{
1680  talloc_free(i);
1681}
1682
1683
1684
1685/******************************************************************************
1686 *****************************************************************************/
1687/* XXX: some way of indicating reason for failure should be added. */
1688bool regfi_iterator_down(REGFI_ITERATOR* i)
1689{
1690  REGFI_NK_REC* subkey;
1691  REGFI_ITER_POSITION* pos;
1692
1693  pos = talloc(i->key_positions, REGFI_ITER_POSITION);
1694  if(pos == NULL)
1695    return false;
1696
1697  subkey = (REGFI_NK_REC*)regfi_iterator_cur_subkey(i);
1698  if(subkey == NULL)
1699  {
1700    talloc_free(pos);
1701    return false;
1702  }
1703
1704  pos->nk = i->cur_key;
1705  pos->cur_subkey = i->cur_subkey;
1706  if(!void_stack_push(i->key_positions, pos))
1707  {
1708    talloc_free(pos);
1709    regfi_free_key(subkey);
1710    return false;
1711  }
1712  talloc_reference(i, subkey);
1713
1714  i->cur_key = subkey;
1715  i->cur_subkey = 0;
1716  i->cur_value = 0;
1717
1718  return true;
1719}
1720
1721
1722/******************************************************************************
1723 *****************************************************************************/
1724bool regfi_iterator_up(REGFI_ITERATOR* i)
1725{
1726  REGFI_ITER_POSITION* pos;
1727
1728  pos = (REGFI_ITER_POSITION*)void_stack_pop(i->key_positions);
1729  if(pos == NULL)
1730    return false;
1731
1732  regfi_free_key(i->cur_key);
1733  i->cur_key = pos->nk;
1734  i->cur_subkey = pos->cur_subkey;
1735  i->cur_value = 0;
1736  talloc_free(pos);
1737
1738  return true;
1739}
1740
1741
1742/******************************************************************************
1743 *****************************************************************************/
1744bool regfi_iterator_to_root(REGFI_ITERATOR* i)
1745{
1746  while(regfi_iterator_up(i))
1747    continue;
1748
1749  return true;
1750}
1751
1752
1753/******************************************************************************
1754 *****************************************************************************/
1755bool regfi_iterator_find_subkey(REGFI_ITERATOR* i, const char* subkey_name)
1756{
1757  REGFI_NK_REC* subkey;
1758  bool found = false;
1759  uint32_t old_subkey = i->cur_subkey;
1760
1761  if(subkey_name == NULL)
1762    return false;
1763
1764  /* XXX: this alloc/free of each sub key might be a bit excessive */
1765  subkey = (REGFI_NK_REC*)regfi_iterator_first_subkey(i);
1766  while((subkey != NULL) && (found == false))
1767  {
1768    if(subkey->keyname != NULL 
1769       && strcasecmp(subkey->keyname, subkey_name) == 0)
1770      found = true;
1771    else
1772    {
1773      regfi_free_key(subkey);
1774      subkey = (REGFI_NK_REC*)regfi_iterator_next_subkey(i);
1775    }
1776  }
1777
1778  if(found == false)
1779  {
1780    i->cur_subkey = old_subkey;
1781    return false;
1782  }
1783
1784  regfi_free_key(subkey);
1785  return true;
1786}
1787
1788
1789/******************************************************************************
1790 *****************************************************************************/
1791bool regfi_iterator_walk_path(REGFI_ITERATOR* i, const char** path)
1792{
1793  uint32_t x;
1794  if(path == NULL)
1795    return false;
1796
1797  for(x=0; 
1798      ((path[x] != NULL) && regfi_iterator_find_subkey(i, path[x])
1799       && regfi_iterator_down(i));
1800      x++)
1801  { continue; }
1802
1803  if(path[x] == NULL)
1804    return true;
1805 
1806  /* XXX: is this the right number of times? */
1807  for(; x > 0; x--)
1808    regfi_iterator_up(i);
1809 
1810  return false;
1811}
1812
1813
1814/******************************************************************************
1815 *****************************************************************************/
1816const REGFI_NK_REC* regfi_iterator_cur_key(REGFI_ITERATOR* i)
1817{
1818  return i->cur_key;
1819}
1820
1821
1822/******************************************************************************
1823 *****************************************************************************/
1824const REGFI_SK_REC* regfi_iterator_cur_sk(REGFI_ITERATOR* i)
1825{
1826  if(i->cur_key == NULL || i->cur_key->sk_off == REGFI_OFFSET_NONE)
1827    return NULL;
1828
1829  return regfi_load_sk(i->f, i->cur_key->sk_off + REGFI_REGF_SIZE, true);
1830}
1831
1832
1833/******************************************************************************
1834 *****************************************************************************/
1835REGFI_NK_REC* regfi_iterator_first_subkey(REGFI_ITERATOR* i)
1836{
1837  i->cur_subkey = 0;
1838  return regfi_iterator_cur_subkey(i);
1839}
1840
1841
1842/******************************************************************************
1843 *****************************************************************************/
1844REGFI_NK_REC* regfi_iterator_cur_subkey(REGFI_ITERATOR* i)
1845{
1846  uint32_t nk_offset;
1847
1848  /* see if there is anything left to report */
1849  if (!(i->cur_key) || (i->cur_key->subkeys_off==REGFI_OFFSET_NONE)
1850      || (i->cur_subkey >= i->cur_key->num_subkeys))
1851    return NULL;
1852
1853  nk_offset = i->cur_key->subkeys->elements[i->cur_subkey].offset;
1854
1855  return regfi_load_key(i->f, nk_offset+REGFI_REGF_SIZE, i->string_encoding, 
1856                        true);
1857}
1858
1859
1860/******************************************************************************
1861 *****************************************************************************/
1862/* XXX: some way of indicating reason for failure should be added. */
1863REGFI_NK_REC* regfi_iterator_next_subkey(REGFI_ITERATOR* i)
1864{
1865  REGFI_NK_REC* subkey;
1866
1867  i->cur_subkey++;
1868  subkey = regfi_iterator_cur_subkey(i);
1869
1870  if(subkey == NULL)
1871    i->cur_subkey--;
1872
1873  return subkey;
1874}
1875
1876
1877/******************************************************************************
1878 *****************************************************************************/
1879bool regfi_iterator_find_value(REGFI_ITERATOR* i, const char* value_name)
1880{
1881  REGFI_VK_REC* cur;
1882  bool found = false;
1883  uint32_t old_value = i->cur_value;
1884
1885  /* XXX: cur->valuename can be NULL in the registry. 
1886   *      Should we allow for a way to search for that?
1887   */
1888  if(value_name == NULL)
1889    return false;
1890
1891  cur = regfi_iterator_first_value(i);
1892  while((cur != NULL) && (found == false))
1893  {
1894    if((cur->valuename != NULL)
1895       && (strcasecmp(cur->valuename, value_name) == 0))
1896      found = true;
1897    else
1898    {
1899      regfi_free_value(cur);
1900      cur = regfi_iterator_next_value(i);
1901    }
1902  }
1903 
1904  if(found == false)
1905  {
1906    i->cur_value = old_value;
1907    return false;
1908  }
1909
1910  regfi_free_value(cur);
1911  return true;
1912}
1913
1914
1915/******************************************************************************
1916 *****************************************************************************/
1917REGFI_VK_REC* regfi_iterator_first_value(REGFI_ITERATOR* i)
1918{
1919  i->cur_value = 0;
1920  return regfi_iterator_cur_value(i);
1921}
1922
1923
1924/******************************************************************************
1925 *****************************************************************************/
1926REGFI_VK_REC* regfi_iterator_cur_value(REGFI_ITERATOR* i)
1927{
1928  REGFI_VK_REC* ret_val = NULL;
1929  uint32_t voffset;
1930
1931  if(i->cur_key->values != NULL && i->cur_key->values->elements != NULL)
1932  {
1933    if(i->cur_value < i->cur_key->values->num_values)
1934    {
1935      voffset = i->cur_key->values->elements[i->cur_value];
1936      ret_val = regfi_load_value(i->f, voffset+REGFI_REGF_SIZE, 
1937                                 i->string_encoding, true);
1938    }
1939  }
1940
1941  return ret_val;
1942}
1943
1944
1945/******************************************************************************
1946 *****************************************************************************/
1947REGFI_VK_REC* regfi_iterator_next_value(REGFI_ITERATOR* i)
1948{
1949  REGFI_VK_REC* ret_val;
1950
1951  i->cur_value++;
1952  ret_val = regfi_iterator_cur_value(i);
1953  if(ret_val == NULL)
1954    i->cur_value--;
1955
1956  return ret_val;
1957}
1958
1959
1960/******************************************************************************
1961 *****************************************************************************/
1962REGFI_CLASSNAME* regfi_iterator_fetch_classname(REGFI_ITERATOR* i, 
1963                                                const REGFI_NK_REC* key)
1964{
1965  REGFI_CLASSNAME* ret_val;
1966  uint8_t* raw;
1967  char* interpreted;
1968  uint32_t offset;
1969  int32_t conv_size, max_size;
1970  uint16_t parse_length;
1971
1972  if(key->classname_off == REGFI_OFFSET_NONE || key->classname_length == 0)
1973    return NULL;
1974
1975  offset = key->classname_off + REGFI_REGF_SIZE;
1976  max_size = regfi_calc_maxsize(i->f, offset);
1977  if(max_size <= 0)
1978    return NULL;
1979
1980  parse_length = key->classname_length;
1981  raw = regfi_parse_classname(i->f, offset, &parse_length, max_size, true);
1982 
1983  if(raw == NULL)
1984  {
1985    regfi_add_message(i->f, REGFI_MSG_WARN, "Could not parse class"
1986                      " name at offset 0x%.8X for key record at offset 0x%.8X.",
1987                      offset, key->offset);
1988    return NULL;
1989  }
1990
1991  ret_val = talloc(NULL, REGFI_CLASSNAME);
1992  if(ret_val == NULL)
1993    return NULL;
1994
1995  ret_val->raw = raw;
1996  ret_val->size = parse_length;
1997  talloc_reference(ret_val, raw);
1998
1999  interpreted = talloc_array(NULL, char, parse_length);
2000
2001  conv_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2002                                 regfi_encoding_int2str(i->string_encoding),
2003                                 raw, interpreted,
2004                                 parse_length, parse_length);
2005  if(conv_size < 0)
2006  {
2007    regfi_add_message(i->f, REGFI_MSG_WARN, "Error occurred while"
2008                      " converting classname to charset %s.  Error message: %s",
2009                      i->string_encoding, strerror(-conv_size));
2010    talloc_free(interpreted);
2011    ret_val->interpreted = NULL;
2012  }
2013  else
2014  {
2015    interpreted = talloc_realloc(NULL, interpreted, char, conv_size);
2016    ret_val->interpreted = interpreted;
2017    talloc_reference(ret_val, interpreted);
2018  }
2019
2020  return ret_val;
2021}
2022
2023
2024/******************************************************************************
2025 *****************************************************************************/
2026REGFI_DATA* regfi_iterator_fetch_data(REGFI_ITERATOR* i, 
2027                                      const REGFI_VK_REC* value)
2028{
2029  REGFI_DATA* ret_val = NULL;
2030  REGFI_BUFFER raw_data;
2031
2032  if(value->data_size != 0)
2033  {
2034    raw_data = regfi_load_data(i->f, value->data_off, value->data_size,
2035                              value->data_in_offset, true);
2036    if(raw_data.buf == NULL)
2037    {
2038      regfi_add_message(i->f, REGFI_MSG_WARN, "Could not parse data record"
2039                        " while parsing VK record at offset 0x%.8X.",
2040                        value->offset);
2041    }
2042    else
2043    {
2044      ret_val = regfi_buffer_to_data(raw_data);
2045
2046      if(ret_val == NULL)
2047      {
2048        regfi_add_message(i->f, REGFI_MSG_WARN, "Error occurred in converting"
2049                          " data buffer to data structure while interpreting "
2050                          "data for VK record at offset 0x%.8X.",
2051                          value->offset);
2052        talloc_free(raw_data.buf);
2053        return NULL;
2054      }
2055
2056      if(!regfi_interpret_data(i->f, i->string_encoding, value->type, ret_val))
2057      {
2058        regfi_add_message(i->f, REGFI_MSG_INFO, "Error occurred while"
2059                          " interpreting data for VK record at offset 0x%.8X.",
2060                          value->offset);
2061      }
2062    }
2063  }
2064 
2065  return ret_val;
2066}
2067
2068
2069/******************************************************************************
2070 *****************************************************************************/
2071void regfi_free_classname(REGFI_CLASSNAME* classname)
2072{
2073  talloc_free(classname);
2074}
2075
2076/******************************************************************************
2077 *****************************************************************************/
2078void regfi_free_data(REGFI_DATA* data)
2079{
2080  talloc_free(data);
2081}
2082
2083
2084/******************************************************************************
2085 *****************************************************************************/
2086REGFI_DATA* regfi_buffer_to_data(REGFI_BUFFER raw_data)
2087{
2088  REGFI_DATA* ret_val;
2089
2090  if(raw_data.buf == NULL)
2091    return NULL;
2092
2093  ret_val = talloc(NULL, REGFI_DATA);
2094  if(ret_val == NULL)
2095    return NULL;
2096 
2097  talloc_reference(ret_val, raw_data.buf);
2098  ret_val->raw = raw_data.buf;
2099  ret_val->size = raw_data.len;
2100  ret_val->interpreted_size = 0;
2101  ret_val->interpreted.qword = 0;
2102
2103  return ret_val;
2104}
2105
2106
2107/******************************************************************************
2108 *****************************************************************************/
2109bool regfi_interpret_data(REGFI_FILE* file, REGFI_ENCODING string_encoding,
2110                          uint32_t type, REGFI_DATA* data)
2111{
2112  uint8_t** tmp_array;
2113  uint8_t* tmp_str;
2114  int32_t tmp_size;
2115  uint32_t i, j, array_size;
2116
2117  if(data == NULL)
2118    return false;
2119
2120  switch (type)
2121  {
2122  case REG_SZ:
2123  case REG_EXPAND_SZ:
2124  /* REG_LINK is a symbolic link, stored as a unicode string. */
2125  case REG_LINK:
2126    tmp_str = talloc_array(NULL, uint8_t, data->size);
2127    if(tmp_str == NULL)
2128    {
2129      data->interpreted.string = NULL;
2130      data->interpreted_size = 0;
2131      return false;
2132    }
2133     
2134    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2135                                  regfi_encoding_int2str(string_encoding),
2136                                  data->raw, (char*)tmp_str, 
2137                                  data->size, data->size);
2138    if(tmp_size < 0)
2139    {
2140      regfi_add_message(file, REGFI_MSG_INFO, "Error occurred while"
2141                        " converting data of type %d to %s.  Error message: %s",
2142                        type, string_encoding, strerror(-tmp_size));
2143      talloc_free(tmp_str);
2144      data->interpreted.string = NULL;
2145      data->interpreted_size = 0;
2146      return false;
2147    }
2148
2149    tmp_str = talloc_realloc(NULL, tmp_str, uint8_t, tmp_size);
2150    data->interpreted.string = tmp_str;
2151    data->interpreted_size = tmp_size;
2152    talloc_reference(data, tmp_str);
2153    break;
2154
2155  case REG_DWORD:
2156    if(data->size < 4)
2157    {
2158      data->interpreted.dword = 0;
2159      data->interpreted_size = 0;
2160      return false;
2161    }
2162    data->interpreted.dword = IVAL(data->raw, 0);
2163    data->interpreted_size = 4;
2164    break;
2165
2166  case REG_DWORD_BE:
2167    if(data->size < 4)
2168    {
2169      data->interpreted.dword_be = 0;
2170      data->interpreted_size = 0;
2171      return false;
2172    }
2173    data->interpreted.dword_be = RIVAL(data->raw, 0);
2174    data->interpreted_size = 4;
2175    break;
2176
2177  case REG_QWORD:
2178    if(data->size < 8)
2179    {
2180      data->interpreted.qword = 0;
2181      data->interpreted_size = 0;
2182      return false;
2183    }
2184    data->interpreted.qword = 
2185      (uint64_t)IVAL(data->raw, 0) + (((uint64_t)IVAL(data->raw, 4))<<32);
2186    data->interpreted_size = 8;
2187    break;
2188   
2189  case REG_MULTI_SZ:
2190    tmp_str = talloc_array(NULL, uint8_t, data->size);
2191    if(tmp_str == NULL)
2192    {
2193      data->interpreted.multiple_string = NULL;
2194      data->interpreted_size = 0;
2195      return false;
2196    }
2197
2198    /* Attempt to convert entire string from UTF-16LE to output encoding,
2199     * then parse and quote fields individually.
2200     */
2201    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2202                                  regfi_encoding_int2str(string_encoding),
2203                                  data->raw, (char*)tmp_str,
2204                                  data->size, data->size);
2205    if(tmp_size < 0)
2206    {
2207      regfi_add_message(file, REGFI_MSG_INFO, "Error occurred while"
2208                        " converting data of type %d to %s.  Error message: %s",
2209                        type, string_encoding, strerror(-tmp_size));
2210      talloc_free(tmp_str);
2211      data->interpreted.multiple_string = NULL;
2212      data->interpreted_size = 0;
2213      return false;
2214    }
2215
2216    array_size = tmp_size+1;
2217    tmp_array = talloc_array(NULL, uint8_t*, array_size);
2218    if(tmp_array == NULL)
2219    {
2220      talloc_free(tmp_str);
2221      data->interpreted.string = NULL;
2222      data->interpreted_size = 0;
2223      return false;
2224    }
2225   
2226    tmp_array[0] = tmp_str;
2227    for(i=0,j=1; i < tmp_size && j < array_size-1; i++)
2228    {
2229      if(tmp_str[i] == '\0' && (i+1 < tmp_size))
2230        tmp_array[j++] = tmp_str+i+1;
2231    }
2232    tmp_array[j] = NULL;
2233    tmp_array = talloc_realloc(NULL, tmp_array, uint8_t*, j+1);
2234    data->interpreted.multiple_string = tmp_array;
2235    /* XXX: how meaningful is this?  should we store number of strings instead? */
2236    data->interpreted_size = tmp_size;
2237    talloc_reference(tmp_array, tmp_str);
2238    talloc_reference(data, tmp_array);
2239    break;
2240
2241  /* XXX: Dont know how to interpret these yet, just treat as binary */
2242  case REG_NONE:
2243    data->interpreted.none = data->raw;
2244    data->interpreted_size = data->size;
2245    break;
2246
2247  case REG_RESOURCE_LIST:
2248    data->interpreted.resource_list = data->raw;
2249    data->interpreted_size = data->size;
2250    break;
2251
2252  case REG_FULL_RESOURCE_DESCRIPTOR:
2253    data->interpreted.full_resource_descriptor = data->raw;
2254    data->interpreted_size = data->size;
2255    break;
2256
2257  case REG_RESOURCE_REQUIREMENTS_LIST:
2258    data->interpreted.resource_requirements_list = data->raw;
2259    data->interpreted_size = data->size;
2260    break;
2261
2262  case REG_BINARY:
2263    data->interpreted.binary = data->raw;
2264    data->interpreted_size = data->size;
2265    break;
2266
2267  default:
2268    data->interpreted.qword = 0;
2269    data->interpreted_size = 0;
2270    return false;
2271  }
2272
2273  data->type = type;
2274  return true;
2275}
2276
2277
2278/******************************************************************************
2279 * Convert from UTF-16LE to specified character set.
2280 * On error, returns a negative errno code.
2281 *****************************************************************************/
2282int32_t regfi_conv_charset(const char* input_charset, const char* output_charset,
2283                         uint8_t* input, char* output, 
2284                         uint32_t input_len, uint32_t output_max)
2285{
2286  iconv_t conv_desc;
2287  char* inbuf = (char*)input;
2288  char* outbuf = output;
2289  size_t in_len = (size_t)input_len;
2290  size_t out_len = (size_t)(output_max-1);
2291  int ret;
2292
2293  /* XXX: Consider creating a couple of conversion descriptors earlier,
2294   *      storing them on an iterator so they don't have to be recreated
2295   *      each time.
2296   */
2297
2298  /* Set up conversion descriptor. */
2299  conv_desc = iconv_open(output_charset, input_charset);
2300
2301  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
2302  if(ret == -1)
2303  {
2304    iconv_close(conv_desc);
2305    return -errno;
2306  }
2307  *outbuf = '\0';
2308
2309  iconv_close(conv_desc); 
2310  return output_max-out_len-1;
2311}
2312
2313
2314
2315/*******************************************************************
2316 * Computes the checksum of the registry file header.
2317 * buffer must be at least the size of a regf header (4096 bytes).
2318 *******************************************************************/
2319static uint32_t regfi_compute_header_checksum(uint8_t* buffer)
2320{
2321  uint32_t checksum, x;
2322  int i;
2323
2324  /* XOR of all bytes 0x0000 - 0x01FB */
2325
2326  checksum = x = 0;
2327 
2328  for ( i=0; i<0x01FB; i+=4 ) {
2329    x = IVAL(buffer, i );
2330    checksum ^= x;
2331  }
2332 
2333  return checksum;
2334}
2335
2336
2337/*******************************************************************
2338 * XXX: Add way to return more detailed error information.
2339 *******************************************************************/
2340REGFI_FILE* regfi_parse_regf(REGFI_RAW_FILE* file_cb, bool strict)
2341{
2342  uint8_t file_header[REGFI_REGF_SIZE];
2343  uint32_t length;
2344  REGFI_FILE* ret_val;
2345
2346  ret_val = talloc(NULL, REGFI_FILE);
2347  if(ret_val == NULL)
2348    return NULL;
2349
2350  ret_val->sk_cache = NULL;
2351  ret_val->last_message = NULL;
2352  ret_val->hbins = NULL;
2353
2354  length = REGFI_REGF_SIZE;
2355  if((regfi_read(file_cb, file_header, &length)) != 0 
2356     || length != REGFI_REGF_SIZE)
2357    goto fail;
2358 
2359  ret_val->checksum = IVAL(file_header, 0x1FC);
2360  ret_val->computed_checksum = regfi_compute_header_checksum(file_header);
2361  if (strict && (ret_val->checksum != ret_val->computed_checksum))
2362    goto fail;
2363
2364  memcpy(ret_val->magic, file_header, REGFI_REGF_MAGIC_SIZE);
2365  if(memcmp(ret_val->magic, "regf", REGFI_REGF_MAGIC_SIZE) != 0)
2366  {
2367    if(strict)
2368      goto fail;
2369    regfi_add_message(ret_val, REGFI_MSG_WARN, "Magic number mismatch "
2370                      "(%.2X %.2X %.2X %.2X) while parsing hive header",
2371                      ret_val->magic[0], ret_val->magic[1], 
2372                      ret_val->magic[2], ret_val->magic[3]);
2373  }
2374
2375  ret_val->sequence1 = IVAL(file_header, 0x4);
2376  ret_val->sequence2 = IVAL(file_header, 0x8);
2377  ret_val->mtime.low = IVAL(file_header, 0xC);
2378  ret_val->mtime.high = IVAL(file_header, 0x10);
2379  ret_val->major_version = IVAL(file_header, 0x14);
2380  ret_val->minor_version = IVAL(file_header, 0x18);
2381  ret_val->type = IVAL(file_header, 0x1C);
2382  ret_val->format = IVAL(file_header, 0x20);
2383  ret_val->root_cell = IVAL(file_header, 0x24);
2384  ret_val->last_block = IVAL(file_header, 0x28);
2385
2386  ret_val->cluster = IVAL(file_header, 0x2C);
2387
2388  memcpy(ret_val->file_name, file_header+0x30,  REGFI_REGF_NAME_SIZE);
2389
2390  /* XXX: Should we add a warning if these uuid parsers fail?  Can they? */
2391  ret_val->rm_id = winsec_parse_uuid(ret_val, file_header+0x70, 16);
2392  ret_val->log_id = winsec_parse_uuid(ret_val, file_header+0x80, 16);
2393  ret_val->flags = IVAL(file_header, 0x90);
2394  ret_val->tm_id = winsec_parse_uuid(ret_val, file_header+0x94, 16);
2395  ret_val->guid_signature = IVAL(file_header, 0xa4);
2396
2397  memcpy(ret_val->reserved1, file_header+0xa8, REGFI_REGF_RESERVED1_SIZE);
2398  memcpy(ret_val->reserved2, file_header+0x200, REGFI_REGF_RESERVED2_SIZE);
2399
2400  ret_val->thaw_tm_id = winsec_parse_uuid(ret_val, file_header+0xFC8, 16);
2401  ret_val->thaw_rm_id = winsec_parse_uuid(ret_val, file_header+0xFD8, 16);
2402  ret_val->thaw_log_id = winsec_parse_uuid(ret_val, file_header+0xFE8, 16);
2403  ret_val->boot_type = IVAL(file_header, 0xFF8);
2404  ret_val->boot_recover = IVAL(file_header, 0xFFC);
2405
2406  return ret_val;
2407
2408 fail:
2409  talloc_free(ret_val);
2410  return NULL;
2411}
2412
2413
2414
2415/******************************************************************************
2416 * Given real file offset, read and parse the hbin at that location
2417 * along with it's associated cells.
2418 ******************************************************************************/
2419REGFI_HBIN* regfi_parse_hbin(REGFI_FILE* file, uint32_t offset, bool strict)
2420{
2421  REGFI_HBIN *hbin;
2422  uint8_t hbin_header[REGFI_HBIN_HEADER_SIZE];
2423  uint32_t length;
2424 
2425  if(offset >= file->file_length)
2426    goto fail;
2427 
2428  if(!regfi_lock(file, file->cb_lock, "regfi_parse_hbin"))
2429    goto fail;
2430
2431  if(regfi_seek(file->cb, offset, SEEK_SET) == -1)
2432  {
2433    regfi_add_message(file, REGFI_MSG_ERROR, "Seek failed"
2434                      " while parsing hbin at offset 0x%.8X.", offset);
2435    goto fail_locked;
2436  }
2437
2438  length = REGFI_HBIN_HEADER_SIZE;
2439  if((regfi_read(file->cb, hbin_header, &length) != 0) 
2440     || length != REGFI_HBIN_HEADER_SIZE)
2441    goto fail_locked;
2442
2443  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_hbin"))
2444    goto fail;
2445
2446  hbin = talloc(NULL, REGFI_HBIN);
2447  if(hbin == NULL)
2448    goto fail;
2449  hbin->file_off = offset;
2450
2451  memcpy(hbin->magic, hbin_header, 4);
2452  if(strict && (memcmp(hbin->magic, "hbin", 4) != 0))
2453  {
2454    regfi_add_message(file, REGFI_MSG_INFO, "Magic number mismatch "
2455                      "(%.2X %.2X %.2X %.2X) while parsing hbin at offset"
2456                      " 0x%.8X.", hbin->magic[0], hbin->magic[1], 
2457                      hbin->magic[2], hbin->magic[3], offset);
2458    goto fail;
2459  }
2460
2461  hbin->first_hbin_off = IVAL(hbin_header, 0x4);
2462  hbin->block_size = IVAL(hbin_header, 0x8);
2463  /* this should be the same thing as hbin->block_size but just in case */
2464  hbin->next_block = IVAL(hbin_header, 0x1C);
2465
2466
2467  /* Ensure the block size is a multiple of 0x1000 and doesn't run off
2468   * the end of the file.
2469   */
2470  /* XXX: This may need to be relaxed for dealing with
2471   *      partial or corrupt files.
2472   */
2473  if((offset + hbin->block_size > file->file_length)
2474     || (hbin->block_size & 0xFFFFF000) != hbin->block_size)
2475  {
2476    regfi_add_message(file, REGFI_MSG_ERROR, "The hbin offset is not aligned"
2477                      " or runs off the end of the file"
2478                      " while parsing hbin at offset 0x%.8X.", offset);
2479    goto fail;
2480  }
2481
2482  return hbin;
2483
2484 fail_locked:
2485  regfi_unlock(file, file->cb_lock, "regfi_parse_hbin");
2486 fail:
2487  talloc_free(hbin);
2488  return NULL;
2489}
2490
2491
2492/*******************************************************************
2493 *******************************************************************/
2494REGFI_NK_REC* regfi_parse_nk(REGFI_FILE* file, uint32_t offset, 
2495                             uint32_t max_size, bool strict)
2496{
2497  uint8_t nk_header[REGFI_NK_MIN_LENGTH];
2498  REGFI_NK_REC* ret_val;
2499  uint32_t length,cell_length;
2500  bool unalloc = false;
2501
2502  ret_val = talloc(NULL, REGFI_NK_REC);
2503  if(ret_val == NULL)
2504  {
2505    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to allocate memory while"
2506                      " parsing NK record at offset 0x%.8X.", offset);
2507    goto fail;
2508  }
2509
2510  if(!regfi_lock(file, file->cb_lock, "regfi_parse_nk"))
2511    goto fail;
2512
2513  if(!regfi_parse_cell(file->cb, offset, nk_header, REGFI_NK_MIN_LENGTH,
2514                       &cell_length, &unalloc))
2515  {
2516    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2517                      " while parsing NK record at offset 0x%.8X.", offset);
2518    goto fail_locked;
2519  }
2520
2521  if((nk_header[0x0] != 'n') || (nk_header[0x1] != 'k'))
2522  {
2523    regfi_add_message(file, REGFI_MSG_WARN, "Magic number mismatch in parsing"
2524                      " NK record at offset 0x%.8X.", offset);
2525    goto fail_locked;
2526  }
2527
2528  ret_val->values = NULL;
2529  ret_val->subkeys = NULL;
2530  ret_val->offset = offset;
2531  ret_val->cell_size = cell_length;
2532
2533  if(ret_val->cell_size > max_size)
2534    ret_val->cell_size = max_size & 0xFFFFFFF8;
2535  if((ret_val->cell_size < REGFI_NK_MIN_LENGTH) 
2536     || (strict && (ret_val->cell_size & 0x00000007) != 0))
2537  {
2538    regfi_add_message(file, REGFI_MSG_WARN, "A length check failed while"
2539                      " parsing NK record at offset 0x%.8X.", offset);
2540    goto fail_locked;
2541  }
2542
2543  ret_val->magic[0] = nk_header[0x0];
2544  ret_val->magic[1] = nk_header[0x1];
2545  ret_val->flags = SVAL(nk_header, 0x2);
2546 
2547  if((ret_val->flags & ~REGFI_NK_KNOWN_FLAGS) != 0)
2548  {
2549    regfi_add_message(file, REGFI_MSG_WARN, "Unknown key flags (0x%.4X) while"
2550                      " parsing NK record at offset 0x%.8X.", 
2551                      (ret_val->flags & ~REGFI_NK_KNOWN_FLAGS), offset);
2552  }
2553
2554  ret_val->mtime.low = IVAL(nk_header, 0x4);
2555  ret_val->mtime.high = IVAL(nk_header, 0x8);
2556  /* If the key is unallocated and the MTIME is earlier than Jan 1, 1990
2557   * or later than Jan 1, 2290, we consider this a bad key.  This helps
2558   * weed out some false positives during deleted data recovery.
2559   */
2560  if(unalloc
2561     && (ret_val->mtime.high < REGFI_MTIME_MIN_HIGH
2562         || ret_val->mtime.high > REGFI_MTIME_MAX_HIGH))
2563  { goto fail_locked; }
2564
2565  ret_val->unknown1 = IVAL(nk_header, 0xC);
2566  ret_val->parent_off = IVAL(nk_header, 0x10);
2567  ret_val->num_subkeys = IVAL(nk_header, 0x14);
2568  ret_val->unknown2 = IVAL(nk_header, 0x18);
2569  ret_val->subkeys_off = IVAL(nk_header, 0x1C);
2570  ret_val->unknown3 = IVAL(nk_header, 0x20);
2571  ret_val->num_values = IVAL(nk_header, 0x24);
2572  ret_val->values_off = IVAL(nk_header, 0x28);
2573  ret_val->sk_off = IVAL(nk_header, 0x2C);
2574  ret_val->classname_off = IVAL(nk_header, 0x30);
2575
2576  ret_val->max_bytes_subkeyname = IVAL(nk_header, 0x34);
2577  ret_val->max_bytes_subkeyclassname = IVAL(nk_header, 0x38);
2578  ret_val->max_bytes_valuename = IVAL(nk_header, 0x3C);
2579  ret_val->max_bytes_value = IVAL(nk_header, 0x40);
2580  ret_val->unk_index = IVAL(nk_header, 0x44);
2581
2582  ret_val->name_length = SVAL(nk_header, 0x48);
2583  ret_val->classname_length = SVAL(nk_header, 0x4A);
2584  ret_val->keyname = NULL;
2585
2586  if(ret_val->name_length + REGFI_NK_MIN_LENGTH > ret_val->cell_size)
2587  {
2588    if(strict)
2589    {
2590      regfi_add_message(file, REGFI_MSG_ERROR, "Contents too large for cell"
2591                        " while parsing NK record at offset 0x%.8X.", offset);
2592      goto fail_locked;
2593    }
2594    else
2595      ret_val->name_length = ret_val->cell_size - REGFI_NK_MIN_LENGTH;
2596  }
2597  else if (unalloc)
2598  { /* Truncate cell_size if it's much larger than the apparent total record length. */
2599    /* Round up to the next multiple of 8 */
2600    length = (ret_val->name_length + REGFI_NK_MIN_LENGTH) & 0xFFFFFFF8;
2601    if(length < ret_val->name_length + REGFI_NK_MIN_LENGTH)
2602      length+=8;
2603
2604    /* If cell_size is still greater, truncate. */
2605    if(length < ret_val->cell_size)
2606      ret_val->cell_size = length;
2607  }
2608
2609  ret_val->keyname_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2610  if(ret_val->keyname_raw == NULL)
2611    goto fail_locked;
2612
2613  /* Don't need to seek, should be at the right offset */
2614  length = ret_val->name_length;
2615  if((regfi_read(file->cb, (uint8_t*)ret_val->keyname_raw, &length) != 0)
2616     || length != ret_val->name_length)
2617  {
2618    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to read key name"
2619                      " while parsing NK record at offset 0x%.8X.", offset);
2620    goto fail_locked;
2621  }
2622
2623  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_nk"))
2624    goto fail;
2625
2626  return ret_val;
2627
2628 fail_locked:
2629  regfi_unlock(file, file->cb_lock, "regfi_parse_nk");
2630 fail:
2631  talloc_free(ret_val);
2632  return NULL;
2633}
2634
2635
2636uint8_t* regfi_parse_classname(REGFI_FILE* file, uint32_t offset, 
2637                             uint16_t* name_length, uint32_t max_size, bool strict)
2638{
2639  uint8_t* ret_val = NULL;
2640  uint32_t length;
2641  uint32_t cell_length;
2642  bool unalloc = false;
2643
2644  if(*name_length <= 0 || offset == REGFI_OFFSET_NONE 
2645     || (offset & 0x00000007) != 0)
2646  { goto fail; }
2647
2648  if(!regfi_lock(file, file->cb_lock, "regfi_parse_classname"))
2649    goto fail;
2650
2651  if(!regfi_parse_cell(file->cb, offset, NULL, 0, &cell_length, &unalloc))
2652  {
2653    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2654                      " while parsing class name at offset 0x%.8X.", offset);
2655    goto fail_locked;
2656  }
2657 
2658  if((cell_length & 0x0000007) != 0)
2659  {
2660    regfi_add_message(file, REGFI_MSG_ERROR, "Cell length not a multiple of 8"
2661                      " while parsing class name at offset 0x%.8X.", offset);
2662    goto fail_locked;
2663  }
2664 
2665  if(cell_length > max_size)
2666  {
2667    regfi_add_message(file, REGFI_MSG_WARN, "Cell stretches past hbin "
2668                      "boundary while parsing class name at offset 0x%.8X.",
2669                      offset);
2670    if(strict)
2671      goto fail_locked;
2672    cell_length = max_size;
2673  }
2674 
2675  if((cell_length - 4) < *name_length)
2676  {
2677    regfi_add_message(file, REGFI_MSG_WARN, "Class name is larger than"
2678                      " cell_length while parsing class name at offset"
2679                      " 0x%.8X.", offset);
2680    if(strict)
2681      goto fail_locked;
2682    *name_length = cell_length - 4;
2683  }
2684 
2685  ret_val = talloc_array(NULL, uint8_t, *name_length);
2686  if(ret_val != NULL)
2687  {
2688    length = *name_length;
2689    if((regfi_read(file->cb, ret_val, &length) != 0)
2690       || length != *name_length)
2691    {
2692      regfi_add_message(file, REGFI_MSG_ERROR, "Could not read class name"
2693                        " while parsing class name at offset 0x%.8X.", offset);
2694      goto fail_locked;
2695    }
2696  }
2697
2698  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_classname"))
2699    goto fail;
2700
2701  return ret_val;
2702
2703 fail_locked:
2704  regfi_unlock(file, file->cb_lock, "regfi_parse_classname");
2705 fail:
2706  talloc_free(ret_val);
2707  return NULL;
2708}
2709
2710
2711/******************************************************************************
2712*******************************************************************************/
2713REGFI_VK_REC* regfi_parse_vk(REGFI_FILE* file, uint32_t offset, 
2714                             uint32_t max_size, bool strict)
2715{
2716  REGFI_VK_REC* ret_val;
2717  uint8_t vk_header[REGFI_VK_MIN_LENGTH];
2718  uint32_t raw_data_size, length, cell_length;
2719  bool unalloc = false;
2720
2721  ret_val = talloc(NULL, REGFI_VK_REC);
2722  if(ret_val == NULL)
2723    goto fail;
2724
2725  if(!regfi_lock(file, file->cb_lock, "regfi_parse_nk"))
2726    goto fail;
2727
2728  if(!regfi_parse_cell(file->cb, offset, vk_header, REGFI_VK_MIN_LENGTH,
2729                       &cell_length, &unalloc))
2730  {
2731    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2732                      " while parsing VK record at offset 0x%.8X.", offset);
2733    goto fail_locked;
2734  }
2735
2736  ret_val->offset = offset;
2737  ret_val->cell_size = cell_length;
2738  ret_val->valuename = NULL;
2739  ret_val->valuename_raw = NULL;
2740 
2741  if(ret_val->cell_size > max_size)
2742    ret_val->cell_size = max_size & 0xFFFFFFF8;
2743  if((ret_val->cell_size < REGFI_VK_MIN_LENGTH) 
2744     || (ret_val->cell_size & 0x00000007) != 0)
2745  {
2746    regfi_add_message(file, REGFI_MSG_WARN, "Invalid cell size encountered"
2747                      " while parsing VK record at offset 0x%.8X.", offset);
2748    goto fail_locked;
2749  }
2750
2751  ret_val->magic[0] = vk_header[0x0];
2752  ret_val->magic[1] = vk_header[0x1];
2753  if((ret_val->magic[0] != 'v') || (ret_val->magic[1] != 'k'))
2754  {
2755    /* XXX: This does not account for deleted keys under Win2K which
2756     *      often have this (and the name length) overwritten with
2757     *      0xFFFF.
2758     */
2759    regfi_add_message(file, REGFI_MSG_WARN, "Magic number mismatch"
2760                      " while parsing VK record at offset 0x%.8X.", offset);
2761    goto fail_locked;
2762  }
2763
2764  ret_val->name_length = SVAL(vk_header, 0x2);
2765  raw_data_size = IVAL(vk_header, 0x4);
2766  ret_val->data_size = raw_data_size & ~REGFI_VK_DATA_IN_OFFSET;
2767  /* The data is typically stored in the offset if the size <= 4,
2768   * in which case this flag is set.
2769   */
2770  ret_val->data_in_offset = (bool)(raw_data_size & REGFI_VK_DATA_IN_OFFSET);
2771  ret_val->data_off = IVAL(vk_header, 0x8);
2772  ret_val->type = IVAL(vk_header, 0xC);
2773  ret_val->flags = SVAL(vk_header, 0x10);
2774  ret_val->unknown1 = SVAL(vk_header, 0x12);
2775
2776  if(ret_val->name_length > 0)
2777  {
2778    if(ret_val->name_length + REGFI_VK_MIN_LENGTH + 4 > ret_val->cell_size)
2779    {
2780      regfi_add_message(file, REGFI_MSG_WARN, "Name too long for remaining cell"
2781                        " space while parsing VK record at offset 0x%.8X.",
2782                        offset);
2783      if(strict)
2784        goto fail_locked;
2785      else
2786        ret_val->name_length = ret_val->cell_size - REGFI_VK_MIN_LENGTH - 4;
2787    }
2788
2789    /* Round up to the next multiple of 8 */
2790    cell_length = (ret_val->name_length + REGFI_VK_MIN_LENGTH + 4) & 0xFFFFFFF8;
2791    if(cell_length < ret_val->name_length + REGFI_VK_MIN_LENGTH + 4)
2792      cell_length+=8;
2793
2794    ret_val->valuename_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2795    if(ret_val->valuename_raw == NULL)
2796      goto fail_locked;
2797
2798    length = ret_val->name_length;
2799    if((regfi_read(file->cb, (uint8_t*)ret_val->valuename_raw, &length) != 0)
2800       || length != ret_val->name_length)
2801    {
2802      regfi_add_message(file, REGFI_MSG_ERROR, "Could not read value name"
2803                        " while parsing VK record at offset 0x%.8X.", offset);
2804      goto fail_locked;
2805    }
2806  }
2807  else
2808    cell_length = REGFI_VK_MIN_LENGTH + 4;
2809
2810  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_nk"))
2811    goto fail;
2812
2813  if(unalloc)
2814  {
2815    /* If cell_size is still greater, truncate. */
2816    if(cell_length < ret_val->cell_size)
2817      ret_val->cell_size = cell_length;
2818  }
2819
2820  return ret_val;
2821 
2822 fail_locked:
2823  regfi_unlock(file, file->cb_lock, "regfi_parse_vk");
2824 fail:
2825  talloc_free(ret_val);
2826  return NULL;
2827}
2828
2829
2830/******************************************************************************
2831 *
2832 ******************************************************************************/
2833REGFI_BUFFER regfi_load_data(REGFI_FILE* file, uint32_t voffset,
2834                             uint32_t length, bool data_in_offset,
2835                             bool strict)
2836{
2837  REGFI_BUFFER ret_val;
2838  uint32_t cell_length, offset;
2839  int32_t max_size;
2840  bool unalloc;
2841 
2842  /* Microsoft's documentation indicates that "available memory" is
2843   * the limit on value sizes for the more recent registry format version.
2844   * This is not only annoying, but it's probably also incorrect, since clearly
2845   * value data sizes are limited to 2^31 (high bit used as a flag) and even
2846   * with big data records, the apparent max size is:
2847   *   16344 * 2^16 = 1071104040 (~1GB).
2848   *
2849   * We choose to limit it to 1M which was the limit in older versions and
2850   * should rarely be exceeded unless the file is corrupt or malicious.
2851   * For more info, see:
2852   *   http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
2853   */
2854  /* XXX: add way to skip this check at user discression. */
2855  if(length > REGFI_VK_MAX_DATA_LENGTH)
2856  {
2857    regfi_add_message(file, REGFI_MSG_WARN, "Value data size %d larger than "
2858                      "%d, truncating...", length, REGFI_VK_MAX_DATA_LENGTH);
2859    length = REGFI_VK_MAX_DATA_LENGTH;
2860  }
2861
2862  if(data_in_offset)
2863    return regfi_parse_little_data(file, voffset, length, strict);
2864  else
2865  {
2866    offset = voffset + REGFI_REGF_SIZE;
2867    max_size = regfi_calc_maxsize(file, offset);
2868    if(max_size < 0)
2869    {
2870      regfi_add_message(file, REGFI_MSG_WARN, "Could not find HBIN for data"
2871                        " at offset 0x%.8X.", offset);
2872      goto fail;
2873    }
2874   
2875    if(!regfi_lock(file, file->cb_lock, "regfi_load_data"))
2876      goto fail;
2877
2878    if(!regfi_parse_cell(file->cb, offset, NULL, 0,
2879                         &cell_length, &unalloc))
2880    {
2881      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2882                        " parsing data record at offset 0x%.8X.", offset);
2883      goto fail_locked;
2884    }
2885
2886    if(!regfi_unlock(file, file->cb_lock, "regfi_load_data"))
2887      goto fail;
2888
2889    if((cell_length & 0x00000007) != 0)
2890    {
2891      regfi_add_message(file, REGFI_MSG_WARN, "Cell length not multiple of 8"
2892                        " while parsing data record at offset 0x%.8X.",
2893                        offset);
2894      goto fail;
2895    }
2896
2897    if(cell_length > max_size)
2898    {
2899      regfi_add_message(file, REGFI_MSG_WARN, "Cell extends past HBIN boundary"
2900                        " while parsing data record at offset 0x%.8X.",
2901                        offset);
2902      goto fail;
2903    }
2904
2905    if(cell_length - 4 < length)
2906    {
2907      /* XXX: All big data records thus far have been 16 bytes long. 
2908       *      Should we check for this precise size instead of just
2909       *      relying upon the above check?
2910       */
2911      if (file->major_version >= 1 && file->minor_version >= 5)
2912      {
2913        /* Attempt to parse a big data record */
2914        return regfi_load_big_data(file, offset, length, cell_length, 
2915                                   NULL, strict);
2916      }
2917      else
2918      {
2919        regfi_add_message(file, REGFI_MSG_WARN, "Data length (0x%.8X) larger than"
2920                          " remaining cell length (0x%.8X)"
2921                          " while parsing data record at offset 0x%.8X.", 
2922                          length, cell_length - 4, offset);
2923        if(strict)
2924          goto fail;
2925        else
2926          length = cell_length - 4;
2927      }
2928    }
2929
2930    ret_val = regfi_parse_data(file, offset, length, strict);
2931  }
2932
2933  return ret_val;
2934
2935 fail_locked:
2936  regfi_unlock(file, file->cb_lock, "regfi_load_data");
2937 fail:
2938  ret_val.buf = NULL;
2939  ret_val.len = 0;
2940  return ret_val;
2941}
2942
2943
2944/******************************************************************************
2945 * Parses the common case data records stored in a single cell.
2946 ******************************************************************************/
2947REGFI_BUFFER regfi_parse_data(REGFI_FILE* file, uint32_t offset,
2948                              uint32_t length, bool strict)
2949{
2950  REGFI_BUFFER ret_val;
2951  uint32_t read_length;
2952
2953  ret_val.buf = NULL;
2954  ret_val.len = 0;
2955 
2956  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
2957    goto fail;
2958  ret_val.len = length;
2959
2960  if(!regfi_lock(file, file->cb_lock, "regfi_parse_data"))
2961    goto fail;
2962
2963  if(regfi_seek(file->cb, offset+4, SEEK_SET) == -1)
2964  {
2965    regfi_add_message(file, REGFI_MSG_WARN, "Could not seek while "
2966                      "reading data at offset 0x%.8X.", offset);
2967    goto fail_locked;
2968  }
2969 
2970  read_length = length;
2971  if((regfi_read(file->cb, ret_val.buf, &read_length) != 0)
2972     || read_length != length)
2973  {
2974    regfi_add_message(file, REGFI_MSG_ERROR, "Could not read data block while"
2975                      " parsing data record at offset 0x%.8X.", offset);
2976    goto fail_locked;
2977  }
2978
2979  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_data"))
2980    goto fail;
2981
2982  return ret_val;
2983
2984 fail_locked:
2985  regfi_unlock(file, file->cb_lock, "regfi_parse_data");
2986 fail:
2987  talloc_free(ret_val.buf);
2988  ret_val.buf = NULL;
2989  ret_val.buf = 0;
2990  return ret_val;
2991}
2992
2993
2994
2995/******************************************************************************
2996 *
2997 ******************************************************************************/
2998REGFI_BUFFER regfi_parse_little_data(REGFI_FILE* file, uint32_t voffset,
2999                                     uint32_t length, bool strict)
3000{
3001  uint8_t i;
3002  REGFI_BUFFER ret_val;
3003
3004  ret_val.buf = NULL;
3005  ret_val.len = 0;
3006
3007  if(length > 4)
3008  {
3009    regfi_add_message(file, REGFI_MSG_ERROR, "Data in offset but length > 4"
3010                      " while parsing data record. (voffset=0x%.8X, length=%d)",
3011                      voffset, length);
3012    return ret_val;
3013  }
3014
3015  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
3016    return ret_val;
3017  ret_val.len = length;
3018 
3019  for(i = 0; i < length; i++)
3020    ret_val.buf[i] = (uint8_t)((voffset >> i*8) & 0xFF);
3021
3022  return ret_val;
3023}
3024
3025/******************************************************************************
3026*******************************************************************************/
3027REGFI_BUFFER regfi_parse_big_data_header(REGFI_FILE* file, uint32_t offset, 
3028                                         uint32_t max_size, bool strict)
3029{
3030  REGFI_BUFFER ret_val;
3031  uint32_t cell_length;
3032  bool unalloc;
3033
3034  /* XXX: do something with unalloc? */
3035  ret_val.buf = (uint8_t*)talloc_array(NULL, uint8_t, REGFI_BIG_DATA_MIN_LENGTH);
3036  if(ret_val.buf == NULL)
3037    goto fail;
3038
3039  if(REGFI_BIG_DATA_MIN_LENGTH > max_size)
3040  {
3041    regfi_add_message(file, REGFI_MSG_WARN, "Big data header exceeded max_size "
3042                      "while parsing big data header at offset 0x%.8X.",offset);
3043    goto fail;
3044  }
3045
3046  if(!regfi_lock(file, file->cb_lock, "regfi_parse_big_data_header"))
3047    goto fail;
3048
3049
3050  if(!regfi_parse_cell(file->cb, offset, ret_val.buf, REGFI_BIG_DATA_MIN_LENGTH,
3051                       &cell_length, &unalloc))
3052  {
3053    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
3054                      " parsing big data header at offset 0x%.8X.", offset);
3055    goto fail_locked;
3056  }
3057
3058  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_header"))
3059    goto fail;
3060
3061  if((ret_val.buf[0] != 'd') || (ret_val.buf[1] != 'b'))
3062  {
3063    regfi_add_message(file, REGFI_MSG_WARN, "Unknown magic number"
3064                      " (0x%.2X, 0x%.2X) encountered while parsing"
3065                      " big data header at offset 0x%.8X.", 
3066                      ret_val.buf[0], ret_val.buf[1], offset);
3067    goto fail;
3068  }
3069
3070  ret_val.len = REGFI_BIG_DATA_MIN_LENGTH;
3071  return ret_val;
3072
3073 fail_locked:
3074  regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_header");
3075 fail:
3076  talloc_free(ret_val.buf);
3077  ret_val.buf = NULL;
3078  ret_val.len = 0;
3079  return ret_val;
3080}
3081
3082
3083
3084/******************************************************************************
3085 *
3086 ******************************************************************************/
3087uint32_t* regfi_parse_big_data_indirect(REGFI_FILE* file, uint32_t offset,
3088                                      uint16_t num_chunks, bool strict)
3089{
3090  uint32_t* ret_val;
3091  uint32_t indirect_length;
3092  int32_t max_size;
3093  uint16_t i;
3094  bool unalloc;
3095
3096  /* XXX: do something with unalloc? */
3097
3098  max_size = regfi_calc_maxsize(file, offset);
3099  if((max_size < 0) || (num_chunks*sizeof(uint32_t) + 4 > max_size))
3100    return NULL;
3101
3102  ret_val = (uint32_t*)talloc_array(NULL, uint32_t, num_chunks);
3103  if(ret_val == NULL)
3104    goto fail;
3105
3106  if(!regfi_lock(file, file->cb_lock, "regfi_parse_big_data_indirect"))
3107    goto fail;
3108
3109  if(!regfi_parse_cell(file->cb, offset, (uint8_t*)ret_val,
3110                       num_chunks*sizeof(uint32_t),
3111                       &indirect_length, &unalloc))
3112  {
3113    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
3114                      " parsing big data indirect record at offset 0x%.8X.", 
3115                      offset);
3116    goto fail_locked;
3117  }
3118
3119  if(!regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_indirect"))
3120    goto fail;
3121
3122  /* Convert pointers to proper endianess, verify they are aligned. */
3123  for(i=0; i<num_chunks; i++)
3124  {
3125    ret_val[i] = IVAL(ret_val, i*sizeof(uint32_t));
3126    if((ret_val[i] & 0x00000007) != 0)
3127      goto fail;
3128  }
3129 
3130  return ret_val;
3131
3132 fail_locked:
3133  regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_indirect");
3134 fail:
3135  talloc_free(ret_val);
3136  return NULL;
3137}
3138
3139
3140/******************************************************************************
3141 * Arguments:
3142 *  file       --
3143 *  offsets    -- list of virtual offsets.
3144 *  num_chunks --
3145 *  strict     --
3146 *
3147 * Returns:
3148 *  A range_list with physical offsets and complete lengths
3149 *  (including cell headers) of associated cells. 
3150 *  No data in range_list elements.
3151 ******************************************************************************/
3152range_list* regfi_parse_big_data_cells(REGFI_FILE* file, uint32_t* offsets,
3153                                       uint16_t num_chunks, bool strict)
3154{
3155  uint32_t cell_length, chunk_offset;
3156  range_list* ret_val;
3157  uint16_t i;
3158  bool unalloc;
3159 
3160  /* XXX: do something with unalloc? */
3161  ret_val = range_list_new();
3162  if(ret_val == NULL)
3163    goto fail;
3164 
3165  for(i=0; i<num_chunks; i++)
3166  {
3167    if(!regfi_lock(file, file->cb_lock, "regfi_parse_big_data_cells"))
3168      goto fail;
3169
3170    chunk_offset = offsets[i]+REGFI_REGF_SIZE;
3171    if(!regfi_parse_cell(file->cb, chunk_offset, NULL, 0,
3172                         &cell_length, &unalloc))
3173    {
3174      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
3175                        " parsing big data chunk at offset 0x%.8X.", 
3176                        chunk_offset);
3177      goto fail_locked;
3178    }
3179
3180    if(!regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_cells"))
3181      goto fail;
3182
3183    if(!range_list_add(ret_val, chunk_offset, cell_length, NULL))
3184      goto fail;
3185  }
3186
3187  return ret_val;
3188
3189 fail_locked:
3190  regfi_unlock(file, file->cb_lock, "regfi_parse_big_data_cells");
3191 fail:
3192  if(ret_val != NULL)
3193    range_list_free(ret_val);
3194  return NULL;
3195}
3196
3197
3198/******************************************************************************
3199*******************************************************************************/
3200REGFI_BUFFER regfi_load_big_data(REGFI_FILE* file, 
3201                                 uint32_t offset, uint32_t data_length, 
3202                                 uint32_t cell_length, range_list* used_ranges,
3203                                 bool strict)
3204{
3205  REGFI_BUFFER ret_val;
3206  uint16_t num_chunks, i;
3207  uint32_t read_length, data_left, tmp_len, indirect_offset;
3208  uint32_t* indirect_ptrs = NULL;
3209  REGFI_BUFFER bd_header;
3210  range_list* bd_cells = NULL;
3211  const range_list_element* cell_info;
3212
3213  ret_val.buf = NULL;
3214
3215  /* XXX: Add better error/warning messages */
3216
3217  bd_header = regfi_parse_big_data_header(file, offset, cell_length, strict);
3218  if(bd_header.buf == NULL)
3219    goto fail;
3220
3221  /* Keep track of used space for use by reglookup-recover */
3222  if(used_ranges != NULL)
3223    if(!range_list_add(used_ranges, offset, cell_length, NULL))
3224      goto fail;
3225
3226  num_chunks = SVAL(bd_header.buf, 0x2);
3227  indirect_offset = IVAL(bd_header.buf, 0x4) + REGFI_REGF_SIZE;
3228  talloc_free(bd_header.buf);
3229
3230  indirect_ptrs = regfi_parse_big_data_indirect(file, indirect_offset,
3231                                                num_chunks, strict);
3232  if(indirect_ptrs == NULL)
3233    goto fail;
3234
3235  if(used_ranges != NULL)
3236    if(!range_list_add(used_ranges, indirect_offset, num_chunks*4+4, NULL))
3237      goto fail;
3238 
3239  if((ret_val.buf = talloc_array(NULL, uint8_t, data_length)) == NULL)
3240    goto fail;
3241  data_left = data_length;
3242
3243  bd_cells = regfi_parse_big_data_cells(file, indirect_ptrs, num_chunks, strict);
3244  if(bd_cells == NULL)
3245    goto fail;
3246
3247  talloc_free(indirect_ptrs);
3248  indirect_ptrs = NULL;
3249 
3250  for(i=0; (i<num_chunks) && (data_left>0); i++)
3251  {
3252    cell_info = range_list_get(bd_cells, i);
3253    if(cell_info == NULL)
3254      goto fail;
3255
3256    /* XXX: This should be "cell_info->length-4" to account for the 4 byte cell
3257     *      length.  However, it has been observed that some (all?) chunks
3258     *      have an additional 4 bytes of 0 at the end of their cells that
3259     *      isn't part of the data, so we're trimming that off too.
3260     *      Perhaps it's just an 8 byte alignment requirement...
3261     */
3262    if(cell_info->length - 8 >= data_left)
3263    {
3264      if(i+1 != num_chunks)
3265      {
3266        regfi_add_message(file, REGFI_MSG_WARN, "Left over chunks detected "
3267                          "while constructing big data at offset 0x%.8X "
3268                          "(chunk offset 0x%.8X).", offset, cell_info->offset);
3269      }
3270      read_length = data_left;
3271    }
3272    else
3273      read_length = cell_info->length - 8;
3274
3275
3276    if(read_length > regfi_calc_maxsize(file, cell_info->offset))
3277    {
3278      regfi_add_message(file, REGFI_MSG_WARN, "A chunk exceeded the maxsize "
3279                        "while constructing big data at offset 0x%.8X "
3280                        "(chunk offset 0x%.8X).", offset, cell_info->offset);
3281      goto fail;
3282    }
3283
3284    if(!regfi_lock(file, file->cb_lock, "regfi_load_big_data"))
3285      goto fail;
3286
3287    if(regfi_seek(file->cb, cell_info->offset+sizeof(uint32_t), SEEK_SET) == -1)
3288    {
3289      regfi_add_message(file, REGFI_MSG_WARN, "Could not seek to chunk while "
3290                        "constructing big data at offset 0x%.8X "
3291                        "(chunk offset 0x%.8X).", offset, cell_info->offset);
3292      goto fail_locked;
3293    }
3294
3295    tmp_len = read_length;
3296    if(regfi_read(file->cb, ret_val.buf+(data_length-data_left), 
3297                  &read_length) != 0 || (read_length != tmp_len))
3298    {
3299      regfi_add_message(file, REGFI_MSG_WARN, "Could not read data chunk while"
3300                        " constructing big data at offset 0x%.8X"
3301                        " (chunk offset 0x%.8X).", offset, cell_info->offset);
3302      goto fail_locked;
3303    }
3304
3305    if(!regfi_unlock(file, file->cb_lock, "regfi_load_big_data"))
3306      goto fail;
3307
3308    if(used_ranges != NULL)
3309      if(!range_list_add(used_ranges, cell_info->offset,cell_info->length,NULL))
3310        goto fail;
3311
3312    data_left -= read_length;
3313  }
3314  range_list_free(bd_cells);
3315
3316  ret_val.len = data_length-data_left;
3317  return ret_val;
3318
3319 fail_locked:
3320  regfi_unlock(file, file->cb_lock, "regfi_load_big_data");
3321 fail:
3322  talloc_free(ret_val.buf);
3323  talloc_free(indirect_ptrs);
3324  if(bd_cells != NULL)
3325    range_list_free(bd_cells);
3326  ret_val.buf = NULL;
3327  ret_val.len = 0;
3328  return ret_val;
3329}
3330
3331
3332range_list* regfi_parse_unalloc_cells(REGFI_FILE* file)
3333{
3334  range_list* ret_val;
3335  REGFI_HBIN* hbin;
3336  const range_list_element* hbins_elem;
3337  uint32_t i, num_hbins, curr_off, cell_len;
3338  bool is_unalloc;
3339
3340  ret_val = range_list_new();
3341  if(ret_val == NULL)
3342    return NULL;
3343
3344  if(!regfi_read_lock(file, file->hbins_lock, "regfi_parse_unalloc_cells"))
3345  {
3346    range_list_free(ret_val);
3347    return NULL;
3348  }
3349
3350  num_hbins = range_list_size(file->hbins);
3351  for(i=0; i<num_hbins; i++)
3352  {
3353    hbins_elem = range_list_get(file->hbins, i);
3354    if(hbins_elem == NULL)
3355      break;
3356    hbin = (REGFI_HBIN*)hbins_elem->data;
3357
3358    curr_off = REGFI_HBIN_HEADER_SIZE;
3359    while(curr_off < hbin->block_size)
3360    {
3361      if(!regfi_lock(file, file->cb_lock, "regfi_parse_unalloc_cells"))
3362        break;
3363
3364      if(!regfi_parse_cell(file->cb, hbin->file_off+curr_off, NULL, 0,
3365                           &cell_len, &is_unalloc))
3366      {
3367        regfi_unlock(file, file->cb_lock, "regfi_parse_unalloc_cells");
3368        break;
3369      }
3370
3371      if(!regfi_unlock(file, file->cb_lock, "regfi_parse_unalloc_cells"))
3372        break;
3373
3374      if((cell_len == 0) || ((cell_len & 0x00000007) != 0))
3375      {
3376        regfi_add_message(file, REGFI_MSG_ERROR, "Bad cell length encountered"
3377                          " while parsing unallocated cells at offset 0x%.8X.",
3378                          hbin->file_off+curr_off);
3379        break;
3380      }
3381
3382      /* for some reason the record_size of the last record in
3383         an hbin block can extend past the end of the block
3384         even though the record fits within the remaining
3385         space....aaarrrgggghhhhhh */ 
3386      if(curr_off + cell_len >= hbin->block_size)
3387        cell_len = hbin->block_size - curr_off;
3388     
3389      if(is_unalloc)
3390        range_list_add(ret_val, hbin->file_off+curr_off, 
3391                       cell_len, NULL);
3392     
3393      curr_off = curr_off+cell_len;
3394    }
3395  }
3396
3397  if(!regfi_rw_unlock(file, file->hbins_lock, "regfi_parse_unalloc_cells"))
3398  {
3399    range_list_free(ret_val);
3400    return NULL;
3401  }
3402
3403  return ret_val;
3404}
3405
3406
3407/* From lib/time.c */
3408
3409/****************************************************************************
3410 Put a 8 byte filetime from a time_t
3411 This takes real GMT as input and converts to kludge-GMT
3412****************************************************************************/
3413void regfi_unix2nt_time(REGFI_NTTIME *nt, time_t t)
3414{
3415  double d;
3416 
3417  if (t==0) 
3418  {
3419    nt->low = 0;
3420    nt->high = 0;
3421    return;
3422  }
3423 
3424  if (t == TIME_T_MAX) 
3425  {
3426    nt->low = 0xffffffff;
3427    nt->high = 0x7fffffff;
3428    return;
3429  }             
3430 
3431  if (t == -1) 
3432  {
3433    nt->low = 0xffffffff;
3434    nt->high = 0xffffffff;
3435    return;
3436  }             
3437 
3438  /* this converts GMT to kludge-GMT */
3439  /* XXX: This was removed due to difficult dependency requirements. 
3440   *      So far, times appear to be correct without this adjustment, but
3441   *      that may be proven wrong with adequate testing.
3442   */
3443  /* t -= TimeDiff(t) - get_serverzone(); */
3444 
3445  d = (double)(t);
3446  d += TIME_FIXUP_CONSTANT;
3447  d *= 1.0e7;
3448 
3449  nt->high = (uint32_t)(d * (1.0/(4.0*(double)(1<<30))));
3450  nt->low  = (uint32_t)(d - ((double)nt->high)*4.0*(double)(1<<30));
3451}
3452
3453
3454/****************************************************************************
3455 Interpret an 8 byte "filetime" structure to a time_t
3456 It's originally in "100ns units since jan 1st 1601"
3457
3458 An 8 byte value of 0xffffffffffffffff will be returned as (time_t)0.
3459
3460 It appears to be kludge-GMT (at least for file listings). This means
3461 its the GMT you get by taking a localtime and adding the
3462 serverzone. This is NOT the same as GMT in some cases. This routine
3463 converts this to real GMT.
3464****************************************************************************/
3465time_t regfi_nt2unix_time(const REGFI_NTTIME* nt)
3466{
3467  double d;
3468  time_t ret;
3469  /* The next two lines are a fix needed for the
3470     broken SCO compiler. JRA. */
3471  time_t l_time_min = TIME_T_MIN;
3472  time_t l_time_max = TIME_T_MAX;
3473 
3474  if (nt->high == 0 || (nt->high == 0xffffffff && nt->low == 0xffffffff))
3475    return(0);
3476 
3477  d = ((double)nt->high)*4.0*(double)(1<<30);
3478  d += (nt->low&0xFFF00000);
3479  d *= 1.0e-7;
3480 
3481  /* now adjust by 369 years to make the secs since 1970 */
3482  d -= TIME_FIXUP_CONSTANT;
3483 
3484  if (d <= l_time_min)
3485    return (l_time_min);
3486 
3487  if (d >= l_time_max)
3488    return (l_time_max);
3489 
3490  ret = (time_t)(d+0.5);
3491 
3492  /* this takes us from kludge-GMT to real GMT */
3493  /* XXX: This was removed due to difficult dependency requirements. 
3494   *      So far, times appear to be correct without this adjustment, but
3495   *      that may be proven wrong with adequate testing.
3496   */
3497  /*
3498    ret -= get_serverzone();
3499    ret += LocTimeDiff(ret);
3500  */
3501
3502  return(ret);
3503}
3504
3505/* End of stuff from lib/time.c */
Note: See TracBrowser for help on using the repository browser.