def CreateApp(self, name): """ Creates new app. @param name: Name of an app. @type name: C{str} @return: Instance id of an app. @rtype: C{int} """ if not self.Apps: return 0 if name not in self.Apps: return 0 id= int(random.getrandbits(16)) print self.Apps[name] if not self.instances: self.instances= {} self.instances[id]= (self.Apps[name](), name,) dispatcher= SimpleXMLRPCDispatcher() dispatcher.register_introspection_functions() dispatcher.register_instance(self.instances[id][0]) self.server.add_dispatcher( "/"+str(id), dispatcher) return id
class WSGIXMLRPCApplication(object): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=[]): """Create windmill xmlrpc dispatcher""" self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def handler(self, environ, start_response): """XMLRPC service for windmill browser core to communicate with""" if environ['REQUEST_METHOD'] == 'POST': return self.handle_POST(environ, start_response) else: start_response("400 Bad request", [('Content-Type', 'text/plain')]) return [''] def handle_POST(self, environ, start_response): """Handles 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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: # Get arguments by reading body of request. # We read this in chunks to avoid straining length = int(environ['CONTENT_LENGTH']) data = environ['wsgi.input'].read(length) # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error start_response("500 Server error", [('Content-Type', 'text/plain')]) return [] else: # got a valid XML RPC response start_response("200 OK", [('Content-Type', 'text/xml'), ('Content-Length', str(len(response)),)]) return [response] def __call__(self, environ, start_response): return self.handler(environ, start_response)
class WSGIXMLRPCApplication(object): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=()): """Create windmill xmlrpc dispatcher""" try: self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) except TypeError: # python 2.4 self.dispatcher = SimpleXMLRPCDispatcher() if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() @Request.application def handler(self, request): if request.method == 'POST': return self.handle_POST(request) else: return BadRequest() def handle_POST(self, request): """Handles 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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: # Read the data from the request data = request.get_data() # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None)) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error return InternalServerError() else: # got a valid XML RPC response return Response(response, mimetype='text/xml') def __call__(self, environ, start_response): return self.handler(environ, start_response)
class Server(Thread): """ XML-RPC server. """ @LogCall() def __init__(self, requestHandler, host="localhost", port=8400): """ Initializes server. @param requestHandler: Request handler for base class calls. @type requestHandler: C{AppsHandler} @param host: Host where to bind. @type host: C{str} @param port: Port where to bind. @type port: C{int} @return: Instance of self. @rtype: C{Server} """ Thread.__init__(self) self.server = MultiPathXMLRPCServer((host, port), requestHandler=RHandler) self.requestHandler= requestHandler(self.server, False) self.dispatcher= SimpleXMLRPCDispatcher() self.dispatcher.register_introspection_functions() self.dispatcher.register_instance(self.requestHandler) self.server.add_dispatcher("/", self.dispatcher) @LogCall({"level": INFO}) def run(self): """ Runs server. @return: Nothing @rtype: C{None} """ self.server.serve_forever() @LogCall({"level": INFO}) def __del__(self): """ Stops server. @return: Nothing @rtype: C{None} """ self.server.shutdown() def GetRequestHandler(self): """ Gets base request handler used with this server. @return: Request handler used with this server. @rtype: C{AppsHandler} """ return self.requestHandler
def xmlrpc_handle_mp(server_handler, request_text): """ Same as xmlrpc_handle_cgi() but within a mod_python environment. Return a pair of the response and a list of affected unids. """ # create an XMLRPC server handler and bind interface handler = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) handler.register_instance(server_handler) response, error = _exc_marshaled_dispatch(handler, request_text) return response, error, list(server_handler.affected_unids())
def main_loop(): setproctitle("webshelld") dispatcher = SimpleXMLRPCDispatcher() SOCKFILE = "/var/run/webshell.sock" if os.path.exists(SOCKFILE): os.unlink(SOCKFILE) server = SocketServer.UnixStreamServer(SOCKFILE, XMLRPCHandler) os.chmod(SOCKFILE, 0o700) dispatcher.register_instance(Multiplex("/usr/local/bin/bash", "xterm-color")) server.dispatcher = dispatcher server.serve_forever()
def main_loop(): setproctitle('webshelld') dispatcher = SimpleXMLRPCDispatcher() SOCKFILE = '/var/run/webshell.sock' if os.path.exists(SOCKFILE): os.unlink(SOCKFILE) server = SocketServer.UnixStreamServer(SOCKFILE, XMLRPCHandler) os.chmod(SOCKFILE, 0o700) dispatcher.register_instance( Multiplex("/usr/local/bin/bash", "xterm-color")) server.dispatcher = dispatcher server.serve_forever()
def handle_request(app, request): '''Wrap an invocation of the XML-RPC dispatcher. ''' dispatcher = SimpleXMLRPCDispatcher() dispatcher.register_instance(Interface(app, request)) # read in the XML-RPC request data, limiting to a sensible size if int(request.headers['Content-Length']) > 10 * 1024 * 1024: raise BadRequest('request data too large') xml_request = request.get_data(cache=False, as_text=True) # errors here are handled by _marshaled_dispatch response = dispatcher._marshaled_dispatch(xml_request) # legacy; remove non-printable ASCII control codes from the response response = re.sub('([\x00-\x08]|[\x0b-\x0c]|[\x0e-\x1f])+', '', response) return Response(response, mimetype="text/xml")
def register_instance(self, instance, allow_dotted_names=False): """ This registers any kind of object. If the requested method hasn't been registered by :meth:`register_function`, it will be checked against the instance. You can only have one instance at a time, however. If :obj:`allow_dotted_names` is True, the name will be split on the dots and the object will be traveled down recursively. However, this is a **HUGE SECURITY LOOPHOLE**, as while private methods (starting with ``_``) will not be exposed, it's still possible that someone could get access to your globals and do very bad things. So don't do it unless you have a very good reason. :param instance: The instance to register. :param allow_dotted_names: Whether to resolve dots in method names. You probably shouldn't. """ # Yes, it's just a wrapper. I know. This way the docs are consistent. Dispatcher.register_instance(self, instance, allow_dotted_names)
class XMLRPCApplication(RestApplication): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=[]): """Create windmill xmlrpc dispatcher""" try: self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) except TypeError: # python 2.4 self.dispatcher = SimpleXMLRPCDispatcher() if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def POST(self, request, *path): """Handles 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. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: data = str(request.body) # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error return Response500() else: # got a valid XML RPC response return XMLResponse(response)
def handle_request(app, request): '''Wrap an invocation of the XML-RPC dispatcher. ''' # unicode strings will be encoded in utf-8 by xmlrpclib dispatcher = SimpleXMLRPCDispatcher() dispatcher.register_instance(Interface(app, request)) # read in the XML-RPC request data, limiting to a sensible size if int(request.headers['Content-Length']) > 10 * 1024 * 1024: raise BadRequest('request data too large') xml_request = request.get_data(cache=False, as_text=True) # errors here are handled by _marshaled_dispatch response = dispatcher._marshaled_dispatch(xml_request) # legacy; remove non-printable ASCII control codes from the response # RJ: disabled this as it's a giant, unreliable hack that doesn't work and # I can't even remember why it's in here to start with # response = re.sub('([\x00-\x08]|[\x0b-\x0c]|[\x0e-\x1f])+', '', response) return Response(response, mimetype="text/xml; charset=utf-8")
class WSGIXMLRPCApplication: def __init__(self,instance=None,methods=[]): self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True,encoding=None) if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def __call__(self,environ,start_response): if environ["REQUEST_METHOD"] == "POST": return self.handle_post(environ,start_response) else: start_response("400 Bad request",[("Content-Type","text/plain")]) return [''] def handle_post(self,environ,start_response): try: max_chunk_size = 10*1024*1024 size_remaining = int(environ["CONTENT_LENGTH"]) L = [] rfile = environ['wsgi.input'] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]) data = ''.join(L) data = self.decode_request_content(data,environ,start_response) if isinstance(data, list): return data response = self.dispatcher._marshaled_dispatch(data) except Exception, e: start_response("%d %s" % (500,_RESPONSE_STATUSES[500]),[ ("Content-length", '') ]) return [] else:
class XMLRPCDispatcher(Resource): '''A Resource that knows how to host an XMLRPCObject and serve it''' def __init__(self, application, request, response, session, instance=None, methods=[], allow_none=True, encoding=None): '''initializes this dispatcher which can handle XMLRPC requests.''' if not instance: raise ValueError("You must pass in a non-null object which we will serve") super(XMLRPCDispatcher, self).__init__(application, request, response, session) self.dispatcher = SimpleXMLRPCDispatcher(allow_none=allow_none, encoding=encoding) self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() self.dispatcher.register_multicall_functions() @POST @Route("/{path:.*}") def post(self, path): ''' Attempts to process all posts as XMLRPC Requests which are then dispatched to the XMLRPCObject. Most of the code was taken from SimpleXMLRPCServer with modifications to make it compatible with Gates ''' try: data = self.request.body response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) except Exception as e: # This should only happen if the module is buggy # internal error, report as Internal HTTP Server error traceback.print_exc(e) abort(500, "XMLRPC Application Error! You shouldn't be seeing this. We're sorry.") else: # We got a valid XML RPC response self.response.type = "text/xml" self.response.write(response)
from django.contrib.sessions.backends.db import Session try: Session.objects.get(session_key=token) return True except Session.DoesNotExist: return False def login(username, password): ''' params (username, password) ''' from django.contrib.sessions.backends.db import SessionStore user = auth.authenticate(identification=username, password=password) # import pdb; pdb.set_trace() if user: session = SessionStore() session['user_id'] = user.id session.save() response = session.session_key else: response = 'username or password is wrong' return response dispatcher.register_instance(Services()) dispatcher.register_function(login) dispatcher.register_function(token_is_valid) #dispatcher.register_function(get_notifications_by_id) #dispatcher.register_function(get_notifications_by_date) #dispatcher.register_function(get_notifications_by_location) #dispatcher.register_function(register_to_app)
@csrf_exempt def rpc_handler(request): """ All xmlrpc requests are initially routed here by django. The actual functions we implement are in the views.py file. This rpc_handler function will make sure that what we return from the functions in views.py will be turned into a valid xmlrpc response. If POST data is defined, it assumes it's XML-RPC and tries to process as such. If the POST data is empty or if it is a GET request, this assumes the request is from a browser and responds saying it's an xmlrpc service. This function does not need to be called from anywhere other than having it defined in urls.py. That is, you generally shouldn't need to ever use this function directly. """ response = HttpResponse() if len(request.POST): response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) else: response.write("<b>This is the SeattleGeni XML-RPC Service.</b><br>") response.write("Please see <a href=" + SEATTLECLEARINGHOUSE_XMLRPC_API_DOC_URL + ">" + SEATTLECLEARINGHOUSE_XMLRPC_API_DOC_URL + "</a> for more information.") response['Content-length'] = str(len(response.content)) return response # All methods in the PublicXMLRPCFunctions class will be available as xmlrpc functions. dispatcher.register_instance(PublicXMLRPCFunctions())
class MyXMLRPCApp(object): """WSGI to XMLRPC callable. XMLRPC WSGI callable app. Args: instance: An instance of XMLRPC module. Callable args: environ: WSGI environment dictionary. start_response: WSGI response functor for sending HTTP headers. """ _MAX_CHUNK_SIZE = 10 * 1024 * 1024 def __init__(self, instance): """Creates XML RPC dispatcher.""" self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) self.dispatcher.register_introspection_functions() if instance is not None: self.RegisterInstance(instance) def __call__(self, environ, start_response): session = WSGISession(environ, start_response) if session.Method() != 'POST': return session.BadRequest() return self._XMLRPCCall(session) def RegisterInstance(self, instance): self.dispatcher.register_instance(instance) def _XMLRPCCall(self, session): """Dispatches request data body.""" mediator = SessionMediator(session, self.dispatcher) response_data = '' try: # Reading body in chunks to avoid straining (python bug #792570) size_remaining = session.ContentLength() chunks = [] while size_remaining > 0: chunk_size = min(self._MAX_CHUNK_SIZE, size_remaining) buf = session.Read(chunk_size) if not buf: break chunks.append(buf) size_remaining -= len(buf) data = ''.join(chunks) # Dispatching data response_data = mediator.MarshaledDispatch(data) except: # pylint: disable=W0702 return session.ServerError() else: # Sending valid XML RPC response data return session.Response('text/xml', response_data) finally: error_message = session['xmlrpc_exception'] error_message = (': %s' % error_message if error_message else '') logging.info('%s %s [%3f s, %d B in, %d B out]%s', session.RemoteAddress(), session['xmlrpc_method'], time.time() - session.time, len(data), len(response_data), error_message)
return 1 else: return 0 def ABC(self): if(self.finished == 1): self.c.execute('SELECT ID, vote FROM votes') for row in self.c: self.voter_list.append((row[0], row[1])) return self.voter_list else: return 0 dispatcher.register_instance(voting_BS()) def results(request): cache._cache.clear() results_list = Choice.objects.all() return render_to_response('results.html', {'results_list': results_list}) def showResults(request): Y_tally = 0 N_tally = 0 results_list = Choice.objects.all() for object in results_list: if object.votes == '1': Y_tally = Y_tally + 1 else:
response = HttpResponse(mimetype="application/xml") response.write(dispatcher._marshaled_dispatch(request.body)) else: response = HttpResponse() response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: # right now, my version of SimpleXMLRPCDispatcher always # returns "signatures not supported"... :( # but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help_txt = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help_txt)) response.write("</ul>") response['Content-length'] = str(len(response.content)) return response # you have to manually register all functions that are xml-rpc-able with the dispatcher # the dispatcher then maps the args down. # The first argument is the actual method, the second is what to call it from the XML-RPC side... dispatcher.register_instance(FooService())
def decode_request_content(self, data): encoding = self.headers.get("content-encoding", "identity").lower() if encoding != "gzip": self.send_response(501, "encoding %r not supported" % encoding) return SimpleXMLRPCRequestHandler.decode_request_content(self, data) if __name__ == "__main__": server = MultiPathXMLRPCServer(("0.0.0.0", 12345), requestHandler=RequestHandler, allow_none=True, encoding="utf8") random_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") random_server.register_introspection_functions() random_server.register_instance(RandomServer()) server.add_dispatcher("/random", random_server) file_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") file_server.register_introspection_functions() file_server.register_instance(FileServer()) server.add_dispatcher("/fileserver", file_server) secret_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") secret_server.register_introspection_functions() secret_server.register_instance(SecretServer()) server.add_dispatcher("/secret_illuminati_world_domination_plans", secret_server) info_server = SimpleXMLRPCDispatcher(allow_none=True, encoding="utf8") info_server.register_introspection_functions() info_server.register_instance(InfoServer())