o bR@s&dZddlZddlmZddlmZddlmZmZm Z m Z ddl m Z m Z mZddlmZddlmZmZddlmZdd lmZmZmZd Zd Zd d ZGddde ZGdddZGdddejZ Gddde Z!ddZ"Gdddej#Z$dZ%Gdddej&Z'GdddZ(gdZ)dS) z A generic resource for publishing objects via XML-RPC. Maintainer: Itamar Shtull-Trauring @var Fault: See L{xmlrpclib.Fault} @type Fault: L{xmlrpclib.Fault} N)urlparse)BinaryBooleanDateTimeFault)defererrorprotocol)Logger)failurereflect) nativeString)httpresourceserverABcCs d|_|S)a\ Decorator to cause the request to be passed as the first argument to the method. If an I{xmlrpc_} method is wrapped with C{withRequest}, the request object is passed as the first argument to that method. For example:: @withRequest def xmlrpc_echo(self, request, s): return s @since: 10.2 T) withRequest)fr4/usr/lib/python3/dist-packages/twisted/web/xmlrpc.pyr"src@seZdZdZdS)NoSuchFunctionz1 There is no function by the given name. N)__name__ __module__ __qualname____doc__rrrrr5src@s eZdZdZddZddZdS)HandleraP Handle a XML-RPC request and store the state for a request in progress. Override the run() method and return result using self.result, a Deferred. We require this class since we're not using threads, so we can't encapsulate state in a running function if we're going to have to wait for results. For example, lets say we want to authenticate against twisted.cred, run a LDAP query and then pass its result to a database query, all as a result of a single XML-RPC command. We'd use a Handler instance to store the state of the running command. cGs||_t|_|j|dSN)rrDeferredresultrun)selfrargsrrr__init__Ls zHandler.__init__cGs|jtddS)NzImplement run() in subclasses)rerrbackNotImplementedError)r!r"rrrr Qsz Handler.runN)rrrrr#r rrrrr;s rc@s~eZdZdZdZdZdZdZdZe Z ddd Z d d Z d d Z ddZddZddZdddZddZddZddZdS)XMLRPCa A resource that implements XML-RPC. You probably want to connect this to '/RPC2'. Methods published can return XML-RPC serializable results, Faults, Binary, Boolean, DateTime, Deferreds, or Handler instances. By default methods beginning with 'xmlrpc_' are published. Sub-handlers for prefixed methods (e.g., system.listMethods) can be added with putSubHandler. By default, prefixes are separated with a '.'. Override self.separator to change this. @ivar allowNone: Permit XML translating of Python constant None. @type allowNone: C{bool} @ivar useDateTime: Present C{datetime} values as C{datetime.datetime} objects? @type useDateTime: C{bool} rr.)POSTFcCs"tj|i|_||_||_dSr)rResourcer# subHandlers allowNone useDateTime)r!r,r-rrrr#ws  zXMLRPC.__init__cC||j|<dSr)__dict__)r!namevaluerrr __setattr__}zXMLRPC.__setattr__cCr.r)r+)r!prefixhandlerrrr putSubHandlerr3zXMLRPC.putSubHandlercCs|j|dSr)r+get)r!r4rrr getSubHandlerr3zXMLRPC.getSubHandlercCst|jSr)listr+keysr!rrrgetSubHandlerPrefixesr3zXMLRPC.getSubHandlerPrefixesc Cs.|jdd|ddztj|j|jd\}}Wn#ty?}zt|j d|}| ||WYd}~tjSd}~wwz| |}Wntya}z| ||WYd}~tjSd}~wwg}| |jt|ddr}tj||g|R}n tj|g|R}| |j||j ||tjS)Nrs content-typetext/xml; charset=utf-8 use_datetimezCan't deserialize input: rF)contentseek setHeader xmlrpclibloadsreadr- ExceptionrFAILURE _cbRenderlookupProcedure notifyFinish addErrbackappendgetattrr maybeDeferred _ebRender addCallbackr NOT_DONE_YET) r!requestr" functionPatherfunctionresponseFaileddrrr render_POSTs6     zXMLRPC.render_POSTNc Cs|rdSt|tr |j}t|ts|f}zLz tj|d|jd}Wn$tyD}zt|jd|}tj|d|jd}WYd}~nd}~wwt|t rO| d}| ddt |f| |Wntyo|jdYnw|dS)NT)methodresponse allow_nonezCan't serialize output: utf8scontent-length%d) isinstancerrrrCdumpsr,rFrGstrencoderBlenwrite_logr finish)r!rrRrVr@rTrrrrrHs4       zXMLRPC._cbRendercCs,t|jtr |jS|jd|t|jdS)Nr]r)r^r1rrdr rG)r!r rrrrOs  zXMLRPC._ebRendercCs||jdkr'||jd\}}||}|dur"t|jd|||St|d|d}|s9t|jd|t|sEt|jd||S)aN Given a string naming a procedure, return a callable object for that procedure or raise NoSuchFunction. The returned object will be called, and should return the result of the procedure, a Deferred, or a Fault instance. Override in subclasses if you want your own policy. The base implementation that given C{'foo'}, C{self.xmlrpc_foo} will be returned. If C{procedurePath} contains C{self.separator}, the sub-handler for the initial prefix is used to search for the remaining path. If you override C{lookupProcedure}, you may also want to override C{listProcedures} to accurately report the procedures supported by your resource, so that clients using the I{system.listMethods} procedure receive accurate results. @since: 11.1 r'Nzno such subHandler %sz xmlrpc_%szprocedure %s not foundzprocedure %s not callable) find separatorsplitr8r NOT_FOUNDrIrMcallable)r! procedurePathr4r5rrrrrIs     zXMLRPC.lookupProcedurecCst|jdS)z\ Return a list of the names of all xmlrpc procedures. @since: 11.1 xmlrpc_)r prefixedMethodNames __class__r;rrrlistProceduresszXMLRPC.listProcedures)FFr)rrrrrjrGisLeafrhallowedMethodsr rdr#r2r6r8r<rXrHrOrIrprrrrr&Vs$   'r&c@sXeZdZdZddZddZdgge_ddZd d gge_d d Zdd gd d gge_d S) XMLRPCIntrospectiona Implement the XML-RPC Introspection API. By default, the methodHelp method returns the 'help' method attribute, if it exists, otherwise the __doc__ method attribute, if it exists, otherwise the empty string. To enable the methodSignature method, add a 'signature' method attribute containing a list of lists. See methodSignature's documentation for the format. Note the type strings should be XML-RPC types, not Python types. cCst|||_dS)z Implement Introspection support for an XMLRPC server. @param parent: the XMLRPC server to add Introspection support to. @type parent: L{XMLRPC} N)r&r#_xmlrpc_parent)r!parentrrrr#s  zXMLRPCIntrospection.__init__csdg}|jdfg}|r0|d\|fddD|fddD|s |S)zO Return a list of the method names implemented by this server. r]rcsg|]}|qSrr.0r0)r4rr sz:XMLRPCIntrospection.xmlrpc_listMethods..cs$g|]}||jfqSr)r8rhrvobjr4rrrxs)rtpopextendrpr<)r! functionstodorryrxmlrpc_listMethodss   z&XMLRPCIntrospection.xmlrpc_listMethodsarraycCs(|j|}t|ddpt|ddpdS)zW Return a documentation string describing the use of the given method. helpNrr]rtrIrMr!methodrrrxmlrpc_methodHelp!s z%XMLRPCIntrospection.xmlrpc_methodHelpstringcCs|j|}t|ddp dS)a+ Return a list of type signatures. Each type signature is a list of the form [rtype, type1, type2, ...] where rtype is the return type and typeN is the type of the Nth argument. If no signature information is available, the empty string is returned. signatureNr]rrrrrxmlrpc_methodSignature*s z*XMLRPCIntrospection.xmlrpc_methodSignatureN) rrrrr#rrrrrrrrrss     rscCs|dt|dS)z Add Introspection support to an XMLRPC server. @param xmlrpc: the XMLRPC server to add Introspection support to. @type xmlrpc: L{XMLRPC} systemN)r6rs)xmlrpcrrraddIntrospection<src@s,eZdZddZddZddZddZd S) QueryProtocolcCsd|_|d|jj|dd|d|jj|dd|jj}|ddt|f|jjrMd |jj|jj g}d d t |g}|d || |j|dS) Nr)s User-AgentsTwisted/XMLRPClibsHosts Content-typer=sContent-lengthr\:sBasic s Authorization) _response sendCommandfactorypath sendHeaderhostpayloadrbuserjoinpasswordbase64 b64encode endHeaders transportrc)r!rauth authHeaderrrrconnectionMadeGs   zQueryProtocol.connectionMadecCs|dkr |j||dSdS)Ns200)r badStatus)r!versionstatusmessagerrr handleStatusWszQueryProtocol.handleStatuscCs|j||_dS)z Handle the XML-RPC response received from the server. Specifically, disconnect from the server and store the XML-RPC response so that it can be properly handled when the disconnect is finished. N)rloseConnectionr)r!contentsrrrhandleResponse[s  zQueryProtocol.handleResponsecCsX|tjtjs|jd|tj|||j dur*|j d}|_ |j |dSdS)z The connection to the server has been lost. If we have a full response from the server, then parse it and fired a Deferred with the return value or C{Fault} that the server gave us. N) checkrConnectionDoneConnectionLostrclientConnectionLostr HTTPClientconnectionLostr parseResponse)r!reasonresponserrrrfs zQueryProtocol.connectionLostN)rrrrrrrrrrrrFs  rzP %s %s c@sJeZdZdZdZeZ      d ddZddZd d Z e Z d d Z dS) QueryFactorya XML-RPC Client Factory @ivar path: The path portion of the URL to which to post method calls. @type path: L{bytes} @ivar host: The value to use for the Host HTTP header. @type host: L{bytes} @ivar user: The username with which to authenticate with the server when making calls. @type user: L{bytes} or L{None} @ivar password: The password with which to authenticate with the server when making calls. @type password: L{bytes} or L{None} @ivar useDateTime: Accept datetime values as datetime.datetime objects. also passed to the underlying xmlrpclib implementation. Defaults to C{False}. @type useDateTime: C{bool} NFrc Csd|||_|_|||_|_t|tj||df|_t|jt r'|j d|_t ||_ | |_dS)a* @param method: The name of the method to call. @type method: C{str} @param allowNone: allow the use of None values in parameters. It's passed to the underlying xmlrpclib implementation. Defaults to C{False}. @type allowNone: C{bool} or L{None} @param args: the arguments to pass to the method. @type args: C{tuple} @param canceller: A 1-argument callable passed to the deferred as the canceller callback. @type canceller: callable or L{None} )rZr[N)rrrrpayloadTemplaterCr_rr^r`rarrdeferredr-) r!rrrrrr,r" cancellerr-rrrr#s    zQueryFactory.__init__cCst|jsdSztj||jddd}Wnty+|jd}|_|tYdSw|jd}|_||dS)Nr>r) rrCrDr- BaseExceptionr$r Failurecallback)r!rrrrrrrs zQueryFactory.parseResponsecCs*|jdur|jd}|_||dSdSr)rr$)r!_rrrrrrs z!QueryFactory.clientConnectionLostcCs"|jd}|_|t||dSr)rr$ ValueError)r!rrrrrrrszQueryFactory.badStatus)NNFrNF) rrrrrrr r#rrclientConnectionFailedrrrrrr~s '  rc@s2eZdZdZeZ      d ddZddZdS) Proxya A Proxy for making remote XML-RPC calls. Pass the URL of the remote XML-RPC server to the constructor. Use C{proxy.callRemote('foobar', *args)} to call remote method 'foobar' with *args. @ivar user: The username with which to authenticate with the server when making calls. If specified, overrides any username information embedded in C{url}. If not specified, a value may be taken from C{url} if present. @type user: L{bytes} or L{None} @ivar password: The password with which to authenticate with the server when making calls. If specified, overrides any password information embedded in C{url}. If not specified, a value may be taken from C{url} if present. @type password: L{bytes} or L{None} @ivar allowNone: allow the use of None values in parameters. It's passed to the underlying L{xmlrpclib} implementation. Defaults to C{False}. @type allowNone: C{bool} or L{None} @ivar useDateTime: Accept datetime values as datetime.datetime objects. also passed to the underlying L{xmlrpclib} implementation. Defaults to C{False}. @type useDateTime: C{bool} @ivar connectTimeout: Number of seconds to wait before assuming the connection has failed. @type connectTimeout: C{float} @ivar _reactor: The reactor used to create connections. @type _reactor: Object providing L{twisted.internet.interfaces.IReactorTCP} @ivar queryFactory: Object returning a factory for XML-RPC protocol. Use this for testing, or to manipulate the XML-RPC parsing behavior. For example, you may set this to a custom "debugging" factory object that reimplements C{parseResponse} in order to log the raw XML-RPC contents from the server before continuing on with parsing. Another possibility is to implement your own XML-RPC marshaller here to handle non-standard XML-RPC traffic. @type queryFactory: L{twisted.web.xmlrpc.QueryFactory} NF>@cCs0|dur ddlm}t|\}} } } } } | d}t|dkrB|dd}|d|_z|d|_WntyAd|_Ynwd|_|_|dd}|d|_ z t |d|_ Wn tykd|_ Ynw| |_ |j dvrwd|_ |d k|_ |dur||_|dur||_||_||_||_||_dS) aX @param url: The URL to which to post method calls. Calls will be made over SSL if the scheme is HTTPS. If netloc contains username or password information, these will be used to authenticate, as long as the C{user} and C{password} arguments are not specified. @type url: L{bytes} Nr)reactor@r)rN/shttps)twisted.internetrrrirbr{rrrrintportrsecurer,r-connectTimeout_reactor)r!urlrrr,r-rrschemenetlocrparamsqueryfragment netlocPartsuserpasshostportrrrr# s@             zProxy.__init__c sfdd}||j|j||j|j|j|||j |jrAddlm }|j t |jd}|j j t |j|jp7d||jdjS|j jt |j|jpLd|jdjS) a Call remote XML-RPC C{method} with given arguments. @return: a L{defer.Deferred} that will fire with the method response, or a failure if the method failed. Generally, the failure type will be L{Fault}, but you can also have an C{IndexError} on some buggy servers giving empty responses. If the deferred is cancelled before the request completes, the connection is closed and the deferred will fire with a L{defer.CancelledError}. csd_dSr)r disconnect)rW connectorrrrcancelKs z Proxy.callRemote..cancelr)ssl)hostnamei)timeoutP) queryFactoryrrrrr,r-rrroptionsForClientTLSr r connectSSLrr connectTCPr)r!rr"rrcontextFactoryrrr callRemote=s< zProxy.callRemote)NNFFrN)rrrrrrr#rrrrrrs/ 3r)r&rrrrrrr)*rr xmlrpc.clientclientrC urllib.parserrrrrrrrr twisted.loggerr twisted.pythonr r twisted.python.compatr twisted.webrrrrjrGrrrr*r&rsrrrr ClientFactoryrr__all__rrrrs2    "E 0Z