a oeu@s\dZdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z m Z m Z m Z mZmZmZmZmZmZmZmZdZejejZejejZddlmZedZdZ d Z!d Z"d Z#d d Z$GdddZ%Gddde%Z&Gddde&Z'Gddde'Z(Gddde%Z)e'Z*ddZ+ddZ,ddZ-zddl.m/Z/m0Z0Wne1yVYn0dS)a Policies Note that Dispatchers are now implemented in "dispatcher.py", but are still documented here. Policies A policy is an object which manages the interaction between a public Python object, and COM . In simple terms, the policy object is the object which is actually called by COM, and it invokes the requested method, fetches/sets the requested property, etc. See the @win32com.server.policy.CreateInstance@ method for a description of how a policy is specified or created. Exactly how a policy determines which underlying object method/property is obtained is up to the policy. A few policies are provided, but you can build your own. See each policy class for a description of how it implements its policy. There is a policy that allows the object to specify exactly which methods and properties will be exposed. There is also a policy that will dynamically expose all Python methods and properties - even those added after the object has been instantiated. Dispatchers A Dispatcher is a level in front of a Policy. A dispatcher is the thing which actually receives the COM calls, and passes them to the policy object (which in turn somehow does something with the wrapped object). It is important to note that a policy does not need to have a dispatcher. A dispatcher has the same interface as a policy, and simply steps in its place, delegating to the real policy. The primary use for a Dispatcher is to support debugging when necessary, but without imposing overheads when not (ie, by not using a dispatcher at all). There are a few dispatchers provided - "tracing" dispatchers which simply prints calls and args (including a variation which uses win32api.OutputDebugString), and a "debugger" dispatcher, which can invoke the debugger when necessary. Error Handling It is important to realise that the caller of these interfaces may not be Python. Therefore, general Python exceptions and tracebacks aren't much use. In general, there is an Exception class that should be raised, to allow the framework to extract rich COM type error information. The general rule is that the **only** exception returned from Python COM Server code should be an Exception instance. Any other Python exception should be considered an implementation bug in the server (if not, it should be handled, and an appropriate Exception instance raised). Any other exception is considered "unexpected", and a dispatcher may take special action (see Dispatchers above) Occasionally, the implementation will raise the policy.error error. This usually means there is a problem in the implementation that the Python programmer should fix. For example, if policy is asked to wrap an object which it can not support (because, eg, it does not provide _public_methods_ or _dynamic_) then policy.error will be raised, indicating it is a Python programmers problem, rather than a COM error. zGreg Stein and Mark HammondN) DISPATCH_METHODDISPATCH_PROPERTYGETDISPATCH_PROPERTYPUTDISPATCH_PROPERTYPUTREFDISPID_COLLECTDISPID_CONSTRUCTORDISPID_DESTRUCTORDISPID_EVALUATEDISPID_NEWENUMDISPID_PROPERTYPUTDISPID_STARTENUMDISPID_UNKNOWN DISPID_VALUE) COMExceptionz errorzCLSID\%s\PythonCOMzCLSID\%s\PythonCOMPolicyzCLSID\%s\PythonCOMDispatcherzCLSID\%s\PythonCOMPathcCsz>ttjt|d}|D]}|tjvrtjd|qWntj yRYn0zttjt |}t |}Wntj yt }Yn0z"ttjt |}|rt |}Wntj yd}Yn0|r||d}n|d}|||S)aCreate a new instance of the specified IID The COM framework **always** calls this function to create a new instance for the specified CLSID. This function looks up the registry for the name of a policy, creates the policy, and asks the policy to create the specified object by calling the _CreateInstance_ method. Exactly how the policy creates the instance is up to the policy. See the specific policy documentation for more details. ;rN)win32api RegQueryValuewin32conHKEY_CLASSES_ROOT regAddnPathsplitsyspathinserterror regPolicy resolve_func DefaultPolicy regDispatcher_CreateInstance_)clsidreqIIDZ addnPathsZnewPathZpolicy dispatcherZretObjr$7C:\Program Files\Certbot\pkgs\win32com\server\policy.pyCreateInstanceqs8         r&c@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4S)5BasicWrapPolicyaThe base class of policies. Normally not used directly (use a child class, instead) This policy assumes we are wrapping another object as the COM server. This supports the delegation of the core COM entry points to either the wrapped object, or to a child class. This policy supports the following special attributes on the wrapped object _query_interface_ -- A handler which can respond to the COM 'QueryInterface' call. _com_interfaces_ -- An optional list of IIDs which the interface will assume are valid for the object. _invoke_ -- A handler which can respond to the COM 'Invoke' call. If this attribute is not provided, then the default policy implementation is used. If this attribute does exist, it is responsible for providing all required functionality - ie, the policy _invoke_ method is not invoked at all (and nor are you able to call it!) _getidsofnames_ -- A handler which can respond to the COM 'GetIDsOfNames' call. If this attribute is not provided, then the default policy implementation is used. If this attribute does exist, it is responsible for providing all required functionality - ie, the policy _getidsofnames_ method is not invoked at all (and nor are you able to call it!) IDispatchEx functionality: _invokeex_ -- Very similar to _invoke_, except slightly different arguments are used. And the result is just the _real_ result (rather than the (hresult, argErr, realResult) tuple that _invoke_ uses. This is the new, prefered handler (the default _invoke_ handler simply called _invokeex_) _getdispid_ -- Very similar to _getidsofnames_, except slightly different arguments are used, and only 1 property at a time can be fetched (which is all we support in getidsofnames anyway!) This is the new, prefered handler (the default _invoke_ handler simply called _invokeex_) _getnextdispid_- uses self._name_to_dispid_ to enumerate the DISPIDs cCs|dur||dS)zInitialise the policy object Params: object -- The object to wrap. May be None *iff* @BasicWrapPolicy._CreateInstance_@ will be called immediately after this to setup a brand new object N)_wrap_selfobjectr$r$r%__init__szBasicWrapPolicy.__init__c Cszttjt|}Wn$tjy:tdt|Yn0t|}||zt ||WStj y}zJ|j \}}}} ddl m } d|| |||f}t |||| WYd}~n d}~00dS)zCreates a new instance of a **wrapped** object This method looks up a "@win32com.server.policy.regSpec@" % clsid entry in the registry (using @DefaultPolicy@) z?The object is not correctly registered - %s key can not be readr)IIDToInterfaceNamezLThe object '%r' was created, but does not support the interface '%s'(%s): %sN)rrrrregSpecr call_funcr( pythoncomZ WrapObject com_errorargsZ win32com.utilr-) r*r!r"Z classSpecZmyobZxxx_todo_changemehrdescexcargr-r$r$r%r s,    z BasicWrapPolicy._CreateInstance_cCsi|_|}|_t|dr"|j|_t|dr4|j|_t|drF|j|_t|drX|j|_t|drj|j|_t|drg|_|jD]@}t |t j kr|ddkrt j |}n t |}|j|qng|_d S) zWraps up the specified object. This function keeps a reference to the passed object, and may interogate it to determine how to respond to COM requests, etc. _query_interface__invoke_ _invokeex__getidsofnames_ _getdispid__com_interfaces_r{N)_name_to_dispid__obj_hasattrr7r8r9r:r;r<type pywintypesIIDTyper0ZInterfaceNamesZMakeIIDappend)r*r+obir$r$r%r(s*           zBasicWrapPolicy._wrap_cCs||jvrdS||S)zThe main COM entry-point for QueryInterface. This checks the _com_interfaces_ attribute and if the interface is not specified there, it calls the derived helper _query_interface_ r)r<r7r*Ziidr$r$r%_QueryInterface_s z BasicWrapPolicy._QueryInterface_cCsdS)zCalled if the object does not provide the requested interface in _com_interfaces_, and does not provide a _query_interface_ handler. Returns a result to the COM framework indicating the interface is not supported. rr$rGr$r$r%r7sz!BasicWrapPolicy._query_interface_cCsTt|tdkrDz|j|}Wn tyBttjddYn0|||||S)zVThe main COM entry-point for Invoke. This calls the _invoke_ helper. Member not foundscoder4)rAr>lowerKeyErrorrwinerrorDISP_E_MEMBERNOTFOUNDr8r*dispidlcidwFlagsr2r$r$r%_Invoke_$s  zBasicWrapPolicy._Invoke_c Cstd|||||ddfSNS_OKr9rQr$r$r%r83szBasicWrapPolicy._invoke_cCs&t|dkrttjdd|||S)zThe main COM entry-point for GetIDsOfNames. This checks the validity of the arguments, and calls the _getidsofnames_ helper. rz$Cannot support member argument namesrK)lenrrOZDISP_E_INVALIDr:r*namesrSr$r$r%_GetIDsOfNames_9s  zBasicWrapPolicy._GetIDsOfNames_cCs||ddfSNrr;r[r$r$r%r:EszBasicWrapPolicy._getidsofnames_cCs |||SNr_r*namefdexr$r$r% _GetDispID_MszBasicWrapPolicy._GetDispID_cCs4z|j|WSty.ttjdYn0dSNrL)r>rMrNrrOZDISP_E_UNKNOWNNAMErar$r$r%r;Ps zBasicWrapPolicy._getdispid_cCsXt|tdkrDz|j|}Wn tyBttjddYn0|||||||S)zZThe main COM entry-point for InvokeEx. This calls the _invokeex_ helper. rIrJrK)rAr>rMrNrrOrPr9r*rRrSrTr2kwargsserviceProviderr$r$r% _InvokeEx_Xs  zBasicWrapPolicy._InvokeEx_cCs tddS)z]A stub for _invokeex_ - should never be called. Simply raises an exception. z0This class does not provide _invokeex_ semanticsN)rrgr$r$r%r9gszBasicWrapPolicy._invokeex_cCs |||Sr`)_deletememberbyname_rar$r$r%_DeleteMemberByName_osz$BasicWrapPolicy._DeleteMemberByName_cCsttjddSrerrOZ E_NOTIMPLrar$r$r%rkrsz$BasicWrapPolicy._deletememberbyname_cCs ||Sr`)Z_deletememberbydispidr*idr$r$r%_DeleteMemberByDispID_usz&BasicWrapPolicy._DeleteMemberByDispID_cCsttjddSrermrnr$r$r%_deletememberbydispid_xsz&BasicWrapPolicy._deletememberbydispid_cCs |||Sr`)_getmemberproperties_r*rorcr$r$r%_GetMemberProperties_{sz%BasicWrapPolicy._GetMemberProperties_cCsttjddSrermrsr$r$r%rr~sz%BasicWrapPolicy._getmemberproperties_cCs ||Sr`)_getmembername_r*rRr$r$r%_GetMemberName_szBasicWrapPolicy._GetMemberName_cCsttjddSrermrvr$r$r%ruszBasicWrapPolicy._getmembername_cCs |||Sr`)_getnextdispid_)r*rcrRr$r$r%_GetNextDispID_szBasicWrapPolicy._GetNextDispID_cCst|j}|t|vr(|t|tkr8|dSz|||dWStyjtt j dYnt ytt j dYn0dS)Nrrrf) listr>valuessortr removeindex ValueErrorrrOZ E_UNEXPECTED IndexErrorZS_FALSE)r*rcrRZidsr$r$r%rxs   zBasicWrapPolicy._getnextdispid_cCs|Sr`)Z_getnamespaceparentr*r$r$r%_GetNameSpaceParent_sz$BasicWrapPolicy._GetNameSpaceParent_cCsttjddSrermrr$r$r%_getnamespaceparent_sz$BasicWrapPolicy._getnamespaceparent_N)__name__ __module__ __qualname____doc__r,r r(rHr7rUr8r]r:rdr;rjr9rlrkrprqrtrrrwruryrxrrr$r$r$r%r's4" )   r'c@s eZdZdZddZddZdS)MappedWrapPolicyaKWraps an object using maps to do its magic This policy wraps up a Python object, using a number of maps which translate from a Dispatch ID and flags, into an object to call/getattr, etc. It is the responsibility of derived classes to determine exactly how the maps are filled (ie, the derived classes determine the map filling policy. This policy supports the following special attributes on the wrapped object _dispid_to_func_/_dispid_to_get_/_dispid_to_put_ -- These are dictionaries (keyed by integer dispid, values are string attribute names) which the COM implementation uses when it is processing COM requests. Note that the implementation uses this dictionary for its own purposes - not a copy - which means the contents of these dictionaries will change as the object is used. cCsdt|||j}t|dr&|j|_ni|_t|dr@|j|_ni|_t|drZ|j|_ni|_dS)N_dispid_to_func__dispid_to_get__dispid_to_put_)r'r(r?r@rrr)r*r+rEr$r$r%r(s       zMappedWrapPolicy._wrap_cCsL||jvr|j|S||jvr(|j|S||jvr<|j|SttjddSre)rrrrrOrPrvr$r$r%rus      z MappedWrapPolicy._getmembername_N)rrrrr(rur$r$r$r%rsrc@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)DesignatedWrapPolicyaPA policy which uses a mapping to link functions and dispid A MappedWrappedPolicy which allows the wrapped object to specify, via certain special named attributes, exactly which methods and properties are exposed. All a wrapped object need do is provide the special attributes, and the policy will handle everything else. Attributes: _public_methods_ -- Required, unless a typelib GUID is given -- A list of strings, which must be the names of methods the object provides. These methods will be exposed and callable from other COM hosts. _public_attrs_ A list of strings, which must be the names of attributes on the object. These attributes will be exposed and readable and possibly writeable from other COM hosts. _readonly_attrs_ -- A list of strings, which must also appear in _public_attrs. These attributes will be readable, but not writable, by other COM hosts. _value_ -- A method that will be called if the COM host requests the "default" method (ie, calls Invoke with dispid==DISPID_VALUE) _NewEnum -- A method that will be called if the COM host requests an enumerator on the object (ie, calls Invoke with dispid==DISPID_NEWENUM.) It is the responsibility of the method to ensure the returned object conforms to the required Enum interface. _typelib_guid_ -- The GUID of the typelibrary with interface definitions we use. _typelib_version_ -- A tuple of (major, minor) with a default of 1,1 _typelib_lcid_ -- The LCID of the typelib, default = LOCALE_USER_DEFAULT _Evaluate -- Dunno what this means, except the host has called Invoke with dispid==DISPID_EVALUATE! See the COM documentation for details. cCst|dd}|durft|dd\}}t|dd}ddlm}ddt|d gD}||||||}ng}t||t|d st|dstd |j D]\} } | |j | <q|j D]\} } | |j | <q|j D]\} } | |j | <q|D]n\} } } | |j | <| tkr*| |j| <q| ttfvrD| |j | <q| tkrZ| |j | <qtd | | fqt|d rd |j t<d |j t<t|drt|j d<d|jt<t|drt|j d<d|jt<|d} t|dr\t|dr|j} ng} |jD]Z} |j | } | dur:| } | |j | <|| } | |j | <| | vr| |j | <qt|d gD]F} |j | } | dur| } | |j | <|| } | |j| <qhd|_dS)N_typelib_guid__typelib_version_rrZ_typelib_lcid_r) universalcSs(g|] }t|tjkr|ds|qS)r=)rArBrC startswith).0rFr$r$r% sz/DesignatedWrapPolicy._wrap_..r<Z_public_methods_zwObject does not support DesignatedWrapPolicy, as it does not have either _public_methods_ or _typelib_guid_ attributes.zunexpected invkind: %d (%s)_value__NewEnumZ_newenumZ _Evaluate _evaluatei_public_attrs__readonly_attrs_)getattrwin32comrZRegisterInterfacesrr(r@rritemsr>rMrrrrrrrrr r r _allocnextdispidrrget _typeinfos_)r*rEtlb_guid tlb_major tlb_minorZtlb_lcidrZ interfacesZuniversal_datarRrbZinvkindZ next_dispidreadonlyr$r$r%r(s~                              zDesignatedWrapPolicy._wrap_c Cst|jdd}|durgSt|jdd\}}t|||}|}|jjD]@}z&||\}}|durr|gWSWqJtjyYqJ0qJgS)Nrrr)rr?r0ZLoadRegTypeLibZ GetTypeCompr<ZBindTyper1) r*rrrZtlbZtypecompZinameZ type_infoZ type_compr$r$r%_build_typeinfos_Cs z&DesignatedWrapPolicy._build_typeinfos_cCs|jdur||_t|jSr`)rrrZrr$r$r%_GetTypeInfoCount_Vs  z'DesignatedWrapPolicy._GetTypeInfoCount_cCsD|jdur||_|dks*|t|jkr6ttjdd|j|fS)Nrrf)rrrZrrOZDISP_E_BADINDEX)r*r~rSr$r$r% _GetTypeInfo_[s    z"DesignatedWrapPolicy._GetTypeInfo_cCs0|d}||jvr||jvr||jvr|SqdSNr)rrr)r*Z last_dispidr$r$r%rbsz%DesignatedWrapPolicy._allocnextdispidc Cs|t@rz|j|}Wn&ty<|t@s8ttjdYn0zt|j|}Wnt ylttjdYn0z ||WSt y} z2t |  ddkrt d| ||fWYd} ~ n d} ~ 00|t@r$z|j|} WntyttjdYn0t|j| } t| tjkr | |} | S|ttB@rz|j|} Wn ty`ttjdYn0tt|j| dtjkrtt|jd| dtjkrt|jd| } | |nt|j| |ddSttjdddS)NrfZ argumentsrz'** TypeError %s calling function %r(%r)Setzinvalid wFlagsrK)rrrNrrrOrPrr?AttributeError TypeErrorstrfindprintrrAtypes MethodTyperrrsetattrZ E_INVALIDARG) r*rRrSrTr2kwArgsrifuncnamefuncvrbZretobfnr$r$r%r9lsV         zDesignatedWrapPolicy._invokeex_N) rrrrr(rrrrr9r$r$r$r%rs!S rc@s eZdZdZddZddZdS)EventHandlerPolicyasThe default policy used by event handlers in the win32com.client package. In addition to the base policy, this provides argument conversion semantics for params * dispatch params are converted to dispatch objects. * Unicode objects are converted to strings (1.5.2 and earlier) NOTE: Later, we may allow the object to override this process?? c Csg}|D]r}t|} | tkr2ddl} | j|}n>| tkrpz ddl} | j|tj}Wntj ynYn0| |qt ||fSr^) rA IDispatchTypeZwin32com.clientZclientZDispatch IUnknownTypeZQueryInterfacer0 IID_IDispatchrrDtuple) r*r2rrRrSrTriretr6Zarg_typerr$r$r%_transform_args_s   z#EventHandlerPolicy._transform_args_c Cs.|||||||\}}t|||||||Sr`)rrr9)r*rRrSrTr2rrir$r$r%r9s  zEventHandlerPolicy._invokeex_N)rrrrrr9r$r$r$r%rs rc@s0eZdZdZddZddZddZdd Zd S) DynamicPolicya*A policy which dynamically (ie, at run-time) determines public interfaces. A dynamic policy is used to dynamically dispatch methods and properties to the wrapped object. The list of objects and properties does not need to be known in advance, and methods or properties added to the wrapped object after construction are also handled. The wrapped object must provide the following attributes: _dynamic_ -- A method that will be called whenever an invoke on the object is called. The method is called with the name of the underlying method/property (ie, the mapping of dispid to/from name has been resolved.) This name property may also be '_value_' to indicate the default, and '_NewEnum' to indicate a new enumerator is requested. cCs>t||t|jds tdd|_|_tdtdi|_ dS)N _dynamic_z*Object does not support Dynamic COM Policyirr) r'r(r@r?r_next_dynamic_Z _min_dynamic_rr _dyn_dispid_to_name_r)r$r$r%r(s   zDynamicPolicy._wrap_cCsT|}z |j|WStyN|jd}|_||j|<||j|<|YS0dSr)rMr>rNrr)r*rbrcZlnamerRr$r$r%r;s    zDynamicPolicy._getdispid_c Cstd|||||ddfSrVrXrQr$r$r%r8szDynamicPolicy._invoke_cCsBz|j|}Wn ty.ttjddYn0|j||||S)NrJrK)rrNrrOrPr?r)r*rRrSrTr2rhrirbr$r$r%r9s  zDynamicPolicy._invokeex_N)rrrrr(r;r8r9r$r$r$r%rs   rcCs\z:|d}|d|}||dd}t|}t||WStyVt|YS0dS)zResolve a function by name Given a function specified by 'module.function', return a callable object (ie, the function itself) .Nr)rindex_import_modulerrglobals)specidxmnamefnamemoduler$r$r%r s    rcGs t||S)zrCall a function specified by name. Call a function specified by 'module.function' and return the result. )r)rr2r$r$r%r/sr/cCst|tj|S)zImport a module just like the 'import' statement. Having this function is much nicer for importing arbitrary modules than using the 'exec' keyword. It is more efficient and obvious to the reader. ) __import__rmodules)rr$r$r%r(sr)DispatcherTraceDispatcherWin32trace)2r __author__rrr0rBrrrOrrrrrrrr r r r r rrYZTypeIIDsrrZ IID_IUnknownr exceptionrrrr.rrrr&r'rrrrrrr/rr#rr ImportErrorr$r$r$r%sFD<   +.[)8