[Winopenrpg-developer] openrpg1/orpg/networking __init__.py,NONE,1.1 gsclient.py,NONE,1.1 meta_serve
Status: Inactive
Brought to you by:
digitalxero
|
From: Digital X. <dig...@us...> - 2006-01-26 17:33:27
|
Update of /cvsroot/winopenrpg/openrpg1/orpg/networking In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30930/orpg/networking Added Files: __init__.py gsclient.py meta_server_lib.py mplay_client.py mplay_server.py mplay_server_gui.py Log Message: Initial commit of OpenRPG++ python --- NEW FILE: mplay_server.py --- #!/usr/bin/python2.1 # Copyright (C) 2000-2001 The OpenRPG Project # # ope...@li... # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # -- [...2464 lines suppressed...] else: FG = LCOLOR else: FG = PCOLOR pl += "<tr><td bgcolor=" + COLOR3 + ">" pl += "<font color=" + FG + " " + SIZE + "> (" + (self.players[id]).id + ") " pl += (self.players[id]).name pl += "</font></td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + ">[IP: " + (self.players[id]).ip + "]</font></td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + "> " pl += (self.players[id]).idle_status() pl += "</font></td><td><font color=" + FG + " " + SIZE + ">" pl += (self.players[id]).connected_time_string() pl += "</font>" else: self.groups[k].remove_player(id) pl +="<tr><td colspan='4' bgcolor=" + COLOR3 + " >Bad Player Ref (#" + id + ") in group" pl+="</td></tr>" pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + "><font color=" + COLOR4 + "><b><i>Statistics: groups: " + str(len(self.groups)) + " players: " + str(len(self.players)) + "</i></b></font></td></tr></table>" except Exception, e: self.log_msg(str(e)) self.p_lock.release() return pl --- NEW FILE: meta_server_lib.py --- #!/usr/bin/python2.1 # Copyright (C) 2000-2001 The OpenRPG Project # # ope...@li... # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # -- # # File: meta_server_lib.py # Author: Chris Davis # Maintainer: # Version: # $Id: meta_server_lib.py,v 1.1 2006/01/26 17:33:16 digitalxero Exp $ # # Description: A collection of functions to communicate with the meta server. # #added debug flag for meta messages to cut console server spam --Snowdog META_DEBUG = 0 __version__ = "$Id: meta_server_lib.py,v 1.1 2006/01/26 17:33:16 digitalxero Exp $" from orpg.orpg_version import PROTOCOL_VERSION from orpg.orpg_xml import * import orpg.dirpath import orpg.tools.config_files import urllib import orpg.minidom from threading import * import time import sys import random import traceback import re metacache_lock = RLock() def get_server_dom(data=None,path=None): # post data at server and get the resulting DOM if path == None: # get meta server URI path = getMetaServerBaseURL() # POST the data # print # print "Sending the following POST info to Meta at " + path + ":" # print "==========================================" # print data # print file = urllib.urlopen(path,data) data = file.read() # Remove any leading or trailing data. This can happen on some satellite connections p = re.compile('(<servers>.*?</servers>)',re.DOTALL|re.IGNORECASE) mo=p.search(data) if mo: data=mo.group(0) # print # print "Got this string from the Meta at " + path + ":" # print "===============================================" # print data # print # build dom xml_dom = parseXml(data) xml_dom = xml_dom._get_documentElement() return xml_dom def post_server_data( name, realHostName=None): # build POST data ## data = urllib.urlencode( {"server_data[name]":name, ## "server_data[version]":PROTOCOL_VERSION, ## "act":"new"} ) ## if realHostName: data = urllib.urlencode( {"server_data[name]":name, "server_data[version]":PROTOCOL_VERSION, "act":"new", "REMOTE_ADDR": realHostName } ) else: #print "Letting meta server decide the hostname to list..." data = urllib.urlencode( {"server_data[name]":name, "server_data[version]":PROTOCOL_VERSION, "act":"new"} ) xml_dom = get_server_dom( data , "http://openrpg.sf.net/openrpg_servers.php") ret_val = int( xml_dom.getAttribute( "id" ) ) return ret_val def post_failed_connection(id,meta=None,address=None,port=None): # For now, turning this off. This needs to be re-vamped for # handling multiple Metas. return 0 # data = urllib.urlencode({"id":id,"act":"failed"}); # xml_dom = get_server_dom(data) # ret_val = int(xml_dom.getAttribute("return")) # return ret_val def remove_server(id): data = urllib.urlencode({"id":id,"act":"del"}); xml_dom = get_server_dom(data) ret_val = int(xml_dom.getAttribute("return")) return ret_val def byStartAttribute(first,second): # This function is used to easily sort a list of nodes # by their start time if first.hasAttribute("start"): first_start = int(first.getAttribute("start")) else: first_start = 0 if second.hasAttribute("start"): second_start = int(second.getAttribute("start")) else: second_start = 0 # Return the result of the cmp function on the two strings return cmp(first_start,second_start) def byNameAttribute(first,second): # This function is used to easily sort a list of nodes # by their name attribute # Ensure there is something to sort with for each if first.hasAttribute("name"): first_name = str(first.getAttribute("name")).lower() else: first_name = "" if second.hasAttribute("name"): second_name = str(second.getAttribute("name")).lower() else: second_name = "" # Return the result of the cmp function on the two strings return cmp(first_name,second_name) def get_server_list(versions = None,sort_by="start"): data = urllib.urlencode({"version":PROTOCOL_VERSION,"ports":"%"}) all_metas = getMetaServers(versions,1) # get the list of metas base_meta = getMetaServerBaseURL() #all_metas.reverse() # The last one checked will take precedence, so reverse the order # so that the top one on the actual list is checked last return_hash = {} # this will end up with an amalgamated list of servers for meta in all_metas: # check all of the metas # get the server's xml from the current meta bad_meta = 0 #print "Getting server list from " + meta + "..." try: xml_dom = get_server_dom(data=data,path=meta) except: #print "Trouble getting servers from " + meta + "..." bad_meta = 1 if bad_meta: continue if base_meta == meta: #print "This is our base meta: " + meta updateMetaCache(xml_dom) node_list = xml_dom.getElementsByTagName('server') if len(node_list): # if there are entries in the node list # otherwise, just loop to next meta # for each node found, we're going to check the nodes from prior # metas in the list. If a match is found, then use the new values. for n in node_list: # set them from current node if not n.hasAttribute('name'): n.setAttribute('name','NO_NAME_GIVEN') name = n.getAttribute('name') if not n.hasAttribute('num_users'): n.setAttribute('num_users','N/A') num_users = n.getAttribute('num_users') if not n.hasAttribute('address'): n.setAttribute('address','NO_ADDRESS_GIVEN') address = n.getAttribute('address') if not n.hasAttribute('port'): n.setAttribute('port','6774') port = n.getAttribute('port') n.setAttribute('meta',meta) end_point = str(address) + ":" + str(port) if return_hash.has_key(end_point): if META_DEBUG: print "Replacing duplicate server entry at " + end_point return_hash[end_point] = n # At this point, we have an amalgamated list of servers # Now, we have to construct a new DOM to pass back. # Create a servers element return_dom = orpg.minidom.Element("servers") # get the nodes stored in return_hash return_list = return_hash.values() # sort them by their name attribute. Uses byNameAttribute() # defined above as a comparison function if sort_by == "start": return_list.sort(byStartAttribute) elif sort_by == "name": return_list.sort(byNameAttribute) # Add each node to the DOM for n in return_list: return_dom.appendChild(n) return return_dom ## List Format: ## <servers> ## <server address=? id=? name=? failed_count=? > ## </servers> def updateMetaCache(xml_dom): try: if META_DEBUG: print "Updating Meta Server Cache" metaservers = xml_dom.getElementsByTagName( 'metaservers' ) # pull out the metaservers bit authoritative = metaservers[0].getAttribute('auth') if META_DEBUG: print " Authoritive Meta: "+str(authoritative) metas = metaservers[0].getElementsByTagName("meta") # get the list of metas if META_DEBUG: print " Meta List ("+str(len(metas))+" servers)" try: metacache_lock.acquire() ini = open(orpg.dirpath.dir_struct["user"]+"metaservers.cache","w") for meta in metas: if META_DEBUG: print " Writing: "+str(meta.getAttribute('path')) ini.write(str(meta.getAttribute('path')) + " " + str(meta.getAttribute('versions')) + "\n") ini.close() finally: metacache_lock.release() except Exception, e: if META_DEBUG: traceback.print_exc() print "Meta Server Lib: UpdateMetaChache(): " + str(e) def getRawMetaList(): try: try: metacache_lock.acquire() # Read in the metas orpg.tools.config_files.validate_config_file("metaservers.cache","metaservers.cache") ini = open(orpg.dirpath.dir_struct["user"]+"metaservers.cache","r") metas = ini.readlines() ini.close() return metas finally: metacache_lock.release() except Exception, e: if META_DEBUG: traceback.print_exc() print "Meta Server Lib: getRawMetaList(): " + str(e) return [] def getMetaServers(versions = None, pick_random=0): # get meta server URLs as a list # versions is a list of acceptable version numbers. # A false truth value will use getMetaServerBaseURL() # set a default if we have weird reading problems # default_url = "http://www.openrpg.com/openrpg_servers.php" meta_names = [] if(versions): # If versions are supplied, then look in metaservers.conf try: # read in the metas from file # format of file is one meta entry per line # each entry will be the meta url, followed by one or more version numbers that it # handle. Generally, this will be either a 1 for the original Meta format, or # 2 for the new one. # Read in the metas metas = getRawMetaList() #print str(metas) # go through each one to check if it should be returned, based on the # version numbers allowed. for meta in metas: # split the line on whitespace # obviously, your meta servers urls shouldn't contain whitespace. duh. words = meta.split() success = 0 # init success flag for version check for version in versions: # run through each allowed version from caller if version in words[1:]: # if the allowed version token was found success += 1 # then increment the success indicator if success: # if the meta entry is acceptable to the caller meta_names.append(words[0]) # add the entry if META_DEBUG: print "adding metaserver " + meta # at this point, we should have at least one name from the cache. If not ... if not meta_names: default_meta = getMetaServerBaseURL() # grab the meta from ini.xml meta_names.append(default_meta) # add it to the return list # print "Warning!!\nNo valid metaservers cached." # print "Using meta from MetaServerBaseURL: " + default_meta + "\n" # if we have more than one and want a random one elif pick_random: if META_DEBUG: print "choosing random meta from: " + str(meta_names) i = int(random.uniform(0,len(meta_names))) #meta = meta_names[i] meta_names = [meta_names[i]] if META_DEBUG: print "using: " + str(meta_names) else: if META_DEBUG: print "using all metas: " + str(meta_names) return meta_names except Exception,e: print e #print "using default meta server URI: " + default_url metas = [] #metas.append(default_url) return metas # return an empty list else: # otherwise, use MetaServerBaseURL() url = getMetaServerBaseURL() meta_names.append(url) return meta_names def getMetaServerBaseURL(): # get meta server URL url = "http://www.openrpg.com/openrpg_servers.php" try: orpg.tools.config_files.validate_config_file("ini.xml","default_ini.xml") ini = open(orpg.dirpath.dir_struct["user"]+"ini.xml","r") txt = ini.read() tree = parseXml(txt)._get_documentElement() ini.close() node_list = tree.getElementsByTagName("MetaServerBaseURL") if node_list: url = node_list[0].getAttribute("value") # allow tree to be collected try: tree.unlink() except: pass except Exception,e: print e # print "using meta server URI: " + url return url ####################################################################################### # Beginning of Class registerThread # # A Class to Manage Registration with the Meta2 # Create an instance and call it's start() method # if you want to be (and stay) registered. This class # will take care of registering and re-registering as # often as necessary to stay in the Meta list. # # You may call register() yourself if you wish to change your # server's name. It will immediately update the Meta. There # is no need to unregister first. # # Call unregister() when you no longer want to be registered. # This will result in the registerThread dying after # attempting to immediately remove itself from the Meta. # # If you need to become registered again after that, you # must create a new instance of class registerThread. Don't # just try to call register() on the old, dead thread class. class registerThread(Thread): # Originally, I wrote this as a sub-class of wxThread, but # A) I couldn't get it to import right # B) I realized that I want this to be used in a server, # which I don't want needing wxWindows to run! # # Because of this fact, there are some methods from wxThread # that I implemented to minimize changes to the code I had # just written, i.e. TestDeleteStatus() and Delete() def __init__(self,name=None,realHostName=None,num_users = "Hmmm",MetaPath=None,port=6774,register_callback=None): Thread.__init__(self,name="registerThread") self.rlock = RLock() # Re-entrant lock used to make this class thread safe self.die_event = Event() # The main loop in run() will wait with timeout on this if name: self.name = name # Name that the server want's displayed on the Meta else: self.name = "Unnamed server" # But use this if for some crazy reason no name is # passed to the constructor self.num_users = num_users # the number of users currently on this server self.realHostName = realHostName # Name to advertise for connection self.id = "0" # id returned from Meta. Defaults to "0", which # indicates a new registration. self.cookie = "0" # cookie returned from Meta. Defaults to "0",which # indicates a new registration. self.interval = 0 # interval returned from Meta. Is how often to # re-register, in minutes. self.destroy = 0 # Used to flag that this thread should die self.port = str(port) self.register_callback = register_callback # set a method to call to report result of register # This thread will communicate with one and only one # Meta. If the Meta in ini.xml is changed after # instantiation, then this instance must be # unregistered and a new instance instantiated. # # Also, if MetaPath is specified, then use that. Makes # it easier to have multiple registerThreads going to keep the server registered # on multiple (compatible) Metas. if MetaPath == None: self.path = getMetaServerBaseURL() # Do this if no Meta specified else: self.path = MetaPath def TestDeleteStatus(self): try: self.rlock.acquire() return self.die_event.isSet() finally: self.rlock.release() def Delete(self): try: self.rlock.acquire() self.die_event.set() finally: self.rlock.release() def run(self): # This method gets called by Thread implementation # when self.start() is called to begin the thread's # execution # # We will basically enter a loop that continually # re-registers this server and sleeps Interval # minutes until the thread is ordered to die in place while(not self.TestDeleteStatus()): # Loop while until told to die # Otherwise, call thread safe register(). self.register(self.name, self.realHostName, self.num_users) # register() will end up setting the state variables # for us, including self.interval. try: self.rlock.acquire() # Serialize access to this state information if self.interval >= 1: # If the number of minutes is one or greater self.interval -= .5 # wake up with 30 seconds left to re-register else: self.interval = .1 # Otherwise, we probably experienced some kind # of error from the Meta in register(). Sleep # for 6 seconds and start from scratch. finally: # no matter what, release the lock self.rlock.release() # Wait interval minutes for a command to die die_signal = self.die_event.wait(self.interval*60) # If we get past the while loop, it's because we've been asked to die, # so just let run() end. Once this occurs, the thread is dead and # calls to Thread.isAlive() return false. def unregister(self): # This method can (I hope) be called from both within the thread # and from other threads. It will attempt to unregister this # server from the Meta database # When this is either accomplished or has been tried hard enough # (after which it just makes sense to let the Meta remove the # entry itself when we don't re-register using this id), # this method will either cause the thread to immediately die # (if called from this thread's context) or set the Destroy flag # (if called from the main thread), a positive test for which will cause # the code in Entry() to exit() when the thread wakes up and # checks TestDeleteStatus(). # lock the critical section. The unlock will # automatically occur at the end of the function in the finally clause try: self.rlock.acquire() if not self.isAlive(): # check to see if this thread is dead return 1 # If so, return an error result # Do the actual unregistering here data = urllib.urlencode( {"server_data[id]":self.id, "server_data[cookie]":self.cookie, "server_data[version]":PROTOCOL_VERSION, "act":"unregister"} ) try: xml_dom = get_server_dom( data=data,path=self.path ) # this POSTS the request and returns the result if xml_dom.hasAttribute("errmsg"): if META_DEBUG: print "Error message returned from Meta: " + xml_dom.getAttribute("errmsg") except: if META_DEBUG: print "Problem talking to Meta. Will go ahead and die, letting Meta remove us." # If there's an error, echo it to the console # No special handling is required. If the de-registration worked we're done. If # not, then it's because we've already been removed or have a bad cookie. Either # way, we can't do anything else, so die. self.Delete() # This will cause the registerThread to die in register() # prep xml_dom for garbage collection try: xml_dom.unlink() except: pass return 0 finally: self.rlock.release() def register(self,name = None, realHostName=None, num_users = None): # Designed to handle the registration, both new and # repeated. # # It is intended to be called once every interval # (or interval - delta) minutes. # lock the critical section. The unlock will # automatically occur at the end of the function in the finally clause try: self.rlock.acquire() if not self.isAlive(): # check to see if this thread is dead return 1 # If so, return an error result # Set the server's attibutes, if specified. if name: self.name = name if num_users != None: self.num_users = num_users if realHostName: self.realHostName = realHostName # build POST data if self.realHostName: data = urllib.urlencode( {"server_data[id]":self.id, "server_data[cookie]":self.cookie, "server_data[name]":self.name, "server_data[port]":self.port, "server_data[version]":PROTOCOL_VERSION, "server_data[num_users]":self.num_users, "act":"register", "server_data[address]": self.realHostName } ) else: # print "Letting meta server decide the hostname to list..." data = urllib.urlencode( {"server_data[id]":self.id, "server_data[cookie]":self.cookie, "server_data[name]":self.name, "server_data[port]":self.port, "server_data[version]":PROTOCOL_VERSION, "server_data[num_users]":self.num_users, "act":"register"} ) try: xml_dom = get_server_dom( data=data,path=self.path ) # this POSTS the request and returns the result except: if META_DEBUG: print "Problem talking to server. Setting interval for retry ..." self.interval = 0 if self.register_callback: # if a callback is registered, call it self.register_callback(None,self.path) # If we are in the registerThread thread, then setting interval to 0 # will end up causing a retry in about 6 seconds (see self.run()) # If we are in the main thread, then setting interval to 0 will do one # of two things: # 1) Do the same as if we were in the registerThread # 2) Cause the next, normally scheduled register() call to use the values # provided in this call. # # Which case occurs depends on where the registerThread thread is when # the main thread calls register(). return 0 # indicates that it was okay to call, not that no errors occurred # If there is a DOM returned .... if xml_dom: if self.register_callback: # if a callback is registered, call it self.register_callback(xml_dom,self.path) # If there's an error, echo it to the console if xml_dom.hasAttribute("errmsg"): if META_DEBUG: print "Error message returned from Meta: " + xml_dom.getAttribute("errmsg") # No special handling is required. If the registration worked, id, cookie, and interval # can be stored and used for the next time. # If an error occurred, then the Meta will delete us and we need to re-register as # a new server. The way to indicate this is with a "0" id and "0" cookie sent to # the server during the next registration. Since that's what the server returns to # us on an error anyway, we just store them and the next registration will # automatically be set up as a new one. # # Unless the server calls register() itself in the meantime. Of course, that's okay # too, because a success on THAT register() call will set up the next one to use # the issued id and cookie. # # The interval is stored unconditionally for similar reasons. If there's an error, # the interval will be less than 1, and the main thread's while loop will reset it # to 6 seconds for the next retry. # Is it wrong to have a method where there's more comments than code? :) try: self.interval = int(xml_dom.getAttribute("interval")) self.id = xml_dom.getAttribute("id") self.cookie = xml_dom.getAttribute("cookie") except: if META_DEBUG: print if META_DEBUG: print "OOPS! Is the Meta okay? It should be returning an id, cookie, and interval." if META_DEBUG: print "Check to see what it really returned.\n" # Let xml_dom get garbage collected try: xml_dom.unlink() except: pass else: # else if no DOM is returned from get_server_dom() if META_DEBUG: print "Error - no DOM constructed from Meta message!" return 0 # Let caller know it was okay to call us finally: self.rlock.release() # End of class registerThread ################################################################################ --- NEW FILE: mplay_client.py --- # Copyright (C) 2000-2001 The OpenRPG Project # # ope...@li... # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # -- # # File: mplay_client.py # Author: Chris Davis # Maintainer: # Version: # $Id: mplay_client.py,v 1.1 2006/01/26 17:33:16 digitalxero Exp $ # # Description: This file contains the code for the client stubs of the multiplayer # features in the orpg project. # __version__ = "$Id: mplay_client.py,v 1.1 2006/01/26 17:33:16 digitalxero Exp $" import orpg.minidom import socket import Queue import thread import traceback from threading import Event, Lock from xml.sax.saxutils import escape from struct import pack, unpack, calcsize from string import * from orpg.orpg_version import * import errno import os import time # This should be configurable OPENRPG_PORT = 6774 # We should be sending a length for each packet MPLAY_LENSIZE = calcsize( 'i' ) MPLAY_DISCONNECTED = 0 MPLAY_CONNECTED = 1 MPLAY_DISCONNECTING = 3 MPLAY_GROUP_CHANGE = 4 MPLAY_GROUP_CHANGE_F = 5 PLAYER_NEW = 1 PLAYER_DEL = 2 PLAYER_GROUP = 3 # The next two messages are used to inform others that a player is typing PLAYER_TYPING = 4 PLAYER_NOT_TYPING = 5 PLAYER_UPDATE = 6 GROUP_JOIN = 1 GROUP_NEW = 2 GROUP_DEL = 3 GROUP_UPDATE = 4 STATUS_SET_URL = 1 def parseXml(data): "parse and return doc" #print data doc = orpg.minidom.parseString(data) doc.normalize() return doc def myescape(data): return escape(data,{"\"":""}) class mplay_event: def __init__(self,id,data=None): self.id = id self.data = data def get_id(self): return self.id def get_data(self): return self.data BOOT_MSG = "YoU ArE ThE WeAkEsT LiNk. GoOdByE." class client_base: # Player role definitions def __init__(self): self.outbox = Queue.Queue(0) self.inbox = Queue.Queue(0) self.startedEvent = Event() self.exitEvent = Event() self.sendThreadExitEvent = Event() self.recvThreadExitEvent = Event() self.id = "0" self.group_id = "0" self.name = "" self.role = "GM" self.ROLE_GM = "GM" self.ROLE_PLAYER = "PLAYER" self.ROLE_LURKER = "LURKER" self.ip = socket.gethostbyname(socket.gethostname()) self.remote_ip = None self.version = VERSION self.protocol_version = PROTOCOL_VERSION self.client_string = CLIENT_STRING self.status = MPLAY_DISCONNECTED self.log_console = None self.sock = None self.text_status = "Idle" self.statLock = Lock() self.useroles = 0 self.ROLE_GM="GM" self.ROLE_PLAYER="PLAYER" self.ROLE_LURKER="LURKER" self.lastmessagetime = time.time() self.connecttime = time.time() def sendThread( self, arg ): "Sending thread. This thread reads from the data queue and writes to the socket." # Wait to be told it's okay to start running self.startedEvent.wait() # Loop as long as we have a connection while( self.get_status() == MPLAY_CONNECTED ): try: readMsg = self.outbox.get( block=1 ) except Exception, text: self.log_msg( ("outbox.get() got an exception: ", text) ) # If we are here, it's because we have data to send, no doubt! if self.status == MPLAY_CONNECTED: try: # Send the entire message, properly formated/encoded sent = self.sendMsg( self.sock, readMsg ) except Exception, e: self.log_msg( e ) else: # If we are not connected, purge the data queue self.log_msg( "Data queued without a connection, purging data from queue..." ) self.sendThreadExitEvent.set() self.log_msg( "sendThread has terminated..." ) def recvThread( self, arg ): "Receiving thread. This thread reads from the socket and writes to the data queue." # Wait to be told it's okay to start running self.startedEvent.wait() while( self.get_status() == MPLAY_CONNECTED ): readMsg = self.recvMsg( self.sock ) # Make sure we didn't get disconnected bytes = len( readMsg ) if bytes == 0: break # Check the length of the message bytes = len( readMsg ) # Make sure we are still connected if bytes == 0: break else: # Pass along the message so it can be processed self.inbox.put( readMsg ) self.update_idle_time() #update the last message time if bytes == 0: self.log_msg( "Remote has disconnected!" ) self.set_status( MPLAY_DISCONNECTING ) self.outbox.put( "" ) # Make sure the other thread is woken up! self.sendThreadExitEvent.set() self.log_msg( "recvThread has terminated..." ) def sendMsg( self, sock, msg ): """Very simple function that will properly encode and send a message to te remote on the specified socket.""" # Calculate our message length length = len( msg ) # Encode the message length into network byte order lp = pack( 'i', socket.htonl( length ) ) try: # Send the encoded length sentl = sock.send( lp ) # Now, send the message the the length was describing sentm = sock.send( msg ) if self.isServer(): self.log_msg(("data_sent", sentl+sentm)) except socket.error, e: self.log_msg( e ) except Exception, e: self.log_msg( e ) return sentm def recvData( self, sock, readSize ): """Simple socket receive method. This method will only return when the exact byte count has been read from the connection, if remote terminates our connection or we get some other socket exception.""" data = "" offset = 0 try: while offset != readSize: frag = sock.recv( readSize - offset ) # See if we've been disconnected rs = len( frag ) if rs <= 0: # Loudly raise an exception because we've been disconnected! raise IOError, "Remote closed the connection!" else: # Continue to build complete message offset += rs data += frag except socket.error, e: self.log_msg( e ) data = "" return data def recvMsg( self, sock ): """This method now expects to receive a message having a 4-byte prefix length. It will ONLY read completed messages. In the event that the remote's connection is terminated, it will throw an exception which should allow for the caller to more gracefully handle this exception event. Because we use strictly reading ONLY based on the length that is told to use, we no longer have to worry about partially adjusting for fragmented buffers starting somewhere within a buffer that we've read. Rather, it will get ONLY a whole message and nothing more. Everything else will remain buffered with the OS until we attempt to read the next complete message.""" msgData = "" try: lenData = self.recvData( sock, MPLAY_LENSIZE ) # Now, convert to a usable form (length,) = unpack( 'i', lenData ) length = socket.ntohl( length ) # Read exactly the remaining amount of data msgData = self.recvData( sock, length ) if self.isServer(): self.log_msg(("data_recv", length+4)) # Make the peer IP address available for reference later if self.remote_ip is None: self.remote_ip = self.sock.getpeername() except IOError, e: self.log_msg( e ) except Exception, e: self.log_msg( e ) return msgData def initialize_threads(self): "Starts up our threads (2) and waits for them to make sure they are running!" self.status = MPLAY_CONNECTED self.sock.setblocking(1) # Confirm that our threads have started thread.start_new_thread( self.sendThread,(0,) ) thread.start_new_thread( self.recvThread,(0,) ) self.startedEvent.set() def disconnect(self): self.set_status(MPLAY_DISCONNECTING) self.log_msg("client stub " + self.ip +" disconnecting...") self.log_msg("closing sockets...") try: self.sock.shutdown( 2 ) except Exception, e: print "Caught exception: " + str(e) print print "Continuing" self.set_status(MPLAY_DISCONNECTED) def reset(self,sock): self.disconnect() self.sock = sock self.initialize_threads() def update_role(self,role): self.useroles = 1 self.role = role def use_roles(self): if self.useroles: return 1 else: return 0 def update_self_from_player(self, player): try: (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string,role) = player except Exception, e: print e # The IP field should really be deprecated as too many systems are NAT'd and/or behind firewalls for a # client provided IP address to have much value. As such, we now label it as deprecated. def toxml(self,action): xml_data = "<player name=\""+myescape(self.name) + "\"" xml_data += " action=\""+action+"\" id=\""+self.id + "\"" xml_data += " group_id=\""+self.group_id+"\" ip=\""+self.ip + "\"" xml_data += " status=\""+self.text_status + "\"" xml_data += " version=\""+self.version + "\"" xml_data += " protocol_version=\""+self.protocol_version + "\"" xml_data += " client_string=\""+self.client_string + "\"" xml_data += "/>" return xml_data def log_msg(self,msg): if self.log_console: self.log_console(msg) # else: # print "message", msg def get_status(self): self.statLock.acquire() status = self.status self.statLock.release() return status def my_role(self): if self.role == "GM": return self.ROLE_GM elif self.role == "Player": return self.ROLE_PLAYER elif self.role == "Lurker": return self.ROLE_LURKER return -1 def set_status(self,status): self.statLock.acquire() self.status = status self.statLock.release() def isServer( self ): # Return 1 if we are running as a server, else, return 0. # This method must be overloaded by whomever derives from us pass def __str__(self): return "%s(%s)\nIP:%s\ngroup_id:%s\n" % (self.name, self.id, self.ip, self.group_id) # idle time functions added by snowdog 3/31/04 def update_idle_time(self): self.lastmessagetime = time.time() def idle_time(self): curtime = time.time() idletime = curtime - self.lastmessagetime return idletime def idle_status(self): idletime = self.idle_time() idlemins = idletime / 60 status = "Unknown" if idlemins < 3: status = "Active" elif idlemins < 10: status = "Idle ("+str(int(idlemins))+" mins)" else: status = "Inactive ("+str(int(idlemins))+" mins)" return status def connected_time(self): curtime = time.time() timeoffset = curtime - self.connecttime return timeoffset def connected_time_string(self): "returns the time client has been connected as a formated time string" ct = self.connected_time() d = int(ct/86400) h = int( (ct-(86400*d))/3600 ) m = int( (ct-(86400*d)-(3600*h))/60) s = int( (ct-(86400*d)-(3600*h)-(60*m)) ) cts = zfill(d,2)+":"+zfill(h,2)+":"+zfill(m,2)+":"+zfill(s,2) return cts #======================================================================== # # # MPLAY CLIENT # # #======================================================================== class mplay_client(client_base): "mplay client" def __init__(self,name,callbacks): client_base.__init__(self) self.set_name(name) self.on_receive = callbacks['on_receive'] self.on_mplay_event = callbacks['on_mplay_event'] self.on_group_event = callbacks['on_group_event'] self.on_player_event = callbacks['on_player_event'] self.on_status_event = callbacks['on_status_event'] self.on_password_signal = callbacks['on_password_signal'] # I know this is a bad thing to do but it has to be # be done to use the unified password manager. # Should really find a better solution. -- SD 8/03 self.orpgFrame_callback = callbacks['orpgFrame'] self.settings = self.orpgFrame_callback.settings #self.version = VERSION #self.protocol_version = PROTOCOL_VERSION #self.client_string = CLIENT_STRING self.ignore_id = [] self.ignore_name = [] self.players = {} self.groups = {} self.unique_cookie = 0 self.msg_handlers = {} self.core_msg_handlers = [] self.load_core_msg_handlers() # implement from our base class def isServer( self ): return 0 def set_name(self,name): self.name = name self.update() def set_text_status(self,status): if self.text_status != status: self.text_status = status self.update() def set_status_url(self,url="None"): self.on_status_event(mplay_event(STATUS_SET_URL,url)) def update(self): if self.status == MPLAY_CONNECTED: self.outbox.put(self.toxml('update')) self.inbox.put(self.toxml('update')) def get_group_info(self,id=0): self.statLock.acquire() id = self.groups[id] self.statLock.release() return id def get_my_group(self): self.statLock.acquire() id = self.groups[self.group_id] self.statLock.release() return id def get_groups(self): self.statLock.acquire() groups = self.groups.values() self.statLock.release() return groups def get_players(self): self.statLock.acquire() players = self.players.values() self.statLock.release() return players def get_player_info(self,id): self.statLock.acquire() player = self.players[id] self.statLock.release() return player def get_player_by_player_id(self,player): players = self.get_players() if self.players.has_key(player): for m in players: if player == m[2]: return m return -1 def get_id(self): return self.id def get_my_info(self): return (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string, self.role) def is_valid_id(self,id): self.statLock.acquire() value = self.players.has_key( id ) self.statLock.release() return value def clear_players(self,save_self=0): self.statLock.acquire() keys = self.players.keys() for k in keys: del self.players[k] self.statLock.release() def clear_groups(self): self.statLock.acquire() keys = self.groups.keys() for k in keys: del self.groups[k] self.statLock.release() def find_role(self,id): return self.players[id].role def get_ignore_list(self): try: return (self.ignore_id, self.ignore_name) except: return (None, None) def toggle_ignore(self, id): for m in self.ignore_id: if `self.ignore_id[self.ignore_id.index(m)]` == `id`: name = self.ignore_name[self.ignore_id.index(m)] self.ignore_id.remove(m) self.ignore_name.remove(name) return (0,id,name) self.ignore_name.append(self.players[id][0]) self.ignore_id.append(self.players[id][2]) return (1,self.players[id][2],self.players[id][0]) def boot_player(self,id,boot_pwd = ""): #self.send(BOOT_MSG,id) msg = '<boot boot_pwd="' + boot_pwd + '"/>' self.send(msg,id) #--------------------------------------------------------- # [START] Snowdog Password/Room Name altering code 12/02 #--------------------------------------------------------- def set_room_pass(self,npwd,pwd=""): self.outbox.put("<alter key=\"pwd\" val=\"" +npwd+ "\" bpw=\"" + pwd + "\" plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />") self.update() def set_room_name(self,name,pwd=""): loc = name.find("&") oldloc=0 while loc > -1: loc = name.find("&",oldloc) if loc > -1: b = name[:loc] e = name[loc+1:] name = b + "&" + e oldloc = loc+1 loc = name.find('"') oldloc=0 while loc > -1: loc = name.find('"',oldloc) if loc > -1: b = name[:loc] e = name[loc+1:] name = b + """ + e oldloc = loc+1 loc = name.find("'") oldloc=0 while loc > -1: loc = name.find("'",oldloc) if loc > -1: b = name[:loc] e = name[loc+1:] name = b + "'" + e oldloc = loc+1 self.outbox.put("<alter key=\"name\" val=\"" + name + "\" bpw=\"" + pwd + "\" plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />") self.update() #--------------------------------------------------------- # [END] Snowdog Password/Room Name altering code 12/02 #--------------------------------------------------------- def display_roles(self): self.outbox.put("<role action=\"display\" player=\"" + self.id +"\" group_id=\""+self.group_id + "\" />") def get_role(self): self.outbox.put("<role action=\"get\" player=\"" + self.id +"\" group_id=\""+self.group_id + "\" />") def set_role(self,player,role,pwd=""): self.outbox.put("<role action=\"set\" player=\"" + player + "\" role=\"" +role+ "\" boot_pwd=\"" + pwd + "\" group_id=\"" + self.group_id + "\" />") self.update() def send(self,msg,player="all"): if self.status == MPLAY_CONNECTED and player != self.id: self.outbox.put("<msg to='"+player+"' from='"+self.id+"' group_id='"+self.group_id+"' />"+msg) self.check_my_status() def send_create_group(self,name,pwd,boot_pwd,minversion): self.outbox.put("<create_group from=\""+self.id+"\" pwd=\""+pwd+"\" name=\""+ name+"\" boot_pwd=\""+boot_pwd+"\" min_version=\"" + minversion +"\" />") def send_join_group(self,group_id,pwd): if (group_id != 0): self.update_role("LURKER") self.outbox.put("<join_group from=\""+self.id+"\" pwd=\""+pwd+"\" group_id=\""+str(group_id)+"\" />") def poll(self): try: msg = self.inbox.get_nowait() except: if self.get_status() <> MPLAY_CONNECTED: self.check_my_status() else: try: self.pretranslate(msg) except Exception, e: print "The following message: " + str(msg) print "created the following exception: " traceback.print_exc() print self.players self.poll() def add_msg_handler(self, tag, function, core=False): if not self.msg_handlers.has_key(tag): self.msg_handlers[tag] = function if core: self.core_msg_handlers.append(tag) else: print 'XML Messages ' + tag + ' already has a handler' def remove_msg_handler(self, tag): if self.msg_handlers.has_key(tag) and not tag in self.core_msg_handlers: del self.msg_handlers[tag] else: print 'XML Messages ' + tag + ' already deleted' def load_core_msg_handlers(self): self.add_msg_handler('msg', self.on_msg, True) self.add_msg_handler('ping', self.on_ping, True) self.add_msg_handler('group', self.on_group, True) self.add_msg_handler('role', self.on_role, True) self.add_msg_handler('player', self.on_player, True) self.add_msg_handler('password', self.on_password, True) def pretranslate(self,data): # Pre-qualify our data. If we don't have atleast 5-bytes, then there is # no way we even have a valid message! if len(data) < 5: return end = data.find(">") head = data[:end+1] msg = data[end+1:] xml_dom = parseXml(head) xml_dom = xml_dom._get_documentElement() tag_name = xml_dom._get_tagName() id = xml_dom.getAttribute("from") if id == '': id = xml_dom.getAttribute("id") if self.msg_handlers.has_key(tag_name): self.msg_handlers[tag_name](id, data, xml_dom) else: #Unknown messages recived ignoring #using pass insted or printing an error message #because plugins should now be able to send and proccess messages #if someone is using a plugin to send messages and this user does not #have the plugin they would be getting errors pass if xml_dom: xml_dom.unlink() def on_msg(self, id, data, xml_dom): end = data.find(">") head = data[:end+1] msg = data[end+1:] if id == "0": self.on_receive(msg,None) # None get's interpreted in on_receive as the sys admin. # Doing it this way makes it harder to impersonate the admin else: if self.is_valid_id(id): self.on_receive(msg,self.players[id]) if xml_dom: xml_dom.unlink() def on_ping(self, id, msg, xml_dom): #a REAL ping time implementation by Snowdog 8/03 # recieves special server <ping time="###" /> command # where ### is a returning time from the clients ping command #get current time, pull old time from object and compare them # the difference is the latency between server and client * 2 ct = time.clock() ot = xml_dom.getAttribute("time") latency = float(float(ct) - float(ot)) latency = int( latency * 10000.0 ) latency = float( latency) / 10.0 ping_msg = "Ping Results: "+str(latency)+" ms (parsed message, round trip)" self.on_receive(ping_msg,None) if xml_dom: xml_dom.unlink() def on_group(self, id, msg, xml_dom): name = xml_dom.getAttribute("name") players = xml_dom.getAttribute("players") act = xml_dom.getAttribute("action") pwd = xml_dom.getAttribute("pwd") group_data = (id,name,pwd,players) if act=='new': self.groups[id] = group_data self.on_group_event(mplay_event(GROUP_NEW,group_data)) elif act=='del': self.on_group_event(mplay_event(GROUP_DEL,group_data)) del self.groups[id] elif act=='update': self.groups[id] = group_data self.on_group_event(mplay_event(GROUP_UPDATE,group_data)) if xml_dom: xml_dom.unlink() def on_role(self, id, msg, xml_dom): act = xml_dom.getAttribute("action") role = xml_dom.getAttribute("role") if (act == "set") or (act == "update"): try: (a,b,c,d,e,f,g,h) = self.players[id] if id == self.id: self.players[id] = (a,b,c,d,e,f,g,role) self.update_role(role) else: self.players[id] = (a,b,c,d,e,f,g,role) self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) except: pass if xml_dom: xml_dom.unlink() def on_player(self, id, msg, xml_dom): act = xml_dom.getAttribute("action") ip = xml_dom.getAttribute("ip") name = xml_dom.getAttribute("name") status = xml_dom.getAttribute("status") version = xml_dom.getAttribute("version") protocol_version = xml_dom.getAttribute("protocol_version") client_string = xml_dom.getAttribute("client_string") try: player = (name,ip,id,status,version,protocol_version,client_string,self.players[id][7]) except Exception, e: player = (name,ip,id,status,version,protocol_version,client_string,"Player") if act == "new": self.players[id] = player self.on_player_event(mplay_event(PLAYER_NEW,self.players[id])) elif act == "group": self.group_id = xml_dom.getAttribute("group_id") self.clear_players() self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE,self.groups[self.group_id])) self.players[self.id] = self.get_my_info() #(self.name,self.ip,self.id,self.text_status) self.on_player_event(mplay_event(PLAYER_NEW,self.players[self.id])) elif act == "failed": self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE_F)) elif act == "del": self.on_player_event(mplay_event(PLAYER_DEL,self.players[id])) del self.players[id] if id == self.id: self.do_disconnect() # the next two cases handle the events that are used to let you know when others are typing elif act == "update": if id == self.id: self.players[id] = player self.update_self_from_player(player) else: self.players[id] = player dont_send = 0 for m in self.ignore_id: if m == id: dont_send=1 if dont_send != 1: self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) if xml_dom: xml_dom.unlink() def on_password(self, id, msg, xml_dom): signal = type = id = data = None id = xml_dom.getAttribute("id") type = xml_dom.getAttribute("type") signal = xml_dom.getAttribute("signal") data = xml_dom.getAttribute("data") self.on_password_signal( signal,type,id,data ) if xml_dom: xml_dom.unlink() def check_my_status(self): status = self.get_status() if status == MPLAY_DISCONNECTING: self.do_disconnect() def connect(self,addressport): """Establish a connection to a server while still using sendThread & recvThread for its communication.""" if self.is_connected(): self.log_msg( "Client is already connected to a server?!? Need to disconnect first." ) return 0 xml_dom = None self.inbox = Queue.Queue(0) self.outbox = Queue.Queue(0) addressport_ar = addressport.split(":") if len(addressport_ar) == 1: address = addressport_ar[0] port = OPENRPG_PORT else: address = addressport_ar[0] port = int(addressport_ar[1]) self.host_server = addressport self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.sock.connect((address,port)) # send client into with id=0 self.sendMsg( self.sock, self.toxml("new") ) data = self.recvMsg( self.sock ) # get new id and group_id xml_dom = parseXml(data) xml_dom = xml_dom._get_documentElement() self.id = xml_dom.getAttribute("id") self.group_id = xml_dom.getAttribute("group_id") #send confirmation self.sendMsg( self.sock, self.toxml("new") ) except Exception, e: self.log_msg(e) if xml_dom: xml_dom.unlink() return 0 # Start things rollings along self.initialize_threads() self.on_mplay_event(mplay_event(MPLAY_CONNECTED)) self.players[self.id] = (self.name,self.ip,self.id,self.text_status,self.version,self.protocol_version,self.client_string,self.role) self.on_player_event(mplay_event(PLAYER_NEW,self.players[self.id])) if xml_dom: xml_dom.unlink() return 1 def start_disconnect(self): self.on_mplay_event(mplay_event(MPLAY_DISCONNECTING)) self.outbox.put( self.toxml("del") ) ## Client Side Disconect Forced -- Snowdog 10-09-2003 #pause to allow GUI events time to sync. time.sleep(1) self.do_disconnect() def do_disconnect(self): client_base.disconnect(self) self.clear_players() self.clear_groups() self.useroles = 0 ... [truncated message content] |