from random import choice, randrange
from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
from stat import S_IMODE, ST_MODE
+from telnetlib import DO, DONT, ECHO, EOR, IAC, WILL, WONT
from time import asctime, sleep
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 + ".")
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)
DataFile(include_file, universe)
def save(self):
if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("control", "read_only") and self.data.getboolean("control", "read_only") ):
- if not exists(dirname(self.filename)): makedirs(dirname)
+ if not exists(dirname(self.filename)): makedirs(dirname(self.filename))
file_descriptor = file(self.filename, "w")
if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
chmod(self.filename, 0600)
def send(self, output, eol="$(eol)"):
"""Send arbitrary text to a connected user."""
- # only when there is actual output
- #if output:
-
# 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 = replace_macros(self, output)
# wrap the text at 80 characters
- # TODO: prompt user for preferred wrap width
output = wrap_ansi_text(output, 80)
# drop the formatted output into the output queue
self.output_queue.append(output)
- # try to send the last item in the queue, remove it and
- # flag that menu display is not needed
+ # try to send the last item in the queue and remove it
try:
self.connection.send(self.output_queue[0])
- self.output_queue.remove(self.output_queue[0])
- self.menu_seen = False
+ del self.output_queue[0]
# but if we can't, that's okay too
except:
self.show_menu()
# 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:
# 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")
# 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)
+
# 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()
# 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 and move on
+ elif len(text) > position+1 and text[position+1] == IAC:
+ text = text.replace(IAC+IAC, IAC)
+ position += 1
+
+ # this must be an option negotiation
+ elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
+
+ # if we turned echo off, ignore the confirmation
+ if not self.echoing and text[position+1:position+3] == DO+ECHO: pass
+
+ # we don't want to allow anything else
+ elif text[position+1] in (DO, WILL): self.send(IAC+WONT+text[position+2])
+
+ # strip the negotiation from the input
+ text = text.replace(text[position:position+3], "")
+
+ # otherwise, strip out a two-byte IAC command
+ else: text = text.replace(text[position:position+2], "")
+
+ # 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 = 0
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].delete()
+ universe.contents[avatar].destroy()
avatars = self.account.getlist("avatars")
avatars.remove(avatar)
self.account.set("avatars", avatars)
- def delete(self):
- """Delete the user and associated avatars."""
+ def destroy(self):
+ """Destroy the user and associated avatars."""
for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
- self.account.delete()
+ self.account.destroy()
def list_avatar_names(self):
"""List names of assigned avatars."""
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:
# display a message indicating if echo is off
message += get_echo_message(state)
+ # tack on IAC EOR to indicate the prompt will not be followed by CRLF
+ message += IAC+EOR
+
# return the assembly of various strings defined above
return message
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 ""
# 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):
# 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):
# split out the command (first word) and parameters (everything else)
if input_data.find(" ") > 0:
- command, parameters = input_data.split(" ", 1)
+ command_name, parameters = input_data.split(" ", 1)
else:
- command = input_data
+ command_name = input_data
parameters = ""
# lowercase the command
- command = command.lower()
+ command_name = command_name.lower()
# 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 command_name in universe.categories["command"]:
+ command = universe.categories["command"][command_name]
+ else: command = None
+
+ # 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=""):
+def command_halt(user, parameters):
"""Halt the world."""
# see if there's a message or use a generic one
# 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
# set a flag to reload
universe.reload_modules = True
-def command_quit(user, command="", parameters=""):
- """Quit the world."""
- 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?
# 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
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_say(user, parameters):
"""Speak to others in the same room."""
# check for replacement macros
# tell the room
# TODO: we won't be using broadcast once there are actual rooms
- broadcast(user.account.get("name") + " " + action + "s, \"" + message + "\"")
+ broadcast(user.avatar.get("name") + " " + action + "s, \"" + 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)"
+ 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)
+ 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)
+ 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: