
    <io                     T   S r SSKrSSKrSSKrSSKrSSKrSSKrSSKJrJ	r	  SSK
Jr  SSKJrJrJrJr  SSKJrJrJr  SSKJr  SSKJr  SS	KJrJrJr  S
 r " S S\5      r\" S\ " 5       5      r!S r"S r#SS jr$S r%S r&S r'S r( " S S\5      r) " S S\5      r* " S S\5      r+g)z#Python STIX2 FileSystem Source/Sink    N)v20v21)	_STIXBase)DataSink
DataSourceDataSourceErrorDataStoreMixin)Filter	FilterSetapply_common_filters)parse)fp_serialize)format_datetimeget_type_from_idparse_into_datetimec                     [        U [        5      (       a  [        U 5      n [        U 5      n[        R
                  " SSU5      nU$ )z
Encapsulates a way to create unique filenames based on an object's
"modified" property value.  This should not include an extension.

Args:
    timestamp: A timestamp, as a datetime.datetime object or string.

z	[-T:\.Z ] )
isinstancestrr   r   resub)	timestamptss     T/home/james-whalen/.local/lib/python3.13/site-packages/stix2/datastore/filesystem.py_timestamp2filenamer      s<     )S!!'	2			#B	b"	%BI    c                   L    \ rS rSrSrSrSrS r\S 5       r	\S 5       r
S rS	rg
)AuthSet%   a  
Represents either a whitelist or blacklist of values, where/what we
must/must not search to find objects which match a query.  (Maybe "AuthSet"
isn't the right name, but determining authorization is a typical context in
which black/white lists are used.)

The set may be empty.  For a whitelist, this means you mustn't search
anywhere, which means the query was impossible to match, so you can skip
searching altogether.  For a blacklist, this means nothing is excluded
and you must search everywhere.

r      c                 ~    Uc  X l         [        R                  U l        gX-
  U l         [        R                  U l        g)aT  
Initialize this AuthSet from the given sets of allowed and/or
prohibited values.  The type of set (black or white) is determined
from the allowed and/or prohibited values given.

Args:
    allowed: A set of allowed values (or None if no allow filters
        were found in the query)
    prohibited: A set of prohibited values (not None)

N)_AuthSet__valuesr   BLACK_AuthSet__typeWHITE)selfallowed
prohibiteds      r   __init__AuthSet.__init__5   s0     ?&M!--DK $0DM!--DKr   c                     U R                   $ )z3
Get the values in this white/blacklist, as a set.
)r"   r&   s    r   valuesAuthSet.valuesL   s    
 }}r   c                     U R                   $ )z6
