1 # -*- coding: utf-8 -*-
2 """Miscellaneous functions for the mudpy engine."""
4 # Copyright (c) 2004-2014 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.
25 """An element of the universe."""
27 def __init__(self, key, universe, filename=None):
28 """Set up a new element."""
30 # keep track of our key name
33 # keep track of what universe it's loading into
34 self.universe = universe
36 # clone attributes if this is replacing another element
37 if self.key in self.universe.contents:
38 old_element = self.universe.contents[self.key]
39 for attribute in vars(old_element).keys():
40 exec("self." + attribute + " = old_element." + attribute)
42 self.owner.avatar = self
44 # i guess this is a new element then
47 # not owned by a user by default (used for avatars)
50 # no contents in here by default
53 # parse out appropriate category and subkey names, add to list
54 if self.key.find(":") > 0:
55 self.category, self.subkey = self.key.split(":", 1)
57 self.category = "other"
58 self.subkey = self.key
59 if self.category not in self.universe.categories:
60 self.category = "other"
61 self.subkey = self.key
63 # get an appropriate filename for the origin
65 filename = self.universe.default_origins[self.category]
66 if not os.path.isabs(filename):
67 filename = os.path.abspath(filename)
69 # add the file if it doesn't exist yet
70 if filename not in self.universe.files:
71 mudpy.data.DataFile(filename, self.universe)
73 # record or reset a pointer to the origin file
74 self.origin = self.universe.files[filename]
76 # add a data section to the origin if necessary
77 # TODO(fungi): remove this indirection after the YAML transition
78 if self.origin._format == "yaml":
79 if self.key not in self.origin.data:
80 self.origin.data[self.key] = {}
82 if not self.origin.data.has_section(self.key):
83 self.origin.data.add_section(self.key)
85 # add or replace this element in the universe
86 self.universe.contents[self.key] = self
87 self.universe.categories[self.category][self.subkey] = self
90 """Create a new element and replace this one."""
91 Element(self.key, self.universe, self.origin.filename)
95 """Remove an element from the universe and destroy it."""
96 self.origin.data.remove_section(self.key)
97 del self.universe.categories[self.category][self.subkey]
98 del self.universe.contents[self.key]
102 """Return a list of non-inherited facets for this element."""
103 # TODO(fungi): remove this indirection after the YAML transition
104 if self.origin._format == "yaml":
106 return self.origin.data[self.key].keys()
110 if self.key in self.origin.data.sections():
111 return self.origin.data.options(self.key)
115 def has_facet(self, facet):
116 """Return whether the non-inherited facet exists."""
117 return facet in self.facets()
119 def remove_facet(self, facet):
120 """Remove a facet from the element."""
121 if self.has_facet(facet):
122 self.origin.data.remove_option(self.key, facet)
123 self.origin.modified = True
126 """Return a list of the element's inheritance lineage."""
127 if self.has_facet("inherit"):
128 ancestry = self.getlist("inherit")
129 for parent in ancestry[:]:
130 ancestors = self.universe.contents[parent].ancestry()
131 for ancestor in ancestors:
132 if ancestor not in ancestry:
133 ancestry.append(ancestor)
138 def get(self, facet, default=None):
139 """Retrieve values."""
142 # TODO(fungi): remove this indirection after the YAML transition
143 if self.origin._format == "yaml":
145 return self.origin.data[self.key][facet]
148 if self.has_facet("inherit"):
149 for ancestor in self.ancestry():
150 if self.universe.contents[ancestor].has_facet(facet):
151 return self.universe.contents[ancestor].get(facet)
155 if self.origin.data.has_option(self.key, facet):
156 raw_data = self.origin.data.get(self.key, facet)
157 if raw_data.startswith("u\"") or raw_data.startswith("u'"):
158 raw_data = raw_data[1:]
159 raw_data.strip("\"'")
161 elif self.has_facet("inherit"):
162 for ancestor in self.ancestry():
163 if self.universe.contents[ancestor].has_facet(facet):
164 return self.universe.contents[ancestor].get(facet)
168 def getboolean(self, facet, default=None):
169 """Retrieve values as boolean type."""
172 # TODO(fungi): remove this indirection after the YAML transition
173 if self.origin._format == "yaml":
175 return bool(self.origin.data[self.key][facet])
178 for ancestor in self.ancestry():
180 return self.universe.contents[ancestor].getboolean(facet)
185 if self.origin.data.has_option(self.key, facet):
186 return self.origin.data.getboolean(self.key, facet)
187 elif self.has_facet("inherit"):
188 for ancestor in self.ancestry():
189 if self.universe.contents[ancestor].has_facet(facet):
190 return self.universe.contents[ancestor].getboolean(
195 def getint(self, facet, default=None):
196 """Return values as int type."""
199 if self.origin.data.has_option(self.key, facet):
200 return self.origin.data.getint(self.key, facet)
201 elif self.has_facet("inherit"):
202 for ancestor in self.ancestry():
203 if self.universe.contents[ancestor].has_facet(facet):
204 return self.universe.contents[ancestor].getint(facet)
208 def getfloat(self, facet, default=None):
209 """Return values as float type."""
212 if self.origin.data.has_option(self.key, facet):
213 return self.origin.data.getfloat(self.key, facet)
214 elif self.has_facet("inherit"):
215 for ancestor in self.ancestry():
216 if self.universe.contents[ancestor].has_facet(facet):
217 return self.universe.contents[ancestor].getfloat(facet)
221 def getlist(self, facet, default=None):
222 """Return values as list type."""
225 value = self.get(facet)
227 return mudpy.data.makelist(value)
231 def getdict(self, facet, default=None):
232 """Return values as dict type."""
235 value = self.get(facet)
237 return mudpy.data.makedict(value)
241 def set(self, facet, value):
243 if not self.has_facet(facet) or not self.get(facet) == value:
244 if not type(value) is str:
246 self.origin.data.set(self.key, facet, value)
247 self.origin.modified = True
249 def append(self, facet, value):
250 """Append value to a list."""
251 if not type(value) is str:
253 newlist = self.getlist(facet)
254 newlist.append(value)
255 self.set(facet, newlist)
265 add_terminator=False,
268 """Convenience method to pass messages to an owner."""
281 def can_run(self, command):
282 """Check if the user can run this command object."""
284 # has to be in the commands category
285 if command not in self.universe.categories["command"].values():
288 # avatars of administrators can run any command
289 elif self.owner and self.owner.account.getboolean("administrator"):
292 # everyone can run non-administrative commands
293 elif not command.getboolean("administrative"):
296 # otherwise the command cannot be run by this actor
300 # pass back the result
303 def update_location(self):
304 """Make sure the location's contents contain this element."""
305 area = self.get("location")
306 if area in self.universe.contents:
307 self.universe.contents[area].contents[self.key] = self
309 def clean_contents(self):
310 """Make sure the element's contents aren't bogus."""
311 for element in self.contents.values():
312 if element.get("location") != self.key:
313 del self.contents[element.key]
315 def go_to(self, area):
316 """Relocate the element to a specific area."""
317 current = self.get("location")
318 if current and self.key in self.universe.contents[current].contents:
319 del universe.contents[current].contents[self.key]
320 if area in self.universe.contents:
321 self.set("location", area)
322 self.universe.contents[area].contents[self.key] = self
326 """Relocate the element to its default location."""
327 self.go_to(self.get("default_location"))
328 self.echo_to_location(
329 "You suddenly realize that " + self.get("name") + " is here."
332 def move_direction(self, direction):
333 """Relocate the element in a specified direction."""
334 self.echo_to_location(
337 ) + " exits " + self.universe.categories[
348 "You exit " + self.universe.categories[
360 self.universe.contents[
361 self.get("location")].link_neighbor(direction)
363 self.echo_to_location(
366 ) + " arrives from " + self.universe.categories[
377 def look_at(self, key):
378 """Show an element to another element."""
380 element = self.universe.contents[key]
382 name = element.get("name")
384 message += "$(cyn)" + name + "$(nrm)$(eol)"
385 description = element.get("description")
387 message += description + "$(eol)"
388 portal_list = list(element.portals().keys())
391 message += "$(cyn)[ Exits: " + ", ".join(
394 for element in self.universe.contents[
397 if element.getboolean("is_actor") and element is not self:
398 message += "$(yel)" + element.get(
400 ) + " is here.$(nrm)$(eol)"
401 elif element is not self:
402 message += "$(grn)" + element.get(
408 """Map the portal directions for an area to neighbors."""
410 if re.match("""^area:-?\d+,-?\d+,-?\d+$""", self.key):
411 coordinates = [(int(x))
412 for x in self.key.split(":")[1].split(",")]
413 directions = self.universe.categories["internal"]["directions"]
417 x, directions.getdict(x)["vector"]
418 ) for x in directions.facets()
421 for portal in self.getlist("gridlinks"):
422 adjacent = map(lambda c, o: c + o,
423 coordinates, offsets[portal])
424 neighbor = "area:" + ",".join(
425 [(str(x)) for x in adjacent]
427 if neighbor in self.universe.contents:
428 portals[portal] = neighbor
429 for facet in self.facets():
430 if facet.startswith("link_"):
431 neighbor = self.get(facet)
432 if neighbor in self.universe.contents:
433 portal = facet.split("_")[1]
434 portals[portal] = neighbor
437 def link_neighbor(self, direction):
438 """Return the element linked in a given direction."""
439 portals = self.portals()
440 if direction in portals:
441 return portals[direction]
443 def echo_to_location(self, message):
444 """Show a message to other elements in the current location."""
445 for element in self.universe.contents[
448 if element is not self:
449 element.send(message)
456 def __init__(self, filename="", load=False):
457 """Initialize the universe."""
460 self.default_origins = {}
462 self.private_files = []
463 self.reload_flag = False
464 self.startdir = os.getcwd()
465 self.terminate_flag = False
468 possible_filenames = [
474 "/usr/local/mudpy/mudpy.conf",
475 "/usr/local/mudpy/etc/mudpy.conf",
476 "/etc/mudpy/mudpy.conf",
479 for filename in possible_filenames:
480 if os.access(filename, os.R_OK):
482 if not os.path.isabs(filename):
483 filename = os.path.join(self.startdir, filename)
484 self.filename = filename
489 """Load universe data from persistent storage."""
491 # the files dict must exist and filename needs to be read-only
495 self.filename in self.files and self.files[
500 # clear out all read-only files
501 if hasattr(self, "files"):
502 for data_filename in list(self.files.keys()):
503 if not self.files[data_filename].is_writeable():
504 del self.files[data_filename]
506 # start loading from the initial file
507 mudpy.data.DataFile(self.filename, self)
509 # make a list of inactive avatars
510 inactive_avatars = []
511 for account in self.categories["account"].values():
512 inactive_avatars += [
513 (self.contents[x]) for x in account.getlist("avatars")
515 for user in self.userlist:
516 if user.avatar in inactive_avatars:
517 inactive_avatars.remove(user.avatar)
519 # go through all elements to clear out inactive avatar locations
520 for element in self.contents.values():
521 area = element.get("location")
522 if element in inactive_avatars and area:
523 if area in self.contents and element.key in self.contents[
526 del self.contents[area].contents[element.key]
527 element.set("default_location", area)
528 element.remove_facet("location")
530 # another pass to straighten out all the element contents
531 for element in self.contents.values():
532 element.update_location()
533 element.clean_contents()
536 """Create a new, empty Universe (the Big Bang)."""
537 new_universe = Universe()
538 for attribute in vars(self).keys():
539 exec("new_universe." + attribute + " = self." + attribute)
540 new_universe.reload_flag = False
545 """Save the universe to persistent storage."""
546 for key in self.files:
547 self.files[key].save()
549 def initialize_server_socket(self):
550 """Create and open the listening socket."""
552 # need to know the local address and port number for the listener
553 host = self.categories["internal"]["network"].get("host")
554 port = self.categories["internal"]["network"].getint("port")
556 # if no host was specified, bind to all local addresses (preferring
564 # figure out if this is ipv4 or v6
565 family = socket.getaddrinfo(host, port)[0][0]
566 if family is socket.AF_INET6 and not socket.has_ipv6:
567 log("No support for IPv6 address %s (use IPv4 instead)." % host)
569 # create a new stream-type socket object
570 self.listening_socket = socket.socket(family, socket.SOCK_STREAM)
572 # set the socket options to allow existing open ones to be
573 # reused (fixes a bug where the server can't bind for a minute
574 # when restarting on linux systems)
575 self.listening_socket.setsockopt(
576 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
579 # bind the socket to to our desired server ipa and port
580 self.listening_socket.bind((host, port))
582 # disable blocking so we can proceed whether or not we can
584 self.listening_socket.setblocking(0)
586 # start listening on the socket
587 self.listening_socket.listen(1)
589 # note that we're now ready for user connections
591 "Listening for Telnet connections on: " +
592 host + ":" + str(port)
596 """Convenience method to get the elapsed time counter."""
597 return self.categories["internal"]["counters"].getint("elapsed")
602 """This is a connected user."""
605 """Default values for the in-memory user variables."""
608 self.authenticated = False
611 self.connection = None
613 self.input_queue = []
614 self.last_address = ""
615 self.last_input = universe.get_time()
616 self.menu_choices = {}
617 self.menu_seen = False
618 self.negotiation_pause = 0
619 self.output_queue = []
620 self.partial_input = b""
621 self.password_tries = 0
622 self.state = "initial"
626 """Log, close the connection and remove."""
628 name = self.account.get("name")
632 message = "User " + name
634 message = "An unnamed user"
635 message += " logged out."
637 self.deactivate_avatar()
638 self.connection.close()
641 def check_idle(self):
642 """Warn or disconnect idle users as appropriate."""
643 idletime = universe.get_time() - self.last_input
644 linkdead_dict = universe.categories["internal"]["time"].getdict(
647 if self.state in linkdead_dict:
648 linkdead_state = self.state
650 linkdead_state = "default"
651 if idletime > linkdead_dict[linkdead_state]:
653 "$(eol)$(red)You've done nothing for far too long... goodbye!"
658 logline = "Disconnecting "
659 if self.account and self.account.get("name"):
660 logline += self.account.get("name")
662 logline += "an unknown user"
663 logline += (" after idling too long in the " + self.state
666 self.state = "disconnecting"
667 self.menu_seen = False
668 idle_dict = universe.categories["internal"]["time"].getdict("idle")
669 if self.state in idle_dict:
670 idle_state = self.state
672 idle_state = "default"
673 if idletime == idle_dict[idle_state]:
675 "$(eol)$(red)If you continue to be unproductive, "
676 + "you'll be shown the door...$(nrm)$(eol)"
680 """Save, load a new user and relocate the connection."""
682 # get out of the list
685 # create a new user object
688 # set everything equivalent
689 for attribute in vars(self).keys():
690 exec("new_user." + attribute + " = self." + attribute)
692 # the avatar needs a new owner
694 new_user.avatar.owner = new_user
697 universe.userlist.append(new_user)
699 # get rid of the old user object
702 def replace_old_connections(self):
703 """Disconnect active users with the same name."""
705 # the default return value
708 # iterate over each user in the list
709 for old_user in universe.userlist:
711 # the name is the same but it's not us
714 ) and old_user.account and old_user.account.get(
716 ) == self.account.get(
718 ) and old_user is not self:
722 "User " + self.account.get(
724 ) + " reconnected--closing old connection to "
725 + old_user.address + ".",
729 "$(eol)$(red)New connection from " + self.address
730 + ". Terminating old connection...$(nrm)$(eol)",
735 # close the old connection
736 old_user.connection.close()
738 # replace the old connection with this one
740 "$(eol)$(red)Taking over old connection from "
741 + old_user.address + ".$(nrm)"
743 old_user.connection = self.connection
744 old_user.last_address = old_user.address
745 old_user.address = self.address
747 # take this one out of the list and delete
753 # true if an old connection was replaced, false if not
756 def authenticate(self):
757 """Flag the user as authenticated and disconnect duplicates."""
758 if self.state is not "authenticated":
759 log("User " + self.account.get("name") + " logged in.", 2)
760 self.authenticated = True
761 if self.account.subkey in universe.categories[
768 self.account.set("administrator", "True")
771 """Send the user their current menu."""
772 if not self.menu_seen:
773 self.menu_choices = get_menu_choices(self)
775 get_menu(self.state, self.error, self.menu_choices),
779 self.menu_seen = True
781 self.adjust_echoing()
783 def adjust_echoing(self):
784 """Adjust echoing to match state menu requirements."""
785 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_ECHO,
787 if menu_echo_on(self.state):
788 mudpy.telnet.disable(self, mudpy.telnet.TELOPT_ECHO,
790 elif not menu_echo_on(self.state):
791 mudpy.telnet.enable(self, mudpy.telnet.TELOPT_ECHO,
795 """Remove a user from the list of connected users."""
796 universe.userlist.remove(self)
806 add_terminator=False,
809 """Send arbitrary text to a connected user."""
811 # unless raw mode is on, clean it up all nice and pretty
814 # strip extra $(eol) off if present
815 while output.startswith("$(eol)"):
817 while output.endswith("$(eol)"):
819 extra_lines = output.find("$(eol)$(eol)$(eol)")
820 while extra_lines > -1:
821 output = output[:extra_lines] + output[extra_lines + 6:]
822 extra_lines = output.find("$(eol)$(eol)$(eol)")
824 # start with a newline, append the message, then end
825 # with the optional eol string passed to this function
826 # and the ansi escape to return to normal text
827 if not just_prompt and prepend_padding:
828 if (not self.output_queue or not
829 self.output_queue[-1].endswith(b"\r\n")):
830 output = "$(eol)" + output
831 elif not self.output_queue[-1].endswith(
833 ) and not self.output_queue[-1].endswith(
836 output = "$(eol)" + output
837 output += eol + chr(27) + "[0m"
839 # tack on a prompt if active
840 if self.state == "active":
845 mode = self.avatar.get("mode")
847 output += "(" + mode + ") "
849 # find and replace macros in the output
850 output = replace_macros(self, output)
852 # wrap the text at the client's width (min 40, 0 disables)
854 if self.columns < 40:
858 output = wrap_ansi_text(output, wrap)
860 # if supported by the client, encode it utf-8
861 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
863 encoded_output = output.encode("utf-8")
865 # otherwise just send ascii
867 encoded_output = output.encode("ascii", "replace")
869 # end with a terminator if requested
870 if add_prompt or add_terminator:
871 if mudpy.telnet.is_enabled(
872 self, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US):
873 encoded_output += mudpy.telnet.telnet_proto(
874 mudpy.telnet.IAC, mudpy.telnet.EOR)
875 elif not mudpy.telnet.is_enabled(
876 self, mudpy.telnet.TELOPT_SGA, mudpy.telnet.US):
877 encoded_output += mudpy.telnet.telnet_proto(
878 mudpy.telnet.IAC, mudpy.telnet.GA)
880 # and tack it onto the queue
881 self.output_queue.append(encoded_output)
883 # if this is urgent, flush all pending output
887 # just dump raw bytes as requested
889 self.output_queue.append(output)
893 """All the things to do to the user per increment."""
895 # if the world is terminating, disconnect
896 if universe.terminate_flag:
897 self.state = "disconnecting"
898 self.menu_seen = False
900 # check for an idle connection and act appropriately
904 # if output is paused, decrement the counter
905 if self.state == "initial":
906 if self.negotiation_pause:
907 self.negotiation_pause -= 1
909 self.state = "entering_account_name"
911 # show the user a menu as needed
912 elif not self.state == "active":
915 # flush any pending output in the queue
918 # disconnect users with the appropriate state
919 if self.state == "disconnecting":
922 # check for input and add it to the queue
925 # there is input waiting in the queue
927 handle_user_input(self)
930 """Try to send the last item in the queue and remove it."""
931 if self.output_queue:
933 self.connection.send(self.output_queue[0])
934 del self.output_queue[0]
935 except BrokenPipeError:
936 if self.account and self.account.get("name"):
937 account = self.account.get("name")
939 account = "an unknown user"
940 log("Broken pipe sending to %s." % account, 7)
941 self.state = "disconnecting"
943 def enqueue_input(self):
944 """Process and enqueue any new input."""
946 # check for some input
948 raw_input = self.connection.recv(1024)
949 except (BlockingIOError, OSError):
955 # tack this on to any previous partial
956 self.partial_input += raw_input
958 # reply to and remove any IAC negotiation codes
959 mudpy.telnet.negotiate_telnet_options(self)
961 # separate multiple input lines
962 new_input_lines = self.partial_input.split(b"\n")
964 # if input doesn't end in a newline, replace the
965 # held partial input with the last line of it
966 if not self.partial_input.endswith(b"\n"):
967 self.partial_input = new_input_lines.pop()
969 # otherwise, chop off the extra null input and reset
970 # the held partial input
972 new_input_lines.pop()
973 self.partial_input = b""
975 # iterate over the remaining lines
976 for line in new_input_lines:
978 # strip off extra whitespace
981 # log non-printable characters remaining
982 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
984 asciiline = b"".join(
985 filter(lambda x: b" " <= x <= b"~", line))
986 if line != asciiline:
987 logline = "Non-ASCII characters from "
988 if self.account and self.account.get("name"):
989 logline += self.account.get("name") + ": "
991 logline += "unknown user: "
992 logline += repr(line)
997 line = line.decode("utf-8")
998 except UnicodeDecodeError:
999 logline = "Non-UTF-8 characters from "
1000 if self.account and self.account.get("name"):
1001 logline += self.account.get("name") + ": "
1003 logline += "unknown user: "
1004 logline += repr(line)
1008 line = unicodedata.normalize("NFKC", line)
1010 # put on the end of the queue
1011 self.input_queue.append(line)
1013 def new_avatar(self):
1014 """Instantiate a new, unconfigured avatar for this user."""
1016 while "avatar:" + self.account.get("name") + ":" + str(
1018 ) in universe.categories["actor"].keys():
1020 self.avatar = Element(
1021 "actor:avatar:" + self.account.get("name") + ":" + str(
1026 self.avatar.append("inherit", "archetype:avatar")
1027 self.account.append("avatars", self.avatar.key)
1029 def delete_avatar(self, avatar):
1030 """Remove an avatar from the world and from the user's list."""
1031 if self.avatar is universe.contents[avatar]:
1033 universe.contents[avatar].destroy()
1034 avatars = self.account.getlist("avatars")
1035 avatars.remove(avatar)
1036 self.account.set("avatars", avatars)
1038 def activate_avatar_by_index(self, index):
1039 """Enter the world with a particular indexed avatar."""
1040 self.avatar = universe.contents[
1041 self.account.getlist("avatars")[index]]
1042 self.avatar.owner = self
1043 self.state = "active"
1044 self.avatar.go_home()
1046 def deactivate_avatar(self):
1047 """Have the active avatar leave the world."""
1049 current = self.avatar.get("location")
1051 self.avatar.set("default_location", current)
1052 self.avatar.echo_to_location(
1053 "You suddenly wonder where " + self.avatar.get(
1057 del universe.contents[current].contents[self.avatar.key]
1058 self.avatar.remove_facet("location")
1059 self.avatar.owner = None
1063 """Destroy the user and associated avatars."""
1064 for avatar in self.account.getlist("avatars"):
1065 self.delete_avatar(avatar)
1066 self.account.destroy()
1068 def list_avatar_names(self):
1069 """List names of assigned avatars."""
1071 universe.contents[avatar].get(
1073 ) for avatar in self.account.getlist("avatars")
1077 def broadcast(message, add_prompt=True):
1078 """Send a message to all connected users."""
1079 for each_user in universe.userlist:
1080 each_user.send("$(eol)" + message, add_prompt=add_prompt)
1083 def log(message, level=0):
1084 """Log a message."""
1086 # a couple references we need
1087 file_name = universe.categories["internal"]["logging"].get("file")
1088 max_log_lines = universe.categories["internal"]["logging"].getint(
1091 syslog_name = universe.categories["internal"]["logging"].get("syslog")
1092 timestamp = time.asctime()[4:19]
1094 # turn the message into a list of lines
1096 lambda x: x != "", [(x.rstrip()) for x in message.split("\n")]
1099 # send the timestamp and line to a file
1101 if not os.path.isabs(file_name):
1102 file_name = os.path.join(universe.startdir, file_name)
1103 file_descriptor = codecs.open(file_name, "a", "utf-8")
1105 file_descriptor.write(timestamp + " " + line + "\n")
1106 file_descriptor.flush()
1107 file_descriptor.close()
1109 # send the timestamp and line to standard output
1110 if universe.categories["internal"]["logging"].getboolean("stdout"):
1112 print(timestamp + " " + line)
1114 # send the line to the system log
1117 syslog_name.encode("utf-8"),
1119 syslog.LOG_INFO | syslog.LOG_DAEMON
1125 # display to connected administrators
1126 for user in universe.userlist:
1127 if user.state == "active" and user.account.getboolean(
1129 ) and user.account.getint("loglevel") <= level:
1130 # iterate over every line in the message
1134 "$(bld)$(red)" + timestamp + " "
1135 + line.replace("$(", "$_(") + "$(nrm)$(eol)")
1136 user.send(full_message, flush=True)
1138 # add to the recent log list
1140 while 0 < len(universe.loglines) >= max_log_lines:
1141 del universe.loglines[0]
1142 universe.loglines.append((level, timestamp + " " + line))
1145 def get_loglines(level, start, stop):
1146 """Return a specific range of loglines filtered by level."""
1148 # filter the log lines
1149 loglines = filter(lambda x: x[0] >= level, universe.loglines)
1151 # we need these in several places
1152 total_count = str(len(universe.loglines))
1153 filtered_count = len(loglines)
1155 # don't proceed if there are no lines
1158 # can't start before the begining or at the end
1159 if start > filtered_count:
1160 start = filtered_count
1164 # can't stop before we start
1171 message = "There are " + str(total_count)
1172 message += " log lines in memory and " + str(filtered_count)
1173 message += " at or above level " + str(level) + "."
1174 message += " The matching lines from " + str(stop) + " to "
1175 message += str(start) + " are:$(eol)$(eol)"
1177 # add the text from the selected lines
1179 range_lines = loglines[-start:-(stop - 1)]
1181 range_lines = loglines[-start:]
1182 for line in range_lines:
1183 message += " (" + str(line[0]) + ") " + line[1].replace(
1187 # there were no lines
1189 message = "None of the " + str(total_count)
1190 message += " lines in memory matches your request."
1196 def glyph_columns(character):
1197 """Convenience function to return the column width of a glyph."""
1198 if unicodedata.east_asian_width(character) in "FW":
1204 def wrap_ansi_text(text, width):
1205 """Wrap text with arbitrary width while ignoring ANSI colors."""
1207 # the current position in the entire text string, including all
1208 # characters, printable or otherwise
1211 # the current text position relative to the begining of the line,
1212 # ignoring color escape sequences
1215 # the absolute position of the most recent whitespace character
1218 # whether the current character is part of a color escape sequence
1221 # normalize any potentially composited unicode before we count it
1222 text = unicodedata.normalize("NFKC", text)
1224 # iterate over each character from the begining of the text
1225 for each_character in text:
1227 # the current character is the escape character
1228 if each_character == "\x1b" and not escape:
1231 # the current character is within an escape sequence
1234 # the current character is m, which terminates the
1236 if each_character == "m":
1239 # the current character is a newline, so reset the relative
1240 # position (start a new line)
1241 elif each_character == "\n":
1243 last_whitespace = abs_pos
1245 # the current character meets the requested maximum line width,
1246 # so we need to backtrack and find a space at which to wrap;
1247 # special care is taken to avoid an off-by-one in case the
1248 # current character is a double-width glyph
1249 elif each_character != "\r" and (
1250 rel_pos >= width or (
1251 rel_pos >= width - 1 and glyph_columns(
1257 # it's always possible we landed on whitespace
1258 if unicodedata.category(each_character) in ("Cc", "Zs"):
1259 last_whitespace = abs_pos
1261 # insert an eol in place of the space
1262 text = text[:last_whitespace] + "\r\n" + text[last_whitespace + 1:]
1264 # increase the absolute position because an eol is two
1265 # characters but the space it replaced was only one
1268 # now we're at the begining of a new line, plus the
1269 # number of characters wrapped from the previous line
1271 for remaining_characters in text[last_whitespace:abs_pos]:
1272 rel_pos += glyph_columns(remaining_characters)
1274 # as long as the character is not a carriage return and the
1275 # other above conditions haven't been met, count it as a
1276 # printable character
1277 elif each_character != "\r":
1278 rel_pos += glyph_columns(each_character)
1279 if unicodedata.category(each_character) in ("Cc", "Zs"):
1280 last_whitespace = abs_pos
1282 # increase the absolute position for every character
1285 # return the newly-wrapped text
1289 def weighted_choice(data):
1290 """Takes a dict weighted by value and returns a random key."""
1292 # this will hold our expanded list of keys from the data
1295 # create the expanded list of keys
1296 for key in data.keys():
1297 for count in range(data[key]):
1298 expanded.append(key)
1300 # return one at random
1301 return random.choice(expanded)
1305 """Returns a random character name."""
1307 # the vowels and consonants needed to create romaji syllables
1336 # this dict will hold our weighted list of syllables
1339 # generate the list with an even weighting
1340 for consonant in consonants:
1341 for vowel in vowels:
1342 syllables[consonant + vowel] = 1
1344 # we'll build the name into this string
1347 # create a name of random length from the syllables
1348 for syllable in range(random.randrange(2, 6)):
1349 name += weighted_choice(syllables)
1351 # strip any leading quotemark, capitalize and return the name
1352 return name.strip("'").capitalize()
1355 def replace_macros(user, text, is_input=False):
1356 """Replaces macros in text output."""
1358 # third person pronouns
1360 "female": {"obj": "her", "pos": "hers", "sub": "she"},
1361 "male": {"obj": "him", "pos": "his", "sub": "he"},
1362 "neuter": {"obj": "it", "pos": "its", "sub": "it"}
1365 # a dict of replacement macros
1368 "bld": chr(27) + "[1m",
1369 "nrm": chr(27) + "[0m",
1370 "blk": chr(27) + "[30m",
1371 "blu": chr(27) + "[34m",
1372 "cyn": chr(27) + "[36m",
1373 "grn": chr(27) + "[32m",
1374 "mgt": chr(27) + "[35m",
1375 "red": chr(27) + "[31m",
1376 "yel": chr(27) + "[33m",
1379 # add dynamic macros where possible
1381 account_name = user.account.get("name")
1383 macros["account"] = account_name
1385 avatar_gender = user.avatar.get("gender")
1387 macros["tpop"] = pronouns[avatar_gender]["obj"]
1388 macros["tppp"] = pronouns[avatar_gender]["pos"]
1389 macros["tpsp"] = pronouns[avatar_gender]["sub"]
1394 # find and replace per the macros dict
1395 macro_start = text.find("$(")
1396 if macro_start == -1:
1398 macro_end = text.find(")", macro_start) + 1
1399 macro = text[macro_start + 2:macro_end - 1]
1400 if macro in macros.keys():
1401 replacement = macros[macro]
1403 # this is how we handle local file inclusion (dangerous!)
1404 elif macro.startswith("inc:"):
1405 incfile = mudpy.data.find_file(macro[4:], universe=universe)
1406 if os.path.exists(incfile):
1407 incfd = codecs.open(incfile, "r", "utf-8")
1410 if line.endswith("\n") and not line.endswith("\r\n"):
1411 line = line.replace("\n", "\r\n")
1413 # lose the trailing eol
1414 replacement = replacement[:-2]
1417 log("Couldn't read included " + incfile + " file.", 6)
1419 # if we get here, log and replace it with null
1423 log("Unexpected replacement macro " +
1424 macro + " encountered.", 6)
1426 # and now we act on the replacement
1427 text = text.replace("$(" + macro + ")", replacement)
1429 # replace the look-like-a-macro sequence
1430 text = text.replace("$_(", "$(")
1435 def escape_macros(text):
1436 """Escapes replacement macros in text."""
1437 return text.replace("$(", "$_(")
1440 def first_word(text, separator=" "):
1441 """Returns a tuple of the first word and the rest."""
1443 if text.find(separator) > 0:
1444 return text.split(separator, 1)
1452 """The things which should happen on each pulse, aside from reloads."""
1454 # open the listening socket if it hasn't been already
1455 if not hasattr(universe, "listening_socket"):
1456 universe.initialize_server_socket()
1458 # assign a user if a new connection is waiting
1459 user = check_for_connection(universe.listening_socket)
1461 universe.userlist.append(user)
1463 # iterate over the connected users
1464 for user in universe.userlist:
1467 # add an element for counters if it doesn't exist
1468 if "counters" not in universe.categories["internal"]:
1469 universe.categories["internal"]["counters"] = Element(
1470 "internal:counters", universe
1473 # update the log every now and then
1474 if not universe.categories["internal"]["counters"].getint("mark"):
1475 log(str(len(universe.userlist)) + " connection(s)")
1476 universe.categories["internal"]["counters"].set(
1477 "mark", universe.categories["internal"]["time"].getint(
1482 universe.categories["internal"]["counters"].set(
1483 "mark", universe.categories["internal"]["counters"].getint(
1488 # periodically save everything
1489 if not universe.categories["internal"]["counters"].getint("save"):
1491 universe.categories["internal"]["counters"].set(
1492 "save", universe.categories["internal"]["time"].getint(
1497 universe.categories["internal"]["counters"].set(
1498 "save", universe.categories["internal"]["counters"].getint(
1503 # pause for a configurable amount of time (decimal seconds)
1504 time.sleep(universe.categories["internal"]
1505 ["time"].getfloat("increment"))
1507 # increase the elapsed increment counter
1508 universe.categories["internal"]["counters"].set(
1509 "elapsed", universe.categories["internal"]["counters"].getint(
1516 """Reload all relevant objects."""
1517 for user in universe.userlist[:]:
1519 for element in universe.contents.values():
1520 if element.origin.is_writeable():
1525 def check_for_connection(listening_socket):
1526 """Check for a waiting connection and return a new user object."""
1528 # try to accept a new connection
1530 connection, address = listening_socket.accept()
1531 except BlockingIOError:
1534 # note that we got one
1535 log("Connection from " + address[0], 2)
1537 # disable blocking so we can proceed whether or not we can send/receive
1538 connection.setblocking(0)
1540 # create a new user object
1543 # associate this connection with it
1544 user.connection = connection
1546 # set the user's ipa from the connection's ipa
1547 user.address = address[0]
1549 # let the client know we WILL EOR (RFC 885)
1550 mudpy.telnet.enable(user, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US)
1551 user.negotiation_pause = 2
1553 # return the new user object
1557 def get_menu(state, error=None, choices=None):
1558 """Show the correct menu text to a user."""
1560 # make sure we don't reuse a mutable sequence by default
1564 # get the description or error text
1565 message = get_menu_description(state, error)
1567 # get menu choices for the current state
1568 message += get_formatted_menu_choices(state, choices)
1570 # try to get a prompt, if it was defined
1571 message += get_menu_prompt(state)
1573 # throw in the default choice, if it exists
1574 message += get_formatted_default_menu_choice(state)
1576 # display a message indicating if echo is off
1577 message += get_echo_message(state)
1579 # return the assembly of various strings defined above
1583 def menu_echo_on(state):
1584 """True if echo is on, false if it is off."""
1585 return universe.categories["menu"][state].getboolean("echo", True)
1588 def get_echo_message(state):
1589 """Return a message indicating that echo is off."""
1590 if menu_echo_on(state):
1593 return "(won't echo) "
1596 def get_default_menu_choice(state):
1597 """Return the default choice for a menu."""
1598 return universe.categories["menu"][state].get("default")
1601 def get_formatted_default_menu_choice(state):
1602 """Default menu choice foratted for inclusion in a prompt string."""
1603 default_choice = get_default_menu_choice(state)
1605 return "[$(red)" + default_choice + "$(nrm)] "
1610 def get_menu_description(state, error):
1611 """Get the description or error text."""
1613 # an error condition was raised by the handler
1616 # try to get an error message matching the condition
1618 description = universe.categories[
1619 "menu"][state].get("error_" + error)
1621 description = "That is not a valid choice..."
1622 description = "$(red)" + description + "$(nrm)"
1624 # there was no error condition
1627 # try to get a menu description for the current state
1628 description = universe.categories["menu"][state].get("description")
1630 # return the description or error message
1632 description += "$(eol)$(eol)"
1636 def get_menu_prompt(state):
1637 """Try to get a prompt, if it was defined."""
1638 prompt = universe.categories["menu"][state].get("prompt")
1644 def get_menu_choices(user):
1645 """Return a dict of choice:meaning."""
1646 menu = universe.categories["menu"][user.state]
1647 create_choices = menu.get("create")
1649 choices = eval(create_choices)
1655 for facet in menu.facets():
1656 if facet.startswith("demand_") and not eval(
1657 universe.categories["menu"][user.state].get(facet)
1659 ignores.append(facet.split("_", 2)[1])
1660 elif facet.startswith("create_"):
1661 creates[facet] = facet.split("_", 2)[1]
1662 elif facet.startswith("choice_"):
1663 options[facet] = facet.split("_", 2)[1]
1664 for facet in creates.keys():
1665 if not creates[facet] in ignores:
1666 choices[creates[facet]] = eval(menu.get(facet))
1667 for facet in options.keys():
1668 if not options[facet] in ignores:
1669 choices[options[facet]] = menu.get(facet)
1673 def get_formatted_menu_choices(state, choices):
1674 """Returns a formatted string of menu choices."""
1676 choice_keys = list(choices.keys())
1678 for choice in choice_keys:
1679 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[
1683 choice_output += "$(eol)"
1684 return choice_output
1687 def get_menu_branches(state):
1688 """Return a dict of choice:branch."""
1690 for facet in universe.categories["menu"][state].facets():
1691 if facet.startswith("branch_"):
1693 facet.split("_", 2)[1]
1694 ] = universe.categories["menu"][state].get(facet)
1698 def get_default_branch(state):
1699 """Return the default branch."""
1700 return universe.categories["menu"][state].get("branch")
1703 def get_choice_branch(user, choice):
1704 """Returns the new state matching the given choice."""
1705 branches = get_menu_branches(user.state)
1706 if choice in branches.keys():
1707 return branches[choice]
1708 elif choice in user.menu_choices.keys():
1709 return get_default_branch(user.state)
1714 def get_menu_actions(state):
1715 """Return a dict of choice:branch."""
1717 for facet in universe.categories["menu"][state].facets():
1718 if facet.startswith("action_"):
1720 facet.split("_", 2)[1]
1721 ] = universe.categories["menu"][state].get(facet)
1725 def get_default_action(state):
1726 """Return the default action."""
1727 return universe.categories["menu"][state].get("action")
1730 def get_choice_action(user, choice):
1731 """Run any indicated script for the given choice."""
1732 actions = get_menu_actions(user.state)
1733 if choice in actions.keys():
1734 return actions[choice]
1735 elif choice in user.menu_choices.keys():
1736 return get_default_action(user.state)
1741 def handle_user_input(user):
1742 """The main handler, branches to a state-specific handler."""
1744 # if the user's client echo is off, send a blank line for aesthetics
1745 if mudpy.telnet.is_enabled(user, mudpy.telnet.TELOPT_ECHO,
1747 user.send("", add_prompt=False, prepend_padding=False)
1749 # check to make sure the state is expected, then call that handler
1750 if "handler_" + user.state in globals():
1751 exec("handler_" + user.state + "(user)")
1753 generic_menu_handler(user)
1755 # since we got input, flag that the menu/prompt needs to be redisplayed
1756 user.menu_seen = False
1758 # update the last_input timestamp while we're at it
1759 user.last_input = universe.get_time()
1762 def generic_menu_handler(user):
1763 """A generic menu choice handler."""
1765 # get a lower-case representation of the next line of input
1766 if user.input_queue:
1767 choice = user.input_queue.pop(0)
1769 choice = choice.lower()
1773 choice = get_default_menu_choice(user.state)
1774 if choice in user.menu_choices:
1775 exec(get_choice_action(user, choice))
1776 new_state = get_choice_branch(user, choice)
1778 user.state = new_state
1780 user.error = "default"
1783 def handler_entering_account_name(user):
1784 """Handle the login account name."""
1786 # get the next waiting line of input
1787 input_data = user.input_queue.pop(0)
1789 # did the user enter anything?
1792 # keep only the first word and convert to lower-case
1793 name = input_data.lower()
1795 # fail if there are non-alphanumeric characters
1796 if name != "".join(filter(
1797 lambda x: x >= "0" and x <= "9" or x >= "a" and x <= "z",
1799 user.error = "bad_name"
1801 # if that account exists, time to request a password
1802 elif name in universe.categories["account"]:
1803 user.account = universe.categories["account"][name]
1804 user.state = "checking_password"
1806 # otherwise, this could be a brand new user
1808 user.account = Element("account:" + name, universe)
1809 user.account.set("name", name)
1810 log("New user: " + name, 2)
1811 user.state = "checking_new_account_name"
1813 # if the user entered nothing for a name, then buhbye
1815 user.state = "disconnecting"
1818 def handler_checking_password(user):
1819 """Handle the login account password."""
1821 # get the next waiting line of input
1822 input_data = user.input_queue.pop(0)
1824 # does the hashed input equal the stored hash?
1825 if mudpy.password.verify(input_data, user.account.get("passhash")):
1827 # if so, set the username and load from cold storage
1828 if not user.replace_old_connections():
1830 user.state = "main_utility"
1832 # if at first your hashes don't match, try, try again
1833 elif user.password_tries < universe.categories[
1840 user.password_tries += 1
1841 user.error = "incorrect"
1843 # we've exceeded the maximum number of password failures, so disconnect
1846 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1848 user.state = "disconnecting"
1851 def handler_entering_new_password(user):
1852 """Handle a new password entry."""
1854 # get the next waiting line of input
1855 input_data = user.input_queue.pop(0)
1857 # make sure the password is strong--at least one upper, one lower and
1858 # one digit, seven or more characters in length
1859 if len(input_data) > 6 and len(
1860 list(filter(lambda x: x >= "0" and x <= "9", input_data))
1862 list(filter(lambda x: x >= "A" and x <= "Z", input_data))
1864 list(filter(lambda x: x >= "a" and x <= "z", input_data))
1867 # hash and store it, then move on to verification
1868 user.account.set("passhash", mudpy.password.create(input_data))
1869 user.state = "verifying_new_password"
1871 # the password was weak, try again if you haven't tried too many times
1872 elif user.password_tries < universe.categories[
1879 user.password_tries += 1
1882 # too many tries, so adios
1885 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1887 user.account.destroy()
1888 user.state = "disconnecting"
1891 def handler_verifying_new_password(user):
1892 """Handle the re-entered new password for verification."""
1894 # get the next waiting line of input
1895 input_data = user.input_queue.pop(0)
1897 # hash the input and match it to storage
1898 if mudpy.password.verify(input_data, user.account.get("passhash")):
1901 # the hashes matched, so go active
1902 if not user.replace_old_connections():
1903 user.state = "main_utility"
1905 # go back to entering the new password as long as you haven't tried
1907 elif user.password_tries < universe.categories[
1914 user.password_tries += 1
1915 user.error = "differs"
1916 user.state = "entering_new_password"
1918 # otherwise, sayonara
1921 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1923 user.account.destroy()
1924 user.state = "disconnecting"
1927 def handler_active(user):
1928 """Handle input for active users."""
1930 # get the next waiting line of input
1931 input_data = user.input_queue.pop(0)
1936 # split out the command and parameters
1938 mode = actor.get("mode")
1939 if mode and input_data.startswith("!"):
1940 command_name, parameters = first_word(input_data[1:])
1941 elif mode == "chat":
1942 command_name = "say"
1943 parameters = input_data
1945 command_name, parameters = first_word(input_data)
1947 # lowercase the command
1948 command_name = command_name.lower()
1950 # the command matches a command word for which we have data
1951 if command_name in universe.categories["command"]:
1952 command = universe.categories["command"][command_name]
1956 # if it's allowed, do it
1957 if actor.can_run(command):
1958 exec(command.get("action"))
1960 # otherwise, give an error
1962 command_error(actor, input_data)
1964 # if no input, just idle back with a prompt
1966 user.send("", just_prompt=True)
1969 def command_halt(actor, parameters):
1970 """Halt the world."""
1973 # see if there's a message or use a generic one
1975 message = "Halting: " + parameters
1977 message = "User " + actor.owner.account.get(
1979 ) + " halted the world."
1982 broadcast(message, add_prompt=False)
1985 # set a flag to terminate the world
1986 universe.terminate_flag = True
1989 def command_reload(actor):
1990 """Reload all code modules, configs and data."""
1993 # let the user know and log
1994 actor.send("Reloading all code modules, configs and data.")
1997 actor.owner.account.get("name") + " reloaded the world.",
2001 # set a flag to reload
2002 universe.reload_flag = True
2005 def command_quit(actor):
2006 """Leave the world and go back to the main menu."""
2008 actor.owner.state = "main_utility"
2009 actor.owner.deactivate_avatar()
2012 def command_help(actor, parameters):
2013 """List available commands and provide help for commands."""
2015 # did the user ask for help on a specific command word?
2016 if parameters and actor.owner:
2018 # is the command word one for which we have data?
2019 if parameters in universe.categories["command"]:
2020 command = universe.categories["command"][parameters]
2024 # only for allowed commands
2025 if actor.can_run(command):
2027 # add a description if provided
2028 description = command.get("description")
2030 description = "(no short description provided)"
2031 if command.getboolean("administrative"):
2035 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
2037 # add the help text if provided
2038 help_text = command.get("help")
2040 help_text = "No help is provided for this command."
2043 # list related commands
2044 see_also = command.getlist("see_also")
2046 really_see_also = ""
2047 for item in see_also:
2048 if item in universe.categories["command"]:
2049 command = universe.categories["command"][item]
2050 if actor.can_run(command):
2052 really_see_also += ", "
2053 if command.getboolean("administrative"):
2054 really_see_also += "$(red)"
2056 really_see_also += "$(grn)"
2057 really_see_also += item + "$(nrm)"
2059 output += "$(eol)$(eol)See also: " + really_see_also
2061 # no data for the requested command word
2063 output = "That is not an available command."
2065 # no specific command word was indicated
2068 # give a sorted list of commands with descriptions if provided
2069 output = "These are the commands available to you:$(eol)$(eol)"
2070 sorted_commands = list(universe.categories["command"].keys())
2071 sorted_commands.sort()
2072 for item in sorted_commands:
2073 command = universe.categories["command"][item]
2074 if actor.can_run(command):
2075 description = command.get("description")
2077 description = "(no short description provided)"
2078 if command.getboolean("administrative"):
2082 output += item + "$(nrm) - " + description + "$(eol)"
2083 output += ("$(eol)Enter \"help COMMAND\" for help on a command "
2084 "named \"COMMAND\".")
2086 # send the accumulated output to the user
2090 def command_move(actor, parameters):
2091 """Move the avatar in a given direction."""
2092 if parameters in universe.contents[actor.get("location")].portals():
2093 actor.move_direction(parameters)
2095 actor.send("You cannot go that way.")
2098 def command_look(actor, parameters):
2101 actor.send("You can't look at or in anything yet.")
2103 actor.look_at(actor.get("location"))
2106 def command_say(actor, parameters):
2107 """Speak to others in the same area."""
2109 # check for replacement macros and escape them
2110 parameters = escape_macros(parameters)
2112 # if the message is wrapped in quotes, remove them and leave contents
2114 if parameters.startswith("\"") and parameters.endswith("\""):
2115 message = parameters[1:-1]
2118 # otherwise, get rid of stray quote marks on the ends of the message
2120 message = parameters.strip("\"'`")
2123 # the user entered a message
2126 # match the punctuation used, if any, to an action
2127 actions = universe.categories["internal"]["language"].getdict(
2130 default_punctuation = (
2131 universe.categories["internal"]["language"].get(
2132 "default_punctuation"))
2134 for mark in actions.keys():
2135 if not literal and message.endswith(mark):
2136 action = actions[mark]
2139 # add punctuation if needed
2141 action = actions[default_punctuation]
2142 if message and not (
2143 literal or unicodedata.category(message[-1]) == "Po"
2145 message += default_punctuation
2147 # failsafe checks to avoid unwanted reformatting and null strings
2148 if message and not literal:
2150 # decapitalize the first letter to improve matching
2151 message = message[0].lower() + message[1:]
2153 # iterate over all words in message, replacing typos
2154 typos = universe.categories["internal"]["language"].getdict(
2157 words = message.split()
2158 for index in range(len(words)):
2160 while unicodedata.category(word[0]) == "Po":
2162 while unicodedata.category(word[-1]) == "Po":
2164 if word in typos.keys():
2165 words[index] = words[index].replace(word, typos[word])
2166 message = " ".join(words)
2168 # capitalize the first letter
2169 message = message[0].upper() + message[1:]
2173 actor.echo_to_location(
2174 actor.get("name") + " " + action + "s, \"" + message + "\""
2176 actor.send("You " + action + ", \"" + message + "\"")
2178 # there was no message
2180 actor.send("What do you want to say?")
2183 def command_chat(actor):
2184 """Toggle chat mode."""
2185 mode = actor.get("mode")
2187 actor.set("mode", "chat")
2188 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
2189 elif mode == "chat":
2190 actor.remove_facet("mode")
2191 actor.send("Exiting chat mode.")
2193 actor.send("Sorry, but you're already busy with something else!")
2196 def command_show(actor, parameters):
2197 """Show program data."""
2199 arguments = parameters.split()
2201 message = "What do you want to show?"
2202 elif arguments[0] == "time":
2203 message = universe.categories["internal"]["counters"].get(
2205 ) + " increments elapsed since the world was created."
2206 elif arguments[0] == "categories":
2207 message = "These are the element categories:$(eol)"
2208 categories = list(universe.categories.keys())
2210 for category in categories:
2211 message += "$(eol) $(grn)" + category + "$(nrm)"
2212 elif arguments[0] == "files":
2213 message = "These are the current files containing the universe:$(eol)"
2214 filenames = list(universe.files.keys())
2216 for filename in filenames:
2217 if universe.files[filename].is_writeable():
2221 message += ("$(eol) $(red)(" + status + ") $(grn)" + filename
2223 elif arguments[0] == "category":
2224 if len(arguments) != 2:
2225 message = "You must specify one category."
2226 elif arguments[1] in universe.categories:
2227 message = ("These are the elements in the \"" + arguments[1]
2228 + "\" category:$(eol)")
2231 universe.categories[arguments[1]][x].key
2232 ) for x in universe.categories[arguments[1]].keys()
2235 for element in elements:
2236 message += "$(eol) $(grn)" + element + "$(nrm)"
2238 message = "Category \"" + arguments[1] + "\" does not exist."
2239 elif arguments[0] == "file":
2240 if len(arguments) != 2:
2241 message = "You must specify one file."
2242 elif arguments[1] in universe.files:
2243 message = ("These are the elements in the \"" + arguments[1]
2245 elements = universe.files[arguments[1]].data.sections()
2247 for element in elements:
2248 message += "$(eol) $(grn)" + element + "$(nrm)"
2250 message = "Category \"" + arguments[1] + "\" does not exist."
2251 elif arguments[0] == "element":
2252 if len(arguments) != 2:
2253 message = "You must specify one element."
2254 elif arguments[1] in universe.contents:
2255 element = universe.contents[arguments[1]]
2256 message = ("These are the properties of the \"" + arguments[1]
2257 + "\" element (in \"" + element.origin.filename
2259 facets = element.facets()
2261 for facet in facets:
2262 message += ("$(eol) $(grn)" + facet + ": $(red)"
2263 + escape_macros(element.get(facet)) + "$(nrm)")
2265 message = "Element \"" + arguments[1] + "\" does not exist."
2266 elif arguments[0] == "result":
2267 if len(arguments) < 2:
2268 message = "You need to specify an expression."
2271 message = repr(eval(" ".join(arguments[1:])))
2272 except Exception as e:
2273 message = ("$(red)Your expression raised an exception...$(eol)"
2274 "$(eol)$(bld)%s$(nrm)" % e)
2275 elif arguments[0] == "log":
2276 if len(arguments) == 4:
2277 if re.match("^\d+$", arguments[3]) and int(arguments[3]) >= 0:
2278 stop = int(arguments[3])
2283 if len(arguments) >= 3:
2284 if re.match("^\d+$", arguments[2]) and int(arguments[2]) > 0:
2285 start = int(arguments[2])
2290 if len(arguments) >= 2:
2291 if (re.match("^\d+$", arguments[1])
2292 and 0 <= int(arguments[1]) <= 9):
2293 level = int(arguments[1])
2296 elif 0 <= actor.owner.account.getint("loglevel") <= 9:
2297 level = actor.owner.account.getint("loglevel")
2300 if level > -1 and start > -1 and stop > -1:
2301 message = get_loglines(level, start, stop)
2303 message = ("When specified, level must be 0-9 (default 1), "
2304 "start and stop must be >=1 (default 10 and 1).")
2306 message = "I don't know what \"" + parameters + "\" is."
2310 def command_create(actor, parameters):
2311 """Create an element if it does not exist."""
2313 message = "You must at least specify an element to create."
2314 elif not actor.owner:
2317 arguments = parameters.split()
2318 if len(arguments) == 1:
2319 arguments.append("")
2320 if len(arguments) == 2:
2321 element, filename = arguments
2322 if element in universe.contents:
2323 message = "The \"" + element + "\" element already exists."
2325 message = ("You create \"" +
2326 element + "\" within the universe.")
2327 logline = actor.owner.account.get(
2329 ) + " created an element: " + element
2331 logline += " in file " + filename
2332 if filename not in universe.files:
2334 " Warning: \"" + filename + "\" is not yet "
2335 "included in any other file and will not be read "
2336 "on startup unless this is remedied.")
2337 Element(element, universe, filename)
2339 elif len(arguments) > 2:
2340 message = "You can only specify an element and a filename."
2344 def command_destroy(actor, parameters):
2345 """Destroy an element if it exists."""
2348 message = "You must specify an element to destroy."
2350 if parameters not in universe.contents:
2351 message = "The \"" + parameters + "\" element does not exist."
2353 universe.contents[parameters].destroy()
2354 message = ("You destroy \"" + parameters
2355 + "\" within the universe.")
2357 actor.owner.account.get(
2359 ) + " destroyed an element: " + parameters,
2365 def command_set(actor, parameters):
2366 """Set a facet of an element."""
2368 message = "You must specify an element, a facet and a value."
2370 arguments = parameters.split(" ", 2)
2371 if len(arguments) == 1:
2372 message = ("What facet of element \"" + arguments[0]
2373 + "\" would you like to set?")
2374 elif len(arguments) == 2:
2375 message = ("What value would you like to set for the \"" +
2376 arguments[1] + "\" facet of the \"" + arguments[0]
2379 element, facet, value = arguments
2380 if element not in universe.contents:
2381 message = "The \"" + element + "\" element does not exist."
2383 universe.contents[element].set(facet, value)
2384 message = ("You have successfully (re)set the \"" + facet
2385 + "\" facet of element \"" + element
2386 + "\". Try \"show element " +
2387 element + "\" for verification.")
2391 def command_delete(actor, parameters):
2392 """Delete a facet from an element."""
2394 message = "You must specify an element and a facet."
2396 arguments = parameters.split(" ")
2397 if len(arguments) == 1:
2398 message = ("What facet of element \"" + arguments[0]
2399 + "\" would you like to delete?")
2400 elif len(arguments) != 2:
2401 message = "You may only specify an element and a facet."
2403 element, facet = arguments
2404 if element not in universe.contents:
2405 message = "The \"" + element + "\" element does not exist."
2406 elif facet not in universe.contents[element].facets():
2407 message = ("The \"" + element + "\" element has no \"" + facet
2410 universe.contents[element].remove_facet(facet)
2411 message = ("You have successfully deleted the \"" + facet
2412 + "\" facet of element \"" + element
2413 + "\". Try \"show element " +
2414 element + "\" for verification.")
2418 def command_error(actor, input_data):
2419 """Generic error for an unrecognized command word."""
2421 # 90% of the time use a generic error
2422 if random.randrange(10):
2423 message = "I'm not sure what \"" + input_data + "\" means..."
2425 # 10% of the time use the classic diku error
2427 message = "Arglebargle, glop-glyf!?!"
2429 # send the error message
2433 def daemonize(universe):
2434 """Fork and disassociate from everything."""
2436 # only if this is what we're configured to do
2437 if universe.contents["internal:process"].getboolean("daemon"):
2439 # log before we start forking around, so the terminal gets the message
2440 log("Disassociating from the controlling terminal.")
2442 # fork off and die, so we free up the controlling terminal
2446 # switch to a new process group
2449 # fork some more, this time to free us from the old process group
2453 # reset the working directory so we don't needlessly tie up mounts
2456 # clear the file creation mask so we can bend it to our will later
2459 # redirect stdin/stdout/stderr and close off their former descriptors
2460 for stdpipe in range(3):
2462 sys.stdin = codecs.open("/dev/null", "r", "utf-8")
2463 sys.__stdin__ = codecs.open("/dev/null", "r", "utf-8")
2464 sys.stdout = codecs.open("/dev/null", "w", "utf-8")
2465 sys.stderr = codecs.open("/dev/null", "w", "utf-8")
2466 sys.__stdout__ = codecs.open("/dev/null", "w", "utf-8")
2467 sys.__stderr__ = codecs.open("/dev/null", "w", "utf-8")
2470 def create_pidfile(universe):
2471 """Write a file containing the current process ID."""
2472 pid = str(os.getpid())
2473 log("Process ID: " + pid)
2474 file_name = universe.contents["internal:process"].get("pidfile")
2476 if not os.path.isabs(file_name):
2477 file_name = os.path.join(universe.startdir, file_name)
2478 file_descriptor = codecs.open(file_name, "w", "utf-8")
2479 file_descriptor.write(pid + "\n")
2480 file_descriptor.flush()
2481 file_descriptor.close()
2484 def remove_pidfile(universe):
2485 """Remove the file containing the current process ID."""
2486 file_name = universe.contents["internal:process"].get("pidfile")
2488 if not os.path.isabs(file_name):
2489 file_name = os.path.join(universe.startdir, file_name)
2490 if os.access(file_name, os.W_OK):
2491 os.remove(file_name)
2494 def excepthook(excepttype, value, tracebackdata):
2495 """Handle uncaught exceptions."""
2497 # assemble the list of errors into a single string
2499 traceback.format_exception(excepttype, value, tracebackdata)
2502 # try to log it, if possible
2505 except Exception as e:
2506 # try to write it to stderr, if possible
2507 sys.stderr.write(message + "\nException while logging...\n%s" % e)
2510 def sighook(what, where):
2511 """Handle external signals."""
2514 message = "Caught signal: "
2516 # for a hangup signal
2517 if what == signal.SIGHUP:
2518 message += "hangup (reloading)"
2519 universe.reload_flag = True
2521 # for a terminate signal
2522 elif what == signal.SIGTERM:
2523 message += "terminate (halting)"
2524 universe.terminate_flag = True
2526 # catchall for unexpected signals
2528 message += str(what) + " (unhandled)"
2534 def override_excepthook():
2535 """Redefine sys.excepthook with our own."""
2536 sys.excepthook = excepthook
2539 def assign_sighook():
2540 """Assign a customized handler for some signals."""
2541 signal.signal(signal.SIGHUP, sighook)
2542 signal.signal(signal.SIGTERM, sighook)
2546 """This contains functions to be performed when starting the engine."""
2548 # see if a configuration file was specified
2549 if len(sys.argv) > 1:
2550 conffile = sys.argv[1]
2556 universe = Universe(conffile, True)
2558 # log an initial message
2559 log("Started mudpy with command line: " + " ".join(sys.argv))
2561 # fork and disassociate
2564 # override the default exception handler so we get logging first thing
2565 override_excepthook()
2567 # set up custom signal handlers
2571 create_pidfile(universe)
2573 # pass the initialized universe back
2578 """These are functions performed when shutting down the engine."""
2580 # the loop has terminated, so save persistent data
2583 # log a final message
2584 log("Shutting down now.")
2586 # get rid of the pidfile
2587 remove_pidfile(universe)