source: trunk/python/pyregfi/__init__.py @ 222

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

added a lot of documentation for pyregfi and a few more attributes

File size: 28.2 KB
RevLine 
[204]1#!/usr/bin/env python
2
[210]3## @package pyregfi
4# Python interface to the regfi library.
5#
6
[221]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#
[204]95import sys
[219]96import time
[214]97import weakref
[204]98from pyregfi.structures import *
99
100import ctypes
101import ctypes.util
102
[221]103## An enumeration of registry Value data types
[210]104#
[221]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
[205]134
135
[208]136def _buffer2bytearray(char_pointer, length):
137    if length == 0 or char_pointer == None:
138        return None
139   
140    ret_val = bytearray(length)
141    for i in range(0,length):
142        ret_val[i] = char_pointer[i][0]
143
144    return ret_val
145
146
[215]147def _strlist2charss(str_list):
148    ret_val = []
149    for s in str_list:
150        ret_val.append(s.encode('utf-8', 'replace'))
151
[220]152    ret_val = (ctypes.c_char_p*(len(str_list)+1))(*ret_val)
[215]153    # Terminate the char** with a NULL pointer
154    ret_val[-1] = 0
155
156    return ret_val
157
158
[209]159def _charss2strlist(chars_pointer):
160    ret_val = []
161    i = 0
162    s = chars_pointer[i]
163    while s != None:
[213]164        ret_val.append(s.decode('utf-8', 'replace'))
[209]165        i += 1
166        s = chars_pointer[i]
[208]167
[209]168    return ret_val
[208]169
[210]170
[221]171## Retrieves messages produced by regfi during parsing and interpretation
172#
173# The regfi C library may generate log messages stored in a special thread-safe
174# global data structure.  These messages should be retrieved periodically or
175# after each major operation by callers to determine if any errors or warnings
176# should be reported to the user.  Failure to retrieve these could result in
177# excessive memory consumption.
178def GetLogMessages():
179    msgs = regfi.regfi_log_get_str()
180    if msgs == None:
181        return ''
182    return msgs.decode('utf-8')
183
184
185## Abstract class for most objects returned by the library
[212]186class _StructureWrapper(object):
[214]187    _hive = None
188    _base = None
[206]189
[207]190    def __init__(self, hive, base):
[215]191        if not hive:
192            raise Exception("Could not create _StructureWrapper,"
193                            + " hive is NULL.  Current log:\n"
194                            + GetLogMessages())
195        if not base:
196            raise Exception("Could not create _StructureWrapper,"
197                            + " base is NULL.  Current log:\n"
198                            + GetLogMessages())
[214]199        self._hive = hive
200        self._base = base
[206]201
[221]202    # Memory management for most regfi structures is taken care of here
[206]203    def __del__(self):
[214]204        regfi.regfi_free_record(self._base)
[206]205
[221]206    # Any attribute requests not explicitly defined in subclasses gets passed
207    # to the equivalent REGFI_* structure defined in structures.py
[206]208    def __getattr__(self, name):
[214]209        return getattr(self._base.contents, name)
[221]210   
211    ## Test for equality
212    #
213    # Records returned by pyregfi may be compared with one another.  For example:
214    # @code
215    #  >>> key2 = key1.subkeys['child']
216    #  >>> key1 == key2
217    #  False
218    #  >>> key1 != key2
219    #  True
220    #  >>> key1 == key2.get_parent()
221    #  True
222    # @endcode
[206]223    def __eq__(self, other):
224        return (type(self) == type(other)) and (self.offset == other.offset)
225
226    def __ne__(self, other):
227        return (not self.__eq__(other))
228
[208]229
[221]230class Key():
[206]231    pass
232
[221]233
234class Value():
[206]235    pass
236
[221]237
238## Registry security record and descriptor
239# XXX: Access to security descriptors not yet implemented
[206]240class Security(_StructureWrapper):
241    pass
242
[221]243## Abstract class for ValueList and SubkeyList
[212]244class _GenericList(object):
[214]245    _hive = None
246    _key = None
247    _length = None
248    _current = None
[207]249
[221]250    # implementation-specific functions for SubkeyList and ValueList
[214]251    _fetch_num = None
252    _find_element = None
253    _get_element = None
254    _constructor = None
[208]255
[207]256    def __init__(self, key):
[214]257        self._hive = key._hive
258
259        # Normally it's good to avoid cyclic references like this
260        # (key.list.key...) but in this case it makes ctypes memory
261        # management easier to reference the Key instead of the base
262        # structure.  We use a weak reference in order to allow for garbage
263        # collection, since value/subkey lists should not be usable if their
264        # parent Key is freed anyway.
265
[207]266        # XXX: check for NULL here, throw an exception if so.
[214]267        self._key = weakref.proxy(key)
268        self._length = self._fetch_num(key._base)
[207]269   
[221]270   
271    ## Length of list
[207]272    def __len__(self):
[214]273        return self._length
[207]274
[221]275
276    ## Retrieves a list element by name
277    #
278    # @return the first element whose name matches, or None if the element
279    #         could not be found
[207]280    def __getitem__(self, name):
[220]281        index = ctypes.c_uint32()
[208]282        if isinstance(name, str):
283            name = name.encode('utf-8')
284
[209]285        if name != None:
286            name = create_string_buffer(bytes(name))
287
[220]288        if self._find_element(self._hive.file, self._key._base, 
289                              name, byref(index)):
290            return self._constructor(self._hive,
[214]291                                     self._get_element(self._hive.file,
[216]292                                                       self._key._base,
[214]293                                                       index))
[207]294        raise KeyError('')
295
[209]296    def get(self, name, default):
297        try:
298            return self[name]
299        except KeyError:
300            return default
301   
[207]302    def __iter__(self):
[214]303        self._current = 0
[207]304        return self
305   
306    def __next__(self):
[214]307        if self._current >= self._length:
[207]308            raise StopIteration('')
309
[214]310        elem = self._get_element(self._hive.file, self._key._base,
[220]311                                 ctypes.c_uint32(self._current))
[214]312        self._current += 1
313        return self._constructor(self._hive, elem)
[207]314   
[212]315    # For Python 2.x
[214]316    next = __next__
[207]317
[212]318
[221]319## The list of subkeys associated with a Key
320#
321# This attribute is both iterable:
322# @code
323#   for k in myKey.subkeys:
324#     ...
325# @endcode
326# and accessible as a dictionary:
327# @code
328#   mySubkey = myKey.subkeys["keyName"]
329# @endcode
330#
331# @note SubkeyLists should never be accessed directly and only exist
332#       in association with a parent Key object.  Do not retain references to
333#       SubkeyLists.  Instead, access them via their parent Key at all times.
334class SubkeyList(_GenericList):
[214]335    _fetch_num = regfi.regfi_fetch_num_subkeys
336    _find_element = regfi.regfi_find_subkey
337    _get_element = regfi.regfi_get_subkey
[208]338
339
[221]340## The list of values associated with a Key
341#
342# This attribute is both iterable:
343# @code
344#   for v in myKey.values:
345#     ...
346# @endcode
347# and accessible as a dictionary:
348# @code
349#   myValue = myKey.values["valueName"]
350# @endcode
351#
352# @note ValueLists should never be accessed directly and only exist
353#       in association with a parent Key object.  Do not retain references to
354#       ValueLists.  Instead, access them via their parent Key at all times.
355class ValueList(_GenericList):
[214]356    _fetch_num = regfi.regfi_fetch_num_values
357    _find_element = regfi.regfi_find_value
358    _get_element = regfi.regfi_get_value
[208]359
360
[215]361## Registry key
[221]362# These represent registry keys (@ref REGFI_NK records) and provide
363# access to their subkeys, values, and other metadata.
364#
365# @note Value instances may provide access to more than the attributes
366#       documented here.  However, undocumented attributes may change over time
367#       and are not officially supported.  If you need access to an attribute
368#       not shown here, see pyregfi.structures.
[207]369class Key(_StructureWrapper):
[221]370    ## A @ref ValueList object representing the list of Values
371    #  stored on this Key
[207]372    values = None
[221]373
374    ## A @ref SubkeyList object representing the list of subkeys
375    #  stored on this Key
[208]376    subkeys = None
[207]377
[221]378    ## The raw Key name as an uninterpreted bytearray
379    name_raw = (b"...")
380   
381    ## The name of the Key as a (unicode) string
382    name = "..."
383   
384    ## The absolute file offset of the Key record's cell in the Hive file
385    offset = 0xCAFEBABE
386
387    ## This Key's last modified time represented as the number of seconds
388    #  since the UNIX epoch in UTC; similar to what time.time() returns
389    modified = 1300000000.123456
390
391    ## The NK record's flags field
392    flags = 0x10110001
393
[207]394    def __init__(self, hive, base):
395        super(Key, self).__init__(hive, base)
[221]396        self.values = ValueList(self)
397        self.subkeys = SubkeyList(self)
[207]398
[208]399    def __getattr__(self, name):
400        if name == "name":
[219]401            ret_val = super(Key, self).__getattr__(name)
402
[209]403            if ret_val == None:
404                ret_val = self.name_raw
405            else:
[213]406                ret_val = ret_val.decode('utf-8', 'replace')
[209]407               
[208]408        elif name == "name_raw":
[219]409            ret_val = super(Key, self).__getattr__(name)
[208]410            length = super(Key, self).__getattr__('name_length')
411            ret_val = _buffer2bytearray(ret_val, length)
412       
[219]413        elif name == "modified":
414            ret_val = regfi.regfi_nt2unix_time(byref(self._base.contents.mtime))
415
416        else:
417            ret_val = super(Key, self).__getattr__(name)
418
[208]419        return ret_val
420
[221]421
422    ## Retrieves the Security properties for this key
[207]423    def fetch_security(self):
[214]424        return Security(self._hive,
[215]425                        regfi.regfi_fetch_sk(self._hive.file, self._base))
[207]426
[221]427
428    ## Retrieves the class name for this key
429    #
430    # Class names are typically stored as UTF-16LE strings, so these are decoded
431    # into proper python (unicode) strings.  However, if this fails, a bytearray
432    # is instead returned containing the raw buffer stored for the class name.
433    #
434    # @return The class name as a string or bytearray.  None if a class name
435    #         doesn't exist or an unrecoverable error occurred during retrieval.
[219]436    def fetch_classname(self):
437        ret_val = None
438        cn_p = regfi.regfi_fetch_classname(self._hive.file, self._base)
439        if cn_p:
440            cn_struct = cn_p.contents
441            if cn_struct.interpreted:
442                ret_val = cn_struct.interpreted.decode('utf-8', 'replace')
443            else:
444                ret_val = _buffer2bytearray(cn_struct.raw,
445                                            cn_struct.size)
446            regfi.regfi_free_record(cn_p)
447
448        return ret_val
449
[221]450
451    ## Retrieves this key's parent key
452    #
453    # @return The parent's Key instance or None if current key is root
454    #         (or an error occured)
[215]455    def get_parent(self):
[218]456        if self.is_root():
457            return None
[215]458        parent_base = regfi.regfi_get_parentkey(self._hive.file, self._base)
459        if parent_base:
460            return Key(self._hive, parent_base)
461        return None
462
463    def is_root(self):
[218]464        return (self._hive.root == self)
[215]465
466
[210]467## Registry value (metadata)
468#
469# These represent registry values (@ref REGFI_VK records) and provide
470# access to their associated data.
[221]471#
472# @note Value instances may provide access to more than the attributes
473#       documented here.  However, undocumented attributes may change over time
474#       and are not officially supported.  If you need access to an attribute
475#       not shown here, see pyregfi.structures.
[208]476class Value(_StructureWrapper):
[221]477    ## The raw Value name as an uninterpreted bytearray
478    name_raw = (b"...")
479   
480    ## The name of the Value as a (unicode) string
481    name = "..."
482   
483    ## The absolute file offset of the Value record's cell in the Hive file
484    offset = 0xCAFEBABE
485
486    ## The length of data advertised in the VK record
487    data_size = 0xCAFEBABE
488
489    ## An integer which represents the data type for this Value's data
490    # Typically this value is one of 12 types defined in @ref DATA_TYPES,
491    # but in some cases (the SAM hive) it may be used for other purposes
492    type = DATA_TYPES.NONE
493
494    ## The VK record's flags field
495    flags = 0x10110001
496
497    ## Retrieves the Value's data according to advertised type
498    #
499    # Data is loaded from its cell(s) and then interpreted based on the data
500    # type recorded in the Value.  It is not uncommon for data to be stored with
501    # the wrong type or even with invalid types.  If you have difficulty
502    # obtaining desired data here, use @ref fetch_raw_data().
503    #
504    # @return The interpreted representation of the data as one of several
505    #         possible Python types, as listed below.  None if any failure
506    #         occurred during extraction or conversion.
507    #
508    # @retval string for SZ, EXPAND_SZ, and LINK
509    # @retval int for DWORD, DWORD_BE, and QWORD
510    # @retval list(string) for MULTI_SZ
511    # @retval bytearray for NONE, BINARY, RESOURCE_LIST,
512    #         FULL_RESOURCE_DESCRIPTOR, and RESOURCE_REQUIREMENTS_LIST
513    #
[219]514    def fetch_data(self):
[209]515        ret_val = None
[219]516        data_p = regfi.regfi_fetch_data(self._hive.file, self._base)
517        if not data_p:
518            return None
519        data_struct = data_p.contents
[208]520
[219]521        if data_struct.interpreted_size == 0:
522            ret_val = None
[221]523        elif data_struct.type in (DATA_TYPES.SZ, DATA_TYPES.EXPAND_SZ, DATA_TYPES.LINK):
[219]524            # Unicode strings
525            ret_val = data_struct.interpreted.string.decode('utf-8', 'replace')
[221]526        elif data_struct.type in (DATA_TYPES.DWORD, DATA_TYPES.DWORD_BE):
[219]527            # 32 bit integers
528            ret_val = data_struct.interpreted.dword
[221]529        elif data_struct.type == DATA_TYPES.QWORD:
[219]530            # 64 bit integers
531            ret_val = data_struct.interpreted.qword
[221]532        elif data_struct.type == DATA_TYPES.MULTI_SZ:
[219]533            ret_val = _charss2strlist(data_struct.interpreted.multiple_string)
[221]534        elif data_struct.type in (DATA_TYPES.NONE, DATA_TYPES.RESOURCE_LIST,
535                                  DATA_TYPES.FULL_RESOURCE_DESCRIPTOR,
536                                  DATA_TYPES.RESOURCE_REQUIREMENTS_LIST,
537                                  DATA_TYPES.BINARY):
[219]538            ret_val = _buffer2bytearray(data_struct.interpreted.none,
539                                        data_struct.interpreted_size)
[209]540
[219]541        regfi.regfi_free_record(data_p)
542        return ret_val
[221]543   
544
545    ## Retrieves raw representation of Value's data
546    #
547    # @return A bytearray containing the data
548    #
[219]549    def fetch_raw_data(self):
550        ret_val = None
551        # XXX: should we load the data without interpretation instead?
552        data_p = regfi.regfi_fetch_data(self._hive.file, self._base)
553        if not data_p:
554            return None
[209]555
[219]556        data_struct = data_p.contents
557        ret_val = _buffer2bytearray(data_struct.raw,
558                                    data_struct.size)
559        regfi.regfi_free_record(data_p)
[208]560        return ret_val
561
[221]562
[219]563    def __getattr__(self, name):
564        ret_val = super(Value, self).__getattr__(name)
565        if name == "name":
566            if ret_val == None:
567                ret_val = self.name_raw
568            else:
569                ret_val = ret_val.decode('utf-8', 'replace')
[208]570
[219]571        elif name == "name_raw":
572            length = super(Value, self).__getattr__('name_length')
573            ret_val = _buffer2bytearray(ret_val, length)
574
575        return ret_val
576
577
[208]578# Avoids chicken/egg class definitions.
579# Also makes for convenient code reuse in these lists' parent classes.
[221]580SubkeyList._constructor = Key
581ValueList._constructor = Value
[208]582
583
584
[210]585## Represents a single registry hive (file)
586class Hive():
[204]587    file = None
588    raw_file = None
[218]589    _root = None
590
[221]591    ## The root Key of this Hive
592    root = None
593
594    ## This Hives's last modified time represented as the number of seconds
595    #  since the UNIX epoch in UTC; similar to what time.time() returns
596    modified = 1300000000.123456
597
598    ## First sequence number
599    sequence1 = 12345678
600
601    ## Second sequence number
602    sequence2 = 12345678
603
604    ## Major version
605    major_version = 1
606
607    ## Minor version
608    minor_version = 5
609
610    # XXX: Possibly add a second or factory function which opens a
611    #      hive file for you
612
613    ## Constructor
614    #
615    # @param fh A Python file object.  The constructor first looks for a valid
616    #           fileno attribute on this object and uses it if possible. 
617    #           Otherwise, the seek and read methods are used for file
618    #           access.
619    #
620    # @note Supplied file must be seekable
[204]621    def __init__(self, fh):
[205]622        try:
[221]623            # The fileno method may not exist, or it may throw an exception
624            # when called if the file isn't backed with a descriptor.
[205]625            if hasattr(fh, 'fileno'):
[213]626                self.file = regfi.regfi_alloc(fh.fileno(), REGFI_ENCODING_UTF8)
[205]627                return
628        except:
629            pass
[204]630       
[205]631        self.raw_file = structures.REGFI_RAW_FILE()
632        self.raw_file.fh = fh
633        self.raw_file.seek = seek_cb_type(self.raw_file.cb_seek)
634        self.raw_file.read = read_cb_type(self.raw_file.cb_read)
[213]635        self.file = regfi.regfi_alloc_cb(self.raw_file, REGFI_ENCODING_UTF8)
[204]636
[221]637
[204]638    def __getattr__(self, name):
[218]639        if name == "root":
640            if self._root == None:
641                self._root = Key(self, regfi.regfi_get_rootkey(self.file))
642            return self._root
643
[221]644        elif name == "modified":
645            return regfi.regfi_nt2unix_time(byref(self._base.contents.mtime))
646
[204]647        return getattr(self.file.contents, name)
[221]648
[205]649   
[210]650    def __del__(self):
[205]651        regfi.regfi_free(self.file)
652        if self.raw_file != None:
[213]653            self.raw_file = None
[204]654
[221]655
[205]656    def __iter__(self):
657        return HiveIterator(self)
[204]658
[215]659
[210]660    ## Creates a @ref HiveIterator initialized at the specified path in
[221]661    #  the hive.
[210]662    #
[221]663    # @param path A list of Key names which represent an absolute path within
664    #             the Hive
665    #
666    # @return A @ref HiveIterator which is positioned at the specified path.
667    #
668    # @exception Exception If the path could not be found/traversed
[206]669    def subtree(self, path):
670        hi = HiveIterator(self)
671        hi.descend(path)
672        return hi
[205]673
[206]674
[210]675## A special purpose iterator for registry hives
676#
677# Iterating over an object of this type causes all keys in a specific
678# hive subtree to be returned in a depth-first manner. These iterators
679# are typically created using the @ref Hive.subtree() function on a @ref Hive
680# object.
681#
682# HiveIterators can also be used to manually traverse up and down a
683# registry hive as they retain information about the current position in
684# the hive, along with which iteration state for subkeys and values for
685# every parent key.  See the @ref up and @ref down methods for more
686# information.
[205]687class HiveIterator():
[220]688    _hive = None
689    _iter = None
690    _iteration_root = None
[205]691
692    def __init__(self, hive):
[220]693        self._iter = regfi.regfi_iterator_new(hive.file, REGFI_ENCODING_UTF8)
694        if self._iter == None:
[205]695            raise Exception("Could not create iterator.  Current log:\n"
696                            + GetLogMessages())
[214]697        self._hive = hive
[205]698       
699    def __getattr__(self, name):
700        return getattr(self.file.contents, name)
701
702    def __del__(self):   
[220]703        regfi.regfi_iterator_free(self._iter)
[205]704
705    def __iter__(self):
[220]706        self._iteration_root = None
[205]707        return self
708
709    def __next__(self):
[220]710        if self._iteration_root == None:
711            self._iteration_root = self.current_key()
712        elif not regfi.regfi_iterator_down(self._iter):
713            up_ret = regfi.regfi_iterator_up(self._iter)
[206]714            while (up_ret and
[220]715                   not regfi.regfi_iterator_next_subkey(self._iter)):
716                if self._iteration_root == self.current_key():
717                    self._iteration_root = None
[206]718                    raise StopIteration('')
[220]719                up_ret = regfi.regfi_iterator_up(self._iter)
[205]720
721            if not up_ret:
[221]722                self._iteration_root = None
[205]723                raise StopIteration('')
724           
[210]725            # XXX: Use non-generic exception
[220]726            if not regfi.regfi_iterator_down(self._iter):
[205]727                raise Exception('Error traversing iterator downward.'+
728                                ' Current log:\n'+ GetLogMessages())
729
[220]730        regfi.regfi_iterator_first_subkey(self._iter)
[206]731        return self.current_key()
[205]732
[212]733    # For Python 2.x
[214]734    next = __next__
[212]735
[221]736    # XXX: Should add sanity checks on some of these traversal functions
737    #      to throw exceptions if a traversal/retrieval *should* have worked
738    #      but failed for some reason.
739
740    ## Descends the iterator to a subkey
741    #
742    # Descends the iterator one level to the current subkey, or a subkey
743    # specified by name.
744    #
745    # @param subkey_name If specified, locates specified subkey by name
746    #                    (via find_subkey()) and descends to it.
747    #
748    # @return True if successful, False otherwise
[220]749    def down(self, subkey_name=None):
750        if subkey_name == None:
751            return regfi.regfi_iterator_down(self._iter)
752        else:
753            if name != None:
754                name = name.encode('utf-8')
755            return (regfi.regfi_iterator_find_subkey(self._iter, name) 
756                    and regfi.regfi_iterator_down(self._iter))
[206]757
[221]758
759    ## Causes the iterator to ascend to the current Key's parent
760    #
761    # @return True if successful, False otherwise
762    #
763    # @note The state of current subkeys and values at this level in the tree
764    #       is lost as a side effect.  That is, if you go up() and then back
765    #       down() again, current_subkey() and current_value() will return
766    #       default selections.
[206]767    def up(self):
[220]768        return regfi.regfi_iterator_up(self._iter)
[206]769
[221]770
771    ## Selects first subkey of current key
772    #
773    # @return A Key instance for the first subkey. 
774    #         None on error or if the current key has no subkeys.
[220]775    def first_subkey(self):
776        if regfi.regfi_iterator_first_subkey(self._iter):
777            return self.current_subkey()
778        return None
779
[221]780
781    ## Selects first value of current Key
782    #
783    # @return A Value instance for the first value. 
784    #         None on error or if the current key has no values.
[220]785    def first_value(self):
786        if regfi.regfi_iterator_first_value(self._iter):
787            return self.current_value()
788        return None
789
[221]790
791    ## Selects the next subkey in the current Key's list
792    #
793    # @return A Key instance for the next subkey.
794    #         None if there are no remaining subkeys or an error occurred.
[220]795    def next_subkey(self):
796        if regfi.regfi_iterator_next_subkey(self._iter):
797            return self.current_subkey()
798        return None
799
[221]800
801    ## Selects the next value in the current Key's list
802   
803    # @return A Value instance for the next value.
804    #         None if there are no remaining values or an error occurred.
[220]805    def next_value(self):
806        if regfi.regfi_iterator_next_value(self._iter):
807            return self.current_value()
808        return None
809
[221]810
811    ## Selects the first subkey which has the specified name
812    #
813    # @return A Key instance for the selected key.
814    #         None if it could not be located or an error occurred.
[220]815    def find_subkey(self, name):
816        if name != None:
817            name = name.encode('utf-8')
818        if regfi.regfi_iterator_find_subkey(self._iter, name):
819            return self.current_subkey()
820        return None
821
[221]822
823    ## Selects the first value which has the specified name
824    #
825    # @return A Value instance for the selected value.
826    #         None if it could not be located or an error occurred.
[220]827    def find_value(self, name):
828        if name != None:
829            name = name.encode('utf-8')
830        if regfi.regfi_iterator_find_value(self._iter, name):
831            return self.current_value()
832        return None
833
[221]834    ## Retrieves the currently selected subkey
835    #
836    # @return A Key instance of the current subkey
[220]837    def current_subkey(self):
838        return Key(self._hive, regfi.regfi_iterator_cur_subkey(self._iter))
839
[221]840    ## Retrieves the currently selected value
841    #
842    # @return A Value instance of the current value
[220]843    def current_value(self):
844        return Value(self._hive, regfi.regfi_iterator_cur_value(self._iter))
845
[221]846    ## Retrieves the current key
847    #
848    # @return A Key instance of the current position of the iterator
[220]849    def current_key(self):
850        return Key(self._hive, regfi.regfi_iterator_cur_key(self._iter))
851
[221]852
853    ## Traverse downward multiple levels
854    #
855    # This is more efficient than calling down() multiple times
856    #
857    # @param path A list of Key names which represent the path to descend
858    #
859    # @exception Exception If path could not be located
[206]860    def descend(self, path):
[215]861        cpath = _strlist2charss(path)
[206]862
[210]863        # XXX: Use non-generic exception
[220]864        if not regfi.regfi_iterator_walk_path(self._iter, cpath):
[206]865            raise Exception('Could not locate path.\n'+GetLogMessages())
[221]866
867
868# Freeing symbols defined for the sake of documentation
869del Value.name,Value.name_raw,Value.offset,Value.data_size,Value.type,Value.flags
870del Key.name,Key.name_raw,Key.offset,Key.modified,Key.flags
871del Hive.root,Hive.modified,Hive.sequence1,Hive.sequence2,Hive.major_version,Hive.minor_version
Note: See TracBrowser for help on using the repository browser.