Imported from archive.
[mudpy.git] / mudpy.py
index b149fc4..8519d05 100644 (file)
--- a/mudpy.py
+++ b/mudpy.py
@@ -9,14 +9,39 @@ from md5 import new as new_md5
 from os import R_OK, access, chmod, makedirs, stat
 from os.path import abspath, dirname, exists, isabs, join as path_join
 from random import choice, randrange
+from re import match
 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
 from stat import S_IMODE, ST_MODE
+from sys import stderr
+from syslog import LOG_PID, LOG_INFO, LOG_DAEMON, closelog, openlog, syslog
+from telnetlib import DO, DONT, ECHO, EOR, GA, IAC, LINEMODE, SB, SE, SGA, WILL, WONT
 from time import asctime, sleep
+from traceback import format_exception
+
+def excepthook(excepttype, value, traceback):
+       """Handle uncaught exceptions."""
+
+       # assemble the list of errors into a single string
+       message = "".join(format_exception(excepttype, value, traceback))
+
+       # try to log it, if possible
+       try: log(message, 9)
+       except: pass
+
+       # try to write it to stderr, if possible
+       try: stderr.write(message)
+       except: pass
+
+# redefine sys.excepthook with ours
+import sys
+sys.excepthook = excepthook
 
 class Element:
        """An element of the universe."""
        def __init__(self, key, universe, origin=""):
                """Default values for the in-memory element variables."""
+               self.owner = None
+               self.contents = {}
                self.key = key
                if self.key.find(":") > 0:
                        self.category, self.subkey = self.key.split(":", 1)
@@ -34,50 +59,166 @@ class Element:
                        DataFile(self.origin, universe)
                if not universe.files[self.origin].data.has_section(self.key):
                        universe.files[self.origin].data.add_section(self.key)
-       def delete(self):
-               log("Deleting: " + self.key + ".")
+       def destroy(self):
+               """Remove an element from the universe and destroy it."""
+               log("Destroying: " + self.key + ".", 2)
                universe.files[self.origin].data.remove_section(self.key)
                del universe.categories[self.category][self.subkey]
                del universe.contents[self.key]
                del self
+       def delete(self, facet):
+               """Delete a facet from the element."""
+               if universe.files[self.origin].data.has_option(self.key, facet):
+                       universe.files[self.origin].data.remove_option(self.key, facet)
        def facets(self):
-               """Return a list of facets for this element."""
-               return universe.files[self.origin].data.options(self.key)
-       def get(self, facet, default=""):
+               """Return a list of non-inherited facets for this element."""
+               if self.key in universe.files[self.origin].data.sections():
+                       return universe.files[self.origin].data.options(self.key)
+               else: return []
+       def has_facet(self, facet):
+               """Return whether the non-inherited facet exists."""
+               return facet in self.facets()
+       def remove_facet(self, facet):
+               """Remove a facet from the element."""
+               if self.has_facet(facet): universe.files[self.origin].data.remove_option(self.key, facet)
+       def ancestry(self):
+               """Return a list of the element's inheritance lineage."""
+               if self.has_facet("inherit"):
+                       ancestry = self.getlist("inherit")
+                       for parent in ancestry[:]:
+                               ancestors = universe.contents[parent].ancestry()
+                               for ancestor in ancestors:
+                                       if ancestor not in ancestry: ancestry.append(ancestor)
+                       return ancestry
+               else: return []
+       def get(self, facet, default=None):
                """Retrieve values."""
+               if default is None: default = ""
                if universe.files[self.origin].data.has_option(self.key, facet):
                        return universe.files[self.origin].data.get(self.key, facet)
+               elif self.has_facet("inherit"):
+                       for ancestor in self.ancestry():
+                               if universe.contents[ancestor].has_facet(facet):
+                                       return universe.contents[ancestor].get(facet)
                else: return default
-       def getboolean(self, facet, default=False):
+       def getboolean(self, facet, default=None):
                """Retrieve values as boolean type."""
+               if default is None: default=False
                if universe.files[self.origin].data.has_option(self.key, facet):
                        return universe.files[self.origin].data.getboolean(self.key, facet)
+               elif self.has_facet("inherit"):
+                       for ancestor in self.ancestry():
+                               if universe.contents[ancestor].has_facet(facet):
+                                       return universe.contents[ancestor].getboolean(facet)
                else: return default
-       def getint(self, facet, default=0):
+       def getint(self, facet, default=None):
                """Return values as int/long type."""
+               if default is None: default = 0
                if universe.files[self.origin].data.has_option(self.key, facet):
                        return universe.files[self.origin].data.getint(self.key, facet)
+               elif self.has_facet("inherit"):
+                       for ancestor in self.ancestry():
+                               if universe.contents[ancestor].has_facet(facet):
+                                       return universe.contents[ancestor].getint(facet)
                else: return default
-       def getfloat(self, facet, default=0.0):
+       def getfloat(self, facet, default=None):
                """Return values as float type."""
+               if default is None: default = 0.0
                if universe.files[self.origin].data.has_option(self.key, facet):
                        return universe.files[self.origin].data.getfloat(self.key, facet)
+               elif self.has_facet("inherit"):
+                       for ancestor in self.ancestry():
+                               if universe.contents[ancestor].has_facet(facet):
+                                       return universe.contents[ancestor].getfloat(facet)
                else: return default
-       def getlist(self, facet, default=[]):
+       def getlist(self, facet, default=None):
                """Return values as list type."""
+               if default is None: default = []
                value = self.get(facet)
-               if not value: return default
-               else: return makelist(value)
-       def getdict(self, facet, default={}):
+               if value: return makelist(value)
+               else: return default
+       def getdict(self, facet, default=None):
                """Return values as dict type."""
