a 97a@s2dZddlmZmZmZmZddlmZmZddl m Z m Z m Z m Z mZddlmZddlmmmZddlmZddlZddlZddlZddlZddlZddlZz ddlZWneydZYn0d,d d Zd d Z Gd dde!Z"GdddeZ#Gdddej$e"Z%Gddde%Z&Gddde"Z'Gdddej(Z)Gddde!Z*Gddde#Z+Gddde%e*Z,Gdd d e'e*Z-e.d!kr.ddl/Z/Gd"d#d#Z0e%d$Ze1e2e1d%d&d'ej3e0dd(e4e5d)e5d*z e6Wn.e7y,e5d+e8e9dYn0dS)-aK Ported using Python-Future from the Python 3.3 standard library. XML-RPC Servers. This module can be used to create simple XML-RPC servers by creating a server and either installing functions, a class instance, or by extending the SimpleXMLRPCServer class. It can also be used to handle XML-RPC requests in a CGI environment using CGIXMLRPCRequestHandler. The Doc* classes can be used to create XML-RPC servers that serve pydoc-style documentation in response to HTTP GET requests. This documentation is dynamically generated based on the functions and methods registered with the server. A list of possible usage patterns follows: 1. Install functions: server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') server.serve_forever() 2. Install an instance: class MyFuncs: def __init__(self): # make all of the sys functions available through sys.func_name import sys self.sys = sys def _listMethods(self): # implement this method so that system.listMethods # knows to advertise the sys methods return list_public_methods(self) + \ ['sys.' + method for method in list_public_methods(self.sys)] def pow(self, x, y): return pow(x, y) def add(self, x, y) : return x + y server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() server.register_instance(MyFuncs()) server.serve_forever() 3. Install an instance with custom dispatch method: class Math: def _listMethods(self): # this method must be present for system.listMethods # to work return ['add', 'pow'] def _methodHelp(self, method): # this method must be present for system.methodHelp # to work if method == 'add': return "add(2,3) => 5" elif method == 'pow': return "pow(x, y[, z]) => number" else: # By convention, return empty # string if no help is available return "" def _dispatch(self, method, params): if method == 'pow': return pow(*params) elif method == 'add': return params[0] + params[1] else: raise ValueError('bad method') server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() server.register_instance(Math()) server.serve_forever() 4. Subclass SimpleXMLRPCServer: class MathServer(SimpleXMLRPCServer): def _dispatch(self, method, params): try: # We are forcing the 'export_' prefix on methods that are # callable through XML-RPC to prevent potential security # problems func = getattr(self, 'export_' + method) except AttributeError: raise Exception('method "%s" is not supported' % method) else: return func(*params) def export_add(self, x, y): return x + y server = MathServer(("localhost", 8000)) server.serve_forever() 5. CGI script: server = CGIXMLRPCRequestHandler() server.register_function(pow) server.handle_request() )absolute_importdivisionprint_functionunicode_literals)intstr)Faultdumpsloads gzip_encode gzip_decode)BaseHTTPRequestHandlerN) socketserverTcCsF|r|d}n|g}|D]&}|dr6td|qt||}q|S)aGresolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr). ._z(attempt to access private attribute "%s")split startswithAttributeErrorgetattr)objattrallow_dotted_namesattrsiry/private/var/folders/s6/9n5zrl012gv99k63s4q6ccsd4s6mqz/T/pip-target-f5cq3f2q/lib/python/future/backports/xmlrpc/server.pyresolve_dotted_attributes    rcsfddtDS)zkReturns a list of attribute strings, found in the specified object, which represent callable attributescs(g|] }|dstt|r|qS)r)rcallabler).0memberrrr s z'list_public_methods..)dirr rr rlist_public_methodssr#c@speZdZdZdddZdddZddd Zd d Zd d ZdddZ ddZ ddZ ddZ ddZ ddZdS)SimpleXMLRPCDispatchera&Mix-in class that dispatches XML-RPC requests. This class is used to register XML-RPC method handlers and then to dispatch them. This class doesn't need to be instanced directly when used by SimpleXMLRPCServer but it can be instanced when used by the MultiPathXMLRPCServer FNcCs&i|_d|_||_|pd|_||_dSNutf-8)funcsinstance allow_noneencodinguse_builtin_typesselfr)r*r+rrr__init__s  zSimpleXMLRPCDispatcher.__init__cCs||_||_dS)aRegisters an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. N)r(r)r-r(rrrrregister_instances!z(SimpleXMLRPCDispatcher.register_instancecCs|dur|j}||j|<dS)zRegisters a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function. N)__name__r')r-functionnamerrrregister_functionsz(SimpleXMLRPCDispatcher.register_functioncCs|j|j|j|jddS)zRegisters the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html )zsystem.listMethodszsystem.methodSignaturezsystem.methodHelpN)r'updatesystem_listMethodssystem_methodSignaturesystem_methodHelpr-rrr register_introspection_functionss z7SimpleXMLRPCDispatcher.register_introspection_functionscCs|jd|jidS)zRegisters the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208zsystem.multicallN)r'r4system_multicallr8rrrregister_multicall_functionssz3SimpleXMLRPCDispatcher.register_multicall_functionsc CszPt||jd\}}|dur(|||}n |||}|f}t|d|j|jd}Wnnty}zt||j|jd}WYd}~nBd}~0t\}} } ttdd|| f|j|jd}Yn0| |jS)aDispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior. )r+N)methodresponser)r*)r)r*%s:%sr*r)) r r+ _dispatchr r)r*rsysexc_infoencode) r-datadispatch_methodpathparamsmethodresponsefaultexc_type exc_valueexc_tbrrr_marshaled_dispatchs(     z*SimpleXMLRPCDispatcher._marshaled_dispatchcCs^t|j}|jdurVt|jdr8|t|jO}nt|jdsV|tt|jO}t|S)zwsystem.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.N _listMethodsr@)setr'keysr(hasattrrOr#sorted)r-methodsrrrr5s   z)SimpleXMLRPCDispatcher.system_listMethodscCsdS)a#system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.zsignatures not supportedr)r- method_namerrrr6*s z-SimpleXMLRPCDispatcher.system_methodSignaturecCsd}||jvr|j|}nV|jdurpt|jdr<|j|St|jdspzt|j||j}WntynYn0|dur|dSt|SdS)zsystem.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.N _methodHelpr@) r'r(rRrVrrrpydocgetdoc)r-rUrHrrrr77s$       z(SimpleXMLRPCDispatcher.system_methodHelpc Csg}|D]}|d}|d}z||||gWqtyl}z ||j|jdWYd}~qd}~0t\}}} |dd||fdYq0q|S)zsystem.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208 methodNamerG) faultCode faultStringNr<r>)appendr@rr[r\rArB) r- call_listresultscallrUrGrJrKrLrMrrrr:Vs(   z'SimpleXMLRPCDispatcher.system_multicallc Csd}z|j|}Wnbtyt|jdurpt|jdrH|j||YSzt|j||j}WntynYn0Yn0|dur||Std|dS)aDispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. Nr@zmethod "%s" is not supported) r'KeyErrorr(rRr@rrr Exception)r-rHrGfuncrrrr@vs$     z SimpleXMLRPCDispatcher._dispatch)FNF)F)N)NN)r0 __module__ __qualname____doc__r.r/r3r9r;rNr5r6r7r:r@rrrrr$s  $   %  r$c@sfeZdZdZdZdZdZdZe dej ej BZ ddZ d d Zd d Zd dZddZdddZdS)SimpleXMLRPCRequestHandlerzSimple XML-RPC request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. )/z/RPC2ixTz \s* ([^\s;]+) \s* #content-coding (;\s* q \s*=\s* ([0-9\.]+))? #q cCs^i}|jdd}|dD]<}|j|}|r|d}|rFt|nd}|||d<q|S)NzAccept-EncodingrW,g?r<)headersgetr aepatternmatchgroupfloat)r-rZaeerovrrraccept_encodingss  z+SimpleXMLRPCRequestHandler.accept_encodingscCs|jr|j|jvSdSdS)NT) rpc_pathsrFr8rrris_rpc_path_valids z,SimpleXMLRPCRequestHandler.is_rpc_path_validc Cs|s|dSzd}t|jd}g}|rht||}|j|}|sLqh|||t|d8}q,d |}| |}|durWdS|j |t |dd|j}Wnty8}zx|dt|j dr|j jr|d t|t} t| d d d } |d | |d d|WYd}~nd}~00|d|dd|jdurt||jkr|dd} | rzt|}|ddWntyYn0|d tt|||j|dS)zHandles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Nizcontent-lengthrir@i_send_traceback_headerz X-exceptionASCIIbackslashreplacez X-tracebackContent-length0 Content-typeztext/xmlgziprzContent-Encoding) rw report_404rrlminrfilereadr]lenjoindecode_request_contentserverrNrrFrb send_responserRry send_headerr traceback format_excrC end_headersencode_thresholdrurmr NotImplementedErrorwfilewrite) r-Zmax_chunk_sizeZsize_remainingL chunk_sizechunkrDrIrstraceqrrrdo_POSTs\           z"SimpleXMLRPCRequestHandler.do_POSTcCs|jdd}|dkr|S|dkrrz t|WStyR|dd|Yqtyn|ddYq0n|dd||dd |dS) Nzcontent-encodingidentityrizencoding %r not supportedzerror decoding gzip contentr|r}) rlrmlowerr rr ValueErrorrr)r-rDr*rrrrs    z1SimpleXMLRPCRequestHandler.decode_request_contentcCsF|dd}|dd|dtt|||j|dS)Nis No such pagerz text/plainr|)rrrrrrrr-rIrrrr's   z%SimpleXMLRPCRequestHandler.report_404-cCs|jjrt|||dS)z$Selectively log an accepted request.N)r logRequestsr log_request)r-codesizerrrr0sz&SimpleXMLRPCRequestHandler.log_requestN)rr)r0rdrerfrvrwbufsizedisable_nagle_algorithmrecompileVERBOSE IGNORECASErnrurwrrrrrrrrrgs  G rgc@s.eZdZdZdZdZedddddfddZdS)SimpleXMLRPCServeragSimple XML-RPC server. Simple XML-RPC server that allows functions and a single instance to be installed to handle requests. The default implementation attempts to dispatch XML-RPC calls to the functions or instance installed in the server. Override the _dispatch method inherited from SimpleXMLRPCDispatcher to change this behavior. TFNc Csn||_t||||tj||||tdurjttdrjt|tj}|tj O}t|tj |dS)N FD_CLOEXEC) rr$r.r TCPServerfcntlrRfilenoZF_GETFDrZF_SETFD) r-addrrequestHandlerrr)r*bind_and_activater+flagsrrrr.Is zSimpleXMLRPCServer.__init__)r0rdrerfallow_reuse_addressryrgr.rrrrr6s rc@s@eZdZdZedddddfddZddZd d Zd d d ZdS)MultiPathXMLRPCServera\Multipath XML-RPC Server This specialization of SimpleXMLRPCServer allows the user to create multiple Dispatcher instances and assign them to different HTTP request paths. This makes it possible to run two or more 'virtual XML-RPC servers' at the same port. Make sure that the requestHandler accepts the paths in question. TFNc Cs2t||||||||i|_||_|p*d|_dSr%)rr. dispatchersr)r*r-rrrr)r*rr+rrrr.as zMultiPathXMLRPCServer.__init__cCs||j|<|SNr)r-rF dispatcherrrradd_dispatcherks z$MultiPathXMLRPCServer.add_dispatchercCs |j|Srr)r-rFrrrget_dispatcherosz$MultiPathXMLRPCServer.get_dispatcherc Csjz|j||||}WnLtdd\}}ttdd||f|j|jd}||j}Yn0|S)Nr<r>r?) rrNrArBr rr*r)rC)r-rDrErFrIrKrLrrrrNrs z)MultiPathXMLRPCServer._marshaled_dispatch)NN) r0rdrerfrgr.rrrNrrrrrYs rc@s4eZdZdZd ddZddZdd Zd d d ZdS)CGIXMLRPCRequestHandlerz3Simple handler for XML-RPC data passed through CGI.FNcCst||||dSr)r$r.r,rrrr.sz CGIXMLRPCRequestHandler.__init__cCsP||}tdtdt|ttjtjj|tjjdS)zHandle a single XML-RPC requestzContent-Type: text/xmlContent-Length: %dN)rNprintrrAstdoutflushbufferr)r- request_textrIrrr handle_xmlrpcs  z%CGIXMLRPCRequestHandler.handle_xmlrpccCsd}tj|\}}tj|||d}|d}td||ftdtjtdt|ttj tj j |tj j dS)zHandle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method. r)rmessageexplainr&z Status: %d %szContent-Type: %srN) r responses http_serverZDEFAULT_ERROR_MESSAGErCrZDEFAULT_ERROR_CONTENT_TYPErrArrrr)r-rrrrIrrr handle_gets   z"CGIXMLRPCRequestHandler.handle_getc Csx|dur$tjdddkr$|nPzttjdd}WnttfyTd}Yn0|durjtj |}| |dS)zHandle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers. NREQUEST_METHODGETCONTENT_LENGTHri) osenvironrmrrr TypeErrorrAstdinrr)r-rlengthrrrhandle_requests   z&CGIXMLRPCRequestHandler.handle_request)FNF)N)r0rdrerfr.rrrrrrrrs   rc@s>eZdZdZdiiifddZdiiidfddZddZdS) ServerHTMLDocz7Class used to generate pydoc HTML document for a serverNcCsZ|p|j}g}d}td}|||} | s0q:| \} } ||||| | \} } }}}}| r|| dd}|d||fn|rdt|}|d||| fn~|rdt|}|d||| fnV|| | dd kr || ||||n(|r"|d |n|| ||| }q||||d d |S) zMark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.rzM\b((http|ftp)://\S+[\w/]|RFC[- ]?(\d+)|PEP[- ]?(\d+)|(self\.)?((?:\w|\.)+))\b"z"z%sz'http://www.rfc-editor.org/rfc/rfc%d.txtz(http://www.python.org/dev/peps/pep-%04d/r<(zself.%sNrW) escaperrsearchspanr]groupsreplacerZnamelinkr)r-textrr'classesrTr_herepatternrostartendallschemeZrfcZpepZselfdotr2urlrrrmarkups4      zServerHTMLDoc.markupcCs$|r |jp dd|}d} d||||f} t|rrt|} tj| jdd| j| j| j | j |j d} n%sr<N) annotations formatvaluez(...)rz'%sz
%s
z
%s
%s
)r0rinspectismethodgetfullargspec formatargspecargsvarargsvarkwdefaultsrr isfunction isinstancetuplerXrYZgreyr preformat)r-objectr2modr'rrTZclanchorZnotetitlerZargspec docstringdecldocrrr docroutinesF         zServerHTMLDoc.docroutinec Csi}|D] \}}d|||<||||<q ||}d|}||dd}|||j|} | ohd| } |d| }g} t|} | D]\}}| |j|||dq||ddd d | }|S) z1Produce HTML documentation for an XML-RPC server.z#-z)%sz#ffffffz#7799eez %sz

