1 # -*- coding: utf-8 -*-
2 """Miscellaneous functions for the mudpy engine."""
4 # Copyright (c) 2004-2013 Jeremy Stanley <fungi@yuggoth.org>. Permission
5 # to use, copy, modify, and distribute this software is granted under
6 # terms provided in the LICENSE file distributed with this software.
27 """An element of the universe."""
29 def __init__(self, key, universe, filename=None):
30 """Set up a new element."""
32 # keep track of our key name
35 # keep track of what universe it's loading into
36 self.universe = universe
38 # clone attributes if this is replacing another element
39 if self.key in self.universe.contents:
40 old_element = self.universe.contents[self.key]
41 for attribute in vars(old_element).keys():
42 exec("self." + attribute + " = old_element." + attribute)
44 self.owner.avatar = self
46 # i guess this is a new element then
49 # not owned by a user by default (used for avatars)
52 # no contents in here by default
55 # parse out appropriate category and subkey names, add to list
56 if self.key.find(":") > 0:
57 self.category, self.subkey = self.key.split(":", 1)
59 self.category = "other"
60 self.subkey = self.key
61 if self.category not in self.universe.categories:
62 self.category = "other"
63 self.subkey = self.key
65 # get an appropriate filename for the origin
67 filename = self.universe.default_origins[self.category]
68 if not os.path.isabs(filename):
69 filename = os.path.abspath(filename)
71 # add the file if it doesn't exist yet
72 if filename not in self.universe.files:
73 mudpy.data.DataFile(filename, self.universe)
75 # record or reset a pointer to the origin file
76 self.origin = self.universe.files[filename]
78 # add a data section to the origin if necessary
79 if not self.origin.data.has_section(self.key):
80 self.origin.data.add_section(self.key)
82 # add or replace this element in the universe
83 self.universe.contents[self.key] = self
84 self.universe.categories[self.category][self.subkey] = self
87 """Create a new element and replace this one."""
88 new_element = Element(self.key, self.universe, self.origin.filename)
92 """Remove an element from the universe and destroy it."""
93 self.origin.data.remove_section(self.key)
94 del self.universe.categories[self.category][self.subkey]
95 del self.universe.contents[self.key]
99 """Return a list of non-inherited facets for this element."""
100 if self.key in self.origin.data.sections():
101 return self.origin.data.options(self.key)
105 def has_facet(self, facet):
106 """Return whether the non-inherited facet exists."""
107 return facet in self.facets()
109 def remove_facet(self, facet):
110 """Remove a facet from the element."""
111 if self.has_facet(facet):
112 self.origin.data.remove_option(self.key, facet)
113 self.origin.modified = True
116 """Return a list of the element's inheritance lineage."""
117 if self.has_facet("inherit"):
118 ancestry = self.getlist("inherit")
119 for parent in ancestry[:]:
120 ancestors = self.universe.contents[parent].ancestry()
121 for ancestor in ancestors:
122 if ancestor not in ancestry:
123 ancestry.append(ancestor)
128 def get(self, facet, default=None):
129 """Retrieve values."""
132 if self.origin.data.has_option(self.key, facet):
133 raw_data = self.origin.data.get(self.key, facet)
134 if raw_data.startswith("u\"") or raw_data.startswith("u'"):
135 raw_data = raw_data[1:]
136 raw_data.strip("\"'")
138 elif self.has_facet("inherit"):
139 for ancestor in self.ancestry():
140 if self.universe.contents[ancestor].has_facet(facet):
141 return self.universe.contents[ancestor].get(facet)
145 def getboolean(self, facet, default=None):
146 """Retrieve values as boolean type."""
149 if self.origin.data.has_option(self.key, facet):
150 return self.origin.data.getboolean(self.key, facet)
151 elif self.has_facet("inherit"):
152 for ancestor in self.ancestry():
153 if self.universe.contents[ancestor].has_facet(facet):
154 return self.universe.contents[ancestor].getboolean(facet)
158 def getint(self, facet, default=None):
159 """Return values as int type."""
162 if self.origin.data.has_option(self.key, facet):
163 return self.origin.data.getint(self.key, facet)
164 elif self.has_facet("inherit"):
165 for ancestor in self.ancestry():
166 if self.universe.contents[ancestor].has_facet(facet):
167 return self.universe.contents[ancestor].getint(facet)
171 def getfloat(self, facet, default=None):
172 """Return values as float type."""
175 if self.origin.data.has_option(self.key, facet):
176 return self.origin.data.getfloat(self.key, facet)
177 elif self.has_facet("inherit"):
178 for ancestor in self.ancestry():
179 if self.universe.contents[ancestor].has_facet(facet):
180 return self.universe.contents[ancestor].getfloat(facet)
184 def getlist(self, facet, default=None):
185 """Return values as list type."""
188 value = self.get(facet)
190 return mudpy.data.makelist(value)
194 def getdict(self, facet, default=None):
195 """Return values as dict type."""
198 value = self.get(facet)
200 return mudpy.data.makedict(value)
204 def set(self, facet, value):
206 if not self.has_facet(facet) or not self.get(facet) == value:
207 # TODO: remove this check after the switch to py3k
208 if repr(type(value)) == "<type 'unicode'>":
210 if not type(value) is str:
212 self.origin.data.set(self.key, facet, value)
213 self.origin.modified = True
215 def append(self, facet, value):
216 """Append value to a list."""
217 if not type(value) is str:
219 newlist = self.getlist(facet)
220 newlist.append(value)
221 self.set(facet, newlist)
223 def new_event(self, action, when=None):
224 """Create, attach and enqueue an event element."""
226 # if when isn't specified, that means now
228 when = self.universe.get_time()
230 # events are elements themselves
231 event = Element("event:" + self.key + ":" + counter)
241 add_terminator=False,
244 """Convenience method to pass messages to an owner."""
257 def can_run(self, command):
258 """Check if the user can run this command object."""
260 # has to be in the commands category
261 if command not in self.universe.categories["command"].values():
264 # avatars of administrators can run any command
265 elif self.owner and self.owner.account.getboolean("administrator"):
268 # everyone can run non-administrative commands
269 elif not command.getboolean("administrative"):
272 # otherwise the command cannot be run by this actor
276 # pass back the result
279 def update_location(self):
280 """Make sure the location's contents contain this element."""
281 location = self.get("location")
282 if location in self.universe.contents:
283 self.universe.contents[location].contents[self.key] = self
285 def clean_contents(self):
286 """Make sure the element's contents aren't bogus."""
287 for element in self.contents.values():
288 if element.get("location") != self.key:
289 del self.contents[element.key]
291 def go_to(self, location):
292 """Relocate the element to a specific location."""
293 current = self.get("location")
294 if current and self.key in self.universe.contents[current].contents:
295 del universe.contents[current].contents[self.key]
296 if location in self.universe.contents:
297 self.set("location", location)
298 self.universe.contents[location].contents[self.key] = self
299 self.look_at(location)
302 """Relocate the element to its default location."""
303 self.go_to(self.get("default_location"))
304 self.echo_to_location(
305 "You suddenly realize that " + self.get("name") + " is here."
308 def move_direction(self, direction):
309 """Relocate the element in a specified direction."""
310 self.echo_to_location(
313 ) + " exits " + self.universe.categories[
324 "You exit " + self.universe.categories[
336 self.universe.contents[
337 self.get("location")].link_neighbor(direction)
339 self.echo_to_location(
342 ) + " arrives from " + self.universe.categories[
353 def look_at(self, key):
354 """Show an element to another element."""
356 element = self.universe.contents[key]
358 name = element.get("name")
360 message += "$(cyn)" + name + "$(nrm)$(eol)"
361 description = element.get("description")
363 message += description + "$(eol)"
364 portal_list = list(element.portals().keys())
367 message += "$(cyn)[ Exits: " + ", ".join(
370 for element in self.universe.contents[
373 if element.getboolean("is_actor") and element is not self:
374 message += "$(yel)" + element.get(
376 ) + " is here.$(nrm)$(eol)"
377 elif element is not self:
378 message += "$(grn)" + element.get(
384 """Map the portal directions for a room to neighbors."""
386 if re.match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
387 coordinates = [(int(x))
388 for x in self.key.split(":")[1].split(",")]
389 directions = self.universe.categories["internal"]["directions"]
393 x, directions.getdict(x)["vector"]
394 ) for x in directions.facets()
397 for portal in self.getlist("gridlinks"):
398 adjacent = map(lambda c, o: c + o,
399 coordinates, offsets[portal])
400 neighbor = "location:" + ",".join(
401 [(str(x)) for x in adjacent]
403 if neighbor in self.universe.contents:
404 portals[portal] = neighbor
405 for facet in self.facets():
406 if facet.startswith("link_"):
407 neighbor = self.get(facet)
408 if neighbor in self.universe.contents:
409 portal = facet.split("_")[1]
410 portals[portal] = neighbor
413 def link_neighbor(self, direction):
414 """Return the element linked in a given direction."""
415 portals = self.portals()
416 if direction in portals:
417 return portals[direction]
419 def echo_to_location(self, message):
420 """Show a message to other elements in the current location."""
421 for element in self.universe.contents[
424 if element is not self:
425 element.send(message)
432 def __init__(self, filename="", load=False):
433 """Initialize the universe."""
436 self.default_origins = {}
438 self.pending_events_long = {}
439 self.pending_events_short = {}
440 self.private_files = []
441 self.reload_flag = False
442 self.startdir = os.getcwd()
443 self.terminate_flag = False
446 possible_filenames = [
452 "/usr/local/mudpy/mudpy.conf",
453 "/usr/local/mudpy/etc/mudpy.conf",
454 "/etc/mudpy/mudpy.conf",
457 for filename in possible_filenames:
458 if os.access(filename, os.R_OK):
460 if not os.path.isabs(filename):
461 filename = os.path.join(self.startdir, filename)
462 self.filename = filename
467 """Load universe data from persistent storage."""
469 # the files dict must exist and filename needs to be read-only
473 self.filename in self.files and self.files[
478 # clear out all read-only files
479 if hasattr(self, "files"):
480 for data_filename in self.files.keys():
481 if not self.files[data_filename].is_writeable():
482 del self.files[data_filename]
484 # start loading from the initial file
485 mudpy.data.DataFile(self.filename, self)
487 # make a list of inactive avatars
488 inactive_avatars = []
489 for account in self.categories["account"].values():
490 inactive_avatars += [
491 (self.contents[x]) for x in account.getlist("avatars")
493 for user in self.userlist:
494 if user.avatar in inactive_avatars:
495 inactive_avatars.remove(user.avatar)
497 # go through all elements to clear out inactive avatar locations
498 for element in self.contents.values():
499 location = element.get("location")
500 if element in inactive_avatars and location:
501 if location in self.contents and element.key in self.contents[
504 del self.contents[location].contents[element.key]
505 element.set("default_location", location)
506 element.remove_facet("location")
508 # another pass to straighten out all the element contents
509 for element in self.contents.values():
510 element.update_location()
511 element.clean_contents()
514 """Create a new, empty Universe (the Big Bang)."""
515 new_universe = Universe()
516 for attribute in vars(self).keys():
517 exec("new_universe." + attribute + " = self." + attribute)
518 new_universe.reload_flag = False
523 """Save the universe to persistent storage."""
524 for key in self.files:
525 self.files[key].save()
527 def initialize_server_socket(self):
528 """Create and open the listening socket."""
530 # need to know the local address and port number for the listener
531 host = self.categories["internal"]["network"].get("host")
532 port = self.categories["internal"]["network"].getint("port")
534 # if no host was specified, bind to all local addresses (preferring
542 # figure out if this is ipv4 or v6
543 family = socket.getaddrinfo(host, port)[0][0]
544 if family is socket.AF_INET6 and not socket.has_ipv6:
545 log("No support for IPv6 address %s (use IPv4 instead)." % host)
547 # create a new stream-type socket object
548 self.listening_socket = socket.socket(family, socket.SOCK_STREAM)
550 # set the socket options to allow existing open ones to be
551 # reused (fixes a bug where the server can't bind for a minute
552 # when restarting on linux systems)
553 self.listening_socket.setsockopt(
554 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
557 # bind the socket to to our desired server ipa and port
558 self.listening_socket.bind((host, port))
560 # disable blocking so we can proceed whether or not we can
562 self.listening_socket.setblocking(0)
564 # start listening on the socket
565 self.listening_socket.listen(1)
567 # note that we're now ready for user connections
569 "Listening for Telnet connections on: " +
570 host + ":" + str(port)
574 """Convenience method to get the elapsed time counter."""
575 return self.categories["internal"]["counters"].getint("elapsed")
580 """This is a connected user."""
583 """Default values for the in-memory user variables."""
586 self.authenticated = False
589 self.connection = None
591 self.input_queue = []
592 self.last_address = ""
593 self.last_input = universe.get_time()
594 self.menu_choices = {}
595 self.menu_seen = False
596 self.negotiation_pause = 0
597 self.output_queue = []
598 self.partial_input = b""
599 self.password_tries = 0
600 self.state = "initial"
604 """Log, close the connection and remove."""
606 name = self.account.get("name")
610 message = "User " + name
612 message = "An unnamed user"
613 message += " logged out."
615 self.deactivate_avatar()
616 self.connection.close()
619 def check_idle(self):
620 """Warn or disconnect idle users as appropriate."""
621 idletime = universe.get_time() - self.last_input
622 linkdead_dict = universe.categories["internal"]["time"].getdict(
625 if self.state in linkdead_dict:
626 linkdead_state = self.state
628 linkdead_state = "default"
629 if idletime > linkdead_dict[linkdead_state]:
631 "$(eol)$(red)You've done nothing for far too long... goodbye!"
636 logline = "Disconnecting "
637 if self.account and self.account.get("name"):
638 logline += self.account.get("name")
640 logline += "an unknown user"
641 logline += " after idling too long in the " + \
642 self.state + " state."
644 self.state = "disconnecting"
645 self.menu_seen = False
646 idle_dict = universe.categories["internal"]["time"].getdict("idle")
647 if self.state in idle_dict:
648 idle_state = self.state
650 idle_state = "default"
651 if idletime == idle_dict[idle_state]:
653 "$(eol)$(red)If you continue to be unproductive, "
654 + "you'll be shown the door...$(nrm)$(eol)"
658 """Save, load a new user and relocate the connection."""
660 # get out of the list
663 # create a new user object
666 # set everything equivalent
667 for attribute in vars(self).keys():
668 exec("new_user." + attribute + " = self." + attribute)
670 # the avatar needs a new owner
672 new_user.avatar.owner = new_user
675 universe.userlist.append(new_user)
677 # get rid of the old user object
680 def replace_old_connections(self):
681 """Disconnect active users with the same name."""
683 # the default return value
686 # iterate over each user in the list
687 for old_user in universe.userlist:
689 # the name is the same but it's not us
692 ) and old_user.account and old_user.account.get(
694 ) == self.account.get(
696 ) and old_user is not self:
700 "User " + self.account.get(
702 ) + " reconnected--closing old connection to "
703 + old_user.address + ".",
707 "$(eol)$(red)New connection from " + self.address
708 + ". Terminating old connection...$(nrm)$(eol)",
713 # close the old connection
714 old_user.connection.close()
716 # replace the old connection with this one
718 "$(eol)$(red)Taking over old connection from "
719 + old_user.address + ".$(nrm)"
721 old_user.connection = self.connection
722 old_user.last_address = old_user.address
723 old_user.address = self.address
725 # take this one out of the list and delete
731 # true if an old connection was replaced, false if not
734 def authenticate(self):
735 """Flag the user as authenticated and disconnect duplicates."""
736 if self.state is not "authenticated":
737 log("User " + self.account.get("name") + " logged in.", 2)
738 self.authenticated = True
739 if self.account.subkey in universe.categories[
746 self.account.set("administrator", "True")
749 """Send the user their current menu."""
750 if not self.menu_seen:
751 self.menu_choices = get_menu_choices(self)
753 get_menu(self.state, self.error, self.menu_choices),
757 self.menu_seen = True
759 self.adjust_echoing()
761 def adjust_echoing(self):
762 """Adjust echoing to match state menu requirements."""
763 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_ECHO,
765 if menu_echo_on(self.state):
766 mudpy.telnet.disable(self, mudpy.telnet.TELOPT_ECHO,
768 elif not menu_echo_on(self.state):
769 mudpy.telnet.enable(self, mudpy.telnet.TELOPT_ECHO,
773 """Remove a user from the list of connected users."""
774 universe.userlist.remove(self)
784 add_terminator=False,
787 """Send arbitrary text to a connected user."""
789 # unless raw mode is on, clean it up all nice and pretty
792 # strip extra $(eol) off if present
793 while output.startswith("$(eol)"):
795 while output.endswith("$(eol)"):
797 extra_lines = output.find("$(eol)$(eol)$(eol)")
798 while extra_lines > -1:
799 output = output[:extra_lines] + output[extra_lines + 6:]
800 extra_lines = output.find("$(eol)$(eol)$(eol)")
802 # start with a newline, append the message, then end
803 # with the optional eol string passed to this function
804 # and the ansi escape to return to normal text
805 if not just_prompt and prepend_padding:
806 if not self.output_queue \
807 or not self.output_queue[-1].endswith(b"\r\n"):
808 output = "$(eol)" + output
809 elif not self.output_queue[-1].endswith(
811 ) and not self.output_queue[-1].endswith(
814 output = "$(eol)" + output
815 output += eol + chr(27) + "[0m"
817 # tack on a prompt if active
818 if self.state == "active":
823 mode = self.avatar.get("mode")
825 output += "(" + mode + ") "
827 # find and replace macros in the output
828 output = replace_macros(self, output)
830 # wrap the text at the client's width (min 40, 0 disables)
832 if self.columns < 40:
836 output = wrap_ansi_text(output, wrap)
838 # if supported by the client, encode it utf-8
839 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
841 encoded_output = output.encode("utf-8")
843 # otherwise just send ascii
845 encoded_output = output.encode("ascii", "replace")
847 # end with a terminator if requested
848 if add_prompt or add_terminator:
849 if mudpy.telnet.is_enabled(
850 self, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US):
851 encoded_output += mudpy.telnet.telnet_proto(
852 mudpy.telnet.IAC, mudpy.telnet.EOR)
853 elif not mudpy.telnet.is_enabled(
854 self, mudpy.telnet.TELOPT_SGA, mudpy.telnet.US):
855 encoded_output += mudpy.telnet.telnet_proto(
856 mudpy.telnet.IAC, mudpy.telnet.GA)
858 # and tack it onto the queue
859 self.output_queue.append(encoded_output)
861 # if this is urgent, flush all pending output
865 # just dump raw bytes as requested
867 self.output_queue.append(output)
871 """All the things to do to the user per increment."""
873 # if the world is terminating, disconnect
874 if universe.terminate_flag:
875 self.state = "disconnecting"
876 self.menu_seen = False
878 # check for an idle connection and act appropriately
882 # if output is paused, decrement the counter
883 if self.state == "initial":
884 if self.negotiation_pause:
885 self.negotiation_pause -= 1
887 self.state = "entering_account_name"
889 # show the user a menu as needed
890 elif not self.state == "active":
893 # flush any pending output in the queue
896 # disconnect users with the appropriate state
897 if self.state == "disconnecting":
900 # check for input and add it to the queue
903 # there is input waiting in the queue
905 handle_user_input(self)
908 """Try to send the last item in the queue and remove it."""
909 if self.output_queue:
911 self.connection.send(self.output_queue[0])
912 del self.output_queue[0]
914 if self.account and self.account.get("name"):
915 account = self.account.get("name")
917 account = "an unknown user"
918 log("Sending to %s raised an exception (broken pipe?)."
922 def enqueue_input(self):
923 """Process and enqueue any new input."""
925 # check for some input
927 raw_input = self.connection.recv(1024)
934 # tack this on to any previous partial
935 self.partial_input += raw_input
937 # reply to and remove any IAC negotiation codes
938 mudpy.telnet.negotiate_telnet_options(self)
940 # separate multiple input lines
941 new_input_lines = self.partial_input.split(b"\n")
943 # if input doesn't end in a newline, replace the
944 # held partial input with the last line of it
945 if not self.partial_input.endswith(b"\n"):
946 self.partial_input = new_input_lines.pop()
948 # otherwise, chop off the extra null input and reset
949 # the held partial input
951 new_input_lines.pop()
952 self.partial_input = b""
954 # iterate over the remaining lines
955 for line in new_input_lines:
957 # strip off extra whitespace
960 # log non-printable characters remaining
961 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
963 asciiline = b"".join(
964 filter(lambda x: b" " <= x <= b"~", line))
965 if line != asciiline:
966 logline = "Non-ASCII characters from "
967 if self.account and self.account.get("name"):
968 logline += self.account.get("name") + ": "
970 logline += "unknown user: "
971 logline += repr(line)
976 line = line.decode("utf-8")
977 except UnicodeDecodeError:
978 logline = "Non-UTF-8 characters from "
979 if self.account and self.account.get("name"):
980 logline += self.account.get("name") + ": "
982 logline += "unknown user: "
983 logline += repr(line)
987 line = unicodedata.normalize("NFKC", line)
989 # put on the end of the queue
990 self.input_queue.append(line)
992 def new_avatar(self):
993 """Instantiate a new, unconfigured avatar for this user."""
995 while "avatar:" + self.account.get("name") + ":" + str(
997 ) in universe.categories["actor"].keys():
999 self.avatar = Element(
1000 "actor:avatar:" + self.account.get("name") + ":" + str(
1005 self.avatar.append("inherit", "archetype:avatar")
1006 self.account.append("avatars", self.avatar.key)
1008 def delete_avatar(self, avatar):
1009 """Remove an avatar from the world and from the user's list."""
1010 if self.avatar is universe.contents[avatar]:
1012 universe.contents[avatar].destroy()
1013 avatars = self.account.getlist("avatars")
1014 avatars.remove(avatar)
1015 self.account.set("avatars", avatars)
1017 def activate_avatar_by_index(self, index):
1018 """Enter the world with a particular indexed avatar."""
1019 self.avatar = universe.contents[
1020 self.account.getlist("avatars")[index]]
1021 self.avatar.owner = self
1022 self.state = "active"
1023 self.avatar.go_home()
1025 def deactivate_avatar(self):
1026 """Have the active avatar leave the world."""
1028 current = self.avatar.get("location")
1030 self.avatar.set("default_location", current)
1031 self.avatar.echo_to_location(
1032 "You suddenly wonder where " + self.avatar.get(
1036 del universe.contents[current].contents[self.avatar.key]
1037 self.avatar.remove_facet("location")
1038 self.avatar.owner = None
1042 """Destroy the user and associated avatars."""
1043 for avatar in self.account.getlist("avatars"):
1044 self.delete_avatar(avatar)
1045 self.account.destroy()
1047 def list_avatar_names(self):
1048 """List names of assigned avatars."""
1050 universe.contents[avatar].get(
1052 ) for avatar in self.account.getlist("avatars")
1056 def broadcast(message, add_prompt=True):
1057 """Send a message to all connected users."""
1058 for each_user in universe.userlist:
1059 each_user.send("$(eol)" + message, add_prompt=add_prompt)
1062 def log(message, level=0):
1063 """Log a message."""
1065 # a couple references we need
1066 file_name = universe.categories["internal"]["logging"].get("file")
1067 max_log_lines = universe.categories["internal"]["logging"].getint(
1070 syslog_name = universe.categories["internal"]["logging"].get("syslog")
1071 timestamp = time.asctime()[4:19]
1073 # turn the message into a list of lines
1075 lambda x: x != "", [(x.rstrip()) for x in message.split("\n")]
1078 # send the timestamp and line to a file
1080 if not os.path.isabs(file_name):
1081 file_name = os.path.join(universe.startdir, file_name)
1082 file_descriptor = codecs.open(file_name, "a", "utf-8")
1084 file_descriptor.write(timestamp + " " + line + "\n")
1085 file_descriptor.flush()
1086 file_descriptor.close()
1088 # send the timestamp and line to standard output
1089 if universe.categories["internal"]["logging"].getboolean("stdout"):
1091 print(timestamp + " " + line)
1093 # send the line to the system log
1096 syslog_name.encode("utf-8"),
1098 syslog.LOG_INFO | syslog.LOG_DAEMON
1104 # display to connected administrators
1105 for user in universe.userlist:
1106 if user.state == "active" and user.account.getboolean(
1108 ) and user.account.getint("loglevel") <= level:
1109 # iterate over every line in the message
1113 "$(bld)$(red)" + timestamp + " "
1114 + line.replace("$(", "$_(") + "$(nrm)$(eol)")
1115 user.send(full_message, flush=True)
1117 # add to the recent log list
1119 while 0 < len(universe.loglines) >= max_log_lines:
1120 del universe.loglines[0]
1121 universe.loglines.append((level, timestamp + " " + line))
1124 def get_loglines(level, start, stop):
1125 """Return a specific range of loglines filtered by level."""
1127 # filter the log lines
1128 loglines = filter(lambda x: x[0] >= level, universe.loglines)
1130 # we need these in several places
1131 total_count = str(len(universe.loglines))
1132 filtered_count = len(loglines)
1134 # don't proceed if there are no lines
1137 # can't start before the begining or at the end
1138 if start > filtered_count:
1139 start = filtered_count
1143 # can't stop before we start
1150 message = "There are " + str(total_count)
1151 message += " log lines in memory and " + str(filtered_count)
1152 message += " at or above level " + str(level) + "."
1153 message += " The matching lines from " + str(stop) + " to "
1154 message += str(start) + " are:$(eol)$(eol)"
1156 # add the text from the selected lines
1158 range_lines = loglines[-start:-(stop - 1)]
1160 range_lines = loglines[-start:]
1161 for line in range_lines:
1162 message += " (" + str(line[0]) + ") " + line[1].replace(
1166 # there were no lines
1168 message = "None of the " + str(total_count)
1169 message += " lines in memory matches your request."
1175 def glyph_columns(character):
1176 """Convenience function to return the column width of a glyph."""
1177 if unicodedata.east_asian_width(character) in "FW":
1183 def wrap_ansi_text(text, width):
1184 """Wrap text with arbitrary width while ignoring ANSI colors."""
1186 # the current position in the entire text string, including all
1187 # characters, printable or otherwise
1190 # the current text position relative to the begining of the line,
1191 # ignoring color escape sequences
1194 # the absolute position of the most recent whitespace character
1197 # whether the current character is part of a color escape sequence
1200 # normalize any potentially composited unicode before we count it
1201 # TODO: remove this check after the switch to py3k
1203 text = unicodedata.normalize("NFKC", text)
1205 text = unicodedata.normalize("NFKC", unicode(text))
1207 # iterate over each character from the begining of the text
1208 for each_character in text:
1210 # the current character is the escape character
1211 if each_character == "\x1b" and not escape:
1214 # the current character is within an escape sequence
1217 # the current character is m, which terminates the
1219 if each_character == "m":
1222 # the current character is a newline, so reset the relative
1223 # position (start a new line)
1224 elif each_character == "\n":
1226 last_whitespace = abs_pos
1228 # the current character meets the requested maximum line width,
1229 # so we need to backtrack and find a space at which to wrap;
1230 # special care is taken to avoid an off-by-one in case the
1231 # current character is a double-width glyph
1232 elif each_character != "\r" and (
1233 rel_pos >= width or (
1234 rel_pos >= width - 1 and glyph_columns(
1240 # it's always possible we landed on whitespace
1241 if unicodedata.category(each_character) in ("Cc", "Zs"):
1242 last_whitespace = abs_pos
1244 # insert an eol in place of the space
1245 text = text[:last_whitespace] + \
1246 "\r\n" + text[last_whitespace + 1:]
1248 # increase the absolute position because an eol is two
1249 # characters but the space it replaced was only one
1252 # now we're at the begining of a new line, plus the
1253 # number of characters wrapped from the previous line
1255 for remaining_characters in text[last_whitespace:abs_pos]:
1256 rel_pos += glyph_columns(remaining_characters)
1258 # as long as the character is not a carriage return and the
1259 # other above conditions haven't been met, count it as a
1260 # printable character
1261 elif each_character != "\r":
1262 rel_pos += glyph_columns(each_character)
1263 if unicodedata.category(each_character) in ("Cc", "Zs"):
1264 last_whitespace = abs_pos
1266 # increase the absolute position for every character
1269 # return the newly-wrapped text
1273 def weighted_choice(data):
1274 """Takes a dict weighted by value and returns a random key."""
1276 # this will hold our expanded list of keys from the data
1279 # create the expanded list of keys
1280 for key in data.keys():
1281 for count in range(data[key]):
1282 expanded.append(key)
1284 # return one at random
1285 return random.choice(expanded)
1289 """Returns a random character name."""
1291 # the vowels and consonants needed to create romaji syllables
1320 # this dict will hold our weighted list of syllables
1323 # generate the list with an even weighting
1324 for consonant in consonants:
1325 for vowel in vowels:
1326 syllables[consonant + vowel] = 1
1328 # we'll build the name into this string
1331 # create a name of random length from the syllables
1332 for syllable in range(random.randrange(2, 6)):
1333 name += weighted_choice(syllables)
1335 # strip any leading quotemark, capitalize and return the name
1336 return name.strip("'").capitalize()
1339 def replace_macros(user, text, is_input=False):
1340 """Replaces macros in text output."""
1342 # third person pronouns
1344 "female": {"obj": "her", "pos": "hers", "sub": "she"},
1345 "male": {"obj": "him", "pos": "his", "sub": "he"},
1346 "neuter": {"obj": "it", "pos": "its", "sub": "it"}
1349 # a dict of replacement macros
1352 "bld": chr(27) + "[1m",
1353 "nrm": chr(27) + "[0m",
1354 "blk": chr(27) + "[30m",
1355 "blu": chr(27) + "[34m",
1356 "cyn": chr(27) + "[36m",
1357 "grn": chr(27) + "[32m",
1358 "mgt": chr(27) + "[35m",
1359 "red": chr(27) + "[31m",
1360 "yel": chr(27) + "[33m",
1363 # add dynamic macros where possible
1365 account_name = user.account.get("name")
1367 macros["account"] = account_name
1369 avatar_gender = user.avatar.get("gender")
1371 macros["tpop"] = pronouns[avatar_gender]["obj"]
1372 macros["tppp"] = pronouns[avatar_gender]["pos"]
1373 macros["tpsp"] = pronouns[avatar_gender]["sub"]
1378 # find and replace per the macros dict
1379 macro_start = text.find("$(")
1380 if macro_start == -1:
1382 macro_end = text.find(")", macro_start) + 1
1383 macro = text[macro_start + 2:macro_end - 1]
1384 if macro in macros.keys():
1385 replacement = macros[macro]
1387 # this is how we handle local file inclusion (dangerous!)
1388 elif macro.startswith("inc:"):
1389 incfile = mudpy.data.find_file(macro[4:], universe=universe)
1390 if os.path.exists(incfile):
1391 incfd = codecs.open(incfile, "r", "utf-8")
1394 if line.endswith("\n") and not line.endswith("\r\n"):
1395 line = line.replace("\n", "\r\n")
1397 # lose the trailing eol
1398 replacement = replacement[:-2]
1401 log("Couldn't read included " + incfile + " file.", 6)
1403 # if we get here, log and replace it with null
1407 log("Unexpected replacement macro " +
1408 macro + " encountered.", 6)
1410 # and now we act on the replacement
1411 text = text.replace("$(" + macro + ")", replacement)
1413 # replace the look-like-a-macro sequence
1414 text = text.replace("$_(", "$(")
1419 def escape_macros(text):
1420 """Escapes replacement macros in text."""
1421 return text.replace("$(", "$_(")
1424 def first_word(text, separator=" "):
1425 """Returns a tuple of the first word and the rest."""
1427 if text.find(separator) > 0:
1428 return text.split(separator, 1)
1436 """The things which should happen on each pulse, aside from reloads."""
1438 # open the listening socket if it hasn't been already
1439 if not hasattr(universe, "listening_socket"):
1440 universe.initialize_server_socket()
1442 # assign a user if a new connection is waiting
1443 user = check_for_connection(universe.listening_socket)
1445 universe.userlist.append(user)
1447 # iterate over the connected users
1448 for user in universe.userlist:
1451 # add an element for counters if it doesn't exist
1452 if "counters" not in universe.categories["internal"]:
1453 universe.categories["internal"]["counters"] = Element(
1454 "internal:counters", universe
1457 # update the log every now and then
1458 if not universe.categories["internal"]["counters"].getint("mark"):
1459 log(str(len(universe.userlist)) + " connection(s)")
1460 universe.categories["internal"]["counters"].set(
1461 "mark", universe.categories["internal"]["time"].getint(
1466 universe.categories["internal"]["counters"].set(
1467 "mark", universe.categories["internal"]["counters"].getint(
1472 # periodically save everything
1473 if not universe.categories["internal"]["counters"].getint("save"):
1475 universe.categories["internal"]["counters"].set(
1476 "save", universe.categories["internal"]["time"].getint(
1481 universe.categories["internal"]["counters"].set(
1482 "save", universe.categories["internal"]["counters"].getint(
1487 # pause for a configurable amount of time (decimal seconds)
1488 time.sleep(universe.categories["internal"]
1489 ["time"].getfloat("increment"))
1491 # increase the elapsed increment counter
1492 universe.categories["internal"]["counters"].set(
1493 "elapsed", universe.categories["internal"]["counters"].getint(
1500 """Reload all relevant objects."""
1501 for user in universe.userlist[:]:
1503 for element in universe.contents.values():
1504 if element.origin.is_writeable():
1509 def check_for_connection(listening_socket):
1510 """Check for a waiting connection and return a new user object."""
1512 # try to accept a new connection
1514 connection, address = listening_socket.accept()
1518 # note that we got one
1519 log("Connection from " + address[0], 2)
1521 # disable blocking so we can proceed whether or not we can send/receive
1522 connection.setblocking(0)
1524 # create a new user object
1527 # associate this connection with it
1528 user.connection = connection
1530 # set the user's ipa from the connection's ipa
1531 user.address = address[0]
1533 # let the client know we WILL EOR (RFC 885)
1534 mudpy.telnet.enable(user, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US)
1535 user.negotiation_pause = 2
1537 # return the new user object
1541 def get_menu(state, error=None, choices=None):
1542 """Show the correct menu text to a user."""
1544 # make sure we don't reuse a mutable sequence by default
1548 # get the description or error text
1549 message = get_menu_description(state, error)
1551 # get menu choices for the current state
1552 message += get_formatted_menu_choices(state, choices)
1554 # try to get a prompt, if it was defined
1555 message += get_menu_prompt(state)
1557 # throw in the default choice, if it exists
1558 message += get_formatted_default_menu_choice(state)
1560 # display a message indicating if echo is off
1561 message += get_echo_message(state)
1563 # return the assembly of various strings defined above
1567 def menu_echo_on(state):
1568 """True if echo is on, false if it is off."""
1569 return universe.categories["menu"][state].getboolean("echo", True)
1572 def get_echo_message(state):
1573 """Return a message indicating that echo is off."""
1574 if menu_echo_on(state):
1577 return "(won't echo) "
1580 def get_default_menu_choice(state):
1581 """Return the default choice for a menu."""
1582 return universe.categories["menu"][state].get("default")
1585 def get_formatted_default_menu_choice(state):
1586 """Default menu choice foratted for inclusion in a prompt string."""
1587 default_choice = get_default_menu_choice(state)
1589 return "[$(red)" + default_choice + "$(nrm)] "
1594 def get_menu_description(state, error):
1595 """Get the description or error text."""
1597 # an error condition was raised by the handler
1600 # try to get an error message matching the condition
1602 description = universe.categories[
1603 "menu"][state].get("error_" + error)
1605 description = "That is not a valid choice..."
1606 description = "$(red)" + description + "$(nrm)"
1608 # there was no error condition
1611 # try to get a menu description for the current state
1612 description = universe.categories["menu"][state].get("description")
1614 # return the description or error message
1616 description += "$(eol)$(eol)"
1620 def get_menu_prompt(state):
1621 """Try to get a prompt, if it was defined."""
1622 prompt = universe.categories["menu"][state].get("prompt")
1628 def get_menu_choices(user):
1629 """Return a dict of choice:meaning."""
1630 menu = universe.categories["menu"][user.state]
1631 create_choices = menu.get("create")
1633 choices = eval(create_choices)
1639 for facet in menu.facets():
1640 if facet.startswith("demand_") and not eval(
1641 universe.categories["menu"][user.state].get(facet)
1643 ignores.append(facet.split("_", 2)[1])
1644 elif facet.startswith("create_"):
1645 creates[facet] = facet.split("_", 2)[1]
1646 elif facet.startswith("choice_"):
1647 options[facet] = facet.split("_", 2)[1]
1648 for facet in creates.keys():
1649 if not creates[facet] in ignores:
1650 choices[creates[facet]] = eval(menu.get(facet))
1651 for facet in options.keys():
1652 if not options[facet] in ignores:
1653 choices[options[facet]] = menu.get(facet)
1657 def get_formatted_menu_choices(state, choices):
1658 """Returns a formatted string of menu choices."""
1660 choice_keys = list(choices.keys())
1662 for choice in choice_keys:
1663 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[
1667 choice_output += "$(eol)"
1668 return choice_output
1671 def get_menu_branches(state):
1672 """Return a dict of choice:branch."""
1674 for facet in universe.categories["menu"][state].facets():
1675 if facet.startswith("branch_"):
1677 facet.split("_", 2)[1]
1678 ] = universe.categories["menu"][state].get(facet)
1682 def get_default_branch(state):
1683 """Return the default branch."""
1684 return universe.categories["menu"][state].get("branch")
1687 def get_choice_branch(user, choice):
1688 """Returns the new state matching the given choice."""
1689 branches = get_menu_branches(user.state)
1690 if choice in branches.keys():
1691 return branches[choice]
1692 elif choice in user.menu_choices.keys():
1693 return get_default_branch(user.state)
1698 def get_menu_actions(state):
1699 """Return a dict of choice:branch."""
1701 for facet in universe.categories["menu"][state].facets():
1702 if facet.startswith("action_"):
1704 facet.split("_", 2)[1]
1705 ] = universe.categories["menu"][state].get(facet)
1709 def get_default_action(state):
1710 """Return the default action."""
1711 return universe.categories["menu"][state].get("action")
1714 def get_choice_action(user, choice):
1715 """Run any indicated script for the given choice."""
1716 actions = get_menu_actions(user.state)
1717 if choice in actions.keys():
1718 return actions[choice]
1719 elif choice in user.menu_choices.keys():
1720 return get_default_action(user.state)
1725 def handle_user_input(user):
1726 """The main handler, branches to a state-specific handler."""
1728 # if the user's client echo is off, send a blank line for aesthetics
1729 if mudpy.telnet.is_enabled(user, mudpy.telnet.TELOPT_ECHO,
1731 user.send("", add_prompt=False, prepend_padding=False)
1733 # check to make sure the state is expected, then call that handler
1734 if "handler_" + user.state in globals():
1735 exec("handler_" + user.state + "(user)")
1737 generic_menu_handler(user)
1739 # since we got input, flag that the menu/prompt needs to be redisplayed
1740 user.menu_seen = False
1742 # update the last_input timestamp while we're at it
1743 user.last_input = universe.get_time()
1746 def generic_menu_handler(user):
1747 """A generic menu choice handler."""
1749 # get a lower-case representation of the next line of input
1750 if user.input_queue:
1751 choice = user.input_queue.pop(0)
1753 choice = choice.lower()
1757 choice = get_default_menu_choice(user.state)
1758 if choice in user.menu_choices:
1759 exec(get_choice_action(user, choice))
1760 new_state = get_choice_branch(user, choice)
1762 user.state = new_state
1764 user.error = "default"
1767 def handler_entering_account_name(user):
1768 """Handle the login account name."""
1770 # get the next waiting line of input
1771 input_data = user.input_queue.pop(0)
1773 # did the user enter anything?
1776 # keep only the first word and convert to lower-case
1777 name = input_data.lower()
1779 # fail if there are non-alphanumeric characters
1780 if name != "".join(filter(
1781 lambda x: x >= "0" and x <= "9" or x >= "a" and x <= "z",
1783 user.error = "bad_name"
1785 # if that account exists, time to request a password
1786 elif name in universe.categories["account"]:
1787 user.account = universe.categories["account"][name]
1788 user.state = "checking_password"
1790 # otherwise, this could be a brand new user
1792 user.account = Element("account:" + name, universe)
1793 user.account.set("name", name)
1794 log("New user: " + name, 2)
1795 user.state = "checking_new_account_name"
1797 # if the user entered nothing for a name, then buhbye
1799 user.state = "disconnecting"
1802 def handler_checking_password(user):
1803 """Handle the login account password."""
1805 # get the next waiting line of input
1806 input_data = user.input_queue.pop(0)
1808 # does the hashed input equal the stored hash?
1809 if mudpy.password.verify(input_data, user.account.get("passhash")):
1811 # if so, set the username and load from cold storage
1812 if not user.replace_old_connections():
1814 user.state = "main_utility"
1816 # if at first your hashes don't match, try, try again
1817 elif user.password_tries < universe.categories[
1824 user.password_tries += 1
1825 user.error = "incorrect"
1827 # we've exceeded the maximum number of password failures, so disconnect
1830 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1832 user.state = "disconnecting"
1835 def handler_entering_new_password(user):
1836 """Handle a new password entry."""
1838 # get the next waiting line of input
1839 input_data = user.input_queue.pop(0)
1841 # make sure the password is strong--at least one upper, one lower and
1842 # one digit, seven or more characters in length
1843 if len(input_data) > 6 and len(
1844 list(filter(lambda x: x >= "0" and x <= "9", input_data))
1846 list(filter(lambda x: x >= "A" and x <= "Z", input_data))
1848 list(filter(lambda x: x >= "a" and x <= "z", input_data))
1851 # hash and store it, then move on to verification
1852 user.account.set("passhash", mudpy.password.create(input_data))
1853 user.state = "verifying_new_password"
1855 # the password was weak, try again if you haven't tried too many times
1856 elif user.password_tries < universe.categories[
1863 user.password_tries += 1
1866 # too many tries, so adios
1869 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1871 user.account.destroy()
1872 user.state = "disconnecting"
1875 def handler_verifying_new_password(user):
1876 """Handle the re-entered new password for verification."""
1878 # get the next waiting line of input
1879 input_data = user.input_queue.pop(0)
1881 # hash the input and match it to storage
1882 if mudpy.password.verify(input_data, user.account.get("passhash")):
1885 # the hashes matched, so go active
1886 if not user.replace_old_connections():
1887 user.state = "main_utility"
1889 # go back to entering the new password as long as you haven't tried
1891 elif user.password_tries < universe.categories[
1898 user.password_tries += 1
1899 user.error = "differs"
1900 user.state = "entering_new_password"
1902 # otherwise, sayonara
1905 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1907 user.account.destroy()
1908 user.state = "disconnecting"
1911 def handler_active(user):
1912 """Handle input for active users."""
1914 # get the next waiting line of input
1915 input_data = user.input_queue.pop(0)
1920 # split out the command and parameters
1922 mode = actor.get("mode")
1923 if mode and input_data.startswith("!"):
1924 command_name, parameters = first_word(input_data[1:])
1925 elif mode == "chat":
1926 command_name = "say"
1927 parameters = input_data
1929 command_name, parameters = first_word(input_data)
1931 # lowercase the command
1932 command_name = command_name.lower()
1934 # the command matches a command word for which we have data
1935 if command_name in universe.categories["command"]:
1936 command = universe.categories["command"][command_name]
1940 # if it's allowed, do it
1941 if actor.can_run(command):
1942 exec(command.get("action"))
1944 # otherwise, give an error
1946 command_error(actor, input_data)
1948 # if no input, just idle back with a prompt
1950 user.send("", just_prompt=True)
1953 def command_halt(actor, parameters):
1954 """Halt the world."""
1957 # see if there's a message or use a generic one
1959 message = "Halting: " + parameters
1961 message = "User " + actor.owner.account.get(
1963 ) + " halted the world."
1966 broadcast(message, add_prompt=False)
1969 # set a flag to terminate the world
1970 universe.terminate_flag = True
1973 def command_reload(actor):
1974 """Reload all code modules, configs and data."""
1977 # let the user know and log
1978 actor.send("Reloading all code modules, configs and data.")
1981 actor.owner.account.get("name") + " reloaded the world.",
1985 # set a flag to reload
1986 universe.reload_flag = True
1989 def command_quit(actor):
1990 """Leave the world and go back to the main menu."""
1992 actor.owner.state = "main_utility"
1993 actor.owner.deactivate_avatar()
1996 def command_help(actor, parameters):
1997 """List available commands and provide help for commands."""
1999 # did the user ask for help on a specific command word?
2000 if parameters and actor.owner:
2002 # is the command word one for which we have data?
2003 if parameters in universe.categories["command"]:
2004 command = universe.categories["command"][parameters]
2008 # only for allowed commands
2009 if actor.can_run(command):
2011 # add a description if provided
2012 description = command.get("description")
2014 description = "(no short description provided)"
2015 if command.getboolean("administrative"):
2019 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
2021 # add the help text if provided
2022 help_text = command.get("help")
2024 help_text = "No help is provided for this command."
2027 # list related commands
2028 see_also = command.getlist("see_also")
2030 really_see_also = ""
2031 for item in see_also:
2032 if item in universe.categories["command"]:
2033 command = universe.categories["command"][item]
2034 if actor.can_run(command):
2036 really_see_also += ", "
2037 if command.getboolean("administrative"):
2038 really_see_also += "$(red)"
2040 really_see_also += "$(grn)"
2041 really_see_also += item + "$(nrm)"
2043 output += "$(eol)$(eol)See also: " + really_see_also
2045 # no data for the requested command word
2047 output = "That is not an available command."
2049 # no specific command word was indicated
2052 # give a sorted list of commands with descriptions if provided
2053 output = "These are the commands available to you:$(eol)$(eol)"
2054 sorted_commands = list(universe.categories["command"].keys())
2055 sorted_commands.sort()
2056 for item in sorted_commands:
2057 command = universe.categories["command"][item]
2058 if actor.can_run(command):
2059 description = command.get("description")
2061 description = "(no short description provided)"
2062 if command.getboolean("administrative"):
2066 output += item + "$(nrm) - " + description + "$(eol)"
2067 output += "$(eol)Enter \"help COMMAND\" for help on a command " \
2068 + "named \"COMMAND\"."
2070 # send the accumulated output to the user
2074 def command_move(actor, parameters):
2075 """Move the avatar in a given direction."""
2076 if parameters in universe.contents[actor.get("location")].portals():
2077 actor.move_direction(parameters)
2079 actor.send("You cannot go that way.")
2082 def command_look(actor, parameters):
2085 actor.send("You can't look at or in anything yet.")
2087 actor.look_at(actor.get("location"))
2090 def command_say(actor, parameters):
2091 """Speak to others in the same room."""
2093 # check for replacement macros and escape them
2094 parameters = escape_macros(parameters)
2096 # if the message is wrapped in quotes, remove them and leave contents
2098 if parameters.startswith("\"") and parameters.endswith("\""):
2099 message = parameters[1:-1]
2102 # otherwise, get rid of stray quote marks on the ends of the message
2104 message = parameters.strip("\"'`")
2107 # the user entered a message
2110 # match the punctuation used, if any, to an action
2111 actions = universe.categories["internal"]["language"].getdict(
2114 default_punctuation = (
2115 universe.categories["internal"]["language"].get(
2116 "default_punctuation"))
2118 for mark in actions.keys():
2119 if not literal and message.endswith(mark):
2120 action = actions[mark]
2123 # add punctuation if needed
2125 action = actions[default_punctuation]
2126 if message and not (
2127 literal or unicodedata.category(message[-1]) == "Po"
2129 message += default_punctuation
2131 # failsafe checks to avoid unwanted reformatting and null strings
2132 if message and not literal:
2134 # decapitalize the first letter to improve matching
2135 message = message[0].lower() + message[1:]
2137 # iterate over all words in message, replacing typos
2138 typos = universe.categories["internal"]["language"].getdict(
2141 words = message.split()
2142 for index in range(len(words)):
2144 while unicodedata.category(word[0]) == "Po":
2146 while unicodedata.category(word[-1]) == "Po":
2148 if word in typos.keys():
2149 words[index] = words[index].replace(word, typos[word])
2150 message = " ".join(words)
2152 # capitalize the first letter
2153 message = message[0].upper() + message[1:]
2157 actor.echo_to_location(
2158 actor.get("name") + " " + action + "s, \"" + message + "\""
2160 actor.send("You " + action + ", \"" + message + "\"")
2162 # there was no message
2164 actor.send("What do you want to say?")
2167 def command_chat(actor):
2168 """Toggle chat mode."""
2169 mode = actor.get("mode")
2171 actor.set("mode", "chat")
2172 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
2173 elif mode == "chat":
2174 actor.remove_facet("mode")
2175 actor.send("Exiting chat mode.")
2177 actor.send("Sorry, but you're already busy with something else!")
2180 def command_show(actor, parameters):
2181 """Show program data."""
2183 arguments = parameters.split()
2185 message = "What do you want to show?"
2186 elif arguments[0] == "time":
2187 message = universe.categories["internal"]["counters"].get(
2189 ) + " increments elapsed since the world was created."
2190 elif arguments[0] == "categories":
2191 message = "These are the element categories:$(eol)"
2192 categories = list(universe.categories.keys())
2194 for category in categories:
2195 message += "$(eol) $(grn)" + category + "$(nrm)"
2196 elif arguments[0] == "files":
2197 message = "These are the current files containing the universe:$(eol)"
2198 filenames = list(universe.files.keys())
2200 for filename in filenames:
2201 if universe.files[filename].is_writeable():
2205 message += "$(eol) $(red)(" + status + ") $(grn)" + filename \
2207 elif arguments[0] == "category":
2208 if len(arguments) != 2:
2209 message = "You must specify one category."
2210 elif arguments[1] in universe.categories:
2211 message = "These are the elements in the \"" + arguments[1] \
2212 + "\" category:$(eol)"
2215 universe.categories[arguments[1]][x].key
2216 ) for x in universe.categories[arguments[1]].keys()
2219 for element in elements:
2220 message += "$(eol) $(grn)" + element + "$(nrm)"
2222 message = "Category \"" + arguments[1] + "\" does not exist."
2223 elif arguments[0] == "file":
2224 if len(arguments) != 2:
2225 message = "You must specify one file."
2226 elif arguments[1] in universe.files:
2227 message = "These are the elements in the \"" + arguments[1] \
2229 elements = universe.files[arguments[1]].data.sections()
2231 for element in elements:
2232 message += "$(eol) $(grn)" + element + "$(nrm)"
2234 message = "Category \"" + arguments[1] + "\" does not exist."
2235 elif arguments[0] == "element":
2236 if len(arguments) != 2:
2237 message = "You must specify one element."
2238 elif arguments[1] in universe.contents:
2239 element = universe.contents[arguments[1]]
2240 message = "These are the properties of the \"" + arguments[1] \
2242 "\" element (in \"" + \
2243 element.origin.filename + "\"):$(eol)"
2244 facets = element.facets()
2246 for facet in facets:
2247 message += "$(eol) $(grn)" + facet + ": $(red)" \
2248 + escape_macros(element.get(facet)) + "$(nrm)"
2250 message = "Element \"" + arguments[1] + "\" does not exist."
2251 elif arguments[0] == "result":
2252 if len(arguments) < 2:
2253 message = "You need to specify an expression."
2256 message = repr(eval(" ".join(arguments[1:])))
2258 message = "Your expression raised an exception!"
2259 elif arguments[0] == "log":
2260 if len(arguments) == 4:
2261 if re.match("^\d+$", arguments[3]) and int(arguments[3]) >= 0:
2262 stop = int(arguments[3])
2267 if len(arguments) >= 3:
2268 if re.match("^\d+$", arguments[2]) and int(arguments[2]) > 0:
2269 start = int(arguments[2])
2274 if len(arguments) >= 2:
2275 if (re.match("^\d+$", arguments[1])
2276 and 0 <= int(arguments[1]) <= 9):
2277 level = int(arguments[1])
2280 elif 0 <= actor.owner.account.getint("loglevel") <= 9:
2281 level = actor.owner.account.getint("loglevel")
2284 if level > -1 and start > -1 and stop > -1:
2285 message = get_loglines(level, start, stop)
2287 message = "When specified, level must be 0-9 (default 1), " \
2288 + "start and stop must be >=1 (default 10 and 1)."
2290 message = "I don't know what \"" + parameters + "\" is."
2294 def command_create(actor, parameters):
2295 """Create an element if it does not exist."""
2297 message = "You must at least specify an element to create."
2298 elif not actor.owner:
2301 arguments = parameters.split()
2302 if len(arguments) == 1:
2303 arguments.append("")
2304 if len(arguments) == 2:
2305 element, filename = arguments
2306 if element in universe.contents:
2307 message = "The \"" + element + "\" element already exists."
2309 message = "You create \"" + \
2310 element + "\" within the universe."
2311 logline = actor.owner.account.get(
2313 ) + " created an element: " + element
2315 logline += " in file " + filename
2316 if filename not in universe.files:
2317 message += " Warning: \"" + filename \
2318 + "\" is not yet included in any other file and will " \
2320 "not be read on startup unless this is remedied."
2321 Element(element, universe, filename)
2323 elif len(arguments) > 2:
2324 message = "You can only specify an element and a filename."
2328 def command_destroy(actor, parameters):
2329 """Destroy an element if it exists."""
2332 message = "You must specify an element to destroy."
2334 if parameters not in universe.contents:
2335 message = "The \"" + parameters + \
2336 "\" element does not exist."
2338 universe.contents[parameters].destroy()
2339 message = "You destroy \"" + parameters \
2340 + "\" within the universe."
2342 actor.owner.account.get(
2344 ) + " destroyed an element: " + parameters,
2350 def command_set(actor, parameters):
2351 """Set a facet of an element."""
2353 message = "You must specify an element, a facet and a value."
2355 arguments = parameters.split(" ", 2)
2356 if len(arguments) == 1:
2357 message = "What facet of element \"" + arguments[0] \
2358 + "\" would you like to set?"
2359 elif len(arguments) == 2:
2360 message = "What value would you like to set for the \"" \
2361 + arguments[1] + "\" facet of the \"" + arguments[0] \
2364 element, facet, value = arguments
2365 if element not in universe.contents:
2366 message = "The \"" + element + "\" element does not exist."
2368 universe.contents[element].set(facet, value)
2369 message = "You have successfully (re)set the \"" + facet \
2370 + "\" facet of element \"" + element \
2371 + "\". Try \"show element " + \
2372 element + "\" for verification."
2376 def command_delete(actor, parameters):
2377 """Delete a facet from an element."""
2379 message = "You must specify an element and a facet."
2381 arguments = parameters.split(" ")
2382 if len(arguments) == 1:
2383 message = "What facet of element \"" + arguments[0] \
2384 + "\" would you like to delete?"
2385 elif len(arguments) != 2:
2386 message = "You may only specify an element and a facet."
2388 element, facet = arguments
2389 if element not in universe.contents:
2390 message = "The \"" + element + "\" element does not exist."
2391 elif facet not in universe.contents[element].facets():
2392 message = "The \"" + element + "\" element has no \"" + facet \
2395 universe.contents[element].remove_facet(facet)
2396 message = "You have successfully deleted the \"" + facet \
2397 + "\" facet of element \"" + element \
2398 + "\". Try \"show element " + \
2399 element + "\" for verification."
2403 def command_error(actor, input_data):
2404 """Generic error for an unrecognized command word."""
2406 # 90% of the time use a generic error
2407 if random.randrange(10):
2408 message = "I'm not sure what \"" + input_data + "\" means..."
2410 # 10% of the time use the classic diku error
2412 message = "Arglebargle, glop-glyf!?!"
2414 # send the error message
2418 def daemonize(universe):
2419 """Fork and disassociate from everything."""
2421 # only if this is what we're configured to do
2422 if universe.contents["internal:process"].getboolean("daemon"):
2424 # if possible, we want to rename the process to the same as the script
2425 new_argv = b"\x00".join(x.encode("utf-8") for x in sys.argv) + b"\x00"
2426 short_argv0 = os.path.basename(sys.argv[0]).encode("utf-8") + b"\x00"
2428 # attempt the linux way first
2430 argv_array = ctypes.POINTER(ctypes.c_char_p)
2431 ctypes.pythonapi.Py_GetArgcArgv.argtypes = (
2432 ctypes.POINTER(ctypes.c_int),
2433 ctypes.POINTER(argv_array)
2436 ctypes.pythonapi.Py_GetArgcArgv(
2438 ctypes.pointer(argc)
2440 old_argv0_size = len(argc.contents.value)
2441 ctypes.memset(argc.contents, 0, len(new_argv) + old_argv0_size)
2442 ctypes.memmove(argc.contents, new_argv, len(new_argv))
2443 ctypes.CDLL(ctypes.util.find_library("c")).prctl(
2453 # since that failed, maybe it's bsd?
2456 # much simpler, since bsd has a libc function call for this
2457 ctypes.CDLL(ctypes.util.find_library("c")).setproctitle(
2463 # that didn't work either, so just log that we couldn't
2464 log("Failed to rename the interpreter process (cosmetic).")
2466 # log before we start forking around, so the terminal gets the message
2467 log("Disassociating from the controlling terminal.")
2469 # fork off and die, so we free up the controlling terminal
2473 # switch to a new process group
2476 # fork some more, this time to free us from the old process group
2480 # reset the working directory so we don't needlessly tie up mounts
2483 # clear the file creation mask so we can bend it to our will later
2486 # redirect stdin/stdout/stderr and close off their former descriptors
2487 for stdpipe in range(3):
2489 sys.stdin = codecs.open("/dev/null", "r", "utf-8")
2490 sys.__stdin__ = codecs.open("/dev/null", "r", "utf-8")
2491 sys.stdout = codecs.open("/dev/null", "w", "utf-8")
2492 sys.stderr = codecs.open("/dev/null", "w", "utf-8")
2493 sys.__stdout__ = codecs.open("/dev/null", "w", "utf-8")
2494 sys.__stderr__ = codecs.open("/dev/null", "w", "utf-8")
2497 def create_pidfile(universe):
2498 """Write a file containing the current process ID."""
2499 pid = str(os.getpid())
2500 log("Process ID: " + pid)
2501 file_name = universe.contents["internal:process"].get("pidfile")
2503 if not os.path.isabs(file_name):
2504 file_name = os.path.join(universe.startdir, file_name)
2505 file_descriptor = codecs.open(file_name, "w", "utf-8")
2506 file_descriptor.write(pid + "\n")
2507 file_descriptor.flush()
2508 file_descriptor.close()
2511 def remove_pidfile(universe):
2512 """Remove the file containing the current process ID."""
2513 file_name = universe.contents["internal:process"].get("pidfile")
2515 if not os.path.isabs(file_name):
2516 file_name = os.path.join(universe.startdir, file_name)
2517 if os.access(file_name, os.W_OK):
2518 os.remove(file_name)
2521 def excepthook(excepttype, value, tracebackdata):
2522 """Handle uncaught exceptions."""
2524 # assemble the list of errors into a single string
2526 traceback.format_exception(excepttype, value, tracebackdata)
2529 # try to log it, if possible
2535 # try to write it to stderr, if possible
2537 sys.stderr.write(message)
2542 def sighook(what, where):
2543 """Handle external signals."""
2546 message = "Caught signal: "
2548 # for a hangup signal
2549 if what == signal.SIGHUP:
2550 message += "hangup (reloading)"
2551 universe.reload_flag = True
2553 # for a terminate signal
2554 elif what == signal.SIGTERM:
2555 message += "terminate (halting)"
2556 universe.terminate_flag = True
2558 # catchall for unexpected signals
2560 message += str(what) + " (unhandled)"
2566 def override_excepthook():
2567 """Redefine sys.excepthook with our own."""
2568 sys.excepthook = excepthook
2571 def assign_sighook():
2572 """Assign a customized handler for some signals."""
2573 signal.signal(signal.SIGHUP, sighook)
2574 signal.signal(signal.SIGTERM, sighook)
2578 """This contains functions to be performed when starting the engine."""
2580 # see if a configuration file was specified
2581 if len(sys.argv) > 1:
2582 conffile = sys.argv[1]
2588 universe = Universe(conffile, True)
2590 # log an initial message
2591 log("Started mudpy with command line: " + " ".join(sys.argv))
2593 # fork and disassociate
2596 # override the default exception handler so we get logging first thing
2597 override_excepthook()
2599 # set up custom signal handlers
2603 create_pidfile(universe)
2605 # pass the initialized universe back
2610 """This contains functions to be performed when shutting down the
2613 # the loop has terminated, so save persistent data
2616 # log a final message
2617 log("Shutting down now.")
2619 # get rid of the pidfile
2620 remove_pidfile(universe)