+               if default is None: default = {}
                value = self.get(facet)
-               if not value: return default
-               else: return makedict(value)
+               if value: return makedict(value)
+               else: return default
        def set(self, facet, value):
                """Set values."""
-               if type(value) is long: value = repr(value).rstrip("L")
+               if type(value) is long: value = str(value)
                elif not type(value) is str: value = repr(value)
                universe.files[self.origin].data.set(self.key, facet, value)
+       def append(self, facet, value):
+               """Append value tp a list."""
+               if type(value) is long: value = str(value)
+               elif not type(value) is str: value = repr(value)
+               newlist = self.getlist(facet)
+               newlist.append(value)
+               self.set(facet, newlist)
+       def send(self, message, eol="$(eol)"):
+               """Convenience method to pass messages to an owner."""
+               if self.owner: self.owner.send(message, eol)
+       def go_to(self, location):
+               """Relocate the element to a specific location."""
+               current = self.get("location")
+               if current and self.key in universe.contents[current].contents:
+                       del universe.contents[current].contents[self.key]
+               if location in universe.contents: self.set("location", location)
+               universe.contents[location].contents[self.key] = self
+               self.look_at(location)
+       def go_home(self):
+               """Relocate the element to its default location."""
+               self.go_to(self.get("default_location"))
+               self.echo_to_location("You suddenly realize that " + self.get("name") + " is here.")
+       def move_direction(self, direction):
+               """Relocate the element in a specified direction."""
+               self.echo_to_location(self.get("name") + " exits " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
+               self.send("You exit " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
+               self.go_to(universe.contents[self.get("location")].link_neighbor(direction))
+               self.echo_to_location(self.get("name") + " arrives from " + universe.categories["internal"]["directions"].getdict(direction)["enter"] + ".")
+       def look_at(self, key):
+               """Show an element to another element."""
+               if self.owner:
+                       element = universe.contents[key]
+                       message = ""
+                       name = element.get("name")
+                       if name: message += "$(cyn)" + name + "$(nrm)$(eol)"
+                       description = element.get("description")
+                       if description: message += description + "$(eol)"
+                       portal_list = element.portals().keys()
+                       if portal_list:
+                               portal_list.sort()
+                               message += "$(cyn)[ Exits: " + ", ".join(portal_list) + " ]$(nrm)$(eol)"
+                       for element in universe.contents[self.get("location")].contents.values():
+                               if element.getboolean("is_actor") and element is not self:
+                                       message += "$(yel)" + element.get("name") + " is here.$(nrm)$(eol)"
+                       self.send(message)
+       def portals(self):
+               """Map the portal directions for a room to neighbors."""
+               portals = {}
+               if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
+                       coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
+                       directions = universe.categories["internal"]["directions"]
+                       offsets = dict([(x, directions.getdict(x)["vector"]) for x in directions.facets()])
+                       for portal in self.getlist("gridlinks"):
+                               adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
+                               neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
+                               if neighbor in universe.contents: portals[portal] = neighbor
+               for facet in self.facets():
+                       if facet.startswith("link_"):
+                               neighbor = self.get(facet)
+                               if neighbor in universe.contents:
+                                       portal = facet.split("_")[1]
+                                       portals[portal] = neighbor
+               return portals
+       def link_neighbor(self, direction):
+               """Return the element linked in a given direction."""
+               portals = self.portals()
+               if direction in portals: return portals[direction]
+       def echo_to_location(self, message):
+               """Show a message to other elements in the current location."""
+               for element in universe.contents[self.get("location")].contents.values():
+                       if element is not self: element.send(message)
 
 class DataFile:
        """A file containing universe elements."""
@@ -86,37 +227,59 @@ class DataFile:
                if access(filename, R_OK): self.data.read(filename)
                self.filename = filename
                universe.files[filename] = self
-               if self.data.has_option("control", "include_files"):
-                       includes = makelist(self.data.get("control", "include_files"))
+               if self.data.has_option("__control__", "include_files"):
+                       includes = makelist(self.data.get("__control__", "include_files"))
                else: includes = []
-               if self.data.has_option("control", "default_files"):
-                       origins = makedict(self.data.get("control", "default_files"))
+               if self.data.has_option("__control__", "default_files"):
+                       origins = makedict(self.data.get("__control__", "default_files"))
                        for key in origins.keys():
                                if not key in includes: includes.append(key)
                                universe.default_origins[key] = origins[key]
                                if not key in universe.categories:
                                        universe.categories[key] = {}
-               if self.data.has_option("control", "private_files"):
-                       for item in makelist(self.data.get("control", "private_files")):
+               if self.data.has_option("__control__", "private_files"):
+                       for item in makelist(self.data.get("__control__", "private_files")):
                                if not item in includes: includes.append(item)
                                if not item in universe.private_files:
                                        if not isabs(item):
                                                item = path_join(dirname(filename), item)
                                        universe.private_files.append(item)
                for section in self.data.sections():
-                       if section != "control":
+                       if section != "__control__":
                                Element(section, universe, filename)
                for include_file in includes:
                        if not isabs(include_file):
                                include_file = path_join(dirname(filename), include_file)
                        DataFile(include_file, universe)
        def save(self):
-               if self.data.sections() and ( not self.data.has_option("control", "read_only") or not self.data.getboolean("control", "read_only") ):
-                       if not exists(dirname(self.filename)): makedirs(dirname)
+               """Write the data, if necessary."""
+
+               # when there is content or the file exists, but is not read-only
+               if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("__control__", "read_only") and self.data.getboolean("__control__", "read_only") ):
+
+                       # make parent directories if necessary
+                       if not exists(dirname(self.filename)):
+                               makedirs(dirname(self.filename))
+
+                       # our data file
                        file_descriptor = file(self.filename, "w")
+
+                       # if it's marked private, chmod it appropriately
                        if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
                                chmod(self.filename, 0600)
-                       self.data.write(file_descriptor)
+
+                       # write it back sorted, instead of using ConfigParser
+                       sections = self.data.sections()
+                       sections.sort()
+                       for section in sections:
+                               file_descriptor.write("[" + section + "]\n")
+                               options = self.data.options(section)
+                               options.sort()
+                               for option in options:
+                                       file_descriptor.write(option + " = " + self.data.get(section, option) + "\n")
+                               file_descriptor.write("\n")
+
+                       # flush and close the file
                        file_descriptor.flush()
                        file_descriptor.close()
 
@@ -129,6 +292,7 @@ class Universe:
                self.default_origins = {}
                self.files = {}
                self.private_files = []
+               self.loglist = []
                self.userlist = []
                self.terminate_world = False
                self.reload_modules = False
@@ -187,13 +351,16 @@ class User:
                self.connection = None
                self.authenticated = False
                self.password_tries = 0
-               self.state = "entering_account_name"
+               self.state = "initial"
                self.menu_seen = False
                self.error = ""
                self.input_queue = []
                self.output_queue = []
                self.partial_input = ""
                self.echoing = True
+               self.received_newline = True
+               self.terminator = IAC+GA
+               self.negotiation_pause = 0
                self.avatar = None
                self.account = None
 
@@ -204,7 +371,8 @@ class User:
                if name: message = "User " + name
                else: message = "An unnamed user"
                message += " logged out."
-               log(message)
+               log(message, 2)
+               self.deactivate_avatar()
                self.connection.close()
                self.remove()
 
@@ -231,6 +399,9 @@ class User:
                        "output_queue",
                        "partial_input",
                        "echoing",
+                       "received_newline",
+                       "terminator",
+                       "negotiation_pause",
                        "avatar",
                        "account"
                        ]:
