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."""
+ def __init__(self, key, universe, filename=""):
+ """Set up a new element."""
+
+ # not owned by a user by default (used for avatars)
self.owner = None
+
+ # no contents in here by default
self.contents = {}
+
+ # keep track of our key name
self.key = key
+
+ # parse out appropriate category and subkey names, add to list
if self.key.find(":") > 0:
self.category, self.subkey = self.key.split(":", 1)
else:
self.subkey = self.key
if not self.category in universe.categories: self.category = "other"
universe.categories[self.category][self.subkey] = self
- self.origin = origin
- if not self.origin: self.origin = universe.default_origins[self.category]
- if not isabs(self.origin):
- self.origin = abspath(self.origin)
+
+ # get an appropriate filename for the origin
+ if not filename: filename = universe.default_origins[self.category]
+ if not isabs(filename): filename = abspath(filename)
+
+ # add the file if it doesn't exist yet
+ if not filename in universe.files: DataFile(filename, universe)
+
+ # record a pointer to the origin file
+ self.origin = universe.files[filename]
+
+ # add a data section to the origin if necessary
+ if not self.origin.data.has_section(self.key):
+ self.origin.data.add_section(self.key)
+
+ # add this element to the universe contents
universe.contents[self.key] = self
- if not self.origin in universe.files:
- 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 destroy(self):
"""Remove an element from the universe and destroy it."""
- log("Destroying: " + self.key + ".")
- universe.files[self.origin].data.remove_section(self.key)
+ log("Destroying: " + self.key + ".", 2)
+ 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 non-inherited facets for this element."""
- return universe.files[self.origin].data.options(self.key)
+ if self.key in self.origin.data.sections():
+ return 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)
+ if self.has_facet(facet):
+ self.origin.data.remove_option(self.key, facet)
+ self.origin.modified = True
def ancestry(self):
"""Return a list of the element's inheritance lineage."""
if self.has_facet("inherit"):
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)
+ if self.origin.data.has_option(self.key, facet):
+ return self.origin.data.get(self.key, facet)
elif self.has_facet("inherit"):
for ancestor in self.ancestry():
if universe.contents[ancestor].has_facet(facet):
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)
+ if self.origin.data.has_option(self.key, facet):
+ return self.origin.data.getboolean(self.key, facet)
elif self.has_facet("inherit"):
for ancestor in self.ancestry():
if universe.contents[ancestor].has_facet(facet):
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)
+ if self.origin.data.has_option(self.key, facet):
+ return self.origin.data.getint(self.key, facet)
elif self.has_facet("inherit"):
for ancestor in self.ancestry():
if universe.contents[ancestor].has_facet(facet):
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)
+ if self.origin.data.has_option(self.key, facet):
+ return self.origin.data.getfloat(self.key, facet)
elif self.has_facet("inherit"):
for ancestor in self.ancestry():
if universe.contents[ancestor].has_facet(facet):
else: return default
def set(self, facet, value):
"""Set values."""
- 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)
+ if not self.has_facet(facet) or not self.get(facet) == value:
+ if type(value) is long: value = str(value)
+ elif not type(value) is str: value = repr(value)
+ self.origin.data.set(self.key, facet, value)
+ self.origin.modified = True
def append(self, facet, value):
"""Append value tp a list."""
if type(value) is long: value = str(value)
class DataFile:
"""A file containing universe elements."""
def __init__(self, filename, universe):
+ self.modified = False
self.data = RawConfigParser()
if access(filename, R_OK): self.data.read(filename)
self.filename = filename
if not isabs(include_file):
include_file = path_join(dirname(filename), include_file)
DataFile(include_file, universe)
+ def is_writeable(self):
+ """Returns True if the __control__ read_only is False."""
+ return not self.data.has_option("__control__", "read_only") or not self.data.getboolean("__control__", "read_only")
def save(self):
"""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") ):
+ # when modified, writeable and has content or the file exists
+ if self.modified and self.is_writeable() and ( self.data.sections() or exists(self.filename) ):
# make parent directories if necessary
if not exists(dirname(self.filename)):
self.default_origins = {}
self.files = {}
self.private_files = []
+ self.loglist = []
self.userlist = []
self.terminate_world = False
self.reload_modules = False
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()
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 + ".")
+ 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
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")
if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
else: logline += "unknown user: "
logline += repr(removed)
- log(logline)
+ log(logline, 4)
# filter out non-printables
line = filter(lambda x: " " <= x <= "~", line)
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.avatar.append("inherit", "archetype:avatar")
self.account.append("avatars", self.avatar.key)
def delete_avatar(self, avatar):
"""Send a message to all connected users."""
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]
- file_name = universe.categories["internal"]["logging"].get("file")
+ # 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")
- file_descriptor.write(timestamp + " " + message + "\n")
+ for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
file_descriptor.flush()
file_descriptor.close()
- # send the timestamp and message to standard output
+ # send the timestamp and line to standard output
if universe.categories["internal"]["logging"].getboolean("stdout"):
- print(timestamp + " " + message)
+ for line in lines: print(timestamp + " " + line)
- # send the message to the system log
- syslog_name = universe.categories["internal"]["logging"].get("syslog")
+ # send the line to the system log
if syslog_name:
openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
- syslog(message)
+ 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."""
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 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)
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
# let everyone know
broadcast(message, add_prompt=False)
- log(message)
+ log(message, 8)
# set a flag to terminate the world
universe.terminate_world = True
# 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_look(user, parameters):
"""Look around."""
- if parameters: user.send("You look at or in anything yet.")
+ if parameters: user.send("You can't look at or in anything yet.")
else: user.avatar.look_at(user.avatar.get("location"))
def command_say(user, parameters):
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?"
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)
+ log(logline, 6)
elif len(arguments) > 2: message = "You can only specify an element and a filename."
user.send(message)
else:
universe.contents[parameters].destroy()
message = "You destroy \"" + parameters + "\" within the universe."
- log(user.account.get("name") + " destroyed an element: " + parameters)
+ log(user.account.get("name") + " destroyed an element: " + parameters, 6)
user.send(message)
def command_set(user, parameters):
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)
+ universe.contents[element].remove_facet(facet)
message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
user.send(message)