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

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

fixed Value attribute brokenness

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