@@ -255,14 +426,14 @@ class User:
                        if old_user.account.get("name") == self.account.get("name") and old_user is not self:
 
                                # make a note of it
-                               log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".")
-                               old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)")
-                               self.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
+                               log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
+                               old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
 
                                # close the old connection
                                old_user.connection.close()
 
                                # replace the old connection with this one
+                               old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
                                old_user.connection = self.connection
                                old_user.last_address = old_user.address
                                old_user.address = self.address
@@ -280,14 +451,16 @@ class User:
        def authenticate(self):
                """Flag the user as authenticated and disconnect duplicates."""
                if not self.state is "authenticated":
-                       log("User " + self.account.get("name") + " logged in.")
+                       log("User " + self.account.get("name") + " logged in.", 2)
                        self.authenticated = True
+                       if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
+                               self.account.set("administrator", "True")
 
        def show_menu(self):
                """Send the user their current menu."""
                if not self.menu_seen:
                        self.menu_choices = get_menu_choices(self)
-                       self.send(get_menu(self.state, self.error, self.echoing, self.menu_choices), "")
+                       self.send(get_menu(self.state, self.error, self.echoing, self.terminator, self.menu_choices), "")
                        self.menu_seen = True
                        self.error = False
                        self.adjust_echoing()
@@ -301,37 +474,47 @@ class User:
                """Remove a user from the list of connected users."""
                universe.userlist.remove(self)
 
-       def send(self, output, eol="$(eol)"):
+       def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
                """Send arbitrary text to a connected user."""
 
-               # only when there is actual output
-               #if output:
+               # unless raw mode is on, clean it up all nice and pretty
+               if not raw:
 
-               # start with a newline, append the message, then end
-               # with the optional eol string passed to this function
-               # and the ansi escape to return to normal text
-               output = "\r\n" + output + eol + chr(27) + "[0m"
+                       # strip extra $(eol) off if present
+                       while output.startswith("$(eol)"): output = output[6:]
+                       while output.endswith("$(eol)"): output = output[:-6]
 
-               # find and replace macros in the output
-               output = replace_macros(self, output)
+                       # we'll take out GA or EOR and add them back on the end
+                       if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
+                               terminate = True
+                               output = output[:-2]
+                       else: terminate = False
 
-               # wrap the text at 80 characters
-               # TODO: prompt user for preferred wrap width
-               output = wrap_ansi_text(output, 80)
+                       # start with a newline, append the message, then end
+                       # with the optional eol string passed to this function
+                       # and the ansi escape to return to normal text
+                       if not just_prompt: output = "$(eol)$(eol)" + output
+                       output += eol + chr(27) + "[0m"
 
-               # drop the formatted output into the output queue
-               self.output_queue.append(output)
+                       # tack on a prompt if active
+                       if self.state == "active":
+                               if not just_prompt: output += "$(eol)"
+                               if add_prompt: output += "> "
 
-               # try to send the last item in the queue, remove it and
-               # flag that menu display is not needed
-               try:
-                       self.connection.send(self.output_queue[0])
-                       self.output_queue.remove(self.output_queue[0])
-                       self.menu_seen = False
+                       # find and replace macros in the output
+                       output = replace_macros(self, output)
 
-               # but if we can't, that's okay too
-               except:
-                       pass
+                       # wrap the text at 80 characters
+                       output = wrap_ansi_text(output, 80)
+
+                       # tack the terminator back on
+                       if terminate: output += self.terminator
+
+               # drop the output into the user's output queue
+               self.output_queue.append(output)
+
+               # if this is urgent, flush all pending output
+               if flush: self.flush()
 
        def pulse(self):
                """All the things to do to the user per increment."""
@@ -341,21 +524,39 @@ class User:
                        self.state = "disconnecting"
                        self.menu_seen = False
 
