source: releases/0.99.0/python/pyregfi/__init__.py @ 235

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

improved version information interface by adding a special purpose function

File size: 32.4 KB
Line 
1#!/usr/bin/env python
2
3## @package pyregfi
4# Python interface to the regfi library.
5#
6
7## @mainpage API Documentation
8#
9# The pyregfi module provides a Python interface to the @ref regfi Windows
10# registry library. 
11#
12# The library operates on registry hives, each of which is contained within a
13# single file.  To get started, one must first open the registry hive file with
14# the open() or file() Python built-in functions (or equivalent) and then pass
15# the resulting file object to pyregfi. For example:
16# @code
17# >>> import pyregfi
18# >>> fh = open('/mnt/win/c/WINDOWS/system32/config/system', 'rb')
19# >>> myHive = pyregfi.Hive(fh)
20# @endcode
21#
22# Using this Hive object, one can begin investigating what top-level keys
23# exist by starting with the root Key attribute:
24# @code
25# >>> for key in myHive.root.subkeys:
26# ...   print(key.name)
27# ControlSet001
28# ControlSet003
29# LastKnownGoodRecovery
30# MountedDevices
31# Select
32# Setup
33# WPA
34# @endcode
35#
36# From there, accessing subkeys and values by name is a simple matter of:
37# @code
38# >>> myKey = myHive.root.subkeys['Select']
39# >>> myValue = myKey.values['Current']
40# @endcode
41#
42# The data associated with a Value can be obtained through the fetch_data()
43# method:
44# @code
45# >>> print(myValue.fetch_data())
46# 1
47# @endcode
48#
49# While useful for simple exercises, using the subkeys object for deeply nested
50# paths is not efficient and doesn't make for particularly attractive code. 
51# Instead, a special-purpose HiveIterator class is provided for simplicity of
52# use and fast access to specific known paths:
53# @code
54# >>> myIter = pyregfi.HiveIterator(myHive)
55# >>> myIter.descend(['ControlSet001','Control','NetworkProvider','HwOrder'])
56# >>> myKey = myIter.current_key()
57# >>> print(myKey.values['ProviderOrder'].fetch_data())
58# RDPNP,LanmanWorkstation,WebClient
59# @endcode
60#
61# The first two lines above can be simplified in some "syntactic sugar" provided
62# by the Hive.subtree() method.  Also, as one might expect, the HiveIterator
63# also acts as an iterator, producing keys in a depth-first order.
64# For instance, to traverse all keys under the ControlSet003\\Services key,
65# printing their names as we go, we could do:
66# @code
67# >>> for key in Hive.subtree(['ControlSet003','Services']):
68# >>>   print(key.name)
69# Services
70# Abiosdsk
71# abp480n5
72# Parameters
73# PnpInterface
74# ACPI
75# [...]
76# @endcode
77#
78# Note that "Services" was printed first, since the subtree is traversed as a
79# "preordering depth-first" search starting with the HiveIterator's current_key(). 
80# As one might expect, traversals of subtrees stops when all elements in a
81# specific subtree (and none outside of it) have been traversed.
82#
83# For more information, peruse the various attributes and methods available on
84# the Hive, HiveIterator, Key, Value, and Security classes.
85#
86# @note @ref regfi is a read-only library by design and there
87# are no plans to implement write support.
88#
89# @note At present, pyregfi has been tested with Python versions 2.6 and 3.1
90#
91# @note Developers strive to make pyregfi thread-safe.
92#
93# @note Key and Value names are case-sensitive in regfi and pyregfi
94#
95import sys
96import time
97import ctypes
98import ctypes.util
99import threading
100from pyregfi.structures import *
101
102
103## An enumeration of registry Value data types
104#
105# @note This is a static class, there is no need to instantiate it.
106#       Just access its attributes directly as DATA_TYPES.SZ, etc
107class DATA_TYPES(object):
108    ## None / Unknown
109    NONE                       =  0
110    ## String
111    SZ                         =  1
112    ## String with %...% expansions
113    EXPAND_SZ                  =  2
114    ## Binary buffer
115    BINARY                     =  3
116    ## 32 bit integer (little endian)
117    DWORD                      =  4 # DWORD, little endian
118    ## 32 bit integer (little endian)
119    DWORD_LE                   =  4
120    ## 32 bit integer (big endian)
121    DWORD_BE                   =  5 # DWORD, big endian
122    ## Symbolic link
123    LINK                       =  6
124    ## List of strings
125    MULTI_SZ                   =  7
126    ## Unknown structure
127    RESOURCE_LIST              =  8
128    ## Unknown structure
129    FULL_RESOURCE_DESCRIPTOR   =  9
130    ## Unknown structure
131    RESOURCE_REQUIREMENTS_LIST = 10
132    ## 64 bit integer
133    QWORD                      = 11 # 64-bit little endian
134
135
136## An enumeration of log message types
137#
138# @note This is a static class, there is no need to instantiate it.
139#       Just access its attributes directly as LOG_TYPES.INFO, etc
140class LOG_TYPES(object):
141    ## Informational messages, useful in debugging
142    INFO  =  0x01
143    ## Non-critical problems in structure parsing or intepretation
144    WARN  =  0x04
145    ## Major failures
146    ERROR =  0x10
147
148
149def _buffer2bytearray(char_pointer, length):
150    if length == 0 or char_pointer == None:
151        return None
152   
153    ret_val = bytearray(length)
154    for i in range(0,length):
155        ret_val[i] = char_pointer[i][0]
156
157    return ret_val
158
159
160def _strlist2charss(str_list):
161    ret_val = []
162    for s in str_list:
163        ret_val.append(s.encode('utf-8', 'replace'))
164
165    ret_val = (ctypes.c_char_p*(len(str_list)+1))(*ret_val)
166    # Terminate the char** with a NULL pointer
167    ret_val[-1] = 0
168
169    return ret_val
170
171
172def _charss2strlist(chars_pointer):
173    ret_val = []
174    i = 0
175    s = chars_pointer[i]
176    while s != None:
177        ret_val.append(s.decode('utf-8', 'replace'))
178        i += 1
179        s = chars_pointer[i]
180
181    return ret_val
182
183
184## Returns the (py)regfi library version
185#
186# @return A string indicating the version
187def getVersion():
188    return regfi.regfi_version()
189
190
191## Retrieves messages produced by regfi during parsing and interpretation
192#
193# The regfi C library may generate log messages stored in a special thread-safe
194# global data structure.  These messages should be retrieved periodically or
195# after each major operation by callers to determine if any errors or warnings
196# should be reported to the user.  Failure to retrieve these could result in
197# excessive memory consumption.
198def getLogMessages():
199    msgs = regfi.regfi_log_get_str()
200    if not msgs:
201        return ''
202    return msgs.decode('utf-8')
203
204
205## Sets the types of log messages to record
206#
207# @param log_types A sequence of message types that regfi should generate.
208#                  Message types can be found in the LOG_TYPES enumeration.
209#
210# @return True on success, False on failure.  Failures are rare, but could
211#         indicate that global logging is not operating as expected.
212#
213# Example:
214# @code
215# setLogMask((LOG_TYPES.ERROR, LOG_TYPES.WARN, LOG_TYPES.INFO))
216# @endcode
217#
218# The message mask is a global (all hives, iterators), thread-specific value.
219# For more information, see @ref regfi_log_set_mask.
220#
221def setLogMask(log_types):
222    mask = 0
223    for m in log_types:
224        mask |= m
225    return regfi.regfi_log_set_mask(mask)
226
227
228## Opens a file as a registry hive
229#
230# @param path The file path of a hive, as one would provide to the
231#             open() built-in
232#
233# @return A new Hive instance
234def openHive(path):
235    fh = open(path, 'rb')
236    return Hive(fh)
237
238
239## Abstract class for most objects returned by the library
240class _StructureWrapper(object):
241    _hive = None
242    _base = None
243
244    def __init__(self, hive, base):
245        if not hive:
246            raise Exception("Could not create _StructureWrapper,"
247                            + " hive is NULL.  Current log:\n"
248                            + getLogMessages())
249        if not base:
250            raise Exception("Could not create _StructureWrapper,"
251                            + " base is NULL.  Current log:\n"
252                            + getLogMessages())
253        self._hive = hive
254        self._base = base
255
256
257    # Memory management for most regfi structures is taken care of here
258    def __del__(self):
259        regfi.regfi_free_record(self._hive.file, self._base)
260
261
262    # Any attribute requests not explicitly defined in subclasses gets passed
263    # to the equivalent REGFI_* structure defined in structures.py
264    def __getattr__(self, name):
265        return getattr(self._base.contents, name)
266
267   
268    ## Test for equality
269    #
270    # Records returned by pyregfi may be compared with one another.  For example:
271    # @code
272    #  >>> key2 = key1.subkeys['child']
273    #  >>> key1 == key2
274    #  False
275    #  >>> key1 != key2
276    #  True
277    #  >>> key1 == key2.get_parent()
278    #  True
279    # @endcode
280    def __eq__(self, other):
281        return (type(self) == type(other)) and (self.offset == other.offset)
282
283
284    def __ne__(self, other):
285        return (not self.__eq__(other))
286
287
288class Key():
289    pass
290
291
292class Value():
293    pass
294
295
296## Registry security record and descriptor
297# XXX: Access to security descriptors not yet implemented
298class Security(_StructureWrapper):
299    pass
300
301## Abstract class for ValueList and SubkeyList
302class _GenericList(object):
303    _hive = None
304    _key_base = None
305    _length = None
306    _current = None
307
308    # implementation-specific functions for SubkeyList and ValueList
309    _fetch_num = None
310    _find_element = None
311    _get_element = None
312    _constructor = None
313
314    def __init__(self, key):
315        if not key:
316            raise Exception("Could not create _GenericList; key is NULL."
317                            + "Current log:\n" + getLogMessages())
318       
319        if not regfi.regfi_reference_record(key._hive.file, key._base):
320            raise Exception("Could not create _GenericList; memory error."
321                            + "Current log:\n" + getLogMessages())
322        self._key_base = key._base
323        self._length = self._fetch_num(self._key_base)
324        self._hive = key._hive
325
326   
327    def __del__(self):
328        regfi.regfi_free_record(self._hive.file, self._key_base)
329
330
331    ## Length of list
332    def __len__(self):
333        return self._length
334
335
336    ## Retrieves a list element by name
337    #
338    # @return the first element whose name matches, or None if the element
339    #         could not be found
340    def __getitem__(self, name):
341        index = ctypes.c_uint32()
342        if isinstance(name, str):
343            name = name.encode('utf-8')
344
345        if name != None:
346            name = create_string_buffer(bytes(name))
347
348        if self._find_element(self._hive.file, self._key_base, 
349                              name, byref(index)):
350            return self._constructor(self._hive,
351                                     self._get_element(self._hive.file,
352                                                       self._key_base,
353                                                       index))
354        raise KeyError('')
355
356    def get(self, name, default):
357        try:
358            return self[name]
359        except KeyError:
360            return default
361   
362    def __iter__(self):
363        self._current = 0
364        return self
365   
366    def __next__(self):
367        if self._current >= self._length:
368            raise StopIteration('')
369
370        elem = self._get_element(self._hive.file, self._key_base,
371                                 ctypes.c_uint32(self._current))
372        self._current += 1
373        return self._constructor(self._hive, elem)
374   
375    # For Python 2.x
376    next = __next__
377
378
379## The list of subkeys associated with a Key
380#
381# This attribute is both iterable:
382# @code
383#   for k in myKey.subkeys:
384#     ...
385# @endcode
386# and accessible as a dictionary:
387# @code
388#   mySubkey = myKey.subkeys["keyName"]
389# @endcode
390#
391# @note SubkeyLists should never be accessed directly and only exist
392#       in association with a parent Key object.  Do not retain references to
393#       SubkeyLists.  Instead, access them via their parent Key at all times.
394class SubkeyList(_GenericList):
395    _fetch_num = regfi.regfi_fetch_num_subkeys
396    _find_element = regfi.regfi_find_subkey
397    _get_element = regfi.regfi_get_subkey
398
399
400## The list of values associated with a Key
401#
402# This attribute is both iterable:
403# @code
404#   for v in myKey.values:
405#     ...
406# @endcode
407# and accessible as a dictionary:
408# @code
409#   myValue = myKey.values["valueName"]
410# @endcode
411#
412# @note ValueLists should never be accessed directly and only exist
413#       in association with a parent Key object.  Do not retain references to
414#       ValueLists.  Instead, access them via their parent Key at all times.
415class ValueList(_GenericList):
416    _fetch_num = regfi.regfi_fetch_num_values
417    _find_element = regfi.regfi_find_value
418    _get_element = regfi.regfi_get_value
419
420
421## Registry key
422# These represent registry keys (@ref REGFI_NK records) and provide
423# access to their subkeys, values, and other metadata.
424#
425# @note Value instances may provide access to more than the attributes
426#       documented here.  However, undocumented attributes may change over time
427#       and are not officially supported.  If you need access to an attribute
428#       not shown here, see pyregfi.structures.
429class Key(_StructureWrapper):
430    ## A @ref ValueList object representing the list of Values
431    #  stored on this Key
432    values = None
433
434    ## A @ref SubkeyList object representing the list of subkeys
435    #  stored on this Key
436    subkeys = None
437
438    ## The raw Key name as an uninterpreted bytearray
439    name_raw = (b"...")
440   
441    ## The name of the Key as a (unicode) string
442    name = "..."
443   
444    ## The absolute file offset of the Key record's cell in the Hive file
445    offset = 0xCAFEBABE
446
447    ## This Key's last modified time represented as the number of seconds
448    #  since the UNIX epoch in UTC; similar to what time.time() returns
449    modified = 1300000000.123456
450
451    ## The NK record's flags field
452    flags = 0x10110001
453
454    def __init__(self, hive, base):
455        super(Key, self).__init__(hive, base)
456        self.values = ValueList(self)
457        self.subkeys = SubkeyList(self)
458
459    def __getattr__(self, name):
460        if name == "name":
461            ret_val = super(Key, self).__getattr__(name)
462
463            if ret_val == None:
464                ret_val = self.name_raw
465            else:
466                ret_val = ret_val.decode('utf-8', 'replace')
467               
468        elif name == "name_raw":
469            ret_val = super(Key, self).__getattr__(name)
470            length = super(Key, self).__getattr__('name_length')
471            ret_val = _buffer2bytearray(ret_val, length)
472       
473        elif name == "modified":
474            ret_val = regfi.regfi_nt2unix_time(byref(self._base.contents.mtime))
475
476        else:
477            ret_val = super(Key, self).__getattr__(name)
478
479        return ret_val
480
481
482    ## Retrieves the Security properties for this key
483    def fetch_security(self):
484        return Security(self._hive,
485                        regfi.regfi_fetch_sk(self._hive.file, self._base))
486
487
488    ## Retrieves the class name for this key
489    #
490    # Class names are typically stored as UTF-16LE strings, so these are decoded
491    # into proper python (unicode) strings.  However, if this fails, a bytearray
492    # is instead returned containing the raw buffer stored for the class name.
493    #
494    # @return The class name as a string or bytearray.  None if a class name
495    #         doesn't exist or an unrecoverable error occurred during retrieval.
496    def fetch_classname(self):
497        ret_val = None
498        cn_p = regfi.regfi_fetch_classname(self._hive.file, self._base)
499        if cn_p:
500            cn_struct = cn_p.contents
501            if cn_struct.interpreted:
502                ret_val = cn_struct.interpreted.decode('utf-8', 'replace')
503            else:
504                ret_val = _buffer2bytearray(cn_struct.raw,
505                                            cn_struct.size)
506            regfi.regfi_free_record(self._hive.file, cn_p)
507
508        return ret_val
509
510
511    ## Retrieves this key's parent key
512    #
513    # @return The parent's Key instance or None if current key is root
514    #         (or an error occured)
515    def get_parent(self):
516        if self.is_root():
517            return None
518        parent_base = regfi.regfi_get_parentkey(self._hive.file, self._base)
519        if parent_base:
520            return Key(self._hive, parent_base)
521        return None
522
523    def is_root(self):
524        return (self._hive.root == self)
525
526
527## Registry value (metadata)
528#
529# These represent registry values (@ref REGFI_VK records) and provide
530# access to their associated data.
531#
532# @note Value instances may provide access to more than the attributes
533#       documented here.  However, undocumented attributes may change over time
534#       and are not officially supported.  If you need access to an attribute
535#       not shown here, see pyregfi.structures.
536class Value(_StructureWrapper):
537    ## The raw Value name as an uninterpreted bytearray
538    name_raw = (b"...")
539   
540    ## The name of the Value as a (unicode) string
541    name = "..."
542   
543    ## The absolute file offset of the Value record's cell in the Hive file
544    offset = 0xCAFEBABE
545
546    ## The length of data advertised in the VK record
547    data_size = 0xCAFEBABE
548
549    ## An integer which represents the data type for this Value's data
550    # Typically this value is one of 12 types defined in @ref DATA_TYPES,
551    # but in some cases (the SAM hive) it may be used for other purposes
552    type = DATA_TYPES.NONE
553
554    ## The VK record's flags field
555    flags = 0x10110001
556
557    ## Retrieves the Value's data according to advertised type
558    #
559    # Data is loaded from its cell(s) and then interpreted based on the data
560    # type recorded in the Value.  It is not uncommon for data to be stored with
561    # the wrong type or even with invalid types.  If you have difficulty
562    # obtaining desired data here, use @ref fetch_raw_data().
563    #
564    # @return The interpreted representation of the data as one of several
565    #         possible Python types, as listed below.  None if any failure
566    #         occurred during extraction or conversion.
567    #
568    # @retval string for SZ, EXPAND_SZ, and LINK
569    # @retval int for DWORD, DWORD_BE, and QWORD
570    # @retval list(string) for MULTI_SZ
571    # @retval bytearray for NONE, BINARY, RESOURCE_LIST,
572    #         FULL_RESOURCE_DESCRIPTOR, and RESOURCE_REQUIREMENTS_LIST
573    #
574    def fetch_data(self):
575        ret_val = None
576        data_p = regfi.regfi_fetch_data(self._hive.file, self._base)
577        if not data_p:
578            return None
579        data_struct = data_p.contents
580
581        if data_struct.interpreted_size == 0:
582            ret_val = None
583        elif data_struct.type in (DATA_TYPES.SZ, DATA_TYPES.EXPAND_SZ, DATA_TYPES.LINK):
584            # Unicode strings
585            ret_val = data_struct.interpreted.string.decode('utf-8', 'replace')
586        elif data_struct.type in (DATA_TYPES.DWORD, DATA_TYPES.DWORD_BE):
587            # 32 bit integers
588            ret_val = data_struct.interpreted.dword
589        elif data_struct.type == DATA_TYPES.QWORD:
590            # 64 bit integers
591            ret_val = data_struct.interpreted.qword
592        elif data_struct.type == DATA_TYPES.MULTI_SZ:
593            ret_val = _charss2strlist(data_struct.interpreted.multiple_string)
594        elif data_struct.type in (DATA_TYPES.NONE, DATA_TYPES.RESOURCE_LIST,
595                                  DATA_TYPES.FULL_RESOURCE_DESCRIPTOR,
596                                  DATA_TYPES.RESOURCE_REQUIREMENTS_LIST,
597                                  DATA_TYPES.BINARY):
598            ret_val = _buffer2bytearray(data_struct.interpreted.none,
599                                        data_struct.interpreted_size)
600
601        regfi.regfi_free_record(self._hive.file, data_p)
602        return ret_val
603   
604
605    ## Retrieves raw representation of Value's data
606    #
607    # @return A bytearray containing the data
608    #
609    def fetch_raw_data(self):
610        ret_val = None
611        # XXX: should we load the data without interpretation instead?
612        data_p = regfi.regfi_fetch_data(self._hive.file, self._base)
613        if not data_p:
614            return None
615
616        data_struct = data_p.contents
617        ret_val = _buffer2bytearray(data_struct.raw,
618                                    data_struct.size)
619        regfi.regfi_free_record(self._hive.file, data_p)
620        return ret_val
621
622
623    def __getattr__(self, name):
624        ret_val = super(Value, self).__getattr__(name)
625        if name == "name":
626            if ret_val == None:
627                ret_val = self.name_raw
628            else:
629                ret_val = ret_val.decode('utf-8', 'replace')
630
631        elif name == "name_raw":
632            length = super(Value, self).__getattr__('name_length')
633            ret_val = _buffer2bytearray(ret_val, length)
634
635        return ret_val
636
637
638# Avoids chicken/egg class definitions.
639# Also makes for convenient code reuse in these lists' parent classes.
640SubkeyList._constructor = Key
641ValueList._constructor = Value
642
643
644
645## Represents a single registry hive (file)
646class Hive():
647    file = None
648    raw_file = None
649    _root = None
650
651    ## The root Key of this Hive
652    root = None
653
654    ## This Hives's last modified time represented as the number of seconds
655    #  since the UNIX epoch in UTC; similar to what time.time() returns
656    modified = 1300000000.123456
657
658    ## First sequence number
659    sequence1 = 12345678
660
661    ## Second sequence number
662    sequence2 = 12345678
663
664    ## Major version
665    major_version = 1
666
667    ## Minor version
668    minor_version = 5
669
670    ## Constructor
671    #
672    # Initialize a new Hive based on a Python file object.  To open a file by
673    # path, see @ref openHive.
674    #
675    # @param fh A Python file object.  The constructor first looks for a valid
676    #           fileno attribute on this object and uses it if possible. 
677    #           Otherwise, the seek and read methods are used for file
678    #           access.
679    #
680    # @note Supplied file must be seekable.  Do not perform any operation on
681    #       the provided file object while a Hive is using it.  Do not
682    #       construct multiple Hive instances from the same file object.
683    #       If a file must be accessed by separate code and pyregfi
684    #       simultaneously, use a separate file descriptor.  Hives are
685    #       thread-safe, so multiple threads may use a single Hive object.
686    def __init__(self, fh):
687        # The fileno method may not exist, or it may throw an exception
688        # when called if the file isn't backed with a descriptor.
689        fn = None
690        try:
691            # XXX: Native calls to Windows filenos don't seem to work. 
692            #      Need to investigate why.
693            if not is_win32 and hasattr(fh, 'fileno'):
694                fn = fh.fileno()
695        except:
696            pass
697
698        if fn != None:
699            self.file = regfi.regfi_alloc(fn, REGFI_ENCODING_UTF8)
700            if not self.file:
701                # XXX: switch to non-generic exception
702                raise Exception("Could not open registry file.  Current log:\n"
703                                + getLogMessages())
704        else:
705            fh.seek(0)
706            self.raw_file = structures.REGFI_RAW_FILE()
707            self.raw_file.fh = fh
708            self.raw_file.seek = seek_cb_type(self.raw_file.cb_seek)
709            self.raw_file.read = read_cb_type(self.raw_file.cb_read)
710            self.file = regfi.regfi_alloc_cb(pointer(self.raw_file), REGFI_ENCODING_UTF8)
711            if not self.file:
712                # XXX: switch to non-generic exception
713                raise Exception("Could not open registry file.  Current log:\n"
714                                + getLogMessages())
715
716
717    def __getattr__(self, name):
718        if name == "root":
719            # XXX: This creates reference loops.  Need to cache better inside regfi
720            #if self._root == None:
721            #    self._root = Key(self, regfi.regfi_get_rootkey(self.file))
722            #return self._root
723            return Key(self, regfi.regfi_get_rootkey(self.file))
724
725        elif name == "modified":
726            return regfi.regfi_nt2unix_time(byref(self._base.contents.mtime))
727
728        return getattr(self.file.contents, name)
729
730   
731    def __del__(self):
732        regfi.regfi_free(self.file)
733        if self.raw_file != None:
734            self.raw_file = None
735
736
737    def __iter__(self):
738        return HiveIterator(self)
739
740
741    ## Creates a @ref HiveIterator initialized at the specified path in
742    #  the hive.
743    #
744    # @param path A list of Key names which represent an absolute path within
745    #             the Hive
746    #
747    # @return A @ref HiveIterator which is positioned at the specified path.
748    #
749    # @exception Exception If the path could not be found/traversed
750    def subtree(self, path):
751        hi = HiveIterator(self)
752        hi.descend(path)
753        return hi
754
755
756## A special purpose iterator for registry hives
757#
758# Iterating over an object of this type causes all keys in a specific
759# hive subtree to be returned in a depth-first manner. These iterators
760# are typically created using the @ref Hive.subtree() function on a @ref Hive
761# object.
762#
763# HiveIterators can also be used to manually traverse up and down a
764# registry hive as they retain information about the current position in
765# the hive, along with which iteration state for subkeys and values for
766# every parent key.  See the @ref up and @ref down methods for more
767# information.
768class HiveIterator():
769    _hive = None
770    _iter = None
771    _iteration_root = None
772    _lock = None
773
774    def __init__(self, hive):
775        self._iter = regfi.regfi_iterator_new(hive.file)
776        if not self._iter:
777            raise Exception("Could not create iterator.  Current log:\n"
778                            + getLogMessages())
779        self._hive = hive
780        self._lock = threading.RLock()
781   
782    def __getattr__(self, name):
783        self._lock.acquire()
784        ret_val = getattr(self._iter.contents, name)
785        self._lock.release()
786        return ret_val
787
788    def __del__(self):
789        self._lock.acquire()
790        regfi.regfi_iterator_free(self._iter)
791        self._lock.release()
792
793    def __iter__(self):
794        self._lock.acquire()
795        self._iteration_root = None
796        self._lock.release()
797        return self
798
799    def __next__(self):
800        self._lock.acquire()
801        if self._iteration_root == None:
802            self._iteration_root = self.current_key().offset
803        elif not regfi.regfi_iterator_down(self._iter):
804            up_ret = regfi.regfi_iterator_up(self._iter)
805            while (up_ret and
806                   not regfi.regfi_iterator_next_subkey(self._iter)):
807                if self._iteration_root == self.current_key().offset:
808                    self._iteration_root = None
809                    self._lock.release()
810                    raise StopIteration('')
811                up_ret = regfi.regfi_iterator_up(self._iter)
812
813            if not up_ret:
814                self._iteration_root = None
815                self._lock.release()
816                raise StopIteration('')
817           
818            # XXX: Use non-generic exception
819            if not regfi.regfi_iterator_down(self._iter):
820                self._lock.release()
821                raise Exception('Error traversing iterator downward.'+
822                                ' Current log:\n'+ getLogMessages())
823
824        regfi.regfi_iterator_first_subkey(self._iter)
825        ret_val = self.current_key()
826        self._lock.release()
827
828        return ret_val
829
830
831    # For Python 2.x
832    next = __next__
833
834    # XXX: Should add sanity checks on some of these traversal functions
835    #      to throw exceptions if a traversal/retrieval *should* have worked
836    #      but failed for some reason.
837
838    ## Descends the iterator to a subkey
839    #
840    # Descends the iterator one level to the current subkey, or a subkey
841    # specified by name.
842    #
843    # @param subkey_name If specified, locates specified subkey by name
844    #                    (via find_subkey()) and descends to it.
845    #
846    # @return True if successful, False otherwise
847    def down(self, subkey_name=None):
848        ret_val = None
849        if subkey_name == None:
850            self._lock.acquire()
851            ret_val = regfi.regfi_iterator_down(self._iter)
852        else:
853            if name != None:
854                name = name.encode('utf-8')
855            self._lock.acquire()
856            ret_val = (regfi.regfi_iterator_find_subkey(self._iter, name) 
857                       and regfi.regfi_iterator_down(self._iter))
858       
859        self._lock.release()
860        return ret_val
861
862
863    ## Causes the iterator to ascend to the current Key's parent
864    #
865    # @return True if successful, False otherwise
866    #
867    # @note The state of current subkeys and values at this level in the tree
868    #       is lost as a side effect.  That is, if you go up() and then back
869    #       down() again, current_subkey() and current_value() will return
870    #       default selections.
871    def up(self):
872        self._lock.acquire()
873        ret_val = regfi.regfi_iterator_up(self._iter)
874        self._lock.release()
875        return ret_val
876
877
878    ## Selects first subkey of current key
879    #
880    # @return A Key instance for the first subkey. 
881    #         None on error or if the current key has no subkeys.
882    def first_subkey(self):
883        ret_val = None
884        self._lock.acquire()
885        if regfi.regfi_iterator_first_subkey(self._iter):
886            ret_val = self.current_subkey()
887        self._lock.release()
888        return ret_val
889
890
891    ## Selects first value of current Key
892    #
893    # @return A Value instance for the first value. 
894    #         None on error or if the current key has no values.
895    def first_value(self):
896        ret_val = None
897        self._lock.acquire()
898        if regfi.regfi_iterator_first_value(self._iter):
899            ret_val = self.current_value()
900        self._lock.release()
901        return ret_val
902
903
904    ## Selects the next subkey in the current Key's list
905    #
906    # @return A Key instance for the next subkey.
907    #         None if there are no remaining subkeys or an error occurred.
908    def next_subkey(self):
909        ret_val = None
910        self._lock.acquire()
911        if regfi.regfi_iterator_next_subkey(self._iter):
912            ret_val = self.current_subkey()
913        self._lock.release()
914        return ret_val
915
916
917    ## Selects the next value in the current Key's list
918   
919    # @return A Value instance for the next value.
920    #         None if there are no remaining values or an error occurred.
921    def next_value(self):
922        ret_val = None
923        self._lock.acquire()
924        if regfi.regfi_iterator_next_value(self._iter):
925            ret_val = self.current_value()
926        self._lock.release()
927        return ret_val
928
929
930    ## Selects the first subkey which has the specified name
931    #
932    # @return A Key instance for the selected key.
933    #         None if it could not be located or an error occurred.
934    def find_subkey(self, name):
935        if name != None:
936            name = name.encode('utf-8')
937        ret_val = None
938        self._lock.acquire()
939        if regfi.regfi_iterator_find_subkey(self._iter, name):
940            ret_val = self.current_subkey()
941        self._lock.release()
942        return ret_val
943
944
945    ## Selects the first value which has the specified name
946    #
947    # @return A Value instance for the selected value.
948    #         None if it could not be located or an error occurred.
949    def find_value(self, name):
950        if name != None:
951            name = name.encode('utf-8')
952        ret_val = None
953        self._lock.acquire()
954        if regfi.regfi_iterator_find_value(self._iter, name):
955            ret_val = self.current_value()
956        self._lock.release()
957        return ret_val
958
959    ## Retrieves the currently selected subkey
960    #
961    # @return A Key instance of the current subkey
962    def current_subkey(self):
963        self._lock.acquire()
964        ret_val = Key(self._hive, regfi.regfi_iterator_cur_subkey(self._iter))
965        self._lock.release()
966        return ret_val
967
968    ## Retrieves the currently selected value
969    #
970    # @return A Value instance of the current value
971    def current_value(self):
972        self._lock.acquire()
973        ret_val = Value(self._hive, regfi.regfi_iterator_cur_value(self._iter))
974        self._lock.release()
975        return ret_val
976
977    ## Retrieves the current key
978    #
979    # @return A Key instance of the current position of the iterator
980    def current_key(self):
981        self._lock.acquire()
982        ret_val = Key(self._hive, regfi.regfi_iterator_cur_key(self._iter))
983        self._lock.release()
984        return ret_val
985
986
987    ## Traverse downward multiple levels
988    #
989    # This is more efficient than calling down() multiple times
990    #
991    # @param path A list of Key names which represent the path to descend
992    #
993    # @exception Exception If path could not be located
994    def descend(self, path):
995        cpath = _strlist2charss(path)
996
997        self._lock.acquire()
998        result = regfi.regfi_iterator_walk_path(self._iter, cpath)
999        self._lock.release()
1000        if not result:
1001            # XXX: Use non-generic exception
1002            raise Exception('Could not locate path.\n'+getLogMessages())
1003
1004
1005# Freeing symbols defined for the sake of documentation
1006del Value.name,Value.name_raw,Value.offset,Value.data_size,Value.type,Value.flags
1007del Key.name,Key.name_raw,Key.offset,Key.modified,Key.flags
1008del Hive.root,Hive.modified,Hive.sequence1,Hive.sequence2,Hive.major_version,Hive.minor_version
Note: See TracBrowser for help on using the repository browser.