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=""):
47 """Retrieve values."""
48 if universe.files[self.origin].data.has_option(self.key, facet):
49 return universe.files[self.origin].data.get(self.key, facet)
51 def getboolean(self, facet, default=False):
52 """Retrieve values as boolean type."""
53 if universe.files[self.origin].data.has_option(self.key, facet):
54 return universe.files[self.origin].data.getboolean(self.key, facet)
56 def getint(self, facet, default=0):
57 """Return values as int/long type."""
58 if universe.files[self.origin].data.has_option(self.key, facet):
59 return universe.files[self.origin].data.getint(self.key, facet)
61 def getfloat(self, facet, default=0.0):
62 """Return values as float type."""
63 if universe.files[self.origin].data.has_option(self.key, facet):
64 return universe.files[self.origin].data.getfloat(self.key, facet)
66 def getlist(self, facet, default=[]):
67 """Return values as list type."""
68 value = self.get(facet)
69 if not value: return default
70 else: return makelist(value)
71 def getdict(self, facet, default={}):
72 """Return values as dict type."""
73 value = self.get(facet)
74 if not value: return default
75 else: return makedict(value)
76 def set(self, facet, value):
78 if type(value) is long: value = repr(value).rstrip("L")
79 elif not type(value) is str: value = repr(value)
80 universe.files[self.origin].data.set(self.key, facet, value)
83 """A file containing universe elements."""
84 def __init__(self, filename, universe):
85 self.data = RawConfigParser()
86 if access(filename, R_OK): self.data.read(filename)
87 self.filename = filename
88 universe.files[filename] = self
89 if self.data.has_option("control", "include_files"):
90 includes = makelist(self.data.get("control", "include_files"))
92 if self.data.has_option("control", "default_files"):
93 origins = makedict(self.data.get("control", "default_files"))
94 for key in origins.keys():
95 if not key in includes: includes.append(key)
96 universe.default_origins[key] = origins[key]
97 if not key in universe.categories:
98 universe.categories[key] = {}
99 if self.data.has_option("control", "private_files"):
100 for item in makelist(self.data.get("control", "private_files")):
101 if not item in includes: includes.append(item)
102 if not item in universe.private_files:
104 item = path_join(dirname(filename), item)
105 universe.private_files.append(item)
106 for section in self.data.sections():
107 if section != "control":
108 Element(section, universe, filename)
109 for include_file in includes:
110 if not isabs(include_file):
111 include_file = path_join(dirname(filename), include_file)
112 DataFile(include_file, universe)
114 if self.data.sections() and ( not self.data.has_option("control", "read_only") or not self.data.getboolean("control", "read_only") ):
115 if not exists(dirname(self.filename)): makedirs(dirname)
116 file_descriptor = file(self.filename, "w")
117 if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
118 chmod(self.filename, 0600)
119 self.data.write(file_descriptor)
120 file_descriptor.flush()
121 file_descriptor.close()
125 def __init__(self, filename=""):
126 """Initialize the universe."""
129 self.default_origins = {}
131 self.private_files = []
133 self.terminate_world = False
134 self.reload_modules = False
136 possible_filenames = [
142 "/usr/local/mudpy/mudpy.conf",
143 "/usr/local/mudpy/etc/mudpy.conf",
144 "/etc/mudpy/mudpy.conf",
147 for filename in possible_filenames:
148 if access(filename, R_OK): break
149 if not isabs(filename):
150 filename = abspath(filename)
151 DataFile(filename, self)
153 """Save the universe to persistent storage."""
154 for key in self.files: self.files[key].save()
156 def initialize_server_socket(self):
157 """Create and open the listening socket."""
159 # create a new ipv4 stream-type socket object
160 self.listening_socket = socket(AF_INET, SOCK_STREAM)
162 # set the socket options to allow existing open ones to be
163 # reused (fixes a bug where the server can't bind for a minute
164 # when restarting on linux systems)
165 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
167 # bind the socket to to our desired server ipa and port
168 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
170 # disable blocking so we can proceed whether or not we can
172 self.listening_socket.setblocking(0)
174 # start listening on the socket
175 self.listening_socket.listen(1)
177 # note that we're now ready for user connections
178 log("Waiting for connection(s)...")
181 """This is a connected user."""
184 """Default values for the in-memory user variables."""
186 self.last_address = ""
187 self.connection = None
188 self.authenticated = False
189 self.password_tries = 0
190 self.state = "entering_account_name"
191 self.menu_seen = False
193 self.input_queue = []
194 self.output_queue = []
195 self.partial_input = ""
201 """Log, close the connection and remove."""
202 if self.account: name = self.account.get("name")
204 if name: message = "User " + name
205 else: message = "An unnamed user"
206 message += " logged out."
208 self.connection.close()
212 """Save, load a new user and relocate the connection."""
214 # get out of the list
217 # create a new user object
220 # set everything else equivalent
237 exec("new_user." + attribute + " = self." + attribute)
240 universe.userlist.append(new_user)
242 # get rid of the old user object
245 def replace_old_connections(self):
246 """Disconnect active users with the same name."""
248 # the default return value
251 # iterate over each user in the list
252 for old_user in universe.userlist:
254 # the name is the same but it's not us
255 if old_user.account.get("name") == self.account.get("name") and old_user is not self:
258 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".")
259 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)")
260 self.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
262 # close the old connection
263 old_user.connection.close()
265 # replace the old connection with this one
266 old_user.connection = self.connection
267 old_user.last_address = old_user.address
268 old_user.address = self.address
269 old_user.echoing = self.echoing
271 # take this one out of the list and delete
277 # true if an old connection was replaced, false if not
280 def authenticate(self):
281 """Flag the user as authenticated and disconnect duplicates."""
282 if not self.state is "authenticated":
283 log("User " + self.account.get("name") + " logged in.")
284 self.authenticated = True
287 """Send the user their current menu."""
288 if not self.menu_seen:
289 self.menu_choices = get_menu_choices(self)
290 self.send(get_menu(self.state, self.error, self.echoing, self.menu_choices), "")
291 self.menu_seen = True
293 self.adjust_echoing()
295 def adjust_echoing(self):
296 """Adjust echoing to match state menu requirements."""
297 if self.echoing and not menu_echo_on(self.state): self.echoing = False
298 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
301 """Remove a user from the list of connected users."""
302 universe.userlist.remove(self)
304 def send(self, output, eol="$(eol)"):
305 """Send arbitrary text to a connected user."""
307 # only when there is actual output
310 # start with a newline, append the message, then end
311 # with the optional eol string passed to this function
312 # and the ansi escape to return to normal text
313 output = "\r\n" + output + eol + chr(27) + "[0m"
315 # find and replace macros in the output
316 output = replace_macros(self, output)
318 # wrap the text at 80 characters
319 # TODO: prompt user for preferred wrap width
320 output = wrap_ansi_text(output, 80)
322 # drop the formatted output into the output queue
323 self.output_queue.append(output)
325 # try to send the last item in the queue, remove it and
326 # flag that menu display is not needed
328 self.connection.send(self.output_queue[0])
329 self.output_queue.remove(self.output_queue[0])
330 self.menu_seen = False
332 # but if we can't, that's okay too
337 """All the things to do to the user per increment."""
339 # if the world is terminating, disconnect
340 if universe.terminate_world:
341 self.state = "disconnecting"
342 self.menu_seen = False
344 # show the user a menu as needed
347 # disconnect users with the appropriate state
348 if self.state == "disconnecting":
351 # the user is unique and not flagged to disconnect
354 # check for input and add it to the queue
357 # there is input waiting in the queue
358 if self.input_queue: handle_user_input(self)
360 def enqueue_input(self):
361 """Process and enqueue any new input."""
363 # check for some input
365 input_data = self.connection.recv(1024)
372 # tack this on to any previous partial
373 self.partial_input += input_data
375 # separate multiple input lines
376 new_input_lines = self.partial_input.split("\n")
378 # if input doesn't end in a newline, replace the
379 # held partial input with the last line of it
380 if not self.partial_input.endswith("\n"):
381 self.partial_input = new_input_lines.pop()
383 # otherwise, chop off the extra null input and reset
384 # the held partial input
386 new_input_lines.pop()
387 self.partial_input = ""
389 # iterate over the remaining lines
390 for line in new_input_lines:
392 # filter out non-printables
393 line = filter(lambda x: x>=' ' and x<='~', line)
395 # strip off extra whitespace
398 # put on the end of the queue
399 self.input_queue.append(line)
401 def new_avatar(self):
402 """Instantiate a new, unconfigured avatar for this user."""
403 counter = universe.categories["internal"]["counters"].getint("next_avatar")
404 while "avatar:" + repr(counter + 1) in universe.categories["actor"].keys(): counter += 1
405 universe.categories["internal"]["counters"].set("next_avatar", counter + 1)
406 self.avatar = Element("actor:avatar:" + repr(counter), universe)
407 avatars = self.account.getlist("avatars")
408 avatars.append(self.avatar.key)
409 self.account.set("avatars", avatars)
411 def list_avatar_names(self):
412 """A test function to list names of assigned avatars."""
413 avatars = self.account.getlist("avatars")
415 for avatar in avatars:
416 avatar_names.append(universe.contents[avatar].get("name"))
420 """Turn string into list type."""
421 if value[0] + value[-1] == "[]": return eval(value)
422 else: return [ value ]
425 """Turn string into dict type."""
426 if value[0] + value[-1] == "{}": return eval(value)
427 elif value.find(":") > 0: return eval("{" + value + "}")
428 else: return { value: None }
430 def broadcast(message):
431 """Send a message to all connected users."""
432 for each_user in universe.userlist: each_user.send("$(eol)" + message)
437 # the time in posix log timestamp format
438 timestamp = asctime()[4:19]
440 # send the timestamp and message to standard output
441 print(timestamp + " " + message)
443 def wrap_ansi_text(text, width):
444 """Wrap text with arbitrary width while ignoring ANSI colors."""
446 # the current position in the entire text string, including all
447 # characters, printable or otherwise
448 absolute_position = 0
450 # the current text position relative to the begining of the line,
451 # ignoring color escape sequences
452 relative_position = 0
454 # whether the current character is part of a color escape sequence
457 # iterate over each character from the begining of the text
458 for each_character in text:
460 # the current character is the escape character
461 if each_character == chr(27):
464 # the current character is within an escape sequence
467 # the current character is m, which terminates the
468 # current escape sequence
469 if each_character == "m":
472 # the current character is a newline, so reset the relative
473 # position (start a new line)
474 elif each_character == "\n":
475 relative_position = 0
477 # the current character meets the requested maximum line width,
478 # so we need to backtrack and find a space at which to wrap
479 elif relative_position == width:
481 # distance of the current character examined from the
485 # count backwards until we find a space
486 while text[absolute_position - wrap_offset] != " ":
489 # insert an eol in place of the space
490 text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
492 # increase the absolute position because an eol is two
493 # characters but the space it replaced was only one
494 absolute_position += 1
496 # now we're at the begining of a new line, plus the
497 # number of characters wrapped from the previous line
498 relative_position = wrap_offset
500 # as long as the character is not a carriage return and the
501 # other above conditions haven't been met, count it as a
502 # printable character
503 elif each_character != "\r":
504 relative_position += 1
506 # increase the absolute position for every character
507 absolute_position += 1
509 # return the newly-wrapped text
512 def weighted_choice(data):
513 """Takes a dict weighted by value and returns a random key."""
515 # this will hold our expanded list of keys from the data
518 # create thee expanded list of keys
519 for key in data.keys():
520 for count in range(data[key]):
523 # return one at random
524 return choice(expanded)
527 """Returns a random character name."""
529 # the vowels and consonants needed to create romaji syllables
530 vowels = [ "a", "i", "u", "e", "o" ]
531 consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
533 # this dict will hold our weighted list of syllables
536 # generate the list with an even weighting
537 for consonant in consonants:
539 syllables[consonant + vowel] = 1
541 # we'll build the name into this string
544 # create a name of random length from the syllables
545 for syllable in range(randrange(2, 6)):
546 name += weighted_choice(syllables)
548 # strip any leading quotemark, capitalize and return the name
549 return name.strip("'").capitalize()
551 def replace_macros(user, text, is_input=False):
552 """Replaces macros in text output."""
557 # third person pronouns
559 "female": { "obj": "her", "pos": "hers", "sub": "she" },
560 "male": { "obj": "him", "pos": "his", "sub": "he" },
561 "neuter": { "obj": "it", "pos": "its", "sub": "it" }
564 # a dict of replacement macros
567 "$(bld)": chr(27) + "[1m",
568 "$(nrm)": chr(27) + "[0m",
569 "$(blk)": chr(27) + "[30m",
570 "$(grn)": chr(27) + "[32m",
571 "$(red)": chr(27) + "[31m",
574 # add dynamic macros where possible
576 account_name = user.account.get("name")
578 macros["$(account)"] = account_name
580 avatar_gender = user.avatar.get("gender")
582 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
583 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
584 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
586 # find and replace per the macros dict
587 macro_start = text.find("$(")
588 if macro_start == -1: break
589 macro_end = text.find(")", macro_start) + 1
590 macro = text[macro_start:macro_end]
591 if macro in macros.keys():
592 text = text.replace(macro, macros[macro])
594 # if we get here, log and replace it with null
596 text = text.replace(macro, "")
598 log("Unexpected replacement macro " + macro + " encountered.")
600 # replace the look-like-a-macro sequence
601 text = text.replace("$_(", "$(")
605 def check_time(frequency):
606 """Check for a factor of the current increment count."""
607 if type(frequency) is str:
608 frequency = universe.categories["internal"]["time"].getint(frequency)
609 if not "counters" in universe.categories["internal"]:
610 Element("internal:counters", universe)
611 return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
614 """The things which should happen on each pulse, aside from reloads."""
616 # open the listening socket if it hasn't been already
617 if not hasattr(universe, "listening_socket"):
618 universe.initialize_server_socket()
620 # assign a user if a new connection is waiting
621 user = check_for_connection(universe.listening_socket)
622 if user: universe.userlist.append(user)
624 # iterate over the connected users
625 for user in universe.userlist: user.pulse()
627 # update the log every now and then
628 if check_time("frequency_log"):
629 log(repr(len(universe.userlist)) + " connection(s)")
631 # periodically save everything
632 if check_time("frequency_save"):
635 # pause for a configurable amount of time (decimal seconds)
636 sleep(universe.categories["internal"]["time"].getfloat("increment"))
638 # increment the elapsed increment counter
639 universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
642 """Reload data into new persistent objects."""
643 for user in universe.userlist[:]: user.reload()
645 def check_for_connection(listening_socket):
646 """Check for a waiting connection and return a new user object."""
648 # try to accept a new connection
650 connection, address = listening_socket.accept()
654 # note that we got one
655 log("Connection from " + address[0])
657 # disable blocking so we can proceed whether or not we can send/receive
658 connection.setblocking(0)
660 # create a new user object
663 # associate this connection with it
664 user.connection = connection
666 # set the user's ipa from the connection's ipa
667 user.address = address[0]
669 # return the new user object
672 def get_menu(state, error=None, echoing=True, choices={}):
673 """Show the correct menu text to a user."""
675 # begin with a telnet echo command sequence if needed
676 message = get_echo_sequence(state, echoing)
678 # get the description or error text
679 message += get_menu_description(state, error)
681 # get menu choices for the current state
682 message += get_formatted_menu_choices(state, choices)
684 # try to get a prompt, if it was defined
685 message += get_menu_prompt(state)
687 # throw in the default choice, if it exists
688 message += get_formatted_default_menu_choice(state)
690 # display a message indicating if echo is off
691 message += get_echo_message(state)
693 # return the assembly of various strings defined above
696 def menu_echo_on(state):
697 """True if echo is on, false if it is off."""
698 return universe.categories["menu"][state].getboolean("echo", True)
700 def get_echo_sequence(state, echoing):
701 """Build the appropriate IAC ECHO sequence as needed."""
703 # if the user has echo on and the menu specifies it should be turned
704 # off, send: iac + will + echo + null
705 if echoing and not menu_echo_on(state): return chr(255) + chr(251) + chr(1) + chr(0)
707 # if echo is not set to off in the menu and the user curently has echo
708 # off, send: iac + wont + echo + null
709 elif not echoing and menu_echo_on(state): return chr(255) + chr(252) + chr(1) + chr(0)
711 # default is not to send an echo control sequence at all
714 def get_echo_message(state):
715 """Return a message indicating that echo is off."""
716 if menu_echo_on(state): return ""
717 else: return "(won't echo) "
719 def get_default_menu_choice(state):
720 """Return the default choice for a menu."""
721 return universe.categories["menu"][state].get("default")
723 def get_formatted_default_menu_choice(state):
724 """Default menu choice foratted for inclusion in a prompt string."""
725 default = get_default_menu_choice(state)
726 if default: return "[$(red)" + default + "$(nrm)] "
729 def get_menu_description(state, error):
730 """Get the description or error text."""
732 # an error condition was raised by the handler
735 # try to get an error message matching the condition
737 description = universe.categories["menu"][state].get("error_" + error)
738 if not description: description = "That is not a valid choice..."
739 description = "$(red)" + description + "$(nrm)"
741 # there was no error condition
744 # try to get a menu description for the current state
745 description = universe.categories["menu"][state].get("description")
747 # return the description or error message
748 if description: description += "$(eol)$(eol)"
751 def get_menu_prompt(state):
752 """Try to get a prompt, if it was defined."""
753 prompt = universe.categories["menu"][state].get("prompt")
754 if prompt: prompt += " "
757 def get_menu_choices(user):
758 """Return a dict of choice:meaning."""
763 for facet in universe.categories["menu"][user.state].facets():
764 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
765 ignores.append(facet.split("_", 2)[1])
766 elif facet.startswith("choice_"):
767 options[facet] = facet.split("_", 2)[1]
768 elif facet.startswith("create_"):
769 creates[facet] = facet.split("_", 2)[1]
770 for facet in options.keys():
771 if not options[facet] in ignores:
772 choices[options[facet]] = universe.categories["menu"][user.state].get(facet)
773 for facet in creates.keys():
774 if not creates[facet] in ignores:
775 choices[creates[facet]] = eval(universe.categories["menu"][user.state].get(facet))
778 def get_formatted_menu_choices(state, choices):
779 """Returns a formatted string of menu choices."""
781 choice_keys = choices.keys()
783 for choice in choice_keys:
784 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[choice] + "$(eol)"
785 if choice_output: choice_output += "$(eol)"
788 def get_menu_branches(state):
789 """Return a dict of choice:branch."""
791 for facet in universe.categories["menu"][state].facets():
792 if facet.startswith("branch_"):
793 branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
796 def get_default_branch(state):
797 """Return the default branch."""
798 return universe.categories["menu"][state].get("branch")
800 def get_choice_branch(user, choice):
801 """Returns the new state matching the given choice."""
802 branches = get_menu_branches(user.state)
803 if not choice: choice = get_default_menu_choice(user.state)
804 if choice in branches.keys(): return branches[choice]
805 elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
808 def get_menu_actions(state):
809 """Return a dict of choice:branch."""
811 for facet in universe.categories["menu"][state].facets():
812 if facet.startswith("action_"):
813 actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
816 def get_default_action(state):
817 """Return the default action."""
818 return universe.categories["menu"][state].get("action")
820 def get_choice_action(user, choice):
821 """Run any indicated script for the given choice."""
822 actions = get_menu_actions(user.state)
823 if not choice: choice = get_default_menu_choice(user.state)
824 if choice in actions.keys(): return actions[choice]
825 elif choice in user.menu_choices.keys(): return get_default_action(user.state)
828 def handle_user_input(user):
829 """The main handler, branches to a state-specific handler."""
831 # check to make sure the state is expected, then call that handler
832 if "handler_" + user.state in globals():
833 exec("handler_" + user.state + "(user)")
835 generic_menu_handler(user)
837 # since we got input, flag that the menu/prompt needs to be redisplayed
838 user.menu_seen = False
840 # if the user's client echo is off, send a blank line for aesthetics
841 if not user.echoing: user.send("", "")
843 def generic_menu_handler(user):
844 """A generic menu choice handler."""
846 # get a lower-case representation of the next line of input
848 choice = user.input_queue.pop(0)
849 if choice: choice = choice.lower()
852 if choice in user.menu_choices:
853 exec(get_choice_action(user, choice))
854 new_state = get_choice_branch(user, choice)
855 if new_state: user.state = new_state
856 else: user.error = "default"
858 def handler_entering_account_name(user):
859 """Handle the login account name."""
861 # get the next waiting line of input
862 input_data = user.input_queue.pop(0)
864 # did the user enter anything?
867 # keep only the first word and convert to lower-case
868 name = input_data.lower()
870 # fail if there are non-alphanumeric characters
871 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
872 user.error = "bad_name"
874 # if that account exists, time to request a password
875 elif name in universe.categories["account"]:
876 user.account = universe.categories["account"][name]
877 user.state = "checking_password"
879 # otherwise, this could be a brand new user
881 user.account = Element("account:" + name, universe)
882 user.account.set("name", name)
883 log("New user: " + name)
884 user.state = "checking_new_account_name"
886 # if the user entered nothing for a name, then buhbye
888 user.state = "disconnecting"
890 def handler_checking_password(user):
891 """Handle the login account password."""
893 # get the next waiting line of input
894 input_data = user.input_queue.pop(0)
896 # does the hashed input equal the stored hash?
897 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
899 # if so, set the username and load from cold storage
900 if not user.replace_old_connections():
902 user.state = "main_utility"
904 # if at first your hashes don't match, try, try again
905 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
906 user.password_tries += 1
907 user.error = "incorrect"
909 # we've exceeded the maximum number of password failures, so disconnect
911 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
912 user.state = "disconnecting"
914 def handler_entering_new_password(user):
915 """Handle a new password entry."""
917 # get the next waiting line of input
918 input_data = user.input_queue.pop(0)
920 # make sure the password is strong--at least one upper, one lower and
921 # one digit, seven or more characters in length
922 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)):
924 # hash and store it, then move on to verification
925 user.account.set("passhash", new_md5(user.account.get("name") + input_data).hexdigest())
926 user.state = "verifying_new_password"
928 # the password was weak, try again if you haven't tried too many times
929 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
930 user.password_tries += 1
933 # too many tries, so adios
935 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
936 user.account.delete()
937 user.state = "disconnecting"
939 def handler_verifying_new_password(user):
940 """Handle the re-entered new password for verification."""
942 # get the next waiting line of input
943 input_data = user.input_queue.pop(0)
945 # hash the input and match it to storage
946 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
949 # the hashes matched, so go active
950 if not user.replace_old_connections(): user.state = "main_utility"
952 # go back to entering the new password as long as you haven't tried
954 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
955 user.password_tries += 1
956 user.error = "differs"
957 user.state = "entering_new_password"
959 # otherwise, sayonara
961 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
962 user.account.delete()
963 user.state = "disconnecting"
965 def handler_active(user):
966 """Handle input for active users."""
968 # get the next waiting line of input
969 input_data = user.input_queue.pop(0)
971 # split out the command (first word) and parameters (everything else)
972 if input_data.find(" ") > 0:
973 command, parameters = input_data.split(" ", 1)
978 # lowercase the command
979 command = command.lower()
981 # the command matches a command word for which we have data
982 if command in universe.categories["command"]:
983 exec(universe.categories["command"][command].get("action"))
985 # no data matching the entered command word
986 elif command: command_error(user, command, parameters)
988 def command_halt(user, command="", parameters=""):
989 """Halt the world."""
991 # see if there's a message or use a generic one
992 if parameters: message = "Halting: " + parameters
993 else: message = "User " + user.account.get("name") + " halted the world."
999 # set a flag to terminate the world
1000 universe.terminate_world = True
1002 def command_reload(user, command="", parameters=""):
1003 """Reload all code modules, configs and data."""
1005 # let the user know and log
1006 user.send("Reloading all code modules, configs and data.")
1007 log("User " + user.account.get("name") + " reloaded the world.")
1009 # set a flag to reload
1010 universe.reload_modules = True
1012 def command_quit(user, command="", parameters=""):
1013 """Quit the world."""
1014 user.state = "disconnecting"
1016 def command_help(user, command="", parameters=""):
1017 """List available commands and provide help for commands."""
1019 # did the user ask for help on a specific command word?
1022 # is the command word one for which we have data?
1023 if parameters in universe.categories["command"]:
1025 # add a description if provided
1026 description = universe.categories["command"][parameters].get("description")
1028 description = "(no short description provided)"
1029 output = "$(grn)" + parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1031 # add the help text if provided
1032 help_text = universe.categories["command"][parameters].get("help")
1034 help_text = "No help is provided for this command."
1037 # no data for the requested command word
1039 output = "That is not an available command."
1041 # no specific command word was indicated
1044 # give a sorted list of commands with descriptions if provided
1045 output = "These are the commands available to you:$(eol)$(eol)"
1046 sorted_commands = universe.categories["command"].keys()
1047 sorted_commands.sort()
1048 for item in sorted_commands:
1049 description = universe.categories["command"][item].get("description")
1051 description = "(no short description provided)"
1052 output += " $(grn)" + item + "$(nrm) - " + description + "$(eol)"
1053 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1055 # send the accumulated output to the user
1058 def command_say(user, command="", parameters=""):
1059 """Speak to others in the same room."""
1061 # check for replacement macros
1062 if replace_macros(user, parameters, True) != parameters:
1063 user.send("You cannot speak $_(replacement macros).")
1065 # the user entered a message
1068 # get rid of quote marks on the ends of the message and
1069 # capitalize the first letter
1070 message = parameters.strip("\"'`").capitalize()
1072 # a dictionary of punctuation:action pairs
1074 for facet in universe.categories["internal"]["language"].facets():
1075 if facet.startswith("punctuation_"):
1076 action = facet.split("_")[1]
1077 for mark in universe.categories["internal"]["language"].getlist(facet):
1078 actions[mark] = action
1080 # match the punctuation used, if any, to an action
1081 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1082 action = actions[default_punctuation]
1083 for mark in actions.keys():
1084 if message.endswith(mark) and mark != default_punctuation:
1085 action = actions[mark]
1088 # if the action is default and there is no mark, add one
1089 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1090 message += default_punctuation
1092 # capitalize a list of words within the message
1093 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1094 for word in capitalize_words:
1095 message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1098 # TODO: we won't be using broadcast once there are actual rooms
1099 broadcast(user.account.get("name") + " " + action + "s, \"" + message + "\"")
1101 # there was no message
1103 user.send("What do you want to say?")
1105 def command_show(user, command="", parameters=""):
1106 """Show program data."""
1107 if parameters == "avatars":
1108 message = "These are the avatars managed by your account:$(eol)"
1109 avatars = user.list_avatar_names()
1111 for avatar in avatars: message += "$(eol) $(grn)" + avatar + "$(nrm)"
1112 elif parameters == "files":
1113 message = "These are the current files containing the universe:$(eol)"
1114 keys = universe.files.keys()
1116 for key in keys: message += "$(eol) $(grn)" + key + "$(nrm)"
1117 elif parameters == "universe":
1118 message = "These are the current elements in the universe:$(eol)"
1119 keys = universe.contents.keys()
1121 for key in keys: message += "$(eol) $(grn)" + key + "$(nrm)"
1122 elif parameters == "time":
1123 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1124 elif parameters: message = "I don't know what \"" + parameters + "\" is."
1125 else: message = "What do you want to show?"
1128 def command_error(user, command="", parameters=""):
1129 """Generic error for an unrecognized command word."""
1131 # 90% of the time use a generic error
1133 message = "I'm not sure what \"" + command
1135 message += " " + parameters
1136 message += "\" means..."
1138 # 10% of the time use the classic diku error
1140 message = "Arglebargle, glop-glyf!?!"
1142 # send the error message
1145 # if there is no universe, create an empty one
1146 if not "universe" in locals(): universe = Universe()