+               # if output is paused, decrement the counter
+               if self.state == "initial":
+                       if self.negotiation_pause: self.negotiation_pause -= 1
+                       else: self.state = "entering_account_name"
+
                # show the user a menu as needed
-               self.show_menu()
+               elif not self.state == "active": self.show_menu()
+
+               # flush any pending output in teh queue
+               self.flush()
 
                # disconnect users with the appropriate state
-               if self.state == "disconnecting":
-                       self.quit()
+               if self.state == "disconnecting": self.quit()
 
-               # the user is unique and not flagged to disconnect
-               else:
-               
-                       # check for input and add it to the queue
-                       self.enqueue_input()
+               # check for input and add it to the queue
+               self.enqueue_input()
+
+               # there is input waiting in the queue
+               if self.input_queue: handle_user_input(self)
+
+       def flush(self):
+               """Try to send the last item in the queue and remove it."""
+               if self.output_queue:
+                       if self.received_newline:
+                               self.received_newline = False
+                               if self.output_queue[0].startswith("\r\n"):
+                                       self.output_queue[0] = self.output_queue[0][2:]
+                       try:
+                               self.connection.send(self.output_queue[0])
+                               del self.output_queue[0]
+                       except:
+                               pass
 
-                       # there is input waiting in the queue
-                       if self.input_queue: handle_user_input(self)
 
        def enqueue_input(self):
                """Process and enqueue any new input."""
@@ -372,6 +573,9 @@ class User:
                        # tack this on to any previous partial
                        self.partial_input += input_data
 
+                       # reply to and remove any IAC negotiation codes
+                       self.negotiate_telnet_options()
+
                        # separate multiple input lines
                        new_input_lines = self.partial_input.split("\n")
 
@@ -389,8 +593,20 @@ class User:
                        # iterate over the remaining lines
                        for line in new_input_lines:
 
+                               # remove a trailing carriage return
+                               if line.endswith("\r"): line = line.rstrip("\r")
+
+                               # log non-printable characters remaining
+                               removed = filter(lambda x: (x < " " or x > "~"), line)
+                               if removed:
+                                       logline = "Non-printable characters from "
+                                       if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
+                                       else: logline += "unknown user: "
+                                       logline += repr(removed)
+                                       log(logline, 4)
+
                                # filter out non-printables
-                               line = filter(lambda x: x>=' ' and x<='~', line)
+                               line = filter(lambda x: " " <= x <= "~", line)
 
                                # strip off extra whitespace
                                line = line.strip()
@@ -398,23 +614,133 @@ class User:
                                # put on the end of the queue
                                self.input_queue.append(line)
 
+       def negotiate_telnet_options(self):
+               """Reply to/remove partial_input telnet negotiation options."""
+
+               # start at the begining of the input
+               position = 0
+
+               # make a local copy to play with
+               text = self.partial_input
+
+               # as long as we haven't checked it all
+               while position < len(text):
+
+                       # jump to the first IAC you find
+                       position = text.find(IAC, position)
+
+                       # if there wasn't an IAC in the input, skip to the end
+                       if position < 0: position = len(text)
+
+                       # replace a double (literal) IAC if there's an LF later
+                       elif len(text) > position+1 and text[position+1] == IAC:
+                               if text.find("\n", position) > 0: text = text.replace(IAC+IAC, IAC)
+                               else: position += 1
+                               position += 1
+
+                       # this must be an option negotiation
+                       elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
+
+                               negotiation = text[position+1:position+3]
+
+                               # if we turned echo off, ignore the confirmation
+                               if not self.echoing and negotiation == DO+ECHO: pass
+
+                               # allow LINEMODE
+                               elif negotiation == WILL+LINEMODE: self.send(IAC+DO+LINEMODE, raw=True)
+
+                               # if the client likes EOR instead of GA, make a note of it
+                               elif negotiation == DO+EOR: self.terminator = IAC+EOR
+                               elif negotiation == DONT+EOR and self.terminator == IAC+EOR:
+                                       self.terminator = IAC+GA
+
+                               # if the client doesn't want GA, oblige
+                               elif negotiation == DO+SGA and self.terminator == IAC+GA:
+                                       self.terminator = ""
+                                       self.send(IAC+WILL+SGA, raw=True)
+
+                               # we don't want to allow anything else
+                               elif text[position+1] == DO: self.send(IAC+WONT+text[position+2], raw=True)
+                               elif text[position+1] == WILL: self.send(IAC+DONT+text[position+2], raw=True)
+
+                               # strip the negotiation from the input
+                               text = text.replace(text[position:position+3], "")
+
+                       # get rid of IAC SB .* IAC SE
+                       elif len(text) > position+4 and text[position:position+2] == IAC+SB:
+                               end_subnegotiation = text.find(IAC+SE, position)
+                               if end_subnegotiation > 0: text = text[:position] + text[end_subnegotiation+2:]
+                               else: position += 1
+
+                       # otherwise, strip out a two-byte IAC command
+                       elif len(text) > position+2: text = text.replace(text[position:position+2], "")
+
+                       # and this means we got the begining of an IAC
+                       else: position += 1
+
+               # replace the input with our cleaned-up text
+               self.partial_input = text
+
+       def can_run(self, command):
+               """Check if the user can run this command object."""
+
+               # has to be in the commands category
+               if command not in universe.categories["command"].values(): result = False
+
+               # administrators can run any command
+               elif self.account.getboolean("administrator"): result = True
+
+               # everyone can run non-administrative commands
+               elif not command.getboolean("administrative"): result = True
+
+               # otherwise the command cannot be run by this user
+               else: result = False
+
+               # pass back the result
+               return result
+
        def new_avatar(self):
                """Instantiate a new, unconfigured avatar for this user."""
