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

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

several fixes for pyregfi Windows portability
better error handling within pyregfi

File size: 28.9 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
97from pyregfi.structures import *
98
99import ctypes
100import ctypes.util
101
102## An enumeration of registry Value data types
103#
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
133
134
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
146def _strlist2charss(str_list):
147    ret_val = []
148    for s in str_list:
149        ret_val.append(s.encode('utf-8', 'replace'))
150
151    ret_val = (ctypes.c_char_p*(len(str_list)+1))(*ret_val)
152    # Terminate the char** with a NULL pointer
153    ret_val[-1] = 0
154
155    return ret_val
156
157
158def _charss2strlist(chars_pointer):
159    ret_val = []
160    i = 0
161    s = chars_pointer[i]
162    while s != None:
163        ret_val.append(s.decode('utf-8', 'replace'))
164        i += 1
165        s = chars_pointer[i]
166
167    return ret_val
168
169
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 not msgs:
180        return ''
181    return msgs.decode('utf-8')
182
183
184## Abstract class for most objects returned by the library
185class _StructureWrapper(object):
186    _hive = None
187    _base = None
188
189    def __init__(self, hive, base):
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())
198        self._hive = hive
199        self._base = base
200
201
202    # Memory management for most regfi structures is taken care of here
203    def __del__(self):
204        regfi.regfi_free_record(self._base)
205
206
207    # Any attribute requests not explicitly defined in subclasses gets passed
208    # to the equivalent REGFI_* structure defined in structures.py
209    def __getattr__(self, name):
210        return getattr(self._base.contents, name)
211
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
225    def __eq__(self, other):
226        return (type(self) == type(other)) and (self.offset == other.offset)
227
228
229    def __ne__(self, other):
230        return (not self.__eq__(other))
231
232
233class Key():
234    pass
235
236
237class Value():
238    pass
239
240
241## Registry security record and descriptor
242# XXX: Access to security descriptors not yet implemented
243class Security(_StructureWrapper):
244    pass
245
246## Abstract class for ValueList and SubkeyList
247class _GenericList(object):
248    _hive = None
249    _key_base = None
250    _length = None
251    _current = None
252
253    # implementation-specific functions for SubkeyList and ValueList
254    _fetch_num = None
255    _find_element = None
256    _get_element = None
257    _constructor = None
258
259    def __init__(self, key):
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)
269        self._hive = key._hive
270
271   
272    def __del__(self):
273        regfi.regfi_free_record(self._key_base)
274   
275
276    ## Length of list
277    def __len__(self):
278        return self._length
279
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
285    def __getitem__(self, name):
286        index = ctypes.c_uint32()
287        if isinstance(name, str):
288            name = name.encode('utf-8')
289
290        if name != None:
291            name = create_string_buffer(bytes(name))
292
293        if self._find_element(self._hive.file, self._key_base, 
294                              name, byref(index)):
295            return self._constructor(self._hive,
296                                     self._get_element(self._hive.file,
297                                                       self._key_base,
298                                                       index))
299        raise KeyError('')
300
301    def get(self, name, default):
302        try:
303            return self[name]
304        except KeyError:
305            return default
306   
307    def __iter__(self):
308        self._current = 0
309        return self
310   
311    def __next__(self):
312        if self._current >= self._length:
313            raise StopIteration('')
314
315        elem = self._get_element(self._hive.file, self._key_base,
316                                 ctypes.c_uint32(self._current))
317        self._current += 1
318        return self._constructor(self._hive, elem)
319   
320    # For Python 2.x
321    next = __next__
322
323
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):
340    _fetch_num = regfi.regfi_fetch_num_subkeys
341    _find_element = regfi.regfi_find_subkey
342    _get_element = regfi.regfi_get_subkey
343
344
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):
361    _fetch_num = regfi.regfi_fetch_num_values
362    _find_element = regfi.regfi_find_value
363    _get_element = regfi.regfi_get_value
364
365
366## Registry key
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.
374class Key(_StructureWrapper):
375    ## A @ref ValueList object representing the list of Values
376    #  stored on this Key
377    values = None
378
379    ## A @ref SubkeyList object representing the list of subkeys
380    #  stored on this Key
381    subkeys = None
382
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
399    def __init__(self, hive, base):
400        super(Key, self).__init__(hive, base)
401        self.values = ValueList(self)
402        self.subkeys = SubkeyList(self)
403
404    def __getattr__(self, name):
405        if name == "name":
406            ret_val = super(Key, self).__getattr__(name)
407
408            if ret_val == None:
409                ret_val = self.name_raw
410            else:
411                ret_val = ret_val.decode('utf-8', 'replace')
412               
413        elif name == "name_raw":
414            ret_val = super(Key, self).__getattr__(name)
415            length = super(Key, self).__getattr__('name_length')
416            ret_val = _buffer2bytearray(ret_val, length)
417       
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
424        return ret_val
425
426
427    ## Retrieves the Security properties for this key
428    def fetch_security(self):
429        return Security(self._hive,
430                        regfi.regfi_fetch_sk(self._hive.file, self._base))
431
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.
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
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)
460    def get_parent(self):
461        if self.is_root():
462            return None
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):
469        return (self._hive.root == self)
470
471
472## Registry value (metadata)
473#
474# These represent registry values (@ref REGFI_VK records) and provide
475# access to their associated data.
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.
481class Value(_StructureWrapper):
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    #
519    def fetch_data(self):
520        ret_val = None
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
525
526        if data_struct.interpreted_size == 0:
527            ret_val = None
528        elif data_struct.type in (DATA_TYPES.SZ, DATA_TYPES.EXPAND_SZ, DATA_TYPES.LINK):
529            # Unicode strings
530            ret_val = data_struct.interpreted.string.decode('utf-8', 'replace')
531        elif data_struct.type in (DATA_TYPES.DWORD, DATA_TYPES.DWORD_BE):
532            # 32 bit integers
533            ret_val = data_struct.interpreted.dword
534        elif data_struct.type == DATA_TYPES.QWORD:
535            # 64 bit integers
536            ret_val = data_struct.interpreted.qword
537        elif data_struct.type == DATA_TYPES.MULTI_SZ:
538            ret_val = _charss2strlist(data_struct.interpreted.multiple_string)
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):
543            ret_val = _buffer2bytearray(data_struct.interpreted.none,
544                                        data_struct.interpreted_size)
545
546        regfi.regfi_free_record(data_p)
547        return ret_val
548   
549
550    ## Retrieves raw representation of Value's data
551    #
552    # @return A bytearray containing the data
553    #
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
560
561        data_struct = data_p.contents
562        ret_val = _buffer2bytearray(data_struct.raw,
563                                    data_struct.size)
564        regfi.regfi_free_record(data_p)
565        return ret_val
566
567
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')
575
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
583# Avoids chicken/egg class definitions.
584# Also makes for convenient code reuse in these lists' parent classes.
585SubkeyList._constructor = Key
586ValueList._constructor = Value
587
588
589
590## Represents a single registry hive (file)
591class Hive():
592    file = None
593    raw_file = None
594    _root = None
595
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
626    def __init__(self, fh):
627        # The fileno method may not exist, or it may throw an exception
628        # when called if the file isn't backed with a descriptor.
629        fn = None
630        try:
631            # XXX: Native calls to Windows filenos don't seem to work. 
632            #      Need to investigate why.
633            if not is_win32 and hasattr(fh, 'fileno'):
634                fn = fh.fileno()
635        except:
636            pass
637
638        if fn != None:
639            self.file = regfi.regfi_alloc(fn, REGFI_ENCODING_UTF8)
640            if not self.file:
641                # XXX: switch to non-generic exception
642                raise Exception("Could not open registry file.  Current log:\n"
643                                + GetLogMessages())
644        else:
645            fh.seek(0)
646            self.raw_file = structures.REGFI_RAW_FILE()
647            self.raw_file.fh = fh
648            self.raw_file.seek = seek_cb_type(self.raw_file.cb_seek)
649            self.raw_file.read = read_cb_type(self.raw_file.cb_read)
650            self.file = regfi.regfi_alloc_cb(pointer(self.raw_file), REGFI_ENCODING_UTF8)
651            if not self.file:
652                # XXX: switch to non-generic exception
653                raise Exception("Could not open registry file.  Current log:\n"
654                                + GetLogMessages())
655
656
657    def __getattr__(self, name):
658        if name == "root":
659            # XXX: This creates reference loops.  Need to cache better inside regfi
660            #if self._root == None:
661            #    self._root = Key(self, regfi.regfi_get_rootkey(self.file))
662            #return self._root
663            return Key(self, regfi.regfi_get_rootkey(self.file))
664
665        elif name == "modified":
666            return regfi.regfi_nt2unix_time(byref(self._base.contents.mtime))
667
668        return getattr(self.file.contents, name)
669
670   
671    def __del__(self):
672        regfi.regfi_free(self.file)
673        if self.raw_file != None:
674            self.raw_file = None
675
676
677    def __iter__(self):
678        return HiveIterator(self)
679
680
681    ## Creates a @ref HiveIterator initialized at the specified path in
682    #  the hive.
683    #
684    # @param path A list of Key names which represent an absolute path within
685    #             the Hive
686    #
687    # @return A @ref HiveIterator which is positioned at the specified path.
688    #
689    # @exception Exception If the path could not be found/traversed
690    def subtree(self, path):
691        hi = HiveIterator(self)
692        hi.descend(path)
693        return hi
694
695
696## A special purpose iterator for registry hives
697#
698# Iterating over an object of this type causes all keys in a specific
699# hive subtree to be returned in a depth-first manner. These iterators
700# are typically created using the @ref Hive.subtree() function on a @ref Hive
701# object.
702#
703# HiveIterators can also be used to manually traverse up and down a
704# registry hive as they retain information about the current position in
705# the hive, along with which iteration state for subkeys and values for
706# every parent key.  See the @ref up and @ref down methods for more
707# information.
708class HiveIterator():
709    _hive = None
710    _iter = None
711    _iteration_root = None
712
713    def __init__(self, hive):
714        self._iter = regfi.regfi_iterator_new(hive.file, REGFI_ENCODING_UTF8)
715        if not self._iter:
716            raise Exception("Could not create iterator.  Current log:\n"
717                            + GetLogMessages())
718        self._hive = hive
719       
720    def __getattr__(self, name):
721        return getattr(self.file.contents, name)
722
723    def __del__(self):   
724        regfi.regfi_iterator_free(self._iter)
725
726    def __iter__(self):
727        self._iteration_root = None
728        return self
729
730    def __next__(self):
731        if self._iteration_root == None:
732            self._iteration_root = self.current_key()
733        elif not regfi.regfi_iterator_down(self._iter):
734            up_ret = regfi.regfi_iterator_up(self._iter)
735            while (up_ret and
736                   not regfi.regfi_iterator_next_subkey(self._iter)):
737                if self._iteration_root == self.current_key():
738                    self._iteration_root = None
739                    raise StopIteration('')
740                up_ret = regfi.regfi_iterator_up(self._iter)
741
742            if not up_ret:
743                self._iteration_root = None
744                raise StopIteration('')
745           
746            # XXX: Use non-generic exception
747            if not regfi.regfi_iterator_down(self._iter):
748                raise Exception('Error traversing iterator downward.'+
749                                ' Current log:\n'+ GetLogMessages())
750
751        regfi.regfi_iterator_first_subkey(self._iter)
752        return self.current_key()
753
754    # For Python 2.x
755    next = __next__
756
757    # XXX: Should add sanity checks on some of these traversal functions
758    #      to throw exceptions if a traversal/retrieval *should* have worked
759    #      but failed for some reason.
760
761    ## Descends the iterator to a subkey
762    #
763    # Descends the iterator one level to the current subkey, or a subkey
764    # specified by name.
765    #
766    # @param subkey_name If specified, locates specified subkey by name
767    #                    (via find_subkey()) and descends to it.
768    #
769    # @return True if successful, False otherwise
770    def down(self, subkey_name=None):
771        if subkey_name == None:
772            return regfi.regfi_iterator_down(self._iter)
773        else:
774            if name != None:
775                name = name.encode('utf-8')
776            return (regfi.regfi_iterator_find_subkey(self._iter, name) 
777                    and regfi.regfi_iterator_down(self._iter))
778
779
780    ## Causes the iterator to ascend to the current Key's parent
781    #
782    # @return True if successful, False otherwise
783    #
784    # @note The state of current subkeys and values at this level in the tree
785    #       is lost as a side effect.  That is, if you go up() and then back
786    #       down() again, current_subkey() and current_value() will return
787    #       default selections.
788    def up(self):
789        return regfi.regfi_iterator_up(self._iter)
790
791
792    ## Selects first subkey of current key
793    #
794    # @return A Key instance for the first subkey. 
795    #         None on error or if the current key has no subkeys.
796    def first_subkey(self):
797        if regfi.regfi_iterator_first_subkey(self._iter):
798            return self.current_subkey()
799        return None
800
801
802    ## Selects first value of current Key
803    #
804    # @return A Value instance for the first value. 
805    #         None on error or if the current key has no values.
806    def first_value(self):
807        if regfi.regfi_iterator_first_value(self._iter):
808            return self.current_value()
809        return None
810
811
812    ## Selects the next subkey in the current Key's list
813    #
814    # @return A Key instance for the next subkey.
815    #         None if there are no remaining subkeys or an error occurred.
816    def next_subkey(self):
817        if regfi.regfi_iterator_next_subkey(self._iter):
818            return self.current_subkey()
819        return None
820
821
822    ## Selects the next value in the current Key's list
823   
824    # @return A Value instance for the next value.
825    #         None if there are no remaining values or an error occurred.
826    def next_value(self):
827        if regfi.regfi_iterator_next_value(self._iter):
828            return self.current_value()
829        return None
830
831
832    ## Selects the first subkey which has the specified name
833    #
834    # @return A Key instance for the selected key.
835    #         None if it could not be located or an error occurred.
836    def find_subkey(self, name):
837        if name != None:
838            name = name.encode('utf-8')
839        if regfi.regfi_iterator_find_subkey(self._iter, name):
840            return self.current_subkey()
841        return None
842
843
844    ## Selects the first value which has the specified name
845    #
846    # @return A Value instance for the selected value.
847    #         None if it could not be located or an error occurred.
848    def find_value(self, name):
849        if name != None:
850            name = name.encode('utf-8')
851        if regfi.regfi_iterator_find_value(self._iter, name):
852            return self.current_value()
853        return None
854
855    ## Retrieves the currently selected subkey
856    #
857    # @return A Key instance of the current subkey
858    def current_subkey(self):
859        return Key(self._hive, regfi.regfi_iterator_cur_subkey(self._iter))
860
861    ## Retrieves the currently selected value
862    #
863    # @return A Value instance of the current value
864    def current_value(self):
865        return Value(self._hive, regfi.regfi_iterator_cur_value(self._iter))
866
867    ## Retrieves the current key
868    #
869    # @return A Key instance of the current position of the iterator
870    def current_key(self):
871        return Key(self._hive, regfi.regfi_iterator_cur_key(self._iter))
872
873
874    ## Traverse downward multiple levels
875    #
876    # This is more efficient than calling down() multiple times
877    #
878    # @param path A list of Key names which represent the path to descend
879    #
880    # @exception Exception If path could not be located
881    def descend(self, path):
882        cpath = _strlist2charss(path)
883
884        # XXX: Use non-generic exception
885        if not regfi.regfi_iterator_walk_path(self._iter, cpath):
886            raise Exception('Could not locate path.\n'+GetLogMessages())
887
888
889# Freeing symbols defined for the sake of documentation
890del Value.name,Value.name_raw,Value.offset,Value.data_size,Value.type,Value.flags
891del Key.name,Key.name_raw,Key.offset,Key.modified,Key.flags
892del Hive.root,Hive.modified,Hive.sequence1,Hive.sequence2,Hive.major_version,Hive.minor_version
Note: See TracBrowser for help on using the repository browser.