%s

)r'ZMethodsz#eeaa77rW) itemsrheadingrrrSr]rZ bigsectionr) r- server_nameZpackage_documentationrTZfdictkeyvalueheadresultrcontentsZ method_itemsrrr docservers$      zServerHTMLDoc.docserver)r0rdrerfrrrrrrrrs ) -rc@s8eZdZdZddZddZddZdd Zd d Zd S) XMLRPCDocGeneratorzGenerates documentation for an XML-RPC server. This class is designed as mix-in and should not be constructed directly. cCsd|_d|_d|_dS)NzXML-RPC Server DocumentationzGThis server exports the following methods through the XML-RPC protocol.)rserver_documentation server_titler8rrrr.?szXMLRPCDocGenerator.__init__cCs ||_dS)z8Set the HTML title of the generated server documentationN)r)r-rrrrset_server_titleGsz#XMLRPCDocGenerator.set_server_titlecCs ||_dS)z7Set the name of the generated HTML server documentationN)r)r-rrrrset_server_nameLsz"XMLRPCDocGenerator.set_server_namecCs ||_dS)z3Set the documentation string for the entire server.N)r)r-rrrrset_server_documentationQsz+XMLRPCDocGenerator.set_server_documentationc Csi}|D]}||jvr&|j|}n|jdurddg}t|jdrT|j||d<t|jdrp|j||d<t|}|dkr|}qt|jdszt|j|}Wqty|}Yq0q|}n dsJd|||<q t }| |j |j |}| |j|S) agenerate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring(method_name) method to provide the argument string used in the documentation and the _methodHelp(method_name) method to provide the help text used in the documentation.N_get_method_argstringrrVr<)NNr@zACould not find method in self.functions and no instance installed)r5r'r(rRrrVrrrrrrrpager)r-rTrUrHZ method_infoZ documenterZ documentationrrrgenerate_html_documentationVs>            z.XMLRPCDocGenerator.generate_html_documentationN) r0rdrerfr.rrrr rrrrr8s rc@seZdZdZddZdS)DocXMLRPCRequestHandlerzXML-RPC and documentation request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. Handles all HTTP GET requests and interprets them as requests for documentation. cCsf|s|dS|jd}|d|dd|dtt|| |j |dS)}Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. Nr&r~rz text/htmlr|) rwrrr rCrrrrrrrrrrrdo_GETs  zDocXMLRPCRequestHandler.do_GETN)r0rdrerfr rrrrr s r c@s&eZdZdZedddddfddZdS)DocXMLRPCServerzXML-RPC and HTML documentation server. Adds the ability to serve server documentation to the capabilities of SimpleXMLRPCServer. TFNc Cs&t||||||||t|dSr)rr.rrrrrr.s  zDocXMLRPCServer.__init__)r0rdrerfr r.rrrrrs rc@s eZdZdZddZddZdS)DocCGIXMLRPCRequestHandlerzJHandler for XML-RPC data and documentation requests passed through CGIcCsT|d}tdtdt|ttjtjj|tjjdS)r r&zContent-Type: text/htmlrN) r rCrrrArrrrrrrrrs z%DocCGIXMLRPCRequestHandler.handle_getcCst|t|dSr)rr.rr8rrrr.s z#DocCGIXMLRPCRequestHandler.__init__N)r0rdrerfrr.rrrrrsr__main__c@s"eZdZddZGdddZdS)ExampleServicecCsdS)NZ42rr8rrrgetDataszExampleService.getDatac@seZdZeddZdS)zExampleService.currentTimecCs tjSr)datetimenowrrrrgetCurrentTimesz)ExampleService.currentTime.getCurrentTimeN)r0rdre staticmethodrrrrr currentTimesrN)r0rdrerrrrrrrsr) localhosti@cCs||Srr)xyrrrrxradd)rz&Serving XML-RPC on localhost port 8000zKIt is advisable to run this example server within a secure, closed network.z& Keyboard interrupt received, exiting.)T):rf __future__rrrrZfuture.builtinsrrZfuture.backports.xmlrpc.clientrr r r r Zfuture.backports.http.serverr Z backportshttprrZfuture.backportsrrArrrXrrr ImportErrorrr#rr$rgrrrrZHTMLDocrrr rrr0rrr3powr/r;r serve_foreverKeyboardInterrupt server_closeexitrrrrsjj      #(ErQ