1 """Miscellaneous functions for the mudpy engine."""
3 # Copyright (c) 2004-2018 Jeremy Stanley <fungi@yuggoth.org>. Permission
4 # to use, copy, modify, and distribute this software is granted under
5 # terms provided in the LICENSE file distributed with this software.
24 """An element of the universe."""
26 def __init__(self, key, universe, origin=None):
27 """Set up a new element."""
29 # keep track of our key name
32 # keep track of what universe it's loading into
33 self.universe = universe
35 # set of facet keys from the universe
36 self.facethash = dict()
38 # not owned by a user by default (used for avatars)
41 # no contents in here by default
44 if self.key.find(".") > 0:
45 self.group, self.subkey = self.key.split(".")[-2:]
48 self.subkey = self.key
49 if self.group not in self.universe.groups:
50 self.universe.groups[self.group] = {}
52 # get an appropriate origin
54 self.universe.add_group(self.group)
55 origin = self.universe.files[
56 self.universe.origins[self.group]["fallback"]]
58 # record or reset a pointer to the origin file
59 self.origin = self.universe.files[origin.source]
61 # add or replace this element in the universe
62 self.universe.contents[self.key] = self
63 self.universe.groups[self.group][self.subkey] = self
66 """Create a new element and replace this one."""
67 Element(self.key, self.universe, self.origin)
71 """Remove an element from the universe and destroy it."""
72 for facet in dict(self.facethash):
73 self.remove_facet(facet)
74 del self.universe.groups[self.group][self.subkey]
75 del self.universe.contents[self.key]
79 """Return a list of non-inherited facets for this element."""
82 def has_facet(self, facet):
83 """Return whether the non-inherited facet exists."""
84 return facet in self.facets()
86 def remove_facet(self, facet):
87 """Remove a facet from the element."""
88 if ".".join((self.key, facet)) in self.origin.data:
89 del self.origin.data[".".join((self.key, facet))]
90 if facet in self.facethash:
91 del self.facethash[facet]
92 self.origin.modified = True
95 """Return a list of the element's inheritance lineage."""
96 if self.has_facet("inherit"):
97 ancestry = self.get("inherit")
100 for parent in ancestry[:]:
101 ancestors = self.universe.contents[parent].ancestry()
102 for ancestor in ancestors:
103 if ancestor not in ancestry:
104 ancestry.append(ancestor)
109 def get(self, facet, default=None):
110 """Retrieve values."""
114 return self.origin.data[".".join((self.key, facet))]
115 except (KeyError, TypeError):
117 if self.has_facet("inherit"):
118 for ancestor in self.ancestry():
119 if self.universe.contents[ancestor].has_facet(facet):
120 return self.universe.contents[ancestor].get(facet)
124 def set(self, facet, value):
126 if not self.origin.is_writeable() and not self.universe.loading:
127 # break if there is an attempt to update an element from a
128 # read-only file, unless the universe is in the midst of loading
129 # updated data from files
130 raise PermissionError("Altering elements in read-only files is "
132 # Coerce some values to appropriate data types
133 # TODO(fungi) Move these to a separate validation mechanism
134 if facet in ["loglevel"]:
136 elif facet in ["administrator"]:
139 # The canonical node for this facet within its origin
140 node = ".".join((self.key, facet))
142 if node not in self.origin.data or self.origin.data[node] != value:
143 # Be careful to only update the origin's contents when required,
144 # since that affects whether the backing file gets written
145 self.origin.data[node] = value
146 self.origin.modified = True
148 # Make sure this facet is included in the element's facets
149 self.facethash[facet] = self.origin.data[node]
151 def append(self, facet, value):
152 """Append value to a list."""
153 newlist = self.get(facet)
156 if type(newlist) is not list:
157 newlist = list(newlist)
158 newlist.append(value)
159 self.set(facet, newlist)
169 add_terminator=False,
172 """Convenience method to pass messages to an owner."""
185 def can_run(self, command):
186 """Check if the user can run this command object."""
188 # has to be in the commands group
189 if command not in self.universe.groups["command"].values():
192 # avatars of administrators can run any command
193 elif self.owner and self.owner.account.get("administrator"):
196 # everyone can run non-administrative commands
197 elif not command.get("administrative"):
200 # otherwise the command cannot be run by this actor
204 # pass back the result
207 def update_location(self):
208 """Make sure the location's contents contain this element."""
209 area = self.get("location")
210 if area in self.universe.contents:
211 self.universe.contents[area].contents[self.key] = self
213 def clean_contents(self):
214 """Make sure the element's contents aren't bogus."""
215 for element in self.contents.values():
216 if element.get("location") != self.key:
217 del self.contents[element.key]
219 def go_to(self, area):
220 """Relocate the element to a specific area."""
221 current = self.get("location")
222 if current and self.key in self.universe.contents[current].contents:
223 del universe.contents[current].contents[self.key]
224 if area in self.universe.contents:
225 self.set("location", area)
226 self.universe.contents[area].contents[self.key] = self
230 """Relocate the element to its default location."""
231 self.go_to(self.get("default_location"))
232 self.echo_to_location(
233 "You suddenly realize that " + self.get("name") + " is here."
236 def move_direction(self, direction):
237 """Relocate the element in a specified direction."""
238 motion = self.universe.contents["mudpy.movement.%s" % direction]
239 enter_term = motion.get("enter_term")
240 exit_term = motion.get("exit_term")
241 self.echo_to_location("%s exits %s." % (self.get("name"), exit_term))
242 self.send("You exit %s." % exit_term, add_prompt=False)
244 self.universe.contents[
245 self.get("location")].link_neighbor(direction)
247 self.echo_to_location("%s arrives from %s." % (
248 self.get("name"), enter_term))
250 def look_at(self, key):
251 """Show an element to another element."""
253 element = self.universe.contents[key]
255 name = element.get("name")
257 message += "$(cyn)" + name + "$(nrm)$(eol)"
258 description = element.get("description")
260 message += description + "$(eol)"
261 portal_list = list(element.portals().keys())
264 message += "$(cyn)[ Exits: " + ", ".join(
267 for element in self.universe.contents[
270 if element.get("is_actor") and element is not self:
271 message += "$(yel)" + element.get(
273 ) + " is here.$(nrm)$(eol)"
274 elif element is not self:
275 message += "$(grn)" + element.get(
281 """Map the portal directions for an area to neighbors."""
283 if re.match(r"""^area\.-?\d+,-?\d+,-?\d+$""", self.key):
284 coordinates = [(int(x))
285 for x in self.key.split(".")[-1].split(",")]
288 self.universe.contents["mudpy.movement.%s" % x].get("vector")
289 ) for x in self.universe.directions)
290 for portal in self.get("gridlinks"):
291 adjacent = map(lambda c, o: c + o,
292 coordinates, offsets[portal])
293 neighbor = "area." + ",".join(
294 [(str(x)) for x in adjacent]
296 if neighbor in self.universe.contents:
297 portals[portal] = neighbor
298 for facet in self.facets():
299 if facet.startswith("link_"):
300 neighbor = self.get(facet)
301 if neighbor in self.universe.contents:
302 portal = facet.split("_")[1]
303 portals[portal] = neighbor
306 def link_neighbor(self, direction):
307 """Return the element linked in a given direction."""
308 portals = self.portals()
309 if direction in portals:
310 return portals[direction]
312 def echo_to_location(self, message):
313 """Show a message to other elements in the current location."""
314 for element in self.universe.contents[
317 if element is not self:
318 element.send(message)
325 def __init__(self, filename="", load=False):
326 """Initialize the universe."""
329 self.directions = set()
333 self.reload_flag = False
334 self.setup_loglines = []
335 self.startdir = os.getcwd()
336 self.terminate_flag = False
340 possible_filenames = [
342 "/usr/local/mudpy/etc/mudpy.yaml",
343 "/usr/local/etc/mudpy.yaml",
344 "/etc/mudpy/mudpy.yaml",
347 for filename in possible_filenames:
348 if os.access(filename, os.R_OK):
350 if not os.path.isabs(filename):
351 filename = os.path.join(self.startdir, filename)
352 self.filename = filename
354 # make sure to preserve any accumulated log entries during load
355 self.setup_loglines += self.load()
358 """Load universe data from persistent storage."""
360 # while loading, it's safe to update elements from read-only files
363 # it's possible for this to enter before logging configuration is read
364 pending_loglines = []
366 # the files dict must exist and filename needs to be read-only
370 self.filename in self.files and self.files[
375 # clear out all read-only files
376 if hasattr(self, "files"):
377 for data_filename in list(self.files.keys()):
378 if not self.files[data_filename].is_writeable():
379 del self.files[data_filename]
381 # start loading from the initial file
382 mudpy.data.Data(self.filename, self)
384 # load default storage locations for groups
385 if hasattr(self, "contents") and "mudpy.filing" in self.contents:
386 self.origins.update(self.contents["mudpy.filing"].get(
389 # add some builtin groups we know we'll need
390 for group in ("account", "actor", "internal"):
391 self.add_group(group)
393 # make a list of inactive avatars
394 inactive_avatars = []
395 for account in self.groups.get("account", {}).values():
396 for avatar in account.get("avatars"):
398 inactive_avatars.append(self.contents[avatar])
400 pending_loglines.append((
401 'Missing avatar "%s", possible data corruption' %
403 for user in self.userlist:
404 if user.avatar in inactive_avatars:
405 inactive_avatars.remove(user.avatar)
407 # go through all elements to clear out inactive avatar locations
408 for element in self.contents.values():
409 area = element.get("location")
410 if element in inactive_avatars and area:
411 if area in self.contents and element.key in self.contents[
414 del self.contents[area].contents[element.key]
415 element.set("default_location", area)
416 element.remove_facet("location")
418 # another pass to straighten out all the element contents
419 for element in self.contents.values():
420 element.update_location()
421 element.clean_contents()
423 # done loading, so disallow updating elements from read-only files
426 return pending_loglines
429 """Create a new, empty Universe (the Big Bang)."""
430 new_universe = Universe()
431 for attribute in vars(self).keys():
432 exec("new_universe." + attribute + " = self." + attribute)
433 new_universe.reload_flag = False
438 """Save the universe to persistent storage."""
439 for key in self.files:
440 self.files[key].save()
442 def initialize_server_socket(self):
443 """Create and open the listening socket."""
445 # need to know the local address and port number for the listener
446 host = self.contents["mudpy.network"].get("host")
447 port = self.contents["mudpy.network"].get("port")
449 # if no host was specified, bind to all local addresses (preferring
457 # figure out if this is ipv4 or v6
458 family = socket.getaddrinfo(host, port)[0][0]
459 if family is socket.AF_INET6 and not socket.has_ipv6:
460 log("No support for IPv6 address %s (use IPv4 instead)." % host)
462 # create a new stream-type socket object
463 self.listening_socket = socket.socket(family, socket.SOCK_STREAM)
465 # set the socket options to allow existing open ones to be
466 # reused (fixes a bug where the server can't bind for a minute
467 # when restarting on linux systems)
468 self.listening_socket.setsockopt(
469 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
472 # bind the socket to to our desired server ipa and port
473 self.listening_socket.bind((host, port))
475 # disable blocking so we can proceed whether or not we can
477 self.listening_socket.setblocking(0)
479 # start listening on the socket
480 self.listening_socket.listen(1)
482 # note that we're now ready for user connections
484 "Listening for Telnet connections on: " +
485 host + ":" + str(port)
489 """Convenience method to get the elapsed time counter."""
490 return self.groups["internal"]["counters"].get("elapsed")
492 def add_group(self, group, fallback=None):
493 """Set up group tracking/metadata."""
494 if group not in self.origins:
495 self.origins[group] = {}
497 fallback = mudpy.data.find_file(
498 ".".join((group, "yaml")), universe=self)
499 if "fallback" not in self.origins[group]:
500 self.origins[group]["fallback"] = fallback
501 flags = self.origins[group].get("flags", None)
502 if fallback not in self.files:
503 mudpy.data.Data(fallback, self, flags=flags)
508 """This is a connected user."""
511 """Default values for the in-memory user variables."""
514 self.authenticated = False
517 self.connection = None
519 self.input_queue = []
520 self.last_address = ""
521 self.last_input = universe.get_time()
522 self.menu_choices = {}
523 self.menu_seen = False
524 self.negotiation_pause = 0
525 self.output_queue = []
526 self.partial_input = b""
527 self.password_tries = 0
528 self.state = "telopt_negotiation"
532 """Log, close the connection and remove."""
534 name = self.account.get("name")
538 message = "User " + name
540 message = "An unnamed user"
541 message += " logged out."
543 self.deactivate_avatar()
544 self.connection.close()
547 def check_idle(self):
548 """Warn or disconnect idle users as appropriate."""
549 idletime = universe.get_time() - self.last_input
550 linkdead_dict = universe.contents[
551 "mudpy.timing.idle.disconnect"].facets()
552 if self.state in linkdead_dict:
553 linkdead_state = self.state
555 linkdead_state = "default"
556 if idletime > linkdead_dict[linkdead_state]:
558 "$(eol)$(red)You've done nothing for far too long... goodbye!"
563 logline = "Disconnecting "
564 if self.account and self.account.get("name"):
565 logline += self.account.get("name")
567 logline += "an unknown user"
568 logline += (" after idling too long in the " + self.state
571 self.state = "disconnecting"
572 self.menu_seen = False
573 idle_dict = universe.contents["mudpy.timing.idle.warn"].facets()
574 if self.state in idle_dict:
575 idle_state = self.state
577 idle_state = "default"
578 if idletime == idle_dict[idle_state]:
580 "$(eol)$(red)If you continue to be unproductive, "
581 + "you'll be shown the door...$(nrm)$(eol)"
585 """Save, load a new user and relocate the connection."""
587 # get out of the list
590 # create a new user object
593 # set everything equivalent
594 for attribute in vars(self).keys():
595 exec("new_user." + attribute + " = self." + attribute)
597 # the avatar needs a new owner
599 new_user.avatar.owner = new_user
602 universe.userlist.append(new_user)
604 # get rid of the old user object
607 def replace_old_connections(self):
608 """Disconnect active users with the same name."""
610 # the default return value
613 # iterate over each user in the list
614 for old_user in universe.userlist:
616 # the name is the same but it's not us
619 ) and old_user.account and old_user.account.get(
621 ) == self.account.get(
623 ) and old_user is not self:
627 "User " + self.account.get(
629 ) + " reconnected--closing old connection to "
630 + old_user.address + ".",
634 "$(eol)$(red)New connection from " + self.address
635 + ". Terminating old connection...$(nrm)$(eol)",
640 # close the old connection
641 old_user.connection.close()
643 # replace the old connection with this one
645 "$(eol)$(red)Taking over old connection from "
646 + old_user.address + ".$(nrm)"
648 old_user.connection = self.connection
649 old_user.last_address = old_user.address
650 old_user.address = self.address
652 # take this one out of the list and delete
658 # true if an old connection was replaced, false if not
661 def authenticate(self):
662 """Flag the user as authenticated and disconnect duplicates."""
663 if self.state is not "authenticated":
664 self.authenticated = True
665 if ("mudpy.limit" in universe.contents and self.account.subkey in
666 universe.contents["mudpy.limit"].get("admins")):
667 self.account.set("administrator", True)
668 log("Administrator %s authenticated." %
669 self.account.get("name"), 2)
671 # log("User %s authenticated." % self.account.get("name"), 2)
672 log("User %s authenticated." % self.account.subkey, 2)
675 """Send the user their current menu."""
676 if not self.menu_seen:
677 self.menu_choices = get_menu_choices(self)
679 get_menu(self.state, self.error, self.menu_choices),
683 self.menu_seen = True
685 self.adjust_echoing()
687 def adjust_echoing(self):
688 """Adjust echoing to match state menu requirements."""
689 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_ECHO,
691 if menu_echo_on(self.state):
692 mudpy.telnet.disable(self, mudpy.telnet.TELOPT_ECHO,
694 elif not menu_echo_on(self.state):
695 mudpy.telnet.enable(self, mudpy.telnet.TELOPT_ECHO,
699 """Remove a user from the list of connected users."""
700 universe.userlist.remove(self)
710 add_terminator=False,
713 """Send arbitrary text to a connected user."""
715 # unless raw mode is on, clean it up all nice and pretty
718 # strip extra $(eol) off if present
719 while output.startswith("$(eol)"):
721 while output.endswith("$(eol)"):
723 extra_lines = output.find("$(eol)$(eol)$(eol)")
724 while extra_lines > -1:
725 output = output[:extra_lines] + output[extra_lines + 6:]
726 extra_lines = output.find("$(eol)$(eol)$(eol)")
728 # start with a newline, append the message, then end
729 # with the optional eol string passed to this function
730 # and the ansi escape to return to normal text
731 if not just_prompt and prepend_padding:
732 if (not self.output_queue or not
733 self.output_queue[-1].endswith(b"\r\n")):
734 output = "$(eol)" + output
735 elif not self.output_queue[-1].endswith(
737 ) and not self.output_queue[-1].endswith(
740 output = "$(eol)" + output
741 output += eol + chr(27) + "[0m"
743 # tack on a prompt if active
744 if self.state == "active":
749 mode = self.avatar.get("mode")
751 output += "(" + mode + ") "
753 # find and replace macros in the output
754 output = replace_macros(self, output)
756 # wrap the text at the client's width (min 40, 0 disables)
758 if self.columns < 40:
762 output = wrap_ansi_text(output, wrap)
764 # if supported by the client, encode it utf-8
765 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
767 encoded_output = output.encode("utf-8")
769 # otherwise just send ascii
771 encoded_output = output.encode("ascii", "replace")
773 # end with a terminator if requested
774 if add_prompt or add_terminator:
775 if mudpy.telnet.is_enabled(
776 self, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US):
777 encoded_output += mudpy.telnet.telnet_proto(
778 mudpy.telnet.IAC, mudpy.telnet.EOR)
779 elif not mudpy.telnet.is_enabled(
780 self, mudpy.telnet.TELOPT_SGA, mudpy.telnet.US):
781 encoded_output += mudpy.telnet.telnet_proto(
782 mudpy.telnet.IAC, mudpy.telnet.GA)
784 # and tack it onto the queue
785 self.output_queue.append(encoded_output)
787 # if this is urgent, flush all pending output
791 # just dump raw bytes as requested
793 self.output_queue.append(output)
797 """All the things to do to the user per increment."""
799 # if the world is terminating, disconnect
800 if universe.terminate_flag:
801 self.state = "disconnecting"
802 self.menu_seen = False
804 # check for an idle connection and act appropriately
808 # if output is paused, decrement the counter
809 if self.state == "telopt_negotiation":
810 if self.negotiation_pause:
811 self.negotiation_pause -= 1
813 self.state = "entering_account_name"
815 # show the user a menu as needed
816 elif not self.state == "active":
819 # flush any pending output in the queue
822 # disconnect users with the appropriate state
823 if self.state == "disconnecting":
826 # check for input and add it to the queue
829 # there is input waiting in the queue
831 handle_user_input(self)
834 """Try to send the last item in the queue and remove it."""
835 if self.output_queue:
837 self.connection.send(self.output_queue[0])
838 except (BrokenPipeError, ConnectionResetError):
839 if self.account and self.account.get("name"):
840 account = self.account.get("name")
842 account = "an unknown user"
843 self.state = "disconnecting"
844 log("Disconnected while sending to %s." % account, 7)
845 del self.output_queue[0]
847 def enqueue_input(self):
848 """Process and enqueue any new input."""
850 # check for some input
852 raw_input = self.connection.recv(1024)
853 except (BlockingIOError, OSError):
859 # tack this on to any previous partial
860 self.partial_input += raw_input
862 # reply to and remove any IAC negotiation codes
863 mudpy.telnet.negotiate_telnet_options(self)
865 # separate multiple input lines
866 new_input_lines = self.partial_input.split(b"\n")
868 # if input doesn't end in a newline, replace the
869 # held partial input with the last line of it
870 if not self.partial_input.endswith(b"\n"):
871 self.partial_input = new_input_lines.pop()
873 # otherwise, chop off the extra null input and reset
874 # the held partial input
876 new_input_lines.pop()
877 self.partial_input = b""
879 # iterate over the remaining lines
880 for line in new_input_lines:
882 # strip off extra whitespace
885 # log non-printable characters remaining
886 if not mudpy.telnet.is_enabled(
887 self, mudpy.telnet.TELOPT_BINARY, mudpy.telnet.HIM):
888 asciiline = bytes([x for x in line if 32 <= x <= 126])
889 if line != asciiline:
890 logline = "Non-ASCII characters from "
891 if self.account and self.account.get("name"):
892 logline += self.account.get("name") + ": "
894 logline += "unknown user: "
895 logline += repr(line)
900 line = line.decode("utf-8")
901 except UnicodeDecodeError:
902 logline = "Non-UTF-8 sequence from "
903 if self.account and self.account.get("name"):
904 logline += self.account.get("name") + ": "
906 logline += "unknown user: "
907 logline += repr(line)
911 line = unicodedata.normalize("NFKC", line)
913 # put on the end of the queue
914 self.input_queue.append(line)
916 def new_avatar(self):
917 """Instantiate a new, unconfigured avatar for this user."""
919 while ("avatar_%s_%s" % (self.account.get("name"), counter)
920 in universe.groups.get("actor", {}).keys()):
922 self.avatar = Element(
923 "actor.avatar_%s_%s" % (self.account.get("name"), counter),
925 self.avatar.append("inherit", "archetype.avatar")
926 self.account.append("avatars", self.avatar.key)
928 def delete_avatar(self, avatar):
929 """Remove an avatar from the world and from the user's list."""
930 if self.avatar is universe.contents[avatar]:
932 universe.contents[avatar].destroy()
933 avatars = self.account.get("avatars")
934 avatars.remove(avatar)
935 self.account.set("avatars", avatars)
937 def activate_avatar_by_index(self, index):
938 """Enter the world with a particular indexed avatar."""
939 self.avatar = universe.contents[
940 self.account.get("avatars")[index]]
941 self.avatar.owner = self
942 self.state = "active"
943 self.avatar.go_home()
945 def deactivate_avatar(self):
946 """Have the active avatar leave the world."""
948 current = self.avatar.get("location")
950 self.avatar.set("default_location", current)
951 self.avatar.echo_to_location(
952 "You suddenly wonder where " + self.avatar.get(
956 del universe.contents[current].contents[self.avatar.key]
957 self.avatar.remove_facet("location")
958 self.avatar.owner = None
962 """Destroy the user and associated avatars."""
963 for avatar in self.account.get("avatars"):
964 self.delete_avatar(avatar)
965 self.account.destroy()
967 def list_avatar_names(self):
968 """List names of assigned avatars."""
970 for avatar in self.account.get("avatars"):
972 avatars.append(universe.contents[avatar].get("name"))
974 log('Missing avatar "%s", possible data corruption.' %
979 def broadcast(message, add_prompt=True):
980 """Send a message to all connected users."""
981 for each_user in universe.userlist:
982 each_user.send("$(eol)" + message, add_prompt=add_prompt)
985 def log(message, level=0):
988 # a couple references we need
989 if "mudpy.log" in universe.contents:
990 file_name = universe.contents["mudpy.log"].get("file", "")
991 max_log_lines = universe.contents["mudpy.log"].get("lines", 0)
992 syslog_name = universe.contents["mudpy.log"].get("syslog", "")
997 timestamp = time.asctime()[4:19]
999 # turn the message into a list of nonempty lines
1000 lines = [x for x in [(x.rstrip()) for x in message.split("\n")] if x != ""]
1002 # send the timestamp and line to a file
1004 if not os.path.isabs(file_name):
1005 file_name = os.path.join(universe.startdir, file_name)
1006 file_descriptor = codecs.open(file_name, "a", "utf-8")
1008 file_descriptor.write(timestamp + " " + line + "\n")
1009 file_descriptor.flush()
1010 file_descriptor.close()
1012 # send the timestamp and line to standard output
1013 if ("mudpy.log" in universe.contents and
1014 universe.contents["mudpy.log"].get("stdout")):
1016 print(timestamp + " " + line)
1018 # send the line to the system log
1021 syslog_name.encode("utf-8"),
1023 syslog.LOG_INFO | syslog.LOG_DAEMON
1029 # display to connected administrators
1030 for user in universe.userlist:
1031 if user.state == "active" and user.account.get(
1033 ) and user.account.get("loglevel", 0) <= level:
1034 # iterate over every line in the message
1038 "$(bld)$(red)" + timestamp + " "
1039 + line.replace("$(", "$_(") + "$(nrm)$(eol)")
1040 user.send(full_message, flush=True)
1042 # add to the recent log list
1044 while 0 < len(universe.loglines) >= max_log_lines:
1045 del universe.loglines[0]
1046 universe.loglines.append((level, timestamp + " " + line))
1049 def get_loglines(level, start, stop):
1050 """Return a specific range of loglines filtered by level."""
1052 # filter the log lines
1053 loglines = [x for x in universe.loglines if x[0] >= level]
1055 # we need these in several places
1056 total_count = str(len(universe.loglines))
1057 filtered_count = len(loglines)
1059 # don't proceed if there are no lines
1062 # can't start before the begining or at the end
1063 if start > filtered_count:
1064 start = filtered_count
1068 # can't stop before we start
1075 message = "There are " + str(total_count)
1076 message += " log lines in memory and " + str(filtered_count)
1077 message += " at or above level " + str(level) + "."
1078 message += " The matching lines from " + str(stop) + " to "
1079 message += str(start) + " are:$(eol)$(eol)"
1081 # add the text from the selected lines
1083 range_lines = loglines[-start:-(stop - 1)]
1085 range_lines = loglines[-start:]
1086 for line in range_lines:
1087 message += " (" + str(line[0]) + ") " + line[1].replace(
1091 # there were no lines
1093 message = "None of the " + str(total_count)
1094 message += " lines in memory matches your request."
1100 def glyph_columns(character):
1101 """Convenience function to return the column width of a glyph."""
1102 if unicodedata.east_asian_width(character) in "FW":
1108 def wrap_ansi_text(text, width):
1109 """Wrap text with arbitrary width while ignoring ANSI colors."""
1111 # the current position in the entire text string, including all
1112 # characters, printable or otherwise
1115 # the current text position relative to the begining of the line,
1116 # ignoring color escape sequences
1119 # the absolute and relative positions of the most recent whitespace
1121 last_abs_whitespace = 0
1122 last_rel_whitespace = 0
1124 # whether the current character is part of a color escape sequence
1127 # normalize any potentially composited unicode before we count it
1128 text = unicodedata.normalize("NFKC", text)
1130 # iterate over each character from the begining of the text
1131 for each_character in text:
1133 # the current character is the escape character
1134 if each_character == "\x1b" and not escape:
1138 # the current character is within an escape sequence
1141 if each_character == "m":
1142 # the current character is m, which terminates the
1146 # the current character is a space
1147 elif each_character == " ":
1148 last_abs_whitespace = abs_pos
1149 last_rel_whitespace = rel_pos
1151 # the current character is a newline, so reset the relative
1152 # position too (start a new line)
1153 elif each_character == "\n":
1155 last_abs_whitespace = abs_pos
1156 last_rel_whitespace = rel_pos
1158 # the current character meets the requested maximum line width, so we
1159 # need to wrap unless the current word is wider than the terminal (in
1160 # which case we let it do the wrapping instead)
1161 if last_rel_whitespace != 0 and (rel_pos > width or (
1162 rel_pos > width - 1 and glyph_columns(each_character) == 2)):
1164 # insert an eol in place of the last space
1165 text = (text[:last_abs_whitespace] + "\r\n" +
1166 text[last_abs_whitespace + 1:])
1168 # increase the absolute position because an eol is two
1169 # characters but the space it replaced was only one
1172 # now we're at the begining of a new line, plus the
1173 # number of characters wrapped from the previous line
1174 rel_pos -= last_rel_whitespace
1175 last_rel_whitespace = 0
1177 # as long as the character is not a carriage return and the
1178 # other above conditions haven't been met, count it as a
1179 # printable character
1180 elif each_character != "\r":
1181 rel_pos += glyph_columns(each_character)
1182 if each_character in (" ", "\n"):
1183 last_abs_whitespace = abs_pos
1184 last_rel_whitespace = rel_pos
1186 # increase the absolute position for every character
1189 # return the newly-wrapped text
1193 def weighted_choice(data):
1194 """Takes a dict weighted by value and returns a random key."""
1196 # this will hold our expanded list of keys from the data
1199 # create the expanded list of keys
1200 for key in data.keys():
1201 for count in range(data[key]):
1202 expanded.append(key)
1204 # return one at random
1205 return random.choice(expanded)
1209 """Returns a random character name."""
1211 # the vowels and consonants needed to create romaji syllables
1240 # this dict will hold our weighted list of syllables
1243 # generate the list with an even weighting
1244 for consonant in consonants:
1245 for vowel in vowels:
1246 syllables[consonant + vowel] = 1
1248 # we'll build the name into this string
1251 # create a name of random length from the syllables
1252 for syllable in range(random.randrange(2, 6)):
1253 name += weighted_choice(syllables)
1255 # strip any leading quotemark, capitalize and return the name
1256 return name.strip("'").capitalize()
1259 def replace_macros(user, text, is_input=False):
1260 """Replaces macros in text output."""
1262 # third person pronouns
1264 "female": {"obj": "her", "pos": "hers", "sub": "she"},
1265 "male": {"obj": "him", "pos": "his", "sub": "he"},
1266 "neuter": {"obj": "it", "pos": "its", "sub": "it"}
1269 # a dict of replacement macros
1272 "bld": chr(27) + "[1m",
1273 "nrm": chr(27) + "[0m",
1274 "blk": chr(27) + "[30m",
1275 "blu": chr(27) + "[34m",
1276 "cyn": chr(27) + "[36m",
1277 "grn": chr(27) + "[32m",
1278 "mgt": chr(27) + "[35m",
1279 "red": chr(27) + "[31m",
1280 "yel": chr(27) + "[33m",
1283 # add dynamic macros where possible
1285 account_name = user.account.get("name")
1287 macros["account"] = account_name
1289 avatar_gender = user.avatar.get("gender")
1291 macros["tpop"] = pronouns[avatar_gender]["obj"]
1292 macros["tppp"] = pronouns[avatar_gender]["pos"]
1293 macros["tpsp"] = pronouns[avatar_gender]["sub"]
1298 # find and replace per the macros dict
1299 macro_start = text.find("$(")
1300 if macro_start == -1:
1302 macro_end = text.find(")", macro_start) + 1
1303 macro = text[macro_start + 2:macro_end - 1]
1304 if macro in macros.keys():
1305 replacement = macros[macro]
1307 # this is how we handle local file inclusion (dangerous!)
1308 elif macro.startswith("inc:"):
1309 incfile = mudpy.data.find_file(macro[4:], universe=universe)
1310 if os.path.exists(incfile):
1311 incfd = codecs.open(incfile, "r", "utf-8")
1314 if line.endswith("\n") and not line.endswith("\r\n"):
1315 line = line.replace("\n", "\r\n")
1317 # lose the trailing eol
1318 replacement = replacement[:-2]
1321 log("Couldn't read included " + incfile + " file.", 7)
1323 # if we get here, log and replace it with null
1327 log("Unexpected replacement macro " +
1328 macro + " encountered.", 6)
1330 # and now we act on the replacement
1331 text = text.replace("$(" + macro + ")", replacement)
1333 # replace the look-like-a-macro sequence
1334 text = text.replace("$_(", "$(")
1339 def escape_macros(value):
1340 """Escapes replacement macros in text."""
1341 if type(value) is str:
1342 return value.replace("$(", "$_(")
1347 def first_word(text, separator=" "):
1348 """Returns a tuple of the first word and the rest."""
1350 if text.find(separator) > 0:
1351 return text.split(separator, 1)
1359 """The things which should happen on each pulse, aside from reloads."""
1361 # open the listening socket if it hasn't been already
1362 if not hasattr(universe, "listening_socket"):
1363 universe.initialize_server_socket()
1365 # assign a user if a new connection is waiting
1366 user = check_for_connection(universe.listening_socket)
1368 universe.userlist.append(user)
1370 # iterate over the connected users
1371 for user in universe.userlist:
1374 # add an element for counters if it doesn't exist
1375 if "counters" not in universe.groups.get("internal", {}):
1376 Element("internal.counters", universe)
1378 # update the log every now and then
1379 if not universe.groups["internal"]["counters"].get("mark"):
1380 log(str(len(universe.userlist)) + " connection(s)")
1381 universe.groups["internal"]["counters"].set(
1382 "mark", universe.contents["mudpy.timing"].get("status")
1385 universe.groups["internal"]["counters"].set(
1386 "mark", universe.groups["internal"]["counters"].get(
1391 # periodically save everything
1392 if not universe.groups["internal"]["counters"].get("save"):
1394 universe.groups["internal"]["counters"].set(
1395 "save", universe.contents["mudpy.timing"].get("save")
1398 universe.groups["internal"]["counters"].set(
1399 "save", universe.groups["internal"]["counters"].get(
1404 # pause for a configurable amount of time (decimal seconds)
1405 time.sleep(universe.contents["mudpy.timing"].get("increment"))
1407 # increase the elapsed increment counter
1408 universe.groups["internal"]["counters"].set(
1409 "elapsed", universe.groups["internal"]["counters"].get(
1416 """Reload all relevant objects."""
1417 for user in universe.userlist[:]:
1419 for element in universe.contents.values():
1420 if element.origin.is_writeable():
1425 def check_for_connection(listening_socket):
1426 """Check for a waiting connection and return a new user object."""
1428 # try to accept a new connection
1430 connection, address = listening_socket.accept()
1431 except BlockingIOError:
1434 # note that we got one
1435 log("Connection from " + address[0], 2)
1437 # disable blocking so we can proceed whether or not we can send/receive
1438 connection.setblocking(0)
1440 # create a new user object
1443 # associate this connection with it
1444 user.connection = connection
1446 # set the user's ipa from the connection's ipa
1447 user.address = address[0]
1449 # let the client know we WILL EOR (RFC 885)
1450 mudpy.telnet.enable(user, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US)
1451 user.negotiation_pause = 2
1453 # return the new user object
1457 def get_menu(state, error=None, choices=None):
1458 """Show the correct menu text to a user."""
1460 # make sure we don't reuse a mutable sequence by default
1464 # get the description or error text
1465 message = get_menu_description(state, error)
1467 # get menu choices for the current state
1468 message += get_formatted_menu_choices(state, choices)
1470 # try to get a prompt, if it was defined
1471 message += get_menu_prompt(state)
1473 # throw in the default choice, if it exists
1474 message += get_formatted_default_menu_choice(state)
1476 # display a message indicating if echo is off
1477 message += get_echo_message(state)
1479 # return the assembly of various strings defined above
1483 def menu_echo_on(state):
1484 """True if echo is on, false if it is off."""
1485 return universe.groups["menu"][state].get("echo", True)
1488 def get_echo_message(state):
1489 """Return a message indicating that echo is off."""
1490 if menu_echo_on(state):
1493 return "(won't echo) "
1496 def get_default_menu_choice(state):
1497 """Return the default choice for a menu."""
1498 return universe.groups["menu"][state].get("default")
1501 def get_formatted_default_menu_choice(state):
1502 """Default menu choice foratted for inclusion in a prompt string."""
1503 default_choice = get_default_menu_choice(state)
1505 return "[$(red)" + default_choice + "$(nrm)] "
1510 def get_menu_description(state, error):
1511 """Get the description or error text."""
1513 # an error condition was raised by the handler
1516 # try to get an error message matching the condition
1518 description = universe.groups[
1519 "menu"][state].get("error_" + error)
1521 description = "That is not a valid choice..."
1522 description = "$(red)" + description + "$(nrm)"
1524 # there was no error condition
1527 # try to get a menu description for the current state
1528 description = universe.groups["menu"][state].get("description")
1530 # return the description or error message
1532 description += "$(eol)$(eol)"
1536 def get_menu_prompt(state):
1537 """Try to get a prompt, if it was defined."""
1538 prompt = universe.groups["menu"][state].get("prompt")
1544 def get_menu_choices(user):
1545 """Return a dict of choice:meaning."""
1546 menu = universe.groups["menu"][user.state]
1547 create_choices = menu.get("create")
1549 choices = eval(create_choices)
1555 for facet in menu.facets():
1556 if facet.startswith("demand_") and not eval(
1557 universe.groups["menu"][user.state].get(facet)
1559 ignores.append(facet.split("_", 2)[1])
1560 elif facet.startswith("create_"):
1561 creates[facet] = facet.split("_", 2)[1]
1562 elif facet.startswith("choice_"):
1563 options[facet] = facet.split("_", 2)[1]
1564 for facet in creates.keys():
1565 if not creates[facet] in ignores:
1566 choices[creates[facet]] = eval(menu.get(facet))
1567 for facet in options.keys():
1568 if not options[facet] in ignores:
1569 choices[options[facet]] = menu.get(facet)
1573 def get_formatted_menu_choices(state, choices):
1574 """Returns a formatted string of menu choices."""
1576 choice_keys = list(choices.keys())
1578 for choice in choice_keys:
1579 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[
1583 choice_output += "$(eol)"
1584 return choice_output
1587 def get_menu_branches(state):
1588 """Return a dict of choice:branch."""
1590 for facet in universe.groups["menu"][state].facets():
1591 if facet.startswith("branch_"):
1593 facet.split("_", 2)[1]
1594 ] = universe.groups["menu"][state].get(facet)
1598 def get_default_branch(state):
1599 """Return the default branch."""
1600 return universe.groups["menu"][state].get("branch")
1603 def get_choice_branch(user, choice):
1604 """Returns the new state matching the given choice."""
1605 branches = get_menu_branches(user.state)
1606 if choice in branches.keys():
1607 return branches[choice]
1608 elif choice in user.menu_choices.keys():
1609 return get_default_branch(user.state)
1614 def get_menu_actions(state):
1615 """Return a dict of choice:branch."""
1617 for facet in universe.groups["menu"][state].facets():
1618 if facet.startswith("action_"):
1620 facet.split("_", 2)[1]
1621 ] = universe.groups["menu"][state].get(facet)
1625 def get_default_action(state):
1626 """Return the default action."""
1627 return universe.groups["menu"][state].get("action")
1630 def get_choice_action(user, choice):
1631 """Run any indicated script for the given choice."""
1632 actions = get_menu_actions(user.state)
1633 if choice in actions.keys():
1634 return actions[choice]
1635 elif choice in user.menu_choices.keys():
1636 return get_default_action(user.state)
1641 def handle_user_input(user):
1642 """The main handler, branches to a state-specific handler."""
1644 # if the user's client echo is off, send a blank line for aesthetics
1645 if mudpy.telnet.is_enabled(user, mudpy.telnet.TELOPT_ECHO,
1647 user.send("", add_prompt=False, prepend_padding=False)
1649 # check to make sure the state is expected, then call that handler
1650 if "handler_" + user.state in globals():
1651 exec("handler_" + user.state + "(user)")
1653 generic_menu_handler(user)
1655 # since we got input, flag that the menu/prompt needs to be redisplayed
1656 user.menu_seen = False
1658 # update the last_input timestamp while we're at it
1659 user.last_input = universe.get_time()
1662 def generic_menu_handler(user):
1663 """A generic menu choice handler."""
1665 # get a lower-case representation of the next line of input
1666 if user.input_queue:
1667 choice = user.input_queue.pop(0)
1669 choice = choice.lower()
1673 choice = get_default_menu_choice(user.state)
1674 if choice in user.menu_choices:
1675 exec(get_choice_action(user, choice))
1676 new_state = get_choice_branch(user, choice)
1678 user.state = new_state
1680 user.error = "default"
1683 def handler_entering_account_name(user):
1684 """Handle the login account name."""
1686 # get the next waiting line of input
1687 input_data = user.input_queue.pop(0)
1689 # did the user enter anything?
1692 # keep only the first word and convert to lower-case
1693 name = input_data.lower()
1695 # fail if there are non-alphanumeric characters
1696 if name != "".join(filter(
1697 lambda x: x >= "0" and x <= "9" or x >= "a" and x <= "z",
1699 user.error = "bad_name"
1701 # if that account exists, time to request a password
1702 elif name in universe.groups.get("account", {}):
1703 user.account = universe.groups["account"][name]
1704 user.state = "checking_password"
1706 # otherwise, this could be a brand new user
1708 user.account = Element("account.%s" % name, universe)
1709 user.account.set("name", name)
1710 log("New user: " + name, 2)
1711 user.state = "checking_new_account_name"
1713 # if the user entered nothing for a name, then buhbye
1715 user.state = "disconnecting"
1718 def handler_checking_password(user):
1719 """Handle the login account password."""
1721 # get the next waiting line of input
1722 input_data = user.input_queue.pop(0)
1724 if "mudpy.limit" in universe.contents:
1725 max_password_tries = universe.contents["mudpy.limit"].get(
1726 "password_tries", 3)
1728 max_password_tries = 3
1730 # does the hashed input equal the stored hash?
1731 if mudpy.password.verify(input_data, user.account.get("passhash")):
1733 # if so, set the username and load from cold storage
1734 if not user.replace_old_connections():
1736 user.state = "main_utility"
1738 # if at first your hashes don't match, try, try again
1739 elif user.password_tries < max_password_tries - 1:
1740 user.password_tries += 1
1741 user.error = "incorrect"
1743 # we've exceeded the maximum number of password failures, so disconnect
1746 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1748 user.state = "disconnecting"
1751 def handler_entering_new_password(user):
1752 """Handle a new password entry."""
1754 # get the next waiting line of input
1755 input_data = user.input_queue.pop(0)
1757 if "mudpy.limit" in universe.contents:
1758 max_password_tries = universe.contents["mudpy.limit"].get(
1759 "password_tries", 3)
1761 max_password_tries = 3
1763 # make sure the password is strong--at least one upper, one lower and
1764 # one digit, seven or more characters in length
1765 if len(input_data) > 6 and len(
1766 list(filter(lambda x: x >= "0" and x <= "9", input_data))
1768 list(filter(lambda x: x >= "A" and x <= "Z", input_data))
1770 list(filter(lambda x: x >= "a" and x <= "z", input_data))
1773 # hash and store it, then move on to verification
1774 user.account.set("passhash", mudpy.password.create(input_data))
1775 user.state = "verifying_new_password"
1777 # the password was weak, try again if you haven't tried too many times
1778 elif user.password_tries < max_password_tries - 1:
1779 user.password_tries += 1
1782 # too many tries, so adios
1785 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1787 user.account.destroy()
1788 user.state = "disconnecting"
1791 def handler_verifying_new_password(user):
1792 """Handle the re-entered new password for verification."""
1794 # get the next waiting line of input
1795 input_data = user.input_queue.pop(0)
1797 if "mudpy.limit" in universe.contents:
1798 max_password_tries = universe.contents["mudpy.limit"].get(
1799 "password_tries", 3)
1801 max_password_tries = 3
1803 # hash the input and match it to storage
1804 if mudpy.password.verify(input_data, user.account.get("passhash")):
1807 # the hashes matched, so go active
1808 if not user.replace_old_connections():
1809 user.state = "main_utility"
1811 # go back to entering the new password as long as you haven't tried
1813 elif user.password_tries < max_password_tries - 1:
1814 user.password_tries += 1
1815 user.error = "differs"
1816 user.state = "entering_new_password"
1818 # otherwise, sayonara
1821 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1823 user.account.destroy()
1824 user.state = "disconnecting"
1827 def handler_active(user):
1828 """Handle input for active users."""
1830 # get the next waiting line of input
1831 input_data = user.input_queue.pop(0)
1836 # split out the command and parameters
1838 mode = actor.get("mode")
1839 if mode and input_data.startswith("!"):
1840 command_name, parameters = first_word(input_data[1:])
1841 elif mode == "chat":
1842 command_name = "say"
1843 parameters = input_data
1845 command_name, parameters = first_word(input_data)
1847 # lowercase the command
1848 command_name = command_name.lower()
1850 # the command matches a command word for which we have data
1851 if command_name in universe.groups["command"]:
1852 command = universe.groups["command"][command_name]
1856 # if it's allowed, do it
1857 if actor.can_run(command):
1858 exec(command.get("action"))
1860 # otherwise, give an error
1862 command_error(actor, input_data)
1864 # if no input, just idle back with a prompt
1866 user.send("", just_prompt=True)
1869 def command_halt(actor, parameters):
1870 """Halt the world."""
1873 # see if there's a message or use a generic one
1875 message = "Halting: " + parameters
1877 message = "User " + actor.owner.account.get(
1879 ) + " halted the world."
1882 broadcast(message, add_prompt=False)
1885 # set a flag to terminate the world
1886 universe.terminate_flag = True
1889 def command_reload(actor):
1890 """Reload all code modules, configs and data."""
1893 # let the user know and log
1894 actor.send("Reloading all code modules, configs and data.")
1897 actor.owner.account.get("name") + " reloaded the world.",
1901 # set a flag to reload
1902 universe.reload_flag = True
1905 def command_quit(actor):
1906 """Leave the world and go back to the main menu."""
1908 actor.owner.state = "main_utility"
1909 actor.owner.deactivate_avatar()
1912 def command_help(actor, parameters):
1913 """List available commands and provide help for commands."""
1915 # did the user ask for help on a specific command word?
1916 if parameters and actor.owner:
1918 # is the command word one for which we have data?
1919 if parameters in universe.groups["command"]:
1920 command = universe.groups["command"][parameters]
1924 # only for allowed commands
1925 if actor.can_run(command):
1927 # add a description if provided
1928 description = command.get("description")
1930 description = "(no short description provided)"
1931 if command.get("administrative"):
1935 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1937 # add the help text if provided
1938 help_text = command.get("help")
1940 help_text = "No help is provided for this command."
1943 # list related commands
1944 see_also = command.get("see_also")
1946 really_see_also = ""
1947 for item in see_also:
1948 if item in universe.groups["command"]:
1949 command = universe.groups["command"][item]
1950 if actor.can_run(command):
1952 really_see_also += ", "
1953 if command.get("administrative"):
1954 really_see_also += "$(red)"
1956 really_see_also += "$(grn)"
1957 really_see_also += item + "$(nrm)"
1959 output += "$(eol)$(eol)See also: " + really_see_also
1961 # no data for the requested command word
1963 output = "That is not an available command."
1965 # no specific command word was indicated
1968 # give a sorted list of commands with descriptions if provided
1969 output = "These are the commands available to you:$(eol)$(eol)"
1970 sorted_commands = list(universe.groups["command"].keys())
1971 sorted_commands.sort()
1972 for item in sorted_commands:
1973 command = universe.groups["command"][item]
1974 if actor.can_run(command):
1975 description = command.get("description")
1977 description = "(no short description provided)"
1978 if command.get("administrative"):
1982 output += item + "$(nrm) - " + description + "$(eol)"
1983 output += ('$(eol)Enter "help COMMAND" for help on a command '
1986 # send the accumulated output to the user
1990 def command_move(actor, parameters):
1991 """Move the avatar in a given direction."""
1992 if parameters in universe.contents[actor.get("location")].portals():
1993 actor.move_direction(parameters)
1995 actor.send("You cannot go that way.")
1998 def command_look(actor, parameters):
2001 actor.send("You can't look at or in anything yet.")
2003 actor.look_at(actor.get("location"))
2006 def command_say(actor, parameters):
2007 """Speak to others in the same area."""
2009 # check for replacement macros and escape them
2010 parameters = escape_macros(parameters)
2012 # if the message is wrapped in quotes, remove them and leave contents
2014 if parameters.startswith('"') and parameters.endswith('"'):
2015 message = parameters[1:-1]
2018 # otherwise, get rid of stray quote marks on the ends of the message
2020 message = parameters.strip('''"'`''')
2023 # the user entered a message
2026 # match the punctuation used, if any, to an action
2027 if "mudpy.linguistic" in universe.contents:
2028 actions = universe.contents["mudpy.linguistic"].get("actions", {})
2029 default_punctuation = (universe.contents["mudpy.linguistic"].get(
2030 "default_punctuation", "."))
2033 default_punctuation = "."
2036 # reverse sort punctuation options so the longest match wins
2037 for mark in sorted(actions.keys(), reverse=True):
2038 if not literal and message.endswith(mark):
2039 action = actions[mark]
2042 # add punctuation if needed
2044 action = actions[default_punctuation]
2045 if message and not (
2046 literal or unicodedata.category(message[-1]) == "Po"
2048 message += default_punctuation
2050 # failsafe checks to avoid unwanted reformatting and null strings
2051 if message and not literal:
2053 # decapitalize the first letter to improve matching
2054 message = message[0].lower() + message[1:]
2056 # iterate over all words in message, replacing typos
2057 if "mudpy.linguistic" in universe.contents:
2058 typos = universe.contents["mudpy.linguistic"].get("typos", {})
2061 words = message.split()
2062 for index in range(len(words)):
2064 while unicodedata.category(word[0]) == "Po":
2066 while unicodedata.category(word[-1]) == "Po":
2068 if word in typos.keys():
2069 words[index] = words[index].replace(word, typos[word])
2070 message = " ".join(words)
2072 # capitalize the first letter
2073 message = message[0].upper() + message[1:]
2077 actor.echo_to_location(
2078 actor.get("name") + " " + action + 's, "' + message + '"'
2080 actor.send("You " + action + ', "' + message + '"')
2082 # there was no message
2084 actor.send("What do you want to say?")
2087 def command_chat(actor):
2088 """Toggle chat mode."""
2089 mode = actor.get("mode")
2091 actor.set("mode", "chat")
2092 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
2093 elif mode == "chat":
2094 actor.remove_facet("mode")
2095 actor.send("Exiting chat mode.")
2097 actor.send("Sorry, but you're already busy with something else!")
2100 def command_show(actor, parameters):
2101 """Show program data."""
2103 arguments = parameters.split()
2105 message = "What do you want to show?"
2106 elif arguments[0] == "version":
2107 message = repr(universe.versions)
2108 elif arguments[0] == "time":
2109 message = universe.groups["internal"]["counters"].get(
2111 ) + " increments elapsed since the world was created."
2112 elif arguments[0] == "groups":
2113 message = "These are the element groups:$(eol)"
2114 groups = list(universe.groups.keys())
2116 for group in groups:
2117 message += "$(eol) $(grn)" + group + "$(nrm)"
2118 elif arguments[0] == "files":
2119 message = "These are the current files containing the universe:$(eol)"
2120 filenames = sorted(universe.files)
2121 for filename in filenames:
2122 if universe.files[filename].is_writeable():
2126 message += ("$(eol) $(red)(%s) $(grn)%s$(nrm)" %
2128 if universe.files[filename].flags:
2129 message += (" $(yel)[%s]$(nrm)" %
2130 ",".join(universe.files[filename].flags))
2131 elif arguments[0] == "group":
2132 if len(arguments) != 2:
2133 message = "You must specify one group."
2134 elif arguments[1] in universe.groups:
2135 message = ('These are the elements in the "' + arguments[1]
2139 universe.groups[arguments[1]][x].key
2140 ) for x in universe.groups[arguments[1]].keys()
2143 for element in elements:
2144 message += "$(eol) $(grn)" + element + "$(nrm)"
2146 message = 'Group "' + arguments[1] + '" does not exist.'
2147 elif arguments[0] == "file":
2148 if len(arguments) != 2:
2149 message = "You must specify one file."
2150 elif arguments[1] in universe.files:
2151 message = ('These are the nodes in the "' + arguments[1]
2153 elements = sorted(universe.files[arguments[1]].data)
2154 for element in elements:
2155 message += "$(eol) $(grn)" + element + "$(nrm)"
2157 message = 'File "%s" does not exist.' % arguments[1]
2158 elif arguments[0] == "element":
2159 if len(arguments) != 2:
2160 message = "You must specify one element."
2161 elif arguments[1].strip(".") in universe.contents:
2162 element = universe.contents[arguments[1].strip(".")]
2163 message = ('These are the properties of the "' + arguments[1]
2164 + '" element (in "' + element.origin.source
2166 facets = element.facets()
2167 for facet in sorted(facets):
2168 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
2169 (facet, str(facets[facet])))
2171 message = 'Element "' + arguments[1] + '" does not exist.'
2172 elif arguments[0] == "result":
2173 if len(arguments) < 2:
2174 message = "You need to specify an expression."
2177 message = repr(eval(" ".join(arguments[1:])))
2178 except Exception as e:
2179 message = ("$(red)Your expression raised an exception...$(eol)"
2180 "$(eol)$(bld)%s$(nrm)" % e)
2181 elif arguments[0] == "log":
2182 if len(arguments) == 4:
2183 if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
2184 stop = int(arguments[3])
2189 if len(arguments) >= 3:
2190 if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
2191 start = int(arguments[2])
2196 if len(arguments) >= 2:
2197 if (re.match(r"^\d+$", arguments[1])
2198 and 0 <= int(arguments[1]) <= 9):
2199 level = int(arguments[1])
2202 elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
2203 level = actor.owner.account.get("loglevel", 0)
2206 if level > -1 and start > -1 and stop > -1:
2207 message = get_loglines(level, start, stop)
2209 message = ("When specified, level must be 0-9 (default 1), "
2210 "start and stop must be >=1 (default 10 and 1).")
2212 message = '''I don't know what "''' + parameters + '" is.'
2216 def command_create(actor, parameters):
2217 """Create an element if it does not exist."""
2219 message = "You must at least specify an element to create."
2220 elif not actor.owner:
2223 arguments = parameters.split()
2224 if len(arguments) == 1:
2225 arguments.append("")
2226 if len(arguments) == 2:
2227 element, filename = arguments
2228 if element in universe.contents:
2229 message = 'The "' + element + '" element already exists.'
2231 message = ('You create "' +
2232 element + '" within the universe.')
2233 logline = actor.owner.account.get(
2235 ) + " created an element: " + element
2237 logline += " in file " + filename
2238 if filename not in universe.files:
2240 ' Warning: "' + filename + '" is not yet '
2241 "included in any other file and will not be read "
2242 "on startup unless this is remedied.")
2243 Element(element, universe, filename)
2245 elif len(arguments) > 2:
2246 message = "You can only specify an element and a filename."
2250 def command_destroy(actor, parameters):
2251 """Destroy an element if it exists."""
2254 message = "You must specify an element to destroy."
2256 if parameters not in universe.contents:
2257 message = 'The "' + parameters + '" element does not exist.'
2259 universe.contents[parameters].destroy()
2260 message = ('You destroy "' + parameters
2261 + '" within the universe.')
2263 actor.owner.account.get(
2265 ) + " destroyed an element: " + parameters,
2271 def command_set(actor, parameters):
2272 """Set a facet of an element."""
2274 message = "You must specify an element, a facet and a value."
2276 arguments = parameters.split(" ", 2)
2277 if len(arguments) == 1:
2278 message = ('What facet of element "' + arguments[0]
2279 + '" would you like to set?')
2280 elif len(arguments) == 2:
2281 message = ('What value would you like to set for the "' +
2282 arguments[1] + '" facet of the "' + arguments[0]
2285 element, facet, value = arguments
2286 if element not in universe.contents:
2287 message = 'The "' + element + '" element does not exist.'
2290 universe.contents[element].set(facet, value)
2291 except PermissionError:
2292 message = ('The "%s" element is kept in read-only file '
2293 '"%s" and cannot be altered.' %
2294 (element, universe.contents[
2295 element].origin.source))
2297 message = ('Value "%s" of type "%s" cannot be coerced '
2298 'to the correct datatype for facet "%s".' %
2299 (value, type(value), facet))
2301 message = ('You have successfully (re)set the "' + facet
2302 + '" facet of element "' + element
2303 + '". Try "show element ' +
2304 element + '" for verification.')
2308 def command_delete(actor, parameters):
2309 """Delete a facet from an element."""
2311 message = "You must specify an element and a facet."
2313 arguments = parameters.split(" ")
2314 if len(arguments) == 1:
2315 message = ('What facet of element "' + arguments[0]
2316 + '" would you like to delete?')
2317 elif len(arguments) != 2:
2318 message = "You may only specify an element and a facet."
2320 element, facet = arguments
2321 if element not in universe.contents:
2322 message = 'The "' + element + '" element does not exist.'
2323 elif facet not in universe.contents[element].facets():
2324 message = ('The "' + element + '" element has no "' + facet
2327 universe.contents[element].remove_facet(facet)
2328 message = ('You have successfully deleted the "' + facet
2329 + '" facet of element "' + element
2330 + '". Try "show element ' +
2331 element + '" for verification.')
2335 def command_error(actor, input_data):
2336 """Generic error for an unrecognized command word."""
2338 # 90% of the time use a generic error
2339 if random.randrange(10):
2340 message = '''I'm not sure what "''' + input_data + '''" means...'''
2342 # 10% of the time use the classic diku error
2344 message = "Arglebargle, glop-glyf!?!"
2346 # send the error message
2350 def daemonize(universe):
2351 """Fork and disassociate from everything."""
2353 # only if this is what we're configured to do
2354 if "mudpy.process" in universe.contents and universe.contents[
2355 "mudpy.process"].get("daemon"):
2357 # log before we start forking around, so the terminal gets the message
2358 log("Disassociating from the controlling terminal.")
2360 # fork off and die, so we free up the controlling terminal
2364 # switch to a new process group
2367 # fork some more, this time to free us from the old process group
2371 # reset the working directory so we don't needlessly tie up mounts
2374 # clear the file creation mask so we can bend it to our will later
2377 # redirect stdin/stdout/stderr and close off their former descriptors
2378 for stdpipe in range(3):
2380 sys.stdin = codecs.open("/dev/null", "r", "utf-8")
2381 sys.__stdin__ = codecs.open("/dev/null", "r", "utf-8")
2382 sys.stdout = codecs.open("/dev/null", "w", "utf-8")
2383 sys.stderr = codecs.open("/dev/null", "w", "utf-8")
2384 sys.__stdout__ = codecs.open("/dev/null", "w", "utf-8")
2385 sys.__stderr__ = codecs.open("/dev/null", "w", "utf-8")
2388 def create_pidfile(universe):
2389 """Write a file containing the current process ID."""
2390 pid = str(os.getpid())
2391 log("Process ID: " + pid)
2392 if "mudpy.process" in universe.contents:
2393 file_name = universe.contents["mudpy.process"].get("pidfile", "")
2397 if not os.path.isabs(file_name):
2398 file_name = os.path.join(universe.startdir, file_name)
2399 file_descriptor = codecs.open(file_name, "w", "utf-8")
2400 file_descriptor.write(pid + "\n")
2401 file_descriptor.flush()
2402 file_descriptor.close()
2405 def remove_pidfile(universe):
2406 """Remove the file containing the current process ID."""
2407 if "mudpy.process" in universe.contents:
2408 file_name = universe.contents["mudpy.process"].get("pidfile", "")
2412 if not os.path.isabs(file_name):
2413 file_name = os.path.join(universe.startdir, file_name)
2414 if os.access(file_name, os.W_OK):
2415 os.remove(file_name)
2418 def excepthook(excepttype, value, tracebackdata):
2419 """Handle uncaught exceptions."""
2421 # assemble the list of errors into a single string
2423 traceback.format_exception(excepttype, value, tracebackdata)
2426 # try to log it, if possible
2429 except Exception as e:
2430 # try to write it to stderr, if possible
2431 sys.stderr.write(message + "\nException while logging...\n%s" % e)
2434 def sighook(what, where):
2435 """Handle external signals."""
2438 message = "Caught signal: "
2440 # for a hangup signal
2441 if what == signal.SIGHUP:
2442 message += "hangup (reloading)"
2443 universe.reload_flag = True
2445 # for a terminate signal
2446 elif what == signal.SIGTERM:
2447 message += "terminate (halting)"
2448 universe.terminate_flag = True
2450 # catchall for unexpected signals
2452 message += str(what) + " (unhandled)"
2458 def override_excepthook():
2459 """Redefine sys.excepthook with our own."""
2460 sys.excepthook = excepthook
2463 def assign_sighook():
2464 """Assign a customized handler for some signals."""
2465 signal.signal(signal.SIGHUP, sighook)
2466 signal.signal(signal.SIGTERM, sighook)
2470 """This contains functions to be performed when starting the engine."""
2472 # see if a configuration file was specified
2473 if len(sys.argv) > 1:
2474 conffile = sys.argv[1]
2480 universe = Universe(conffile, True)
2482 # report any loglines which accumulated during setup
2483 for logline in universe.setup_loglines:
2485 universe.setup_loglines = []
2487 # fork and disassociate
2490 # override the default exception handler so we get logging first thing
2491 override_excepthook()
2493 # set up custom signal handlers
2497 create_pidfile(universe)
2499 # load and store diagnostic info
2500 universe.versions = mudpy.version.Versions("mudpy")
2502 # log startup diagnostic messages
2503 log("On %s at %s" % (universe.versions.python_version, sys.executable), 1)
2504 log("Import path: %s" % ", ".join(sys.path), 1)
2505 log("Installed dependencies: %s" % universe.versions.dependencies_text, 1)
2506 log("Other python packages: %s" % universe.versions.environment_text, 1)
2507 log("Started %s with command line: %s" % (
2508 universe.versions.version, " ".join(sys.argv)), 1)
2510 # pass the initialized universe back
2515 """These are functions performed when shutting down the engine."""
2517 # the loop has terminated, so save persistent data
2520 # log a final message
2521 log("Shutting down now.")
2523 # get rid of the pidfile
2524 remove_pidfile(universe)