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

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

added a convenience openHive function in pyregfi
standardized static function names
improvements to scons release script and library versioning

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