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

Last change on this file since 225 was 225, checked in by tim, 13 years ago

added test case for python callback read/seek
began adding windows support in pyregfi
improved win32 build target

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