1 """Core objects for the mudpy engine."""
3 # Copyright (c) 2005, 2006 Jeremy Stanley <fungi@yuggoth.org>. All rights
4 # reserved. Licensed per terms in the LICENSE file distributed with this
7 # import some things we need
8 from ConfigParser import RawConfigParser
9 from md5 import new as new_md5
10 from os import _exit, R_OK, W_OK, access, chdir, chmod, close, fork, getcwd, getpid, listdir, makedirs, remove, rename, setsid, stat, umask
11 from os.path import abspath, basename, dirname, exists, isabs, join as path_join
12 from random import choice, randrange
14 from signal import SIGHUP, SIGTERM, signal
15 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
16 from stat import S_IMODE, ST_MODE
17 from string import digits, letters, punctuation, uppercase
18 from sys import argv, stderr
19 from syslog import LOG_PID, LOG_INFO, LOG_DAEMON, closelog, openlog, syslog
20 from telnetlib import DO, DONT, ECHO, EOR, GA, IAC, LINEMODE, SB, SE, SGA, WILL, WONT
21 from time import asctime, sleep
22 from traceback import format_exception
25 """An element of the universe."""
26 def __init__(self, key, universe, filename=None):
27 """Set up a new element."""
29 # keep track of our key name
32 # keep track of what universe it's loading` into
33 self.universe = universe
35 # clone attributes if this is replacing another element
36 if self.key in self.universe.contents:
37 old_element = self.universe.contents[self.key]
38 for attribute in vars(old_element).keys():
39 exec("self." + attribute + " = old_element." + attribute)
40 if self.owner: self.owner.avatar = self
42 # i guess this is a new element then
45 # not owned by a user by default (used for avatars)
48 # no contents in here by default
51 # parse out appropriate category and subkey names, add to list
52 if self.key.find(":") > 0:
53 self.category, self.subkey = self.key.split(":", 1)
55 self.category = "other"
56 self.subkey = self.key
57 if not self.category in self.universe.categories:
58 self.category = "other"
59 self.subkey = self.key
61 # get an appropriate filename for the origin
62 if not filename: filename = self.universe.default_origins[self.category]
63 if not isabs(filename): filename = abspath(filename)
65 # add the file if it doesn't exist yet
66 if not filename in self.universe.files: DataFile(filename, self.universe)
68 # record or reset a pointer to the origin file
69 self.origin = self.universe.files[filename]
71 # add a data section to the origin if necessary
72 if not self.origin.data.has_section(self.key):
73 self.origin.data.add_section(self.key)
75 # add or replace this element in the universe
76 self.universe.contents[self.key] = self
77 self.universe.categories[self.category][self.subkey] = self
80 """Create a new element and replace this one."""
81 new_element = Element(self.key, self.universe, self.origin.filename)
84 """Remove an element from the universe and destroy it."""
85 self.origin.data.remove_section(self.key)
86 del self.universe.categories[self.category][self.subkey]
87 del self.universe.contents[self.key]
90 """Return a list of non-inherited facets for this element."""
91 if self.key in self.origin.data.sections():
92 return self.origin.data.options(self.key)
94 def has_facet(self, facet):
95 """Return whether the non-inherited facet exists."""
96 return facet in self.facets()
97 def remove_facet(self, facet):
98 """Remove a facet from the element."""
99 if self.has_facet(facet):
100 self.origin.data.remove_option(self.key, facet)
101 self.origin.modified = True
103 """Return a list of the element's inheritance lineage."""
104 if self.has_facet("inherit"):
105 ancestry = self.getlist("inherit")
106 for parent in ancestry[:]:
107 ancestors = self.universe.contents[parent].ancestry()
108 for ancestor in ancestors:
109 if ancestor not in ancestry: ancestry.append(ancestor)
112 def get(self, facet, default=None):
113 """Retrieve values."""
114 if default is None: default = ""
115 if self.origin.data.has_option(self.key, facet):
116 return self.origin.data.get(self.key, facet)
117 elif self.has_facet("inherit"):
118 for ancestor in self.ancestry():
119 if self.universe.contents[ancestor].has_facet(facet):
120 return self.universe.contents[ancestor].get(facet)
122 def getboolean(self, facet, default=None):
123 """Retrieve values as boolean type."""
124 if default is None: default=False
125 if self.origin.data.has_option(self.key, facet):
126 return self.origin.data.getboolean(self.key, facet)
127 elif self.has_facet("inherit"):
128 for ancestor in self.ancestry():
129 if self.universe.contents[ancestor].has_facet(facet):
130 return self.universe.contents[ancestor].getboolean(facet)
132 def getint(self, facet, default=None):
133 """Return values as int/long type."""
134 if default is None: default = 0
135 if self.origin.data.has_option(self.key, facet):
136 return self.origin.data.getint(self.key, facet)
137 elif self.has_facet("inherit"):
138 for ancestor in self.ancestry():
139 if self.universe.contents[ancestor].has_facet(facet):
140 return self.universe.contents[ancestor].getint(facet)
142 def getfloat(self, facet, default=None):
143 """Return values as float type."""
144 if default is None: default = 0.0
145 if self.origin.data.has_option(self.key, facet):
146 return self.origin.data.getfloat(self.key, facet)
147 elif self.has_facet("inherit"):
148 for ancestor in self.ancestry():
149 if self.universe.contents[ancestor].has_facet(facet):
150 return self.universe.contents[ancestor].getfloat(facet)
152 def getlist(self, facet, default=None):
153 """Return values as list type."""
154 if default is None: default = []
155 value = self.get(facet)
156 if value: return makelist(value)
158 def getdict(self, facet, default=None):
159 """Return values as dict type."""
160 if default is None: default = {}
161 value = self.get(facet)
162 if value: return makedict(value)
164 def set(self, facet, value):
166 if not self.has_facet(facet) or not self.get(facet) == value:
167 if type(value) is long: value = str(value)
168 elif not type(value) is str: value = repr(value)
169 self.origin.data.set(self.key, facet, value)
170 self.origin.modified = True
171 def append(self, facet, value):
172 """Append value tp a list."""
173 if type(value) is long: value = str(value)
174 elif not type(value) is str: value = repr(value)
175 newlist = self.getlist(facet)
176 newlist.append(value)
177 self.set(facet, newlist)
179 def new_event(self, action, when=None):
180 """Create, attach and enqueue an event element."""
182 # if when isn't specified, that means now
183 if not when: when = self.universe.get_time()
185 # events are elements themselves
186 event = Element("event:" + self.key + ":" + counter)
188 def send(self, message, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
189 """Convenience method to pass messages to an owner."""
190 if self.owner: self.owner.send(message, eol, raw, flush, add_prompt, just_prompt)
192 def can_run(self, command):
193 """Check if the user can run this command object."""
195 # has to be in the commands category
196 if command not in self.universe.categories["command"].values(): result = False
198 # avatars of administrators can run any command
199 elif self.owner and self.owner.account.getboolean("administrator"): result = True
201 # everyone can run non-administrative commands
202 elif not command.getboolean("administrative"): result = True
204 # otherwise the command cannot be run by this actor
207 # pass back the result
210 def update_location(self):
211 """Make sure the location's contents contain this element."""
212 location = self.get("location")
213 if location in self.universe.contents:
214 self.universe.contents[location].contents[self.key] = self
215 def clean_contents(self):
216 """Make sure the element's contents aren't bogus."""
217 for element in self.contents.values():
218 if element.get("location") != self.key:
219 del self.contents[element.key]
220 def go_to(self, location):
221 """Relocate the element to a specific location."""
222 current = self.get("location")
223 if current and self.key in self.universe.contents[current].contents:
224 del universe.contents[current].contents[self.key]
225 if location in self.universe.contents: self.set("location", location)
226 self.universe.contents[location].contents[self.key] = self
227 self.look_at(location)
229 """Relocate the element to its default location."""
230 self.go_to(self.get("default_location"))
231 self.echo_to_location("You suddenly realize that " + self.get("name") + " is here.")
232 def move_direction(self, direction):
233 """Relocate the element in a specified direction."""
234 self.echo_to_location(self.get("name") + " exits " + self.universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
235 self.send("You exit " + self.universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".", add_prompt=False)
236 self.go_to(self.universe.contents[self.get("location")].link_neighbor(direction))
237 self.echo_to_location(self.get("name") + " arrives from " + self.universe.categories["internal"]["directions"].getdict(direction)["enter"] + ".")
238 def look_at(self, key):
239 """Show an element to another element."""
241 element = self.universe.contents[key]
243 name = element.get("name")
244 if name: message += "$(cyn)" + name + "$(nrm)$(eol)"
245 description = element.get("description")
246 if description: message += description + "$(eol)"
247 portal_list = element.portals().keys()
250 message += "$(cyn)[ Exits: " + ", ".join(portal_list) + " ]$(nrm)$(eol)"
251 for element in self.universe.contents[self.get("location")].contents.values():
252 if element.getboolean("is_actor") and element is not self:
253 message += "$(yel)" + element.get("name") + " is here.$(nrm)$(eol)"
254 elif element is not self:
255 message += "$(grn)" + element.get("impression") + "$(nrm)$(eol)"
258 """Map the portal directions for a room to neighbors."""
260 if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
261 coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
262 directions = self.universe.categories["internal"]["directions"]
263 offsets = dict([(x, directions.getdict(x)["vector"]) for x in directions.facets()])
264 for portal in self.getlist("gridlinks"):
265 adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
266 neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
267 if neighbor in self.universe.contents: portals[portal] = neighbor
268 for facet in self.facets():
269 if facet.startswith("link_"):
270 neighbor = self.get(facet)
271 if neighbor in self.universe.contents:
272 portal = facet.split("_")[1]
273 portals[portal] = neighbor
275 def link_neighbor(self, direction):
276 """Return the element linked in a given direction."""
277 portals = self.portals()
278 if direction in portals: return portals[direction]
279 def echo_to_location(self, message):
280 """Show a message to other elements in the current location."""
281 for element in self.universe.contents[self.get("location")].contents.values():
282 if element is not self: element.send(message)
285 """A file containing universe elements."""
286 def __init__(self, filename, universe):
287 self.filename = filename
288 self.universe = universe
291 """Read a file and create elements accordingly."""
292 self.modified = False
293 self.data = RawConfigParser()
294 if access(self.filename, R_OK): self.data.read(self.filename)
295 if not hasattr(self.universe, "files"): self.universe.files = {}
296 self.universe.files[self.filename] = self
297 if self.data.has_option("__control__", "include_files"):
298 includes = makelist(self.data.get("__control__", "include_files"))
300 if self.data.has_option("__control__", "default_files"):
301 origins = makedict(self.data.get("__control__", "default_files"))
302 for key in origins.keys():
303 if not isabs(origins[key]):
304 origins[key] = path_join(dirname(self.filename), origins[key])
305 if not origins[key] in includes: includes.append(origins[key])
306 self.universe.default_origins[key] = origins[key]
307 if not key in self.universe.categories:
308 self.universe.categories[key] = {}
309 if self.data.has_option("__control__", "private_files"):
310 for item in makelist(self.data.get("__control__", "private_files")):
311 if not item in includes: includes.append(item)
312 if not item in self.universe.private_files:
314 item = path_join(dirname(self.filename), item)
315 self.universe.private_files.append(item)
316 for section in self.data.sections():
317 if section != "__control__":
318 Element(section, self.universe, self.filename)
319 for include_file in includes:
320 if not isabs(include_file):
321 include_file = path_join(dirname(self.filename), include_file)
322 if include_file not in self.universe.files or not self.universe.files[include_file].is_writeable():
323 DataFile(include_file, self.universe)
325 """Write the data, if necessary."""
327 # when modified, writeable and has content or the file exists
328 if self.modified and self.is_writeable() and ( self.data.sections() or exists(self.filename) ):
330 # make parent directories if necessary
331 if not exists(dirname(self.filename)):
332 makedirs(dirname(self.filename))
335 if self.data.has_option("__control__", "backup_count"):
336 max_count = self.data.has_option("__control__", "backup_count")
337 else: max_count = universe.categories["internal"]["limits"].getint("default_backup_count")
338 if exists(self.filename) and max_count:
340 for candidate in listdir(dirname(self.filename)):
341 if match(basename(self.filename) + """\.\d+$""", candidate):
342 backups.append(int(candidate.split(".")[-1]))
345 for old_backup in backups:
346 if old_backup >= max_count-1:
347 remove(self.filename+"."+str(old_backup))
348 elif not exists(self.filename+"."+str(old_backup+1)):
349 rename(self.filename+"."+str(old_backup), self.filename+"."+str(old_backup+1))
350 if not exists(self.filename+".0"):
351 rename(self.filename, self.filename+".0")
354 file_descriptor = file(self.filename, "w")
356 # if it's marked private, chmod it appropriately
357 if self.filename in self.universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
358 chmod(self.filename, 0600)
360 # write it back sorted, instead of using ConfigParser
361 sections = self.data.sections()
363 for section in sections:
364 file_descriptor.write("[" + section + "]\n")
365 options = self.data.options(section)
367 for option in options:
368 file_descriptor.write(option + " = " + self.data.get(section, option) + "\n")
369 file_descriptor.write("\n")
371 # flush and close the file
372 file_descriptor.flush()
373 file_descriptor.close()
375 # unset the modified flag
376 self.modified = False
377 def is_writeable(self):
378 """Returns True if the __control__ read_only is False."""
379 return not self.data.has_option("__control__", "read_only") or not self.data.getboolean("__control__", "read_only")
384 def __init__(self, filename="", load=False):
385 """Initialize the universe."""
388 self.default_origins = {}
390 self.pending_events_long = {}
391 self.pending_events_short = {}
392 self.private_files = []
393 self.reload_flag = False
394 self.startdir = getcwd()
395 self.terminate_flag = False
398 possible_filenames = [
404 "/usr/local/mudpy/mudpy.conf",
405 "/usr/local/mudpy/etc/mudpy.conf",
406 "/etc/mudpy/mudpy.conf",
409 for filename in possible_filenames:
410 if access(filename, R_OK): break
411 if not isabs(filename):
412 filename = path_join(self.startdir, filename)
413 self.filename = filename
417 """Load universe data from persistent storage."""
419 # the files dict must exist and filename needs to be read-only
420 if not hasattr(self, "files") or not ( self.filename in self.files and self.files[self.filename].is_writeable() ):
422 # clear out all read-only files
423 if hasattr(self, "files"):
424 for data_filename in self.files.keys():
425 if not self.files[data_filename].is_writeable():
426 del self.files[data_filename]
428 # start loading from the initial file
429 DataFile(self.filename, self)
431 # make a list of inactive avatars
432 inactive_avatars = []
433 for account in self.categories["account"].values():
434 inactive_avatars += [ (self.contents[x]) for x in account.getlist("avatars") ]
435 for user in self.userlist:
436 if user.avatar in inactive_avatars:
437 inactive_avatars.remove(user.avatar)
439 # go through all elements to clear out inactive avatar locations
440 for element in self.contents.values():
441 location = element.get("location")
442 if element in inactive_avatars and location:
443 if location in self.contents and element.key in self.contents[location].contents:
444 del self.contents[location].contents[element.key]
445 element.set("default_location", location)
446 element.remove_facet("location")
448 # another pass to straighten out all the element contents
449 for element in self.contents.values():
450 element.update_location()
451 element.clean_contents()
454 """Create a new, empty Universe (the Big Bang)."""
455 new_universe = Universe()
456 for attribute in vars(self).keys():
457 exec("new_universe." + attribute + " = self." + attribute)
458 new_universe.reload_flag = False
463 """Save the universe to persistent storage."""
464 for key in self.files: self.files[key].save()
466 def initialize_server_socket(self):
467 """Create and open the listening socket."""
469 # create a new ipv4 stream-type socket object
470 self.listening_socket = socket(AF_INET, SOCK_STREAM)
472 # set the socket options to allow existing open ones to be
473 # reused (fixes a bug where the server can't bind for a minute
474 # when restarting on linux systems)
475 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
477 # bind the socket to to our desired server ipa and port
478 host = self.categories["internal"]["network"].get("host")
479 port = self.categories["internal"]["network"].getint("port")
480 self.listening_socket.bind((host, port))
482 # disable blocking so we can proceed whether or not we can
484 self.listening_socket.setblocking(0)
486 # start listening on the socket
487 self.listening_socket.listen(1)
489 # note that we're now ready for user connections
490 if not host: host = "0.0.0.0"
491 log("Listening for Telnet connections on: " + host + ":" + str(port))
494 """Convenience method to get the elapsed time counter."""
495 return self.categories["internal"]["counters"].getint("elapsed")
498 """This is a connected user."""
501 """Default values for the in-memory user variables."""
504 self.authenticated = False
506 self.connection = None
509 self.input_queue = []
510 self.last_address = ""
511 self.menu_choices = {}
512 self.menu_seen = False
513 self.negotiation_pause = 0
514 self.output_queue = []
515 self.partial_input = ""
516 self.password_tries = 0
517 self.received_newline = True
518 self.state = "initial"
519 self.terminator = IAC+GA
522 """Log, close the connection and remove."""
523 if self.account: name = self.account.get("name")
525 if name: message = "User " + name
526 else: message = "An unnamed user"
527 message += " logged out."
529 self.deactivate_avatar()
530 self.connection.close()
534 """Save, load a new user and relocate the connection."""
536 # get out of the list
539 # create a new user object
542 # set everything equivalent
543 for attribute in vars(self).keys():
544 exec("new_user." + attribute + " = self." + attribute)
546 # the avatar needs a new owner
547 if new_user.avatar: new_user.avatar.owner = new_user
550 universe.userlist.append(new_user)
552 # get rid of the old user object
555 def replace_old_connections(self):
556 """Disconnect active users with the same name."""
558 # the default return value
561 # iterate over each user in the list
562 for old_user in universe.userlist:
564 # the name is the same but it's not us
565 if hasattr(old_user, "account") and old_user.account and old_user.account.get("name") == self.account.get("name") and old_user is not self:
568 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
569 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
571 # close the old connection
572 old_user.connection.close()
574 # replace the old connection with this one
575 old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
576 old_user.connection = self.connection
577 old_user.last_address = old_user.address
578 old_user.address = self.address
580 # may need to tell the new connection to echo
582 old_user.send(get_echo_sequence(old_user.state, self.echoing), raw=True)
584 # take this one out of the list and delete
590 # true if an old connection was replaced, false if not
593 def authenticate(self):
594 """Flag the user as authenticated and disconnect duplicates."""
595 if not self.state is "authenticated":
596 log("User " + self.account.get("name") + " logged in.", 2)
597 self.authenticated = True
598 if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
599 self.account.set("administrator", "True")
602 """Send the user their current menu."""
603 if not self.menu_seen:
604 self.menu_choices = get_menu_choices(self)
605 self.send(get_menu(self.state, self.error, self.echoing, self.terminator, self.menu_choices), "")
606 self.menu_seen = True
608 self.adjust_echoing()
610 def adjust_echoing(self):
611 """Adjust echoing to match state menu requirements."""
612 if self.echoing and not menu_echo_on(self.state): self.echoing = False
613 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
616 """Remove a user from the list of connected users."""
617 universe.userlist.remove(self)
619 def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
620 """Send arbitrary text to a connected user."""
622 # unless raw mode is on, clean it up all nice and pretty
625 # strip extra $(eol) off if present
626 while output.startswith("$(eol)"): output = output[6:]
627 while output.endswith("$(eol)"): output = output[:-6]
628 extra_lines = output.find("$(eol)$(eol)$(eol)")
629 while extra_lines > -1:
630 output = output[:extra_lines] + output[extra_lines+6:]
631 extra_lines = output.find("$(eol)$(eol)$(eol)")
633 # we'll take out GA or EOR and add them back on the end
634 if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
637 else: terminate = False
639 # start with a newline, append the message, then end
640 # with the optional eol string passed to this function
641 # and the ansi escape to return to normal text
643 if not self.output_queue or not self.output_queue[-1].endswith("\r\n"):
644 output = "$(eol)$(eol)" + output
645 elif not self.output_queue[-1].endswith("\r\n"+chr(27)+"[0m"+"\r\n") and not self.output_queue[-1].endswith("\r\n\r\n"):
646 output = "$(eol)" + output
647 output += eol + chr(27) + "[0m"
649 # tack on a prompt if active
650 if self.state == "active":
651 if not just_prompt: output += "$(eol)"
654 mode = self.avatar.get("mode")
655 if mode: output += "(" + mode + ") "
657 # find and replace macros in the output
658 output = replace_macros(self, output)
660 # wrap the text at 79 characters
661 output = wrap_ansi_text(output, 79)
663 # tack the terminator back on
664 if terminate: output += self.terminator
666 # drop the output into the user's output queue
667 self.output_queue.append(output)
669 # if this is urgent, flush all pending output
670 if flush: self.flush()
673 """All the things to do to the user per increment."""
675 # if the world is terminating, disconnect
676 if universe.terminate_flag:
677 self.state = "disconnecting"
678 self.menu_seen = False
680 # if output is paused, decrement the counter
681 if self.state == "initial":
682 if self.negotiation_pause: self.negotiation_pause -= 1
683 else: self.state = "entering_account_name"
685 # show the user a menu as needed
686 elif not self.state == "active": self.show_menu()
688 # flush any pending output in teh queue
691 # disconnect users with the appropriate state
692 if self.state == "disconnecting": self.quit()
694 # check for input and add it to the queue
697 # there is input waiting in the queue
699 handle_user_input(self)
702 """Try to send the last item in the queue and remove it."""
703 if self.output_queue:
704 if self.received_newline:
705 self.received_newline = False
706 if self.output_queue[0].startswith("\r\n"):
707 self.output_queue[0] = self.output_queue[0][2:]
709 self.connection.send(self.output_queue[0])
710 del self.output_queue[0]
715 def enqueue_input(self):
716 """Process and enqueue any new input."""
718 # check for some input
720 input_data = self.connection.recv(1024)
727 # tack this on to any previous partial
728 self.partial_input += input_data
730 # reply to and remove any IAC negotiation codes
731 self.negotiate_telnet_options()
733 # separate multiple input lines
734 new_input_lines = self.partial_input.split("\n")
736 # if input doesn't end in a newline, replace the
737 # held partial input with the last line of it
738 if not self.partial_input.endswith("\n"):
739 self.partial_input = new_input_lines.pop()
741 # otherwise, chop off the extra null input and reset
742 # the held partial input
744 new_input_lines.pop()
745 self.partial_input = ""
747 # iterate over the remaining lines
748 for line in new_input_lines:
750 # remove a trailing carriage return
751 if line.endswith("\r"): line = line.rstrip("\r")
753 # log non-printable characters remaining
754 removed = filter(lambda x: (x < " " or x > "~"), line)
756 logline = "Non-printable characters from "
757 if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
758 else: logline += "unknown user: "
759 logline += repr(removed)
762 # filter out non-printables
763 line = filter(lambda x: " " <= x <= "~", line)
765 # strip off extra whitespace
768 # put on the end of the queue
769 self.input_queue.append(line)
771 def negotiate_telnet_options(self):
772 """Reply to/remove partial_input telnet negotiation options."""
774 # start at the begining of the input
777 # make a local copy to play with
778 text = self.partial_input
780 # as long as we haven't checked it all
781 while position < len(text):
783 # jump to the first IAC you find
784 position = text.find(IAC, position)
786 # if there wasn't an IAC in the input, skip to the end
787 if position < 0: position = len(text)
789 # replace a double (literal) IAC if there's an LF later
790 elif len(text) > position+1 and text[position+1] == IAC:
791 if text.find("\n", position) > 0: text = text.replace(IAC+IAC, IAC)
795 # this must be an option negotiation
796 elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
798 negotiation = text[position+1:position+3]
800 # if we turned echo off, ignore the confirmation
801 if not self.echoing and negotiation == DO+ECHO: pass
804 elif negotiation == WILL+LINEMODE: self.send(IAC+DO+LINEMODE, raw=True)
806 # if the client likes EOR instead of GA, make a note of it
807 elif negotiation == DO+EOR: self.terminator = IAC+EOR
808 elif negotiation == DONT+EOR and self.terminator == IAC+EOR:
809 self.terminator = IAC+GA
811 # if the client doesn't want GA, oblige
812 elif negotiation == DO+SGA and self.terminator == IAC+GA:
814 self.send(IAC+WILL+SGA, raw=True)
816 # we don't want to allow anything else
817 elif text[position+1] == DO: self.send(IAC+WONT+text[position+2], raw=True)
818 elif text[position+1] == WILL: self.send(IAC+DONT+text[position+2], raw=True)
820 # strip the negotiation from the input
821 text = text.replace(text[position:position+3], "")
823 # get rid of IAC SB .* IAC SE
824 elif len(text) > position+4 and text[position:position+2] == IAC+SB:
825 end_subnegotiation = text.find(IAC+SE, position)
826 if end_subnegotiation > 0: text = text[:position] + text[end_subnegotiation+2:]
829 # otherwise, strip out a two-byte IAC command
830 elif len(text) > position+2: text = text.replace(text[position:position+2], "")
832 # and this means we got the begining of an IAC
835 # replace the input with our cleaned-up text
836 self.partial_input = text
838 def new_avatar(self):
839 """Instantiate a new, unconfigured avatar for this user."""
841 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
842 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
843 self.avatar.append("inherit", "archetype:avatar")
844 self.account.append("avatars", self.avatar.key)
846 def delete_avatar(self, avatar):
847 """Remove an avatar from the world and from the user's list."""
848 if self.avatar is universe.contents[avatar]: self.avatar = None
849 universe.contents[avatar].destroy()
850 avatars = self.account.getlist("avatars")
851 avatars.remove(avatar)
852 self.account.set("avatars", avatars)
854 def activate_avatar_by_index(self, index):
855 """Enter the world with a particular indexed avatar."""
856 self.avatar = universe.contents[self.account.getlist("avatars")[index]]
857 self.avatar.owner = self
858 self.state = "active"
859 self.avatar.go_home()
861 def deactivate_avatar(self):
862 """Have the active avatar leave the world."""
864 current = self.avatar.get("location")
866 self.avatar.set("default_location", current)
867 self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
868 del universe.contents[current].contents[self.avatar.key]
869 self.avatar.remove_facet("location")
870 self.avatar.owner = None
874 """Destroy the user and associated avatars."""
875 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
876 self.account.destroy()
878 def list_avatar_names(self):
879 """List names of assigned avatars."""
880 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
883 """Turn string into list type."""
884 if value[0] + value[-1] == "[]": return eval(value)
885 else: return [ value ]
888 """Turn string into dict type."""
889 if value[0] + value[-1] == "{}": return eval(value)
890 elif value.find(":") > 0: return eval("{" + value + "}")
891 else: return { value: None }
893 def broadcast(message, add_prompt=True):
894 """Send a message to all connected users."""
895 for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
897 def log(message, level=0):
900 # a couple references we need
901 file_name = universe.categories["internal"]["logging"].get("file")
902 max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
903 syslog_name = universe.categories["internal"]["logging"].get("syslog")
904 timestamp = asctime()[4:19]
906 # turn the message into a list of lines
907 lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
909 # send the timestamp and line to a file
911 if not isabs(file_name):
912 file_name = path_join(universe.startdir, file_name)
913 file_descriptor = file(file_name, "a")
914 for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
915 file_descriptor.flush()
916 file_descriptor.close()
918 # send the timestamp and line to standard output
919 if universe.categories["internal"]["logging"].getboolean("stdout"):
920 for line in lines: print(timestamp + " " + line)
922 # send the line to the system log
924 openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
925 for line in lines: syslog(line)
928 # display to connected administrators
929 for user in universe.userlist:
930 if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
931 # iterate over every line in the message
934 full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
935 user.send(full_message, flush=True)
937 # add to the recent log list
939 while 0 < len(universe.loglines) >= max_log_lines: del universe.loglines[0]
940 universe.loglines.append((level, timestamp + " " + line))
942 def get_loglines(level, start, stop):
943 """Return a specific range of loglines filtered by level."""
945 # filter the log lines
946 loglines = filter(lambda x: x[0]>=level, universe.loglines)
948 # we need these in several places
949 total_count = str(len(universe.loglines))
950 filtered_count = len(loglines)
952 # don't proceed if there are no lines
955 # can't start before the begining or at the end
956 if start > filtered_count: start = filtered_count
957 if start < 1: start = 1
959 # can't stop before we start
960 if stop > start: stop = start
961 elif stop < 1: stop = 1
964 message = "There are " + str(total_count)
965 message += " log lines in memory and " + str(filtered_count)
966 message += " at or above level " + str(level) + "."
967 message += " The matching lines from " + str(stop) + " to "
968 message += str(start) + " are:$(eol)$(eol)"
970 # add the text from the selected lines
971 if stop > 1: range_lines = loglines[-start:-(stop-1)]
972 else: range_lines = loglines[-start:]
973 for line in range_lines:
974 message += " (" + str(line[0]) + ") " + line[1] + "$(eol)"
976 # there were no lines
978 message = "None of the " + str(total_count)
979 message += " lines in memory matches your request."
984 def wrap_ansi_text(text, width):
985 """Wrap text with arbitrary width while ignoring ANSI colors."""
987 # the current position in the entire text string, including all
988 # characters, printable or otherwise
989 absolute_position = 0
991 # the current text position relative to the begining of the line,
992 # ignoring color escape sequences
993 relative_position = 0
995 # whether the current character is part of a color escape sequence
998 # iterate over each character from the begining of the text
999 for each_character in text:
1001 # the current character is the escape character
1002 if each_character == chr(27):
1005 # the current character is within an escape sequence
1008 # the current character is m, which terminates the
1009 # current escape sequence
1010 if each_character == "m":
1013 # the current character is a newline, so reset the relative
1014 # position (start a new line)
1015 elif each_character == "\n":
1016 relative_position = 0
1018 # the current character meets the requested maximum line width,
1019 # so we need to backtrack and find a space at which to wrap
1020 elif relative_position == width:
1022 # distance of the current character examined from the
1026 # count backwards until we find a space
1027 while text[absolute_position - wrap_offset] != " ":
1030 # insert an eol in place of the space
1031 text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
1033 # increase the absolute position because an eol is two
1034 # characters but the space it replaced was only one
1035 absolute_position += 1
1037 # now we're at the begining of a new line, plus the
1038 # number of characters wrapped from the previous line
1039 relative_position = wrap_offset
1041 # as long as the character is not a carriage return and the
1042 # other above conditions haven't been met, count it as a
1043 # printable character
1044 elif each_character != "\r":
1045 relative_position += 1
1047 # increase the absolute position for every character
1048 absolute_position += 1
1050 # return the newly-wrapped text
1053 def weighted_choice(data):
1054 """Takes a dict weighted by value and returns a random key."""
1056 # this will hold our expanded list of keys from the data
1059 # create thee expanded list of keys
1060 for key in data.keys():
1061 for count in range(data[key]):
1062 expanded.append(key)
1064 # return one at random
1065 return choice(expanded)
1068 """Returns a random character name."""
1070 # the vowels and consonants needed to create romaji syllables
1071 vowels = [ "a", "i", "u", "e", "o" ]
1072 consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
1074 # this dict will hold our weighted list of syllables
1077 # generate the list with an even weighting
1078 for consonant in consonants:
1079 for vowel in vowels:
1080 syllables[consonant + vowel] = 1
1082 # we'll build the name into this string
1085 # create a name of random length from the syllables
1086 for syllable in range(randrange(2, 6)):
1087 name += weighted_choice(syllables)
1089 # strip any leading quotemark, capitalize and return the name
1090 return name.strip("'").capitalize()
1092 def replace_macros(user, text, is_input=False):
1093 """Replaces macros in text output."""
1098 # third person pronouns
1100 "female": { "obj": "her", "pos": "hers", "sub": "she" },
1101 "male": { "obj": "him", "pos": "his", "sub": "he" },
1102 "neuter": { "obj": "it", "pos": "its", "sub": "it" }
1105 # a dict of replacement macros
1108 "$(bld)": chr(27) + "[1m",
1109 "$(nrm)": chr(27) + "[0m",
1110 "$(blk)": chr(27) + "[30m",
1111 "$(blu)": chr(27) + "[34m",
1112 "$(cyn)": chr(27) + "[36m",
1113 "$(grn)": chr(27) + "[32m",
1114 "$(mgt)": chr(27) + "[35m",
1115 "$(red)": chr(27) + "[31m",
1116 "$(yel)": chr(27) + "[33m",
1119 # add dynamic macros where possible
1121 account_name = user.account.get("name")
1123 macros["$(account)"] = account_name
1125 avatar_gender = user.avatar.get("gender")
1127 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
1128 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
1129 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
1131 # find and replace per the macros dict
1132 macro_start = text.find("$(")
1133 if macro_start == -1: break
1134 macro_end = text.find(")", macro_start) + 1
1135 macro = text[macro_start:macro_end]
1136 if macro in macros.keys():
1137 text = text.replace(macro, macros[macro])
1139 # if we get here, log and replace it with null
1141 text = text.replace(macro, "")
1143 log("Unexpected replacement macro " + macro + " encountered.", 6)
1145 # replace the look-like-a-macro sequence
1146 text = text.replace("$_(", "$(")
1150 def escape_macros(text):
1151 """Escapes replacement macros in text."""
1152 return text.replace("$(", "$_(")
1154 def first_word(text, separator=" "):
1155 """Returns a tuple of the first word and the rest."""
1157 if text.find(separator) > 0: return text.split(separator, 1)
1158 else: return text, ""
1162 """The things which should happen on each pulse, aside from reloads."""
1164 # open the listening socket if it hasn't been already
1165 if not hasattr(universe, "listening_socket"):
1166 universe.initialize_server_socket()
1168 # assign a user if a new connection is waiting
1169 user = check_for_connection(universe.listening_socket)
1170 if user: universe.userlist.append(user)
1172 # iterate over the connected users
1173 for user in universe.userlist: user.pulse()
1175 # add an element for counters if it doesn't exist
1176 if not "counters" in universe.categories["internal"]:
1177 universe.categories["internal"]["counters"] = Element("internal:counters", universe)
1179 # update the log every now and then
1180 if not universe.categories["internal"]["counters"].getint("mark"):
1181 log(str(len(universe.userlist)) + " connection(s)")
1182 universe.categories["internal"]["counters"].set("mark", universe.categories["internal"]["time"].getint("frequency_log"))
1183 else: universe.categories["internal"]["counters"].set("mark", universe.categories["internal"]["counters"].getint("mark") - 1)
1185 # periodically save everything
1186 if not universe.categories["internal"]["counters"].getint("save"):
1188 universe.categories["internal"]["counters"].set("save", universe.categories["internal"]["time"].getint("frequency_save"))
1189 else: universe.categories["internal"]["counters"].set("save", universe.categories["internal"]["counters"].getint("save") - 1)
1191 # pause for a configurable amount of time (decimal seconds)
1192 sleep(universe.categories["internal"]["time"].getfloat("increment"))
1194 # increase the elapsed increment counter
1195 universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
1198 """Reload all relevant objects."""
1199 for user in universe.userlist[:]: user.reload()
1200 for element in universe.contents.values():
1201 if element.origin.is_writeable(): element.reload()
1204 def check_for_connection(listening_socket):
1205 """Check for a waiting connection and return a new user object."""
1207 # try to accept a new connection
1209 connection, address = listening_socket.accept()
1213 # note that we got one
1214 log("Connection from " + address[0], 2)
1216 # disable blocking so we can proceed whether or not we can send/receive
1217 connection.setblocking(0)
1219 # create a new user object
1222 # associate this connection with it
1223 user.connection = connection
1225 # set the user's ipa from the connection's ipa
1226 user.address = address[0]
1228 # let the client know we WILL EOR
1229 user.send(IAC+WILL+EOR, raw=True)
1230 user.negotiation_pause = 2
1232 # return the new user object
1235 def get_menu(state, error=None, echoing=True, terminator="", choices=None):
1236 """Show the correct menu text to a user."""
1238 # make sure we don't reuse a mutable sequence by default
1239 if choices is None: choices = {}
1241 # begin with a telnet echo command sequence if needed
1242 message = get_echo_sequence(state, echoing)
1244 # get the description or error text
1245 message += get_menu_description(state, error)
1247 # get menu choices for the current state
1248 message += get_formatted_menu_choices(state, choices)
1250 # try to get a prompt, if it was defined
1251 message += get_menu_prompt(state)
1253 # throw in the default choice, if it exists
1254 message += get_formatted_default_menu_choice(state)
1256 # display a message indicating if echo is off
1257 message += get_echo_message(state)
1259 # tack on EOR or GA to indicate the prompt will not be followed by CRLF
1260 message += terminator
1262 # return the assembly of various strings defined above
1265 def menu_echo_on(state):
1266 """True if echo is on, false if it is off."""
1267 return universe.categories["menu"][state].getboolean("echo", True)
1269 def get_echo_sequence(state, echoing):
1270 """Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
1272 # if the user has echo on and the menu specifies it should be turned
1273 # off, send: iac + will + echo + null
1274 if echoing and not menu_echo_on(state): return IAC+WILL+ECHO
1276 # if echo is not set to off in the menu and the user curently has echo
1277 # off, send: iac + wont + echo + null
1278 elif not echoing and menu_echo_on(state): return IAC+WONT+ECHO
1280 # default is not to send an echo control sequence at all
1283 def get_echo_message(state):
1284 """Return a message indicating that echo is off."""
1285 if menu_echo_on(state): return ""
1286 else: return "(won't echo) "
1288 def get_default_menu_choice(state):
1289 """Return the default choice for a menu."""
1290 return universe.categories["menu"][state].get("default")
1292 def get_formatted_default_menu_choice(state):
1293 """Default menu choice foratted for inclusion in a prompt string."""
1294 default_choice = get_default_menu_choice(state)
1295 if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
1298 def get_menu_description(state, error):
1299 """Get the description or error text."""
1301 # an error condition was raised by the handler
1304 # try to get an error message matching the condition
1306 description = universe.categories["menu"][state].get("error_" + error)
1307 if not description: description = "That is not a valid choice..."
1308 description = "$(red)" + description + "$(nrm)"
1310 # there was no error condition
1313 # try to get a menu description for the current state
1314 description = universe.categories["menu"][state].get("description")
1316 # return the description or error message
1317 if description: description += "$(eol)$(eol)"
1320 def get_menu_prompt(state):
1321 """Try to get a prompt, if it was defined."""
1322 prompt = universe.categories["menu"][state].get("prompt")
1323 if prompt: prompt += " "
1326 def get_menu_choices(user):
1327 """Return a dict of choice:meaning."""
1328 menu = universe.categories["menu"][user.state]
1329 create_choices = menu.get("create")
1330 if create_choices: choices = eval(create_choices)
1335 for facet in menu.facets():
1336 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
1337 ignores.append(facet.split("_", 2)[1])
1338 elif facet.startswith("create_"):
1339 creates[facet] = facet.split("_", 2)[1]
1340 elif facet.startswith("choice_"):
1341 options[facet] = facet.split("_", 2)[1]
1342 for facet in creates.keys():
1343 if not creates[facet] in ignores:
1344 choices[creates[facet]] = eval(menu.get(facet))
1345 for facet in options.keys():
1346 if not options[facet] in ignores:
1347 choices[options[facet]] = menu.get(facet)
1350 def get_formatted_menu_choices(state, choices):
1351 """Returns a formatted string of menu choices."""
1353 choice_keys = choices.keys()
1355 for choice in choice_keys:
1356 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[choice] + "$(eol)"
1357 if choice_output: choice_output += "$(eol)"
1358 return choice_output
1360 def get_menu_branches(state):
1361 """Return a dict of choice:branch."""
1363 for facet in universe.categories["menu"][state].facets():
1364 if facet.startswith("branch_"):
1365 branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1368 def get_default_branch(state):
1369 """Return the default branch."""
1370 return universe.categories["menu"][state].get("branch")
1372 def get_choice_branch(user, choice):
1373 """Returns the new state matching the given choice."""
1374 branches = get_menu_branches(user.state)
1375 if choice in branches.keys(): return branches[choice]
1376 elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
1379 def get_menu_actions(state):
1380 """Return a dict of choice:branch."""
1382 for facet in universe.categories["menu"][state].facets():
1383 if facet.startswith("action_"):
1384 actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1387 def get_default_action(state):
1388 """Return the default action."""
1389 return universe.categories["menu"][state].get("action")
1391 def get_choice_action(user, choice):
1392 """Run any indicated script for the given choice."""
1393 actions = get_menu_actions(user.state)
1394 if choice in actions.keys(): return actions[choice]
1395 elif choice in user.menu_choices.keys(): return get_default_action(user.state)
1398 def handle_user_input(user):
1399 """The main handler, branches to a state-specific handler."""
1401 # if the user's client echo is off, send a blank line for aesthetics
1402 if user.echoing: user.received_newline = True
1404 # check to make sure the state is expected, then call that handler
1405 if "handler_" + user.state in globals():
1406 exec("handler_" + user.state + "(user)")
1408 generic_menu_handler(user)
1410 # since we got input, flag that the menu/prompt needs to be redisplayed
1411 user.menu_seen = False
1413 def generic_menu_handler(user):
1414 """A generic menu choice handler."""
1416 # get a lower-case representation of the next line of input
1417 if user.input_queue:
1418 choice = user.input_queue.pop(0)
1419 if choice: choice = choice.lower()
1421 if not choice: choice = get_default_menu_choice(user.state)
1422 if choice in user.menu_choices:
1423 exec(get_choice_action(user, choice))
1424 new_state = get_choice_branch(user, choice)
1425 if new_state: user.state = new_state
1426 else: user.error = "default"
1428 def handler_entering_account_name(user):
1429 """Handle the login account name."""
1431 # get the next waiting line of input
1432 input_data = user.input_queue.pop(0)
1434 # did the user enter anything?
1437 # keep only the first word and convert to lower-case
1438 name = input_data.lower()
1440 # fail if there are non-alphanumeric characters
1441 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
1442 user.error = "bad_name"
1444 # if that account exists, time to request a password
1445 elif name in universe.categories["account"]:
1446 user.account = universe.categories["account"][name]
1447 user.state = "checking_password"
1449 # otherwise, this could be a brand new user
1451 user.account = Element("account:" + name, universe)
1452 user.account.set("name", name)
1453 log("New user: " + name, 2)
1454 user.state = "checking_new_account_name"
1456 # if the user entered nothing for a name, then buhbye
1458 user.state = "disconnecting"
1460 def handler_checking_password(user):
1461 """Handle the login account password."""
1463 # get the next waiting line of input
1464 input_data = user.input_queue.pop(0)
1466 # does the hashed input equal the stored hash?
1467 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1469 # if so, set the username and load from cold storage
1470 if not user.replace_old_connections():
1472 user.state = "main_utility"
1474 # if at first your hashes don't match, try, try again
1475 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1476 user.password_tries += 1
1477 user.error = "incorrect"
1479 # we've exceeded the maximum number of password failures, so disconnect
1481 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1482 user.state = "disconnecting"
1484 def handler_entering_new_password(user):
1485 """Handle a new password entry."""
1487 # get the next waiting line of input
1488 input_data = user.input_queue.pop(0)
1490 # make sure the password is strong--at least one upper, one lower and
1491 # one digit, seven or more characters in length
1492 if len(input_data) > 6 and len(filter(lambda x: x>="0" and x<="9", input_data)) and len(filter(lambda x: x>="A" and x<="Z", input_data)) and len(filter(lambda x: x>="a" and x<="z", input_data)):
1494 # hash and store it, then move on to verification
1495 user.account.set("passhash", new_md5(user.account.get("name") + input_data).hexdigest())
1496 user.state = "verifying_new_password"
1498 # the password was weak, try again if you haven't tried too many times
1499 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1500 user.password_tries += 1
1503 # too many tries, so adios
1505 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1506 user.account.destroy()
1507 user.state = "disconnecting"
1509 def handler_verifying_new_password(user):
1510 """Handle the re-entered new password for verification."""
1512 # get the next waiting line of input
1513 input_data = user.input_queue.pop(0)
1515 # hash the input and match it to storage
1516 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1519 # the hashes matched, so go active
1520 if not user.replace_old_connections(): user.state = "main_utility"
1522 # go back to entering the new password as long as you haven't tried
1524 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1525 user.password_tries += 1
1526 user.error = "differs"
1527 user.state = "entering_new_password"
1529 # otherwise, sayonara
1531 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1532 user.account.destroy()
1533 user.state = "disconnecting"
1535 def handler_active(user):
1536 """Handle input for active users."""
1538 # get the next waiting line of input
1539 input_data = user.input_queue.pop(0)
1544 # split out the command and parameters
1546 mode = actor.get("mode")
1547 if mode and input_data.startswith("!"):
1548 command_name, parameters = first_word(input_data[1:])
1549 elif mode == "chat":
1550 command_name = "say"
1551 parameters = input_data
1553 command_name, parameters = first_word(input_data)
1555 # lowercase the command
1556 command_name = command_name.lower()
1558 # the command matches a command word for which we have data
1559 if command_name in universe.categories["command"]:
1560 command = universe.categories["command"][command_name]
1561 else: command = None
1563 # if it's allowed, do it
1564 if actor.can_run(command): exec(command.get("action"))
1566 # otherwise, give an error
1567 elif command_name: command_error(actor, input_data)
1569 # if no input, just idle back with a prompt
1570 else: user.send("", just_prompt=True)
1572 def command_halt(actor, parameters):
1573 """Halt the world."""
1576 # see if there's a message or use a generic one
1577 if parameters: message = "Halting: " + parameters
1578 else: message = "User " + actor.owner.account.get("name") + " halted the world."
1581 broadcast(message, add_prompt=False)
1584 # set a flag to terminate the world
1585 universe.terminate_flag = True
1587 def command_reload(actor):
1588 """Reload all code modules, configs and data."""
1591 # let the user know and log
1592 actor.send("Reloading all code modules, configs and data.")
1593 log("User " + actor.owner.account.get("name") + " reloaded the world.", 8)
1595 # set a flag to reload
1596 universe.reload_flag = True
1598 def command_quit(actor):
1599 """Leave the world and go back to the main menu."""
1601 actor.owner.state = "main_utility"
1602 actor.owner.deactivate_avatar()
1604 def command_help(actor, parameters):
1605 """List available commands and provide help for commands."""
1607 # did the user ask for help on a specific command word?
1608 if parameters and actor.owner:
1610 # is the command word one for which we have data?
1611 if parameters in universe.categories["command"]:
1612 command = universe.categories["command"][parameters]
1613 else: command = None
1615 # only for allowed commands
1616 if actor.can_run(command):
1618 # add a description if provided
1619 description = command.get("description")
1621 description = "(no short description provided)"
1622 if command.getboolean("administrative"): output = "$(red)"
1623 else: output = "$(grn)"
1624 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1626 # add the help text if provided
1627 help_text = command.get("help")
1629 help_text = "No help is provided for this command."
1632 # list related commands
1633 see_also = command.getlist("see_also")
1635 really_see_also = ""
1636 for item in see_also:
1637 if item in universe.categories["command"]:
1638 command = universe.categories["command"][item]
1639 if actor.can_run(command):
1641 really_see_also += ", "
1642 if command.getboolean("administrative"):
1643 really_see_also += "$(red)"
1645 really_see_also += "$(grn)"
1646 really_see_also += item + "$(nrm)"
1648 output += "$(eol)$(eol)See also: " + really_see_also
1650 # no data for the requested command word
1652 output = "That is not an available command."
1654 # no specific command word was indicated
1657 # give a sorted list of commands with descriptions if provided
1658 output = "These are the commands available to you:$(eol)$(eol)"
1659 sorted_commands = universe.categories["command"].keys()
1660 sorted_commands.sort()
1661 for item in sorted_commands:
1662 command = universe.categories["command"][item]
1663 if actor.can_run(command):
1664 description = command.get("description")
1666 description = "(no short description provided)"
1667 if command.getboolean("administrative"): output += " $(red)"
1668 else: output += " $(grn)"
1669 output += item + "$(nrm) - " + description + "$(eol)"
1670 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1672 # send the accumulated output to the user
1675 def command_move(actor, parameters):
1676 """Move the avatar in a given direction."""
1677 if parameters in universe.contents[actor.get("location")].portals():
1678 actor.move_direction(parameters)
1679 else: actor.send("You cannot go that way.")
1681 def command_look(actor, parameters):
1683 if parameters: actor.send("You can't look at or in anything yet.")
1684 else: actor.look_at(actor.get("location"))
1686 def command_say(actor, parameters):
1687 """Speak to others in the same room."""
1689 # check for replacement macros
1690 if replace_macros(actor.owner, parameters, True) != parameters:
1691 actor.send("You cannot speak $_(replacement macros).")
1693 # the user entered a message
1696 # get rid of quote marks on the ends of the message
1697 message = parameters.strip("\"'`")
1699 # match the punctuation used, if any, to an action
1700 actions = universe.categories["internal"]["language"].getdict("actions")
1701 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1703 for mark in actions.keys():
1704 if message.endswith(mark):
1705 action = actions[mark]
1708 # add punctuation if needed
1710 action = actions[default_punctuation]
1711 if message and not message[-1] in punctuation:
1712 message += default_punctuation
1714 # decapitalize the first letter to improve matching
1715 if message and message[0] in uppercase:
1716 message = message[0].lower() + message[1:]
1718 # iterate over all words in message, replacing typos
1719 typos = universe.categories["internal"]["language"].getdict("typos")
1720 words = message.split()
1721 for index in range(len(words)):
1723 bare_word = word.strip(punctuation)
1724 if bare_word in typos.keys():
1725 words[index] = word.replace(bare_word, typos[bare_word])
1726 message = " ".join(words)
1728 # capitalize the first letter
1729 message = message[0].upper() + message[1:]
1732 actor.echo_to_location(actor.get("name") + " " + action + "s, \"" + message + "\"")
1733 actor.send("You " + action + ", \"" + message + "\"")
1735 # there was no message
1737 actor.send("What do you want to say?")
1739 def command_chat(actor):
1740 """Toggle chat mode."""
1741 mode = actor.get("mode")
1743 actor.set("mode", "chat")
1744 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
1745 elif mode == "chat":
1746 actor.remove_facet("mode")
1747 actor.send("Exiting chat mode.")
1748 else: actor.send("Sorry, but you're already busy with something else!")
1750 def command_show(actor, parameters):
1751 """Show program data."""
1753 arguments = parameters.split()
1754 if not parameters: message = "What do you want to show?"
1755 elif arguments[0] == "time":
1756 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1757 elif arguments[0] == "categories":
1758 message = "These are the element categories:$(eol)"
1759 categories = universe.categories.keys()
1761 for category in categories: message += "$(eol) $(grn)" + category + "$(nrm)"
1762 elif arguments[0] == "files":
1763 message = "These are the current files containing the universe:$(eol)"
1764 filenames = universe.files.keys()
1766 for filename in filenames:
1767 if universe.files[filename].is_writeable(): status = "rw"
1769 message += "$(eol) $(red)(" + status + ") $(grn)" + filename + "$(nrm)"
1770 elif arguments[0] == "category":
1771 if len(arguments) != 2: message = "You must specify one category."
1772 elif arguments[1] in universe.categories:
1773 message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
1774 elements = [(universe.categories[arguments[1]][x].key) for x in universe.categories[arguments[1]].keys()]
1776 for element in elements:
1777 message += "$(eol) $(grn)" + element + "$(nrm)"
1778 else: message = "Category \"" + arguments[1] + "\" does not exist."
1779 elif arguments[0] == "file":
1780 if len(arguments) != 2: message = "You must specify one file."
1781 elif arguments[1] in universe.files:
1782 message = "These are the elements in the \"" + arguments[1] + "\" file:$(eol)"
1783 elements = universe.files[arguments[1]].data.sections()
1785 for element in elements:
1786 message += "$(eol) $(grn)" + element + "$(nrm)"
1787 else: message = "Category \"" + arguments[1] + "\" does not exist."
1788 elif arguments[0] == "element":
1789 if len(arguments) != 2: message = "You must specify one element."
1790 elif arguments[1] in universe.contents:
1791 element = universe.contents[arguments[1]]
1792 message = "These are the properties of the \"" + arguments[1] + "\" element (in \"" + element.origin.filename + "\"):$(eol)"
1793 facets = element.facets()
1795 for facet in facets:
1796 message += "$(eol) $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
1797 else: message = "Element \"" + arguments[1] + "\" does not exist."
1798 elif arguments[0] == "result":
1799 if len(arguments) < 2: message = "You need to specify an expression."
1802 message = repr(eval(" ".join(arguments[1:])))
1804 message = "Your expression raised an exception!"
1805 elif arguments[0] == "log":
1806 if len(arguments) == 4:
1807 if match("^\d+$", arguments[3]) and int(arguments[3]) >= 0:
1808 stop = int(arguments[3])
1811 if len(arguments) >= 3:
1812 if match("^\d+$", arguments[2]) and int(arguments[2]) > 0:
1813 start = int(arguments[2])
1816 if len(arguments) >= 2:
1817 if match("^\d+$", arguments[1]) and 0 <= int(arguments[1]) <= 9:
1818 level = int(arguments[1])
1820 elif 0 <= actor.owner.account.getint("loglevel") <= 9:
1821 level = actor.owner.account.getint("loglevel")
1823 if level > -1 and start > -1 and stop > -1:
1824 message = get_loglines(level, start, stop)
1825 else: message = "When specified, level must be 0-9 (default 1), start and stop must be >=1 (default 10 and 1)."
1826 else: message = "I don't know what \"" + parameters + "\" is."
1829 def command_create(actor, parameters):
1830 """Create an element if it does not exist."""
1831 if not parameters: message = "You must at least specify an element to create."
1832 elif not actor.owner: message = ""
1834 arguments = parameters.split()
1835 if len(arguments) == 1: arguments.append("")
1836 if len(arguments) == 2:
1837 element, filename = arguments
1838 if element in universe.contents: message = "The \"" + element + "\" element already exists."
1840 message = "You create \"" + element + "\" within the universe."
1841 logline = actor.owner.account.get("name") + " created an element: " + element
1843 logline += " in file " + filename
1844 if filename not in universe.files:
1845 message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
1846 Element(element, universe, filename)
1848 elif len(arguments) > 2: message = "You can only specify an element and a filename."
1851 def command_destroy(actor, parameters):
1852 """Destroy an element if it exists."""
1854 if not parameters: message = "You must specify an element to destroy."
1856 if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
1858 universe.contents[parameters].destroy()
1859 message = "You destroy \"" + parameters + "\" within the universe."
1860 log(actor.owner.account.get("name") + " destroyed an element: " + parameters, 6)
1863 def command_set(actor, parameters):
1864 """Set a facet of an element."""
1865 if not parameters: message = "You must specify an element, a facet and a value."
1867 arguments = parameters.split(" ", 2)
1868 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
1869 elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
1871 element, facet, value = arguments
1872 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1874 universe.contents[element].set(facet, value)
1875 message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1878 def command_delete(actor, parameters):
1879 """Delete a facet from an element."""
1880 if not parameters: message = "You must specify an element and a facet."
1882 arguments = parameters.split(" ")
1883 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
1884 elif len(arguments) != 2: message = "You may only specify an element and a facet."
1886 element, facet = arguments
1887 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1888 elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
1890 universe.contents[element].remove_facet(facet)
1891 message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1894 def command_error(actor, input_data):
1895 """Generic error for an unrecognized command word."""
1897 # 90% of the time use a generic error
1899 message = "I'm not sure what \"" + input_data + "\" means..."
1901 # 10% of the time use the classic diku error
1903 message = "Arglebargle, glop-glyf!?!"
1905 # send the error message
1909 """Fork and disassociate from everything."""
1910 if universe.contents["internal:process"].getboolean("daemon"):
1912 from resource import getrlimit, RLIMIT_NOFILE
1913 log("Disassociating from the controlling terminal.")
1919 for stdpipe in range(3): close(stdpipe)
1920 sys.stdin = sys.__stdin__ = file("/dev/null", "r")
1921 sys.stdout = sys.stderr = sys.__stdout__ = sys.__stderr__ = file("/dev/null", "w")
1923 def create_pidfile(universe):
1924 """Write a file containing the current process ID."""
1926 log("Process ID: " + pid)
1927 file_name = universe.contents["internal:process"].get("pidfile")
1929 if not isabs(file_name):
1930 file_name = path_join(universe.startdir, file_name)
1931 file_descriptor = file(file_name, 'w')
1932 file_descriptor.write(pid + "\n")
1933 file_descriptor.flush()
1934 file_descriptor.close()
1936 def remove_pidfile(universe):
1937 """Remove the file containing the current process ID."""
1938 file_name = universe.contents["internal:process"].get("pidfile")
1940 if not isabs(file_name):
1941 file_name = path_join(universe.startdir, file_name)
1942 if access(file_name, W_OK): remove(file_name)
1944 def excepthook(excepttype, value, traceback):
1945 """Handle uncaught exceptions."""
1947 # assemble the list of errors into a single string
1948 message = "".join(format_exception(excepttype, value, traceback))
1950 # try to log it, if possible
1951 try: log(message, 9)
1954 # try to write it to stderr, if possible
1955 try: stderr.write(message)
1958 def sighook(what, where):
1959 """Handle external signals."""
1962 message = "Caught signal: "
1964 # for a hangup signal
1966 message += "hangup (reloading)"
1967 universe.reload_flag = True
1969 # for a terminate signal
1970 elif what == SIGTERM:
1971 message += "terminate (halting)"
1972 universe.terminate_flag = True
1974 # catchall for unexpected signals
1975 else: message += str(what) + " (unhandled)"
1980 # redefine sys.excepthook with ours
1982 sys.excepthook = excepthook
1984 # assign the sgnal handlers
1985 signal(SIGHUP, sighook)
1986 signal(SIGTERM, sighook)
1988 # if there is no universe, create an empty one
1989 if not "universe" in locals():
1990 if len(argv) > 1: conffile = argv[1]
1992 universe = Universe(conffile, True)
1993 elif universe.reload_flag:
1994 universe = universe.new()