1 """Core objects for the mudpy engine."""
3 # Copyright (c) 2005 mudpy, The Fungi <fungi@yuggoth.org>, all rights reserved.
4 # Licensed per terms in the LICENSE file distributed with this software.
6 # import some things we need
7 from ConfigParser import RawConfigParser
8 from md5 import new as new_md5
9 from os import R_OK, access, chmod, makedirs, stat
10 from os.path import abspath, dirname, exists, isabs, join as path_join
11 from random import choice, randrange
12 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
13 from stat import S_IMODE, ST_MODE
14 from time import asctime, sleep
17 """An element of the universe."""
18 def __init__(self, key, universe, origin=""):
19 """Default values for the in-memory element variables."""
21 if self.key.find(":") > 0:
22 self.category, self.subkey = self.key.split(":", 1)
24 self.category = "other"
25 self.subkey = self.key
26 if not self.category in universe.categories: self.category = "other"
27 universe.categories[self.category][self.subkey] = self
29 if not self.origin: self.origin = universe.default_origins[self.category]
30 if not isabs(self.origin):
31 self.origin = abspath(self.origin)
32 universe.contents[self.key] = self
33 if not self.origin in universe.files:
34 DataFile(self.origin, universe)
35 if not universe.files[self.origin].data.has_section(self.key):
36 universe.files[self.origin].data.add_section(self.key)
38 log("Deleting: " + self.key + ".")
39 universe.files[self.origin].data.remove_section(self.key)
40 del universe.categories[self.category][self.subkey]
41 del universe.contents[self.key]
44 """Return a list of facets for this element."""
45 return universe.files[self.origin].data.options(self.key)
46 def get(self, facet, default=None):
47 """Retrieve values."""
48 if default is None: default = ""
49 if universe.files[self.origin].data.has_option(self.key, facet):
50 return universe.files[self.origin].data.get(self.key, facet)
52 def getboolean(self, facet, default=None):
53 """Retrieve values as boolean type."""
54 if default is None: default=False
55 if universe.files[self.origin].data.has_option(self.key, facet):
56 return universe.files[self.origin].data.getboolean(self.key, facet)
58 def getint(self, facet, default=None):
59 """Return values as int/long type."""
60 if default is None: default = 0
61 if universe.files[self.origin].data.has_option(self.key, facet):
62 return universe.files[self.origin].data.getint(self.key, facet)
64 def getfloat(self, facet, default=None):
65 """Return values as float type."""
66 if default is None: default = 0.0
67 if universe.files[self.origin].data.has_option(self.key, facet):
68 return universe.files[self.origin].data.getfloat(self.key, facet)
70 def getlist(self, facet, default=None):
71 """Return values as list type."""
72 if default is None: default = []
73 value = self.get(facet)
74 if value: return makelist(value)
76 def getdict(self, facet, default=None):
77 """Return values as dict type."""
78 if default is None: default = {}
79 value = self.get(facet)
80 if value: return makedict(value)
82 def set(self, facet, value):
84 if type(value) is long: value = str(value)
85 elif not type(value) is str: value = repr(value)
86 universe.files[self.origin].data.set(self.key, facet, value)
89 """A file containing universe elements."""
90 def __init__(self, filename, universe):
91 self.data = RawConfigParser()
92 if access(filename, R_OK): self.data.read(filename)
93 self.filename = filename
94 universe.files[filename] = self
95 if self.data.has_option("control", "include_files"):
96 includes = makelist(self.data.get("control", "include_files"))
98 if self.data.has_option("control", "default_files"):
99 origins = makedict(self.data.get("control", "default_files"))
100 for key in origins.keys():
101 if not key in includes: includes.append(key)
102 universe.default_origins[key] = origins[key]
103 if not key in universe.categories:
104 universe.categories[key] = {}
105 if self.data.has_option("control", "private_files"):
106 for item in makelist(self.data.get("control", "private_files")):
107 if not item in includes: includes.append(item)
108 if not item in universe.private_files:
110 item = path_join(dirname(filename), item)
111 universe.private_files.append(item)
112 for section in self.data.sections():
113 if section != "control":
114 Element(section, universe, filename)
115 for include_file in includes:
116 if not isabs(include_file):
117 include_file = path_join(dirname(filename), include_file)
118 DataFile(include_file, universe)
120 if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("control", "read_only") and self.data.getboolean("control", "read_only") ):
121 if not exists(dirname(self.filename)): makedirs(dirname)
122 file_descriptor = file(self.filename, "w")
123 if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
124 chmod(self.filename, 0600)
125 self.data.write(file_descriptor)
126 file_descriptor.flush()
127 file_descriptor.close()
131 def __init__(self, filename=""):
132 """Initialize the universe."""
135 self.default_origins = {}
137 self.private_files = []
139 self.terminate_world = False
140 self.reload_modules = False
142 possible_filenames = [
148 "/usr/local/mudpy/mudpy.conf",
149 "/usr/local/mudpy/etc/mudpy.conf",
150 "/etc/mudpy/mudpy.conf",
153 for filename in possible_filenames:
154 if access(filename, R_OK): break
155 if not isabs(filename):
156 filename = abspath(filename)
157 DataFile(filename, self)
159 """Save the universe to persistent storage."""
160 for key in self.files: self.files[key].save()
162 def initialize_server_socket(self):
163 """Create and open the listening socket."""
165 # create a new ipv4 stream-type socket object
166 self.listening_socket = socket(AF_INET, SOCK_STREAM)
168 # set the socket options to allow existing open ones to be
169 # reused (fixes a bug where the server can't bind for a minute
170 # when restarting on linux systems)
171 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
173 # bind the socket to to our desired server ipa and port
174 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
176 # disable blocking so we can proceed whether or not we can
178 self.listening_socket.setblocking(0)
180 # start listening on the socket
181 self.listening_socket.listen(1)
183 # note that we're now ready for user connections
184 log("Waiting for connection(s)...")
187 """This is a connected user."""
190 """Default values for the in-memory user variables."""
192 self.last_address = ""
193 self.connection = None
194 self.authenticated = False
195 self.password_tries = 0
196 self.state = "entering_account_name"
197 self.menu_seen = False
199 self.input_queue = []
200 self.output_queue = []
201 self.partial_input = ""
207 """Log, close the connection and remove."""
208 if self.account: name = self.account.get("name")
210 if name: message = "User " + name
211 else: message = "An unnamed user"
212 message += " logged out."
214 self.connection.close()
218 """Save, load a new user and relocate the connection."""
220 # get out of the list
223 # create a new user object
226 # set everything else equivalent
243 exec("new_user." + attribute + " = self." + attribute)
246 universe.userlist.append(new_user)
248 # get rid of the old user object
251 def replace_old_connections(self):
252 """Disconnect active users with the same name."""
254 # the default return value
257 # iterate over each user in the list
258 for old_user in universe.userlist:
260 # the name is the same but it's not us
261 if old_user.account.get("name") == self.account.get("name") and old_user is not self:
264 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".")
265 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)")
266 self.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
268 # close the old connection
269 old_user.connection.close()
271 # replace the old connection with this one
272 old_user.connection = self.connection
273 old_user.last_address = old_user.address
274 old_user.address = self.address
275 old_user.echoing = self.echoing
277 # take this one out of the list and delete
283 # true if an old connection was replaced, false if not
286 def authenticate(self):
287 """Flag the user as authenticated and disconnect duplicates."""
288 if not self.state is "authenticated":
289 log("User " + self.account.get("name") + " logged in.")
290 self.authenticated = True
293 """Send the user their current menu."""
294 if not self.menu_seen:
295 self.menu_choices = get_menu_choices(self)
296 self.send(get_menu(self.state, self.error, self.echoing, self.menu_choices), "")
297 self.menu_seen = True
299 self.adjust_echoing()
301 def adjust_echoing(self):
302 """Adjust echoing to match state menu requirements."""
303 if self.echoing and not menu_echo_on(self.state): self.echoing = False
304 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
307 """Remove a user from the list of connected users."""
308 universe.userlist.remove(self)
310 def send(self, output, eol="$(eol)"):
311 """Send arbitrary text to a connected user."""
313 # only when there is actual output
316 # start with a newline, append the message, then end
317 # with the optional eol string passed to this function
318 # and the ansi escape to return to normal text
319 output = "\r\n" + output + eol + chr(27) + "[0m"
321 # find and replace macros in the output
322 output = replace_macros(self, output)
324 # wrap the text at 80 characters
325 # TODO: prompt user for preferred wrap width
326 output = wrap_ansi_text(output, 80)
328 # drop the formatted output into the output queue
329 self.output_queue.append(output)
331 # try to send the last item in the queue, remove it and
332 # flag that menu display is not needed
334 self.connection.send(self.output_queue[0])
335 self.output_queue.remove(self.output_queue[0])
336 self.menu_seen = False
338 # but if we can't, that's okay too
343 """All the things to do to the user per increment."""
345 # if the world is terminating, disconnect
346 if universe.terminate_world:
347 self.state = "disconnecting"
348 self.menu_seen = False
350 # show the user a menu as needed
353 # disconnect users with the appropriate state
354 if self.state == "disconnecting":
357 # the user is unique and not flagged to disconnect
360 # check for input and add it to the queue
363 # there is input waiting in the queue
364 if self.input_queue: handle_user_input(self)
366 def enqueue_input(self):
367 """Process and enqueue any new input."""
369 # check for some input
371 input_data = self.connection.recv(1024)
378 # tack this on to any previous partial
379 self.partial_input += input_data
381 # separate multiple input lines
382 new_input_lines = self.partial_input.split("\n")
384 # if input doesn't end in a newline, replace the
385 # held partial input with the last line of it
386 if not self.partial_input.endswith("\n"):
387 self.partial_input = new_input_lines.pop()
389 # otherwise, chop off the extra null input and reset
390 # the held partial input
392 new_input_lines.pop()
393 self.partial_input = ""
395 # iterate over the remaining lines
396 for line in new_input_lines:
398 # filter out non-printables
399 line = filter(lambda x: x>=' ' and x<='~', line)
401 # strip off extra whitespace
404 # put on the end of the queue
405 self.input_queue.append(line)
407 def new_avatar(self):
408 """Instantiate a new, unconfigured avatar for this user."""
410 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
411 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
412 avatars = self.account.getlist("avatars")
413 avatars.append(self.avatar.key)
414 self.account.set("avatars", avatars)
416 def delete_avatar(self, avatar):
417 """Remove an avatar from the world and from the user's list."""
418 if self.avatar is universe.contents[avatar]: self.avatar = None
419 universe.contents[avatar].delete()
420 avatars = self.account.getlist("avatars")
421 avatars.remove(avatar)
422 self.account.set("avatars", avatars)
425 """Delete the user and associated avatars."""
426 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
427 self.account.delete()
429 def list_avatar_names(self):
430 """List names of assigned avatars."""
431 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
434 """Turn string into list type."""
435 if value[0] + value[-1] == "[]": return eval(value)
436 else: return [ value ]
439 """Turn string into dict type."""
440 if value[0] + value[-1] == "{}": return eval(value)
441 elif value.find(":") > 0: return eval("{" + value + "}")
442 else: return { value: None }
444 def broadcast(message):
445 """Send a message to all connected users."""
446 for each_user in universe.userlist: each_user.send("$(eol)" + message)
451 # the time in posix log timestamp format
452 timestamp = asctime()[4:19]
454 # send the timestamp and message to standard output
455 print(timestamp + " " + message)
457 def wrap_ansi_text(text, width):
458 """Wrap text with arbitrary width while ignoring ANSI colors."""
460 # the current position in the entire text string, including all
461 # characters, printable or otherwise
462 absolute_position = 0
464 # the current text position relative to the begining of the line,
465 # ignoring color escape sequences
466 relative_position = 0
468 # whether the current character is part of a color escape sequence
471 # iterate over each character from the begining of the text
472 for each_character in text:
474 # the current character is the escape character
475 if each_character == chr(27):
478 # the current character is within an escape sequence
481 # the current character is m, which terminates the
482 # current escape sequence
483 if each_character == "m":
486 # the current character is a newline, so reset the relative
487 # position (start a new line)
488 elif each_character == "\n":
489 relative_position = 0
491 # the current character meets the requested maximum line width,
492 # so we need to backtrack and find a space at which to wrap
493 elif relative_position == width:
495 # distance of the current character examined from the
499 # count backwards until we find a space
500 while text[absolute_position - wrap_offset] != " ":
503 # insert an eol in place of the space
504 text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
506 # increase the absolute position because an eol is two
507 # characters but the space it replaced was only one
508 absolute_position += 1
510 # now we're at the begining of a new line, plus the
511 # number of characters wrapped from the previous line
512 relative_position = wrap_offset
514 # as long as the character is not a carriage return and the
515 # other above conditions haven't been met, count it as a
516 # printable character
517 elif each_character != "\r":
518 relative_position += 1
520 # increase the absolute position for every character
521 absolute_position += 1
523 # return the newly-wrapped text
526 def weighted_choice(data):
527 """Takes a dict weighted by value and returns a random key."""
529 # this will hold our expanded list of keys from the data
532 # create thee expanded list of keys
533 for key in data.keys():
534 for count in range(data[key]):
537 # return one at random
538 return choice(expanded)
541 """Returns a random character name."""
543 # the vowels and consonants needed to create romaji syllables
544 vowels = [ "a", "i", "u", "e", "o" ]
545 consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
547 # this dict will hold our weighted list of syllables
550 # generate the list with an even weighting
551 for consonant in consonants:
553 syllables[consonant + vowel] = 1
555 # we'll build the name into this string
558 # create a name of random length from the syllables
559 for syllable in range(randrange(2, 6)):
560 name += weighted_choice(syllables)
562 # strip any leading quotemark, capitalize and return the name
563 return name.strip("'").capitalize()
565 def replace_macros(user, text, is_input=False):
566 """Replaces macros in text output."""
571 # third person pronouns
573 "female": { "obj": "her", "pos": "hers", "sub": "she" },
574 "male": { "obj": "him", "pos": "his", "sub": "he" },
575 "neuter": { "obj": "it", "pos": "its", "sub": "it" }
578 # a dict of replacement macros
581 "$(bld)": chr(27) + "[1m",
582 "$(nrm)": chr(27) + "[0m",
583 "$(blk)": chr(27) + "[30m",
584 "$(grn)": chr(27) + "[32m",
585 "$(red)": chr(27) + "[31m",
588 # add dynamic macros where possible
590 account_name = user.account.get("name")
592 macros["$(account)"] = account_name
594 avatar_gender = user.avatar.get("gender")
596 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
597 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
598 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
600 # find and replace per the macros dict
601 macro_start = text.find("$(")
602 if macro_start == -1: break
603 macro_end = text.find(")", macro_start) + 1
604 macro = text[macro_start:macro_end]
605 if macro in macros.keys():
606 text = text.replace(macro, macros[macro])
608 # if we get here, log and replace it with null
610 text = text.replace(macro, "")
612 log("Unexpected replacement macro " + macro + " encountered.")
614 # replace the look-like-a-macro sequence
615 text = text.replace("$_(", "$(")
619 def check_time(frequency):
620 """Check for a factor of the current increment count."""
621 if type(frequency) is str:
622 frequency = universe.categories["internal"]["time"].getint(frequency)
623 if not "counters" in universe.categories["internal"]:
624 Element("internal:counters", universe)
625 return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
628 """The things which should happen on each pulse, aside from reloads."""
630 # open the listening socket if it hasn't been already
631 if not hasattr(universe, "listening_socket"):
632 universe.initialize_server_socket()
634 # assign a user if a new connection is waiting
635 user = check_for_connection(universe.listening_socket)
636 if user: universe.userlist.append(user)
638 # iterate over the connected users
639 for user in universe.userlist: user.pulse()
641 # update the log every now and then
642 if check_time("frequency_log"):
643 log(str(len(universe.userlist)) + " connection(s)")
645 # periodically save everything
646 if check_time("frequency_save"):
649 # pause for a configurable amount of time (decimal seconds)
650 sleep(universe.categories["internal"]["time"].getfloat("increment"))
652 # increment the elapsed increment counter
653 universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
656 """Reload data into new persistent objects."""
657 for user in universe.userlist[:]: user.reload()
659 def check_for_connection(listening_socket):
660 """Check for a waiting connection and return a new user object."""
662 # try to accept a new connection
664 connection, address = listening_socket.accept()
668 # note that we got one
669 log("Connection from " + address[0])
671 # disable blocking so we can proceed whether or not we can send/receive
672 connection.setblocking(0)
674 # create a new user object
677 # associate this connection with it
678 user.connection = connection
680 # set the user's ipa from the connection's ipa
681 user.address = address[0]
683 # return the new user object
686 def get_menu(state, error=None, echoing=True, choices={}):
687 """Show the correct menu text to a user."""
689 # begin with a telnet echo command sequence if needed
690 message = get_echo_sequence(state, echoing)
692 # get the description or error text
693 message += get_menu_description(state, error)
695 # get menu choices for the current state
696 message += get_formatted_menu_choices(state, choices)
698 # try to get a prompt, if it was defined
699 message += get_menu_prompt(state)
701 # throw in the default choice, if it exists
702 message += get_formatted_default_menu_choice(state)
704 # display a message indicating if echo is off
705 message += get_echo_message(state)
707 # return the assembly of various strings defined above
710 def menu_echo_on(state):
711 """True if echo is on, false if it is off."""
712 return universe.categories["menu"][state].getboolean("echo", True)
714 def get_echo_sequence(state, echoing):
715 """Build the appropriate IAC ECHO sequence as needed."""
717 # if the user has echo on and the menu specifies it should be turned
718 # off, send: iac + will + echo + null
719 if echoing and not menu_echo_on(state): return chr(255) + chr(251) + chr(1) + chr(0)
721 # if echo is not set to off in the menu and the user curently has echo
722 # off, send: iac + wont + echo + null
723 elif not echoing and menu_echo_on(state): return chr(255) + chr(252) + chr(1) + chr(0)
725 # default is not to send an echo control sequence at all
728 def get_echo_message(state):
729 """Return a message indicating that echo is off."""
730 if menu_echo_on(state): return ""
731 else: return "(won't echo) "
733 def get_default_menu_choice(state):
734 """Return the default choice for a menu."""
735 return universe.categories["menu"][state].get("default")
737 def get_formatted_default_menu_choice(state):
738 """Default menu choice foratted for inclusion in a prompt string."""
739 default_choice = get_default_menu_choice(state)
740 if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
743 def get_menu_description(state, error):
744 """Get the description or error text."""
746 # an error condition was raised by the handler
749 # try to get an error message matching the condition
751 description = universe.categories["menu"][state].get("error_" + error)
752 if not description: description = "That is not a valid choice..."
753 description = "$(red)" + description + "$(nrm)"
755 # there was no error condition
758 # try to get a menu description for the current state
759 description = universe.categories["menu"][state].get("description")
761 # return the description or error message
762 if description: description += "$(eol)$(eol)"
765 def get_menu_prompt(state):
766 """Try to get a prompt, if it was defined."""
767 prompt = universe.categories["menu"][state].get("prompt")
768 if prompt: prompt += " "
771 def get_menu_choices(user):
772 """Return a dict of choice:meaning."""
773 menu = universe.categories["menu"][user.state]
774 create_choices = menu.get("create")
775 if create_choices: choices = eval(create_choices)
780 for facet in menu.facets():
781 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
782 ignores.append(facet.split("_", 2)[1])
783 elif facet.startswith("create_"):
784 creates[facet] = facet.split("_", 2)[1]
785 elif facet.startswith("choice_"):
786 options[facet] = facet.split("_", 2)[1]
787 for facet in creates.keys():
788 if not creates[facet] in ignores:
789 choices[creates[facet]] = eval(menu.get(facet))
790 for facet in options.keys():
791 if not options[facet] in ignores:
792 choices[options[facet]] = menu.get(facet)
795 def get_formatted_menu_choices(state, choices):
796 """Returns a formatted string of menu choices."""
798 choice_keys = choices.keys()
800 for choice in choice_keys:
801 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[choice] + "$(eol)"
802 if choice_output: choice_output += "$(eol)"
805 def get_menu_branches(state):
806 """Return a dict of choice:branch."""
808 for facet in universe.categories["menu"][state].facets():
809 if facet.startswith("branch_"):
810 branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
813 def get_default_branch(state):
814 """Return the default branch."""
815 return universe.categories["menu"][state].get("branch")
817 def get_choice_branch(user, choice):
818 """Returns the new state matching the given choice."""
819 branches = get_menu_branches(user.state)
820 if choice in branches.keys(): return branches[choice]
821 elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
824 def get_menu_actions(state):
825 """Return a dict of choice:branch."""
827 for facet in universe.categories["menu"][state].facets():
828 if facet.startswith("action_"):
829 actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
832 def get_default_action(state):
833 """Return the default action."""
834 return universe.categories["menu"][state].get("action")
836 def get_choice_action(user, choice):
837 """Run any indicated script for the given choice."""
838 actions = get_menu_actions(user.state)
839 if choice in actions.keys(): return actions[choice]
840 elif choice in user.menu_choices.keys(): return get_default_action(user.state)
843 def handle_user_input(user):
844 """The main handler, branches to a state-specific handler."""
846 # check to make sure the state is expected, then call that handler
847 if "handler_" + user.state in globals():
848 exec("handler_" + user.state + "(user)")
850 generic_menu_handler(user)
852 # since we got input, flag that the menu/prompt needs to be redisplayed
853 user.menu_seen = False
855 # if the user's client echo is off, send a blank line for aesthetics
856 if not user.echoing: user.send("", "")
858 def generic_menu_handler(user):
859 """A generic menu choice handler."""
861 # get a lower-case representation of the next line of input
863 choice = user.input_queue.pop(0)
864 if choice: choice = choice.lower()
866 if not choice: choice = get_default_menu_choice(user.state)
867 if choice in user.menu_choices:
868 exec(get_choice_action(user, choice))
869 new_state = get_choice_branch(user, choice)
870 if new_state: user.state = new_state
871 else: user.error = "default"
873 def handler_entering_account_name(user):
874 """Handle the login account name."""
876 # get the next waiting line of input
877 input_data = user.input_queue.pop(0)
879 # did the user enter anything?
882 # keep only the first word and convert to lower-case
883 name = input_data.lower()
885 # fail if there are non-alphanumeric characters
886 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
887 user.error = "bad_name"
889 # if that account exists, time to request a password
890 elif name in universe.categories["account"]:
891 user.account = universe.categories["account"][name]
892 user.state = "checking_password"
894 # otherwise, this could be a brand new user
896 user.account = Element("account:" + name, universe)
897 user.account.set("name", name)
898 log("New user: " + name)
899 user.state = "checking_new_account_name"
901 # if the user entered nothing for a name, then buhbye
903 user.state = "disconnecting"
905 def handler_checking_password(user):
906 """Handle the login account password."""
908 # get the next waiting line of input
909 input_data = user.input_queue.pop(0)
911 # does the hashed input equal the stored hash?
912 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
914 # if so, set the username and load from cold storage
915 if not user.replace_old_connections():
917 user.state = "main_utility"
919 # if at first your hashes don't match, try, try again
920 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
921 user.password_tries += 1
922 user.error = "incorrect"
924 # we've exceeded the maximum number of password failures, so disconnect
926 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
927 user.state = "disconnecting"
929 def handler_entering_new_password(user):
930 """Handle a new password entry."""
932 # get the next waiting line of input
933 input_data = user.input_queue.pop(0)
935 # make sure the password is strong--at least one upper, one lower and
936 # one digit, seven or more characters in length
937 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)):
939 # hash and store it, then move on to verification
940 user.account.set("passhash", new_md5(user.account.get("name") + input_data).hexdigest())
941 user.state = "verifying_new_password"
943 # the password was weak, try again if you haven't tried too many times
944 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
945 user.password_tries += 1
948 # too many tries, so adios
950 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
951 user.account.delete()
952 user.state = "disconnecting"
954 def handler_verifying_new_password(user):
955 """Handle the re-entered new password for verification."""
957 # get the next waiting line of input
958 input_data = user.input_queue.pop(0)
960 # hash the input and match it to storage
961 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
964 # the hashes matched, so go active
965 if not user.replace_old_connections(): user.state = "main_utility"
967 # go back to entering the new password as long as you haven't tried
969 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
970 user.password_tries += 1
971 user.error = "differs"
972 user.state = "entering_new_password"
974 # otherwise, sayonara
976 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
977 user.account.delete()
978 user.state = "disconnecting"
980 def handler_active(user):
981 """Handle input for active users."""
983 # get the next waiting line of input
984 input_data = user.input_queue.pop(0)
986 # split out the command (first word) and parameters (everything else)
987 if input_data.find(" ") > 0:
988 command, parameters = input_data.split(" ", 1)
993 # lowercase the command
994 command = command.lower()
996 # the command matches a command word for which we have data
997 if command in universe.categories["command"]:
998 exec(universe.categories["command"][command].get("action"))
1000 # no data matching the entered command word
1001 elif command: command_error(user, command, parameters)
1003 def command_halt(user, command="", parameters=""):
1004 """Halt the world."""
1006 # see if there's a message or use a generic one
1007 if parameters: message = "Halting: " + parameters
1008 else: message = "User " + user.account.get("name") + " halted the world."
1014 # set a flag to terminate the world
1015 universe.terminate_world = True
1017 def command_reload(user, command="", parameters=""):
1018 """Reload all code modules, configs and data."""
1020 # let the user know and log
1021 user.send("Reloading all code modules, configs and data.")
1022 log("User " + user.account.get("name") + " reloaded the world.")
1024 # set a flag to reload
1025 universe.reload_modules = True
1027 def command_quit(user, command="", parameters=""):
1028 """Quit the world."""
1029 user.state = "main_utility"
1031 def command_help(user, command="", parameters=""):
1032 """List available commands and provide help for commands."""
1034 # did the user ask for help on a specific command word?
1037 # is the command word one for which we have data?
1038 if parameters in universe.categories["command"]:
1040 # add a description if provided
1041 description = universe.categories["command"][parameters].get("description")
1043 description = "(no short description provided)"
1044 output = "$(grn)" + parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1046 # add the help text if provided
1047 help_text = universe.categories["command"][parameters].get("help")
1049 help_text = "No help is provided for this command."
1052 # no data for the requested command word
1054 output = "That is not an available command."
1056 # no specific command word was indicated
1059 # give a sorted list of commands with descriptions if provided
1060 output = "These are the commands available to you:$(eol)$(eol)"
1061 sorted_commands = universe.categories["command"].keys()
1062 sorted_commands.sort()
1063 for item in sorted_commands:
1064 description = universe.categories["command"][item].get("description")
1066 description = "(no short description provided)"
1067 output += " $(grn)" + item + "$(nrm) - " + description + "$(eol)"
1068 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1070 # send the accumulated output to the user
1073 def command_say(user, command="", parameters=""):
1074 """Speak to others in the same room."""
1076 # check for replacement macros
1077 if replace_macros(user, parameters, True) != parameters:
1078 user.send("You cannot speak $_(replacement macros).")
1080 # the user entered a message
1083 # get rid of quote marks on the ends of the message and
1084 # capitalize the first letter
1085 message = parameters.strip("\"'`").capitalize()
1087 # a dictionary of punctuation:action pairs
1089 for facet in universe.categories["internal"]["language"].facets():
1090 if facet.startswith("punctuation_"):
1091 action = facet.split("_")[1]
1092 for mark in universe.categories["internal"]["language"].getlist(facet):
1093 actions[mark] = action
1095 # match the punctuation used, if any, to an action
1096 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1097 action = actions[default_punctuation]
1098 for mark in actions.keys():
1099 if message.endswith(mark) and mark != default_punctuation:
1100 action = actions[mark]
1103 # if the action is default and there is no mark, add one
1104 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1105 message += default_punctuation
1107 # capitalize a list of words within the message
1108 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1109 for word in capitalize_words:
1110 message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1113 # TODO: we won't be using broadcast once there are actual rooms
1114 broadcast(user.account.get("name") + " " + action + "s, \"" + message + "\"")
1116 # there was no message
1118 user.send("What do you want to say?")
1120 def command_show(user, command="", parameters=""):
1121 """Show program data."""
1122 if parameters == "avatars":
1123 message = "These are the avatars managed by your account:$(eol)"
1124 avatars = user.list_avatar_names()
1126 for avatar in avatars: message += "$(eol) $(grn)" + avatar + "$(nrm)"
1127 elif parameters == "files":
1128 message = "These are the current files containing the universe:$(eol)"
1129 keys = universe.files.keys()
1131 for key in keys: message += "$(eol) $(grn)" + key + "$(nrm)"
1132 elif parameters == "universe":
1133 message = "These are the current elements in the universe:$(eol)"
1134 keys = universe.contents.keys()
1136 for key in keys: message += "$(eol) $(grn)" + key + "$(nrm)"
1137 elif parameters == "time":
1138 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1139 elif parameters: message = "I don't know what \"" + parameters + "\" is."
1140 else: message = "What do you want to show?"
1143 def command_error(user, command="", parameters=""):
1144 """Generic error for an unrecognized command word."""
1146 # 90% of the time use a generic error
1148 message = "I'm not sure what \"" + command
1150 message += " " + parameters
1151 message += "\" means..."
1153 # 10% of the time use the classic diku error
1155 message = "Arglebargle, glop-glyf!?!"
1157 # send the error message
1160 # if there is no universe, create an empty one
1161 if not "universe" in locals(): universe = Universe()