-               counter = universe.categories["internal"]["counters"].getint("next_avatar")
-               while "avatar:" + repr(counter + 1) in universe.categories["actor"].keys(): counter += 1
-               universe.categories["internal"]["counters"].set("next_avatar", counter + 1)
-               self.avatar = Element("actor:avatar:" + repr(counter), universe)
+               counter = 0
+               while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
+               self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
+               self.avatar.append("inherit", "template:actor")
+               self.account.append("avatars", self.avatar.key)
+
+       def delete_avatar(self, avatar):
+               """Remove an avatar from the world and from the user's list."""
+               if self.avatar is universe.contents[avatar]: self.avatar = None
+               universe.contents[avatar].destroy()
                avatars = self.account.getlist("avatars")
-               avatars.append(self.avatar.key)
+               avatars.remove(avatar)
                self.account.set("avatars", avatars)
 
+       def activate_avatar_by_index(self, index):
+               """Enter the world with a particular indexed avatar."""
+               self.avatar = universe.contents[self.account.getlist("avatars")[index]]
+               self.avatar.owner = self
+               self.state = "active"
+               self.avatar.go_home()
+
+       def deactivate_avatar(self):
+               """Have the active avatar leave the world."""
+               if self.avatar:
+                       current = self.avatar.get("location")
+                       self.avatar.set("default_location", current)
+                       self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
+                       del universe.contents[current].contents[self.avatar.key]
+                       self.avatar.remove_facet("location")
+                       self.avatar.owner = None
+                       self.avatar = None
+
+       def destroy(self):
+               """Destroy the user and associated avatars."""
+               for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
+               self.account.destroy()
+
        def list_avatar_names(self):
-               """A test function to list names of assigned avatars."""
-               avatars = self.account.getlist("avatars")
-               avatar_names = []
-               for avatar in avatars:
-                       avatar_names.append(universe.contents[avatar].get("name"))
-               return avatar_names
+               """List names of assigned avatars."""
+               return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
 
 def makelist(value):
        """Turn string into list type."""
@@ -427,18 +753,52 @@ def makedict(value):
        elif value.find(":") > 0: return eval("{" + value + "}")
        else: return { value: None }
 
-def broadcast(message):
+def broadcast(message, add_prompt=True):
        """Send a message to all connected users."""
-       for each_user in universe.userlist: each_user.send("$(eol)" + message)
+       for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
 
-def log(message):
+def log(message, level=0):
        """Log a message."""
 
-       # the time in posix log timestamp format
+       # a couple references we need
+       file_name = universe.categories["internal"]["logging"].get("file")
+       max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
+       syslog_name = universe.categories["internal"]["logging"].get("syslog")
        timestamp = asctime()[4:19]
 
-       # send the timestamp and message to standard output
-       print(timestamp + " " + message)
+       # turn the message into a list of lines
+       lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
+
+       # send the timestamp and line to a file
+       if file_name:
+               file_descriptor = file(file_name, "a")
+               for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
+               file_descriptor.flush()
+               file_descriptor.close()
+
+       # send the timestamp and line to standard output
+       if universe.categories["internal"]["logging"].getboolean("stdout"):
+               for line in lines: print(timestamp + " " + line)
+
+       # send the line to the system log
+       if syslog_name:
+               openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
+               for line in lines: syslog(line)
+               closelog()
+
+       # display to connected administrators
+       for user in universe.userlist:
+               if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
+                       # iterate over every line in the message
+                       full_message = ""
+                       for line in lines:
+                               full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
+                       user.send(full_message, flush=True)
+
+       # add to the recent log list
+       for line in lines:
+               while 0 < len(universe.loglist) >= max_log_lines: del universe.loglist[0]
+               universe.loglist.append(timestamp + " " + line)
 
 def wrap_ansi_text(text, width):
        """Wrap text with arbitrary width while ignoring ANSI colors."""
@@ -567,8 +927,12 @@ def replace_macros(user, text, is_input=False):
                        "$(bld)": chr(27) + "[1m",
                        "$(nrm)": chr(27) + "[0m",
                        "$(blk)": chr(27) + "[30m",
+                       "$(blu)": chr(27) + "[34m",
+                       "$(cyn)": chr(27) + "[36m",
                        "$(grn)": chr(27) + "[32m",
+                       "$(mgt)": chr(27) + "[35m",
                        "$(red)": chr(27) + "[31m",
+                       "$(yel)": chr(27) + "[33m",
                        }
 
                # add dynamic macros where possible
@@ -595,13 +959,17 @@ def replace_macros(user, text, is_input=False):
                else:
                        text = text.replace(macro, "")
                        if not is_input:
-                               log("Unexpected replacement macro " + macro + " encountered.")
+                               log("Unexpected replacement macro " + macro + " encountered.", 6)
 
        # replace the look-like-a-macro sequence
        text = text.replace("$_(", "$(")
 
        return text
 
+def escape_macros(text):
+       """Escapes replacement macros in text."""
+       return text.replace("$(", "$_(")
+
 def check_time(frequency):
        """Check for a factor of the current increment count."""
        if type(frequency) is str:
@@ -626,7 +994,7 @@ def on_pulse():
 
        # update the log every now and then
        if check_time("frequency_log"):
-               log(repr(len(universe.userlist)) + " connection(s)")
+               log(str(len(universe.userlist)) + " connection(s)")
 
        # periodically save everything
        if check_time("frequency_save"):
@@ -652,7 +1020,7 @@ def check_for_connection(listening_socket):
                return None
 
        # note that we got one
-       log("Connection from " + address[0])
+       log("Connection from " + address[0], 2)
 
        # disable blocking so we can proceed whether or not we can send/receive
        connection.setblocking(0)
@@ -666,12 +1034,19 @@ def check_for_connection(listening_socket):
        # set the user's ipa from the connection's ipa
        user.address = address[0]
 
