1 """Miscellaneous functions for the mudpy engine."""
3 # Copyright (c) 2004-2017 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 if facet in ["loglevel"]:
134 elif facet in ["administrator"]:
136 if not self.has_facet(facet) or not self.get(facet) == value:
137 node = ".".join((self.key, facet))
138 self.origin.data[node] = value
139 self.facethash[facet] = self.origin.data[node]
140 self.origin.modified = True
142 def append(self, facet, value):
143 """Append value to a list."""
144 newlist = self.get(facet)
147 if type(newlist) is not list:
148 newlist = list(newlist)
149 newlist.append(value)
150 self.set(facet, newlist)
160 add_terminator=False,
163 """Convenience method to pass messages to an owner."""
176 def can_run(self, command):
177 """Check if the user can run this command object."""
179 # has to be in the commands group
180 if command not in self.universe.groups["command"].values():
183 # avatars of administrators can run any command
184 elif self.owner and self.owner.account.get("administrator"):
187 # everyone can run non-administrative commands
188 elif not command.get("administrative"):
191 # otherwise the command cannot be run by this actor
195 # pass back the result
198 def update_location(self):
199 """Make sure the location's contents contain this element."""
200 area = self.get("location")
201 if area in self.universe.contents:
202 self.universe.contents[area].contents[self.key] = self
204 def clean_contents(self):
205 """Make sure the element's contents aren't bogus."""
206 for element in self.contents.values():
207 if element.get("location") != self.key:
208 del self.contents[element.key]
210 def go_to(self, area):
211 """Relocate the element to a specific area."""
212 current = self.get("location")
213 if current and self.key in self.universe.contents[current].contents:
214 del universe.contents[current].contents[self.key]
215 if area in self.universe.contents:
216 self.set("location", area)
217 self.universe.contents[area].contents[self.key] = self
221 """Relocate the element to its default location."""
222 self.go_to(self.get("default_location"))
223 self.echo_to_location(
224 "You suddenly realize that " + self.get("name") + " is here."
227 def move_direction(self, direction):
228 """Relocate the element in a specified direction."""
229 motion = self.universe.contents["mudpy.movement.%s" % direction]
230 enter_term = motion.get("enter_term")
231 exit_term = motion.get("exit_term")
232 self.echo_to_location("%s exits %s." % (self.get("name"), exit_term))
233 self.send("You exit %s." % exit_term, add_prompt=False)
235 self.universe.contents[
236 self.get("location")].link_neighbor(direction)
238 self.echo_to_location("%s arrives from %s." % (
239 self.get("name"), enter_term))
241 def look_at(self, key):
242 """Show an element to another element."""
244 element = self.universe.contents[key]
246 name = element.get("name")
248 message += "$(cyn)" + name + "$(nrm)$(eol)"
249 description = element.get("description")
251 message += description + "$(eol)"
252 portal_list = list(element.portals().keys())
255 message += "$(cyn)[ Exits: " + ", ".join(
258 for element in self.universe.contents[
261 if element.get("is_actor") and element is not self:
262 message += "$(yel)" + element.get(
264 ) + " is here.$(nrm)$(eol)"
265 elif element is not self:
266 message += "$(grn)" + element.get(
272 """Map the portal directions for an area to neighbors."""
274 if re.match(r"""^area\.-?\d+,-?\d+,-?\d+$""", self.key):
275 coordinates = [(int(x))
276 for x in self.key.split(".")[-1].split(",")]
279 self.universe.contents["mudpy.movement.%s" % x].get("vector")
280 ) for x in self.universe.directions)
281 for portal in self.get("gridlinks"):
282 adjacent = map(lambda c, o: c + o,
283 coordinates, offsets[portal])
284 neighbor = "area." + ",".join(
285 [(str(x)) for x in adjacent]
287 if neighbor in self.universe.contents:
288 portals[portal] = neighbor
289 for facet in self.facets():
290 if facet.startswith("link_"):
291 neighbor = self.get(facet)
292 if neighbor in self.universe.contents:
293 portal = facet.split("_")[1]
294 portals[portal] = neighbor
297 def link_neighbor(self, direction):
298 """Return the element linked in a given direction."""
299 portals = self.portals()
300 if direction in portals:
301 return portals[direction]
303 def echo_to_location(self, message):
304 """Show a message to other elements in the current location."""
305 for element in self.universe.contents[
308 if element is not self:
309 element.send(message)
316 def __init__(self, filename="", load=False):
317 """Initialize the universe."""
320 self.directions = set()
324 self.reload_flag = False
325 self.setup_loglines = []
326 self.startdir = os.getcwd()
327 self.terminate_flag = False
330 possible_filenames = [
332 "/usr/local/mudpy/etc/mudpy.yaml",
333 "/usr/local/etc/mudpy.yaml",
334 "/etc/mudpy/mudpy.yaml",
337 for filename in possible_filenames:
338 if os.access(filename, os.R_OK):
340 if not os.path.isabs(filename):
341 filename = os.path.join(self.startdir, filename)
342 self.filename = filename
344 # make sure to preserve any accumulated log entries during load
345 self.setup_loglines += self.load()
348 """Load universe data from persistent storage."""
350 # while loading, it's safe to update elements from read-only files
353 # it's possible for this to enter before logging configuration is read
354 pending_loglines = []
356 # the files dict must exist and filename needs to be read-only
360 self.filename in self.files and self.files[
365 # clear out all read-only files
366 if hasattr(self, "files"):
367 for data_filename in list(self.files.keys()):
368 if not self.files[data_filename].is_writeable():
369 del self.files[data_filename]
371 # start loading from the initial file
372 mudpy.data.Data(self.filename, self)
374 # load default storage locations for groups
375 if hasattr(self, "contents") and "mudpy.filing" in self.contents:
376 self.origins.update(self.contents["mudpy.filing"].get(
379 # add some builtin groups we know we'll need
380 for group in ("account", "actor", "internal"):
381 self.add_group(group)
383 # make a list of inactive avatars
384 inactive_avatars = []
385 for account in self.groups.get("account", {}).values():
386 for avatar in account.get("avatars"):
388 inactive_avatars.append(self.contents[avatar])
390 pending_loglines.append((
391 'Missing avatar "%s", possible data corruption' %
393 for user in self.userlist:
394 if user.avatar in inactive_avatars:
395 inactive_avatars.remove(user.avatar)
397 # go through all elements to clear out inactive avatar locations
398 for element in self.contents.values():
399 area = element.get("location")
400 if element in inactive_avatars and area:
401 if area in self.contents and element.key in self.contents[
404 del self.contents[area].contents[element.key]
405 element.set("default_location", area)
406 element.remove_facet("location")
408 # another pass to straighten out all the element contents
409 for element in self.contents.values():
410 element.update_location()
411 element.clean_contents()
413 # done loading, so disallow updating elements from read-only files
416 return pending_loglines
419 """Create a new, empty Universe (the Big Bang)."""
420 new_universe = Universe()
421 for attribute in vars(self).keys():
422 exec("new_universe." + attribute + " = self." + attribute)
423 new_universe.reload_flag = False
428 """Save the universe to persistent storage."""
429 for key in self.files:
430 self.files[key].save()
432 def initialize_server_socket(self):
433 """Create and open the listening socket."""
435 # need to know the local address and port number for the listener
436 host = self.contents["mudpy.network"].get("host")
437 port = self.contents["mudpy.network"].get("port")
439 # if no host was specified, bind to all local addresses (preferring
447 # figure out if this is ipv4 or v6
448 family = socket.getaddrinfo(host, port)[0][0]
449 if family is socket.AF_INET6 and not socket.has_ipv6:
450 log("No support for IPv6 address %s (use IPv4 instead)." % host)
452 # create a new stream-type socket object
453 self.listening_socket = socket.socket(family, socket.SOCK_STREAM)
455 # set the socket options to allow existing open ones to be
456 # reused (fixes a bug where the server can't bind for a minute
457 # when restarting on linux systems)
458 self.listening_socket.setsockopt(
459 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1
462 # bind the socket to to our desired server ipa and port
463 self.listening_socket.bind((host, port))
465 # disable blocking so we can proceed whether or not we can
467 self.listening_socket.setblocking(0)
469 # start listening on the socket
470 self.listening_socket.listen(1)
472 # note that we're now ready for user connections
474 "Listening for Telnet connections on: " +
475 host + ":" + str(port)
479 """Convenience method to get the elapsed time counter."""
480 return self.groups["internal"]["counters"].get("elapsed")
482 def add_group(self, group, fallback=None):
483 """Set up group tracking/metadata."""
484 if group not in self.origins:
485 self.origins[group] = {}
487 fallback = mudpy.data.find_file(
488 ".".join((group, "yaml")), universe=self)
489 if "fallback" not in self.origins[group]:
490 self.origins[group]["fallback"] = fallback
491 flags = self.origins[group].get("flags", None)
492 if fallback not in self.files:
493 mudpy.data.Data(fallback, self, flags=flags)
498 """This is a connected user."""
501 """Default values for the in-memory user variables."""
504 self.authenticated = False
507 self.connection = None
509 self.input_queue = []
510 self.last_address = ""
511 self.last_input = universe.get_time()
512 self.menu_choices = {}
513 self.menu_seen = False
514 self.negotiation_pause = 0
515 self.output_queue = []
516 self.partial_input = b""
517 self.password_tries = 0
518 self.state = "initial"
522 """Log, close the connection and remove."""
524 name = self.account.get("name")
528 message = "User " + name
530 message = "An unnamed user"
531 message += " logged out."
533 self.deactivate_avatar()
534 self.connection.close()
537 def check_idle(self):
538 """Warn or disconnect idle users as appropriate."""
539 idletime = universe.get_time() - self.last_input
540 linkdead_dict = universe.contents[
541 "mudpy.timing.idle.disconnect"].facets()
542 if self.state in linkdead_dict:
543 linkdead_state = self.state
545 linkdead_state = "default"
546 if idletime > linkdead_dict[linkdead_state]:
548 "$(eol)$(red)You've done nothing for far too long... goodbye!"
553 logline = "Disconnecting "
554 if self.account and self.account.get("name"):
555 logline += self.account.get("name")
557 logline += "an unknown user"
558 logline += (" after idling too long in the " + self.state
561 self.state = "disconnecting"
562 self.menu_seen = False
563 idle_dict = universe.contents["mudpy.timing.idle.warn"].facets()
564 if self.state in idle_dict:
565 idle_state = self.state
567 idle_state = "default"
568 if idletime == idle_dict[idle_state]:
570 "$(eol)$(red)If you continue to be unproductive, "
571 + "you'll be shown the door...$(nrm)$(eol)"
575 """Save, load a new user and relocate the connection."""
577 # get out of the list
580 # create a new user object
583 # set everything equivalent
584 for attribute in vars(self).keys():
585 exec("new_user." + attribute + " = self." + attribute)
587 # the avatar needs a new owner
589 new_user.avatar.owner = new_user
592 universe.userlist.append(new_user)
594 # get rid of the old user object
597 def replace_old_connections(self):
598 """Disconnect active users with the same name."""
600 # the default return value
603 # iterate over each user in the list
604 for old_user in universe.userlist:
606 # the name is the same but it's not us
609 ) and old_user.account and old_user.account.get(
611 ) == self.account.get(
613 ) and old_user is not self:
617 "User " + self.account.get(
619 ) + " reconnected--closing old connection to "
620 + old_user.address + ".",
624 "$(eol)$(red)New connection from " + self.address
625 + ". Terminating old connection...$(nrm)$(eol)",
630 # close the old connection
631 old_user.connection.close()
633 # replace the old connection with this one
635 "$(eol)$(red)Taking over old connection from "
636 + old_user.address + ".$(nrm)"
638 old_user.connection = self.connection
639 old_user.last_address = old_user.address
640 old_user.address = self.address
642 # take this one out of the list and delete
648 # true if an old connection was replaced, false if not
651 def authenticate(self):
652 """Flag the user as authenticated and disconnect duplicates."""
653 if self.state is not "authenticated":
654 self.authenticated = True
655 if ("mudpy.limit" in universe.contents and self.account.subkey in
656 universe.contents["mudpy.limit"].get("admins")):
657 self.account.set("administrator", True)
658 log("Administrator %s authenticated." %
659 self.account.get("name"), 2)
661 # log("User %s authenticated." % self.account.get("name"), 2)
662 log("User %s authenticated." % self.account.subkey, 2)
665 """Send the user their current menu."""
666 if not self.menu_seen:
667 self.menu_choices = get_menu_choices(self)
669 get_menu(self.state, self.error, self.menu_choices),
673 self.menu_seen = True
675 self.adjust_echoing()
677 def adjust_echoing(self):
678 """Adjust echoing to match state menu requirements."""
679 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_ECHO,
681 if menu_echo_on(self.state):
682 mudpy.telnet.disable(self, mudpy.telnet.TELOPT_ECHO,
684 elif not menu_echo_on(self.state):
685 mudpy.telnet.enable(self, mudpy.telnet.TELOPT_ECHO,
689 """Remove a user from the list of connected users."""
690 universe.userlist.remove(self)
700 add_terminator=False,
703 """Send arbitrary text to a connected user."""
705 # unless raw mode is on, clean it up all nice and pretty
708 # strip extra $(eol) off if present
709 while output.startswith("$(eol)"):
711 while output.endswith("$(eol)"):
713 extra_lines = output.find("$(eol)$(eol)$(eol)")
714 while extra_lines > -1:
715 output = output[:extra_lines] + output[extra_lines + 6:]
716 extra_lines = output.find("$(eol)$(eol)$(eol)")
718 # start with a newline, append the message, then end
719 # with the optional eol string passed to this function
720 # and the ansi escape to return to normal text
721 if not just_prompt and prepend_padding:
722 if (not self.output_queue or not
723 self.output_queue[-1].endswith(b"\r\n")):
724 output = "$(eol)" + output
725 elif not self.output_queue[-1].endswith(
727 ) and not self.output_queue[-1].endswith(
730 output = "$(eol)" + output
731 output += eol + chr(27) + "[0m"
733 # tack on a prompt if active
734 if self.state == "active":
739 mode = self.avatar.get("mode")
741 output += "(" + mode + ") "
743 # find and replace macros in the output
744 output = replace_macros(self, output)
746 # wrap the text at the client's width (min 40, 0 disables)
748 if self.columns < 40:
752 output = wrap_ansi_text(output, wrap)
754 # if supported by the client, encode it utf-8
755 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
757 encoded_output = output.encode("utf-8")
759 # otherwise just send ascii
761 encoded_output = output.encode("ascii", "replace")
763 # end with a terminator if requested
764 if add_prompt or add_terminator:
765 if mudpy.telnet.is_enabled(
766 self, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US):
767 encoded_output += mudpy.telnet.telnet_proto(
768 mudpy.telnet.IAC, mudpy.telnet.EOR)
769 elif not mudpy.telnet.is_enabled(
770 self, mudpy.telnet.TELOPT_SGA, mudpy.telnet.US):
771 encoded_output += mudpy.telnet.telnet_proto(
772 mudpy.telnet.IAC, mudpy.telnet.GA)
774 # and tack it onto the queue
775 self.output_queue.append(encoded_output)
777 # if this is urgent, flush all pending output
781 # just dump raw bytes as requested
783 self.output_queue.append(output)
787 """All the things to do to the user per increment."""
789 # if the world is terminating, disconnect
790 if universe.terminate_flag:
791 self.state = "disconnecting"
792 self.menu_seen = False
794 # check for an idle connection and act appropriately
798 # if output is paused, decrement the counter
799 if self.state == "initial":
800 if self.negotiation_pause:
801 self.negotiation_pause -= 1
803 self.state = "entering_account_name"
805 # show the user a menu as needed
806 elif not self.state == "active":
809 # flush any pending output in the queue
812 # disconnect users with the appropriate state
813 if self.state == "disconnecting":
816 # check for input and add it to the queue
819 # there is input waiting in the queue
821 handle_user_input(self)
824 """Try to send the last item in the queue and remove it."""
825 if self.output_queue:
827 self.connection.send(self.output_queue[0])
828 except BrokenPipeError:
829 if self.account and self.account.get("name"):
830 account = self.account.get("name")
832 account = "an unknown user"
833 self.state = "disconnecting"
834 log("Broken pipe sending to %s." % account, 7)
835 del self.output_queue[0]
837 def enqueue_input(self):
838 """Process and enqueue any new input."""
840 # check for some input
842 raw_input = self.connection.recv(1024)
843 except (BlockingIOError, OSError):
849 # tack this on to any previous partial
850 self.partial_input += raw_input
852 # reply to and remove any IAC negotiation codes
853 mudpy.telnet.negotiate_telnet_options(self)
855 # separate multiple input lines
856 new_input_lines = self.partial_input.split(b"\n")
858 # if input doesn't end in a newline, replace the
859 # held partial input with the last line of it
860 if not self.partial_input.endswith(b"\n"):
861 self.partial_input = new_input_lines.pop()
863 # otherwise, chop off the extra null input and reset
864 # the held partial input
866 new_input_lines.pop()
867 self.partial_input = b""
869 # iterate over the remaining lines
870 for line in new_input_lines:
872 # strip off extra whitespace
875 # log non-printable characters remaining
876 if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
878 asciiline = bytes([x for x in line if 32 <= x <= 126])
879 if line != asciiline:
880 logline = "Non-ASCII characters from "
881 if self.account and self.account.get("name"):
882 logline += self.account.get("name") + ": "
884 logline += "unknown user: "
885 logline += repr(line)
890 line = line.decode("utf-8")
891 except UnicodeDecodeError:
892 logline = "Non-UTF-8 characters from "
893 if self.account and self.account.get("name"):
894 logline += self.account.get("name") + ": "
896 logline += "unknown user: "
897 logline += repr(line)
901 line = unicodedata.normalize("NFKC", line)
903 # put on the end of the queue
904 self.input_queue.append(line)
906 def new_avatar(self):
907 """Instantiate a new, unconfigured avatar for this user."""
909 while ("avatar_%s_%s" % (self.account.get("name"), counter)
910 in universe.groups.get("actor", {}).keys()):
912 self.avatar = Element(
913 "actor.avatar_%s_%s" % (self.account.get("name"), counter),
915 self.avatar.append("inherit", "archetype.avatar")
916 self.account.append("avatars", self.avatar.key)
918 def delete_avatar(self, avatar):
919 """Remove an avatar from the world and from the user's list."""
920 if self.avatar is universe.contents[avatar]:
922 universe.contents[avatar].destroy()
923 avatars = self.account.get("avatars")
924 avatars.remove(avatar)
925 self.account.set("avatars", avatars)
927 def activate_avatar_by_index(self, index):
928 """Enter the world with a particular indexed avatar."""
929 self.avatar = universe.contents[
930 self.account.get("avatars")[index]]
931 self.avatar.owner = self
932 self.state = "active"
933 self.avatar.go_home()
935 def deactivate_avatar(self):
936 """Have the active avatar leave the world."""
938 current = self.avatar.get("location")
940 self.avatar.set("default_location", current)
941 self.avatar.echo_to_location(
942 "You suddenly wonder where " + self.avatar.get(
946 del universe.contents[current].contents[self.avatar.key]
947 self.avatar.remove_facet("location")
948 self.avatar.owner = None
952 """Destroy the user and associated avatars."""
953 for avatar in self.account.get("avatars"):
954 self.delete_avatar(avatar)
955 self.account.destroy()
957 def list_avatar_names(self):
958 """List names of assigned avatars."""
960 for avatar in self.account.get("avatars"):
962 avatars.append(universe.contents[avatar].get("name"))
964 log('Missing avatar "%s", possible data corruption.' %
969 def broadcast(message, add_prompt=True):
970 """Send a message to all connected users."""
971 for each_user in universe.userlist:
972 each_user.send("$(eol)" + message, add_prompt=add_prompt)
975 def log(message, level=0):
978 # a couple references we need
979 if "mudpy.log" in universe.contents:
980 file_name = universe.contents["mudpy.log"].get("file", "")
981 max_log_lines = universe.contents["mudpy.log"].get("lines", 0)
982 syslog_name = universe.contents["mudpy.log"].get("syslog", "")
987 timestamp = time.asctime()[4:19]
989 # turn the message into a list of nonempty lines
990 lines = [x for x in [(x.rstrip()) for x in message.split("\n")] if x != ""]
992 # send the timestamp and line to a file
994 if not os.path.isabs(file_name):
995 file_name = os.path.join(universe.startdir, file_name)
996 file_descriptor = codecs.open(file_name, "a", "utf-8")
998 file_descriptor.write(timestamp + " " + line + "\n")
999 file_descriptor.flush()
1000 file_descriptor.close()
1002 # send the timestamp and line to standard output
1003 if ("mudpy.log" in universe.contents and
1004 universe.contents["mudpy.log"].get("stdout")):
1006 print(timestamp + " " + line)
1008 # send the line to the system log
1011 syslog_name.encode("utf-8"),
1013 syslog.LOG_INFO | syslog.LOG_DAEMON
1019 # display to connected administrators
1020 for user in universe.userlist:
1021 if user.state == "active" and user.account.get(
1023 ) and user.account.get("loglevel", 0) <= level:
1024 # iterate over every line in the message
1028 "$(bld)$(red)" + timestamp + " "
1029 + line.replace("$(", "$_(") + "$(nrm)$(eol)")
1030 user.send(full_message, flush=True)
1032 # add to the recent log list
1034 while 0 < len(universe.loglines) >= max_log_lines:
1035 del universe.loglines[0]
1036 universe.loglines.append((level, timestamp + " " + line))
1039 def get_loglines(level, start, stop):
1040 """Return a specific range of loglines filtered by level."""
1042 # filter the log lines
1043 loglines = [x for x in universe.loglines if x[0] >= level]
1045 # we need these in several places
1046 total_count = str(len(universe.loglines))
1047 filtered_count = len(loglines)
1049 # don't proceed if there are no lines
1052 # can't start before the begining or at the end
1053 if start > filtered_count:
1054 start = filtered_count
1058 # can't stop before we start
1065 message = "There are " + str(total_count)
1066 message += " log lines in memory and " + str(filtered_count)
1067 message += " at or above level " + str(level) + "."
1068 message += " The matching lines from " + str(stop) + " to "
1069 message += str(start) + " are:$(eol)$(eol)"
1071 # add the text from the selected lines
1073 range_lines = loglines[-start:-(stop - 1)]
1075 range_lines = loglines[-start:]
1076 for line in range_lines:
1077 message += " (" + str(line[0]) + ") " + line[1].replace(
1081 # there were no lines
1083 message = "None of the " + str(total_count)
1084 message += " lines in memory matches your request."
1090 def glyph_columns(character):
1091 """Convenience function to return the column width of a glyph."""
1092 if unicodedata.east_asian_width(character) in "FW":
1098 def wrap_ansi_text(text, width):
1099 """Wrap text with arbitrary width while ignoring ANSI colors."""
1101 # the current position in the entire text string, including all
1102 # characters, printable or otherwise
1105 # the current text position relative to the begining of the line,
1106 # ignoring color escape sequences
1109 # the absolute position of the most recent whitespace character
1112 # whether the current character is part of a color escape sequence
1115 # normalize any potentially composited unicode before we count it
1116 text = unicodedata.normalize("NFKC", text)
1118 # iterate over each character from the begining of the text
1119 for each_character in text:
1121 # the current character is the escape character
1122 if each_character == "\x1b" and not escape:
1125 # the current character is within an escape sequence
1128 # the current character is m, which terminates the
1130 if each_character == "m":
1133 # the current character is a newline, so reset the relative
1134 # position (start a new line)
1135 elif each_character == "\n":
1137 last_whitespace = abs_pos
1139 # the current character meets the requested maximum line width,
1140 # so we need to backtrack and find a space at which to wrap;
1141 # special care is taken to avoid an off-by-one in case the
1142 # current character is a double-width glyph
1143 elif each_character != "\r" and (
1144 rel_pos >= width or (
1145 rel_pos >= width - 1 and glyph_columns(
1151 # it's always possible we landed on whitespace
1152 if unicodedata.category(each_character) in ("Cc", "Zs"):
1153 last_whitespace = abs_pos
1155 # insert an eol in place of the space
1156 text = text[:last_whitespace] + "\r\n" + text[last_whitespace + 1:]
1158 # increase the absolute position because an eol is two
1159 # characters but the space it replaced was only one
1162 # now we're at the begining of a new line, plus the
1163 # number of characters wrapped from the previous line
1165 for remaining_characters in text[last_whitespace:abs_pos]:
1166 rel_pos += glyph_columns(remaining_characters)
1168 # as long as the character is not a carriage return and the
1169 # other above conditions haven't been met, count it as a
1170 # printable character
1171 elif each_character != "\r":
1172 rel_pos += glyph_columns(each_character)
1173 if unicodedata.category(each_character) in ("Cc", "Zs"):
1174 last_whitespace = abs_pos
1176 # increase the absolute position for every character
1179 # return the newly-wrapped text
1183 def weighted_choice(data):
1184 """Takes a dict weighted by value and returns a random key."""
1186 # this will hold our expanded list of keys from the data
1189 # create the expanded list of keys
1190 for key in data.keys():
1191 for count in range(data[key]):
1192 expanded.append(key)
1194 # return one at random
1195 return random.choice(expanded)
1199 """Returns a random character name."""
1201 # the vowels and consonants needed to create romaji syllables
1230 # this dict will hold our weighted list of syllables
1233 # generate the list with an even weighting
1234 for consonant in consonants:
1235 for vowel in vowels:
1236 syllables[consonant + vowel] = 1
1238 # we'll build the name into this string
1241 # create a name of random length from the syllables
1242 for syllable in range(random.randrange(2, 6)):
1243 name += weighted_choice(syllables)
1245 # strip any leading quotemark, capitalize and return the name
1246 return name.strip("'").capitalize()
1249 def replace_macros(user, text, is_input=False):
1250 """Replaces macros in text output."""
1252 # third person pronouns
1254 "female": {"obj": "her", "pos": "hers", "sub": "she"},
1255 "male": {"obj": "him", "pos": "his", "sub": "he"},
1256 "neuter": {"obj": "it", "pos": "its", "sub": "it"}
1259 # a dict of replacement macros
1262 "bld": chr(27) + "[1m",
1263 "nrm": chr(27) + "[0m",
1264 "blk": chr(27) + "[30m",
1265 "blu": chr(27) + "[34m",
1266 "cyn": chr(27) + "[36m",
1267 "grn": chr(27) + "[32m",
1268 "mgt": chr(27) + "[35m",
1269 "red": chr(27) + "[31m",
1270 "yel": chr(27) + "[33m",
1273 # add dynamic macros where possible
1275 account_name = user.account.get("name")
1277 macros["account"] = account_name
1279 avatar_gender = user.avatar.get("gender")
1281 macros["tpop"] = pronouns[avatar_gender]["obj"]
1282 macros["tppp"] = pronouns[avatar_gender]["pos"]
1283 macros["tpsp"] = pronouns[avatar_gender]["sub"]
1288 # find and replace per the macros dict
1289 macro_start = text.find("$(")
1290 if macro_start == -1:
1292 macro_end = text.find(")", macro_start) + 1
1293 macro = text[macro_start + 2:macro_end - 1]
1294 if macro in macros.keys():
1295 replacement = macros[macro]
1297 # this is how we handle local file inclusion (dangerous!)
1298 elif macro.startswith("inc:"):
1299 incfile = mudpy.data.find_file(macro[4:], universe=universe)
1300 if os.path.exists(incfile):
1301 incfd = codecs.open(incfile, "r", "utf-8")
1304 if line.endswith("\n") and not line.endswith("\r\n"):
1305 line = line.replace("\n", "\r\n")
1307 # lose the trailing eol
1308 replacement = replacement[:-2]
1311 log("Couldn't read included " + incfile + " file.", 7)
1313 # if we get here, log and replace it with null
1317 log("Unexpected replacement macro " +
1318 macro + " encountered.", 6)
1320 # and now we act on the replacement
1321 text = text.replace("$(" + macro + ")", replacement)
1323 # replace the look-like-a-macro sequence
1324 text = text.replace("$_(", "$(")
1329 def escape_macros(value):
1330 """Escapes replacement macros in text."""
1331 if type(value) is str:
1332 return value.replace("$(", "$_(")
1337 def first_word(text, separator=" "):
1338 """Returns a tuple of the first word and the rest."""
1340 if text.find(separator) > 0:
1341 return text.split(separator, 1)
1349 """The things which should happen on each pulse, aside from reloads."""
1351 # open the listening socket if it hasn't been already
1352 if not hasattr(universe, "listening_socket"):
1353 universe.initialize_server_socket()
1355 # assign a user if a new connection is waiting
1356 user = check_for_connection(universe.listening_socket)
1358 universe.userlist.append(user)
1360 # iterate over the connected users
1361 for user in universe.userlist:
1364 # add an element for counters if it doesn't exist
1365 if "counters" not in universe.groups.get("internal", {}):
1366 Element("internal.counters", universe)
1368 # update the log every now and then
1369 if not universe.groups["internal"]["counters"].get("mark"):
1370 log(str(len(universe.userlist)) + " connection(s)")
1371 universe.groups["internal"]["counters"].set(
1372 "mark", universe.contents["mudpy.timing"].get("status")
1375 universe.groups["internal"]["counters"].set(
1376 "mark", universe.groups["internal"]["counters"].get(
1381 # periodically save everything
1382 if not universe.groups["internal"]["counters"].get("save"):
1384 universe.groups["internal"]["counters"].set(
1385 "save", universe.contents["mudpy.timing"].get("save")
1388 universe.groups["internal"]["counters"].set(
1389 "save", universe.groups["internal"]["counters"].get(
1394 # pause for a configurable amount of time (decimal seconds)
1395 time.sleep(universe.contents["mudpy.timing"].get("increment"))
1397 # increase the elapsed increment counter
1398 universe.groups["internal"]["counters"].set(
1399 "elapsed", universe.groups["internal"]["counters"].get(
1406 """Reload all relevant objects."""
1407 for user in universe.userlist[:]:
1409 for element in universe.contents.values():
1410 if element.origin.is_writeable():
1415 def check_for_connection(listening_socket):
1416 """Check for a waiting connection and return a new user object."""
1418 # try to accept a new connection
1420 connection, address = listening_socket.accept()
1421 except BlockingIOError:
1424 # note that we got one
1425 log("Connection from " + address[0], 2)
1427 # disable blocking so we can proceed whether or not we can send/receive
1428 connection.setblocking(0)
1430 # create a new user object
1433 # associate this connection with it
1434 user.connection = connection
1436 # set the user's ipa from the connection's ipa
1437 user.address = address[0]
1439 # let the client know we WILL EOR (RFC 885)
1440 mudpy.telnet.enable(user, mudpy.telnet.TELOPT_EOR, mudpy.telnet.US)
1441 user.negotiation_pause = 2
1443 # return the new user object
1447 def get_menu(state, error=None, choices=None):
1448 """Show the correct menu text to a user."""
1450 # make sure we don't reuse a mutable sequence by default
1454 # get the description or error text
1455 message = get_menu_description(state, error)
1457 # get menu choices for the current state
1458 message += get_formatted_menu_choices(state, choices)
1460 # try to get a prompt, if it was defined
1461 message += get_menu_prompt(state)
1463 # throw in the default choice, if it exists
1464 message += get_formatted_default_menu_choice(state)
1466 # display a message indicating if echo is off
1467 message += get_echo_message(state)
1469 # return the assembly of various strings defined above
1473 def menu_echo_on(state):
1474 """True if echo is on, false if it is off."""
1475 return universe.groups["menu"][state].get("echo", True)
1478 def get_echo_message(state):
1479 """Return a message indicating that echo is off."""
1480 if menu_echo_on(state):
1483 return "(won't echo) "
1486 def get_default_menu_choice(state):
1487 """Return the default choice for a menu."""
1488 return universe.groups["menu"][state].get("default")
1491 def get_formatted_default_menu_choice(state):
1492 """Default menu choice foratted for inclusion in a prompt string."""
1493 default_choice = get_default_menu_choice(state)
1495 return "[$(red)" + default_choice + "$(nrm)] "
1500 def get_menu_description(state, error):
1501 """Get the description or error text."""
1503 # an error condition was raised by the handler
1506 # try to get an error message matching the condition
1508 description = universe.groups[
1509 "menu"][state].get("error_" + error)
1511 description = "That is not a valid choice..."
1512 description = "$(red)" + description + "$(nrm)"
1514 # there was no error condition
1517 # try to get a menu description for the current state
1518 description = universe.groups["menu"][state].get("description")
1520 # return the description or error message
1522 description += "$(eol)$(eol)"
1526 def get_menu_prompt(state):
1527 """Try to get a prompt, if it was defined."""
1528 prompt = universe.groups["menu"][state].get("prompt")
1534 def get_menu_choices(user):
1535 """Return a dict of choice:meaning."""
1536 menu = universe.groups["menu"][user.state]
1537 create_choices = menu.get("create")
1539 choices = eval(create_choices)
1545 for facet in menu.facets():
1546 if facet.startswith("demand_") and not eval(
1547 universe.groups["menu"][user.state].get(facet)
1549 ignores.append(facet.split("_", 2)[1])
1550 elif facet.startswith("create_"):
1551 creates[facet] = facet.split("_", 2)[1]
1552 elif facet.startswith("choice_"):
1553 options[facet] = facet.split("_", 2)[1]
1554 for facet in creates.keys():
1555 if not creates[facet] in ignores:
1556 choices[creates[facet]] = eval(menu.get(facet))
1557 for facet in options.keys():
1558 if not options[facet] in ignores:
1559 choices[options[facet]] = menu.get(facet)
1563 def get_formatted_menu_choices(state, choices):
1564 """Returns a formatted string of menu choices."""
1566 choice_keys = list(choices.keys())
1568 for choice in choice_keys:
1569 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[
1573 choice_output += "$(eol)"
1574 return choice_output
1577 def get_menu_branches(state):
1578 """Return a dict of choice:branch."""
1580 for facet in universe.groups["menu"][state].facets():
1581 if facet.startswith("branch_"):
1583 facet.split("_", 2)[1]
1584 ] = universe.groups["menu"][state].get(facet)
1588 def get_default_branch(state):
1589 """Return the default branch."""
1590 return universe.groups["menu"][state].get("branch")
1593 def get_choice_branch(user, choice):
1594 """Returns the new state matching the given choice."""
1595 branches = get_menu_branches(user.state)
1596 if choice in branches.keys():
1597 return branches[choice]
1598 elif choice in user.menu_choices.keys():
1599 return get_default_branch(user.state)
1604 def get_menu_actions(state):
1605 """Return a dict of choice:branch."""
1607 for facet in universe.groups["menu"][state].facets():
1608 if facet.startswith("action_"):
1610 facet.split("_", 2)[1]
1611 ] = universe.groups["menu"][state].get(facet)
1615 def get_default_action(state):
1616 """Return the default action."""
1617 return universe.groups["menu"][state].get("action")
1620 def get_choice_action(user, choice):
1621 """Run any indicated script for the given choice."""
1622 actions = get_menu_actions(user.state)
1623 if choice in actions.keys():
1624 return actions[choice]
1625 elif choice in user.menu_choices.keys():
1626 return get_default_action(user.state)
1631 def handle_user_input(user):
1632 """The main handler, branches to a state-specific handler."""
1634 # if the user's client echo is off, send a blank line for aesthetics
1635 if mudpy.telnet.is_enabled(user, mudpy.telnet.TELOPT_ECHO,
1637 user.send("", add_prompt=False, prepend_padding=False)
1639 # check to make sure the state is expected, then call that handler
1640 if "handler_" + user.state in globals():
1641 exec("handler_" + user.state + "(user)")
1643 generic_menu_handler(user)
1645 # since we got input, flag that the menu/prompt needs to be redisplayed
1646 user.menu_seen = False
1648 # update the last_input timestamp while we're at it
1649 user.last_input = universe.get_time()
1652 def generic_menu_handler(user):
1653 """A generic menu choice handler."""
1655 # get a lower-case representation of the next line of input
1656 if user.input_queue:
1657 choice = user.input_queue.pop(0)
1659 choice = choice.lower()
1663 choice = get_default_menu_choice(user.state)
1664 if choice in user.menu_choices:
1665 exec(get_choice_action(user, choice))
1666 new_state = get_choice_branch(user, choice)
1668 user.state = new_state
1670 user.error = "default"
1673 def handler_entering_account_name(user):
1674 """Handle the login account name."""
1676 # get the next waiting line of input
1677 input_data = user.input_queue.pop(0)
1679 # did the user enter anything?
1682 # keep only the first word and convert to lower-case
1683 name = input_data.lower()
1685 # fail if there are non-alphanumeric characters
1686 if name != "".join(filter(
1687 lambda x: x >= "0" and x <= "9" or x >= "a" and x <= "z",
1689 user.error = "bad_name"
1691 # if that account exists, time to request a password
1692 elif name in universe.groups.get("account", {}):
1693 user.account = universe.groups["account"][name]
1694 user.state = "checking_password"
1696 # otherwise, this could be a brand new user
1698 user.account = Element("account.%s" % name, universe)
1699 user.account.set("name", name)
1700 log("New user: " + name, 2)
1701 user.state = "checking_new_account_name"
1703 # if the user entered nothing for a name, then buhbye
1705 user.state = "disconnecting"
1708 def handler_checking_password(user):
1709 """Handle the login account password."""
1711 # get the next waiting line of input
1712 input_data = user.input_queue.pop(0)
1714 if "mudpy.limit" in universe.contents:
1715 max_password_tries = universe.contents["mudpy.limit"].get(
1716 "password_tries", 3)
1718 max_password_tries = 3
1720 # does the hashed input equal the stored hash?
1721 if mudpy.password.verify(input_data, user.account.get("passhash")):
1723 # if so, set the username and load from cold storage
1724 if not user.replace_old_connections():
1726 user.state = "main_utility"
1728 # if at first your hashes don't match, try, try again
1729 elif user.password_tries < max_password_tries - 1:
1730 user.password_tries += 1
1731 user.error = "incorrect"
1733 # we've exceeded the maximum number of password failures, so disconnect
1736 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1738 user.state = "disconnecting"
1741 def handler_entering_new_password(user):
1742 """Handle a new password entry."""
1744 # get the next waiting line of input
1745 input_data = user.input_queue.pop(0)
1747 if "mudpy.limit" in universe.contents:
1748 max_password_tries = universe.contents["mudpy.limit"].get(
1749 "password_tries", 3)
1751 max_password_tries = 3
1753 # make sure the password is strong--at least one upper, one lower and
1754 # one digit, seven or more characters in length
1755 if len(input_data) > 6 and len(
1756 list(filter(lambda x: x >= "0" and x <= "9", input_data))
1758 list(filter(lambda x: x >= "A" and x <= "Z", input_data))
1760 list(filter(lambda x: x >= "a" and x <= "z", input_data))
1763 # hash and store it, then move on to verification
1764 user.account.set("passhash", mudpy.password.create(input_data))
1765 user.state = "verifying_new_password"
1767 # the password was weak, try again if you haven't tried too many times
1768 elif user.password_tries < max_password_tries - 1:
1769 user.password_tries += 1
1772 # too many tries, so adios
1775 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1777 user.account.destroy()
1778 user.state = "disconnecting"
1781 def handler_verifying_new_password(user):
1782 """Handle the re-entered new password for verification."""
1784 # get the next waiting line of input
1785 input_data = user.input_queue.pop(0)
1787 if "mudpy.limit" in universe.contents:
1788 max_password_tries = universe.contents["mudpy.limit"].get(
1789 "password_tries", 3)
1791 max_password_tries = 3
1793 # hash the input and match it to storage
1794 if mudpy.password.verify(input_data, user.account.get("passhash")):
1797 # the hashes matched, so go active
1798 if not user.replace_old_connections():
1799 user.state = "main_utility"
1801 # go back to entering the new password as long as you haven't tried
1803 elif user.password_tries < max_password_tries - 1:
1804 user.password_tries += 1
1805 user.error = "differs"
1806 user.state = "entering_new_password"
1808 # otherwise, sayonara
1811 "$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)"
1813 user.account.destroy()
1814 user.state = "disconnecting"
1817 def handler_active(user):
1818 """Handle input for active users."""
1820 # get the next waiting line of input
1821 input_data = user.input_queue.pop(0)
1826 # split out the command and parameters
1828 mode = actor.get("mode")
1829 if mode and input_data.startswith("!"):
1830 command_name, parameters = first_word(input_data[1:])
1831 elif mode == "chat":
1832 command_name = "say"
1833 parameters = input_data
1835 command_name, parameters = first_word(input_data)
1837 # lowercase the command
1838 command_name = command_name.lower()
1840 # the command matches a command word for which we have data
1841 if command_name in universe.groups["command"]:
1842 command = universe.groups["command"][command_name]
1846 # if it's allowed, do it
1847 if actor.can_run(command):
1848 exec(command.get("action"))
1850 # otherwise, give an error
1852 command_error(actor, input_data)
1854 # if no input, just idle back with a prompt
1856 user.send("", just_prompt=True)
1859 def command_halt(actor, parameters):
1860 """Halt the world."""
1863 # see if there's a message or use a generic one
1865 message = "Halting: " + parameters
1867 message = "User " + actor.owner.account.get(
1869 ) + " halted the world."
1872 broadcast(message, add_prompt=False)
1875 # set a flag to terminate the world
1876 universe.terminate_flag = True
1879 def command_reload(actor):
1880 """Reload all code modules, configs and data."""
1883 # let the user know and log
1884 actor.send("Reloading all code modules, configs and data.")
1887 actor.owner.account.get("name") + " reloaded the world.",
1891 # set a flag to reload
1892 universe.reload_flag = True
1895 def command_quit(actor):
1896 """Leave the world and go back to the main menu."""
1898 actor.owner.state = "main_utility"
1899 actor.owner.deactivate_avatar()
1902 def command_help(actor, parameters):
1903 """List available commands and provide help for commands."""
1905 # did the user ask for help on a specific command word?
1906 if parameters and actor.owner:
1908 # is the command word one for which we have data?
1909 if parameters in universe.groups["command"]:
1910 command = universe.groups["command"][parameters]
1914 # only for allowed commands
1915 if actor.can_run(command):
1917 # add a description if provided
1918 description = command.get("description")
1920 description = "(no short description provided)"
1921 if command.get("administrative"):
1925 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1927 # add the help text if provided
1928 help_text = command.get("help")
1930 help_text = "No help is provided for this command."
1933 # list related commands
1934 see_also = command.get("see_also")
1936 really_see_also = ""
1937 for item in see_also:
1938 if item in universe.groups["command"]:
1939 command = universe.groups["command"][item]
1940 if actor.can_run(command):
1942 really_see_also += ", "
1943 if command.get("administrative"):
1944 really_see_also += "$(red)"
1946 really_see_also += "$(grn)"
1947 really_see_also += item + "$(nrm)"
1949 output += "$(eol)$(eol)See also: " + really_see_also
1951 # no data for the requested command word
1953 output = "That is not an available command."
1955 # no specific command word was indicated
1958 # give a sorted list of commands with descriptions if provided
1959 output = "These are the commands available to you:$(eol)$(eol)"
1960 sorted_commands = list(universe.groups["command"].keys())
1961 sorted_commands.sort()
1962 for item in sorted_commands:
1963 command = universe.groups["command"][item]
1964 if actor.can_run(command):
1965 description = command.get("description")
1967 description = "(no short description provided)"
1968 if command.get("administrative"):
1972 output += item + "$(nrm) - " + description + "$(eol)"
1973 output += ('$(eol)Enter "help COMMAND" for help on a command '
1976 # send the accumulated output to the user
1980 def command_move(actor, parameters):
1981 """Move the avatar in a given direction."""
1982 if parameters in universe.contents[actor.get("location")].portals():
1983 actor.move_direction(parameters)
1985 actor.send("You cannot go that way.")
1988 def command_look(actor, parameters):
1991 actor.send("You can't look at or in anything yet.")
1993 actor.look_at(actor.get("location"))
1996 def command_say(actor, parameters):
1997 """Speak to others in the same area."""
1999 # check for replacement macros and escape them
2000 parameters = escape_macros(parameters)
2002 # if the message is wrapped in quotes, remove them and leave contents
2004 if parameters.startswith('"') and parameters.endswith('"'):
2005 message = parameters[1:-1]
2008 # otherwise, get rid of stray quote marks on the ends of the message
2010 message = parameters.strip('''"'`''')
2013 # the user entered a message
2016 # match the punctuation used, if any, to an action
2017 if "mudpy.linguistic" in universe.contents:
2018 actions = universe.contents["mudpy.linguistic"].get("actions", {})
2019 default_punctuation = (universe.contents["mudpy.linguistic"].get(
2020 "default_punctuation", "."))
2023 default_punctuation = "."
2026 # reverse sort punctuation options so the longest match wins
2027 for mark in sorted(actions.keys(), reverse=True):
2028 if not literal and message.endswith(mark):
2029 action = actions[mark]
2032 # add punctuation if needed
2034 action = actions[default_punctuation]
2035 if message and not (
2036 literal or unicodedata.category(message[-1]) == "Po"
2038 message += default_punctuation
2040 # failsafe checks to avoid unwanted reformatting and null strings
2041 if message and not literal:
2043 # decapitalize the first letter to improve matching
2044 message = message[0].lower() + message[1:]
2046 # iterate over all words in message, replacing typos
2047 if "mudpy.linguistic" in universe.contents:
2048 typos = universe.contents["mudpy.linguistic"].get("typos", {})
2051 words = message.split()
2052 for index in range(len(words)):
2054 while unicodedata.category(word[0]) == "Po":
2056 while unicodedata.category(word[-1]) == "Po":
2058 if word in typos.keys():
2059 words[index] = words[index].replace(word, typos[word])
2060 message = " ".join(words)
2062 # capitalize the first letter
2063 message = message[0].upper() + message[1:]
2067 actor.echo_to_location(
2068 actor.get("name") + " " + action + 's, "' + message + '"'
2070 actor.send("You " + action + ', "' + message + '"')
2072 # there was no message
2074 actor.send("What do you want to say?")
2077 def command_chat(actor):
2078 """Toggle chat mode."""
2079 mode = actor.get("mode")
2081 actor.set("mode", "chat")
2082 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
2083 elif mode == "chat":
2084 actor.remove_facet("mode")
2085 actor.send("Exiting chat mode.")
2087 actor.send("Sorry, but you're already busy with something else!")
2090 def command_show(actor, parameters):
2091 """Show program data."""
2093 arguments = parameters.split()
2095 message = "What do you want to show?"
2096 elif arguments[0] == "time":
2097 message = universe.groups["internal"]["counters"].get(
2099 ) + " increments elapsed since the world was created."
2100 elif arguments[0] == "groups":
2101 message = "These are the element groups:$(eol)"
2102 groups = list(universe.groups.keys())
2104 for group in groups:
2105 message += "$(eol) $(grn)" + group + "$(nrm)"
2106 elif arguments[0] == "files":
2107 message = "These are the current files containing the universe:$(eol)"
2108 filenames = sorted(universe.files)
2109 for filename in filenames:
2110 if universe.files[filename].is_writeable():
2114 message += ("$(eol) $(red)(%s) $(grn)%s$(nrm)" %
2116 if universe.files[filename].flags:
2117 message += (" $(yel)[%s]$(nrm)" %
2118 ",".join(universe.files[filename].flags))
2119 elif arguments[0] == "group":
2120 if len(arguments) != 2:
2121 message = "You must specify one group."
2122 elif arguments[1] in universe.groups:
2123 message = ('These are the elements in the "' + arguments[1]
2127 universe.groups[arguments[1]][x].key
2128 ) for x in universe.groups[arguments[1]].keys()
2131 for element in elements:
2132 message += "$(eol) $(grn)" + element + "$(nrm)"
2134 message = 'Group "' + arguments[1] + '" does not exist.'
2135 elif arguments[0] == "file":
2136 if len(arguments) != 2:
2137 message = "You must specify one file."
2138 elif arguments[1] in universe.files:
2139 message = ('These are the nodes in the "' + arguments[1]
2141 elements = sorted(universe.files[arguments[1]].data)
2142 for element in elements:
2143 message += "$(eol) $(grn)" + element + "$(nrm)"
2145 message = 'File "%s" does not exist.' % arguments[1]
2146 elif arguments[0] == "element":
2147 if len(arguments) != 2:
2148 message = "You must specify one element."
2149 elif arguments[1].strip(".") in universe.contents:
2150 element = universe.contents[arguments[1].strip(".")]
2151 message = ('These are the properties of the "' + arguments[1]
2152 + '" element (in "' + element.origin.source
2154 facets = element.facets()
2155 for facet in sorted(facets):
2156 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
2157 (facet, str(facets[facet])))
2159 message = 'Element "' + arguments[1] + '" does not exist.'
2160 elif arguments[0] == "result":
2161 if len(arguments) < 2:
2162 message = "You need to specify an expression."
2165 message = repr(eval(" ".join(arguments[1:])))
2166 except Exception as e:
2167 message = ("$(red)Your expression raised an exception...$(eol)"
2168 "$(eol)$(bld)%s$(nrm)" % e)
2169 elif arguments[0] == "log":
2170 if len(arguments) == 4:
2171 if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
2172 stop = int(arguments[3])
2177 if len(arguments) >= 3:
2178 if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
2179 start = int(arguments[2])
2184 if len(arguments) >= 2:
2185 if (re.match(r"^\d+$", arguments[1])
2186 and 0 <= int(arguments[1]) <= 9):
2187 level = int(arguments[1])
2190 elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
2191 level = actor.owner.account.get("loglevel", 0)
2194 if level > -1 and start > -1 and stop > -1:
2195 message = get_loglines(level, start, stop)
2197 message = ("When specified, level must be 0-9 (default 1), "
2198 "start and stop must be >=1 (default 10 and 1).")
2200 message = '''I don't know what "''' + parameters + '" is.'
2204 def command_create(actor, parameters):
2205 """Create an element if it does not exist."""
2207 message = "You must at least specify an element to create."
2208 elif not actor.owner:
2211 arguments = parameters.split()
2212 if len(arguments) == 1:
2213 arguments.append("")
2214 if len(arguments) == 2:
2215 element, filename = arguments
2216 if element in universe.contents:
2217 message = 'The "' + element + '" element already exists.'
2219 message = ('You create "' +
2220 element + '" within the universe.')
2221 logline = actor.owner.account.get(
2223 ) + " created an element: " + element
2225 logline += " in file " + filename
2226 if filename not in universe.files:
2228 ' Warning: "' + filename + '" is not yet '
2229 "included in any other file and will not be read "
2230 "on startup unless this is remedied.")
2231 Element(element, universe, filename)
2233 elif len(arguments) > 2:
2234 message = "You can only specify an element and a filename."
2238 def command_destroy(actor, parameters):
2239 """Destroy an element if it exists."""
2242 message = "You must specify an element to destroy."
2244 if parameters not in universe.contents:
2245 message = 'The "' + parameters + '" element does not exist.'
2247 universe.contents[parameters].destroy()
2248 message = ('You destroy "' + parameters
2249 + '" within the universe.')
2251 actor.owner.account.get(
2253 ) + " destroyed an element: " + parameters,
2259 def command_set(actor, parameters):
2260 """Set a facet of an element."""
2262 message = "You must specify an element, a facet and a value."
2264 arguments = parameters.split(" ", 2)
2265 if len(arguments) == 1:
2266 message = ('What facet of element "' + arguments[0]
2267 + '" would you like to set?')
2268 elif len(arguments) == 2:
2269 message = ('What value would you like to set for the "' +
2270 arguments[1] + '" facet of the "' + arguments[0]
2273 element, facet, value = arguments
2274 if element not in universe.contents:
2275 message = 'The "' + element + '" element does not exist.'
2278 universe.contents[element].set(facet, value)
2279 except PermissionError:
2280 message = ('The "%s" element is kept in read-only file '
2281 '"%s" and cannot be altered.' %
2282 (element, universe.contents[
2283 element].origin.source))
2285 message = ('Value "%s" of type "%s" cannot be coerced '
2286 'to the correct datatype for facet "%s".' %
2287 (value, type(value), facet))
2289 message = ('You have successfully (re)set the "' + facet
2290 + '" facet of element "' + element
2291 + '". Try "show element ' +
2292 element + '" for verification.')
2296 def command_delete(actor, parameters):
2297 """Delete a facet from an element."""
2299 message = "You must specify an element and a facet."
2301 arguments = parameters.split(" ")
2302 if len(arguments) == 1:
2303 message = ('What facet of element "' + arguments[0]
2304 + '" would you like to delete?')
2305 elif len(arguments) != 2:
2306 message = "You may only specify an element and a facet."
2308 element, facet = arguments
2309 if element not in universe.contents:
2310 message = 'The "' + element + '" element does not exist.'
2311 elif facet not in universe.contents[element].facets():
2312 message = ('The "' + element + '" element has no "' + facet
2315 universe.contents[element].remove_facet(facet)
2316 message = ('You have successfully deleted the "' + facet
2317 + '" facet of element "' + element
2318 + '". Try "show element ' +
2319 element + '" for verification.')
2323 def command_error(actor, input_data):
2324 """Generic error for an unrecognized command word."""
2326 # 90% of the time use a generic error
2327 if random.randrange(10):
2328 message = '''I'm not sure what "''' + input_data + '''" means...'''
2330 # 10% of the time use the classic diku error
2332 message = "Arglebargle, glop-glyf!?!"
2334 # send the error message
2338 def daemonize(universe):
2339 """Fork and disassociate from everything."""
2341 # only if this is what we're configured to do
2342 if "mudpy.process" in universe.contents and universe.contents[
2343 "mudpy.process"].get("daemon"):
2345 # log before we start forking around, so the terminal gets the message
2346 log("Disassociating from the controlling terminal.")
2348 # fork off and die, so we free up the controlling terminal
2352 # switch to a new process group
2355 # fork some more, this time to free us from the old process group
2359 # reset the working directory so we don't needlessly tie up mounts
2362 # clear the file creation mask so we can bend it to our will later
2365 # redirect stdin/stdout/stderr and close off their former descriptors
2366 for stdpipe in range(3):
2368 sys.stdin = codecs.open("/dev/null", "r", "utf-8")
2369 sys.__stdin__ = codecs.open("/dev/null", "r", "utf-8")
2370 sys.stdout = codecs.open("/dev/null", "w", "utf-8")
2371 sys.stderr = codecs.open("/dev/null", "w", "utf-8")
2372 sys.__stdout__ = codecs.open("/dev/null", "w", "utf-8")
2373 sys.__stderr__ = codecs.open("/dev/null", "w", "utf-8")
2376 def create_pidfile(universe):
2377 """Write a file containing the current process ID."""
2378 pid = str(os.getpid())
2379 log("Process ID: " + pid)
2380 if "mudpy.process" in universe.contents:
2381 file_name = universe.contents["mudpy.process"].get("pidfile", "")
2385 if not os.path.isabs(file_name):
2386 file_name = os.path.join(universe.startdir, file_name)
2387 file_descriptor = codecs.open(file_name, "w", "utf-8")
2388 file_descriptor.write(pid + "\n")
2389 file_descriptor.flush()
2390 file_descriptor.close()
2393 def remove_pidfile(universe):
2394 """Remove the file containing the current process ID."""
2395 if "mudpy.process" in universe.contents:
2396 file_name = universe.contents["mudpy.process"].get("pidfile", "")
2400 if not os.path.isabs(file_name):
2401 file_name = os.path.join(universe.startdir, file_name)
2402 if os.access(file_name, os.W_OK):
2403 os.remove(file_name)
2406 def excepthook(excepttype, value, tracebackdata):
2407 """Handle uncaught exceptions."""
2409 # assemble the list of errors into a single string
2411 traceback.format_exception(excepttype, value, tracebackdata)
2414 # try to log it, if possible
2417 except Exception as e:
2418 # try to write it to stderr, if possible
2419 sys.stderr.write(message + "\nException while logging...\n%s" % e)
2422 def sighook(what, where):
2423 """Handle external signals."""
2426 message = "Caught signal: "
2428 # for a hangup signal
2429 if what == signal.SIGHUP:
2430 message += "hangup (reloading)"
2431 universe.reload_flag = True
2433 # for a terminate signal
2434 elif what == signal.SIGTERM:
2435 message += "terminate (halting)"
2436 universe.terminate_flag = True
2438 # catchall for unexpected signals
2440 message += str(what) + " (unhandled)"
2446 def override_excepthook():
2447 """Redefine sys.excepthook with our own."""
2448 sys.excepthook = excepthook
2451 def assign_sighook():
2452 """Assign a customized handler for some signals."""
2453 signal.signal(signal.SIGHUP, sighook)
2454 signal.signal(signal.SIGTERM, sighook)
2458 """This contains functions to be performed when starting the engine."""
2460 # see if a configuration file was specified
2461 if len(sys.argv) > 1:
2462 conffile = sys.argv[1]
2468 universe = Universe(conffile, True)
2470 # report any loglines which accumulated during setup
2471 for logline in universe.setup_loglines:
2473 universe.setup_loglines = []
2475 # log an initial message
2476 log("Started mudpy with command line: " + " ".join(sys.argv))
2478 # fork and disassociate
2481 # override the default exception handler so we get logging first thing
2482 override_excepthook()
2484 # set up custom signal handlers
2488 create_pidfile(universe)
2490 # pass the initialized universe back
2495 """These are functions performed when shutting down the engine."""
2497 # the loop has terminated, so save persistent data
2500 # log a final message
2501 log("Shutting down now.")
2503 # get rid of the pidfile
2504 remove_pidfile(universe)