Get the type of set: AuthSet.WHITE or AuthSet.BLACK.
)r$   r,   s    r   	auth_typeAuthSet.auth_typeS   s    
 {{r   c                     SR                  U R                  [        R                  :X  a  SU R                  5      $ SU R                  5      $ )Nz
{}list: {}whiteblack)formatr0   r   r%   r-   r,   s    r   __repr__AuthSet.__repr__Z   sB    ""~~6GKK
 	
<CKK
 	
r   )__type__valuesN)__name__
__module____qualname____firstlineno____doc__r#   r%   r)   propertyr-   r0   r6   __static_attributes__ r   r   r   r   %   sE     EE(.    
r   r   c                 $   [        US5      =(       a    [        U[        5      (       + nU c8  [        5       n U(       a  U R	                  U5        U $ U R                  U5         U $ U(       a  U R                  U5        U $ U R                  U15        U $ )a  
Updates the given set of "allow" values.  The first time an update to the
set occurs, the value(s) are added.  Thereafter, since all filters are
implicitly AND'd, the given values are intersected with the existing allow
set, which may remove values.  At the end, it may even wind up empty.

Args:
    allow_set: The allow set, or None
    value: The value(s) to add (single value, or iterable of values)

Returns:
    The updated allow set (not None)

__iter__)hasattrr   r   setupdateaddintersection_update)	allow_setvalue
adding_seqs      r   _update_allowrL   e   s     
+ #uc""  E	U#  MM%   ))%0  ))5'2r   c                 
  ^ S=p[        5       n[        5       nU  GH4  nUR                  S:X  aV  UR                  S;   a  [        XR                  5      nM;  UR                  S:X  a  UR                  UR                  5        Mh  Mj  UR                  S:X  d  M|  UR                  S:X  a6  [        X%R                  5      n[        U[        UR                  5      5      nM  UR                  S:X  a  UR                  UR                  5        M  UR                  S:X  d  GM  [        X%R                  5      n[        US UR                   5       5      nGM7     [        X5      m[        X$5      nTR                  [        R                  :X  ay  UR                  [        R                  :X  a[  TR                  R                  S	 UR                   5       5        UR                  R                  U4S
 jUR                   5       5        TU4$ )a@  
Searches through all the filters, and creates white/blacklists of types and
IDs, which can be used to optimize the filesystem search.

Args:
    filters: An iterable of filter objects representing a query

Returns:
    A 2-tuple of AuthSet objects: the first is for object types, and
    the second is for object IDs.

Ntype)=inz!=idrO   rP   c              3   8   #    U  H  n[        U5      v   M     g 7fNr   .0id_s     r   	<genexpr>-_find_search_optimizations.<locals>.<genexpr>   s      $9F#(--   c              3   8   #    U  H  n[        U5      v   M     g 7frS   rT   rU   s     r   rX   rY      s      -
-;cS!!^rZ   c              3   ^   >#    U  H"  n[        U5      TR                  ;   d  M  Uv   M$     g 7frS   )r   r-   )rV   rW   	opt_typess     r   rX   rY      s,      +
)C$	(8(88 C>s   -	-)rE   r?   oprL   rJ   rG   r   r   r0   r%   r-   rH   )filtersallowed_typesallowed_idsprohibited_typesprohibited_idsfilter_opt_idsr]   s          @r   _find_search_optimizationsrf      s   " #'&MuUNv%zz[( -m]] Kt# $$W]]3 $ %zzS  ,KG -!$W]]3! t#""7==1t#+KG -! $9@$!) 4 8Ik2G gmm+.,, -
-4^^-
 	
 	** +
">>+
 	

 gr   c                    / nUR                   [        R                  :X  a  UR                   Hq  nXS-   n U(       aF  [        R
                  " [        R                  R                  X5      5      nU" UR                  5      nOSnU(       a  UR                  U5        Mq  Ms     U$ [        R                  " U 5       H  n
U(       a)  [        R                  R                  U
5      u  pX:w  a  M2  OU
nXR                  ;   a  MF   U(       aF  [        R
                  " [        R                  R                  X
5      5      nU" UR                  5      nOSnU(       a  UR                  U
5        M  M     U$ ! [         a+  n	U	R                  [        R                  :w  a  e  Sn	A	GMs  Sn	A	ff = f! [         a+  n	U	R                  [        R                  :w  a  e  Sn	A	GM  Sn	A	ff = f)a  
Search a directory (non-recursively), and find entries which match the
given criteria.

Args:
    parent_dir: The directory to search
    auth_set: an AuthSet instance, which represents a black/whitelist
        filter on filenames
    st_mode_test: A callable allowing filtering based on the type of
        directory entry.  E.g. just get directories, or just get files.  It
        will be passed the st_mode field of a stat() structure and should
        return True to include the file, or False to exclude it.  Easy thing to
        do is pass one of the stat module functions, e.g. stat.S_ISREG.  If
        None, don't filter based on entry type.
    ext: Determines how names from auth_set match up to directory
        entries, and allows filtering by extension.  The extension is added
        to auth_set values to obtain directory entries; it is removed from
        directory entries to obtain auth_set values.  In this way, auth_set
        may be treated as having only "basenames" of the entries.  Only entries
        having the given extension will be included in the results.  If not
        empty, the extension MUST include a leading ".".  The default is the
        empty string, which will result in direct comparisons, and no
        extension-based filtering.

Returns:
    (list): A list of directory entries matching the criteria.  These will not
        have any path info included; they will just be bare names.

Raises:
    OSError: If there are errors accessing directory contents or stat()'ing
        files

TN)r0   r   r%   r-   osstatpathjoinst_modeappendOSErrorerrnoENOENTlistdirsplitext)
parent_dirauth_setst_mode_testextresultsrJ   filenames	type_passeentry	auth_namethis_exts                r   _get_matching_dir_entriesr      sw   D GW]]*__E{HZ BCA ,QYY 7I $INN8,  %R N3 ZZ
+E&(gg&6&6u&=#	? # "	OO+Z ?@A ,QYY 7I $INN5) % ,2 N=  77ell* +2  77ell* +s1   A'E0A'F(0
F%:F  F%(
G2GGc                 L    [         R                  " USUS9 n[        R                  " U5      nSSS5        [        WX#5      nUS   S:X  a  US   S   n[        [        U/U 5      S5      nU$ ! , (       d  f       ND= f! [         a    [        SR                  U5      5      ef = f)	aY  
Read a STIX object from the given file, and check it against the given
filters.

Args:
    query: Iterable of filters
    filepath (str): Path to file to read
    allow_custom (bool): Whether to allow custom properties as well unknown
    custom objects.
    version (str): If present, it forces the parser to use the version
        provided. Otherwise, the library will make the best effort based
        on checking the "spec_version" property.
    encoding (str): The encoding to use when reading a file from the
        filesystem.

Returns:
    The (parsed) STIX object, if the object passes the filters.  If
    not, None is returned.

Raises:
    TypeError: If the file had invalid JSON
    IOError: If there are problems opening/reading the file
    stix2.exceptions.STIXError: If there were problems creating a STIX
        object from the JSON

r)encodingNzWSTIX JSON object at '{0}' could either not be parsed to JSON or was not valid STIX JSONrN   bundleobjectsr   )
ioopenjsonload
ValueError	TypeErrorr5   r   nextr   )	queryfilepathallow_customversionr   f	stix_jsonstix_objresults	            r   _check_object_from_filer     s    6
WWXsX6!		!I 7 Y6H8#I&q) &z594@FM! 76 
1171A
 	

s'   A> A-A> -
A;7A> ;A> >%B#c                    [         R                  " S[         R                  " U5      -   S-   [         R                  5      n[        R
                  " U 5       Hx  n[        R                  " [        R                  R                  X5      5      n[        R                  " UR                  5      (       d  M]  UR                  U5      (       d  Mu  Sn  U$    SnU$ )a  
Try to detect whether the given directory is for a versioned type of STIX
object.  This is done by looking for a directory whose name is a STIX ID
of the appropriate type.  If found, treat this type as versioned.  This
doesn't work when a versioned type directory is empty (it will be
mis-classified as unversioned), but this detection is only necessary when
reading/querying data.  If a directory is empty, you'll get no results
either way.

Args:
    type_path: A path to a directory containing one type of STIX object.
    type_name: The STIX type name.

Returns:
    True if the directory looks like it contains versioned objects; False
    if not.

Raises:
    OSError: If there are errors accessing directory contents or stat()'ing
        files
^z?--[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$TF)r   compileescapeIrh   rq   ri   rj   rk   S_ISDIRrl   match)	type_path	type_nameid_regexr|   ry   is_versioneds         r   _is_versioned_type_dirr   M  s    , zzryy##		 		H I&GGBGGLL23<<		""x~~e'<'<L  ' r   c           	         / n[        X[        R                  5      nU H  n[        R                  R                  X5      n	[        U	[        [        R                  S5      n
U
 HJ  n[        R                  R                  X5      n [        XX4U5      nU(       a  UR                  U5        MJ  ML     M     [        XX#XE5      nUR                  U5        U$ ! [         a*  nUR                  [        R                  :w  a  e  SnAM  SnAff = f)a  
Searches the given directory, which contains data for STIX objects of a
particular versioned type, and return any which match the query.

Args:
    query: The query to match against
    type_path: The directory with type-specific STIX object files
    auth_ids: Search optimization based on object ID
    allow_custom (bool): Whether to allow custom properties as well unknown
        custom objects.
    version (str): If present, it forces the parser to use the version
        provided. Otherwise, the library will make the best effort based
        on checking the "spec_version" property.
    encoding (str): The encoding to use when reading a file from the
        filesystem.

Returns:
    A list of all matching objects

Raises:
    stix2.exceptions.STIXError: If any objects had invalid content
    TypeError: If any objects had invalid content
    IOError: If there were any problems opening/reading files
    OSError: If there were any problems opening/reading files

.jsonN)r   ri   r   rh   rj   rk   _AUTHSET_ANYS_ISREGr   rm   IOErrorro   rp   _search_unversionedextend)r   r   auth_idsr   r   r   rw   id_dirsid_dirid_pathversion_filesversion_fileversion_pathr   r{   backcompat_resultss                   r   _search_versionedr   u  s    6 G'G '',,y1
 2\LL'
 *L77<<>L
2 
 NN8,  * 8 -(' NN%&N  77ell* +s   %C
D	DD	c                 N   / n[        X[        R                  S5      nU HJ  n[        R                  R                  X5      n	 [        X	UXE5      n
U
(       a  UR                  U
5        MJ  ML     U$ ! [         a*  nUR                  [        R                  :w  a  e  SnAM  SnAff = f)a  
Searches the given directory, which contains unversioned data, and return
any objects which match the query.

Args:
    query: The query to match against
    type_path: The directory with STIX files of unversioned type
    auth_ids: Search optimization based on object ID
    allow_custom (bool): Whether to allow custom properties as well unknown
        custom objects.
    version (str): If present, it forces the parser to use the version
        provided. Otherwise, the library will make the best effort based
        on checking the "spec_version" property.
    encoding (str): The encoding to use when reading a file from the
        filesystem.

Returns:
    A list of all matching objects

Raises:
    stix2.exceptions.STIXError: If any objects had invalid content
    TypeError: If any objects had invalid content
    IOError: If there were any problems opening/reading files
    OSError: If there were any problems opening/reading files

r   N)r   ri   r   rh   rj   rk   r   rm   r   ro   rp   )r   r   r   r   r   r   rw   id_filesid_filer   r   r{   s               r   r   r     s    : G(T\\H '',,y2		.H x(   N  	ww%,,& '	s   %A00
B$:BB$c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )FileSystemStorei  a+  Interface to a file directory of STIX objects.

FileSystemStore is a wrapper around a paired FileSystemSink
and FileSystemSource.

Args:
    stix_dir (str): path to directory of STIX objects
    allow_custom (bool): whether to allow custom STIX content to be
        pushed/retrieved. Defaults to True for FileSystemSource side
        (retrieving data) and False for FileSystemSink
        side(pushing data). However, when parameter is supplied, it
        will be applied to both FileSystemSource and FileSystemSink.
    bundlify (bool): whether to wrap objects in bundles when saving
        them. Default: False.
    encoding (str): The encoding to use when reading a file from the
        filesystem.

Attributes:
    source (FileSystemSource): FileSystemSource
    sink (FileSystemSink): FileSystemSink

c           	      `   > Uc  SnSnOU=pe[         [        U ]  [        XUS9[	        XUS9S9  g )NTF)stix_dirr   r   )r   r   bundlify)sourcesink)superr   r)   FileSystemSourceFileSystemSink)r&   r   r   r   r   allow_custom_sourceallow_custom_sink	__class__s          r   r)   FileSystemStore.__init__  sH    "& %6BBot-#Xbjk\de 	. 	
r   rA   )NFutf-8)r:   r;   r<   r=   r>   r)   r@   __classcell__r   s   @r   r   r     s    ,

 

r   r   c                   T   ^  \ rS rSrSrSU 4S jjr\S 5       rS	S jrS
S jr	Sr
U =r$ )r   i  a  Interface for adding/pushing STIX objects to file directory of STIX
objects.

Can be paired with a FileSystemSource, together as the two
components of a FileSystemStore.

Args:
    stix_dir (str): path to directory of STIX objects.
    allow_custom (bool): Whether to allow custom STIX content to be
        added to the FileSystemSource. Default: False
    bundlify (bool): Whether to wrap objects in bundles when saving them.
        Default: False.

c                    > [         [        U ]  5         [        R                  R                  U5      U l        X l        X0l        [        R                  R                  U R                  5      (       d  [        S5      eg )Nz+directory path for STIX data does not exist)r   r   r)   rh   rj   abspath	_stix_dirr   r   existsr   )r&   r   r   r   r   s       r   r)   FileSystemSink.__init__   sW    nd,.2( ww~~dnn--JKK .r   c                     U R                   $ rS   r   r,   s    r   r   FileSystemSink.stix_dir)      ~~r   c           	      .   [         R                  R                  U R                  US   5      nSU;   a1  [	        US   5      n[         R                  R                  X1S   5      nOUS   nUn[         R                  R                  XTS-   5      n[         R                  R                  U5      (       d  [         R                  " U5        U R                  (       aC  SU;   a  [        R                  " XR                  S9nO[        R                  " XR                  S9n[         R                  R                  U5      (       a  [        SR                  U5      5      e[        R                   " USUS	9 n[#        XS
USS9  SSS5        g! , (       d  f       g= f)zJWrite the given STIX object to a file in the STIX file directory.
        rN   modifiedrQ   r   spec_version)r   z&Attempted to overwrite file (!) at: {}w)moder   TF)prettyr   ensure_asciiN)rh   rj   rk   r   r   r   makedirsr   r   Bundler   r   isfiler   r5   r   r   r   )r&   r   r   type_dirrx   obj_dir	file_pathr   s           r   _check_path_and_write$FileSystemSink._check_path_and_write-  s%    77<<0@A !*8J+?@Hggll8d^<G~HGGGLLW*<=	ww~~g&&KK ==) ::h=N=NO::h=N=NO77>>)$$!"J"Q"QR["\]]WWYS8<THSXY =<<s   0F
Fc                 B   [        U[        R                  [        R                  45      (       a)  UR	                  S/ 5       H  nU R                  X2S9  M     g[        U[        5      (       a  U R                  U5        g[        U[        [        45      (       aK  [        XR                  US9n[        U[        5      (       a  U R                  XBS9  gU R                  U5        g[        U[        5      (       a  U H  nU R                  U5        M     g[        S5      e)ag  Add STIX objects to file directory.

Args:
    stix_data (STIX object OR dict OR str OR list): valid STIX 2.0 content
        in a STIX object (or list of), dict (or list of), or a STIX 2.0
        json encoded string.
    version (str): If present, it forces the parser to use the version
        provided. Otherwise, the library will make the best effort based
        on checking the "spec_version" property.

Note:
    ``stix_data`` can be a Bundle object, but each object in it will be
    saved separately; you will be able to retrieve any of the objects
    the Bundle contained, but not the Bundle itself.

r   )r   )r   r   zostix_data must be a STIX object (or list of), JSON formatted STIX (or list of), or a JSON formatted STIX bundleN)r   r   r   r   getrG   r   r   r   dictr   r   listr   )r&   	stix_datar   r   parsed_datas        r   rG   FileSystemSink.addN  s    " i#**cjj!9::%MM)R83 9 	9--&&y1	C;//	8I8ISZ[K+y116 **;7	4((%" & 2 r   )r   r   r   )FF)r   NN)r:   r;   r<   r=   r>   r)   r?   r   r   rG   r@   r   r   s   @r   r   r     s3    L  ZB, ,r   r   c                   ^   ^  \ rS rSrSrS	U 4S jjr\S 5       rS
S jrS
S jr	SS jr
SrU =r$ )r   i}  a  Interface for searching/retrieving STIX objects from a STIX object file
directory.

Can be paired with a FileSystemSink, together as the two
components of a FileSystemStore.

Args:
    stix_dir (str): path to directory of STIX objects
    allow_custom (bool): Whether to allow custom STIX content to be
        added to the FileSystemSink. Default: True
    encoding (str): The encoding to use when reading a file from the
        filesystem.

c                   > [         [        U ]  5         [        R                  R                  U5      U l        X l        X0l        [        R                  R                  U R                  5      (       d  [        SU R                  -  5      eg )Nz/directory path for STIX data does not exist: %s)r   r   r)   rh   rj   r   r   r   r   r   r   )r&   r   r   r   r   s       r   r)   FileSystemSource.__init__  sd    .02( ww~~dnn--NQUQ_Q__`` .r   c                     U R                   $ rS   r   r,   s    r   r   FileSystemSource.stix_dir  r   r   c                     U R                  XUS9nU(       a'  SUS   ;   nU(       a  [        US S9S   nU$ US   n U$ SnU$ )a{  Retrieve STIX object from file directory via STIX ID.

Args:
    stix_id (str): The STIX ID of the STIX object to be retrieved.
    _composite_filters (FilterSet): collection of filters passed from the parent
        CompositeDataSource, not user supplied
    version (str): If present, it forces the parser to use the version
        provided. Otherwise, the library will make the best effort based
        on checking the "spec_version" property.

Returns:
    (STIX object): STIX object that has the supplied STIX ID.
        The STIX object is loaded from its json file, parsed into
        a python STIX object and then returned

r   _composite_filtersr   r   c                     U S   $ )Nr   rA   )ks    r   <lambda>&FileSystemSource.get.<locals>.<lambda>  s    !J-r   )keyN)all_versionssorted)r&   stix_idr   r   all_datar   r   s          r   r   FileSystemSource.get  sg    " $$WRd$e &!4L!(0GHL 	 $A;  Hr   c                 >    [        SSU5      /nU R                  XBUS9$ )a  Retrieve STIX object from file directory via STIX ID, all versions.

Note: Since FileSystem sources/sinks don't handle multiple versions
of a STIX object, this operation is unnecessary. Pass call to get().

Args:
    stix_id (str): The STIX ID of the STIX objects to be retrieved.
    _composite_filters (FilterSet): collection of filters passed from
        the parent CompositeDataSource, not user supplied
    version (str): If present, it forces the parser to use the version
        provided. Otherwise, the library will make the best effort based
        on checking the "spec_version" property.

Returns:
    (list): of STIX objects that has the supplied STIX ID.
        The STIX objects are loaded from their json files, parsed into
        a python STIX objects and then returned

rQ   rO   r   )r
   r   )r&   r   r   r   r   s        r   r   FileSystemSource.all_versions  s)    ( c7+,zz%EWzXXr   c           	      F   / n[        U5      nU R                  (       a  UR                  U R                  5        U(       a  UR                  U5        [        U5      u  pV[	        U R
                  U[        R                  5      nU H  n[        R                  R                  U R
                  U5      n	[        X5      n
U
(       a$  [        XUU R                  UU R                  5      nO#[        XUU R                  UU R                  5      nUR!                  U5        M     U$ )a(  Search and retrieve STIX objects based on the complete query.

A "complete query" includes the filters from the query, the filters
attached to this FileSystemSource, and any filters passed from a
CompositeDataSource (i.e. _composite_filters).

Args:
    query (list): list of filters to search on
    _composite_filters (FilterSet): collection of filters passed from
        the CompositeDataSource, not user supplied
    version (str): If present, it forces the parser to use the version
        provided. Otherwise, the library will make the best effort based
        on checking the "spec_version" property.

Returns:
    (list): list of STIX objects that matches the supplied
        query. The STIX objects are loaded from their json files,
        parsed into a python STIX objects and then returned.

)r   r_   rG   rf   r   r   ri   r   rh   rj   rk   r   r   r   r   r   r   )r&   r   r   r   r   
auth_typesr   	type_dirsr   r   type_is_versionedtype_resultss               r   r   FileSystemSource.query  s    * %  <<IIdll#II()9%@
-NNJLL
	 "HT^^X>I 6y K 0h%%wMM   3h%%wMM 
 OOL) "" r   )r   r   r   )Tr   r   )NNN)r:   r;   r<   r=   r>   r)   r?   r   r   r   r   r@   r   r   s   @r   r   r   }  s8    a  BY.4 4r   r   )Nr   ),r>   ro   r   r   rh   r   ri   stix2r   r   
stix2.baser   stix2.datastorer   r   r   r	   stix2.datastore.filtersr
   r   r   stix2.parsingr   stix2.serializationr   stix2.utilsr   r   r   r   objectr   rE   r   rL   rf   r   r   r   r   r   r   r   r   rA   r   r   <module>r	     s    )  	  	 	      L K  , N N"9
f 9
z tSU# FCLM`,^%PAH1h!
n !
HiX iXHz Hr   