+       # let the client know we WILL EOR
+       user.send(IAC+WILL+EOR, raw=True)
+       user.negotiation_pause = 2
+
        # return the new user object
        return user
 
-def get_menu(state, error=None, echoing=True, choices={}):
+def get_menu(state, error=None, echoing=True, terminator="", choices=None):
        """Show the correct menu text to a user."""
 
+       # make sure we don't reuse a mutable sequence by default
+       if choices is None: choices = {}
+
        # begin with a telnet echo command sequence if needed
        message = get_echo_sequence(state, echoing)
 
@@ -690,6 +1065,9 @@ def get_menu(state, error=None, echoing=True, choices={}):
        # display a message indicating if echo is off
        message += get_echo_message(state)
 
+       # tack on EOR or GA to indicate the prompt will not be followed by CRLF
+       message += terminator
+
        # return the assembly of various strings defined above
        return message
 
@@ -698,15 +1076,15 @@ def menu_echo_on(state):
        return universe.categories["menu"][state].getboolean("echo", True)
 
 def get_echo_sequence(state, echoing):
-       """Build the appropriate IAC ECHO sequence as needed."""
+       """Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
 
        # if the user has echo on and the menu specifies it should be turned
        # off, send: iac + will + echo + null
-       if echoing and not menu_echo_on(state): return chr(255) + chr(251) + chr(1) + chr(0)
+       if echoing and not menu_echo_on(state): return IAC+WILL+ECHO
 
        # if echo is not set to off in the menu and the user curently has echo
        # off, send: iac + wont + echo + null
-       elif not echoing and menu_echo_on(state): return chr(255) + chr(252) + chr(1) + chr(0)
+       elif not echoing and menu_echo_on(state): return IAC+WONT+ECHO
 
        # default is not to send an echo control sequence at all
        else: return ""
@@ -722,8 +1100,8 @@ def get_default_menu_choice(state):
 
 def get_formatted_default_menu_choice(state):
        """Default menu choice foratted for inclusion in a prompt string."""
-       default = get_default_menu_choice(state)
-       if default: return "[$(red)" + default + "$(nrm)] "
+       default_choice = get_default_menu_choice(state)
+       if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
        else: return ""
 
 def get_menu_description(state, error):
@@ -756,23 +1134,26 @@ def get_menu_prompt(state):
 
 def get_menu_choices(user):
        """Return a dict of choice:meaning."""
-       choices = {}
+       menu = universe.categories["menu"][user.state]
+       create_choices = menu.get("create")
+       if create_choices: choices = eval(create_choices)
+       else: choices = {}
        ignores = []
        options = {}
        creates = {}
-       for facet in universe.categories["menu"][user.state].facets():
+       for facet in menu.facets():
                if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
                        ignores.append(facet.split("_", 2)[1])
-               elif facet.startswith("choice_"):
-                       options[facet] = facet.split("_", 2)[1]
                elif facet.startswith("create_"):
                        creates[facet] = facet.split("_", 2)[1]
-       for facet in options.keys():
-               if not options[facet] in ignores:
-                       choices[options[facet]] = universe.categories["menu"][user.state].get(facet)
+               elif facet.startswith("choice_"):
+                       options[facet] = facet.split("_", 2)[1]
        for facet in creates.keys():
                if not creates[facet] in ignores:
-                       choices[creates[facet]] = eval(universe.categories["menu"][user.state].get(facet))
+                       choices[creates[facet]] = eval(menu.get(facet))
+       for facet in options.keys():
+               if not options[facet] in ignores:
+                       choices[options[facet]] = menu.get(facet)
        return choices
 
 def get_formatted_menu_choices(state, choices):
@@ -800,7 +1181,6 @@ def get_default_branch(state):
 def get_choice_branch(user, choice):
        """Returns the new state matching the given choice."""
        branches = get_menu_branches(user.state)
-       if not choice: choice = get_default_menu_choice(user.state)
        if choice in branches.keys(): return branches[choice]
        elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
        else: return ""
@@ -820,7 +1200,6 @@ def get_default_action(state):
 def get_choice_action(user, choice):
        """Run any indicated script for the given choice."""
        actions = get_menu_actions(user.state)
-       if not choice: choice = get_default_menu_choice(user.state)
        if choice in actions.keys(): return actions[choice]
        elif choice in user.menu_choices.keys(): return get_default_action(user.state)
        else: return ""
@@ -838,7 +1217,7 @@ def handle_user_input(user):
        user.menu_seen = False
 
        # if the user's client echo is off, send a blank line for aesthetics
-       if not user.echoing: user.send("", "")
+       if user.echoing: user.received_newline = True
 
 def generic_menu_handler(user):
        """A generic menu choice handler."""
@@ -848,7 +1227,7 @@ def generic_menu_handler(user):
                choice = user.input_queue.pop(0)
                if choice: choice = choice.lower()
        else: choice = ""
-
+       if not choice: choice = get_default_menu_choice(user.state)
        if choice in user.menu_choices:
                exec(get_choice_action(user, choice))
                new_state = get_choice_branch(user, choice)
@@ -880,7 +1259,7 @@ def handler_entering_account_name(user):
                else:
                        user.account = Element("account:" + name, universe)
                        user.account.set("name", name)
-                       log("New user: " + name)
+                       log("New user: " + name, 2)
                        user.state = "checking_new_account_name"
 
        # if the user entered nothing for a name, then buhbye
@@ -933,7 +1312,7 @@ def handler_entering_new_password(user):
        # too many tries, so adios
        else:
                user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
-               user.account.delete()
+               user.account.destroy()
                user.state = "disconnecting"
 
 def handler_verifying_new_password(user):
@@ -959,7 +1338,7 @@ def handler_verifying_new_password(user):
        # otherwise, sayonara
        else:
                user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
-               user.account.delete()
+               user.account.destroy()
                user.state = "disconnecting"
 
 def handler_active(user):
@@ -968,24 +1347,34 @@ def handler_active(user):
        # get the next waiting line of input
        input_data = user.input_queue.pop(0)
 
-       # split out the command (first word) and parameters (everything else)
-       if input_data.find(" ") > 0:
-               command, parameters = input_data.split(" ", 1)
-       else:
-               command = input_data
-               parameters = ""
+       # is there input?
+       if input_data:
+
+               # split out the command (first word) and parameters (everything else)
+               if input_data.find(" ") > 0:
+                       command_name, parameters = input_data.split(" ", 1)
+               else:
+                       command_name = input_data
+                       parameters = ""
+
+               # lowercase the command
+               command_name = command_name.lower()
 
-       # lowercase the command
-       command = command.lower()
+               # the command matches a command word for which we have data
+               if command_name in universe.categories["command"]:
+                       command = universe.categories["command"][command_name]
+               else: command = None
 
-       # the command matches a command word for which we have data
-       if command in universe.categories["command"]:
-               exec(universe.categories["command"][command].get("action"))
+               # if it's allowed, do it
+               if user.can_run(command): exec(command.get("action"))
 
-       # no data matching the entered command word
-       elif command: command_error(user, command, parameters)
+               # otherwise, give an error
+               elif command_name: command_error(user, input_data)
 
-def command_halt(user, command="", parameters=""):
+       # if no input, just idle back with a prompt
+       else: user.send("", just_prompt=True)
+       
+def command_halt(user, parameters):
        """Halt the world."""
 
        # see if there's a message or use a generic one
@@ -993,27 +1382,28 @@ def command_halt(user, command="", parameters=""):
        else: message = "User " + user.account.get("name") + " halted the world."
 
        # let everyone know
-       broadcast(message)
-       log(message)
+       broadcast(message, add_prompt=False)
+       log(message, 8)
 
        # set a flag to terminate the world
        universe.terminate_world = True
 
-def command_reload(user, command="", parameters=""):
+def command_reload(user):
        """Reload all code modules, configs and data."""
 
        # let the user know and log
        user.send("Reloading all code modules, configs and data.")
-       log("User " + user.account.get("name") + " reloaded the world.")
+       log("User " + user.account.get("name") + " reloaded the world.", 8)
 
        # set a flag to reload
        universe.reload_modules = True
 
-def command_quit(user, command="", parameters=""):
-       """Quit the world."""
-       user.state = "disconnecting"
+def command_quit(user):
+       """Leave the world and go back to the main menu."""
+       user.deactivate_avatar()
+       user.state = "main_utility"
 
-def command_help(user, command="", parameters=""):
+def command_help(user, parameters):
        """List available commands and provide help for commands."""
 
        # did the user ask for help on a specific command word?
@@ -1021,15 +1411,22 @@ def command_help(user, command="", parameters=""):
 
                # is the command word one for which we have data?
                if parameters in universe.categories["command"]:
+                       command = universe.categories["command"][parameters]
+               else: command = None
+
+               # only for allowed commands
+               if user.can_run(command):
 
                        # add a description if provided
-                       description = universe.categories["command"][parameters].get("description")
+                       description = command.get("description")
                        if not description:
                                description = "(no short description provided)"
-                       output = "$(grn)" + parameters + "$(nrm) - " + description + "$(eol)$(eol)"
+                       if command.getboolean("administrative"): output = "$(red)"
+                       else: output = "$(grn)"
+                       output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
 
                        # add the help text if provided
-                       help_text = universe.categories["command"][parameters].get("help")
+                       help_text = command.get("help")
                        if not help_text:
                                help_text = "No help is provided for this command."
                        output += help_text
@@ -1046,16 +1443,31 @@ def command_help(user, command="", parameters=""):
                sorted_commands = universe.categories["command"].keys()
                sorted_commands.sort()
                for item in sorted_commands:
-                       description = universe.categories["command"][item].get("description")
-                       if not description:
-                               description = "(no short description provided)"
-                       output += "   $(grn)" + item + "$(nrm) - " + description + "$(eol)"
+                       command = universe.categories["command"][item]
+                       if user.can_run(command):
+                               description = command.get("description")
+                               if not description:
+                                       description = "(no short description provided)"
+                               if command.getboolean("administrative"): output += "   $(red)"
+                               else: output += "   $(grn)"
+                               output += item + "$(nrm) - " + description + "$(eol)"
                output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
 
        # send the accumulated output to the user
        user.send(output)
 
-def command_say(user, command="", parameters=""):
+def command_move(user, parameters):
+       """Move the avatar in a given direction."""
+       if parameters in universe.contents[user.avatar.get("location")].portals():
+               user.avatar.move_direction(parameters)
+       else: user.send("You cannot go that way.")
+
+def command_look(user, parameters):
+       """Look around."""
+       if parameters: user.send("You look at or in anything yet.")
+       else: user.avatar.look_at(user.avatar.get("location"))
+
+def command_say(user, parameters):
        """Speak to others in the same room."""
 
        # check for replacement macros
@@ -1095,45 +1507,136 @@ def command_say(user, command="", parameters=""):
                        message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
 
                # tell the room
-               # TODO: we won't be using broadcast once there are actual rooms
-               broadcast(user.account.get("name") + " " + action + "s, \"" + message + "\"")
+               user.avatar.echo_to_location(user.avatar.get("name") + " " + action + "s, \"" + message + "\"")
+               user.send("You " + action + ", \"" + message + "\"")
 
        # there was no message
        else:
                user.send("What do you want to say?")
 
-def command_show(user, command="", parameters=""):
+def command_show(user, parameters):
        """Show program data."""
-       if parameters == "avatars":
-               message = "These are the avatars managed by your account:$(eol)"
-               avatars = user.list_avatar_names()
-               avatars.sort()
-               for avatar in avatars: message += "$(eol)   $(grn)" + avatar + "$(nrm)"
-       elif parameters == "files":
-               message = "These are the current files containing the universe:$(eol)"
-               keys = universe.files.keys()
-               keys.sort()
-               for key in keys: message += "$(eol)   $(grn)" + key + "$(nrm)"
-       elif parameters == "universe":
-               message = "These are the current elements in the universe:$(eol)"
-               keys = universe.contents.keys()
-               keys.sort()
-               for key in keys: message += "$(eol)   $(grn)" + key + "$(nrm)"
-       elif parameters == "time":
-               message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
-       elif parameters: message = "I don't know what \"" + parameters + "\" is."
-       else: message = "What do you want to show?"
+       message = ""
+       if parameters.find(" ") < 1:
+               if parameters == "time":
+                       message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
+               elif parameters == "categories":
+                       message = "These are the element categories:$(eol)"
+                       categories = universe.categories.keys()
+                       categories.sort()
+                       for category in categories: message += "$(eol)   $(grn)" + category + "$(nrm)"
+               elif parameters == "files":
+                       message = "These are the current files containing the universe:$(eol)"
+                       filenames = universe.files.keys()
+                       filenames.sort()
+                       for filename in filenames: message += "$(eol)   $(grn)" + filename + "$(nrm)"
+               else: message = ""
+       else:
+               arguments = parameters.split()
+               if arguments[0] == "category":
+                       if arguments[1] in universe.categories:
+                               message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
+                               elements = universe.categories[arguments[1]].keys()
+                               elements.sort()
+                               for element in elements:
+                                       message += "$(eol)   $(grn)" + universe.categories[arguments[1]][element].key + "$(nrm)"
+               elif arguments[0] == "element":
+                       if arguments[1] in universe.contents:
+                               message = "These are the properties of the \"" + arguments[1] + "\" element:$(eol)"
+                               element = universe.contents[arguments[1]]
+                               facets = element.facets()
+                               facets.sort()
+                               for facet in facets:
+                                       message += "$(eol)   $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
+               elif arguments[0] == "result":
+                       if len(arguments) > 1:
+                               try:
+                                       message = repr(eval(" ".join(arguments[1:])))
+                               except:
+                                       message = "Your expression raised an exception!"
+               elif arguments[0] == "log":
+                       if match("^\d+$", arguments[1]) and int(arguments[1]) > 0:
+                               linecount = int(arguments[1])
+                               if linecount > len(universe.loglist): linecount = len(universe.loglist)
+                               message = "There are " + str(len(universe.loglist)) + " log lines in memory."
+                               message += " The most recent " + str(linecount) + " lines are:$(eol)$(eol)"
+                               for line in universe.loglist[-linecount:]:
+                                       message += "   " + line + "$(eol)"
+                       else: message = "\"" + arguments[1] + "\" is not a positive integer greater than 0."
+       if not message:
+               if parameters: message = "I don't know what \"" + parameters + "\" is."
+               else: message = "What do you want to show?"
+       user.send(message)
+
+def command_create(user, parameters):
+       """Create an element if it does not exist."""
+       if not parameters: message = "You must at least specify an element to create."
+       else:
+               arguments = parameters.split()
+               if len(arguments) == 1: arguments.append("")
+               if len(arguments) == 2:
+                       element, filename = arguments
+                       if element in universe.contents: message = "The \"" + element + "\" element already exists."
+                       else:
+                               message = "You create \"" + element + "\" within the universe."
+                               logline = user.account.get("name") + " created an element: " + element
+                               if filename:
+                                       logline += " in file " + filename
+                                       if filename not in universe.files:
+                                               message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
+                               Element(element, universe, filename)
+                               log(logline, 6)
+               elif len(arguments) > 2: message = "You can only specify an element and a filename."
+       user.send(message)
+
+def command_destroy(user, parameters):
+       """Destroy an element if it exists."""
+       if not parameters: message = "You must specify an element to destroy."
+       else:
+               if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
+               else:
+                       universe.contents[parameters].destroy()
+                       message = "You destroy \"" + parameters + "\" within the universe."
+                       log(user.account.get("name") + " destroyed an element: " + parameters, 6)
+       user.send(message)
+
+def command_set(user, parameters):
+       """Set a facet of an element."""
+       if not parameters: message = "You must specify an element, a facet and a value."
+       else:
+               arguments = parameters.split(" ", 2)
+               if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
+               elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
+               else:
+                       element, facet, value = arguments
+                       if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
+                       else:
+                               universe.contents[element].set(facet, value)
+                               message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
+       user.send(message)
+
+def command_delete(user, parameters):
+       """Delete a facet from an element."""
+       if not parameters: message = "You must specify an element and a facet."
+       else:
+               arguments = parameters.split(" ")
+               if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
+               elif len(arguments) != 2: message = "You may only specify an element and a facet."
+               else:
+                       element, facet = arguments
+                       if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
+                       elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
+                       else:
+                               universe.contents[element].delete(facet)
+                               message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
        user.send(message)
 
-def command_error(user, command="", parameters=""):
+def command_error(user, input_data):
        """Generic error for an unrecognized command word."""
 
        # 90% of the time use a generic error
        if randrange(10):
-               message = "I'm not sure what \"" + command
-               if parameters:
-                       message += " " + parameters
-               message += "\" means..."
+               message = "I'm not sure what \"" + input_data + "\" means..."
 
        # 10% of the time use the classic diku error
        else: