source: trunk/src/reglookup.c @ 77

Last change on this file since 77 was 77, checked in by tim, 17 years ago

Improved support for unknown registry types.

Fixed potential security issue.

  • Property svn:keywords set to Id
File size: 24.5 KB
Line 
1/*
2 * A utility to read a Windows NT/2K/XP/2K3 registry file, using
3 * Gerald Carter''s regfio interface.
4 *
5 * Copyright (C) 2005-2006 Timothy D. Morgan
6 * Copyright (C) 2002 Richard Sharpe, rsharpe@richardsharpe.com
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; version 2 of the License.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
20 *
21 * $Id: reglookup.c 77 2007-01-07 15:19:43Z tim $
22 */
23
24
25#include <stdlib.h>
26#include <stdio.h>
27#include <string.h>
28#include <strings.h>
29#include <time.h>
30#include <iconv.h>
31#include "../include/regfio.h"
32#include "../include/void_stack.h"
33
34/* Globals, influenced by command line parameters */
35bool print_verbose = false;
36bool print_security = false;
37bool print_header = true;
38bool path_filter_enabled = false;
39bool type_filter_enabled = false;
40char* path_filter = NULL;
41int type_filter;
42char* registry_file = NULL;
43
44/* Other globals */
45const char* key_special_chars = ",\"\\/";
46const char* subfield_special_chars = ",\"\\|";
47const char* common_special_chars = ",\"\\";
48
49iconv_t conv_desc;
50
51
52void bailOut(int code, char* message)
53{
54  fprintf(stderr, message);
55  exit(code);
56}
57
58
59/* Returns a newly malloc()ed string which contains original buffer,
60 * except for non-printable or special characters are quoted in hex
61 * with the syntax '\xQQ' where QQ is the hex ascii value of the quoted
62 * character.  A null terminator is added, since only ascii, not binary,
63 * is returned.
64 */
65static char* quote_buffer(const unsigned char* str, 
66                          unsigned int len, const char* special)
67{
68  unsigned int i, added_len;
69  unsigned int num_written = 0;
70
71  unsigned int buf_len = sizeof(char)*(len+1);
72  char* ret_val = malloc(buf_len);
73  char* tmp_buf;
74
75  if(ret_val == NULL)
76    return NULL;
77
78  for(i=0; i<len; i++)
79  {
80    if(buf_len <= (num_written+5))
81    {
82      /* Expand the buffer by the memory consumption rate seen so far
83       * times the amount of input left to process.  The expansion is bounded
84       * below by a minimum safety increase, and above by the maximum possible
85       * output string length.  This should minimize both the number of
86       * reallocs() and the amount of wasted memory.
87       */
88      added_len = (len-i)*num_written/(i+1);
89      if((buf_len+added_len) > (len*4+1))
90        buf_len = len*4+1;
91      else
92      {
93        if (added_len < 5)
94          buf_len += 5;
95        else
96          buf_len += added_len;
97      }
98
99      tmp_buf = realloc(ret_val, buf_len);
100      if(tmp_buf == NULL)
101      {
102        free(ret_val);
103        return NULL;
104      }
105      ret_val = tmp_buf;
106    }
107   
108    if(str[i] < 32 || str[i] > 126 || strchr(special, str[i]) != NULL)
109    {
110      num_written += snprintf(ret_val + num_written, buf_len - num_written,
111                              "\\x%.2X", str[i]);
112    }
113    else
114      ret_val[num_written++] = str[i];
115  }
116  ret_val[num_written] = '\0';
117
118  return ret_val;
119}
120
121
122/* Returns a newly malloc()ed string which contains original string,
123 * except for non-printable or special characters are quoted in hex
124 * with the syntax '\xQQ' where QQ is the hex ascii value of the quoted
125 * character.
126 */
127static char* quote_string(const char* str, const char* special)
128{
129  unsigned int len;
130
131  if(str == NULL)
132    return NULL;
133
134  len = strlen(str);
135  return quote_buffer((const unsigned char*)str, len, special);
136}
137
138
139/*
140 * Convert from UTF-16LE to ASCII.  Accepts a Unicode buffer, uni, and
141 * it's length, uni_max.  Writes ASCII to the buffer ascii, whose size
142 * is ascii_max.  Writes at most (ascii_max-1) bytes to ascii, and null
143 * terminates the string.  Returns the length of the string stored in
144 * ascii.  On error, returns a negative errno code.
145 */
146static int uni_to_ascii(unsigned char* uni, char* ascii, 
147                        unsigned int uni_max, unsigned int ascii_max)
148{
149  char* inbuf = (char*)uni;
150  char* outbuf = ascii;
151  size_t in_len = (size_t)uni_max;
152  size_t out_len = (size_t)(ascii_max-1);
153  int ret;
154
155  /* Set up conversion descriptor. */
156  conv_desc = iconv_open("US-ASCII", "UTF-16LE");
157
158  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
159  if(ret == -1)
160  {
161    iconv_close(conv_desc);
162    return -errno;
163  }
164  *outbuf = '\0';
165
166  iconv_close(conv_desc); 
167  return strlen(ascii);
168}
169
170
171/*
172 * Convert a data value to a string for display.  Returns NULL on error,
173 * and the string to display if there is no error, or a non-fatal
174 * error.  On any error (fatal or non-fatal) occurs, (*error_msg) will
175 * be set to a newly allocated string, containing an error message.  If
176 * a memory allocation failure occurs while generating the error
177 * message, both the return value and (*error_msg) will be NULL.  It
178 * is the responsibility of the caller to free both a non-NULL return
179 * value, and a non-NULL (*error_msg).
180 */
181static char* data_to_ascii(unsigned char *datap, uint32 len, uint32 type, 
182                           char** error_msg)
183{
184  char* asciip;
185  char* ascii;
186  unsigned char* cur_str;
187  char* cur_ascii;
188  char* cur_quoted;
189  char* tmp_err;
190  const char* str_type;
191  uint32 i;
192  uint32 cur_str_len;
193  uint32 ascii_max, cur_str_max;
194  uint32 str_rem, cur_str_rem, alen;
195  int ret_err;
196  unsigned short num_nulls;
197
198  *error_msg = NULL;
199
200  switch (type) 
201  {
202  case REG_SZ:
203  case REG_EXPAND_SZ:
204    /* REG_LINK is a symbolic link, stored as a unicode string. */
205  case REG_LINK:
206    ascii_max = sizeof(char)*(len+1);
207    ascii = malloc(ascii_max);
208    if(ascii == NULL)
209      return NULL;
210   
211    /* Sometimes values have binary stored in them.  If the unicode
212     * conversion fails, just quote it raw.
213     */
214    ret_err = uni_to_ascii(datap, ascii, len, ascii_max);
215    if(ret_err < 0)
216    {
217      tmp_err = strerror(-ret_err);
218      str_type = regfio_type_val2str(type);
219      *error_msg = (char*)malloc(65+strlen(str_type)+strlen(tmp_err)+1);
220      if(*error_msg == NULL)
221      {
222        free(ascii);
223        return NULL;
224      }
225      sprintf(*error_msg, "Unicode conversion failed on %s field; "
226               "printing as binary.  Error: %s", str_type, tmp_err);
227     
228      cur_quoted = quote_buffer(datap, len, common_special_chars);
229    }
230    else
231      cur_quoted = quote_string(ascii, common_special_chars);
232    free(ascii);
233    if(cur_quoted == NULL)
234    {
235      *error_msg = (char*)malloc(27+1);
236      if(*error_msg != NULL)
237        strcpy(*error_msg, "Buffer could not be quoted.");
238    }
239    return cur_quoted;
240    break;
241
242  case REG_DWORD:
243    ascii_max = sizeof(char)*(8+2+1);
244    ascii = malloc(ascii_max);
245    if(ascii == NULL)
246      return NULL;
247
248    snprintf(ascii, ascii_max, "0x%.2X%.2X%.2X%.2X", 
249             datap[0], datap[1], datap[2], datap[3]);
250    return ascii;
251    break;
252
253  case REG_DWORD_BE:
254    ascii_max = sizeof(char)*(8+2+1);
255    ascii = malloc(ascii_max);
256    if(ascii == NULL)
257      return NULL;
258
259    snprintf(ascii, ascii_max, "0x%.2X%.2X%.2X%.2X", 
260             datap[3], datap[2], datap[1], datap[0]);
261    return ascii;
262    break;
263
264  case REG_QWORD:
265    ascii_max = sizeof(char)*(16+2+1);
266    ascii = malloc(ascii_max);
267    if(ascii == NULL)
268      return NULL;
269
270    snprintf(ascii, ascii_max, "0x%.2X%.2X%.2X%.2X%.2X%.2X%.2X%.2X",
271             datap[7], datap[6], datap[5], datap[4],
272             datap[3], datap[2], datap[1], datap[0]);
273    return ascii;
274    break;
275   
276
277  /* XXX: this MULTI_SZ parser is pretty inefficient.  Should be
278   *      redone with fewer malloc calls and better string concatenation.
279   */
280  case REG_MULTI_SZ:
281    ascii_max = sizeof(char)*(len*4+1);
282    cur_str_max = sizeof(char)*(len+1);
283    cur_str = malloc(cur_str_max);
284    cur_ascii = malloc(cur_str_max);
285    ascii = malloc(ascii_max);
286    if(ascii == NULL || cur_str == NULL || cur_ascii == NULL)
287      return NULL;
288
289    /* Reads until it reaches 4 consecutive NULLs,
290     * which is two nulls in unicode, or until it reaches len, or until we
291     * run out of buffer.  The latter should never happen, but we shouldn't
292     * trust our file to have the right lengths/delimiters.
293     */
294    asciip = ascii;
295    num_nulls = 0;
296    str_rem = ascii_max;
297    cur_str_rem = cur_str_max;
298    cur_str_len = 0;
299
300    for(i=0; (i < len) && str_rem > 0; i++)
301    {
302      *(cur_str+cur_str_len) = *(datap+i);
303      if(*(cur_str+cur_str_len) == 0)
304        num_nulls++;
305      else
306        num_nulls = 0;
307      cur_str_len++;
308
309      if(num_nulls == 2)
310      {
311        ret_err = uni_to_ascii(cur_str, cur_ascii, cur_str_len-1, cur_str_max);
312        if(ret_err < 0)
313        {
314          /* XXX: should every sub-field error be enumerated? */
315          if(*error_msg == NULL)
316          {
317            tmp_err = strerror(-ret_err);
318            *error_msg = (char*)malloc(90+strlen(tmp_err)+1);
319            if(*error_msg == NULL)
320            {
321              free(cur_str);
322              free(cur_ascii);
323              free(ascii);
324              return NULL;
325            }
326            sprintf(*error_msg, "Unicode conversion failed on at least one "
327                    "MULTI_SZ sub-field; printing as binary.  Error: %s",
328                    tmp_err);
329          }
330          cur_quoted = quote_buffer(cur_str, cur_str_len-1, 
331                                    subfield_special_chars);
332        }
333        else
334          cur_quoted = quote_string(cur_ascii, subfield_special_chars);
335
336        alen = snprintf(asciip, str_rem, "%s", cur_quoted);
337        asciip += alen;
338        str_rem -= alen;
339        free(cur_quoted);
340
341        if(*(datap+i+1) == 0 && *(datap+i+2) == 0)
342          break;
343        else
344        {
345          if(str_rem > 0)
346          {
347            asciip[0] = '|';
348            asciip[1] = '\0';
349            asciip++;
350            str_rem--;
351          }
352          memset(cur_str, 0, cur_str_max);
353          cur_str_len = 0;
354          num_nulls = 0;
355          /* To eliminate leading nulls in subsequent strings. */
356          i++;
357        }
358      }
359    }
360    *asciip = 0;
361    free(cur_str);
362    free(cur_ascii);
363    return ascii;
364    break;
365
366  /* XXX: Dont know what to do with these yet, just print as binary... */
367  default:
368    fprintf(stderr, "WARNING: Unrecognized registry data type (0x%.8X); quoting as binary.\n", type);
369   
370  case REG_NONE:
371  case REG_RESOURCE_LIST:
372  case REG_FULL_RESOURCE_DESCRIPTOR:
373  case REG_RESOURCE_REQUIREMENTS_LIST:
374
375  case REG_BINARY:
376    return quote_buffer(datap, len, common_special_chars);
377    break;
378  }
379
380  return NULL;
381}
382
383
384void_stack* path2Stack(const char* s)
385{
386  void_stack* ret_val;
387  void_stack* rev_ret = void_stack_new(1024);
388  const char* cur = s;
389  char* next = NULL;
390  char* copy;
391
392  if (rev_ret == NULL)
393    return NULL;
394  if (s == NULL)
395    return rev_ret;
396 
397  while((next = strchr(cur, '/')) != NULL)
398  {
399    if ((next-cur) > 0)
400    {
401      copy = (char*)malloc((next-cur+1)*sizeof(char));
402      if(copy == NULL)
403        bailOut(2, "ERROR: Memory allocation problem.\n");
404         
405      memcpy(copy, cur, next-cur);
406      copy[next-cur] = '\0';
407      void_stack_push(rev_ret, copy);
408    }
409    cur = next+1;
410  }
411  if(strlen(cur) > 0)
412  {
413    copy = strdup(cur);
414    void_stack_push(rev_ret, copy);
415  }
416
417  ret_val = void_stack_copy_reverse(rev_ret);
418  void_stack_destroy(rev_ret);
419
420  return ret_val;
421}
422
423/* Returns a quoted path from an nk_stack */
424char* stack2Path(void_stack* nk_stack)
425{
426  const REGF_NK_REC* cur;
427  uint32 buf_left = 127;
428  uint32 buf_len = buf_left+1;
429  uint32 name_len = 0;
430  uint32 grow_amt;
431  char* buf; 
432  char* new_buf;
433  char* name;
434  void_stack_iterator* iter;
435 
436  buf = (char*)malloc((buf_len)*sizeof(char));
437  if (buf == NULL)
438    return NULL;
439  buf[0] = '\0';
440
441  iter = void_stack_iterator_new(nk_stack);
442  if (iter == NULL)
443  {
444    free(buf);
445    return NULL;
446  }
447
448  /* skip root element */
449  cur = void_stack_iterator_next(iter);
450
451  while((cur = void_stack_iterator_next(iter)) != NULL)
452  {
453    buf[buf_len-buf_left-1] = '/';
454    buf_left -= 1;
455    name = quote_string(cur->keyname, key_special_chars);
456    name_len = strlen(name);
457    if(name_len+1 > buf_left)
458    {
459      grow_amt = (uint32)(buf_len/2);
460      buf_len += name_len+1+grow_amt-buf_left;
461      if((new_buf = realloc(buf, buf_len)) == NULL)
462      {
463        free(buf);
464        free(iter);
465        return NULL;
466      }
467      buf = new_buf;
468      buf_left = grow_amt + name_len + 1;
469    }
470    strncpy(buf+(buf_len-buf_left-1), name, name_len);
471    buf_left -= name_len;
472    buf[buf_len-buf_left-1] = '\0';
473    free(name);
474  }
475
476  return buf;
477}
478
479
480void printValue(REGF_VK_REC* vk, char* prefix)
481{
482  char* quoted_value = NULL;
483  char* quoted_name = NULL;
484  char* conv_error = NULL;
485  const char* str_type = NULL;
486  uint32 size;
487  uint8 tmp_buf[4];
488
489  /* Thanks Microsoft for making this process so straight-forward!!! */
490  size = (vk->data_size & ~VK_DATA_IN_OFFSET);
491  if(vk->data_size & VK_DATA_IN_OFFSET)
492  {
493    tmp_buf[0] = (uint8)((vk->data_off >> 3) & 0xFF);
494    tmp_buf[1] = (uint8)((vk->data_off >> 2) & 0xFF);
495    tmp_buf[2] = (uint8)((vk->data_off >> 1) & 0xFF);
496    tmp_buf[3] = (uint8)(vk->data_off & 0xFF);
497    if(size > 4)
498      /* XXX: should we kick out a warning here?  If it is in the
499       *      offset and longer than four, file could be corrupt
500       *      or malicious... */
501      size = 4;
502    quoted_value = data_to_ascii(tmp_buf, 4, vk->type, &conv_error);
503  }
504  else
505  {
506    /* Microsoft's documentation indicates that "available memory" is
507     * the limit on value sizes.  Annoying.  We limit it to 1M which
508     * should rarely be exceeded, unless the file is corrupt or
509     * malicious. For more info, see:
510     *   http://msdn2.microsoft.com/en-us/library/ms724872.aspx
511     */
512    if(size > VK_MAX_DATA_LENGTH)
513    {
514      fprintf(stderr, "WARNING: value data size %d larger than "
515              "%d, truncating...\n", size, VK_MAX_DATA_LENGTH);
516      size = VK_MAX_DATA_LENGTH;
517    }
518
519    quoted_value = data_to_ascii(vk->data, vk->data_size, 
520                                 vk->type, &conv_error);
521  }
522 
523  /* XXX: Sometimes value names can be NULL in registry.  Need to
524   *      figure out why and when, and generate the appropriate output
525   *      for that condition.
526   */
527  quoted_name = quote_string(vk->valuename, common_special_chars);
528
529  if(quoted_value == NULL)
530  {
531    if(conv_error == NULL)
532      fprintf(stderr, "WARNING: Could not quote value for '%s/%s'.  "
533              "Memory allocation failure likely.\n", prefix, quoted_name);
534    else
535      fprintf(stderr, "WARNING: Could not quote value for '%s/%s'.  "
536              "Returned error: %s\n", prefix, quoted_name, conv_error);
537  }
538  /* XXX: should these always be printed? */
539  else if(conv_error != NULL && print_verbose)
540      fprintf(stderr, "VERBOSE: While quoting value for '%s/%s', "
541              "warning returned: %s\n", prefix, quoted_name, conv_error);
542
543  str_type = regfio_type_val2str(vk->type);
544  if(print_security)
545  {
546    if(str_type == NULL)
547      printf("%s/%s,0x%.8X,%s,,,,,\n", prefix, quoted_name,
548             vk->type, quoted_value);
549    else
550      printf("%s/%s,%s,%s,,,,,\n", prefix, quoted_name,
551             str_type, quoted_value);
552  }
553  else
554  {
555    if(str_type == NULL)
556      printf("%s/%s,0x%.8X,%s,\n", prefix, quoted_name,
557             vk->type, quoted_value);
558    else
559      printf("%s/%s,%s,%s,\n", prefix, quoted_name,
560             str_type, quoted_value);
561  }
562
563  if(quoted_value != NULL)
564    free(quoted_value);
565  if(quoted_name != NULL)
566    free(quoted_name);
567  if(conv_error != NULL)
568    free(conv_error);
569}
570
571
572void printValueList(REGF_NK_REC* nk, char* prefix)
573{
574  uint32 i;
575 
576  for(i=0; i < nk->num_values; i++)
577    if(!type_filter_enabled || (nk->values[i].type == type_filter))
578      printValue(nk->values+i, prefix);
579}
580
581
582void printKey(REGF_NK_REC* k, char* full_path)
583{
584  static char empty_str[1] = "";
585  char* owner = NULL;
586  char* group = NULL;
587  char* sacl = NULL;
588  char* dacl = NULL;
589  char mtime[20];
590  time_t tmp_time[1];
591  struct tm* tmp_time_s = NULL;
592
593  *tmp_time = nt_time_to_unix(&k->mtime);
594  tmp_time_s = gmtime(tmp_time);
595  strftime(mtime, sizeof(mtime), "%Y-%m-%d %H:%M:%S", tmp_time_s);
596
597  if(print_security)
598  {
599    owner = regfio_get_owner(k->sec_desc->sec_desc);
600    group = regfio_get_group(k->sec_desc->sec_desc);
601    sacl = regfio_get_sacl(k->sec_desc->sec_desc);
602    dacl = regfio_get_dacl(k->sec_desc->sec_desc);
603    if(owner == NULL)
604      owner = empty_str;
605    if(group == NULL)
606      group = empty_str;
607    if(sacl == NULL)
608      sacl = empty_str;
609    if(dacl == NULL)
610      dacl = empty_str;
611
612    printf("%s,KEY,,%s,%s,%s,%s,%s\n", full_path, mtime, 
613           owner, group, sacl, dacl);
614
615    if(owner != empty_str)
616      free(owner);
617    if(group != empty_str)
618      free(group);
619    if(sacl != empty_str)
620      free(sacl);
621    if(dacl != empty_str)
622      free(dacl);
623  }
624  else
625    printf("%s,KEY,,%s\n", full_path, mtime);
626}
627
628
629void printKeyTree(REGF_FILE* f, void_stack* nk_stack, const char* prefix)
630{
631  REGF_NK_REC* cur = NULL;
632  REGF_NK_REC* sub = NULL;
633  char* path = NULL;
634  char* val_path = NULL;
635  uint32 val_path_len = 0;
636  uint32 path_len = 0;
637  uint32 prefix_len = strlen(prefix);
638  int key_type = regfio_type_str2val("KEY");
639 
640  if((cur = (REGF_NK_REC*)void_stack_cur(nk_stack)) != NULL)
641  {
642    cur->subkey_index = 0;
643    path = stack2Path(nk_stack);
644
645    if(print_verbose)
646    {
647      if(prefix[0] == '\0')
648        fprintf(stderr, "VERBOSE: Printing key tree under path: /\n");
649      else
650        fprintf(stderr, "VERBOSE: Printing key tree under path: %s\n",
651                prefix);
652    }
653
654    path_len = strlen(path);
655    val_path_len = prefix_len+path_len;
656    val_path = (char*)malloc(val_path_len+1+1);
657    if(val_path == NULL)
658      bailOut(2, "ERROR: Could not allocate val_path.\n");
659
660    strcpy(val_path, prefix);
661    strcpy(val_path+prefix_len, path);
662    if(val_path[0] == '\0')
663    {
664      val_path[0] = '/';
665      val_path[1] = '\0';
666    }
667    if(!type_filter_enabled || (key_type == type_filter))
668      printKey(cur, val_path);
669    if(!type_filter_enabled || (key_type != type_filter))
670      printValueList(cur, val_path);
671   
672    while((cur = (REGF_NK_REC*)void_stack_cur(nk_stack)) != NULL)
673    {
674      if((sub = regfio_fetch_subkey(f, cur)) == NULL)
675      {
676        sub = void_stack_pop(nk_stack);
677        /* XXX: This is just a shallow free.  Need to write deep free
678         * routines to replace the Samba code for this.
679         */ 
680        if(sub != NULL)
681          free(sub);
682      }
683      else
684      {
685        sub->subkey_index = 0;
686        void_stack_push(nk_stack, sub);
687        path = stack2Path(nk_stack);
688        if(path != NULL)
689        {
690          path_len = strlen(path);
691          if(val_path_len < prefix_len+path_len)
692          {
693            val_path_len = prefix_len+path_len;
694            val_path = (char*)realloc(val_path, val_path_len+1);
695            if(val_path == NULL)
696              bailOut(2, "ERROR: Could not reallocate val_path.\n");
697          }
698          strcpy(val_path, prefix);
699          strcpy(val_path+prefix_len, path);
700          if(!type_filter_enabled || (key_type == type_filter))
701            printKey(sub, val_path);
702          if(!type_filter_enabled || (key_type != type_filter))
703            printValueList(sub, val_path);
704        }
705      }
706    }
707  }
708  if(val_path != NULL)
709    free(val_path);
710  if(print_verbose)
711    fprintf(stderr, "VERBOSE: Finished printing key tree.\n");
712}
713
714
715/*
716 * Returns 0 if path was found.
717 * Returns 1 if path was not found.
718 * Returns less than 0 on other error.
719 */
720int retrievePath(REGF_FILE* f, void_stack* nk_stack,
721                 void_stack* path_stack)
722{
723  REGF_NK_REC* sub = NULL; 
724  REGF_NK_REC* cur = NULL;
725  void_stack* sub_nk_stack;
726  char* prefix;
727  char* cur_str = NULL;
728  char* path = NULL;
729  char* name;
730  uint16 path_depth;
731  uint32 i, prefix_len;
732  bool found_cur = true;
733  if(path_stack == NULL)
734    return -1;
735
736  path_depth = void_stack_size(path_stack);
737  if(path_depth < 1)
738    return -2;
739
740  if(void_stack_size(nk_stack) < 1)
741    return -3;
742  cur = (REGF_NK_REC*)void_stack_cur(nk_stack);
743
744  if(print_verbose)
745    fprintf(stderr, "VERBOSE: Beginning retrieval of specified path: %s\n", 
746            path_filter);
747
748  while(void_stack_size(path_stack) > 1)
749  {
750    /* Search key records only */
751    cur_str = (char*)void_stack_pop(path_stack);
752
753    found_cur = false;
754    while(!found_cur &&
755          (sub = regfio_fetch_subkey(f, cur)) != NULL)
756    {
757      if(strcasecmp(sub->keyname, cur_str) == 0)
758      {
759        cur = sub;
760        void_stack_push(nk_stack, sub);
761        found_cur = true;
762      }
763    }
764    if(print_verbose && !found_cur)
765      fprintf(stderr, "VERBOSE: Could not find KEY '%s' in specified path.\n", 
766              cur_str);
767
768    free(cur_str);
769    if(!found_cur)
770      return 1;
771  }
772
773  /* Last round, search value and key records */
774  cur_str = (char*)void_stack_pop(path_stack);
775
776  if(print_verbose)
777    fprintf(stderr, "VERBOSE: Searching values for last component"
778                    " of specified path.\n");
779
780  for(i=0; (i < cur->num_values); i++)
781  {
782    /* XXX: Not sure when/why this can be NULL, but it's happened. */
783    if(sub->values[i].valuename != NULL 
784       && strcasecmp(sub->values[i].valuename, cur_str) == 0)
785    {
786      path = stack2Path(nk_stack);
787
788      if(print_verbose)
789        fprintf(stderr, "VERBOSE: Found final path element as value.\n");
790
791      if(!type_filter_enabled || (sub->values[i].type == type_filter))
792        printValue(&sub->values[i], path);
793      if(path != NULL)
794        free(path);
795
796      return 0;
797    }
798  }
799
800  if(print_verbose)
801    fprintf(stderr, "VERBOSE: Searching keys for last component"
802                    " of specified path.\n");
803
804  while((sub = regfio_fetch_subkey(f, cur)) != NULL)
805  {
806    if(strcasecmp(sub->keyname, cur_str) == 0)
807    {
808      sub_nk_stack = void_stack_new(1024);
809      void_stack_push(sub_nk_stack, sub);
810      prefix = stack2Path(nk_stack);
811      prefix_len = strlen(prefix);
812      prefix = realloc(prefix, prefix_len+strlen(sub->keyname)+2);
813      if(prefix == NULL)
814        return -1;
815      name = quote_string(sub->keyname, key_special_chars);
816      strcat(prefix, "/");
817      strcat(prefix, name);
818      free(name);
819
820      if(print_verbose)
821        fprintf(stderr, "VERBOSE: Found final path element as key.\n");
822
823      printKeyTree(f, sub_nk_stack, prefix);
824
825      return 0;
826    }
827  }
828
829  if(print_verbose)
830    fprintf(stderr, "VERBOSE: Could not find last element of path.\n");
831
832  return 1;
833}
834
835
836static void usage(void)
837{
838  fprintf(stderr, "Usage: reglookup [-v] [-s]"
839          " [-p <PATH_FILTER>] [-t <TYPE_FILTER>]"
840          " <REGISTRY_FILE>\n");
841  fprintf(stderr, "Version: 0.3.0\n");
842  fprintf(stderr, "Options:\n");
843  fprintf(stderr, "\t-v\t sets verbose mode.\n");
844  fprintf(stderr, "\t-h\t enables header row. (default)\n");
845  fprintf(stderr, "\t-H\t disables header row.\n");
846  fprintf(stderr, "\t-s\t enables security descriptor output.\n");
847  fprintf(stderr, "\t-S\t disables security descriptor output. (default)\n");
848  fprintf(stderr, "\t-p\t restrict output to elements below this path.\n");
849  fprintf(stderr, "\t-t\t restrict results to this specific data type.\n");
850  fprintf(stderr, "\n");
851}
852
853
854int main(int argc, char** argv)
855{
856  void_stack* nk_stack;
857  void_stack* path_stack;
858  REGF_FILE* f;
859  REGF_NK_REC* root;
860  int retr_path_ret;
861  uint32 argi, arge;
862
863  /* Process command line arguments */
864  if(argc < 2)
865  {
866    usage();
867    bailOut(1, "ERROR: Requires at least one argument.\n");
868  }
869 
870  arge = argc-1;
871  for(argi = 1; argi < arge; argi++)
872  {
873    if (strcmp("-p", argv[argi]) == 0)
874    {
875      if(++argi >= arge)
876      {
877        usage();
878        bailOut(1, "ERROR: '-p' option requires parameter.\n");
879      }
880      if((path_filter = strdup(argv[argi])) == NULL)
881        bailOut(2, "ERROR: Memory allocation problem.\n");
882
883      path_filter_enabled = true;
884    }
885    else if (strcmp("-t", argv[argi]) == 0)
886    {
887      if(++argi >= arge)
888      {
889        usage();
890        bailOut(1, "ERROR: '-t' option requires parameter.\n");
891      }
892      if((type_filter = regfio_type_str2val(argv[argi])) < 0)
893      {
894        fprintf(stderr, "ERROR: Invalid type specified: %s.\n", argv[argi]);
895        bailOut(1, "");
896      }
897      type_filter_enabled = true;
898    }
899    else if (strcmp("-h", argv[argi]) == 0)
900      print_header = true;
901    else if (strcmp("-H", argv[argi]) == 0)
902      print_header = false;
903    else if (strcmp("-s", argv[argi]) == 0)
904      print_security = true;
905    else if (strcmp("-S", argv[argi]) == 0)
906      print_security = false;
907    else if (strcmp("-v", argv[argi]) == 0)
908      print_verbose = true;
909    else
910    {
911      usage();
912      fprintf(stderr, "ERROR: Unrecognized option: %s\n", argv[argi]);
913      bailOut(1, "");
914    }
915  }
916  if((registry_file = strdup(argv[argi])) == NULL)
917    bailOut(2, "ERROR: Memory allocation problem.\n");
918
919  f = regfio_open(registry_file);
920  if(f == NULL)
921  {
922    fprintf(stderr, "ERROR: Couldn't open registry file: %s\n", registry_file);
923    bailOut(3, "");
924  }
925
926  root = regfio_rootkey(f);
927  nk_stack = void_stack_new(1024);
928
929  if(void_stack_push(nk_stack, root))
930  {
931    if(print_header)
932    {
933      if(print_security)
934        printf("PATH,TYPE,VALUE,MTIME,OWNER,GROUP,SACL,DACL\n");
935      else
936        printf("PATH,TYPE,VALUE,MTIME\n");
937    }
938
939    path_stack = path2Stack(path_filter);
940    if(void_stack_size(path_stack) < 1)
941      printKeyTree(f, nk_stack, "");
942    else
943    {
944      retr_path_ret = retrievePath(f, nk_stack, path_stack);
945      if(retr_path_ret == 1)
946        fprintf(stderr, "WARNING: specified path not found.\n");
947      else if(retr_path_ret != 0)
948        bailOut(4, "ERROR:\n");
949    }
950  }
951  else
952    bailOut(2, "ERROR: Memory allocation problem.\n");
953
954  void_stack_destroy_deep(nk_stack);
955  regfio_close(f);
956
957  return 0;
958}
Note: See TracBrowser for help on using the repository browser.